shadow-claw 1.34.5 → 1.35.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/.well-known/mcp/server-card.json +1 -1
- package/.well-known/mcp.json +1 -1
- package/README.md +5 -1
- package/dist/cli/chunk-BCLxzLO92.js +5 -0
- package/dist/cli/chunk-BHNCi3ui2.js +1 -0
- package/dist/cli/chunk-BMPhLSn8.js +1 -0
- package/dist/cli/chunk-BMW6QB5-2.js +27 -0
- package/dist/cli/chunk-BQCWtrzh.js +1 -0
- package/dist/cli/chunk-BQCWtrzh2.js +1 -0
- package/dist/cli/chunk-BdJUjMuz.js +1 -0
- package/dist/cli/chunk-C47WdxKx2.js +1 -0
- package/dist/cli/{chunk-D9dku_3t.js → chunk-CAqvQuGr.js} +1 -1
- package/dist/cli/{chunk-DoVxObGa2.js → chunk-CHzhUS1N2.js} +1 -1
- package/dist/cli/chunk-CUMlq7Jw2.js +263 -0
- package/dist/cli/chunk-CXi9LU9e2.js +110 -0
- package/dist/cli/chunk-ChefnX-r.js +110 -0
- package/dist/cli/{chunk-zvi71-77.js → chunk-D3JxbzjI2.js} +15 -15
- package/dist/cli/chunk-D7VYMl092.js +1 -0
- package/dist/cli/chunk-DNIduiJ82.js +91 -0
- package/dist/cli/{chunk-C4UfzPK4.js → chunk-DTbrldk_.js} +1 -1
- package/dist/cli/chunk-DZ8YBXax.js +969 -0
- package/dist/cli/chunk-DduRvw8B2.js +1 -0
- package/dist/cli/chunk-DnYxGjdu2.js +1 -0
- package/dist/cli/chunk-Ea7nXmgb2.js +1 -0
- package/dist/cli/{chunk-BRiGkTIi.js → chunk-EohNY8vW.js} +1 -1
- package/dist/cli/chunk-LIIpZlwP2.js +1 -0
- package/dist/cli/chunk-LIJZHJml2.js +1 -0
- package/dist/cli/chunk-MHBh2BgF2.js +91 -0
- package/dist/cli/{chunk-BQ7lHA7c.js → chunk-SKgLGyTY.js} +1 -1
- package/dist/cli/chunk-kcJSXcbq2.js +1 -0
- package/dist/cli/cli.js +12 -11
- package/dist/headless-agent.js +191 -187
- package/dist/lib/components/index.js +21 -21
- package/dist/lib/components/settings/shadow-claw-channel-config.js +1 -1
- package/dist/lib/components/settings/shadow-claw-control-plane.js +1 -1
- package/dist/lib/components/settings/shadow-claw-git.js +1 -1
- package/dist/lib/components/settings/shadow-claw-llm.js +1 -1
- package/dist/lib/components/settings/shadow-claw-networking.js +1 -1
- package/dist/lib/components/settings/shadow-claw-notifications.js +1 -1
- package/dist/lib/components/settings/shadow-claw-peerjs.js +1 -1
- package/dist/lib/components/settings/shadow-claw-storage.js +1 -1
- package/dist/lib/components/settings/shadow-claw-task-server.js +1 -1
- package/dist/lib/components/settings/shadow-claw-webvm.js +1 -1
- package/dist/lib/components/shadow-claw-channel-config.js +1 -1
- package/dist/lib/components/shadow-claw-channels.js +1 -1
- package/dist/lib/components/shadow-claw-chat.js +1 -1
- package/dist/lib/components/shadow-claw-control-plane.js +1 -1
- package/dist/lib/components/shadow-claw-conversations.js +1 -1
- package/dist/lib/components/shadow-claw-file-viewer.js +1 -1
- package/dist/lib/components/shadow-claw-files.js +1 -1
- package/dist/lib/components/shadow-claw-git.js +1 -1
- package/dist/lib/components/shadow-claw-llm.js +1 -1
- package/dist/lib/components/shadow-claw-networking.js +1 -1
- package/dist/lib/components/shadow-claw-notifications.js +1 -1
- package/dist/lib/components/shadow-claw-pages.js +1 -1
- package/dist/lib/components/shadow-claw-peerjs.js +1 -1
- package/dist/lib/components/shadow-claw-settings.js +1 -1
- package/dist/lib/components/shadow-claw-storage.js +1 -1
- package/dist/lib/components/shadow-claw-task-server.js +1 -1
- package/dist/lib/components/shadow-claw-tasks.js +1 -1
- package/dist/lib/components/shadow-claw-terminal.js +1 -1
- package/dist/lib/components/shadow-claw-tools.js +1 -1
- package/dist/lib/components/shadow-claw-webvm.js +1 -1
- package/dist/lib/components/shadow-claw.js +1 -1
- package/dist/lib/{configurePeerJs-DSRcNp3v.js → configurePeerJs-CdPzmpyI.js} +2 -2
- package/dist/lib/{configurePeerJs-DSRcNp3v.js.map → configurePeerJs-CdPzmpyI.js.map} +1 -1
- package/dist/lib/index.js +21 -21
- package/dist/lib/{initControlPlane-CWfE_Oan.js → initControlPlane-BLymRW34.js} +7 -7
- package/dist/lib/{initControlPlane-CWfE_Oan.js.map → initControlPlane-BLymRW34.js.map} +1 -1
- package/dist/lib/{orchestrator-BEUug1TW.js → orchestrator-DZkhJj7f.js} +13 -2
- package/dist/lib/{orchestrator-BEUug1TW.js.map → orchestrator-DZkhJj7f.js.map} +1 -1
- package/dist/lib/{orchestrator-CGUzfGbE.js → orchestrator-ZsQTRknI.js} +5 -5
- package/dist/lib/{orchestrator-CGUzfGbE.js.map → orchestrator-ZsQTRknI.js.map} +1 -1
- package/dist/lib/{peerjs-BSD88rT3.js → peerjs-CJYfnR5V.js} +3 -3
- package/dist/lib/{peerjs-BSD88rT3.js.map → peerjs-CJYfnR5V.js.map} +1 -1
- package/dist/lib/{push-client-CC3qifgc.js → push-client-C9hIPqLZ.js} +2 -2
- package/dist/lib/{push-client-CC3qifgc.js.map → push-client-C9hIPqLZ.js.map} +1 -1
- package/dist/lib/{shadow-claw-BWS-UVnE.js → shadow-claw-8qL2-QoK.js} +4 -4
- package/dist/lib/{shadow-claw-BWS-UVnE.js.map → shadow-claw-8qL2-QoK.js.map} +1 -1
- package/dist/lib/{shadow-claw-channel-config-DwMn3nFJ.js → shadow-claw-channel-config-CvnbqGBy.js} +3 -3
- package/dist/lib/{shadow-claw-channel-config-DwMn3nFJ.js.map → shadow-claw-channel-config-CvnbqGBy.js.map} +1 -1
- package/dist/lib/{shadow-claw-channels-BdE4cUlx.js → shadow-claw-channels-CkCvjWn1.js} +2 -2
- package/dist/lib/{shadow-claw-channels-BdE4cUlx.js.map → shadow-claw-channels-CkCvjWn1.js.map} +1 -1
- package/dist/lib/{shadow-claw-chat-DqaMoE9C.js → shadow-claw-chat-B1YEHKN3.js} +3 -3
- package/dist/lib/{shadow-claw-chat-DqaMoE9C.js.map → shadow-claw-chat-B1YEHKN3.js.map} +1 -1
- package/dist/lib/{shadow-claw-control-plane-D3DUDO29.js → shadow-claw-control-plane-jjo789IE.js} +6 -6
- package/dist/lib/{shadow-claw-control-plane-D3DUDO29.js.map → shadow-claw-control-plane-jjo789IE.js.map} +1 -1
- package/dist/lib/{shadow-claw-conversations-XT-OXogj.js → shadow-claw-conversations-MMT7wYH3.js} +2 -2
- package/dist/lib/{shadow-claw-conversations-XT-OXogj.js.map → shadow-claw-conversations-MMT7wYH3.js.map} +1 -1
- package/dist/lib/{shadow-claw-file-viewer-DJqxyd97.js → shadow-claw-file-viewer-qSkD1RQK.js} +2 -2
- package/dist/lib/{shadow-claw-file-viewer-DJqxyd97.js.map → shadow-claw-file-viewer-qSkD1RQK.js.map} +1 -1
- package/dist/lib/{shadow-claw-files-CUEJlA1o.js → shadow-claw-files-Cg8ycQ_N.js} +2 -2
- package/dist/lib/{shadow-claw-files-CUEJlA1o.js.map → shadow-claw-files-Cg8ycQ_N.js.map} +1 -1
- package/dist/lib/{shadow-claw-git-D_iVcb86.js → shadow-claw-git-gaClz-ZC.js} +3 -3
- package/dist/lib/{shadow-claw-git-D_iVcb86.js.map → shadow-claw-git-gaClz-ZC.js.map} +1 -1
- package/dist/lib/{shadow-claw-llm-C2msAsyU.js → shadow-claw-llm-DyOz0qzT.js} +2 -2
- package/dist/lib/{shadow-claw-llm-C2msAsyU.js.map → shadow-claw-llm-DyOz0qzT.js.map} +1 -1
- package/dist/lib/{shadow-claw-networking-D2NvodC-.js → shadow-claw-networking-B2xx0UUR.js} +2 -2
- package/dist/lib/{shadow-claw-networking-D2NvodC-.js.map → shadow-claw-networking-B2xx0UUR.js.map} +1 -1
- package/dist/lib/{shadow-claw-notifications-BcvVn_vu.js → shadow-claw-notifications-BjKfZy0k.js} +2 -2
- package/dist/lib/{shadow-claw-notifications-BcvVn_vu.js.map → shadow-claw-notifications-BjKfZy0k.js.map} +1 -1
- package/dist/lib/{shadow-claw-pages-CTMXRhEX.js → shadow-claw-pages-CJ2tsMtL.js} +2 -2
- package/dist/lib/{shadow-claw-pages-CTMXRhEX.js.map → shadow-claw-pages-CJ2tsMtL.js.map} +1 -1
- package/dist/lib/{shadow-claw-peerjs-C2YvypqM.js → shadow-claw-peerjs-CazCkXQ1.js} +3 -3
- package/dist/lib/{shadow-claw-peerjs-C2YvypqM.js.map → shadow-claw-peerjs-CazCkXQ1.js.map} +1 -1
- package/dist/lib/{shadow-claw-settings-B0hiDwEt.js → shadow-claw-settings-qro6pO9I.js} +2 -2
- package/dist/lib/{shadow-claw-settings-B0hiDwEt.js.map → shadow-claw-settings-qro6pO9I.js.map} +1 -1
- package/dist/lib/{shadow-claw-storage-Dt4yg4Q4.js → shadow-claw-storage-ewDdvCGa.js} +2 -2
- package/dist/lib/{shadow-claw-storage-Dt4yg4Q4.js.map → shadow-claw-storage-ewDdvCGa.js.map} +1 -1
- package/dist/lib/{shadow-claw-task-server-B2gbZaz4.js → shadow-claw-task-server-DpqQcNIs.js} +2 -2
- package/dist/lib/{shadow-claw-task-server-B2gbZaz4.js.map → shadow-claw-task-server-DpqQcNIs.js.map} +1 -1
- package/dist/lib/{shadow-claw-tasks-Bxq-niuM.js → shadow-claw-tasks-B2fMF4qE.js} +2 -2
- package/dist/lib/{shadow-claw-tasks-Bxq-niuM.js.map → shadow-claw-tasks-B2fMF4qE.js.map} +1 -1
- package/dist/lib/{shadow-claw-terminal-BfbW3xtg.js → shadow-claw-terminal-B25kQJC3.js} +2 -2
- package/dist/lib/{shadow-claw-terminal-BfbW3xtg.js.map → shadow-claw-terminal-B25kQJC3.js.map} +1 -1
- package/dist/lib/{shadow-claw-tools-BNSAaK0Y.js → shadow-claw-tools-B0y8JzoA.js} +10 -3
- package/dist/lib/{shadow-claw-tools-BNSAaK0Y.js.map → shadow-claw-tools-B0y8JzoA.js.map} +1 -1
- package/dist/lib/{shadow-claw-webvm-Dc2KmEXq.js → shadow-claw-webvm-CoCedIza.js} +2 -2
- package/dist/lib/{shadow-claw-webvm-Dc2KmEXq.js.map → shadow-claw-webvm-CoCedIza.js.map} +1 -1
- package/dist/lib/{syncWebMcpRegistration-BIL83P0Q.js → syncWebMcpRegistration-JKLALq4e.js} +2 -2
- package/dist/lib/{syncWebMcpRegistration-BIL83P0Q.js.map → syncWebMcpRegistration-JKLALq4e.js.map} +1 -1
- package/dist/lib/worker/utils/sandboxedEval.d.ts +8 -0
- package/dist/public/.well-known/mcp/server-card.json +1 -1
- package/dist/public/.well-known/mcp.json +1 -1
- package/dist/public/AGENTS.md +1 -1
- package/dist/public/README.md +5 -1
- package/dist/public/agent.worker.js +1 -1
- package/dist/public/components/shadow-claw-tools/shadow-claw-tools.html +1 -1
- package/dist/public/{configurePeerJs-B925t9C7.js → configurePeerJs-BrHeJGw1.js} +1 -1
- package/dist/public/docs/decisions/headless-cli-agent-participant.md +1 -1
- package/dist/public/docs/example/article/index.html +1 -1
- package/dist/public/docs/publishing/index.html +1 -1
- package/dist/public/docs/skill-creator/index.html +1 -1
- package/dist/public/docs/subsystems/cli.md +33 -23
- package/dist/public/docs/subsystems/skills.md +17 -0
- package/dist/public/docs/subsystems/tools.md +1 -1
- package/dist/public/e2e/README.md +2 -2
- package/dist/public/{e2e-bridge-CE1xleGn.js → e2e-bridge-D_lyH__p.js} +1 -1
- package/dist/public/{executeTool-DtTrsZHV.js → executeTool-b6DnRhcv.js} +2 -1
- package/dist/public/{file-viewer-LEEStSq-.js → file-viewer-CKrQoxZi.js} +1 -1
- package/dist/public/index.html +1 -1
- package/dist/public/index.js +1 -1
- package/dist/public/{initControlPlane-e2JgxXEb.js → initControlPlane-Dn-XFuxg.js} +1 -1
- package/dist/public/llms.txt +2 -0
- package/dist/public/main/index.html +1 -1
- package/dist/public/main/memory/index.html +1 -1
- package/dist/public/{orchestrator-Baif6kmu.js → orchestrator-0BnBtxHO.js} +3 -2
- package/dist/public/{orchestrator-TndREZPL.js → orchestrator-C3GKZriH.js} +1 -1
- package/dist/public/{peerjs-DE6WF3h2.js → peerjs-CgfLEp2N.js} +1 -1
- package/dist/public/{push-client-B_IkTpNm.js → push-client-D6DLiY1s.js} +1 -1
- package/dist/public/service-worker.js +1 -1
- package/dist/public/{shadow-claw-channels-BCGz36Zl.js → shadow-claw-channels-DSijinZ9.js} +1 -1
- package/dist/public/{shadow-claw-chat-H9U9jbqD.js → shadow-claw-chat-BeHlAjnA.js} +1 -1
- package/dist/public/{shadow-claw-control-plane-CeKh64s2.js → shadow-claw-control-plane-BfF_AZSg.js} +2 -2
- package/dist/public/{shadow-claw-conversations-C26t1HXN.js → shadow-claw-conversations-Bb_2bVLJ.js} +1 -1
- package/dist/public/{shadow-claw-DBeXILmk.js → shadow-claw-f71DlRdV.js} +2 -2
- package/dist/public/{shadow-claw-file-viewer-DWUoTjkr.js → shadow-claw-file-viewer-B67000Mm.js} +1 -1
- package/dist/public/{shadow-claw-files-BQ8DSX-z.js → shadow-claw-files-DeZZYt01.js} +1 -1
- package/dist/public/{shadow-claw-git-CIXyISw-.js → shadow-claw-git-Ccy25LuW.js} +2 -2
- package/dist/public/{shadow-claw-llm-D_GpOSZE.js → shadow-claw-llm-XjYcTlXT.js} +1 -1
- package/dist/public/{shadow-claw-networking-BYp5K3B7.js → shadow-claw-networking-efXQtydQ.js} +1 -1
- package/dist/public/{shadow-claw-notifications-ZiXmPweY.js → shadow-claw-notifications-Cq2ZSeJa.js} +1 -1
- package/dist/public/{shadow-claw-pages-BHXwf3BD.js → shadow-claw-pages-BVFNSSb1.js} +1 -1
- package/dist/public/{shadow-claw-settings-BfvDvt9c.js → shadow-claw-settings-B3sHxPh9.js} +2 -2
- package/dist/public/{shadow-claw-storage-Bvn85DII.js → shadow-claw-storage-DNdlzCgC.js} +1 -1
- package/dist/public/{shadow-claw-task-server-DZL_d8FC.js → shadow-claw-task-server-BJq0rpju.js} +1 -1
- package/dist/public/{shadow-claw-tasks-Cy8jzd8q.js → shadow-claw-tasks-CkF1uMeZ.js} +1 -1
- package/dist/public/{shadow-claw-terminal-BgEXr82T.js → shadow-claw-terminal-CnHhcpA-.js} +1 -1
- package/dist/public/{shadow-claw-tools-BjnssRSi.js → shadow-claw-tools-iw0fljud.js} +8 -1
- package/dist/public/{shadow-claw-webvm-tZ1VDoVA.js → shadow-claw-webvm-Bliu4V__.js} +1 -1
- package/dist/public/{syncWebMcpRegistration-CLMvJ4kV.js → syncWebMcpRegistration-D91usEMu.js} +1 -1
- package/package.json +1 -1
- package/src/cli/cli.ts +26 -2
- package/src/cli/commands/agent.test.ts +421 -0
- package/src/cli/commands/agent.ts +270 -20
- package/src/components/shadow-claw-tools/shadow-claw-tools.html +7 -0
- package/src/worker/headless-agent.ts +14 -0
- package/src/worker/headless-types.ts +39 -0
- package/src/worker/utils/native-eval-executor.test.ts +36 -0
- package/src/worker/utils/native-eval-executor.ts +58 -0
- package/src/worker/utils/sandboxedEval.ts +36 -0
- package/dist/cli/chunk-1BmpU7jO2.js +0 -1
- package/dist/cli/chunk-54Euq8Ji2.js +0 -1
- package/dist/cli/chunk-BTitwCgT2.js +0 -88
- package/dist/cli/chunk-Bjh76Dai.js +0 -1081
- package/dist/cli/chunk-C2HeZQ6K.js +0 -1
- package/dist/cli/chunk-CxdpafWg.js +0 -1
- package/dist/cli/chunk-DEy72ZNV2.js +0 -88
- package/dist/cli/chunk-Da1BZyqf.js +0 -1
- package/dist/cli/chunk-FHsJD-Sf2.js +0 -27
- package/dist/cli/chunk-aWgoVB7x2.js +0 -1
- package/dist/cli/chunk-hOceZVB92.js +0 -371
- package/dist/cli/chunk-pwNc6VtC2.js +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://modelcontextprotocol.io/schemas/server-card/v1.json",
|
|
3
3
|
"name": "shadow-claw",
|
|
4
|
-
"version": "1.
|
|
4
|
+
"version": "1.35.0",
|
|
5
5
|
"description": "Browser-native personal AI assistant with local and remote LLM orchestration, Web Workers, OPFS storage, and agentic tool execution.",
|
|
6
6
|
"title": "ShadowClaw MCP Server",
|
|
7
7
|
"websiteUrl": "https://xt-ml.github.io/shadow-claw/",
|
package/.well-known/mcp.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://modelcontextprotocol.io/schemas/server-card/v1.json",
|
|
3
3
|
"name": "shadow-claw",
|
|
4
|
-
"version": "1.
|
|
4
|
+
"version": "1.35.0",
|
|
5
5
|
"description": "Browser-native personal AI assistant with local and remote LLM orchestration, Web Workers, OPFS storage, and agentic tool execution.",
|
|
6
6
|
"title": "ShadowClaw MCP Server",
|
|
7
7
|
"websiteUrl": "https://xt-ml.github.io/shadow-claw/",
|
package/README.md
CHANGED
|
@@ -65,6 +65,9 @@ cat doc.txt | npx shadow-claw agent run "Summarize this" -o summary.txt
|
|
|
65
65
|
# Inspect available tools and skills
|
|
66
66
|
npx shadow-claw agent tools
|
|
67
67
|
npx shadow-claw agent skills
|
|
68
|
+
|
|
69
|
+
# Discover and import remote skills, declarative tools, and companion scripts
|
|
70
|
+
npx shadow-claw agent import https://xt-ml.github.io/shadow-claw-agent-cli-weather/
|
|
68
71
|
```
|
|
69
72
|
|
|
70
73
|
### 3. Scaffold a Project or Knowledge Hub
|
|
@@ -108,7 +111,7 @@ npm install && npm run dev # Dev server → http://localhost:8888
|
|
|
108
111
|
|
|
109
112
|
- **Client-Side Worker Orchestration:** The frontend agent decision loop, system prompt building, and tool execution run off the main thread in a dedicated Web Worker to keep the UI smooth and responsive.
|
|
110
113
|
- **In-Browser Inference by Default:** Uses the Prompt API (`window.LanguageModel`) by default in the browser client (`DEFAULT_PROVIDER = "prompt_api"`) with guided onboarding. When native support is not present, integrated polyfills (`prompt-api-polyfill` and `built-in-ai-task-apis-polyfills` backed by Transformers.js / ONNX) enable cross-browser execution.
|
|
111
|
-
- **Headless Server-Side Agent Client:** Execute the same tool-use loop, prompt assembly, and declarative skill tool chains directly from the terminal or CI/CD pipelines via `shadow-claw agent` (`init`, `model`, `skills`, `tools`, `tool`, `skill`, `run`), with native host OS shell access (`node:child_process`), SQLite persistence (`node:sqlite`), real filesystem access (`NodeFsDirectoryHandle`), and in-process offline model execution via Transformers.js ONNX and Llamafile (featuring visual download progress bars and streaming) or cloud providers.
|
|
114
|
+
- **Headless Server-Side Agent Client:** Execute the same tool-use loop, prompt assembly, and declarative skill tool chains directly from the terminal or CI/CD pipelines via `shadow-claw agent` (`init`, `model`, `skills`, `tools`, `tool`, `skill`, `import`, `run`), with native host OS shell access (`node:child_process`), SQLite persistence (`node:sqlite`), real filesystem access (`NodeFsDirectoryHandle`), and in-process offline model execution via Transformers.js ONNX and Llamafile (featuring visual download progress bars and streaming) or cloud providers.
|
|
112
115
|
- **Configurable Multi-Model Routing:** Route queries to Cloud providers (OpenRouter, Anthropic, Gemini, OpenAI, AWS Bedrock), local engines (Ollama, Llamafile, Transformers.js with on-demand Hugging Face model downloading and disk caching), or in-browser WebGPU models (LiteRT-LM).
|
|
113
116
|
- **Dual-Dispatch Sandboxing & Storage:** Client-side compute via sandboxed JavaScript and `just-bash` (or WebVM Alpine Linux) backed by Origin Private File System (OPFS) and IndexedDB; paired with host-native Node filesystem handles and SQLite database persistence on the server side.
|
|
114
117
|
- **PWA & Electron Desktop Parity:** Deployable as a progressive web app with Service Worker and Web Push, or as a native desktop application with full feature parity.
|
|
@@ -330,6 +333,7 @@ npx shadow-claw agent tools # List tools with capabilit
|
|
|
330
333
|
npx shadow-claw agent tool <name> [jsonArgs] # Inspect tool schema or execute directly
|
|
331
334
|
echo "hello" | npx shadow-claw agent tool <name> # Pipe text directly into tool (schema auto-mapping)
|
|
332
335
|
npx shadow-claw agent skill <name> # Execute a declarative skill tool chain
|
|
336
|
+
npx shadow-claw agent import <url> [options] # Discover and import remote RFC v0.2.0 skills and tools
|
|
333
337
|
|
|
334
338
|
# Browser & Client Interactivity
|
|
335
339
|
npx shadow-claw clients # List connected browser/Electron clients
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{r as e}from"./chunk-BkKN8FNP.js";import{i as t}from"./chunk-DFLqhyP_.js";import{t as n}from"./chunk-Dhh0lHO6.js";import r from"process";
|
|
2
|
+
/*! @license DOMPurify 3.4.13 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.13/LICENSE */
|
|
3
|
+
function i(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function a(e){if(Array.isArray(e))return e}function o(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function s(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
4
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function c(e,t){return a(e)||o(e,t)||l(e,t)||s()}function l(e,t){if(e){if(typeof e==`string`)return i(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?i(e,t):void 0}}const u=Object.entries,d=Object.setPrototypeOf,f=Object.isFrozen,ee=Object.getPrototypeOf,te=Object.getOwnPropertyDescriptor;let p=Object.freeze,m=Object.seal,h=Object.create,ne=typeof Reflect<`u`&&Reflect,g=ne.apply,_=ne.construct;p||=function(e){return e},m||=function(e){return e},g||=function(e,t){var n=[...arguments].slice(2);return e.apply(t,n)},_||=function(e){return new e(...[...arguments].slice(1))};const re=T(Array.prototype.forEach),ie=T(Array.prototype.lastIndexOf),ae=T(Array.prototype.pop),oe=T(Array.prototype.push),se=T(Array.prototype.splice),v=Array.isArray,ce=T(String.prototype.toLowerCase),le=T(String.prototype.toString),ue=T(String.prototype.match),de=T(String.prototype.replace),fe=T(String.prototype.indexOf),pe=T(String.prototype.trim),me=T(Number.prototype.toString),he=T(Boolean.prototype.toString),y=typeof BigInt>`u`?null:T(BigInt.prototype.toString),b=typeof Symbol>`u`?null:T(Symbol.prototype.toString),x=T(Object.prototype.hasOwnProperty),S=T(Object.prototype.toString),C=T(RegExp.prototype.test),w=E(TypeError);function T(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);var n=[...arguments].slice(1);return g(e,t,n)}}function E(e){return function(){return _(e,[...arguments])}}function D(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ce;if(d&&d(e,null),!v(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i==`string`){let e=n(i);e!==i&&(f(t)||(t[r]=e),i=e)}e[i]=!0}return e}function ge(e){for(let t=0;t<e.length;t++)x(e,t)||(e[t]=null);return e}function O(e){let t=h(null);for(let r of u(e)){var n=c(r,2);let i=n[0],a=n[1];x(e,i)&&(v(a)?t[i]=ge(a):a&&typeof a==`object`&&a.constructor===Object?t[i]=O(a):t[i]=a)}return t}function _e(e){switch(typeof e){case`string`:return e;case`number`:return me(e);case`boolean`:return he(e);case`bigint`:return y?y(e):`0`;case`symbol`:return b?b(e):`Symbol()`;case`undefined`:return S(e);case`function`:case`object`:{if(e===null)return S(e);let t=e,n=k(t,`toString`);if(typeof n==`function`){let e=n(t);return typeof e==`string`?e:S(e)}return S(e)}default:return S(e)}}function k(e,t){for(;e!==null;){let n=te(e,t);if(n){if(n.get)return T(n.get);if(typeof n.value==`function`)return T(n.value)}e=ee(e)}function n(){return null}return n}function ve(e){try{return C(e,``),!0}catch{return!1}}const ye=p(`a.abbr.acronym.address.area.article.aside.audio.b.bdi.bdo.big.blink.blockquote.body.br.button.canvas.caption.center.cite.code.col.colgroup.content.data.datalist.dd.decorator.del.details.dfn.dialog.dir.div.dl.dt.element.em.fieldset.figcaption.figure.font.footer.form.h1.h2.h3.h4.h5.h6.head.header.hgroup.hr.html.i.img.input.ins.kbd.label.legend.li.main.map.mark.marquee.menu.menuitem.meter.nav.nobr.ol.optgroup.option.output.p.picture.pre.progress.q.rp.rt.ruby.s.samp.search.section.select.shadow.slot.small.source.spacer.span.strike.strong.style.sub.summary.sup.table.tbody.td.template.textarea.tfoot.th.thead.time.tr.track.tt.u.ul.var.video.wbr`.split(`.`)),be=p(`svg.a.altglyph.altglyphdef.altglyphitem.animatecolor.animatemotion.animatetransform.circle.clippath.defs.desc.ellipse.enterkeyhint.exportparts.filter.font.g.glyph.glyphref.hkern.image.inputmode.line.lineargradient.marker.mask.metadata.mpath.part.path.pattern.polygon.polyline.radialgradient.rect.stop.style.switch.symbol.text.textpath.title.tref.tspan.view.vkern`.split(`.`)),xe=p([`feBlend`,`feColorMatrix`,`feComponentTransfer`,`feComposite`,`feConvolveMatrix`,`feDiffuseLighting`,`feDisplacementMap`,`feDistantLight`,`feDropShadow`,`feFlood`,`feFuncA`,`feFuncB`,`feFuncG`,`feFuncR`,`feGaussianBlur`,`feImage`,`feMerge`,`feMergeNode`,`feMorphology`,`feOffset`,`fePointLight`,`feSpecularLighting`,`feSpotLight`,`feTile`,`feTurbulence`]),Se=p([`animate`,`color-profile`,`cursor`,`discard`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`foreignobject`,`hatch`,`hatchpath`,`mesh`,`meshgradient`,`meshpatch`,`meshrow`,`missing-glyph`,`script`,`set`,`solidcolor`,`unknown`,`use`]),Ce=p(`math.menclose.merror.mfenced.mfrac.mglyph.mi.mlabeledtr.mmultiscripts.mn.mo.mover.mpadded.mphantom.mroot.mrow.ms.mspace.msqrt.mstyle.msub.msup.msubsup.mtable.mtd.mtext.mtr.munder.munderover.mprescripts`.split(`.`)),we=p([`maction`,`maligngroup`,`malignmark`,`mlongdiv`,`mscarries`,`mscarry`,`msgroup`,`mstack`,`msline`,`msrow`,`semantics`,`annotation`,`annotation-xml`,`mprescripts`,`none`]),Te=p([`#text`]),Ee=p(`accept.action.align.alt.autocapitalize.autocomplete.autopictureinpicture.autoplay.background.bgcolor.border.capture.cellpadding.cellspacing.checked.cite.class.clear.color.cols.colspan.command.commandfor.controls.controlslist.coords.crossorigin.datetime.decoding.default.dir.disabled.disablepictureinpicture.disableremoteplayback.download.draggable.enctype.enterkeyhint.exportparts.face.for.headers.height.hidden.high.href.hreflang.id.inert.inputmode.integrity.ismap.kind.label.lang.list.loading.loop.low.max.maxlength.media.method.min.minlength.multiple.muted.name.nonce.noshade.novalidate.nowrap.open.optimum.part.pattern.placeholder.playsinline.popover.popovertarget.popovertargetaction.poster.preload.pubdate.radiogroup.readonly.rel.required.rev.reversed.role.rows.rowspan.spellcheck.scope.selected.shape.size.sizes.slot.span.srclang.start.src.srcset.step.style.summary.tabindex.title.translate.type.usemap.valign.value.width.wrap.xmlns`.split(`.`)),De=p(`accent-height.accumulate.additive.alignment-baseline.amplitude.ascent.attributename.attributetype.azimuth.basefrequency.baseline-shift.begin.bias.by.class.clip.clippathunits.clip-path.clip-rule.color.color-interpolation.color-interpolation-filters.color-profile.color-rendering.cx.cy.d.dx.dy.diffuseconstant.direction.display.divisor.dominant-baseline.dur.edgemode.elevation.end.exponent.fill.fill-opacity.fill-rule.filter.filterunits.flood-color.flood-opacity.font-family.font-size.font-size-adjust.font-stretch.font-style.font-variant.font-weight.fx.fy.g1.g2.glyph-name.glyphref.gradientunits.gradienttransform.height.href.id.image-rendering.in.in2.intercept.k.k1.k2.k3.k4.kerning.keypoints.keysplines.keytimes.lang.lengthadjust.letter-spacing.kernelmatrix.kernelunitlength.lighting-color.local.marker-end.marker-mid.marker-start.markerheight.markerunits.markerwidth.maskcontentunits.maskunits.max.mask.mask-type.media.method.mode.min.name.numoctaves.offset.operator.opacity.order.orient.orientation.origin.overflow.paint-order.path.pathlength.patterncontentunits.patterntransform.patternunits.points.preservealpha.preserveaspectratio.primitiveunits.r.rx.ry.radius.refx.refy.repeatcount.repeatdur.restart.result.rotate.scale.seed.shape-rendering.slope.specularconstant.specularexponent.spreadmethod.startoffset.stddeviation.stitchtiles.stop-color.stop-opacity.stroke-dasharray.stroke-dashoffset.stroke-linecap.stroke-linejoin.stroke-miterlimit.stroke-opacity.stroke.stroke-width.style.surfacescale.systemlanguage.tabindex.tablevalues.targetx.targety.transform.transform-origin.text-anchor.text-decoration.text-orientation.text-rendering.textlength.type.u1.u2.unicode.values.viewbox.visibility.version.vert-adv-y.vert-origin-x.vert-origin-y.width.word-spacing.wrap.writing-mode.xchannelselector.ychannelselector.x.x1.x2.xmlns.y.y1.y2.z.zoomandpan`.split(`.`)),Oe=p(`accent.accentunder.align.bevelled.close.columnalign.columnlines.columnspacing.columnspan.denomalign.depth.dir.display.displaystyle.encoding.fence.frame.height.href.id.largeop.length.linethickness.lquote.lspace.mathbackground.mathcolor.mathsize.mathvariant.maxsize.minsize.movablelimits.notation.numalign.open.rowalign.rowlines.rowspacing.rowspan.rspace.rquote.scriptlevel.scriptminsize.scriptsizemultiplier.selection.separator.separators.stretchy.subscriptshift.supscriptshift.symmetric.voffset.width.xmlns`.split(`.`)),ke=p([`xlink:href`,`xml:id`,`xlink:title`,`xml:space`,`xmlns:xlink`]),Ae=m(/{{[\w\W]*|^[\w\W]*}}/g),je=m(/<%[\w\W]*|^[\w\W]*%>/g),Me=m(/\${[\w\W]*/g),Ne=m(/^data-[\-\w.\u00B7-\uFFFF]+$/),Pe=m(/^aria-[\-\w]+$/),Fe=m(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Ie=m(/^(?:\w+script|data):/i),Le=m(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Re=m(/^html$/i),ze=m(/^[a-z][.\w]*(-[.\w]+)+$/i),Be=m(/<[/\w!]/g),Ve=m(/<[/\w]/g),He=m(/<\/no(script|embed|frames)/i),Ue=m(/\/>/i),A={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},We=function(){return typeof window>`u`?null:window},Ge=function(e,t){if(typeof e!=`object`||typeof e.createPolicy!=`function`)return null;let n=null,r=`data-tt-policy-suffix`;t&&t.hasAttribute(r)&&(n=t.getAttribute(r));let i=`dompurify`+(n?`#`+n:``);try{return e.createPolicy(i,{createHTML(e){return e},createScriptURL(e){return e}})}catch{return console.warn(`TrustedTypes policy `+i+` could not be created.`),null}},Ke=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},j=function(e,t,n,r){return x(e,t)&&v(e[t])?D(r.base?O(r.base):{},e[t],r.transform):n};function qe(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:We(),t=e=>qe(e);if(t.version=`3.4.13`,t.removed=[],!e||!e.document||e.document.nodeType!==A.document||!e.Element)return t.isSupported=!1,t;let n=e.document,r=n,i=r.currentScript;e.DocumentFragment;let a=e.HTMLTemplateElement,o=e.Node,s=e.Element,c=e.NodeFilter;e.NamedNodeMap===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;let l=e.DOMParser,d=e.trustedTypes,f=s.prototype,ee=k(f,`cloneNode`),te=k(f,`remove`),ne=k(f,`nextSibling`),g=k(f,`childNodes`),_=k(f,`parentNode`),me=k(f,`shadowRoot`),he=k(f,`attributes`),y=o&&o.prototype?k(o.prototype,`nodeType`):null,b=o&&o.prototype?k(o.prototype,`nodeName`):null,S=o&&o.prototype?k(o.prototype,`ownerDocument`):null;if(typeof a==`function`){let e=n.createElement(`template`);e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let T,E=``,ge,Je=!1,M=0,Ye=function(){if(M>0)throw w(`A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.`)},N=function(e){Ye(),M++;try{return T.createHTML(e)}finally{M--}},P=function(e){Ye(),M++;try{return T.createScriptURL(e)}finally{M--}},Xe=function(){return Je||=(ge=Ge(d,i),!0),ge},Ze=n,Qe=Ze.implementation,$e=Ze.createNodeIterator,et=Ze.createDocumentFragment,tt=Ze.getElementsByTagName,nt=r.importNode,F=Ke();t.isSupported=typeof u==`function`&&typeof _==`function`&&Qe&&Qe.createHTMLDocument!==void 0;let rt=Ae,I=je,it=Me,at=Ne,ot=Pe,st=Ie,ct=Le,lt=ze,ut=Fe,L=null,R=D({},[...ye,...be,...xe,...Ce,...Te]),z=null,dt=D({},[...Ee,...De,...Oe,...ke]),B=Object.seal(h(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ft=null,pt=null,V=Object.seal(h(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),mt=!0,ht=!0,gt=!1,_t=!0,H=!1,U=!0,W=!1,G=!1,K=null,vt=null,yt=!1,q=!1,bt=!1,xt=!1,St=!0,Ct=!1,wt=`user-content-`,Tt=!0,Et=!1,Dt={},J=null,Ot=D({},`annotation-xml.audio.colgroup.desc.foreignobject.head.iframe.math.mi.mn.mo.ms.mtext.noembed.noframes.noscript.plaintext.script.selectedcontent.style.svg.template.thead.title.video.xmp`.split(`.`)),kt=null,At=D({},[`audio`,`video`,`img`,`source`,`image`,`track`]),jt=null,Mt=D({},[`alt`,`class`,`for`,`id`,`label`,`name`,`pattern`,`placeholder`,`role`,`summary`,`title`,`value`,`style`,`xmlns`]),Nt=`http://www.w3.org/1998/Math/MathML`,Pt=`http://www.w3.org/2000/svg`,Y=`http://www.w3.org/1999/xhtml`,Ft=Y,It=!1,Lt=null,Rt=D({},[Nt,Pt,Y],le),zt=p([`mi`,`mo`,`mn`,`ms`,`mtext`]),Bt=D({},zt),Vt=p([`annotation-xml`]),Ht=D({},Vt),Ut=D({},[`title`,`style`,`font`,`a`,`script`]),Wt=null,Gt=[`application/xhtml+xml`,`text/html`],X=null,Kt=null,qt=n.createElement(`form`),Jt=function(e){return e instanceof RegExp||e instanceof Function},Yt=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Kt&&Kt===e)return;(!e||typeof e!=`object`)&&(e={}),e=O(e),Wt=Gt.indexOf(e.PARSER_MEDIA_TYPE)===-1?`text/html`:e.PARSER_MEDIA_TYPE,X=Wt===`application/xhtml+xml`?le:ce,L=j(e,`ALLOWED_TAGS`,R,{transform:X}),z=j(e,`ALLOWED_ATTR`,dt,{transform:X}),Lt=j(e,`ALLOWED_NAMESPACES`,Rt,{transform:le}),jt=j(e,`ADD_URI_SAFE_ATTR`,Mt,{transform:X,base:Mt}),kt=j(e,`ADD_DATA_URI_TAGS`,At,{transform:X,base:At}),J=j(e,`FORBID_CONTENTS`,Ot,{transform:X}),ft=j(e,`FORBID_TAGS`,O({}),{transform:X}),pt=j(e,`FORBID_ATTR`,O({}),{transform:X}),Dt=x(e,`USE_PROFILES`)?e.USE_PROFILES&&typeof e.USE_PROFILES==`object`?O(e.USE_PROFILES):e.USE_PROFILES:!1,mt=e.ALLOW_ARIA_ATTR!==!1,ht=e.ALLOW_DATA_ATTR!==!1,gt=e.ALLOW_UNKNOWN_PROTOCOLS||!1,_t=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,H=e.SAFE_FOR_TEMPLATES||!1,U=e.SAFE_FOR_XML!==!1,W=e.WHOLE_DOCUMENT||!1,q=e.RETURN_DOM||!1,bt=e.RETURN_DOM_FRAGMENT||!1,xt=e.RETURN_TRUSTED_TYPE||!1,yt=e.FORCE_BODY||!1,St=e.SANITIZE_DOM!==!1,Ct=e.SANITIZE_NAMED_PROPS||!1,Tt=e.KEEP_CONTENT!==!1,Et=e.IN_PLACE||!1,ut=ve(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:Fe,Ft=typeof e.NAMESPACE==`string`?e.NAMESPACE:Y,Bt=x(e,`MATHML_TEXT_INTEGRATION_POINTS`)&&e.MATHML_TEXT_INTEGRATION_POINTS&&typeof e.MATHML_TEXT_INTEGRATION_POINTS==`object`?O(e.MATHML_TEXT_INTEGRATION_POINTS):D({},zt),Ht=x(e,`HTML_INTEGRATION_POINTS`)&&e.HTML_INTEGRATION_POINTS&&typeof e.HTML_INTEGRATION_POINTS==`object`?O(e.HTML_INTEGRATION_POINTS):D({},Vt);let t=x(e,`CUSTOM_ELEMENT_HANDLING`)&&e.CUSTOM_ELEMENT_HANDLING&&typeof e.CUSTOM_ELEMENT_HANDLING==`object`?O(e.CUSTOM_ELEMENT_HANDLING):h(null);if(B=h(null),x(t,`tagNameCheck`)&&Jt(t.tagNameCheck)&&(B.tagNameCheck=t.tagNameCheck),x(t,`attributeNameCheck`)&&Jt(t.attributeNameCheck)&&(B.attributeNameCheck=t.attributeNameCheck),x(t,`allowCustomizedBuiltInElements`)&&typeof t.allowCustomizedBuiltInElements==`boolean`&&(B.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),m(B),H&&(ht=!1),bt&&(q=!0),Dt&&(L=D({},Te),z=h(null),Dt.html===!0&&(D(L,ye),D(z,Ee)),Dt.svg===!0&&(D(L,be),D(z,De),D(z,ke)),Dt.svgFilters===!0&&(D(L,xe),D(z,De),D(z,ke)),Dt.mathMl===!0&&(D(L,Ce),D(z,Oe),D(z,ke))),V.tagCheck=null,V.attributeCheck=null,x(e,`ADD_TAGS`)&&(typeof e.ADD_TAGS==`function`?V.tagCheck=e.ADD_TAGS:v(e.ADD_TAGS)&&(L===R&&(L=O(L)),D(L,e.ADD_TAGS,X))),x(e,`ADD_ATTR`)&&(typeof e.ADD_ATTR==`function`?V.attributeCheck=e.ADD_ATTR:v(e.ADD_ATTR)&&(z===dt&&(z=O(z)),D(z,e.ADD_ATTR,X))),x(e,`ADD_URI_SAFE_ATTR`)&&v(e.ADD_URI_SAFE_ATTR)&&D(jt,e.ADD_URI_SAFE_ATTR,X),x(e,`FORBID_CONTENTS`)&&v(e.FORBID_CONTENTS)&&(J===Ot&&(J=O(J)),D(J,e.FORBID_CONTENTS,X)),x(e,`ADD_FORBID_CONTENTS`)&&v(e.ADD_FORBID_CONTENTS)&&(J===Ot&&(J=O(J)),D(J,e.ADD_FORBID_CONTENTS,X)),Tt&&(L[`#text`]=!0),W&&D(L,[`html`,`head`,`body`]),L.table&&(D(L,[`tbody`]),delete ft.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!=`function`)throw w(`TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.`);if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!=`function`)throw w(`TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.`);let t=T;T=e.TRUSTED_TYPES_POLICY;try{E=N(``)}catch(e){throw T=t,e}}else e.TRUSTED_TYPES_POLICY===null?(T=void 0,E=``):(T===void 0&&(T=Xe()),T&&typeof E==`string`&&(E=N(``)));p&&p(e),Kt=e},Xt=D({},[...be,...xe,...Se]),Zt=D({},[...Ce,...we]),Qt=function(e,t,n){return t.namespaceURI===Y?e===`svg`:t.namespaceURI===Nt?e===`svg`&&(n===`annotation-xml`||Bt[n]):!!Xt[e]},$t=function(e,t,n){return t.namespaceURI===Y?e===`math`:t.namespaceURI===Pt?e===`math`&&Ht[n]:!!Zt[e]},en=function(e,t,n){return t.namespaceURI===Pt&&!Ht[n]||t.namespaceURI===Nt&&!Bt[n]?!1:!Zt[e]&&(Ut[e]||!Xt[e])},tn=function(e){let t=_(e);(!t||!t.tagName)&&(t={namespaceURI:Ft,tagName:`template`});let n=ce(e.tagName),r=ce(t.tagName);return Lt[e.namespaceURI]?e.namespaceURI===Pt?Qt(n,t,r):e.namespaceURI===Nt?$t(n,t,r):e.namespaceURI===Y?en(n,t,r):!!(Wt===`application/xhtml+xml`&&Lt[e.namespaceURI]):!1},Z=function(e){oe(t.removed,{element:e});try{_(e).removeChild(e)}catch{if(te(e),!_(e))throw w(`a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place`)}},nn=function(e){an(e);let t=g(e);if(t){let e=[];re(t,t=>{oe(e,t)}),re(e,e=>{try{te(e)}catch{}})}let n=he(e);if(n)for(let t=n.length-1;t>=0;--t){let r=n[t],i=r&&r.name;if(typeof i==`string`)try{e.removeAttribute(i)}catch{}}},Q=function(e,n){try{oe(t.removed,{attribute:n.getAttributeNode(e),from:n})}catch{oe(t.removed,{attribute:null,from:n})}if(n.removeAttribute(e),e===`is`)if(q||bt)try{Z(n)}catch{}else try{n.setAttribute(e,``)}catch{}},rn=function(e){let t=he(e);if(t)for(let n=t.length-1;n>=0;--n){let r=t[n],i=r&&r.name;if(!(typeof i!=`string`||z[X(i)]))try{e.removeAttribute(i)}catch{}}},an=function(e){let t=[e];for(;t.length>0;){let e=t.pop();(y?y(e):e.nodeType)===A.element&&rn(e);let n=g(e);if(n)for(let e=n.length-1;e>=0;--e)t.push(n[e])}},on=function(e){if(!U)return;let t=[e];for(;t.length>0;){let e=t.pop(),n=y?y(e):e.nodeType;if(n===A.processingInstruction||n===A.comment&&C(Ve,e.data)){try{te(e)}catch{}continue}if(n===A.element){let t=e,n=X(b?b(e):e.nodeName);try{t.hasAttribute&&t.hasAttribute(`patchsrc`)&&t.removeAttribute(`patchsrc`),t.hasAttribute&&t.hasAttribute(`for`)&&n!==`label`&&n!==`output`&&t.removeAttribute(`for`)}catch{}}let r=g(e);if(r)for(let e=r.length-1;e>=0;--e)t.push(r[e])}},sn=function(e){let t=null,r=null;if(yt)e=`<remove></remove>`+e;else{let t=ue(e,/^[\r\n\t ]+/);r=t&&t[0]}Wt===`application/xhtml+xml`&&Ft===Y&&(e=`<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>`+e+`</body></html>`);let i=T?N(e):e;if(Ft===Y)try{t=new l().parseFromString(i,Wt)}catch{}if(!t||!t.documentElement){t=Qe.createDocument(Ft,`template`,null);try{t.documentElement.innerHTML=It?E:i}catch{}}let a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),Ft===Y?tt.call(t,W?`html`:`body`)[0]:W?t.documentElement:a},cn=function(e){let t=S?S(e):e.ownerDocument;return $e.call(t||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},ln=function(e){return e=de(e,rt,` `),e=de(e,I,` `),e=de(e,it,` `),e},un=function(e){e.normalize();let t=S?S(e):e.ownerDocument,n=$e.call(t||e,e,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null),r=n.nextNode();for(;r;)r.data=ln(r.data),r=n.nextNode();let i=e.querySelectorAll?.call(e,`template`);i&&re(i,e=>{fn(e.content)&&un(e.content)})},dn=function(e){let t=b?b(e):null;return typeof t!=`string`||X(t)!==`form`?!1:typeof e.nodeName!=`string`||typeof e.textContent!=`string`||typeof e.removeChild!=`function`||e.attributes!==he(e)||typeof e.removeAttribute!=`function`||typeof e.setAttribute!=`function`||typeof e.namespaceURI!=`string`||typeof e.insertBefore!=`function`||typeof e.hasChildNodes!=`function`||e.nodeType!==y(e)||e.childNodes!==g(e)},fn=function(e){if(!y||typeof e!=`object`||!e)return!1;try{return y(e)===A.documentFragment}catch{return!1}},pn=function(e){if(!y||typeof e!=`object`||!e)return!1;try{return typeof y(e)==`number`}catch{return!1}};function $(e,n,r){e.length!==0&&re(e,e=>{e.call(t,n,r,Kt)})}let mn=function(e,t){return!!(U&&e.hasChildNodes()&&!pn(e.firstElementChild)&&C(Be,e.textContent)&&C(Be,e.innerHTML)||U&&e.namespaceURI===Y&&t===`style`&&pn(e.firstElementChild)||e.nodeType===A.processingInstruction||U&&e.nodeType===A.comment&&C(Ve,e.data))},hn=function(e,t,n){if(!ft[t]&&bn(t)&&(B.tagNameCheck instanceof RegExp&&C(B.tagNameCheck,t)||B.tagNameCheck instanceof Function&&B.tagNameCheck(t)))return!1;if(Tt&&!J[t]){let t=_(e),r=g(e);if(r&&t){let i=r.length;for(let a=i-1;a>=0;--a){let i=e===n?ee(r[a],!0):r[a];t.insertBefore(i,ne(e))}}}return Z(e),!0},gn=function(e,t,n,r){return e.length===0?t:t===n||t===r?O(t):t},_n=function(e,n){if($(F.beforeSanitizeElements,e,null),e!==n&&_(e)===null)return Et&&an(e),!0;if(dn(e))return Z(e),!0;let r=X(b?b(e):e.nodeName);if(L=gn(F.uponSanitizeElement,L,R,K),$(F.uponSanitizeElement,e,{tagName:r,allowedTags:L}),e!==n&&_(e)===null)return Et&&an(e),!0;if(mn(e,r))return Z(e),!0;if(ft[r]||!(V.tagCheck instanceof Function&&V.tagCheck(r))&&!L[r]){let t=hn(e,r,n);return t===!1&&$(F.afterSanitizeElements,e,null),t}if((y?y(e):e.nodeType)===A.element&&!tn(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&C(He,e.innerHTML))return Z(e),!0;if(H&&e.nodeType===A.text){let n=ln(e.textContent);e.textContent!==n&&(oe(t.removed,{element:e.cloneNode()}),e.textContent=n)}return $(F.afterSanitizeElements,e,null),!1},vn=function(e,t,r){if(pt[t]||U&&t===`patchsrc`||U&&t===`for`&&e!==`label`&&e!==`output`||St&&(t===`id`||t===`name`)&&(r in n||r in qt))return!1;let i=z[t]||V.attributeCheck instanceof Function&&V.attributeCheck(t,e);if(!(ht&&C(at,t))&&!(mt&&C(ot,t))){if(!i){if(!(bn(e)&&(B.tagNameCheck instanceof RegExp&&C(B.tagNameCheck,e)||B.tagNameCheck instanceof Function&&B.tagNameCheck(e))&&(B.attributeNameCheck instanceof RegExp&&C(B.attributeNameCheck,t)||B.attributeNameCheck instanceof Function&&B.attributeNameCheck(t,e))||t===`is`&&B.allowCustomizedBuiltInElements&&(B.tagNameCheck instanceof RegExp&&C(B.tagNameCheck,r)||B.tagNameCheck instanceof Function&&B.tagNameCheck(r))))return!1}else if(!jt[t]&&!C(ut,de(r,ct,``))&&!((t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&fe(r,`data:`)===0&&kt[e])&&!(gt&&!C(st,de(r,ct,``)))&&r)return!1}return!0},yn=D({},[`annotation-xml`,`color-profile`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`missing-glyph`]),bn=function(e){return!yn[ce(e)]&&C(lt,e)},xn=function(e,t,n,r){if(T&&typeof d==`object`&&typeof d.getAttributeType==`function`&&!n)switch(d.getAttributeType(e,t)){case`TrustedHTML`:return N(r);case`TrustedScriptURL`:return P(r)}return r},Sn=function(e,n,r,i){try{r?e.setAttributeNS(r,n,i):e.setAttribute(n,i),dn(e)?Z(e):ae(t.removed)}catch{Q(n,e)}},Cn=function(e){$(F.beforeSanitizeAttributes,e,null);let t=e.attributes;if(!t||dn(e))return;z=gn(F.uponSanitizeAttribute,z,dt,vt);let n={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:z,forceKeepAttr:void 0},r=t.length,i=X(e.nodeName);for(;r--;){let a=t[r],o=a.name,s=a.namespaceURI,c=a.value,l=X(o),u=c,d=o===`value`?u:pe(u);if(n.attrName=l,n.attrValue=d,n.keepAttr=!0,n.forceKeepAttr=void 0,$(F.uponSanitizeAttribute,e,n),d=n.attrValue,Ct&&(l===`id`||l===`name`)&&fe(d,wt)!==0&&(Q(o,e),d=wt+d),U&&C(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,d)){Q(o,e);continue}if(l===`attributename`&&ue(d,`href`)){Q(o,e);continue}if(!n.forceKeepAttr){if(!n.keepAttr){Q(o,e);continue}if(!_t&&C(Ue,d)){Q(o,e);continue}if(H&&(d=ln(d)),!vn(i,l,d)){Q(o,e);continue}d=xn(i,l,s,d),d!==u&&Sn(e,o,s,d)}}$(F.afterSanitizeAttributes,e,null)},wn=function(e){let t=null,n=cn(e);for($(F.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if($(F.uponSanitizeShadowNode,t,null),_n(t,e),Cn(t),fn(t.content)&&wn(t.content),(y?y(t):t.nodeType)===A.element){let e=me(t);fn(e)&&(Tn(e),wn(e))}$(F.afterSanitizeShadowDOM,e,null)},Tn=function(e){let t=[{node:e,shadow:null}];for(;t.length>0;){let e=t.pop();if(e.shadow){wn(e.shadow);continue}let n=e.node,r=(y?y(n):n.nodeType)===A.element,i=g(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){let e=b?b(n):null;if(typeof e==`string`&&X(e)===`template`){let e=n.content;fn(e)&&t.push({node:e,shadow:null})}}if(r){let e=me(n);fn(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return t.sanitize=function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=null,a=null,o=null,s=null;if(It=!e,It&&(e=`<!-->`),typeof e!=`string`&&!pn(e)&&(e=_e(e),typeof e!=`string`))throw w(`dirty is not a string, aborting`);if(!t.isSupported)return e;G?(L=K,z=vt):Yt(n),(F.uponSanitizeElement.length>0||F.uponSanitizeAttribute.length>0)&&(L=O(L)),F.uponSanitizeAttribute.length>0&&(z=O(z)),t.removed=[];let c=Et&&typeof e!=`string`&&pn(e);if(c){on(e);let t=b?b(e):e.nodeName;if(typeof t==`string`){let n=X(t);if(!L[n]||ft[n])throw nn(e),w(`root node is forbidden and cannot be sanitized in-place`)}if(dn(e))throw nn(e),w(`root node is clobbered and cannot be sanitized in-place`);try{Tn(e)}catch(t){throw nn(e),t}}else if(pn(e))i=sn(`<!---->`),a=i.ownerDocument.importNode(e,!0),a.nodeType===A.element&&a.nodeName===`BODY`||a.nodeName===`HTML`?i=a:i.appendChild(a),Tn(a);else{if(!q&&!H&&!W&&e.indexOf(`<`)===-1)return T&&xt?N(e):e;if(i=sn(e),!i)return q?null:xt?E:``}i&&yt&&Z(i.firstChild);let l=c?e:i;try{let e=cn(l);for(;o=e.nextNode();)_n(o,l),Cn(o),fn(o.content)&&wn(o.content)}catch(n){throw c&&(nn(e),re(t.removed,e=>{e.element&&an(e.element)})),n}if(c)return re(t.removed,e=>{e.element&&an(e.element)}),H&&un(e),e;if(q){if(H&&un(i),bt)for(s=et.call(i.ownerDocument);i.firstChild;)s.appendChild(i.firstChild);else s=i;return(z.shadowroot||z.shadowrootmode)&&(s=nt.call(r,s,!0)),s}let u=W?i.outerHTML:i.innerHTML;return W&&L[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&C(Re,i.ownerDocument.doctype.name)&&(u=`<!DOCTYPE `+i.ownerDocument.doctype.name+`>
|
|
5
|
+
`+u),H&&(u=ln(u)),T&&xt?N(u):u},t.setConfig=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Yt(e),G=!0,K=L,vt=z},t.clearConfig=function(){Kt=null,G=!1,K=null,vt=null,T=ge,E=``},t.isValidAttribute=function(e,t,n){Kt||Yt({});let r=X(e),i=X(t);return vn(r,i,n)},t.addHook=function(e,t){typeof t==`function`&&x(F,e)&&oe(F[e],t)},t.removeHook=function(e,t){if(x(F,e)){if(t!==void 0){let n=ie(F[e],t);return n===-1?void 0:se(F[e],n,1)[0]}return ae(F[e])}},t.removeHooks=function(e){x(F,e)&&(F[e]=[])},t.removeAllHooks=function(){F=Ke()},t}qe();let Je=[`youtube.com`,`youtube-nocookie.com`,`youtu.be`,`xt-ml.github.io`,`kherrick.github.io`];function M(e){e.map(e=>Ye(e)).filter(Boolean)}M(Je);function Ye(e){let t=e.trim();if(!t)return()=>!1;if(t.startsWith(`/`)&&(t.endsWith(`/`)||/\/[gimuy]*$/.test(t)))try{let e=t.lastIndexOf(`/`),n=t.slice(1,e),r=t.slice(e+1),i=new RegExp(n,r||`i`);return e=>i.test(e)}catch{}if(t.includes(`^`)||t.includes(`$`)||t.includes(`(`)&&t.includes(`)`))try{let e=new RegExp(t,`i`);return t=>e.test(t)}catch{}if(t.startsWith(`*.`)){let e=t.slice(2).toLowerCase();return t=>{let n=t.toLowerCase();return n===e||n.endsWith(`.`+e)}}let n=t.toLowerCase();return e=>{let t=e.toLowerCase();return t===n||t.endsWith(`.`+n)}}const N=`shadowclaw`;let P;function Xe(){let e=globalThis.trustedTypes;return!e||typeof e.createPolicy!=`function`?null:e}function Ze(){if(P!==void 0)return P;let e=Xe();if(!e)return P=null,P;if(typeof e.getPolicy==`function`){let t=e.getPolicy(N);if(t)return P=t,P}try{P=e.createPolicy(N,{createHTML:e=>e,createScriptURL:e=>e})}catch{P=typeof e.getPolicy==`function`?e.getPolicy(N)??null:null}return P}function Qe(e){let t=Ze();return!t||typeof t.createScriptURL!=`function`?e:t.createScriptURL(e)}const $e=[],et=[];let tt=new Set($e.map(e=>e.toLowerCase().trim())),nt=[...et];function F(e){e.map(e=>Ye(e)).filter(Boolean)}F(nt);function rt(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.toLowerCase().trim():``).filter(Boolean):typeof e==`string`?e.split(/[\n,]+/).map(e=>e.toLowerCase().trim()).filter(Boolean):[]}function I(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):typeof e==`string`?e.split(/[\n,]+/).map(e=>e.trim()).filter(Boolean):[]}function it(e){let t=rt(e);tt=new Set(t)}function at(e){let t=I(e);nt=t,F(t)}function ot(e){if(!e||typeof e!=`string`)return!1;let t=e.trim().toLowerCase();return!t.includes(`-`)||t===`shadow-claw`||t.startsWith(`shadow-claw-`)?!0:tt.has(t)}const st=`allow-modals allow-scripts allow-popups allow-popups-to-escape-sandbox`,ct=[`'self'`,`blob:`,`data:`],lt=[`'self'`,`blob:`,`data:`],ut=[`'self'`,`'unsafe-inline'`,`https:`,`http:`],L=[`'self'`,`blob:`,`data:`,`https:`,`http:`];let R=st;[...ct],[...lt],[...ut],[...L];function z(e){R=Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean).join(` `):typeof e==`string`&&e.trim()?e.trim():st}function dt(e){if(!e||typeof e!=`object`)return;let t=e.allowedCustomElements||(typeof e.customElements==`object`&&!Array.isArray(e.customElements)?e.customElements?.allowedElements:void 0);t!==void 0&&it(t);let n=e.allowedCustomElementDomains||(typeof e.customElements==`object`&&!Array.isArray(e.customElements)?e.customElements?.allowedDomains:void 0);n!==void 0&&at(n),e.security?.iframeSandbox===void 0?(e.security?.allowSameOrigin===!0||e.security?.allowIframeSameOrigin===!0)&&(R.includes(`allow-same-origin`)||(R=`${R} allow-same-origin`.trim())):z(e.security.iframeSandbox),e.security?.workerSrc!==void 0&&I(e.security.workerSrc),e.security?.connectSrc!==void 0&&I(e.security.connectSrc),e.security?.scriptSrc!==void 0&&I(e.security.scriptSrc),e.security?.styleSrc!==void 0&&I(e.security.styleSrc),e.security?.imgSrc!==void 0&&I(e.security.imgSrc)}function B(){if(typeof document>`u`)return;let e=document.getElementById(`shadow-claw-site-config`);if(e&&e.textContent)try{dt(JSON.parse(e.textContent))}catch{}}async function ft(r){try{let i=r??await t();if(!i)return;let[a,o]=await Promise.all([n(i,e.ALLOWED_CUSTOM_ELEMENTS),n(i,e.ALLOWED_CUSTOM_ELEMENT_HOST_PATTERNS)]);if(typeof a==`string`&&a.trim())try{it(JSON.parse(a))}catch{it(a)}if(typeof o==`string`&&o.trim())try{at(JSON.parse(o))}catch{at(o)}}catch(e){console.warn(`Failed to load custom element security from db:`,e)}}let pt=null,V=!1;function mt(){B(),!(V||typeof customElements>`u`||typeof customElements.define!=`function`)&&(pt=customElements.define.bind(customElements),customElements.define=function(e,t,n){if(!ot((e||``).toLowerCase().trim())){let t=`[Security] Registration blocked: <${e}> is not an approved custom element.`;throw console.error(t),Error(t)}return pt(e,t,n)},V=!0)}function ht(e=typeof document<`u`?document.documentElement:null){if(typeof MutationObserver>`u`||!e)return null;if(typeof e.querySelectorAll==`function`)try{e.querySelectorAll(`*`).forEach(e=>{let t=e.tagName?e.tagName.toLowerCase():``;t.includes(`-`)&&!ot(t)&&(console.warn(`[Security] Removing existing unapproved custom element: <${t}>`),e.remove())})}catch{}let t=new MutationObserver(e=>{for(let t of e)t.addedNodes.forEach(e=>{if(e.nodeType===1){let t=e,n=t.tagName?t.tagName.toLowerCase():``;n.includes(`-`)&&!ot(n)&&(console.warn(`[Security] Removing unapproved custom element: <${n}>`),t.remove())}})});return t.observe(e,{childList:!0,subtree:!0}),t}function gt(e){if(e instanceof Blob)return e.arrayBuffer();if(e instanceof ArrayBuffer)return Promise.resolve(e.slice(0));let{buffer:t,byteOffset:n,byteLength:r}=e;return Promise.resolve(t.slice(n,n+r))}function _t(e){return Array.from(new Uint8Array(e)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function H(e){let t=await gt(e),n=globalThis.crypto?.subtle??globalThis.window?.crypto?.subtle??(r===void 0?void 0:(await import(`node:crypto`)).webcrypto?.subtle);if(!n)throw Error(`crypto.subtle is not available in current environment`);return _t(await n.digest(`SHA-256`,t))}const U=`.well-known/agent-skills/index.json`;function W(e){let t=e.trim();if(!t)throw Error(`URL cannot be empty`);let n=t;if(!n.startsWith(`http://`)&&!n.startsWith(`https://`)&&(n=`https://${n}`),n=n.replace(/\/+$/,``),n.endsWith(U)){let e=n.slice(0,-35).replace(/\/+$/,``);return{baseUrl:e,siteUrl:e,manifestUrl:n}}return{baseUrl:n,siteUrl:n,manifestUrl:`${n}/${U}`}}function G(e,t){if(!e)return``;try{return new URL(e,t).href}catch{return e}}function K(e,t){let n=JSON.parse(JSON.stringify(e));return Array.isArray(n.tools)&&(n.tools=n.tools.map(e=>({...e,url:G(e.url,t)}))),Array.isArray(n.scripts)&&(n.scripts=n.scripts.map(e=>({...e,url:G(e.url,t)}))),Array.isArray(n.skills)&&(n.skills=n.skills.map(e=>({...e,url:G(e.url,t),tools:Array.isArray(e.tools)?e.tools.map(e=>({...e,url:e.url?G(e.url,t):void 0})):void 0,scripts:Array.isArray(e.scripts)?e.scripts.map(e=>({...e,url:e.url?G(e.url,t):void 0})):void 0}))),n}async function vt(e,t){if(!t||!t.startsWith(`sha256:`))return!0;let n=t.slice(7).trim().toLowerCase();return!n||(await H(typeof e==`string`?new TextEncoder().encode(e):e)).toLowerCase()===n}async function yt(e,t=globalThis.fetch){let{baseUrl:n,manifestUrl:r}=W(e),i=await t(r,{headers:{Accept:`application/json`}});if(!i.ok)throw Error(`Failed to fetch discovery manifest: HTTP ${i.status} ${i.statusText}`.trim());let a=await i.json();if(!a||typeof a!=`object`)throw Error(`Invalid discovery manifest: expected a JSON object`);return{manifest:K(a,r),siteUrl:n,manifestUrl:r}}export{vt as a,mt as c,K as i,ft as l,W as n,dt as o,G as r,ht as s,yt as t,Qe as u};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./chunk-D3JxbzjI2.js";export{e as executeNativeAiTask};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./chunk-CAqvQuGr.js";export{e as getAgentCore};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import{C as e,b as t,c as n,r}from"./chunk-BkKN8FNP.js";import{i}from"./chunk-DFLqhyP_.js";import{t as a}from"./chunk-Dhh0lHO62.js";import{r as o}from"./chunk-BQCWtrzh2.js";function s(e=``,t=``){let n=e.toLowerCase(),r=t.toLowerCase();return n.startsWith(`text/`)||n.includes(`json`)||n.includes(`xml`)||r.endsWith(`.md`)||r.endsWith(`.txt`)?`text`:n.startsWith(`image/`)?`image`:n.startsWith(`audio/`)?`audio`:n.startsWith(`video/`)?`video`:n===`application/pdf`||r.endsWith(`.pdf`)?`document`:`file`}function c(t){let n=(t||``).toLowerCase(),r=e.getModelInfo(n);if(r){let e=r.supportsImageInput===!0||r.routesByRequestFeatures===!0,t=r.supportsAudioInput===!0||r.routesByRequestFeatures===!0,n=r.supportsVideoInput===!0||r.routesByRequestFeatures===!0,i=r.supportsDocumentInput===!0||r.routesByRequestFeatures===!0;if(r.supportsImageInput!==void 0||r.supportsAudioInput!==void 0||r.supportsVideoInput!==void 0||r.supportsDocumentInput!==void 0||r.routesByRequestFeatures)return{images:e,audio:t,video:n,documents:i,routerByFeatures:!!r.routesByRequestFeatures,source:`metadata`}}let i=[`gpt-4o`,`gpt-4.1`,`claude-3`,`claude-4`,`claude-sonnet`,`claude-haiku`,`claude-opus`,`gemini`,`llava`,`qwen-vl`,`pixtral`].some(e=>n.includes(e)),a=n.includes(`claude-3-5`)||n.includes(`claude-3.5`)||n.includes(`claude-3-7`)||n.includes(`claude-3.7`)||n.includes(`claude-4`)||n.includes(`gemini`)||/claude-(?:sonnet|haiku|opus)-\d/.test(n);return i?{images:!0,audio:n.includes(`omni`)||n.includes(`audio`),video:n.includes(`omni`)||n.includes(`video`),documents:a,routerByFeatures:n===`openrouter/free`,source:`heuristic`}:{images:!1,audio:!1,video:!1,documents:!1,routerByFeatures:n===`openrouter/free`,source:`unknown`}}const l=[/<\|start_header_id\|>\s*(?:system|user|assistant|tool)\s*<\|end_header_id\|>/gi,/<\|(?:begin_of_text|end_of_text|eot_id|im_start|im_end|end_of_message)\|>/gi,/<\|(?:startofturn|endofturn|start_of_turn|end_of_turn)\|>/gi,/<\|(?:image|audio|video|tool_call|tool_response|tool_result|function_call)\|>|<\|\/function_call\|>/gi,/<|(?:system|user|assistant|im_start|im_end)|>/g,/\[\s*INST\s*\]|\[\s*\/INST\s*\]|<<\s*SYS\s*>>|<<\s*\/SYS\s*>>/gi,/<\/?s>|<\/?bos>|<\/?eos>|<\|(?:bos|eos|pad|unk)\|>/gi,/<\|(?:START_OF_TURN_TOKEN|END_OF_TURN_TOKEN|CHATBOT_TOKEN|USER_TOKEN|SYSTEM_TOKEN)\|>/gi,/<\|(?:system|user|assistant|end|endoftext|placeholder\d*)\|>/gi,/<|(?:begin▁of▁sentence|end▁of▁sentence)|>/g,/<\|start\|>\s*(?:system|user|assistant|tool)\s*<\|message\|>/gi];function u(e){for(let t of l)if(t.test(e))return!0;return!1}function d(e){let t=String(e||``),n=t;for(let e of l)t=t.replace(e,``);return t!==n&&(t=t.replace(/^[ \t]+$/gm,``),t=t.replace(/\n{3,}/g,`
|
|
2
|
+
|
|
3
|
+
`)),t}function f(e,t){let n=d(e);return n!==e&&u(e)&&console.info(`[ShadowClaw] Chat-template control token(s) detected and stripped from "${t}" output. The provider or model may not be applying its chat template correctly. Original length: ${e.length}, cleaned length: ${n.length}.`),n}const p=`shadow-claw-browser-models`,m=16*1024*1024;function h(){return typeof caches<`u`&&typeof caches.open==`function`}function g(e){return`${e}?__sc_meta=1`}function _(e,t){return`${e}?__sc_chunk=${t}`}async function v(e,t=p){if(!h())return null;try{let n=await(await caches.open(t)).match(g(e));if(!n?.body)return null;let r=await n.text();return JSON.parse(r)}catch{return null}}async function y(e,t,n=p){if(h())try{await(await caches.open(n)).put(g(e),new Response(JSON.stringify(t),{headers:{"Content-Type":`application/json`}}))}catch(e){console.error(`writePartialMeta error:`,e)}}async function ee(e,t,n,r=p){if(h())try{await(await caches.open(r)).put(_(e,t),new Response(new Blob([n]),{headers:{"Content-Type":`application/octet-stream`,"Content-Length":String(n.byteLength)}}))}catch(e){console.error(`flushChunkToCache error:`,e)}}function b(e,t,n=p){let r=0,i=null;return new ReadableStream({async pull(a){if(i){let{done:e,value:t}=await i.read();if(!e){a.enqueue(t);return}i=null,r++}if(r>=t.chunks){a.close();return}try{let t=await(await caches.open(n)).match(_(e,r));if(!t?.body){a.error(Error(`ModelCache: missing cache chunk ${r} for ${e}`));return}i=t.body.getReader();let{done:o,value:s}=await i.read();o?(i=null,r++):a.enqueue(s)}catch(e){a.error(e)}},cancel(){i&&=(i.cancel(),null)}})}function te(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new DOMException(`Aborted`,`AbortError`));return}let i=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),r(new DOMException(`Aborted`,`AbortError`))};t?.addEventListener(`abort`,a,{once:!0})})}function ne(e){return Math.min(15e3,1e3*2**(Math.max(1,e)-1))}async function re(e,t,n,r,i=globalThis.fetch?globalThis.fetch.bind(globalThis):fetch){let a=r?.cacheName??`shadow-claw-browser-models`,o=r?.chunkSize??16777216,s=r?.maxAttempts??6,c=r?.headers??{},l=h(),u=0,d=0,f=null,p=!1,m=e;if(l){let t=await v(e,a);t&&!t.complete&&(u=t.chunks,d=t.received,f=t.total,p=t.acceptsRanges,t.resolvedUrl&&(m=t.resolvedUrl))}let g=null,b=null;for(let e=1;e<=s;e++){if(n?.aborted)throw new DOMException(`Aborted`,`AbortError`);let t={...c};d>0&&p&&(t.Range=`bytes=${d}-`);try{b=await i(m,{signal:n,headers:t})}catch(t){if(n?.aborted||t?.name===`AbortError`)throw t;if(g=t,e<s){await te(ne(e),n);continue}break}if(b.url&&(m=b.url),t.Range&&b.status===200&&(u=0,d=0),b.status!==200&&b.status!==206){if(g=Error(`ModelCache: Failed to fetch model from '${m}': ${b.status} ${b.statusText}`),b.status>=500&&e<s){await te(ne(e),n);continue}throw g}if(!b.body)throw Error(`ModelCache: Failed to fetch model from '${m}': No response body`);g=null;break}if(g||!b||!b.body)throw Error(`ModelCache: failed to download model from '${e}' after ${s} attempts: ${g?.message??String(g)}`);if(f==null)if(p=b.status===206||b.headers.get(`accept-ranges`)===`bytes`,b.status===206){let e=b.headers.get(`content-range`)?.match(/\/\s*(\d+)\s*$/);e&&(f=Number(e[1]))}else{let e=b.headers.get(`content-length`),t=e?Number(e):NaN;f=Number.isFinite(t)&&t>0?t:null}l&&await y(e,{chunks:u,received:d,total:f,acceptsRanges:p,complete:!1,resolvedUrl:m},a);let re=b.body;return new ReadableStream({async start(r){try{if(l&&u>0){let i=await caches.open(a),o=0;for(let a=0;a<u;a++){if(n?.aborted)throw new DOMException(`Aborted`,`AbortError`);let s=await i.match(_(e,a));if(s?.body){let e=s.body.getReader();for(;;){let{done:n,value:i}=await e.read();if(n)break;r.enqueue(i),o+=i.byteLength,t?.(o,f)}}else if(s&&typeof s.arrayBuffer==`function`){let e=await s.arrayBuffer(),n=new Uint8Array(e);r.enqueue(n),o+=n.byteLength,t?.(o,f)}}}let i=[],s=0,c=d;async function h(){if(s===0)return;let t=new Uint8Array(s),n=0;for(let e of i)t.set(e,n),n+=e.byteLength;i=[],s=0,l?(await ee(e,u,t,a),u++,d+=t.byteLength,await y(e,{chunks:u,received:d,total:f,acceptsRanges:p,complete:!1,resolvedUrl:m},a)):(u++,d+=t.byteLength)}let g=re.getReader();try{for(;;){if(n?.aborted)throw await g.cancel(),new DOMException(`Aborted`,`AbortError`);let{done:e,value:a}=await g.read();if(e)break;r.enqueue(a),i.push(a),s+=a.byteLength,c+=a.byteLength,t?.(c,f),s>=o&&await h()}await h(),l&&await y(e,{chunks:u,received:d,total:f,acceptsRanges:p,complete:!0,resolvedUrl:m},a),t?.(c,f,!0),r.close()}catch(e){try{await g.cancel()}catch{}throw e}}catch(e){r.error(e)}}})}async function x(e,t,n,r,i=globalThis.fetch?globalThis.fetch.bind(globalThis):fetch){let a=r?.cacheName??`shadow-claw-browser-models`;try{let n=await v(e,a);if(n?.complete)return t?.(n.received,n.received,!0),b(e,n,a)}catch(e){console.warn(`loadModelStream cache check failed, falling back to download:`,e)}return re(e,t,n,r,i)}let S=null;function ie(e){S=e}function ae(){S=null}function C(e=globalThis.fetch?globalThis.fetch.bind(globalThis):fetch,t,n){let r=t?.cacheName??`shadow-claw-browser-models`;return async function(i,a){let o=typeof i==`string`?i:i instanceof URL?i.toString():i.url,s=(a?.method||(typeof i==`object`&&`method`in i?i.method:`GET`)||`GET`).toUpperCase(),c=a?.headers||(typeof i==`object`&&`headers`in i?i.headers:void 0);if(c instanceof Headers?c.has(`Range`)||c.has(`range`):c&&typeof c==`object`&&(`Range`in c||`range`in c))return e(i,{...a||{},cache:`no-store`});if(s!==`GET`||!h())return e(i,a);try{let i=await v(o,r);if(i?.complete){n?.(o,i.received,i.received,!0),S?.(o,i.received,i.received,!0);let e=b(o,i,r);return new Response(e,{status:200,statusText:`OK`,headers:{"Content-Type":`application/octet-stream`,...i.total!=null&&i.total>0?{"Content-Length":String(i.total)}:{}}})}let s=await x(o,(e,t,r)=>{n?.(o,e,t,!!r),S?.(o,e,t,!!r)},a?.signal??void 0,{cacheName:r,...t||{}},e),c=(await v(o,r))?.total;return new Response(s,{status:200,statusText:`OK`,headers:{"Content-Type":`application/octet-stream`,...c!=null&&c>0?{"Content-Length":String(c)}:{}}})}catch(t){return console.warn(`[ModelCacheFetch] Cache stream failed for ${o}, falling back to native fetch:`,t),e(i,a)}}}var oe=Object.defineProperty,se=(e,t,n)=>t in e?oe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ce=(e,t,n)=>(se(e,typeof t==`symbol`?t:t+``,n),n),w=Object.freeze({Text:`Text`,NumericLiteral:`NumericLiteral`,StringLiteral:`StringLiteral`,Identifier:`Identifier`,Equals:`Equals`,OpenParen:`OpenParen`,CloseParen:`CloseParen`,OpenStatement:`OpenStatement`,CloseStatement:`CloseStatement`,OpenExpression:`OpenExpression`,CloseExpression:`CloseExpression`,OpenSquareBracket:`OpenSquareBracket`,CloseSquareBracket:`CloseSquareBracket`,OpenCurlyBracket:`OpenCurlyBracket`,CloseCurlyBracket:`CloseCurlyBracket`,Comma:`Comma`,Dot:`Dot`,Colon:`Colon`,Pipe:`Pipe`,CallOperator:`CallOperator`,AdditiveBinaryOperator:`AdditiveBinaryOperator`,MultiplicativeBinaryOperator:`MultiplicativeBinaryOperator`,ComparisonBinaryOperator:`ComparisonBinaryOperator`,UnaryOperator:`UnaryOperator`,Comment:`Comment`}),T=class{constructor(e,t){this.value=e,this.type=t}};function E(e){return/\w/.test(e)}function D(e){return/[0-9]/.test(e)}function le(e){return/\s/.test(e)}var ue=[[`{%`,w.OpenStatement],[`%}`,w.CloseStatement],[`{{`,w.OpenExpression],[`}}`,w.CloseExpression],[`(`,w.OpenParen],[`)`,w.CloseParen],[`{`,w.OpenCurlyBracket],[`}`,w.CloseCurlyBracket],[`[`,w.OpenSquareBracket],[`]`,w.CloseSquareBracket],[`,`,w.Comma],[`.`,w.Dot],[`:`,w.Colon],[`|`,w.Pipe],[`<=`,w.ComparisonBinaryOperator],[`>=`,w.ComparisonBinaryOperator],[`==`,w.ComparisonBinaryOperator],[`!=`,w.ComparisonBinaryOperator],[`<`,w.ComparisonBinaryOperator],[`>`,w.ComparisonBinaryOperator],[`+`,w.AdditiveBinaryOperator],[`-`,w.AdditiveBinaryOperator],[`~`,w.AdditiveBinaryOperator],[`*`,w.MultiplicativeBinaryOperator],[`/`,w.MultiplicativeBinaryOperator],[`%`,w.MultiplicativeBinaryOperator],[`=`,w.Equals]],de=new Map([[`n`,`
|
|
4
|
+
`],[`t`,` `],[`r`,`\r`],[`b`,`\b`],[`f`,`\f`],[`v`,`\v`],[`'`,`'`],[`"`,`"`],[`\\`,`\\`]]);function fe(e,t={}){return e.endsWith(`
|
|
5
|
+
`)&&(e=e.slice(0,-1)),t.lstrip_blocks&&(e=e.replace(/^[ \t]*({[#%-])/gm,`$1`)),t.trim_blocks&&(e=e.replace(/([#%-]})\n/g,`$1`)),e.replace(/(\s*){%(-?)\s*(?:end)?generation\s*(-?)%}(\s*)/gs,(e,t,n,r,i)=>(n?``:t)+(r?``:i))}function pe(e,t={}){let n=[],r=fe(e,t),i=0,a=0,o=e=>{let t=``;for(;e(r[i]);){if(r[i]===`\\`){if(++i,i>=r.length)throw SyntaxError(`Unexpected end of input`);let e=r[i++],n=de.get(e);if(n===void 0)throw SyntaxError(`Unexpected escaped character: ${e}`);t+=n;continue}if(t+=r[i++],i>=r.length)throw SyntaxError(`Unexpected end of input`)}return t},s=()=>{let e=n.at(-1);e&&e.type===w.Text&&(e.value=e.value.trimEnd(),e.value===``&&n.pop())},c=()=>{for(;i<r.length&&le(r[i]);)++i};main:for(;i<r.length;){let e=n.at(-1)?.type;if(e===void 0||e===w.CloseStatement||e===w.CloseExpression||e===w.Comment){let e=``;for(;i<r.length&&!(r[i]===`{`&&(r[i+1]===`%`||r[i+1]===`{`||r[i+1]===`#`));)e+=r[i++];if(e.length>0){n.push(new T(e,w.Text));continue}}if(r[i]===`{`&&r[i+1]===`#`){i+=2;let e=r[i]===`-`;e&&++i;let t=``;for(;r[i]!==`#`||r[i+1]!==`}`;){if(i+2>=r.length)throw SyntaxError(`Missing end of comment tag`);t+=r[i++]}let a=t.endsWith(`-`);a&&(t=t.slice(0,-1)),e&&s(),n.push(new T(t,w.Comment)),i+=2,a&&c();continue}if(r.slice(i,i+3)===`{%-`){s(),n.push(new T(`{%`,w.OpenStatement)),i+=3;continue}if(r.slice(i,i+3)===`{{-`){s(),n.push(new T(`{{`,w.OpenExpression)),a=0,i+=3;continue}if(o(le),r.slice(i,i+3)===`-%}`){n.push(new T(`%}`,w.CloseStatement)),i+=3,c();continue}if(r.slice(i,i+3)===`-}}`){n.push(new T(`}}`,w.CloseExpression)),i+=3,c();continue}let t=r[i];if(t===`-`||t===`+`){let e=n.at(-1)?.type;if(e===w.Text||e===void 0)throw SyntaxError(`Unexpected character: ${t}`);switch(e){case w.Identifier:case w.NumericLiteral:case w.StringLiteral:case w.CloseParen:case w.CloseSquareBracket:break;default:{++i;let e=o(D);n.push(new T(`${t}${e}`,e.length>0?w.NumericLiteral:w.UnaryOperator));continue}}}for(let[e,t]of ue)if(!(e===`}}`&&a>0)&&r.slice(i,i+e.length)===e){n.push(new T(e,t)),t===w.OpenExpression?a=0:t===w.OpenCurlyBracket?++a:t===w.CloseCurlyBracket&&--a,i+=e.length;continue main}if(t===`'`||t===`"`){++i;let e=o(e=>e!==t);n.push(new T(e,w.StringLiteral)),++i;continue}if(D(t)){let e=o(D);if(r[i]===`.`&&D(r[i+1])){++i;let t=o(D);e=`${e}.${t}`}n.push(new T(e,w.NumericLiteral));continue}if(E(t)){let e=o(E);n.push(new T(e,w.Identifier));continue}throw SyntaxError(`Unexpected character: ${t}`)}return n}var O=class{type=`Statement`},me=class extends O{constructor(e){super(),this.body=e}type=`Program`},he=class extends O{constructor(e,t,n){super(),this.test=e,this.body=t,this.alternate=n}type=`If`},ge=class extends O{constructor(e,t,n,r){super(),this.loopvar=e,this.iterable=t,this.body=n,this.defaultBlock=r}type=`For`},_e=class extends O{type=`Break`},ve=class extends O{type=`Continue`},ye=class extends O{constructor(e,t,n){super(),this.assignee=e,this.value=t,this.body=n}type=`Set`},be=class extends O{constructor(e,t,n){super(),this.name=e,this.args=t,this.body=n}type=`Macro`},xe=class extends O{constructor(e){super(),this.value=e}type=`Comment`},k=class extends O{type=`Expression`},Se=class extends k{constructor(e,t,n){super(),this.object=e,this.property=t,this.computed=n}type=`MemberExpression`},Ce=class extends k{constructor(e,t){super(),this.callee=e,this.args=t}type=`CallExpression`},A=class extends k{constructor(e){super(),this.value=e}type=`Identifier`},j=class extends k{constructor(e){super(),this.value=e}type=`Literal`},we=class extends j{type=`IntegerLiteral`},Te=class extends j{type=`FloatLiteral`},Ee=class extends j{type=`StringLiteral`},De=class extends j{type=`ArrayLiteral`},Oe=class extends j{type=`TupleLiteral`},ke=class extends j{type=`ObjectLiteral`},M=class extends k{constructor(e,t,n){super(),this.operator=e,this.left=t,this.right=n}type=`BinaryExpression`},Ae=class extends k{constructor(e,t){super(),this.operand=e,this.filter=t}type=`FilterExpression`},je=class extends O{constructor(e,t){super(),this.filter=e,this.body=t}type=`FilterStatement`},Me=class extends k{constructor(e,t){super(),this.lhs=e,this.test=t}type=`SelectExpression`},Ne=class extends k{constructor(e,t,n){super(),this.operand=e,this.negate=t,this.test=n}type=`TestExpression`},Pe=class extends k{constructor(e,t){super(),this.operator=e,this.argument=t}type=`UnaryExpression`},Fe=class extends k{constructor(e=void 0,t=void 0,n=void 0){super(),this.start=e,this.stop=t,this.step=n}type=`SliceExpression`},Ie=class extends k{constructor(e,t){super(),this.key=e,this.value=t}type=`KeywordArgumentExpression`},Le=class extends k{constructor(e){super(),this.argument=e}type=`SpreadExpression`},Re=class extends O{constructor(e,t,n){super(),this.call=e,this.callerArgs=t,this.body=n}type=`CallStatement`},ze=class extends k{constructor(e,t,n){super(),this.condition=e,this.trueExpr=t,this.falseExpr=n}type=`Ternary`};function Be(e){let t=new me([]),n=0;function r(t,r){let i=e[n++];if(!i||i.type!==t)throw Error(`Parser Error: ${r}. ${i.type} !== ${t}.`);return i}function i(e){if(!c(e))throw SyntaxError(`Expected ${e}`);++n}function a(){switch(e[n].type){case w.Comment:return new xe(e[n++].value);case w.Text:return l();case w.OpenStatement:return u();case w.OpenExpression:return d();default:throw SyntaxError(`Unexpected token type: ${e[n].type}`)}}function o(...t){return n+t.length<=e.length&&t.every((t,r)=>t===e[n+r].type)}function s(...t){return e[n]?.type===w.OpenStatement&&e[n+1]?.type===w.Identifier&&t.includes(e[n+1]?.value)}function c(...t){return n+t.length<=e.length&&t.every((t,r)=>e[n+r].type===`Identifier`&&t===e[n+r].value)}function l(){return new Ee(r(w.Text,`Expected text token`).value)}function u(){if(r(w.OpenStatement,`Expected opening statement token`),e[n].type!==w.Identifier)throw SyntaxError(`Unknown statement, got ${e[n].type}`);let t=e[n].value,c;switch(t){case`set`:++n,c=f();break;case`if`:++n,c=p(),r(w.OpenStatement,`Expected {% token`),i(`endif`),r(w.CloseStatement,`Expected %} token`);break;case`macro`:++n,c=m(),r(w.OpenStatement,`Expected {% token`),i(`endmacro`),r(w.CloseStatement,`Expected %} token`);break;case`for`:++n,c=g(),r(w.OpenStatement,`Expected {% token`),i(`endfor`),r(w.CloseStatement,`Expected %} token`);break;case`call`:{++n;let e=null;o(w.OpenParen)&&(e=S());let t=E();if(t.type!==`Identifier`)throw SyntaxError(`Expected identifier following call statement`);let l=S();r(w.CloseStatement,`Expected closing statement token`);let u=[];for(;!s(`endcall`);)u.push(a());r(w.OpenStatement,`Expected '{%'`),i(`endcall`),r(w.CloseStatement,`Expected closing statement token`),c=new Re(new Ce(t,l),e,u);break}case`break`:++n,r(w.CloseStatement,`Expected closing statement token`),c=new _e;break;case`continue`:++n,r(w.CloseStatement,`Expected closing statement token`),c=new ve;break;case`filter`:{++n;let e=E();e instanceof A&&o(w.OpenParen)&&(e=x(e)),r(w.CloseStatement,`Expected closing statement token`);let t=[];for(;!s(`endfilter`);)t.push(a());r(w.OpenStatement,`Expected '{%'`),i(`endfilter`),r(w.CloseStatement,`Expected '%}'`),c=new je(e,t);break}default:throw SyntaxError(`Unknown statement type: ${t}`)}return c}function d(){r(w.OpenExpression,`Expected opening expression token`);let e=_();return r(w.CloseExpression,`Expected closing expression token`),e}function f(){let e=h(),t=null,c=[];if(o(w.Equals))++n,t=h();else{for(r(w.CloseStatement,`Expected %} token`);!s(`endset`);)c.push(a());r(w.OpenStatement,`Expected {% token`),i(`endset`)}return r(w.CloseStatement,`Expected closing statement token`),new ye(e,t,c)}function p(){let e=_();r(w.CloseStatement,`Expected closing statement token`);let t=[],i=[];for(;!s(`elif`,`else`,`endif`);)t.push(a());if(s(`elif`)){++n,++n;let e=p();i.push(e)}else if(s(`else`))for(++n,++n,r(w.CloseStatement,`Expected closing statement token`);!s(`endif`);)i.push(a());return new he(e,t,i)}function m(){let e=E();if(e.type!==`Identifier`)throw SyntaxError(`Expected identifier following macro statement`);let t=S();r(w.CloseStatement,`Expected closing statement token`);let n=[];for(;!s(`endmacro`);)n.push(a());return new be(e,t,n)}function h(e=!1){let t=e?E:_,r=[t()],i=o(w.Comma);for(;i&&(++n,r.push(t()),o(w.Comma)););return i?new Oe(r):r[0]}function g(){let e=h(!0);if(!(e instanceof A||e instanceof Oe))throw SyntaxError(`Expected identifier/tuple for the loop variable, got ${e.type} instead`);if(!c(`in`))throw SyntaxError("Expected `in` keyword following loop variable");++n;let t=_();r(w.CloseStatement,`Expected closing statement token`);let i=[];for(;!s(`endfor`,`else`);)i.push(a());let o=[];if(s(`else`))for(++n,++n,r(w.CloseStatement,`Expected closing statement token`);!s(`endfor`);)o.push(a());return new ge(e,t,i,o)}function _(){return v()}function v(){let e=y();if(c(`if`)){++n;let t=y();return c(`else`)?(++n,new ze(t,e,v())):new Me(e,t)}return e}function y(){let t=ee();for(;c(`or`);){let r=e[n];++n;let i=ee();t=new M(r,t,i)}return t}function ee(){let t=b();for(;c(`and`);){let r=e[n];++n;let i=b();t=new M(r,t,i)}return t}function b(){let t;for(;c(`not`);){let r=e[n];++n,t=new Pe(r,b())}return t??te()}function te(){let t=ne();for(;;){let r;if(c(`not`,`in`))r=new T(`not in`,w.Identifier),n+=2;else if(c(`in`))r=e[n++];else if(o(w.ComparisonBinaryOperator))r=e[n++];else break;let i=ne();t=new M(r,t,i)}return t}function ne(){let t=oe();for(;o(w.AdditiveBinaryOperator);){let r=e[n];++n;let i=oe();t=new M(r,t,i)}return t}function re(){let e=C(E());return o(w.OpenParen)?x(e):e}function x(e){let t=new Ce(e,S());return t=C(t),o(w.OpenParen)&&(t=x(t)),t}function S(){r(w.OpenParen,`Expected opening parenthesis for arguments list`);let e=ie();return r(w.CloseParen,`Expected closing parenthesis for arguments list`),e}function ie(){let t=[];for(;!o(w.CloseParen);){let r;if(e[n].type===w.MultiplicativeBinaryOperator&&e[n].value===`*`)++n,r=new Le(_());else if(r=_(),o(w.Equals)){if(++n,!(r instanceof A))throw SyntaxError(`Expected identifier for keyword argument`);let e=_();r=new Ie(r,e)}t.push(r),o(w.Comma)&&++n}return t}function ae(){let e=[],t=!1;for(;!o(w.CloseSquareBracket);)o(w.Colon)?(e.push(void 0),++n,t=!0):(e.push(_()),o(w.Colon)&&(++n,t=!0));if(e.length===0)throw SyntaxError(`Expected at least one argument for member/slice expression`);if(t){if(e.length>3)throw SyntaxError(`Expected 0-3 arguments for slice expression`);return new Fe(...e)}return e[0]}function C(t){for(;o(w.Dot)||o(w.OpenSquareBracket);){let i=e[n];++n;let a,o=i.type===w.OpenSquareBracket;if(o)a=ae(),r(w.CloseSquareBracket,`Expected closing square bracket`);else if(a=E(),a.type!==`Identifier`)throw SyntaxError(`Expected identifier following dot operator`);t=new Se(t,a,o)}return t}function oe(){let t=se();for(;o(w.MultiplicativeBinaryOperator);){let r=e[n++],i=se();t=new M(r,t,i)}return t}function se(){let e=ce();for(;c(`is`);){++n;let t=c(`not`);t&&++n;let r=E();if(!(r instanceof A))throw SyntaxError(`Expected identifier for the test`);e=new Ne(e,t,r)}return e}function ce(){let e=re();for(;o(w.Pipe);){++n;let t=E();if(!(t instanceof A))throw SyntaxError(`Expected identifier for the filter`);o(w.OpenParen)&&(t=x(t)),e=new Ae(e,t)}return e}function E(){let t=e[n++];switch(t.type){case w.NumericLiteral:{let e=t.value;return e.includes(`.`)?new Te(Number(e)):new we(Number(e))}case w.StringLiteral:{let r=t.value;for(;o(w.StringLiteral);)r+=e[n++].value;return new Ee(r)}case w.Identifier:return new A(t.value);case w.OpenParen:{let e=h();return r(w.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),e}case w.OpenSquareBracket:{let e=[];for(;!o(w.CloseSquareBracket);)e.push(_()),o(w.Comma)&&++n;return++n,new De(e)}case w.OpenCurlyBracket:{let e=new Map;for(;!o(w.CloseCurlyBracket);){let t=_();r(w.Colon,`Expected colon between key and value in object literal`);let i=_();e.set(t,i),o(w.Comma)&&++n}return++n,new ke(e)}default:throw SyntaxError(`Unexpected token: ${t.type}`)}}for(;n<e.length;)t.body.push(a());return t}function Ve(e,t,n=1){if(t===void 0&&(t=e,e=0),n===0)throw Error(`range() step must not be zero`);let r=[];if(n>0)for(let i=e;i<t;i+=n)r.push(i);else for(let i=e;i>t;i+=n)r.push(i);return r}function He(e,t,n,r=1){let i=Math.sign(r);i>=0?(t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length),n=(n??=e.length)<0?Math.max(e.length+n,0):Math.min(n,e.length)):(t=(t??=e.length-1)<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),n=(n??=-1)<-1?Math.max(e.length+n,-1):Math.min(n,e.length-1));let a=[];for(let o=t;i*o<i*n;o+=r)a.push(e[o]);return a}function Ue(e){return e.replace(/\b\w/g,e=>e.toUpperCase())}function We(e){return Ge(new Date,e)}function Ge(e,t){let n=new Intl.DateTimeFormat(void 0,{month:`long`}),r=new Intl.DateTimeFormat(void 0,{month:`short`}),i=e=>e<10?`0`+e:e.toString();return t.replace(/%[YmdbBHM%]/g,t=>{switch(t){case`%Y`:return e.getFullYear().toString();case`%m`:return i(e.getMonth()+1);case`%d`:return i(e.getDate());case`%b`:return r.format(e);case`%B`:return n.format(e);case`%H`:return i(e.getHours());case`%M`:return i(e.getMinutes());case`%%`:return`%`;default:return t}})}function Ke(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function qe(e,t,n,r){if(r===0)return e;let i=r==null||r<0?1/0:r,a=t.length===0?RegExp(`(?=)`,`gu`):new RegExp(Ke(t),`gu`);return e.replaceAll(a,e=>i>0?(--i,n):e)}var Je=class extends Error{},Ye=class extends Error{},Xe=new Map,N=class{type=`RuntimeValue`;value;get builtins(){return Xe}constructor(e=void 0){this.value=e}__bool__(){return new L(!!this.value)}toString(){return String(this.value)}},P=class extends N{type=`IntegerValue`},F=class extends N{type=`FloatValue`;toString(){return this.value%1==0?this.value.toFixed(1):this.value.toString()}},I=class extends N{type=`StringValue`;_builtins;get builtins(){return this._builtins??=new Map([[`upper`,new H(()=>new I(this.value.toUpperCase()))],[`lower`,new H(()=>new I(this.value.toLowerCase()))],[`strip`,new H(()=>new I(this.value.trim()))],[`title`,new H(()=>new I(Ue(this.value)))],[`capitalize`,new H(()=>new I(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],[`length`,new P(this.value.length)],[`rstrip`,new H(()=>new I(this.value.trimEnd()))],[`lstrip`,new H(()=>new I(this.value.trimStart()))],[`startswith`,new H(e=>{if(e.length===0)throw Error(`startswith() requires at least one argument`);let t=e[0];if(t instanceof I)return new L(this.value.startsWith(t.value));if(t instanceof V){for(let e of t.value){if(!(e instanceof I))throw Error(`startswith() tuple elements must be strings`);if(this.value.startsWith(e.value))return new L(!0)}return new L(!1)}throw Error(`startswith() argument must be a string or tuple of strings`)})],[`endswith`,new H(e=>{if(e.length===0)throw Error(`endswith() requires at least one argument`);let t=e[0];if(t instanceof I)return new L(this.value.endsWith(t.value));if(t instanceof V){for(let e of t.value){if(!(e instanceof I))throw Error(`endswith() tuple elements must be strings`);if(this.value.endsWith(e.value))return new L(!0)}return new L(!1)}throw Error(`endswith() argument must be a string or tuple of strings`)})],[`split`,new H(e=>{let t=e[0]??new U;if(!(t instanceof I||t instanceof U))throw Error(`sep argument must be a string or null`);let n=e[1]??new P(-1);if(!(n instanceof P))throw Error(`maxsplit argument must be a number`);let r=[];if(t instanceof U){let e=this.value.trimStart();for(let{0:t,index:i}of e.matchAll(/\S+/g)){if(n.value!==-1&&r.length>=n.value&&i!==void 0){r.push(t+e.slice(i+t.length));break}r.push(t)}}else{if(t.value===``)throw Error(`empty separator`);r=this.value.split(t.value),n.value!==-1&&r.length>n.value&&r.push(r.splice(n.value).join(t.value))}return new V(r.map(e=>new I(e)))})],[`replace`,new H(e=>{if(e.length<2)throw Error(`replace() requires at least two arguments`);let t=e[0],n=e[1];if(!(t instanceof I&&n instanceof I))throw Error(`replace() arguments must be strings`);let r;if(r=e.length>2?e[2].type===`KeywordArgumentsValue`?e[2].value.get(`count`)??new U:e[2]:new U,!(r instanceof P||r instanceof U))throw Error(`replace() count argument must be a number or null`);return new I(qe(this.value,t.value,n.value,r.value))})]])}},L=class extends N{type=`BooleanValue`},Ze=/[\x7f-\uffff]/g;function Qe(e){return e.replace(Ze,e=>`\\u`+e.charCodeAt(0).toString(16).padStart(4,`0`))}function R(e,t={},n=0,r=!0){let{indent:i=null,ensureAscii:a=!1,separators:o=null,sortKeys:s=!1}=t,c,l;switch(o?[c,l]=o:i?(c=`,`,l=`: `):(c=`, `,l=`: `),e.type){case`NullValue`:return`null`;case`UndefinedValue`:return r?`null`:`undefined`;case`IntegerValue`:case`FloatValue`:case`BooleanValue`:return JSON.stringify(e.value);case`StringValue`:{let t=JSON.stringify(e.value);return a&&(t=Qe(t)),t}case`ArrayValue`:case`ObjectValue`:{let o=i?` `.repeat(i):``,u=`
|
|
6
|
+
`+o.repeat(n),d=u+o;if(e.type===`ArrayValue`){let a=e.value.map(e=>R(e,t,n+1,r));return i?`[${d}${a.join(`${c}${d}`)}${u}]`:`[${a.join(c)}]`}else{let o=Array.from(e.value.entries());s&&(o=o.sort(([e],[t])=>e.localeCompare(t)));let f=o.map(([e,o])=>{let s=JSON.stringify(e);a&&(s=Qe(s));let c=`${s}${l}${R(o,t,n+1,r)}`;return i?`${d}${c}`:c});return i?`{${f.join(c)}${u}}`:`{${f.join(c)}}`}}default:throw Error(`Cannot convert to JSON: ${e.type}`)}}var z=class extends N{type=`ObjectValue`;_builtins;__bool__(){return new L(this.value.size>0)}get builtins(){return this._builtins??=new Map([[`get`,new H(([e,t])=>{if(!(e instanceof I))throw Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new U})],[`items`,new H(()=>this.items())],[`keys`,new H(()=>this.keys())],[`values`,new H(()=>this.values())],[`dictsort`,new H(e=>{let t=new Map,n=e.filter(e=>e instanceof B?(t=e.value,!1):!0),r=n.at(0)??t.get(`case_sensitive`)??new L(!1);if(!(r instanceof L))throw Error(`case_sensitive must be a boolean`);let i=n.at(1)??t.get(`by`)??new I(`key`);if(!(i instanceof I))throw Error(`by must be a string`);if(![`key`,`value`].includes(i.value))throw Error(`by must be either 'key' or 'value'`);let a=n.at(2)??t.get(`reverse`)??new L(!1);if(!(a instanceof L))throw Error(`reverse must be a boolean`);return new V(Array.from(this.value.entries()).map(([e,t])=>new V([new I(e),t])).sort((e,t)=>{let n=i.value===`key`?0:1,o=e.value[n],s=t.value[n],c=rt(o,s,r.value);return a.value?-c:c}))})]])}items(){return new V(Array.from(this.value.entries()).map(([e,t])=>new V([new I(e),t])))}keys(){return new V(Array.from(this.value.keys()).map(e=>new I(e)))}values(){return new V(Array.from(this.value.values()))}toString(){return R(this,{},0,!1)}},B=class extends z{type=`KeywordArgumentsValue`},V=class extends N{type=`ArrayValue`;_builtins;get builtins(){return this._builtins??=new Map([[`length`,new P(this.value.length)]])}__bool__(){return new L(this.value.length>0)}toString(){return R(this,{},0,!1)}},$e=class extends V{type=`TupleValue`},H=class extends N{type=`FunctionValue`},U=class extends N{type=`NullValue`},W=class extends N{type=`UndefinedValue`},et=class{constructor(e){this.parent=e}variables=new Map([[`namespace`,new H(e=>{if(e.length===0)return new z(new Map);if(e.length!==1||!(e[0]instanceof z))throw Error("`namespace` expects either zero arguments or a single object argument");return e[0]})]]);tests=et.TESTS;set(e,t){return this.declareVariable(e,K(t))}declareVariable(e,t){if(this.variables.has(e))throw SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new W}catch{return new W}}},G=et;ce(G,`TESTS`,new Map([[`boolean`,e=>e.type===`BooleanValue`],[`callable`,e=>e instanceof H],[`odd`,e=>{if(!(e instanceof P))throw Error(`cannot odd on ${e.type}`);return e.value%2!=0}],[`even`,e=>{if(!(e instanceof P))throw Error(`cannot even on ${e.type}`);return e.value%2==0}],[`false`,e=>e.type===`BooleanValue`&&!e.value],[`true`,e=>e.type===`BooleanValue`&&e.value],[`none`,e=>e.type===`NullValue`],[`string`,e=>e.type===`StringValue`],[`number`,e=>e instanceof P||e instanceof F],[`integer`,e=>e instanceof P],[`iterable`,e=>e.type===`ArrayValue`||e.type===`StringValue`],[`mapping`,e=>e instanceof z],[`sequence`,e=>e instanceof V||e instanceof z||e instanceof I],[`lower`,e=>{let t=e.value;return e.type===`StringValue`&&t===t.toLowerCase()}],[`upper`,e=>{let t=e.value;return e.type===`StringValue`&&t===t.toUpperCase()}],[`none`,e=>e.type===`NullValue`],[`defined`,e=>e.type!==`UndefinedValue`],[`undefined`,e=>e.type===`UndefinedValue`],[`equalto`,(e,t)=>e.value===t.value],[`eq`,(e,t)=>e.value===t.value]]));function tt(e){e.set(`false`,!1),e.set(`true`,!0),e.set(`none`,null),e.set(`raise_exception`,e=>{throw Error(e)}),e.set(`range`,Ve),e.set(`strftime_now`,We),e.set(`True`,!0),e.set(`False`,!1),e.set(`None`,null)}function nt(e,t){let n=t.split(`.`),r=e;for(let e of n)if(r instanceof z)r=r.value.get(e)??new W;else if(r instanceof V){let t=parseInt(e,10);if(!isNaN(t)&&t>=0&&t<r.value.length)r=r.value[t];else return new W}else return new W;return r}function rt(e,t,n=!1){if(e instanceof U&&t instanceof U)return 0;if(e instanceof U||t instanceof U)throw Error(`Cannot compare ${e.type} with ${t.type}`);if(e instanceof W&&t instanceof W)return 0;if(e instanceof W||t instanceof W)throw Error(`Cannot compare ${e.type} with ${t.type}`);let r=e=>e instanceof P||e instanceof F||e instanceof L,i=e=>e instanceof L?+!!e.value:e.value;if(r(e)&&r(t)){let n=i(e),r=i(t);return n<r?-1:+(n>r)}if(e.type!==t.type)throw Error(`Cannot compare different types: ${e.type} and ${t.type}`);switch(e.type){case`StringValue`:{let r=e.value,i=t.value;return n||(r=r.toLowerCase(),i=i.toLowerCase()),r<i?-1:+(r>i)}default:throw Error(`Cannot compare type: ${e.type}`)}}var it=class{global;constructor(e){this.global=e??new G}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){let n=this.evaluate(e.left,t);switch(e.operator.value){case`and`:return n.__bool__().value?this.evaluate(e.right,t):n;case`or`:return n.__bool__().value?n:this.evaluate(e.right,t)}let r=this.evaluate(e.right,t);switch(e.operator.value){case`==`:return new L(n.value==r.value);case`!=`:return new L(n.value!=r.value)}if(n instanceof W||r instanceof W){if(r instanceof W&&[`in`,`not in`].includes(e.operator.value))return new L(e.operator.value===`not in`);throw Error(`Cannot perform operation ${e.operator.value} on undefined values`)}else if(n instanceof U||r instanceof U)throw Error(`Cannot perform operation on null values`);else if(e.operator.value===`~`)return new I(n.value.toString()+r.value.toString());else if((n instanceof P||n instanceof F)&&(r instanceof P||r instanceof F)){let t=n.value,i=r.value;switch(e.operator.value){case`+`:case`-`:case`*`:{let a=e.operator.value===`+`?t+i:e.operator.value===`-`?t-i:t*i;return n instanceof F||r instanceof F?new F(a):new P(a)}case`/`:return new F(t/i);case`%`:{let e=t%i;return n instanceof F||r instanceof F?new F(e):new P(e)}case`<`:return new L(t<i);case`>`:return new L(t>i);case`>=`:return new L(t>=i);case`<=`:return new L(t<=i)}}else if(n instanceof V&&r instanceof V)switch(e.operator.value){case`+`:return new V(n.value.concat(r.value))}else if(r instanceof V){let t=r.value.find(e=>e.value===n.value)!==void 0;switch(e.operator.value){case`in`:return new L(t);case`not in`:return new L(!t)}}if(n instanceof I||r instanceof I)switch(e.operator.value){case`+`:return new I(n.value.toString()+r.value.toString())}if(n instanceof I&&r instanceof I)switch(e.operator.value){case`in`:return new L(r.value.includes(n.value));case`not in`:return new L(!r.value.includes(n.value))}if(n instanceof I&&r instanceof z)switch(e.operator.value){case`in`:return new L(r.value.has(n.value));case`not in`:return new L(!r.value.has(n.value))}throw SyntaxError(`Unknown operator "${e.operator.value}" between ${n.type} and ${r.type}`)}evaluateArguments(e,t){let n=[],r=new Map;for(let i of e)if(i.type===`SpreadExpression`){let e=i,r=this.evaluate(e.argument,t);if(!(r instanceof V))throw Error(`Cannot unpack non-iterable type: ${r.type}`);for(let e of r.value)n.push(e)}else if(i.type===`KeywordArgumentExpression`){let e=i;r.set(e.key.value,this.evaluate(e.value,t))}else{if(r.size>0)throw Error(`Positional arguments must come before keyword arguments`);n.push(this.evaluate(i,t))}return[n,r]}applyFilter(e,t,n){if(t.type===`Identifier`){let r=t;if(r.value===`safe`)return e;if(r.value===`tojson`)return new I(R(e,{}));if(e instanceof V)switch(r.value){case`list`:return e;case`first`:return e.value[0];case`last`:return e.value[e.value.length-1];case`length`:return new P(e.value.length);case`reverse`:return new V(e.value.slice().reverse());case`sort`:return new V(e.value.slice().sort((e,t)=>rt(e,t,!1)));case`join`:return new I(e.value.map(e=>e.value).join(``));case`string`:return new I(R(e,{},0,!1));case`unique`:{let t=new Set,n=[];for(let r of e.value)t.has(r.value)||(t.add(r.value),n.push(r));return new V(n)}default:throw Error(`Unknown ArrayValue filter: ${r.value}`)}else if(e instanceof I)switch(r.value){case`length`:case`upper`:case`lower`:case`title`:case`capitalize`:{let t=e.builtins.get(r.value);if(t instanceof H)return t.value([],n);if(t instanceof P)return t;throw Error(`Unknown StringValue filter: ${r.value}`)}case`trim`:return new I(e.value.trim());case`indent`:return new I(e.value.split(`
|
|
7
|
+
`).map((e,t)=>t===0||e.length===0?e:` `+e).join(`
|
|
8
|
+
`));case`join`:case`string`:return e;case`int`:{let t=parseInt(e.value,10);return new P(isNaN(t)?0:t)}case`float`:{let t=parseFloat(e.value);return new F(isNaN(t)?0:t)}default:throw Error(`Unknown StringValue filter: ${r.value}`)}else if(e instanceof P||e instanceof F)switch(r.value){case`abs`:return e instanceof P?new P(Math.abs(e.value)):new F(Math.abs(e.value));case`int`:return new P(Math.floor(e.value));case`float`:return new F(e.value);case`string`:return new I(e.toString());default:throw Error(`Unknown NumericValue filter: ${r.value}`)}else if(e instanceof z)switch(r.value){case`items`:return new V(Array.from(e.value.entries()).map(([e,t])=>new V([new I(e),t])));case`length`:return new P(e.value.size);default:{let t=e.builtins.get(r.value);if(t)return t instanceof H?t.value([],n):t;throw Error(`Unknown ObjectValue filter: ${r.value}`)}}else if(e instanceof L)switch(r.value){case`bool`:return new L(e.value);case`int`:return new P(+!!e.value);case`float`:return new F(+!!e.value);case`string`:return new I(e.value?`true`:`false`);default:throw Error(`Unknown BooleanValue filter: ${r.value}`)}throw Error(`Cannot apply filter "${r.value}" to type: ${e.type}`)}else if(t.type===`CallExpression`){let r=t;if(r.callee.type!==`Identifier`)throw Error(`Unknown filter: ${r.callee.type}`);let i=r.callee.value;if(i===`tojson`){let[,t]=this.evaluateArguments(r.args,n),i=t.get(`indent`)??new U;if(!(i instanceof P||i instanceof U))throw Error(`If set, indent must be a number`);let a=t.get(`ensure_ascii`)??new L(!1);if(!(a instanceof L))throw Error(`If set, ensure_ascii must be a boolean`);let o=t.get(`sort_keys`)??new L(!1);if(!(o instanceof L))throw Error(`If set, sort_keys must be a boolean`);let s=t.get(`separators`)??new U,c=null;if(s instanceof V||s instanceof $e){if(s.value.length!==2)throw Error(`separators must be a tuple of two strings`);let[e,t]=s.value;if(!(e instanceof I)||!(t instanceof I))throw Error(`separators must be a tuple of two strings`);c=[e.value,t.value]}else if(!(s instanceof U))throw Error(`If set, separators must be a tuple of two strings`);return new I(R(e,{indent:i.value,ensureAscii:a.value,sortKeys:o.value,separators:c}))}else if(i===`join`){let t;if(e instanceof I)t=Array.from(e.value);else if(e instanceof V)t=e.value.map(e=>e.value);else throw Error(`Cannot apply filter "${i}" to type: ${e.type}`);let[a,o]=this.evaluateArguments(r.args,n),s=a.at(0)??o.get(`separator`)??new I(``);if(!(s instanceof I))throw Error(`separator must be a string`);return new I(t.join(s.value))}else if(i===`int`||i===`float`){let[t,a]=this.evaluateArguments(r.args,n),o=t.at(0)??a.get(`default`)??(i===`int`?new P(0):new F(0));if(e instanceof I){let t=i===`int`?parseInt(e.value,10):parseFloat(e.value);return isNaN(t)?o:i===`int`?new P(t):new F(t)}else if(e instanceof P||e instanceof F)return e;else if(e instanceof L)return i===`int`?new P(+!!e.value):new F(+!!e.value);else throw Error(`Cannot apply filter "${i}" to type: ${e.type}`)}else if(i==="default"){let[t,i]=this.evaluateArguments(r.args,n),a=t[0]??new I(``),o=t[1]??i.get(`boolean`)??new L(!1);if(!(o instanceof L))throw Error("`default` filter flag must be a boolean");return e instanceof W||o.value&&!e.__bool__().value?a:e}if(e instanceof V){switch(i){case`sort`:{let[t,i]=this.evaluateArguments(r.args,n),a=t.at(0)??i.get(`reverse`)??new L(!1);if(!(a instanceof L))throw Error(`reverse must be a boolean`);let o=t.at(1)??i.get(`case_sensitive`)??new L(!1);if(!(o instanceof L))throw Error(`case_sensitive must be a boolean`);let s=t.at(2)??i.get(`attribute`)??new U;if(!(s instanceof I||s instanceof P||s instanceof U))throw Error(`attribute must be a string, integer, or null`);let c=e=>s instanceof U?e:nt(e,s instanceof P?String(s.value):s.value);return new V(e.value.slice().sort((e,t)=>{let n=rt(c(e),c(t),o.value);return a.value?-n:n}))}case`selectattr`:case`rejectattr`:{let t=i===`selectattr`;if(e.value.some(e=>!(e instanceof z)))throw Error(`\`${i}\` can only be applied to array of objects`);if(r.args.some(e=>e.type!==`StringLiteral`))throw Error(`arguments of \`${i}\` must be strings`);let[a,o,s]=r.args.map(e=>this.evaluate(e,n)),c;if(o){let e=n.tests.get(o.value);if(!e)throw Error(`Unknown test: ${o.value}`);c=e}else c=(...e)=>e[0].__bool__().value;return new V(e.value.filter(e=>{let n=e.value.get(a.value),r=n?c(n,s):!1;return t?r:!r}))}case`map`:{let[,t]=this.evaluateArguments(r.args,n);if(t.has(`attribute`)){let n=t.get(`attribute`);if(!(n instanceof I))throw Error(`attribute must be a string`);let r=t.get(`default`);return new V(e.value.map(e=>{if(!(e instanceof z))throw Error(`items in map must be an object`);let t=nt(e,n.value);return t instanceof W?r??new W:t}))}else throw Error("`map` expressions without `attribute` set are not currently supported.")}}throw Error(`Unknown ArrayValue filter: ${i}`)}else if(e instanceof I){switch(i){case`indent`:{let[t,i]=this.evaluateArguments(r.args,n),a=t.at(0)??i.get(`width`)??new P(4);if(!(a instanceof P))throw Error(`width must be a number`);let o=t.at(1)??i.get(`first`)??new L(!1),s=t.at(2)??i.get(`blank`)??new L(!1),c=e.value.split(`
|
|
9
|
+
`),l=` `.repeat(a.value);return new I(c.map((e,t)=>!o.value&&t===0||!s.value&&e.length===0?e:l+e).join(`
|
|
10
|
+
`))}case`replace`:{let t=e.builtins.get(`replace`);if(!(t instanceof H))throw Error(`replace filter not available`);let[i,a]=this.evaluateArguments(r.args,n);return t.value([...i,new B(a)],n)}}throw Error(`Unknown StringValue filter: ${i}`)}else if(e instanceof z){let t=e.builtins.get(i);if(t&&t instanceof H){let[e,i]=this.evaluateArguments(r.args,n);return i.size>0&&e.push(new B(i)),t.value(e,n)}throw Error(`Unknown ObjectValue filter: ${i}`)}else throw Error(`Cannot apply filter "${i}" to type: ${e.type}`)}throw Error(`Unknown filter: ${t.type}`)}evaluateFilterExpression(e,t){let n=this.evaluate(e.operand,t);return this.applyFilter(n,e.filter,t)}evaluateTestExpression(e,t){let n=this.evaluate(e.operand,t),r=t.tests.get(e.test.value);if(!r)throw Error(`Unknown test: ${e.test.value}`);let i=r(n);return new L(e.negate?!i:i)}evaluateSelectExpression(e,t){return this.evaluate(e.test,t).__bool__().value?this.evaluate(e.lhs,t):new W}evaluateUnaryExpression(e,t){let n=this.evaluate(e.argument,t);switch(e.operator.value){case`not`:return new L(!n.value);default:throw SyntaxError(`Unknown operator: ${e.operator.value}`)}}evaluateTernaryExpression(e,t){return this.evaluate(e.condition,t).__bool__().value?this.evaluate(e.trueExpr,t):this.evaluate(e.falseExpr,t)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let n=``;for(let r of e){let e=this.evaluate(r,t);e.type!==`NullValue`&&e.type!==`UndefinedValue`&&(n+=e.toString())}return new I(n)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){let[n,r]=this.evaluateArguments(e.args,t);r.size>0&&n.push(new B(r));let i=this.evaluate(e.callee,t);if(i.type!==`FunctionValue`)throw Error(`Cannot call something that is not a function: got ${i.type}`);return i.value(n,t)}evaluateSliceExpression(e,t,n){if(!(e instanceof V||e instanceof I))throw Error(`Slice object must be an array or string`);let r=this.evaluate(t.start,n),i=this.evaluate(t.stop,n),a=this.evaluate(t.step,n);if(!(r instanceof P||r instanceof W))throw Error(`Slice start must be numeric or undefined`);if(!(i instanceof P||i instanceof W))throw Error(`Slice stop must be numeric or undefined`);if(!(a instanceof P||a instanceof W))throw Error(`Slice step must be numeric or undefined`);return e instanceof V?new V(He(e.value,r.value,i.value,a.value)):new I(He(Array.from(e.value),r.value,i.value,a.value).join(``))}evaluateMemberExpression(e,t){let n=this.evaluate(e.object,t),r;if(e.computed){if(e.property.type===`SliceExpression`)return this.evaluateSliceExpression(n,e.property,t);r=this.evaluate(e.property,t)}else r=new I(e.property.value);let i;if(n instanceof z){if(!(r instanceof I))throw Error(`Cannot access property with non-string: got ${r.type}`);i=n.value.get(r.value)??n.builtins.get(r.value)}else if(n instanceof V||n instanceof I)if(r instanceof P)i=n.value.at(r.value),n instanceof I&&(i=new I(n.value.at(r.value)));else if(r instanceof I)i=n.builtins.get(r.value);else throw Error(`Cannot access property with non-string/non-number: got ${r.type}`);else{if(!(r instanceof I))throw Error(`Cannot access property with non-string: got ${r.type}`);i=n.builtins.get(r.value)}return i instanceof N?i:new W}evaluateSet(e,t){let n=e.value?this.evaluate(e.value,t):this.evaluateBlock(e.body,t);if(e.assignee.type===`Identifier`){let r=e.assignee.value;t.setVariable(r,n)}else if(e.assignee.type===`TupleLiteral`){let r=e.assignee;if(!(n instanceof V))throw Error(`Cannot unpack non-iterable type in set: ${n.type}`);let i=n.value;if(i.length!==r.value.length)throw Error(`Too ${r.value.length>i.length?`few`:`many`} items to unpack in set`);for(let e=0;e<r.value.length;++e){let n=r.value[e];if(n.type!==`Identifier`)throw Error(`Cannot unpack to non-identifier in set: ${n.type}`);t.setVariable(n.value,i[e])}}else if(e.assignee.type===`MemberExpression`){let r=e.assignee,i=this.evaluate(r.object,t);if(!(i instanceof z))throw Error(`Cannot assign to member of non-object`);if(r.property.type!==`Identifier`)throw Error(`Cannot assign to member with non-identifier property`);i.value.set(r.property.value,n)}else throw Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`);return new U}evaluateIf(e,t){let n=this.evaluate(e.test,t);return this.evaluateBlock(n.__bool__().value?e.body:e.alternate,t)}evaluateFor(e,t){let n=new G(t),r,i;if(e.iterable.type===`SelectExpression`){let t=e.iterable;i=this.evaluate(t.lhs,n),r=t.test}else i=this.evaluate(e.iterable,n);if(!(i instanceof V||i instanceof z))throw Error(`Expected iterable or object type in for loop: got ${i.type}`);i instanceof z&&(i=i.keys());let a=[],o=[];for(let t=0;t<i.value.length;++t){let s=new G(n),c=i.value[t],l;if(e.loopvar.type===`Identifier`)l=t=>t.setVariable(e.loopvar.value,c);else if(e.loopvar.type===`TupleLiteral`){let t=e.loopvar;if(c.type!==`ArrayValue`)throw Error(`Cannot unpack non-iterable type: ${c.type}`);let n=c;if(t.value.length!==n.value.length)throw Error(`Too ${t.value.length>n.value.length?`few`:`many`} items to unpack`);l=e=>{for(let r=0;r<t.value.length;++r){if(t.value[r].type!==`Identifier`)throw Error(`Cannot unpack non-identifier type: ${t.value[r].type}`);e.setVariable(t.value[r].value,n.value[r])}}}else throw Error(`Invalid loop variable(s): ${e.loopvar.type}`);r&&(l(s),!this.evaluate(r,s).__bool__().value)||(a.push(c),o.push(l))}let s=``,c=!0;for(let t=0;t<a.length;++t){let r=new Map([[`index`,new P(t+1)],[`index0`,new P(t)],[`revindex`,new P(a.length-t)],[`revindex0`,new P(a.length-t-1)],[`first`,new L(t===0)],[`last`,new L(t===a.length-1)],[`length`,new P(a.length)],[`previtem`,t>0?a[t-1]:new W],[`nextitem`,t<a.length-1?a[t+1]:new W]]);n.setVariable(`loop`,new z(r)),o[t](n);try{let t=this.evaluateBlock(e.body,n);s+=t.value}catch(e){if(e instanceof Ye)continue;if(e instanceof Je)break;throw e}c=!1}if(c){let t=this.evaluateBlock(e.defaultBlock,n);s+=t.value}return new I(s)}evaluateMacro(e,t){return t.setVariable(e.name.value,new H((t,n)=>{let r=new G(n);t=t.slice();let i;t.at(-1)?.type===`KeywordArgumentsValue`&&(i=t.pop());for(let n=0;n<e.args.length;++n){let a=e.args[n],o=t[n];if(a.type===`Identifier`){let e=a;if(!o)throw Error(`Missing positional argument: ${e.value}`);r.setVariable(e.value,o)}else if(a.type===`KeywordArgumentExpression`){let e=a,t=o??i?.value.get(e.key.value)??this.evaluate(e.value,r);r.setVariable(e.key.value,t)}else throw Error(`Unknown argument type: ${a.type}`)}return this.evaluateBlock(e.body,r)})),new U}evaluateCallStatement(e,t){let n=new H((t,n)=>{let r=new G(n);if(e.callerArgs)for(let n=0;n<e.callerArgs.length;++n){let i=e.callerArgs[n];if(i.type!==`Identifier`)throw Error(`Caller parameter must be an identifier, got ${i.type}`);r.setVariable(i.value,t[n]??new W)}return this.evaluateBlock(e.body,r)}),[r,i]=this.evaluateArguments(e.call.args,t);r.push(new B(i));let a=this.evaluate(e.call.callee,t);if(a.type!==`FunctionValue`)throw Error(`Cannot call something that is not a function: got ${a.type}`);let o=new G(t);return o.setVariable(`caller`,n),a.value(r,o)}evaluateFilterStatement(e,t){let n=this.evaluateBlock(e.body,t);return this.applyFilter(n,e.filter,t)}evaluate(e,t){if(!e)return new W;switch(e.type){case`Program`:return this.evalProgram(e,t);case`Set`:return this.evaluateSet(e,t);case`If`:return this.evaluateIf(e,t);case`For`:return this.evaluateFor(e,t);case`Macro`:return this.evaluateMacro(e,t);case`CallStatement`:return this.evaluateCallStatement(e,t);case`Break`:throw new Je;case`Continue`:throw new Ye;case`IntegerLiteral`:return new P(e.value);case`FloatLiteral`:return new F(e.value);case`StringLiteral`:return new I(e.value);case`ArrayLiteral`:return new V(e.value.map(e=>this.evaluate(e,t)));case`TupleLiteral`:return new $e(e.value.map(e=>this.evaluate(e,t)));case`ObjectLiteral`:{let n=new Map;for(let[r,i]of e.value){let e=this.evaluate(r,t);if(!(e instanceof I))throw Error(`Object keys must be strings: got ${e.type}`);n.set(e.value,this.evaluate(i,t))}return new z(n)}case`Identifier`:return this.evaluateIdentifier(e,t);case`CallExpression`:return this.evaluateCallExpression(e,t);case`MemberExpression`:return this.evaluateMemberExpression(e,t);case`UnaryExpression`:return this.evaluateUnaryExpression(e,t);case`BinaryExpression`:return this.evaluateBinaryExpression(e,t);case`FilterExpression`:return this.evaluateFilterExpression(e,t);case`FilterStatement`:return this.evaluateFilterStatement(e,t);case`TestExpression`:return this.evaluateTestExpression(e,t);case`SelectExpression`:return this.evaluateSelectExpression(e,t);case`Ternary`:return this.evaluateTernaryExpression(e,t);case`Comment`:return new U;default:throw SyntaxError(`Unknown node type: ${e.type}`)}}};function K(e){switch(typeof e){case`number`:return Number.isInteger(e)?new P(e):new F(e);case`string`:return new I(e);case`boolean`:return new L(e);case`undefined`:return new W;case`object`:return e===null?new U:Array.isArray(e)?new V(e.map(K)):new z(new Map(Object.entries(e).map(([e,t])=>[e,K(t)])));case`function`:return new H((t,n)=>K(e(...t.map(e=>e.value))??null));default:throw Error(`Cannot convert to runtime value: ${e}`)}}var q=`
|
|
11
|
+
`,at=`{%- `,ot=` -%}`;function st(e){switch(e.operator.type){case`MultiplicativeBinaryOperator`:return 4;case`AdditiveBinaryOperator`:return 3;case`ComparisonBinaryOperator`:return 2;case`Identifier`:return e.operator.value===`and`?1:e.operator.value===`in`||e.operator.value===`not in`?2:0}return 0}function ct(e,t=` `){let n=typeof t==`number`?` `.repeat(t):t;return Y(e.body,0,n).replace(/\n$/,``)}function J(...e){return at+e.join(` `)+ot}function Y(e,t,n){return e.map(e=>lt(e,t,n)).join(q)}function lt(e,t,n){let r=n.repeat(t);switch(e.type){case`Program`:return Y(e.body,t,n);case`If`:return ut(e,t,n);case`For`:return dt(e,t,n);case`Set`:return ft(e,t,n);case`Macro`:return pt(e,t,n);case`Break`:return r+J(`break`);case`Continue`:return r+J(`continue`);case`CallStatement`:return mt(e,t,n);case`FilterStatement`:return ht(e,t,n);case`Comment`:return r+`{# `+e.value+` #}`;default:return r+`{{- `+X(e)+` -}}`}}function ut(e,t,n){let r=n.repeat(t),i=[],a=e;for(;a&&(i.push({test:a.test,body:a.body}),a.alternate.length===1&&a.alternate[0].type===`If`);)a=a.alternate[0];let o=r+J(`if`,X(i[0].test))+q+Y(i[0].body,t+1,n);for(let e=1;e<i.length;++e)o+=q+r+J(`elif`,X(i[e].test))+q+Y(i[e].body,t+1,n);return a&&a.alternate.length>0&&(o+=q+r+J(`else`)+q+Y(a.alternate,t+1,n)),o+=q+r+J(`endif`),o}function dt(e,t,n){let r=n.repeat(t),i=``;if(e.iterable.type===`SelectExpression`){let t=e.iterable;i=`${X(t.lhs)} if ${X(t.test)}`}else i=X(e.iterable);let a=r+J(`for`,X(e.loopvar),`in`,i)+q+Y(e.body,t+1,n);return e.defaultBlock.length>0&&(a+=q+r+J(`else`)+q+Y(e.defaultBlock,t+1,n)),a+=q+r+J(`endfor`),a}function ft(e,t,n){let r=n.repeat(t),i=X(e.assignee),a=e.value?X(e.value):``,o=r+J(`set`,`${i}${e.value?` = `+a:``}`);return e.body.length===0?o:o+q+Y(e.body,t+1,n)+q+r+J(`endset`)}function pt(e,t,n){let r=n.repeat(t),i=e.args.map(X).join(`, `);return r+J(`macro`,`${e.name.value}(${i})`)+q+Y(e.body,t+1,n)+q+r+J(`endmacro`)}function mt(e,t,n){let r=n.repeat(t),i=e.callerArgs&&e.callerArgs.length>0?`(${e.callerArgs.map(X).join(`, `)})`:``,a=X(e.call),o=r+J(`call${i}`,a)+q;return o+=Y(e.body,t+1,n)+q,o+=r+J(`endcall`),o}function ht(e,t,n){let r=n.repeat(t),i=r+J(`filter`,e.filter.type===`Identifier`?e.filter.value:X(e.filter))+q;return i+=Y(e.body,t+1,n)+q,i+=r+J(`endfilter`),i}function X(e,t=-1){switch(e.type){case`SpreadExpression`:return`*${X(e.argument)}`;case`Identifier`:return e.value;case`IntegerLiteral`:return`${e.value}`;case`FloatLiteral`:return`${e.value}`;case`StringLiteral`:return JSON.stringify(e.value);case`BinaryExpression`:{let n=e,r=st(n),i=X(n.left,r),a=X(n.right,r+1),o=`${i} ${n.operator.value} ${a}`;return r<t?`(${o})`:o}case`UnaryExpression`:{let t=e;return t.operator.value+(t.operator.value===`not`?` `:``)+X(t.argument,1/0)}case`CallExpression`:{let t=e,n=t.args.map(X).join(`, `);return`${X(t.callee)}(${n})`}case`MemberExpression`:{let t=e,n=X(t.object);[`Identifier`,`MemberExpression`,`CallExpression`,`StringLiteral`,`IntegerLiteral`,`FloatLiteral`,`ArrayLiteral`,`TupleLiteral`,`ObjectLiteral`].includes(t.object.type)||(n=`(${n})`);let r=X(t.property);return!t.computed&&t.property.type!==`Identifier`&&(r=`(${r})`),t.computed?`${n}[${r}]`:`${n}.${r}`}case`FilterExpression`:{let t=e,n=X(t.operand,1/0);return t.filter.type===`CallExpression`?`${n} | ${X(t.filter)}`:`${n} | ${t.filter.value}`}case`SelectExpression`:{let t=e;return`${X(t.lhs)} if ${X(t.test)}`}case`TestExpression`:{let t=e;return`${X(t.operand)} is${t.negate?` not`:``} ${t.test.value}`}case`ArrayLiteral`:case`TupleLiteral`:{let t=e.value.map(X),n=e.type===`ArrayLiteral`?`[]`:`()`;return`${n[0]}${t.join(`, `)}${n[1]}`}case`ObjectLiteral`:return`{${Array.from(e.value.entries()).map(([e,t])=>`${X(e)}: ${X(t)}`).join(`, `)}}`;case`SliceExpression`:{let t=e;return`${t.start?X(t.start):``}:${t.stop?X(t.stop):``}${t.step?`:${X(t.step)}`:``}`}case`KeywordArgumentExpression`:{let t=e;return`${t.key.value}=${X(t.value)}`}case`Ternary`:{let n=e,r=`${X(n.trueExpr)} if ${X(n.condition,0)} else ${X(n.falseExpr)}`;return t>-1?`(${r})`:r}default:throw Error(`Unknown expression type: ${e.type}`)}}var gt=class{parsed;constructor(e){let t=pe(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Be(t)}render(e){let t=new G;if(tt(t),e)for(let[n,r]of Object.entries(e))t.set(n,r);return new it(t).run(this.parsed).value}format(e){return ct(this.parsed,e?.indent||` `)}};const _t=new Map,vt=new Map;function yt(e){return typeof e==`string`?e:e?Array.isArray(e)?e.map(e=>{if(!e)return``;if(typeof e==`string`)return e;if(e.type===`text`)return e.text||e.value||``;if(e.type===`tool_use`)return`[TOOL_CALL ${e.name}] ${JSON.stringify(e.input||{})}`;if(e.type===`tool_result`){let t=typeof e.content==`string`?e.content:JSON.stringify(e.content||``);return`[TOOL_RESULT ${e.tool_use_id||``}] ${t}`}return e.type===`attachment`?`[ATTACHMENT ${e.mediaType||`file`}] ${e.fileName||`attachment`}`:``}).filter(Boolean).join(`
|
|
12
|
+
`):typeof e==`object`?JSON.stringify(e):String(e):``}async function bt(t,n){let r=String(t||``).trim();if(!r)return null;if(_t.has(r))return _t.get(r);let i=n||(typeof globalThis.fetch==`function`?globalThis.fetch.bind(globalThis):void 0);if(!i)return null;let a=n||C(i),o=`https://huggingface.co/${encodeURI(r)}/resolve/main/tokenizer_config.json`;try{let t=await a(o);if(t.ok){let n=await t.json();if(n&&typeof n==`object`){if(!n.chat_template)try{let e=await a(`https://huggingface.co/${encodeURI(r)}/resolve/main/chat_template.jinja`);if(e.ok){let t=await e.text();t&&t.trim()&&(n.chat_template=t.trim())}}catch{}if(typeof n.model_max_length==`number`&&Number.isFinite(n.model_max_length)&&n.model_max_length>0&&n.model_max_length<=2097152){let t=e.getModelInfo(r);e.registerModelInfo(r,{contextWindow:n.model_max_length,maxOutput:t?.maxOutput??null,...t||{}})}return _t.set(r,n),n}}}catch{}return null}function xt(e){if(!(!e||!Array.isArray(e)||e.length===0))return e.map(e=>e.type===`function`&&e.function?e:{type:`function`,function:{name:e.name,description:e.description||``,parameters:e.input_schema||e.parameters||{type:`object`,properties:{}}}})}function St(e,t){let n=String(t||``).trim(),r=[];for(let t of e){if(!t)continue;let e=String(t.role||`user`).toLowerCase(),i=yt(t.content);e===`system`?n=n?`${n}\n\n${i}`:i:e===`tool`?r.push({role:`tool`,content:i}):e===`assistant`||e===`model`?r.push({role:`assistant`,content:i,...t.tool_calls?{tool_calls:t.tool_calls}:{}}):r.push({role:`user`,content:i})}let i=[];for(let e of r)if(i.length>0&&i[i.length-1].role===e.role&&e.role!==`tool`){let t=i[i.length-1];t.content=t.content?`${t.content}\n\n${e.content}`:e.content,e.tool_calls&&(t.tool_calls=[...t.tool_calls||[],...e.tool_calls])}else i.push({...e});i.length>0&&i[0].role===`assistant`&&i.unshift({role:`user`,content:`Hello`}),i.length===0&&!n&&i.push({role:`user`,content:`Hello`});let a=[];return n&&a.push({role:`system`,content:n}),a.push(...i),a}async function Ct(e){let{modelName:t=``,messages:n,systemPrompt:r,tools:i,documents:a,addGenerationPrompt:o=!0,customFetch:s}=e,c=null;typeof e.template==`string`?c=e.template:e.template&&typeof e.template==`object`&&(i&&i.length>0&&`tool_use`in e.template?c=e.template.tool_use:`default`in e.template&&(c=e.template.default));let l=e.bosToken,u=e.eosToken;if(!c&&t){let e=await bt(t,s);e&&(typeof e.chat_template==`string`?c=e.chat_template:e.chat_template&&typeof e.chat_template==`object`&&(i&&i.length>0&&`tool_use`in e.chat_template?c=e.chat_template.tool_use:`default`in e.chat_template&&(c=e.chat_template.default)),!l&&e.bos_token&&(l=typeof e.bos_token==`string`?e.bos_token:e.bos_token.content),!u&&e.eos_token&&(u=typeof e.eos_token==`string`?e.eos_token:e.eos_token.content))}c||=`{%- for message in messages -%}
|
|
13
|
+
{{- '<|im_start|>' + message.role + '
|
|
14
|
+
' + message.content + '<|im_end|>
|
|
15
|
+
' -}}
|
|
16
|
+
{%- endfor -%}
|
|
17
|
+
{%- if add_generation_prompt -%}
|
|
18
|
+
{{- '<|im_start|>assistant
|
|
19
|
+
' -}}
|
|
20
|
+
{%- endif -%}`;let d=St(n,r),f=xt(i),p=vt.get(c);return p||(p=new gt(c),vt.set(c,p)),p.render({messages:d,tools:f,documents:a||null,add_generation_prompt:o,bos_token:l||``,eos_token:u||``,pad_token:e.padToken||``,unk_token:e.unkToken||``})}function wt(){let e=globalThis;return e.Summarizer||e.ai?.summarizer}function Tt(){let e=globalThis;return e.Writer||e.ai?.writer}function Et(){let e=globalThis;return e.Rewriter||e.ai?.rewriter}function Dt(){let e=globalThis;return e.LanguageDetector||e.ai?.languageDetector||e.translation?.languageDetector}function Ot(){let e=globalThis;return e.Translator||e.ai?.translator||e.translation?.translator}function kt(){let e=globalThis;return e.Proofreader||e.ai?.proofreader}function At(){let e=globalThis;return e.SemanticEmbedder||e.TextEmbedder||e.ai?.semanticEmbedder||e.ai?.textEmbedder}async function jt(){if(typeof navigator>`u`||!(`gpu`in navigator))return!1;try{let e=await navigator.gpu.requestAdapter({powerPreference:`high-performance`});if(!e||e.isFallbackAdapter===!0||e.features&&!e.features.has(`shader-f16`))return!1;let t=e.info||(typeof e.requestAdapterInfo==`function`?await e.requestAdapterInfo():null);if(t){let e=(t.vendor||``).toLowerCase(),n=(t.architecture||``).toLowerCase(),r=(t.description||``).toLowerCase(),i=(t.device||``).toLowerCase(),a=(t.adapterType||t.deviceType||t.type||``).toLowerCase();if(a===`cpu`||a===`software`||n===`swiftshader`||n===`llvmpipe`||n===`softpipe`||n===`lavapipe`||n===`cpu`||e.includes(`swiftshader`)||r.includes(`llvmpipe`)||r.includes(`softpipe`)||r.includes(`lavapipe`)||r.includes(`software`)||r.includes(`basic render`)||i.includes(`llvmpipe`)||i.includes(`softpipe`)||i.includes(`lavapipe`)||i.includes(`swiftshader`)||i.includes(`basic render`))return!1}let n=await e.requestDevice();return n?(typeof n.destroy==`function`&&n.destroy(),!0):!1}catch{return!1}}function Mt(e){let t=e.toLowerCase();return t.includes(`webgpu`)||t.includes(`webgpuinit`)||t.includes(`no available backend`)||t.includes(`webnn`)||t.includes(`error_code: 9`)||t.includes(`could not find an implementation`)||t.includes(`gatherblockquantized`)||t.includes(`ort_not_implemented`)||t.includes(`error_code: 6`)||t.includes(`bad_alloc`)||t.includes(`out of memory`)||t.includes(`allocation failed`)}let Nt=n;async function Pt(){try{let e=await i();if(e){let t=await a(e,r.PROMPT_API_FALLBACK_MODEL);if(t&&typeof t==`string`)return t}}catch{}return Nt}async function Z(e,t){try{return await e.create(t)}catch(n){let r=String(n?.message||n),i=globalThis,a=i.TRANSFORMERS_CONFIG?.device??``;if((a===`webgpu`||a.startsWith(`webnn`))&&Mt(r)){let o=await Pt();return console.warn(`Built-in AI Polyfill: ${a} backend failed (${r.slice(0,120)}). Retrying with WASM/q4 CPU fallback (${o})...`,n),i.TRANSFORMERS_CONFIG||={apiKey:`dummy`},i.TRANSFORMERS_CONFIG.device=`wasm`,i.TRANSFORMERS_CONFIG.dtype=`q4`,i.TRANSFORMERS_CONFIG.modelName=o,i.TRANSFORMERS_CONFIG.env||(i.TRANSFORMERS_CONFIG.env={useBrowserCache:!1,useWasmCache:!0,fetch:C()}),await e.create(t)}throw n}}async function Q(){let e=globalThis,t=[];`document`in e||(e.document={defaultView:e,documentElement:null,querySelector:()=>null,querySelectorAll:()=>[],createElement:e=>typeof OffscreenCanvas<`u`&&e===`canvas`?new OffscreenCanvas(300,150):{}}),`MutationObserver`in e||(e.MutationObserver=class{observe(){}disconnect(){}takeRecords(){return[]}});let n;if(!(`LanguageModel`in e)&&!e.ai?.languageModel){if(n=await Pt(),e.TRANSFORMERS_CONFIG)e.TRANSFORMERS_CONFIG.env||(e.TRANSFORMERS_CONFIG.env={useBrowserCache:!1,useWasmCache:!0,fetch:C()});else{let t=`wasm`,o=`q4f16`,s=null,c=null;try{let e=await i();e&&(s=await a(e,r.PROMPT_API_BACKEND)||await a(e,r.TRANSFORMERS_JS_BACKEND)||null,c=await a(e,r.PROMPT_API_DTYPE_STRATEGY)||await a(e,r.TRANSFORMERS_JS_DTYPE_STRATEGY)||null)}catch{}s===`wasm`?t=`wasm`:s===`webgpu`?t=`webgpu`:s&&s.startsWith(`webnn`)?t=`webnn`:typeof navigator<`u`&&(`ml`in navigator?t=`webnn`:`gpu`in navigator&&await jt()&&(t=`webgpu`)),o=c&&c!==`auto`?c:`q4f16`,e.TRANSFORMERS_CONFIG={apiKey:`dummy`,device:t,dtype:o,...n?{modelName:n}:{},env:{useBrowserCache:!1,useWasmCache:!0,fetch:C()}}}t.push(import(`./chunk-Bf_B14Ld.js`).then(t=>{t?.LanguageModel&&!e.LanguageModel&&(e.LanguageModel=t.LanguageModel)}).catch(()=>{}))}e.TRANSFORMERS_CONFIG&&(n||=await Pt(),n&&(e.TRANSFORMERS_CONFIG.modelName=n)),wt()||t.push(import(`./chunk-kjHBRdMr.js`).then(t=>{t?.Summarizer&&!e.Summarizer&&(e.Summarizer=t.Summarizer)}).catch(()=>{})),Tt()||t.push(import(`./chunk-B7CJ25uq.js`).then(t=>{t?.Writer&&!e.Writer&&(e.Writer=t.Writer)}).catch(()=>{})),Et()||t.push(import(`./chunk-BHb9fxp0.js`).then(t=>{t?.Rewriter&&!e.Rewriter&&(e.Rewriter=t.Rewriter)}).catch(()=>{})),Dt()||t.push(import(`./chunk-Pbp3Q16z.js`).then(t=>{t?.LanguageDetector&&!e.LanguageDetector&&(e.LanguageDetector=t.LanguageDetector)}).catch(()=>{})),Ot()||t.push(import(`./chunk-C1wx9MzX.js`).then(t=>{t?.Translator&&!e.Translator&&(e.Translator=t.Translator)}).catch(()=>{})),t.length>0&&await Promise.all(t)}function $(e,t){if(t)return n=>{!n||typeof n.addEventListener!=`function`||(t({status:`running`,progress:0,message:`Downloading ${e} model... 0%`}),n.addEventListener(`downloadprogress`,n=>{let r=Number(n?.loaded),i=Number(n?.total),a=null,o=``;Number.isFinite(r)&&Number.isFinite(i)&&i>0?(a=Math.max(0,Math.min(1,r/i)),o=` ${Math.round(a*100)}%`):Number.isFinite(r)&&r>=0&&r<=1?(a=Math.max(0,Math.min(1,r)),o=` ${Math.round(a*100)}%`):Number.isFinite(r)&&r>1&&(o=` (${(r/1024/1024).toFixed(1)} MB downloaded)`),t({status:`running`,progress:a,message:`Downloading ${e} model...${o}`})}))}}async function Ft(e,t){await Q();let n=wt();if(!n)throw Error(`Summarizer API is not supported or polyfilled`);let r=$(`Summarizer`,t?.onProgress),i=await Z(n,{...t||{},...r?{monitor:r}:{}});try{return await i.summarize(e,t?.context?{context:t.context}:void 0)}finally{typeof i.destroy==`function`&&i.destroy()}}async function It(e,t){await Q();let n=Tt();if(!n)throw Error(`Writer API is not supported or polyfilled`);let r=$(`Writer`,t?.onProgress),i=await Z(n,{...t||{},...r?{monitor:r}:{}});try{return await i.write(e,t?.context?{context:t.context}:void 0)}finally{typeof i.destroy==`function`&&i.destroy()}}async function Lt(e,t){await Q();let n=Et();if(!n)throw Error(`Rewriter API is not supported or polyfilled`);let r=$(`Rewriter`,t?.onProgress),i=await Z(n,{...t||{},...r?{monitor:r}:{}});try{return await i.rewrite(e,t?.context?{context:t.context}:void 0)}finally{typeof i.destroy==`function`&&i.destroy()}}async function Rt(e,t){await Q();let n=Dt();if(!n)throw Error(`Language Detector API is not supported or polyfilled`);let r=$(`LanguageDetector`,t?.onProgress),i=await Z(n,{...t||{},...r?{monitor:r}:{}});try{return await i.detect(e)}finally{typeof i.destroy==`function`&&i.destroy()}}async function zt(e,t){await Q();let n=Ot();if(!n)throw Error(`Translator API is not supported or polyfilled`);let r=$(`Translator`,t?.onProgress),i=await Z(n,{...t,...r?{monitor:r}:{}});try{return await i.translate(e)}finally{typeof i.destroy==`function`&&i.destroy()}}async function Bt(e,t){await Q();let n=kt();if(n){let r=$(`Proofreader`,t?.onProgress),i=await Z(n,{...t||{},...r?{monitor:r}:{}});try{if(typeof i.proofread==`function`)return await i.proofread(e,t?.context?{context:t.context}:void 0)}finally{typeof i.destroy==`function`&&i.destroy()}}return await Lt(e,{context:t?.context?`Proofread and correct grammar, spelling, and style errors. ${t.context}`:`Proofread and correct grammar, spelling, and style errors.`,onProgress:t?.onProgress})}async function Vt(e,t){await Q();let n=At();if(!n)throw Error(`Semantic Embedder API is not supported in this browser environment. Enable #semantic-embedder-api in chrome://flags or Edge Canary.`);let r=$(`SemanticEmbedder`,t?.onProgress),i=await Z(n,{...t?.taskType?{taskType:t.taskType}:{},...r?{monitor:r}:{}});try{return await i.embed(e)}finally{typeof i.destroy==`function`&&i.destroy()}}function Ht(e){return`[Attachment: ${e.fileName} (${e.mimeType}) is available in chat history${e.path?` at ${e.path}`:``}]`}function Ut(e){return e.map(e=>e.type===`text`?e.text:e.type===`image`?`[Image: ${e.media_type}, ${Math.ceil(e.data.length*3/4)} bytes base64-encoded]`:``).filter(Boolean).join(`
|
|
21
|
+
`)}function Wt(e,t){if(!Kt(t))return Ut(e);let n=[];for(let t of e)t.type===`text`?n.push({type:`text`,text:t.text}):t.type===`image`&&n.push({type:`image_url`,image_url:{url:`data:${t.media_type};base64,${t.data}`}});return n}function Gt(e,t){if(!Kt(t))return Ut(e);let n=[];for(let t of e)t.type===`text`?n.push({type:`text`,text:t.text}):t.type===`image`&&n.push({type:`image`,source:{type:`base64`,media_type:t.media_type,data:t.data}});return n}function Kt(e){let t=c(e);return t.images||t.routerByFeatures}function qt(e){let t=c(e);return t.audio||t.routerByFeatures}function Jt(e){let t=c(e);return t.documents||t.routerByFeatures}function Yt(e){let t=e.toLowerCase();return t.includes(`wav`)?`wav`:t.includes(`flac`)?`flac`:t.includes(`ogg`)?`ogg`:t.includes(`aac`)?`aac`:t.includes(`webm`)?`webm`:t.includes(`mp4`)?`mp4`:`mp3`}function Xt(e,t){let n=[],r=Kt(t);for(let i of e){if(i?.type===`text`){n.push({type:`text`,text:i.text||``});continue}i?.type===`attachment`&&(i.mediaType===`image`&&typeof i.data==`string`&&i.data&&r?n.push({type:`image_url`,image_url:{url:`data:${i.mimeType};base64,${i.data}`}}):i.mediaType===`audio`&&typeof i.data==`string`&&i.data&&qt(t)?n.push({type:`input_audio`,input_audio:{data:i.data,format:Yt(i.mimeType)}}):n.push({type:`text`,text:Ht(i)}))}return n}function Zt(e){return typeof e!=`string`||e.trim().length===0?``:e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``)}function Qt(e){let t=Zt(e);return t?t.includes(`claude-1`)||t.includes(`claude-2`)||t.includes(`claude-v1`)||t.includes(`claude-v2`)||t.includes(`claude-instant`):!1}function $t(t){if(typeof t!=`string`||t.trim().length===0)return!1;let n=e.getModelInfo(t);if(typeof n?.supportsPromptCaching==`boolean`)return n.supportsPromptCaching;let r=Zt(t);return!Qt(r)&&!!(r.includes(`claude-3-5-sonnet`)||r.includes(`claude-3-5-haiku`)||r.includes(`claude-3-7-sonnet`)||r.includes(`claude-3-haiku`)||r.includes(`claude-3-opus`)||/claude-(?:sonnet|opus|haiku)-[4-9]/.test(r)||/claude-[4-9]-(?:sonnet|opus|haiku)/.test(r))}function en(e,t){let n=[],r=Kt(t);for(let i of e){if(i?.type===`text`){let e=typeof i.text==`string`?i.text:``;if(e.trim().length===0)continue;n.push({type:`text`,text:e,...i.cache_control&&{cache_control:i.cache_control}});continue}if(i?.type===`tool_use`){n.push(i);continue}if(i?.type===`thinking`){n.push({type:`thinking`,thinking:i.thinking||``,...typeof i.signature==`string`&&{signature:i.signature}});continue}if(i?.type===`redacted_thinking`){n.push({type:`redacted_thinking`,data:i.data||``});continue}if(i?.type===`tool_result`){Array.isArray(i.content)?n.push({...i,content:Gt(i.content,t)}):n.push(i);continue}i?.type===`attachment`&&(i.mediaType===`image`&&typeof i.data==`string`&&i.data&&r?n.push({type:`image`,source:{type:`base64`,media_type:i.mimeType,data:i.data},...i.cache_control&&{cache_control:i.cache_control}}):i.mediaType===`document`&&typeof i.data==`string`&&i.data&&Jt(t)?n.push({type:`document`,source:{type:`base64`,media_type:`application/pdf`,data:i.data},...i.cache_control&&{cache_control:i.cache_control}}):n.push({type:`text`,text:Ht(i),...i.cache_control&&{cache_control:i.cache_control}}))}return n}function tn(e,t){let n={"Content-Type":`application/json`,...e.headers};return e.apiKeyHeaderFormat?n[e.apiKeyHeader]=e.apiKeyHeaderFormat.replace(`{key}`,t):n[e.apiKeyHeader]=t,n}var nn=class{provider;constructor(e){this.provider=e}formatRequest(e,t,n){throw Error(`Not implemented`)}parseResponse(e){throw Error(`Not implemented`)}},rn=class extends nn{formatRequest(t,n,r){let{model:i,maxTokens:a,system:o,contextCompression:s,reasoning:c}=r,l=[];o&&l.push({role:`system`,content:o});for(let e of t){if(e.role===`system`){if(o)continue;l.push(e);continue}if(e.role===`assistant`&&Array.isArray(e.content)){let t=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
22
|
+
`),n=e.content.filter(e=>e.type===`tool_use`),r={role:`assistant`,content:t||null};n.length>0&&(r.tool_calls=n.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.input)}}))),l.push(r);continue}if(e.role===`user`&&Array.isArray(e.content)){let t=e.content.filter(e=>e.type===`tool_result`),n=Xt(e.content,i),r=n.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
23
|
+
`);if(t.length===0){n.length>0&&l.push({role:`user`,content:n});continue}r&&l.push({role:`user`,content:r});for(let e of t){let t;t=typeof e.content==`string`?e.content:Array.isArray(e.content)?Wt(e.content,i):JSON.stringify(e.content),l.push({role:`tool`,tool_call_id:e.tool_use_id,content:t})}continue}l.push(e)}let u=e.getModelInfo(i),d=(this.provider.id!==`ollama`||u?.supportsTools!==!1)&&n?.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.input_schema}}))||[],f={model:i,max_tokens:a,messages:l,...d.length>0&&{tools:d}};return this.provider.id===`ollama`&&u?.contextWindow&&u.contextWindow>0&&(f.options={...f.options||{},num_ctx:u.contextWindow}),this.provider.id===`openrouter`&&s&&(f.plugins=[{id:`context-compression`,enabled:!0}]),(this.provider.reasoningParam===`reasoning`||this.provider.reasoningParam===`thinkingConfig`)&&c&&(f.reasoning=c),f}parseResponse(e){let t=e.choices?.[0];if(!t)throw Error(`No choices in OpenAI response`);let{message:n,finish_reason:r}=t,i=[],a=`end_turn`;if(typeof n.content==`string`&&n.content){let e=f(n.content,`openai`);e&&i.push({type:`text`,text:e})}if(n.tool_calls&&Array.isArray(n.tool_calls)){a=`tool_use`;for(let e of n.tool_calls){let t;try{t=typeof e.function.arguments==`string`?JSON.parse(e.function.arguments):e.function.arguments}catch(e){console.error(`Failed to parse tool arguments:`,e),t={}}i.push({type:`tool_use`,id:e.id||`call_${Date.now()}_${Math.random()}`,name:e.function.name,input:t})}}return r===`tool_calls`&&(a=`tool_use`),{content:i,stop_reason:a,usage:{input_tokens:e.usage?.prompt_tokens||0,output_tokens:e.usage?.completion_tokens||0}}}},an=class extends nn{formatRequest(t,n,r){let{model:i,maxTokens:a,system:o,reasoning:s}=r,c=e.getModelInfo(i),l=!(Qt(i)||c?.supportsPromptCaching===!1)&&(r.promptCaching===!0||r.promptCaching!==!1&&$t(i)),u=t.filter(e=>e.role!==`system`).map(e=>Array.isArray(e.content)?{...e,content:en(e.content,i)}:{...e}),d=n?.map(e=>({name:e.name,description:e.description,input_schema:e.input_schema}))||[];if(l&&d.length>0){let e=d[d.length-1];e.cache_control={type:`ephemeral`}}let f=l&&typeof o==`string`&&o.trim().length>0?[{type:`text`,text:o,cache_control:{type:`ephemeral`}}]:o;if(l&&u.length>1)for(let e=u.length-1;e>=0;e--){let t=u[e];if(t.role===`user`){if(typeof t.content==`string`)u[e]={...t,content:[{type:`text`,text:t.content,cache_control:{type:`ephemeral`}}]};else if(Array.isArray(t.content)&&t.content.length>0){let n=[...t.content],r=n.length-1,i=n[r];i&&typeof i==`object`&&!i.cache_control&&(n[r]={...i,cache_control:{type:`ephemeral`}},u[e]={...t,content:n})}break}}let p={model:i,max_tokens:a,...o&&{system:f},messages:u,...d.length>0&&{tools:d}};if(this.provider.reasoningParam===`thinking`&&s?.max_tokens&&Number.isFinite(s.max_tokens))p.thinking={type:`enabled`,budget_tokens:Math.max(1024,Math.floor(s.max_tokens))};else if(this.provider.reasoningParam===`thinking`&&typeof s?.effort==`string`){let e=mn(s.effort);e>0&&(p.thinking={type:`enabled`,budget_tokens:Math.max(1024,Math.floor(a*e))})}return p}parseResponse(e){return{content:Array.isArray(e.content)?e.content.map(e=>e?.type!==`text`||typeof e?.text!=`string`?e:{...e,text:f(e.text,`anthropic`)}).filter(e=>e?.type!==`text`||typeof e.text==`string`&&e.text.length>0):[],stop_reason:e.stop_reason||`end_turn`,usage:{input_tokens:e.usage?.input_tokens||0,output_tokens:e.usage?.output_tokens||0,cache_read_input_tokens:e.usage?.cache_read_input_tokens||0,cache_creation_input_tokens:e.usage?.cache_creation_input_tokens||0}}}};function on(e,t){return e.map(e=>{if(e.type===`text`)return{text:e.text};if(e.type===`image_url`){let t=e.image_url.url;if(t.startsWith(`data:`)){let e=t.match(/^data:([^;]+);base64,(.+)$/);if(e)return{inlineData:{mimeType:e[1],data:e[2]}}}}if(e.type===`document_url`||e.type===`audio_url`||e.type===`video_url`){let t=e[e.type]?.url;if(t?.startsWith(`data:`)){let e=t.match(/^data:([^;]+);base64,(.+)$/);if(e)return{inlineData:{mimeType:e[1],data:e[2]}}}}if(e.type===`tool_use`)return{functionCall:{name:e.name,args:e.input||{}}};if(e.type===`tool_result`){let t;return t=typeof e.content==`string`?e.content:Array.isArray(e.content)?Ut(e.content):typeof e.output==`string`?e.output:JSON.stringify(e.output??e.content??``),{functionResponse:{name:e.name,response:{result:t}}}}return{text:``}}).filter(Boolean)}var sn=class extends nn{formatRequest(e,t,n){let{model:r,maxTokens:i,system:a}=n,o=e.filter(e=>e.role!==`system`).map(e=>({role:e.role===`assistant`?`model`:e.role===`tool`?`function`:`user`,parts:Array.isArray(e.content)?on(e.content,r):[{text:e.content||``}]})),s=t?.map(e=>({name:e.name,description:e.description,parameters:e.input_schema}))||[];return{contents:o,...a&&{system_instruction:{parts:[{text:a}]}},generationConfig:{maxOutputTokens:i},...s.length>0&&{tools:[{function_declarations:s}]}}}parseResponse(e){let t=e.candidates?.[0];if(!t)throw Error(`No candidates in Gemini response`);let n=[],r=`end_turn`;if(t.content?.parts)for(let e of t.content.parts){if(e.text){let t=f(e.text,`openai`);t&&n.push({type:`text`,text:t})}e.functionCall&&(r=`tool_use`,n.push({type:`tool_use`,id:`call_${Date.now()}_${Math.random()}`,name:e.functionCall.name,input:e.functionCall.args||{}}))}if(t.finishReason===`SAFETY`)throw Error(`Gemini response blocked by safety filters`);return{content:n,stop_reason:r,usage:{input_tokens:e.usageMetadata?.promptTokenCount||0,output_tokens:e.usageMetadata?.candidatesTokenCount||0}}}};function cn(e){return e.replace(/<\|channel>[\s\S]*?<channel\|>/g,``).replace(/^[ \t]+$/gm,``).replace(/\n{3,}/g,`
|
|
24
|
+
|
|
25
|
+
`).trim()}function ln(e){let t=/<\|tool_call>call:([a-zA-Z_][a-zA-Z0-9_]*)(\{[\s\S]*?\})?<tool_call\|>/g,n=[];return{toolBlocks:n,residualText:e.replace(t,(e,t,r)=>{let i={};if(r)try{let e=JSON.parse(r);e&&typeof e==`object`&&!Array.isArray(e)&&(i=e)}catch{}return n.push({type:`tool_use`,id:`mesh_llm_call_${Date.now()}_${Math.random().toString(36).slice(2)}`,name:t,input:i}),``}).replace(/^[ \t]+$/gm,``).replace(/\n{3,}/g,`
|
|
26
|
+
|
|
27
|
+
`).trim()}}function un(e){if(!e||!Array.isArray(e.content))return e;let t=[],n=!1;for(let r of e.content){if(r.type!==`text`){t.push(r);continue}let{toolBlocks:e,residualText:i}=ln(cn(r.text));i&&t.push({type:`text`,text:i}),e.length>0&&(n=!0,t.push(...e))}return{...e,content:t,stop_reason:n||e.stop_reason===`tool_use`?`tool_use`:e.stop_reason}}const dn={openai:rn,anthropic:an,google:sn,"mesh-llm":class extends rn{parseResponse(e){return un(super.parseResponse(e))}}};function fn(e){let t=dn[e.format];if(!t)throw Error(`Unsupported provider format: ${e.format}`);return new t(e)}function pn(e,t,n,r){return fn(e).formatRequest(t,n,r)}function mn(e){let t=e.toLowerCase();return t===`none`?0:t===`max`||t===`xhigh`?.95:t===`high`?.8:t===`medium`?.5:t===`low`?.2:t===`minimal`?.1:0}function hn(e,t){return fn(e).parseResponse(t)}function gn(t){let n=e.getModelInfo(t);if(n?.contextWindow)return n.contextWindow;let r=t.toLowerCase();return r.includes(`gpt-4.1`)?1047576:r.includes(`gpt-5`)?4e5:r.includes(`gpt-4o`)||r.includes(`gpt-4-turbo`)?128e3:r===`gpt-4`||r.startsWith(`gpt-4-`)?8192:r.includes(`gpt-3.5-turbo`)?16385:r.includes(`gpt-3.5`)?4096:r.includes(`o1`)||r.includes(`o3`)||r.includes(`o4`)?2e5:r.includes(`claude-opus-4`)||r.includes(`claude-sonnet-4`)?1e6:r.includes(`claude`)?2e5:r.includes(`gemini-nano`)?4096:r.includes(`gemini-1.5-pro`)?2097152:r.includes(`gemini-2.5`)||r.includes(`gemini-2.0`)||r.includes(`gemini-1.5`)?1048576:r.includes(`gemini-1.0`)||r.includes(`gemini-pro`)?32768:r.includes(`gemini`)?1048576:r.includes(`llama-3.1`)||r.includes(`llama-3-1`)?128e3:r.includes(`llama-3`)?8192:r.includes(`llama`)?4096:r.includes(`gemma-4-12b`)||r.includes(`gemma-4-26b`)||r.includes(`gemma-4-31b`)||r.includes(`gemma-4-e9b`)||r.includes(`gemma-4-e27b`)?256e3:r.includes(`gemma-4`)||r.includes(`gemma 4`)||r.includes(`gemma-3-4b`)||r.includes(`gemma-3-12b`)||r.includes(`gemma-3-27b`)?128e3:r.includes(`gemma-3`)||r.includes(`gemma 3`)?32e3:r.includes(`gemma-2`)||r.includes(`gemma-7b`)||r.includes(`gemma-2b`)||r.includes(`gemma`)?8192:r.includes(`mistral-large`)?128e3:r.includes(`mistral`)?32e3:r.includes(`amazon.titan`)?8192:r.includes(`amazon.nova-micro`)||r.includes(`nova-micro`)?128e3:r.includes(`amazon.nova`)||r.includes(`nova-pro`)||r.includes(`nova-lite`)?3e5:r.includes(`ai21`)?8192:r.includes(`cohere`)||r.includes(`phi-4-mini`)?128e3:r.includes(`phi-4`)?16384:r.includes(`phi-3.5`)||r.includes(`128k`)?128e3:r.includes(`phi-3`)?4096:r.includes(`qwen3.5`)?262144:r.includes(`qwen3-0.6b`)||r.includes(`qwen3-1.7b`)?40960:r.includes(`qwen3`)?128e3:r===`mesh`?242144:4096}function _n(e,t){if(e===`translate`)return`Translate the following text from ${t.sourceLanguage||`auto`} to ${t.targetLanguage}. Provide ONLY the raw translated text without commentary or quotation marks:\n\n${t.text}`;if(e===`summarize`)return`Summarize the following text (type: ${t.type||`tldr`}, format: ${t.format||`plain-text`}, length: ${t.length||`medium`}). Provide ONLY the summary:\n\n${t.text}`;if(e===`write`)return`Draft content for the following request (context: ${t.context||`none`}):\n\n${t.prompt}`;if(e===`rewrite`)return`Rewrite the following text (tone: ${t.tone||`standard`}, length: ${t.length||`as-is`}):\n\n${t.text}`;if(e===`proofread`)return`Proofread and correct grammar, spelling, and style in the following text. Provide ONLY the corrected text:\n\n${t.text}`;if(e===`detect-language`)return`Detect the language of the following text. Return ONLY a JSON array of objects with "detectedLanguage" (BCP 47 code) and "confidence" (0.0 - 1.0), e.g. [{"detectedLanguage":"en","confidence":0.99}]:\n\n${t.text}`;if(e===`semantic-embedder`)return`Provide a concise semantic description/representation for the following content:\n\n${JSON.stringify(t.text)}`;throw Error(`Unknown native AI task type: ${e}`)}async function vn(e){if(e.toolsBackendPref)return e.toolsBackendPref;if(e.db)try{let{getConfig:t}=await import(`./chunk-C-J89fsv.js`),n=await t(e.db,r.BUILTIN_AI_TOOLS_BACKEND);if(n)return n}catch{}return`active_provider`}async function yn(e,t,n){if(n.apiKey!==void 0)return n.apiKey;if(typeof process<`u`&&process.env){let e=process.env.SHADOW_CLAW_API_KEY;if(e)return e;switch(t){case`openrouter`:if(process.env.OPENROUTER_API_KEY)return process.env.OPENROUTER_API_KEY;break;case`huggingface`:if(process.env.HUGGINGFACE_API_KEY||process.env.HF_TOKEN)return process.env.HUGGINGFACE_API_KEY||process.env.HF_TOKEN||``;break;case`gemini_proxy`:if(process.env.GEMINI_API_KEY)return process.env.GEMINI_API_KEY;break}let n=`${t.toUpperCase()}_API_KEY`;if(process.env[n])return process.env[n]}if(n.db)try{let{getConfig:e}=await import(`./chunk-C-J89fsv.js`),r=await e(n.db,`api_key:${t}`)||await e(n.db,`apiKey`);if(r)return r}catch{}return``}async function bn(e){let{taskType:n,input:i,onProgress:a}=e;if(await vn(e)===`local`){if(n===`summarize`)return await Ft(i.text,{...i,onProgress:a});if(n===`write`)return await It(i.prompt,{...i,onProgress:a});if(n===`rewrite`)return await Lt(i.text,{...i,onProgress:a});if(n===`proofread`)return await Bt(i.text,{...i,onProgress:a});if(n===`detect-language`)return await Rt(i.text,{onProgress:a});if(n===`translate`)return await zt(i.text,{sourceLanguage:i.sourceLanguage||`auto`,targetLanguage:i.targetLanguage||`en`,...i,onProgress:a});if(n===`semantic-embedder`)return await Vt(i.text,{...i,onProgress:a});throw Error(`Unknown native AI task: ${n}`)}let s=o()?`openrouter`:`prompt_api`,c=e.providerId;if(!c&&e.db)try{let{getConfig:t}=await import(`./chunk-C-J89fsv.js`);c=await t(e.db,r.PROVIDER)||s}catch{}c||=typeof process<`u`&&(process.env.SHADOW_CLAW_PROVIDER||process.env.SHADOW_CLAW_DEFAULT_PROVIDER)||s;let l=_n(n,i);if(c===`prompt_api`){await Q();let e=globalThis,t=e.LanguageModel||e.ai?.languageModel;if(t&&typeof t.create==`function`){let e;try{e=await t.create()}catch(e){console.warn(`Prompt API session creation failed in active provider task:`,e)}if(e)try{let t=await e.prompt(l),r=String(t||``).trim();if(n===`detect-language`)try{let e=JSON.parse(r);return Array.isArray(e)?e:[e]}catch{return[{detectedLanguage:`en`,confidence:.8}]}return r}finally{typeof e.destroy==`function`&&e.destroy()}}}let u=t(c);if(!u||!u.baseUrl||u.baseUrl.startsWith(`builtin://`)||u.baseUrl.startsWith(`local://`)||u.format===`prompt_api`||u.format===`transformers_js`){if(n===`summarize`)return await Ft(i.text,i);if(n===`write`)return await It(i.prompt,i);if(n===`rewrite`)return await Lt(i.text,i);if(n===`proofread`)return await Bt(i.text,i);if(n===`detect-language`)return await Rt(i.text);if(n===`translate`)return await zt(i.text,{sourceLanguage:i.sourceLanguage||`auto`,targetLanguage:i.targetLanguage||`en`,...i});if(n===`semantic-embedder`)return await Vt(i.text,i);throw Error(`Provider ${c} not found and no local fallback available`)}let d=await yn(u,c,e);if(u.requiresApiKey!==!1&&!d)throw Error(`Provider "${u.name||c}" requires an API key for task "${n}". Please provide an API key or configure tools backend.`);let f=e.model||u.defaultModel||`default`,p={...tn(u,d),...e.headers||{}},m=pn(u,[{role:`user`,content:l}],[],{maxTokens:e.maxTokens||2048,model:f,system:`You are a specialized text task assistant. Fulfill the user request directly and accurately without conversational filler.`}),h=await fetch(u.baseUrl,{body:JSON.stringify(m),headers:p,method:`POST`});if(!h.ok){let e=await h.text();throw Error(`Active provider task API error ${h.status}: ${e}`)}let g=hn(u,await h.json()).content?.filter(e=>e.type===`text`)?.map(e=>e.text)?.join(``)?.trim()||``;if(n===`detect-language`)try{let e=JSON.parse(g);return Array.isArray(e)?e:[e]}catch{return[{detectedLanguage:`en`,confidence:.8}]}return g}export{m as C,x as S,s as T,It as _,gn as a,ae as b,Z as c,Q as d,Pt as f,zt as g,Ft as h,pn as i,Rt as l,Lt as m,bn as n,un as o,Bt as p,tn as r,hn as s,_n as t,Vt as u,St as v,f as w,ie as x,Ct as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
let e=!1;const t=new Set([`ask_user`,`attach_file_to_chat`,`clear_chat`,`create_room`,`invite_to_room`,`leave_room`,`list_components`,`list_room_members`,`open_file`,`render_component`,`send_file`,`send_notification`,`show_toast`,`spawn_subagent`]);function n(e){return!t.has(e)}function r(e){return e.filter(e=>!t.has(e.name))}function i(){return e}function a(t){e=t}export{a,n as i,r as n,i as r,t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
let e=!1;const t=new Set([`ask_user`,`attach_file_to_chat`,`clear_chat`,`create_room`,`invite_to_room`,`leave_room`,`list_components`,`list_room_members`,`open_file`,`render_component`,`send_file`,`send_notification`,`show_toast`,`spawn_subagent`]);function n(e){return!t.has(e)}function r(e){return e.filter(e=>!t.has(e.name))}function i(){return e}function a(t){e=t}export{a,n as i,r as n,i as r,t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./chunk-EohNY8vW.js";export{e as getAgentCore};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as e}from"./chunk-CUMlq7Jw2.js";export{e as orchestratorStore};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./chunk-uAI_Zi6n.js";import{existsSync as t}from"node:fs";import n from"node:path";import{pathToFileURL as r}from"node:url";import i from"node:process";const a=e(import.meta.url);let o=null;async function s(){if(o)return o;let e=i.env.NODE_ENV===`test`,s=n.join(a,`dist/headless-agent.js`);if(!e&&t(s))return o=await import(r(s).href),o;try{return o={...await import(`./chunk-
|
|
1
|
+
import{t as e}from"./chunk-uAI_Zi6n.js";import{existsSync as t}from"node:fs";import n from"node:path";import{pathToFileURL as r}from"node:url";import i from"node:process";const a=e(import.meta.url);let o=null;async function s(){if(o)return o;let e=i.env.NODE_ENV===`test`,s=n.join(a,`dist/headless-agent.js`);if(!e&&t(s))return o=await import(r(s).href),o;try{return o={...await import(`./chunk-MHBh2BgF2.js`)},o}catch{try{return o={...await import(`./chunk-MHBh2BgF2.js`)},o}catch(e){if(t(s))return o={...await import(r(s).href)},o;throw e}}}export{s as t};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as e,i as t}from"./chunk-BkKN8FNP.js";import{Buffer as n}from"buffer";import r from"isomorphic-git";globalThis.Buffer||(globalThis.Buffer=n);function i(e){try{let t=typeof location<`u`&&location.origin?location.origin:typeof globalThis<`u`&&globalThis.location?.origin?globalThis.location.origin:`http://127.0.0.1:8888`,n=new URL(e,t).hostname.toLowerCase();if(n===`localhost`||n===`127.0.0.1`||n===`::1`||n===`[::1]`)return`loopback`;if(/^(10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.)/.test(n)||!n.includes(`.`)||n.endsWith(`.local`)||n.endsWith(`.lan`)||n.endsWith(`.home`)||n.endsWith(`.internal`))return`private`}catch{}}const a={async request({url:e,method:t=`GET`,headers:n={},body:r}){r&&=await o(r);let a=i(e),c={method:t,headers:n,body:r,credentials:`omit`};a&&(c.targetAddressSpace=a);let l=await fetch(e,c),u=l.body&&typeof l.body.getReader==`function`?s(l.body):[new Uint8Array(await l.arrayBuffer())],d={};for(let[e,t]of l.headers.entries())d[e]=t;return{url:l.url,method:t,statusCode:l.status,statusMessage:l.statusText,body:u,headers:d}}};async function o(e){let t=[];if(e[Symbol.asyncIterator])for await(let n of e)t.push(n);else if(e[Symbol.iterator])for(let n of e)t.push(n);else if(e.next){let n=await e.nexT();for(;!n.done;)t.push(n.value),n=await e.nexT()}else return e;let n=t.reduce((e,t)=>e+t.length,0),r=new Uint8Array(n),i=0;for(let e of t)r.set(e,i),i+=e.length;return r}function s(e){let t=e.getReader();return{next(){return t.read()},return(){return t.releaseLock(),{}},[Symbol.asyncIterator](){return this}}}let c=null,l=null,u=null,d=null,f=null;function p(e){return e.trim().replace(/^[\\/]+/,``).replace(/[\\/]+$/,``).split(/[\\/]+/).filter(e=>e!==`.`&&e!==``).join(`/`)}const m=new class{_map=new Map;_maxSize;constructor(e=2048){this._maxSize=e}clear(){this._map.clear()}get(e){let t=this._map.get(e);return t!==void 0&&(this._map.delete(e),this._map.set(e,t)),t}invalidate(e){let t=e.endsWith(`/`)?e:e+`/`;for(let n of this._map.keys())(n===e||n.startsWith(t))&&this._map.delete(n)}set(e,t){if(this._map.size>=this._maxSize){let e=this._map.keys().next().value;e!==void 0&&this._map.delete(e)}this._map.set(e,t)}};async function h(e,t,n={},r=``){let i=e,a=r;for(let e of t){a=a?`${a}/${e}`:e;let t=m.get(a);t&&!n.create?i=t:(i=await i.getDirectoryHandle(e,{create:n.create??!1}),m.set(a,i))}return i}async function g(e,t,n={}){let r=p(t),i=r.split(`/`).filter(Boolean);if(i.length===0)return e;let a=await h(e,i.slice(0,-1),n),o=i[i.length-1];if(n.forceFile||o.includes(`.`))try{return await a.getFileHandle(o,{create:n.create??!1})}catch{}try{let e=await a.getDirectoryHandle(o,{create:n.create??!1}),t=r;return m.set(t,e),e}catch{return await a.getFileHandle(o,{create:n.create??!1})}}async function _(e,t,n={}){let r=p(t).split(`/`).filter(Boolean);return r.length===0?e:h(e,r,n)}async function v(e,t,n={}){let r=p(t).split(`/`).filter(Boolean);if(r.length===0)throw Error(`Cannot resolve '.' as file`);return(await h(e,r.slice(0,-1),n)).getFileHandle(r[r.length-1],{create:n.create??!1})}async function y(e,t){let n=p(t).split(`/`).filter(Boolean);if(n.length===0)throw Error(`Cannot get parent of root`);let r=n[n.length-1];return[await h(e,n.slice(0,-1)),r]}function b(e){return e.trim().replace(/\\/g,`/`).replace(/^\/+/,``).replace(/^\.\//,``)}function x(e){let t=new Map,n=`repos/.git-modes`;function r(e){return e.replace(/\\/g,`/`.replace(/^\/+/,``))}async function i(){try{let r=await(await(await v(e,n)).getFile()).text(),i=JSON.parse(r);for(let[e,n]of i)t.set(e,n)}catch{}}let a=null;function o(){a===null&&(a=setTimeout(async()=>{a=null;try{let r=await(await v(e,n,{create:!0})).createWritable(),i=JSON.stringify([...t.entries()]);await r.write(new TextEncoder().encode(i)),await r.close()}catch{}},500))}let s=i(),c={async readFile(t,n){let r=await(await(await v(e,t)).getFile()).arrayBuffer(),i=typeof n==`string`?n:n?.encoding;return i===`utf8`||i===`utf-8`?new TextDecoder().decode(r):new Uint8Array(r)},async writeFile(n,i,a){let s=await(await v(e,n,{create:!0})).createWritable();typeof i==`string`&&(i=new TextEncoder().encode(i)),await s.write(i),await s.close();let c=typeof a==`object`&&a?a.mode:void 0,l=r(n);if(c!=null){let e=(c&73)!=0;t.set(l,e?33261:33188),o()}else t.has(l)||t.set(l,33188)},async mkdir(t){await _(e,t,{create:!0})},async rmdir(n){let[i,a]=await y(e,n);await i.removeEntry(a,{recursive:!0});let o=r(n)+`/`;for(let e of t.keys())(e===r(n)||e.startsWith(o))&&t.delete(e);m.invalidate(p(n))},async readdir(t){let n=await _(e,t),r=[];for await(let[e]of n.entries())r.push(e);return r},async stat(n){await s;let i;try{i=await g(e,n)}catch{let e=Error(`ENOENT: no such file or directory, stat '${n}'`);throw e.code=`ENOENT`,e}if(i.kind===`directory`){let e=new Date;return{isDirectory:()=>!0,isFile:()=>!1,isSymbolicLink:()=>!1,size:0,mtimeMs:Date.now(),mode:16877,ino:0,dev:0,nlink:1,uid:0,gid:0,ctime:e,mtime:e}}else{let e=await i.getFile(),a=new Date(e.lastModified),o=r(n),s=t.get(o)??33188;return{isDirectory:()=>!1,isFile:()=>!0,isSymbolicLink:()=>!1,size:e.size,mtimeMs:e.lastModified,mode:s,ino:0,dev:0,nlink:1,uid:0,gid:0,ctime:a,mtime:a}}},async lstat(e){return c.stat(e)},async unlink(n){let[i,a]=await y(e,n);await i.removeEntry(a),t.delete(r(n))},async symlink(e,t){throw Error(`OPFS does not support symlinks`)},async readlink(e){return await c.readFile(e,`utf8`)}};return{promises:c}}const ee=x,S=`repos`;function C(n,r,i){if(n===`custom`&&r)return r;if(n===`public`)return`https://www.cors-anywhere.com`;let a=i||(typeof globalThis<`u`&&globalThis.location?globalThis.location:typeof self<`u`&&self.location?self.location:typeof window<`u`&&window.location?window.location:null),o=a?.protocol||``,s=o===`https:`||o===`https`||typeof a?.origin==`string`&&a.origin.startsWith(`https:`)||typeof a?.href==`string`&&a.href.startsWith(`https://`)?`https:`:`http:`,c=a?.host||``,l=a?.hostname||``,u=l===`localhost`||l===`127.0.0.1`||l===`::1`||l===`[::1]`||l===`0.0.0.0`||c.startsWith(`localhost:`)||c.startsWith(`127.0.0.1:`)||c.startsWith(`[::1]:`),d=a&&(a.protocol===`file:`||l&&(l.endsWith(`.github.io`)||l.endsWith(`.pages.dev`)));return c&&(u||!d)?`${s}//${c}/git-proxy`:`${s}//${t}:${e}/git-proxy`}async function w(){return f||=(async()=>{if(c=r,l=a,!u){let e;try{e=await navigator.storage.getDirectory()}catch(t){console.warn(`OPFS is unavailable for git root, falling back to memory:`,t);let{getMemoryOpfsRoot:n}=await import(`./chunk-
|
|
1
|
+
import{a as e,i as t}from"./chunk-BkKN8FNP.js";import{Buffer as n}from"buffer";import r from"isomorphic-git";globalThis.Buffer||(globalThis.Buffer=n);function i(e){try{let t=typeof location<`u`&&location.origin?location.origin:typeof globalThis<`u`&&globalThis.location?.origin?globalThis.location.origin:`http://127.0.0.1:8888`,n=new URL(e,t).hostname.toLowerCase();if(n===`localhost`||n===`127.0.0.1`||n===`::1`||n===`[::1]`)return`loopback`;if(/^(10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.)/.test(n)||!n.includes(`.`)||n.endsWith(`.local`)||n.endsWith(`.lan`)||n.endsWith(`.home`)||n.endsWith(`.internal`))return`private`}catch{}}const a={async request({url:e,method:t=`GET`,headers:n={},body:r}){r&&=await o(r);let a=i(e),c={method:t,headers:n,body:r,credentials:`omit`};a&&(c.targetAddressSpace=a);let l=await fetch(e,c),u=l.body&&typeof l.body.getReader==`function`?s(l.body):[new Uint8Array(await l.arrayBuffer())],d={};for(let[e,t]of l.headers.entries())d[e]=t;return{url:l.url,method:t,statusCode:l.status,statusMessage:l.statusText,body:u,headers:d}}};async function o(e){let t=[];if(e[Symbol.asyncIterator])for await(let n of e)t.push(n);else if(e[Symbol.iterator])for(let n of e)t.push(n);else if(e.next){let n=await e.nexT();for(;!n.done;)t.push(n.value),n=await e.nexT()}else return e;let n=t.reduce((e,t)=>e+t.length,0),r=new Uint8Array(n),i=0;for(let e of t)r.set(e,i),i+=e.length;return r}function s(e){let t=e.getReader();return{next(){return t.read()},return(){return t.releaseLock(),{}},[Symbol.asyncIterator](){return this}}}let c=null,l=null,u=null,d=null,f=null;function p(e){return e.trim().replace(/^[\\/]+/,``).replace(/[\\/]+$/,``).split(/[\\/]+/).filter(e=>e!==`.`&&e!==``).join(`/`)}const m=new class{_map=new Map;_maxSize;constructor(e=2048){this._maxSize=e}clear(){this._map.clear()}get(e){let t=this._map.get(e);return t!==void 0&&(this._map.delete(e),this._map.set(e,t)),t}invalidate(e){let t=e.endsWith(`/`)?e:e+`/`;for(let n of this._map.keys())(n===e||n.startsWith(t))&&this._map.delete(n)}set(e,t){if(this._map.size>=this._maxSize){let e=this._map.keys().next().value;e!==void 0&&this._map.delete(e)}this._map.set(e,t)}};async function h(e,t,n={},r=``){let i=e,a=r;for(let e of t){a=a?`${a}/${e}`:e;let t=m.get(a);t&&!n.create?i=t:(i=await i.getDirectoryHandle(e,{create:n.create??!1}),m.set(a,i))}return i}async function g(e,t,n={}){let r=p(t),i=r.split(`/`).filter(Boolean);if(i.length===0)return e;let a=await h(e,i.slice(0,-1),n),o=i[i.length-1];if(n.forceFile||o.includes(`.`))try{return await a.getFileHandle(o,{create:n.create??!1})}catch{}try{let e=await a.getDirectoryHandle(o,{create:n.create??!1}),t=r;return m.set(t,e),e}catch{return await a.getFileHandle(o,{create:n.create??!1})}}async function _(e,t,n={}){let r=p(t).split(`/`).filter(Boolean);return r.length===0?e:h(e,r,n)}async function v(e,t,n={}){let r=p(t).split(`/`).filter(Boolean);if(r.length===0)throw Error(`Cannot resolve '.' as file`);return(await h(e,r.slice(0,-1),n)).getFileHandle(r[r.length-1],{create:n.create??!1})}async function y(e,t){let n=p(t).split(`/`).filter(Boolean);if(n.length===0)throw Error(`Cannot get parent of root`);let r=n[n.length-1];return[await h(e,n.slice(0,-1)),r]}function b(e){return e.trim().replace(/\\/g,`/`).replace(/^\/+/,``).replace(/^\.\//,``)}function x(e){let t=new Map,n=`repos/.git-modes`;function r(e){return e.replace(/\\/g,`/`.replace(/^\/+/,``))}async function i(){try{let r=await(await(await v(e,n)).getFile()).text(),i=JSON.parse(r);for(let[e,n]of i)t.set(e,n)}catch{}}let a=null;function o(){a===null&&(a=setTimeout(async()=>{a=null;try{let r=await(await v(e,n,{create:!0})).createWritable(),i=JSON.stringify([...t.entries()]);await r.write(new TextEncoder().encode(i)),await r.close()}catch{}},500))}let s=i(),c={async readFile(t,n){let r=await(await(await v(e,t)).getFile()).arrayBuffer(),i=typeof n==`string`?n:n?.encoding;return i===`utf8`||i===`utf-8`?new TextDecoder().decode(r):new Uint8Array(r)},async writeFile(n,i,a){let s=await(await v(e,n,{create:!0})).createWritable();typeof i==`string`&&(i=new TextEncoder().encode(i)),await s.write(i),await s.close();let c=typeof a==`object`&&a?a.mode:void 0,l=r(n);if(c!=null){let e=(c&73)!=0;t.set(l,e?33261:33188),o()}else t.has(l)||t.set(l,33188)},async mkdir(t){await _(e,t,{create:!0})},async rmdir(n){let[i,a]=await y(e,n);await i.removeEntry(a,{recursive:!0});let o=r(n)+`/`;for(let e of t.keys())(e===r(n)||e.startsWith(o))&&t.delete(e);m.invalidate(p(n))},async readdir(t){let n=await _(e,t),r=[];for await(let[e]of n.entries())r.push(e);return r},async stat(n){await s;let i;try{i=await g(e,n)}catch{let e=Error(`ENOENT: no such file or directory, stat '${n}'`);throw e.code=`ENOENT`,e}if(i.kind===`directory`){let e=new Date;return{isDirectory:()=>!0,isFile:()=>!1,isSymbolicLink:()=>!1,size:0,mtimeMs:Date.now(),mode:16877,ino:0,dev:0,nlink:1,uid:0,gid:0,ctime:e,mtime:e}}else{let e=await i.getFile(),a=new Date(e.lastModified),o=r(n),s=t.get(o)??33188;return{isDirectory:()=>!1,isFile:()=>!0,isSymbolicLink:()=>!1,size:e.size,mtimeMs:e.lastModified,mode:s,ino:0,dev:0,nlink:1,uid:0,gid:0,ctime:a,mtime:a}}},async lstat(e){return c.stat(e)},async unlink(n){let[i,a]=await y(e,n);await i.removeEntry(a),t.delete(r(n))},async symlink(e,t){throw Error(`OPFS does not support symlinks`)},async readlink(e){return await c.readFile(e,`utf8`)}};return{promises:c}}const ee=x,S=`repos`;function C(n,r,i){if(n===`custom`&&r)return r;if(n===`public`)return`https://www.cors-anywhere.com`;let a=i||(typeof globalThis<`u`&&globalThis.location?globalThis.location:typeof self<`u`&&self.location?self.location:typeof window<`u`&&window.location?window.location:null),o=a?.protocol||``,s=o===`https:`||o===`https`||typeof a?.origin==`string`&&a.origin.startsWith(`https:`)||typeof a?.href==`string`&&a.href.startsWith(`https://`)?`https:`:`http:`,c=a?.host||``,l=a?.hostname||``,u=l===`localhost`||l===`127.0.0.1`||l===`::1`||l===`[::1]`||l===`0.0.0.0`||c.startsWith(`localhost:`)||c.startsWith(`127.0.0.1:`)||c.startsWith(`[::1]:`),d=a&&(a.protocol===`file:`||l&&(l.endsWith(`.github.io`)||l.endsWith(`.pages.dev`)));return c&&(u||!d)?`${s}//${c}/git-proxy`:`${s}//${t}:${e}/git-proxy`}async function w(){return f||=(async()=>{if(c=r,l=a,!u){let e;try{e=await navigator.storage.getDirectory()}catch(t){console.warn(`OPFS is unavailable for git root, falling back to memory:`,t);let{getMemoryOpfsRoot:n}=await import(`./chunk-Da1BZyqf2.js`);e=n()}u=x(e),d=u.promises}})(),await f,{git:c,http:l,fs:u,pfs:d}}async function T(e){let t=await w();if(e){let n=x(e);return{git:t.git,http:t.http,fs:n,pfs:n.promises,repoDirFn:e=>`repos/${e}`}}return{...t,repoDirFn:D}}function E(e){return(e.replace(/\/+$/,``).split(`/`).pop()||`repo`).replace(/\.git$/,``)}function D(e){return`${S}/${e}`}async function O(e,t,n){try{await e.getConfig({fs:t,dir:n,path:`core.filemode`})!==!1&&await e.setConfig({fs:t,dir:n,path:`core.filemode`,value:!1})}catch(e){console.error(`Failed to set core.filemode=false:`,e)}}async function k(e,t){try{await e.mkdir(t)}catch{}}function A({token:e,username:t,password:n}={}){if(!e&&!t)return{};let r;e?r={Authorization:`Basic ${btoa(`${e}:x-oauth-basic`)}`}:t&&(r={Authorization:`Basic ${btoa(`${t}:${n||``}`)}`});let i=()=>e?{username:e,password:`x-oauth-basic`}:t?{username:t,password:n||``}:{cancel:!0},a=()=>({cancel:!0});return{...r?{headers:r}:{},onAuth:i,onAuthFailure:a}}async function j({url:e,branch:t,depth:n=20,corsProxy:r,name:i,token:a,username:o,password:s,groupRoot:c}){let{git:l,http:u,fs:d,pfs:f,repoDirFn:p}=await T(c),m=i||E(e),h=p(m);r||=C(`local`),await k(f,S),await k(f,h);let g=A({token:a,username:o,password:s});try{let i={fs:d,http:u,dir:h,url:e,singleBranch:!0,depth:n,corsProxy:r,...g};t&&(i.ref=t),await l.clone(i)}catch{try{let i={fs:d,http:u,dir:h,url:e,singleBranch:!0,depth:n,corsProxy:r,...g};t&&(i.ref=t),await l.fetch(i)}catch{try{await Q(f,h),await k(f,h);let i={fs:d,http:u,dir:h,url:e,singleBranch:!0,depth:n,corsProxy:r,...g};t&&(i.ref=t),await l.clone(i)}catch(t){throw Error(`Failed to clone/fetch ${e}: ${t instanceof Error?t.message:String(t)}`)}}}return await O(l,d,h),m}async function M({repo:e,ref:t,groupRoot:n}){let{git:r,fs:i,repoDirFn:a}=await T(n),o=a(e);return await r.checkout({fs:i,dir:o,ref:t,force:!0}),`Checked out ${t} in ${e}`}async function N({repo:e,name:t,checkout:n=!1,startPoint:r,groupRoot:i}){let{git:a,fs:o,repoDirFn:s}=await T(i),c=s(e),l={fs:o,dir:c,ref:t};return r&&(l.object=r),await a.branch(l),n?(await a.checkout({fs:o,dir:c,ref:t}),`Created and switched to branch ${t} in ${e}`):`Created branch ${t} in ${e}`}async function P({repo:e,groupRoot:t}){let{git:n,fs:r,repoDirFn:i}=await T(t),a=i(e);await O(n,r,a);let o=await n.statusMatrix({fs:r,dir:a});if(o.length===0)return`Empty repository.`;let s=[];for(let[e,t,n,r]of o){let i=``;if(t===0&&n===2&&r===2)i=`added`;else if(t===0&&n===2&&r===0)i=`new (unstaged)`;else if(t===1&&n===2&&r===2)i=`modified (staged)`;else if(t===1&&n===2&&r===1)i=`modified`;else if(t===1&&n===0&&r===0)i=`deleted`;else if(t===1&&n===1&&r===1)continue;else i=`[${t},${n},${r}]`;s.push(`${i}: ${e}`)}return s.length===0?`On branch ${await n.currentBranch({fs:r,dir:a})||`(detached HEAD)`}\nNothing to commit, working tree clean.`:`On branch ${await n.currentBranch({fs:r,dir:a})||`(detached HEAD)`}\n${s.join(`
|
|
2
2
|
`)}`}async function F({repo:e,ref:t,depth:n=10,groupRoot:r}){let{git:i,fs:a,repoDirFn:o}=await T(r),s={fs:a,dir:o(e),depth:n};t&&(s.ref=t);let c=await i.log(s);return c.length===0?`No commits found.`:c.map(e=>{let t=e.commit,n=new Date(t.author.timestamp*1e3).toISOString();return`${e.oid} ${n} ${t.author.name} — ${t.message.trim().split(`
|
|
3
3
|
`)[0]}`}).join(`
|
|
4
4
|
`)}async function I({repo:e,ref1:t,ref2:n,groupRoot:r}){let{git:i,fs:a,repoDirFn:o}=await T(r),s=o(e),c=a.promises;if(await O(i,a,s),!t&&!n){let e=(await i.statusMatrix({fs:a,dir:s})).filter(([,e,t])=>!(e===1&&t===1));if(e.length===0)return`No differences.`;let t=[];for(let[n,r,o]of e)try{if(r===0&&o===2){let e=(await R(c,s,n)).split(`
|