Add experimental package for working with OpenCode sessions#1274
Draft
Add experimental package for working with OpenCode sessions#1274
Conversation
added 7 commits
April 7, 2026 21:16
Wrap the OpenCode coding agent for use inside Cloudflare sandbox containers. The package handles session lifecycle, provider detection, streaming, backup and restore, and file watching. The high-level entry point is `opencodeTask()`, which returns an AI SDK compatible tool you can drop into any `streamText` call. It auto-detects provider credentials from environment variables, manages the sandbox session, and streams `OpenCodeRunOutput` snapshots containing the agent's sub-conversation, file diffs, diagnostics, and process info. For full lifecycle control, `OpenCodeSession` gives direct access to start, run, backup, restore, and file watch operations. The `packages/agents/README.md` is updated with a section pointing to the new package.
A full chat application at `examples/opencode` that delegates coding tasks to an autonomous OpenCode agent running inside a sandbox container. Uses `@cloudflare/ai-chat` for the agent framework and `@cloudflare/sandbox` for the container runtime. The server wires up `opencodeTask()` with a system prompt, exposes an `/artifacts/<sandboxId>/<path>` route for downloading files from the sandbox, and handles session backup and restore via R2. The React client renders the chat with inline OpenCode sub-conversations showing collapsible message panels, file change summaries, process status, and a download button when a task produces an output file.
All @vitest/* projects needed to be pinned to 4.1.3.
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This PR adds
@cloudflare/agents-opencode, a new package that wraps the OpenCode coding agent for use inside Cloudflare sandbox containers. It handles session lifecycle, provider detection, streaming, backup and restore, and file watching — so you can drop a single tool into anystreamTextcall and get a fully autonomous coding agent.The package exposes two levels of API. The high-level
opencodeTask()function returns an AI SDK compatible tool that manages everything automatically. The low-levelOpenCodeSessionclass gives full control over the session lifecycle for custom integrations. Both yieldOpenCodeRunOutputsnapshots as the agent works, containing the sub-conversation messages, file diffs, diagnostics, process info, and todos.The outer model can set an
outputFileparameter on the tool call to designate a sandbox file as the task's downloadable output. The value flows through toOpenCodeRunOutputso clients can render a download button or link.An example project at
examples/opencodedemonstrates the full integration as a chat application backed by aSandboxChatAgentdurable object. It includes a React frontend that renders the OpenCode sub-conversation inline with collapsible panels, file change summaries, process status, and — when a task produces an output file — a download button. The server exposes an/artifacts/<sandboxId>/<path>route that streams files directly from the sandbox container.API
The high-level entry point is
opencodeTask(). It returns an AI SDKtoolthat you wire into anystreamTextorgenerateTextcall. It handles sandbox provisioning, provider credential detection, session creation, streaming, and backup automatically.The tool itself accepts three parameters from the calling model.
promptis the coding task description.sessionIdoptionally continues a previous session.outputFileoptionally designates a sandbox file path as the downloadable output artifact. Provider credentials are auto-detected from environment variables (ANTHROPIC_API_KEY,OPENAI_API_KEY, orCLOUDFLARE_ACCOUNT_ID+CLOUDFLARE_API_KEY), or you can pass them explicitly via thecredentialsoption. You can also pass auserConfigto override the OpenCode configuration, including the model.For full lifecycle control, use
OpenCodeSessiondirectly. This is useful when you need to manage the sandbox session outside of the AI SDK tool abstraction, for example to integrate file watching or custom backup strategies.Each
OpenCodeRunOutputsnapshot contains the full state of the run:status,sessionId,messages(an array of AI SDKUIMessageobjects representing the agent's sub-conversation),filesEdited,fileChanges,diffs,diagnostics,processes,todos,modelID,summary,error, andoutputFile.The package also exports lower-level utilities for provider detection (
detectProviders,resolveProviders), stream accumulation to track changes over time (OpenCodeStreamAccumulator), file watching (FileWatcher), and backup management (backupSession,restoreSession).examples/opencodeThe example project is a full chat application that delegates coding tasks to OpenCode. It uses
@cloudflare/ai-chatfor the chat agent framework and@cloudflare/sandboxfor the container runtime.To run it locally you need Docker running (the sandbox container builds from a Dockerfile) and at least one provider credential set. Copy
.env.exampleto.envand fill in your keys.The worker configuration in
wrangler.jsoncsets up the sandbox container binding, an R2 bucket for workspace backup, and the Workers AI binding. TheSandboxChatAgentdurable object inserver.tswires upopencodeTask()with a system prompt that instructs the outer model to delegate coding tasks and use theoutputFileparameter for downloadable artifacts. The React client inclient.tsxconnects via WebSocket and renders the chat with inline OpenCode sub-conversations, file diffs, process panels, and download buttons.Important
An R2 bucket is required for sandbox backup and restore. The bucket binding is configured in
wrangler.jsoncunderr2_buckets. Without it the sandbox filesystem will not persist across container evictions.Verification
Testing covers:
OpenCodeRunOutputsnapshots with the right status transitions, message assembly, and metadata extractionTo manually verify the artifact download feature, start the example locally and ask the agent to produce a file (for example, "Create a CSV file with sample user data"). The completed sub-conversation panel should show a download button linking to
/artifacts/<sessionId>/<path>. Clicking it streams the file from the sandbox. Tasks that do not produce output files render normally with no download button.