Skip to content
Source
Sign inSign up
TanStack/ai

fix: make default Daytona + Grok/Codex sandbox runs work #1094

MergedAlemTuzlakmerged 7 commits intomain fromrefs/pull/1094/headmerged by AlemTuzlak View on GitHub

AlemTuzlakcommented

🎯 Changes

Closes #1081, #1083, #1084, #1085.

Default defineSandbox + gitSkill + grokBuildText / codexText + withSandbox works on Daytona without empty commands.deny, a provider create wrapper, hardcoded /home/daytona/workspace, or hand skill symlinks.

#1081 — headless edges

  • Deny-only policy with default: 'allow' stays permissive for headless Grok and Codex (isolation is the outer sandbox).
  • mkdir -p before gitSkill clone.
  • Nested project SKILL.md dirs project by skill name.
  • Daytona remaps /workspace for git, bootstrap, and harness cwd.
  • Durable Grok uses streaming-json when durability is wired and protocol is unset.
  • Headless Grok gets --no-plan --no-auto-update.
  • Codex defaults to danger-full-access on Daytona/Cloudflare (no nested bwrap).
  • Daytona cold snapshots: stop → _experimental_createSnapshot → start (hyphen names).

#1083 — resume after idle stop

  • resume() starts sandboxes in stopped or archived state before returning a handle.
  • Optional autoStopInterval / ephemeral on daytonaSandbox().

#1084 — secrets not in create records or command strings

  • Create/restore do not put secrets in Daytona envVars.
  • ensure() re-applies workspace secrets after resume and restore.
  • Exec env goes through executeCommand(command, cwd, env).
  • Spawn sources a workdir env file so the stored session command has no secret values.
  • Native git clone passes username/password args.

#1085 — use more of the Daytona SDK (no bump past 0.191.0)

  • Spawn follows logs with streaming getSessionCommandLogs.
  • writableStdin: true via sendSessionCommandInput.
  • killableProcesses stays false (honest; PTY kill out of scope).
  • Native sandbox.fs and sandbox.git with /workspace remap.
  • Create forwards name, autoStopInterval, ephemeral, and networkBlockAll from policy.

✅ Checklist

  • I have followed the steps in the Contributing guide.
  • I have tested this code locally with package-scoped pnpm --filter gates (types, oxlint, test:lib, build, test:docs). Full pnpm test:pr / Nx was skipped because leftover nested worktrees/ dirs break the Nx graph on this machine.

🚀 Release Impact

  • This change affects published code, and I have generated a changeset.
  • This change is docs/CI/dev-only (no release).

Test plan

  • @tanstack/ai-sandbox unit tests (642)
  • @tanstack/ai-sandbox-daytona unit tests (29 passed, 3 skipped without DAYTONA_API_KEY)
  • @tanstack/ai-grok-build / @tanstack/ai-codex / @tanstack/ai-acp / @tanstack/ai-claude-code unit tests
  • types + oxlint + build on the six affected packages
  • pnpm test:docs (no broken links)

