* fix: chunk resumable stream replay to avoid Upstash 10 MB limit
Large replay payloads (chunks.join("")) published as a single Redis
PUBLISH can exceed Upstash's 10 MB request size cap, causing resume
failures and OOM crashes. Wrap the publisher adapter to split oversized
replay payloads into sequential 256 KB frames while leaving small live
publishes unchanged.
* chore: update bun.lock format
* fix: dispatch all replay frames synchronously to prevent DONE_MESSAGE race
When the upstream runtime uses Promise.all to publish replay + DONE_MESSAGE
concurrently, awaiting between frames yields control and lets DONE_MESSAGE
enter the ioredis pipeline before remaining frames. Dispatch all frames
synchronously so they pipeline ahead of any subsequent caller publishes.
* update plan and add learnings
* feat: sandbox lifecycle management with durable workflows
Implement automatic sandbox hibernation, rollover, and restore using
Vercel Workflow DevKit for durable scheduling. Key changes:
- Add lifecycle state machine (active → hibernating → hibernated → restoring)
- Durable workflow sleeps until hibernateAfter or near-expiry, then evaluates
- Refresh activity timestamps at chat start (not just onFinish) to prevent
mid-request hibernation
- Status endpoint checks expiry with same 10s buffer as chat route
- Reconnect probe no longer resets inactivity timer
- Safety nets: status poll kicks overdue lifecycles, workflow retries on skip
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* docs: add sandbox lifecycle architecture doc
Documents the full sandbox lifecycle state machine, workflow scheduling,
activity tracking, safety nets, and client-side UI sync behavior.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: remove sandbox hard-timeout rollover
The rollover feature (snapshot + restore into fresh sandbox at hard
timeout) added significant complexity for a scenario that rarely
occurs — the 5-hour hard timeout is almost never reached before
inactivity hibernation kicks in. When the hard timeout is reached,
the sandbox now simply hibernates like any other idle sandbox.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: remove redundant chat-started lifecycle workflow kick
The chat-started workflow kick was wrapped in Next.js `after()`, which
defers execution until the response stream completes. This caused it to
fire at the same time as the chat-finished kick, spawning two redundant
workflows. The DB activity refresh (`buildActiveLifecycleUpdate`) already
runs immediately at request start, which is sufficient to prevent
mid-request hibernation.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* update timeouts
* Update apps/web/next.config.ts
Co-authored-by: vercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
* fix: sandbox lifecycle bug fixes and utility deduplication
- Extract shared `hasRuntimeSandboxState` and `isSandboxUnavailableError` into
lib/sandbox/utils.ts, replacing 4 duplicate copies across route files
- Tighten "not found" match to "sandbox not found" to prevent false positives
from unrelated errors (e.g. "command not found", "file not found")
- Reset lifecycleState back to "active" when snapshot is not supported, fixing
sessions getting stuck in "hibernating" state
- Only forward expiresAt to client on transient reconnect errors if still in the
future, preventing negative timeout computation
- Unify diff/files routes to use the full unavailability check (4 patterns)
instead of only matching "expected a stream of command data"
- Clean up commented-out debug config values in config.ts
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* remove prebuild script
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: vercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
* Inject skill directory path into skill content for script access
Skills can have bundled scripts in a scripts/ directory. This change
prepends the skill directory path to the skill content so Claude can
construct full paths to execute scripts.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Add completed plan for skill script invocation support
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
* Add token usage reporting for subagents
Display input tokens inline in task views next to tool count and duration.
Shows tokens while streaming and final count on completion.
Changes:
- Add messageMetadata callback to task tool to attach usage data
- Add token display to TUI and web task-group-view components
- Add tokens to task-renderer completion views
- Refactor web task-renderer to use proper types instead of casts
- Switch tool-call.tsx to narrow on part.type instead of derived string
- Add SubagentUIMessage type for proper typing of subagent output
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Consolidate formatTokens and improve type safety
- Move formatTokens to shared package to eliminate duplication across 4 files
- Add getToolSummary helper with proper type narrowing (replaces unsafe cast)
- Simplify IIFE patterns to ternary expressions in task renderers
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Migrate from custom blob snapshots to native Vercel snapshots
Replace the custom tarball-based snapshot system with Vercel's native
snapshot API. This simplifies the codebase and removes the @vercel/blob
dependency.
Key changes:
- snapshot() now uses native SDK method (automatically stops sandbox)
- Restoration happens at sandbox creation via source: { type: 'snapshot' }
- Added backwards compatibility for legacy blob URLs (https://)
- Removed SnapshotOptions, renamed RestoreOptions to LegacyRestoreOptions
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Fix code review issues from snapshot migration
- Configure git user after native snapshot restoration in vercel and hybrid sandboxes
- Only render expanded input when non-empty in task-renderer
- Restore getToolSummary fallback for unknown tool types
- Remove legacy blob snapshot code (isLegacySnapshot, restoreLegacySnapshot, LegacyRestoreOptions)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Extract configureGitUser utility and remove legacy blob comments
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Add sandbox snapshot reliability plan
Documents two approaches for ensuring sandboxes are snapshotted before
timeout even when clients are inactive:
- Approach A: Snapshot after every assistant response + auto-extend
- Approach B: Cron-based snapshot for sandboxes near expiration
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Preserve sandbox type on stop/snapshot for correct restoration
- Add isSandboxActive() type guard and clearSandboxState() helper
- Update API routes to use isSandboxActive() for active sandbox checks
- Preserve sandbox type in sandboxState when stopping/snapshotting
- Fix snapshot restoration to not create sandbox first (was preventing
snapshot restore due to sandboxId taking precedence over snapshotId)
- Update frontend task context to preserve type on state clearing
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Add expiresAt tracking to sandbox state for client-side expiration checks
Store expiresAt timestamp in persisted sandbox state so the client can
immediately determine if a sandbox has expired without making a network
call. This fixes the issue where the UI shows "active" for expired
sandboxes until a network call fails.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Fix sandbox timeout snapshot and cleanup flow
- Add canOperateOnSandbox() to allow operations on expired sandboxes
- Make DELETE /api/sandbox idempotent (return success if already stopped)
- Fix snapshot response parsing to use snapshotId instead of downloadUrl
The client was looking for 'downloadUrl' but the API returns 'snapshotId',
causing the task's snapshotUrl to never be updated locally. This made the
UI show "Create sandbox" instead of "Resume sandbox" after timeout.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* add comment
* Fix sandbox utils type safety and snapshot restore race condition
- Add comprehensive JSDoc comments to isSandboxActive and canOperateOnSandbox
- Extract hasRuntimeState helper to reduce code duplication
- Fix clearSandboxState to use explicit switch instead of type cast
- Add null check for getState result in extend route
- Prevent snapshot restore while sandbox is running (race condition fix)
- Only pass type and snapshotId when restoring (avoid stale sandboxId)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Consolidate sandbox timeout configuration into single file
- Create apps/web/lib/sandbox/config.ts with timeout constants
- Replace hardcoded 300_000 values across web app with shared constants
- DEFAULT_SANDBOX_TIMEOUT_MS for new sandboxes
- EXTEND_TIMEOUT_DURATION_MS for timeout extensions
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Fix sandbox timeout propagation and client display on refresh
- Add timeout option to ConnectOptions and pass through to Vercel SDK
- Pass DEFAULT_SANDBOX_TIMEOUT_MS when creating sandboxes in web app
- Return expiresAt from reconnect endpoint for accurate client display
- Calculate remaining timeout from expiresAt on reconnect (not default)
- Pass remainingTimeout when restoring from snapshot
- Display remaining seconds next to sandbox status indicator
Previously, the timeout was only sent to the client but not to the SDK,
causing sandboxes to use the SDK's 300s default. On refresh, the client
would also reset to the default instead of showing actual remaining time.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* update
* Fix timeout propagation when restoring hybrid sandbox from snapshot
Pass remainingTimeout to VercelSandbox.connect() during snapshot restoration,
matching the pattern in vercel/connect.ts.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
* Add token usage reporting for subagents
Display input tokens inline in task views next to tool count and duration.
Shows tokens while streaming and final count on completion.
Changes:
- Add messageMetadata callback to task tool to attach usage data
- Add token display to TUI and web task-group-view components
- Add tokens to task-renderer completion views
- Refactor web task-renderer to use proper types instead of casts
- Switch tool-call.tsx to narrow on part.type instead of derived string
- Add SubagentUIMessage type for proper typing of subagent output
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Consolidate formatTokens and improve type safety
- Move formatTokens to shared package to eliminate duplication across 4 files
- Add getToolSummary helper with proper type narrowing (replaces unsafe cast)
- Simplify IIFE patterns to ternary expressions in task renderers
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Fix tool-write and tool-edit summaries in task renderers
The getToolSummary function was missing cases for tool-write and tool-edit,
causing file paths to not display for executor subagent operations. Updated
SubagentUIMessage to be a union of both explorer and executor types so
TypeScript recognizes these tool types.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Refactor token usage metadata to track last step and total usage separately
Changes metadata from { usage } to { lastStepUsage, totalMessageUsage } to
distinguish between context window utilization (last step) and cumulative
token usage across all steps in a message.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Fix type safety in CLI task renderer
Replace loose typing and unsafe casts with proper SubagentMessagePart
type derived from SubagentUIMessage. Add getToolSummary function that
uses discriminated union narrowing for type-safe tool input access.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
* Refactor approval config to discriminated union
Replace the implicit mode/autoApprove/approvalRules fields with a
discriminated union ApprovalConfig type:
- "interactive": Human in the loop with autoApprove and sessionRules
- "background": Async execution with full trust
- "delegated": Subagent inherits trust from parent
This change makes the trust model explicit, removes redundant fields,
and simplifies approval logic with clear switch statements.
Changes:
- Update types.ts with new ApprovalConfig type
- Update utils.ts with helper functions (shouldAutoApprove, getSessionRules)
- Update all tool files to use new approval config pattern
- Update subagents to use { type: "delegated" }
- Update TUI, CLI, and web app consumers
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* remove onFinish
* Fix delegated mode approval for subagents
Move shouldAutoApprove check to the top of needsApproval functions
so background and delegated modes immediately return false (no approval)
before any other checks. Previously, tools would still require approval
for paths outside the working directory even in delegated mode, causing
subagents to hang since there's no interactive UI to handle approval.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Refactor approval logic with type guard and path helpers
- Make shouldAutoApprove a type guard for proper type narrowing
- Add centralized pathMatchesApprovalRule and pathNeedsApproval helpers
- Use explicit switch statement in transport.ts for approval config
- Simplify tool needsApproval functions by using shared helpers
- Remove duplicate pathMatchesApprovalRule from individual tool files
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Consolidate write/edit tool approval logic with pathNeedsApproval helper
- Refactor writeFileTool and editFileTool to use shared pathNeedsApproval
- Remove redundant isOutsideWorkingDirectory helper and inline approval logic
- Remove unused getSessionRules function from utils
- Remove unused options parameter from write/edit tools
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Add documentation for tool approval system
Documents the discriminated union pattern for approval config,
the three trust models (interactive/background/delegated), approval
rules, and tool-specific approval logic.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>