@chatpanel/events 0.433.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/events",
3
- "version": "0.433.0",
3
+ "version": "0.446.0",
4
4
  "description": "The canonical ChatPanel event-log and capability contracts — typed durable facts, clock-free deterministic linearization, schema upcasting, and the invariants the replay harness asserts. Pure, dependency-free ESM shared by the ChatPanel extension, gateway and bridge.",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -69,6 +69,7 @@
69
69
  "./client-prefs.js": "./client-prefs.js",
70
70
  "./composer-chips.js": "./composer-chips.js",
71
71
  "./settings-registry.js": "./settings-registry.js",
72
+ "./settings-chat.js": "./settings-chat.js",
72
73
  "./feature-map.js": "./feature-map.js",
73
74
  "./context-attachments.js": "./context-attachments.js",
74
75
  "./context-breakdown.js": "./context-breakdown.js",
@@ -108,6 +109,9 @@
108
109
  "./sideline.js": "./sideline.js",
109
110
  "./mcp-client.js": "./mcp-client.js",
110
111
  "./mcp-config-import.js": "./mcp-config-import.js",
112
+ "./agent-mcp.js": "./agent-mcp.js",
113
+ "./mentions.js": "./mentions.js",
114
+ "./agent-mcp-host.js": "./agent-mcp-host.js",
111
115
  "./mcp-args-env.js": "./mcp-args-env.js",
112
116
  "./mcp-dispatch.js": "./mcp-dispatch.js",
113
117
  "./mcp-errors.js": "./mcp-errors.js",
@@ -422,6 +426,7 @@
422
426
  "client-prefs.js",
423
427
  "composer-chips.js",
424
428
  "settings-registry.js",
429
+ "settings-chat.js",
425
430
  "feature-map.js",
426
431
  "context-attachments.js",
427
432
  "context-breakdown.js",
@@ -464,6 +469,9 @@
464
469
  "sideline.js",
465
470
  "mcp-client.js",
466
471
  "mcp-config-import.js",
472
+ "agent-mcp.js",
473
+ "mentions.js",
474
+ "agent-mcp-host.js",
467
475
  "mcp-args-env.js",
468
476
  "mcp-dispatch.js",
469
477
  "mcp-errors.js",
@@ -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};
@@ -0,0 +1,4 @@
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};