@chatpanel/events 0.435.0 → 0.446.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- const i=[{id:"custom",name:"Custom / self-hosted",kind:"openai",baseUrl:"",authMode:"apiKey",custom:!0},{id:"openai",name:"OpenAI",kind:"openai",baseUrl:"https://api.openai.com/v1",authMode:"apiKey",keyUrl:"https://platform.openai.com/api-keys",docsUrl:"https://platform.openai.com/docs/api-reference"},{id:"anthropic",name:"Anthropic",kind:"anthropic",baseUrl:"https://api.anthropic.com",authMode:"apiKey",keyUrl:"https://console.anthropic.com/settings/keys",docsUrl:"https://docs.anthropic.com/en/api/overview"},{id:"openrouter",name:"OpenRouter",kind:"openai",baseUrl:"https://openrouter.ai/api/v1",authMode:"openrouter",keyUrl:"https://openrouter.ai/settings/keys",docsUrl:"https://openrouter.ai/docs/quickstart",defaultHeaders:{"HTTP-Referer":"https://chatpanel.net"},note:"Chap adds HTTP-Referer so OpenRouter can attribute traffic. You can edit or remove it in Advanced request options."},{id:"huggingface-api-key",name:"Hugging Face Router",kind:"openai",baseUrl:"https://router.huggingface.co/v1",authMode:"apiKey",keyUrl:"https://huggingface.co/settings/tokens",docsUrl:"https://huggingface.co/docs/inference-providers/en/index",note:"Use API key with a fine-grained HF token that has Inference Providers permission, or switch Method to OAuth: Hugging Face and connect. A 401 HTML page usually means the wrong auth method or token."},{id:"gemini-api-key",name:"Google AI Studio · Gemini",kind:"openai",baseUrl:"https://generativelanguage.googleapis.com/v1beta/openai",authMode:"apiKey",keyUrl:"https://aistudio.google.com/apikey",docsUrl:"https://ai.google.dev/gemini-api/docs/openai"},{id:"nvidia",name:"NVIDIA NIM",kind:"openai",baseUrl:"https://integrate.api.nvidia.com/v1",authMode:"apiKey",keyUrl:"https://build.nvidia.com/settings/api-keys",docsUrl:"https://docs.nvidia.com/ai-workbench/user-guide/latest/how-to/integrations/nvidia-integrations.html#integration-endpoint",note:"NVIDIA endpoint API keys may require phone verification."},{id:"groq",name:"Groq",kind:"openai",baseUrl:"https://api.groq.com/openai/v1",authMode:"apiKey",keyUrl:"https://console.groq.com/keys",docsUrl:"https://console.groq.com/docs/openai"},{id:"vercel-ai-gateway",name:"Vercel AI Gateway",kind:"openai",baseUrl:"https://ai-gateway.vercel.sh/v1",authMode:"apiKey",signupUrl:"https://vercel.com/signup",docsUrl:"https://vercel.com/docs/ai-gateway",note:"Use a Vercel AI Gateway API key. Model IDs are provider-prefixed, for example anthropic/claude-sonnet-4.6."},{id:"opencode-zen",name:"OpenCode Zen",kind:"openai",baseUrl:"https://opencode.ai/zen/v1",authMode:"apiKey",signupUrl:"https://opencode.ai/zen",docsUrl:"https://opencode.ai/docs/zen/",note:"Chap uses the OpenAI-compatible chat completions path. Use OpenCode Zen model IDs such as opencode/deepseek-v4-flash-free."},{id:"elevenlabs",name:"ElevenLabs",kind:"openai",baseUrl:"https://api.elevenlabs.io/v1",authMode:"apiKey",keyUrl:"https://elevenlabs.io/app/settings/api-keys",docsUrl:"https://elevenlabs.io/docs/api-reference",note:"Speech to text (Scribe) and voices only — no chat. Use its models under Models › Every model, by type.",jobsOnly:!0},{id:"cohere",name:"Cohere",kind:"openai",baseUrl:"https://api.cohere.ai/compatibility/v1",authMode:"apiKey",keyUrl:"https://dashboard.cohere.com/api-keys",docsUrl:"https://docs.cohere.com/docs/compatibility-api"},{id:"together",name:"Together AI",kind:"openai",baseUrl:"https://api.together.ai/v1",authMode:"apiKey",keyUrl:"https://api.together.ai/settings/api-keys",docsUrl:"https://docs.together.ai/docs/openai-api-compatibility"},{id:"mistral",name:"Mistral · La Plateforme",kind:"openai",baseUrl:"https://api.mistral.ai/v1",authMode:"apiKey",keyUrl:"https://console.mistral.ai/api-keys",docsUrl:"https://docs.mistral.ai/api"},{id:"mistral-codestral",name:"Mistral · Codestral",kind:"openai",baseUrl:"https://api.mistral.ai/v1",authMode:"apiKey",keyUrl:"https://console.mistral.ai/api-keys",docsUrl:"https://docs.mistral.ai/api",note:"Codestral model IDs are available through the regular Mistral API."},{id:"xai",name:"xAI",kind:"openai",baseUrl:"https://api.x.ai/v1",authMode:"apiKey",keyUrl:"https://console.x.ai/team/default/api-keys",docsUrl:"https://docs.x.ai/docs/api-reference"},{id:"deepinfra",name:"DeepInfra",kind:"openai",baseUrl:"https://api.deepinfra.com/v1/openai",authMode:"apiKey",keyUrl:"https://deepinfra.com/dash/api_keys",docsUrl:"https://deepinfra.com/docs/openai_api",note:"Model listing may work without proving chat auth. If chat returns “Missing captcha token”, add a DeepInfra API key and click Test."},{id:"fireworks",name:"Fireworks AI",kind:"openai",baseUrl:"https://api.fireworks.ai/inference/v1",authMode:"apiKey",keyUrl:"https://fireworks.ai/account/api-keys",docsUrl:"https://docs.fireworks.ai/api-reference/introduction"},{id:"cerebras",name:"Cerebras",kind:"openai",baseUrl:"https://api.cerebras.ai/v1",authMode:"apiKey",keyUrl:"https://cloud.cerebras.ai",docsUrl:"https://inference-docs.cerebras.ai/resources/openai"},{id:"github-models",name:"GitHub Models",kind:"openai",baseUrl:"https://models.github.ai/inference",authMode:"apiKey",keyUrl:"https://github.com/settings/personal-access-tokens",docsUrl:"https://docs.github.com/en/rest/models/inference",defaultHeaders:{Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2026-03-10"},note:"Use a GitHub token with models:read. Model listing may differ from generic OpenAI-compatible /models endpoints."},{id:"cloudflare-workers-ai",name:"Cloudflare Workers AI",kind:"openai",baseUrl:"https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/v1",authMode:"apiKey",keyUrl:"https://dash.cloudflare.com/profile/api-tokens",docsUrl:"https://developers.cloudflare.com/workers-ai/configuration/open-ai-compatibility/",note:"Replace {account_id} in Base URL with your Cloudflare account ID."},{id:"ollama",name:"Local · Ollama",kind:"openai",baseUrl:"http://localhost:11434/v1",authMode:"apiKey",docsUrl:"https://github.com/ollama/ollama/blob/main/docs/openai.md"},{id:"lmstudio",name:"Local · LM Studio",kind:"openai",baseUrl:"http://localhost:1234/v1",authMode:"apiKey",docsUrl:"https://lmstudio.ai/docs/app/api/endpoints/openai"},{id:"llamacpp",name:"Local · llama.cpp",kind:"openai",baseUrl:"http://localhost:8080/v1",authMode:"apiKey",docsUrl:"https://github.com/ggml-org/llama.cpp/tree/master/tools/server"},{id:"vllm",name:"Local · vLLM",kind:"openai",baseUrl:"http://localhost:8000/v1",authMode:"apiKey",docsUrl:"https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html"},{id:"apple",name:"Local · Apple on-device (Mac)",kind:"openai",baseUrl:"http://127.0.0.1:8895/v1",authMode:"apiKey",model:"apple-on-device",window:4096,docsUrl:"https://developer.apple.com/documentation/foundationmodels",note:"Apple Intelligence on this Mac: macOS 26 on Apple Silicon, with Apple Intelligence turned on. Start it first in Settings › Runtime › Apple on-device — the gateway runs it. No key. Text only; 4,096 tokens at a time, and a longer chat is trimmed to fit."},{id:"webllm",name:"In-browser · WebLLM (WebGPU)",kind:"webllm",baseUrl:"",authMode:"apiKey",model:"Llama-3.2-1B-Instruct-q4f16_1-MLC",docsUrl:"https://llm.mlc.ai/docs/",note:"Runs 100% in your browser on WebGPU — no API key, no server, works offline after a one-time download. Pick any model from the catalog; bigger models give better answers."}],s=new Set(["ollama","lmstudio","llamacpp","vllm","apple","webllm"]),c={custom:{mark:"+",color:"#64748b"},openai:{mark:"AI",color:"#10a37f"},anthropic:{mark:"A",color:"#d97757"},openrouter:{mark:"OR",color:"#6467f2"},"huggingface-api-key":{mark:"HF",color:"#ff9d00"},"gemini-api-key":{mark:"G",color:"#1a73e8"},nvidia:{mark:"N",color:"#76b900"},groq:{mark:"GQ",color:"#f55036"},"vercel-ai-gateway":{mark:"▲",color:"#111317"},"opencode-zen":{mark:"Z",color:"#3b82f6"},cohere:{mark:"C",color:"#ff7759"},together:{mark:"T",color:"#0f6fff"},mistral:{mark:"M",color:"#fa520f"},"mistral-codestral":{mark:"MC",color:"#fa520f"},xai:{mark:"X",color:"#111317"},deepinfra:{mark:"DI",color:"#4f46e5"},fireworks:{mark:"F",color:"#5019c5"},cerebras:{mark:"CB",color:"#ff6b35"},"github-models":{mark:"GH",color:"#2b3137"},"cloudflare-workers-ai":{mark:"CF",color:"#f6821f"},ollama:{mark:"OL",color:"#0b0d12"},lmstudio:{mark:"LM",color:"#2563eb"},llamacpp:{mark:"LC",color:"#6b7280"},vllm:{mark:"VL",color:"#0ea5e9"},apple:{mark:"Ap",color:"#1d1d1f"},webllm:{mark:"WL",color:"#7c3aed"}},d=new Set(["openai","anthropic","huggingface-api-key","gemini-api-key","nvidia","vercel-ai-gateway","mistral","mistral-codestral","xai","github-models","cloudflare-workers-ai","openrouter","groq","cohere","cerebras","ollama"]);function u(e){return{...c[e]||{mark:String(e||"?").replace(/[^a-z0-9]/gi,"").charAt(0).toUpperCase()||"?",color:"#64748b"},logo:d.has(e)?`assets/providers/${e}.svg`:null}}const n={claude:{mark:"CC",color:"#d97757",logo:"assets/providers/anthropic.svg"},codex:{mark:"CX",color:"#10a37f",logo:"assets/providers/openai.svg"},antigravity:{mark:"AG",color:"#1a73e8"},pi:{mark:"PI",color:"#8b5cf6"},opencode:{mark:"OC",color:"#0ea5e9"},kiro:{mark:"KI",color:"#a855f7"},copilot:{mark:"GH",color:"#24292f"},deepseek:{mark:"DS",color:"#4d6bfe"},custom:{mark:"BYO",color:"#64748b"}};function k(e){return{logo:null,...n[e]||n.custom}}function l(e){return String(e||"").trim().replace(/\/+$/,"")}function f(){const e=i.filter(t=>t.custom),o=i.filter(t=>s.has(t.id)),a=i.filter(t=>!t.custom&&!s.has(t.id)).sort((t,p)=>t.name.localeCompare(p.name));return[...e,...a,...o]}function r(e){return i.find(o=>o.id===e)||null}function m(e={}){if(e.providerPreset){const a=r(e.providerPreset);if(a&&!a.custom)return a}if(e.kind==="webllm")return r("webllm");const o=l(e.baseUrl);return o&&i.find(a=>!a.custom&&l(a.baseUrl)===o&&(!e.kind||a.kind===e.kind))||null}function b(e){if(!e||typeof e!="object")return e;const o=m(e);if(!o)return e;const a={};return o.window&&!(Number(e.window||e.contextLength||e.contextWindow)>0)&&(a.window=o.window),o.toolCalls&&e.toolCalls===void 0&&(a.toolCalls=o.toolCalls),Object.keys(a).length?{...e,...a}:e}function g(e={}){const o=r(e.providerPreset);return!o||o.custom?{...e,providerPreset:"custom"}:{...e,providerPreset:o.id,name:o.name,kind:o.kind,baseUrl:o.baseUrl,authMode:o.authMode,...o.model&&!e.model?{model:o.model}:{},...o.jobsOnly?{jobsOnly:!0,model:""}:{jobsOnly:void 0},headers:{...o.defaultHeaders||{},...e.headers||{}}}}const h=Object.freeze({8891:"vLLM",8892:"vLLM (Metal, Apple Silicon)",8893:"llama.cpp",8894:"MLX",8895:"Apple on-device"});function y(e){let o;try{o=new URL(String(e||""))}catch{return null}if(!/^(?:127\.0\.0\.1|localhost|\[::1\])$/i.test(o.hostname))return null;const a=h[Number(o.port)];return a?{port:Number(o.port),label:a}:null}export{i as API_PROVIDER_PRESETS,h as RUNTIME_CHAT_PORTS,k as agentBrand,g as applyProviderPreset,f as orderedProviderPresets,b as presetFacts,u as providerBrand,r as providerPresetById,m as providerPresetForEndpoint,y as runtimeServiceAt};
1
+ const i=[{id:"custom",name:"Custom / self-hosted",kind:"openai",baseUrl:"",authMode:"apiKey",custom:!0},{id:"openai",name:"OpenAI",kind:"openai",baseUrl:"https://api.openai.com/v1",authMode:"apiKey",keyUrl:"https://platform.openai.com/api-keys",docsUrl:"https://platform.openai.com/docs/api-reference"},{id:"anthropic",name:"Anthropic",kind:"anthropic",baseUrl:"https://api.anthropic.com",authMode:"apiKey",keyUrl:"https://console.anthropic.com/settings/keys",docsUrl:"https://docs.anthropic.com/en/api/overview"},{id:"openrouter",name:"OpenRouter",kind:"openai",baseUrl:"https://openrouter.ai/api/v1",authMode:"openrouter",keyUrl:"https://openrouter.ai/settings/keys",docsUrl:"https://openrouter.ai/docs/quickstart",defaultHeaders:{"HTTP-Referer":"https://chatpanel.net"},note:"Chap adds HTTP-Referer so OpenRouter can attribute traffic. You can edit or remove it in Advanced request options."},{id:"huggingface-api-key",name:"Hugging Face Router",kind:"openai",baseUrl:"https://router.huggingface.co/v1",authMode:"apiKey",keyUrl:"https://huggingface.co/settings/tokens",docsUrl:"https://huggingface.co/docs/inference-providers/en/index",note:"Use API key with a fine-grained HF token that has Inference Providers permission, or switch Method to OAuth: Hugging Face and connect. A 401 HTML page usually means the wrong auth method or token."},{id:"gemini-api-key",name:"Google AI Studio · Gemini",kind:"openai",baseUrl:"https://generativelanguage.googleapis.com/v1beta/openai",authMode:"apiKey",keyUrl:"https://aistudio.google.com/apikey",docsUrl:"https://ai.google.dev/gemini-api/docs/openai"},{id:"nvidia",name:"NVIDIA NIM",kind:"openai",baseUrl:"https://integrate.api.nvidia.com/v1",authMode:"apiKey",keyUrl:"https://build.nvidia.com/settings/api-keys",docsUrl:"https://docs.nvidia.com/ai-workbench/user-guide/latest/how-to/integrations/nvidia-integrations.html#integration-endpoint",note:"NVIDIA endpoint API keys may require phone verification."},{id:"groq",name:"Groq",kind:"openai",baseUrl:"https://api.groq.com/openai/v1",authMode:"apiKey",keyUrl:"https://console.groq.com/keys",docsUrl:"https://console.groq.com/docs/openai"},{id:"vercel-ai-gateway",name:"Vercel AI Gateway",kind:"openai",baseUrl:"https://ai-gateway.vercel.sh/v1",authMode:"apiKey",signupUrl:"https://vercel.com/signup",docsUrl:"https://vercel.com/docs/ai-gateway",note:"Use a Vercel AI Gateway API key. Model IDs are provider-prefixed, for example anthropic/claude-sonnet-4.6."},{id:"opencode-zen",name:"OpenCode Console (pay-as-you-go)",kind:"openai",baseUrl:"https://opencode.ai/inference/openai/v1",authMode:"apiKey",signupUrl:"https://opencode.ai/console",docsUrl:"https://opencode.ai/docs/zen/",note:"An OpenCode Console API key, billed to Console credits. Chap uses the OpenAI-compatible chat completions path; pick a model from the list it loads."},{id:"opencode-go",name:"OpenCode Go (subscription)",kind:"openai",baseUrl:"https://opencode.ai/inference/go/v1",authMode:"apiKey",signupUrl:"https://opencode.ai/console/go",docsUrl:"https://opencode.ai/docs/go/",note:"The API key from your OpenCode Go subscription (opencode.ai/console). Go models only — DeepSeek V4.1 Flash, Kimi K3, GLM-5.3 and the rest of its list — within its 5-hour and weekly limits."},{id:"elevenlabs",name:"ElevenLabs",kind:"openai",baseUrl:"https://api.elevenlabs.io/v1",authMode:"apiKey",keyUrl:"https://elevenlabs.io/app/settings/api-keys",docsUrl:"https://elevenlabs.io/docs/api-reference",note:"Speech to text (Scribe) and voices only — no chat. Use its models under Models › Every model, by type.",jobsOnly:!0},{id:"cohere",name:"Cohere",kind:"openai",baseUrl:"https://api.cohere.ai/compatibility/v1",authMode:"apiKey",keyUrl:"https://dashboard.cohere.com/api-keys",docsUrl:"https://docs.cohere.com/docs/compatibility-api"},{id:"together",name:"Together AI",kind:"openai",baseUrl:"https://api.together.ai/v1",authMode:"apiKey",keyUrl:"https://api.together.ai/settings/api-keys",docsUrl:"https://docs.together.ai/docs/openai-api-compatibility"},{id:"mistral",name:"Mistral · La Plateforme",kind:"openai",baseUrl:"https://api.mistral.ai/v1",authMode:"apiKey",keyUrl:"https://console.mistral.ai/api-keys",docsUrl:"https://docs.mistral.ai/api"},{id:"mistral-codestral",name:"Mistral · Codestral",kind:"openai",baseUrl:"https://api.mistral.ai/v1",authMode:"apiKey",keyUrl:"https://console.mistral.ai/api-keys",docsUrl:"https://docs.mistral.ai/api",note:"Codestral model IDs are available through the regular Mistral API."},{id:"xai",name:"xAI",kind:"openai",baseUrl:"https://api.x.ai/v1",authMode:"apiKey",keyUrl:"https://console.x.ai/team/default/api-keys",docsUrl:"https://docs.x.ai/docs/api-reference"},{id:"deepinfra",name:"DeepInfra",kind:"openai",baseUrl:"https://api.deepinfra.com/v1/openai",authMode:"apiKey",keyUrl:"https://deepinfra.com/dash/api_keys",docsUrl:"https://deepinfra.com/docs/openai_api",note:"Model listing may work without proving chat auth. If chat returns “Missing captcha token”, add a DeepInfra API key and click Test."},{id:"fireworks",name:"Fireworks AI",kind:"openai",baseUrl:"https://api.fireworks.ai/inference/v1",authMode:"apiKey",keyUrl:"https://fireworks.ai/account/api-keys",docsUrl:"https://docs.fireworks.ai/api-reference/introduction"},{id:"cerebras",name:"Cerebras",kind:"openai",baseUrl:"https://api.cerebras.ai/v1",authMode:"apiKey",keyUrl:"https://cloud.cerebras.ai",docsUrl:"https://inference-docs.cerebras.ai/resources/openai"},{id:"github-models",name:"GitHub Models",kind:"openai",baseUrl:"https://models.github.ai/inference",authMode:"apiKey",keyUrl:"https://github.com/settings/personal-access-tokens",docsUrl:"https://docs.github.com/en/rest/models/inference",defaultHeaders:{Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2026-03-10"},note:"Use a GitHub token with models:read. Model listing may differ from generic OpenAI-compatible /models endpoints."},{id:"cloudflare-workers-ai",name:"Cloudflare Workers AI",kind:"openai",baseUrl:"https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/v1",authMode:"apiKey",keyUrl:"https://dash.cloudflare.com/profile/api-tokens",docsUrl:"https://developers.cloudflare.com/workers-ai/configuration/open-ai-compatibility/",note:"Replace {account_id} in Base URL with your Cloudflare account ID."},{id:"ollama",name:"Local · Ollama",kind:"openai",baseUrl:"http://localhost:11434/v1",authMode:"apiKey",docsUrl:"https://github.com/ollama/ollama/blob/main/docs/openai.md"},{id:"lmstudio",name:"Local · LM Studio",kind:"openai",baseUrl:"http://localhost:1234/v1",authMode:"apiKey",docsUrl:"https://lmstudio.ai/docs/app/api/endpoints/openai"},{id:"llamacpp",name:"Local · llama.cpp",kind:"openai",baseUrl:"http://localhost:8080/v1",authMode:"apiKey",docsUrl:"https://github.com/ggml-org/llama.cpp/tree/master/tools/server"},{id:"vllm",name:"Local · vLLM",kind:"openai",baseUrl:"http://localhost:8000/v1",authMode:"apiKey",docsUrl:"https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html"},{id:"apple",name:"Local · Apple on-device (Mac)",kind:"openai",baseUrl:"http://127.0.0.1:8895/v1",authMode:"apiKey",model:"apple-on-device",window:4096,docsUrl:"https://developer.apple.com/documentation/foundationmodels",note:"Apple Intelligence on this Mac: macOS 26 on Apple Silicon, with Apple Intelligence turned on. Start it first in Settings › Runtime › Apple on-device — the gateway runs it. No key. Text only; 4,096 tokens at a time, and a longer chat is trimmed to fit."},{id:"webllm",name:"In-browser · WebLLM (WebGPU)",kind:"webllm",baseUrl:"",authMode:"apiKey",model:"Llama-3.2-1B-Instruct-q4f16_1-MLC",docsUrl:"https://llm.mlc.ai/docs/",note:"Runs 100% in your browser on WebGPU — no API key, no server, works offline after a one-time download. Pick any model from the catalog; bigger models give better answers."}],s=new Set(["ollama","lmstudio","llamacpp","vllm","apple","webllm"]),c={custom:{mark:"+",color:"#64748b"},openai:{mark:"AI",color:"#10a37f"},anthropic:{mark:"A",color:"#d97757"},openrouter:{mark:"OR",color:"#6467f2"},"huggingface-api-key":{mark:"HF",color:"#ff9d00"},"gemini-api-key":{mark:"G",color:"#1a73e8"},nvidia:{mark:"N",color:"#76b900"},groq:{mark:"GQ",color:"#f55036"},"vercel-ai-gateway":{mark:"▲",color:"#111317"},"opencode-zen":{mark:"Z",color:"#3b82f6"},"opencode-go":{mark:"Go",color:"#0ea5e9"},cohere:{mark:"C",color:"#ff7759"},together:{mark:"T",color:"#0f6fff"},mistral:{mark:"M",color:"#fa520f"},"mistral-codestral":{mark:"MC",color:"#fa520f"},xai:{mark:"X",color:"#111317"},deepinfra:{mark:"DI",color:"#4f46e5"},fireworks:{mark:"F",color:"#5019c5"},cerebras:{mark:"CB",color:"#ff6b35"},"github-models":{mark:"GH",color:"#2b3137"},"cloudflare-workers-ai":{mark:"CF",color:"#f6821f"},ollama:{mark:"OL",color:"#0b0d12"},lmstudio:{mark:"LM",color:"#2563eb"},llamacpp:{mark:"LC",color:"#6b7280"},vllm:{mark:"VL",color:"#0ea5e9"},apple:{mark:"Ap",color:"#1d1d1f"},webllm:{mark:"WL",color:"#7c3aed"}},d=new Set(["openai","anthropic","huggingface-api-key","gemini-api-key","nvidia","vercel-ai-gateway","mistral","mistral-codestral","xai","github-models","cloudflare-workers-ai","openrouter","groq","cohere","cerebras","ollama"]);function u(e){return{...c[e]||{mark:String(e||"?").replace(/[^a-z0-9]/gi,"").charAt(0).toUpperCase()||"?",color:"#64748b"},logo:d.has(e)?`assets/providers/${e}.svg`:null}}const n={claude:{mark:"CC",color:"#d97757",logo:"assets/providers/anthropic.svg"},codex:{mark:"CX",color:"#10a37f",logo:"assets/providers/openai.svg"},antigravity:{mark:"AG",color:"#1a73e8"},pi:{mark:"PI",color:"#8b5cf6"},opencode:{mark:"OC",color:"#0ea5e9"},kiro:{mark:"KI",color:"#a855f7"},copilot:{mark:"GH",color:"#24292f"},deepseek:{mark:"DS",color:"#4d6bfe"},custom:{mark:"BYO",color:"#64748b"}};function k(e){return{logo:null,...n[e]||n.custom}}function l(e){return String(e||"").trim().replace(/\/+$/,"")}function f(){const e=i.filter(t=>t.custom),o=i.filter(t=>s.has(t.id)),a=i.filter(t=>!t.custom&&!s.has(t.id)).sort((t,p)=>t.name.localeCompare(p.name));return[...e,...a,...o]}function r(e){return i.find(o=>o.id===e)||null}function m(e={}){if(e.providerPreset){const a=r(e.providerPreset);if(a&&!a.custom)return a}if(e.kind==="webllm")return r("webllm");const o=l(e.baseUrl);return o&&i.find(a=>!a.custom&&l(a.baseUrl)===o&&(!e.kind||a.kind===e.kind))||null}function b(e){if(!e||typeof e!="object")return e;const o=m(e);if(!o)return e;const a={};return o.window&&!(Number(e.window||e.contextLength||e.contextWindow)>0)&&(a.window=o.window),o.toolCalls&&e.toolCalls===void 0&&(a.toolCalls=o.toolCalls),Object.keys(a).length?{...e,...a}:e}function g(e={}){const o=r(e.providerPreset);return!o||o.custom?{...e,providerPreset:"custom"}:{...e,providerPreset:o.id,name:o.name,kind:o.kind,baseUrl:o.baseUrl,authMode:o.authMode,...o.model&&!e.model?{model:o.model}:{},...o.jobsOnly?{jobsOnly:!0,model:""}:{jobsOnly:void 0},headers:{...o.defaultHeaders||{},...e.headers||{}}}}const h=Object.freeze({8891:"vLLM",8892:"vLLM (Metal, Apple Silicon)",8893:"llama.cpp",8894:"MLX",8895:"Apple on-device"});function y(e){let o;try{o=new URL(String(e||""))}catch{return null}if(!/^(?:127\.0\.0\.1|localhost|\[::1\])$/i.test(o.hostname))return null;const a=h[Number(o.port)];return a?{port:Number(o.port),label:a}:null}export{i as API_PROVIDER_PRESETS,h as RUNTIME_CHAT_PORTS,k as agentBrand,g as applyProviderPreset,f as orderedProviderPresets,b as presetFacts,u as providerBrand,r as providerPresetById,m as providerPresetForEndpoint,y as runtimeServiceAt};
package/retrieval-plan.js CHANGED
@@ -1,2 +1,2 @@
1
- import{needsWhole as E,noteShape as C}from"./digest.js";import{lookupSubject as P,prefetchPlan as _,answeredByPrefetch as D}from"./prefetch.js";import{partChars as W,STITCH_LIMITS as q}from"./stitch.js";import{isSmallWindow as k,FIT_HEADROOM as F,SMALL_WINDOW_ROUNDS as b}from"./context-window.js";import{isPleasantry as L}from"./tool-need.js";const j=4,H={device:3,api:2,agent:8};function ee({question:r="",sources:e=[],fixedTokens:n=0,target:o={}}={}){const a=o.kind||"api",s=Number(o.window)||0,i=k(s),c=E(r),S=Math.max(1,Number(o.concurrency)||(a==="device"?1:4)),M=Number(o.secondsPerCall)||H[a]||2,u=(Array.isArray(e)?e:[]).filter(Boolean).map(t=>({...t,chars:Math.max(0,Number(t.chars)||0)})),d=s?Math.floor(s*F)-(Number(o.reserve)||1024)-(Number(n)||0):1/0,m=Number.isFinite(d)?Math.max(0,d)*j:1/0,g=new Map,h=new Set;let f=m;for(let t=!0;t;){t=!1;const l=u.filter(w=>!h.has(w.id)),y=l.length?f/l.length:0;for(const w of l)w.chars<=y&&(h.add(w.id),f-=w.chars,t=!0)}const p=u.filter(t=>!h.has(t.id)).reduce((t,l)=>t+l.chars,0);for(const t of u)g.set(t.id,h.has(t.id)?t.chars:Math.floor(f*t.chars/(p||1)));const A=W({windowTokens:s,reserveTokens:C(r).tokens})||0,$=u.map(t=>{const l={id:t.id,kind:t.kind,title:t.title||"",chars:t.chars,share:g.get(t.id)};if(a==="agent")return{...l,how:"agent",calls:0,why:"an agent reads it itself — handed the material, not a digest"};if(h.has(t.id)||!Number.isFinite(m))return{...l,how:"whole",calls:0,why:"it fits"};if(!i)return{...l,how:"merge",calls:Math.ceil(t.chars/Math.max(1,l.share)),why:"a large window: what does not fit is merged by the model"};if(c&&A>0){const y=Math.min(q.parts,Math.ceil(t.chars/A)),w=Math.ceil(t.chars/A),R=Math.max(1,Math.ceil(y/4));return{...l,how:"digest",parts:y,calls:y+R,unread:Math.max(0,w-y),why:"the question needs all of it, and it does not fit: read in parts, the notes combined"}}return{...l,how:"cut",calls:0,why:c?"no room to read it in parts: the parts that bear on the question":"a focused question: the parts that bear on it, by relevance"}}),I=u.some(t=>t.prefetched),O=a==="agent"?{offer:!0,rounds:null,why:"an agent keeps its own tools"}:i&&I&&!x.test(String(r||""))?{offer:!1,rounds:1,why:"a small window, and a prefetch already answered"}:i?{offer:!0,rounds:b,why:"a small window: one tool round, then the answer"}:{offer:!0,rounds:null,why:""},N=$.reduce((t,l)=>t+(l.calls||0),0),v=Math.round((Math.ceil(N/S)+1)*M);return{sources:$,tools:O,estimate:{calls:N+1,seconds:v},say:B($,v)}}function B(r,e){const n=r.filter(i=>i.how==="digest");if(!n.length)return"";const o=n.length===1?`"${n[0].title||"what is attached"}"`:`${n.length} attachments`,a=n.reduce((i,c)=>i+c.parts,0),s=n.reduce((i,c)=>i+(c.unread||0),0);return`Reading all of ${o} in ${a} part${a===1?"":"s"} first, so the answer covers the whole of it${s?` (the last ${s} part${s===1?"":"s"} will not fit)`:""} — about ${e} s.`}const x=/\b(?:schedule|reschedule|remind(?:er)?|calendar|invite|e-?mail|inbox|send|reply|draft|create|add|save|write (?:a |an )?note|open|click|fill|book|order|cancel|delete|rename|move|upload|download|run|execute|deploy|commit|share|post)\b/i,U=/\b(?:find out|find more|more (?:info|information|details)|look into|latest|current(?:ly)?|today|tonight|tomorrow|right now|this (?:week|weekend|month|year)|price|prices|cost|stock|shares?|score|news|headlines?|weather|forecast|hours|near me|nearby|directions|traffic|flight|look (?:it |that )?up|search|google|website|link|url|https?:\/\/|who(?:'s| is| was| are)|where(?:'s| is| are)|when(?:'s| is| does| do))\b/i,K=/\b(?:my|mine|our|ours|we|us|did i|have i|i (?:said|asked|wrote|told|had|was)|remember|last time|earlier today|meetings?|notes?|transcripts?|conversations?|chats?)\b/i;function Y(r){const e=String(r||"").trim();return e?x.test(e)||U.test(e)||K.test(e)||!!P(e):!1}const T=new Set(["weather","stock","news","page","web","research"]);function te(r=[]){return(Array.isArray(r)?r:[]).some(e=>e?.kind==="prefetch"&&T.has(e.prefetch)&&String(e.text||"").trim())}function re(r=[]){return(Array.isArray(r)?r:[]).some(e=>e&&T.has(e.kind))}function z({window:r=0,question:e="",answered:n=!1,decided:o="",reference:a=!1}={}){return k(r)?a?{offer:!0,rounds:b,why:"a small window, and a document attached by reference that was not read ahead — the files tool stays"}:n&&!x.test(String(e||""))?{offer:!1,rounds:1,why:"a small window, and a prefetch already answered"}:n?{offer:!0,rounds:b,why:"a small window: a prefetch answered the look-up, and something is still to be done"}:o==="none"?x.test(String(e||""))?{offer:!0,rounds:b,why:"a small window: nothing to look up, and something to do"}:{offer:!1,rounds:1,why:"a small window, and the decider found nothing to look up"}:o?{offer:!0,rounds:b,why:`a small window, the decider asked for ${o}, and the fetch found nothing`}:Y(e)?{offer:!0,rounds:b,why:"a small window: one tool round, then the answer"}:{offer:!1,rounds:1,why:"a small window, and a question that needs no tools"}:{offer:!0,rounds:null,why:""}}function ne({window:r=0,question:e="",answered:n=!1}={}){if(!k(r))return{history:"all",memories:"all",before:!1,why:""};const o=L(e);return{history:n?"none":"all",memories:o?"none":n?"pinned":"matched",before:!0,why:[n?"a small window a fetch answered: the evidence, the question and pinned memories":"",o?"a greeting: no memories":n?"":"a small window: only the memories that bear on it"].filter(Boolean).join("; ")}}const G="From the user's own history. It may have nothing to do with the question: use it only if it answers it, otherwise answer from your own knowledge.";function oe(r=[],e={}){const n=(Array.isArray(r)?r:[]).filter(o=>o&&typeof o=="object");return e?.before?n.map(o=>({...o,before:!0,text:`${G}
2
- ${String(o.text||"")}`})):n}function ae(r=[],e=""){const n=String(e||"").trim();if(!n)return r;const o=/^(?:here|near me|nearby|my (?:location|area|city))$/i;return(Array.isArray(r)?r:[]).map(a=>{const s=a?.input?.args||a?.input;if(!s)return a;if(a.kind==="weather"&&o.test(String(s.location||"").trim())){const i={...s,location:n};return{...a,input:a.input.args?{...a.input,args:i}:i,label:`Weather — ${n}`}}if(typeof s.query=="string"&&/\bnear (?:me|here)\b|\bnearby\b|\baround here\b/i.test(s.query)){const i=s.query.replace(/\bnear (?:me|here)\b|\bnearby\b|\baround here\b/i,`near ${n}`);return{...a,input:a.input.args?{...a.input,args:{...s,query:i}}:{...s,query:i},subject:i,label:String(a.label||"").replace(/\bnear (?:me|here)\b|\bnearby\b|\baround here\b/i,`near ${n}`)}}return a})}function se({question:r="",previousText:e="",previousAnswer:n="",previous:o=null,reach:a=new Set,window:s=0,personal:i=!1,lookup:c=null,tab:S=null,now:M=Date.now()}={}){const u=k(s),d=_({text:r,previous:o,previousText:e,previousAnswer:n,reach:a,research:!0,page:!0,tab:S,lookup:c??u,now:M}),m=d.some(p=>["weather","stock","news","page","web","research"].includes(p.kind)),g=!!i&&!m,h=[];d.length&&h.push(`fetch first: ${d.map(p=>p.label||p.kind).join(", ")}`),i&&m&&h.push("a world fact — the person's history is not searched for it");const f=z({window:s,question:r,answered:d.length>0});return f.why&&h.push(f.why),{prefetch:d,world:m,research:g,tools:f,why:h}}export{G as HISTORY_NOTE,D as answeredByPrefetch,ne as contextPlan,oe as historyContext,ae as placeItems,ee as planRetrieval,se as planTurn,z as toolPlan,Y as toolsWanted,te as worldAnswered,re as worldPlanned};
1
+ import{needsWhole as C,noteShape as E}from"./digest.js";import{lookupSubject as P,prefetchPlan as _,answeredByPrefetch as q}from"./prefetch.js";import{partChars as D,STITCH_LIMITS as W}from"./stitch.js";import{isSmallWindow as k,FIT_HEADROOM as F,SMALL_WINDOW_ROUNDS as d}from"./context-window.js";import{isPleasantry as L}from"./tool-need.js";const j=4,H={device:3,api:2,agent:8};function ee({question:t="",sources:e=[],fixedTokens:r=0,target:o={}}={}){const a=o.kind||"api",s=Number(o.window)||0,i=k(s),c=C(t),S=Math.max(1,Number(o.concurrency)||(a==="device"?1:4)),A=Number(o.secondsPerCall)||H[a]||2,f=(Array.isArray(e)?e:[]).filter(Boolean).map(n=>({...n,chars:Math.max(0,Number(n.chars)||0)})),u=s?Math.floor(s*F)-(Number(o.reserve)||1024)-(Number(r)||0):1/0,p=Number.isFinite(u)?Math.max(0,u)*j:1/0,g=new Map,h=new Set;let w=p;for(let n=!0;n;){n=!1;const l=f.filter(m=>!h.has(m.id)),b=l.length?w/l.length:0;for(const m of l)m.chars<=b&&(h.add(m.id),w-=m.chars,n=!0)}const y=f.filter(n=>!h.has(n.id)).reduce((n,l)=>n+l.chars,0);for(const n of f)g.set(n.id,h.has(n.id)?n.chars:Math.floor(w*n.chars/(y||1)));const M=D({windowTokens:s,reserveTokens:E(t).tokens})||0,$=f.map(n=>{const l={id:n.id,kind:n.kind,title:n.title||"",chars:n.chars,share:g.get(n.id)};if(a==="agent")return{...l,how:"agent",calls:0,why:"an agent reads it itself — handed the material, not a digest"};if(h.has(n.id)||!Number.isFinite(p))return{...l,how:"whole",calls:0,why:"it fits"};if(!i)return{...l,how:"merge",calls:Math.ceil(n.chars/Math.max(1,l.share)),why:"a large window: what does not fit is merged by the model"};if(c&&M>0){const b=Math.min(W.parts,Math.ceil(n.chars/M)),m=Math.ceil(n.chars/M),O=Math.max(1,Math.ceil(b/4));return{...l,how:"digest",parts:b,calls:b+O,unread:Math.max(0,m-b),why:"the question needs all of it, and it does not fit: read in parts, the notes combined"}}return{...l,how:"cut",calls:0,why:c?"no room to read it in parts: the parts that bear on the question":"a focused question: the parts that bear on it, by relevance"}}),T=f.some(n=>n.prefetched),I=a==="agent"?{offer:!0,rounds:null,why:"an agent keeps its own tools"}:i&&T&&!x.test(String(t||""))?{offer:!1,rounds:1,why:"a small window, and a prefetch already answered"}:i?{offer:!0,rounds:d,why:"a small window: one tool round, then the answer"}:{offer:!0,rounds:null,why:""},N=$.reduce((n,l)=>n+(l.calls||0),0),v=Math.round((Math.ceil(N/S)+1)*A);return{sources:$,tools:I,estimate:{calls:N+1,seconds:v},say:B($,v)}}function B(t,e){const r=t.filter(i=>i.how==="digest");if(!r.length)return"";const o=r.length===1?`"${r[0].title||"what is attached"}"`:`${r.length} attachments`,a=r.reduce((i,c)=>i+c.parts,0),s=r.reduce((i,c)=>i+(c.unread||0),0);return`Reading all of ${o} in ${a} part${a===1?"":"s"} first, so the answer covers the whole of it${s?` (the last ${s} part${s===1?"":"s"} will not fit)`:""} — about ${e} s.`}const x=/\b(?:schedule|reschedule|remind(?:er)?|calendar|invite|e-?mail|inbox|send|reply|draft|create|add|save|write (?:a |an )?note|open|click|fill|book|order|cancel|delete|rename|move|upload|download|run|execute|deploy|commit|share|post)\b/i,U=/\b(?:find out|find more|more (?:info|information|details)|look into|latest|current(?:ly)?|today|tonight|tomorrow|right now|this (?:week|weekend|month|year)|price|prices|cost|stock|shares?|score|news|headlines?|weather|forecast|hours|near me|nearby|directions|traffic|flight|look (?:it |that )?up|search|google|website|link|url|https?:\/\/|who(?:'s| is| was| are)|where(?:'s| is| are)|when(?:'s| is| does| do))\b/i,K=/\b(?:my|mine|our|ours|we|us|did i|have i|i (?:said|asked|wrote|told|had|was)|remember|last time|earlier today|meetings?|notes?|transcripts?|conversations?|chats?)\b/i;function Y(t){const e=String(t||"").trim();return e?x.test(e)||U.test(e)||K.test(e)||!!P(e):!1}const R=new Set(["weather","stock","news","page","web","research"]);function te(t=[]){return(Array.isArray(t)?t:[]).some(e=>e?.kind==="prefetch"&&R.has(e.prefetch)&&String(e.text||"").trim())}function re(t=[]){return(Array.isArray(t)?t:[]).some(e=>e&&R.has(e.kind))}function ne(t,e=!1,{answered:r=!1}={}){return!e||r||t?.offer?t:{offer:!0,rounds:d,why:"a small window: a request about Chap's own settings — one round to look it up or propose it"}}function oe(t,{skills:e=[],files:r=[]}={}){return t?.offer?t:Array.isArray(e)&&e.length?{offer:!0,rounds:d,why:`a small window: the message names the ${e[0]} skill — one round to open it`}:Array.isArray(r)&&r.length?{offer:!0,rounds:d,why:`a small window: the conversation names ${r[0].split("/").pop()} — one round to read or change it`}:t}function z({window:t=0,question:e="",answered:r=!1,decided:o="",reference:a=!1}={}){return k(t)?a?{offer:!0,rounds:d,why:"a small window, and a document attached by reference that was not read ahead — the files tool stays"}:r&&!x.test(String(e||""))?{offer:!1,rounds:1,why:"a small window, and a prefetch already answered"}:r?{offer:!0,rounds:d,why:"a small window: a prefetch answered the look-up, and something is still to be done"}:o==="none"?x.test(String(e||""))?{offer:!0,rounds:d,why:"a small window: nothing to look up, and something to do"}:{offer:!1,rounds:1,why:"a small window, and the decider found nothing to look up"}:o?{offer:!0,rounds:d,why:`a small window, the decider asked for ${o}, and the fetch found nothing`}:Y(e)?{offer:!0,rounds:d,why:"a small window: one tool round, then the answer"}:{offer:!1,rounds:1,why:"a small window, and a question that needs no tools"}:{offer:!0,rounds:null,why:""}}function ae({window:t=0,question:e="",answered:r=!1}={}){if(!k(t))return{history:"all",memories:"all",before:!1,why:""};const o=L(e);return{history:r?"none":"all",memories:o?"none":r?"pinned":"matched",before:!0,why:[r?"a small window a fetch answered: the evidence, the question and pinned memories":"",o?"a greeting: no memories":r?"":"a small window: only the memories that bear on it"].filter(Boolean).join("; ")}}const G="From the user's own history. It may have nothing to do with the question: use it only if it answers it, otherwise answer from your own knowledge.";function se(t=[],e={}){const r=(Array.isArray(t)?t:[]).filter(o=>o&&typeof o=="object");return e?.before?r.map(o=>({...o,before:!0,text:`${G}
2
+ ${String(o.text||"")}`})):r}function ie(t=[],e=""){const r=String(e||"").trim();if(!r)return t;const o=/^(?:here|near me|nearby|my (?:location|area|city))$/i;return(Array.isArray(t)?t:[]).map(a=>{const s=a?.input?.args||a?.input;if(!s)return a;if(a.kind==="weather"&&o.test(String(s.location||"").trim())){const i={...s,location:r};return{...a,input:a.input.args?{...a.input,args:i}:i,label:`Weather — ${r}`}}if(typeof s.query=="string"&&/\bnear (?:me|here)\b|\bnearby\b|\baround here\b/i.test(s.query)){const i=s.query.replace(/\bnear (?:me|here)\b|\bnearby\b|\baround here\b/i,`near ${r}`);return{...a,input:a.input.args?{...a.input,args:{...s,query:i}}:{...s,query:i},subject:i,label:String(a.label||"").replace(/\bnear (?:me|here)\b|\bnearby\b|\baround here\b/i,`near ${r}`)}}return a})}function le({question:t="",previousText:e="",previousAnswer:r="",previous:o=null,reach:a=new Set,window:s=0,personal:i=!1,lookup:c=null,tab:S=null,now:A=Date.now()}={}){const f=k(s),u=_({text:t,previous:o,previousText:e,previousAnswer:r,reach:a,research:!0,page:!0,tab:S,lookup:c??f,now:A}),p=u.some(y=>["weather","stock","news","page","web","research"].includes(y.kind)),g=!!i&&!p,h=[];u.length&&h.push(`fetch first: ${u.map(y=>y.label||y.kind).join(", ")}`),i&&p&&h.push("a world fact — the person's history is not searched for it");const w=z({window:s,question:t,answered:u.length>0});return w.why&&h.push(w.why),{prefetch:u,world:p,research:g,tools:w,why:h}}export{G as HISTORY_NOTE,q as answeredByPrefetch,ae as contextPlan,se as historyContext,ie as placeItems,ee as planRetrieval,le as planTurn,z as toolPlan,Y as toolsWanted,oe as withNamedRound,ne as withSettingsRound,te as worldAnswered,re as worldPlanned};
package/schedule.js CHANGED
@@ -1 +1 @@
1
- class l extends Error{constructor(t,n){super(n),this.name="ScheduleError",this.code=t}}const B=Object.freeze(["once","interval","daily","weekly","cron"]),C=Object.freeze(["timer","meeting","voice","data","channel"]),D=Object.freeze(["skill","prompt","monitor","notify"]),L=Object.freeze(["skip","runOnce","runAll"]),E=20;function f(e,{days:t=0,hour:n,minute:o=0}){const r=new Date(e);return r.setDate(r.getDate()+t),r.setHours(n,o,0,0),r.getTime()}const I=e=>{const t=new Date(e).getDay();return t===0||t===6};function A(e){if(!e||typeof e!="object")throw new l("BAD_SCHEDULE","schedule must be an object");if(!B.includes(e.kind))throw new l("BAD_SCHEDULE",`unknown schedule kind '${e.kind}'`);if(e.kind==="once"&&!(e.at>0))throw new l("BAD_SCHEDULE","once needs `at`");if(e.kind==="interval"&&!(e.everyMs>=6e4))throw new l("BAD_SCHEDULE","interval needs everyMs >= 60000");if(e.kind==="daily"||e.kind==="weekly"){if(!Number.isInteger(e.hour)||e.hour<0||e.hour>23)throw new l("BAD_SCHEDULE","hour must be 0-23");const t=e.minute??0;if(!Number.isInteger(t)||t<0||t>59)throw new l("BAD_SCHEDULE","minute must be 0-59")}if(e.kind==="weekly"&&(!Number.isInteger(e.weekday)||e.weekday<0||e.weekday>6))throw new l("BAD_SCHEDULE","weekly needs weekday 0-6 (Sunday = 0)");return e.kind==="cron"&&p(e.expr),e}const M=Object.freeze([{name:"minute",min:0,max:59},{name:"hour",min:0,max:23},{name:"day-of-month",min:1,max:31},{name:"month",min:1,max:12,names:["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"]},{name:"day-of-week",min:0,max:7,names:["sun","mon","tue","wed","thu","fri","sat"]}]);function w(e,t){const n=e.toLowerCase();if(t.names){const r=t.names.indexOf(n.slice(0,3));if(r>=0&&n.length===3)return t.min===1?r+1:r}if(!/^\d+$/.test(n))throw new l("BAD_SCHEDULE",`cron: '${e}' is not a ${t.name}`);const o=Number(n);if(o<t.min||o>t.max)throw new l("BAD_SCHEDULE",`cron: ${t.name} ${o} is outside ${t.min}-${t.max}`);return o}function N(e,t){const n=new Set;for(const o of String(e).split(",")){if(!o)throw new l("BAD_SCHEDULE",`cron: empty entry in ${t.name}`);const[r,s]=o.split("/"),i=s===void 0?1:Number(s);if(!Number.isInteger(i)||i<1)throw new l("BAD_SCHEDULE",`cron: bad step '/${s}' in ${t.name}`);let c,a;if(r==="*")c=t.min,a=t.max;else if(r.includes("-")){const[u,h]=r.split("-");if(c=w(u,t),a=w(h,t),a<c)throw new l("BAD_SCHEDULE",`cron: range ${r} runs backwards in ${t.name}`)}else c=w(r,t),a=s===void 0?c:t.max;for(let u=c;u<=a;u+=i)n.add(u)}return t.name==="day-of-week"&&n.has(7)&&(n.delete(7),n.add(0)),n}function p(e){const t=String(e??"").trim().split(/\s+/);if(t.length!==5||!t[0])throw new l("BAD_SCHEDULE","cron needs five fields: minute hour day-of-month month day-of-week");const[n,o,r,s,i]=t.map((u,h)=>N(u,M[h])),c=t[2]==="*",a=t[4]==="*";return{minute:n,hour:o,dom:r,month:s,dow:i,domAny:c,dowAny:a}}const H=366*5;function R(e,t){const n=i=>{if(!e.month.has(i.getMonth()+1))return!1;const c=e.dom.has(i.getDate()),a=e.dow.has(i.getDay());return e.domAny&&e.dowAny?!0:e.domAny?a:e.dowAny?c:c||a},o=[...e.hour].sort((i,c)=>i-c),r=[...e.minute].sort((i,c)=>i-c),s=new Date(t);s.setSeconds(0,0);for(let i=0;i<H;i++){const c=new Date(s);if(c.setDate(s.getDate()+i),c.setHours(0,0,0,0),!!n(c))for(const a of o)for(const u of r){const h=new Date(c);if(h.setHours(a,u,0,0),h.getHours()===a&&h.getTime()>t)return h.getTime()}}return null}function _(e,t){const n=A(e),o=n.minute??0;switch(n.kind){case"once":return n.at>t?n.at:null;case"interval":{const r=n.anchor??t;if(r>t)return r;const s=Math.floor((t-r)/n.everyMs)+1;return r+s*n.everyMs}case"daily":{let r=f(t,{hour:n.hour,minute:o});if(r<=t&&(r=f(t,{days:1,hour:n.hour,minute:o})),n.weekdaysOnly)for(let s=0;s<7&&I(r);s++)r=f(r,{days:1,hour:n.hour,minute:o});return r}case"weekly":{const r=new Date(t).getDay();let s=(n.weekday-r+7)%7;return s===0&&f(t,{hour:n.hour,minute:o})<=t&&(s=7),f(t,{days:s,hour:n.hour,minute:o})}case"cron":return R(p(n.expr),t);default:return null}}const v=Object.freeze(["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]),y=e=>`${String(e?.hour??0).padStart(2,"0")}:${String(e?.minute??0).padStart(2,"0")}`;function re(e){if(!e||typeof e!="object")return"";switch(e.kind){case"once":return e.at>0?`once, at ${new Date(e.at).toLocaleString()}`:"";case"interval":{const t=Number(e.everyMs)||0;if(t<6e4)return"";const n=Math.round(t/6e4);if(n%1440===0){const o=n/1440;return`every ${o===1?"day":`${o} days`}`}if(n%60===0){const o=n/60;return`every ${o===1?"hour":`${o} hours`}`}return`every ${n} minutes`}case"daily":return e.weekdaysOnly?`every weekday at ${y(e)}`:`every day at ${y(e)}`;case"weekly":{const t=v[e.weekday];return t?`every ${t} at ${y(e)}`:""}case"cron":{try{p(e.expr)}catch{return""}return`on the cron schedule ${String(e.expr).trim()}`}default:return""}}function U(e,t,n,o=E){const r=[];let s=t;for(;r.length<o;){const i=_(e,s);if(i===null||i>n)break;r.push(i),s=i}return r}function m({id:e,label:t,kind:n,watches:o=[],description:r="",classUsed:s="R",matches:i=null,params:c={}}){if(!e)throw new l("BAD_TRIGGER","trigger.id required");if(!C.includes(n))throw new l("BAD_TRIGGER",`trigger '${e}': unknown kind '${n}'`);if(n!=="timer"&&typeof i!="function")throw new l("BAD_TRIGGER",`trigger '${e}': an event trigger needs matches()`);return Object.freeze({id:e,label:t||e,kind:n,watches:Object.freeze([...o]),description:r,classUsed:s,matches:i,params:Object.freeze({...c})})}function oe(e=[]){const t=[...e];return{add(n){return t.push(n),()=>{const o=t.indexOf(n);o>=0&&t.splice(o,1)}},list:()=>[...t],get:n=>t.find(o=>o.id===n)||null}}const G=e=>String(e||"").toLowerCase().match(/[\p{L}\p{N}']+/gu)||[],d=e=>String(e||"").trim().toLowerCase(),T=3,W=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function x(e,t=120){const n=String(e||"").replace(/\s+/g," ").trim();if(n.length<=t)return n;const o=n.slice(0,t),r=o.lastIndexOf(" ");return`${(r>t*.6?o.slice(0,r):o).replace(/[\s,;:.!?—-]+$/,"")}…`}function j(e,t){const n=d(t);if(n.length<T)return!1;const o=/[\p{L}\p{N}]/u.test(n[0])?"\\b":"",r=/[\p{L}\p{N}]/u.test(n[n.length-1])?"\\b":"";try{return new RegExp(`${o}${W(n)}${r}`,"iu").test(String(e||""))}catch{return d(e).includes(n)}}function b(e,t,n){return e==="me"?!!n?.isSelf?.(t):e==="others"?!n?.isSelf?.(t):!0}const z=Object.freeze(new Set(["and","or","but","so","because","cause","cos","since","although","though","while","whereas","unless","until","if","when","whenever","that","which","who","whom","whose","than","as","like","what","to","of","in","on","at","by","for","from","with","without","about","into","onto","over","under","between","through","during","against","per","a","an","the","my","our","your","their","its","is","are","was","were","be","been","being","am","do","does","did","have","has","had","will","would","can","could","should","shall","may","might","must","um","uh","er"]));function ie(e){const t=String(e||"").trim();if(!t)return!1;if(/[.!?…]["'\u2019\u201d)\]]*$/.test(t))return!0;if(/[,;:\-\u2013\u2014]$/.test(t))return!1;const n=t.toLowerCase().match(/[\p{L}\p{N}']+/gu)||[],o=n[n.length-1];return o?!z.has(o):!0}const J="text.delta",O=Object.freeze(["meeting","note","chat"]),k=Object.freeze(["meeting.transcript.delta",J]);function q(e){if(e?.type==="meeting.transcript.delta")return"meeting";const t=d(e?.source);return O.includes(t)?t:""}function S(e,t){const n=q(t);if(!n)return!1;const o=(Array.isArray(e)?e:[]).map(d).filter(r=>O.includes(r));return o.length?o.includes(n):n==="meeting"}const g=m({id:"timer:schedule",label:"On a schedule",kind:"timer",description:'Once, on an interval, daily, or on a weekday — "every weekday at 8am".'}),F=m({id:"meeting:started",label:"When a meeting starts",kind:"meeting",watches:["meeting.started"],matches:(e,t={})=>t.platform&&d(e.platform)!==d(t.platform)||t.titleIncludes&&!d(e.title).includes(d(t.titleIncludes))?null:{why:`meeting started: ${e.title||e.meetingId}`}}),X=m({id:"meeting:ended",label:"When a meeting ends",kind:"meeting",watches:["meeting.ended"],matches:e=>({why:`meeting ended: ${e.title||e.meetingId}`})}),K=m({id:"meeting:person-joined",label:"When someone joins",kind:"meeting",watches:["meeting.person-joined"],matches:(e,t={})=>{const n=(t.names||[]).map(d).filter(Boolean),o=(e.people||[]).filter(r=>!n.length||n.some(s=>d(r)===s||d(r).startsWith(`${s} `)));return o.length?{why:`joined: ${o.join(", ")}`,people:o}:null}}),P=m({id:"meeting:phrase",label:"When a phrase is said",kind:"meeting",watches:k,matches:(e,t={},n={})=>{if(!S(t.sources,e))return null;const o=(t.any||[]).map(d).filter(r=>r.length>=T);if(!o.length)return null;for(const r of e.segments||[]){if(!b(t.speaker,r.speaker,n))continue;const s=o.find(i=>j(r.text,i)||!!r.en&&j(r.en,i));if(s)return{why:`“${s}” said by ${r.speaker||"someone"}`,segment:r,phrase:s}}return null}}),Y=m({id:"meeting:topic",label:"When someone talks about something",kind:"meeting",watches:k,matches:(e,t={},n={})=>{if(!S(t.sources,e))return null;const o=(t.terms||[]).map(d).filter(Boolean);if(!o.length)return null;const r=Math.max(1,Math.min(t.minHits||1,o.length)),s=(e.segments||[]).filter(a=>b(t.speaker,a.speaker,n)),i=new Set(s.flatMap(a=>G(a.text))),c=o.filter(a=>a.split(/\s+/).every(u=>i.has(u)));return c.length>=r?{why:`talking about ${c.join(", ")}`,terms:c}:null}}),Q=/^(who|what|when|where|why|how|which|whose|can|could|would|should|shall|do|does|did|is|are|was|were|will|have|has|any(one|body)|is there|are there)\b/i,V=m({id:"meeting:question",label:"When a question is asked",kind:"meeting",watches:k,matches:(e,t={},n={})=>{if(!S(t.sources,e))return null;for(const o of e.segments||[]){if(!b(t.speaker||"anyone",o.speaker,n))continue;const r=String(o.en||o.text||"").trim();if(!(r.length<8)&&(r.includes("?")||Q.test(r)))return{why:`question from ${o.speaker||"someone"}: “${x(r,100)}”`,segment:o}}return null}}),Z=m({id:"voice:command",label:"When you say the wake word",kind:"voice",watches:["voice.command"],matches:(e,t={})=>{const n=t.intents||[];return!e.command?.allowed||n.length&&!n.includes(e.command.intent)?null:{why:`you said “${e.command.command}”`,command:e.command}}}),se=Object.freeze([g,F,X,K,P,Y,V,Z]);function ce({id:e,name:t,trigger:n,schedule:o=null,params:r={},action:s,enabled:i=!0,onMissed:c="runOnce",limits:a={},approval:u=null,createdAt:h=0}){if(!e)throw new l("BAD_JOB","job.id required");if(!t)throw new l("BAD_JOB",`job '${e}': name required`);if(!n)throw new l("BAD_JOB",`job '${e}': trigger required`);if(!s||!D.includes(s.kind))throw new l("BAD_JOB",`job '${e}': action.kind must be one of ${D}`);if(s.kind==="skill"&&!s.skillId)throw new l("BAD_JOB",`job '${e}': skill action needs skillId`);if(!L.includes(c))throw new l("BAD_JOB",`job '${e}': unknown onMissed '${c}'`);return(n===g.id||o)&&A(o),{id:e,name:t,trigger:n,schedule:o,params:{...r},action:{...s},enabled:!!i,onMissed:c,limits:{...a},approval:u,createdAt:h||0}}function $(e,t){return`${e}@${t}`}function ae(e,{now:t,lastRun:n={},admit:o=null,max:r=E}={}){const s=[];for(const i of e||[]){if(!i.enabled||i.trigger!==g.id||!i.schedule||o&&!o(i))continue;const c=n[i.id]||i.createdAt||0;if(!c)continue;const a=U(i.schedule,c,t,r);if(!a.length)continue;const u=i.onMissed==="runAll"?a:i.onMissed==="runOnce"?[a[a.length-1]]:[];for(const h of u)s.push({job:i,at:h,key:$(i.id,h),late:t-h>6e4,missedCount:a.length});u.length||s.push({job:i,at:a[a.length-1],key:$(i.id,a[a.length-1]),skipped:!0,missedCount:a.length})}return s}function ue(e,{now:t,lastRun:n={}}={}){let o=null;for(const r of e||[]){if(!r.enabled||r.trigger!==g.id||!r.schedule)continue;const s=_(r.schedule,Math.max(t,n[r.id]||0));s!==null&&(o===null||s<o)&&(o=s)}return o}const ee=8;function te(e=[],{max:t=ee}={}){const n=[];for(const o of e){const r=String(o?.segment?.text||o?.why||"").trim();if(!r)continue;const s=d(o?.segment?.speaker),i=o?.segment?.t||0,c=r.toLowerCase().replace(/\s+/g," "),a=n.findIndex(u=>u.who===s&&(i&&u.t?u.t===i:u.flat.startsWith(c)||c.startsWith(u.flat)));if(a>=0){r.length>n[a].text.length&&(n[a]={...n[a],match:o,text:r,flat:c});continue}n.push({who:s,t:i,match:o,text:r,flat:c})}return n.slice(-Math.max(1,t)).map(o=>o.match)}function ne(e=[]){return te(e,{max:Number.MAX_SAFE_INTEGER}).map(t=>String(t?.segment?.text||t?.why||"").trim()).filter(Boolean)}function le(e=[],{noun:t="matches",max:n=3,chars:o=180}={}){const r=(e||[]).filter(Boolean);if(!r.length)return"";if(r.length===1)return String(r[0].why||"")||x(r[0]?.segment?.text,o);const s=ne(r);if(!s.length)return`${r.length} ${t}`;const i=s.slice(0,n),c=Math.max(40,Math.floor(o/i.length)),a=s.length-i.length;return`${s.length} ${t}: ${i.map(u=>`“${x(u,c)}”`).join(" · ")}`+(a>0?` +${a} more`:"")}function he(e,t,{registry:n,ctx:o={},admit:r=null}={}){const s=[];for(const i of e||[]){if(!i.enabled||r&&!r(i))continue;const c=n?.get(i.trigger);if(!c||c.kind==="timer"||c.watches.length&&!c.watches.includes(t?.type))continue;let a=null;try{a=c.matches(t,i.params,o)}catch{a=null}a&&s.push({job:i,trigger:c,match:a,key:$(i.id,t.at||t.t||0)})}return s}export{se as BUILTIN_TRIGGERS,z as DANGLING_TAILS,ee as DEFAULT_COALESCE_MAX,D as JOB_ACTIONS,T as MIN_PHRASE_CHARS,L as MISSED_POLICIES,B as SCHEDULE_KINDS,l as ScheduleError,J as TEXT_DELTA,k as TEXT_WATCHES,C as TRIGGER_KINDS,O as TRIGGER_SOURCES,v as WEEKDAY_NAMES,x as clipText,te as coalesceMatches,oe as createTriggerRegistry,ce as defineJob,m as defineTrigger,re as describeSchedule,ae as dueJobs,q as eventSource,he as jobsForEvent,le as matchSummary,ne as matchTexts,X as meetingEndedTrigger,F as meetingStartedTrigger,_ as nextFireAt,ue as nextWakeAt,$ as occurrenceKey,U as occurrencesBetween,p as parseCron,K as personJoinedTrigger,P as phraseTrigger,V as questionTrigger,j as saidIn,S as sourceAllowed,g as timerTrigger,Y as topicTrigger,ie as utteranceLooksComplete,A as validateSchedule,Z as voiceCommandTrigger};
1
+ class l extends Error{constructor(t,n){super(n),this.name="ScheduleError",this.code=t}}const M=Object.freeze(["once","interval","daily","weekly","cron"]),N=Object.freeze(["timer","meeting","voice","data","channel"]),E=Object.freeze(["skill","prompt","monitor","notify"]),H=Object.freeze(["skip","runOnce","runAll"]),_=20;function f(e,{days:t=0,hour:n,minute:o=0}){const r=new Date(e);return r.setDate(r.getDate()+t),r.setHours(n,o,0,0),r.getTime()}const R=e=>{const t=new Date(e).getDay();return t===0||t===6};function j(e){if(!e||typeof e!="object")throw new l("BAD_SCHEDULE","schedule must be an object");if(!M.includes(e.kind))throw new l("BAD_SCHEDULE",`unknown schedule kind '${e.kind}'`);if(e.kind==="once"&&!(e.at>0))throw new l("BAD_SCHEDULE","once needs `at`");if(e.kind==="interval"&&!(e.everyMs>=6e4))throw new l("BAD_SCHEDULE","interval needs everyMs >= 60000");if(e.kind==="daily"||e.kind==="weekly"){if(!Number.isInteger(e.hour)||e.hour<0||e.hour>23)throw new l("BAD_SCHEDULE","hour must be 0-23");const t=e.minute??0;if(!Number.isInteger(t)||t<0||t>59)throw new l("BAD_SCHEDULE","minute must be 0-59")}if(e.kind==="weekly"&&(!Number.isInteger(e.weekday)||e.weekday<0||e.weekday>6))throw new l("BAD_SCHEDULE","weekly needs weekday 0-6 (Sunday = 0)");return e.kind==="cron"&&y(e.expr),e}const v=Object.freeze([{name:"minute",min:0,max:59},{name:"hour",min:0,max:23},{name:"day-of-month",min:1,max:31},{name:"month",min:1,max:12,names:["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"]},{name:"day-of-week",min:0,max:7,names:["sun","mon","tue","wed","thu","fri","sat"]}]);function p(e,t){const n=e.toLowerCase();if(t.names){const r=t.names.indexOf(n.slice(0,3));if(r>=0&&n.length===3)return t.min===1?r+1:r}if(!/^\d+$/.test(n))throw new l("BAD_SCHEDULE",`cron: '${e}' is not a ${t.name}`);const o=Number(n);if(o<t.min||o>t.max)throw new l("BAD_SCHEDULE",`cron: ${t.name} ${o} is outside ${t.min}-${t.max}`);return o}function U(e,t){const n=new Set;for(const o of String(e).split(",")){if(!o)throw new l("BAD_SCHEDULE",`cron: empty entry in ${t.name}`);const[r,i]=o.split("/"),s=i===void 0?1:Number(i);if(!Number.isInteger(s)||s<1)throw new l("BAD_SCHEDULE",`cron: bad step '/${i}' in ${t.name}`);let a,c;if(r==="*")a=t.min,c=t.max;else if(r.includes("-")){const[u,m]=r.split("-");if(a=p(u,t),c=p(m,t),c<a)throw new l("BAD_SCHEDULE",`cron: range ${r} runs backwards in ${t.name}`)}else a=p(r,t),c=i===void 0?a:t.max;for(let u=a;u<=c;u+=s)n.add(u)}return t.name==="day-of-week"&&n.has(7)&&(n.delete(7),n.add(0)),n}function y(e){const t=String(e??"").trim().split(/\s+/);if(t.length!==5||!t[0])throw new l("BAD_SCHEDULE","cron needs five fields: minute hour day-of-month month day-of-week");const[n,o,r,i,s]=t.map((u,m)=>U(u,v[m])),a=t[2]==="*",c=t[4]==="*";return{minute:n,hour:o,dom:r,month:i,dow:s,domAny:a,dowAny:c}}const W=366*5;function z(e,t){const n=s=>{if(!e.month.has(s.getMonth()+1))return!1;const a=e.dom.has(s.getDate()),c=e.dow.has(s.getDay());return e.domAny&&e.dowAny?!0:e.domAny?c:e.dowAny?a:a||c},o=[...e.hour].sort((s,a)=>s-a),r=[...e.minute].sort((s,a)=>s-a),i=new Date(t);i.setSeconds(0,0);for(let s=0;s<W;s++){const a=new Date(i);if(a.setDate(i.getDate()+s),a.setHours(0,0,0,0),!!n(a))for(const c of o)for(const u of r){const m=new Date(a);if(m.setHours(c,u,0,0),m.getHours()===c&&m.getTime()>t)return m.getTime()}}return null}function O(e,t){const n=j(e),o=n.minute??0;switch(n.kind){case"once":return n.at>t?n.at:null;case"interval":{const r=n.anchor??t;if(r>t)return r;const i=Math.floor((t-r)/n.everyMs)+1;return r+i*n.everyMs}case"daily":{let r=f(t,{hour:n.hour,minute:o});if(r<=t&&(r=f(t,{days:1,hour:n.hour,minute:o})),n.weekdaysOnly)for(let i=0;i<7&&R(r);i++)r=f(r,{days:1,hour:n.hour,minute:o});return r}case"weekly":{const r=new Date(t).getDay();let i=(n.weekday-r+7)%7;return i===0&&f(t,{hour:n.hour,minute:o})<=t&&(i=7),f(t,{days:i,hour:n.hour,minute:o})}case"cron":return z(y(n.expr),t);default:return null}}const G=Object.freeze(["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]),$=e=>`${String(e?.hour??0).padStart(2,"0")}:${String(e?.minute??0).padStart(2,"0")}`;function q(e){if(!e||typeof e!="object")return"";switch(e.kind){case"once":return e.at>0?`once, at ${new Date(e.at).toLocaleString()}`:"";case"interval":{const t=Number(e.everyMs)||0;if(t<6e4)return"";const n=Math.round(t/6e4);if(n%1440===0){const o=n/1440;return`every ${o===1?"day":`${o} days`}`}if(n%60===0){const o=n/60;return`every ${o===1?"hour":`${o} hours`}`}return`every ${n} minutes`}case"daily":return e.weekdaysOnly?`every weekday at ${$(e)}`:`every day at ${$(e)}`;case"weekly":{const t=G[e.weekday];return t?`every ${t} at ${$(e)}`:""}case"cron":{try{y(e.expr)}catch{return""}return`on the cron schedule ${String(e.expr).trim()}`}default:return""}}function J(e,t,n,o=_){const r=[];let i=t;for(;r.length<o;){const s=O(e,i);if(s===null||s>n)break;r.push(s),i=s}return r}function d({id:e,label:t,kind:n,watches:o=[],description:r="",classUsed:i="R",matches:s=null,params:a={}}){if(!e)throw new l("BAD_TRIGGER","trigger.id required");if(!N.includes(n))throw new l("BAD_TRIGGER",`trigger '${e}': unknown kind '${n}'`);if(n!=="timer"&&typeof s!="function")throw new l("BAD_TRIGGER",`trigger '${e}': an event trigger needs matches()`);return Object.freeze({id:e,label:t||e,kind:n,watches:Object.freeze([...o]),description:r,classUsed:i,matches:s,params:Object.freeze({...a})})}function ue(e=[]){const t=[...e];return{add(n){return t.push(n),()=>{const o=t.indexOf(n);o>=0&&t.splice(o,1)}},list:()=>[...t],get:n=>t.find(o=>o.id===n)||null}}const F=e=>String(e||"").toLowerCase().match(/[\p{L}\p{N}']+/gu)||[],h=e=>String(e||"").trim().toLowerCase(),T=3,X=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function b(e,t=120){const n=String(e||"").replace(/\s+/g," ").trim();if(n.length<=t)return n;const o=n.slice(0,t),r=o.lastIndexOf(" ");return`${(r>t*.6?o.slice(0,r):o).replace(/[\s,;:.!?—-]+$/,"")}…`}function B(e,t){const n=h(t);if(n.length<T)return!1;const o=/[\p{L}\p{N}]/u.test(n[0])?"\\b":"",r=/[\p{L}\p{N}]/u.test(n[n.length-1])?"\\b":"";try{return new RegExp(`${o}${X(n)}${r}`,"iu").test(String(e||""))}catch{return h(e).includes(n)}}function k(e,t,n){return e==="me"?!!n?.isSelf?.(t):e==="others"?!n?.isSelf?.(t):!0}const K=Object.freeze(new Set(["and","or","but","so","because","cause","cos","since","although","though","while","whereas","unless","until","if","when","whenever","that","which","who","whom","whose","than","as","like","what","to","of","in","on","at","by","for","from","with","without","about","into","onto","over","under","between","through","during","against","per","a","an","the","my","our","your","their","its","is","are","was","were","be","been","being","am","do","does","did","have","has","had","will","would","can","could","should","shall","may","might","must","um","uh","er"]));function le(e){const t=String(e||"").trim();if(!t)return!1;if(/[.!?…]["'\u2019\u201d)\]]*$/.test(t))return!0;if(/[,;:\-\u2013\u2014]$/.test(t))return!1;const n=t.toLowerCase().match(/[\p{L}\p{N}']+/gu)||[],o=n[n.length-1];return o?!K.has(o):!0}const P="text.delta",x=Object.freeze(["meeting","note","chat"]),S=Object.freeze(["meeting.transcript.delta",P]);function Y(e){if(e?.type==="meeting.transcript.delta")return"meeting";const t=h(e?.source);return x.includes(t)?t:""}function A(e,t){const n=Y(t);if(!n)return!1;const o=(Array.isArray(e)?e:[]).map(h).filter(r=>x.includes(r));return o.length?o.includes(n):n==="meeting"}const Q=Object.freeze({meeting:"meetings",note:"notes",chat:"chats"}),C=Object.freeze({me:" by you",others:" by someone else",anyone:""}),g=(e,t="or")=>e.length<=1?e.join(""):`${e.slice(0,-1).join(", ")} ${t} ${e[e.length-1]}`,I=e=>g(e.map(t=>`“${t}”`));function L(e={}){const t=(Array.isArray(e?.sources)?e.sources:[]).map(h).filter(n=>x.includes(n));return t.length?[...new Set(t)]:["meeting"]}function he(e){const t=e?.params||{},n=`in ${g(L(t).map(i=>Q[i]))}`,o=C[t.speaker]??"",r=i=>(Array.isArray(i)?i:[]).map(s=>String(s).trim()).filter(Boolean);switch(e?.trigger){case"timer:schedule":return q(e.schedule);case"meeting:phrase":return r(t.any).length?`when ${I(r(t.any))} is said${o}, ${n}`:`when a phrase is said${o}, ${n}`;case"meeting:topic":return r(t.terms).length?`when someone talks about ${I(r(t.terms))}${o}, ${n}`:"";case"meeting:question":return`when a question is asked${C[t.speaker||"anyone"]??""}, ${n}`;case"meeting:person-joined":return r(t.names).length?`when ${g(r(t.names))} join${r(t.names).length>1?"":"s"} a meeting`:"when someone joins a meeting";case"meeting:started":return`when a meeting starts${t.platform?` on ${t.platform}`:""}${t.titleIncludes?` whose title has “${t.titleIncludes}”`:""}`;case"meeting:ended":return"when a meeting ends";default:return""}}function me(e){const t=L(e?.params).map(n=>({meeting:"during a live meeting",note:"as you write a note (offered there as a chip)",chat:"when you send a chat"})[n]);return`Fires ${g(t)} — only while Chap is open there.`}const w=d({id:"timer:schedule",label:"On a schedule",kind:"timer",description:'Once, on an interval, daily, or on a weekday — "every weekday at 8am".'}),V=d({id:"meeting:started",label:"When a meeting starts",kind:"meeting",watches:["meeting.started"],matches:(e,t={})=>t.platform&&h(e.platform)!==h(t.platform)||t.titleIncludes&&!h(e.title).includes(h(t.titleIncludes))?null:{why:`meeting started: ${e.title||e.meetingId}`}}),Z=d({id:"meeting:ended",label:"When a meeting ends",kind:"meeting",watches:["meeting.ended"],matches:e=>({why:`meeting ended: ${e.title||e.meetingId}`})}),ee=d({id:"meeting:person-joined",label:"When someone joins",kind:"meeting",watches:["meeting.person-joined"],matches:(e,t={})=>{const n=(t.names||[]).map(h).filter(Boolean),o=(e.people||[]).filter(r=>!n.length||n.some(i=>h(r)===i||h(r).startsWith(`${i} `)));return o.length?{why:`joined: ${o.join(", ")}`,people:o}:null}}),te=d({id:"meeting:phrase",label:"When a phrase is said",kind:"meeting",watches:S,matches:(e,t={},n={})=>{if(!A(t.sources,e))return null;const o=(t.any||[]).map(h).filter(r=>r.length>=T);if(!o.length)return null;for(const r of e.segments||[]){if(!k(t.speaker,r.speaker,n))continue;const i=o.find(s=>B(r.text,s)||!!r.en&&B(r.en,s));if(i)return{why:`“${i}” said by ${r.speaker||"someone"}`,segment:r,phrase:i}}return null}}),ne=d({id:"meeting:topic",label:"When someone talks about something",kind:"meeting",watches:S,matches:(e,t={},n={})=>{if(!A(t.sources,e))return null;const o=(t.terms||[]).map(h).filter(Boolean);if(!o.length)return null;const r=Math.max(1,Math.min(t.minHits||1,o.length)),i=(e.segments||[]).filter(c=>k(t.speaker,c.speaker,n)),s=new Set(i.flatMap(c=>F(c.text))),a=o.filter(c=>c.split(/\s+/).every(u=>s.has(u)));return a.length>=r?{why:`talking about ${a.join(", ")}`,terms:a}:null}}),re=/^(who|what|when|where|why|how|which|whose|can|could|would|should|shall|do|does|did|is|are|was|were|will|have|has|any(one|body)|is there|are there)\b/i,oe=d({id:"meeting:question",label:"When a question is asked",kind:"meeting",watches:S,matches:(e,t={},n={})=>{if(!A(t.sources,e))return null;for(const o of e.segments||[]){if(!k(t.speaker||"anyone",o.speaker,n))continue;const r=String(o.en||o.text||"").trim();if(!(r.length<8)&&(r.includes("?")||re.test(r)))return{why:`question from ${o.speaker||"someone"}: “${b(r,100)}”`,segment:o}}return null}}),ie=d({id:"voice:command",label:"When you say the wake word",kind:"voice",watches:["voice.command"],matches:(e,t={})=>{const n=t.intents||[];return!e.command?.allowed||n.length&&!n.includes(e.command.intent)?null:{why:`you said “${e.command.command}”`,command:e.command}}}),de=Object.freeze([w,V,Z,ee,te,ne,oe,ie]);function fe({id:e,name:t,trigger:n,schedule:o=null,params:r={},action:i,enabled:s=!0,onMissed:a="runOnce",limits:c={},approval:u=null,createdAt:m=0}){if(!e)throw new l("BAD_JOB","job.id required");if(!t)throw new l("BAD_JOB",`job '${e}': name required`);if(!n)throw new l("BAD_JOB",`job '${e}': trigger required`);if(!i||!E.includes(i.kind))throw new l("BAD_JOB",`job '${e}': action.kind must be one of ${E}`);if(i.kind==="skill"&&!i.skillId)throw new l("BAD_JOB",`job '${e}': skill action needs skillId`);if(!H.includes(a))throw new l("BAD_JOB",`job '${e}': unknown onMissed '${a}'`);return(n===w.id||o)&&j(o),{id:e,name:t,trigger:n,schedule:o,params:{...r},action:{...i},enabled:!!s,onMissed:a,limits:{...c},approval:u,createdAt:m||0}}function D(e,t){return`${e}@${t}`}function ge(e,{now:t,lastRun:n={},admit:o=null,max:r=_}={}){const i=[];for(const s of e||[]){if(!s.enabled||s.trigger!==w.id||!s.schedule||o&&!o(s))continue;const a=n[s.id]||s.createdAt||0;if(!a)continue;const c=J(s.schedule,a,t,r);if(!c.length)continue;const u=s.onMissed==="runAll"?c:s.onMissed==="runOnce"?[c[c.length-1]]:[];for(const m of u)i.push({job:s,at:m,key:D(s.id,m),late:t-m>6e4,missedCount:c.length});u.length||i.push({job:s,at:c[c.length-1],key:D(s.id,c[c.length-1]),skipped:!0,missedCount:c.length})}return i}function we(e,{now:t,lastRun:n={}}={}){let o=null;for(const r of e||[]){if(!r.enabled||r.trigger!==w.id||!r.schedule)continue;const i=O(r.schedule,Math.max(t,n[r.id]||0));i!==null&&(o===null||i<o)&&(o=i)}return o}const se=8;function ae(e=[],{max:t=se}={}){const n=[];for(const o of e){const r=String(o?.segment?.text||o?.why||"").trim();if(!r)continue;const i=h(o?.segment?.speaker),s=o?.segment?.t||0,a=r.toLowerCase().replace(/\s+/g," "),c=n.findIndex(u=>u.who===i&&(s&&u.t?u.t===s:u.flat.startsWith(a)||a.startsWith(u.flat)));if(c>=0){r.length>n[c].text.length&&(n[c]={...n[c],match:o,text:r,flat:a});continue}n.push({who:i,t:s,match:o,text:r,flat:a})}return n.slice(-Math.max(1,t)).map(o=>o.match)}function ce(e=[]){return ae(e,{max:Number.MAX_SAFE_INTEGER}).map(t=>String(t?.segment?.text||t?.why||"").trim()).filter(Boolean)}function pe(e=[],{noun:t="matches",max:n=3,chars:o=180}={}){const r=(e||[]).filter(Boolean);if(!r.length)return"";if(r.length===1)return String(r[0].why||"")||b(r[0]?.segment?.text,o);const i=ce(r);if(!i.length)return`${r.length} ${t}`;const s=i.slice(0,n),a=Math.max(40,Math.floor(o/s.length)),c=i.length-s.length;return`${i.length} ${t}: ${s.map(u=>`“${b(u,a)}”`).join(" · ")}`+(c>0?` +${c} more`:"")}function ye(e,t,{registry:n,ctx:o={},admit:r=null}={}){const i=[];for(const s of e||[]){if(!s.enabled||r&&!r(s))continue;const a=n?.get(s.trigger);if(!a||a.kind==="timer"||a.watches.length&&!a.watches.includes(t?.type))continue;let c=null;try{c=a.matches(t,s.params,o)}catch{c=null}c&&i.push({job:s,trigger:a,match:c,key:D(s.id,t.at||t.t||0)})}return i}export{de as BUILTIN_TRIGGERS,K as DANGLING_TAILS,se as DEFAULT_COALESCE_MAX,E as JOB_ACTIONS,T as MIN_PHRASE_CHARS,H as MISSED_POLICIES,M as SCHEDULE_KINDS,l as ScheduleError,P as TEXT_DELTA,S as TEXT_WATCHES,N as TRIGGER_KINDS,x as TRIGGER_SOURCES,G as WEEKDAY_NAMES,b as clipText,ae as coalesceMatches,ue as createTriggerRegistry,fe as defineJob,d as defineTrigger,q as describeSchedule,he as describeTrigger,ge as dueJobs,Y as eventSource,ye as jobsForEvent,pe as matchSummary,ce as matchTexts,Z as meetingEndedTrigger,V as meetingStartedTrigger,O as nextFireAt,we as nextWakeAt,D as occurrenceKey,J as occurrencesBetween,y as parseCron,ee as personJoinedTrigger,te as phraseTrigger,oe as questionTrigger,B as saidIn,A as sourceAllowed,w as timerTrigger,ne as topicTrigger,L as triggerSources,le as utteranceLooksComplete,j as validateSchedule,ie as voiceCommandTrigger,me as whereItFires};
package/settings-chat.js CHANGED
@@ -1,4 +1,4 @@
1
- import{listRows as be,findRow as X,rowsFor as Se,breadcrumb as _,linkToRow as ke,setValue as $e,effectiveValue as ve,describeValue as Ne,gateOf as Y}from"./settings-registry.js";import{makeDispatchProvider as Oe}from"./tool-dispatch.js";import{exprLit as S}from"./a2ui-tool-cards.js";const oe="settings",z="settings_find",H="settings_change",ie="settings_run",K=Object.freeze({allow:"chap.settings.allow",deny:"chap.settings.deny",open:"chap.settings.open"}),M=6,xe=new Set(["bridge-url","bridge-token","gw-url","gw-token","ch-token"]),Te=new Set(["internal-restore","license-deactivate","backup-import","btn-subscribe-pro","btn-check-purchase","btn-restore","gw-pro-activate","link-pair","link-partner-pair","ch-pair","ch-connect","drive-connect"]),Ce=Object.freeze({"memory-clear":"forget","activity-clear":"clear","obs-clear":"clear","usage-clear":"clear","reset-skills":"reset","drive-disconnect":"disconnect","ch-disconnect":"disconnect","drive-backup-restore":"restore","drive-backup-restore-all":"restore"}),_e=new Set(["local-recheck","bridge-test","priv-ner-check","gw-check","gw-ner-check","gw-logs-refresh","rt-recheck","obs-refresh","check-updates","plugins-refresh","skill-sources-refresh"]),se=new Set(["toggle","select","text","number","textarea","picker"]),Ee=500,Ae=8e3;function Re(e,{bound:t={},actions:s={},choices:n=null}={}){const o=e?.row;return!o||o.composer?"none":o.type==="secret"||xe.has(o.id)||o.consent?"open":e.page?.id==="plan"||e.group?.id==="privacy"&&!(o.stricter&&se.has(o.type))?o.type==="status"?"read":"open":o.type==="status"?"read":o.type==="link"?"open":o.type==="action"?Te.has(o.id)?"open":typeof s[o.id]?.run=="function"?"run":"open":typeof s[o.id]?.run=="function"?"run":se.has(o.type)?o.store==="local"||o.store==="gateway"||!o.key?typeof t[o.id]?.write=="function"?"change":"open":o.type==="picker"&&typeof n!="function"?"open":"change":"open"}const A=e=>String(e??"").trim().toLowerCase(),Je=new Set(["true","on","yes","1","enable","enabled"]),je=new Set(["false","off","no","0","disable","disabled"]);function ae(e,t){return e.type==="secret"?t?"set":"not set":Ne(e,t)||(t==null||t===""?"not set":String(t))}function Ie(e,t,{options:s=e.options}={}){switch(e.type){case"toggle":{if(typeof t=="boolean")return{ok:!0,value:t};const n=A(t);return Je.has(n)?{ok:!0,value:!0}:je.has(n)?{ok:!0,value:!1}:{ok:!1,why:`"${e.label}" is on or off`}}case"select":case"picker":{const n=Array.isArray(s)?s:[];if(!n.length)return{ok:!1,why:`there are no choices for "${e.label}" here`};const o=n.find(l=>String(l[0])===String(t))||n.find(l=>A(l[0])===A(t)||A(l[1])===A(t));return o?{ok:!0,value:o[0]}:{ok:!1,why:`"${t}" is not one of the choices for "${e.label}": ${n.slice(0,12).map(l=>l[1]||l[0]).join(", ")}`}}case"number":{const n=typeof t=="number"?t:Number(String(t??"").trim());return!Number.isFinite(n)||String(t??"").trim()===""?{ok:!1,why:`"${e.label}" takes a number`}:n<0?{ok:!1,why:`"${e.label}" cannot be negative`}:Number.isFinite(e.min)&&n<e.min?{ok:!1,why:`"${e.label}" is at least ${e.min}`}:Number.isFinite(e.max)&&n>e.max?{ok:!1,why:`"${e.label}" is at most ${e.max}`}:{ok:!0,value:n}}case"text":case"textarea":{if(typeof t!="string"&&typeof t!="number")return{ok:!1,why:`"${e.label}" takes text`};const n=String(t),o=e.type==="text"?Ee:Ae;return n.length>o?{ok:!1,why:`"${e.label}" takes at most ${o} characters`}:/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(n)||e.type==="text"&&/[\r\n]/.test(n)?{ok:!1,why:`"${e.label}" takes plain text on one line`}:{ok:!0,value:e.type==="text"?n.trim():n}}default:return{ok:!1,why:`"${e.label}" is not set by value`}}}function Le(e,t,s){const n=e?.stricter;if(!n)return!1;if(n===!0){const b=t==null?e.default===!0:t===!0;return s===!0||s===b}const o=Array.isArray(n.order)?n.order.map(String):[],l=o.indexOf(String(t==null||t===""?n.unset:t)),p=o.indexOf(String(s));return l!==-1&&p!==-1&&p>=l}const f=(e,t=160)=>{const s=String(e??"");return s.length>t?`${s.slice(0,t-1)}…`:s};function ce({title:e,items:t=[],reason:s="",ticket:n="",allowLabel:o="Apply",note:l="",mustType:p=""}){const b=t.map(y=>({l:f(y.label,60),w:f(y.where,80),f:f(y.from,60),t:f(y.to,80)}));return[`$/c = ${S({title:f(e,80),reason:s?`Chap says: ${f(s,200)}`:"",note:f(l,200),warn:p?"This cannot be undone":"",typeLabel:p?`Type “${p}” to confirm`:""})}`,...p?['$/typed = ""']:[],`$/items = ${S(b)}`,'head = Row([Icon("settings"), Text($/c/title, "h3")])','items = List(_template($/items, Column([Text($l), Text($w, "caption"), Row([Badge($f), Text("→"), Badge($t, "info")])])))',...s?['why = Text($/c/reason, "caption")']:[],...l?['note = Text($/c/note, "caption")']:[],...p?['warn = Badge($/c/warn, "bad")',"typed = TextField($/c/typeLabel, $/typed, "+S(p)+', "shortText")']:[],`allow = Button(Text(${S(o)}), "primary", Event(${S(K.allow)}, {ticket: ${S(n)}${p?", typed: $/typed":""}}))`,`deny = Button(Text("Not now"), _, Event(${S(K.deny)}, {ticket: ${S(n)}}))`,`root = Card(Column([head, items, ${s?"why, ":""}${l?"note, ":""}${p?"warn, typed, ":""}Row([allow, deny])]))`].join(`
2
- `)}function Fe({items:e=[],why:t=""}){const s=e.slice(0,M).map(o=>({l:f(o.label,60),w:f(o.where,80),id:o.id}));return[`$/c = ${S({why:f(t||"You change these in Settings yourself.",200)})}`,`$/items = ${S(s)}`,'head = Row([Icon("settings"), Text("In Settings", "h3")])',`items = List(_template($/items, Row([Column([Text($l), Text($w, "caption")]), Button(Text("Open"), "borderless", Event(${S(K.open)}, {row: $id}))])))`,'root = Card(Column([head, Text($/c/why, "caption"), items]))'].join(`
3
- `)}const Pe=new Set("the a an and or but to of in on at by for with from into onto my me i you your we our it its this that these those is are was were be been am do does did can could would should will shall may might must please hey chap just also so then than there here what which who whom how why when where all any some each every not no yes ok okay get got make made let use using want need like".split(" ")),qe=e=>e.length>4&&e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e,L=e=>String(e||"").toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g,"").split(/[^a-z0-9]+/).filter(t=>t.length>=3&&!Pe.has(t)).map(qe);let Q=null;function De(e){const{row:t}=e;return{name:new Set([t.label,...t.synonyms||[]].flatMap(L)),names:[t.label,...t.synonyms||[]].map(L).filter(s=>s.length),opts:new Set((t.options||[]).flatMap(s=>L(s[1]))),place:new Set([e.page.label,e.section.label].flatMap(L))}}function Ge(){return Q||(Q=new Map(be().map(e=>[e.row.id,De(e)]))),Q}function Ue(e,t){let s=e.indexOf(t[0]);for(;s!==-1;){let n=s,o=!0;for(const l of t.slice(1))if(e[n+1]===l)n+=1;else if(e[n+2]===l)n+=2;else{o=!1;break}if(o)return!0;s=e.indexOf(t[0],s+1)}return!1}function le(e,{rows:t=null,min:s=10,limit:n=3}={}){const o=L(e),l=[...new Set(o)];if(!l.length)return[];const p=t?new Set(t):null,b=[];for(const[x,y]of Ge()){if(p&&!p.has(x))continue;let v=0,F=0;for(const k of l){const E=y.name.has(k)?3:y.opts.has(k)?2:y.place.has(k)?1:0;E&&(v+=E,F+=1)}const R=y.names.filter(k=>Ue(o,k));R.length&&(v+=4);const T=R.some(k=>k.length>1);v>=s&&(F>=2||T)&&b.push({id:x,score:v})}return b.sort((x,y)=>y.score-x.score).slice(0,n)}const Me={name:z,description:"Look up Chap's own settings — models and which model does what, voices, search engines, backups, updates, privacy, everything on the Settings pages — and their current values.",parameters:{type:"object",properties:{query:{type:"string",description:'What the setting is about, in a few words ("title model", "dark mode", "backup").'}},required:["query"]},annotations:{readOnlyHint:!0}},Ve={name:H,description:"Propose a change to one or more of Chap's settings. The person sees a card and decides; nothing changes until they apply it.",parameters:{type:"object",properties:{changes:{type:"array",description:`Up to ${M}, applied together on one card.`,items:{type:"object",properties:{id:{type:"string",description:"The setting id from settings_find."},value:{description:"The new value: true/false, a choice's value, a number or text."}},required:["id","value"]}},reason:{type:"string",description:"One short sentence the person reads on the card: why this change."}},required:["changes"]}},Be={name:ie,description:"Run one of Chap's settings actions (back up now, check for updates, download a model…). One that changes something shows the person a card first.",parameters:{type:"object",properties:{id:{type:"string",description:"The action id from settings_find."},args:{type:"object",description:"The action's own arguments, when settings_find lists any."},reason:{type:"string",description:"One short sentence the person reads on the card."}},required:["id"]}},We='Chap\'s own settings: `settings_find` looks them up with their values and what you may do with each (`can`): "change" → propose with `settings_change` (the person decides on a card); "run" → `settings_run`; "open" → the person changes it in Settings — say so, Chap shows them the way. Never claim a setting changed unless the result says it did.';let Xe=0;const he=e=>(typeof e=="string"?e:e?.decision)==="allow"?"allow":"deny";function Ke({client:e="browser",read:t=()=>({}),write:s=null,bound:n={},choices:o=null,actions:l={},runtime:p=()=>({}),confirm:b=null,record:x=null,newTicket:y=()=>`s${Date.now().toString(36)}${Xe+=1}`}={}){const v=new Set(Se(e)),F={bound:n,actions:l,choices:o},R=r=>{const h=X(String(r||""));return h&&v.has(h.row.id)?h:null},T=r=>Re(r,F),k=(r,h)=>n[r.row.id]?.read?n[r.row.id].read():ve(h,r.row),E=(r,h)=>r.row.type==="picker"?typeof o=="function"?o(r.row.id,h):null:r.row.options,V=r=>{try{x?.(r)}catch{}};function ue(r,h){const g=T(r),a=g==="change"?E(r,h):null,d=Y(r.row,p()||{});return{id:r.row.id,label:r.row.label,where:_(r),...r.row.key||n[r.row.id]?.read?{value:ae(r.row,k(r,h))}:{},can:g,type:r.row.type,...a?.length?{choices:a.slice(0,12).map($=>$[0])}:{},...l[r.row.id]?.args?{args:l[r.row.id].args}:{},...d.ok?{}:{blocked:d.reason},...r.row.pro?{pro:!0}:{},...r.row.help?{help:f(r.row.help,140)}:{}}}function de({query:r=""}={}){const h=t()||{},g=le(r,{rows:[...v],min:3,limit:8}).map(a=>a.id);return g.length?JSON.stringify({matches:g.map(a=>ue(X(a),h)).filter(a=>a.can!=="none")}):JSON.stringify({matches:[],hint:"Nothing matched — try other words for the setting (what it does, or where it lives in Settings)."})}const Z=(r,h)=>({text:JSON.stringify({changed:!1,open:r.map(g=>g.id),say:`${h} Chap shows the person a card that opens it in Settings; do not say it changed.`}),card:{lang:"a2ui",source:Fe({items:r,why:h})}});async function pe({changes:r,reason:h="",id:g,value:a}={}){const d=Array.isArray(r)?r:g?[{id:g,value:a}]:[];if(!d.length)return JSON.stringify({error:'No change given. Pass {"changes":[{"id":"<from settings_find>","value":…}]}.'});if(d.length>M)return JSON.stringify({error:`At most ${M} changes on one card.`});const $=t()||{},J=p()||{},w=[],u=[],m=[];for(const c of d){const i=R(c?.id);if(!i){u.push({id:c?.id,why:"no such setting here — look it up with settings_find"});continue}const B=T(i);if(B==="open"){m.push({id:i.row.id,label:i.row.label,where:_(i)});continue}if(B!=="change"){u.push({id:i.row.id,why:B==="run"?"this is an action — use settings_run":"this one is shown, not set"});continue}const D=Y(i.row,J);if(!D.ok){u.push({id:i.row.id,why:`${D.reason}${D.fix?` (${D.fix})`:""}`});continue}const C=Ie(i.row,c.value,{options:E(i,$)});if(!C.ok){u.push({id:i.row.id,why:C.why});continue}const G=k(i,$),W=(G==null||G==="")&&i.row.stricter?.unset!==void 0?i.row.stricter.unset:G;if(JSON.stringify(W)===JSON.stringify(C.value))continue;if(i.group?.id==="privacy"&&!Le(i.row,W,C.value)){m.push({id:i.row.id,label:i.row.label,where:_(i)}),u.push({id:i.row.id,why:"that loosens privacy — the person changes it in Settings"});continue}const te=E(i,$);if(te?.find(U=>String(U[0])===String(C.value))?.[2]?.leaves===!0){m.push({id:i.row.id,label:i.row.label,where:_(i)}),u.push({id:i.row.id,why:"that choice sends your words off this device"});continue}const ne=U=>{const re=te?.find(me=>String(me[0])===String(U));return re?re[1]:ae(i.row,U)};w.push({e:i,value:C.value,item:{id:i.row.id,label:i.row.label,where:_(i),from:ne(W),to:ne(C.value)}})}if(m.length&&!w.length)return Z(m,u.length?`Not changed from the chat: ${u.map(c=>c.why).join("; ")}.`:"These are changed by the person in Settings, not from the chat.");if(!w.length)return u.length?JSON.stringify({changed:!1,refused:u}):JSON.stringify({changed:!1,unchanged:!0,say:"Already set that way — nothing to change."});if(typeof b!="function"||typeof s!="function"&&w.some(c=>!n[c.e.row.id]?.write))return JSON.stringify({changed:!1,error:"Settings cannot be changed from this chat here — the person can change them in Settings."});const j=y(),I=w.map(c=>c.item.id),N=w.length===1?`Change ${w[0].item.label}?`:`Change ${w.length} settings?`,O=w.map(c=>`${c.item.label}: ${c.item.from} → ${c.item.to}`).join(`
4
- `),P=m.length?`Not on this card — change in Settings: ${m.map(c=>c.label).join(", ")}.`:"";let q="deny";try{q=he(await b({kind:"change",title:N,detail:O,reason:f(h,200),card:ce({title:N,items:w.map(c=>c.item),reason:h,ticket:j,note:P}),ticket:j,ids:I}))}catch{q="deny"}if(V({kind:"change",ids:I,decision:q==="allow"?"allow":"deny"}),q!=="allow")return JSON.stringify({changed:!1,declined:I,say:"The person kept their settings as they were. Do not propose this again unless they ask."});try{const c=w.filter(i=>!n[i.e.row.id]?.write);c.length&&await s(c.map(i=>({id:i.e.row.id,key:i.e.row.key,value:i.value})));for(const i of w)n[i.e.row.id]?.write&&await n[i.e.row.id].write(i.value)}catch(c){return JSON.stringify({changed:!1,error:`Could not save: ${f(c?.message||c,160)}`})}return JSON.stringify({changed:!0,now:w.map(c=>({id:c.item.id,label:c.item.label,value:c.item.to})),...u.length?{refused:u}:{},...m.length?{open:m.map(c=>c.id)}:{}})}async function fe({id:r,args:h={},reason:g=""}={}){const a=R(r);if(!a)return JSON.stringify({error:"No such action here — look it up with settings_find."});const d=T(a);if(d==="open")return Z([{id:a.row.id,label:a.row.label,where:_(a)}],`"${a.row.label}" is done by the person in Settings, not from the chat.`);if(d!=="run")return JSON.stringify({error:d==="change"?"This is a setting — propose it with settings_change.":"This one is shown, not run."});const $=Y(a.row,p()||{});if(!$.ok)return JSON.stringify({ran:!1,why:`${$.reason}${$.fix?` (${$.fix})`:""}`});const J=l[a.row.id],w=h&&typeof h=="object"?h:{};if(_e.has(a.row.id))V({kind:"run",ids:[a.row.id],decision:"look"});else{if(typeof b!="function")return JSON.stringify({ran:!1,error:"Actions cannot be run from this chat here — the person can run it in Settings."});let u="";try{u=J.preview?String(J.preview(w)||""):""}catch{u=""}const m=y(),j=`${a.row.label}?`,I={id:a.row.id,label:a.row.label,where:_(a),from:"now",to:f(u||a.row.help||a.row.label,80)},N=Ce[a.row.id]||"";let O="deny";try{const P=await b({kind:"run",title:j,detail:u||a.row.help||"",reason:f(g,200),card:ce({title:j,items:[I],reason:g,ticket:m,allowLabel:a.row.label,mustType:N}),ticket:m,ids:[a.row.id],...N?{mustType:N}:{}});O=he(P),N&&O==="allow"&&A(P?.typed)!==N&&(O="deny")}catch{O="deny"}if(V({kind:"run",ids:[a.row.id],decision:O==="allow"?"allow":"deny"}),O!=="allow")return JSON.stringify({ran:!1,declined:a.row.id,say:"The person chose not to. Do not ask again unless they do."})}try{const u=await J.run(w);return JSON.stringify({ran:!0,id:a.row.id,result:f(typeof u=="string"?u:JSON.stringify(u??""),1500)})}catch(u){return JSON.stringify({ran:!1,id:a.row.id,error:f(u?.message||u,200)})}}const ee=Object.keys(l).some(r=>typeof l[r]?.run=="function"&&v.has(r)),ge=[Me,Ve,...ee?[Be]:[]],we=Oe({name:oe,description:"Chap's own settings — look up, propose a change (the person approves), run an action.",resident:We,inner:{specs:ge,async execute(r,h={}){return r===z?de(h):r===H?pe(h):r===ie&&ee?fe(h):JSON.stringify({error:`Unknown settings action: ${r}`})}}});function ye(r,{small:h=!1}={}){const g=le(r,{rows:[...v],min:h?12:10,limit:3}).map(d=>X(d.id)).filter(d=>d&&T(d)!=="none");return g.length?`[Chap] This may be about Chap's own settings: ${g.map(d=>`${d.row.label} (\`${d.row.id}\`, ${T(d)})`).join("; ")}. Through \`tools\`: {"action":"${z}","args":{"query":"…"}} for values and choices, then {"action":"${H}","args":{"changes":[{"id":"…","value":…}]}} — the person approves on a card.`:""}return{...we,id:oe,quiet:!0,hint:ye}}const Qe=e=>ke(e);function Ze(e,t=[]){return(t||[]).filter(s=>s?.key).reduce((s,n)=>$e(s,n.key,n.value),e||{})}export{_e as LOOK_ONLY_ACTIONS,M as MAX_CHANGES,H as SETTINGS_CHANGE,K as SETTINGS_EVENTS,z as SETTINGS_FIND,oe as SETTINGS_GROUP,ie as SETTINGS_RUN,Ce as TYPE_TO_RUN,Ze as applyChanges,ce as changeCard,Re as chatReachOf,Ie as coerceValue,Le as isStricter,Fe as openCard,le as rankForMessage,Ke as settingsChatProvider,Qe as settingsLinkFor,ae as shownValue};
1
+ import{listRows as Se,findRow as X,rowsFor as ie,breadcrumb as _,linkToRow as ke,setValue as $e,effectiveValue as ve,describeValue as Ne,gateOf as Y}from"./settings-registry.js";import{makeDispatchProvider as Oe}from"./tool-dispatch.js";import{exprLit as b}from"./a2ui-tool-cards.js";const se="settings",z="settings_find",H="settings_change",ae="settings_run",K=Object.freeze({allow:"chap.settings.allow",deny:"chap.settings.deny",open:"chap.settings.open"}),M=6,xe=new Set(["bridge-url","bridge-token","gw-url","gw-token","ch-token"]),Te=new Set(["internal-restore","license-deactivate","backup-import","btn-subscribe-pro","btn-check-purchase","btn-restore","gw-pro-activate","link-pair","link-partner-pair","ch-pair","ch-connect","drive-connect"]),Ce=Object.freeze({"memory-clear":"forget","activity-clear":"clear","obs-clear":"clear","usage-clear":"clear","reset-skills":"reset","drive-disconnect":"disconnect","ch-disconnect":"disconnect","drive-backup-restore":"restore","drive-backup-restore-all":"restore"}),_e=new Set(["local-recheck","bridge-test","priv-ner-check","gw-check","gw-ner-check","gw-logs-refresh","rt-recheck","obs-refresh","check-updates","plugins-refresh","skill-sources-refresh"]),ce=new Set(["toggle","select","text","number","textarea","picker"]),Ee=500,Ae=8e3;function Re(e,{bound:t={},actions:a={},choices:r=null}={}){const o=e?.row;return!o||o.composer?"none":o.type==="secret"||xe.has(o.id)||o.consent?"open":e.page?.id==="plan"||e.group?.id==="privacy"&&!(o.stricter&&ce.has(o.type))?o.type==="status"?"read":"open":o.type==="status"?"read":o.type==="link"?"open":o.type==="action"?Te.has(o.id)?"open":typeof a[o.id]?.run=="function"?"run":"open":typeof a[o.id]?.run=="function"?"run":ce.has(o.type)?o.store==="local"||o.store==="gateway"||!o.key?typeof t[o.id]?.write=="function"?"change":"open":o.type==="picker"&&typeof r!="function"?"open":"change":"open"}const A=e=>String(e??"").trim().toLowerCase(),Je=new Set(["true","on","yes","1","enable","enabled"]),je=new Set(["false","off","no","0","disable","disabled"]);function le(e,t){return e.type==="secret"?t?"set":"not set":Ne(e,t)||(t==null||t===""?"not set":String(t))}function Ie(e,t,{options:a=e.options}={}){switch(e.type){case"toggle":{if(typeof t=="boolean")return{ok:!0,value:t};const r=A(t);return Je.has(r)?{ok:!0,value:!0}:je.has(r)?{ok:!0,value:!1}:{ok:!1,why:`"${e.label}" is on or off`}}case"select":case"picker":{const r=Array.isArray(a)?a:[];if(!r.length)return{ok:!1,why:`there are no choices for "${e.label}" here`};const o=r.find(h=>String(h[0])===String(t))||r.find(h=>A(h[0])===A(t)||A(h[1])===A(t));return o?{ok:!0,value:o[0]}:{ok:!1,why:`"${t}" is not one of the choices for "${e.label}": ${r.slice(0,12).map(h=>h[1]||h[0]).join(", ")}`}}case"number":{const r=typeof t=="number"?t:Number(String(t??"").trim());return!Number.isFinite(r)||String(t??"").trim()===""?{ok:!1,why:`"${e.label}" takes a number`}:r<0?{ok:!1,why:`"${e.label}" cannot be negative`}:Number.isFinite(e.min)&&r<e.min?{ok:!1,why:`"${e.label}" is at least ${e.min}`}:Number.isFinite(e.max)&&r>e.max?{ok:!1,why:`"${e.label}" is at most ${e.max}`}:{ok:!0,value:r}}case"text":case"textarea":{if(typeof t!="string"&&typeof t!="number")return{ok:!1,why:`"${e.label}" takes text`};const r=String(t),o=e.type==="text"?Ee:Ae;return r.length>o?{ok:!1,why:`"${e.label}" takes at most ${o} characters`}:/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(r)||e.type==="text"&&/[\r\n]/.test(r)?{ok:!1,why:`"${e.label}" takes plain text on one line`}:{ok:!0,value:e.type==="text"?r.trim():r}}default:return{ok:!1,why:`"${e.label}" is not set by value`}}}function Le(e,t,a){const r=e?.stricter;if(!r)return!1;if(r===!0){const m=t==null?e.default===!0:t===!0;return a===!0||a===m}const o=Array.isArray(r.order)?r.order.map(String):[],h=o.indexOf(String(t==null||t===""?r.unset:t)),d=o.indexOf(String(a));return h!==-1&&d!==-1&&d>=h}const f=(e,t=160)=>{const a=String(e??"");return a.length>t?`${a.slice(0,t-1)}…`:a};function he({title:e,items:t=[],reason:a="",ticket:r="",allowLabel:o="Apply",note:h="",mustType:d=""}){const m=t.map(w=>({l:f(w.label,60),w:f(w.where,80),f:f(w.from,60),t:f(w.to,80)}));return[`$/c = ${b({title:f(e,80),reason:a?`Chap says: ${f(a,200)}`:"",note:f(h,200),warn:d?"This cannot be undone":"",typeLabel:d?`Type “${d}” to confirm`:""})}`,...d?['$/typed = ""']:[],`$/items = ${b(m)}`,'head = Row([Icon("settings"), Text($/c/title, "h3")])','items = List(_template($/items, Column([Text($l), Text($w, "caption"), Row([Badge($f), Text("→"), Badge($t, "info")])])))',...a?['why = Text($/c/reason, "caption")']:[],...h?['note = Text($/c/note, "caption")']:[],...d?['warn = Badge($/c/warn, "bad")',"typed = TextField($/c/typeLabel, $/typed, "+b(d)+', "shortText")']:[],`allow = Button(Text(${b(o)}), "primary", Event(${b(K.allow)}, {ticket: ${b(r)}${d?", typed: $/typed":""}}))`,`deny = Button(Text("Not now"), _, Event(${b(K.deny)}, {ticket: ${b(r)}}))`,`root = Card(Column([head, items, ${a?"why, ":""}${h?"note, ":""}${d?"warn, typed, ":""}Row([allow, deny])]))`].join(`
2
+ `)}function Fe({items:e=[],why:t=""}){const a=e.slice(0,M).map(o=>({l:f(o.label,60),w:f(o.where,80),id:o.id}));return[`$/c = ${b({why:f(t||"You change these in Settings yourself.",200)})}`,`$/items = ${b(a)}`,'head = Row([Icon("settings"), Text("In Settings", "h3")])',`items = List(_template($/items, Row([Column([Text($l), Text($w, "caption")]), Button(Text("Open"), "borderless", Event(${b(K.open)}, {row: $id}))])))`,'root = Card(Column([head, Text($/c/why, "caption"), items]))'].join(`
3
+ `)}const Pe=new Set("the a an and or but to of in on at by for with from into onto my me i you your we our it its this that these those is are was were be been am do does did can could would should will shall may might must please hey chap just also so then than there here what which who whom how why when where all any some each every not no yes ok okay get got make made let use using want need like".split(" ")),qe=e=>e.length>4&&e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e,L=e=>String(e||"").toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g,"").split(/[^a-z0-9]+/).filter(t=>t.length>=3&&!Pe.has(t)).map(qe);let Q=null;function De(e){const{row:t}=e;return{name:new Set([t.label,...t.synonyms||[]].flatMap(L)),names:[t.label,...t.synonyms||[]].map(L).filter(a=>a.length),opts:new Set((t.options||[]).flatMap(a=>L(a[1]))),place:new Set([e.page.label,e.section.label].flatMap(L))}}function Ge(){return Q||(Q=new Map(Se().map(e=>[e.row.id,De(e)]))),Q}function Ue(e,t){let a=e.indexOf(t[0]);for(;a!==-1;){let r=a,o=!0;for(const h of t.slice(1))if(e[r+1]===h)r+=1;else if(e[r+2]===h)r+=2;else{o=!1;break}if(o)return!0;a=e.indexOf(t[0],a+1)}return!1}function Z(e,{rows:t=null,min:a=10,limit:r=3}={}){const o=L(e),h=[...new Set(o)];if(!h.length)return[];const d=t?new Set(t):null,m=[];for(const[x,w]of Ge()){if(d&&!d.has(x))continue;let v=0,F=0;for(const S of h){const E=w.name.has(S)?3:w.opts.has(S)?2:w.place.has(S)?1:0;E&&(v+=E,F+=1)}const R=w.names.filter(S=>Ue(o,S));R.length&&(v+=4);const T=R.some(S=>S.length>1);v>=a&&(F>=2||T)&&m.push({id:x,score:v})}return m.sort((x,w)=>w.score-x.score).slice(0,r)}const Me={name:z,description:"Look up Chap's own settings — models and which model does what, voices, search engines, backups, updates, privacy, everything on the Settings pages — and their current values.",parameters:{type:"object",properties:{query:{type:"string",description:'What the setting is about, in a few words ("title model", "dark mode", "backup").'}},required:["query"]},annotations:{readOnlyHint:!0}},Ve={name:H,description:"Propose a change to one or more of Chap's settings. The person sees a card and decides; nothing changes until they apply it.",parameters:{type:"object",properties:{changes:{type:"array",description:`Up to ${M}, applied together on one card.`,items:{type:"object",properties:{id:{type:"string",description:"The setting id from settings_find."},value:{description:"The new value: true/false, a choice's value, a number or text."}},required:["id","value"]}},reason:{type:"string",description:"One short sentence the person reads on the card: why this change."}},required:["changes"]}},Be={name:ae,description:"Run one of Chap's settings actions (back up now, check for updates, download a model…). One that changes something shows the person a card first.",parameters:{type:"object",properties:{id:{type:"string",description:"The action id from settings_find."},args:{type:"object",description:"The action's own arguments, when settings_find lists any."},reason:{type:"string",description:"One short sentence the person reads on the card."}},required:["id"]}},We='Chap\'s own settings: `settings_find` looks them up with their values and what you may do with each (`can`): "change" → propose with `settings_change` (the person decides on a card); "run" → `settings_run`; "open" → the person changes it in Settings — say so, Chap shows them the way. Never claim a setting changed unless the result says it did.';let Xe=0;const ue=e=>(typeof e=="string"?e:e?.decision)==="allow"?"allow":"deny";function Ke({client:e="browser",read:t=()=>({}),write:a=null,bound:r={},choices:o=null,actions:h={},runtime:d=()=>({}),confirm:m=null,record:x=null,newTicket:w=()=>`s${Date.now().toString(36)}${Xe+=1}`}={}){const v=new Set(ie(e)),F={bound:r,actions:h,choices:o},R=n=>{const c=X(String(n||""));return c&&v.has(c.row.id)?c:null},T=n=>Re(n,F),S=(n,c)=>r[n.row.id]?.read?r[n.row.id].read():ve(c,n.row),E=(n,c)=>{const p=()=>{try{return typeof o=="function"?o(n.row.id,c):null}catch{return null}};return n.row.type==="picker"?p():n.row.options?.length?n.row.options:p()},V=n=>{try{x?.(n)}catch{}};function de(n,c){const p=T(n),i=p==="change"?E(n,c):null,k=Y(n.row,d()||{});return{id:n.row.id,label:n.row.label,where:_(n),...n.row.key||r[n.row.id]?.read?{value:le(n.row,S(n,c))}:{},can:p,type:n.row.type,...i?.length?{choices:i.slice(0,12).map($=>$[0])}:{},...h[n.row.id]?.args?{args:h[n.row.id].args}:{},...k.ok?{}:{blocked:k.reason},...n.row.pro?{pro:!0}:{},...n.row.help?{help:f(n.row.help,140)}:{}}}function pe({query:n=""}={}){const c=t()||{},p=Z(n,{rows:[...v],min:3,limit:8}).map(i=>i.id);return p.length?JSON.stringify({matches:p.map(i=>de(X(i),c)).filter(i=>i.can!=="none")}):JSON.stringify({matches:[],hint:"Nothing matched — try other words for the setting (what it does, or where it lives in Settings)."})}const ee=(n,c)=>({text:JSON.stringify({changed:!1,open:n.map(p=>p.id),say:`${c} Chap shows the person a card that opens it in Settings; do not say it changed.`}),card:{lang:"a2ui",source:Fe({items:n,why:c})}});async function fe({changes:n,reason:c="",id:p,value:i}={}){const k=Array.isArray(n)?n:p?[{id:p,value:i}]:[];if(!k.length)return JSON.stringify({error:'No change given. Pass {"changes":[{"id":"<from settings_find>","value":…}]}.'});if(k.length>M)return JSON.stringify({error:`At most ${M} changes on one card.`});const $=t()||{},J=d()||{},g=[],u=[],y=[];for(const l of k){const s=R(l?.id);if(!s){u.push({id:l?.id,why:"no such setting here — look it up with settings_find"});continue}const B=T(s);if(B==="open"){y.push({id:s.row.id,label:s.row.label,where:_(s)});continue}if(B!=="change"){u.push({id:s.row.id,why:B==="run"?"this is an action — use settings_run":"this one is shown, not set"});continue}const D=Y(s.row,J);if(!D.ok){u.push({id:s.row.id,why:`${D.reason}${D.fix?` (${D.fix})`:""}`});continue}const C=Ie(s.row,l.value,{options:E(s,$)});if(!C.ok){u.push({id:s.row.id,why:C.why});continue}const G=S(s,$),W=(G==null||G==="")&&s.row.stricter?.unset!==void 0?s.row.stricter.unset:G;if(JSON.stringify(W)===JSON.stringify(C.value))continue;if(s.group?.id==="privacy"&&!Le(s.row,W,C.value)){y.push({id:s.row.id,label:s.row.label,where:_(s)}),u.push({id:s.row.id,why:"that loosens privacy — the person changes it in Settings"});continue}const ne=E(s,$);if(ne?.find(U=>String(U[0])===String(C.value))?.[2]?.leaves===!0){y.push({id:s.row.id,label:s.row.label,where:_(s)}),u.push({id:s.row.id,why:"that choice sends your words off this device"});continue}const re=U=>{const oe=ne?.find(be=>String(be[0])===String(U));return oe?oe[1]:le(s.row,U)};g.push({e:s,value:C.value,item:{id:s.row.id,label:s.row.label,where:_(s),from:re(W),to:re(C.value)}})}if(y.length&&!g.length)return ee(y,u.length?`Not changed from the chat: ${u.map(l=>l.why).join("; ")}.`:"These are changed by the person in Settings, not from the chat.");if(!g.length)return u.length?JSON.stringify({changed:!1,refused:u}):JSON.stringify({changed:!1,unchanged:!0,say:"Already set that way — nothing to change."});if(typeof m!="function"||typeof a!="function"&&g.some(l=>!r[l.e.row.id]?.write))return JSON.stringify({changed:!1,error:"Settings cannot be changed from this chat here — the person can change them in Settings."});const j=w(),I=g.map(l=>l.item.id),N=g.length===1?`Change ${g[0].item.label}?`:`Change ${g.length} settings?`,O=g.map(l=>`${l.item.label}: ${l.item.from} → ${l.item.to}`).join(`
4
+ `),P=y.length?`Not on this card — change in Settings: ${y.map(l=>l.label).join(", ")}.`:"";let q="deny";try{q=ue(await m({kind:"change",title:N,detail:O,reason:f(c,200),card:he({title:N,items:g.map(l=>l.item),reason:c,ticket:j,note:P}),ticket:j,ids:I}))}catch{q="deny"}if(V({kind:"change",ids:I,decision:q==="allow"?"allow":"deny"}),q!=="allow")return JSON.stringify({changed:!1,declined:I,say:"The person kept their settings as they were. Do not propose this again unless they ask."});try{const l=g.filter(s=>!r[s.e.row.id]?.write);l.length&&await a(l.map(s=>({id:s.e.row.id,key:s.e.row.key,value:s.value})));for(const s of g)r[s.e.row.id]?.write&&await r[s.e.row.id].write(s.value)}catch(l){return JSON.stringify({changed:!1,error:`Could not save: ${f(l?.message||l,160)}`})}return JSON.stringify({changed:!0,now:g.map(l=>({id:l.item.id,label:l.item.label,value:l.item.to})),...u.length?{refused:u}:{},...y.length?{open:y.map(l=>l.id)}:{}})}async function ge({id:n,args:c={},reason:p=""}={}){const i=R(n);if(!i)return JSON.stringify({error:"No such action here — look it up with settings_find."});const k=T(i);if(k==="open")return ee([{id:i.row.id,label:i.row.label,where:_(i)}],`"${i.row.label}" is done by the person in Settings, not from the chat.`);if(k!=="run")return JSON.stringify({error:k==="change"?"This is a setting — propose it with settings_change.":"This one is shown, not run."});const $=Y(i.row,d()||{});if(!$.ok)return JSON.stringify({ran:!1,why:`${$.reason}${$.fix?` (${$.fix})`:""}`});const J=h[i.row.id],g=c&&typeof c=="object"?c:{};if(_e.has(i.row.id))V({kind:"run",ids:[i.row.id],decision:"look"});else{if(typeof m!="function")return JSON.stringify({ran:!1,error:"Actions cannot be run from this chat here — the person can run it in Settings."});let u="";try{u=J.preview?String(J.preview(g)||""):""}catch{u=""}const y=w(),j=`${i.row.label}?`,I={id:i.row.id,label:i.row.label,where:_(i),from:"now",to:f(u||i.row.help||i.row.label,80)},N=Ce[i.row.id]||"";let O="deny";try{const P=await m({kind:"run",title:j,detail:u||i.row.help||"",reason:f(p,200),card:he({title:j,items:[I],reason:p,ticket:y,allowLabel:i.row.label,mustType:N}),ticket:y,ids:[i.row.id],...N?{mustType:N}:{}});O=ue(P),N&&O==="allow"&&A(P?.typed)!==N&&(O="deny")}catch{O="deny"}if(V({kind:"run",ids:[i.row.id],decision:O==="allow"?"allow":"deny"}),O!=="allow")return JSON.stringify({ran:!1,declined:i.row.id,say:"The person chose not to. Do not ask again unless they do."})}try{const u=await J.run(g);return JSON.stringify({ran:!0,id:i.row.id,result:f(typeof u=="string"?u:JSON.stringify(u??""),1500)})}catch(u){return JSON.stringify({ran:!1,id:i.row.id,error:f(u?.message||u,200)})}}const te=Object.keys(h).some(n=>typeof h[n]?.run=="function"&&v.has(n)),we=[Me,Ve,...te?[Be]:[]],ye=Oe({name:se,description:"Chap's own settings — look up, propose a change (the person approves), run an action.",resident:We,inner:{specs:we,async execute(n,c={}){return n===z?pe(c):n===H?fe(c):n===ae&&te?ge(c):JSON.stringify({error:`Unknown settings action: ${n}`})}}});function me(n){const c=Z(n,{rows:[...v],min:10,limit:3}).map(i=>X(i.id)).filter(i=>i&&T(i)!=="none");return c.length?`[Chap] This may be about Chap's own settings: ${c.map(i=>`${i.row.label} (\`${i.row.id}\`, ${T(i)})`).join("; ")}. Through \`tools\`: {"action":"${z}","args":{"query":"…"}} for values and choices, then {"action":"${H}","args":{"changes":[{"id":"…","value":…}]}} — the person approves on a card.`:""}return{...ye,id:se,quiet:!0,hint:me}}function Qe(e,{client:t="browser"}={}){return Z(e,{rows:ie(t),min:10,limit:1}).length>0}const Ze=e=>ke(e);function et(e,t=[]){return(t||[]).filter(a=>a?.key).reduce((a,r)=>$e(a,r.key,r.value),e||{})}export{_e as LOOK_ONLY_ACTIONS,M as MAX_CHANGES,H as SETTINGS_CHANGE,K as SETTINGS_EVENTS,z as SETTINGS_FIND,se as SETTINGS_GROUP,ae as SETTINGS_RUN,Ce as TYPE_TO_RUN,et as applyChanges,Qe as asksAboutSettings,he as changeCard,Re as chatReachOf,Ie as coerceValue,Le as isStricter,Fe as openCard,Z as rankForMessage,Ke as settingsChatProvider,Ze as settingsLinkFor,le as shownValue};
package/sideline.js CHANGED
@@ -1,21 +1,21 @@
1
- import{approxTokens as y,queryTerms as k}from"./sources-retrieval.js";const I=Object.freeze(["sideline","breakout"]),L="bringback",m="thread";import{SIDELINE_SLASH_ITEMS as W}from"./slash-commands.js";function O(t){const e=/^\/(sideline|breakout)\b\s*([\s\S]*)$/i.exec(String(t||"").trim());if(!e)return null;let i=e[2].trim(),n=null;const r=/^@(?:(team|agent|cli|model):)?(?:"([^"]+)"|([^\s]+))\s*/i.exec(i);return r&&(n={kind:r[1]?r[1].toLowerCase():null,name:(r[2]||r[3]||"").trim()},i=i.slice(r[0].length).trim()),{question:i,target:n}}function j(t){const e=/^\/bringback\b\s*(full|brief)?\s*$/i.exec(String(t||"").trim());return e?{mode:e[1]?e[1].toLowerCase():"brief"}:null}function C(t,{teams:e=[],agents:i=[],clis:n=[],models:r=[]}={}){if(!t?.name)return null;const a=t.name.toLowerCase(),o=s=>String(s||"").toLowerCase()===a,l=[["team",e,s=>o(s.name)||o(s.id)],["agent",i,s=>o(s.name)||o(s.id)],["cli",n,s=>o(s.id)||o(s.label)||o(s.name)],["model",r,s=>o(s.id)||o(s.label)||o(s.model)||o(s.name)]];for(const[s,u,c]of l){if(t.kind&&t.kind!==s)continue;const h=(u||[]).find(d=>d&&c(d));if(h)return{kind:s,ref:h}}return null}function N(t=[]){return(t||[]).filter(e=>e&&(e.role==="user"||e.role==="assistant"))}const p=Object.freeze({chat:"message",sideline:"message",note:"section",meeting:"segment",run:"post",text:"part"});function x(t=""){const e=[];let i=null;const n=()=>{i&&i.text.trim()&&e.push({label:i.label,text:i.text.trim()}),i=null};for(const r of String(t||"").split(`
1
+ import{approxTokens as y,queryTerms as k}from"./sources-retrieval.js";const I=Object.freeze(["sideline","breakout"]),L="bringback",m="thread";import{SIDELINE_SLASH_ITEMS as G}from"./slash-commands.js";function O(t){const e=/^\/(sideline|breakout)\b\s*([\s\S]*)$/i.exec(String(t||"").trim());if(!e)return null;let i=e[2].trim(),n=null;const r=/^@(?:(team|agent|cli|model):)?(?:"([^"]+)"|([^\s]+))\s*/i.exec(i);return r&&(n={kind:r[1]?r[1].toLowerCase():null,name:(r[2]||r[3]||"").trim()},i=i.slice(r[0].length).trim()),{question:i,target:n}}function j(t){const e=/^\/bringback\b\s*(full|brief)?\s*$/i.exec(String(t||"").trim());return e?{mode:e[1]?e[1].toLowerCase():"brief"}:null}function C(t,{teams:e=[],agents:i=[],clis:n=[],models:r=[]}={}){if(!t?.name)return null;const a=t.name.toLowerCase(),o=s=>String(s||"").toLowerCase()===a,l=[["team",e,s=>o(s.name)||o(s.id)],["agent",i,s=>o(s.name)||o(s.id)],["cli",n,s=>o(s.id)||o(s.label)||o(s.name)||o(s.bridgeAgent)],["model",r,s=>o(s.id)||o(s.label)||o(s.model)||o(s.name)]];for(const[s,d,c]of l){if(t.kind&&t.kind!==s)continue;const h=(d||[]).find(u=>u&&c(u));if(h)return{kind:s,ref:h}}return null}function N(t=[]){return(t||[]).filter(e=>e&&(e.role==="user"||e.role==="assistant"))}const p=Object.freeze({chat:"message",sideline:"message",note:"section",meeting:"segment",run:"post",text:"part"});function x(t=""){const e=[];let i=null;const n=()=>{i&&i.text.trim()&&e.push({label:i.label,text:i.text.trim()}),i=null};for(const r of String(t||"").split(`
2
2
  `)){const a=/^(#{1,6})\s+(.*)$/.exec(r);if(a){n(),i={label:a[2].trim().slice(0,80)||"section",text:""};continue}if(!r.trim()){i&&!i.label?n():i&&(i.text+=`
3
3
  `);continue}i||(i={label:"",text:""}),i.text+=(i.text?`
4
- `:"")+r}return n(),e.map((r,a)=>({n:a+1,label:r.label||`paragraph ${a+1}`,text:r.text}))}function g(t){if(!t)return{kind:"text",title:"",units:[],focus:"",sources:[]};if(Array.isArray(t.units))return{kind:t.kind||"text",title:t.title||"",units:t.units,focus:t.focus||"",sources:t.sources||[]};const e=t.body||t,n=!!(t.sidelineOf||t.meta?.sidelineOf)?"sideline":t.kind||(Array.isArray(e.messages)?"chat":e.markdown!=null?"note":Array.isArray(e.segments)?"meeting":"text"),r=t.title||"",a=(e.attachments||[]).filter(o=>o&&o.kind!=="image"&&(o.title||o.url));if(n==="chat"||n==="sideline"){const o=N(e.messages||[]),l=[...o].reverse().find(u=>u.role==="user"),s=(e.messages||[]).flatMap(u=>(u.attachments||[]).filter(c=>c&&c.kind!=="image"&&c.kind!=="sideline"&&(c.title||c.url)));return{kind:n,title:r,sources:[...a,...s],units:o.map((u,c)=>({n:c+1,label:u.role,text:String(u.content||"")})),focus:String(l?.content||"")}}if(n==="note")return{kind:n,title:r,sources:a,units:x(e.markdown??e.text??""),focus:""};if(n==="meeting"){const o=Array.isArray(e.segments)?e.segments:[],l=o.length?o.map((s,u)=>({n:u+1,label:s.speaker||s.who||"speaker",text:String(s.text||"")})):x(e.summary?`# Summary
4
+ `:"")+r}return n(),e.map((r,a)=>({n:a+1,label:r.label||`paragraph ${a+1}`,text:r.text}))}function g(t){if(!t)return{kind:"text",title:"",units:[],focus:"",sources:[]};if(Array.isArray(t.units))return{kind:t.kind||"text",title:t.title||"",units:t.units,focus:t.focus||"",sources:t.sources||[]};const e=t.body||t,n=!!(t.sidelineOf||t.meta?.sidelineOf)?"sideline":t.kind||(Array.isArray(e.messages)?"chat":e.markdown!=null?"note":Array.isArray(e.segments)?"meeting":"text"),r=t.title||"",a=(e.attachments||[]).filter(o=>o&&o.kind!=="image"&&(o.title||o.url));if(n==="chat"||n==="sideline"){const o=N(e.messages||[]),l=[...o].reverse().find(d=>d.role==="user"),s=(e.messages||[]).flatMap(d=>(d.attachments||[]).filter(c=>c&&c.kind!=="image"&&c.kind!=="sideline"&&(c.title||c.url)));return{kind:n,title:r,sources:[...a,...s],units:o.map((d,c)=>({n:c+1,label:d.role,text:String(d.content||"")})),focus:String(l?.content||"")}}if(n==="note")return{kind:n,title:r,sources:a,units:x(e.markdown??e.text??""),focus:""};if(n==="meeting"){const o=Array.isArray(e.segments)?e.segments:[],l=o.length?o.map((s,d)=>({n:d+1,label:s.speaker||s.who||"speaker",text:String(s.text||"")})):x(e.summary?`# Summary
5
5
  ${e.summary}
6
6
 
7
7
  ${e.text||e.transcript||""}`:e.text||e.transcript||"");return{kind:n,title:r,sources:a,units:l,focus:String(e.summary||"").slice(0,240)}}if(n==="run"||Array.isArray(e.posts)){const o=e.posts||e.steps||[];return{kind:"run",title:r,sources:a,units:o.map((l,s)=>({n:s+1,label:l.actor||l.by||l.role||"post",text:String(l.text||l.content||"")})),focus:String(e.goal||e.request||"")}}return{kind:"text",title:r,sources:a,units:x(e.text||e.markdown||""),focus:""}}function A(t={}){const e=t.units?t:g(t.messages?{kind:"chat",title:t.title,body:{messages:t.messages,attachments:t.sources}}:t),i=p[e.kind]||"part",n=e.kind==="note"?"Main note":e.kind==="meeting"?"Meeting":e.kind==="run"?"Team run":"Main thread",r=String(e.focus||"").replace(/\s+/g," ").trim().slice(0,240),a=(e.sources||[]).map(l=>l?.title||l?.url).filter(Boolean).slice(0,6);return[`${n}${e.title?`: "${e.title}"`:""} — ${e.units.length} ${i}${e.units.length===1?"":"s"}, ~${y(e.units.map(l=>l.text).join(" "))} tokens.`,r?e.kind==="meeting"?`Summary: "${r}${r.length===240?"…":""}"`:`It is currently working on: "${r}${r.length===240?"…":""}"`:"",a.length?`Attached there: ${a.join(" · ")}.`:"",`Its content is NOT in this conversation. Call \`${m}\` to search it or read a range of ${i}s when the question depends on it — and only then.`].filter(Boolean).join(`
8
- `)}const q=Object.freeze({name:m,annotations:{readOnlyHint:!0,idempotentHint:!0},description:"Search or read what this sideline branched from — the main thread, note, meeting or run. Its content is not in this conversation; use this when the question depends on what was said or found there.",parameters:{type:"object",properties:{action:{type:"string",enum:["search","read","latest"],description:"search: parts matching a query (numbered). read: parts from..to by number. latest: the last n parts."},query:{type:"string",description:"For search: what you are looking for."},from:{type:"integer",description:"For read: first part number (1 = oldest)."},to:{type:"integer",description:"For read: last part number (inclusive)."},n:{type:"integer",description:"For latest: how many (default 4)."}},required:["action"],additionalProperties:!1}}),S=320;function T(t,e){const i=String(t||"").replace(/\s+/g," ").trim();if(i.length<=S)return i;const n=i.toLowerCase();let r=-1;for(const o of e)if(r=n.indexOf(o),r>=0)break;const a=Math.max(0,r-80);return`${a?"…":""}${i.slice(a,a+S)}…`}function $(t={},e={}){const i=t.units?t:g(t.messages?{kind:"chat",body:{messages:t.messages}}:t),n=i.units.map(o=>({n:o.n,role:o.label,text:String(o.text||"")})),r=String(e?.action||"latest");if(r==="search"){const o=k(e?.query);if(!o.length)return{error:"search needs a query."};const l=n.map(s=>({...s,score:o.reduce((u,c)=>u+(s.text.toLowerCase().includes(c)?Math.min(3,c.length/4):0),0)})).filter(s=>s.score>0).sort((s,u)=>u.score-s.score||s.n-u.n).slice(0,6).sort((s,u)=>s.n-u.n).map(s=>({n:s.n,role:s.role,snippet:T(s.text,o)}));return{of:n.length,hits:l,note:l.length?'Read a range with action "read" for the full text.':"Nothing there mentions that."}}if(r==="read"){const o=Math.max(1,Number(e?.from)||1),l=Math.min(n.length,Number(e?.to)||o);if(o>n.length)return{error:`There are ${n.length} ${p[i.kind]||"part"}s.`};const s=n.filter(d=>d.n>=o&&d.n<=l);let u=2e3*4;const c=[];let h=!1;for(const d of s){if(u<=0){h=!0;break}const f=d.text.length>u?`${d.text.slice(0,u)}…`:d.text;f.length<d.text.length&&(h=!0),u-=f.length,c.push({n:d.n,role:d.role,text:f})}return{of:n.length,from:o,to:l,messages:c,truncated:h}}const a=Math.max(1,Math.min(12,Number(e?.n)||4));return{of:n.length,messages:n.slice(-a).map(o=>({n:o.n,role:o.role,text:o.text.length>1600?`${o.text.slice(0,1600)}…`:o.text}))}}function _(t={},e="",{maxChars:i=2400}={}){const n=t.units?t:g(t.messages?{kind:"chat",title:t.title,body:{messages:t.messages}}:t),r=n.units.filter(c=>String(c.text||"").trim());if(!r.length)return"";const a=r.slice(-2).reverse().map(c=>c.n);if(k(e).length)for(const c of $(n,{action:"search",query:e}).hits||[])a.push(c.n);const o=new Map(r.map(c=>[c.n,c])),l=[];let s=0;for(const c of[...new Set(a)]){const h=o.get(c);if(!h)continue;const d=i-s;if(d<160)break;const f=String(h.text).replace(/\s+\n/g,`
9
- `).trim(),b=f.length>d?`${f.slice(0,d-1)}…`:f;l.push({n:c,label:h.label,text:b}),s+=b.length}l.sort((c,h)=>c.n-h.n);const u=p[n.kind]||"part";return[`From the main thread${n.title?` "${n.title}"`:""} — ${l.length} of its ${r.length} ${u}${r.length===1?"":"s"}: the latest, and what mentions this question. Answer the side question with this in mind${r.length>l.length?`; \`${m}\` reads the rest`:""}.`,...l.map(c=>`[${c.n}] ${c.label}: ${c.text}`)].join(`
10
- `)}function v(t={}){const e=t.units?t:g(t.messages?{kind:"chat",title:t.title,body:{messages:t.messages,attachments:t.sources}}:t),i=A(e);return{specs:[{...q}],system:i,systemParts:{thread:y(i)},async execute(n,r){if(n!==m)return JSON.stringify({error:`Unknown tool: ${n}`});const a=typeof r=="string"?JSON.parse(r||"{}"):r||{};return JSON.stringify($(e,a))}}}function P({title:t="",turns:e=[]}={}){const i=(e||[]).filter(n=>n&&(n.role==="user"||n.role==="assistant")).map(n=>`${n.role==="user"?"Asked":"Answered"}: ${String(n.content||"").trim()}`).join(`
8
+ `)}const q=Object.freeze({name:m,annotations:{readOnlyHint:!0,idempotentHint:!0},description:"Search or read what this sideline branched from — the main thread, note, meeting or run. Its content is not in this conversation; use this when the question depends on what was said or found there.",parameters:{type:"object",properties:{action:{type:"string",enum:["search","read","latest"],description:"search: parts matching a query (numbered). read: parts from..to by number. latest: the last n parts."},query:{type:"string",description:"For search: what you are looking for."},from:{type:"integer",description:"For read: first part number (1 = oldest)."},to:{type:"integer",description:"For read: last part number (inclusive)."},n:{type:"integer",description:"For latest: how many (default 4)."}},required:["action"],additionalProperties:!1}}),S=320;function T(t,e){const i=String(t||"").replace(/\s+/g," ").trim();if(i.length<=S)return i;const n=i.toLowerCase();let r=-1;for(const o of e)if(r=n.indexOf(o),r>=0)break;const a=Math.max(0,r-80);return`${a?"…":""}${i.slice(a,a+S)}…`}function $(t={},e={}){const i=t.units?t:g(t.messages?{kind:"chat",body:{messages:t.messages}}:t),n=i.units.map(o=>({n:o.n,role:o.label,text:String(o.text||"")})),r=String(e?.action||"latest");if(r==="search"){const o=k(e?.query);if(!o.length)return{error:"search needs a query."};const l=n.map(s=>({...s,score:o.reduce((d,c)=>d+(s.text.toLowerCase().includes(c)?Math.min(3,c.length/4):0),0)})).filter(s=>s.score>0).sort((s,d)=>d.score-s.score||s.n-d.n).slice(0,6).sort((s,d)=>s.n-d.n).map(s=>({n:s.n,role:s.role,snippet:T(s.text,o)}));return{of:n.length,hits:l,note:l.length?'Read a range with action "read" for the full text.':"Nothing there mentions that."}}if(r==="read"){const o=Math.max(1,Number(e?.from)||1),l=Math.min(n.length,Number(e?.to)||o);if(o>n.length)return{error:`There are ${n.length} ${p[i.kind]||"part"}s.`};const s=n.filter(u=>u.n>=o&&u.n<=l);let d=2e3*4;const c=[];let h=!1;for(const u of s){if(d<=0){h=!0;break}const f=u.text.length>d?`${u.text.slice(0,d)}…`:u.text;f.length<u.text.length&&(h=!0),d-=f.length,c.push({n:u.n,role:u.role,text:f})}return{of:n.length,from:o,to:l,messages:c,truncated:h}}const a=Math.max(1,Math.min(12,Number(e?.n)||4));return{of:n.length,messages:n.slice(-a).map(o=>({n:o.n,role:o.role,text:o.text.length>1600?`${o.text.slice(0,1600)}…`:o.text}))}}function _(t={},e="",{maxChars:i=2400}={}){const n=t.units?t:g(t.messages?{kind:"chat",title:t.title,body:{messages:t.messages}}:t),r=n.units.filter(c=>String(c.text||"").trim());if(!r.length)return"";const a=r.slice(-2).reverse().map(c=>c.n);if(k(e).length)for(const c of $(n,{action:"search",query:e}).hits||[])a.push(c.n);const o=new Map(r.map(c=>[c.n,c])),l=[];let s=0;for(const c of[...new Set(a)]){const h=o.get(c);if(!h)continue;const u=i-s;if(u<160)break;const f=String(h.text).replace(/\s+\n/g,`
9
+ `).trim(),b=f.length>u?`${f.slice(0,u-1)}…`:f;l.push({n:c,label:h.label,text:b}),s+=b.length}l.sort((c,h)=>c.n-h.n);const d=p[n.kind]||"part";return[`From the main thread${n.title?` "${n.title}"`:""} — ${l.length} of its ${r.length} ${d}${r.length===1?"":"s"}: the latest, and what mentions this question. Answer the side question with this in mind${r.length>l.length?`; \`${m}\` reads the rest`:""}.`,...l.map(c=>`[${c.n}] ${c.label}: ${c.text}`)].join(`
10
+ `)}function P(t={}){const e=t.units?t:g(t.messages?{kind:"chat",title:t.title,body:{messages:t.messages,attachments:t.sources}}:t),i=A(e);return{specs:[{...q}],system:i,systemParts:{thread:y(i)},async execute(n,r){if(n!==m)return JSON.stringify({error:`Unknown tool: ${n}`});const a=typeof r=="string"?JSON.parse(r||"{}"):r||{};return JSON.stringify($(e,a))}}}function v({title:t="",turns:e=[]}={}){const i=(e||[]).filter(n=>n&&(n.role==="user"||n.role==="assistant")).map(n=>`${n.role==="user"?"Asked":"Answered"}: ${String(n.content||"").trim()}`).join(`
11
11
 
12
12
  `);return[`This was a side conversation${t?` about "${t}"`:""}, held apart from a main thread that is still being worked on. Write the brief the main thread should receive.`,"Rules: at most 120 words. State what was asked, the answer, any decision or recommendation, and anything still open. Plain prose or up to four short bullets. No preamble, no headings, no restating the main thread.","",i].join(`
13
- `)}function B({sideline:t,mode:e="brief",brief:i="",now:n=Date.now,newId:r=()=>`sl_${Math.random().toString(36).slice(2,10)}`}={}){const a=(t?.turns||[]).filter(u=>u&&(u.role==="user"||u.role==="assistant")),o=a.map(u=>`${u.role==="user"?"Asked":"Answered"}: ${String(u.content||"").trim()}`).join(`
13
+ `)}function B({sideline:t,mode:e="brief",brief:i="",now:n=Date.now,newId:r=()=>`sl_${Math.random().toString(36).slice(2,10)}`}={}){const a=(t?.turns||[]).filter(d=>d&&(d.role==="user"||d.role==="assistant")),o=a.map(d=>`${d.role==="user"?"Asked":"Answered"}: ${String(d.content||"").trim()}`).join(`
14
14
 
15
- `),l=e==="full"?o:String(i||"").trim()||o,s=`From Sideline ${t?.index||1}${t?.model?` · ${t.model}`:""}`;return{id:r(),role:"note",kind:"sideline",ts:n(),content:l,sideline:{id:t?.id||null,index:t?.index||1,model:t?.model||"",turns:a.length,mode:e,broughtBackAt:n()},attachments:[{kind:"sideline",title:s,text:l}]}}function D(t=[]){const e=Array.isArray(t)?t:[];if(!e.some(r=>r?.role==="note"))return e;const i=[];let n=[];for(const r of e){if(r?.role==="note"){n.push(...r.attachments||[]);continue}if(r?.role==="user"&&n.length){i.push({...r,attachments:[...n,...r.attachments||[]]}),n=[];continue}i.push(r)}return i}function J(t=[]){return(t||[]).reduce((e,i)=>Math.max(e,Number(i?.index)||0),0)+1}function F(t,e){const i=[];let n=t,r=0;for(;n&&(n.sideline||n.meta?.sideline)&&r++<16;)i.unshift((n.sideline||n.meta?.sideline)?.index||1),n=e?.(n)||null;return i.join(".")}function U(t,e){if(t==="note"){const i=e.attachments?.[0]?.title||`From Sideline ${e.sideline?.index||1}`,n=String(e.content||"").trim().split(`
15
+ `),l=e==="full"?o:String(i||"").trim()||o,s=`From Sideline ${t?.index||1}${t?.model?` · ${t.model}`:""}`;return{id:r(),role:"note",kind:"sideline",ts:n(),content:l,sideline:{id:t?.id||null,index:t?.index||1,model:t?.model||"",turns:a.length,mode:e,broughtBackAt:n()},attachments:[{kind:"sideline",title:s,text:l}]}}function D(t=[]){const e=Array.isArray(t)?t:[];if(!e.some(r=>r?.role==="note"))return e;const i=[];let n=[];for(const r of e){if(r?.role==="note"){n.push(...r.attachments||[]);continue}if(r?.role==="user"&&n.length){i.push({...r,attachments:[...n,...r.attachments||[]]}),n=[];continue}i.push(r)}return i}function F(t=[]){return(t||[]).reduce((e,i)=>Math.max(e,Number(i?.index)||0),0)+1}function J(t,e){const i=[];let n=t,r=0;for(;n&&(n.sideline||n.meta?.sideline)&&r++<16;)i.unshift((n.sideline||n.meta?.sideline)?.index||1),n=e?.(n)||null;return i.join(".")}function H(t,e){if(t==="note"){const i=e.attachments?.[0]?.title||`From Sideline ${e.sideline?.index||1}`,n=String(e.content||"").trim().split(`
16
16
  `).map(r=>`> ${r}`).join(`
17
17
  `);return{kind:"markdown",markdown:`
18
18
 
19
19
  > **${i}**
20
20
  ${n}
21
- `}}return{kind:"message",message:e}}const w="sideline",E=Object.freeze({name:w,annotations:{readOnlyHint:!1,idempotentHint:!1},description:"Open a SIDELINE — a separate conversation about one question, apart from this one — and get its brief back. Use it to fork a sub-question to a team, an agent or another model without cluttering this thread; the sideline can search or read this thread with its own `thread` tool. Returns the brief (or the full text) when it is done.",parameters:{type:"object",properties:{question:{type:"string",description:"The question or task for the sideline, self-contained."},target:{type:"string",description:"Optional: who answers — a team name, an agent name, a CLI agent or a model id. Omit for the same model as this conversation."},bring:{type:"string",enum:["brief","full"],description:"What comes back: a brief (default) or the full exchange."}},required:["question"],additionalProperties:!1}});function H({run:t,depth:e=0,maxDepth:i=3}={}){if(typeof t!="function")throw new Error("sidelineToolProvider: run required");return{id:"sideline",specs:[{...E}],system:"You may fork a sub-question into a `sideline` (a team, an agent or a model works on it apart from this thread and you get the brief back). Use it for work that would otherwise clutter this thread; do not use it for a question you can answer directly.",async execute(n,r){if(n!==w)return JSON.stringify({error:`Unknown tool: ${n}`});const a=typeof r=="string"?JSON.parse(r||"{}"):r||{},o=String(a.question||"").trim();if(!o)return JSON.stringify({error:"question is required."});if(e>=i)return JSON.stringify({error:`Sidelines nest at most ${i} deep; answer this one here.`});const l=a.target&&O(`/sideline @${/\s/.test(String(a.target))?`"${a.target}"`:a.target} x`)?.target||null;try{const s=await t({question:o,target:l,bring:a.bring==="full"?"full":"brief"});return JSON.stringify({sideline:s?.index!=null?`Sideline ${s.index}`:"sideline",id:s?.id||null,model:s?.model||"",brief:String(s?.brief||"")})}catch(s){return JSON.stringify({error:`The sideline failed: ${s?.message||s}`})}}}}export{L as BRINGBACK_COMMAND,I as SIDELINE_COMMANDS,W as SIDELINE_SLASH_ITEMS,w as SIDELINE_TOOL_NAME,E as SIDELINE_TOOL_SPEC,m as THREAD_TOOL_NAME,q as THREAD_TOOL_SPEC,P as briefPrompt,U as foldBackFor,B as foldBackNote,D as foldNotes,J as nextSidelineIndex,x as noteUnits,j as parseBringBack,O as parseSideline,$ as readThread,C as resolveSidelineTarget,_ as sidelineExcerpt,F as sidelinePath,H as sidelineToolProvider,g as sourceOf,A as threadManifest,v as threadToolProvider};
21
+ `}}return{kind:"message",message:e}}const w="sideline",E=Object.freeze({name:w,annotations:{readOnlyHint:!1,idempotentHint:!1},description:"Get work that needs code done (python, a script, an xlsx/docx/pdf/pptx file) by a coding agent here — or hand any task to another agent, team or model — in a SIDELINE apart from this thread, and get its brief back. For code, target claude, codex or opencode with the whole task. Also forks a sub-question without cluttering this thread; the sideline can search or read this thread with its own `thread` tool. Returns the brief (or the full text) when it is done.",parameters:{type:"object",properties:{question:{type:"string",description:"The question or task for the sideline, self-contained."},target:{type:"string",description:"Optional: who answers — a team name, an agent name, a CLI agent or a model id. Omit for the same model as this conversation."},bring:{type:"string",enum:["brief","full"],description:"What comes back: a brief (default) or the full exchange."}},required:["question"],additionalProperties:!1}});function R({run:t,depth:e=0,maxDepth:i=3}={}){if(typeof t!="function")throw new Error("sidelineToolProvider: run required");return{id:"sideline",specs:[{...E}],system:"You may fork a sub-question into a `sideline` (a team, an agent or a model works on it apart from this thread and you get the brief back). Use it for work that would otherwise clutter this thread; do not use it for a question you can answer directly.",async execute(n,r){if(n!==w)return JSON.stringify({error:`Unknown tool: ${n}`});const a=typeof r=="string"?JSON.parse(r||"{}"):r||{},o=String(a.question||"").trim();if(!o)return JSON.stringify({error:"question is required."});if(e>=i)return JSON.stringify({error:`Sidelines nest at most ${i} deep; answer this one here.`});const l=a.target&&O(`/sideline @${/\s/.test(String(a.target))?`"${a.target}"`:a.target} x`)?.target||null;try{const s=await t({question:o,target:l,bring:a.bring==="full"?"full":"brief"});return JSON.stringify({sideline:s?.index!=null?`Sideline ${s.index}`:"sideline",id:s?.id||null,model:s?.model||"",brief:String(s?.brief||"")})}catch(s){return JSON.stringify({error:`The sideline failed: ${s?.message||s}`})}}}}export{L as BRINGBACK_COMMAND,I as SIDELINE_COMMANDS,G as SIDELINE_SLASH_ITEMS,w as SIDELINE_TOOL_NAME,E as SIDELINE_TOOL_SPEC,m as THREAD_TOOL_NAME,q as THREAD_TOOL_SPEC,v as briefPrompt,H as foldBackFor,B as foldBackNote,D as foldNotes,F as nextSidelineIndex,x as noteUnits,j as parseBringBack,O as parseSideline,$ as readThread,C as resolveSidelineTarget,_ as sidelineExcerpt,J as sidelinePath,R as sidelineToolProvider,g as sourceOf,A as threadManifest,P as threadToolProvider};
package/skill-files.js CHANGED
@@ -1,7 +1,13 @@
1
- import{skillHandle as y,skillPackageFiles as k}from"./skill-runtime.js";const u=24e3,g="skill_file";function x({skillRun:e,read:l}){return!(Array.isArray(e?.files)?e.files.filter(Boolean):[]).length||!e?.origin?.source||typeof l!="function"?null:{id:"skill-files",specs:[{name:g,description:"Read one reference file that the active skill ships. Only the exact paths listed in the skill instructions are available. Read one at a time, and only when the task needs it.",input_schema:{type:"object",properties:{path:{type:"string",description:"A reference path this skill's instructions point at, e.g. references/auth.md or foundry-agent/deploy/deploy.md"}},required:["path"]}}],async execute(h,d){if(h!==g)return null;const n=String(d?.path||"").trim();if(n.split("/")[0]==="scripts")return`${n} is a script — it runs, it is not read as text.`;try{const s=await l(e.origin,n),a=String(s?.text??"");return a.trim()?a.length>u?`${a.slice(0,u)}
1
+ import{skillHandle as x,skillPackageFiles as L,skillsNamed as k}from"./skill-runtime.js";const y=24e3,A="skill_file";function E({skillRun:e,read:i}){return!(Array.isArray(e?.files)?e.files.filter(Boolean):[]).length||!e?.origin?.source||typeof i!="function"?null:{id:"skill-files",specs:[{name:A,description:"Read one reference file that the active skill ships. Only the exact paths listed in the skill instructions are available. Read one at a time, and only when the task needs it.",input_schema:{type:"object",properties:{path:{type:"string",description:"A reference path this skill's instructions point at, e.g. references/auth.md or foundry-agent/deploy/deploy.md"}},required:["path"]}}],async execute(r,c){if(r!==A)return null;const p=String(c?.path||"").trim();if(p.split("/")[0]==="scripts")return`${p} is a script — it runs, it is not read as text.`;try{const l=await i(e.origin,p),o=String(l?.text??"");return o.trim()?o.length>y?`${o.slice(0,y)}
2
2
 
3
- …[truncated — ${a.length-u} more characters]`:a:`${n} is empty.`}catch(s){return`Could not read ${n}: ${s?.message||s}`}}}}function _(e,{prompt:l=e?.prompt??null}={}){return{command:y(e),name:e?.name||y(e),description:e?.description||"",files:k(e),origin:e?.origin?.source?{source:e.origin.source,id:e.origin.id||""}:null,prompt:l}}function L({entries:e=[],loadPrompt:l,read:m}){const h=e.filter(i=>i&&i.command);if(!h.length)return null;const d=new Map(h.map(i=>[i.command,i])),n=new Map,s=[{name:"skill_open",description:"Load a skill from the SKILLS AVAILABLE list to get its full instructions. Open one only when the request clearly matches it, then follow what it returns.",input_schema:{type:"object",properties:{name:{type:"string",enum:[...d.keys()].slice(0,60)}},required:["name"]}}];return typeof m=="function"&&h.some(i=>i.files?.length)&&s.push({name:"skill_file",description:"Read one reference file from a skill you have opened with skill_open.",input_schema:{type:"object",properties:{skill:{type:"string"},path:{type:"string"}},required:["skill","path"]}}),{id:"skill-discovery",specs:s,async execute(i,c){if(i==="skill_open"){const p=String(c?.name??c?.skill??c?.id??c?.command??"").trim().toLowerCase(),t=d.get(p);if(!t)return`No such skill. Available: ${[...d.keys()].join(", ")}`;n.set(t.command,t);let o="";try{o=await l(t)||""}catch(f){return`Could not load ${t.name}: ${f?.message||f}`}let r=o.trim()||"(this skill has no extra instructions — just apply it.)";return r+=`
3
+ …[truncated — ${o.length-y} more characters]`:o:`${p} is empty.`}catch(l){return`Could not read ${p}: ${l?.message||l}`}}}}function I(e,{prompt:i=e?.prompt??null}={}){return{command:x(e),name:e?.name||x(e),description:e?.description||"",files:L(e),scripts:(Array.isArray(e?.files?.scripts)?e.files.scripts:[]).filter(t=>typeof t=="string"&&t).slice(0,20),origin:e?.origin?.source?{source:e.origin.source,id:e.origin.id||""}:null,prompt:i}}const j={claude:"claude",codex:"codex",opencode:"opencode",copilot:"copilot",gemini:"antigravity",kiro:"kiro",pi:"pi",hermes:"hermes"};function N({entries:e=[],userText:i="",armed:t=!1,runsCode:r=!0,codingAgents:c=[],loadPrompt:p,read:l}={}){const o=k(e,i).map(g=>g.command);if(!e.length||!t&&!o.length)return{provider:null,named:o,handoff:!1};const f=q({entries:e,loadPrompt:p,read:l,runsCode:r,codingAgents:c,quiet:!t});return{provider:f,named:o,handoff:!!f&&S({entries:e,runsCode:r,codingAgents:c})}}function S({entries:e=[],runsCode:i=!0,codingAgents:t=[]}={}){return!i&&Array.isArray(t)&&t.length>0&&e.some(r=>r?.scripts?.length)}function B(e=[]){const i=(Array.isArray(e)?e:[]).filter(t=>t&&(t.viaBridge===!0||t.providerType==="agent"||t.provider_type==="agent")&&t.available!==!1).map(t=>String(t.bridgeAgent||t.id||"")).filter(Boolean);return[...new Set(i)]}function D(e,{entries:i=[],runsCode:t=!0,codingAgents:r=[]}={}){return!e||!S({entries:i,runsCode:t,codingAgents:r})?null:{...e,quiet:!0,system:""}}function T(e,i=[]){const t=(Array.isArray(i)?i:[]).filter(c=>typeof c=="string"&&c),r=j[String(e||"")];return(r&&t.includes(r)?r:t[0])||""}function q({entries:e=[],loadPrompt:i,read:t,runsCode:r=!0,quiet:c=!1,codingAgents:p=[]}){const l=e.filter(s=>s&&s.command);if(!l.length)return null;const o=new Map(l.map(s=>[s.command,s])),f=new Map,g=[{name:"skill_open",description:"Load a skill from the SKILLS AVAILABLE list to get its full instructions. Open one only when the request clearly matches it, then follow what it returns.",input_schema:{type:"object",properties:{name:{type:"string",enum:[...o.keys()].slice(0,60)},from:{type:"string",description:"Only when the person names another agent's copy: claude, codex, opencode, copilot, gemini, kiro, pi or hermes."}},required:["name"]}}];typeof t=="function"&&l.some(s=>s.files?.length)&&g.push({name:"skill_file",description:"Read one reference file from a skill you have opened with skill_open.",input_schema:{type:"object",properties:{skill:{type:"string"},path:{type:"string"}},required:["skill","path"]}});const _=s=>k(l,s).map(a=>a.command);function b(s){const a=k(l,s).slice(0,2);return a.length?`[Chap] The installed skill ${a.map(n=>`\`${n.command}\`${n.origin?.source?` (${n.origin.source})`:""}`).join(", ")} fits this message. Through \`tools\`: {"action":"skill_open","args":{"name":"${a[0].command}"}} loads its instructions; the conversation above is the material to use.`:""}return{id:"skill-discovery",...c?{quiet:!0}:{},hint:b,named:_,specs:g,async execute(s,a){if(s==="skill_open"){const u=String(a?.name??a?.skill??a?.id??a?.command??"").trim().toLowerCase(),n=o.get(u);if(!n)return`No such skill. Available: ${[...o.keys()].join(", ")}`;const h=String(a?.from??"").trim().toLowerCase(),d=!r&&n.scripts?.length?T(n.origin?.source,p):"",m=!r&&n.scripts?.length?d?`This skill runs scripts (${n.scripts.join(", ")}), and you do not run code yourself — you hand the job to a coding agent on this machine, which has this skill: call \`tools\` with {"action":"sideline","args":{"target":"${d}","question":"Use the ${n.command} skill to … — <the whole task, with every value it needs from this conversation>. Save the file in ~/Downloads and reply with its path."}}. When it answers, tell the person what was made and where. Never say a script ran unless the sideline says so.`:`This skill's scripts (${n.scripts.join(", ")}) run only where code runs — in a coding agent, and none is reachable from this chat right now. Do not say they ran: do what the instructions allow without them, and say plainly what would need them.`:"";if(m&&f.has(n.command)&&(f.get(n.command).from||"")===h)return`You opened \`${n.command}\` already — its instructions are above.${m?` Next: ${m}`:" Apply them now."}`;f.set(n.command,h?{...n,from:h}:n);let $="";try{$=await i(n,{from:h})||""}catch(v){return`Could not load ${n.name}: ${v?.message||v}`}let w=$.trim()||"(this skill has no extra instructions — just apply it.)";return w+=`
4
4
 
5
- To read a reference file this skill points at, call skill_file with skill="${t.command}" and the path exactly as written in the instructions above.`,r}if(i==="skill_file"){const p=n.get(String(c?.skill||"").trim().toLowerCase());if(!p)return"Open the skill first with skill_open, then read its files.";const t=String(c?.path||"").trim();if(t.split("/")[0]==="scripts")return`${t} is a script — it runs, it is not read as text.`;if(!p.origin?.source)return`${p.name} has no package files on disk.`;try{const o=await m(p.origin,t),r=String(o?.text??"");return r.trim()?r.length>u?`${r.slice(0,u)}
5
+ To read a reference file this skill points at, call skill_file with skill="${n.command}" and the path exactly as written in the instructions above.`,m&&(w=`${m}
6
6
 
7
- …[truncated — ${r.length-u} more characters]`:r:`${t} is empty.`}catch(o){return`Could not read ${t}: ${o?.message||o}`}}return null}}}export{g as SKILL_FILE_TOOL,L as skillDiscoveryProvider,_ as skillEntry,x as skillFileProvider};
7
+ ---
8
+
9
+ ${w}
10
+
11
+ ${m}`),w}if(s==="skill_file"){const u=f.get(String(a?.skill||"").trim().toLowerCase());if(!u)return"Open the skill first with skill_open, then read its files.";const n=String(a?.path||"").trim();if(n.split("/")[0]==="scripts")return`${n} is a script — it runs, it is not read as text.`;if(!u.origin?.source)return`${u.name} has no package files on disk.`;try{const h=await t(u.origin,n,{from:u.from||""}),d=String(h?.text??"");return d.trim()?d.length>y?`${d.slice(0,y)}
12
+
13
+ …[truncated — ${d.length-y} more characters]`:d:`${n} is empty.`}catch(h){return`Could not read ${n}: ${h?.message||h}`}}return null}}}export{A as SKILL_FILE_TOOL,B as codingAgentsIn,T as handoffAgent,D as handoffSideline,S as needsHandoff,N as skillDiscoveryForTurn,q as skillDiscoveryProvider,I as skillEntry,E as skillFileProvider};
package/skill-runtime.js CHANGED
@@ -1,5 +1,5 @@
1
- import{sourceCitationSystem as g}from"./tool-hints.js";function y(e){const t=String(e||"none").toLowerCase();return t==="chat"||t==="chats"?"chats":t==="meeting"||t==="meetings"?"meetings":t==="all"||t==="both"||t==="history"?"all":"none"}function w(e){const t=String(e||"none").toLowerCase();return t==="none"||t==="off"?"none":t==="selected"||t==="select"?"selected":"default"}function S(e){return(e||[]).filter(t=>t&&t.enabled!==!1&&(t.url||t.command||t.tools?.length))}function b(e){return!!e&&e.enabled!==!1}function d(e){return(Array.isArray(e)?e:[]).filter(b)}function I(e={},{includeMeetings:t=!1}={}){const o=y(e.historyContext);let s=null;if(o!=="none"){const n=o==="meetings"||o==="all",r=n&&!t?"meetings":"";s={enabled:!r,scope:o,includeMeetings:n&&!!t,requested:o,...r?{blocked:r}:{}}}return{skillId:e.id||"",history:s,mcp:{mode:w(e.mcpMode),serverIds:Array.isArray(e.mcpServerIds)?e.mcpServerIds.filter(Boolean):[]},files:C(e),origin:e.origin&&e.origin.source?{source:e.origin.source,id:e.origin.id||""}:null,hosts:Array.isArray(e.sandboxHosts)?e.sandboxHosts.filter(n=>typeof n=="string"&&n):[]}}function C(e){const t=e?.files;if(!t||typeof t!="object")return[];const o=[];for(const s of["references","assets","templates","examples"])for(const n of Array.isArray(t[s])?t[s]:[])typeof n=="string"&&n&&o.push(`${s}/${n}`);return o.slice(0,60)}function x(e,t){const o=S(e),s=t?.mcp?.mode||"none";if(s==="none")return[];if(s!=="selected")return o;const n=new Set(t?.mcp?.serverIds||[]);return n.size?o.filter(r=>n.has(r.id)):[]}function $(e){const t=(e.tools||[]).map(o=>o.name).filter(Boolean).slice(0,12);return t.length?`${e.name||e.id}: ${t.join(", ")}`:`${e.name||e.id}`}function j(e,t=[]){if(!e)return"";const o=[];if(e.history?.enabled){const s=e.history.scope==="all"?"chat and meeting history":e.history.scope==="meetings"?"meeting history":"chat history";o.push(`This skill has ${s} tools available. Use history_search first when prior local context would improve the answer, then history_get_source or history_related when useful.`)}if(e.history?.blocked==="meetings"&&o.push("Meeting history was requested for this skill, but it is not available for the current plan."),e.files?.length&&o.push(`This skill ships reference files: ${e.files.join(", ")}. Their contents are NOT included above. Call skill_file with one of those exact paths to read one, and only when the task needs it — read the smallest set that answers the question.`),e.mcp?.mode==="none")o.push("MCP tools are disabled for this skill.");else if(e.mcp?.mode==="selected"){const s=x(t,e);s.length?o.push(`This skill is scoped to these MCP servers/tools: ${s.map($).join(" | ")}. Prefer these tools when they help complete the skill.`):o.push("This skill selected MCP tools, but none of the selected MCP servers are currently enabled.")}return(e.history?.enabled||e.mcp?.mode==="selected"||e.mcp?.mode==="default")&&o.push(g()),o.join(`
2
- `)}function u(e){return String(e?.command||e?.name||"").trim().toLowerCase()}const A=14;function L(e,t){if(!t.size)return 0;const o=`${e.name} ${e.command} ${e.description||""}`.toLowerCase(),s=new Set(o.split(/\W+/).filter(r=>r.length>3));let n=0;for(const r of t)s.has(r)&&(n+=1);return n}function v(e,t=""){const o=d(e),s=new Set(String(t||"").toLowerCase().split(/\W+/).filter(n=>n.length>3));return o.map((n,r)=>({s:n,i:r,score:L(n,s)})).sort((n,r)=>r.score-n.score||n.i-r.i).map(n=>n.s)}const M=(e,t)=>e.length>t?`${e.slice(0,t-1).trimEnd()}…`:e;function P(e,{userText:t="",cap:o=A}={}){const s=d(e),n=v(e,t);if(!n.length)return"";let r=n.slice(0,o);const c=String(t||"").toLowerCase();if(c){const i=n.filter(l=>{const f=u(l),h=String(l.name||"").toLowerCase();return f&&c.includes(f)||h.length>2&&c.includes(h)});for(const l of i)r.includes(l)||(r=[l,...r].slice(0,o))}const a=new Map(s.map((i,l)=>[i,l]));r=[...r].sort((i,l)=>(a.get(i)??0)-(a.get(l)??0));const m=i=>`- ${u(i)||i.name}: ${M(String(i.description||i.name),90)}`,p=n.length>r.length?`
3
- (+${n.length-r.length} more — the user can type /command to run any skill directly.)`:"";return["SKILLS AVAILABLE — reusable procedures the user has set up. If the request clearly matches one, call skill_open with its name to load its full instructions, then follow them. For a simple or unrelated request, answer directly and do not open a skill.",r.map(m).join(`
4
- `)+p].join(`
5
- `)}export{d as enabledSkills,x as filterMcpServersForSkill,b as isSkillEnabled,v as rankSkills,P as skillCatalogSystem,u as skillHandle,C as skillPackageFiles,I as skillRunFromSkill,j as skillToolSystem};
1
+ import{sourceCitationSystem as u}from"./tool-hints.js";function p(e){const t=String(e||"none").toLowerCase();return t==="chat"||t==="chats"?"chats":t==="meeting"||t==="meetings"?"meetings":t==="all"||t==="both"||t==="history"?"all":"none"}function g(e){const t=String(e||"none").toLowerCase();return t==="none"||t==="off"?"none":t==="selected"||t==="select"?"selected":"default"}function y(e){return(e||[]).filter(t=>t&&t.enabled!==!1&&(t.url||t.command||t.from||t.tools?.length))}function S(e){return!!e&&e.enabled!==!1}function h(e){return(Array.isArray(e)?e:[]).filter(S)}function I(e={},{includeMeetings:t=!1}={}){const n=p(e.historyContext);let s=null;if(n!=="none"){const o=n==="meetings"||n==="all",r=o&&!t?"meetings":"";s={enabled:!r,scope:n,includeMeetings:o&&!!t,requested:n,...r?{blocked:r}:{}}}return{skillId:e.id||"",history:s,mcp:{mode:g(e.mcpMode),serverIds:Array.isArray(e.mcpServerIds)?e.mcpServerIds.filter(Boolean):[]},files:w(e),origin:e.origin&&e.origin.source?{source:e.origin.source,id:e.origin.id||""}:null,hosts:Array.isArray(e.sandboxHosts)?e.sandboxHosts.filter(o=>typeof o=="string"&&o):[]}}function w(e){const t=e?.files;if(!t||typeof t!="object")return[];const n=[];for(const s of["references","assets","templates","examples"])for(const o of Array.isArray(t[s])?t[s]:[])typeof o=="string"&&o&&n.push(`${s}/${o}`);return n.slice(0,60)}function b(e,t){const n=y(e),s=t?.mcp?.mode||"none";if(s==="none")return[];if(s!=="selected")return n;const o=new Set(t?.mcp?.serverIds||[]);return o.size?n.filter(r=>o.has(r.id)):[]}function x(e){const t=(e.tools||[]).map(n=>n.name).filter(Boolean).slice(0,12);return t.length?`${e.name||e.id}: ${t.join(", ")}`:`${e.name||e.id}`}function T(e,t=[]){if(!e)return"";const n=[];if(e.history?.enabled){const s=e.history.scope==="all"?"chat and meeting history":e.history.scope==="meetings"?"meeting history":"chat history";n.push(`This skill has ${s} tools available. Use history_search first when prior local context would improve the answer, then history_get_source or history_related when useful.`)}if(e.history?.blocked==="meetings"&&n.push("Meeting history was requested for this skill, but it is not available for the current plan."),e.files?.length&&n.push(`This skill ships reference files: ${e.files.join(", ")}. Their contents are NOT included above. Call skill_file with one of those exact paths to read one, and only when the task needs it — read the smallest set that answers the question.`),e.mcp?.mode==="none")n.push("MCP tools are disabled for this skill.");else if(e.mcp?.mode==="selected"){const s=b(t,e);s.length?n.push(`This skill is scoped to these MCP servers/tools: ${s.map(x).join(" | ")}. Prefer these tools when they help complete the skill.`):n.push("This skill selected MCP tools, but none of the selected MCP servers are currently enabled.")}return(e.history?.enabled||e.mcp?.mode==="selected"||e.mcp?.mode==="default")&&n.push(u()),n.join(`
2
+ `)}function m(e){return String(e?.command||e?.name||"").trim().toLowerCase()}const C=14;function A(e,t){if(!t.size)return 0;const n=`${e.name} ${e.command} ${e.description||""}`.toLowerCase(),s=new Set(n.split(/\W+/).filter(r=>r.length>3));let o=0;for(const r of t)s.has(r)&&(o+=1);return o}function $(e,t=""){const n=h(e),s=new Set(String(t||"").toLowerCase().split(/\W+/).filter(o=>o.length>3));return n.map((o,r)=>({s:o,i:r,score:A(o,s)})).sort((o,r)=>r.score-o.score||o.i-r.i).map(o=>o.s)}function L(e,t=""){const n=String(t||"").toLowerCase();if(!n)return[];const s=new Set(n.split(/[^a-z0-9_-]+/).filter(Boolean)),o=(l,i)=>{if(l.length!==i.length||i.length<4||l===i)return!1;const c=[...l].findIndex((d,a)=>d!==i[a]);return c>=0&&c<l.length-1&&l[c]===i[c+1]&&l[c+1]===i[c]&&l.slice(c+2)===i.slice(c+2)},r=l=>[m(l),String(l?.command||""),String(l?.name||"")].map(i=>i.toLowerCase()).filter(i=>i.length>2);return(Array.isArray(e)?e:[]).filter(l=>r(l).some(i=>(/[^a-z0-9]/.test(i)?n.includes(i)||n.includes(i.replace(/[-_]+/g," ")):s.has(i))||[...s].some(c=>o(c,i))))}const v=(e,t)=>e.length>t?`${e.slice(0,t-1).trimEnd()}…`:e;function _(e,{userText:t="",cap:n=C}={}){const s=h(e),o=$(e,t);if(!o.length)return"";let r=o.slice(0,n);const l=new Set(L(o,t));for(const a of o.filter(f=>l.has(f)))r.includes(a)||(r=[a,...r].slice(0,n));const i=new Map(s.map((a,f)=>[a,f]));r=[...r].sort((a,f)=>(i.get(a)??0)-(i.get(f)??0));const c=a=>`- ${m(a)||a.name}: ${v(String(a.description||a.name),90)}`,d=o.length>r.length?`
3
+ (+${o.length-r.length} more — the user can type /command to run any skill directly.)`:"";return["SKILLS AVAILABLE — reusable procedures the user has set up. If the request clearly matches one, call skill_open with its name to load its full instructions, then follow them. For a simple or unrelated request, answer directly and do not open a skill.",r.map(c).join(`
4
+ `)+d].join(`
5
+ `)}export{h as enabledSkills,b as filterMcpServersForSkill,S as isSkillEnabled,$ as rankSkills,_ as skillCatalogSystem,m as skillHandle,w as skillPackageFiles,I as skillRunFromSkill,T as skillToolSystem,L as skillsNamed};
package/slash-commands.js CHANGED
@@ -1 +1 @@
1
- function f(e){return String(e||"").toLowerCase().replace(/^\//,"").replace(/\s+/g," ")}function g(e){return{type:"skill",command:e.command||"",icon:e.icon||"🎓",description:e.description||e.name||"",skill:e}}function h(e){return{type:"recipe",command:e.name||"",icon:"🧩",description:e.description||"Saved recipe",recipe:e}}function S(e){const n=!!e.origin?.agent;return{type:"team",command:e.name||"",icon:n?"🧑‍💻":"🧑‍🤝‍🧑",description:e.description||(n?"Agent":"Agent team"),team:e,...n?{agent:e.origin.agent}:{}}}function x(e){return!!e&&e.enabled!==!1}function s(e){return(Array.isArray(e)?e:[]).filter(x)}function w({builtins:e=[],skills:n=[],recipes:t=[],teams:i=[],prefix:o="",skillsAllowed:c=!1,features:m={}}={}){const a=f(o),u=(Array.isArray(e)?e:[]).map(r=>({type:"builtin",...r,locked:!!r.feature&&!m[r.feature]})),l=c?s(n).map(g):[],d=(t||[]).filter(r=>r&&r.enabled!==!1&&r.name).map(h),p=(i||[]).filter(r=>r&&r.enabled!==!1&&r.name).map(S);return[...u,...l,...d,...p].filter(r=>!(r.typed&&!a)).filter(r=>r.command&&r.command.toLowerCase().startsWith(a)).slice(0,12)}const b=Object.freeze([{command:"sideline",icon:"⇲",description:"Ask on the side without stopping this thread — @ a team, agent or model to hand it elsewhere"},{command:"bringback",icon:"⇱",description:'Fold the open sideline into this thread as a brief (or "full")'},{command:"breakout",icon:"⇲",description:"Same as /sideline"}]),$=Object.freeze([{command:"new",icon:"✚",description:"Start a new chat — this one stays in history"},{command:"clear",icon:"✚",description:"Same as /new"}]);function I(e){const n=/^\/(new|clear)\s*$/i.exec(String(e||"").trim());return n?{command:n[1].toLowerCase()}:null}const L=Object.freeze([{command:"bug",icon:"🐞",description:"Report a problem — a GitHub issue with this app’s diagnostics, shown to you first",typed:!0}]);function _(e){const n=/^\/bug(?:\s+([\s\S]*))?$/i.exec(String(e||"").trim());return n?{title:(n[1]||"").trim().replace(/\s+/g," ")}:null}const y=/^\/([a-z0-9_-]*(?:\s+[a-z0-9_-]*)?)$/i;function A(e,n=[]){const t=/^\/([a-z0-9_-]+)\s*([\s\S]*)$/i.exec(String(e||""));if(!t)return null;const i=s(n).find(o=>String(o.command||"").toLowerCase()===t[1].toLowerCase());return i?{skill:i,args:t[2].trim()}:null}function C(e,n=[]){const t=/^\/([a-z0-9_-]+)\s*([\s\S]*)$/i.exec(String(e||""));if(!t)return null;const i=(n||[]).find(o=>o&&o.enabled!==!1&&String(o.name||"").toLowerCase()===t[1].toLowerCase());return i?{recipe:i,args:t[2].trim()}:null}function z(e,n=""){const t=String(n||"").trim();return`Run the saved recipe "${e.name}"${t?` with this input: ${t}`:""}. Use the recipe tool; if a parameter is missing, ask for it.`}function E(e,n=[]){const t=/^\/([a-z0-9_-]+)\s*([\s\S]*)$/i.exec(String(e||""));if(!t)return null;const i=(n||[]).find(o=>o&&o.enabled!==!1&&String(o.name||"").toLowerCase()===t[1].toLowerCase());return i?{team:i,args:t[2].trim()}:null}function T(e,n=""){const t=String(n||"").trim();return e.origin?.agent?`Run the agent "${e.name}" (a one-role team of that name)${t?` on this request: ${t}`:""}. Use the team tool; if the request is unclear, ask first.`:`Run the saved team "${e.name}"${t?` on this request: ${t}`:""}. Use the team tool; if the request is unclear, ask first.`}function R(e){return e?.command?`/${e.command} `:"/"}function k(e,n=""){return e?.command?{command:e.command,args:String(n||"").trim(),name:e.name||"",icon:e.icon||"🎓"}:null}function H(e){return e?.command?`/${e.command}${e.args?` ${e.args}`:""}`:""}export{L as BUG_REPORT_SLASH_ITEMS,$ as NEW_THREAD_SLASH_ITEMS,b as SIDELINE_SLASH_ITEMS,y as SLASH_TYPING_RE,s as enabledSkills,x as isSkillEnabled,C as matchSlashRecipe,A as matchSlashSkill,E as matchSlashTeam,_ as parseBugCommand,I as parseNewThread,z as recipeInvocationText,H as skillInvocationLabel,k as skillInvocationOf,R as slashCommandInsert,w as slashCommandItems,T as teamInvocationText};
1
+ function x(e){return String(e||"").toLowerCase().replace(/^\//,"").replace(/\s+/g," ")}function c(e){return{type:"skill",command:e.command||"",icon:e.icon||"🎓",description:e.description||e.name||"",skill:e}}function w(e){return{type:"recipe",command:e.name||"",icon:"🧩",description:e.description||"Saved recipe",recipe:e}}function b(e){const t=!!e.origin?.agent;return{type:"team",command:e.name||"",icon:t?"🧑‍💻":"🧑‍🤝‍🧑",description:e.description||(t?"Agent":"Agent team"),team:e,...t?{agent:e.origin.agent}:{}}}function I(e){return!!e&&e.enabled!==!1}function m(e){return(Array.isArray(e)?e:[]).filter(I)}function $({builtins:e=[],skills:t=[],recipes:o=[],teams:a=[],prefix:r="",skillsAllowed:d=!1,features:u={},machineSkills:l=[]}={}){const i=x(r),p=(Array.isArray(e)?e:[]).map(n=>({type:"builtin",...n,locked:!!n.feature&&!u[n.feature]})),s=d?m(t).map(c):[],f=new Set(s.map(n=>n.command)),h=(l||[]).filter(n=>n?.command&&n.enabled!==!1&&!f.has(n.command)).map(n=>({...c(n),machine:!0,icon:"🧰"})),S=(o||[]).filter(n=>n&&n.enabled!==!1&&n.name).map(w),g=(a||[]).filter(n=>n&&n.enabled!==!1&&n.name).map(b);return[...p,...s,...S,...g,...h].filter(n=>!(n.typed&&!i)).filter(n=>n.command&&n.command.toLowerCase().startsWith(i)).slice(0,12)}const L=Object.freeze([{command:"sideline",icon:"⇲",description:"Ask on the side without stopping this thread — @ a team, agent or model to hand it elsewhere"},{command:"bringback",icon:"⇱",description:'Fold the open sideline into this thread as a brief (or "full")'},{command:"breakout",icon:"⇲",description:"Same as /sideline"}]),_=Object.freeze([{command:"new",icon:"✚",description:"Start a new chat — this one stays in history"},{command:"clear",icon:"✚",description:"Same as /new"}]);function y(e){const t=/^\/(new|clear)\s*$/i.exec(String(e||"").trim());return t?{command:t[1].toLowerCase()}:null}const C=Object.freeze([{command:"bug",icon:"🐞",description:"Report a problem — a GitHub issue with this app’s diagnostics, shown to you first",typed:!0}]);function A(e){const t=/^\/bug(?:\s+([\s\S]*))?$/i.exec(String(e||"").trim());return t?{title:(t[1]||"").trim().replace(/\s+/g," ")}:null}const z=/^\/([a-z0-9_-]*(?:\s+[a-z0-9_-]*)?)$/i;function E(e,t=[]){const o=/^\/([a-z0-9_-]+)\s*([\s\S]*)$/i.exec(String(e||""));if(!o)return null;const a=m(t).find(r=>String(r.command||"").toLowerCase()===o[1].toLowerCase());return a?{skill:a,args:o[2].trim()}:null}function T(e,t=[]){const o=/^\/([a-z0-9_-]+)\s*([\s\S]*)$/i.exec(String(e||""));if(!o)return null;const a=(t||[]).find(r=>r&&r.enabled!==!1&&String(r.name||"").toLowerCase()===o[1].toLowerCase());return a?{recipe:a,args:o[2].trim()}:null}function R(e,t=""){const o=String(t||"").trim();return`Run the saved recipe "${e.name}"${o?` with this input: ${o}`:""}. Use the recipe tool; if a parameter is missing, ask for it.`}function H(e,t=[]){const o=/^\/([a-z0-9_-]+)\s*([\s\S]*)$/i.exec(String(e||""));if(!o)return null;const a=(t||[]).find(r=>r&&r.enabled!==!1&&String(r.name||"").toLowerCase()===o[1].toLowerCase());return a?{team:a,args:o[2].trim()}:null}function k(e,t=""){const o=String(t||"").trim();return e.origin?.agent?`Run the agent "${e.name}" (a one-role team of that name)${o?` on this request: ${o}`:""}. Use the team tool; if the request is unclear, ask first.`:`Run the saved team "${e.name}"${o?` on this request: ${o}`:""}. Use the team tool; if the request is unclear, ask first.`}function O(e){return e?.command?`/${e.command} `:"/"}function q(e,t=""){return e?.command?{command:e.command,args:String(t||"").trim(),name:e.name||"",icon:e.icon||"🎓"}:null}function v(e){return e?.command?`/${e.command}${e.args?` ${e.args}`:""}`:""}export{C as BUG_REPORT_SLASH_ITEMS,_ as NEW_THREAD_SLASH_ITEMS,L as SIDELINE_SLASH_ITEMS,z as SLASH_TYPING_RE,m as enabledSkills,I as isSkillEnabled,T as matchSlashRecipe,E as matchSlashSkill,H as matchSlashTeam,A as parseBugCommand,y as parseNewThread,R as recipeInvocationText,v as skillInvocationLabel,q as skillInvocationOf,O as slashCommandInsert,$ as slashCommandItems,k as teamInvocationText};