@mastra/code-sdk 0.0.0-agent-tags-alpha-20261125185303
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/LICENSE.md +32 -0
- package/README.md +284 -0
- package/dist/acp/agent.d.ts +48 -0
- package/dist/acp/agent.js +414 -0
- package/dist/acp/errors.d.ts +3 -0
- package/dist/acp/errors.js +11 -0
- package/dist/acp/event-mapper.d.ts +28 -0
- package/dist/acp/event-mapper.js +274 -0
- package/dist/acp/index.d.ts +9 -0
- package/dist/acp/index.js +21 -0
- package/dist/acp/runtime.d.ts +5 -0
- package/dist/acp/runtime.js +91 -0
- package/dist/acp/server.d.ts +4 -0
- package/dist/acp/server.js +35 -0
- package/dist/acp/skills.d.ts +6 -0
- package/dist/acp/skills.js +30 -0
- package/dist/acp.d.ts +2 -0
- package/dist/acp.js +1 -0
- package/dist/agent-connections/messaging-processor.d.ts +17 -0
- package/dist/agent-connections/messaging-processor.js +131 -0
- package/dist/agent-connections/ownership.d.ts +24 -0
- package/dist/agent-connections/ownership.js +96 -0
- package/dist/agent-connections/registry.d.ts +20 -0
- package/dist/agent-connections/registry.js +167 -0
- package/dist/agent-connections/session-advertisement.d.ts +27 -0
- package/dist/agent-connections/session-advertisement.js +86 -0
- package/dist/agent-connections/signal-provider.d.ts +141 -0
- package/dist/agent-connections/signal-provider.js +35 -0
- package/dist/agent-connections/state-processor.d.ts +23 -0
- package/dist/agent-connections/state-processor.js +270 -0
- package/dist/agent-connections/thread-state.d.ts +41 -0
- package/dist/agent-connections/thread-state.js +157 -0
- package/dist/agent-connections/tools.d.ts +133 -0
- package/dist/agent-connections/tools.js +616 -0
- package/dist/agent-connections/types.d.ts +99 -0
- package/dist/agent-connections/types.js +4 -0
- package/dist/agent-connections/untrusted-text.d.ts +5 -0
- package/dist/agent-connections/untrusted-text.js +19 -0
- package/dist/agents/background-completion-events.d.ts +16 -0
- package/dist/agents/background-completion-events.js +16 -0
- package/dist/agents/background-completion.d.ts +22 -0
- package/dist/agents/background-completion.js +73 -0
- package/dist/agents/context-audit.d.ts +84 -0
- package/dist/agents/context-audit.js +115 -0
- package/dist/agents/credential-resolver.d.ts +74 -0
- package/dist/agents/credential-resolver.js +142 -0
- package/dist/agents/custom-provider-source.d.ts +35 -0
- package/dist/agents/custom-provider-source.js +22 -0
- package/dist/agents/fastembed-subprocess.d.ts +52 -0
- package/dist/agents/fastembed-subprocess.js +282 -0
- package/dist/agents/instructions.d.ts +42 -0
- package/dist/agents/instructions.js +69 -0
- package/dist/agents/mastracode-gateway.d.ts +85 -0
- package/dist/agents/mastracode-gateway.js +500 -0
- package/dist/agents/memory.d.ts +36 -0
- package/dist/agents/memory.js +248 -0
- package/dist/agents/model.d.ts +158 -0
- package/dist/agents/model.js +382 -0
- package/dist/agents/modes/build.d.ts +12 -0
- package/dist/agents/modes/build.js +33 -0
- package/dist/agents/modes/explore.d.ts +10 -0
- package/dist/agents/modes/explore.js +25 -0
- package/dist/agents/modes/plan.d.ts +8 -0
- package/dist/agents/modes/plan.js +43 -0
- package/dist/agents/prompts/agent-instructions.d.ts +122 -0
- package/dist/agents/prompts/agent-instructions.js +617 -0
- package/dist/agents/prompts/build.d.ts +12 -0
- package/dist/agents/prompts/build.js +73 -0
- package/dist/agents/prompts/fast.d.ts +5 -0
- package/dist/agents/prompts/fast.js +23 -0
- package/dist/agents/prompts/index.d.ts +61 -0
- package/dist/agents/prompts/index.js +141 -0
- package/dist/agents/prompts/model.d.ts +5 -0
- package/dist/agents/prompts/model.js +20 -0
- package/dist/agents/prompts/plan.d.ts +11 -0
- package/dist/agents/prompts/plan.js +132 -0
- package/dist/agents/prompts/tool-guidance.d.ts +18 -0
- package/dist/agents/prompts/tool-guidance.js +158 -0
- package/dist/agents/sandbox-filesystem.d.ts +232 -0
- package/dist/agents/sandbox-filesystem.js +851 -0
- package/dist/agents/subagents/execute.d.ts +3 -0
- package/dist/agents/subagents/execute.js +24 -0
- package/dist/agents/subagents/explore.d.ts +3 -0
- package/dist/agents/subagents/explore.js +15 -0
- package/dist/agents/subagents/index.d.ts +6 -0
- package/dist/agents/subagents/index.js +15 -0
- package/dist/agents/subagents/plan.d.ts +3 -0
- package/dist/agents/subagents/plan.js +15 -0
- package/dist/agents/thread-caveman-state.d.ts +17 -0
- package/dist/agents/thread-caveman-state.js +104 -0
- package/dist/agents/tool-availability.d.ts +17 -0
- package/dist/agents/tool-availability.js +134 -0
- package/dist/agents/tools.d.ts +37 -0
- package/dist/agents/tools.js +154 -0
- package/dist/agents/workflow-builder-agent.d.ts +2 -0
- package/dist/agents/workflow-builder-agent.js +79 -0
- package/dist/agents/workspace.d.ts +35 -0
- package/dist/agents/workspace.js +207 -0
- package/dist/analytics.d.ts +18 -0
- package/dist/analytics.js +159 -0
- package/dist/auth/account-rotation-processor.d.ts +210 -0
- package/dist/auth/account-rotation-processor.js +662 -0
- package/dist/auth/account-routing-context.d.ts +17 -0
- package/dist/auth/account-routing-context.js +38 -0
- package/dist/auth/authorization-input.d.ts +16 -0
- package/dist/auth/authorization-input.js +39 -0
- package/dist/auth/device-code.d.ts +93 -0
- package/dist/auth/device-code.js +126 -0
- package/dist/auth/index.d.ts +13 -0
- package/dist/auth/index.js +9 -0
- package/dist/auth/pkce.d.ts +13 -0
- package/dist/auth/pkce.js +29 -0
- package/dist/auth/provider-auth-error.d.ts +24 -0
- package/dist/auth/provider-auth-error.js +44 -0
- package/dist/auth/providers/anthropic.d.ts +40 -0
- package/dist/auth/providers/anthropic.js +117 -0
- package/dist/auth/providers/github-copilot.d.ts +154 -0
- package/dist/auth/providers/github-copilot.js +359 -0
- package/dist/auth/providers/kimi-coding.d.ts +38 -0
- package/dist/auth/providers/kimi-coding.js +225 -0
- package/dist/auth/providers/openai-codex.d.ts +141 -0
- package/dist/auth/providers/openai-codex.js +531 -0
- package/dist/auth/providers/xai.d.ts +64 -0
- package/dist/auth/providers/xai.js +223 -0
- package/dist/auth/storage.d.ts +222 -0
- package/dist/auth/storage.js +805 -0
- package/dist/auth/types.d.ts +164 -0
- package/dist/auth/types.js +1 -0
- package/dist/clipboard/index.d.ts +26 -0
- package/dist/clipboard/index.js +224 -0
- package/dist/constants.d.ts +29 -0
- package/dist/constants.js +34 -0
- package/dist/error-classification.d.ts +10 -0
- package/dist/error-classification.js +19 -0
- package/dist/evals/context-builder.d.ts +41 -0
- package/dist/evals/context-builder.js +156 -0
- package/dist/evals/index.d.ts +4 -0
- package/dist/evals/index.js +5 -0
- package/dist/evals/scorers/classify-command.d.ts +30 -0
- package/dist/evals/scorers/classify-command.js +61 -0
- package/dist/evals/scorers/efficiency.d.ts +44 -0
- package/dist/evals/scorers/efficiency.js +256 -0
- package/dist/evals/scorers/extract-tools.d.ts +25 -0
- package/dist/evals/scorers/extract-tools.js +57 -0
- package/dist/evals/scorers/index.d.ts +3 -0
- package/dist/evals/scorers/index.js +3 -0
- package/dist/evals/scorers/outcome.d.ts +49 -0
- package/dist/evals/scorers/outcome.js +360 -0
- package/dist/experimental-agent.d.ts +19 -0
- package/dist/experimental-agent.js +45 -0
- package/dist/factory/client.d.ts +44 -0
- package/dist/factory/client.js +110 -0
- package/dist/factory/remote-controller.d.ts +34 -0
- package/dist/factory/remote-controller.js +40 -0
- package/dist/factory/remote-session.d.ts +210 -0
- package/dist/factory/remote-session.js +415 -0
- package/dist/goal-manager.d.ts +114 -0
- package/dist/goal-manager.js +351 -0
- package/dist/goal-signal.d.ts +14 -0
- package/dist/goal-signal.js +14 -0
- package/dist/headless/cli.d.ts +55 -0
- package/dist/headless/cli.js +261 -0
- package/dist/headless/flags.d.ts +33 -0
- package/dist/headless/flags.js +207 -0
- package/dist/headless/format.d.ts +41 -0
- package/dist/headless/format.js +94 -0
- package/dist/headless/index.d.ts +25 -0
- package/dist/headless/index.js +6 -0
- package/dist/headless/policy.d.ts +17 -0
- package/dist/headless/policy.js +39 -0
- package/dist/headless/run-mc.d.ts +7 -0
- package/dist/headless/run-mc.js +438 -0
- package/dist/headless/types.d.ts +175 -0
- package/dist/headless/types.js +16 -0
- package/dist/hooks/config.d.ts +11 -0
- package/dist/hooks/config.js +77 -0
- package/dist/hooks/executor.d.ts +13 -0
- package/dist/hooks/executor.js +128 -0
- package/dist/hooks/index.d.ts +6 -0
- package/dist/hooks/index.js +5 -0
- package/dist/hooks/manager.d.ts +75 -0
- package/dist/hooks/manager.js +289 -0
- package/dist/hooks/types.d.ts +180 -0
- package/dist/hooks/types.js +5 -0
- package/dist/index.d.ts +537 -0
- package/dist/index.js +1399 -0
- package/dist/ipc/ipc-reporter.d.ts +14 -0
- package/dist/ipc/ipc-reporter.js +18 -0
- package/dist/knowledge-inspector.d.ts +139 -0
- package/dist/knowledge-inspector.js +533 -0
- package/dist/knowledge-scope-id.d.ts +7 -0
- package/dist/knowledge-scope-id.js +10 -0
- package/dist/knowledge-scope.d.ts +41 -0
- package/dist/knowledge-scope.js +85 -0
- package/dist/lsp/client.d.ts +56 -0
- package/dist/lsp/client.js +248 -0
- package/dist/lsp/index.d.ts +4 -0
- package/dist/lsp/index.js +4 -0
- package/dist/lsp/language.d.ts +9 -0
- package/dist/lsp/language.js +41 -0
- package/dist/lsp/manager.d.ts +34 -0
- package/dist/lsp/manager.js +79 -0
- package/dist/lsp/server.d.ts +27 -0
- package/dist/lsp/server.js +158 -0
- package/dist/lsp/workspace.d.ts +9 -0
- package/dist/lsp/workspace.js +52 -0
- package/dist/mcp/config.d.ts +77 -0
- package/dist/mcp/config.js +313 -0
- package/dist/mcp/index.d.ts +6 -0
- package/dist/mcp/index.js +3 -0
- package/dist/mcp/manager.d.ts +104 -0
- package/dist/mcp/manager.js +693 -0
- package/dist/mcp/state.d.ts +35 -0
- package/dist/mcp/state.js +94 -0
- package/dist/mcp/types.d.ts +139 -0
- package/dist/mcp/types.js +1 -0
- package/dist/onboarding/custom-packs.d.ts +7 -0
- package/dist/onboarding/custom-packs.js +17 -0
- package/dist/onboarding/custom-providers.d.ts +4 -0
- package/dist/onboarding/custom-providers.js +27 -0
- package/dist/onboarding/index.d.ts +5 -0
- package/dist/onboarding/index.js +3 -0
- package/dist/onboarding/om-settings.d.ts +47 -0
- package/dist/onboarding/om-settings.js +80 -0
- package/dist/onboarding/pack-activation.d.ts +43 -0
- package/dist/onboarding/pack-activation.js +105 -0
- package/dist/onboarding/packs.d.ts +106 -0
- package/dist/onboarding/packs.js +283 -0
- package/dist/onboarding/settings.d.ts +563 -0
- package/dist/onboarding/settings.js +1110 -0
- package/dist/permissions.d.ts +55 -0
- package/dist/permissions.js +139 -0
- package/dist/platform/index.d.ts +74 -0
- package/dist/platform/index.js +199 -0
- package/dist/plugin.d.ts +156 -0
- package/dist/plugin.js +27 -0
- package/dist/plugins/dependencies.d.ts +9 -0
- package/dist/plugins/dependencies.js +84 -0
- package/dist/plugins/install.d.ts +21 -0
- package/dist/plugins/install.js +187 -0
- package/dist/plugins/loader.d.ts +25 -0
- package/dist/plugins/loader.js +264 -0
- package/dist/plugins/manager.d.ts +115 -0
- package/dist/plugins/manager.js +507 -0
- package/dist/plugins/manifest.d.ts +14 -0
- package/dist/plugins/manifest.js +47 -0
- package/dist/plugins/package-link.d.ts +3 -0
- package/dist/plugins/package-link.js +58 -0
- package/dist/plugins/paths.d.ts +10 -0
- package/dist/plugins/paths.js +22 -0
- package/dist/plugins/registry.d.ts +8 -0
- package/dist/plugins/registry.js +109 -0
- package/dist/plugins/scaffold.d.ts +10 -0
- package/dist/plugins/scaffold.js +115 -0
- package/dist/plugins/signal-lane.d.ts +59 -0
- package/dist/plugins/signal-lane.js +163 -0
- package/dist/plugins/types.d.ts +95 -0
- package/dist/plugins/types.js +1 -0
- package/dist/process-memory-diagnostics.d.ts +136 -0
- package/dist/process-memory-diagnostics.js +497 -0
- package/dist/processors/plan-rejection-abort.d.ts +16 -0
- package/dist/processors/plan-rejection-abort.js +62 -0
- package/dist/providers/amazon-bedrock-gateway.d.ts +47 -0
- package/dist/providers/amazon-bedrock-gateway.js +142 -0
- package/dist/providers/amazon-bedrock.d.ts +28 -0
- package/dist/providers/amazon-bedrock.js +99 -0
- package/dist/providers/anthropic-prompt-cache.d.ts +19 -0
- package/dist/providers/anthropic-prompt-cache.js +8 -0
- package/dist/providers/anthropic-thinking.d.ts +5 -0
- package/dist/providers/anthropic-thinking.js +22 -0
- package/dist/providers/claude-max.d.ts +67 -0
- package/dist/providers/claude-max.js +232 -0
- package/dist/providers/github-copilot-gateway.d.ts +35 -0
- package/dist/providers/github-copilot-gateway.js +58 -0
- package/dist/providers/github-copilot.d.ts +60 -0
- package/dist/providers/github-copilot.js +320 -0
- package/dist/providers/google-thinking.d.ts +31 -0
- package/dist/providers/google-thinking.js +64 -0
- package/dist/providers/google-vertex-gateway.d.ts +23 -0
- package/dist/providers/google-vertex-gateway.js +49 -0
- package/dist/providers/google-vertex.d.ts +6 -0
- package/dist/providers/google-vertex.js +51 -0
- package/dist/providers/kimi-coding.d.ts +14 -0
- package/dist/providers/kimi-coding.js +80 -0
- package/dist/providers/model-ids.d.ts +53 -0
- package/dist/providers/model-ids.js +132 -0
- package/dist/providers/openai-codex.d.ts +114 -0
- package/dist/providers/openai-codex.js +427 -0
- package/dist/providers/provider-thinking.d.ts +23 -0
- package/dist/providers/provider-thinking.js +61 -0
- package/dist/providers/thinking-request.d.ts +14 -0
- package/dist/providers/thinking-request.js +87 -0
- package/dist/providers/xai.d.ts +33 -0
- package/dist/providers/xai.js +72 -0
- package/dist/schedules/index.d.ts +10 -0
- package/dist/schedules/index.js +6 -0
- package/dist/schedules/interval.d.ts +49 -0
- package/dist/schedules/interval.js +212 -0
- package/dist/schedules/prompt.d.ts +36 -0
- package/dist/schedules/prompt.js +36 -0
- package/dist/schedules/run-script.d.ts +8 -0
- package/dist/schedules/run-script.js +80 -0
- package/dist/schedules/scheduler.d.ts +101 -0
- package/dist/schedules/scheduler.js +167 -0
- package/dist/schedules/tools.d.ts +57 -0
- package/dist/schedules/tools.js +217 -0
- package/dist/schema.d.ts +499 -0
- package/dist/schema.js +131 -0
- package/dist/theme-palette.d.ts +17 -0
- package/dist/theme-palette.js +18 -0
- package/dist/thinking-catalog.d.ts +4 -0
- package/dist/thinking-catalog.js +13 -0
- package/dist/thinking.d.ts +37 -0
- package/dist/thinking.js +134 -0
- package/dist/tool-names.d.ts +77 -0
- package/dist/tool-names.js +53 -0
- package/dist/tools/index.d.ts +6 -0
- package/dist/tools/index.js +3 -0
- package/dist/tools/request-sandbox-access.d.ts +6 -0
- package/dist/tools/request-sandbox-access.js +80 -0
- package/dist/tools/utils.d.ts +20 -0
- package/dist/tools/utils.js +31 -0
- package/dist/tools/web-search.d.ts +116 -0
- package/dist/tools/web-search.js +158 -0
- package/dist/tools/workflows/create-workflow.d.ts +7 -0
- package/dist/tools/workflows/create-workflow.js +82 -0
- package/dist/tools/workflows/delete-workflow.d.ts +7 -0
- package/dist/tools/workflows/delete-workflow.js +18 -0
- package/dist/tools/workflows/ephemeral-memory.d.ts +28 -0
- package/dist/tools/workflows/ephemeral-memory.js +41 -0
- package/dist/tools/workflows/extract-json-schema.d.ts +12 -0
- package/dist/tools/workflows/extract-json-schema.js +19 -0
- package/dist/tools/workflows/get-workflow.d.ts +11 -0
- package/dist/tools/workflows/get-workflow.js +31 -0
- package/dist/tools/workflows/list-available-agents.d.ts +8 -0
- package/dist/tools/workflows/list-available-agents.js +29 -0
- package/dist/tools/workflows/list-available-classifiers.d.ts +19 -0
- package/dist/tools/workflows/list-available-classifiers.js +53 -0
- package/dist/tools/workflows/list-available-tools.d.ts +9 -0
- package/dist/tools/workflows/list-available-tools.js +37 -0
- package/dist/tools/workflows/list-available-workflows.d.ts +9 -0
- package/dist/tools/workflows/list-available-workflows.js +29 -0
- package/dist/tools/workflows/list-workflows.d.ts +9 -0
- package/dist/tools/workflows/list-workflows.js +30 -0
- package/dist/tools/workflows/run-workflow.d.ts +9 -0
- package/dist/tools/workflows/run-workflow.js +49 -0
- package/dist/tools/workflows/save-workflow.d.ts +1125 -0
- package/dist/tools/workflows/save-workflow.js +25 -0
- package/dist/tools/workflows/tool-ids.d.ts +16 -0
- package/dist/tools/workflows/tool-ids.js +17 -0
- package/dist/utils/binaries.d.ts +7 -0
- package/dist/utils/binaries.js +97 -0
- package/dist/utils/debug-log.d.ts +12 -0
- package/dist/utils/debug-log.js +56 -0
- package/dist/utils/discarding-scores-storage.d.ts +33 -0
- package/dist/utils/discarding-scores-storage.js +51 -0
- package/dist/utils/errors.d.ts +36 -0
- package/dist/utils/errors.js +215 -0
- package/dist/utils/gateway-sync.d.ts +26 -0
- package/dist/utils/gateway-sync.js +58 -0
- package/dist/utils/local-observability.d.ts +19 -0
- package/dist/utils/local-observability.js +54 -0
- package/dist/utils/maintenance-lock.d.ts +42 -0
- package/dist/utils/maintenance-lock.js +196 -0
- package/dist/utils/notification-dispatch.d.ts +74 -0
- package/dist/utils/notification-dispatch.js +128 -0
- package/dist/utils/open-url.d.ts +10 -0
- package/dist/utils/open-url.js +27 -0
- package/dist/utils/path-security.d.ts +2 -0
- package/dist/utils/path-security.js +7 -0
- package/dist/utils/plan-diff.d.ts +25 -0
- package/dist/utils/plan-diff.js +59 -0
- package/dist/utils/plans.d.ts +61 -0
- package/dist/utils/plans.js +120 -0
- package/dist/utils/project.d.ts +160 -0
- package/dist/utils/project.js +361 -0
- package/dist/utils/prune-cli.d.ts +24 -0
- package/dist/utils/prune-cli.js +124 -0
- package/dist/utils/signals-pubsub.d.ts +103 -0
- package/dist/utils/signals-pubsub.js +409 -0
- package/dist/utils/slash-command-loader.d.ts +52 -0
- package/dist/utils/slash-command-loader.js +139 -0
- package/dist/utils/slash-command-processor.d.ts +14 -0
- package/dist/utils/slash-command-processor.js +106 -0
- package/dist/utils/stdin-pipe.d.ts +33 -0
- package/dist/utils/stdin-pipe.js +93 -0
- package/dist/utils/storage-factory.d.ts +50 -0
- package/dist/utils/storage-factory.js +118 -0
- package/dist/utils/storage-maintenance.d.ts +121 -0
- package/dist/utils/storage-maintenance.js +352 -0
- package/dist/utils/thread-lock.d.ts +26 -0
- package/dist/utils/thread-lock.js +109 -0
- package/dist/utils/token-estimator.d.ts +3 -0
- package/dist/utils/token-estimator.js +19 -0
- package/dist/utils/update-check.d.ts +151 -0
- package/dist/utils/update-check.js +430 -0
- package/dist/utils/wake-session.d.ts +44 -0
- package/dist/utils/wake-session.js +83 -0
- package/dist/voice/stt-registry.d.ts +67 -0
- package/dist/voice/stt-registry.js +144 -0
- package/dist/voice/transcribe.d.ts +10 -0
- package/dist/voice/transcribe.js +75 -0
- package/dist/workflows/register-primitives.d.ts +52 -0
- package/dist/workflows/register-primitives.js +40 -0
- package/dist/workflows/service.d.ts +64 -0
- package/dist/workflows/service.js +50 -0
- package/package.json +117 -0
|
@@ -0,0 +1,851 @@
|
|
|
1
|
+
import { posix } from "path";
|
|
2
|
+
import { DirectoryNotFoundError, FileExistsError, FileNotFoundError, IsDirectoryError, LocalFilesystem, NotDirectoryError, UnsupportedGrepPatternError, getMimeType } from "@mastra/core/workspace";
|
|
3
|
+
// src/agents/sandbox-filesystem.ts
|
|
4
|
+
/**
|
|
5
|
+
* SandboxFilesystem
|
|
6
|
+
*
|
|
7
|
+
* A `WorkspaceFilesystem` that stores files inside a remote `MastraSandbox`
|
|
8
|
+
* (e.g. a Railway VM) rather than on the server host. File operations are
|
|
9
|
+
* implemented by shelling out through the sandbox's `executeCommand`, so the
|
|
10
|
+
* agent's file tools and command tools share one VM and one view of the repo.
|
|
11
|
+
* When the sandbox exposes its own `filesystem`, file operations use it
|
|
12
|
+
* instead, which takes one round trip rather than several commands; grep and
|
|
13
|
+
* walks still run as shell commands.
|
|
14
|
+
*
|
|
15
|
+
* Paths are workspace-relative (`/src/foo.ts`) and resolve under the sandbox
|
|
16
|
+
* working directory (`basePath`). A traversal guard rejects any path that
|
|
17
|
+
* escapes the workdir, mirroring `LocalFilesystem`'s contained mode.
|
|
18
|
+
*
|
|
19
|
+
* Reads/writes use base64 over the wire so binary content survives the shell.
|
|
20
|
+
*/
|
|
21
|
+
/**
|
|
22
|
+
* Sentinel exit codes used by guard clauses that run before the real command,
|
|
23
|
+
* so shell failures can be mapped to typed filesystem errors.
|
|
24
|
+
*/
|
|
25
|
+
const EXIT_NOT_FOUND = 20;
|
|
26
|
+
const EXIT_IS_DIRECTORY = 21;
|
|
27
|
+
const EXIT_EXISTS = 22;
|
|
28
|
+
const EXIT_NOT_DIRECTORY = 23;
|
|
29
|
+
/** Default per-command deadline so a hung sandbox can't block file tools forever. */
|
|
30
|
+
const COMMAND_TIMEOUT_MS = 3e4;
|
|
31
|
+
/**
|
|
32
|
+
* Explain why a native grep command failed so callers can tell a timeout or
|
|
33
|
+
* broken toolchain apart from a pattern the engine cannot express.
|
|
34
|
+
*/
|
|
35
|
+
function describeGrepFailure(result) {
|
|
36
|
+
if (result.exitCode === 124) return `timed out after ${COMMAND_TIMEOUT_MS / 1e3}s`;
|
|
37
|
+
const stderrLine = result.stderr.split("\n").map((line) => line.trim()).find(Boolean);
|
|
38
|
+
const detail = stderrLine ? `: ${stderrLine.length > 200 ? `${stderrLine.slice(0, 200)}…` : stderrLine}` : "";
|
|
39
|
+
return `exit code ${result.exitCode}${detail}`;
|
|
40
|
+
}
|
|
41
|
+
/** Single-quote a string for safe POSIX shell interpolation. */
|
|
42
|
+
function shellQuote(value) {
|
|
43
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
44
|
+
}
|
|
45
|
+
/** One command that reports which search tools the sandbox has, one name per line. */
|
|
46
|
+
const SEARCH_TOOLS_PROBE = "command -v rg >/dev/null 2>&1 && echo rg; grep --version 2>/dev/null | head -n 1 | grep -q 'GNU grep' && echo gnu-grep; printf 'a1\\n' | grep -qP '\\d(?=)' 2>/dev/null && echo grep-pcre; if command -v git >/dev/null 2>&1; then echo git; d=$(mktemp -d 2>/dev/null) && { (cd \"$d\" && git init -q && printf 'a1\\n' >f && git grep -q --untracked -P -e '\\d(?=)') >/dev/null 2>&1 && echo git-pcre; rm -rf \"$d\"; }; fi; true";
|
|
47
|
+
function isInsideNodeModules(path) {
|
|
48
|
+
return path.split("/").includes("node_modules");
|
|
49
|
+
}
|
|
50
|
+
function fileLines(files, filePath) {
|
|
51
|
+
let state = files.get(filePath);
|
|
52
|
+
if (!state) {
|
|
53
|
+
state = {
|
|
54
|
+
matches: [],
|
|
55
|
+
linesByNumber: /* @__PURE__ */ new Map()
|
|
56
|
+
};
|
|
57
|
+
files.set(filePath, state);
|
|
58
|
+
}
|
|
59
|
+
return state;
|
|
60
|
+
}
|
|
61
|
+
/** Turn per-file lines into results relative to `abs`, attaching before/after context. */
|
|
62
|
+
function toGrepResults(files, abs, contextLines) {
|
|
63
|
+
const results = [];
|
|
64
|
+
for (const [filePath, state] of files) {
|
|
65
|
+
if (state.matches.length === 0) continue;
|
|
66
|
+
const rel = posix.relative(abs, filePath) || posix.basename(filePath);
|
|
67
|
+
const matches = state.matches.map((match) => {
|
|
68
|
+
if (contextLines <= 0) return match;
|
|
69
|
+
const before = [];
|
|
70
|
+
for (let n = match.line - 1; n >= Math.max(1, match.line - contextLines); n--) {
|
|
71
|
+
const text = state.linesByNumber.get(n);
|
|
72
|
+
if (text === void 0) break;
|
|
73
|
+
before.unshift(text);
|
|
74
|
+
}
|
|
75
|
+
const after = [];
|
|
76
|
+
for (let n = match.line + 1; n <= match.line + contextLines; n++) {
|
|
77
|
+
const text = state.linesByNumber.get(n);
|
|
78
|
+
if (text === void 0) break;
|
|
79
|
+
after.push(text);
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
...match,
|
|
83
|
+
before,
|
|
84
|
+
after
|
|
85
|
+
};
|
|
86
|
+
});
|
|
87
|
+
results.push({
|
|
88
|
+
path: rel,
|
|
89
|
+
matches
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
return results;
|
|
93
|
+
}
|
|
94
|
+
function isFileContentString(content) {
|
|
95
|
+
return typeof content === "string";
|
|
96
|
+
}
|
|
97
|
+
function toBuffer(content) {
|
|
98
|
+
if (isFileContentString(content)) return Buffer.from(content, "utf8");
|
|
99
|
+
return Buffer.from(content);
|
|
100
|
+
}
|
|
101
|
+
var SandboxFilesystem = class SandboxFilesystem {
|
|
102
|
+
id;
|
|
103
|
+
name = "SandboxFilesystem";
|
|
104
|
+
provider = "sandbox";
|
|
105
|
+
status = "ready";
|
|
106
|
+
sandbox;
|
|
107
|
+
workdirSource;
|
|
108
|
+
resolvedBase;
|
|
109
|
+
resolvingBase;
|
|
110
|
+
verifySymlinks;
|
|
111
|
+
/**
|
|
112
|
+
* Classifies file names as text: the built-in extensions plus
|
|
113
|
+
* `textExtensions`, normalized exactly as `LocalFilesystem` does. Only its
|
|
114
|
+
* `isTextFile` is ever called; it never touches a file.
|
|
115
|
+
*/
|
|
116
|
+
textClassifier;
|
|
117
|
+
/** `check:absolutePath` keys that passed while the entry existed. */
|
|
118
|
+
verified = /* @__PURE__ */ new Set();
|
|
119
|
+
constructor(options) {
|
|
120
|
+
this.sandbox = options.sandbox;
|
|
121
|
+
this.workdirSource = options.workdir;
|
|
122
|
+
this.verifySymlinks = options.verifySymlinks ?? false;
|
|
123
|
+
this.textClassifier = new LocalFilesystem({
|
|
124
|
+
basePath: "/",
|
|
125
|
+
textExtensions: options.textExtensions
|
|
126
|
+
});
|
|
127
|
+
if (typeof options.workdir === "string") this.resolvedBase = options.workdir;
|
|
128
|
+
this.id = options.id ?? (typeof options.workdir === "string" ? `sandbox-fs:${options.sandbox.id}:${options.workdir}` : `sandbox-fs:${options.sandbox.id}`);
|
|
129
|
+
}
|
|
130
|
+
/** The resolved workspace root; empty until a lazy workdir first resolves. */
|
|
131
|
+
get basePath() {
|
|
132
|
+
return this.resolvedBase ?? "";
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* The sandbox directory shell commands default to: the same root file paths
|
|
136
|
+
* resolve against, so a relative path means the same thing to a shell command
|
|
137
|
+
* and to a file tool. Non-empty whenever the workspace root is known.
|
|
138
|
+
*/
|
|
139
|
+
async getCommandCwd() {
|
|
140
|
+
return await this.base() || void 0;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Whether tools like `grep` should treat a file as text: the built-in text
|
|
144
|
+
* extensions plus any `textExtensions` passed to the constructor.
|
|
145
|
+
*/
|
|
146
|
+
isTextFile(filename) {
|
|
147
|
+
return this.textClassifier.isTextFile(filename);
|
|
148
|
+
}
|
|
149
|
+
/** Await (and memoize) the workspace root, resolving a lazy workdir once. */
|
|
150
|
+
async base() {
|
|
151
|
+
if (this.resolvedBase) return this.resolvedBase;
|
|
152
|
+
const source = this.workdirSource;
|
|
153
|
+
if (typeof source === "string") return this.resolvedBase = source;
|
|
154
|
+
this.resolvingBase ??= Promise.resolve().then(source).then((resolved) => {
|
|
155
|
+
if (!resolved) throw new Error("Sandbox workspace root resolution returned an empty path");
|
|
156
|
+
return this.resolvedBase = resolved;
|
|
157
|
+
}).finally(() => {
|
|
158
|
+
this.resolvingBase = void 0;
|
|
159
|
+
});
|
|
160
|
+
return this.resolvingBase;
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Resolve a workspace path to an absolute path inside the sandbox, enforcing
|
|
164
|
+
* that it stays within the workdir. Awaits the workspace root first, which
|
|
165
|
+
* for a lazy workdir may start the VM.
|
|
166
|
+
*/
|
|
167
|
+
async resolveAsync(inputPath) {
|
|
168
|
+
return this.resolveAgainst(await this.base(), inputPath);
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Resolve a workspace path against a known base, enforcing that it stays
|
|
172
|
+
* within the workdir.
|
|
173
|
+
*
|
|
174
|
+
* Accepts both workspace-relative paths (`src/foo.ts`, `/src/foo.ts`) and
|
|
175
|
+
* absolute sandbox paths that already live under the workdir — the agent's
|
|
176
|
+
* prompt advertises the workdir as its working directory, so tools are
|
|
177
|
+
* routinely called with fully-qualified paths like `<workdir>/src/foo.ts`.
|
|
178
|
+
*/
|
|
179
|
+
resolveAgainst(basePath, inputPath) {
|
|
180
|
+
const base = posix.normalize(basePath);
|
|
181
|
+
const normalizedInput = posix.normalize(inputPath);
|
|
182
|
+
const rel = normalizedInput === base ? "" : normalizedInput.startsWith(`${base}/`) ? normalizedInput.slice(base.length + 1) : inputPath.startsWith("/") ? inputPath.slice(1) : inputPath;
|
|
183
|
+
const resolved = posix.normalize(posix.join(base, rel));
|
|
184
|
+
if (resolved !== base && !resolved.startsWith(`${base}/`)) throw new Error(`Path escapes workspace root: ${inputPath}`);
|
|
185
|
+
return resolved;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* A miss on an absolute path outside the workdir (e.g. `/tmp/x/a.ts`) that
|
|
189
|
+
* does exist at that real sandbox path: the agent meant the sandbox path,
|
|
190
|
+
* but it was remapped under the workdir. Explain that instead of a bare
|
|
191
|
+
* not-found. Undefined when the path is inside the workdir or doesn't exist.
|
|
192
|
+
*/
|
|
193
|
+
async outsideWorkdirNotFound(inputPath, abs) {
|
|
194
|
+
const base = posix.normalize(this.basePath);
|
|
195
|
+
const normalized = posix.normalize(inputPath);
|
|
196
|
+
if (!inputPath.startsWith("/") || normalized === base || normalized.startsWith(`${base}/`)) return void 0;
|
|
197
|
+
if ((await this.exec(`test -e ${shellQuote(normalized)}`).catch(() => void 0))?.exitCode !== 0) return void 0;
|
|
198
|
+
const error = new FileNotFoundError(inputPath);
|
|
199
|
+
error.message = `File not found: ${inputPath} (resolved to ${abs}). File tools only reach files under ${base}; absolute paths are workspace-relative. Put scratch worktrees under ${base}/.worktrees/.`;
|
|
200
|
+
return error;
|
|
201
|
+
}
|
|
202
|
+
resolveAbsolutePath(inputPath) {
|
|
203
|
+
if (!this.resolvedBase) return void 0;
|
|
204
|
+
return this.resolveAgainst(this.resolvedBase, inputPath);
|
|
205
|
+
}
|
|
206
|
+
async exec(script) {
|
|
207
|
+
return this.sandbox.executeCommand("sh", ["-c", script], {
|
|
208
|
+
timeout: COMMAND_TIMEOUT_MS,
|
|
209
|
+
maxRetainedBytes: Infinity
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Lexical guard catches `..` traversal, but a symlink inside the workdir can
|
|
214
|
+
* still point outside it. After resolving a path that refers to an existing
|
|
215
|
+
* entry, verify its realpath is still contained in the workdir.
|
|
216
|
+
*
|
|
217
|
+
* Canonicalization tries `realpath`, then `readlink -f` (GNU/busybox), then
|
|
218
|
+
* `cd && pwd -P` for directories — covering GNU hosts, macOS/BSD, and
|
|
219
|
+
* busybox. If the path exists but cannot be canonicalized we fail CLOSED:
|
|
220
|
+
* returning without a check would let a symlink bypass containment.
|
|
221
|
+
*/
|
|
222
|
+
async assertContainedRealpath(abs, inputPath) {
|
|
223
|
+
const result = await this.exec([
|
|
224
|
+
`p=${shellQuote(abs)}`,
|
|
225
|
+
`if [ ! -e "$p" ] && [ ! -L "$p" ]; then exit ${EXIT_NOT_FOUND}; fi`,
|
|
226
|
+
`root=$(cd ${shellQuote(this.basePath)} 2>/dev/null && pwd -P)`,
|
|
227
|
+
`[ -n "$root" ] || exit 1`,
|
|
228
|
+
`rp=$(realpath "$p" 2>/dev/null) || rp=$(readlink -f "$p" 2>/dev/null) || { [ -d "$p" ] && rp=$(cd "$p" 2>/dev/null && pwd -P); }`,
|
|
229
|
+
`[ -n "$rp" ] || exit 1`,
|
|
230
|
+
`printf '%s\\n%s' "$root" "$rp"`
|
|
231
|
+
].join("\n"));
|
|
232
|
+
if (result.exitCode === EXIT_NOT_FOUND) return false;
|
|
233
|
+
const [root, real] = result.stdout.split("\n").map((s) => s.trim());
|
|
234
|
+
if (result.exitCode !== 0 || !root || !real) throw new Error(`Unable to verify path stays within workspace root: ${inputPath}`);
|
|
235
|
+
if (real !== root && !real.startsWith(`${root}/`)) throw new Error(`Path escapes workspace root (symlink): ${inputPath}`);
|
|
236
|
+
return true;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Guard for write destinations. The lexical guard catches `..`, but a symlink
|
|
240
|
+
* inside the workdir can redirect a write outside it. For an existing target
|
|
241
|
+
* we check its realpath; for a not-yet-existing target we check the realpath
|
|
242
|
+
* of its nearest existing ancestor directory, since a symlinked parent is the
|
|
243
|
+
* escape vector (e.g. `link -> /etc` then writing `link/passwd`).
|
|
244
|
+
*/
|
|
245
|
+
async assertContainedDest(abs, inputPath) {
|
|
246
|
+
const exists = await this.assertContainedRealpath(abs, inputPath);
|
|
247
|
+
const parent = posix.dirname(abs);
|
|
248
|
+
if (parent && parent !== abs) await this.assertContainedRealpath(parent, inputPath);
|
|
249
|
+
return exists;
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Before a native filesystem call, run the containment check the shell path
|
|
253
|
+
* runs for that operation, when `verifySymlinks` is on. A pass is remembered
|
|
254
|
+
* only for an entry that exists: a missing path may later appear as a
|
|
255
|
+
* symlink that leads outside the workdir.
|
|
256
|
+
*/
|
|
257
|
+
async verifyNative(check, abs, inputPath) {
|
|
258
|
+
if (!this.verifySymlinks) return;
|
|
259
|
+
const key = `${check}:${abs}`;
|
|
260
|
+
if (this.verified.has(key)) return;
|
|
261
|
+
if (check === "dest" ? await this.assertContainedDest(abs, inputPath) : await this.assertContainedRealpath(check === "parent" ? posix.dirname(abs) : abs, inputPath)) this.verified.add(key);
|
|
262
|
+
}
|
|
263
|
+
async execOk(script, context) {
|
|
264
|
+
const result = await this.exec(script);
|
|
265
|
+
if (result.exitCode !== 0) throw new Error(`${context} failed (exit ${result.exitCode}): ${result.stderr.trim() || result.stdout.trim()}`);
|
|
266
|
+
return result;
|
|
267
|
+
}
|
|
268
|
+
async readFile(path, options) {
|
|
269
|
+
const abs = await this.resolveAsync(path);
|
|
270
|
+
const native = this.sandbox.filesystem;
|
|
271
|
+
if (native) {
|
|
272
|
+
await this.verifyNative("target", abs, path);
|
|
273
|
+
try {
|
|
274
|
+
return await native.readFile(abs, options);
|
|
275
|
+
} catch (error) {
|
|
276
|
+
throw (error instanceof FileNotFoundError || error?.code === "ENOENT") && await this.outsideWorkdirNotFound(path, abs) || error;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
await this.assertContainedRealpath(abs, path);
|
|
280
|
+
const result = await this.exec(`if [ -d ${shellQuote(abs)} ]; then exit ${EXIT_IS_DIRECTORY}; elif [ ! -e ${shellQuote(abs)} ]; then exit ${EXIT_NOT_FOUND}; fi; base64 < ${shellQuote(abs)}`);
|
|
281
|
+
if (result.exitCode === EXIT_IS_DIRECTORY) throw new IsDirectoryError(path);
|
|
282
|
+
if (result.exitCode === EXIT_NOT_FOUND) throw await this.outsideWorkdirNotFound(path, abs) ?? new FileNotFoundError(path);
|
|
283
|
+
if (result.exitCode !== 0) throw new Error(`readFile ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);
|
|
284
|
+
const buffer = Buffer.from(result.stdout.replace(/\s/g, ""), "base64");
|
|
285
|
+
if (options?.encoding) return buffer.toString(options.encoding);
|
|
286
|
+
return buffer;
|
|
287
|
+
}
|
|
288
|
+
async writeFile(path, content, options) {
|
|
289
|
+
const abs = await this.resolveAsync(path);
|
|
290
|
+
const native = this.sandbox.filesystem;
|
|
291
|
+
if (native) {
|
|
292
|
+
await this.verifyNative("dest", abs, path);
|
|
293
|
+
return native.writeFile(abs, content, options);
|
|
294
|
+
}
|
|
295
|
+
await this.assertContainedDest(abs, path);
|
|
296
|
+
const b64 = toBuffer(content).toString("base64");
|
|
297
|
+
const dir = posix.dirname(abs);
|
|
298
|
+
const mkdir = options?.recursive === false ? "" : `mkdir -p ${shellQuote(dir)} && `;
|
|
299
|
+
if (options?.overwrite === false) {
|
|
300
|
+
const result = await this.exec(`${mkdir}{ (set -C; printf %s ${shellQuote(b64)} | base64 -d > ${shellQuote(abs)}) 2>/dev/null || { [ -e ${shellQuote(abs)} ] && exit ${EXIT_EXISTS} || exit 1; }; }`);
|
|
301
|
+
if (result.exitCode === EXIT_EXISTS) throw new FileExistsError(path);
|
|
302
|
+
if (result.exitCode !== 0) throw new Error(`writeFile ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
await this.execOk(`${mkdir}printf %s ${shellQuote(b64)} | base64 -d > ${shellQuote(abs)}`, `writeFile ${path}`);
|
|
306
|
+
}
|
|
307
|
+
async appendFile(path, content) {
|
|
308
|
+
const abs = await this.resolveAsync(path);
|
|
309
|
+
const native = this.sandbox.filesystem;
|
|
310
|
+
if (native) {
|
|
311
|
+
await this.verifyNative("dest", abs, path);
|
|
312
|
+
return native.appendFile(abs, content);
|
|
313
|
+
}
|
|
314
|
+
await this.assertContainedDest(abs, path);
|
|
315
|
+
const b64 = toBuffer(content).toString("base64");
|
|
316
|
+
await this.execOk(`mkdir -p ${shellQuote(posix.dirname(abs))} && printf %s ${shellQuote(b64)} | base64 -d >> ${shellQuote(abs)}`, `appendFile ${path}`);
|
|
317
|
+
}
|
|
318
|
+
async deleteFile(path, options) {
|
|
319
|
+
const abs = await this.resolveAsync(path);
|
|
320
|
+
const native = this.sandbox.filesystem;
|
|
321
|
+
if (native) {
|
|
322
|
+
await this.verifyNative("parent", abs, path);
|
|
323
|
+
return native.deleteFile(abs, options);
|
|
324
|
+
}
|
|
325
|
+
await this.assertContainedRealpath(posix.dirname(abs), path);
|
|
326
|
+
if (options?.force) {
|
|
327
|
+
await this.execOk(`rm -f ${shellQuote(abs)}`, `deleteFile ${path}`);
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
const result = await this.exec(`if [ ! -e ${shellQuote(abs)} ]; then exit ${EXIT_NOT_FOUND}; fi; rm ${shellQuote(abs)}`);
|
|
331
|
+
if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(path);
|
|
332
|
+
if (result.exitCode !== 0) throw new Error(`deleteFile ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);
|
|
333
|
+
}
|
|
334
|
+
async copyFile(src, dest, options) {
|
|
335
|
+
const srcAbs = await this.resolveAsync(src);
|
|
336
|
+
const destAbs = await this.resolveAsync(dest);
|
|
337
|
+
const native = this.sandbox.filesystem;
|
|
338
|
+
if (native) {
|
|
339
|
+
await this.verifyNative("target", srcAbs, src);
|
|
340
|
+
await this.verifyNative("dest", destAbs, dest);
|
|
341
|
+
return native.copyFile(srcAbs, destAbs, options);
|
|
342
|
+
}
|
|
343
|
+
await this.assertContainedRealpath(srcAbs, src);
|
|
344
|
+
await this.assertContainedDest(destAbs, dest);
|
|
345
|
+
const recursive = options?.recursive ? "-r " : "";
|
|
346
|
+
if (options?.overwrite === false) {
|
|
347
|
+
const result = await this.exec([
|
|
348
|
+
`src=${shellQuote(srcAbs)}`,
|
|
349
|
+
`dest=${shellQuote(destAbs)}`,
|
|
350
|
+
`if [ ! -e "$src" ] && [ ! -L "$src" ]; then exit ${EXIT_NOT_FOUND}; fi`,
|
|
351
|
+
`mkdir -p ${shellQuote(posix.dirname(destAbs))} || exit 1`,
|
|
352
|
+
`if [ -d "$src" ]; then`,
|
|
353
|
+
` mkdir "$dest" 2>/dev/null || exit ${EXIT_EXISTS}`,
|
|
354
|
+
` cp -R "$src"/. "$dest"/`,
|
|
355
|
+
`else`,
|
|
356
|
+
` tmp="$dest.__cptmp$$"`,
|
|
357
|
+
` cp "$src" "$tmp" || exit 1`,
|
|
358
|
+
` ln "$tmp" "$dest" 2>/dev/null || { rm -f "$tmp"; [ -e "$dest" ] && exit ${EXIT_EXISTS} || exit 1; }`,
|
|
359
|
+
` rm -f "$tmp"`,
|
|
360
|
+
`fi`
|
|
361
|
+
].join("\n"));
|
|
362
|
+
if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(src);
|
|
363
|
+
if (result.exitCode === EXIT_EXISTS) throw new FileExistsError(dest);
|
|
364
|
+
if (result.exitCode !== 0) throw new Error(`copyFile ${src} -> ${dest} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
const result = await this.exec(`if [ ! -e ${shellQuote(srcAbs)} ]; then exit ${EXIT_NOT_FOUND}; fi; mkdir -p ${shellQuote(posix.dirname(destAbs))} && cp ${recursive}${shellQuote(srcAbs)} ${shellQuote(destAbs)}`);
|
|
368
|
+
if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(src);
|
|
369
|
+
if (result.exitCode !== 0) throw new Error(`copyFile ${src} -> ${dest} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);
|
|
370
|
+
}
|
|
371
|
+
async moveFile(src, dest, options) {
|
|
372
|
+
const srcAbs = await this.resolveAsync(src);
|
|
373
|
+
const destAbs = await this.resolveAsync(dest);
|
|
374
|
+
const native = this.sandbox.filesystem;
|
|
375
|
+
if (native) {
|
|
376
|
+
await this.verifyNative("target", srcAbs, src);
|
|
377
|
+
await this.verifyNative("dest", destAbs, dest);
|
|
378
|
+
return native.moveFile(srcAbs, destAbs, options);
|
|
379
|
+
}
|
|
380
|
+
await this.assertContainedRealpath(srcAbs, src);
|
|
381
|
+
await this.assertContainedDest(destAbs, dest);
|
|
382
|
+
if (options?.overwrite === false) {
|
|
383
|
+
const result = await this.exec([
|
|
384
|
+
`src=${shellQuote(srcAbs)}`,
|
|
385
|
+
`dest=${shellQuote(destAbs)}`,
|
|
386
|
+
`if [ ! -e "$src" ] && [ ! -L "$src" ]; then exit ${EXIT_NOT_FOUND}; fi`,
|
|
387
|
+
`mkdir -p ${shellQuote(posix.dirname(destAbs))} || exit 1`,
|
|
388
|
+
`mv -n "$src" "$dest" 2>/dev/null || exit 1`,
|
|
389
|
+
`if [ -e "$src" ] || [ -L "$src" ]; then exit ${EXIT_EXISTS}; fi`
|
|
390
|
+
].join("\n"));
|
|
391
|
+
if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(src);
|
|
392
|
+
if (result.exitCode === EXIT_EXISTS) throw new FileExistsError(dest);
|
|
393
|
+
if (result.exitCode !== 0) throw new Error(`moveFile ${src} -> ${dest} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
const result = await this.exec(`if [ ! -e ${shellQuote(srcAbs)} ]; then exit ${EXIT_NOT_FOUND}; fi; mkdir -p ${shellQuote(posix.dirname(destAbs))} && mv ${shellQuote(srcAbs)} ${shellQuote(destAbs)}`);
|
|
397
|
+
if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(src);
|
|
398
|
+
if (result.exitCode !== 0) throw new Error(`moveFile ${src} -> ${dest} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);
|
|
399
|
+
}
|
|
400
|
+
async mkdir(path, options) {
|
|
401
|
+
const abs = await this.resolveAsync(path);
|
|
402
|
+
const native = this.sandbox.filesystem;
|
|
403
|
+
if (native) {
|
|
404
|
+
await this.verifyNative("dest", abs, path);
|
|
405
|
+
return native.mkdir(abs, options);
|
|
406
|
+
}
|
|
407
|
+
await this.assertContainedDest(abs, path);
|
|
408
|
+
const flag = options?.recursive === false ? "" : "-p ";
|
|
409
|
+
await this.execOk(`mkdir ${flag}${shellQuote(abs)}`, `mkdir ${path}`);
|
|
410
|
+
}
|
|
411
|
+
async rmdir(path, options) {
|
|
412
|
+
const abs = await this.resolveAsync(path);
|
|
413
|
+
const native = this.sandbox.filesystem;
|
|
414
|
+
if (native) {
|
|
415
|
+
await this.verifyNative("parent", abs, path);
|
|
416
|
+
return native.rmdir(abs, options);
|
|
417
|
+
}
|
|
418
|
+
await this.assertContainedRealpath(posix.dirname(abs), path);
|
|
419
|
+
if (options?.recursive) {
|
|
420
|
+
const force = options?.force ? "-f " : "";
|
|
421
|
+
await this.execOk(`rm -r ${force}${shellQuote(abs)}`, `rmdir ${path}`);
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
if ((await this.exec(`rmdir ${shellQuote(abs)}`)).exitCode !== 0 && !options?.force) throw new Error(`Directory not empty or not found: ${path}`);
|
|
425
|
+
}
|
|
426
|
+
async readdir(path, options) {
|
|
427
|
+
const abs = await this.resolveAsync(path);
|
|
428
|
+
const native = this.sandbox.filesystem;
|
|
429
|
+
if (native) {
|
|
430
|
+
await this.verifyNative("target", abs, path);
|
|
431
|
+
return native.readdir(abs, options);
|
|
432
|
+
}
|
|
433
|
+
await this.assertContainedRealpath(abs, path);
|
|
434
|
+
if (options?.recursive) {
|
|
435
|
+
const result = await this.exec(`test -d ${shellQuote(abs)} && find ${shellQuote(abs)} -mindepth 1 ${options.maxDepth ? `-maxdepth ${Number(options.maxDepth)} ` : ""}2>/dev/null | while IFS= read -r f; do if [ -d "$f" ]; then printf 'd\\t%s\\n' "$f"; else printf 'f\\t%s\\n' "$f"; fi; done`);
|
|
436
|
+
if (result.exitCode !== 0) throw new Error(`Directory not found: ${path}`);
|
|
437
|
+
return this.parseFindOutput(result.stdout, abs, options);
|
|
438
|
+
}
|
|
439
|
+
const result = await this.exec(`cd ${shellQuote(abs)} 2>/dev/null && for f in * .[!.]*; do [ -e "$f" ] || continue; if [ -d "$f" ]; then printf 'd\\t%s\\n' "$f"; else printf 'f\\t%s\\n' "$f"; fi; done`);
|
|
440
|
+
if (result.exitCode !== 0) throw new Error(`Directory not found: ${path}`);
|
|
441
|
+
return this.parseListOutput(result.stdout, options);
|
|
442
|
+
}
|
|
443
|
+
parseListOutput(stdout, options) {
|
|
444
|
+
const entries = [];
|
|
445
|
+
for (const line of stdout.split("\n")) {
|
|
446
|
+
if (!line) continue;
|
|
447
|
+
const tab = line.indexOf(" ");
|
|
448
|
+
if (tab < 0) continue;
|
|
449
|
+
const type = line.slice(0, tab) === "d" ? "directory" : "file";
|
|
450
|
+
const name = line.slice(tab + 1);
|
|
451
|
+
if (!name || name === "." || name === "..") continue;
|
|
452
|
+
if (type === "file" && !this.matchesExtension(name, options?.extension)) continue;
|
|
453
|
+
entries.push({
|
|
454
|
+
name,
|
|
455
|
+
type
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
return entries;
|
|
459
|
+
}
|
|
460
|
+
parseFindOutput(stdout, base, options) {
|
|
461
|
+
const entries = [];
|
|
462
|
+
for (const line of stdout.split("\n")) {
|
|
463
|
+
if (!line) continue;
|
|
464
|
+
const tab = line.indexOf(" ");
|
|
465
|
+
if (tab < 0) continue;
|
|
466
|
+
const type = line.slice(0, tab) === "d" ? "directory" : "file";
|
|
467
|
+
const fullPath = line.slice(tab + 1);
|
|
468
|
+
const name = posix.relative(base, fullPath);
|
|
469
|
+
if (!name) continue;
|
|
470
|
+
if (type === "file" && !this.matchesExtension(name, options?.extension)) continue;
|
|
471
|
+
entries.push({
|
|
472
|
+
name,
|
|
473
|
+
type
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
return entries;
|
|
477
|
+
}
|
|
478
|
+
matchesExtension(name, extension) {
|
|
479
|
+
if (!extension) return true;
|
|
480
|
+
return (Array.isArray(extension) ? extension : [extension]).some((ext) => name.endsWith(ext));
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* Walk the tree in a single sandbox command instead of one readdir round
|
|
484
|
+
* trip per directory. Uses `find` with a portable classification loop
|
|
485
|
+
* (`find -printf` is GNU-only and fails on macOS/BSD hosts). `find` does
|
|
486
|
+
* not follow symlinked directories by default, matching the host-side
|
|
487
|
+
* walker's no-recursion-into-symlinks behavior.
|
|
488
|
+
*/
|
|
489
|
+
async walk(path, options) {
|
|
490
|
+
const abs = await this.resolveAsync(path);
|
|
491
|
+
await this.assertContainedRealpath(abs, path);
|
|
492
|
+
const maxDepth = options?.maxDepth !== void 0 && Number.isFinite(options.maxDepth) ? `-maxdepth ${Math.max(0, Math.floor(options.maxDepth))} ` : "";
|
|
493
|
+
const keepGitignore = options?.includeGitignoreFiles ? `! \\( -type f -name .gitignore \\) ` : "";
|
|
494
|
+
const hiddenPrune = options?.includeHidden ? "" : `\\( -name '.*' ${keepGitignore}\\) -prune -o `;
|
|
495
|
+
const skipNames = options?.skipDirectoryNames?.filter(Boolean) ?? [];
|
|
496
|
+
const skipPrune = skipNames.length ? `\\( -type d \\( ${skipNames.map((name) => `-name ${shellQuote(name)}`).join(" -o ")} \\) \\) -prune -o ` : "";
|
|
497
|
+
const script = `root=${shellQuote(abs)}\n[ -e "$root" ] || [ -L "$root" ] || exit ${EXIT_NOT_FOUND}\n[ -d "$root" ] || exit ${EXIT_NOT_DIRECTORY}\nfind "$root" -mindepth 1 ${maxDepth}${hiddenPrune}${skipPrune}-print 2>/dev/null | while IFS= read -r f; do if [ -L "$f" ]; then if [ -d "$f" ]; then t=D; else t=F; fi; printf '%s\\t%s\\t%s\\n' "$t" "$f" "$(readlink "$f")"; elif [ -d "$f" ]; then printf 'd\\t%s\\n' "$f"; else printf 'f\\t%s\\n' "$f"; fi; done`;
|
|
498
|
+
const result = await this.exec(script);
|
|
499
|
+
if (result.exitCode === EXIT_NOT_FOUND) throw new DirectoryNotFoundError(path);
|
|
500
|
+
if (result.exitCode === EXIT_NOT_DIRECTORY) throw new NotDirectoryError(path);
|
|
501
|
+
if (result.exitCode !== 0) throw new Error(`walk ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);
|
|
502
|
+
const entries = [];
|
|
503
|
+
for (const line of result.stdout.split("\n")) {
|
|
504
|
+
if (!line) continue;
|
|
505
|
+
const tab = line.indexOf(" ");
|
|
506
|
+
if (tab < 0) continue;
|
|
507
|
+
const flag = line.slice(0, tab);
|
|
508
|
+
const isSymlink = flag === "D" || flag === "F";
|
|
509
|
+
let fullPath = line.slice(tab + 1);
|
|
510
|
+
let symlinkTarget;
|
|
511
|
+
if (isSymlink) {
|
|
512
|
+
const tab2 = fullPath.lastIndexOf(" ");
|
|
513
|
+
if (tab2 >= 0) {
|
|
514
|
+
symlinkTarget = fullPath.slice(tab2 + 1) || void 0;
|
|
515
|
+
fullPath = fullPath.slice(0, tab2);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
const rel = posix.relative(abs, fullPath);
|
|
519
|
+
if (!rel || rel.startsWith("..")) continue;
|
|
520
|
+
entries.push({
|
|
521
|
+
name: posix.basename(rel),
|
|
522
|
+
type: flag === "d" || flag === "D" ? "directory" : "file",
|
|
523
|
+
...isSymlink ? {
|
|
524
|
+
isSymlink: true,
|
|
525
|
+
...symlinkTarget ? { symlinkTarget } : {}
|
|
526
|
+
} : {},
|
|
527
|
+
path: rel
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
return entries;
|
|
531
|
+
}
|
|
532
|
+
/**
|
|
533
|
+
* Content search executed inside the sandbox in one command, using the best
|
|
534
|
+
* engine the sandbox has: ripgrep, then GNU grep (with git choosing files
|
|
535
|
+
* inside repositories), then POSIX `grep -rnE`. Patterns the grep engines
|
|
536
|
+
* can't express (PCRE-style classes, word boundaries, lookarounds,
|
|
537
|
+
* non-greedy quantifiers) throw {@link UnsupportedGrepPatternError} so
|
|
538
|
+
* callers use their host-side walk.
|
|
539
|
+
*
|
|
540
|
+
* ripgrep and GNU grep apply every `.gitignore` in the tree, relative to the
|
|
541
|
+
* directory that holds it, and skip `node_modules` unless the search path
|
|
542
|
+
* is inside one. Callers still apply their own hidden/glob filtering.
|
|
543
|
+
*/
|
|
544
|
+
async grep(options) {
|
|
545
|
+
const abs = await this.resolveAsync(options.path);
|
|
546
|
+
await this.assertContainedRealpath(abs, options.path);
|
|
547
|
+
const tools = await this.searchTools();
|
|
548
|
+
if (tools.rg) return this.grepWithRipgrep(abs, options);
|
|
549
|
+
if (tools.gnuGrep) return this.grepWithGnuGrep(abs, options, tools);
|
|
550
|
+
return this.grepWithPosixGrep(abs, options);
|
|
551
|
+
}
|
|
552
|
+
toolsCheck;
|
|
553
|
+
searchTools() {
|
|
554
|
+
const check = this.toolsCheck ??= this.exec(SEARCH_TOOLS_PROBE).then((result) => {
|
|
555
|
+
if (result.exitCode !== 0) throw new Error(`search tool probe exited with ${result.exitCode}`);
|
|
556
|
+
const found = new Set(result.stdout.split("\n").map((line) => line.trim()));
|
|
557
|
+
const git = found.has("git");
|
|
558
|
+
return {
|
|
559
|
+
rg: found.has("rg"),
|
|
560
|
+
gnuGrep: found.has("gnu-grep"),
|
|
561
|
+
git,
|
|
562
|
+
pcre: found.has("grep-pcre") && (!git || found.has("git-pcre"))
|
|
563
|
+
};
|
|
564
|
+
});
|
|
565
|
+
return check.catch(() => {
|
|
566
|
+
if (this.toolsCheck === check) this.toolsCheck = void 0;
|
|
567
|
+
return {
|
|
568
|
+
rg: false,
|
|
569
|
+
gnuGrep: false,
|
|
570
|
+
git: false,
|
|
571
|
+
pcre: false
|
|
572
|
+
};
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
async grepWithRipgrep(abs, options) {
|
|
576
|
+
const args = [
|
|
577
|
+
"rg --json --hidden --no-require-git",
|
|
578
|
+
`-g ${shellQuote("!.git/**")}`,
|
|
579
|
+
isInsideNodeModules(abs) ? "" : `-g ${shellQuote("!**/node_modules/**")}`,
|
|
580
|
+
options.caseSensitive ? "" : "-i",
|
|
581
|
+
options.maxCountPerFile !== void 0 ? `-m ${Math.max(1, Math.floor(options.maxCountPerFile))}` : "",
|
|
582
|
+
options.contextLines ? `-C ${Math.max(0, Math.floor(options.contextLines))}` : "",
|
|
583
|
+
`-e ${shellQuote(options.pattern)}`,
|
|
584
|
+
shellQuote(abs)
|
|
585
|
+
].filter(Boolean).join(" ");
|
|
586
|
+
const result = await this.exec(args);
|
|
587
|
+
if (result.exitCode === 1) return [];
|
|
588
|
+
const results = this.parseRipgrepJson(result.stdout, abs, options);
|
|
589
|
+
if (result.exitCode !== 0 && results.length === 0) throw new UnsupportedGrepPatternError(options.pattern, describeGrepFailure(result));
|
|
590
|
+
return results;
|
|
591
|
+
}
|
|
592
|
+
parseRipgrepJson(stdout, abs, options) {
|
|
593
|
+
const files = /* @__PURE__ */ new Map();
|
|
594
|
+
for (const line of stdout.split("\n")) {
|
|
595
|
+
if (!line) continue;
|
|
596
|
+
let event;
|
|
597
|
+
try {
|
|
598
|
+
event = JSON.parse(line);
|
|
599
|
+
} catch {
|
|
600
|
+
continue;
|
|
601
|
+
}
|
|
602
|
+
if (event.type !== "match" && event.type !== "context") continue;
|
|
603
|
+
const filePath = event.data?.path?.text;
|
|
604
|
+
const lineNumber = event.data?.line_number;
|
|
605
|
+
if (!filePath || !lineNumber) continue;
|
|
606
|
+
const state = fileLines(files, filePath);
|
|
607
|
+
const text = (event.data?.lines?.text ?? "").replace(/\r?\n$/, "");
|
|
608
|
+
state.linesByNumber.set(lineNumber, text);
|
|
609
|
+
if (event.type === "match") {
|
|
610
|
+
const byteStart = event.data?.submatches?.[0]?.start ?? 0;
|
|
611
|
+
const column = Buffer.from(text, "utf8").subarray(0, byteStart).toString("utf8").length;
|
|
612
|
+
state.matches.push({
|
|
613
|
+
line: lineNumber,
|
|
614
|
+
column,
|
|
615
|
+
text
|
|
616
|
+
});
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
return this.applyTotalCap(toGrepResults(files, abs, options.contextLines ?? 0), options.maxTotalMatches);
|
|
620
|
+
}
|
|
621
|
+
/**
|
|
622
|
+
* Patterns whose meaning differs between POSIX ERE and JS RegExp. The grep
|
|
623
|
+
* runs with ERE but match columns are recomputed with JS, so anything that
|
|
624
|
+
* only one side understands (PCRE classes, lookarounds, lazy quantifiers,
|
|
625
|
+
* POSIX bracket classes, GNU word anchors) must fall back to the host walk.
|
|
626
|
+
*/
|
|
627
|
+
static ERE_UNSUPPORTED = /\\[dDwWsSbB<>]|\(\?|[*+?}]\?|\[:[a-z]+:\]/;
|
|
628
|
+
/**
|
|
629
|
+
* Escapes that `grep -P` (PCRE) and JS RegExp (without the `u` flag) both
|
|
630
|
+
* accept but read differently, e.g. `\A` is "start of subject" in PCRE and
|
|
631
|
+
* a literal `A` in JS, plus POSIX bracket classes. PCRE-only syntax that JS
|
|
632
|
+
* rejects (inline flags, possessive quantifiers, atomic groups) already
|
|
633
|
+
* fails the JS compile below.
|
|
634
|
+
*/
|
|
635
|
+
static PCRE_UNSUPPORTED = /\\[AzZGKQEhHvVRXNCpPe]|\[:[a-z]+:\]/;
|
|
636
|
+
/** Reject patterns grep can't run with the same meaning as JS; return the JS regex used for columns. */
|
|
637
|
+
static grepRegex(options, pcre = false) {
|
|
638
|
+
if (pcre ? SandboxFilesystem.PCRE_UNSUPPORTED.test(options.pattern) : SandboxFilesystem.ERE_UNSUPPORTED.test(options.pattern)) throw new UnsupportedGrepPatternError(options.pattern, pcre ? "grep -P reads this syntax differently from JavaScript" : "POSIX ERE cannot express this syntax");
|
|
639
|
+
try {
|
|
640
|
+
return new RegExp(options.pattern, options.caseSensitive ? "" : "i");
|
|
641
|
+
} catch {
|
|
642
|
+
throw new UnsupportedGrepPatternError(options.pattern, "invalid regular expression");
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
/**
|
|
646
|
+
* GNU grep without ripgrep. Inside a git checkout, `git grep` picks the
|
|
647
|
+
* files (tracked plus untracked, every `.gitignore` applied) and GNU grep
|
|
648
|
+
* prints them with context. Outside a checkout (e.g. a multi-repo root),
|
|
649
|
+
* each child repository is searched the same way and plain grep covers the
|
|
650
|
+
* remaining files, skipping `node_modules`. `--null` ends each file name
|
|
651
|
+
* with NUL, so match (`N:`) and context (`N-`) lines parse unambiguously.
|
|
652
|
+
* When grep and git support it, patterns run as PCRE (`-P`), so `\d`,
|
|
653
|
+
* `\w`, `\s`, `\b`, and lookarounds don't need the host walk.
|
|
654
|
+
*/
|
|
655
|
+
async grepWithGnuGrep(abs, options, tools) {
|
|
656
|
+
const hasGit = tools.git;
|
|
657
|
+
const mode = tools.pcre ? "-P" : "-E";
|
|
658
|
+
const jsRegex = SandboxFilesystem.grepRegex(options, tools.pcre);
|
|
659
|
+
const contextLines = Math.max(0, Math.floor(options.contextLines ?? 0));
|
|
660
|
+
const grepFlags = [
|
|
661
|
+
`-HnI${mode.slice(1)} --null`,
|
|
662
|
+
options.caseSensitive ? "" : "-i",
|
|
663
|
+
options.maxCountPerFile !== void 0 ? `-m ${Math.max(1, Math.floor(options.maxCountPerFile))}` : "",
|
|
664
|
+
contextLines > 0 ? `-C ${contextLines}` : ""
|
|
665
|
+
].filter(Boolean).join(" ");
|
|
666
|
+
const skipNodeModules = !isInsideNodeModules(abs);
|
|
667
|
+
const nodeModulesPathspec = skipNodeModules ? ` ${shellQuote(":(exclude,glob)**/node_modules/**")}` : "";
|
|
668
|
+
const pruneNames = skipNodeModules ? "-name .git -o -name node_modules" : "-name .git";
|
|
669
|
+
const script = [
|
|
670
|
+
`pat=${shellQuote(options.pattern)}`,
|
|
671
|
+
`root=${shellQuote(abs)}`,
|
|
672
|
+
`grep ${mode} -e "$pat" </dev/null >/dev/null 2>&1`,
|
|
673
|
+
"if [ $? -eq 2 ]; then echo \"grep: invalid regular expression\" >&2; exit 2; fi",
|
|
674
|
+
"tmp=$(mktemp -d) || exit 1",
|
|
675
|
+
`trap 'rm -rf "$tmp"' EXIT`,
|
|
676
|
+
`search_files() { xargs -0 -r grep ${grepFlags} -e "$pat" -- 2>/dev/null; }`,
|
|
677
|
+
"search_repo() {",
|
|
678
|
+
` git -C "$1" grep -l -z -I --untracked ${options.caseSensitive ? "" : "-i "}${mode} -e "$pat" -- .${nodeModulesPathspec} >"$tmp/files" 2>/dev/null`,
|
|
679
|
+
" [ $? -gt 1 ] && return 1",
|
|
680
|
+
` printf '\\0%s\\n' "$1"`,
|
|
681
|
+
" (cd \"$1\" && search_files) <\"$tmp/files\"",
|
|
682
|
+
"}",
|
|
683
|
+
...hasGit ? [
|
|
684
|
+
"if git -C \"$root\" rev-parse --is-inside-work-tree >/dev/null 2>&1 && ! git -C \"$root\" check-ignore -q . 2>/dev/null; then",
|
|
685
|
+
" search_repo \"$root\" && exit 0",
|
|
686
|
+
"fi",
|
|
687
|
+
`find "$root" -mindepth 1 -maxdepth 3 \\( ${skipNodeModules ? "-name node_modules -prune" : "-false"} \\) -o \\( -name .git -prune -print \\) >"$tmp/repos" 2>/dev/null`,
|
|
688
|
+
": >\"$tmp/done\"",
|
|
689
|
+
"while IFS= read -r g; do",
|
|
690
|
+
" d=${g%/.git}",
|
|
691
|
+
" search_repo \"$d\" && printf '%s\\n' \"$d\" >>\"$tmp/done\"",
|
|
692
|
+
"done <\"$tmp/repos\"",
|
|
693
|
+
"set --",
|
|
694
|
+
"while IFS= read -r d; do set -- \"$@\" -o -path \"$d\"; done <\"$tmp/done\""
|
|
695
|
+
] : ["set --"],
|
|
696
|
+
`printf '\\0%s\\n' "$root"`,
|
|
697
|
+
`find "$root" -mindepth 1 \\( ${pruneNames} "$@" \\) -prune -o -type f -print0 2>/dev/null | search_files`,
|
|
698
|
+
"exit 0"
|
|
699
|
+
].join("\n");
|
|
700
|
+
const result = await this.exec(script);
|
|
701
|
+
if (result.exitCode !== 0) throw new UnsupportedGrepPatternError(options.pattern, describeGrepFailure(result));
|
|
702
|
+
const files = /* @__PURE__ */ new Map();
|
|
703
|
+
let base = abs;
|
|
704
|
+
for (const line of result.stdout.split("\n")) {
|
|
705
|
+
if (!line || line === "--") continue;
|
|
706
|
+
if (line.startsWith("\0")) {
|
|
707
|
+
base = line.slice(1);
|
|
708
|
+
continue;
|
|
709
|
+
}
|
|
710
|
+
const nul = line.indexOf("\0");
|
|
711
|
+
if (nul <= 0) continue;
|
|
712
|
+
const parsed = /^(\d+)([:-])(.*)$/s.exec(line.slice(nul + 1));
|
|
713
|
+
if (!parsed) continue;
|
|
714
|
+
const lineNumber = Number(parsed[1]);
|
|
715
|
+
const text = parsed[3];
|
|
716
|
+
const state = fileLines(files, posix.resolve(base, line.slice(0, nul)));
|
|
717
|
+
state.linesByNumber.set(lineNumber, text);
|
|
718
|
+
if (parsed[2] !== ":") continue;
|
|
719
|
+
const column = jsRegex.exec(text)?.index;
|
|
720
|
+
if (column === void 0) throw new UnsupportedGrepPatternError(options.pattern, "POSIX ERE and JS RegExp disagree on this pattern");
|
|
721
|
+
state.matches.push({
|
|
722
|
+
line: lineNumber,
|
|
723
|
+
column,
|
|
724
|
+
text
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
return this.applyTotalCap(toGrepResults(files, abs, contextLines), options.maxTotalMatches);
|
|
728
|
+
}
|
|
729
|
+
async grepWithPosixGrep(abs, options) {
|
|
730
|
+
const jsRegex = SandboxFilesystem.grepRegex(options);
|
|
731
|
+
if (options.contextLines) throw new UnsupportedGrepPatternError(options.pattern, "context lines are not supported by POSIX grep");
|
|
732
|
+
const args = [
|
|
733
|
+
"grep -rnIE",
|
|
734
|
+
"--exclude-dir=.git",
|
|
735
|
+
options.caseSensitive ? "" : "-i",
|
|
736
|
+
options.maxCountPerFile !== void 0 ? `-m ${Math.max(1, Math.floor(options.maxCountPerFile))}` : "",
|
|
737
|
+
"--",
|
|
738
|
+
shellQuote(options.pattern),
|
|
739
|
+
shellQuote(abs)
|
|
740
|
+
].filter(Boolean).join(" ");
|
|
741
|
+
const result = await this.exec(args);
|
|
742
|
+
if (result.exitCode === 1) return [];
|
|
743
|
+
if (result.exitCode !== 0 && !(result.exitCode === 2 && result.stdout.trim())) throw new UnsupportedGrepPatternError(options.pattern, describeGrepFailure(result));
|
|
744
|
+
const byFile = /* @__PURE__ */ new Map();
|
|
745
|
+
for (const line of result.stdout.split("\n")) {
|
|
746
|
+
if (!line) continue;
|
|
747
|
+
const parsed = /^(.*?):(\d+):(.*)$/.exec(line);
|
|
748
|
+
if (!parsed) continue;
|
|
749
|
+
const rel = posix.relative(abs, parsed[1]) || posix.basename(parsed[1]);
|
|
750
|
+
const text = parsed[3];
|
|
751
|
+
const column = jsRegex.exec(text)?.index;
|
|
752
|
+
if (column === void 0) throw new UnsupportedGrepPatternError(options.pattern, "POSIX ERE and JS RegExp disagree on this pattern");
|
|
753
|
+
let matches = byFile.get(rel);
|
|
754
|
+
if (!matches) {
|
|
755
|
+
matches = [];
|
|
756
|
+
byFile.set(rel, matches);
|
|
757
|
+
}
|
|
758
|
+
matches.push({
|
|
759
|
+
line: Number(parsed[2]),
|
|
760
|
+
column,
|
|
761
|
+
text
|
|
762
|
+
});
|
|
763
|
+
}
|
|
764
|
+
const results = [...byFile.entries()].map(([path, matches]) => ({
|
|
765
|
+
path,
|
|
766
|
+
matches
|
|
767
|
+
}));
|
|
768
|
+
return this.applyTotalCap(results, options.maxTotalMatches);
|
|
769
|
+
}
|
|
770
|
+
applyTotalCap(results, maxTotal) {
|
|
771
|
+
if (maxTotal === void 0) return results;
|
|
772
|
+
const capped = [];
|
|
773
|
+
let total = 0;
|
|
774
|
+
for (const file of results) {
|
|
775
|
+
if (total >= maxTotal) break;
|
|
776
|
+
const remaining = maxTotal - total;
|
|
777
|
+
const matches = file.matches.slice(0, remaining);
|
|
778
|
+
total += matches.length;
|
|
779
|
+
capped.push({
|
|
780
|
+
path: file.path,
|
|
781
|
+
matches
|
|
782
|
+
});
|
|
783
|
+
}
|
|
784
|
+
return capped;
|
|
785
|
+
}
|
|
786
|
+
async exists(path) {
|
|
787
|
+
const abs = await this.resolveAsync(path);
|
|
788
|
+
const native = this.sandbox.filesystem;
|
|
789
|
+
if (native) return native.exists(abs);
|
|
790
|
+
return (await this.exec(`test -e ${shellQuote(abs)}`)).exitCode === 0;
|
|
791
|
+
}
|
|
792
|
+
async stat(path) {
|
|
793
|
+
const abs = await this.resolveAsync(path);
|
|
794
|
+
const native = this.sandbox.filesystem;
|
|
795
|
+
if (native) {
|
|
796
|
+
await this.verifyNative("target", abs, path);
|
|
797
|
+
let info;
|
|
798
|
+
try {
|
|
799
|
+
info = await native.stat(abs);
|
|
800
|
+
} catch (error) {
|
|
801
|
+
throw (error instanceof FileNotFoundError || error?.code === "ENOENT") && await this.outsideWorkdirNotFound(path, abs) || error;
|
|
802
|
+
}
|
|
803
|
+
return {
|
|
804
|
+
...info,
|
|
805
|
+
name: posix.basename(abs),
|
|
806
|
+
path: `/${posix.relative(this.basePath, abs)}`,
|
|
807
|
+
mimeType: info.type === "file" ? info.mimeType ?? getMimeType(abs) : info.mimeType
|
|
808
|
+
};
|
|
809
|
+
}
|
|
810
|
+
await this.assertContainedRealpath(abs, path);
|
|
811
|
+
const result = await this.exec(`stat -L -c '%F|%s|%Y|%W' ${shellQuote(abs)} 2>/dev/null || stat -L -f '%HT|%z|%m|%B' ${shellQuote(abs)}`);
|
|
812
|
+
if (result.exitCode !== 0) throw await this.outsideWorkdirNotFound(path, abs) ?? new FileNotFoundError(path);
|
|
813
|
+
const [kind, sizeStr, mtimeStr, ctimeStr] = result.stdout.trim().split("|");
|
|
814
|
+
const type = kind && kind.toLowerCase().includes("directory") ? "directory" : "file";
|
|
815
|
+
const size = Number(sizeStr) || 0;
|
|
816
|
+
const mtime = Number(mtimeStr) || 0;
|
|
817
|
+
const ctime = Number(ctimeStr);
|
|
818
|
+
return {
|
|
819
|
+
name: posix.basename(abs),
|
|
820
|
+
path: `/${posix.relative(this.basePath, abs)}`,
|
|
821
|
+
type,
|
|
822
|
+
size: type === "directory" ? 0 : size,
|
|
823
|
+
modifiedAt: /* @__PURE__ */ new Date(mtime * 1e3),
|
|
824
|
+
createdAt: /* @__PURE__ */ new Date((ctime > 0 ? ctime : mtime) * 1e3),
|
|
825
|
+
mimeType: type === "file" ? getMimeType(abs) : void 0
|
|
826
|
+
};
|
|
827
|
+
}
|
|
828
|
+
async init() {
|
|
829
|
+
await this.execOk(`mkdir -p ${shellQuote(await this.base())}`, "init workdir");
|
|
830
|
+
}
|
|
831
|
+
async destroy() {}
|
|
832
|
+
async isReady() {
|
|
833
|
+
return (await this.exec(`test -d ${shellQuote(await this.base())}`)).exitCode === 0;
|
|
834
|
+
}
|
|
835
|
+
getInfo() {
|
|
836
|
+
return {
|
|
837
|
+
id: this.id,
|
|
838
|
+
name: this.name,
|
|
839
|
+
provider: this.provider,
|
|
840
|
+
status: this.status,
|
|
841
|
+
metadata: {
|
|
842
|
+
basePath: this.basePath,
|
|
843
|
+
sandboxId: this.sandbox.id
|
|
844
|
+
}
|
|
845
|
+
};
|
|
846
|
+
}
|
|
847
|
+
getInstructions() {
|
|
848
|
+
return `Files are stored in a remote sandbox at ${this.basePath}. Use absolute workspace paths like /src/index.ts. All reads, writes and commands run inside the same sandbox. Absolute paths are workspace-relative (/tmp/x resolves to ${this.basePath}/tmp/x), so file tools cannot reach files outside ${this.basePath}. Create scratch git worktrees under ${this.basePath}/.worktrees/, then, in a pnpm monorepo, run \`pnpm install --prefer-offline --frozen-lockfile\` in the worktree and build the workspace packages you test against (with Turborepo: \`pnpm turbo build --filter="<package>^..."\`, which reuses the build cache).`;
|
|
849
|
+
}
|
|
850
|
+
};
|
|
851
|
+
export { SandboxFilesystem };
|