dal-code 1.0.43 → 1.0.45
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/CHANGELOG.md +36 -0
- package/NOTICE +17 -0
- package/PRIVACY.md +159 -102
- package/dal-docs/README.md +1 -1
- package/dal-docs/keybindings.md +1 -0
- package/dal-docs/settings.md +5 -0
- package/dist/cli/credential-print.js +1 -1
- package/dist/config.d.ts +1 -0
- package/dist/config.js +1 -1
- package/dist/core/agent-session-runtime.js +1 -1
- package/dist/core/agent-session.d.ts +1 -1
- package/dist/core/agent-session.js +7 -7
- package/dist/core/auth-storage.js +1 -1
- package/dist/core/background-processes.js +7 -7
- package/dist/core/export-html/template.js +34 -34
- package/dist/core/extensions/runner.js +1 -1
- package/dist/core/extensions/types.d.ts +7 -1
- package/dist/core/key-id-schema.js +1 -0
- package/dist/core/keybindings-schema.js +1 -0
- package/dist/core/keybindings.d.ts +5 -0
- package/dist/core/keybindings.js +1 -1
- package/dist/core/model-config.d.ts +818 -99
- package/dist/core/model-config.js +5 -5
- package/dist/core/model-resolver.d.ts +30 -10
- package/dist/core/model-resolver.js +1 -1
- package/dist/core/model-runtime.d.ts +1 -0
- package/dist/core/model-runtime.js +2 -2
- package/dist/core/package-manager.d.ts +5 -0
- package/dist/core/package-manager.js +2 -2
- package/dist/core/permissions/shell-words.d.ts +26 -0
- package/dist/core/permissions/tool-policy.d.ts +2 -1
- package/dist/core/permissions/tool-policy.js +1 -1
- package/dist/core/project-trust.js +2 -2
- package/dist/core/prompt-templates.js +2 -2
- package/dist/core/remote-catalog-provider.js +1 -1
- package/dist/core/resource-loader.js +1 -1
- package/dist/core/sandbox/libreoffice.js +1 -0
- package/dist/core/sandbox/runtime.d.ts +1 -0
- package/dist/core/sandbox/runtime.js +1 -1
- package/dist/core/sandbox/shell-sandbox.js +6 -6
- package/dist/core/sandbox/windows.js +4 -4
- package/dist/core/session-manager.d.ts +1 -0
- package/dist/core/session-manager.js +12 -12
- package/dist/core/settings-defaults.js +1 -0
- package/dist/core/settings-manager.d.ts +5 -0
- package/dist/core/settings-manager.js +1 -1
- package/dist/core/settings-schema.d.ts +229 -0
- package/dist/core/settings-schema.js +1 -0
- package/dist/core/tool-denial.d.ts +13 -0
- package/dist/core/tool-denial.js +1 -0
- package/dist/core/tools/bash-read-only.d.ts +1 -0
- package/dist/core/tools/bash.js +13 -13
- package/dist/core/tools/read.js +12 -12
- package/dist/core/tools/render-utils.d.ts +40 -0
- package/dist/core/tools/render-utils.js +7 -7
- package/dist/core/tools/renderers/read.js +8 -8
- package/dist/core/trust-manager.js +1 -1
- package/dist/core/workspace-lock.d.ts +6 -2
- package/dist/core/workspace-lock.js +3 -3
- package/dist/dal/extension-compat.js +4 -4
- package/dist/dal/hooks/config.d.ts +5 -1
- package/dist/dal/hooks/config.js +1 -1
- package/dist/dal/hooks/extension.js +3 -3
- package/dist/dal/hooks/index.d.ts +1 -1
- package/dist/dal/hooks/index.js +1 -1
- package/dist/dal/i18n.js +1 -1
- package/dist/dal/manifest.js +1 -1
- package/dist/extensions/codemode/execute.js +14 -13
- package/dist/extensions/codemode/index.js +1 -1
- package/dist/extensions/codemode/renderer.js +6 -6
- package/dist/extensions/codemode/tool.d.ts +2 -3
- package/dist/extensions/codemode/tool.js +9 -12
- package/dist/extensions/mcp/cli.js +4 -4
- package/dist/extensions/mcp/index.js +12 -12
- package/dist/extensions/mcp/resources.d.ts +0 -5
- package/dist/extensions/mcp/resources.js +1 -1
- package/dist/extensions/mcp/runtime.d.ts +1 -4
- package/dist/extensions/mcp/runtime.js +3 -3
- package/dist/extensions/mcp/tools.js +7 -7
- package/dist/extensions/tool-search/tool.js +3 -3
- package/dist/index.d.ts +6 -2
- package/dist/index.js +1 -1
- package/dist/main.js +3 -3
- package/dist/migrations.js +5 -5
- package/dist/modes/interactive/components/settings-selector.d.ts +3 -1
- package/dist/modes/interactive/components/settings-selector.js +1 -1
- package/dist/modes/interactive/components/status-indicator.d.ts +1 -1
- package/dist/modes/interactive/components/status-indicator.js +1 -1
- package/dist/modes/interactive/components/tree-selector.js +1 -1
- package/dist/modes/interactive/interactive-mode.js +17 -17
- package/dist/modes/interactive/session-share.js +2 -2
- package/dist/modes/interactive/theme/dark.json +1 -1
- package/dist/modes/interactive/theme/light.json +1 -1
- package/dist/modes/interactive/theme/theme-schema.d.ts +18 -0
- package/dist/modes/interactive/theme/theme-schema.js +12 -0
- package/dist/modes/interactive/theme/theme-tokens.d.ts +255 -0
- package/dist/modes/interactive/theme/theme-tokens.js +1 -0
- package/dist/modes/interactive/theme/theme.d.ts +7 -10
- package/dist/modes/interactive/theme/theme.js +5 -5
- package/dist/modes/rpc/rpc-client.d.ts +5 -1
- package/dist/modes/rpc/rpc-client.js +2 -2
- package/dist/modes/rpc/rpc-mode.js +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +20 -0
- package/dist/node_modules/@dalcode/dal-advisor/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-advisor/src/index.js +8 -8
- package/dist/node_modules/@dalcode/dal-awake/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-bridge/src/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-capabilities/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-capabilities/src/index.js +10 -10
- package/dist/node_modules/@dalcode/dal-codeindex/package.json +34 -0
- package/dist/node_modules/@dalcode/dal-codeindex/src/extract.js +3 -0
- package/dist/node_modules/@dalcode/dal-codeindex/src/format.js +11 -0
- package/dist/node_modules/@dalcode/dal-codeindex/src/index.js +4 -0
- package/dist/node_modules/@dalcode/dal-codeindex/src/indexer.js +1 -0
- package/dist/node_modules/@dalcode/dal-codeindex/src/languages.js +176 -0
- package/dist/node_modules/@dalcode/dal-codeindex/src/project.js +1 -0
- package/dist/node_modules/@dalcode/dal-codeindex/src/query.js +2 -0
- package/dist/node_modules/@dalcode/dal-codeindex/src/runtime.js +1 -0
- package/dist/node_modules/@dalcode/dal-codeindex/src/scan.js +1 -0
- package/dist/node_modules/@dalcode/dal-codeindex/src/semantic.js +2 -0
- package/dist/node_modules/@dalcode/dal-codeindex/src/sqlite.js +1 -0
- package/dist/node_modules/@dalcode/dal-codeindex/src/store.js +33 -0
- package/dist/node_modules/@dalcode/dal-codeindex/src/worker.js +1 -0
- package/dist/node_modules/@dalcode/dal-compat/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-dap/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-goal/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-guard/src/index.js +4 -2
- package/dist/node_modules/@dalcode/dal-guard/src/mode.js +2 -2
- package/dist/node_modules/@dalcode/dal-guard/src/policy.js +1 -0
- package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-learn/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-lsp/src/index.js +12 -10
- package/dist/node_modules/@dalcode/dal-mcp/package.json +7 -5
- package/dist/node_modules/@dalcode/dal-mcp/src/http-client.d.ts +9 -27
- package/dist/node_modules/@dalcode/dal-mcp/src/http-client.js +1 -2
- package/dist/node_modules/@dalcode/dal-mcp/src/index.js +17 -17
- package/dist/node_modules/@dalcode/dal-mcp/src/protocol-client.d.ts +38 -0
- package/dist/node_modules/@dalcode/dal-mcp/src/protocol-client.js +1 -0
- package/dist/node_modules/@dalcode/dal-mcp/src/proxy.js +6 -6
- package/dist/node_modules/@dalcode/dal-mcp/src/resources.js +1 -0
- package/dist/node_modules/@dalcode/dal-mcp/src/stdio-client.d.ts +9 -18
- package/dist/node_modules/@dalcode/dal-mcp/src/stdio-client.js +4 -5
- package/dist/node_modules/@dalcode/dal-mcp/src/types.d.ts +50 -5
- package/dist/node_modules/@dalcode/dal-mcp/src/types.js +1 -1
- package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-office/src/index.d.ts +2 -2
- package/dist/node_modules/@dalcode/dal-office/src/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-office/src/render/docx.js +1 -1
- package/dist/node_modules/@dalcode/dal-office/src/render/pptx.d.ts +8 -0
- package/dist/node_modules/@dalcode/dal-office/src/render/pptx.js +3 -3
- package/dist/node_modules/@dalcode/dal-office/src/render/xlsx.js +1 -1
- package/dist/node_modules/@dalcode/dal-office/src/themes.d.ts +2 -0
- package/dist/node_modules/@dalcode/dal-office/src/themes.js +1 -1
- package/dist/node_modules/@dalcode/dal-office/src/tools/ppt-generate.js +3 -2
- package/dist/node_modules/@dalcode/dal-office/src/tools/ppt-plan.js +2 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +9 -3
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/session-scope.js +1 -0
- package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +9 -3
- package/dist/node_modules/@dalcode/dal-pi-kit/src/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/src/session-scope.js +1 -0
- package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-plugins/src/brand.js +1 -1
- package/dist/node_modules/@dalcode/dal-plugins/src/index.js +11 -11
- package/dist/node_modules/@dalcode/dal-recall/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-remote/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-remote/src/cli.js +14 -9
- package/dist/node_modules/@dalcode/dal-remote/src/processes.js +2 -0
- package/dist/node_modules/@dalcode/dal-remote/src/service.js +7 -7
- package/dist/node_modules/@dalcode/dal-remote/src/spec.js +1 -1
- package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-rewind/src/core.d.ts +0 -1
- package/dist/node_modules/@dalcode/dal-rewind/src/core.js +8 -8
- package/dist/node_modules/@dalcode/dal-rewind/src/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-router/package.json +9 -5
- package/dist/node_modules/@dalcode/dal-router/src/advisor.js +1 -1
- package/dist/node_modules/@dalcode/dal-router/src/commands.js +8 -7
- package/dist/node_modules/@dalcode/dal-router/src/config.d.ts +11 -0
- package/dist/node_modules/@dalcode/dal-router/src/config.js +2 -2
- package/dist/node_modules/@dalcode/dal-router/src/index.js +4 -4
- package/dist/node_modules/@dalcode/dal-router/src/roles/changes.js +5 -0
- package/dist/node_modules/@dalcode/dal-router/src/roles/index.js +13 -0
- package/dist/node_modules/@dalcode/dal-router/src/roles/models.d.ts +50 -0
- package/dist/node_modules/@dalcode/dal-router/src/roles/models.js +1 -0
- package/dist/node_modules/@dalcode/dal-router/src/roles/prompts.js +40 -0
- package/dist/node_modules/@dalcode/dal-router/src/roles/signals.js +2 -0
- package/dist/node_modules/@dalcode/dal-router/src/runtime.d.ts +3 -0
- package/dist/node_modules/@dalcode/dal-router/src/runtime.js +1 -1
- package/dist/node_modules/@dalcode/dal-router/src/subagent.js +1 -1
- package/dist/node_modules/@dalcode/dal-rtk/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-skills/src/bundled/dal-slides/SKILL.md +74 -0
- package/dist/node_modules/@dalcode/dal-skills/src/bundled.js +1 -1
- package/dist/node_modules/@dalcode/dal-skills/src/client.js +1 -1
- package/dist/node_modules/@dalcode/dal-skills/src/index.js +14 -14
- package/dist/node_modules/@dalcode/dal-skills/src/packages.js +3 -3
- package/dist/node_modules/@dalcode/dal-skills/src/search.js +1 -1
- package/dist/node_modules/@dalcode/dal-statusline/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-structured/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-subagent/src/background.js +8 -8
- package/dist/node_modules/@dalcode/dal-subagent/src/index.js +21 -21
- package/dist/node_modules/@dalcode/dal-subagent/src/progress.js +1 -1
- package/dist/node_modules/@dalcode/dal-telemetry/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-tool-catalog/src/index.js +4 -4
- package/dist/node_modules/@dalcode/dal-usage/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-workflow/LICENSE +27 -0
- package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-workflow/src/index.js +4 -4
- package/dist/node_modules/@dalcode/dal-workflow/src/plan-mode.js +13 -13
- package/dist/node_modules/@dalcode/dal-workflow/src/todo-snapshot.js +2 -0
- package/dist/node_modules/@dalcode/dal-workflow/src/todo.js +4 -4
- package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js +1 -1
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/types.d.ts +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-ai/README.md +5 -34
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js +5 -5
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/google-shared.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.js +4 -4
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js +6 -6
- package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js +2 -2
- package/dist/node_modules/@earendil-works/pi-ai/dist/index.d.ts +0 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/index.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/models.d.ts +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/models.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/compat-schema.d.ts +359 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/compat-schema.js +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/anthropic.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/azure.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/baseten.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cerebras.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/github-copilot.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/google.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/groq.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/huggingface.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/kimi-coding.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/minimax-cn.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/minimax.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/mistral.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/moonshotai-cn.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openai-codex.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openai.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/qwen-token-plan-cn.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/qwen-token-plan.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/radius.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/together.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xai.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi-token-plan-ams.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi-token-plan-cn.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi-token-plan-sgp.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/model-schema.d.ts +90 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/model-schema.js +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/openrouter-api.js +1 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/openrouter.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/types.d.ts +5 -146
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/retry.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-codemode/README.md +195 -11
- package/dist/node_modules/@earendil-works/pi-codemode/dist/cloudflare.js +1 -0
- package/dist/node_modules/@earendil-works/pi-codemode/dist/declarations.d.ts +0 -2
- package/dist/node_modules/@earendil-works/pi-codemode/dist/declarations.js +9 -84
- package/dist/node_modules/@earendil-works/pi-codemode/dist/index.d.ts +5 -2
- package/dist/node_modules/@earendil-works/pi-codemode/dist/index.js +1 -1
- package/dist/node_modules/@earendil-works/pi-codemode/dist/portable.js +1 -0
- package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/execution.d.ts +29 -0
- package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/execution.js +1 -0
- package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/host.d.ts +3 -16
- package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/host.js +1 -1
- package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/inline.d.ts +13 -0
- package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/inline.js +1 -0
- package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/prelude-source.js +14 -6
- package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/protocol.d.ts +72 -0
- package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/protocol.js +1 -1
- package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/remote.d.ts +32 -0
- package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/remote.js +1 -0
- package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/vm.js +3 -0
- package/dist/node_modules/@earendil-works/pi-codemode/dist/runtime/worker.js +1 -3
- package/dist/node_modules/@earendil-works/pi-codemode/dist/source.js +4 -3
- package/dist/node_modules/@earendil-works/pi-codemode/dist/types.d.ts +51 -1
- package/dist/node_modules/@earendil-works/pi-codemode/package.json +14 -2
- package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-mcp/CHANGELOG.md +13 -0
- package/dist/node_modules/@earendil-works/pi-mcp/dist/client.js +1 -1
- package/dist/node_modules/@earendil-works/pi-mcp/dist/index.d.ts +1 -1
- package/dist/node_modules/@earendil-works/pi-mcp/dist/oauth/errors.d.ts +2 -2
- package/dist/node_modules/@earendil-works/pi-mcp/dist/oauth/errors.js +1 -1
- package/dist/node_modules/@earendil-works/pi-mcp/dist/oauth/flow.js +1 -1
- package/dist/node_modules/@earendil-works/pi-mcp/dist/protocol/content.d.ts +1 -1
- package/dist/node_modules/@earendil-works/pi-mcp/dist/transports/streamable-http.d.ts +2 -2
- package/dist/node_modules/@earendil-works/pi-mcp/dist/transports/streamable-http.js +4 -4
- package/dist/node_modules/@earendil-works/pi-mcp/dist/transports/transport.d.ts +4 -1
- package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/README.md +5 -3
- package/dist/node_modules/@earendil-works/pi-tui/dist/components/editor.js +6 -6
- package/dist/node_modules/@earendil-works/pi-tui/dist/components/input.js +2 -2
- package/dist/node_modules/@earendil-works/pi-tui/dist/index.d.ts +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/dist/index.js +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/dist/keys.js +5 -5
- package/dist/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.js +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/dist/terminal-image.js +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js +3 -3
- package/dist/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.js +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/dist/tui.d.ts +4 -0
- package/dist/node_modules/@earendil-works/pi-tui/dist/tui.js +2 -2
- package/dist/node_modules/@earendil-works/pi-tui/dist/utils.js +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/dist/sdk/index.d.ts +3 -3
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/rewind.d.ts +1 -1
- package/dist/sdk/rewind.js +1 -1
- package/dist/utils/clipboard.js +1 -1
- package/dist/utils/output-files.js +1 -1
- package/dist/utils/temp-files.js +1 -0
- package/docs/security.md +24 -7
- package/examples/README.md +0 -3
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/dynamic-resources/dynamic.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/minimal-mode.ts +4 -5
- package/examples/extensions/overlay-test.ts +2 -2
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/subagent/index.ts +4 -6
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +9 -460
- package/package.json +3 -12
- package/dist/modes/interactive/theme/theme-json.d.ts +0 -75
- package/dist/modes/interactive/theme/theme-json.js +0 -12
- package/dist/modes/interactive/theme/theme-schema.json +0 -361
- package/dist/node_modules/@earendil-works/chord/README.md +0 -264
- package/dist/node_modules/@earendil-works/chord/dist/api.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/bundler.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/context/index.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/delta/apply-immutable-trusted.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/delta/diff.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/delta/draft.js +0 -0
- package/dist/node_modules/@earendil-works/chord/dist/delta/index.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/delta/revision-validator.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/delta/tracker.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/facets/host.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/facets/loader.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/index.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/json.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/node/bundle-loader.js +0 -2
- package/dist/node_modules/@earendil-works/chord/dist/node/bundle.js +0 -4
- package/dist/node_modules/@earendil-works/chord/dist/node/manifest.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/node/package.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/node.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/services/consumer.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/services/errors.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/services/handle.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/services/instances.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/services/loopback.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/services/provider.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/services/state-codec.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/services/state-internals.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/services/state.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/services/wire.js +0 -1
- package/dist/node_modules/@earendil-works/chord/dist/types.js +0 -0
- package/dist/node_modules/@earendil-works/chord/package.json +0 -62
- package/dist/node_modules/@earendil-works/chord/src/delta/README.md +0 -191
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/assistant-message-frame.d.ts +0 -63
- package/dist/node_modules/@earendil-works/pi-ai/dist/utils/assistant-message-frame.js +0 -1
- package/dist/node_modules/@earendil-works/pi-client/CHANGELOG.md +0 -45
- package/dist/node_modules/@earendil-works/pi-client/LICENSE +0 -21
- package/dist/node_modules/@earendil-works/pi-client/README.md +0 -72
- package/dist/node_modules/@earendil-works/pi-client/dist/client.js +0 -1
- package/dist/node_modules/@earendil-works/pi-client/dist/connection.js +0 -1
- package/dist/node_modules/@earendil-works/pi-client/dist/errors.js +0 -1
- package/dist/node_modules/@earendil-works/pi-client/dist/index.js +0 -1
- package/dist/node_modules/@earendil-works/pi-client/dist/promise.js +0 -1
- package/dist/node_modules/@earendil-works/pi-client/dist/transport.js +0 -0
- package/dist/node_modules/@earendil-works/pi-client/dist/types.js +0 -0
- package/dist/node_modules/@earendil-works/pi-client/dist/unix.js +0 -1
- package/dist/node_modules/@earendil-works/pi-client/package.json +0 -46
- package/dist/node_modules/@earendil-works/pi-protocol/LICENSE +0 -21
- package/dist/node_modules/@earendil-works/pi-protocol/README.md +0 -41
- package/dist/node_modules/@earendil-works/pi-protocol/dist/cbor/decoder.js +0 -1
- package/dist/node_modules/@earendil-works/pi-protocol/dist/cbor/encoder.js +0 -1
- package/dist/node_modules/@earendil-works/pi-protocol/dist/cbor/index.js +0 -1
- package/dist/node_modules/@earendil-works/pi-protocol/dist/cbor/options.js +0 -1
- package/dist/node_modules/@earendil-works/pi-protocol/dist/codec.js +0 -1
- package/dist/node_modules/@earendil-works/pi-protocol/dist/framing.js +0 -1
- package/dist/node_modules/@earendil-works/pi-protocol/dist/index.js +0 -1
- package/dist/node_modules/@earendil-works/pi-protocol/dist/protocol.js +0 -1
- package/dist/node_modules/@earendil-works/pi-protocol/dist/schemas.js +0 -1
- package/dist/node_modules/@earendil-works/pi-protocol/package.json +0 -39
- package/dist/node_modules/@earendil-works/pi-server/CHANGELOG.md +0 -81
- package/dist/node_modules/@earendil-works/pi-server/LICENSE +0 -21
- package/dist/node_modules/@earendil-works/pi-server/README.md +0 -63
- package/dist/node_modules/@earendil-works/pi-server/dist/connection.js +0 -1
- package/dist/node_modules/@earendil-works/pi-server/dist/errors.js +0 -1
- package/dist/node_modules/@earendil-works/pi-server/dist/index.js +0 -1
- package/dist/node_modules/@earendil-works/pi-server/dist/listener.js +0 -0
- package/dist/node_modules/@earendil-works/pi-server/dist/server.js +0 -1
- package/dist/node_modules/@earendil-works/pi-server/dist/session-router.js +0 -1
- package/dist/node_modules/@earendil-works/pi-server/dist/testing/client.js +0 -1
- package/dist/node_modules/@earendil-works/pi-server/dist/testing/host.js +0 -1
- package/dist/node_modules/@earendil-works/pi-server/dist/testing/index.js +0 -1
- package/dist/node_modules/@earendil-works/pi-server/dist/testing/server.js +0 -1
- package/dist/node_modules/@earendil-works/pi-server/dist/transports/unix/address.js +0 -1
- package/dist/node_modules/@earendil-works/pi-server/dist/transports/unix/index.js +0 -1
- package/dist/node_modules/@earendil-works/pi-server/dist/transports/unix/listener.js +0 -1
- package/dist/node_modules/@earendil-works/pi-server/dist/transports/unix/preset.js +0 -1
- package/dist/node_modules/@earendil-works/pi-server/dist/transports/unix/types.js +0 -0
- package/dist/node_modules/@earendil-works/pi-server/dist/types.js +0 -0
- package/dist/node_modules/@earendil-works/pi-server/package.json +0 -45
- package/examples/plugins/pi-example-plugin/README.md +0 -38
- package/examples/plugins/pi-example-plugin/package.json +0 -10
- package/examples/plugins/pi-example-plugin/src/contract.ts +0 -13
- package/examples/plugins/pi-example-plugin/src/session.ts +0 -24
- package/examples/plugins/pi-example-plugin/src/tui.ts +0 -31
- /package/dist/node_modules/{@earendil-works/chord → @dalcode/dal-codeindex}/LICENSE +0 -0
|
@@ -4,7 +4,16 @@ Runs model-written JavaScript in a QuickJS VM (compiled to WebAssembly) where th
|
|
|
4
4
|
|
|
5
5
|
Scripts use `tools`, `ALL_TOOLS`, `text`, `image`, `exit`, `store`, and `load`, and may start with a `// @options:` line. The coding agent uses it for its built-in `codemode` tool. It has no pi dependencies and can be used on its own to expose any functions (remote APIs, MCP servers, application services) to model-written scripts.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
The package runs in two kinds of environments. Each has its own sandbox class, but they share one API, one script environment, and one result format:
|
|
8
|
+
|
|
9
|
+
| Environment | Sandbox | Import from | Where scripts run |
|
|
10
|
+
| --- | --- | --- | --- |
|
|
11
|
+
| Node and Bun | `CodemodeSandbox` | `@earendil-works/pi-codemode` | a worker thread per execution |
|
|
12
|
+
| Cloudflare Workers and Durable Objects | `RemoteCodemodeSandbox` | `@earendil-works/pi-codemode/portable` | a Durable Object in a separately deployed Worker |
|
|
13
|
+
|
|
14
|
+
See [Usage on Node and Bun](#usage-on-node-and-bun) and [Usage on Cloudflare Workers](#usage-on-cloudflare-workers). A third sandbox, `InlineCodemodeSandbox`, runs scripts on the calling thread for other runtimes, or on Cloudflare when blocking the caller is acceptable.
|
|
15
|
+
|
|
16
|
+
## Usage on Node and Bun
|
|
8
17
|
|
|
9
18
|
```ts
|
|
10
19
|
import { CodemodeSandbox } from "@earendil-works/pi-codemode";
|
|
@@ -35,12 +44,12 @@ else console.error(result.error.kind, result.error.message);
|
|
|
35
44
|
await sandbox.close();
|
|
36
45
|
```
|
|
37
46
|
|
|
38
|
-
`code` is the body of an async function: `return` and top-level `await` work. Inside the script:
|
|
47
|
+
`code` is the body of an async function: `return` and top-level `await` work. Inside the script, with every sandbox:
|
|
39
48
|
|
|
40
49
|
- `tools.<name>(args)` returns a promise. Arguments and results make a JSON round trip. A tool that throws rejects with an `Error` carrying the same message. Tool names are also exposed as identifiers: characters that are not valid in identifiers become `_` (`toCodemodeIdentifier`), so `my-tool` is `tools.my_tool` as well as `tools["my-tool"]`.
|
|
41
50
|
- `ALL_TOOLS` lists `{ name, description }` for every tool, with `name` as the identifier.
|
|
42
51
|
- `text(value)` appends a text item to `result.output`; values other than strings are JSON-stringified. `console.log/info/warn/error/debug` append text items with `console: true`.
|
|
43
|
-
- `image(urlOrItem)` appends an image item. It accepts a base64 `data:` URL, `{ image_url }`, or an
|
|
52
|
+
- `image(urlOrItem)` appends an image item. It accepts a base64 `data:` URL, `{ image_url }`, or an image block (`{ type: "image", data, mimeType }`, as MCP tools and `@earendil-works/pi-ai` produce). Remote URLs are rejected.
|
|
44
53
|
- `exit()` ends the script successfully right away, keeping its output and store writes.
|
|
45
54
|
- `globals` passed to the sandbox are called as top-level functions, for example a host helper `image(ref)`. They behave like tools but are not recorded in `result.calls`. A name like `models.classify` puts the function on a frozen `models` object. With `spread: true`, `execute` receives all call arguments as an array instead of the first one, and `signature` replaces the declaration generated from the schemas.
|
|
46
55
|
- `store(key, value)` and `load(key)` read and write JSON values synchronously. See [Store](#store).
|
|
@@ -50,6 +59,24 @@ await sandbox.close();
|
|
|
50
59
|
|
|
51
60
|
`memoryLimitBytes` caps the VM's heap. Allocations beyond it fail inside the script as `InternalError: out of memory`.
|
|
52
61
|
|
|
62
|
+
Aborts, timeouts, and `close()` request worker termination without waiting for the worker to exit. On Bun, a built-in such as a long `String.prototype.indexOf` may not poll QuickJS's interrupt handler, so its worker can keep computing until the built-in returns. Stopping unrefs the worker after requesting termination, because `terminate()` refs it internally. This does not guarantee computation has stopped. On Bun 1.4.0, a pending `terminate()` can still delay host process exit despite `unref()`; cancellation results and `close()` do not wait for it.
|
|
63
|
+
|
|
64
|
+
Hosts that limit concurrency can track actual worker lifetime with `onWorkerStarted(exited)`, called for each worker started by `execute()` or `start()`. Its promise resolves when that worker exits, not when the script result settles:
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
const workers = new Set<Promise<void>>();
|
|
68
|
+
const sandbox = new CodemodeSandbox({
|
|
69
|
+
onWorkerStarted(exited) {
|
|
70
|
+
workers.add(exited);
|
|
71
|
+
void exited.then(() => workers.delete(exited));
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Keep a concurrency slot occupied until `exited` resolves. `close()` does not wait for these promises.
|
|
77
|
+
|
|
78
|
+
To enforce an admission limit, pass `acquireWorker()`. It runs synchronously after WASM loading, immediately before each worker is created. Throw to reject the execution without starting a worker; otherwise return a release callback. The sandbox calls it once on actual worker exit or if the worker constructor fails. Share reservation state across sandbox instances, and do not release it when a script result settles.
|
|
79
|
+
|
|
53
80
|
## Store
|
|
54
81
|
|
|
55
82
|
`store`/`load` let scripts keep values across executions. The sandbox does not persist anything itself: pass the current values as `options.store`, and a successful result reports what the script changed as `result.storeWrites` (`{ set, delete }`). Failed executions report no writes.
|
|
@@ -74,11 +101,11 @@ const source = await tools.read({ path: "package.json" });
|
|
|
74
101
|
text(JSON.parse(source).name);
|
|
75
102
|
```
|
|
76
103
|
|
|
77
|
-
Supported fields are `max_output_tokens`, a token budget for the output, and `timeout_ms`, a hard deadline. The sandbox does not act on them; the caller decides. The options line is replaced by an empty line, so line numbers in stack traces still match the input. Empty input, invalid JSON, unknown fields,
|
|
104
|
+
Supported fields are `max_output_tokens`, a token budget for the output, and `timeout_ms`, a hard deadline. The sandbox does not act on them; the caller decides. The options line is replaced by an empty line, so line numbers in stack traces still match the input. Empty input, invalid JSON, unknown fields, an options line without code, or an options line on any line but the first throw `CodemodeSourceError`. `CODEMODE_SOURCE_GRAMMAR` is a Lark grammar for providers that support grammar-constrained tool input. Both are also available from the lightweight `@earendil-works/pi-codemode/source` entry.
|
|
78
105
|
|
|
79
|
-
## Bundled hosts
|
|
106
|
+
## Bundled Node and Bun hosts
|
|
80
107
|
|
|
81
|
-
By default
|
|
108
|
+
By default `CodemodeSandbox` loads `quickjs-wasi/quickjs.wasm` from the installed package and starts the worker file that sits next to this package's module. Neither exists on disk when the host is bundled, so pass both:
|
|
82
109
|
|
|
83
110
|
```ts
|
|
84
111
|
import { CodemodeSandbox, loadQuickJSWasm } from "@earendil-works/pi-codemode";
|
|
@@ -96,6 +123,130 @@ const sandbox = new CodemodeSandbox({
|
|
|
96
123
|
additional build entrypoint and pass its relative source path as a string, for example
|
|
97
124
|
`"./src/codemode-worker.ts"`; Bun resolves that form from its embedded module graph.
|
|
98
125
|
|
|
126
|
+
## Usage on Cloudflare Workers
|
|
127
|
+
|
|
128
|
+
`CodemodeSandbox` needs Node or Bun. It runs each script in a worker thread and reads the QuickJS binary from disk. Cloudflare Workers have neither, and they cannot compile WebAssembly at runtime. Two other sandboxes have the same API, the same script environment, and the same `CodemodeResult`. Only where the VM runs differs:
|
|
129
|
+
|
|
130
|
+
| Sandbox | Where the VM runs | Use it for |
|
|
131
|
+
| --- | --- | --- |
|
|
132
|
+
| `CodemodeSandbox` | a worker thread | Node and Bun |
|
|
133
|
+
| `RemoteCodemodeSandbox` | another isolate, usually a Durable Object in a separate Worker | a Durable Object that runs an agent session |
|
|
134
|
+
| `InlineCodemodeSandbox` | the calling thread | anywhere else with WebAssembly, when blocking the caller is acceptable |
|
|
135
|
+
|
|
136
|
+
Import the last two from `@earendil-works/pi-codemode/portable`, which has no Node imports. On Cloudflare, `@earendil-works/pi-codemode/cloudflare` adds the deployable Durable Object and the QuickJS module compiled by Wrangler.
|
|
137
|
+
|
|
138
|
+
### Why a separate Worker
|
|
139
|
+
|
|
140
|
+
QuickJS runs synchronously, so a script that computes holds its thread until it awaits a tool. Measured on Cloudflare (October 2026), a script that computed for ten seconds delayed every other request to the session object by the full ten seconds in two placements:
|
|
141
|
+
|
|
142
|
+
- inside the session's Durable Object
|
|
143
|
+
- in a Dynamic Worker loaded by that object
|
|
144
|
+
|
|
145
|
+
In a Durable Object of a separately deployed Worker, the delay was about 50 ms. `RemoteCodemodeSandbox` therefore keeps the tools and call records in the session and sends only the VM to the sandbox Worker. Each tool call travels back to the session over Workers RPC.
|
|
146
|
+
|
|
147
|
+
### Deploying the sandbox Worker
|
|
148
|
+
|
|
149
|
+
A complete setup is in [`examples/cloudflare`](https://github.com/earendil-works/pi/tree/main/packages/codemode/examples/cloudflare). The sandbox Worker is one file:
|
|
150
|
+
|
|
151
|
+
```ts
|
|
152
|
+
// sandbox/src/index.ts
|
|
153
|
+
export { CodemodeSandboxDurableObject as CodemodeSandbox } from "@earendil-works/pi-codemode/cloudflare";
|
|
154
|
+
|
|
155
|
+
export default {
|
|
156
|
+
fetch: () => new Response("Not found", { status: 404 }),
|
|
157
|
+
};
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
```jsonc
|
|
161
|
+
// sandbox/wrangler.jsonc
|
|
162
|
+
{
|
|
163
|
+
"name": "pi-codemode-sandbox",
|
|
164
|
+
"main": "src/index.ts",
|
|
165
|
+
"compatibility_date": "2026-04-22",
|
|
166
|
+
"workers_dev": false,
|
|
167
|
+
"preview_urls": false,
|
|
168
|
+
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["CodemodeSandbox"] }],
|
|
169
|
+
"limits": { "cpu_ms": 60000 }
|
|
170
|
+
}
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
Install `@earendil-works/pi-codemode` in the sandbox Worker's project and run `npx wrangler deploy`. Wrangler bundles QuickJS (about 640 KB) as a compiled WebAssembly module. The object has no routes and keeps no state, and it never uses its storage.
|
|
174
|
+
|
|
175
|
+
### Using it from the agent's Worker
|
|
176
|
+
|
|
177
|
+
Bind the class with `script_name`. Binding a class exported from the agent's own Worker would bring back the blocking described above.
|
|
178
|
+
|
|
179
|
+
```jsonc
|
|
180
|
+
// agent/wrangler.jsonc
|
|
181
|
+
"durable_objects": {
|
|
182
|
+
"bindings": [
|
|
183
|
+
{ "name": "CODEMODE_SANDBOX", "class_name": "CodemodeSandbox", "script_name": "pi-codemode-sandbox" }
|
|
184
|
+
]
|
|
185
|
+
}
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
Then replace the sandbox. Tools, options other than the worker-specific `wasm`, `workerUrl`, `acquireWorker`, and `onWorkerStarted`, and results stay the same:
|
|
189
|
+
|
|
190
|
+
```ts
|
|
191
|
+
import type { CodemodeSandboxDurableObject } from "@earendil-works/pi-codemode/cloudflare";
|
|
192
|
+
import { RemoteCodemodeSandbox } from "@earendil-works/pi-codemode/portable";
|
|
193
|
+
|
|
194
|
+
interface Env {
|
|
195
|
+
CODEMODE_SANDBOX: DurableObjectNamespace<CodemodeSandboxDurableObject>;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// Before: new CodemodeSandbox({ tools, timeoutMs: 60_000 })
|
|
199
|
+
const sandbox = new RemoteCodemodeSandbox({
|
|
200
|
+
tools,
|
|
201
|
+
timeoutMs: 60_000,
|
|
202
|
+
remote: () => env.CODEMODE_SANDBOX.getByName(sessionId),
|
|
203
|
+
});
|
|
204
|
+
const result = await sandbox.execute(code, { signal, store });
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
Import the sandbox from `/portable` in the agent's Worker. Importing `/cloudflare` would also bundle QuickJS there. `remote` is called once per execution and picks the Durable Object that runs it.
|
|
208
|
+
|
|
209
|
+
- **One object per session**, `getByName(sessionId)`, keeps a session's scripts together. Two scripts of the same session take turns on one thread.
|
|
210
|
+
- **One object per execution**, `getByName(crypto.randomUUID())`, runs every script on its own.
|
|
211
|
+
|
|
212
|
+
Run both Workers locally with `wrangler dev -c agent/wrangler.jsonc -c sandbox/wrangler.jsonc`.
|
|
213
|
+
|
|
214
|
+
### Limits on Cloudflare
|
|
215
|
+
|
|
216
|
+
- **Interrupt budget.** While a script computes without calling a tool, no timer can run, and `Date.now()` does not advance. A script that never yields is limited only by the interrupt budget, not by `timeoutMs`. QuickJS polls an interrupt handler while it runs, and the sandbox counts the polls. Past the budget, the execution fails with `kind: "timeout"`.
|
|
217
|
+
- The default `DEFAULT_INTERRUPT_BUDGET` of 100,000 polls is about 2 seconds of a tight loop on an Apple M-series laptop and about 10 seconds on Cloudflare.
|
|
218
|
+
- Keep the budget below the Worker's `cpu_ms` limit (30 seconds by default). Hitting that limit resets the object instead of failing one script.
|
|
219
|
+
- **Memory.** Each VM may use up to 32 MiB by default. All VMs in one isolate share its 128 MB.
|
|
220
|
+
- **Changing the limits.** The Durable Object caps every request at its own limits, whatever the client asks for. To change them, subclass it in the sandbox Worker:
|
|
221
|
+
|
|
222
|
+
```ts
|
|
223
|
+
import { CodemodeSandboxDurableObject } from "@earendil-works/pi-codemode/cloudflare";
|
|
224
|
+
|
|
225
|
+
export class CodemodeSandbox extends CodemodeSandboxDurableObject {
|
|
226
|
+
protected maxInterruptBudget = 200_000;
|
|
227
|
+
protected maxMemoryLimitBytes = 64 * 1024 * 1024;
|
|
228
|
+
}
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
- **Aborts and timeouts.** `timeoutMs` and `signal` end the execution in the caller right away, with `kind: "timeout"` or `kind: "aborted"`. The remote VM stops at its next tool call. A remote VM that is computing at that moment keeps running until it calls a tool or uses up its budget.
|
|
232
|
+
- **Billing.** Each execution is one Durable Object request. The sandbox object is billed for wall-clock duration while an execution runs, including time spent waiting on tools.
|
|
233
|
+
|
|
234
|
+
### On the calling thread
|
|
235
|
+
|
|
236
|
+
When blocking the caller is acceptable, for example in a stateless Worker that serves one request, run the VM on the caller's thread instead. Nothing extra needs to be deployed:
|
|
237
|
+
|
|
238
|
+
```ts
|
|
239
|
+
import { createInlineCodemodeSandbox } from "@earendil-works/pi-codemode/cloudflare";
|
|
240
|
+
|
|
241
|
+
const sandbox = createInlineCodemodeSandbox({ tools, timeoutMs: 60_000, interruptBudget: 50_000 });
|
|
242
|
+
const result = await sandbox.execute(code);
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
`createInlineCodemodeSandbox()` passes the QuickJS module Wrangler compiled to `InlineCodemodeSandbox`. With another bundler, import `InlineCodemodeSandbox` from `/portable` and pass your own compiled module as `wasm`.
|
|
246
|
+
|
|
247
|
+
- **Blocking.** A script that computes blocks the caller until it awaits a tool or uses up its `interruptBudget`.
|
|
248
|
+
- **Stack.** QuickJS's stack guard is reduced to `INLINE_MAX_STACK_SIZE`, so that it trips before the caller's smaller stack runs out.
|
|
249
|
+
|
|
99
250
|
## Declarations for the model
|
|
100
251
|
|
|
101
252
|
Tools and globals can carry `description`, `inputSchema`, and `outputSchema` (JSON Schema). `renderDeclarations()` turns them into TypeScript declarations for a model-facing tool description:
|
|
@@ -110,7 +261,7 @@ renderDeclarations({ tools: sandbox.tools, globals: sandbox.globals });
|
|
|
110
261
|
// };
|
|
111
262
|
```
|
|
112
263
|
|
|
113
|
-
Schemas only shape the declarations; values are not validated against them. Local references (`#/$defs/...`, `#/definitions/...`) are expanded; recursive and remote references render as `unknown`.
|
|
264
|
+
Property descriptions become `//` comments. Constraints the type cannot express follow as tags, such as `// @integer @minimum 1 @default 20`; they are dropped first when a type exceeds the size limit. Schemas only shape the declarations; values are not validated against them. Local references (`#/$defs/...`, `#/definitions/...`) are expanded; recursive and remote references render as `unknown`.
|
|
114
265
|
|
|
115
266
|
## Using with pi-agent-core
|
|
116
267
|
|
|
@@ -160,6 +311,37 @@ const codemodeTool: AgentTool = {
|
|
|
160
311
|
|
|
161
312
|
`result.output` items already have the shape of `@earendil-works/pi-ai`'s `TextContent` and `ImageContent`. Calling `tool.execute()` directly skips the agent's `beforeToolCall` and `afterToolCall` hooks. To apply them to nested calls too, run each call through `runToolCall()` from `@earendil-works/pi-agent-core`, as the [mcp-codemode example](https://github.com/earendil-works/pi/tree/main/packages/agent/examples/mcp-codemode) does. That example also rejects failed nested calls inside the script and combines codemode with MCP tools.
|
|
162
313
|
|
|
314
|
+
## Deterministic runs
|
|
315
|
+
|
|
316
|
+
`sandbox.start(code, options)` runs a script so that a host can run it again after a restart and get the same behavior, for example to resume it from a durable log of its calls' results. `execute()` is unaffected.
|
|
317
|
+
|
|
318
|
+
The VM only runs when the host hands it something, and has no timers or I/O, so it is deterministic except for what it reads from its environment. `start()` fixes that:
|
|
319
|
+
|
|
320
|
+
- **Time:** `Date.now()` reads `startedAt`, then the `now` of the result being processed, never going backwards. `performance.now()` counts from `startedAt`.
|
|
321
|
+
- **Randomness:** `Math.random()` and the VM's other randomness come from `seed`.
|
|
322
|
+
- **Timezone:** UTC, whatever the host's.
|
|
323
|
+
- **Garbage collection:** `WeakRef` and `FinalizationRegistry` do not exist.
|
|
324
|
+
- **Result order:** the host answers each call with a result number (1, 2, ...), and the VM applies results strictly in that order, whatever order a transport delivers them in.
|
|
325
|
+
|
|
326
|
+
The run declares its own tools and globals, and the host answers every call itself:
|
|
327
|
+
|
|
328
|
+
```ts
|
|
329
|
+
const run = sandbox.start(code, {
|
|
330
|
+
startedAt: Date.now(),
|
|
331
|
+
seed: 7,
|
|
332
|
+
tools: [{ name: "read", description: "Read a file" }],
|
|
333
|
+
onStarted: (fingerprint) => {}, // what the VM is: engine versions, prelude hash, limits
|
|
334
|
+
onCall: (call) => {
|
|
335
|
+
// call.id is the VM's own number for the call, in the order the script made them.
|
|
336
|
+
void readFile(call.args).then((text) => run.deliver(nextResult++, Date.now(), call.id, { ok: true, value: text }));
|
|
337
|
+
},
|
|
338
|
+
onIdle: (seq, issued) => {}, // after result `seq` (0: the first run), `issued` calls in total
|
|
339
|
+
});
|
|
340
|
+
const result = await run.result;
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
A run has no deadline unless `timeoutMs` is given. Result numbers must run 1, 2, ... without gaps. The same script, `startedAt`, `seed`, tools (with their `jsName`), globals and store, answered with the same results in the same order, makes the same calls with the same arguments and produces the same output on any VM with the same fingerprint. To end a run with an error the script cannot catch, abort its `signal`.
|
|
344
|
+
|
|
163
345
|
## Results
|
|
164
346
|
|
|
165
347
|
`execute()` never rejects for script failures. `result.error.kind` is one of:
|
|
@@ -167,14 +349,16 @@ const codemodeTool: AgentTool = {
|
|
|
167
349
|
| kind | meaning |
|
|
168
350
|
| --------- | --------------------------------------------------------------------------- |
|
|
169
351
|
| `script` | the script threw or failed to parse; `stack` points at `codemode.js:<line>` |
|
|
170
|
-
| `timeout` | the deadline expired
|
|
171
|
-
| `aborted` | `options.signal` fired or `close()` was called;
|
|
172
|
-
| `sandbox` | the
|
|
352
|
+
| `timeout` | the deadline expired or the interrupt budget ran out; VM shutdown was requested |
|
|
353
|
+
| `aborted` | `options.signal` fired or `close()` was called; VM shutdown was requested |
|
|
354
|
+
| `sandbox` | the VM or its transport failed, for example a wasm trap, a missing worker file, or a failed remote |
|
|
173
355
|
|
|
174
356
|
`result.output` holds the text and image items in the order the script produced them, also for failed executions. The host keeps all of it until the script ends, so output is limited to `MAX_OUTPUT_CHARS` (16 Mi) characters of text and base64 image data and `MAX_OUTPUT_ITEMS` (100000) items. Past either limit the script fails with a `RangeError`, even if it catches the error. `result.calls` lists every tool call with `status: "ok" | "error" | "cancelled"`. A call that is still running when the script returns (not awaited) is aborted through the tool's `signal` and reported as `cancelled`.
|
|
175
357
|
|
|
176
358
|
## How it works
|
|
177
359
|
|
|
360
|
+
This section describes `CodemodeSandbox`. The other sandboxes share the same host side, prelude, and VM, and replace only the worker thread. See [Usage on Cloudflare Workers](#usage-on-cloudflare-workers).
|
|
361
|
+
|
|
178
362
|
Each `execute()` starts a worker thread (about 20 ms including VM creation) that instantiates a fresh QuickJS VM from the compiled wasm module. The VM is a separate wasm instance with its own linear memory. Its only imports are a WASI shim (clock, random, and stdout/stderr writes, which the worker discards) and one host-call entry point, so the script cannot reach the host except through the functions the worker registers.
|
|
179
363
|
|
|
180
364
|
The worker evaluates a prelude inside the VM that holds the single host bridge in a closure and builds `tools`, `console`, and globals on top of it. The script is compiled as an async function body.
|
|
@@ -185,6 +369,6 @@ The worker keeps script execution off the host thread: QuickJS runs synchronousl
|
|
|
185
369
|
|
|
186
370
|
## Runtime notes
|
|
187
371
|
|
|
188
|
-
-
|
|
372
|
+
- Node and Bun support memory limits, interrupts, and a catchable `RangeError` for deep recursion (QuickJS's stack guard is enabled; without it the wasm stack overflows and traps). Bun may delay worker exit during non-interruptible built-ins; results do not wait for exit.
|
|
189
373
|
- Stack traces use QuickJS frames (`at f (codemode.js:2:31)`), prefixed with `Name: message` like V8. The wrapper prefix shares line 1 with the script, so line numbers are exact; column numbers on line 1 are shifted.
|
|
190
374
|
- QuickJS is an interpreter. Glue code and filtering tool results are fast enough; heavy computation is slower than in V8.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var a=Object.defineProperty;var o=(e,t)=>a(e,"name",{value:t,configurable:!0});import{DurableObject as n}from"cloudflare:workers";import s from"quickjs-wasi/quickjs.wasm";import{DEFAULT_INTERRUPT_BUDGET as i,InlineCodemodeSandbox as d}from"./runtime/inline.js";import{serveCodemodeRemote as u}from"./runtime/remote.js";export*from"./portable.js";const r=s,x=32*1024*1024,T=r;function b(e={}){return new d({...e,wasm:r})}o(b,"createInlineCodemodeSandbox");class f extends n{static{o(this,"CodemodeSandboxDurableObject")}maxInterruptBudget=i;maxMemoryLimitBytes=x;execute(t,m){return u(t,m,{wasm:r,maxInterruptBudget:this.maxInterruptBudget,maxMemoryLimitBytes:this.maxMemoryLimitBytes})}}export{f as CodemodeSandboxDurableObject,x as DEFAULT_REMOTE_MEMORY_LIMIT_BYTES,T as cloudflareQuickJSWasm,b as createInlineCodemodeSandbox};
|
|
@@ -2,7 +2,6 @@ import { toCodemodeIdentifier } from "./identifier.ts";
|
|
|
2
2
|
export { toCodemodeIdentifier };
|
|
3
3
|
import type { CodemodeJsonSchema, CodemodeTool } from "./types.ts";
|
|
4
4
|
export declare const DEFAULT_INPUT_SCHEMA_MAX_CHARS = 16000;
|
|
5
|
-
export declare const MCP_TYPESCRIPT_PREAMBLE = "type Role = \"user\" | \"assistant\";\ntype MetaObject = Record<string, unknown>;\ntype Annotations = {\n audience?: Role[];\n priority?: number;\n lastModified?: string;\n};\ntype Icon = {\n src: string;\n mimeType?: string;\n sizes?: string[];\n theme?: \"light\" | \"dark\";\n};\ntype TextResourceContents = {\n uri: string;\n mimeType?: string;\n _meta?: MetaObject;\n text: string;\n};\ntype BlobResourceContents = {\n uri: string;\n mimeType?: string;\n _meta?: MetaObject;\n blob: string;\n};\ntype TextContent = {\n type: \"text\";\n text: string;\n annotations?: Annotations;\n _meta?: MetaObject;\n};\ntype ImageContent = {\n type: \"image\";\n data: string;\n mimeType: string;\n annotations?: Annotations;\n _meta?: MetaObject;\n};\ntype AudioContent = {\n type: \"audio\";\n data: string;\n mimeType: string;\n annotations?: Annotations;\n _meta?: MetaObject;\n};\ntype ResourceLink = {\n icons?: Icon[];\n name: string;\n title?: string;\n uri: string;\n description?: string;\n mimeType?: string;\n annotations?: Annotations;\n size?: number;\n _meta?: MetaObject;\n type: \"resource_link\";\n};\ntype EmbeddedResource = {\n type: \"resource\";\n resource: TextResourceContents | BlobResourceContents;\n annotations?: Annotations;\n _meta?: MetaObject;\n};\ntype ContentBlock =\n | TextContent\n | ImageContent\n | AudioContent\n | ResourceLink\n | EmbeddedResource;\ntype CallToolResult<TStructured = { [key: string]: unknown }> = {\n _meta?: MetaObject;\n content: ContentBlock[];\n isError?: boolean;\n structuredContent?: TStructured;\n [key: string]: unknown;\n};";
|
|
6
5
|
export interface RenderDeclarationsOptions {
|
|
7
6
|
tools?: readonly CodemodeTool[];
|
|
8
7
|
globals?: readonly CodemodeTool[];
|
|
@@ -14,7 +13,6 @@ export declare function renderToolSignature(tool: Pick<CodemodeTool, "name" | "i
|
|
|
14
13
|
export declare function renderToolSample(tool: Pick<CodemodeTool, "name" | "description" | "inputSchema" | "outputSchema">, options?: {
|
|
15
14
|
inputMaxChars?: number;
|
|
16
15
|
}): string;
|
|
17
|
-
export declare function mcpStructuredContentSchema(schema: CodemodeJsonSchema | undefined): CodemodeJsonSchema | undefined;
|
|
18
16
|
export declare function renderToolOutputType(schema: CodemodeJsonSchema | undefined): string;
|
|
19
17
|
export declare function schemaToType(schema: CodemodeJsonSchema, options?: {
|
|
20
18
|
maxChars?: number;
|
|
@@ -1,97 +1,22 @@
|
|
|
1
|
-
var j=Object.defineProperty;var s=(n,e)=>j(n,"name",{value:e,configurable:!0});import{toCodemodeIdentifier as
|
|
2
|
-
type MetaObject = Record<string, unknown>;
|
|
3
|
-
type Annotations = {
|
|
4
|
-
audience?: Role[];
|
|
5
|
-
priority?: number;
|
|
6
|
-
lastModified?: string;
|
|
7
|
-
};
|
|
8
|
-
type Icon = {
|
|
9
|
-
src: string;
|
|
10
|
-
mimeType?: string;
|
|
11
|
-
sizes?: string[];
|
|
12
|
-
theme?: "light" | "dark";
|
|
13
|
-
};
|
|
14
|
-
type TextResourceContents = {
|
|
15
|
-
uri: string;
|
|
16
|
-
mimeType?: string;
|
|
17
|
-
_meta?: MetaObject;
|
|
18
|
-
text: string;
|
|
19
|
-
};
|
|
20
|
-
type BlobResourceContents = {
|
|
21
|
-
uri: string;
|
|
22
|
-
mimeType?: string;
|
|
23
|
-
_meta?: MetaObject;
|
|
24
|
-
blob: string;
|
|
25
|
-
};
|
|
26
|
-
type TextContent = {
|
|
27
|
-
type: "text";
|
|
28
|
-
text: string;
|
|
29
|
-
annotations?: Annotations;
|
|
30
|
-
_meta?: MetaObject;
|
|
31
|
-
};
|
|
32
|
-
type ImageContent = {
|
|
33
|
-
type: "image";
|
|
34
|
-
data: string;
|
|
35
|
-
mimeType: string;
|
|
36
|
-
annotations?: Annotations;
|
|
37
|
-
_meta?: MetaObject;
|
|
38
|
-
};
|
|
39
|
-
type AudioContent = {
|
|
40
|
-
type: "audio";
|
|
41
|
-
data: string;
|
|
42
|
-
mimeType: string;
|
|
43
|
-
annotations?: Annotations;
|
|
44
|
-
_meta?: MetaObject;
|
|
45
|
-
};
|
|
46
|
-
type ResourceLink = {
|
|
47
|
-
icons?: Icon[];
|
|
48
|
-
name: string;
|
|
49
|
-
title?: string;
|
|
50
|
-
uri: string;
|
|
51
|
-
description?: string;
|
|
52
|
-
mimeType?: string;
|
|
53
|
-
annotations?: Annotations;
|
|
54
|
-
size?: number;
|
|
55
|
-
_meta?: MetaObject;
|
|
56
|
-
type: "resource_link";
|
|
57
|
-
};
|
|
58
|
-
type EmbeddedResource = {
|
|
59
|
-
type: "resource";
|
|
60
|
-
resource: TextResourceContents | BlobResourceContents;
|
|
61
|
-
annotations?: Annotations;
|
|
62
|
-
_meta?: MetaObject;
|
|
63
|
-
};
|
|
64
|
-
type ContentBlock =
|
|
65
|
-
| TextContent
|
|
66
|
-
| ImageContent
|
|
67
|
-
| AudioContent
|
|
68
|
-
| ResourceLink
|
|
69
|
-
| EmbeddedResource;
|
|
70
|
-
type CallToolResult<TStructured = { [key: string]: unknown }> = {
|
|
71
|
-
_meta?: MetaObject;
|
|
72
|
-
content: ContentBlock[];
|
|
73
|
-
isError?: boolean;
|
|
74
|
-
structuredContent?: TStructured;
|
|
75
|
-
[key: string]: unknown;
|
|
76
|
-
};`;function v(n){const e=[],t=n.tools??[];if(t.length>0){const r=t.map(i=>`${m(i.description,d)}${d}${k(i)}`);e.push(`declare const tools: {
|
|
1
|
+
var j=Object.defineProperty;var s=(n,e)=>j(n,"name",{value:e,configurable:!0});import{toCodemodeIdentifier as S}from"./identifier.js";const v=/^[A-Za-z_$][A-Za-z0-9_$]*$/,m=" ",T=16e3,M=32,N=["minimum","exclusiveMinimum","maximum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","format","minItems","maxItems"],w=new Set(["minimum","exclusiveMinimum","minLength","minItems"]),_=new Set(["maximum","exclusiveMaximum","maxLength","maxItems"]),h=80,k=/[\r\n\u2028\u2029]/g;function U(n){const e=[],t=n.tools??[];if(t.length>0){const r=t.map(o=>`${A(o.description,m)}${m}${x(o)}`);e.push(`declare const tools: {
|
|
77
2
|
${r.join(`
|
|
78
3
|
`)}
|
|
79
|
-
};`)}const
|
|
80
|
-
${
|
|
4
|
+
};`)}const u=new Map;for(const r of n.globals??[]){const o=r.name.indexOf(".");if(o===-1){e.push(O(`declare function ${r.name}`,r,""));continue}const p=r.name.slice(0,o),f=u.get(p)??[];f.length===0&&u.set(p,f),f.push(O(r.name.slice(o+1),r,m))}for(const[r,o]of u)e.push(`declare const ${r}: {
|
|
5
|
+
${o.join(`
|
|
81
6
|
`)}
|
|
82
7
|
};`);return e.join(`
|
|
83
8
|
|
|
84
|
-
`)}s(
|
|
9
|
+
`)}s(U,"renderDeclarations");function x(n,e={}){const t=n.inputSchema===void 0?"unknown":y(n.inputSchema,{maxChars:e.inputMaxChars??T});return`${S(n.name)}(args: ${t}): Promise<${E(n.outputSchema)}>;`}s(x,"renderToolSignature");function B(n,e={}){const t=`declare const tools: { ${x(n,e)} };`;return`${n.description?.trim()??""}
|
|
85
10
|
|
|
86
11
|
codemode tool declaration:
|
|
87
12
|
\`\`\`ts
|
|
88
13
|
${t}
|
|
89
|
-
\`\`\``}s(B,"renderToolSample");function
|
|
14
|
+
\`\`\``}s(B,"renderToolSample");function E(n){return n===void 0?"unknown":y(n)}s(E,"renderToolOutputType");function O(n,e,t){if(e.signature!==void 0)return`${A(e.description,t)}${t}${n}${e.signature};`;const u=e.inputSchema===void 0?"unknown":y(e.inputSchema),r=e.outputSchema===void 0?"unknown":y(e.outputSchema);return`${A(e.description,t)}${t}${n}(args: ${u}): Promise<${r}>;`}s(O,"renderGlobal");function A(n,e){const t=n?.trim();if(!t)return"";const u=t.replaceAll("*/","*\\/").split(/\r?\n/);return u.length===1?`${e}/** ${u[0]} */
|
|
90
15
|
`:`${e}/**
|
|
91
|
-
${
|
|
16
|
+
${u.map(r=>`${e} *${r?` ${r}`:""}`).join(`
|
|
92
17
|
`)}
|
|
93
18
|
${e} */
|
|
94
|
-
`}s(
|
|
19
|
+
`}s(A,"docComment");function C(n){return v.test(n)?n:JSON.stringify(n)}s(C,"propertyKey");function g(n){const e=[...new Set(n)];return e.includes("unknown")?"unknown":e.length===0?"never":e.join(" | ")}s(g,"union");function y(n,e={}){const t=s(o=>c(n,{root:n,resolving:new Set,expansions:0,tags:o}),"render"),u=t(!0);if(e.maxChars===void 0||u.length<=e.maxChars)return u;const r=t(!1);return r.length<=e.maxChars?r:"unknown"}s(y,"schemaToType");function R(n,e){if(n!=="#"&&!n.startsWith("#/"))return;let t=e;for(const u of n.slice(2).split("/").filter(Boolean)){const r=decodeURIComponent(u).replaceAll("~1","/").replaceAll("~0","~");if(typeof t!="object"||t===null||Array.isArray(t)||!(r in t))return;t=t[r]}return typeof t=="boolean"||typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}s(R,"resolveRef");function c(n,e){if(n===!0)return"unknown";if(n===!1)return"never";if(typeof n!="object"||n===null||Array.isArray(n))return"unknown";if(typeof n.$ref=="string"){const r=n.$ref;if(e.resolving.has(r)||e.expansions>=M)return"unknown";const o=R(r,e.root);if(o===void 0)return"unknown";e.expansions++,e.resolving.add(r);try{return c(o,e)}finally{e.resolving.delete(r)}}if("const"in n)return JSON.stringify(n.const)??"unknown";if(Array.isArray(n.enum))return g(n.enum.map(r=>JSON.stringify(r)??"unknown"));const t=Array.isArray(n.anyOf)?n.anyOf:Array.isArray(n.oneOf)?n.oneOf:void 0;if(t)return g(t.map(r=>c(r,e)));if(Array.isArray(n.allOf)){const r=n.allOf.map(o=>c(o,e)).filter(o=>o!=="unknown");return r.length===0?"unknown":r.map(o=>o.includes(" | ")?`(${o})`:o).join(" & ")}const u=n.type;if(Array.isArray(u))return g(u.map(r=>c({...n,type:r},e)));switch(u){case"string":return"string";case"number":case"integer":return"number";case"boolean":return"boolean";case"null":return"null";case"array":return b(n,e);case"object":return I(n,e);case void 0:return"properties"in n||"additionalProperties"in n||"required"in n?I(n,e):"items"in n||"prefixItems"in n?b(n,e):"unknown";default:return"unknown"}}s(c,"toType");function b(n,e){if(n.items!==void 0&&!Array.isArray(n.items))return`Array<${c(n.items,e)}>`;const t=Array.isArray(n.prefixItems)?n.prefixItems:Array.isArray(n.items)?n.items:[];return t.length>0?`[${t.map(u=>c(u,e)).join(", ")}]`:"unknown[]"}s(b,"arrayType");function P(n){const e=n?.description;return typeof e=="string"?e.trim():""}s(P,"descriptionOf");function q(n){if(typeof n!="object"||n===null||Array.isArray(n))return"";const e=n,t=Array.isArray(e.anyOf)?e.anyOf:e.oneOf,u=Array.isArray(t)?t.filter(i=>i?.type!=="null"):[],r=u.length===1?u[0]:void 0,p=(typeof r=="object"&&r!==null&&!Array.isArray(r)?[e,r]:[e]).map(i=>({...i,...i.exclusiveMinimum===!0?{minimum:void 0,exclusiveMinimum:i.minimum}:{},...i.exclusiveMaximum===!0?{maximum:void 0,exclusiveMaximum:i.maximum}:{}})),f=[],d=s(i=>i==="integer"||Array.isArray(i)&&i.includes("integer"),"isInteger");p.some(i=>d(i.type))&&f.push("@integer");for(const i of N){const l=p.map(a=>a[i]);if(w.has(i)||_.has(i)){const a=l.filter($=>typeof $=="number");if(a.length===0)continue;f.push(`@${i} ${w.has(i)?Math.max(...a):Math.min(...a)}`);continue}for(const a of new Set(l))(typeof a=="number"||typeof a=="string")&&f.push(`@${i} ${a}`)}return p.some(i=>i.uniqueItems===!0)&&f.push("@uniqueItems"),e.default!==void 0&&e.default!==null&&f.push(`@default ${JSON.stringify(e.default)}`),e.deprecated===!0&&f.push("@deprecated"),f.filter(i=>i.length<=h).map(i=>i.replace(k,l=>`\\u${l.charCodeAt(0).toString(16).padStart(4,"0")}`)).join(" ")}s(q,"constraintTags");function I(n,e){const t=typeof n.properties=="object"&&n.properties!==null&&!Array.isArray(n.properties)?n.properties:{},u=new Set(Array.isArray(n.required)?n.required:[]),r=Object.keys(t).sort(),o=r.map(i=>{const l=u.has(i)?"":"?";return`${C(i)}${l}: ${c(t[i],e)};`}),p=n.additionalProperties;if(p!==void 0&&p!==!1){const i=p===!0?"unknown":c(p,e);o.push(`[key: string]: ${i};`)}else p===void 0&&r.length===0&&o.push("[key: string]: unknown;");if(o.length===0)return"{}";const f=r.map(i=>{const l=P(t[i]).split(k).map($=>$.trim()).filter(Boolean),a=e.tags?q(t[i]):"";return a?[...l,a]:l});if(!f.some(i=>i.length>0))return`{ ${o.join(" ")} }`;const d=["{"];f.forEach((i,l)=>{for(const a of i)d.push(`${m}// ${a}`);d.push(`${m}${o[l].replaceAll(`
|
|
95
20
|
`,`
|
|
96
|
-
${
|
|
97
|
-
`)}s(
|
|
21
|
+
${m}`)}`)});for(const i of o.slice(r.length))d.push(`${m}${i}`);return d.push("}"),d.join(`
|
|
22
|
+
`)}s(I,"objectType");export{T as DEFAULT_INPUT_SCHEMA_MAX_CHARS,U as renderDeclarations,E as renderToolOutputType,B as renderToolSample,x as renderToolSignature,y as schemaToType,S as toCodemodeIdentifier};
|
|
@@ -1,7 +1,10 @@
|
|
|
1
|
-
export { DEFAULT_INPUT_SCHEMA_MAX_CHARS,
|
|
1
|
+
export { DEFAULT_INPUT_SCHEMA_MAX_CHARS, type RenderDeclarationsOptions, renderDeclarations, renderToolOutputType, renderToolSample, renderToolSignature, schemaToType, } from "./declarations.ts";
|
|
2
2
|
export { toCodemodeIdentifier } from "./identifier.ts";
|
|
3
|
+
export { CodemodeSandboxBase } from "./runtime/execution.ts";
|
|
3
4
|
export { CodemodeSandbox } from "./runtime/host.ts";
|
|
5
|
+
export { DEFAULT_INTERRUPT_BUDGET, InlineCodemodeSandbox, type InlineCodemodeSandboxOptions, } from "./runtime/inline.ts";
|
|
4
6
|
export { MAX_OUTPUT_CHARS, MAX_OUTPUT_ITEMS, MAX_STORE_TOTAL_CHARS, MAX_STORE_VALUE_CHARS, } from "./runtime/prelude-source.ts";
|
|
7
|
+
export { type CodemodeRemote, type CodemodeRemoteExchange, type CodemodeRemoteMessage, type CodemodeRemoteReply, type CodemodeRemoteRequest, type CodemodeServeOptions, RemoteCodemodeSandbox, type RemoteCodemodeSandboxOptions, serveCodemodeRemote, } from "./runtime/remote.ts";
|
|
5
8
|
export { CODEMODE_OPTIONS_PREFIX, CODEMODE_SOURCE_GRAMMAR, CodemodeSourceError, type CodemodeSourceOptions, type ParsedCodemodeSource, parseCodemodeSource, } from "./source.ts";
|
|
6
|
-
export type { CodemodeCall, CodemodeCallStatus, CodemodeError, CodemodeErrorKind, CodemodeExecuteOptions, CodemodeJsonSchema, CodemodeOutputItem, CodemodeResult, CodemodeSandboxOptions, CodemodeStoreWrites, CodemodeTool, CodemodeToolContext, } from "./types.ts";
|
|
9
|
+
export type { CodemodeCall, CodemodeCallStatus, CodemodeDeclaredGlobal, CodemodeDeclaredTool, CodemodeDuring, CodemodeError, CodemodeErrorKind, CodemodeExecuteOptions, CodemodeHostCall, CodemodeJsonSchema, CodemodeOutcome, CodemodeOutputItem, CodemodeResult, CodemodeRun, CodemodeRunOptions, CodemodeSandboxBaseOptions, CodemodeSandboxOptions, CodemodeStoreWrites, CodemodeTool, CodemodeToolContext, } from "./types.ts";
|
|
7
10
|
export { type CodemodeWasmModule, loadQuickJSWasm } from "./wasm.ts";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{DEFAULT_INPUT_SCHEMA_MAX_CHARS as r,
|
|
1
|
+
import{DEFAULT_INPUT_SCHEMA_MAX_CHARS as r,renderDeclarations as d,renderToolOutputType as m,renderToolSample as T,renderToolSignature as _,schemaToType as S}from"./declarations.js";import{toCodemodeIdentifier as A}from"./identifier.js";import{CodemodeSandboxBase as E}from"./runtime/execution.js";import{CodemodeSandbox as R}from"./runtime/host.js";import{DEFAULT_INTERRUPT_BUDGET as n,InlineCodemodeSandbox as x}from"./runtime/inline.js";import{MAX_OUTPUT_CHARS as M,MAX_OUTPUT_ITEMS as U,MAX_STORE_TOTAL_CHARS as f,MAX_STORE_VALUE_CHARS as D}from"./runtime/prelude-source.js";import{RemoteCodemodeSandbox as I,serveCodemodeRemote as i}from"./runtime/remote.js";import{CODEMODE_OPTIONS_PREFIX as u,CODEMODE_SOURCE_GRAMMAR as P,CodemodeSourceError as X,parseCodemodeSource as c}from"./source.js";import{loadQuickJSWasm as b}from"./wasm.js";export{u as CODEMODE_OPTIONS_PREFIX,P as CODEMODE_SOURCE_GRAMMAR,R as CodemodeSandbox,E as CodemodeSandboxBase,X as CodemodeSourceError,r as DEFAULT_INPUT_SCHEMA_MAX_CHARS,n as DEFAULT_INTERRUPT_BUDGET,x as InlineCodemodeSandbox,M as MAX_OUTPUT_CHARS,U as MAX_OUTPUT_ITEMS,f as MAX_STORE_TOTAL_CHARS,D as MAX_STORE_VALUE_CHARS,I as RemoteCodemodeSandbox,b as loadQuickJSWasm,c as parseCodemodeSource,d as renderDeclarations,m as renderToolOutputType,T as renderToolSample,_ as renderToolSignature,S as schemaToType,i as serveCodemodeRemote,A as toCodemodeIdentifier};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toCodemodeIdentifier as d}from"./identifier.js";import{CodemodeSandboxBase as m}from"./runtime/execution.js";import{DEFAULT_INTERRUPT_BUDGET as _,InlineCodemodeSandbox as A}from"./runtime/inline.js";import{MAX_OUTPUT_CHARS as R,MAX_OUTPUT_ITEMS as S,MAX_STORE_TOTAL_CHARS as x,MAX_STORE_VALUE_CHARS as C}from"./runtime/prelude-source.js";import{RemoteCodemodeSandbox as E,serveCodemodeRemote as f}from"./runtime/remote.js";export{m as CodemodeSandboxBase,_ as DEFAULT_INTERRUPT_BUDGET,A as InlineCodemodeSandbox,R as MAX_OUTPUT_CHARS,S as MAX_OUTPUT_ITEMS,x as MAX_STORE_TOTAL_CHARS,C as MAX_STORE_VALUE_CHARS,E as RemoteCodemodeSandbox,f as serveCodemodeRemote,d as toCodemodeIdentifier};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { CodemodeError, CodemodeExecuteOptions, CodemodeResult, CodemodeRun, CodemodeRunOptions, CodemodeSandboxBaseOptions, CodemodeTool } from "../types.ts";
|
|
2
|
+
import { type HostToWorkerMessage, type VmStartData } from "./protocol.ts";
|
|
3
|
+
export interface VmEvents {
|
|
4
|
+
message(message: unknown): void;
|
|
5
|
+
failure(error: CodemodeError): void;
|
|
6
|
+
}
|
|
7
|
+
export interface VmChannel {
|
|
8
|
+
post(message: HostToWorkerMessage): void;
|
|
9
|
+
stop(): Promise<void>;
|
|
10
|
+
}
|
|
11
|
+
export type VmLauncher = (data: VmStartData, events: VmEvents) => VmChannel | Promise<VmChannel>;
|
|
12
|
+
export declare function errorMessage(error: unknown): string;
|
|
13
|
+
export declare class CodemodeSandboxBase {
|
|
14
|
+
private readonly toolsByName;
|
|
15
|
+
private readonly globalsByName;
|
|
16
|
+
private readonly timeoutMs;
|
|
17
|
+
private readonly memoryLimitBytes;
|
|
18
|
+
private readonly launch;
|
|
19
|
+
private readonly running;
|
|
20
|
+
private closed;
|
|
21
|
+
constructor(options: CodemodeSandboxBaseOptions, launch: VmLauncher);
|
|
22
|
+
registerTool(tool: CodemodeTool): void;
|
|
23
|
+
unregisterTool(name: string): boolean;
|
|
24
|
+
get tools(): CodemodeTool[];
|
|
25
|
+
get globals(): CodemodeTool[];
|
|
26
|
+
execute(code: string, options?: CodemodeExecuteOptions): Promise<CodemodeResult>;
|
|
27
|
+
start(code: string, options: CodemodeRunOptions): CodemodeRun;
|
|
28
|
+
close(): Promise<void>;
|
|
29
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var v=Object.defineProperty;var d=(o,e)=>v(o,"name",{value:e,configurable:!0});import{toCodemodeIdentifier as w}from"../identifier.js";import{isWorkerToHostMessage as k}from"./protocol.js";const S=3e5,E=/^[A-Za-z_$][A-Za-z0-9_$]*$/,N=new Set(["tools","ALL_TOOLS","console","text","image","exit","globalThis","store","load"]);function g(o){return o instanceof Error?o.message:String(o)}d(g,"errorMessage");function p(o){const e={};for(const[s,r]of Object.entries(o??{})){const t=JSON.stringify(r);t!==void 0&&(e[s]=t)}return e}d(p,"serializeStore");class c extends Error{static{d(this,"BridgeError")}}function u(o,e){try{return JSON.parse(o)}catch{throw new c(`${e} is not valid JSON`)}}d(u,"parseBridgeJson");function x(o){const e=u(o,"store writes");if(!Array.isArray(e))throw new c("store writes are not an array");const s={set:{},delete:[]};for(const r of e){if(!Array.isArray(r)||typeof r[0]!="string"||(r.length===2?typeof r[1]!="string":r.length!==1))throw new c("store writes contain a malformed entry");const[t,n]=r;n===void 0?s.delete.push(t):s.set[t]=u(n,`store value for ${JSON.stringify(t)}`)}return s}d(x,"parseStoreWrites");function M(o){const e=u(o,"script error");if(typeof e!="object"||e===null)throw new c("script error is not an object");const{name:s,message:r,stack:t}=e;if(typeof r!="string"||s!==void 0&&typeof s!="string"||t!==void 0&&typeof t!="string")throw new c("script error is malformed");return{kind:"script",name:s,message:r,stack:t}}d(M,"parseScriptError");function b(o){const e=new Set,s=new Set;for(const r of o){const t=r.name.split(".");if(t.length>2||!t.every(n=>E.test(n))||N.has(t[0]))throw new Error(`Invalid global name "${r.name}"`);if(e.has(r.name))throw new Error(`Global "${r.name}" is already registered`);t.length===2&&s.add(t[0]),e.add(r.name)}for(const r of s)if(e.has(r))throw new Error(`Global "${r}" conflicts with the namespace "${r}"`)}d(b,"checkGlobals");class y{static{d(this,"Execution")}promise;resolveResult;channel;unsent=[];executors;control;delivered=new Set;signal;timer;output=[];calls=[];pending=new Map;finished=!1;constructor(e){if(this.promise=new Promise(t=>{this.resolveResult=t}),this.executors=e.executors,this.control=e.control,this.signal=e.signal,Number.isFinite(e.timeoutMs)&&(this.timer=setTimeout(()=>{this.finish({kind:"timeout",message:`Execution timed out after ${e.timeoutMs} ms`})},e.timeoutMs)),e.signal&&(e.signal.aborted?this.onAbort():e.signal.addEventListener("abort",this.onAbort,{once:!0})),this.finished)return;const s={code:e.code,tools:e.tools.map(t=>({name:t.name,jsName:t.jsName??w(t.name),description:t.description??""})),globals:e.globals.map(t=>({name:t.name,spread:t.spread===!0})),memoryLimitBytes:e.memoryLimitBytes,store:e.store,...e.deterministic?{deterministic:e.deterministic}:{}},r={message:d(t=>this.receive(t),"message"),failure:d(t=>this.finish(t),"failure")};new Promise(t=>t(e.launch(s,r))).then(t=>{if(this.finished){t.stop().catch(()=>{});return}this.channel=t;for(const n of this.unsent.splice(0))t.post(n)},t=>{this.finish({kind:"sandbox",message:g(t)})})}deliver(e,s,r,t){if(this.finished)return;if(!Number.isFinite(s))throw new Error(`The clock value of result ${e} is not a finite number`);if(!Number.isInteger(e)||e<1||this.delivered.has(e))throw new Error(`Result number ${e} is not a positive integer used once`);const n=this.pending.get(r);if(n===void 0)throw new Error(`Call ${r} is not waiting for a result`);if(!t.ok&&t.properties!==void 0){const{properties:i}=t;if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`The properties of result ${e} are not an object`)}const a=t.ok?t.value===void 0?void 0:JSON.stringify(t.value):t.message,l=!t.ok&&t.properties!==void 0?JSON.stringify(t.properties):void 0;this.delivered.add(e),this.pending.delete(r),n.record&&(n.record.status=t.ok?"ok":"error",n.record.durationMs=performance.now()-n.startedAt),this.post({type:"result",id:r,ok:t.ok,payload:a,seq:e,now:s,...l===void 0?{}:{properties:l}})}abort(e){return this.finish({kind:"aborted",message:e}),this.promise}onAbort=d(()=>{const e=this.signal?.reason;this.finish({kind:"aborted",message:e instanceof Error?e.message:"Execution aborted"})},"onAbort");post(e){this.channel?this.channel.post(e):this.unsent.push(e)}receive(e){try{this.handleMessage(e)}catch(s){this.finish({kind:"sandbox",message:s instanceof c?`Sandbox bridge broken: ${s.message}. The script may have modified built-ins such as a prototype's toJSON.`:`Sandbox host failed: ${g(s)}`})}}handleMessage(e){if(!this.finished){if(!k(e))throw new c("unknown message from the worker");switch(e.type){case"output":this.output.push(e.item);break;case"call":if(this.pending.has(e.id))throw new c(`duplicate call id ${e.id}`);this.control?this.forwardCall(e,this.control):this.handleCall(e);break;case"started":this.control?.onStarted?.(e.fingerprint);break;case"idle":this.control?.onIdle?.(e.seq,e.issued);break;case"done":this.handleDone(e);break;case"crash":this.finish({kind:"sandbox",message:e.message});break}}}handleDone(e){if(!e.ok){this.finish(M(e.error),void 0,void 0,e.during);return}const s=e.value===void 0?void 0:u(e.value,"return value");this.finish(void 0,s,x(e.writes),e.during)}forwardCall(e,s){const{id:r,name:t,target:n}=e,a=e.args===void 0?void 0:u(e.args,"call arguments"),l=n==="tool"?{name:t,status:"cancelled",durationMs:0}:void 0;l&&this.calls.push(l),this.pending.set(r,{record:l,startedAt:performance.now(),controller:new AbortController}),s.onCall({id:r,target:n,name:t,args:a})}async handleCall(e){const{id:s,name:r}=e,t=e.target==="tool",n=t?{name:r,status:"cancelled",durationMs:0}:void 0;n&&this.calls.push(n);const a={record:n,startedAt:performance.now(),controller:new AbortController};this.pending.set(s,a);let l,i;try{const h=(t?this.executors.tools:this.executors.globals).get(r);if(!h)throw new Error(`Unknown ${t?"tool":"global"} "${r}"`);const m=e.args===void 0?void 0:JSON.parse(e.args),f=await h.execute(m,{signal:a.controller.signal});i={type:"result",id:s,ok:!0,payload:f===void 0?void 0:JSON.stringify(f)},l="ok"}catch(h){i={type:"result",id:s,ok:!1,payload:g(h)},l="error"}this.pending.delete(s)&&(n&&(n.status=l,n.durationMs=performance.now()-a.startedAt),this.post(i))}finish(e,s,r,t){if(this.finished)return;this.finished=!0,clearTimeout(this.timer),this.signal?.removeEventListener("abort",this.onAbort);const n=performance.now();for(const i of this.pending.values())i.record&&(i.record.durationMs=n-i.startedAt),i.controller.abort();this.pending.clear(),this.unsent=[];const a=t===void 0?{}:{during:{seq:t.seq,issued:t.issued}},l=e?{ok:!1,error:e,output:this.output,calls:this.calls,...a}:{ok:!0,value:s,output:this.output,calls:this.calls,storeWrites:r??{set:{},delete:[]},...a};if(!this.channel){this.resolveResult(l);return}this.channel.stop().catch(()=>{}).then(()=>this.resolveResult(l))}}class ${static{d(this,"CodemodeSandboxBase")}toolsByName=new Map;globalsByName=new Map;timeoutMs;memoryLimitBytes;launch;running=new Set;closed=!1;constructor(e,s){this.timeoutMs=e.timeoutMs??S,this.memoryLimitBytes=e.memoryLimitBytes,this.launch=s;for(const r of e.tools??[])this.registerTool(r);b(e.globals??[]);for(const r of e.globals??[])this.globalsByName.set(r.name,r)}registerTool(e){if(this.toolsByName.has(e.name))throw new Error(`Tool "${e.name}" is already registered`);this.toolsByName.set(e.name,e)}unregisterTool(e){return this.toolsByName.delete(e)}get tools(){return[...this.toolsByName.values()]}get globals(){return[...this.globalsByName.values()]}execute(e,s={}){if(this.closed)return Promise.reject(new Error("Sandbox is closed"));const r=new Map(this.toolsByName),t=new y({code:e,tools:[...r.values()],globals:[...this.globalsByName.values()],executors:{tools:r,globals:this.globalsByName},timeoutMs:s.timeoutMs??this.timeoutMs,signal:s.signal,memoryLimitBytes:this.memoryLimitBytes,store:p(s.store),launch:this.launch});return this.running.add(t),t.promise.finally(()=>this.running.delete(t))}start(e,s){if(this.closed)throw new Error("Sandbox is closed");if(!Number.isFinite(s.startedAt)||s.startedAt<0)throw new Error("startedAt must be a non-negative number of milliseconds since the epoch");if(!Number.isInteger(s.seed)||s.seed<0||s.seed>4294967295)throw new Error("seed must be a 32-bit unsigned integer");const r=s.tools??[];if(new Set(r.map(i=>i.name)).size!==r.length)throw new Error("Tool names must be unique");const t=r.map(i=>i.jsName??w(i.name));if(new Set(t).size!==r.length)throw new Error("Tool script names must be unique");const n=s.globals??[];b(n);const a=new y({code:e,tools:r,globals:n,executors:{tools:new Map,globals:new Map},timeoutMs:s.timeoutMs??Number.POSITIVE_INFINITY,signal:s.signal,memoryLimitBytes:this.memoryLimitBytes,store:p(s.store),deterministic:{startedAt:s.startedAt,seed:s.seed},control:{onStarted:s.onStarted,onCall:s.onCall,onIdle:s.onIdle},launch:this.launch});return this.running.add(a),{result:a.promise.finally(()=>this.running.delete(a)),deliver:d((i,h,m,f)=>a.deliver(i,h,m,f),"deliver"),get finished(){return a.finished}}}async close(){this.closed=!0,await Promise.all([...this.running].map(e=>e.abort("Sandbox closed")))}}export{$ as CodemodeSandboxBase,g as errorMessage};
|
|
@@ -1,18 +1,5 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
private readonly globalsByName;
|
|
5
|
-
private readonly timeoutMs;
|
|
6
|
-
private readonly memoryLimitBytes;
|
|
7
|
-
private readonly wasm;
|
|
8
|
-
private readonly workerUrl;
|
|
9
|
-
private readonly running;
|
|
10
|
-
private closed;
|
|
1
|
+
import type { CodemodeSandboxOptions } from "../types.ts";
|
|
2
|
+
import { CodemodeSandboxBase } from "./execution.ts";
|
|
3
|
+
export declare class CodemodeSandbox extends CodemodeSandboxBase {
|
|
11
4
|
constructor(options?: CodemodeSandboxOptions);
|
|
12
|
-
registerTool(tool: CodemodeTool): void;
|
|
13
|
-
unregisterTool(name: string): boolean;
|
|
14
|
-
get tools(): CodemodeTool[];
|
|
15
|
-
get globals(): CodemodeTool[];
|
|
16
|
-
execute(code: string, options?: CodemodeExecuteOptions): Promise<CodemodeResult>;
|
|
17
|
-
close(): Promise<void>;
|
|
18
5
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var m=Object.defineProperty;var n=(o,t)=>m(o,"name",{value:t,configurable:!0});import{Worker as l}from"node:worker_threads";import{loadQuickJSWasm as f}from"../wasm.js";import{CodemodeSandboxBase as k,errorMessage as c}from"./execution.js";function h(){return new URL(import.meta.url.endsWith(".ts")?"./worker.ts":"./worker.js",import.meta.url)}n(h,"defaultWorkerUrl");function p(o){return async(t,a)=>{let s;try{s=await(o.wasm??f())}catch(r){throw new Error(`Failed to load QuickJS: ${c(r)}`)}const d=new SharedArrayBuffer(4),w={...t,wasm:s,interrupt:d},i=o.acquireWorker?.();let e;try{e=new l(o.workerUrl??h(),{workerData:w})}catch(r){throw i?.(),new Error(`Failed to start worker: ${c(r)}`)}i&&e.once("exit",i),e.on("message",r=>{typeof r=="object"&&r!==null&&("watch:import"in r||"watch:require"in r)||a.message(r)}),e.on("error",r=>{a.failure({kind:"sandbox",name:r instanceof Error?r.name:void 0,message:c(r)})}),e.on("exit",r=>{a.failure({kind:"sandbox",message:`Worker exited with code ${r} before the script settled`})});const u=n(async()=>{Atomics.store(new Int32Array(d),0,1),e.terminate().catch(()=>{}),e.unref()},"stop");try{o.onWorkerStarted?.(new Promise(r=>e.once("exit",()=>r())))}catch(r){throw u(),r}return{post:n(r=>e.postMessage(r),"post"),stop:u}}}n(p,"workerLauncher");class S extends k{static{n(this,"CodemodeSandbox")}constructor(t={}){super(t,p(t))}}export{S as CodemodeSandbox};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { CodemodeSandboxBaseOptions } from "../types.ts";
|
|
2
|
+
import type { CodemodeWasmModule } from "../wasm.ts";
|
|
3
|
+
import { CodemodeSandboxBase, type VmLauncher } from "./execution.ts";
|
|
4
|
+
export declare const DEFAULT_INTERRUPT_BUDGET = 100000;
|
|
5
|
+
export declare const INLINE_MAX_STACK_SIZE: number;
|
|
6
|
+
export interface InlineCodemodeSandboxOptions extends CodemodeSandboxBaseOptions {
|
|
7
|
+
wasm: CodemodeWasmModule | Promise<CodemodeWasmModule>;
|
|
8
|
+
interruptBudget?: number;
|
|
9
|
+
}
|
|
10
|
+
export declare function inlineLauncher(wasm: CodemodeWasmModule | Promise<CodemodeWasmModule>, interruptBudget?: number): VmLauncher;
|
|
11
|
+
export declare class InlineCodemodeSandbox extends CodemodeSandboxBase {
|
|
12
|
+
constructor(options: InlineCodemodeSandboxOptions);
|
|
13
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var p=Object.defineProperty;var r=(n,e)=>p(n,"name",{value:e,configurable:!0});import{CodemodeSandboxBase as m,errorMessage as x}from"./execution.js";import{startVm as h}from"./vm.js";const y=1e5,E=256*1024;function S(n,e=y){return async(c,u)=>{let i;try{i=await n}catch(t){throw new Error(`Failed to load QuickJS: ${x(t)}`)}let o=!1,s=!1,f=0,a=!1;const l=await h({data:c,wasm:i,maxStackSize:E,interruptBudget:e,shouldInterrupt:r(()=>o||s||a?!0:++f<=e?!1:(a=!0,!0),"shouldInterrupt"),post:r(t=>{const d=t.type==="done"||t.type==="crash";d&&s||(d&&(s=!0),queueMicrotask(()=>{if(!o){if(a&&(t.type==="done"||t.type==="crash")){u.failure({kind:"timeout",message:`Execution exceeded its interrupt budget of ${e}`});return}u.message(t)}}))},"post")});return{post:r(t=>{o||l.deliver(t)},"post"),stop:r(async()=>{o||(o=!0,l.dispose())},"stop")}}}r(S,"inlineLauncher");class T extends m{static{r(this,"InlineCodemodeSandbox")}constructor(e){super(e,S(e.wasm,e.interruptBudget))}}export{y as DEFAULT_INTERRUPT_BUDGET,E as INLINE_MAX_STACK_SIZE,T as InlineCodemodeSandbox,S as inlineLauncher};
|