Summary by CodeRabbit

  • New Features

    • Daytona sandboxes now support snapshots, restoration, auto-stop settings, network restrictions, writable stdin, and improved resume behavior.
    • Secrets are safely reapplied after resume and snapshot restoration.
    • Nested Git-based skills are discovered and installed individually across supported adapters.
    • Durable Grok Build runs use journaled streaming by default for recovery.
    • Provider-specific Codex sandbox defaults are supported.
  • Bug Fixes

    • Improved sandbox filesystem, Git, session, and environment handling.
    • Command deny rules no longer unnecessarily trigger approval mode.
  • Documentation

    • Expanded sandbox provider, policy, lifecycle, provisioning, and adapter guidance.
    1. Review Change Stack

      Note

      Reviews paused

      It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

      Use the following commands to manage reviews:

      • @coderabbitai resume to resume automatic reviews.
      • @coderabbitai review to trigger a single review.

      Use the checkboxes below for quick actions:

      • ▶️ Resume reviews
      • 🔍 Trigger review

      No actionable comments were generated in the recent review. 🎉

      ℹ️ Recent review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 789b4ee7-625c-4064-9043-901c11c74aa9

      📥 Commits

      Reviewing files that changed from the base of the PR and between 5f2de1211ab443764f795ca8a2c13905afbdf444 and 69d36c89e88f1ee76b7470e8a82e1cd95529e6cd.

      📒 Files selected for processing (1)
      • packages/ai-acp/vite.config.ts

      📝 Walkthrough

      Walkthrough

      This change enables default headless Grok and Codex runs on Daytona. It adds native Daytona filesystem, Git, stdin, snapshot, resume, and secret handling. It also discovers nested skills by name and updates policy, protocol, provider, and adapter documentation.

      Changes

      Sandbox foundation and skill discovery

      Layer / File(s)Summary
      Sandbox path, secret, and skill discovery
      packages/ai-sandbox/src/*, packages/ai-sandbox/tests/*
      Workspace paths are remapped for provider workdirs. Clone parents are created. Nested SKILL.md directories are discovered. Workspace secrets are reapplied after resume and snapshot restoration.
      Named nested skill projection
      packages/ai-*/src/adapters/projection.ts, packages/ai-*/tests/*projection*
      ACP, Claude Code, Codex, and Grok project each discovered skill directory under its skill name.

      Daytona provider

      Layer / File(s)Summary
      Native execution and lifecycle
      packages/ai-sandbox-daytona/src/*, packages/ai-sandbox-daytona/tests/*
      Daytona uses native SDK filesystem and Git operations, separate environment handling, streamed logs, writable stdin, snapshots, restoration, network policy, auto-stop, and resume startup.
      Daytona documentation
      docs/sandbox/*, packages/ai-sandbox/README.md, packages/ai-sandbox/skills/ai-sandbox/SKILL.md
      Documentation describes Daytona lifecycle, snapshots, secrets, workdirs, network policy, privileges, stdin, and setup behavior.

      Headless adapter controls

      Layer / File(s)Summary
      Policy and provider-specific Codex behavior
      packages/ai-codex/src/adapters/*, packages/ai-codex/tests/*, docs/adapters/codex.md
      Deny-only policies no longer request approval. Daytona and Cloudflare default to danger-full-access; local-process retains workspace-write.
      Durable Grok protocol behavior
      packages/ai-grok-build/src/adapters/*, packages/ai-grok-build/src/provider-options.ts, packages/ai-grok-build/tests/*, docs/adapters/grok-build.md
      Durable runs default to journaled streaming-json. Auto-approved headless runs add --no-plan and --no-auto-update. Explicit ACP remains supported with documented durability limitations.

      Estimated code review effort: 5 (Critical) | ~90 minutes

      Sequence Diagram(s)

      sequenceDiagram
        participant App
        participant Sandbox
        participant Daytona
        participant Adapter
        App->>Sandbox: defineSandbox and configure workspace
        Sandbox->>Daytona: create or restore sandbox
        Sandbox->>Daytona: project workspace and apply secrets
        App->>Adapter: start Grok or Codex run
        Adapter->>Daytona: execute with provider-specific sandbox settings
        Daytona-->>Adapter: stream output and accept stdin
        Adapter-->>App: return run events
      🚥 Pre-merge checks | ✅ 4 | ❌ 1

      ❌ Failed checks (1 warning)

      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 60.53% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
      ✅ Passed checks (4 passed)
      Check nameStatusExplanation
      Title check✅ PassedThe title clearly summarizes the primary Daytona, Grok, and Codex sandbox fixes.
      Description check✅ PassedThe description includes the required sections, checklist results, release impact, motivation, linked issues, and test plan.
      Linked Issues check✅ PassedThe changes address the linked issue requirements for permissive policies, skill projection, Daytona lifecycle, secrets, durability, and provider defaults [#1081].
      Out of Scope Changes check✅ PassedThe documentation, tests, changeset, and ACP timeout update support the stated sandbox integration objectives.
      ✨ Finishing Touches 💡 2
      📝 Generate docstrings 💡
      • Create stacked PR
      • Commit on current branch
      🛠️ Fix failing CI checks 💡
      • Create stacked PR
      • Commit on current branch
      🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Commit unit tests in branch `fix/1081-daytona-headless-edges`

      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

      ❤️ Share
      Comment `@coderabbitai help` to get the list of available commands.
    2. View your CI Pipeline Execution ↗ for commit 1475a9218e8c2b46ccd8e44d845f542ca2698e5a

      CommandStatusDurationResult
      nx run-many --targets=build --exclude=examples/...✅ Succeeded2sView ↗

      ☁️ Nx Cloud last updated this comment at 2026-08-12 13:59:36 UTC

    3. Open in StackBlitz

      @tanstack/ai

      npm i https://pkg.pr.new/@tanstack/ai@1094

      @tanstack/ai-acp

      npm i https://pkg.pr.new/@tanstack/ai-acp@1094

      @tanstack/ai-angular

      npm i https://pkg.pr.new/@tanstack/ai-angular@1094

      @tanstack/ai-anthropic

      npm i https://pkg.pr.new/@tanstack/ai-anthropic@1094

      @tanstack/ai-bedrock

      npm i https://pkg.pr.new/@tanstack/ai-bedrock@1094

      @tanstack/ai-byteplus

      npm i https://pkg.pr.new/@tanstack/ai-byteplus@1094

      @tanstack/ai-claude-code

      npm i https://pkg.pr.new/@tanstack/ai-claude-code@1094

      @tanstack/ai-client

      npm i https://pkg.pr.new/@tanstack/ai-client@1094

      @tanstack/ai-code-mode

      npm i https://pkg.pr.new/@tanstack/ai-code-mode@1094

      @tanstack/ai-code-mode-skills

      npm i https://pkg.pr.new/@tanstack/ai-code-mode-skills@1094

      @tanstack/ai-codex

      npm i https://pkg.pr.new/@tanstack/ai-codex@1094

      @tanstack/ai-cohere

      npm i https://pkg.pr.new/@tanstack/ai-cohere@1094

      @tanstack/ai-devtools-core

      npm i https://pkg.pr.new/@tanstack/ai-devtools-core@1094

      @tanstack/ai-durable-stream

      npm i https://pkg.pr.new/@tanstack/ai-durable-stream@1094

      @tanstack/ai-elevenlabs

      npm i https://pkg.pr.new/@tanstack/ai-elevenlabs@1094

      @tanstack/ai-event-client

      npm i https://pkg.pr.new/@tanstack/ai-event-client@1094

      @tanstack/ai-fal

      npm i https://pkg.pr.new/@tanstack/ai-fal@1094

      @tanstack/ai-gemini

      npm i https://pkg.pr.new/@tanstack/ai-gemini@1094

      @tanstack/ai-grok

      npm i https://pkg.pr.new/@tanstack/ai-grok@1094

      @tanstack/ai-grok-build

      npm i https://pkg.pr.new/@tanstack/ai-grok-build@1094

      @tanstack/ai-groq

      npm i https://pkg.pr.new/@tanstack/ai-groq@1094

      @tanstack/ai-isolate-cloudflare

      npm i https://pkg.pr.new/@tanstack/ai-isolate-cloudflare@1094

      @tanstack/ai-isolate-daytona

      npm i https://pkg.pr.new/@tanstack/ai-isolate-daytona@1094

      @tanstack/ai-isolate-node

      npm i https://pkg.pr.new/@tanstack/ai-isolate-node@1094

      @tanstack/ai-isolate-quickjs

      npm i https://pkg.pr.new/@tanstack/ai-isolate-quickjs@1094

      @tanstack/ai-isolate-quickjs-bun

      npm i https://pkg.pr.new/@tanstack/ai-isolate-quickjs-bun@1094

      @tanstack/ai-mcp

      npm i https://pkg.pr.new/@tanstack/ai-mcp@1094

      @tanstack/ai-memory

      npm i https://pkg.pr.new/@tanstack/ai-memory@1094

      @tanstack/ai-mistral

      npm i https://pkg.pr.new/@tanstack/ai-mistral@1094

      @tanstack/ai-ollama

      npm i https://pkg.pr.new/@tanstack/ai-ollama@1094

      @tanstack/ai-openai

      npm i https://pkg.pr.new/@tanstack/ai-openai@1094

      @tanstack/ai-opencode

      npm i https://pkg.pr.new/@tanstack/ai-opencode@1094

      @tanstack/ai-openrouter

      npm i https://pkg.pr.new/@tanstack/ai-openrouter@1094

      @tanstack/ai-persistence

      npm i https://pkg.pr.new/@tanstack/ai-persistence@1094

      @tanstack/ai-preact

      npm i https://pkg.pr.new/@tanstack/ai-preact@1094

      @tanstack/ai-react

      npm i https://pkg.pr.new/@tanstack/ai-react@1094

      @tanstack/ai-react-ui

      npm i https://pkg.pr.new/@tanstack/ai-react-ui@1094

      @tanstack/ai-sandbox

      npm i https://pkg.pr.new/@tanstack/ai-sandbox@1094

      @tanstack/ai-sandbox-cloudflare

      npm i https://pkg.pr.new/@tanstack/ai-sandbox-cloudflare@1094

      @tanstack/ai-sandbox-daytona

      npm i https://pkg.pr.new/@tanstack/ai-sandbox-daytona@1094

      @tanstack/ai-sandbox-docker

      npm i https://pkg.pr.new/@tanstack/ai-sandbox-docker@1094

      @tanstack/ai-sandbox-local-process

      npm i https://pkg.pr.new/@tanstack/ai-sandbox-local-process@1094

      @tanstack/ai-sandbox-sprites

      npm i https://pkg.pr.new/@tanstack/ai-sandbox-sprites@1094

      @tanstack/ai-sandbox-vercel

      npm i https://pkg.pr.new/@tanstack/ai-sandbox-vercel@1094

      @tanstack/ai-solid

      npm i https://pkg.pr.new/@tanstack/ai-solid@1094

      @tanstack/ai-solid-ui

      npm i https://pkg.pr.new/@tanstack/ai-solid-ui@1094

      @tanstack/ai-svelte

      npm i https://pkg.pr.new/@tanstack/ai-svelte@1094

      @tanstack/ai-utils

      npm i https://pkg.pr.new/@tanstack/ai-utils@1094

      @tanstack/ai-vue

      npm i https://pkg.pr.new/@tanstack/ai-vue@1094

      @tanstack/ai-vue-ui

      npm i https://pkg.pr.new/@tanstack/ai-vue-ui@1094

      @tanstack/openai-base

      npm i https://pkg.pr.new/@tanstack/openai-base@1094

      @tanstack/preact-ai-devtools

      npm i https://pkg.pr.new/@tanstack/preact-ai-devtools@1094

      @tanstack/react-ai-devtools

      npm i https://pkg.pr.new/@tanstack/react-ai-devtools@1094

      @tanstack/solid-ai-devtools

      npm i https://pkg.pr.new/@tanstack/solid-ai-devtools@1094

      commit: 1475a92

    4. Actionable comments posted: 7

      Caution

      Some comments are outside the diff and can’t be posted inline due to platform limitations.

      ⚠️ Outside diff range comments (2)
      packages/ai-sandbox-daytona/src/handle.ts (1)

      345-373: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

      The log stream promise is unhandled, and the queues can end before the stream drains.

      Two defects in the spawn output path:

      • void this.sandbox.process.getSessionCommandLogs(...) discards the promise. If the WebSocket call rejects (network drop, session gone), the rejection is unhandled. Node can terminate the process on an unhandled rejection.
      • The pump ends stdoutQ and stderrQ and deletes the session as soon as getSessionCommand reports an exitCode. The log stream is independent, so chunks still in flight are dropped. A short command can complete before the first log chunk arrives, and the consumer then reads empty output. The previous implementation had a final flush; it was removed.

      Await the log stream (with a bounded wait) before ending the queues, and attach a rejection handler.

      🐛 Proposed fix: track the stream promise and drain it before ending
      -    void this.sandbox.process.getSessionCommandLogs(
      -      sessionId,
      -      cmdId,
      -      (chunk) => stdoutQ.push(chunk),
      -      (chunk) => stderrQ.push(chunk),
      -    )
      +    const logStream = this.sandbox.process
      +      .getSessionCommandLogs(
      +        sessionId,
      +        cmdId,
      +        (chunk) => stdoutQ.push(chunk),
      +        (chunk) => stderrQ.push(chunk),
      +      )
      +      // A dropped log socket must not become an unhandled rejection; the
      +      // status poll still decides the exit code.
      +      .catch(() => undefined)
       
           const pump = (async (): Promise<void> => {
             try {
               while (!controller.signal.aborted) {
                 const cmd = await this.sandbox.process.getSessionCommand(
                   sessionId,
                   cmdId,
                 )
                 if (cmd.exitCode !== undefined) {
                   exitCode = cmd.exitCode
                   break
                 }
                 await sleep(400)
               }
             } finally {
               opts?.signal?.removeEventListener('abort', onAbort)
      +        // Let the log stream finish so trailing output is not dropped.
      +        await Promise.race([logStream, sleep(1000)])
               stdoutQ.end()
               stderrQ.end()
               await this.sandbox.process.deleteSession(sessionId).catch(() => {})
             }
           })()
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-sandbox-daytona/src/handle.ts` around lines 345 - 373, Update the
      spawn output flow around getSessionCommandLogs and the pump promise to retain
      the log-stream promise, attach rejection handling, and await it with a bounded
      timeout after command completion before ending stdoutQ/stderrQ or deleting the
      session. Preserve abort cleanup while ensuring delayed log chunks are drained
      and stream failures cannot become unhandled rejections.
      packages/ai-codex/src/adapters/policy-map.ts (1)

      48-55: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

      Map default: 'ask' to a fail-closed Codex policy.

      When policy.default === 'ask' and no commands.ask rule exists, approvalPolicy remains unset. text.ts then falls back to 'never', which bypasses approval for unmatched actions. Map this case to 'on-request' or another fail-closed mode, and add a regression test.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-codex/src/adapters/policy-map.ts` around lines 48 - 55, Update
      the approval-policy mapping around hasAsk so policy.default === 'ask' sets
      flags.approvalPolicy to a fail-closed mode such as 'on-request' even when
      policy.commands.ask is absent, preventing the downstream text.ts fallback to
      'never'. Add a regression test covering default ask without an ask command rule
      and verify the resulting policy.
      🧹 Nitpick comments (3)
      .changeset/daytona-headless-edges.md (1)

      2-3: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

      Consider minor for the packages that gain public API surface.

      This change adds new public config fields autoStopInterval and ephemeral to DaytonaSandboxConfig, adds restoreSnapshot and snapshot, and flips snapshots, networkPolicy, and writableStdin to true. Those are feature additions, not only fixes. @tanstack/ai-sandbox-daytona therefore fits a minor bump under the repo convention that shape and behavior changes use minor.

      Based on learnings: "breaking changes and breaking/shape changes documented in Changesets must use a minor version bump (not major)".

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In @.changeset/daytona-headless-edges.md around lines 2 - 3, Update the
      changeset entry for `@tanstack/ai-sandbox-daytona` from patch to minor because its
      public configuration and snapshot APIs gain feature surface and behavior
      changes. Keep `@tanstack/ai-sandbox` at its existing patch level unless the diff
      requires a separate version adjustment.

      Source: Learnings

      packages/ai-sandbox-daytona/tests/handle.test.ts (1)

      128-162: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

      Add fixtures with fs so the new spawn env-file and clone-parent paths execute.

      Both new sandbox fixtures omit fs. createNativeGit().clone guards with if (this.sandbox.fs), and persistSpawnEnvFile returns early when fs is absent. As a result:

      • The clone test at lines 133-162 never runs createFolder for the clone parent, so the parent-creation behavior described in the PR is untested.
      • The env test at lines 329-368 passes because no env file is written at all, not because the command string excludes the value. The assertion cannot fail today.

      Add fs: { createFolder, uploadFile } to these fixtures and assert the env file path and content.

      Also applies to: 329-368

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-sandbox-daytona/tests/handle.test.ts` around lines 128 - 162, Add
      fs fixtures to the DaytonaHandle.git.clone test and the spawn environment test,
      providing createFolder and uploadFile mocks. Assert clone invokes createFolder
      for the remapped clone parent, and assert the environment test writes the
      expected env-file path and content so the command assertion exercises the real
      persistence path.
      packages/ai-grok-build/tests/durability-protocol-warning.test.ts (1)

      230-259: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoff

      Move these unit tests alongside their source modules.

      • packages/ai-grok-build/tests/durability-protocol-warning.test.ts#L230-L259: move this test to packages/ai-grok-build/src/adapters/.
      • packages/ai-grok-build/tests/text-adapter.test.ts#L123-L124: move this test to packages/ai-grok-build/src/adapters/.

      As per coding guidelines: “Unit tests in *.test.ts files alongside source”.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-grok-build/tests/durability-protocol-warning.test.ts` around
      lines 230 - 259, Move the durability-warning test containing “journals a durable
      run when protocol is left unset” from
      packages/ai-grok-build/tests/durability-protocol-warning.test.ts:230-259 into
      packages/ai-grok-build/src/adapters/, preserving its behavior and required
      imports. Also move the referenced test from
      packages/ai-grok-build/tests/text-adapter.test.ts:123-124 into
      packages/ai-grok-build/src/adapters/ alongside its source module.

      Source: Coding guidelines

      🤖 Prompt for all review comments with AI agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      Inline comments:
      In `@packages/ai-acp/tests/sandbox-provisioning.test.ts`:
      - Around line 341-380: Move the nested-skill projection test from
      packages/ai-acp/tests/sandbox-provisioning.test.ts:341-380 to
      packages/ai-acp/src/adapters/projection.test.ts. Move the projection coverage
      and listChildren helper from
      packages/ai-claude-code/tests/projection.test.ts:244-284,
      packages/ai-codex/tests/projection.test.ts:245-285, and
      packages/ai-grok-build/tests/projection.test.ts:295-337 into each corresponding
      packages/*/src/adapters/projection.test.ts file, keeping the existing test
      behavior and adapting imports as needed.
      
      In `@packages/ai-codex/src/adapters/text.ts`:
      - Around line 54-65: Update the CodexTextConfig.sandboxMode comment to document
      that defaultSandboxMode uses 'danger-full-access' for Daytona and Cloudflare,
      and 'workspace-write' for all other providers; leave the implementation
      unchanged.
      
      In `@packages/ai-grok-build/src/adapters/policy-map.ts`:
      - Around line 7-11: Enforce commands.deny before starting the harness in both
      Grok execution paths: the NDJSON grok -p path and the ACP path using
      SandboxHandle.process.exec. Pass the denied-command policy into each execution
      path so denied commands remain blocked regardless of --always-approve or the
      default ACP permission mode.
      
      In `@packages/ai-sandbox-daytona/src/handle.ts`:
      - Around line 226-241: Update persistSpawnEnvFile and the spawnProcess command
      flow to create a unique environment-file path for each spawn, preventing
      concurrent processes from sharing values. Ensure the generated command sources
      that file and removes it immediately afterward, including cleanup when command
      execution fails, so secret values are not retained in the workspace or
      snapshots.
      - Around line 243-287: Update createNativeGit().clone to accept the requested
      depth, pass numeric depths to sandbox.git.clone, and represent 'full' as an
      unbounded clone using Daytona’s native API contract. Update SandboxGit.status()
      or its public contract so the returned JSON format is explicitly documented as
      Daytona-specific, while preserving compatibility with the exec-backed adapter if
      required by the shared interface.
      
      In `@packages/ai-sandbox-daytona/src/provider.ts`:
      - Around line 36-44: Update the configuration validation around the provider
      options and DaytonaHandle.snapshot flow so ephemeral sandboxes cannot be
      combined with snapshots enabled and the resulting lifecycle.snapshot value of
      'after-setup'. Require lifecycle.snapshot to be explicitly 'none' for ephemeral:
      true, or reject the incompatible configuration before ensure() attempts to
      return the sandbox.
      
      In `@packages/ai-sandbox/src/bootstrap.ts`:
      - Around line 102-105: Ensure the normalized destination produced by
      resolveHarnessCwd in the bootstrap flow is also used by WorkspaceProjection and
      the Grok, Codex, Claude Code, and ACP projectors instead of raw skill.into
      values. Preserve default resolveGitSkillDir behavior, and add Daytona coverage
      verifying an explicit gitSkill({ into: ... }) projects from the resolved clone
      path.
      
      ---
      
      Outside diff comments:
      In `@packages/ai-codex/src/adapters/policy-map.ts`:
      - Around line 48-55: Update the approval-policy mapping around hasAsk so
      policy.default === 'ask' sets flags.approvalPolicy to a fail-closed mode such as
      'on-request' even when policy.commands.ask is absent, preventing the downstream
      text.ts fallback to 'never'. Add a regression test covering default ask without
      an ask command rule and verify the resulting policy.
      
      In `@packages/ai-sandbox-daytona/src/handle.ts`:
      - Around line 345-373: Update the spawn output flow around getSessionCommandLogs
      and the pump promise to retain the log-stream promise, attach rejection
      handling, and await it with a bounded timeout after command completion before
      ending stdoutQ/stderrQ or deleting the session. Preserve abort cleanup while
      ensuring delayed log chunks are drained and stream failures cannot become
      unhandled rejections.
      
      ---
      
      Nitpick comments:
      In @.changeset/daytona-headless-edges.md:
      - Around line 2-3: Update the changeset entry for `@tanstack/ai-sandbox-daytona`
      from patch to minor because its public configuration and snapshot APIs gain
      feature surface and behavior changes. Keep `@tanstack/ai-sandbox` at its existing
      patch level unless the diff requires a separate version adjustment.
      
      In `@packages/ai-grok-build/tests/durability-protocol-warning.test.ts`:
      - Around line 230-259: Move the durability-warning test containing “journals a
      durable run when protocol is left unset” from
      packages/ai-grok-build/tests/durability-protocol-warning.test.ts:230-259 into
      packages/ai-grok-build/src/adapters/, preserving its behavior and required
      imports. Also move the referenced test from
      packages/ai-grok-build/tests/text-adapter.test.ts:123-124 into
      packages/ai-grok-build/src/adapters/ alongside its source module.
      
      In `@packages/ai-sandbox-daytona/tests/handle.test.ts`:
      - Around line 128-162: Add fs fixtures to the DaytonaHandle.git.clone test and
      the spawn environment test, providing createFolder and uploadFile mocks. Assert
      clone invokes createFolder for the remapped clone parent, and assert the
      environment test writes the expected env-file path and content so the command
      assertion exercises the real persistence path.
      🪄 Autofix

      Fix all unresolved CodeRabbit comments on this PR:

      • Push a commit to this branch (recommended)
      • Create a new PR with the fixes

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 9f8f7fc4-1f74-4bb3-a9ce-1eaf4e79d61c

      📥 Commits

      Reviewing files that changed from the base of the PR and between 24622c7927c734bf493cfc332b6baecc4483f366 and 831556a8604786133b3d80f06704cf2abfeff049.

      📒 Files selected for processing (44)
      • .changeset/daytona-headless-edges.md
      • docs/adapters/codex.md
      • docs/adapters/grok-build.md
      • docs/config.json
      • docs/sandbox/lifecycle.md
      • docs/sandbox/policy.md
      • docs/sandbox/providers.md
      • docs/sandbox/provisioning.md
      • docs/sandbox/workspace.md
      • packages/ai-acp/src/adapters/projection.ts
      • packages/ai-acp/tests/sandbox-provisioning.test.ts
      • packages/ai-claude-code/src/adapters/projection.ts
      • packages/ai-claude-code/tests/projection.test.ts
      • packages/ai-codex/src/adapters/policy-map.ts
      • packages/ai-codex/src/adapters/projection.ts
      • packages/ai-codex/src/adapters/text.ts
      • packages/ai-codex/tests/policy-map.test.ts
      • packages/ai-codex/tests/projection.test.ts
      • packages/ai-codex/tests/text-adapter.test.ts
      • packages/ai-grok-build/src/adapters/policy-map.ts
      • packages/ai-grok-build/src/adapters/projection.ts
      • packages/ai-grok-build/src/adapters/text.ts
      • packages/ai-grok-build/src/provider-options.ts
      • packages/ai-grok-build/tests/durability-protocol-warning.test.ts
      • packages/ai-grok-build/tests/policy-map.test.ts
      • packages/ai-grok-build/tests/projection.test.ts
      • packages/ai-grok-build/tests/text-adapter.test.ts
      • packages/ai-sandbox-daytona/src/handle.ts
      • packages/ai-sandbox-daytona/src/provider.ts
      • packages/ai-sandbox-daytona/tests/handle.test.ts
      • packages/ai-sandbox-daytona/tests/provider.test.ts
      • packages/ai-sandbox/README.md
      • packages/ai-sandbox/skills/ai-sandbox/SKILL.md
      • packages/ai-sandbox/src/agents-file.ts
      • packages/ai-sandbox/src/bootstrap.ts
      • packages/ai-sandbox/src/git-exec.ts
      • packages/ai-sandbox/src/index.ts
      • packages/ai-sandbox/src/middleware.ts
      • packages/ai-sandbox/src/sandbox.ts
      • packages/ai-sandbox/tests/agents-file.test.ts
      • packages/ai-sandbox/tests/bootstrap.test.ts
      • packages/ai-sandbox/tests/ensure.test.ts
      • packages/ai-sandbox/tests/git-exec.test.ts
      • packages/ai-sandbox/tests/harness-cwd.test.ts
      packages/ai-acp/tests/sandbox-provisioning.test.ts lines 341 to 380
      @@ -339,0 +360,21 @@
      360+ ],
      361+ plugins: [],
      362+ resolveSecret: () => '',
      363+ markerPath: '/workspace/.tanstack-projected-nested',
      364+ root: '/workspace',
      365+ }
      366+
      367+ await projectAcpWorkspace(sbx, projection, {
      368+ skillsDir: '.pi/skills',
      369+ harnessName: 'pi',
      370+ })
      371+
      372+ expect(await sbx.fs.read('/workspace/.pi/skills/foo/SKILL.md')).toBe(
      373+ 'foo-skill',
      374+ )
      375+ expect(await sbx.fs.read('/workspace/.pi/skills/bar/SKILL.md')).toBe(
      376+ 'bar-skill',
      377+ )
      378+ expect(await sbx.fs.exists('/workspace/.pi/skills/skills-pack')).toBe(false)
      379+ await sbx.destroy()
      380+ })

      📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy lift

      Place the added unit tests beside their source modules.

      Move the added coverage and its supporting test helpers into source-adjacent *.test.ts files.

      • packages/ai-acp/tests/sandbox-provisioning.test.ts#L341-L380: Move this projection coverage to packages/ai-acp/src/adapters/projection.test.ts.
      • packages/ai-claude-code/tests/projection.test.ts#L244-L284: Move this coverage and listChildren support to packages/ai-claude-code/src/adapters/projection.test.ts.
      • packages/ai-codex/tests/projection.test.ts#L245-L285: Move this coverage and listChildren support to packages/ai-codex/src/adapters/projection.test.ts.
      • packages/ai-grok-build/tests/projection.test.ts#L295-L337: Move this coverage and listChildren support to packages/ai-grok-build/src/adapters/projection.test.ts.

      As per coding guidelines, “Unit tests in *.test.ts files alongside source”.

      📍 Affects 4 files
      • packages/ai-acp/tests/sandbox-provisioning.test.ts#L341-L380 (this comment)
      • packages/ai-claude-code/tests/projection.test.ts#L244-L284
      • packages/ai-codex/tests/projection.test.ts#L245-L285
      • packages/ai-grok-build/tests/projection.test.ts#L295-L337
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-acp/tests/sandbox-provisioning.test.ts` around lines 341 - 380,
      Move the nested-skill projection test from
      packages/ai-acp/tests/sandbox-provisioning.test.ts:341-380 to
      packages/ai-acp/src/adapters/projection.test.ts. Move the projection coverage
      and listChildren helper from
      packages/ai-claude-code/tests/projection.test.ts:244-284,
      packages/ai-codex/tests/projection.test.ts:245-285, and
      packages/ai-grok-build/tests/projection.test.ts:295-337 into each corresponding
      packages/*/src/adapters/projection.test.ts file, keeping the existing test
      behavior and adapting imports as needed.

      Source: Coding guidelines

      packages/ai-codex/src/adapters/text.ts lines 54 to 65
      @@ -51,3 +51,15 @@
      5151
      5252 const DEFAULT_WORKDIR = '/workspace'
      5353
      54+/**
      55+ * Providers that already isolate the agent in a VM or container where Codex
      56+ * cannot create a nested bubblewrap user namespace. Isolation is then the
      57+ * outer sandbox plus `defineSandboxPolicy`. Issue #1081 item 8.
      58+ */
      59+const NESTED_BWRAP_UNSUPPORTED = new Set(['daytona', 'cloudflare'])
      60+
      61+function defaultSandboxMode(provider: string): CodexSandboxMode {
      62+ return NESTED_BWRAP_UNSUPPORTED.has(provider)
      63+ ? 'danger-full-access'
      64+ : 'workspace-write'
      65+}

      📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

      🧩 Analysis chain

      🏁 Script executed:

      #!/bin/bash
      set -e
      printf '%s\n' '--- target file outline ---'
      ast-grep outline packages/ai-codex/src/adapters/text.ts
      printf '%s\n' '--- target file sections ---'
      cat -n packages/ai-codex/src/adapters/text.ts | sed -n '1,130p'
      printf '%s\n' '--- sandbox mode references ---'
      rg -n --glob '*.{ts,tsx,md}' 'sandboxMode|defaultSandboxMode|NESTED_BWRAP_UNSUPPORTED|danger-full-access|workspace-write' packages/ai-codex docs 2>/dev/null | head -250

      Repository: TanStack/ai

      Length of output: 9591


      🏁 Script executed:

      #!/bin/bash
      set -e
      printf '%s\n' '--- default resolution and provider source ---'
      cat -n packages/ai-codex/src/adapters/text.ts | sed -n '122,185p'
      printf '%s\n' '--- provider options ---'
      cat -n packages/ai-codex/src/provider-options.ts | sed -n '1,100p'
      printf '%s\n' '--- relevant tests ---'
      cat -n packages/ai-codex/tests/text-adapter.test.ts | sed -n '120,205p'
      printf '%s\n' '--- provider identity and sandbox capability definitions ---'
      rg -n --glob '*.{ts,tsx}' 'provider(Name|Id)?|provider:|name:.*daytona|cloudflare|SandboxHandle|defineSandboxPolicy' packages/ai-codex packages/ai-sandbox* packages | head -300

      Repository: TanStack/ai

      Length of output: 37900


      🏁 Script executed:

      #!/bin/bash
      set -e
      python3 - <<'PY'
      from pathlib import Path
      import re
      
      path = Path("packages/ai-codex/src/adapters/text.ts")
      text = path.read_text()
      
      providers = re.search(
          r"const NESTED_BWRAP_UNSUPPORTED = new Set\(\[([^\]]+)\]\)", text
      ).group(1)
      unsupported = {item.strip().strip("'\"") for item in providers.split(",") if item.strip()}
      
      body = re.search(
          r"function defaultSandboxMode\(provider: string\): CodexSandboxMode \{(.*?)\n\}",
          text,
          re.S,
      ).group(1)
      
      def default_mode(provider):
          return "danger-full-access" if provider in unsupported else "workspace-write"
      
      expected = {
          "daytona": "danger-full-access",
          "cloudflare": "danger-full-access",
          "local-process": "workspace-write",
          "docker": "workspace-write",
          "vercel": "workspace-write",
          "sprites": "workspace-write",
      }
      assert unsupported == {"daytona", "cloudflare"}
      assert "defaultSandboxMode(provider)" in text
      assert "'workspace-write'" in body and "'danger-full-access'" in body
      for provider, expected_mode in expected.items():
          assert default_mode(provider) == expected_mode, (provider, default_mode(provider))
      
      comment = text[text.index("Codex's own sandbox mode"):text.index("sandboxMode?:", text.index("Codex's own sandbox mode"))]
      assert "Defaults to 'workspace-write'" in comment
      assert "Daytona" not in comment and "Cloudflare" not in comment
      
      print("defaultSandboxMode mapping:", expected)
      print("CodexTextConfig.sandboxMode documentation omits the provider-dependent defaults.")
      PY

      Repository: TanStack/ai

      Length of output: 238


      🏁 Script executed:

      #!/bin/bash
      set -e
      python3 - <<'PY'
      from pathlib import Path
      import re
      
      text = Path("packages/ai-codex/src/adapters/text.ts").read_text()
      match = re.search(
          r"const NESTED_BWRAP_UNSUPPORTED = new Set\(\[([^\]]+)\]\)", text
      )
      assert match, "unsupported-provider set not found"
      unsupported = {item.strip().strip("'\"") for item in match.group(1).split(",")}
      
      def default_mode(provider):
          return "danger-full-access" if provider in unsupported else "workspace-write"
      
      expected = {
          "daytona": "danger-full-access",
          "cloudflare": "danger-full-access",
          "local-process": "workspace-write",
          "docker": "workspace-write",
          "vercel": "workspace-write",
          "sprites": "workspace-write",
      }
      assert unsupported == {"daytona", "cloudflare"}
      for provider, expected_mode in expected.items():
          assert default_mode(provider) == expected_mode
      
      start = text.index("Codex's own sandbox mode")
      end = text.index("sandboxMode?:", start)
      comment = text[start:end]
      assert "Defaults to `'workspace-write'`" in comment
      assert "Daytona" not in comment and "Cloudflare" not in comment
      
      print("default mapping:", expected)
      print("documentation still states only the workspace-write default")
      PY

      Repository: TanStack/ai

      Length of output: 420


      Document the provider-dependent sandboxMode default.

      defaultSandboxMode(provider) uses 'danger-full-access' for Daytona and Cloudflare, and 'workspace-write' for other providers. Update the CodexTextConfig.sandboxMode comment to describe both defaults.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-codex/src/adapters/text.ts` around lines 54 - 65, Update the
      CodexTextConfig.sandboxMode comment to document that defaultSandboxMode uses
      'danger-full-access' for Daytona and Cloudflare, and 'workspace-write' for all
      other providers; leave the implementation unchanged.
      packages/ai-grok-build/src/adapters/policy-map.ts lines 7 to 11
      @@ -4,5 +4,8 @@
      44 * Coarse mapping for the headless NDJSON harness (`grok -p`):
      55 * - `capabilities.fileWrite === 'deny'` → `--sandbox read-only`
      66 * - `capabilities.network === 'deny'` → `--disable-web-search`
      7- * - `default: 'deny'`, `default: 'ask'`, or ask/deny rules → conservative
      8- * (omit `--always-approve`, use `--permission-mode default`)
      7+ * - `default: 'deny'`, `default: 'ask'`, or `commands.ask` → conservative
      8+ * (omit `--always-approve`, use `--permission-mode default`).
      9+ * A deny list alone is a hard block, not a human prompt, so it does
      10+ * not flip the approval flag. Headless `grok -p` auto-cancels tools
      11+ * when conservative is true.

      🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

      🧩 Analysis chain

      🏁 Script executed:

      #!/bin/bash
      set -euo pipefail
      
      pnpm install --ignore-scripts
      
      rg -n -C 5 --glob '*.ts' \
        'commands\??\.(deny|ask)|commands:\s*\{|defineSandboxPolicy' \
        packages/ai-sandbox packages/ai-grok-build packages/ai-sandbox-daytona
      
      rg -n -C 5 --glob '*.ts' \
        'process\.exec\(|spawnNdjson\(|--always-approve|permission-mode' \
        packages/ai-sandbox packages/ai-grok-build packages/ai-sandbox-daytona

      Repository: TanStack/ai

      Length of output: 50367


      🏁 Script executed:

      #!/bin/bash
      set -euo pipefail
      
      printf '%s\n' '--- candidate files ---'
      git ls-files 'packages/ai-sandbox/src' 'packages/ai-grok-build/src' 'packages/ai-sandbox-local-process/src' 'packages/ai-sandbox-daytona/src' |
        rg '(policy|approval|middleware|contracts|text|provider|process|handle|index)\.(ts|tsx)$' |
        head -200
      
      printf '%s\n' '--- policy and approval call sites ---'
      rg -n -C 4 --glob '*.ts' \
        'evaluateCommand|resolveApproval|policy\b|capabilities\?\.policy|capability.*policy|SandboxPolicy' \
        packages/ai-sandbox/src packages/ai-grok-build/src packages/ai-sandbox-local-process/src packages/ai-sandbox-daytona/src
      
      printf '%s\n' '--- process.exec definitions and adapter execution path ---'
      rg -n -C 8 --glob '*.ts' \
        '(process:\s*\{|exec:\s*(async\s*)?\(|process\.exec\s*=|spawnNdjson\(|buildCommand\(|runCommand)' \
        packages/ai-sandbox/src packages/ai-grok-build/src packages/ai-sandbox-local-process/src packages/ai-sandbox-daytona/src

      Repository: TanStack/ai

      Length of output: 49336


      🏁 Script executed:

      #!/bin/bash
      set -euo pipefail
      
      printf '%s\n' '--- policy implementation ---'
      sed -n '1,240p' packages/ai-sandbox/src/policy.ts
      
      printf '%s\n' '--- approval implementation ---'
      sed -n '1,220p' packages/ai-sandbox/src/approvals.ts
      
      printf '%s\n' '--- text adapter policy and command construction ---'
      sed -n '130,215p' packages/ai-grok-build/src/adapters/text.ts
      sed -n '560,640p' packages/ai-grok-build/src/adapters/text.ts
      
      printf '%s\n' '--- capability context and middleware policy handling ---'
      rg -n -C 8 --glob '*.ts' \
        'CapabilityContext|capabilityContext|policy|resolveApproval|evaluateCommand' \
        packages/ai-grok-build/src packages/ai-sandbox/src/middleware.ts packages/ai-sandbox/src/contracts.ts

      Repository: TanStack/ai

      Length of output: 36349


      🏁 Script executed:

      #!/bin/bash
      set -euo pipefail
      
      printf '%s\n' '--- provider process implementations ---'
      rg -l --glob '*.ts' 'process:\s*\{|exec:\s*(async\s*)?\(' packages |
        while IFS= read -r file; do
          if rg -q 'process:\s*\{|exec:\s*(async\s*)?\(' "$file"; then
            printf '\n### %s\n' "$file"
            rg -n -C 12 'process:\s*\{|exec:\s*(async\s*)?\(' "$file" | head -160
          fi
        done
      
      printf '%s\n' '--- policy-bearing adapter inputs and factory wiring ---'
      rg -n -C 10 --glob '*.ts' \
        'mapPolicyToGrokBuildFlags|policyFlags|capabilities.*policy|policy.*capabilities|GrokBuildTextAdapter|new GrokBuild|grokBuildText' \
        packages/ai-grok-build/src

      Repository: TanStack/ai

      Length of output: 50367


      🏁 Script executed:

      #!/bin/bash
      set -euo pipefail
      
      printf '%s\n' '--- Grok approval and permission handling ---'
      rg -n -C 10 --glob '*.ts' \
        'resolveApproval|evaluateCommand|canUseTool|permissionMode|permission_request|tool_call|approval|deny|allow' \
        packages/ai-grok-build/src packages/ai-acp/src packages/ai-codex/src
      
      printf '%s\n' '--- concrete provider exec methods ---'
      rg -n -C 18 --glob '*.ts' \
        'private (async )?exec|async exec\(|function exec\(' \
        packages/ai-sandbox-local-process/src/handle.ts \
        packages/ai-sandbox-daytona/src/handle.ts \
        packages/ai-sandbox-docker/src/handle.ts \
        packages/ai-sandbox-sprites/src/handle.ts
      
      printf '%s\n' '--- all production evaluateCommand and resolveApproval uses ---'
      rg -n --glob '*.ts' \
        'evaluateCommand|resolveApproval' packages --glob '!**/tests/**'

      Repository: TanStack/ai

      Length of output: 50367


      🏁 Script executed:

      #!/bin/bash
      set -euo pipefail
      
      python3 - <<'PY'
      from pathlib import Path
      import re
      
      files = {
          "policy_map": Path("packages/ai-grok-build/src/adapters/policy-map.ts"),
          "text_adapter": Path("packages/ai-grok-build/src/adapters/text.ts"),
          "approvals": Path("packages/ai-sandbox/src/approvals.ts"),
          "policy": Path("packages/ai-sandbox/src/policy.ts"),
      }
      
      text = {name: path.read_text() for name, path in files.items()}
      
      print("policy_map_reads_deny:", bool(re.search(r"commands\??\.deny|commands\.deny", text["policy_map"])))
      print("policy_map_reads_allow:", bool(re.search(r"commands\??\.allow|commands\.allow", text["policy_map"])))
      print("text_adapter_calls_evaluateCommand:", "evaluateCommand" in text["text_adapter"])
      print("text_adapter_calls_resolveApproval:", "resolveApproval" in text["text_adapter"])
      print("text_adapter_maps_policy_to_flags:", "mapPolicyToGrokBuildFlags(policy)" in text["text_adapter"])
      print("text_adapter_spawns_built_command:", "spawnNdjson(sandbox, runCommand" in text["text_adapter"])
      print("approval_module_calls_evaluateCommand:", "evaluateCommand(input.command" in text["approvals"])
      
      # Print the exact production call-site files for the policy evaluator.
      for path in Path("packages").rglob("*.ts"):
          if "/tests/" in str(path):
              continue
          body = path.read_text()
          if "evaluateCommand" in body or "resolveApproval" in body:
              print("production_policy_callsite:", path)
      PY

      Repository: TanStack/ai

      Length of output: 677


      Enforce denied commands in both Grok execution paths.

      commands.deny is not passed to Grok or SandboxHandle.process.exec. A permissive policy can therefore run denied commands with --always-approve in the NDJSON path and the default ACP permission mode. Add command-level enforcement before starting the harness.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-grok-build/src/adapters/policy-map.ts` around lines 7 - 11,
      Enforce commands.deny before starting the harness in both Grok execution paths:
      the NDJSON grok -p path and the ACP path using SandboxHandle.process.exec. Pass
      the denied-command policy into each execution path so denied commands remain
      blocked regardless of --always-approve or the default ACP permission mode.
      packages/ai-sandbox-daytona/src/handle.ts lines 226 to 241
      @@ -238,7 +227,15 @@
      227+ * Session execute has no env field. Write values to a workdir file,
      228+ * then source that file so the stored command never contains secrets.
      238229 */
      239- private withEnv(command: string, extra?: Record<string, string>): string {
      240- const merged = { ...this.envVars, ...extra }
      241- const exports = Object.entries(merged)
      242- .map(([k, v]) => `export ${k}=${q(v)}; `)
      243- .join('')
      244- return `${exports}${command}`
      230+ private async persistSpawnEnvFile(
      231+ env: Record<string, string>,
      232+ ): Promise<string | undefined> {
      233+ if (!this.sandbox.fs) return undefined
      234+ const path = `${this.workdir}/.tanstack-ai-env`
      235+ const body = Object.entries(env)
      236+ .map(([key, value]) => `${key}=${q(value)}`)
      237+ .join('\n')
      238+ await this.sandbox.fs.createFolder(this.workdir, '755')
      239+ await this.sandbox.fs.uploadFile(Buffer.from(`${body}\n`, 'utf8'), path)
      240+ return path
      241+ }

      🔒 Security & Privacy | 🔴 Critical | 🏗️ Heavy lift

      The spawn env file uses one fixed path and stays on disk with secret values.

      persistSpawnEnvFile always writes ${workdir}/.tanstack-ai-env. Two problems follow.

      1. Concurrency: every spawnProcess call writes the same path. If spawn B writes the file after spawn A wrote it but before A's command sources it, A reads B's values. The handle supports several concurrent spawns, so this race is reachable.
      2. Retention: the file is never removed. It holds resolved secret values in the workspace root. snapshot() captures the filesystem, so those values land in the Daytona snapshot. An agent running git add -A in the workspace can also commit it. This contradicts the file header claim that secret values stay out of persisted surfaces.

      Use a unique path per session and delete it after the command sources it.

      🔒 Proposed fix: per-session env file, removed after sourcing
         private async persistSpawnEnvFile(
           env: Record<string, string>,
      +    sessionId: string,
         ): Promise<string | undefined> {
           if (!this.sandbox.fs) return undefined
      -    const path = `${this.workdir}/.tanstack-ai-env`
      +    const path = `${this.workdir}/.tanstack-ai-env-${sessionId}`
           const body = Object.entries(env)
             .map(([key, value]) => `${key}=${q(value)}`)
             .join('\n')
           await this.sandbox.fs.createFolder(this.workdir, '755')
           await this.sandbox.fs.uploadFile(Buffer.from(`${body}\n`, 'utf8'), path)
           return path
         }
           const envFile =
             Object.keys(env).length > 0
      -        ? await this.persistSpawnEnvFile(env)
      +        ? await this.persistSpawnEnvFile(env, sessionId)
               : undefined
           const wrapped = envFile
      -      ? `set -a; . ${q(envFile)}; set +a; cd ${q(cwd)} && ${command}`
      +      ? `set -a; . ${q(envFile)}; set +a; rm -f ${q(envFile)}; cd ${q(cwd)} && ${command}`
             : `cd ${q(cwd)} && ${command}`

      Also applies to: 317-324

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-sandbox-daytona/src/handle.ts` around lines 226 - 241, Update
      persistSpawnEnvFile and the spawnProcess command flow to create a unique
      environment-file path for each spawn, preventing concurrent processes from
      sharing values. Ensure the generated command sources that file and removes it
      immediately afterward, including cleanup when command execution fails, so secret
      values are not retained in the workspace or snapshots.
      packages/ai-sandbox-daytona/src/handle.ts lines 243 to 287
      @@ -245 +267,21 @@
      267+ },
      268+ commit: async (message, dir) => {
      269+ await this.sandbox.git.commit(
      270+ repoPath(dir),
      271+ message,
      272+ 'tanstack-ai',
      273+ 'sandbox@tanstack.ai',
      274+ )
      275+ },
      276+ push: async (dir) => {
      277+ await this.sandbox.git.push(repoPath(dir))
      278+ },
      279+ pull: async (dir) => {
      280+ await this.sandbox.git.pull(repoPath(dir))
      281+ },
      282+ branch: async (dir) => {
      283+ const status = await this.sandbox.git.status(repoPath(dir))
      284+ return status.currentBranch
      285+ },
      286+ }
      245287 }

      🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

      🧩 Analysis chain

      🏁 Script executed:

      #!/bin/bash
      # Description: Find consumers of SandboxGit.status and depth to check the contract.
      set -euo pipefail
      
      rg -nP --type=ts -C4 '\.git\.status\s*\(' packages
      rg -nP --type=ts -C4 '\bdepth\s*:' packages | rg -n 'clone|git' -C4 || true
      rg -nP --type=ts -C6 '\bclone\s*\(' packages/ai-sandbox/src

      Repository: TanStack/ai

      Length of output: 9326


      🏁 Script executed:

      #!/bin/bash
      set -euo pipefail
      
      printf '%s\n' '--- contracts ---'
      sed -n '110,155p' packages/ai-sandbox/src/contracts.ts
      
      printf '%s\n' '--- exec git implementation ---'
      ast-grep outline packages/ai-sandbox/src/git-exec.ts
      sed -n '1,180p' packages/ai-sandbox/src/git-exec.ts
      
      printf '%s\n' '--- Daytona types and adapter construction ---'
      rg -n -C5 'SandboxGit|createNativeGit|git:' packages/ai-sandbox-daytona/src packages/ai-sandbox/src
      sed -n '220,295p' packages/ai-sandbox-daytona/src/handle.ts
      
      printf '%s\n' '--- all status consumers and tests ---'
      rg -n -C5 'status\s*\(' packages/ai-sandbox packages/ai-sandbox-daytona --glob '*.{ts,tsx}'
      rg -n -C5 'git\.status|\.status\(' packages --glob '*.{ts,tsx}' | head -250

      Repository: TanStack/ai

      Length of output: 41499


      🏁 Script executed:

      #!/bin/bash
      set -euo pipefail
      
      printf '%s\n' '--- Daytona package metadata and tests ---'
      sed -n '1,180p' packages/ai-sandbox-daytona/package.json
      rg -n -C6 'native git|createNativeGit|clone|status|depth' packages/ai-sandbox-daytona --glob '*.{ts,tsx,md,json}'
      
      printf '%s\n' '--- Daytona SDK references ---'
      rg -n -C4 'daytona|Git|git\.clone|git\.status' package.json pnpm-lock.yaml packages --glob '*.{json,yaml,yml,ts,tsx,md}' | head -300
      
      printf '%s\n' '--- status call graph outside adapters ---'
      rg -n -P '\b(?:handle|sandbox|workspace)\.git\.status\s*\(' . --glob '*.{ts,tsx,js,jsx,md}' --glob '!node_modules'
      rg -n -P '\bgit\.status\s*\(' packages/ai-sandbox/tests packages/ai-sandbox-daytona --glob '*.{ts,tsx}'

      Repository: TanStack/ai

      Length of output: 50370


      🌐 Web query:

      @daytona/sdk 0.191.0 Sandbox git clone status API depth response format

      💡 Result:

      In the @daytona/sdk, the git clone operation supports a depth parameter for creating shallow clones [1][2][3]. Regarding the Git API response format: 1. Clone Operation: The clone operation (POST /git/clone) typically returns a 200 OK status upon success but does not return a complex object, as it is a void/Promise operation in the SDKs [1][2][3][4]. The request body for cloning includes the depth field (integer) to specify the number of commits for a shallow clone [5]. 2. Status Operation: The get git status operation (GET /git/status) returns a JSON object with the GitStatus schema [5][6][7]. The response format includes [6][8]: - currentBranch (string): The current branch name. - branchPublished (boolean): Whether the branch is published. - ahead (integer): Number of commits ahead of the upstream. - behind (integer): Number of commits behind the upstream. - fileStatus (array): A list of objects detailing file states (name, staging, worktree, extra). File status values include Unmodified, Untracked, Modified, Added, Deleted, Renamed, Copied, and Updated but unmerged [6][7].

      Citations:


      Preserve clone depth and document the status format.

      Map numeric depth values to Daytona’s native clone API and map 'full' to an unbounded clone. The native API supports shallow-clone depth, so omitting depth changes the requested behavior.

      Keep SandboxGit.status() compatible with the exec-backed adapter’s porcelain text, or document the Daytona-specific JSON format as a contract change. No in-repository consumer currently parses this value.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-sandbox-daytona/src/handle.ts` around lines 243 - 287, Update
      createNativeGit().clone to accept the requested depth, pass numeric depths to
      sandbox.git.clone, and represent 'full' as an unbounded clone using Daytona’s
      native API contract. Update SandboxGit.status() or its public contract so the
      returned JSON format is explicitly documented as Daytona-specific, while
      preserving compatibility with the exec-backed adapter if required by the shared
      interface.
      packages/ai-sandbox-daytona/src/provider.ts lines 36 to 44
      @@ -32,3 +33,12 @@
      3233 * here. Defaults to `/home/daytona/workspace`.
      3334 */
      3435 workdir?: string
      36+ /**
      37+ * Minutes of idle time before Daytona stops the sandbox. `0` turns auto-stop
      38+ * off. Daytona defaults to 15 minutes when this is omitted.
      39+ */
      40+ autoStopInterval?: number
      41+ /**
      42+ * When true, Daytona deletes the sandbox as soon as it stops.
      43+ */
      44+ ephemeral?: boolean

      🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

      🧩 Analysis chain

      🌐 Web query:

      Daytona sandbox ephemeral option deleted when stopped documentation

      💡 Result:

      In Daytona, ephemeral sandboxes are explicitly designed to be automatically deleted when stopped, discarding all state [1][2]. You can configure this behavior using the ephemeral parameter or the auto_delete_interval setting [1][3][4]. Key configuration details: - Ephemeral Setting: When you create a sandbox and set the ephemeral parameter to True, it is automatically configured to be deleted immediately upon stopping [3][5][6]. - Auto-delete Interval: This parameter controls how long a stopped sandbox persists before being deleted [1][7]. - Setting auto_delete_interval to 0 makes the sandbox ephemeral (it is deleted immediately after it stops) [1][3][6]. - Setting it to a positive integer (in minutes) defines a delay before automatic deletion after the sandbox is stopped [1][7][6]. - Setting it to -1 (the default for non-ephemeral sandboxes) disables automatic deletion [1][3][7][6]. Daytona also provides the ability to modify these settings on existing sandboxes using methods such as set_auto_delete_interval(0) [1][2][7]. Ephemeral sandboxes are typically used for temporary workloads where persistent state is not required [2][5][8].

      Citations:


      🏁 Script executed:

      #!/bin/bash
      set -eu
      
      printf '%s\n' '--- candidate files ---'
      git ls-files 'packages/ai-sandbox-daytona/**' | sed -n '1,120p'
      
      printf '%s\n' '--- provider outline ---'
      ast-grep outline packages/ai-sandbox-daytona/src/provider.ts --view expanded
      
      printf '%s\n' '--- provider implementation ---'
      sed -n '1,240p' packages/ai-sandbox-daytona/src/provider.ts
      
      printf '%s\n' '--- snapshot and ensure references ---'
      rg -n -C 5 'capabilities|snapshot|ephemeral|autoStopInterval|ensure\(' packages/ai-sandbox-daytona packages -g '*.{ts,tsx}' | sed -n '1,260p'

      Repository: TanStack/ai

      Length of output: 28504


      🏁 Script executed:

      #!/bin/bash
      set -eu
      
      printf '%s\n' '--- lifecycle and ensure definitions ---'
      rg -n -C 8 "after-setup|lifecycle\.snapshot|snapshot.*none|async ensure|function ensure|class.*Ensure" packages -g '*.{ts,tsx}' | sed -n '1,320p'
      
      printf '%s\n' '--- Daytona handle snapshot implementation ---'
      sed -n '390,435p' packages/ai-sandbox-daytona/src/handle.ts
      
      printf '%s\n' '--- Daytona provider tests ---'
      sed -n '1,230p' packages/ai-sandbox-daytona/tests/provider.test.ts
      
      printf '%s\n' '--- snapshot-related tests ---'
      rg -n -C 8 "after-setup|snapshot.*none|snapshot\(" packages -g '*.{test,spec}.{ts,tsx}' | sed -n '1,320p'

      Repository: TanStack/ai

      Length of output: 50367


      🏁 Script executed:

      #!/bin/bash
      set -eu
      
      printf '%s\n' '--- complete ensure lifecycle branches ---'
      sed -n '145,285p' packages/ai-sandbox/src/sandbox.ts
      
      printf '%s\n' '--- package versions and Daytona references ---'
      cat packages/ai-sandbox-daytona/package.json
      rg -n -C 3 '"`@daytona/sdk`"|daytona' package.json pnpm-lock.yaml packages/ai-sandbox-daytona/CHANGELOG.md | sed -n '1,180p'
      
      printf '%s\n' '--- read-only lifecycle verifier ---'
      python3 - <<'PY'
      from pathlib import Path
      
      sandbox = Path("packages/ai-sandbox/src/sandbox.ts").read_text()
      handle = Path("packages/ai-sandbox-daytona/src/handle.ts").read_text()
      provider = Path("packages/ai-sandbox-daytona/src/provider.ts").read_text()
      
      checks = {
          "snapshot-capable providers default to after-setup": "config.lifecycle?.snapshot ?? (caps.snapshots ? 'after-setup' : 'none')" in sandbox,
          "after-setup invokes handle.snapshot": "effectiveSnapshot === 'after-setup'" in sandbox and "created.snapshot('after-setup')" in sandbox,
          "Daytona snapshot stops before creating snapshot": "await this.sandbox.stop()" in handle and "await this.sandbox._experimental_createSnapshot(name)" in handle,
          "Daytona snapshot starts after creating snapshot": "await this.sandbox.start()" in handle,
          "ephemeral is forwarded to Daytona create": "...(this.config.ephemeral !== undefined" in provider and "{ ephemeral: this.config.ephemeral }" in provider,
      }
      
      for name, passed in checks.items():
          print(f"{'PASS' if passed else 'FAIL'}: {name}")
      
      if not all(checks.values()):
          raise SystemExit(1)
      PY

      Repository: TanStack/ai

      Length of output: 12493


      Document or reject the incompatible configuration. When ephemeral: true, Daytona deletes the sandbox during DaytonaHandle.snapshot(). Since snapshots: true makes ensure() default to lifecycle.snapshot: 'after-setup', ensure() cannot return the created sandbox. Require lifecycle.snapshot: 'none' for ephemeral sandboxes or reject this configuration.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-sandbox-daytona/src/provider.ts` around lines 36 - 44, Update the
      configuration validation around the provider options and DaytonaHandle.snapshot
      flow so ephemeral sandboxes cannot be combined with snapshots enabled and the
      resulting lifecycle.snapshot value of 'after-setup'. Require lifecycle.snapshot
      to be explicitly 'none' for ephemeral: true, or reject the incompatible
      configuration before ensure() attempts to return the sandbox.
      packages/ai-sandbox/src/bootstrap.ts lines 102 to 105
      @@ -98,4 +99,7 @@
      9899 const url = skill.repo.startsWith('http')
      99100 ? skill.repo
      100101 : `https://github.com/${skill.repo}.git`
      101- const dir = skill.into ?? resolveGitSkillDir(root, skill)
      102+ const dir = resolveHarnessCwd(
      103+ handle,
      104+ skill.into ?? resolveGitSkillDir(root, skill),
      105+ )

      🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

      Normalize explicit gitSkill.into paths for projection.

      Line 102 remaps skill.into before cloning. The supplied Grok, Codex, Claude Code, and ACP projectors still use raw skill.into as their source path. On Daytona, gitSkill({ into: '/workspace/custom-skill' }) clones to /home/daytona/workspace/custom-skill, then projection reads /workspace/custom-skill.

      Store the resolved destination in WorkspaceProjection, or resolve explicit skill.into values in every projector. Add Daytona coverage for an explicit into path.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-sandbox/src/bootstrap.ts` around lines 102 - 105, Ensure the
      normalized destination produced by resolveHarnessCwd in the bootstrap flow is
      also used by WorkspaceProjection and the Grok, Codex, Claude Code, and ACP
      projectors instead of raw skill.into values. Preserve default resolveGitSkillDir
      behavior, and add Daytona coverage verifying an explicit gitSkill({ into: ... })
      projects from the resolved clone path.
    5. Actionable comments posted: 1

      Caution

      Some comments are outside the diff and can’t be posted inline due to platform limitations.

      ⚠️ Outside diff range comments (1)
      packages/ai-sandbox/skills/ai-sandbox/SKILL.md (1)

      210-216: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

      Do not present an ignored deny rule as protection.

      The example sets commands.deny to rm -rf /, but the comment says Grok and Codex do not enforce commands.deny. With default: 'allow', readers can assume that the example blocks the destructive command when it does not. Remove the no-op deny entry, or state explicitly that the outer sandbox—not this policy—provides the safety boundary.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-sandbox/skills/ai-sandbox/SKILL.md` around lines 210 - 216,
      Update the defineSandboxPolicy example around policy so it does not present
      commands.deny as effective protection: remove the rm -rf / deny entry and
      clarify that the outer sandbox provides the safety boundary for Grok and Codex
      harnesses, while preserving default: 'allow' and auto-approve behavior.
      🤖 Prompt for all review comments with AI agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      Inline comments:
      In `@docs/sandbox/workspace.md`:
      - Around line 173-175: Clarify in docs/sandbox/workspace.md that workspace-local
      pnpm install examples run without sudo, while only system or global package
      installs on non-root providers should use non-interactive sudo -n. Update the
      setup guidance near the Providers and Policy references to distinguish these
      scopes and avoid suggesting plain sudo for headless bootstrap.
      
      ---
      
      Outside diff comments:
      In `@packages/ai-sandbox/skills/ai-sandbox/SKILL.md`:
      - Around line 210-216: Update the defineSandboxPolicy example around policy so
      it does not present commands.deny as effective protection: remove the rm -rf /
      deny entry and clarify that the outer sandbox provides the safety boundary for
      Grok and Codex harnesses, while preserving default: 'allow' and auto-approve
      behavior.
      🪄 Autofix

      Fix all unresolved CodeRabbit comments on this PR:

      • Push a commit to this branch (recommended)
      • Create a new PR with the fixes

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 02d6d423-2224-4d7e-a0ad-c4edc10a57c4

      📥 Commits

      Reviewing files that changed from the base of the PR and between 831556a8604786133b3d80f06704cf2abfeff049 and f74325108b345a1556138463e7006d0dcb237856.

      📒 Files selected for processing (7)
      • docs/sandbox/lifecycle.md
      • docs/sandbox/policy.md
      • docs/sandbox/providers.md
      • docs/sandbox/provisioning.md
      • docs/sandbox/workspace.md
      • packages/ai-sandbox/README.md
      • packages/ai-sandbox/skills/ai-sandbox/SKILL.md
      🚧 Files skipped from review as they are similar to previous changes (5)
      • docs/sandbox/lifecycle.md
      • docs/sandbox/providers.md
      • docs/sandbox/policy.md
      • packages/ai-sandbox/README.md
      • docs/sandbox/provisioning.md
      OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)
    6. Actionable comments posted: 3

      🤖 Prompt for all review comments with AI agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      Inline comments:
      In `@packages/ai-claude-code/src/adapters/projection.ts`:
      - Around line 143-150: Define and enforce explicit duplicate-skill collision
      behavior before creating projection targets: in
      packages/ai-claude-code/src/adapters/projection.ts:143-150,
      packages/ai-codex/src/adapters/projection.ts:184-191, and
      packages/ai-grok-build/src/adapters/projection.ts:270-277, detect repeated
      discovered skill names and reject them before linking or copying, or
      consistently apply a documented overwrite policy. Ensure all three adapter
      projection flows use the same behavior.
      - Around line 139-148: Keep skill discovery in the virtual path domain by
      passing the un-mapped skill source to discoverSkillDirs in
      packages/ai-claude-code/src/adapters/projection.ts:139-148,
      packages/ai-codex/src/adapters/projection.ts:180-189, and
      packages/ai-grok-build/src/adapters/projection.ts:266-275. In each adapter,
      apply resolveHarnessCwd only to discovered directories when constructing ln/cp
      commands, preserving virtual-path discovery and existing target handling.
      
      In `@packages/ai-sandbox/skills/ai-sandbox/SKILL.md`:
      - Around line 210-216: Update the documentation around the policy constant to
      explicitly require an isolated provider when using default: 'allow', warning
      that local-process must not be used without an outer sandbox; alternatively,
      enforce this provider restriction in defineSandbox while preserving automatic
      approval for supported isolated providers.
      🪄 Autofix

      Fix all unresolved CodeRabbit comments on this PR:

      • Push a commit to this branch (recommended)
      • Create a new PR with the fixes

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 3e8f8577-5cc3-4849-abc0-48d36360a4a1

      📥 Commits

      Reviewing files that changed from the base of the PR and between d6209d9992efd2702d67b0e4b7be7ac284b56e3e and 5f2de1211ab443764f795ca8a2c13905afbdf444.

      📒 Files selected for processing (13)
      • .changeset/daytona-headless-edges.md
      • docs/sandbox/providers.md
      • docs/sandbox/workspace.md
      • packages/ai-acp/src/adapters/projection.ts
      • packages/ai-claude-code/src/adapters/projection.ts
      • packages/ai-codex/src/adapters/policy-map.ts
      • packages/ai-codex/src/adapters/projection.ts
      • packages/ai-codex/tests/policy-map.test.ts
      • packages/ai-grok-build/src/adapters/projection.ts
      • packages/ai-sandbox-daytona/src/handle.ts
      • packages/ai-sandbox-daytona/tests/handle.test.ts
      • packages/ai-sandbox/README.md
      • packages/ai-sandbox/skills/ai-sandbox/SKILL.md
      🚧 Files skipped from review as they are similar to previous changes (9)
      • .changeset/daytona-headless-edges.md
      • packages/ai-codex/tests/policy-map.test.ts
      • packages/ai-codex/src/adapters/policy-map.ts
      • docs/sandbox/workspace.md
      • packages/ai-sandbox/README.md
      • packages/ai-acp/src/adapters/projection.ts
      • docs/sandbox/providers.md
      • packages/ai-sandbox-daytona/tests/handle.test.ts
      • packages/ai-sandbox-daytona/src/handle.ts
      OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)
      packages/ai-claude-code/src/adapters/projection.ts lines 140 to 147
      @@ -142,7 +137,14 @@
      142- if (result.exitCode !== 0) {
      143- const cpCmd = `cp -r ${shellQuote(source)} ${shellQuote(target)}`
      144- const copied = await handle.process.exec(cpCmd, { cwd: projection.root })
      145- if (copied.exitCode !== 0) {
      146- console.warn(
      147- `[claude-code] failed to link gitSkill "${skill.repo}" into ${target}: ${copied.stderr.trim()}`,
      148- )
      137+ // Remap `/workspace` the same way bootstrap remaps clone dirs, so shell
      138+ // `ln`/`cp` targets match the real provider workdir (e.g. Daytona).
      139+ const source = resolveHarnessCwd(
      140+ handle,
      141+ skill.into ?? resolveGitSkillDir(projection.root, skill),
      142+ )
      143+ const discovered = await discoverSkillDirs(handle, source)
      144+ for (const { name, dir } of discovered) {
      145+ const target = resolveHarnessCwd(handle, `${skillsDir}/${name}`)
      146+ const realDir = resolveHarnessCwd(handle, dir)
      147+ const lnCmd = `ln -s ${shellQuote(realDir)} ${shellQuote(target)}`
      148+ const result = await handle.process.exec(lnCmd, { cwd: projection.root })
      149+ if (result.exitCode !== 0) {
      150+ const cpCmd = `cp -r ${shellQuote(realDir)} ${shellQuote(target)}`

      🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

      🧩 Analysis chain

      🏁 Script executed:

      #!/usr/bin/env bash
      set -euo pipefail
      
      agents_file="$(fd -t f '^agents-file\.ts$' packages/ai-sandbox | head -n1)"
      test -n "$agents_file"
      
      ast-grep outline "$agents_file" --items all --type function
      rg -n -C 10 'DiscoveredSkillDir|discoverSkillDirs|basenameOf|found\.push|name' "$agents_file"
      
      rg -n -C 8 'projectGitSkills|skillsDir|ln -s|cp -r' \
        packages/ai-claude-code/src/adapters/projection.ts \
        packages/ai-codex/src/adapters/projection.ts \
        packages/ai-grok-build/src/adapters/projection.ts

      Repository: TanStack/ai

      Length of output: 22149


      🏁 Script executed:

      #!/usr/bin/env bash
      set -euo pipefail
      
      printf '%s\n' '--- imports and skill types ---'
      rg -n -C 6 'discoverSkillDirs|WorkspaceSkill|interface WorkspaceSkill|kind: .git.|into\?' \
        packages/ai-claude-code packages/ai-codex packages/ai-grok-build packages/ai-sandbox \
        -g '*.ts' -g '*.tsx' | head -n 260
      
      printf '%s\n' '--- tests and fixtures for discovery/projection ---'
      rg -n -C 8 'discoverSkillDirs|projectGitSkills|gitSkill|SKILL\.md|duplicate|collision|same name' \
        packages -g '*test*' -g '*spec*' -g '*.ts' -g '*.tsx' | head -n 360
      
      printf '%s\n' '--- all discovery call sites ---'
      rg -n -C 5 'discoverSkillDirs\(' packages -g '*.ts' -g '*.tsx'
      
      printf '%s\n' '--- projection imports and complete relevant function bodies ---'
      sed -n '1,35p' packages/ai-claude-code/src/adapters/projection.ts
      sed -n '120,165p' packages/ai-claude-code/src/adapters/projection.ts
      sed -n '160,205p' packages/ai-codex/src/adapters/projection.ts
      sed -n '246,291p' packages/ai-grok-build/src/adapters/projection.ts

      Repository: TanStack/ai

      Length of output: 50367


      🏁 Script executed:

      #!/usr/bin/env bash
      set -euo pipefail
      
      python3 - <<'PY'
      from pathlib import Path
      
      def basename_of(path: str) -> str:
          segments = [segment for segment in path.split('/') if segment]
          return segments[-1] if segments else path
      
      # Behavioral verifier for the exact discovery naming rule. It uses synthetic
      # directory-entry data and does not execute repository code or modify files.
      tree = {
          "/clone/skills/one/common": ["SKILL.md"],
          "/clone/skills/two/common": ["SKILL.md"],
      }
      found = []
      for directory, entries in tree.items():
          if any(entry.lower() == "skill.md" for entry in entries):
              found.append({"name": basename_of(directory), "dir": directory})
      
      print("discovered:", found)
      print("names:", [item["name"] for item in found])
      print("unique_names:", len({item["name"] for item in found}) == len(found))
      PY

      Repository: TanStack/ai

      Length of output: 320


      Define collision behavior for duplicate skill names.

      If two discovered directories have the same basename, these adapters reuse one target. Reject duplicate names or define an explicit overwrite policy before projection.

      • packages/ai-claude-code/src/adapters/projection.ts#L143-L150
      • packages/ai-codex/src/adapters/projection.ts#L184-L191
      • packages/ai-grok-build/src/adapters/projection.ts#L270-L277
      🧰 Tools
      🪛 ast-grep (0.45.1)

      [warning] 147-147: Avoid command injection Context: handle.process.exec(lnCmd, { cwd: projection.root }) Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

      (command-injection-typescript)

      🪛 OpenGrep (1.26.0)

      [ERROR] 148-148: Dynamic command passed to child_process.exec/execSync. Use child_process.execFile or spawn with an argument array instead.

      (coderabbit.command-injection.exec-js)

      📍 Affects 3 files
      • packages/ai-claude-code/src/adapters/projection.ts#L143-L150 (this comment)
      • packages/ai-codex/src/adapters/projection.ts#L184-L191
      • packages/ai-grok-build/src/adapters/projection.ts#L270-L277
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-claude-code/src/adapters/projection.ts` around lines 143 - 150,
      Define and enforce explicit duplicate-skill collision behavior before creating
      projection targets: in
      packages/ai-claude-code/src/adapters/projection.ts:143-150,
      packages/ai-codex/src/adapters/projection.ts:184-191, and
      packages/ai-grok-build/src/adapters/projection.ts:270-277, detect repeated
      discovered skill names and reject them before linking or copying, or
      consistently apply a documented overwrite policy. Ensure all three adapter
      projection flows use the same behavior.
      packages/ai-sandbox/skills/ai-sandbox/SKILL.md lines 210 to 216
      @@ -202,14 +207,10 @@
      202207 ```typescript
      203208 import { defineSandboxPolicy } from '@tanstack/ai-sandbox'
      204209
      210+// Headless Grok Build / Codex: stay on auto-approve. Isolation is the
      211+// outer sandbox (Docker, Daytona, …), not commands.deny on this policy.
      205212 const policy = defineSandboxPolicy({
      206- commands: {
      207- allow: ['pnpm test'],
      208- ask: ['curl *'],
      209- deny: ['sudo *', 'rm -rf *'],
      210- },
      211- capabilities: { fileWrite: 'allow', network: 'ask' },
      212- default: 'ask', // deny > ask > allow
      213+ default: 'allow',
      213214 })
      214215 // pass to defineSandbox({ policy }); harness adapters map it to native permissions
      215216 ```

      🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

      State the provider requirement for default: 'allow'.

      default: 'allow' enables automatic command approval. The example does not prohibit local-process. If a caller uses this policy with local-process, Grok or Codex can execute commands on the host without the outer sandbox. State that this policy requires an isolated provider, or enforce that requirement in defineSandbox.

      Proposed documentation change
       // Headless Grok Build / Codex: stay on auto-approve. Isolation is the
      -// outer sandbox (Docker, Daytona, …), not commands.deny on this policy.
      +// outer sandbox (Docker, Daytona, …). Use this policy only with an
      +// isolated provider. Do not use it with local-process.
      📝 Committable suggestion

      ‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      // Headless Grok Build / Codex: stay on auto-approve. Isolation is the
      // outer sandbox (Docker, Daytona, …). Use this policy only with an
      // isolated provider. Do not use it with local-process.
      const policy = defineSandboxPolicy({
        default: 'allow',
      })
      // pass to defineSandbox({ policy }); harness adapters map it to native permissions
      🧰 Tools
      🪛 SkillSpector (2.5.1)

      [error] 581: [AR2] Anti-Refusal Statement: Skill instructs the agent to omit warnings, disclaimers, or ethical commentary. Stripping safety caveats hides risk from the user and is a common jailbreak preamble.

      Remediation: Remove instructions that suppress warnings, disclaimers, or ethical commentary. Let the agent surface safety-relevant caveats to the user.

      (Anti-Refusal (AR2))


      [warning] 195: [PE2] Sudo/Root Execution: Commands invoke sudo or root privileges. Verify this elevated access is necessary and justified.

      Remediation: Avoid sudo/root unless strictly required. Prefer least-privilege patterns. If elevation is needed, document the justification and scope.

      (Privilege Escalation (PE2))


      [warning] 195: [PE2] Sudo/Root Execution: Commands invoke sudo or root privileges. Verify this elevated access is necessary and justified.

      Remediation: Avoid sudo/root unless strictly required. Prefer least-privilege patterns. If elevation is needed, document the justification and scope.

      (Privilege Escalation (PE2))

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-sandbox/skills/ai-sandbox/SKILL.md` around lines 210 - 216,
      Update the documentation around the policy constant to explicitly require an
      isolated provider when using default: 'allow', warning that local-process must
      not be used without an outer sandbox; alternatively, enforce this provider
      restriction in defineSandbox while preserving automatic approval for supported
      isolated providers.
    7. AlemTuzlak merged thisd5bdc36

    8. AlemTuzlak closed this

Sign in to join this conversation.