Merge remote-tracking branch 'origin/main' into test-dev-webhooks-flow

# Conflicts:
#	factory/packages/backend/src/actors/project/actions.ts
#	factory/packages/backend/src/actors/workspace/actions.ts
#	factory/packages/frontend/src/components/mock-layout.tsx
This commit is contained in:
Nathan Flurry 2026-03-11 11:14:04 -07:00
commit c8a095b69f
302 changed files with 11419 additions and 9952 deletions

View file

@ -11,6 +11,8 @@ jobs:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
@ -21,6 +23,35 @@ jobs:
node-version: 20
cache: pnpm
- run: pnpm install
- name: Run formatter hooks
shell: bash
run: |
if [ "${{ github.event_name }}" = "pull_request" ]; then
git fetch origin "${{ github.base_ref }}" --depth=1
diff_range="origin/${{ github.base_ref }}...HEAD"
elif [ "${{ github.event_name }}" = "push" ] && [ "${{ github.event.before }}" != "0000000000000000000000000000000000000000" ]; then
diff_range="${{ github.event.before }}...${{ github.sha }}"
else
diff_range="HEAD^...HEAD"
fi
mapfile -t changed_files < <(
git diff --name-only --diff-filter=ACMR "$diff_range" \
| grep -E '\.(cjs|cts|js|jsx|json|jsonc|mjs|mts|rs|ts|tsx)$' \
|| true
)
if [ ${#changed_files[@]} -eq 0 ]; then
echo "No formatter-managed files changed."
exit 0
fi
args=()
for file in "${changed_files[@]}"; do
args+=(--file "$file")
done
pnpm exec lefthook run pre-commit --no-stage-fixed --fail-on-changes "${args[@]}"
- run: npm install -g tsx
- name: Run checks
run: ./scripts/release/main.ts --version 0.0.0 --only-steps run-ci-checks

View file

@ -1,10 +1,8 @@
{
"mcpServers": {
"everything": {
"args": [
"@modelcontextprotocol/server-everything"
],
"args": ["@modelcontextprotocol/server-everything"],
"command": "npx"
}
}
}
}

View file

@ -66,6 +66,14 @@
- `Session` helpers are `prompt(...)`, `rawSend(...)`, `onEvent(...)`, `setMode(...)`, `setModel(...)`, `setThoughtLevel(...)`, `setConfigOption(...)`, `getConfigOptions()`, `getModes()`, `respondPermission(...)`, `rawRespondPermission(...)`, and `onPermissionRequest(...)`.
- Cleanup is `sdk.dispose()`.
### React Component Methodology
- Shared React UI belongs in `sdks/react` only when it is reusable outside the Inspector.
- If the same UI pattern is shared between the Sandbox Agent Inspector and Foundry, prefer extracting it into `sdks/react` instead of maintaining parallel implementations.
- Keep shared components unstyled by default: behavior in the package, styling in the consumer via `className`, slot-level `classNames`, render overrides, and `data-*` hooks.
- Prefer extracting reusable pieces such as transcript, composer, and conversation surfaces. Keep Inspector-specific shells such as session selection, session headers, and control-plane actions in `frontend/packages/inspector/`.
- Document all shared React components in `docs/react-components.mdx`, and keep that page aligned with the exported surface in `sdks/react/src/index.ts`.
### TypeScript SDK Naming Conventions
- Use `respond<Thing>(id, reply)` for SDK methods that reply to an agent-initiated request (e.g. `respondPermission`). This is the standard pattern for answering any inbound JSON-RPC request from the agent.

7
biome.json Normal file
View file

@ -0,0 +1,7 @@
{
"$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
"formatter": {
"indentStyle": "space",
"lineWidth": 160
}
}

View file

@ -1,131 +1,119 @@
{
"$schema": "https://mintlify.com/docs.json",
"theme": "willow",
"name": "Sandbox Agent SDK",
"appearance": {
"default": "dark",
"strict": true
},
"colors": {
"primary": "#ff4f00",
"light": "#ff4f00",
"dark": "#ff4f00"
},
"favicon": "/favicon.svg",
"logo": {
"light": "/logo/light.svg",
"dark": "/logo/dark.svg"
},
"integrations": {
"posthog": {
"apiKey": "phc_6kfTNEAVw7rn1LA51cO3D69FefbKupSWFaM7OUgEpEo",
"apiHost": "https://ph.rivet.gg",
"sessionRecording": true
}
},
"navbar": {
"links": [
{
"label": "Gigacode",
"icon": "terminal",
"href": "https://github.com/rivet-dev/sandbox-agent/tree/main/gigacode"
},
{
"label": "Discord",
"icon": "discord",
"href": "https://discord.gg/auCecybynK"
},
{
"type": "github",
"href": "https://github.com/rivet-dev/sandbox-agent"
}
]
},
"navigation": {
"tabs": [
{
"tab": "Documentation",
"pages": [
{
"group": "Getting started",
"pages": [
"quickstart",
"sdk-overview",
"react-components",
{
"group": "Deploy",
"icon": "server",
"pages": [
"deploy/local",
"deploy/computesdk",
"deploy/e2b",
"deploy/daytona",
"deploy/vercel",
"deploy/cloudflare",
"deploy/docker",
"deploy/boxlite"
]
}
]
},
{
"group": "Agent",
"pages": [
"agent-sessions",
"attachments",
"skills-config",
"mcp-config",
"custom-tools"
]
},
{
"group": "System",
"pages": ["file-system", "processes"]
},
{
"group": "Orchestration",
"pages": [
"architecture",
"session-persistence",
"observability",
"multiplayer",
"security"
]
},
{
"group": "Reference",
"pages": [
"agent-capabilities",
"cli",
"inspector",
"opencode-compatibility",
{
"group": "More",
"pages": [
"credentials",
"daemon",
"cors",
"session-restoration",
"telemetry",
{
"group": "AI",
"pages": ["ai/skill", "ai/llms-txt"]
}
]
}
]
}
]
},
{
"tab": "HTTP API",
"pages": [
{
"group": "HTTP Reference",
"openapi": "openapi.json"
}
]
}
]
}
"$schema": "https://mintlify.com/docs.json",
"theme": "willow",
"name": "Sandbox Agent SDK",
"appearance": {
"default": "dark",
"strict": true
},
"colors": {
"primary": "#ff4f00",
"light": "#ff4f00",
"dark": "#ff4f00"
},
"favicon": "/favicon.svg",
"logo": {
"light": "/logo/light.svg",
"dark": "/logo/dark.svg"
},
"integrations": {
"posthog": {
"apiKey": "phc_6kfTNEAVw7rn1LA51cO3D69FefbKupSWFaM7OUgEpEo",
"apiHost": "https://ph.rivet.gg",
"sessionRecording": true
}
},
"navbar": {
"links": [
{
"label": "Gigacode",
"icon": "terminal",
"href": "https://github.com/rivet-dev/sandbox-agent/tree/main/gigacode"
},
{
"label": "Discord",
"icon": "discord",
"href": "https://discord.gg/auCecybynK"
},
{
"type": "github",
"href": "https://github.com/rivet-dev/sandbox-agent"
}
]
},
"navigation": {
"tabs": [
{
"tab": "Documentation",
"pages": [
{
"group": "Getting started",
"pages": [
"quickstart",
"sdk-overview",
"react-components",
{
"group": "Deploy",
"icon": "server",
"pages": [
"deploy/local",
"deploy/computesdk",
"deploy/e2b",
"deploy/daytona",
"deploy/vercel",
"deploy/cloudflare",
"deploy/docker",
"deploy/boxlite"
]
}
]
},
{
"group": "Agent",
"pages": ["agent-sessions", "attachments", "skills-config", "mcp-config", "custom-tools"]
},
{
"group": "System",
"pages": ["file-system", "processes"]
},
{
"group": "Orchestration",
"pages": ["architecture", "session-persistence", "observability", "multiplayer", "security"]
},
{
"group": "Reference",
"pages": [
"agent-capabilities",
"cli",
"inspector",
"opencode-compatibility",
{
"group": "More",
"pages": [
"credentials",
"daemon",
"cors",
"session-restoration",
"telemetry",
{
"group": "AI",
"pages": ["ai/skill", "ai/llms-txt"]
}
]
}
]
}
]
},
{
"tab": "HTTP API",
"pages": [
{
"group": "HTTP Reference",
"openapi": "openapi.json"
}
]
}
]
}
}

View file

@ -20,9 +20,7 @@
"paths": {
"/v1/acp": {
"get": {
"tags": [
"v1"
],
"tags": ["v1"],
"operationId": "get_v1_acp_servers",
"responses": {
"200": {
@ -40,9 +38,7 @@
},
"/v1/acp/{server_id}": {
"get": {
"tags": [
"v1"
],
"tags": ["v1"],
"operationId": "get_v1_acp",
"parameters": [
{
@ -92,9 +88,7 @@
}
},
"post": {
"tags": [
"v1"
],
"tags": ["v1"],
"operationId": "post_v1_acp",
"parameters": [
{
@ -204,9 +198,7 @@
}
},
"delete": {
"tags": [
"v1"
],
"tags": ["v1"],
"operationId": "delete_v1_acp",
"parameters": [
{
@ -228,9 +220,7 @@
},
"/v1/agents": {
"get": {
"tags": [
"v1"
],
"tags": ["v1"],
"operationId": "get_v1_agents",
"parameters": [
{
@ -280,9 +270,7 @@
},
"/v1/agents/{agent}": {
"get": {
"tags": [
"v1"
],
"tags": ["v1"],
"operationId": "get_v1_agent",
"parameters": [
{
@ -351,9 +339,7 @@
},
"/v1/agents/{agent}/install": {
"post": {
"tags": [
"v1"
],
"tags": ["v1"],
"operationId": "post_v1_agent_install",
"parameters": [
{
@ -412,9 +398,7 @@
},
"/v1/config/mcp": {
"get": {
"tags": [
"v1"
],
"tags": ["v1"],
"operationId": "get_v1_config_mcp",
"parameters": [
{
@ -460,9 +444,7 @@
}
},
"put": {
"tags": [
"v1"
],
"tags": ["v1"],
"operationId": "put_v1_config_mcp",
"parameters": [
{
@ -501,9 +483,7 @@
}
},
"delete": {
"tags": [
"v1"
],
"tags": ["v1"],
"operationId": "delete_v1_config_mcp",
"parameters": [
{
@ -534,9 +514,7 @@
},
"/v1/config/skills": {
"get": {
"tags": [
"v1"
],
"tags": ["v1"],
"operationId": "get_v1_config_skills",
"parameters": [
{
@ -582,9 +560,7 @@
}
},
"put": {
"tags": [
"v1"
],
"tags": ["v1"],
"operationId": "put_v1_config_skills",
"parameters": [
{
@ -623,9 +599,7 @@
}
},
"delete": {
"tags": [
"v1"
],
"tags": ["v1"],
"operationId": "delete_v1_config_skills",
"parameters": [
{
@ -656,9 +630,7 @@
},
"/v1/fs/entries": {
"get": {
"tags": [
"v1"
],
"tags": ["v1"],
"operationId": "get_v1_fs_entries",
"parameters": [
{
@ -691,9 +663,7 @@
},
"/v1/fs/entry": {
"delete": {
"tags": [
"v1"
],
"tags": ["v1"],
"operationId": "delete_v1_fs_entry",
"parameters": [
{
@ -732,9 +702,7 @@
},
"/v1/fs/file": {
"get": {
"tags": [
"v1"
],
"tags": ["v1"],
"operationId": "get_v1_fs_file",
"parameters": [
{
@ -754,9 +722,7 @@
}
},
"put": {
"tags": [
"v1"
],
"tags": ["v1"],
"operationId": "put_v1_fs_file",
"parameters": [
{
@ -796,9 +762,7 @@
},
"/v1/fs/mkdir": {
"post": {
"tags": [
"v1"
],
"tags": ["v1"],
"operationId": "post_v1_fs_mkdir",
"parameters": [
{
@ -827,9 +791,7 @@
},
"/v1/fs/move": {
"post": {
"tags": [
"v1"
],
"tags": ["v1"],
"operationId": "post_v1_fs_move",
"requestBody": {
"content": {
@ -857,9 +819,7 @@
},
"/v1/fs/stat": {
"get": {
"tags": [
"v1"
],
"tags": ["v1"],
"operationId": "get_v1_fs_stat",
"parameters": [
{
@ -888,9 +848,7 @@
},
"/v1/fs/upload-batch": {
"post": {
"tags": [
"v1"
],
"tags": ["v1"],
"operationId": "post_v1_fs_upload_batch",
"parameters": [
{
@ -931,9 +889,7 @@
},
"/v1/health": {
"get": {
"tags": [
"v1"
],
"tags": ["v1"],
"operationId": "get_v1_health",
"responses": {
"200": {
@ -951,9 +907,7 @@
},
"/v1/processes": {
"get": {
"tags": [
"v1"
],
"tags": ["v1"],
"summary": "List all managed processes.",
"description": "Returns a list of all processes (running and exited) currently tracked\nby the runtime, sorted by process ID.",
"operationId": "get_v1_processes",
@ -981,9 +935,7 @@
}
},
"post": {
"tags": [
"v1"
],
"tags": ["v1"],
"summary": "Create a long-lived managed process.",
"description": "Spawns a new process with the given command and arguments. Supports both\npipe-based and PTY (tty) modes. Returns the process descriptor on success.",
"operationId": "post_v1_processes",
@ -1043,9 +995,7 @@
},
"/v1/processes/config": {
"get": {
"tags": [
"v1"
],
"tags": ["v1"],
"summary": "Get process runtime configuration.",
"description": "Returns the current runtime configuration for the process management API,\nincluding limits for concurrency, timeouts, and buffer sizes.",
"operationId": "get_v1_processes_config",
@ -1073,9 +1023,7 @@
}
},
"post": {
"tags": [
"v1"
],
"tags": ["v1"],
"summary": "Update process runtime configuration.",
"description": "Replaces the runtime configuration for the process management API.\nValidates that all values are non-zero and clamps default timeout to max.",
"operationId": "post_v1_processes_config",
@ -1125,9 +1073,7 @@
},
"/v1/processes/run": {
"post": {
"tags": [
"v1"
],
"tags": ["v1"],
"summary": "Run a one-shot command.",
"description": "Executes a command to completion and returns its stdout, stderr, exit code,\nand duration. Supports configurable timeout and output size limits.",
"operationId": "post_v1_processes_run",
@ -1177,9 +1123,7 @@
},
"/v1/processes/{id}": {
"get": {
"tags": [
"v1"
],
"tags": ["v1"],
"summary": "Get a single process by ID.",
"description": "Returns the current state of a managed process including its status,\nPID, exit code, and creation/exit timestamps.",
"operationId": "get_v1_process",
@ -1228,9 +1172,7 @@
}
},
"delete": {
"tags": [
"v1"
],
"tags": ["v1"],
"summary": "Delete a process record.",
"description": "Removes a stopped process from the runtime. Returns 409 if the process\nis still running; stop or kill it first.",
"operationId": "delete_v1_process",
@ -1284,9 +1226,7 @@
},
"/v1/processes/{id}/input": {
"post": {
"tags": [
"v1"
],
"tags": ["v1"],
"summary": "Write input to a process.",
"description": "Sends data to a process's stdin (pipe mode) or PTY writer (tty mode).\nData can be encoded as base64, utf8, or text. Returns 413 if the decoded\npayload exceeds the configured `maxInputBytesPerRequest` limit.",
"operationId": "post_v1_process_input",
@ -1367,9 +1307,7 @@
},
"/v1/processes/{id}/kill": {
"post": {
"tags": [
"v1"
],
"tags": ["v1"],
"summary": "Send SIGKILL to a process.",
"description": "Sends SIGKILL to the process and optionally waits up to `waitMs`\nmilliseconds for the process to exit before returning.",
"operationId": "post_v1_process_kill",
@ -1432,9 +1370,7 @@
},
"/v1/processes/{id}/logs": {
"get": {
"tags": [
"v1"
],
"tags": ["v1"],
"summary": "Fetch process logs.",
"description": "Returns buffered log entries for a process. Supports filtering by stream\ntype, tail count, and sequence-based resumption. When `follow=true`,\nreturns an SSE stream that replays buffered entries then streams live output.",
"operationId": "get_v1_process_logs",
@ -1532,9 +1468,7 @@
},
"/v1/processes/{id}/stop": {
"post": {
"tags": [
"v1"
],
"tags": ["v1"],
"summary": "Send SIGTERM to a process.",
"description": "Sends SIGTERM to the process and optionally waits up to `waitMs`\nmilliseconds for the process to exit before returning.",
"operationId": "post_v1_process_stop",
@ -1597,9 +1531,7 @@
},
"/v1/processes/{id}/terminal/resize": {
"post": {
"tags": [
"v1"
],
"tags": ["v1"],
"summary": "Resize a process terminal.",
"description": "Sets the PTY window size (columns and rows) for a tty-mode process and\nsends SIGWINCH so the child process can adapt.",
"operationId": "post_v1_process_terminal_resize",
@ -1680,9 +1612,7 @@
},
"/v1/processes/{id}/terminal/ws": {
"get": {
"tags": [
"v1"
],
"tags": ["v1"],
"summary": "Open an interactive WebSocket terminal session.",
"description": "Upgrades the connection to a WebSocket for bidirectional PTY I/O. Accepts\n`access_token` query param for browser-based auth (WebSocket API cannot\nsend custom headers). Streams raw PTY output as binary frames and accepts\nJSON control frames for input, resize, and close.",
"operationId": "get_v1_process_terminal_ws",
@ -1759,9 +1689,7 @@
"schemas": {
"AcpEnvelope": {
"type": "object",
"required": [
"jsonrpc"
],
"required": ["jsonrpc"],
"properties": {
"error": {
"nullable": true
@ -1795,11 +1723,7 @@
},
"AcpServerInfo": {
"type": "object",
"required": [
"serverId",
"agent",
"createdAtMs"
],
"required": ["serverId", "agent", "createdAtMs"],
"properties": {
"agent": {
"type": "string"
@ -1815,9 +1739,7 @@
},
"AcpServerListResponse": {
"type": "object",
"required": [
"servers"
],
"required": ["servers"],
"properties": {
"servers": {
"type": "array",
@ -1908,12 +1830,7 @@
},
"AgentInfo": {
"type": "object",
"required": [
"id",
"installed",
"credentialsAvailable",
"capabilities"
],
"required": ["id", "installed", "credentialsAvailable", "capabilities"],
"properties": {
"capabilities": {
"$ref": "#/components/schemas/AgentCapabilities"
@ -1956,11 +1873,7 @@
},
"AgentInstallArtifact": {
"type": "object",
"required": [
"kind",
"path",
"source"
],
"required": ["kind", "path", "source"],
"properties": {
"kind": {
"type": "string"
@ -1996,10 +1909,7 @@
},
"AgentInstallResponse": {
"type": "object",
"required": [
"already_installed",
"artifacts"
],
"required": ["already_installed", "artifacts"],
"properties": {
"already_installed": {
"type": "boolean"
@ -2014,9 +1924,7 @@
},
"AgentListResponse": {
"type": "object",
"required": [
"agents"
],
"required": ["agents"],
"properties": {
"agents": {
"type": "array",
@ -2049,9 +1957,7 @@
},
"FsActionResponse": {
"type": "object",
"required": [
"path"
],
"required": ["path"],
"properties": {
"path": {
"type": "string"
@ -2060,9 +1966,7 @@
},
"FsDeleteQuery": {
"type": "object",
"required": [
"path"
],
"required": ["path"],
"properties": {
"path": {
"type": "string"
@ -2084,12 +1988,7 @@
},
"FsEntry": {
"type": "object",
"required": [
"name",
"path",
"entryType",
"size"
],
"required": ["name", "path", "entryType", "size"],
"properties": {
"entryType": {
"$ref": "#/components/schemas/FsEntryType"
@ -2113,17 +2012,11 @@
},
"FsEntryType": {
"type": "string",
"enum": [
"file",
"directory"
]
"enum": ["file", "directory"]
},
"FsMoveRequest": {
"type": "object",
"required": [
"from",
"to"
],
"required": ["from", "to"],
"properties": {
"from": {
"type": "string"
@ -2139,10 +2032,7 @@
},
"FsMoveResponse": {
"type": "object",
"required": [
"from",
"to"
],
"required": ["from", "to"],
"properties": {
"from": {
"type": "string"
@ -2154,9 +2044,7 @@
},
"FsPathQuery": {
"type": "object",
"required": [
"path"
],
"required": ["path"],
"properties": {
"path": {
"type": "string"
@ -2165,11 +2053,7 @@
},
"FsStat": {
"type": "object",
"required": [
"path",
"entryType",
"size"
],
"required": ["path", "entryType", "size"],
"properties": {
"entryType": {
"$ref": "#/components/schemas/FsEntryType"
@ -2199,10 +2083,7 @@
},
"FsUploadBatchResponse": {
"type": "object",
"required": [
"paths",
"truncated"
],
"required": ["paths", "truncated"],
"properties": {
"paths": {
"type": "array",
@ -2217,10 +2098,7 @@
},
"FsWriteResponse": {
"type": "object",
"required": [
"path",
"bytesWritten"
],
"required": ["path", "bytesWritten"],
"properties": {
"bytesWritten": {
"type": "integer",
@ -2234,9 +2112,7 @@
},
"HealthResponse": {
"type": "object",
"required": [
"status"
],
"required": ["status"],
"properties": {
"status": {
"type": "string"
@ -2245,10 +2121,7 @@
},
"McpConfigQuery": {
"type": "object",
"required": [
"directory",
"mcpName"
],
"required": ["directory", "mcpName"],
"properties": {
"directory": {
"type": "string"
@ -2262,10 +2135,7 @@
"oneOf": [
{
"type": "object",
"required": [
"command",
"type"
],
"required": ["command", "type"],
"properties": {
"args": {
"type": "array",
@ -2299,18 +2169,13 @@
},
"type": {
"type": "string",
"enum": [
"local"
]
"enum": ["local"]
}
}
},
{
"type": "object",
"required": [
"url",
"type"
],
"required": ["url", "type"],
"properties": {
"bearerTokenEnvVar": {
"type": "string",
@ -2358,9 +2223,7 @@
},
"type": {
"type": "string",
"enum": [
"remote"
]
"enum": ["remote"]
},
"url": {
"type": "string"
@ -2374,11 +2237,7 @@
},
"ProblemDetails": {
"type": "object",
"required": [
"type",
"title",
"status"
],
"required": ["type", "title", "status"],
"properties": {
"detail": {
"type": "string",
@ -2404,14 +2263,7 @@
},
"ProcessConfig": {
"type": "object",
"required": [
"maxConcurrentProcesses",
"defaultRunTimeoutMs",
"maxRunTimeoutMs",
"maxOutputBytes",
"maxLogBytesPerProcess",
"maxInputBytesPerRequest"
],
"required": ["maxConcurrentProcesses", "defaultRunTimeoutMs", "maxRunTimeoutMs", "maxOutputBytes", "maxLogBytesPerProcess", "maxInputBytesPerRequest"],
"properties": {
"defaultRunTimeoutMs": {
"type": "integer",
@ -2443,9 +2295,7 @@
},
"ProcessCreateRequest": {
"type": "object",
"required": [
"command"
],
"required": ["command"],
"properties": {
"args": {
"type": "array",
@ -2476,15 +2326,7 @@
},
"ProcessInfo": {
"type": "object",
"required": [
"id",
"command",
"args",
"tty",
"interactive",
"status",
"createdAtMs"
],
"required": ["id", "command", "args", "tty", "interactive", "status", "createdAtMs"],
"properties": {
"args": {
"type": "array",
@ -2535,9 +2377,7 @@
},
"ProcessInputRequest": {
"type": "object",
"required": [
"data"
],
"required": ["data"],
"properties": {
"data": {
"type": "string"
@ -2550,9 +2390,7 @@
},
"ProcessInputResponse": {
"type": "object",
"required": [
"bytesWritten"
],
"required": ["bytesWritten"],
"properties": {
"bytesWritten": {
"type": "integer",
@ -2562,9 +2400,7 @@
},
"ProcessListResponse": {
"type": "object",
"required": [
"processes"
],
"required": ["processes"],
"properties": {
"processes": {
"type": "array",
@ -2576,13 +2412,7 @@
},
"ProcessLogEntry": {
"type": "object",
"required": [
"sequence",
"stream",
"timestampMs",
"data",
"encoding"
],
"required": ["sequence", "stream", "timestampMs", "data", "encoding"],
"properties": {
"data": {
"type": "string"
@ -2634,11 +2464,7 @@
},
"ProcessLogsResponse": {
"type": "object",
"required": [
"processId",
"stream",
"entries"
],
"required": ["processId", "stream", "entries"],
"properties": {
"entries": {
"type": "array",
@ -2656,18 +2482,11 @@
},
"ProcessLogsStream": {
"type": "string",
"enum": [
"stdout",
"stderr",
"combined",
"pty"
]
"enum": ["stdout", "stderr", "combined", "pty"]
},
"ProcessRunRequest": {
"type": "object",
"required": [
"command"
],
"required": ["command"],
"properties": {
"args": {
"type": "array",
@ -2703,14 +2522,7 @@
},
"ProcessRunResponse": {
"type": "object",
"required": [
"timedOut",
"stdout",
"stderr",
"stdoutTruncated",
"stderrTruncated",
"durationMs"
],
"required": ["timedOut", "stdout", "stderr", "stdoutTruncated", "stderrTruncated", "durationMs"],
"properties": {
"durationMs": {
"type": "integer",
@ -2752,17 +2564,11 @@
},
"ProcessState": {
"type": "string",
"enum": [
"running",
"exited"
]
"enum": ["running", "exited"]
},
"ProcessTerminalResizeRequest": {
"type": "object",
"required": [
"cols",
"rows"
],
"required": ["cols", "rows"],
"properties": {
"cols": {
"type": "integer",
@ -2778,10 +2584,7 @@
},
"ProcessTerminalResizeResponse": {
"type": "object",
"required": [
"cols",
"rows"
],
"required": ["cols", "rows"],
"properties": {
"cols": {
"type": "integer",
@ -2797,16 +2600,11 @@
},
"ServerStatus": {
"type": "string",
"enum": [
"running",
"stopped"
]
"enum": ["running", "stopped"]
},
"ServerStatusInfo": {
"type": "object",
"required": [
"status"
],
"required": ["status"],
"properties": {
"status": {
"$ref": "#/components/schemas/ServerStatus"
@ -2821,10 +2619,7 @@
},
"SkillSource": {
"type": "object",
"required": [
"type",
"source"
],
"required": ["type", "source"],
"properties": {
"ref": {
"type": "string",
@ -2851,9 +2646,7 @@
},
"SkillsConfig": {
"type": "object",
"required": [
"sources"
],
"required": ["sources"],
"properties": {
"sources": {
"type": "array",
@ -2865,10 +2658,7 @@
},
"SkillsConfigQuery": {
"type": "object",
"required": [
"directory",
"skillName"
],
"required": ["directory", "skillName"],
"properties": {
"directory": {
"type": "string"
@ -2886,4 +2676,4 @@
"description": "ACP proxy v1 API"
}
]
}
}

View file

@ -6,6 +6,13 @@ icon: "react"
`@sandbox-agent/react` exposes small React components built on top of the `sandbox-agent` SDK.
Current exports:
- `AgentConversation` for a combined transcript + composer surface
- `ProcessTerminal` for attaching to a running tty process
- `AgentTranscript` for rendering session/message timelines without bundling any styles
- `ChatComposer` for a reusable prompt input/send surface
## Install
```bash
@ -101,3 +108,128 @@ export default function TerminalPane() {
- `onExit`, `onError`: optional lifecycle callbacks
See [Processes](/processes) for the lower-level terminal APIs.
## Headless transcript
`AgentTranscript` is intentionally unstyled. It follows the common headless React pattern used by libraries like Radix, Headless UI, and React Aria: behavior lives in the component, while styling stays in your app through `className`, slot-level `classNames`, and `data-*` state attributes on the rendered DOM.
```tsx TranscriptPane.tsx
import {
AgentTranscript,
type AgentTranscriptClassNames,
type TranscriptEntry,
} from "@sandbox-agent/react";
const transcriptClasses: Partial<AgentTranscriptClassNames> = {
root: "transcript",
message: "transcript-message",
messageContent: "transcript-message-content",
toolGroupContainer: "transcript-tools",
toolGroupHeader: "transcript-tools-header",
toolItem: "transcript-tool-item",
toolItemHeader: "transcript-tool-item-header",
toolItemBody: "transcript-tool-item-body",
divider: "transcript-divider",
dividerText: "transcript-divider-text",
error: "transcript-error",
};
export function TranscriptPane({ entries }: { entries: TranscriptEntry[] }) {
return (
<AgentTranscript
entries={entries}
classNames={transcriptClasses}
renderMessageText={(entry) => <div>{entry.text}</div>}
renderInlinePendingIndicator={() => <span>...</span>}
renderToolGroupIcon={() => <span>Events</span>}
renderChevron={(expanded) => <span>{expanded ? "Hide" : "Show"}</span>}
/>
);
}
```
```css
.transcript {
display: grid;
gap: 12px;
}
.transcript [data-slot="message"][data-variant="user"] .transcript-message-content {
background: #161616;
color: white;
}
.transcript [data-slot="message"][data-variant="assistant"] .transcript-message-content {
background: #f4f4f0;
color: #161616;
}
.transcript [data-slot="tool-item"][data-failed="true"] {
border-color: #d33;
}
.transcript [data-slot="tool-item-header"][data-expanded="true"] {
background: rgba(0, 0, 0, 0.06);
}
```
`AgentTranscript` accepts `TranscriptEntry[]`, which matches the Inspector timeline shape:
- `message` entries render user/assistant text
- `tool` entries render expandable tool input/output sections
- `reasoning` entries render expandable reasoning blocks
- `meta` entries render status rows or expandable metadata details
Useful props:
- `className`: root class hook
- `classNames`: slot-level class hooks for styling from outside the package
- `renderMessageText`: custom text or markdown renderer
- `renderToolItemIcon`, `renderToolGroupIcon`, `renderChevron`, `renderEventLinkContent`: presentation overrides
- `renderInlinePendingIndicator`, `renderThinkingState`: loading/thinking UI overrides
- `isDividerEntry`, `canOpenEvent`, `getToolGroupSummary`: behavior overrides for grouping and labels
## Composer and conversation
`ChatComposer` is the headless message input. `AgentConversation` composes `AgentTranscript` and `ChatComposer` so apps can reuse the transcript/composer pairing without pulling in Inspector session chrome.
```tsx ConversationPane.tsx
import { AgentConversation, type TranscriptEntry } from "@sandbox-agent/react";
export function ConversationPane({
entries,
message,
onMessageChange,
onSubmit,
}: {
entries: TranscriptEntry[];
message: string;
onMessageChange: (value: string) => void;
onSubmit: () => void;
}) {
return (
<AgentConversation
entries={entries}
emptyState={<div>Start the conversation.</div>}
transcriptProps={{
renderMessageText: (entry) => <div>{entry.text}</div>,
}}
composerProps={{
message,
onMessageChange,
onSubmit,
placeholder: "Send a message...",
}}
/>
);
}
```
Useful `ChatComposer` props:
- `className` and `classNames` for external styling
- `inputRef` to manage focus or autoresize from the consumer
- `textareaProps` for lower-level textarea behavior
- `allowEmptySubmit` when the submit action is valid without draft text, such as a stop button
Use `transcriptProps` and `composerProps` when you want the shared composition but still need custom rendering or behavior. Use `transcriptClassNames` and `composerClassNames` when you want styling hooks for each subcomponent.

View file

@ -11,17 +11,14 @@ setupImage();
console.log("Creating BoxLite sandbox...");
const box = new SimpleBox({
rootfsPath: OCI_DIR,
env,
ports: [{ hostPort: 3000, guestPort: 3000 }],
diskSizeGb: 4,
rootfsPath: OCI_DIR,
env,
ports: [{ hostPort: 3000, guestPort: 3000 }],
diskSizeGb: 4,
});
console.log("Starting server...");
const result = await box.exec(
"sh", "-c",
"nohup sandbox-agent server --no-token --host 0.0.0.0 --port 3000 >/tmp/sandbox-agent.log 2>&1 &",
);
const result = await box.exec("sh", "-c", "nohup sandbox-agent server --no-token --host 0.0.0.0 --port 3000 >/tmp/sandbox-agent.log 2>&1 &");
if (result.exitCode !== 0) throw new Error(`Failed to start server: ${result.stderr}`);
const baseUrl = "http://localhost:3000";
@ -36,9 +33,9 @@ console.log(" Press Ctrl+C to stop.");
const keepAlive = setInterval(() => {}, 60_000);
const cleanup = async () => {
clearInterval(keepAlive);
await box.stop();
process.exit(0);
clearInterval(keepAlive);
await box.stop();
process.exit(0);
};
process.once("SIGINT", cleanup);
process.once("SIGTERM", cleanup);

View file

@ -5,12 +5,12 @@ export const DOCKER_IMAGE = "sandbox-agent-boxlite";
export const OCI_DIR = new URL("../oci-image", import.meta.url).pathname;
export function setupImage() {
console.log(`Building image "${DOCKER_IMAGE}" (cached after first run)...`);
execSync(`docker build -t ${DOCKER_IMAGE} ${new URL("..", import.meta.url).pathname}`, { stdio: "inherit" });
console.log(`Building image "${DOCKER_IMAGE}" (cached after first run)...`);
execSync(`docker build -t ${DOCKER_IMAGE} ${new URL("..", import.meta.url).pathname}`, { stdio: "inherit" });
if (!existsSync(`${OCI_DIR}/oci-layout`)) {
console.log("Exporting to OCI layout...");
mkdirSync(OCI_DIR, { recursive: true });
execSync(`docker save ${DOCKER_IMAGE} | tar -xf - -C ${OCI_DIR}`, { stdio: "inherit" });
}
if (!existsSync(`${OCI_DIR}/oci-layout`)) {
console.log("Exporting to OCI layout...");
mkdirSync(OCI_DIR, { recursive: true });
execSync(`docker save ${DOCKER_IMAGE} | tar -xf - -C ${OCI_DIR}`, { stdio: "inherit" });
}
}

View file

@ -128,7 +128,7 @@ export function App() {
console.error("Event stream error:", err);
}
},
[log]
[log],
);
const send = useCallback(async () => {
@ -162,12 +162,7 @@ export function App() {
<div style={styles.connectForm}>
<label style={styles.label}>
Sandbox name:
<input
style={styles.input}
value={sandboxName}
onChange={(e) => setSandboxName(e.target.value)}
placeholder="demo"
/>
<input style={styles.input} value={sandboxName} onChange={(e) => setSandboxName(e.target.value)} placeholder="demo" />
</label>
<button style={styles.button} onClick={connect}>
Connect

View file

@ -5,5 +5,5 @@ import { App } from "./App";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
</StrictMode>
</StrictMode>,
);

View file

@ -2,65 +2,61 @@ import type { Sandbox } from "@cloudflare/sandbox";
import { SandboxAgent } from "sandbox-agent";
export type PromptRequest = {
agent?: string;
prompt?: string;
agent?: string;
prompt?: string;
};
export async function runPromptEndpointStream(
sandbox: Sandbox,
request: PromptRequest,
port: number,
emit: (event: { type: string; [key: string]: unknown }) => Promise<void> | void,
sandbox: Sandbox,
request: PromptRequest,
port: number,
emit: (event: { type: string; [key: string]: unknown }) => Promise<void> | void,
): Promise<void> {
const client = await SandboxAgent.connect({
fetch: (req, init) =>
sandbox.containerFetch(
req,
{
...(init ?? {}),
// Cloudflare containerFetch may drop long-lived update streams when
// a forwarded AbortSignal is cancelled; clear it for this path.
signal: undefined,
},
port,
),
});
const client = await SandboxAgent.connect({
fetch: (req, init) =>
sandbox.containerFetch(
req,
{
...(init ?? {}),
// Cloudflare containerFetch may drop long-lived update streams when
// a forwarded AbortSignal is cancelled; clear it for this path.
signal: undefined,
},
port,
),
});
let unsubscribe: (() => void) | undefined;
try {
const session = await client.createSession({
agent: request.agent ?? "codex",
});
let unsubscribe: (() => void) | undefined;
try {
const session = await client.createSession({
agent: request.agent ?? "codex",
});
const promptText =
request.prompt?.trim() || "Reply with a short confirmation.";
await emit({
type: "session.created",
sessionId: session.id,
agent: session.agent,
prompt: promptText,
});
const promptText = request.prompt?.trim() || "Reply with a short confirmation.";
await emit({
type: "session.created",
sessionId: session.id,
agent: session.agent,
prompt: promptText,
});
let pendingWrites: Promise<void> = Promise.resolve();
unsubscribe = session.onEvent((event) => {
pendingWrites = pendingWrites
.then(async () => {
await emit({ type: "session.event", event });
})
.catch(() => {});
});
let pendingWrites: Promise<void> = Promise.resolve();
unsubscribe = session.onEvent((event) => {
pendingWrites = pendingWrites
.then(async () => {
await emit({ type: "session.event", event });
})
.catch(() => {});
});
const response = await session.prompt([{ type: "text", text: promptText }]);
await pendingWrites;
await emit({ type: "prompt.response", response });
await emit({ type: "prompt.completed" });
} finally {
if (unsubscribe) {
unsubscribe();
}
await Promise.race([
client.dispose(),
new Promise((resolve) => setTimeout(resolve, 250)),
]);
}
const response = await session.prompt([{ type: "text", text: promptText }]);
await pendingWrites;
await emit({ type: "prompt.response", response });
await emit({ type: "prompt.completed" });
} finally {
if (unsubscribe) {
unsubscribe();
}
await Promise.race([client.dispose(), new Promise((resolve) => setTimeout(resolve, 250))]);
}
}

View file

@ -15,8 +15,7 @@ import { fileURLToPath } from "node:url";
import { resolve } from "node:path";
const PORT = 3000;
const REQUEST_TIMEOUT_MS =
Number.parseInt(process.env.COMPUTESDK_TIMEOUT_MS || "", 10) || 120_000;
const REQUEST_TIMEOUT_MS = Number.parseInt(process.env.COMPUTESDK_TIMEOUT_MS || "", 10) || 120_000;
/**
* Detects and validates the provider to use.
@ -24,28 +23,22 @@ const REQUEST_TIMEOUT_MS =
*/
function resolveProvider(): ProviderName {
const providerOverride = process.env.COMPUTESDK_PROVIDER;
if (providerOverride) {
if (!isValidProvider(providerOverride)) {
throw new Error(
`Unsupported ComputeSDK provider "${providerOverride}". Supported providers: ${PROVIDER_NAMES.join(", ")}`
);
throw new Error(`Unsupported ComputeSDK provider "${providerOverride}". Supported providers: ${PROVIDER_NAMES.join(", ")}`);
}
if (!isProviderAuthComplete(providerOverride)) {
const missing = getMissingEnvVars(providerOverride);
throw new Error(
`Missing credentials for provider "${providerOverride}". Set: ${missing.join(", ")}`
);
throw new Error(`Missing credentials for provider "${providerOverride}". Set: ${missing.join(", ")}`);
}
console.log(`Using ComputeSDK provider: ${providerOverride} (explicit)`);
return providerOverride as ProviderName;
}
const detected = detectProvider();
if (!detected) {
throw new Error(
`No provider credentials found. Set one of: ${PROVIDER_NAMES.map((p) => getMissingEnvVars(p).join(", ")).join(" | ")}`
);
throw new Error(`No provider credentials found. Set one of: ${PROVIDER_NAMES.map((p) => getMissingEnvVars(p).join(", ")).join(" | ")}`);
}
console.log(`Using ComputeSDK provider: ${detected} (auto-detected)`);
return detected as ProviderName;
@ -53,20 +46,19 @@ function resolveProvider(): ProviderName {
function configureComputeSDK(): void {
const provider = resolveProvider();
const config: ExplicitComputeConfig = {
provider,
computesdkApiKey: process.env.COMPUTESDK_API_KEY,
requestTimeoutMs: REQUEST_TIMEOUT_MS,
};
const providerConfig = getProviderConfigFromEnv(provider);
if (Object.keys(providerConfig).length > 0) {
const configWithProvider =
config as ExplicitComputeConfig & Record<ProviderName, Record<string, string>>;
const configWithProvider = config as ExplicitComputeConfig & Record<ProviderName, Record<string, string>>;
configWithProvider[provider] = providerConfig;
}
compute.setConfig(config);
}
@ -149,9 +141,7 @@ export async function runComputeSdkExample(): Promise<void> {
await new Promise(() => {});
}
const isDirectRun = Boolean(
process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)
);
const isDirectRun = Boolean(process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url));
if (isDirectRun) {
runComputeSdkExample().catch((error) => {

View file

@ -5,12 +5,7 @@ import { setupComputeSdkSandboxAgent } from "../src/computesdk.ts";
const hasModal = Boolean(process.env.MODAL_TOKEN_ID && process.env.MODAL_TOKEN_SECRET);
const hasVercel = Boolean(process.env.VERCEL_TOKEN || process.env.VERCEL_OIDC_TOKEN);
const hasProviderKey = Boolean(
process.env.BLAXEL_API_KEY ||
process.env.CSB_API_KEY ||
process.env.DAYTONA_API_KEY ||
process.env.E2B_API_KEY ||
hasModal ||
hasVercel
process.env.BLAXEL_API_KEY || process.env.CSB_API_KEY || process.env.DAYTONA_API_KEY || process.env.E2B_API_KEY || hasModal || hasVercel,
);
const shouldRun = Boolean(process.env.COMPUTESDK_API_KEY) && hasProviderKey;
@ -34,6 +29,6 @@ describe("computesdk example", () => {
await cleanup();
}
},
timeoutMs
timeoutMs,
);
});

View file

@ -5,23 +5,19 @@ import { detectAgent, buildInspectorUrl } from "@sandbox-agent/example-shared";
const daytona = new Daytona();
const envVars: Record<string, string> = {};
if (process.env.ANTHROPIC_API_KEY)
envVars.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY;
if (process.env.OPENAI_API_KEY)
envVars.OPENAI_API_KEY = process.env.OPENAI_API_KEY;
if (process.env.ANTHROPIC_API_KEY) envVars.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY;
if (process.env.OPENAI_API_KEY) envVars.OPENAI_API_KEY = process.env.OPENAI_API_KEY;
// Build a custom image with sandbox-agent pre-installed (slower first run, faster subsequent runs)
const image = Image.base("ubuntu:22.04").runCommands(
"apt-get update && apt-get install -y curl ca-certificates",
"curl -fsSL https://releases.rivet.dev/sandbox-agent/0.3.x/install.sh | sh",
"apt-get update && apt-get install -y curl ca-certificates",
"curl -fsSL https://releases.rivet.dev/sandbox-agent/0.3.x/install.sh | sh",
);
console.log("Creating Daytona sandbox (first run builds the base image and may take a few minutes, subsequent runs are fast)...");
const sandbox = await daytona.create({ envVars, image, autoStopInterval: 0 }, { timeout: 180 });
await sandbox.process.executeCommand(
"nohup sandbox-agent server --no-token --host 0.0.0.0 --port 3000 >/tmp/sandbox-agent.log 2>&1 &",
);
await sandbox.process.executeCommand("nohup sandbox-agent server --no-token --host 0.0.0.0 --port 3000 >/tmp/sandbox-agent.log 2>&1 &");
const baseUrl = (await sandbox.getSignedPreviewUrl(3000, 4 * 60 * 60)).url;
@ -35,9 +31,9 @@ console.log(" Press Ctrl+C to stop.");
const keepAlive = setInterval(() => {}, 60_000);
const cleanup = async () => {
clearInterval(keepAlive);
await sandbox.delete(60);
process.exit(0);
clearInterval(keepAlive);
await sandbox.delete(60);
process.exit(0);
};
process.once("SIGINT", cleanup);
process.once("SIGTERM", cleanup);

View file

@ -5,10 +5,8 @@ import { detectAgent, buildInspectorUrl } from "@sandbox-agent/example-shared";
const daytona = new Daytona();
const envVars: Record<string, string> = {};
if (process.env.ANTHROPIC_API_KEY)
envVars.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY;
if (process.env.OPENAI_API_KEY)
envVars.OPENAI_API_KEY = process.env.OPENAI_API_KEY;
if (process.env.ANTHROPIC_API_KEY) envVars.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY;
if (process.env.OPENAI_API_KEY) envVars.OPENAI_API_KEY = process.env.OPENAI_API_KEY;
// Use default image and install sandbox-agent at runtime (faster startup, no snapshot build)
console.log("Creating Daytona sandbox...");
@ -16,17 +14,13 @@ const sandbox = await daytona.create({ envVars, autoStopInterval: 0 });
// Install sandbox-agent and start server
console.log("Installing sandbox-agent...");
await sandbox.process.executeCommand(
"curl -fsSL https://releases.rivet.dev/sandbox-agent/0.3.x/install.sh | sh",
);
await sandbox.process.executeCommand("curl -fsSL https://releases.rivet.dev/sandbox-agent/0.3.x/install.sh | sh");
console.log("Installing agents...");
await sandbox.process.executeCommand("sandbox-agent install-agent claude");
await sandbox.process.executeCommand("sandbox-agent install-agent codex");
await sandbox.process.executeCommand(
"nohup sandbox-agent server --no-token --host 0.0.0.0 --port 3000 >/tmp/sandbox-agent.log 2>&1 &",
);
await sandbox.process.executeCommand("nohup sandbox-agent server --no-token --host 0.0.0.0 --port 3000 >/tmp/sandbox-agent.log 2>&1 &");
const baseUrl = (await sandbox.getSignedPreviewUrl(3000, 4 * 60 * 60)).url;
@ -40,9 +34,9 @@ console.log(" Press Ctrl+C to stop.");
const keepAlive = setInterval(() => {}, 60_000);
const cleanup = async () => {
clearInterval(keepAlive);
await sandbox.delete(60);
process.exit(0);
clearInterval(keepAlive);
await sandbox.delete(60);
process.exit(0);
};
process.once("SIGINT", cleanup);
process.once("SIGTERM", cleanup);

View file

@ -23,6 +23,6 @@ describe("daytona example", () => {
await cleanup();
}
},
timeoutMs
timeoutMs,
);
});

View file

@ -8,9 +8,7 @@ const IMAGE = "node:22-bookworm-slim";
const PORT = 3000;
const agent = detectAgent();
const codexAuthPath = process.env.HOME ? path.join(process.env.HOME, ".codex", "auth.json") : null;
const bindMounts = codexAuthPath && fs.existsSync(codexAuthPath)
? [`${codexAuthPath}:/root/.codex/auth.json:ro`]
: [];
const bindMounts = codexAuthPath && fs.existsSync(codexAuthPath) ? [`${codexAuthPath}:/root/.codex/auth.json:ro`] : [];
const docker = new Docker({ socketPath: "/var/run/docker.sock" });
@ -22,7 +20,7 @@ try {
await new Promise<void>((resolve, reject) => {
docker.pull(IMAGE, (err: Error | null, stream: NodeJS.ReadableStream) => {
if (err) return reject(err);
docker.modem.followProgress(stream, (err: Error | null) => err ? reject(err) : resolve());
docker.modem.followProgress(stream, (err: Error | null) => (err ? reject(err) : resolve()));
});
});
}
@ -30,13 +28,17 @@ try {
console.log("Starting container...");
const container = await docker.createContainer({
Image: IMAGE,
Cmd: ["sh", "-c", [
"apt-get update",
"DEBIAN_FRONTEND=noninteractive apt-get install -y curl ca-certificates bash libstdc++6",
"rm -rf /var/lib/apt/lists/*",
"curl -fsSL https://releases.rivet.dev/sandbox-agent/0.3.x/install.sh | sh",
`sandbox-agent server --no-token --host 0.0.0.0 --port ${PORT}`,
].join(" && ")],
Cmd: [
"sh",
"-c",
[
"apt-get update",
"DEBIAN_FRONTEND=noninteractive apt-get install -y curl ca-certificates bash libstdc++6",
"rm -rf /var/lib/apt/lists/*",
"curl -fsSL https://releases.rivet.dev/sandbox-agent/0.3.x/install.sh | sh",
`sandbox-agent server --no-token --host 0.0.0.0 --port ${PORT}`,
].join(" && "),
],
Env: [
process.env.ANTHROPIC_API_KEY ? `ANTHROPIC_API_KEY=${process.env.ANTHROPIC_API_KEY}` : "",
process.env.OPENAI_API_KEY ? `OPENAI_API_KEY=${process.env.OPENAI_API_KEY}` : "",
@ -63,8 +65,12 @@ console.log(" Press Ctrl+C to stop.");
const keepAlive = setInterval(() => {}, 60_000);
const cleanup = async () => {
clearInterval(keepAlive);
try { await container.stop({ t: 5 }); } catch {}
try { await container.remove({ force: true }); } catch {}
try {
await container.stop({ t: 5 });
} catch {}
try {
await container.remove({ force: true });
} catch {}
process.exit(0);
};
process.once("SIGINT", cleanup);

View file

@ -23,6 +23,6 @@ describe("docker example", () => {
await cleanup();
}
},
timeoutMs
timeoutMs,
);
});

View file

@ -23,6 +23,6 @@ describe("e2b example", () => {
await cleanup();
}
},
timeoutMs
timeoutMs,
);
});

View file

@ -24,10 +24,7 @@ console.log("Uploading files via batch tar...");
const client = await SandboxAgent.connect({ baseUrl });
const tarPath = path.join(tmpDir, "upload.tar");
await tar.create(
{ file: tarPath, cwd: tmpDir },
["my-project"],
);
await tar.create({ file: tarPath, cwd: tmpDir }, ["my-project"]);
const tarBuffer = await fs.promises.readFile(tarPath);
const uploadResult = await client.uploadFsBatch(tarBuffer, { path: "/opt" });
console.log(` Uploaded ${uploadResult.paths.length} files: ${uploadResult.paths.join(", ")}`);
@ -54,4 +51,7 @@ console.log(' Try: "read the README in /opt/my-project"');
console.log(" Press Ctrl+C to stop.");
const keepAlive = setInterval(() => {}, 60_000);
process.on("SIGINT", () => { clearInterval(keepAlive); cleanup().then(() => process.exit(0)); });
process.on("SIGINT", () => {
clearInterval(keepAlive);
cleanup().then(() => process.exit(0));
});

View file

@ -23,10 +23,7 @@ console.log("Uploading MCP server bundle...");
const client = await SandboxAgent.connect({ baseUrl });
const bundle = await fs.promises.readFile(serverFile);
const written = await client.writeFsFile(
{ path: "/opt/mcp/custom-tools/mcp-server.cjs" },
bundle,
);
const written = await client.writeFsFile({ path: "/opt/mcp/custom-tools/mcp-server.cjs" }, bundle);
console.log(` Written: ${written.path} (${written.bytesWritten} bytes)`);
// Create a session with the uploaded MCP server as a local command.
@ -35,12 +32,14 @@ const session = await client.createSession({
agent: detectAgent(),
sessionInit: {
cwd: "/root",
mcpServers: [{
name: "customTools",
command: "node",
args: ["/opt/mcp/custom-tools/mcp-server.cjs"],
env: [],
}],
mcpServers: [
{
name: "customTools",
command: "node",
args: ["/opt/mcp/custom-tools/mcp-server.cjs"],
env: [],
},
],
},
});
const sessionId = session.id;
@ -49,4 +48,7 @@ console.log(' Try: "generate a random number between 1 and 100"');
console.log(" Press Ctrl+C to stop.");
const keepAlive = setInterval(() => {}, 60_000);
process.on("SIGINT", () => { clearInterval(keepAlive); cleanup().then(() => process.exit(0)); });
process.on("SIGINT", () => {
clearInterval(keepAlive);
cleanup().then(() => process.exit(0));
});

View file

@ -5,9 +5,7 @@ import { startDockerSandbox } from "@sandbox-agent/example-shared/docker";
console.log("Starting sandbox...");
const { baseUrl, cleanup } = await startDockerSandbox({
port: 3002,
setupCommands: [
"npm install -g --silent @modelcontextprotocol/server-everything@2026.1.26",
],
setupCommands: ["npm install -g --silent @modelcontextprotocol/server-everything@2026.1.26"],
});
console.log("Creating session with everything MCP server...");
@ -16,12 +14,14 @@ const session = await client.createSession({
agent: detectAgent(),
sessionInit: {
cwd: "/root",
mcpServers: [{
name: "everything",
command: "mcp-server-everything",
args: [],
env: [],
}],
mcpServers: [
{
name: "everything",
command: "mcp-server-everything",
args: [],
env: [],
},
],
},
});
const sessionId = session.id;
@ -30,4 +30,7 @@ console.log(' Try: "generate a random number between 1 and 100"');
console.log(" Press Ctrl+C to stop.");
const keepAlive = setInterval(() => {}, 60_000);
process.on("SIGINT", () => { clearInterval(keepAlive); cleanup().then(() => process.exit(0)); });
process.on("SIGINT", () => {
clearInterval(keepAlive);
cleanup().then(() => process.exit(0));
});

View file

@ -1,18 +1,12 @@
import { createInterface } from "node:readline/promises";
import { stdin as input, stdout as output } from "node:process";
import { Command } from "commander";
import {
SandboxAgent,
type PermissionReply,
type SessionPermissionRequest,
} from "sandbox-agent";
import { SandboxAgent, type PermissionReply, type SessionPermissionRequest } from "sandbox-agent";
const options = parseOptions();
const agent = options.agent.trim().toLowerCase();
const autoReply = parsePermissionReply(options.reply);
const promptText =
options.prompt?.trim() ||
`Create ./permission-example.txt with the text 'hello from the ${agent} permissions example'.`;
const promptText = options.prompt?.trim() || `Create ./permission-example.txt with the text 'hello from the ${agent} permissions example'.`;
const sdk = await SandboxAgent.start({
spawn: {
@ -31,11 +25,7 @@ try {
: [];
const modeOption = configOptions.find((option) => option.category === "mode");
const availableModes = extractOptionValues(modeOption);
const mode =
options.mode?.trim() ||
(typeof modeOption?.currentValue === "string" ? modeOption.currentValue : "") ||
availableModes[0] ||
"";
const mode = options.mode?.trim() || (typeof modeOption?.currentValue === "string" ? modeOption.currentValue : "") || availableModes[0] || "";
console.log(`Agent: ${agent}`);
console.log(`Mode: ${mode || "(default)"}`);
@ -91,10 +81,7 @@ async function handlePermissionRequest(
await session.respondPermission(request.id, reply);
}
async function promptForReply(
request: SessionPermissionRequest,
rl: ReturnType<typeof createInterface> | null,
): Promise<PermissionReply> {
async function promptForReply(request: SessionPermissionRequest, rl: ReturnType<typeof createInterface> | null): Promise<PermissionReply> {
if (!rl) {
return "reject";
}
@ -136,8 +123,7 @@ function extractOptionValues(option: { options?: unknown[] } | undefined): strin
if (!nested || typeof nested !== "object") {
continue;
}
const nestedValue =
"value" in nested && typeof nested.value === "string" ? nested.value : null;
const nestedValue = "value" in nested && typeof nested.value === "string" ? nested.value : null;
if (nestedValue) {
values.push(nestedValue);
}

View file

@ -7,10 +7,7 @@ const persist = new InMemorySessionPersistDriver();
console.log("Starting sandbox...");
const sandbox = await startDockerSandbox({
port: 3000,
setupCommands: [
"sandbox-agent install-agent claude",
"sandbox-agent install-agent codex",
],
setupCommands: ["sandbox-agent install-agent claude", "sandbox-agent install-agent codex"],
});
const sdk = await SandboxAgent.connect({ baseUrl: sandbox.baseUrl, persist });

View file

@ -16,21 +16,47 @@ if (process.env.DATABASE_URL) {
connectionString = process.env.DATABASE_URL;
} else {
const name = `persist-example-${randomUUID().slice(0, 8)}`;
containerId = execFileSync("docker", [
"run", "-d", "--rm", "--name", name,
"-e", "POSTGRES_USER=postgres", "-e", "POSTGRES_PASSWORD=postgres", "-e", "POSTGRES_DB=sandbox",
"-p", "127.0.0.1::5432", "postgres:16-alpine",
], { encoding: "utf8" }).trim();
containerId = execFileSync(
"docker",
[
"run",
"-d",
"--rm",
"--name",
name,
"-e",
"POSTGRES_USER=postgres",
"-e",
"POSTGRES_PASSWORD=postgres",
"-e",
"POSTGRES_DB=sandbox",
"-p",
"127.0.0.1::5432",
"postgres:16-alpine",
],
{ encoding: "utf8" },
).trim();
const port = execFileSync("docker", ["port", containerId, "5432/tcp"], { encoding: "utf8" })
.trim().split("\n")[0]?.match(/:(\d+)$/)?.[1];
.trim()
.split("\n")[0]
?.match(/:(\d+)$/)?.[1];
connectionString = `postgres://postgres:postgres@127.0.0.1:${port}/sandbox`;
console.log(`Postgres on port ${port}`);
const deadline = Date.now() + 30_000;
while (Date.now() < deadline) {
const c = new Client({ connectionString });
try { await c.connect(); await c.query("SELECT 1"); await c.end(); break; }
catch { try { await c.end(); } catch {} await delay(250); }
try {
await c.connect();
await c.query("SELECT 1");
await c.end();
break;
} catch {
try {
await c.end();
} catch {}
await delay(250);
}
}
}
@ -40,10 +66,7 @@ try {
console.log("Starting sandbox...");
const sandbox = await startDockerSandbox({
port: 3000,
setupCommands: [
"sandbox-agent install-agent claude",
"sandbox-agent install-agent codex",
],
setupCommands: ["sandbox-agent install-agent claude", "sandbox-agent install-agent codex"],
});
const sdk = await SandboxAgent.connect({ baseUrl: sandbox.baseUrl, persist });
@ -71,6 +94,8 @@ try {
await sandbox.cleanup();
} finally {
if (containerId) {
try { execFileSync("docker", ["rm", "-f", containerId], { stdio: "ignore" }); } catch {}
try {
execFileSync("docker", ["rm", "-f", containerId], { stdio: "ignore" });
} catch {}
}
}

View file

@ -8,10 +8,7 @@ const persist = new SQLiteSessionPersistDriver({ filename: "./sessions.db" });
console.log("Starting sandbox...");
const sandbox = await startDockerSandbox({
port: 3000,
setupCommands: [
"sandbox-agent install-agent claude",
"sandbox-agent install-agent codex",
],
setupCommands: ["sandbox-agent install-agent claude", "sandbox-agent install-agent codex"],
});
const sdk = await SandboxAgent.connect({ baseUrl: sandbox.baseUrl, persist });

View file

@ -40,7 +40,7 @@ const DIRECT_CREDENTIAL_KEYS = [
function stripShellQuotes(value: string): string {
const trimmed = value.trim();
if (trimmed.length >= 2 && trimmed.startsWith("\"") && trimmed.endsWith("\"")) {
if (trimmed.length >= 2 && trimmed.startsWith('"') && trimmed.endsWith('"')) {
return trimmed.slice(1, -1);
}
if (trimmed.length >= 2 && trimmed.startsWith("'") && trimmed.endsWith("'")) {
@ -107,11 +107,7 @@ function collectCredentialEnv(): Record<string, string> {
const merged: Record<string, string> = {};
let extracted: Record<string, string> = {};
try {
const output = execFileSync(
"sandbox-agent",
["credentials", "extract-env"],
{ encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] },
);
const output = execFileSync("sandbox-agent", ["credentials", "extract-env"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
extracted = parseExtractedCredentials(output);
} catch {
// Fall back to direct env vars if extraction is unavailable.
@ -132,10 +128,7 @@ function shellSingleQuotedLiteral(value: string): string {
}
function stripAnsi(value: string): string {
return value.replace(
/[\u001B\u009B][[\]()#;?]*(?:(?:[a-zA-Z\d]*(?:;[a-zA-Z\d]*)*)?\u0007|(?:\d{1,4}(?:;\d{0,4})*)?[0-9A-ORZcf-nqry=><])/g,
"",
);
return value.replace(/[\u001B\u009B][[\]()#;?]*(?:(?:[a-zA-Z\d]*(?:;[a-zA-Z\d]*)*)?\u0007|(?:\d{1,4}(?:;\d{0,4})*)?[0-9A-ORZcf-nqry=><])/g, "");
}
async function ensureExampleImage(_docker: Docker): Promise<string> {
@ -145,11 +138,7 @@ async function ensureExampleImage(_docker: Docker): Promise<string> {
if (dev) {
console.log(" Building sandbox image from source (may take a while, only runs once)...");
try {
execFileSync("docker", [
"build", "-t", imageName,
"-f", path.join(DOCKERFILE_DIR, "Dockerfile.dev"),
REPO_ROOT,
], {
execFileSync("docker", ["build", "-t", imageName, "-f", path.join(DOCKERFILE_DIR, "Dockerfile.dev"), REPO_ROOT], {
stdio: ["ignore", "ignore", "pipe"],
});
} catch (err: unknown) {
@ -224,19 +213,13 @@ export async function startDockerSandbox(opts: DockerSandboxOptions): Promise<Do
image = await ensureExampleImage(docker);
}
const bootCommands = [
...setupCommands,
`sandbox-agent server --no-token --host 0.0.0.0 --port ${port}`,
];
const bootCommands = [...setupCommands, `sandbox-agent server --no-token --host 0.0.0.0 --port ${port}`];
const container = await docker.createContainer({
Image: image,
WorkingDir: "/root",
Cmd: ["sh", "-c", bootCommands.join(" && ")],
Env: [
...Object.entries(credentialEnv).map(([key, value]) => `${key}=${value}`),
...Object.entries(bootstrapEnv).map(([key, value]) => `${key}=${value}`),
],
Env: [...Object.entries(credentialEnv).map(([key, value]) => `${key}=${value}`), ...Object.entries(bootstrapEnv).map(([key, value]) => `${key}=${value}`)],
ExposedPorts: { [`${port}/tcp`]: {} },
HostConfig: {
AutoRemove: true,
@ -246,12 +229,12 @@ export async function startDockerSandbox(opts: DockerSandboxOptions): Promise<Do
await container.start();
const logChunks: string[] = [];
const startupLogs = await container.logs({
const startupLogs = (await container.logs({
follow: true,
stdout: true,
stderr: true,
since: 0,
}) as NodeJS.ReadableStream;
})) as NodeJS.ReadableStream;
const stdoutStream = new PassThrough();
const stderrStream = new PassThrough();
stdoutStream.on("data", (chunk) => {
@ -263,7 +246,9 @@ export async function startDockerSandbox(opts: DockerSandboxOptions): Promise<Do
docker.modem.demuxStream(startupLogs, stdoutStream, stderrStream);
const stopStartupLogs = () => {
const stream = startupLogs as NodeJS.ReadableStream & { destroy?: () => void };
try { stream.destroy?.(); } catch {}
try {
stream.destroy?.();
} catch {}
};
const inspect = await container.inspect();
@ -279,8 +264,12 @@ export async function startDockerSandbox(opts: DockerSandboxOptions): Promise<Do
const cleanup = async () => {
stopStartupLogs();
try { await container.stop({ t: 5 }); } catch {}
try { await container.remove({ force: true }); } catch {}
try {
await container.stop({ t: 5 });
} catch {}
try {
await container.remove({ force: true });
} catch {}
process.exit(0);
};
process.once("SIGINT", cleanup);

View file

@ -41,15 +41,7 @@ export function buildInspectorUrl({
return `${normalized}/ui/${sessionPath}${queryString ? `?${queryString}` : ""}`;
}
export function logInspectorUrl({
baseUrl,
token,
headers,
}: {
baseUrl: string;
token?: string;
headers?: Record<string, string>;
}): void {
export function logInspectorUrl({ baseUrl, token, headers }: { baseUrl: string; token?: string; headers?: Record<string, string> }): void {
console.log(`Inspector: ${buildInspectorUrl({ baseUrl, token, headers })}`);
}
@ -84,10 +76,7 @@ export function generateSessionId(): string {
export function detectAgent(): string {
if (process.env.SANDBOX_AGENT) return process.env.SANDBOX_AGENT;
const hasClaude = Boolean(
process.env.ANTHROPIC_API_KEY ||
process.env.CLAUDE_API_KEY ||
process.env.CLAUDE_CODE_OAUTH_TOKEN ||
process.env.ANTHROPIC_AUTH_TOKEN,
process.env.ANTHROPIC_API_KEY || process.env.CLAUDE_API_KEY || process.env.CLAUDE_CODE_OAUTH_TOKEN || process.env.ANTHROPIC_AUTH_TOKEN,
);
const openAiLikeKey = process.env.OPENAI_API_KEY || process.env.CODEX_API_KEY || "";
const hasCodexApiKey = openAiLikeKey.startsWith("sk-");

View file

@ -23,25 +23,16 @@ console.log("Uploading script and skill file...");
const client = await SandboxAgent.connect({ baseUrl });
const script = await fs.promises.readFile(scriptFile);
const scriptResult = await client.writeFsFile(
{ path: "/opt/skills/random-number/random-number.cjs" },
script,
);
const scriptResult = await client.writeFsFile({ path: "/opt/skills/random-number/random-number.cjs" }, script);
console.log(` Script: ${scriptResult.path} (${scriptResult.bytesWritten} bytes)`);
const skillMd = await fs.promises.readFile(path.resolve(__dirname, "../SKILL.md"));
const skillResult = await client.writeFsFile(
{ path: "/opt/skills/random-number/SKILL.md" },
skillMd,
);
const skillResult = await client.writeFsFile({ path: "/opt/skills/random-number/SKILL.md" }, skillMd);
console.log(` Skill: ${skillResult.path} (${skillResult.bytesWritten} bytes)`);
// Configure the uploaded skill.
console.log("Configuring custom skill...");
await client.setSkillsConfig(
{ directory: "/", skillName: "random-number" },
{ sources: [{ type: "local", source: "/opt/skills/random-number" }] },
);
await client.setSkillsConfig({ directory: "/", skillName: "random-number" }, { sources: [{ type: "local", source: "/opt/skills/random-number" }] });
// Create a session.
console.log("Creating session with custom skill...");
@ -52,4 +43,7 @@ console.log(' Try: "generate a random number between 1 and 100"');
console.log(" Press Ctrl+C to stop.");
const keepAlive = setInterval(() => {}, 60_000);
process.on("SIGINT", () => { clearInterval(keepAlive); cleanup().then(() => process.exit(0)); });
process.on("SIGINT", () => {
clearInterval(keepAlive);
cleanup().then(() => process.exit(0));
});

View file

@ -22,4 +22,7 @@ console.log(' Try: "How do I start sandbox-agent?"');
console.log(" Press Ctrl+C to stop.");
const keepAlive = setInterval(() => {}, 60_000);
process.on("SIGINT", () => { clearInterval(keepAlive); cleanup().then(() => process.exit(0)); });
process.on("SIGINT", () => {
clearInterval(keepAlive);
cleanup().then(() => process.exit(0));
});

View file

@ -23,6 +23,6 @@ describe("vercel example", () => {
await cleanup();
}
},
timeoutMs
timeoutMs,
);
});

View file

@ -1,10 +1,7 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": [
"ES2022",
"DOM"
],
"lib": ["ES2022", "DOM"],
"module": "ESNext",
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true,
@ -14,11 +11,6 @@
"skipLibCheck": true,
"resolveJsonModule": true
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"**/*.test.ts"
]
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.test.ts"]
}

View file

@ -58,6 +58,8 @@ Use `pnpm` workspaces and Turborepo.
- GUI state should update in realtime (no manual refresh buttons). Prefer RivetKit push reactivity and actor-driven events; do not add polling/refetch for normal product flows.
- Keep the mock workbench types and mock client in `packages/shared` + `packages/client` up to date with the frontend contract. The mock is the UI testing reference implementation while backend functionality catches up.
- Keep frontend route/state coverage current in code and tests; there is no separate page-inventory doc to maintain.
- If Foundry uses a shared component from `@sandbox-agent/react`, make changes in `sdks/react` instead of copying or forking that component into Foundry.
- When changing shared React components in `sdks/react` for Foundry, verify they still work in the Sandbox Agent Inspector before finishing.
- When making UI changes, verify the live flow with `agent-browser`, take screenshots of the updated UI, and offer to open those screenshots in Preview when you finish.
- When asked for screenshots, capture all relevant affected screens and modal states, not just a single viewport. Include empty, populated, success, and blocked/error states when they are part of the changed flow.
- If a screenshot catches a transition frame, blank modal, or otherwise misleading state, retake it before reporting it.

12
factory/factory-cloud.md Normal file
View file

@ -0,0 +1,12 @@
# Factory Cloud
## Mock Server
If you are running the mock server with Beat instead of `docker compose`, use a team accession for the process so it does not terminate when your message is finished.
A detached `tmux` session is acceptable for this. Example:
```bash
tmux new-session -d -s mock-ui-4180 \
'cd /Users/nathan/conductor/workspaces/sandbox-agent/provo && OPENHANDOFF_FRONTEND_CLIENT_MODE=mock pnpm --filter @openhandoff/frontend exec vite --host localhost --port 4180'
```

View file

@ -94,7 +94,7 @@ async function generateOne(drizzleDir: string): Promise<void> {
})),
},
null,
2
2,
);
const outPath = resolve(drizzleDir, "..", "migrations.ts");
@ -128,9 +128,8 @@ async function main(): Promise<void> {
}
main().catch((error: unknown) => {
const message = error instanceof Error ? error.stack ?? error.message : String(error);
const message = error instanceof Error ? (error.stack ?? error.message) : String(error);
// eslint-disable-next-line no-console
console.error(message);
process.exitCode = 1;
});

View file

@ -8,12 +8,7 @@ let providerRegistry: ProviderRegistry | null = null;
let notificationService: NotificationService | null = null;
let runtimeDriver: BackendDriver | null = null;
export function initActorRuntimeContext(
config: AppConfig,
providers: ProviderRegistry,
notifications?: NotificationService,
driver?: BackendDriver
): void {
export function initActorRuntimeContext(config: AppConfig, providers: ProviderRegistry, notifications?: NotificationService, driver?: BackendDriver): void {
runtimeConfig = config;
providerRegistry = providers;
notificationService = notifications ?? null;

View file

@ -1,13 +1,4 @@
import {
handoffKey,
handoffStatusSyncKey,
historyKey,
projectBranchSyncKey,
projectKey,
projectPrSyncKey,
sandboxInstanceKey,
workspaceKey
} from "./keys.js";
import { handoffKey, handoffStatusSyncKey, historyKey, projectBranchSyncKey, projectKey, projectPrSyncKey, sandboxInstanceKey, workspaceKey } from "./keys.js";
import type { ProviderId } from "@openhandoff/shared";
export function actorClient(c: any) {
@ -16,7 +7,7 @@ export function actorClient(c: any) {
export async function getOrCreateWorkspace(c: any, workspaceId: string) {
return await actorClient(c).workspace.getOrCreate(workspaceKey(workspaceId), {
createWithInput: workspaceId
createWithInput: workspaceId,
});
}
@ -25,8 +16,8 @@ export async function getOrCreateProject(c: any, workspaceId: string, repoId: st
createWithInput: {
workspaceId,
repoId,
remoteUrl
}
remoteUrl,
},
});
}
@ -38,15 +29,9 @@ export function getHandoff(c: any, workspaceId: string, repoId: string, handoffI
return actorClient(c).handoff.get(handoffKey(workspaceId, repoId, handoffId));
}
export async function getOrCreateHandoff(
c: any,
workspaceId: string,
repoId: string,
handoffId: string,
createWithInput: Record<string, unknown>
) {
export async function getOrCreateHandoff(c: any, workspaceId: string, repoId: string, handoffId: string, createWithInput: Record<string, unknown>) {
return await actorClient(c).handoff.getOrCreate(handoffKey(workspaceId, repoId, handoffId), {
createWithInput
createWithInput,
});
}
@ -54,42 +39,30 @@ export async function getOrCreateHistory(c: any, workspaceId: string, repoId: st
return await actorClient(c).history.getOrCreate(historyKey(workspaceId, repoId), {
createWithInput: {
workspaceId,
repoId
}
repoId,
},
});
}
export async function getOrCreateProjectPrSync(
c: any,
workspaceId: string,
repoId: string,
repoPath: string,
intervalMs: number
) {
export async function getOrCreateProjectPrSync(c: any, workspaceId: string, repoId: string, repoPath: string, intervalMs: number) {
return await actorClient(c).projectPrSync.getOrCreate(projectPrSyncKey(workspaceId, repoId), {
createWithInput: {
workspaceId,
repoId,
repoPath,
intervalMs
}
intervalMs,
},
});
}
export async function getOrCreateProjectBranchSync(
c: any,
workspaceId: string,
repoId: string,
repoPath: string,
intervalMs: number
) {
export async function getOrCreateProjectBranchSync(c: any, workspaceId: string, repoId: string, repoPath: string, intervalMs: number) {
return await actorClient(c).projectBranchSync.getOrCreate(projectBranchSyncKey(workspaceId, repoId), {
createWithInput: {
workspaceId,
repoId,
repoPath,
intervalMs
}
intervalMs,
},
});
}
@ -102,12 +75,9 @@ export async function getOrCreateSandboxInstance(
workspaceId: string,
providerId: ProviderId,
sandboxId: string,
createWithInput: Record<string, unknown>
createWithInput: Record<string, unknown>,
) {
return await actorClient(c).sandboxInstance.getOrCreate(
sandboxInstanceKey(workspaceId, providerId, sandboxId),
{ createWithInput }
);
return await actorClient(c).sandboxInstance.getOrCreate(sandboxInstanceKey(workspaceId, providerId, sandboxId), { createWithInput });
}
export async function getOrCreateHandoffStatusSync(
@ -117,14 +87,11 @@ export async function getOrCreateHandoffStatusSync(
handoffId: string,
sandboxId: string,
sessionId: string,
createWithInput: Record<string, unknown>
createWithInput: Record<string, unknown>,
) {
return await actorClient(c).handoffStatusSync.getOrCreate(
handoffStatusSyncKey(workspaceId, repoId, handoffId, sandboxId, sessionId),
{
createWithInput
}
);
return await actorClient(c).handoffStatusSync.getOrCreate(handoffStatusSyncKey(workspaceId, repoId, handoffId, sandboxId, sessionId), {
createWithInput,
});
}
export function selfProjectPrSync(c: any) {

View file

@ -32,7 +32,7 @@ const CONTROL = {
start: "handoff.status_sync.control.start",
stop: "handoff.status_sync.control.stop",
setInterval: "handoff.status_sync.control.set_interval",
force: "handoff.status_sync.control.force"
force: "handoff.status_sync.control.force",
} as const;
async function pollSessionStatus(c: { state: HandoffStatusSyncState }): Promise<void> {
@ -43,7 +43,7 @@ async function pollSessionStatus(c: { state: HandoffStatusSyncState }): Promise<
await parent.syncWorkbenchSessionStatus({
sessionId: c.state.sessionId,
status: status.status,
at: Date.now()
at: Date.now(),
});
}
@ -56,7 +56,7 @@ export const handoffStatusSync = actor({
},
options: {
// Polling actors rely on timer-based wakeups; sleeping would pause the timer and stop polling.
noSleep: true
noSleep: true,
},
createState: (_c, input: HandoffStatusSyncInput): HandoffStatusSyncState => ({
workspaceId: input.workspaceId,
@ -66,7 +66,7 @@ export const handoffStatusSync = actor({
sandboxId: input.sandboxId,
sessionId: input.sessionId,
intervalMs: input.intervalMs,
running: true
running: true,
}),
actions: {
async start(c): Promise<void> {
@ -87,7 +87,7 @@ export const handoffStatusSync = actor({
async force(c): Promise<void> {
const self = selfHandoffStatusSync(c);
await self.send(CONTROL.force, {}, { wait: true, timeout: 5 * 60_000 });
}
},
},
run: workflow(async (ctx) => {
await runWorkflowPollingLoop<HandoffStatusSyncState>(ctx, {
@ -99,10 +99,10 @@ export const handoffStatusSync = actor({
} catch (error) {
logActorWarning("handoff-status-sync", "poll failed", {
error: resolveErrorMessage(error),
stack: resolveErrorStack(error)
stack: resolveErrorStack(error),
});
}
}
},
});
})
}),
});

View file

@ -4,4 +4,3 @@ export default defineConfig({
out: "./src/actors/handoff/db/drizzle",
schema: "./src/actors/handoff/db/schema.ts",
});

View file

@ -173,4 +173,4 @@
"internal": {
"indexes": {}
}
}
}

View file

@ -149,4 +149,4 @@
"internal": {
"indexes": {}
}
}
}

View file

@ -219,4 +219,4 @@
"internal": {
"indexes": {}
}
}
}

View file

@ -3,50 +3,50 @@
// Do not hand-edit this file.
const journal = {
"entries": [
entries: [
{
"idx": 0,
"when": 1770924374665,
"tag": "0000_condemned_maria_hill",
"breakpoints": true
idx: 0,
when: 1770924374665,
tag: "0000_condemned_maria_hill",
breakpoints: true,
},
{
"idx": 1,
"when": 1770947251055,
"tag": "0001_rapid_eddie_brock",
"breakpoints": true
idx: 1,
when: 1770947251055,
tag: "0001_rapid_eddie_brock",
breakpoints: true,
},
{
"idx": 2,
"when": 1770948428907,
"tag": "0002_lazy_moira_mactaggert",
"breakpoints": true
idx: 2,
when: 1770948428907,
tag: "0002_lazy_moira_mactaggert",
breakpoints: true,
},
{
"idx": 3,
"when": 1771027535276,
"tag": "0003_plucky_bran",
"breakpoints": true
idx: 3,
when: 1771027535276,
tag: "0003_plucky_bran",
breakpoints: true,
},
{
"idx": 4,
"when": 1771097651912,
"tag": "0004_focused_shuri",
"breakpoints": true
idx: 4,
when: 1771097651912,
tag: "0004_focused_shuri",
breakpoints: true,
},
{
"idx": 5,
"when": 1771370000000,
"tag": "0005_sandbox_actor_id",
"breakpoints": true
idx: 5,
when: 1771370000000,
tag: "0005_sandbox_actor_id",
breakpoints: true,
},
{
"idx": 6,
"when": 1773020000000,
"tag": "0006_workbench_sessions",
"breakpoints": true
}
]
idx: 6,
when: 1773020000000,
tag: "0006_workbench_sessions",
breakpoints: true,
},
],
} as const;
export default {
@ -241,5 +241,5 @@ PRAGMA foreign_keys=on;
\`created_at\` integer NOT NULL,
\`updated_at\` integer NOT NULL
);`,
} as const
} as const,
};

View file

@ -9,7 +9,7 @@ import type {
HandoffWorkbenchSetSessionUnreadInput,
HandoffWorkbenchSendMessageInput,
HandoffWorkbenchUpdateDraftInput,
ProviderId
ProviderId,
} from "@openhandoff/shared";
import { expectQueueResponse } from "../../services/queue.js";
import { selfHandoff } from "../handles.js";
@ -30,13 +30,9 @@ import {
syncWorkbenchSessionStatus,
setWorkbenchSessionUnread,
stopWorkbenchSession,
updateWorkbenchDraft
updateWorkbenchDraft,
} from "./workbench.js";
import {
HANDOFF_QUEUE_NAMES,
handoffWorkflowQueueName,
runHandoffWorkflow
} from "./workflow/index.js";
import { HANDOFF_QUEUE_NAMES, handoffWorkflowQueueName, runHandoffWorkflow } from "./workflow/index.js";
export interface HandoffInput {
workspaceId: string;
@ -115,7 +111,7 @@ export const handoff = actor({
db: handoffDb,
queues: Object.fromEntries(HANDOFF_QUEUE_NAMES.map((name) => [name, queue()])),
options: {
actionTimeout: 5 * 60_000
actionTimeout: 5 * 60_000,
},
createState: (_c, input: HandoffInput) => ({
workspaceId: input.workspaceId,
@ -157,17 +153,21 @@ export const handoff = actor({
const self = selfHandoff(c);
const result = await self.send(handoffWorkflowQueueName("handoff.command.attach"), cmd ?? {}, {
wait: true,
timeout: 20_000
timeout: 20_000,
});
return expectQueueResponse<{ target: string; sessionId: string | null }>(result);
},
async switch(c): Promise<{ switchTarget: string }> {
const self = selfHandoff(c);
const result = await self.send(handoffWorkflowQueueName("handoff.command.switch"), {}, {
wait: true,
timeout: 20_000
});
const result = await self.send(
handoffWorkflowQueueName("handoff.command.switch"),
{},
{
wait: true,
timeout: 20_000,
},
);
return expectQueueResponse<{ switchTarget: string }>(result);
},
@ -175,7 +175,7 @@ export const handoff = actor({
const self = selfHandoff(c);
await self.send(handoffWorkflowQueueName("handoff.command.push"), cmd ?? {}, {
wait: true,
timeout: 180_000
timeout: 180_000,
});
},
@ -183,7 +183,7 @@ export const handoff = actor({
const self = selfHandoff(c);
await self.send(handoffWorkflowQueueName("handoff.command.sync"), cmd ?? {}, {
wait: true,
timeout: 30_000
timeout: 30_000,
});
},
@ -191,7 +191,7 @@ export const handoff = actor({
const self = selfHandoff(c);
await self.send(handoffWorkflowQueueName("handoff.command.merge"), cmd ?? {}, {
wait: true,
timeout: 30_000
timeout: 30_000,
});
},
@ -214,7 +214,7 @@ export const handoff = actor({
const self = selfHandoff(c);
await self.send(handoffWorkflowQueueName("handoff.command.kill"), cmd ?? {}, {
wait: true,
timeout: 60_000
timeout: 60_000,
});
},
@ -227,18 +227,10 @@ export const handoff = actor({
},
async markWorkbenchUnread(c): Promise<void> {
const self = selfHandoff(c);
await self.send(handoffWorkflowQueueName("handoff.command.workbench.mark_unread"), {}, {
wait: true,
timeout: 20_000,
});
},
async renameWorkbenchHandoff(c, input: HandoffWorkbenchRenameInput): Promise<void> {
const self = selfHandoff(c);
await self.send(
handoffWorkflowQueueName("handoff.command.workbench.rename_handoff"),
{ value: input.value } satisfies HandoffWorkbenchValueCommand,
handoffWorkflowQueueName("handoff.command.workbench.mark_unread"),
{},
{
wait: true,
timeout: 20_000,
@ -246,16 +238,20 @@ export const handoff = actor({
);
},
async renameWorkbenchHandoff(c, input: HandoffWorkbenchRenameInput): Promise<void> {
const self = selfHandoff(c);
await self.send(handoffWorkflowQueueName("handoff.command.workbench.rename_handoff"), { value: input.value } satisfies HandoffWorkbenchValueCommand, {
wait: true,
timeout: 20_000,
});
},
async renameWorkbenchBranch(c, input: HandoffWorkbenchRenameInput): Promise<void> {
const self = selfHandoff(c);
await self.send(
handoffWorkflowQueueName("handoff.command.workbench.rename_branch"),
{ value: input.value } satisfies HandoffWorkbenchValueCommand,
{
wait: true,
timeout: 5 * 60_000,
},
);
await self.send(handoffWorkflowQueueName("handoff.command.workbench.rename_branch"), { value: input.value } satisfies HandoffWorkbenchValueCommand, {
wait: true,
timeout: 5 * 60_000,
});
},
async createWorkbenchSession(c, input?: { model?: string }): Promise<{ tabId: string }> {
@ -341,26 +337,18 @@ export const handoff = actor({
async stopWorkbenchSession(c, input: HandoffTabCommand): Promise<void> {
const self = selfHandoff(c);
await self.send(
handoffWorkflowQueueName("handoff.command.workbench.stop_session"),
{ sessionId: input.tabId } satisfies HandoffWorkbenchSessionCommand,
{
wait: true,
timeout: 5 * 60_000,
},
);
await self.send(handoffWorkflowQueueName("handoff.command.workbench.stop_session"), { sessionId: input.tabId } satisfies HandoffWorkbenchSessionCommand, {
wait: true,
timeout: 5 * 60_000,
});
},
async syncWorkbenchSessionStatus(c, input: HandoffStatusSyncCommand): Promise<void> {
const self = selfHandoff(c);
await self.send(
handoffWorkflowQueueName("handoff.command.workbench.sync_session_status"),
input,
{
wait: true,
timeout: 20_000,
},
);
await self.send(handoffWorkflowQueueName("handoff.command.workbench.sync_session_status"), input, {
wait: true,
timeout: 20_000,
});
},
async closeWorkbenchSession(c, input: HandoffTabCommand): Promise<void> {
@ -377,25 +365,25 @@ export const handoff = actor({
async publishWorkbenchPr(c): Promise<void> {
const self = selfHandoff(c);
await self.send(handoffWorkflowQueueName("handoff.command.workbench.publish_pr"), {}, {
wait: true,
timeout: 10 * 60_000,
});
await self.send(
handoffWorkflowQueueName("handoff.command.workbench.publish_pr"),
{},
{
wait: true,
timeout: 10 * 60_000,
},
);
},
async revertWorkbenchFile(c, input: { path: string }): Promise<void> {
const self = selfHandoff(c);
await self.send(
handoffWorkflowQueueName("handoff.command.workbench.revert_file"),
input,
{
wait: true,
timeout: 5 * 60_000,
},
);
}
await self.send(handoffWorkflowQueueName("handoff.command.workbench.revert_file"), input, {
wait: true,
timeout: 5 * 60_000,
});
},
},
run: workflow(runHandoffWorkflow)
run: workflow(runHandoffWorkflow),
});
export { HANDOFF_QUEUE_NAMES };

View file

@ -2,12 +2,7 @@
import { basename } from "node:path";
import { asc, eq } from "drizzle-orm";
import { getActorRuntimeContext } from "../context.js";
import {
getOrCreateHandoffStatusSync,
getOrCreateProject,
getOrCreateWorkspace,
getSandboxInstance,
} from "../handles.js";
import { getOrCreateHandoffStatusSync, getOrCreateProject, getOrCreateWorkspace, getSandboxInstance } from "../handles.js";
import { handoff as handoffTable, handoffRuntime, handoffWorkbenchSessions } from "./db/schema.js";
import { getCurrentRecord } from "./workflow/common.js";
@ -90,11 +85,7 @@ export function shouldMarkSessionUnreadForStatus(meta: { thinkingSinceMs?: numbe
async function listSessionMetaRows(c: any, options?: { includeClosed?: boolean }): Promise<Array<any>> {
await ensureWorkbenchSessionTable(c);
const rows = await c.db
.select()
.from(handoffWorkbenchSessions)
.orderBy(asc(handoffWorkbenchSessions.createdAt))
.all();
const rows = await c.db.select().from(handoffWorkbenchSessions).orderBy(asc(handoffWorkbenchSessions.createdAt)).all();
const mapped = rows.map((row: any) => ({
...row,
id: row.sessionId,
@ -120,11 +111,7 @@ async function nextSessionName(c: any): Promise<string> {
async function readSessionMeta(c: any, sessionId: string): Promise<any | null> {
await ensureWorkbenchSessionTable(c);
const row = await c.db
.select()
.from(handoffWorkbenchSessions)
.where(eq(handoffWorkbenchSessions.sessionId, sessionId))
.get();
const row = await c.db.select().from(handoffWorkbenchSessions).where(eq(handoffWorkbenchSessions.sessionId, sessionId)).get();
if (!row) {
return null;
@ -142,12 +129,15 @@ async function readSessionMeta(c: any, sessionId: string): Promise<any | null> {
};
}
async function ensureSessionMeta(c: any, params: {
sessionId: string;
model?: string;
sessionName?: string;
unread?: boolean;
}): Promise<any> {
async function ensureSessionMeta(
c: any,
params: {
sessionId: string;
model?: string;
sessionName?: string;
unread?: boolean;
},
): Promise<any> {
await ensureWorkbenchSessionTable(c);
const existing = await readSessionMeta(c, params.sessionId);
if (existing) {
@ -202,12 +192,15 @@ function shellFragment(parts: string[]): string {
return parts.join(" && ");
}
async function executeInSandbox(c: any, params: {
sandboxId: string;
cwd: string;
command: string;
label: string;
}): Promise<{ exitCode: number; result: string }> {
async function executeInSandbox(
c: any,
params: {
sandboxId: string;
cwd: string;
command: string;
label: string;
},
): Promise<{ exitCode: number; result: string }> {
const { providers } = getActorRuntimeContext();
const provider = providers.get(c.state.providerId);
return await provider.executeCommand({
@ -226,13 +219,8 @@ function parseGitStatus(output: string): Array<{ path: string; type: "M" | "A" |
.map((line) => {
const status = line.slice(0, 2).trim();
const rawPath = line.slice(3).trim();
const path = rawPath.includes(" -> ") ? rawPath.split(" -> ").pop() ?? rawPath : rawPath;
const type =
status.includes("D")
? "D"
: status.includes("A") || status === "??"
? "A"
: "M";
const path = rawPath.includes(" -> ") ? (rawPath.split(" -> ").pop() ?? rawPath) : rawPath;
const type = status.includes("D") ? "D" : status.includes("A") || status === "??" ? "A" : "M";
return { path, type };
});
}
@ -312,10 +300,7 @@ function buildFileTree(paths: string[]): Array<any> {
async function collectWorkbenchGitState(c: any, record: any) {
const activeSandboxId = record.activeSandboxId;
const activeSandbox =
activeSandboxId != null
? (record.sandboxes ?? []).find((candidate: any) => candidate.sandboxId === activeSandboxId) ?? null
: null;
const activeSandbox = activeSandboxId != null ? ((record.sandboxes ?? []).find((candidate: any) => candidate.sandboxId === activeSandboxId) ?? null) : null;
const cwd = activeSandbox?.cwd ?? record.sandboxes?.[0]?.cwd ?? null;
if (!activeSandboxId || !cwd) {
return {
@ -423,12 +408,7 @@ async function readPullRequestSummary(c: any, branchName: string | null) {
}
try {
const project = await getOrCreateProject(
c,
c.state.workspaceId,
c.state.repoId,
c.state.repoRemote,
);
const project = await getOrCreateProject(c, c.state.workspaceId, c.state.repoId, c.state.repoRemote);
return await project.getPullRequestForBranch({ branchName });
} catch {
return null;
@ -528,8 +508,7 @@ export async function renameWorkbenchBranch(c: any, value: string): Promise<void
if (!record.activeSandboxId) {
throw new Error("cannot rename branch without an active sandbox");
}
const activeSandbox =
(record.sandboxes ?? []).find((candidate: any) => candidate.sandboxId === record.activeSandboxId) ?? null;
const activeSandbox = (record.sandboxes ?? []).find((candidate: any) => candidate.sandboxId === record.activeSandboxId) ?? null;
if (!activeSandbox?.cwd) {
throw new Error("cannot rename branch without a sandbox cwd");
}
@ -572,8 +551,7 @@ export async function createWorkbenchSession(c: any, model?: string): Promise<{
if (!record.activeSandboxId) {
throw new Error("cannot create session without an active sandbox");
}
const activeSandbox =
(record.sandboxes ?? []).find((candidate: any) => candidate.sandboxId === record.activeSandboxId) ?? null;
const activeSandbox = (record.sandboxes ?? []).find((candidate: any) => candidate.sandboxId === record.activeSandboxId) ?? null;
const cwd = activeSandbox?.cwd ?? record.sandboxes?.[0]?.cwd ?? null;
if (!cwd) {
throw new Error("cannot create session without a sandbox cwd");
@ -639,10 +617,7 @@ export async function sendWorkbenchMessage(c: any, sessionId: string, text: stri
await ensureSessionMeta(c, { sessionId });
const sandbox = getSandboxInstance(c, c.state.workspaceId, c.state.providerId, record.activeSandboxId);
const prompt = [
text.trim(),
...attachments.map((attachment: any) => `@ ${attachment.filePath}:${attachment.lineNumber}\n${attachment.lineContent}`),
]
const prompt = [text.trim(), ...attachments.map((attachment: any) => `@ ${attachment.filePath}:${attachment.lineNumber}\n${attachment.lineContent}`)]
.filter(Boolean)
.join("\n\n");
if (!prompt) {
@ -673,23 +648,15 @@ export async function sendWorkbenchMessage(c: any, sessionId: string, text: stri
.where(eq(handoffRuntime.id, 1))
.run();
const sync = await getOrCreateHandoffStatusSync(
c,
c.state.workspaceId,
c.state.repoId,
c.state.handoffId,
record.activeSandboxId,
const sync = await getOrCreateHandoffStatusSync(c, c.state.workspaceId, c.state.repoId, c.state.handoffId, record.activeSandboxId, sessionId, {
workspaceId: c.state.workspaceId,
repoId: c.state.repoId,
handoffId: c.state.handoffId,
providerId: c.state.providerId,
sandboxId: record.activeSandboxId,
sessionId,
{
workspaceId: c.state.workspaceId,
repoId: c.state.repoId,
handoffId: c.state.handoffId,
providerId: c.state.providerId,
sandboxId: record.activeSandboxId,
sessionId,
intervalMs: STATUS_SYNC_INTERVAL_MS,
},
);
intervalMs: STATUS_SYNC_INTERVAL_MS,
});
await sync.setIntervalMs({ intervalMs: STATUS_SYNC_INTERVAL_MS });
await sync.start();
await sync.force();
@ -709,12 +676,7 @@ export async function stopWorkbenchSession(c: any, sessionId: string): Promise<v
await notifyWorkbenchUpdated(c);
}
export async function syncWorkbenchSessionStatus(
c: any,
sessionId: string,
status: "running" | "idle" | "error",
at: number,
): Promise<void> {
export async function syncWorkbenchSessionStatus(c: any, sessionId: string, status: "running" | "idle" | "error", at: number): Promise<void> {
const record = await ensureWorkbenchSeeded(c);
const meta = await ensureSessionMeta(c, { sessionId });
let changed = false;
@ -821,11 +783,7 @@ export async function publishWorkbenchPr(c: any): Promise<void> {
throw new Error("cannot publish PR without a branch");
}
const { driver } = getActorRuntimeContext();
const created = await driver.github.createPr(
c.state.repoLocalPath,
record.branchName,
record.title ?? c.state.task,
);
const created = await driver.github.createPr(c.state.repoLocalPath, record.branchName, record.title ?? c.state.task);
await c.db
.update(handoffTable)
.set({
@ -842,8 +800,7 @@ export async function revertWorkbenchFile(c: any, path: string): Promise<void> {
if (!record.activeSandboxId) {
throw new Error("cannot revert file without an active sandbox");
}
const activeSandbox =
(record.sandboxes ?? []).find((candidate: any) => candidate.sandboxId === record.activeSandboxId) ?? null;
const activeSandbox = (record.sandboxes ?? []).find((candidate: any) => candidate.sandboxId === record.activeSandboxId) ?? null;
if (!activeSandbox?.cwd) {
throw new Error("cannot revert file without a sandbox cwd");
}

View file

@ -14,7 +14,7 @@ async function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: str
promise,
new Promise<T>((_resolve, reject) => {
timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs);
})
}),
]);
} finally {
if (timer) {
@ -26,34 +26,27 @@ async function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: str
export async function handleAttachActivity(loopCtx: any, msg: any): Promise<void> {
const record = await getCurrentRecord(loopCtx);
const { providers } = getActorRuntimeContext();
const activeSandbox =
record.activeSandboxId
? record.sandboxes.find((sb: any) => sb.sandboxId === record.activeSandboxId) ?? null
: null;
const activeSandbox = record.activeSandboxId ? (record.sandboxes.find((sb: any) => sb.sandboxId === record.activeSandboxId) ?? null) : null;
const provider = providers.get(activeSandbox?.providerId ?? record.providerId);
const target = await provider.attachTarget({
workspaceId: loopCtx.state.workspaceId,
sandboxId: record.activeSandboxId ?? ""
sandboxId: record.activeSandboxId ?? "",
});
await appendHistory(loopCtx, "handoff.attach", {
target: target.target,
sessionId: record.activeSessionId
sessionId: record.activeSessionId,
});
await msg.complete({
target: target.target,
sessionId: record.activeSessionId
sessionId: record.activeSessionId,
});
}
export async function handleSwitchActivity(loopCtx: any, msg: any): Promise<void> {
const db = loopCtx.db;
const runtime = await db
.select({ switchTarget: handoffRuntime.activeSwitchTarget })
.from(handoffRuntime)
.where(eq(handoffRuntime.id, HANDOFF_ROW_ID))
.get();
const runtime = await db.select({ switchTarget: handoffRuntime.activeSwitchTarget }).from(handoffRuntime).where(eq(handoffRuntime.id, HANDOFF_ROW_ID)).get();
await msg.complete({ switchTarget: runtime?.switchTarget ?? "" });
}
@ -61,23 +54,14 @@ export async function handleSwitchActivity(loopCtx: any, msg: any): Promise<void
export async function handlePushActivity(loopCtx: any, msg: any): Promise<void> {
await pushActiveBranchActivity(loopCtx, {
reason: msg.body?.reason ?? null,
historyKind: "handoff.push"
historyKind: "handoff.push",
});
await msg.complete({ ok: true });
}
export async function handleSimpleCommandActivity(
loopCtx: any,
msg: any,
statusMessage: string,
historyKind: string
): Promise<void> {
export async function handleSimpleCommandActivity(loopCtx: any, msg: any, statusMessage: string, historyKind: string): Promise<void> {
const db = loopCtx.db;
await db
.update(handoffRuntime)
.set({ statusMessage, updatedAt: Date.now() })
.where(eq(handoffRuntime.id, HANDOFF_ROW_ID))
.run();
await db.update(handoffRuntime).set({ statusMessage, updatedAt: Date.now() }).where(eq(handoffRuntime.id, HANDOFF_ROW_ID)).run();
await appendHistory(loopCtx, historyKind, { reason: msg.body?.reason ?? null });
await msg.complete({ ok: true });
@ -103,8 +87,8 @@ export async function handleArchiveActivity(loopCtx: any, msg: any): Promise<voi
providerId: record.providerId,
sandboxId: record.activeSandboxId,
sessionId: record.activeSessionId,
intervalMs: 2_000
}
intervalMs: 2_000,
},
);
await withTimeout(sync.stop(), 15_000, "handoff status sync stop");
} catch (error) {
@ -114,7 +98,7 @@ export async function handleArchiveActivity(loopCtx: any, msg: any): Promise<voi
handoffId: loopCtx.state.handoffId,
sandboxId: record.activeSandboxId,
sessionId: record.activeSessionId,
error: resolveErrorMessage(error)
error: resolveErrorMessage(error),
});
}
}
@ -122,8 +106,7 @@ export async function handleArchiveActivity(loopCtx: any, msg: any): Promise<voi
if (record.activeSandboxId) {
await setHandoffState(loopCtx, "archive_release_sandbox", "releasing sandbox");
const { providers } = getActorRuntimeContext();
const activeSandbox =
record.sandboxes.find((sb: any) => sb.sandboxId === record.activeSandboxId) ?? null;
const activeSandbox = record.sandboxes.find((sb: any) => sb.sandboxId === record.activeSandboxId) ?? null;
const provider = providers.get(activeSandbox?.providerId ?? record.providerId);
const workspaceId = loopCtx.state.workspaceId;
const repoId = loopCtx.state.repoId;
@ -135,28 +118,24 @@ export async function handleArchiveActivity(loopCtx: any, msg: any): Promise<voi
void withTimeout(
provider.releaseSandbox({
workspaceId,
sandboxId
sandboxId,
}),
45_000,
"provider releaseSandbox"
"provider releaseSandbox",
).catch((error) => {
logActorWarning("handoff.commands", "failed to release sandbox during archive", {
workspaceId,
repoId,
handoffId,
sandboxId,
error: resolveErrorMessage(error)
error: resolveErrorMessage(error),
});
});
}
const db = loopCtx.db;
await setHandoffState(loopCtx, "archive_finalize", "finalizing archive");
await db
.update(handoffTable)
.set({ status: "archived", updatedAt: Date.now() })
.where(eq(handoffTable.id, HANDOFF_ROW_ID))
.run();
await db.update(handoffTable).set({ status: "archived", updatedAt: Date.now() }).where(eq(handoffTable.id, HANDOFF_ROW_ID)).run();
await db
.update(handoffRuntime)
@ -176,29 +155,20 @@ export async function killDestroySandboxActivity(loopCtx: any): Promise<void> {
}
const { providers } = getActorRuntimeContext();
const activeSandbox =
record.sandboxes.find((sb: any) => sb.sandboxId === record.activeSandboxId) ?? null;
const activeSandbox = record.sandboxes.find((sb: any) => sb.sandboxId === record.activeSandboxId) ?? null;
const provider = providers.get(activeSandbox?.providerId ?? record.providerId);
await provider.destroySandbox({
workspaceId: loopCtx.state.workspaceId,
sandboxId: record.activeSandboxId
sandboxId: record.activeSandboxId,
});
}
export async function killWriteDbActivity(loopCtx: any, msg: any): Promise<void> {
await setHandoffState(loopCtx, "kill_finalize", "finalizing kill");
const db = loopCtx.db;
await db
.update(handoffTable)
.set({ status: "killed", updatedAt: Date.now() })
.where(eq(handoffTable.id, HANDOFF_ROW_ID))
.run();
await db.update(handoffTable).set({ status: "killed", updatedAt: Date.now() }).where(eq(handoffTable.id, HANDOFF_ROW_ID)).run();
await db
.update(handoffRuntime)
.set({ statusMessage: "killed", updatedAt: Date.now() })
.where(eq(handoffRuntime.id, HANDOFF_ROW_ID))
.run();
await db.update(handoffRuntime).set({ statusMessage: "killed", updatedAt: Date.now() }).where(eq(handoffRuntime.id, HANDOFF_ROW_ID)).run();
await appendHistory(loopCtx, "handoff.kill", { reason: msg.body?.reason ?? null });
await msg.complete({ ok: true });

View file

@ -48,9 +48,7 @@ export function resolveErrorDetail(error: unknown): string {
return String(error);
}
const nonWorkflowWrapper = messages.find(
(msg) => !/^Step\s+"[^"]+"\s+failed\b/i.test(msg)
);
const nonWorkflowWrapper = messages.find((msg) => !/^Step\s+"[^"]+"\s+failed\b/i.test(msg));
return nonWorkflowWrapper ?? messages[0]!;
}
@ -58,18 +56,10 @@ export function buildAgentPrompt(task: string): string {
return task.trim();
}
export async function setHandoffState(
ctx: any,
status: HandoffStatus,
statusMessage?: string
): Promise<void> {
export async function setHandoffState(ctx: any, status: HandoffStatus, statusMessage?: string): Promise<void> {
const now = Date.now();
const db = ctx.db;
await db
.update(handoffTable)
.set({ status, updatedAt: now })
.where(eq(handoffTable.id, HANDOFF_ROW_ID))
.run();
await db.update(handoffTable).set({ status, updatedAt: now }).where(eq(handoffTable.id, HANDOFF_ROW_ID)).run();
if (statusMessage != null) {
await db
@ -81,14 +71,14 @@ export async function setHandoffState(
activeSwitchTarget: null,
activeCwd: null,
statusMessage,
updatedAt: now
updatedAt: now,
})
.onConflictDoUpdate({
target: handoffRuntime.id,
set: {
statusMessage,
updatedAt: now
}
updatedAt: now,
},
})
.run();
}
@ -112,7 +102,7 @@ export async function getCurrentRecord(ctx: any): Promise<HandoffRecord> {
agentType: handoffTable.agentType,
prSubmitted: handoffTable.prSubmitted,
createdAt: handoffTable.createdAt,
updatedAt: handoffTable.updatedAt
updatedAt: handoffTable.updatedAt,
})
.from(handoffTable)
.leftJoin(handoffRuntime, eq(handoffTable.id, handoffRuntime.id))
@ -176,15 +166,14 @@ export async function getCurrentRecord(ctx: any): Promise<HandoffRecord> {
export async function appendHistory(ctx: any, kind: string, payload: Record<string, unknown>): Promise<void> {
const client = ctx.client();
const history = await client.history.getOrCreate(
historyKey(ctx.state.workspaceId, ctx.state.repoId),
{ createWithInput: { workspaceId: ctx.state.workspaceId, repoId: ctx.state.repoId } }
);
const history = await client.history.getOrCreate(historyKey(ctx.state.workspaceId, ctx.state.repoId), {
createWithInput: { workspaceId: ctx.state.workspaceId, repoId: ctx.state.repoId },
});
await history.append({
kind,
handoffId: ctx.state.handoffId,
branchName: ctx.state.branchName,
payload
payload,
});
const workspace = await getOrCreateWorkspace(ctx, ctx.state.workspaceId);

View file

@ -10,10 +10,11 @@ import {
initCreateSessionActivity,
initEnsureAgentActivity,
initEnsureNameActivity,
initExposeSandboxActivity,
initFailedActivity,
initStartSandboxInstanceActivity,
initStartStatusSyncActivity,
initWriteDbActivity
initWriteDbActivity,
} from "./init.js";
import {
handleArchiveActivity,
@ -23,7 +24,7 @@ import {
handleSimpleCommandActivity,
handleSwitchActivity,
killDestroySandboxActivity,
killWriteDbActivity
killWriteDbActivity,
} from "./commands.js";
import { idleNotifyActivity, idleSubmitPrActivity, statusUpdateActivity } from "./status-sync.js";
import { HANDOFF_QUEUE_NAMES } from "./queue.js";
@ -57,16 +58,13 @@ const commandHandlers: Record<HandoffQueueName, WorkflowHandler> = {
await loopCtx.step("init-bootstrap-db", async () => initBootstrapDbActivity(loopCtx, body));
await loopCtx.removed("init-enqueue-provision", "step");
await loopCtx.removed("init-dispatch-provision-v2", "step");
const currentRecord = await loopCtx.step(
"init-read-current-record",
async () => getCurrentRecord(loopCtx)
);
const currentRecord = await loopCtx.step("init-read-current-record", async () => getCurrentRecord(loopCtx));
try {
await msg.complete(currentRecord);
} catch (error) {
logActorWarning("handoff.workflow", "initialize completion failed", {
error: resolveErrorMessage(error)
error: resolveErrorMessage(error),
});
}
},
@ -93,16 +91,17 @@ const commandHandlers: Record<HandoffQueueName, WorkflowHandler> = {
timeout: 60_000,
run: async () => initStartSandboxInstanceActivity(loopCtx, body, sandbox, agent),
});
await loopCtx.step(
"init-expose-sandbox",
async () => initExposeSandboxActivity(loopCtx, body, sandbox, sandboxInstanceReady),
);
const session = await loopCtx.step({
name: "init-create-session",
timeout: 180_000,
run: async () => initCreateSessionActivity(loopCtx, body, sandbox, sandboxInstanceReady),
});
await loopCtx.step(
"init-write-db",
async () => initWriteDbActivity(loopCtx, body, sandbox, session, sandboxInstanceReady)
);
await loopCtx.step("init-write-db", async () => initWriteDbActivity(loopCtx, body, sandbox, session, sandboxInstanceReady));
await loopCtx.step("init-start-status-sync", async () => initStartStatusSyncActivity(loopCtx, body, sandbox, session));
await loopCtx.step("init-complete", async () => initCompleteActivity(loopCtx, body, sandbox, session));
await msg.complete({ ok: true });
@ -125,17 +124,11 @@ const commandHandlers: Record<HandoffQueueName, WorkflowHandler> = {
},
"handoff.command.sync": async (loopCtx, msg) => {
await loopCtx.step(
"handle-sync",
async () => handleSimpleCommandActivity(loopCtx, msg, "sync requested", "handoff.sync")
);
await loopCtx.step("handle-sync", async () => handleSimpleCommandActivity(loopCtx, msg, "sync requested", "handoff.sync"));
},
"handoff.command.merge": async (loopCtx, msg) => {
await loopCtx.step(
"handle-merge",
async () => handleSimpleCommandActivity(loopCtx, msg, "merge requested", "handoff.merge")
);
await loopCtx.step("handle-merge", async () => handleSimpleCommandActivity(loopCtx, msg, "merge requested", "handoff.merge"));
},
"handoff.command.archive": async (loopCtx, msg) => {
@ -180,30 +173,22 @@ const commandHandlers: Record<HandoffQueueName, WorkflowHandler> = {
},
"handoff.command.workbench.rename_session": async (loopCtx, msg) => {
await loopCtx.step("workbench-rename-session", async () =>
renameWorkbenchSession(loopCtx, msg.body.sessionId, msg.body.title),
);
await loopCtx.step("workbench-rename-session", async () => renameWorkbenchSession(loopCtx, msg.body.sessionId, msg.body.title));
await msg.complete({ ok: true });
},
"handoff.command.workbench.set_session_unread": async (loopCtx, msg) => {
await loopCtx.step("workbench-set-session-unread", async () =>
setWorkbenchSessionUnread(loopCtx, msg.body.sessionId, msg.body.unread),
);
await loopCtx.step("workbench-set-session-unread", async () => setWorkbenchSessionUnread(loopCtx, msg.body.sessionId, msg.body.unread));
await msg.complete({ ok: true });
},
"handoff.command.workbench.update_draft": async (loopCtx, msg) => {
await loopCtx.step("workbench-update-draft", async () =>
updateWorkbenchDraft(loopCtx, msg.body.sessionId, msg.body.text, msg.body.attachments),
);
await loopCtx.step("workbench-update-draft", async () => updateWorkbenchDraft(loopCtx, msg.body.sessionId, msg.body.text, msg.body.attachments));
await msg.complete({ ok: true });
},
"handoff.command.workbench.change_model": async (loopCtx, msg) => {
await loopCtx.step("workbench-change-model", async () =>
changeWorkbenchModel(loopCtx, msg.body.sessionId, msg.body.model),
);
await loopCtx.step("workbench-change-model", async () => changeWorkbenchModel(loopCtx, msg.body.sessionId, msg.body.model));
await msg.complete({ ok: true });
},
@ -226,9 +211,7 @@ const commandHandlers: Record<HandoffQueueName, WorkflowHandler> = {
},
"handoff.command.workbench.sync_session_status": async (loopCtx, msg) => {
await loopCtx.step("workbench-sync-session-status", async () =>
syncWorkbenchSessionStatus(loopCtx, msg.body.sessionId, msg.body.status, msg.body.at),
);
await loopCtx.step("workbench-sync-session-status", async () => syncWorkbenchSessionStatus(loopCtx, msg.body.sessionId, msg.body.status, msg.body.at));
await msg.complete({ ok: true });
},
@ -269,14 +252,14 @@ const commandHandlers: Record<HandoffQueueName, WorkflowHandler> = {
}
await loopCtx.step("idle-notify", async () => idleNotifyActivity(loopCtx));
}
}
},
};
export async function runHandoffWorkflow(ctx: any): Promise<void> {
await ctx.loop("handoff-command-loop", async (loopCtx: any) => {
const msg = await loopCtx.queue.next("next-command", {
names: [...HANDOFF_QUEUE_NAMES],
completable: true
completable: true,
});
if (!msg) {
return Loop.continue(undefined);

View file

@ -8,18 +8,11 @@ import {
getOrCreateProject,
getOrCreateSandboxInstance,
getSandboxInstance,
selfHandoff
selfHandoff,
} from "../../handles.js";
import { logActorWarning, resolveErrorMessage } from "../../logging.js";
import { handoff as handoffTable, handoffRuntime, handoffSandboxes } from "../db/schema.js";
import {
HANDOFF_ROW_ID,
appendHistory,
buildAgentPrompt,
collectErrorMessages,
resolveErrorDetail,
setHandoffState
} from "./common.js";
import { HANDOFF_ROW_ID, appendHistory, buildAgentPrompt, collectErrorMessages, resolveErrorDetail, setHandoffState } from "./common.js";
import { handoffWorkflowQueueName } from "./queue.js";
const DEFAULT_INIT_CREATE_SANDBOX_ACTIVITY_TIMEOUT_MS = 180_000;
@ -43,15 +36,11 @@ function debugInit(loopCtx: any, message: string, context?: Record<string, unkno
workspaceId: loopCtx.state.workspaceId,
repoId: loopCtx.state.repoId,
handoffId: loopCtx.state.handoffId,
...(context ?? {})
...(context ?? {}),
});
}
async function withActivityTimeout<T>(
timeoutMs: number,
label: string,
run: () => Promise<T>
): Promise<T> {
async function withActivityTimeout<T>(timeoutMs: number, label: string, run: () => Promise<T>): Promise<T> {
let timer: ReturnType<typeof setTimeout> | null = null;
try {
return await Promise.race([
@ -60,7 +49,7 @@ async function withActivityTimeout<T>(
timer = setTimeout(() => {
reject(new Error(`${label} timed out after ${timeoutMs}ms`));
}, timeoutMs);
})
}),
]);
} finally {
if (timer) {
@ -88,7 +77,7 @@ export async function initBootstrapDbActivity(loopCtx: any, body: any): Promise<
status: "init_bootstrap_db",
agentType: loopCtx.state.agentType ?? config.default_agent,
createdAt: now,
updatedAt: now
updatedAt: now,
})
.onConflictDoUpdate({
target: handoffTable.id,
@ -99,8 +88,8 @@ export async function initBootstrapDbActivity(loopCtx: any, body: any): Promise<
providerId,
status: "init_bootstrap_db",
agentType: loopCtx.state.agentType ?? config.default_agent,
updatedAt: now
}
updatedAt: now,
},
})
.run();
@ -113,7 +102,7 @@ export async function initBootstrapDbActivity(loopCtx: any, body: any): Promise<
activeSwitchTarget: null,
activeCwd: null,
statusMessage: initialStatusMessage,
updatedAt: now
updatedAt: now,
})
.onConflictDoUpdate({
target: handoffRuntime.id,
@ -123,8 +112,8 @@ export async function initBootstrapDbActivity(loopCtx: any, body: any): Promise<
activeSwitchTarget: null,
activeCwd: null,
statusMessage: initialStatusMessage,
updatedAt: now
}
updatedAt: now,
},
})
.run();
} catch (error) {
@ -155,7 +144,7 @@ export async function initEnsureNameActivity(loopCtx: any): Promise<void> {
const existing = await loopCtx.db
.select({
branchName: handoffTable.branchName,
title: handoffTable.title
title: handoffTable.title,
})
.from(handoffTable)
.where(eq(handoffTable.id, HANDOFF_ROW_ID))
@ -175,19 +164,12 @@ export async function initEnsureNameActivity(loopCtx: any): Promise<void> {
workspaceId: loopCtx.state.workspaceId,
repoId: loopCtx.state.repoId,
handoffId: loopCtx.state.handoffId,
error: resolveErrorMessage(error)
error: resolveErrorMessage(error),
});
}
const remoteBranches = (await driver.git.listRemoteBranches(loopCtx.state.repoLocalPath)).map(
(branch: any) => branch.branchName
);
const remoteBranches = (await driver.git.listRemoteBranches(loopCtx.state.repoLocalPath)).map((branch: any) => branch.branchName);
const project = await getOrCreateProject(
loopCtx,
loopCtx.state.workspaceId,
loopCtx.state.repoId,
loopCtx.state.repoRemote
);
const project = await getOrCreateProject(loopCtx, loopCtx.state.workspaceId, loopCtx.state.repoId, loopCtx.state.repoRemote);
const reservedBranches = await project.listReservedBranches({});
const resolved = resolveCreateFlowDecision({
@ -195,7 +177,7 @@ export async function initEnsureNameActivity(loopCtx: any): Promise<void> {
explicitTitle: loopCtx.state.explicitTitle ?? undefined,
explicitBranchName: loopCtx.state.explicitBranchName ?? undefined,
localBranches: remoteBranches,
handoffBranches: reservedBranches
handoffBranches: reservedBranches,
});
const now = Date.now();
@ -204,7 +186,7 @@ export async function initEnsureNameActivity(loopCtx: any): Promise<void> {
.set({
branchName: resolved.branchName,
title: resolved.title,
updatedAt: now
updatedAt: now,
})
.where(eq(handoffTable.id, HANDOFF_ROW_ID))
.run();
@ -218,19 +200,19 @@ export async function initEnsureNameActivity(loopCtx: any): Promise<void> {
.update(handoffRuntime)
.set({
statusMessage: "provisioning",
updatedAt: now
updatedAt: now,
})
.where(eq(handoffRuntime.id, HANDOFF_ROW_ID))
.run();
await project.registerHandoffBranch({
handoffId: loopCtx.state.handoffId,
branchName: resolved.branchName
branchName: resolved.branchName,
});
await appendHistory(loopCtx, "handoff.named", {
title: resolved.title,
branchName: resolved.branchName
branchName: resolved.branchName,
});
}
@ -252,7 +234,7 @@ export async function initCreateSandboxActivity(loopCtx: any, body: any): Promis
debugInit(loopCtx, "init_create_sandbox started", {
providerId,
timeoutMs,
supportsSessionReuse: provider.capabilities().supportsSessionReuse
supportsSessionReuse: provider.capabilities().supportsSessionReuse,
});
if (provider.capabilities().supportsSessionReuse) {
@ -274,18 +256,16 @@ export async function initCreateSandboxActivity(loopCtx: any, body: any): Promis
if (sandboxId) {
debugInit(loopCtx, "init_create_sandbox attempting resume", { sandboxId });
try {
const resumed = await withActivityTimeout(
timeoutMs,
"resumeSandbox",
async () => provider.resumeSandbox({
const resumed = await withActivityTimeout(timeoutMs, "resumeSandbox", async () =>
provider.resumeSandbox({
workspaceId: loopCtx.state.workspaceId,
sandboxId
})
sandboxId,
}),
);
debugInit(loopCtx, "init_create_sandbox resume succeeded", {
sandboxId: resumed.sandboxId,
durationMs: Date.now() - startedAt
durationMs: Date.now() - startedAt,
});
return resumed;
} catch (error) {
@ -294,39 +274,37 @@ export async function initCreateSandboxActivity(loopCtx: any, body: any): Promis
repoId: loopCtx.state.repoId,
handoffId: loopCtx.state.handoffId,
sandboxId,
error: resolveErrorMessage(error)
error: resolveErrorMessage(error),
});
}
}
}
debugInit(loopCtx, "init_create_sandbox creating fresh sandbox", {
branchName: loopCtx.state.branchName
branchName: loopCtx.state.branchName,
});
try {
const sandbox = await withActivityTimeout(
timeoutMs,
"createSandbox",
async () => provider.createSandbox({
const sandbox = await withActivityTimeout(timeoutMs, "createSandbox", async () =>
provider.createSandbox({
workspaceId: loopCtx.state.workspaceId,
repoId: loopCtx.state.repoId,
repoRemote: loopCtx.state.repoRemote,
branchName: loopCtx.state.branchName,
handoffId: loopCtx.state.handoffId,
debug: (message, context) => debugInit(loopCtx, message, context)
})
debug: (message, context) => debugInit(loopCtx, message, context),
}),
);
debugInit(loopCtx, "init_create_sandbox create succeeded", {
sandboxId: sandbox.sandboxId,
durationMs: Date.now() - startedAt
durationMs: Date.now() - startedAt,
});
return sandbox;
} catch (error) {
debugInit(loopCtx, "init_create_sandbox failed", {
durationMs: Date.now() - startedAt,
error: resolveErrorMessage(error)
error: resolveErrorMessage(error),
});
throw error;
}
@ -339,67 +317,49 @@ export async function initEnsureAgentActivity(loopCtx: any, body: any, sandbox:
const provider = providers.get(providerId);
return await provider.ensureSandboxAgent({
workspaceId: loopCtx.state.workspaceId,
sandboxId: sandbox.sandboxId
sandboxId: sandbox.sandboxId,
});
}
export async function initStartSandboxInstanceActivity(
loopCtx: any,
body: any,
sandbox: any,
agent: any
): Promise<any> {
export async function initStartSandboxInstanceActivity(loopCtx: any, body: any, sandbox: any, agent: any): Promise<any> {
await setHandoffState(loopCtx, "init_start_sandbox_instance", "starting sandbox runtime");
try {
const providerId = body?.providerId ?? loopCtx.state.providerId;
const sandboxInstance = await getOrCreateSandboxInstance(
loopCtx,
loopCtx.state.workspaceId,
const sandboxInstance = await getOrCreateSandboxInstance(loopCtx, loopCtx.state.workspaceId, providerId, sandbox.sandboxId, {
workspaceId: loopCtx.state.workspaceId,
providerId,
sandbox.sandboxId,
{
workspaceId: loopCtx.state.workspaceId,
providerId,
sandboxId: sandbox.sandboxId
}
);
sandboxId: sandbox.sandboxId,
});
await sandboxInstance.ensure({
metadata: sandbox.metadata,
status: "ready",
agentEndpoint: agent.endpoint,
agentToken: agent.token
agentToken: agent.token,
});
const actorId = typeof (sandboxInstance as any).resolve === "function"
? await (sandboxInstance as any).resolve()
: null;
const actorId = typeof (sandboxInstance as any).resolve === "function" ? await (sandboxInstance as any).resolve() : null;
return {
ok: true as const,
actorId: typeof actorId === "string" ? actorId : null
actorId: typeof actorId === "string" ? actorId : null,
};
} catch (error) {
const detail = error instanceof Error ? error.message : String(error);
return {
ok: false as const,
error: `sandbox-instance ensure failed: ${detail}`
error: `sandbox-instance ensure failed: ${detail}`,
};
}
}
export async function initCreateSessionActivity(
loopCtx: any,
body: any,
sandbox: any,
sandboxInstanceReady: any
): Promise<any> {
export async function initCreateSessionActivity(loopCtx: any, body: any, sandbox: any, sandboxInstanceReady: any): Promise<any> {
await setHandoffState(loopCtx, "init_create_session", "creating agent session");
if (!sandboxInstanceReady.ok) {
return {
id: null,
status: "error",
error: sandboxInstanceReady.error ?? "sandbox instance is not ready"
error: sandboxInstanceReady.error ?? "sandbox instance is not ready",
} as const;
}
@ -407,10 +367,7 @@ export async function initCreateSessionActivity(
const providerId = body?.providerId ?? loopCtx.state.providerId;
const sandboxInstance = getSandboxInstance(loopCtx, loopCtx.state.workspaceId, providerId, sandbox.sandboxId);
const cwd =
sandbox.metadata && typeof (sandbox.metadata as any).cwd === "string"
? ((sandbox.metadata as any).cwd as string)
: undefined;
const cwd = sandbox.metadata && typeof (sandbox.metadata as any).cwd === "string" ? ((sandbox.metadata as any).cwd as string) : undefined;
return await sandboxInstance.createSession({
prompt:
@ -418,32 +375,19 @@ export async function initCreateSessionActivity(
? loopCtx.state.initialPrompt
: buildAgentPrompt(loopCtx.state.task),
cwd,
agent: (loopCtx.state.agentType ?? config.default_agent) as any
agent: (loopCtx.state.agentType ?? config.default_agent) as any,
});
}
export async function initWriteDbActivity(
export async function initExposeSandboxActivity(
loopCtx: any,
body: any,
sandbox: any,
session: any,
sandboxInstanceReady?: { actorId?: string | null }
): Promise<void> {
await setHandoffState(loopCtx, "init_write_db", "persisting handoff runtime");
const providerId = body?.providerId ?? loopCtx.state.providerId;
const { config } = getActorRuntimeContext();
const now = Date.now();
const db = loopCtx.db;
const sessionId = session?.id ?? null;
const sessionHealthy = Boolean(sessionId) && session?.status !== "error";
const activeSessionId = sessionHealthy ? sessionId : null;
const statusMessage =
sessionHealthy
? "session created"
: session?.status === "error"
? (session.error ?? "session create failed")
: "session unavailable";
const activeCwd =
sandbox.metadata && typeof (sandbox.metadata as any).cwd === "string"
? ((sandbox.metadata as any).cwd as string)
@ -453,13 +397,71 @@ export async function initWriteDbActivity(
? sandboxInstanceReady.actorId
: null;
await db
.insert(handoffSandboxes)
.values({
sandboxId: sandbox.sandboxId,
providerId,
sandboxActorId,
switchTarget: sandbox.switchTarget,
cwd: activeCwd,
statusMessage: "sandbox ready",
createdAt: now,
updatedAt: now
})
.onConflictDoUpdate({
target: handoffSandboxes.sandboxId,
set: {
providerId,
sandboxActorId,
switchTarget: sandbox.switchTarget,
cwd: activeCwd,
statusMessage: "sandbox ready",
updatedAt: now
}
})
.run();
await db
.update(handoffRuntime)
.set({
activeSandboxId: sandbox.sandboxId,
activeSwitchTarget: sandbox.switchTarget,
activeCwd,
statusMessage: "sandbox ready",
updatedAt: now
})
.where(eq(handoffRuntime.id, HANDOFF_ROW_ID))
.run();
}
export async function initWriteDbActivity(
loopCtx: any,
body: any,
sandbox: any,
session: any,
sandboxInstanceReady?: { actorId?: string | null },
): Promise<void> {
await setHandoffState(loopCtx, "init_write_db", "persisting handoff runtime");
const providerId = body?.providerId ?? loopCtx.state.providerId;
const { config } = getActorRuntimeContext();
const now = Date.now();
const db = loopCtx.db;
const sessionId = session?.id ?? null;
const sessionHealthy = Boolean(sessionId) && session?.status !== "error";
const activeSessionId = sessionHealthy ? sessionId : null;
const statusMessage = sessionHealthy ? "session created" : session?.status === "error" ? (session.error ?? "session create failed") : "session unavailable";
const activeCwd = sandbox.metadata && typeof (sandbox.metadata as any).cwd === "string" ? ((sandbox.metadata as any).cwd as string) : null;
const sandboxActorId = typeof sandboxInstanceReady?.actorId === "string" && sandboxInstanceReady.actorId.length > 0 ? sandboxInstanceReady.actorId : null;
await db
.update(handoffTable)
.set({
providerId,
status: sessionHealthy ? "running" : "error",
agentType: loopCtx.state.agentType ?? config.default_agent,
updatedAt: now
updatedAt: now,
})
.where(eq(handoffTable.id, HANDOFF_ROW_ID))
.run();
@ -474,7 +476,7 @@ export async function initWriteDbActivity(
cwd: activeCwd,
statusMessage,
createdAt: now,
updatedAt: now
updatedAt: now,
})
.onConflictDoUpdate({
target: handoffSandboxes.sandboxId,
@ -484,8 +486,8 @@ export async function initWriteDbActivity(
switchTarget: sandbox.switchTarget,
cwd: activeCwd,
statusMessage,
updatedAt: now
}
updatedAt: now,
},
})
.run();
@ -498,7 +500,7 @@ export async function initWriteDbActivity(
activeSwitchTarget: sandbox.switchTarget,
activeCwd,
statusMessage,
updatedAt: now
updatedAt: now,
})
.onConflictDoUpdate({
target: handoffRuntime.id,
@ -508,18 +510,13 @@ export async function initWriteDbActivity(
activeSwitchTarget: sandbox.switchTarget,
activeCwd,
statusMessage,
updatedAt: now
}
updatedAt: now,
},
})
.run();
}
export async function initStartStatusSyncActivity(
loopCtx: any,
body: any,
sandbox: any,
session: any
): Promise<void> {
export async function initStartStatusSyncActivity(loopCtx: any, body: any, sandbox: any, session: any): Promise<void> {
const sessionId = session?.id ?? null;
if (!sessionId || session?.status === "error") {
return;
@ -541,8 +538,8 @@ export async function initStartStatusSyncActivity(
providerId,
sandboxId: sandbox.sandboxId,
sessionId,
intervalMs: 2_000
}
intervalMs: 2_000,
},
);
await sync.start();
@ -561,21 +558,18 @@ export async function initCompleteActivity(loopCtx: any, body: any, sandbox: any
kind: "handoff.initialized",
handoffId: loopCtx.state.handoffId,
branchName: loopCtx.state.branchName,
payload: { providerId, sandboxId: sandbox.sandboxId, sessionId }
payload: { providerId, sandboxId: sandbox.sandboxId, sessionId },
});
loopCtx.state.initialized = true;
return;
}
const detail =
session?.status === "error"
? (session.error ?? "session create failed")
: "session unavailable";
const detail = session?.status === "error" ? (session.error ?? "session create failed") : "session unavailable";
await setHandoffState(loopCtx, "error", detail);
await appendHistory(loopCtx, "handoff.error", {
detail,
messages: [detail]
messages: [detail],
});
loopCtx.state.initialized = false;
}
@ -599,7 +593,7 @@ export async function initFailedActivity(loopCtx: any, error: unknown): Promise<
status: "error",
agentType: loopCtx.state.agentType ?? config.default_agent,
createdAt: now,
updatedAt: now
updatedAt: now,
})
.onConflictDoUpdate({
target: handoffTable.id,
@ -610,8 +604,8 @@ export async function initFailedActivity(loopCtx: any, error: unknown): Promise<
providerId,
status: "error",
agentType: loopCtx.state.agentType ?? config.default_agent,
updatedAt: now
}
updatedAt: now,
},
})
.run();
@ -624,7 +618,7 @@ export async function initFailedActivity(loopCtx: any, error: unknown): Promise<
activeSwitchTarget: null,
activeCwd: null,
statusMessage: detail,
updatedAt: now
updatedAt: now,
})
.onConflictDoUpdate({
target: handoffRuntime.id,
@ -634,13 +628,13 @@ export async function initFailedActivity(loopCtx: any, error: unknown): Promise<
activeSwitchTarget: null,
activeCwd: null,
statusMessage: detail,
updatedAt: now
}
updatedAt: now,
},
})
.run();
await appendHistory(loopCtx, "handoff.error", {
detail,
messages
messages,
});
}

View file

@ -9,10 +9,7 @@ export interface PushActiveBranchOptions {
historyKind?: string;
}
export async function pushActiveBranchActivity(
loopCtx: any,
options: PushActiveBranchOptions = {}
): Promise<void> {
export async function pushActiveBranchActivity(loopCtx: any, options: PushActiveBranchOptions = {}): Promise<void> {
const record = await getCurrentRecord(loopCtx);
const activeSandboxId = record.activeSandboxId;
const branchName = loopCtx.state.branchName ?? record.branchName;
@ -24,8 +21,7 @@ export async function pushActiveBranchActivity(
throw new Error("cannot push: handoff branch is not set");
}
const activeSandbox =
record.sandboxes.find((sandbox: any) => sandbox.sandboxId === activeSandboxId) ?? null;
const activeSandbox = record.sandboxes.find((sandbox: any) => sandbox.sandboxId === activeSandboxId) ?? null;
const providerId = activeSandbox?.providerId ?? record.providerId;
const cwd = activeSandbox?.cwd ?? null;
if (!cwd) {
@ -53,14 +49,14 @@ export async function pushActiveBranchActivity(
`cd ${JSON.stringify(cwd)}`,
"git rev-parse --verify HEAD >/dev/null",
"git config credential.helper '!f() { echo username=x-access-token; echo password=${GH_TOKEN:-$GITHUB_TOKEN}; }; f'",
`git push -u origin ${JSON.stringify(branchName)}`
`git push -u origin ${JSON.stringify(branchName)}`,
].join("; ");
const result = await provider.executeCommand({
workspaceId: loopCtx.state.workspaceId,
sandboxId: activeSandboxId,
command: ["bash", "-lc", JSON.stringify(script)].join(" "),
label: `git push ${branchName}`
label: `git push ${branchName}`,
});
if (result.exitCode !== 0) {
@ -83,6 +79,6 @@ export async function pushActiveBranchActivity(
await appendHistory(loopCtx, options.historyKind ?? "handoff.push", {
reason: options.reason ?? null,
branchName,
sandboxId: activeSandboxId
sandboxId: activeSandboxId,
});
}

View file

@ -23,7 +23,7 @@ export const HANDOFF_QUEUE_NAMES = [
"handoff.command.workbench.close_session",
"handoff.command.workbench.publish_pr",
"handoff.command.workbench.revert_file",
"handoff.status_sync.result"
"handoff.status_sync.result",
] as const;
export function handoffWorkflowQueueName(name: string): string {

View file

@ -26,21 +26,16 @@ export async function statusUpdateActivity(loopCtx: any, body: any): Promise<boo
const runtime = await db
.select({
activeSandboxId: handoffRuntime.activeSandboxId,
activeSessionId: handoffRuntime.activeSessionId
activeSessionId: handoffRuntime.activeSessionId,
})
.from(handoffRuntime)
.where(eq(handoffRuntime.id, HANDOFF_ROW_ID))
.get();
const isActive =
runtime?.activeSandboxId === body.sandboxId && runtime?.activeSessionId === body.sessionId;
const isActive = runtime?.activeSandboxId === body.sandboxId && runtime?.activeSessionId === body.sessionId;
if (isActive) {
await db
.update(handoffTable)
.set({ status: newStatus, updatedAt: body.at })
.where(eq(handoffTable.id, HANDOFF_ROW_ID))
.run();
await db.update(handoffTable).set({ status: newStatus, updatedAt: body.at }).where(eq(handoffTable.id, HANDOFF_ROW_ID)).run();
await db
.update(handoffRuntime)
@ -58,7 +53,7 @@ export async function statusUpdateActivity(loopCtx: any, body: any): Promise<boo
await appendHistory(loopCtx, "handoff.status", {
status: body.status,
sessionId: body.sessionId,
sandboxId: body.sandboxId
sandboxId: body.sandboxId,
});
if (isActive) {
@ -78,11 +73,7 @@ export async function idleSubmitPrActivity(loopCtx: any): Promise<void> {
const { driver } = getActorRuntimeContext();
const db = loopCtx.db;
const self = await db
.select({ prSubmitted: handoffTable.prSubmitted })
.from(handoffTable)
.where(eq(handoffTable.id, HANDOFF_ROW_ID))
.get();
const self = await db.select({ prSubmitted: handoffTable.prSubmitted }).from(handoffTable).where(eq(handoffTable.id, HANDOFF_ROW_ID)).get();
if (self && self.prSubmitted) return;
@ -93,7 +84,7 @@ export async function idleSubmitPrActivity(loopCtx: any): Promise<void> {
workspaceId: loopCtx.state.workspaceId,
repoId: loopCtx.state.repoId,
handoffId: loopCtx.state.handoffId,
error: resolveErrorMessage(error)
error: resolveErrorMessage(error),
});
}
@ -104,34 +95,26 @@ export async function idleSubmitPrActivity(loopCtx: any): Promise<void> {
try {
await pushActiveBranchActivity(loopCtx, {
reason: "auto_submit_idle",
historyKind: "handoff.push.auto"
historyKind: "handoff.push.auto",
});
const pr = await driver.github.createPr(
loopCtx.state.repoLocalPath,
loopCtx.state.branchName,
loopCtx.state.title
);
const pr = await driver.github.createPr(loopCtx.state.repoLocalPath, loopCtx.state.branchName, loopCtx.state.title);
await db
.update(handoffTable)
.set({ prSubmitted: 1, updatedAt: Date.now() })
.where(eq(handoffTable.id, HANDOFF_ROW_ID))
.run();
await db.update(handoffTable).set({ prSubmitted: 1, updatedAt: Date.now() }).where(eq(handoffTable.id, HANDOFF_ROW_ID)).run();
await appendHistory(loopCtx, "handoff.step", {
step: "pr_submit",
handoffId: loopCtx.state.handoffId,
branchName: loopCtx.state.branchName,
prUrl: pr.url,
prNumber: pr.number
prNumber: pr.number,
});
await appendHistory(loopCtx, "handoff.pr_created", {
handoffId: loopCtx.state.handoffId,
branchName: loopCtx.state.branchName,
prUrl: pr.url,
prNumber: pr.number
prNumber: pr.number,
});
} catch (error) {
const detail = resolveErrorDetail(error);
@ -139,7 +122,7 @@ export async function idleSubmitPrActivity(loopCtx: any): Promise<void> {
.update(handoffRuntime)
.set({
statusMessage: `pr submit failed: ${detail}`,
updatedAt: Date.now()
updatedAt: Date.now(),
})
.where(eq(handoffRuntime.id, HANDOFF_ROW_ID))
.run();
@ -147,7 +130,7 @@ export async function idleSubmitPrActivity(loopCtx: any): Promise<void> {
await appendHistory(loopCtx, "handoff.pr_create_failed", {
handoffId: loopCtx.state.handoffId,
branchName: loopCtx.state.branchName,
error: detail
error: detail,
});
}
}

View file

@ -4,4 +4,3 @@ export default defineConfig({
out: "./src/actors/history/db/drizzle",
schema: "./src/actors/history/db/schema.ts",
});

View file

@ -67,4 +67,4 @@
"internal": {
"indexes": {}
}
}
}

View file

@ -10,4 +10,4 @@
"breakpoints": true
}
]
}
}

View file

@ -3,14 +3,14 @@
// Do not hand-edit this file.
const journal = {
"entries": [
entries: [
{
"idx": 0,
"when": 1770924375133,
"tag": "0000_watery_bushwacker",
"breakpoints": true
}
]
idx: 0,
when: 1770924375133,
tag: "0000_watery_bushwacker",
breakpoints: true,
},
],
} as const;
export default {
@ -25,5 +25,5 @@ export default {
\`created_at\` integer NOT NULL
);
`,
} as const
} as const,
};

View file

@ -36,7 +36,7 @@ async function appendHistoryRow(loopCtx: any, body: AppendHistoryCommand): Promi
branchName: body.branchName ?? null,
kind: body.kind,
payloadJson: JSON.stringify(body.payload),
createdAt: now
createdAt: now,
})
.run();
}
@ -45,7 +45,7 @@ async function runHistoryWorkflow(ctx: any): Promise<void> {
await ctx.loop("history-command-loop", async (loopCtx: any) => {
const msg = await loopCtx.queue.next("next-history-command", {
names: [...HISTORY_QUEUE_NAMES],
completable: true
completable: true,
});
if (!msg) {
return Loop.continue(undefined);
@ -63,11 +63,11 @@ async function runHistoryWorkflow(ctx: any): Promise<void> {
export const history = actor({
db: historyDb,
queues: {
"history.command.append": queue()
"history.command.append": queue(),
},
createState: (_c, input: HistoryInput) => ({
workspaceId: input.workspaceId,
repoId: input.repoId
repoId: input.repoId,
}),
actions: {
async append(c, command: AppendHistoryCommand): Promise<void> {
@ -91,7 +91,7 @@ export const history = actor({
branchName: events.branchName,
kind: events.kind,
payloadJson: events.payloadJson,
createdAt: events.createdAt
createdAt: events.createdAt,
})
.from(events);
@ -103,9 +103,9 @@ export const history = actor({
return rows.map((row) => ({
...row,
workspaceId: c.state.workspaceId,
repoId: c.state.repoId
repoId: c.state.repoId,
}));
}
},
},
run: workflow(runHistoryWorkflow)
run: workflow(runHistoryWorkflow),
});

View file

@ -35,10 +35,10 @@ export const registry = setup({
history,
projectPrSync,
projectBranchSync,
handoffStatusSync
handoffStatusSync,
},
managerPort: resolveManagerPort(),
managerHost: resolveManagerHost()
managerHost: resolveManagerHost(),
});
export * from "./context.js";

View file

@ -12,11 +12,7 @@ export function handoffKey(workspaceId: string, repoId: string, handoffId: strin
return ["ws", workspaceId, "project", repoId, "handoff", handoffId];
}
export function sandboxInstanceKey(
workspaceId: string,
providerId: string,
sandboxId: string
): ActorKey {
export function sandboxInstanceKey(workspaceId: string, providerId: string, sandboxId: string): ActorKey {
return ["ws", workspaceId, "provider", providerId, "sandbox", sandboxId];
}
@ -32,13 +28,7 @@ export function projectBranchSyncKey(workspaceId: string, repoId: string): Actor
return ["ws", workspaceId, "project", repoId, "branch-sync"];
}
export function handoffStatusSyncKey(
workspaceId: string,
repoId: string,
handoffId: string,
sandboxId: string,
sessionId: string
): ActorKey {
export function handoffStatusSyncKey(workspaceId: string, repoId: string, handoffId: string, sandboxId: string, sessionId: string): ActorKey {
// Include sandbox + session so multiple sandboxes/sessions can be tracked per handoff.
return ["ws", workspaceId, "project", repoId, "handoff", handoffId, "status-sync", sandboxId, sessionId];
}

View file

@ -16,15 +16,11 @@ export function resolveErrorStack(error: unknown): string | undefined {
return undefined;
}
export function logActorWarning(
scope: string,
message: string,
context?: Record<string, unknown>
): void {
export function logActorWarning(scope: string, message: string, context?: Record<string, unknown>): void {
const payload = {
scope,
message,
...(context ?? {})
...(context ?? {}),
};
// eslint-disable-next-line no-console
console.warn("[openhandoff][actor:warn]", payload);

View file

@ -23,12 +23,7 @@ interface PollingActorContext<TState extends PollingControlState> {
state: TState;
abortSignal: AbortSignal;
queue: {
nextBatch(options: {
names: readonly string[];
timeout: number;
count: number;
completable: true;
}): Promise<PollingQueueMessage[]>;
nextBatch(options: { names: readonly string[]; timeout: number; count: number; completable: true }): Promise<PollingQueueMessage[]>;
};
}
@ -39,21 +34,16 @@ interface RunPollingOptions<TState extends PollingControlState> {
export async function runPollingControlLoop<TState extends PollingControlState>(
c: PollingActorContext<TState>,
options: RunPollingOptions<TState>
options: RunPollingOptions<TState>,
): Promise<void> {
while (!c.abortSignal.aborted) {
const messages = normalizeMessages(
await c.queue.nextBatch({
names: [
options.control.start,
options.control.stop,
options.control.setInterval,
options.control.force
],
names: [options.control.start, options.control.stop, options.control.setInterval, options.control.force],
timeout: Math.max(500, c.state.intervalMs),
count: 16,
completable: true
})
completable: true,
}),
) as PollingQueueMessage[];
if (messages.length === 0) {
@ -94,12 +84,7 @@ export async function runPollingControlLoop<TState extends PollingControlState>(
interface WorkflowPollingActorContext<TState extends PollingControlState> {
state: TState;
loop(config: {
name: string;
historyEvery: number;
historyKeep: number;
run(ctx: WorkflowPollingActorContext<TState>): Promise<unknown>;
}): Promise<void>;
loop(config: { name: string; historyEvery: number; historyKeep: number; run(ctx: WorkflowPollingActorContext<TState>): Promise<unknown> }): Promise<void>;
}
interface WorkflowPollingQueueMessage extends PollingQueueMessage {}
@ -107,12 +92,15 @@ interface WorkflowPollingQueueMessage extends PollingQueueMessage {}
interface WorkflowPollingLoopContext<TState extends PollingControlState> {
state: TState;
queue: {
nextBatch(name: string, options: {
names: readonly string[];
timeout: number;
count: number;
completable: true;
}): Promise<WorkflowPollingQueueMessage[]>;
nextBatch(
name: string,
options: {
names: readonly string[];
timeout: number;
count: number;
completable: true;
},
): Promise<WorkflowPollingQueueMessage[]>;
};
step<T>(
nameOrConfig:
@ -138,12 +126,7 @@ export async function runWorkflowPollingLoop<TState extends PollingControlState>
const messages = normalizeMessages(
await loopCtx.queue.nextBatch("next-polling-control-batch", {
names: [
options.control.start,
options.control.stop,
options.control.setInterval,
options.control.force,
],
names: [options.control.start, options.control.stop, options.control.setInterval, options.control.force],
timeout: control.running ? control.intervalMs : 60_000,
count: 16,
completable: true,
@ -172,37 +155,35 @@ export async function runWorkflowPollingLoop<TState extends PollingControlState>
continue;
}
if (msg.name === options.control.stop) {
await loopCtx.step("control-stop", async () => {
loopCtx.state.running = false;
});
await msg.complete({ ok: true });
continue;
}
if (msg.name === options.control.setInterval) {
await loopCtx.step("control-set-interval", async () => {
const intervalMs = Number((msg.body as { intervalMs?: unknown })?.intervalMs);
loopCtx.state.intervalMs = Number.isFinite(intervalMs)
? Math.max(500, intervalMs)
: loopCtx.state.intervalMs;
});
await msg.complete({ ok: true });
continue;
}
if (msg.name === options.control.force) {
await loopCtx.step({
name: "control-force",
timeout: 5 * 60_000,
run: async () => {
await options.onPoll(loopCtx as unknown as PollingActorContext<TState>);
},
});
await msg.complete({ ok: true });
}
if (msg.name === options.control.stop) {
await loopCtx.step("control-stop", async () => {
loopCtx.state.running = false;
});
await msg.complete({ ok: true });
continue;
}
if (msg.name === options.control.setInterval) {
await loopCtx.step("control-set-interval", async () => {
const intervalMs = Number((msg.body as { intervalMs?: unknown })?.intervalMs);
loopCtx.state.intervalMs = Number.isFinite(intervalMs) ? Math.max(500, intervalMs) : loopCtx.state.intervalMs;
});
await msg.complete({ ok: true });
continue;
}
if (msg.name === options.control.force) {
await loopCtx.step({
name: "control-force",
timeout: 5 * 60_000,
run: async () => {
await options.onPoll(loopCtx as unknown as PollingActorContext<TState>);
},
});
await msg.complete({ ok: true });
}
}
return Loop.continue(undefined);
});
}

View file

@ -39,15 +39,10 @@ const CONTROL = {
start: "project.branch_sync.control.start",
stop: "project.branch_sync.control.stop",
setInterval: "project.branch_sync.control.set_interval",
force: "project.branch_sync.control.force"
force: "project.branch_sync.control.force",
} as const;
async function enrichBranches(
workspaceId: string,
repoId: string,
repoPath: string,
git: GitDriver
): Promise<EnrichedBranchSnapshot[]> {
async function enrichBranches(workspaceId: string, repoId: string, repoPath: string, git: GitDriver): Promise<EnrichedBranchSnapshot[]> {
return await withRepoGitLock(repoPath, async () => {
await git.fetch(repoPath);
const branches = await git.listRemoteBranches(repoPath);
@ -71,7 +66,7 @@ async function enrichBranches(
workspaceId,
repoId,
branchName: branch.branchName,
error: resolveErrorMessage(error)
error: resolveErrorMessage(error),
});
branchDiffStat = null;
}
@ -84,7 +79,7 @@ async function enrichBranches(
workspaceId,
repoId,
branchName: branch.branchName,
error: resolveErrorMessage(error)
error: resolveErrorMessage(error),
});
branchHasUnpushed = false;
}
@ -96,7 +91,7 @@ async function enrichBranches(
workspaceId,
repoId,
branchName: branch.branchName,
error: resolveErrorMessage(error)
error: resolveErrorMessage(error),
});
branchConflicts = false;
}
@ -108,7 +103,7 @@ async function enrichBranches(
trackedInStack: parentByBranch.has(branch.branchName),
diffStat: branchDiffStat,
hasUnpushed: branchHasUnpushed,
conflictsWithMain: branchConflicts
conflictsWithMain: branchConflicts,
});
}
@ -132,14 +127,14 @@ export const projectBranchSync = actor({
},
options: {
// Polling actors rely on timer-based wakeups; sleeping would pause the timer and stop polling.
noSleep: true
noSleep: true,
},
createState: (_c, input: ProjectBranchSyncInput): ProjectBranchSyncState => ({
workspaceId: input.workspaceId,
repoId: input.repoId,
repoPath: input.repoPath,
intervalMs: input.intervalMs,
running: true
running: true,
}),
actions: {
async start(c): Promise<void> {
@ -160,7 +155,7 @@ export const projectBranchSync = actor({
async force(c): Promise<void> {
const self = selfProjectBranchSync(c);
await self.send(CONTROL.force, {}, { wait: true, timeout: 5 * 60_000 });
}
},
},
run: workflow(async (ctx) => {
await runWorkflowPollingLoop<ProjectBranchSyncState>(ctx, {
@ -172,10 +167,10 @@ export const projectBranchSync = actor({
} catch (error) {
logActorWarning("project-branch-sync", "poll failed", {
error: resolveErrorMessage(error),
stack: resolveErrorStack(error)
stack: resolveErrorStack(error),
});
}
}
},
});
})
}),
});

View file

@ -26,7 +26,7 @@ const CONTROL = {
start: "project.pr_sync.control.start",
stop: "project.pr_sync.control.stop",
setInterval: "project.pr_sync.control.set_interval",
force: "project.pr_sync.control.force"
force: "project.pr_sync.control.force",
} as const;
async function pollPrs(c: { state: ProjectPrSyncState }): Promise<void> {
@ -45,14 +45,14 @@ export const projectPrSync = actor({
},
options: {
// Polling actors rely on timer-based wakeups; sleeping would pause the timer and stop polling.
noSleep: true
noSleep: true,
},
createState: (_c, input: ProjectPrSyncInput): ProjectPrSyncState => ({
workspaceId: input.workspaceId,
repoId: input.repoId,
repoPath: input.repoPath,
intervalMs: input.intervalMs,
running: true
running: true,
}),
actions: {
async start(c): Promise<void> {
@ -73,7 +73,7 @@ export const projectPrSync = actor({
async force(c): Promise<void> {
const self = selfProjectPrSync(c);
await self.send(CONTROL.force, {}, { wait: true, timeout: 5 * 60_000 });
}
},
},
run: workflow(async (ctx) => {
await runWorkflowPollingLoop<ProjectPrSyncState>(ctx, {
@ -85,10 +85,10 @@ export const projectPrSync = actor({
} catch (error) {
logActorWarning("project-pr-sync", "poll failed", {
error: resolveErrorMessage(error),
stack: resolveErrorStack(error)
stack: resolveErrorStack(error),
});
}
}
},
});
})
}),
});

View file

@ -2,24 +2,9 @@
import { randomUUID } from "node:crypto";
import { and, desc, eq, isNotNull, ne } from "drizzle-orm";
import { Loop } from "rivetkit/workflow";
import type {
AgentType,
HandoffRecord,
HandoffSummary,
ProviderId,
RepoOverview,
RepoStackAction,
RepoStackActionResult
} from "@openhandoff/shared";
import type { AgentType, HandoffRecord, HandoffSummary, ProviderId, RepoOverview, RepoStackAction, RepoStackActionResult } from "@openhandoff/shared";
import { getActorRuntimeContext } from "../context.js";
import {
getHandoff,
getOrCreateHandoff,
getOrCreateHistory,
getOrCreateProjectBranchSync,
getOrCreateProjectPrSync,
selfProject
} from "../handles.js";
import { getHandoff, getOrCreateHandoff, getOrCreateHistory, getOrCreateProjectBranchSync, getOrCreateProjectPrSync, selfProject } from "../handles.js";
import { isActorNotFoundError, logActorWarning, resolveErrorMessage } from "../logging.js";
import { openhandoffRepoClonePath } from "../../services/openhandoff-paths.js";
import { expectQueueResponse } from "../../services/queue.js";
@ -164,11 +149,7 @@ async function ensureHandoffIndexHydrated(c: any): Promise<void> {
return;
}
const existing = await c.db
.select({ handoffId: handoffIndex.handoffId })
.from(handoffIndex)
.limit(1)
.get();
const existing = await c.db.select({ handoffId: handoffIndex.handoffId }).from(handoffIndex).limit(1).get();
if (existing) {
c.state.handoffIndexHydrated = true;
@ -205,7 +186,7 @@ async function ensureHandoffIndexHydrated(c: any): Promise<void> {
handoffId: row.handoffId,
branchName: row.branchName,
createdAt: row.createdAt,
updatedAt: row.createdAt
updatedAt: row.createdAt,
})
.onConflictDoNothing()
.run();
@ -215,14 +196,14 @@ async function ensureHandoffIndexHydrated(c: any): Promise<void> {
logActorWarning("project", "skipped missing handoffs while hydrating index", {
workspaceId: c.state.workspaceId,
repoId: c.state.repoId,
skippedMissingHandoffActors
skippedMissingHandoffActors,
});
}
} catch (error) {
logActorWarning("project", "handoff index hydration from history failed", {
workspaceId: c.state.workspaceId,
repoId: c.state.repoId,
error: resolveErrorMessage(error)
error: resolveErrorMessage(error),
});
}
@ -284,7 +265,7 @@ async function enrichHandoffRecord(c: any, record: HandoffRecord): Promise<Hando
diffStat: branches.diffStat,
hasUnpushed: branches.hasUnpushed,
conflictsWithMain: branches.conflictsWithMain,
parentBranch: branches.parentBranch
parentBranch: branches.parentBranch,
})
.from(branches)
.where(eq(branches.branchName, branchName))
@ -299,7 +280,7 @@ async function enrichHandoffRecord(c: any, record: HandoffRecord): Promise<Hando
prAuthor: prCache.prAuthor,
ciStatus: prCache.ciStatus,
reviewStatus: prCache.reviewStatus,
reviewer: prCache.reviewer
reviewer: prCache.reviewer,
})
.from(prCache)
.where(eq(prCache.branchName, branchName))
@ -316,7 +297,7 @@ async function enrichHandoffRecord(c: any, record: HandoffRecord): Promise<Hando
prAuthor: pr?.prAuthor ?? null,
ciStatus: pr?.ciStatus ?? null,
reviewStatus: pr?.reviewStatus ?? null,
reviewer: pr?.reviewer ?? null
reviewer: pr?.reviewer ?? null,
};
}
@ -329,14 +310,14 @@ async function ensureProjectMutation(c: any, cmd: EnsureProjectCommand): Promise
.values({
id: 1,
remoteUrl: cmd.remoteUrl,
updatedAt: Date.now()
updatedAt: Date.now(),
})
.onConflictDoUpdate({
target: repoMeta.id,
set: {
remoteUrl: cmd.remoteUrl,
updatedAt: Date.now()
}
updatedAt: Date.now(),
},
})
.run();
@ -358,11 +339,7 @@ async function createHandoffMutation(c: any, cmd: CreateHandoffCommand): Promise
if (onBranch) {
await forceProjectSync(c, localPath);
const branchRow = await c.db
.select({ branchName: branches.branchName })
.from(branches)
.where(eq(branches.branchName, onBranch))
.get();
const branchRow = await c.db.select({ branchName: branches.branchName }).from(branches).where(eq(branches.branchName, onBranch)).get();
if (!branchRow) {
throw new Error(`Branch not found in repo snapshot: ${onBranch}`);
}
@ -370,7 +347,7 @@ async function createHandoffMutation(c: any, cmd: CreateHandoffCommand): Promise
await registerHandoffBranchMutation(c, {
handoffId,
branchName: onBranch,
requireExistingRemote: true
requireExistingRemote: true,
});
}
@ -393,7 +370,11 @@ async function createHandoffMutation(c: any, cmd: CreateHandoffCommand): Promise
});
} catch (error) {
if (onBranch) {
await c.db.delete(handoffIndex).where(eq(handoffIndex.handoffId, handoffId)).run().catch(() => {});
await c.db
.delete(handoffIndex)
.where(eq(handoffIndex.handoffId, handoffId))
.run()
.catch(() => {});
}
throw error;
}
@ -406,7 +387,7 @@ async function createHandoffMutation(c: any, cmd: CreateHandoffCommand): Promise
handoffId,
branchName: initialBranchName,
createdAt: now,
updatedAt: now
updatedAt: now,
})
.onConflictDoNothing()
.run();
@ -420,17 +401,14 @@ async function createHandoffMutation(c: any, cmd: CreateHandoffCommand): Promise
handoffId,
payload: {
repoId: c.state.repoId,
providerId: cmd.providerId
}
providerId: cmd.providerId,
},
});
return created;
}
async function registerHandoffBranchMutation(
c: any,
cmd: RegisterHandoffBranchCommand,
): Promise<{ branchName: string; headSha: string }> {
async function registerHandoffBranchMutation(c: any, cmd: RegisterHandoffBranchCommand): Promise<{ branchName: string; headSha: string }> {
const localPath = await ensureProjectReady(c);
const branchName = cmd.branchName.trim();
@ -460,7 +438,7 @@ async function registerHandoffBranchMutation(
workspaceId: c.state.workspaceId,
repoId: c.state.repoId,
handoffId: existingOwner.handoffId,
branchName
branchName,
});
} else {
throw error;
@ -510,7 +488,7 @@ async function registerHandoffBranchMutation(
workspaceId: c.state.workspaceId,
repoId: c.state.repoId,
branchName,
error: resolveErrorMessage(error)
error: resolveErrorMessage(error),
});
}
stackRows = await driver.stack.listStack(localPath).catch(() => []);
@ -532,7 +510,7 @@ async function registerHandoffBranchMutation(
trackedInStack: trackedInStack ? 1 : 0,
firstSeenAt: now,
lastSeenAt: now,
updatedAt: now
updatedAt: now,
})
.onConflictDoUpdate({
target: branches.branchName,
@ -541,8 +519,8 @@ async function registerHandoffBranchMutation(
parentBranch,
trackedInStack: trackedInStack ? 1 : 0,
lastSeenAt: now,
updatedAt: now
}
updatedAt: now,
},
})
.run();
@ -552,14 +530,14 @@ async function registerHandoffBranchMutation(
handoffId: cmd.handoffId,
branchName,
createdAt: now,
updatedAt: now
updatedAt: now,
})
.onConflictDoUpdate({
target: handoffIndex.handoffId,
set: {
branchName,
updatedAt: now
}
updatedAt: now,
},
})
.run();
@ -581,7 +559,7 @@ async function runRepoStackActionMutation(c: any, cmd: RunRepoStackActionCommand
action,
executed: false,
message: "git-spice is not available for this repo",
at
at,
};
}
@ -595,11 +573,7 @@ async function runRepoStackActionMutation(c: any, cmd: RunRepoStackActionCommand
await forceProjectSync(c, localPath);
if (branchName) {
const row = await c.db
.select({ branchName: branches.branchName })
.from(branches)
.where(eq(branches.branchName, branchName))
.get();
const row = await c.db.select({ branchName: branches.branchName }).from(branches).where(eq(branches.branchName, branchName)).get();
if (!row) {
throw new Error(`Branch not found in repo snapshot: ${branchName}`);
}
@ -612,11 +586,7 @@ async function runRepoStackActionMutation(c: any, cmd: RunRepoStackActionCommand
if (parentBranch === branchName) {
throw new Error("parentBranch must be different from branchName");
}
const parentRow = await c.db
.select({ branchName: branches.branchName })
.from(branches)
.where(eq(branches.branchName, parentBranch))
.get();
const parentRow = await c.db.select({ branchName: branches.branchName }).from(branches).where(eq(branches.branchName, parentBranch)).get();
if (!parentRow) {
throw new Error(`Parent branch not found in repo snapshot: ${parentBranch}`);
}
@ -648,15 +618,15 @@ async function runRepoStackActionMutation(c: any, cmd: RunRepoStackActionCommand
payload: {
action,
branchName: branchName ?? null,
parentBranch: parentBranch ?? null
}
parentBranch: parentBranch ?? null,
},
});
} catch (error) {
logActorWarning("project", "failed appending repo stack history event", {
workspaceId: c.state.workspaceId,
repoId: c.state.repoId,
action,
error: resolveErrorMessage(error)
error: resolveErrorMessage(error),
});
}
@ -664,7 +634,7 @@ async function runRepoStackActionMutation(c: any, cmd: RunRepoStackActionCommand
action,
executed: true,
message: `stack action executed: ${action}`,
at
at,
};
}
@ -686,7 +656,7 @@ async function applyPrSyncResultMutation(c: any, body: PrSyncResult): Promise<vo
reviewStatus: item.reviewStatus ?? null,
reviewer: item.reviewer ?? null,
fetchedAt: body.at,
updatedAt: body.at
updatedAt: body.at,
})
.onConflictDoUpdate({
target: prCache.branchName,
@ -701,8 +671,8 @@ async function applyPrSyncResultMutation(c: any, body: PrSyncResult): Promise<vo
reviewStatus: item.reviewStatus ?? null,
reviewer: item.reviewer ?? null,
fetchedAt: body.at,
updatedAt: body.at
}
updatedAt: body.at,
},
})
.run();
}
@ -712,11 +682,7 @@ async function applyPrSyncResultMutation(c: any, body: PrSyncResult): Promise<vo
continue;
}
const row = await c.db
.select({ handoffId: handoffIndex.handoffId })
.from(handoffIndex)
.where(eq(handoffIndex.branchName, item.headRefName))
.get();
const row = await c.db.select({ handoffId: handoffIndex.handoffId }).from(handoffIndex).where(eq(handoffIndex.branchName, item.headRefName)).get();
if (!row) {
continue;
}
@ -732,7 +698,7 @@ async function applyPrSyncResultMutation(c: any, body: PrSyncResult): Promise<vo
repoId: c.state.repoId,
handoffId: row.handoffId,
branchName: item.headRefName,
prState: item.state
prState: item.state,
});
continue;
}
@ -742,7 +708,7 @@ async function applyPrSyncResultMutation(c: any, body: PrSyncResult): Promise<vo
handoffId: row.handoffId,
branchName: item.headRefName,
prState: item.state,
error: resolveErrorMessage(error)
error: resolveErrorMessage(error),
});
}
}
@ -754,7 +720,7 @@ async function applyBranchSyncResultMutation(c: any, body: BranchSyncResult): Pr
for (const item of body.items) {
const existing = await c.db
.select({
firstSeenAt: branches.firstSeenAt
firstSeenAt: branches.firstSeenAt,
})
.from(branches)
.where(eq(branches.branchName, item.branchName))
@ -772,7 +738,7 @@ async function applyBranchSyncResultMutation(c: any, body: BranchSyncResult): Pr
conflictsWithMain: item.conflictsWithMain ? 1 : 0,
firstSeenAt: existing?.firstSeenAt ?? body.at,
lastSeenAt: body.at,
updatedAt: body.at
updatedAt: body.at,
})
.onConflictDoUpdate({
target: branches.branchName,
@ -785,16 +751,13 @@ async function applyBranchSyncResultMutation(c: any, body: BranchSyncResult): Pr
conflictsWithMain: item.conflictsWithMain ? 1 : 0,
firstSeenAt: existing?.firstSeenAt ?? body.at,
lastSeenAt: body.at,
updatedAt: body.at
}
updatedAt: body.at,
},
})
.run();
}
const existingRows = await c.db
.select({ branchName: branches.branchName })
.from(branches)
.all();
const existingRows = await c.db.select({ branchName: branches.branchName }).from(branches).all();
for (const row of existingRows) {
if (incoming.has(row.branchName)) {
@ -824,62 +787,60 @@ export async function runProjectWorkflow(ctx: any): Promise<void> {
return Loop.continue(undefined);
}
if (msg.name === "project.command.hydrateHandoffIndex") {
await loopCtx.step("project-hydrate-handoff-index", async () =>
hydrateHandoffIndexMutation(loopCtx, msg.body as HydrateHandoffIndexCommand),
);
await msg.complete({ ok: true });
return Loop.continue(undefined);
}
if (msg.name === "project.command.hydrateHandoffIndex") {
await loopCtx.step("project-hydrate-handoff-index", async () => hydrateHandoffIndexMutation(loopCtx, msg.body as HydrateHandoffIndexCommand));
await msg.complete({ ok: true });
return Loop.continue(undefined);
}
if (msg.name === "project.command.createHandoff") {
const result = await loopCtx.step({
name: "project-create-handoff",
timeout: 12 * 60_000,
run: async () => createHandoffMutation(loopCtx, msg.body as CreateHandoffCommand),
});
await msg.complete(result);
return Loop.continue(undefined);
}
if (msg.name === "project.command.createHandoff") {
const result = await loopCtx.step({
name: "project-create-handoff",
timeout: 12 * 60_000,
run: async () => createHandoffMutation(loopCtx, msg.body as CreateHandoffCommand),
});
await msg.complete(result);
return Loop.continue(undefined);
}
if (msg.name === "project.command.registerHandoffBranch") {
const result = await loopCtx.step({
name: "project-register-handoff-branch",
timeout: 5 * 60_000,
run: async () => registerHandoffBranchMutation(loopCtx, msg.body as RegisterHandoffBranchCommand),
});
await msg.complete(result);
return Loop.continue(undefined);
}
if (msg.name === "project.command.registerHandoffBranch") {
const result = await loopCtx.step({
name: "project-register-handoff-branch",
timeout: 5 * 60_000,
run: async () => registerHandoffBranchMutation(loopCtx, msg.body as RegisterHandoffBranchCommand),
});
await msg.complete(result);
return Loop.continue(undefined);
}
if (msg.name === "project.command.runRepoStackAction") {
const result = await loopCtx.step({
name: "project-run-repo-stack-action",
timeout: 12 * 60_000,
run: async () => runRepoStackActionMutation(loopCtx, msg.body as RunRepoStackActionCommand),
});
await msg.complete(result);
return Loop.continue(undefined);
}
if (msg.name === "project.command.runRepoStackAction") {
const result = await loopCtx.step({
name: "project-run-repo-stack-action",
timeout: 12 * 60_000,
run: async () => runRepoStackActionMutation(loopCtx, msg.body as RunRepoStackActionCommand),
});
await msg.complete(result);
return Loop.continue(undefined);
}
if (msg.name === "project.command.applyPrSyncResult") {
await loopCtx.step({
name: "project-apply-pr-sync-result",
timeout: 60_000,
run: async () => applyPrSyncResultMutation(loopCtx, msg.body as PrSyncResult),
});
await msg.complete({ ok: true });
return Loop.continue(undefined);
}
if (msg.name === "project.command.applyPrSyncResult") {
await loopCtx.step({
name: "project-apply-pr-sync-result",
timeout: 60_000,
run: async () => applyPrSyncResultMutation(loopCtx, msg.body as PrSyncResult),
});
await msg.complete({ ok: true });
return Loop.continue(undefined);
}
if (msg.name === "project.command.applyBranchSyncResult") {
await loopCtx.step({
name: "project-apply-branch-sync-result",
timeout: 60_000,
run: async () => applyBranchSyncResultMutation(loopCtx, msg.body as BranchSyncResult),
});
await msg.complete({ ok: true });
}
if (msg.name === "project.command.applyBranchSyncResult") {
await loopCtx.step({
name: "project-apply-branch-sync-result",
timeout: 60_000,
run: async () => applyBranchSyncResultMutation(loopCtx, msg.body as BranchSyncResult),
});
await msg.complete({ ok: true });
}
return Loop.continue(undefined);
});
@ -909,15 +870,9 @@ export const projectActions = {
async listReservedBranches(c: any, _cmd?: ListReservedBranchesCommand): Promise<string[]> {
await ensureHandoffIndexHydratedForRead(c);
const rows = await c.db
.select({ branchName: handoffIndex.branchName })
.from(handoffIndex)
.where(isNotNull(handoffIndex.branchName))
.all();
const rows = await c.db.select({ branchName: handoffIndex.branchName }).from(handoffIndex).where(isNotNull(handoffIndex.branchName)).all();
return rows
.map((row) => row.branchName)
.filter((name): name is string => typeof name === "string" && name.trim().length > 0);
return rows.map((row) => row.branchName).filter((name): name is string => typeof name === "string" && name.trim().length > 0);
},
async registerHandoffBranch(c: any, cmd: RegisterHandoffBranchCommand): Promise<{ branchName: string; headSha: string }> {
@ -944,11 +899,7 @@ export const projectActions = {
await ensureHandoffIndexHydratedForRead(c);
const handoffRows = await c.db
.select({ handoffId: handoffIndex.handoffId })
.from(handoffIndex)
.orderBy(desc(handoffIndex.updatedAt))
.all();
const handoffRows = await c.db.select({ handoffId: handoffIndex.handoffId }).from(handoffIndex).orderBy(desc(handoffIndex.updatedAt)).all();
for (const row of handoffRows) {
try {
@ -966,7 +917,7 @@ export const projectActions = {
branchName: record.branchName,
title: record.title,
status: record.status,
updatedAt: record.updatedAt
updatedAt: record.updatedAt,
});
} catch (error) {
if (isStaleHandoffReferenceError(error)) {
@ -974,7 +925,7 @@ export const projectActions = {
logActorWarning("project", "pruned stale handoff index row during summary listing", {
workspaceId: c.state.workspaceId,
repoId: c.state.repoId,
handoffId: row.handoffId
handoffId: row.handoffId,
});
continue;
}
@ -982,7 +933,7 @@ export const projectActions = {
workspaceId: c.state.workspaceId,
repoId: c.state.repoId,
handoffId: row.handoffId,
error: resolveErrorMessage(error)
error: resolveErrorMessage(error),
});
}
}
@ -994,11 +945,7 @@ export const projectActions = {
async getHandoffEnriched(c: any, cmd: GetHandoffEnrichedCommand): Promise<HandoffRecord> {
await ensureHandoffIndexHydratedForRead(c);
const row = await c.db
.select({ handoffId: handoffIndex.handoffId })
.from(handoffIndex)
.where(eq(handoffIndex.handoffId, cmd.handoffId))
.get();
const row = await c.db.select({ handoffId: handoffIndex.handoffId }).from(handoffIndex).where(eq(handoffIndex.handoffId, cmd.handoffId)).get();
if (!row) {
throw new Error(`Unknown handoff in repo ${c.state.repoId}: ${cmd.handoffId}`);
}
@ -1037,7 +984,7 @@ export const projectActions = {
conflictsWithMain: branches.conflictsWithMain,
firstSeenAt: branches.firstSeenAt,
lastSeenAt: branches.lastSeenAt,
updatedAt: branches.updatedAt
updatedAt: branches.updatedAt,
})
.from(branches)
.all();
@ -1046,15 +993,12 @@ export const projectActions = {
.select({
handoffId: handoffIndex.handoffId,
branchName: handoffIndex.branchName,
updatedAt: handoffIndex.updatedAt
updatedAt: handoffIndex.updatedAt,
})
.from(handoffIndex)
.all();
const handoffMetaByBranch = new Map<
string,
{ handoffId: string; title: string | null; status: HandoffRecord["status"] | null; updatedAt: number }
>();
const handoffMetaByBranch = new Map<string, { handoffId: string; title: string | null; status: HandoffRecord["status"] | null; updatedAt: number }>();
for (const row of handoffRows) {
if (!row.branchName) {
@ -1067,7 +1011,7 @@ export const projectActions = {
handoffId: row.handoffId,
title: record.title ?? null,
status: record.status,
updatedAt: record.updatedAt
updatedAt: record.updatedAt,
});
} catch (error) {
if (isStaleHandoffReferenceError(error)) {
@ -1076,7 +1020,7 @@ export const projectActions = {
workspaceId: c.state.workspaceId,
repoId: c.state.repoId,
handoffId: row.handoffId,
branchName: row.branchName
branchName: row.branchName,
});
continue;
}
@ -1085,7 +1029,7 @@ export const projectActions = {
repoId: c.state.repoId,
handoffId: row.handoffId,
branchName: row.branchName,
error: resolveErrorMessage(error)
error: resolveErrorMessage(error),
});
}
}
@ -1098,7 +1042,7 @@ export const projectActions = {
prUrl: prCache.prUrl,
ciStatus: prCache.ciStatus,
reviewStatus: prCache.reviewStatus,
reviewer: prCache.reviewer
reviewer: prCache.reviewer,
})
.from(prCache)
.all();
@ -1108,8 +1052,8 @@ export const projectActions = {
branchRowsRaw.map((row) => ({
branchName: row.branchName,
parentBranch: row.parentBranch ?? null,
updatedAt: row.updatedAt
}))
updatedAt: row.updatedAt,
})),
);
const detailByBranch = new Map(branchRowsRaw.map((row) => [row.branchName, row]));
@ -1137,7 +1081,7 @@ export const projectActions = {
reviewer: pr?.reviewer ?? null,
firstSeenAt: row.firstSeenAt ?? null,
lastSeenAt: row.lastSeenAt ?? null,
updatedAt: Math.max(row.updatedAt, handoffMeta?.updatedAt ?? 0)
updatedAt: Math.max(row.updatedAt, handoffMeta?.updatedAt ?? 0),
};
});
@ -1148,14 +1092,11 @@ export const projectActions = {
baseRef,
stackAvailable,
fetchedAt: now,
branches: branchRows
branches: branchRows,
};
},
async getPullRequestForBranch(
c: any,
cmd: GetPullRequestForBranchCommand,
): Promise<{ number: number; status: "draft" | "ready" } | null> {
async getPullRequestForBranch(c: any, cmd: GetPullRequestForBranchCommand): Promise<{ number: number; status: "draft" | "ready" } | null> {
const branchName = cmd.branchName?.trim();
if (!branchName) {
return null;
@ -1204,5 +1145,5 @@ export const projectActions = {
wait: true,
timeout: 5 * 60_000,
});
}
},
};

View file

@ -4,4 +4,3 @@ export default defineConfig({
out: "./src/actors/project/db/drizzle",
schema: "./src/actors/project/db/schema.ts",
});

View file

@ -189,4 +189,4 @@
"internal": {
"indexes": {}
}
}
}

View file

@ -213,4 +213,4 @@
"internal": {
"indexes": {}
}
}
}

View file

@ -251,4 +251,4 @@
"internal": {
"indexes": {}
}
}
}

View file

@ -3,32 +3,32 @@
// Do not hand-edit this file.
const journal = {
"entries": [
entries: [
{
"idx": 0,
"when": 1770924376062,
"tag": "0000_stormy_the_hunter",
"breakpoints": true
idx: 0,
when: 1770924376062,
tag: "0000_stormy_the_hunter",
breakpoints: true,
},
{
"idx": 1,
"when": 1770947252449,
"tag": "0001_wild_carlie_cooper",
"breakpoints": true
idx: 1,
when: 1770947252449,
tag: "0001_wild_carlie_cooper",
breakpoints: true,
},
{
"idx": 2,
"when": 1771276338465,
"tag": "0002_far_war_machine",
"breakpoints": true
idx: 2,
when: 1771276338465,
tag: "0002_far_war_machine",
breakpoints: true,
},
{
"idx": 3,
"when": 1771369000000,
"tag": "0003_busy_legacy",
"breakpoints": true
}
]
idx: 3,
when: 1771369000000,
tag: "0003_busy_legacy",
breakpoints: true,
},
],
} as const;
export default {
@ -77,5 +77,5 @@ ALTER TABLE \`branches\` DROP COLUMN \`worktree_path\`;`,
);
`,
m0003: `ALTER TABLE \`branches\` ADD \`tracked_in_stack\` integer;`,
} as const
} as const,
};

View file

@ -40,5 +40,5 @@ export const handoffIndex = sqliteTable("handoff_index", {
handoffId: text("handoff_id").notNull().primaryKey(),
branchName: text("branch_name"),
createdAt: integer("created_at").notNull(),
updatedAt: integer("updated_at").notNull()
updatedAt: integer("updated_at").notNull(),
});

View file

@ -21,7 +21,7 @@ export const project = actor({
remoteUrl: input.remoteUrl,
localPath: null as string | null,
syncActorsStarted: false,
handoffIndexHydrated: false
handoffIndexHydrated: false,
}),
actions: projectActions,
run: workflow(runProjectWorkflow),

View file

@ -4,4 +4,3 @@ export default defineConfig({
out: "./src/actors/sandbox-instance/db/drizzle",
schema: "./src/actors/sandbox-instance/db/schema.ts",
});

View file

@ -53,4 +53,4 @@
"internal": {
"indexes": {}
}
}
}

View file

@ -3,20 +3,20 @@
// Do not hand-edit this file.
const journal = {
"entries": [
entries: [
{
"idx": 0,
"when": 1770924375604,
"tag": "0000_broad_tyrannus",
"breakpoints": true
idx: 0,
when: 1770924375604,
tag: "0000_broad_tyrannus",
breakpoints: true,
},
{
"idx": 1,
"when": 1776482400000,
"tag": "0001_sandbox_sessions",
"breakpoints": true
}
]
idx: 1,
when: 1776482400000,
tag: "0001_sandbox_sessions",
breakpoints: true,
},
],
} as const;
export default {
@ -57,5 +57,5 @@ CREATE INDEX \`sandbox_session_events_session_id_event_index_idx\` ON \`sandbox_
--> statement-breakpoint
CREATE INDEX \`sandbox_session_events_session_id_created_at_idx\` ON \`sandbox_session_events\` (\`session_id\`,\`created_at\`);
`,
} as const
} as const,
};

View file

@ -3,7 +3,15 @@ import { eq } from "drizzle-orm";
import { actor, queue } from "rivetkit";
import { Loop, workflow } from "rivetkit/workflow";
import type { ProviderId } from "@openhandoff/shared";
import type { SessionEvent, SessionRecord } from "sandbox-agent";
import type {
ProcessCreateRequest,
ProcessInfo,
ProcessLogFollowQuery,
ProcessLogsResponse,
ProcessSignalQuery,
SessionEvent,
SessionRecord,
} from "sandbox-agent";
import { sandboxInstanceDb } from "./db/db.js";
import { sandboxInstance as sandboxInstanceTable } from "./db/schema.js";
import { SandboxInstancePersistDriver } from "./persist.js";
@ -18,14 +26,17 @@ export interface SandboxInstanceInput {
sandboxId: string;
}
interface SandboxAgentConnection {
endpoint: string;
token?: string;
}
const SANDBOX_ROW_ID = 1;
const CREATE_SESSION_MAX_ATTEMPTS = 3;
const CREATE_SESSION_RETRY_BASE_MS = 1_000;
const CREATE_SESSION_STEP_TIMEOUT_MS = 10 * 60_000;
function normalizeStatusFromEventPayload(
payload: unknown,
): "running" | "idle" | "error" | null {
function normalizeStatusFromEventPayload(payload: unknown): "running" | "idle" | "error" | null {
if (payload && typeof payload === "object") {
const envelope = payload as {
error?: unknown;
@ -49,11 +60,7 @@ function normalizeStatusFromEventPayload(
if (lowered.includes("error") || lowered.includes("failed")) {
return "error";
}
if (
lowered.includes("ended") ||
lowered.includes("complete") ||
lowered.includes("stopped")
) {
if (lowered.includes("ended") || lowered.includes("complete") || lowered.includes("stopped")) {
return "idle";
}
}
@ -79,7 +86,7 @@ function parseMetadata(metadataJson: string): Record<string, unknown> {
}
}
async function loadPersistedAgentConfig(c: any): Promise<{ endpoint: string; token?: string } | null> {
async function loadPersistedAgentConfig(c: any): Promise<SandboxAgentConnection | null> {
try {
const row = await c.db
.select({ metadataJson: sandboxInstanceTable.metadataJson })
@ -101,7 +108,7 @@ async function loadPersistedAgentConfig(c: any): Promise<{ endpoint: string; tok
return null;
}
async function loadFreshDaytonaAgentConfig(c: any): Promise<{ endpoint: string; token?: string }> {
async function loadFreshDaytonaAgentConfig(c: any): Promise<SandboxAgentConnection> {
const { config, driver } = getActorRuntimeContext();
const daytona = driver.daytona.createClient({
apiUrl: config.providers.daytona.endpoint,
@ -116,7 +123,7 @@ async function loadFreshDaytonaAgentConfig(c: any): Promise<{ endpoint: string;
return preview.token ? { endpoint: preview.url, token: preview.token } : { endpoint: preview.url };
}
async function loadFreshProviderAgentConfig(c: any): Promise<{ endpoint: string; token?: string }> {
async function loadFreshProviderAgentConfig(c: any): Promise<SandboxAgentConnection> {
const { providers } = getActorRuntimeContext();
const provider = providers.get(c.state.providerId);
return await provider.ensureSandboxAgent({
@ -125,7 +132,7 @@ async function loadFreshProviderAgentConfig(c: any): Promise<{ endpoint: string;
});
}
async function loadAgentConfig(c: any): Promise<{ endpoint: string; token?: string }> {
async function loadAgentConfig(c: any): Promise<SandboxAgentConnection> {
const persisted = await loadPersistedAgentConfig(c);
if (c.state.providerId === "daytona") {
// Keep one stable signed preview endpoint per sandbox-instance actor.
@ -183,12 +190,7 @@ async function derivePersistedSessionStatus(
function isTransientSessionCreateError(detail: string): boolean {
const lowered = detail.toLowerCase();
if (
lowered.includes("timed out") ||
lowered.includes("timeout") ||
lowered.includes("504") ||
lowered.includes("gateway timeout")
) {
if (lowered.includes("timed out") || lowered.includes("timeout") || lowered.includes("504") || lowered.includes("gateway timeout")) {
// ACP timeout errors are expensive and usually deterministic for the same
// request; immediate retries spawn additional sessions/processes and make
// recovery harder.
@ -196,11 +198,7 @@ function isTransientSessionCreateError(detail: string): boolean {
}
return (
lowered.includes("502") ||
lowered.includes("503") ||
lowered.includes("bad gateway") ||
lowered.includes("econnreset") ||
lowered.includes("econnrefused")
lowered.includes("502") || lowered.includes("503") || lowered.includes("bad gateway") || lowered.includes("econnreset") || lowered.includes("econnrefused")
);
}
@ -265,9 +263,7 @@ const SANDBOX_INSTANCE_QUEUE_NAMES = [
type SandboxInstanceQueueName = (typeof SANDBOX_INSTANCE_QUEUE_NAMES)[number];
function sandboxInstanceWorkflowQueueName(
name: SandboxInstanceQueueName,
): SandboxInstanceQueueName {
function sandboxInstanceWorkflowQueueName(name: SandboxInstanceQueueName): SandboxInstanceQueueName {
return name;
}
@ -282,6 +278,13 @@ async function getSandboxAgentClient(c: any) {
});
}
function broadcastProcessesUpdated(c: any): void {
c.broadcast("processesUpdated", {
sandboxId: c.state.sandboxId,
at: Date.now(),
});
}
async function ensureSandboxMutation(c: any, command: EnsureSandboxCommand): Promise<void> {
const now = Date.now();
const metadata = {
@ -297,15 +300,15 @@ async function ensureSandboxMutation(c: any, command: EnsureSandboxCommand): Pro
id: SANDBOX_ROW_ID,
metadataJson,
status: command.status,
updatedAt: now
updatedAt: now,
})
.onConflictDoUpdate({
target: sandboxInstanceTable.id,
set: {
metadataJson,
status: command.status,
updatedAt: now
}
updatedAt: now,
},
})
.run();
}
@ -315,17 +318,14 @@ async function updateHealthMutation(c: any, command: HealthSandboxCommand): Prom
.update(sandboxInstanceTable)
.set({
status: `${command.status}:${command.message}`,
updatedAt: Date.now()
updatedAt: Date.now(),
})
.where(eq(sandboxInstanceTable.id, SANDBOX_ROW_ID))
.run();
}
async function destroySandboxMutation(c: any): Promise<void> {
await c.db
.delete(sandboxInstanceTable)
.where(eq(sandboxInstanceTable.id, SANDBOX_ROW_ID))
.run();
await c.db.delete(sandboxInstanceTable).where(eq(sandboxInstanceTable.id, SANDBOX_ROW_ID)).run();
}
async function createSessionMutation(c: any, command: CreateSessionCommand): Promise<CreateSessionResult> {
@ -362,7 +362,7 @@ async function createSessionMutation(c: any, command: CreateSessionCommand): Pro
attempt,
maxAttempts: CREATE_SESSION_MAX_ATTEMPTS,
waitMs,
error: detail
error: detail,
});
await delay(waitMs);
}
@ -372,7 +372,7 @@ async function createSessionMutation(c: any, command: CreateSessionCommand): Pro
return {
id: null,
status: "error",
error: `sandbox-agent createSession failed after ${attemptsMade} ${attemptLabel}: ${lastDetail}`
error: `sandbox-agent createSession failed after ${attemptsMade} ${attemptLabel}: ${lastDetail}`,
};
}
@ -405,62 +405,50 @@ async function runSandboxInstanceWorkflow(ctx: any): Promise<void> {
return Loop.continue(undefined);
}
if (msg.name === "sandboxInstance.command.ensure") {
await loopCtx.step("sandbox-instance-ensure", async () =>
ensureSandboxMutation(loopCtx, msg.body as EnsureSandboxCommand),
);
await msg.complete({ ok: true });
return Loop.continue(undefined);
}
if (msg.name === "sandboxInstance.command.ensure") {
await loopCtx.step("sandbox-instance-ensure", async () => ensureSandboxMutation(loopCtx, msg.body as EnsureSandboxCommand));
await msg.complete({ ok: true });
return Loop.continue(undefined);
}
if (msg.name === "sandboxInstance.command.updateHealth") {
await loopCtx.step("sandbox-instance-update-health", async () =>
updateHealthMutation(loopCtx, msg.body as HealthSandboxCommand),
);
await msg.complete({ ok: true });
return Loop.continue(undefined);
}
if (msg.name === "sandboxInstance.command.updateHealth") {
await loopCtx.step("sandbox-instance-update-health", async () => updateHealthMutation(loopCtx, msg.body as HealthSandboxCommand));
await msg.complete({ ok: true });
return Loop.continue(undefined);
}
if (msg.name === "sandboxInstance.command.destroy") {
await loopCtx.step("sandbox-instance-destroy", async () =>
destroySandboxMutation(loopCtx),
);
await msg.complete({ ok: true });
return Loop.continue(undefined);
}
if (msg.name === "sandboxInstance.command.destroy") {
await loopCtx.step("sandbox-instance-destroy", async () => destroySandboxMutation(loopCtx));
await msg.complete({ ok: true });
return Loop.continue(undefined);
}
if (msg.name === "sandboxInstance.command.createSession") {
const result = await loopCtx.step({
name: "sandbox-instance-create-session",
timeout: CREATE_SESSION_STEP_TIMEOUT_MS,
run: async () => createSessionMutation(loopCtx, msg.body as CreateSessionCommand),
});
await msg.complete(result);
return Loop.continue(undefined);
}
if (msg.name === "sandboxInstance.command.createSession") {
const result = await loopCtx.step({
name: "sandbox-instance-create-session",
timeout: CREATE_SESSION_STEP_TIMEOUT_MS,
run: async () => createSessionMutation(loopCtx, msg.body as CreateSessionCommand),
});
await msg.complete(result);
return Loop.continue(undefined);
}
if (msg.name === "sandboxInstance.command.sendPrompt") {
await loopCtx.step("sandbox-instance-send-prompt", async () =>
sendPromptMutation(loopCtx, msg.body as SendPromptCommand),
);
await msg.complete({ ok: true });
return Loop.continue(undefined);
}
if (msg.name === "sandboxInstance.command.sendPrompt") {
await loopCtx.step("sandbox-instance-send-prompt", async () => sendPromptMutation(loopCtx, msg.body as SendPromptCommand));
await msg.complete({ ok: true });
return Loop.continue(undefined);
}
if (msg.name === "sandboxInstance.command.cancelSession") {
await loopCtx.step("sandbox-instance-cancel-session", async () =>
cancelSessionMutation(loopCtx, msg.body as SessionControlCommand),
);
await msg.complete({ ok: true });
return Loop.continue(undefined);
}
if (msg.name === "sandboxInstance.command.cancelSession") {
await loopCtx.step("sandbox-instance-cancel-session", async () => cancelSessionMutation(loopCtx, msg.body as SessionControlCommand));
await msg.complete({ ok: true });
return Loop.continue(undefined);
}
if (msg.name === "sandboxInstance.command.destroySession") {
await loopCtx.step("sandbox-instance-destroy-session", async () =>
destroySessionMutation(loopCtx, msg.body as SessionControlCommand),
);
await msg.complete({ ok: true });
}
if (msg.name === "sandboxInstance.command.destroySession") {
await loopCtx.step("sandbox-instance-destroy-session", async () => destroySessionMutation(loopCtx, msg.body as SessionControlCommand));
await msg.complete({ ok: true });
}
return Loop.continue(undefined);
});
@ -478,6 +466,56 @@ export const sandboxInstance = actor({
sandboxId: input.sandboxId,
}),
actions: {
async sandboxAgentConnection(c: any): Promise<SandboxAgentConnection> {
return await loadAgentConfig(c);
},
async createProcess(c: any, request: ProcessCreateRequest): Promise<ProcessInfo> {
const client = await getSandboxAgentClient(c);
const created = await client.createProcess(request);
broadcastProcessesUpdated(c);
return created;
},
async listProcesses(c: any): Promise<{ processes: ProcessInfo[] }> {
const client = await getSandboxAgentClient(c);
return await client.listProcesses();
},
async getProcessLogs(
c: any,
request: { processId: string; query?: ProcessLogFollowQuery }
): Promise<ProcessLogsResponse> {
const client = await getSandboxAgentClient(c);
return await client.getProcessLogs(request.processId, request.query);
},
async stopProcess(
c: any,
request: { processId: string; query?: ProcessSignalQuery }
): Promise<ProcessInfo> {
const client = await getSandboxAgentClient(c);
const stopped = await client.stopProcess(request.processId, request.query);
broadcastProcessesUpdated(c);
return stopped;
},
async killProcess(
c: any,
request: { processId: string; query?: ProcessSignalQuery }
): Promise<ProcessInfo> {
const client = await getSandboxAgentClient(c);
const killed = await client.killProcess(request.processId, request.query);
broadcastProcessesUpdated(c);
return killed;
},
async deleteProcess(c: any, request: { processId: string }): Promise<void> {
const client = await getSandboxAgentClient(c);
await client.deleteProcess(request.processId);
broadcastProcessesUpdated(c);
},
async providerState(c: any): Promise<{ providerId: ProviderId; sandboxId: string; state: string; at: number }> {
const at = Date.now();
const { config, driver } = getActorRuntimeContext();
@ -518,10 +556,14 @@ export const sandboxInstance = actor({
async destroy(c): Promise<void> {
const self = selfSandboxInstance(c);
await self.send(sandboxInstanceWorkflowQueueName("sandboxInstance.command.destroy"), {}, {
wait: true,
timeout: 60_000,
});
await self.send(
sandboxInstanceWorkflowQueueName("sandboxInstance.command.destroy"),
{},
{
wait: true,
timeout: 60_000,
},
);
},
async createSession(c: any, command: CreateSessionCommand): Promise<CreateSessionResult> {
@ -534,10 +576,7 @@ export const sandboxInstance = actor({
);
},
async listSessions(
c: any,
command?: ListSessionsCommand
): Promise<{ items: SessionRecord[]; nextCursor?: string }> {
async listSessions(c: any, command?: ListSessionsCommand): Promise<{ items: SessionRecord[]; nextCursor?: string }> {
const persist = new SandboxInstancePersistDriver(c.db);
try {
const client = await getSandboxAgentClient(c);
@ -556,7 +595,7 @@ export const sandboxInstance = actor({
workspaceId: c.state.workspaceId,
providerId: c.state.providerId,
sandboxId: c.state.sandboxId,
error: resolveErrorMessage(error)
error: resolveErrorMessage(error),
});
return await persist.listSessions({
cursor: command?.cursor,
@ -565,10 +604,7 @@ export const sandboxInstance = actor({
}
},
async listSessionEvents(
c: any,
command: ListSessionEventsCommand
): Promise<{ items: SessionEvent[]; nextCursor?: string }> {
async listSessionEvents(c: any, command: ListSessionEventsCommand): Promise<{ items: SessionEvent[]; nextCursor?: string }> {
const persist = new SandboxInstancePersistDriver(c.db);
return await persist.listEvents({
sessionId: command.sessionId,
@ -601,15 +637,9 @@ export const sandboxInstance = actor({
});
},
async sessionStatus(
c,
command: SessionStatusCommand
): Promise<{ id: string; status: "running" | "idle" | "error" }> {
return await derivePersistedSessionStatus(
new SandboxInstancePersistDriver(c.db),
command.sessionId,
);
}
async sessionStatus(c, command: SessionStatusCommand): Promise<{ id: string; status: "running" | "idle" | "error" }> {
return await derivePersistedSessionStatus(new SandboxInstancePersistDriver(c.db), command.sessionId);
},
},
run: workflow(runSandboxInstanceWorkflow),
});

View file

@ -1,12 +1,5 @@
import { and, asc, count, eq } from "drizzle-orm";
import type {
ListEventsRequest,
ListPage,
ListPageRequest,
SessionEvent,
SessionPersistDriver,
SessionRecord
} from "sandbox-agent";
import type { ListEventsRequest, ListPage, ListPageRequest, SessionEvent, SessionPersistDriver, SessionRecord } from "sandbox-agent";
import { sandboxSessionEvents, sandboxSessions } from "./db/schema.js";
const DEFAULT_MAX_SESSIONS = 1024;
@ -27,11 +20,7 @@ function parseCursor(cursor: string | undefined): number {
return parsed;
}
export function resolveEventListOffset(params: {
cursor?: string;
total: number;
limit: number;
}): number {
export function resolveEventListOffset(params: { cursor?: string; total: number; limit: number }): number {
if (params.cursor != null) {
return parseCursor(params.cursor);
}
@ -65,13 +54,10 @@ export class SandboxInstancePersistDriver implements SessionPersistDriver {
constructor(
private readonly db: any,
options: SandboxInstancePersistDriverOptions = {}
options: SandboxInstancePersistDriverOptions = {},
) {
this.maxSessions = normalizeCap(options.maxSessions, DEFAULT_MAX_SESSIONS);
this.maxEventsPerSession = normalizeCap(
options.maxEventsPerSession,
DEFAULT_MAX_EVENTS_PER_SESSION
);
this.maxEventsPerSession = normalizeCap(options.maxEventsPerSession, DEFAULT_MAX_EVENTS_PER_SESSION);
}
async getSession(id: string): Promise<SessionRecord | null> {
@ -132,10 +118,7 @@ export class SandboxInstancePersistDriver implements SessionPersistDriver {
sessionInit: safeParseJson(row.sessionInitJson, undefined),
}));
const totalRow = await this.db
.select({ c: count() })
.from(sandboxSessions)
.get();
const totalRow = await this.db.select({ c: count() }).from(sandboxSessions).get();
const total = Number(totalRow?.c ?? 0);
const nextOffset = offset + items.length;
@ -172,10 +155,7 @@ export class SandboxInstancePersistDriver implements SessionPersistDriver {
.run();
// Evict oldest sessions beyond cap.
const totalRow = await this.db
.select({ c: count() })
.from(sandboxSessions)
.get();
const totalRow = await this.db.select({ c: count() }).from(sandboxSessions).get();
const total = Number(totalRow?.c ?? 0);
const overflow = total - this.maxSessions;
if (overflow <= 0) return;
@ -195,11 +175,7 @@ export class SandboxInstancePersistDriver implements SessionPersistDriver {
async listEvents(request: ListEventsRequest): Promise<ListPage<SessionEvent>> {
const limit = normalizeCap(request.limit, DEFAULT_LIST_LIMIT);
const totalRow = await this.db
.select({ c: count() })
.from(sandboxSessionEvents)
.where(eq(sandboxSessionEvents.sessionId, request.sessionId))
.get();
const totalRow = await this.db.select({ c: count() }).from(sandboxSessionEvents).where(eq(sandboxSessionEvents.sessionId, request.sessionId)).get();
const total = Number(totalRow?.c ?? 0);
const offset = resolveEventListOffset({
cursor: request.cursor,
@ -267,11 +243,7 @@ export class SandboxInstancePersistDriver implements SessionPersistDriver {
.run();
// Trim oldest events beyond cap.
const totalRow = await this.db
.select({ c: count() })
.from(sandboxSessionEvents)
.where(eq(sandboxSessionEvents.sessionId, event.sessionId))
.get();
const totalRow = await this.db.select({ c: count() }).from(sandboxSessionEvents).where(eq(sandboxSessionEvents.sessionId, event.sessionId)).get();
const total = Number(totalRow?.c ?? 0);
const overflow = total - this.maxEventsPerSession;
if (overflow <= 0) return;

View file

@ -25,8 +25,10 @@ import type {
RepoStackActionInput,
RepoStackActionResult,
RepoRecord,
StarSandboxAgentRepoInput,
StarSandboxAgentRepoResult,
SwitchResult,
WorkspaceUseInput
WorkspaceUseInput,
} from "@openhandoff/shared";
import { getActorRuntimeContext } from "../context.js";
import { getHandoff, getOrCreateHistory, getOrCreateProject, selfWorkspace } from "../handles.js";
@ -58,11 +60,8 @@ interface RepoOverviewInput {
repoId: string;
}
const WORKSPACE_QUEUE_NAMES = [
"workspace.command.addRepo",
"workspace.command.createHandoff",
"workspace.command.refreshProviderProfiles",
] as const;
const WORKSPACE_QUEUE_NAMES = ["workspace.command.addRepo", "workspace.command.createHandoff", "workspace.command.refreshProviderProfiles"] as const;
const SANDBOX_AGENT_REPO = "rivet-dev/sandbox-agent";
type WorkspaceQueueName = (typeof WORKSPACE_QUEUE_NAMES)[number];
@ -79,11 +78,7 @@ function assertWorkspace(c: { state: WorkspaceState }, workspaceId: string): voi
}
async function resolveRepoId(c: any, handoffId: string): Promise<string> {
const row = await c.db
.select({ repoId: handoffLookup.repoId })
.from(handoffLookup)
.where(eq(handoffLookup.handoffId, handoffId))
.get();
const row = await c.db.select({ repoId: handoffLookup.repoId }).from(handoffLookup).where(eq(handoffLookup.handoffId, handoffId)).get();
if (!row) {
throw new Error(`Unknown handoff: ${handoffId} (not in lookup)`);
@ -107,11 +102,7 @@ async function upsertHandoffLookupRow(c: any, handoffId: string, repoId: string)
}
async function collectAllHandoffSummaries(c: any): Promise<HandoffSummary[]> {
const repoRows = await c.db
.select({ repoId: repos.repoId, remoteUrl: repos.remoteUrl })
.from(repos)
.orderBy(desc(repos.updatedAt))
.all();
const repoRows = await c.db.select({ repoId: repos.repoId, remoteUrl: repos.remoteUrl }).from(repos).orderBy(desc(repos.updatedAt)).all();
const all: HandoffSummary[] = [];
for (const row of repoRows) {
@ -123,7 +114,7 @@ async function collectAllHandoffSummaries(c: any): Promise<HandoffSummary[]> {
logActorWarning("workspace", "failed collecting handoffs for repo", {
workspaceId: c.state.workspaceId,
repoId: row.repoId,
error: resolveErrorMessage(error)
error: resolveErrorMessage(error),
});
}
}
@ -172,7 +163,7 @@ async function buildWorkbenchSnapshot(c: any): Promise<HandoffWorkbenchSnapshot>
workspaceId: c.state.workspaceId,
repoId: row.repoId,
handoffId: summary.handoffId,
error: resolveErrorMessage(error)
error: resolveErrorMessage(error),
});
}
}
@ -189,7 +180,7 @@ async function buildWorkbenchSnapshot(c: any): Promise<HandoffWorkbenchSnapshot>
logActorWarning("workspace", "failed collecting workbench repo snapshot", {
workspaceId: c.state.workspaceId,
repoId: row.repoId,
error: resolveErrorMessage(error)
error: resolveErrorMessage(error),
});
}
}
@ -200,7 +191,7 @@ async function buildWorkbenchSnapshot(c: any): Promise<HandoffWorkbenchSnapshot>
workspaceId: c.state.workspaceId,
repos: repoRows.map((row) => ({
id: row.repoId,
label: repoLabelFromRemote(row.remoteUrl)
label: repoLabelFromRemote(row.remoteUrl),
})),
projects,
handoffs,
@ -232,14 +223,14 @@ async function addRepoMutation(c: any, input: AddRepoInput): Promise<RepoRecord>
repoId,
remoteUrl,
createdAt: now,
updatedAt: now
updatedAt: now,
})
.onConflictDoUpdate({
target: repos.repoId,
set: {
remoteUrl,
updatedAt: now
}
updatedAt: now,
},
})
.run();
@ -249,7 +240,7 @@ async function addRepoMutation(c: any, input: AddRepoInput): Promise<RepoRecord>
repoId,
remoteUrl,
createdAt: now,
updatedAt: now
updatedAt: now,
};
}
@ -260,11 +251,7 @@ async function createHandoffMutation(c: any, input: CreateHandoffInput): Promise
const providerId = input.providerId ?? providers.defaultProviderId();
const repoId = input.repoId;
const repoRow = await c.db
.select({ remoteUrl: repos.remoteUrl })
.from(repos)
.where(eq(repos.repoId, repoId))
.get();
const repoRow = await c.db.select({ remoteUrl: repos.remoteUrl }).from(repos).where(eq(repos.repoId, repoId)).get();
if (!repoRow) {
throw new Error(`Unknown repo: ${repoId}`);
}
@ -275,14 +262,14 @@ async function createHandoffMutation(c: any, input: CreateHandoffInput): Promise
.values({
providerId,
profileJson: JSON.stringify({ providerId }),
updatedAt: Date.now()
updatedAt: Date.now(),
})
.onConflictDoUpdate({
target: providerProfiles.providerId,
set: {
profileJson: JSON.stringify({ providerId }),
updatedAt: Date.now()
}
updatedAt: Date.now(),
},
})
.run();
@ -296,18 +283,18 @@ async function createHandoffMutation(c: any, input: CreateHandoffInput): Promise
explicitTitle: input.explicitTitle ?? null,
explicitBranchName: input.explicitBranchName ?? null,
initialPrompt: input.initialPrompt ?? null,
onBranch: input.onBranch ?? null
onBranch: input.onBranch ?? null,
});
await c.db
.insert(handoffLookup)
.values({
handoffId: created.handoffId,
repoId
repoId,
})
.onConflictDoUpdate({
target: handoffLookup.handoffId,
set: { repoId }
set: { repoId },
})
.run();
@ -330,14 +317,14 @@ async function refreshProviderProfilesMutation(c: any, command?: RefreshProvider
.values({
providerId,
profileJson: JSON.stringify({ providerId }),
updatedAt: Date.now()
updatedAt: Date.now(),
})
.onConflictDoUpdate({
target: providerProfiles.providerId,
set: {
profileJson: JSON.stringify({ providerId }),
updatedAt: Date.now()
}
updatedAt: Date.now(),
},
})
.run();
}
@ -408,7 +395,7 @@ export const workspaceActions = {
repoId: repos.repoId,
remoteUrl: repos.remoteUrl,
createdAt: repos.createdAt,
updatedAt: repos.updatedAt
updatedAt: repos.updatedAt,
})
.from(repos)
.orderBy(desc(repos.updatedAt))
@ -419,7 +406,7 @@ export const workspaceActions = {
repoId: row.repoId,
remoteUrl: row.remoteUrl,
createdAt: row.createdAt,
updatedAt: row.updatedAt
updatedAt: row.updatedAt,
}));
},
@ -433,6 +420,16 @@ export const workspaceActions = {
);
},
async starSandboxAgentRepo(c: any, input: StarSandboxAgentRepoInput): Promise<StarSandboxAgentRepoResult> {
assertWorkspace(c, input.workspaceId);
const { driver } = getActorRuntimeContext();
await driver.github.starRepository(SANDBOX_AGENT_REPO);
return {
repo: SANDBOX_AGENT_REPO,
starredAt: Date.now(),
};
},
async getWorkbench(c: any, input: WorkspaceUseInput): Promise<HandoffWorkbenchSnapshot> {
assertWorkspace(c, input.workspaceId);
return await buildWorkbenchSnapshot(c);
@ -450,7 +447,7 @@ export const workspaceActions = {
...(input.title ? { explicitTitle: input.title } : {}),
...(input.branch ? { explicitBranchName: input.branch } : {}),
...(input.initialPrompt !== undefined ? { initialPrompt: input.initialPrompt } : {}),
...(input.model ? { agentType: agentTypeForModel(input.model) } : {})
...(input.model ? { agentType: agentTypeForModel(input.model) } : {}),
});
return {
handoffId: created.handoffId,
@ -527,11 +524,7 @@ export const workspaceActions = {
assertWorkspace(c, input.workspaceId);
if (input.repoId) {
const repoRow = await c.db
.select({ remoteUrl: repos.remoteUrl })
.from(repos)
.where(eq(repos.repoId, input.repoId))
.get();
const repoRow = await c.db.select({ remoteUrl: repos.remoteUrl }).from(repos).where(eq(repos.repoId, input.repoId)).get();
if (!repoRow) {
throw new Error(`Unknown repo: ${input.repoId}`);
}
@ -546,11 +539,7 @@ export const workspaceActions = {
async getRepoOverview(c: any, input: RepoOverviewInput): Promise<RepoOverview> {
assertWorkspace(c, input.workspaceId);
const repoRow = await c.db
.select({ remoteUrl: repos.remoteUrl })
.from(repos)
.where(eq(repos.repoId, input.repoId))
.get();
const repoRow = await c.db.select({ remoteUrl: repos.remoteUrl }).from(repos).where(eq(repos.repoId, input.repoId)).get();
if (!repoRow) {
throw new Error(`Unknown repo: ${input.repoId}`);
}
@ -563,11 +552,7 @@ export const workspaceActions = {
async runRepoStackAction(c: any, input: RepoStackActionInput): Promise<RepoStackActionResult> {
assertWorkspace(c, input.workspaceId);
const repoRow = await c.db
.select({ remoteUrl: repos.remoteUrl })
.from(repos)
.where(eq(repos.repoId, input.repoId))
.get();
const repoRow = await c.db.select({ remoteUrl: repos.remoteUrl }).from(repos).where(eq(repos.repoId, input.repoId)).get();
if (!repoRow) {
throw new Error(`Unknown repo: ${input.repoId}`);
}
@ -577,7 +562,7 @@ export const workspaceActions = {
return await project.runRepoStackAction({
action: input.action,
branchName: input.branchName,
parentBranch: input.parentBranch
parentBranch: input.parentBranch,
});
},
@ -591,7 +576,7 @@ export const workspaceActions = {
workspaceId: c.state.workspaceId,
handoffId,
providerId: record.providerId,
switchTarget: switched.switchTarget
switchTarget: switched.switchTarget,
};
},
@ -617,14 +602,14 @@ export const workspaceActions = {
const items = await hist.list({
branch: input.branch,
handoffId: input.handoffId,
limit
limit,
});
allEvents.push(...items);
} catch (error) {
logActorWarning("workspace", "history lookup failed for repo", {
workspaceId: c.state.workspaceId,
repoId: row.repoId,
error: resolveErrorMessage(error)
error: resolveErrorMessage(error),
});
}
}
@ -638,11 +623,7 @@ export const workspaceActions = {
const repoId = await resolveRepoId(c, input.handoffId);
const repoRow = await c.db
.select({ remoteUrl: repos.remoteUrl })
.from(repos)
.where(eq(repos.repoId, repoId))
.get();
const repoRow = await c.db.select({ remoteUrl: repos.remoteUrl }).from(repos).where(eq(repos.repoId, repoId)).get();
if (!repoRow) {
throw new Error(`Unknown repo: ${repoId}`);
}
@ -691,5 +672,5 @@ export const workspaceActions = {
const repoId = await resolveRepoId(c, input.handoffId);
const h = getHandoff(c, c.state.workspaceId, repoId, input.handoffId);
await h.kill({ reason: input.reason });
}
},
};

View file

@ -4,4 +4,3 @@ export default defineConfig({
out: "./src/actors/workspace/db/drizzle",
schema: "./src/actors/workspace/db/schema.ts",
});

View file

@ -46,4 +46,4 @@
"internal": {
"indexes": {}
}
}
}

View file

@ -84,4 +84,4 @@
"internal": {
"indexes": {}
}
}
}

View file

@ -3,26 +3,26 @@
// Do not hand-edit this file.
const journal = {
"entries": [
entries: [
{
"idx": 0,
"when": 1770924376525,
"tag": "0000_rare_iron_man",
"breakpoints": true
idx: 0,
when: 1770924376525,
tag: "0000_rare_iron_man",
breakpoints: true,
},
{
"idx": 1,
"when": 1770947252912,
"tag": "0001_sleepy_lady_deathstrike",
"breakpoints": true
idx: 1,
when: 1770947252912,
tag: "0001_sleepy_lady_deathstrike",
breakpoints: true,
},
{
"idx": 2,
"when": 1772668800000,
"tag": "0002_tiny_silver_surfer",
"breakpoints": true
}
]
idx: 2,
when: 1772668800000,
tag: "0002_tiny_silver_surfer",
breakpoints: true,
},
],
} as const;
export default {
@ -46,5 +46,5 @@ export default {
\`repo_id\` text NOT NULL
);
`,
} as const
} as const,
};

View file

@ -10,7 +10,7 @@ export const workspace = actor({
actionTimeout: 5 * 60_000,
},
createState: (_c, workspaceId: string) => ({
workspaceId
workspaceId,
}),
actions: workspaceActions,
run: workflow(runWorkspaceWorkflow),

View file

@ -34,11 +34,8 @@ export interface ActorSqliteDbOptions<TSchema extends Record<string, unknown>> {
baseDir?: string;
}
export function actorSqliteDb<TSchema extends Record<string, unknown>>(
options: ActorSqliteDbOptions<TSchema>
): DatabaseProvider<any & RawAccess> {
const isBunRuntime =
typeof (globalThis as any).Bun !== "undefined" && typeof (process as any)?.versions?.bun === "string";
export function actorSqliteDb<TSchema extends Record<string, unknown>>(options: ActorSqliteDbOptions<TSchema>): DatabaseProvider<any & RawAccess> {
const isBunRuntime = typeof (globalThis as any).Bun !== "undefined" && typeof (process as any)?.versions?.bun === "string";
// Backend tests run in a Node-ish Vitest environment where `bun:sqlite` and
// Bun's sqlite-backed Drizzle driver are not supported.

View file

@ -5,7 +5,18 @@ import type {
SandboxAgentClientOptions,
SandboxSessionCreateRequest
} from "./integrations/sandbox-agent/client.js";
import type { ListEventsRequest, ListPage, ListPageRequest, SessionEvent, SessionRecord } from "sandbox-agent";
import type {
ListEventsRequest,
ListPage,
ListPageRequest,
ProcessCreateRequest,
ProcessInfo,
ProcessLogFollowQuery,
ProcessLogsResponse,
ProcessSignalQuery,
SessionEvent,
SessionRecord,
} from "sandbox-agent";
import type {
DaytonaClientOptions,
DaytonaCreateSandboxOptions,
@ -33,7 +44,7 @@ import {
gitSpiceSyncRepo,
gitSpiceTrackBranch,
} from "./integrations/git-spice/index.js";
import { listPullRequests, createPr } from "./integrations/github/index.js";
import { listPullRequests, createPr, starRepository } from "./integrations/github/index.js";
import { SandboxAgentClient } from "./integrations/sandbox-agent/client.js";
import { DaytonaClient } from "./integrations/daytona/client.js";
@ -67,12 +78,8 @@ export interface StackDriver {
export interface GithubDriver {
listPullRequests(repoPath: string): Promise<PullRequestSnapshot[]>;
createPr(
repoPath: string,
headBranch: string,
title: string,
body?: string
): Promise<{ number: number; url: string }>;
createPr(repoPath: string, headBranch: string, title: string, body?: string): Promise<{ number: number; url: string }>;
starRepository(repoFullName: string): Promise<void>;
}
export interface SandboxAgentClientLike {
@ -80,6 +87,12 @@ export interface SandboxAgentClientLike {
sessionStatus(sessionId: string): Promise<SandboxSession>;
listSessions(request?: ListPageRequest): Promise<ListPage<SessionRecord>>;
listEvents(request: ListEventsRequest): Promise<ListPage<SessionEvent>>;
createProcess(request: ProcessCreateRequest): Promise<ProcessInfo>;
listProcesses(): Promise<{ processes: ProcessInfo[] }>;
getProcessLogs(processId: string, query?: ProcessLogFollowQuery): Promise<ProcessLogsResponse>;
stopProcess(processId: string, query?: ProcessSignalQuery): Promise<ProcessInfo>;
killProcess(processId: string, query?: ProcessSignalQuery): Promise<ProcessInfo>;
deleteProcess(processId: string): Promise<void>;
sendPrompt(request: { sessionId: string; prompt: string; notification?: boolean }): Promise<void>;
cancelSession(sessionId: string): Promise<void>;
destroySession(sessionId: string): Promise<void>;
@ -145,6 +158,7 @@ export function createDefaultDriver(): BackendDriver {
github: {
listPullRequests,
createPr,
starRepository,
},
sandboxAgent: {
createClient: (opts) => {

View file

@ -33,10 +33,8 @@ export async function startBackend(options: BackendStartOptions = {}): Promise<v
return undefined;
};
config.providers.daytona.endpoint =
envFirst("HF_DAYTONA_ENDPOINT", "DAYTONA_ENDPOINT") ?? config.providers.daytona.endpoint;
config.providers.daytona.apiKey =
envFirst("HF_DAYTONA_API_KEY", "DAYTONA_API_KEY") ?? config.providers.daytona.apiKey;
config.providers.daytona.endpoint = envFirst("HF_DAYTONA_ENDPOINT", "DAYTONA_ENDPOINT") ?? config.providers.daytona.endpoint;
config.providers.daytona.apiKey = envFirst("HF_DAYTONA_API_KEY", "DAYTONA_API_KEY") ?? config.providers.daytona.apiKey;
const driver = createDefaultDriver();
const providers = createProviderRegistry(config, driver);
@ -58,7 +56,7 @@ export async function startBackend(options: BackendStartOptions = {}): Promise<v
allowHeaders: ["Content-Type", "Authorization", "x-rivet-token"],
allowMethods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
exposeHeaders: ["Content-Type"],
})
}),
);
app.use(
"/api/rivet",
@ -67,7 +65,7 @@ export async function startBackend(options: BackendStartOptions = {}): Promise<v
allowHeaders: ["Content-Type", "Authorization", "x-rivet-token"],
allowMethods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
exposeHeaders: ["Content-Type"],
})
}),
);
const forward = async (c: any) => {
try {
@ -86,7 +84,7 @@ export async function startBackend(options: BackendStartOptions = {}): Promise<v
const server = Bun.serve({
fetch: app.fetch,
hostname: config.backend.host,
port: config.backend.port
port: config.backend.port,
});
process.on("SIGINT", async () => {
@ -130,13 +128,13 @@ async function main(): Promise<void> {
const port = parseArg("--port") ?? process.env.PORT ?? process.env.HF_BACKEND_PORT;
await startBackend({
host,
port: parseEnvPort(port)
port: parseEnvPort(port),
});
}
if (import.meta.url === `file://${process.argv[1]}`) {
main().catch((err: unknown) => {
const message = err instanceof Error ? err.stack ?? err.message : String(err);
const message = err instanceof Error ? (err.stack ?? err.message) : String(err);
console.error(message);
process.exit(1);
});

View file

@ -52,9 +52,7 @@ export class DaytonaClient {
image: options.image,
envVars: options.envVars,
labels: options.labels,
...(options.autoStopInterval !== undefined
? { autoStopInterval: options.autoStopInterval }
: {}),
...(options.autoStopInterval !== undefined ? { autoStopInterval: options.autoStopInterval } : {}),
});
return {

View file

@ -32,18 +32,10 @@ function commandLabel(cmd: SpiceCommand): string {
function looksMissing(error: unknown): boolean {
const detail = error instanceof Error ? error.message : String(error);
return (
detail.includes("ENOENT") ||
detail.includes("not a git command") ||
detail.includes("command not found")
);
return detail.includes("ENOENT") || detail.includes("not a git command") || detail.includes("command not found");
}
async function tryRun(
repoPath: string,
cmd: SpiceCommand,
args: string[]
): Promise<{ stdout: string; stderr: string }> {
async function tryRun(repoPath: string, cmd: SpiceCommand, args: string[]): Promise<{ stdout: string; stderr: string }> {
return await execFileAsync(cmd.command, [...cmd.prefix, ...args], {
cwd: repoPath,
timeout: DEFAULT_TIMEOUT_MS,
@ -51,8 +43,8 @@ async function tryRun(
env: {
...process.env,
NO_COLOR: "1",
FORCE_COLOR: "0"
}
FORCE_COLOR: "0",
},
});
}
@ -140,14 +132,7 @@ export async function gitSpiceAvailable(repoPath: string): Promise<boolean> {
export async function gitSpiceListStack(repoPath: string): Promise<SpiceStackEntry[]> {
try {
const { stdout } = await runSpice(repoPath, [
"log",
"short",
"--all",
"--json",
"--no-cr-status",
"--no-prompt"
]);
const { stdout } = await runSpice(repoPath, ["log", "short", "--all", "--json", "--no-cr-status", "--no-prompt"]);
return parseLogJson(stdout);
} catch {
return [];
@ -160,9 +145,9 @@ export async function gitSpiceSyncRepo(repoPath: string): Promise<void> {
[
["repo", "sync", "--restack", "--no-prompt"],
["repo", "sync", "--restack"],
["repo", "sync"]
["repo", "sync"],
],
"git-spice repo sync failed"
"git-spice repo sync failed",
);
}
@ -171,9 +156,9 @@ export async function gitSpiceRestackRepo(repoPath: string): Promise<void> {
repoPath,
[
["repo", "restack", "--no-prompt"],
["repo", "restack"]
["repo", "restack"],
],
"git-spice repo restack failed"
"git-spice repo restack failed",
);
}
@ -184,9 +169,9 @@ export async function gitSpiceRestackSubtree(repoPath: string, branchName: strin
["upstack", "restack", "--branch", branchName, "--no-prompt"],
["upstack", "restack", "--branch", branchName],
["branch", "restack", "--branch", branchName, "--no-prompt"],
["branch", "restack", "--branch", branchName]
["branch", "restack", "--branch", branchName],
],
`git-spice restack subtree failed for ${branchName}`
`git-spice restack subtree failed for ${branchName}`,
);
}
@ -195,41 +180,33 @@ export async function gitSpiceRebaseBranch(repoPath: string, branchName: string)
repoPath,
[
["branch", "restack", "--branch", branchName, "--no-prompt"],
["branch", "restack", "--branch", branchName]
["branch", "restack", "--branch", branchName],
],
`git-spice branch restack failed for ${branchName}`
`git-spice branch restack failed for ${branchName}`,
);
}
export async function gitSpiceReparentBranch(
repoPath: string,
branchName: string,
parentBranch: string
): Promise<void> {
export async function gitSpiceReparentBranch(repoPath: string, branchName: string, parentBranch: string): Promise<void> {
await runFallbacks(
repoPath,
[
["upstack", "onto", "--branch", branchName, parentBranch, "--no-prompt"],
["upstack", "onto", "--branch", branchName, parentBranch],
["branch", "onto", "--branch", branchName, parentBranch, "--no-prompt"],
["branch", "onto", "--branch", branchName, parentBranch]
["branch", "onto", "--branch", branchName, parentBranch],
],
`git-spice reparent failed for ${branchName} -> ${parentBranch}`
`git-spice reparent failed for ${branchName} -> ${parentBranch}`,
);
}
export async function gitSpiceTrackBranch(
repoPath: string,
branchName: string,
parentBranch: string
): Promise<void> {
export async function gitSpiceTrackBranch(repoPath: string, branchName: string, parentBranch: string): Promise<void> {
await runFallbacks(
repoPath,
[
["branch", "track", branchName, "--base", parentBranch, "--no-prompt"],
["branch", "track", branchName, "--base", parentBranch]
["branch", "track", branchName, "--base", parentBranch],
],
`git-spice track failed for ${branchName}`
`git-spice track failed for ${branchName}`,
);
}

View file

@ -11,12 +11,7 @@ const DEFAULT_GIT_FETCH_TIMEOUT_MS = 2 * 60_000;
const DEFAULT_GIT_CLONE_TIMEOUT_MS = 5 * 60_000;
function resolveGithubToken(): string | null {
const token =
process.env.GH_TOKEN ??
process.env.GITHUB_TOKEN ??
process.env.HF_GITHUB_TOKEN ??
process.env.HF_GH_TOKEN ??
null;
const token = process.env.GH_TOKEN ?? process.env.GITHUB_TOKEN ?? process.env.HF_GITHUB_TOKEN ?? process.env.HF_GH_TOKEN ?? null;
if (!token) return null;
const trimmed = token.trim();
return trimmed.length > 0 ? trimmed : null;
@ -33,19 +28,18 @@ function ensureAskpassScript(): string {
// Git invokes $GIT_ASKPASS with the prompt string as argv[1]. Provide both username and password.
// We avoid embedding the token in this file; it is read from env at runtime.
const content =
[
"#!/bin/sh",
'prompt="$1"',
// Prefer GH_TOKEN/GITHUB_TOKEN but support HF_* aliases too.
'token="${GH_TOKEN:-${GITHUB_TOKEN:-${HF_GITHUB_TOKEN:-${HF_GH_TOKEN:-}}}}"',
'case "$prompt" in',
' *Username*) echo "x-access-token" ;;',
' *Password*) echo "$token" ;;',
' *) echo "" ;;',
"esac",
"",
].join("\n");
const content = [
"#!/bin/sh",
'prompt="$1"',
// Prefer GH_TOKEN/GITHUB_TOKEN but support HF_* aliases too.
'token="${GH_TOKEN:-${GITHUB_TOKEN:-${HF_GITHUB_TOKEN:-${HF_GH_TOKEN:-}}}}"',
'case "$prompt" in',
' *Username*) echo "x-access-token" ;;',
' *Password*) echo "$token" ;;',
' *) echo "" ;;',
"esac",
"",
].join("\n");
writeFileSync(path, content, "utf8");
chmodSync(path, 0o700);
@ -141,12 +135,7 @@ export async function ensureCloned(remoteUrl: string, targetPath: string): Promi
export async function remoteDefaultBaseRef(repoPath: string): Promise<string> {
try {
const { stdout } = await execFileAsync("git", [
"-C",
repoPath,
"symbolic-ref",
"refs/remotes/origin/HEAD",
], { env: gitEnv() });
const { stdout } = await execFileAsync("git", ["-C", repoPath, "symbolic-ref", "refs/remotes/origin/HEAD"], { env: gitEnv() });
const ref = stdout.trim(); // refs/remotes/origin/main
const match = ref.match(/^refs\/remotes\/(.+)$/);
if (match?.[1]) {
@ -169,17 +158,10 @@ export async function remoteDefaultBaseRef(repoPath: string): Promise<string> {
}
export async function listRemoteBranches(repoPath: string): Promise<BranchSnapshot[]> {
const { stdout } = await execFileAsync(
"git",
[
"-C",
repoPath,
"for-each-ref",
"--format=%(refname:short) %(objectname)",
"refs/remotes/origin",
],
{ maxBuffer: 1024 * 1024, env: gitEnv() }
);
const { stdout } = await execFileAsync("git", ["-C", repoPath, "for-each-ref", "--format=%(refname:short) %(objectname)", "refs/remotes/origin"], {
maxBuffer: 1024 * 1024,
env: gitEnv(),
});
return stdout
.trim()
@ -191,24 +173,12 @@ export async function listRemoteBranches(repoPath: string): Promise<BranchSnapsh
const branchName = short.replace(/^origin\//, "");
return { branchName, commitSha: commitSha ?? "" };
})
.filter(
(row) =>
row.branchName.length > 0 &&
row.branchName !== "HEAD" &&
row.branchName !== "origin" &&
row.commitSha.length > 0,
);
.filter((row) => row.branchName.length > 0 && row.branchName !== "HEAD" && row.branchName !== "origin" && row.commitSha.length > 0);
}
async function remoteBranchExists(repoPath: string, branchName: string): Promise<boolean> {
try {
await execFileAsync("git", [
"-C",
repoPath,
"show-ref",
"--verify",
`refs/remotes/origin/${branchName}`,
], { env: gitEnv() });
await execFileAsync("git", ["-C", repoPath, "show-ref", "--verify", `refs/remotes/origin/${branchName}`], { env: gitEnv() });
return true;
} catch {
return false;
@ -233,11 +203,10 @@ export async function diffStatForBranch(repoPath: string, branchName: string): P
try {
const baseRef = await remoteDefaultBaseRef(repoPath);
const headRef = `origin/${branchName}`;
const { stdout } = await execFileAsync(
"git",
["-C", repoPath, "diff", "--shortstat", `${baseRef}...${headRef}`],
{ maxBuffer: 1024 * 1024, env: gitEnv() }
);
const { stdout } = await execFileAsync("git", ["-C", repoPath, "diff", "--shortstat", `${baseRef}...${headRef}`], {
maxBuffer: 1024 * 1024,
env: gitEnv(),
});
const trimmed = stdout.trim();
if (!trimmed) {
return "+0/-0";
@ -252,20 +221,13 @@ export async function diffStatForBranch(repoPath: string, branchName: string): P
}
}
export async function conflictsWithMain(
repoPath: string,
branchName: string
): Promise<boolean> {
export async function conflictsWithMain(repoPath: string, branchName: string): Promise<boolean> {
try {
const baseRef = await remoteDefaultBaseRef(repoPath);
const headRef = `origin/${branchName}`;
// Use merge-tree (git 2.38+) for a clean conflict check.
try {
await execFileAsync(
"git",
["-C", repoPath, "merge-tree", "--write-tree", "--no-messages", baseRef, headRef],
{ env: gitEnv() }
);
await execFileAsync("git", ["-C", repoPath, "merge-tree", "--write-tree", "--no-messages", baseRef, headRef], { env: gitEnv() });
// If merge-tree exits 0, no conflicts. Non-zero exit means conflicts.
return false;
} catch {
@ -279,11 +241,7 @@ export async function conflictsWithMain(
export async function getOriginOwner(repoPath: string): Promise<string> {
try {
const { stdout } = await execFileAsync(
"git",
["-C", repoPath, "remote", "get-url", "origin"],
{ env: gitEnv() }
);
const { stdout } = await execFileAsync("git", ["-C", repoPath, "remote", "get-url", "origin"], { env: gitEnv() });
const url = stdout.trim();
// Handle SSH: git@github.com:owner/repo.git
const sshMatch = url.match(/[:\/]([^\/]+)\/[^\/]+(?:\.git)?$/);

View file

@ -36,9 +36,7 @@ interface GhPrListItem {
}>;
}
function parseCiStatus(
checks: GhPrListItem["statusCheckRollup"]
): string | null {
function parseCiStatus(checks: GhPrListItem["statusCheckRollup"]): string | null {
if (!checks || checks.length === 0) return null;
let total = 0;
@ -53,12 +51,7 @@ function parseCiStatus(
if (conclusion === "SUCCESS" || state === "SUCCESS") {
successes++;
} else if (
status === "IN_PROGRESS" ||
status === "QUEUED" ||
status === "PENDING" ||
state === "PENDING"
) {
} else if (status === "IN_PROGRESS" || status === "QUEUED" || status === "PENDING" || state === "PENDING") {
hasRunning = true;
}
}
@ -70,9 +63,7 @@ function parseCiStatus(
return `${successes}/${total}`;
}
function parseReviewStatus(
reviews: GhPrListItem["reviews"]
): { status: string | null; reviewer: string | null } {
function parseReviewStatus(reviews: GhPrListItem["reviews"]): { status: string | null; reviewer: string | null } {
if (!reviews || reviews.length === 0) {
return { status: null, reviewer: null };
}
@ -120,35 +111,21 @@ function snapshotFromGhItem(item: GhPrListItem): PullRequestSnapshot {
isDraft: item.isDraft ?? false,
ciStatus: parseCiStatus(item.statusCheckRollup),
reviewStatus,
reviewer
reviewer,
};
}
const PR_JSON_FIELDS =
"number,headRefName,state,title,url,author,isDraft,statusCheckRollup,reviews";
const PR_JSON_FIELDS = "number,headRefName,state,title,url,author,isDraft,statusCheckRollup,reviews";
export async function listPullRequests(repoPath: string): Promise<PullRequestSnapshot[]> {
try {
const { stdout } = await execFileAsync(
"gh",
[
"pr",
"list",
"--json",
PR_JSON_FIELDS,
"--limit",
"200"
],
{ maxBuffer: 1024 * 1024 * 4, cwd: repoPath }
);
const { stdout } = await execFileAsync("gh", ["pr", "list", "--json", PR_JSON_FIELDS, "--limit", "200"], { maxBuffer: 1024 * 1024 * 4, cwd: repoPath });
const parsed = JSON.parse(stdout) as GhPrListItem[];
return parsed.map((item) => {
// Handle fork PRs where headRefName may contain "owner:branch"
const headRefName = item.headRefName.includes(":")
? item.headRefName.split(":").pop() ?? item.headRefName
: item.headRefName;
const headRefName = item.headRefName.includes(":") ? (item.headRefName.split(":").pop() ?? item.headRefName) : item.headRefName;
return snapshotFromGhItem({ ...item, headRefName });
});
@ -157,22 +134,9 @@ export async function listPullRequests(repoPath: string): Promise<PullRequestSna
}
}
export async function getPrInfo(
repoPath: string,
branchName: string
): Promise<PullRequestSnapshot | null> {
export async function getPrInfo(repoPath: string, branchName: string): Promise<PullRequestSnapshot | null> {
try {
const { stdout } = await execFileAsync(
"gh",
[
"pr",
"view",
branchName,
"--json",
PR_JSON_FIELDS
],
{ maxBuffer: 1024 * 1024 * 4, cwd: repoPath }
);
const { stdout } = await execFileAsync("gh", ["pr", "view", branchName, "--json", PR_JSON_FIELDS], { maxBuffer: 1024 * 1024 * 4, cwd: repoPath });
const item = JSON.parse(stdout) as GhPrListItem;
return snapshotFromGhItem(item);
@ -181,12 +145,7 @@ export async function getPrInfo(
}
}
export async function createPr(
repoPath: string,
headBranch: string,
title: string,
body?: string
): Promise<{ number: number; url: string }> {
export async function createPr(repoPath: string, headBranch: string, title: string, body?: string): Promise<{ number: number; url: string }> {
const args = ["pr", "create", "--title", title, "--head", headBranch];
if (body) {
args.push("--body", body);
@ -196,7 +155,7 @@ export async function createPr(
const { stdout } = await execFileAsync("gh", args, {
maxBuffer: 1024 * 1024,
cwd: repoPath
cwd: repoPath,
});
// gh pr create outputs the PR URL on success
@ -208,29 +167,29 @@ export async function createPr(
return { number, url };
}
export async function getAllowedMergeMethod(
repoPath: string
): Promise<"squash" | "rebase" | "merge"> {
export async function starRepository(repoFullName: string): Promise<void> {
try {
await execFileAsync("gh", ["api", "--method", "PUT", `user/starred/${repoFullName}`], {
maxBuffer: 1024 * 1024,
});
} catch (error) {
const message =
error instanceof Error ? error.message : `Failed to star GitHub repository ${repoFullName}. Ensure GitHub auth is configured for the backend.`;
throw new Error(message);
}
}
export async function getAllowedMergeMethod(repoPath: string): Promise<"squash" | "rebase" | "merge"> {
try {
// Get the repo owner/name from gh
const { stdout: repoJson } = await execFileAsync(
"gh",
["repo", "view", "--json", "owner,name"],
{ cwd: repoPath }
);
const { stdout: repoJson } = await execFileAsync("gh", ["repo", "view", "--json", "owner,name"], { cwd: repoPath });
const repo = JSON.parse(repoJson) as { owner: { login: string }; name: string };
const repoFullName = `${repo.owner.login}/${repo.name}`;
const { stdout } = await execFileAsync(
"gh",
[
"api",
`repos/${repoFullName}`,
"--jq",
".allow_squash_merge, .allow_rebase_merge, .allow_merge_commit"
],
{ maxBuffer: 1024 * 1024, cwd: repoPath }
);
const { stdout } = await execFileAsync("gh", ["api", `repos/${repoFullName}`, "--jq", ".allow_squash_merge, .allow_rebase_merge, .allow_merge_commit"], {
maxBuffer: 1024 * 1024,
cwd: repoPath,
});
const lines = stdout.trim().split("\n");
const allowSquash = lines[0]?.trim() === "true";
@ -248,23 +207,12 @@ export async function getAllowedMergeMethod(
export async function mergePr(repoPath: string, prNumber: number): Promise<void> {
const method = await getAllowedMergeMethod(repoPath);
await execFileAsync(
"gh",
["pr", "merge", String(prNumber), `--${method}`, "--delete-branch"],
{ cwd: repoPath }
);
await execFileAsync("gh", ["pr", "merge", String(prNumber), `--${method}`, "--delete-branch"], { cwd: repoPath });
}
export async function isPrMerged(
repoPath: string,
branchName: string
): Promise<boolean> {
export async function isPrMerged(repoPath: string, branchName: string): Promise<boolean> {
try {
const { stdout } = await execFileAsync(
"gh",
["pr", "view", branchName, "--json", "state"],
{ cwd: repoPath }
);
const { stdout } = await execFileAsync("gh", ["pr", "view", branchName, "--json", "state"], { cwd: repoPath });
const parsed = JSON.parse(stdout) as { state: string };
return parsed.state.toUpperCase() === "MERGED";
} catch {
@ -272,16 +220,9 @@ export async function isPrMerged(
}
}
export async function getPrTitle(
repoPath: string,
branchName: string
): Promise<string | null> {
export async function getPrTitle(repoPath: string, branchName: string): Promise<string | null> {
try {
const { stdout } = await execFileAsync(
"gh",
["pr", "view", branchName, "--json", "title"],
{ cwd: repoPath }
);
const { stdout } = await execFileAsync("gh", ["pr", "view", branchName, "--json", "title"], { cwd: repoPath });
const parsed = JSON.parse(stdout) as { title: string };
return parsed.title;
} catch {

View file

@ -21,17 +21,11 @@ export async function graphiteGet(repoPath: string, branchName: string): Promise
}
}
export async function graphiteCreateBranch(
repoPath: string,
branchName: string
): Promise<void> {
export async function graphiteCreateBranch(repoPath: string, branchName: string): Promise<void> {
await execFileAsync("gt", ["create", branchName], { cwd: repoPath });
}
export async function graphiteCheckout(
repoPath: string,
branchName: string
): Promise<void> {
export async function graphiteCheckout(repoPath: string, branchName: string): Promise<void> {
await execFileAsync("gt", ["checkout", branchName], { cwd: repoPath });
}
@ -39,17 +33,11 @@ export async function graphiteSubmit(repoPath: string): Promise<void> {
await execFileAsync("gt", ["submit", "--no-edit"], { cwd: repoPath });
}
export async function graphiteMergeBranch(
repoPath: string,
branchName: string
): Promise<void> {
export async function graphiteMergeBranch(repoPath: string, branchName: string): Promise<void> {
await execFileAsync("gt", ["merge", branchName], { cwd: repoPath });
}
export async function graphiteAbandon(
repoPath: string,
branchName: string
): Promise<void> {
export async function graphiteAbandon(repoPath: string, branchName: string): Promise<void> {
await execFileAsync("gt", ["abandon", branchName], { cwd: repoPath });
}
@ -58,14 +46,12 @@ export interface GraphiteStackEntry {
parentBranch: string | null;
}
export async function graphiteGetStack(
repoPath: string
): Promise<GraphiteStackEntry[]> {
export async function graphiteGetStack(repoPath: string): Promise<GraphiteStackEntry[]> {
try {
// Try JSON output first
const { stdout } = await execFileAsync("gt", ["log", "--json"], {
cwd: repoPath,
maxBuffer: 1024 * 1024
maxBuffer: 1024 * 1024,
});
const parsed = JSON.parse(stdout) as Array<{
@ -77,14 +63,14 @@ export async function graphiteGetStack(
return parsed.map((entry) => ({
branchName: entry.branch ?? entry.name ?? "",
parentBranch: entry.parent ?? entry.parentBranch ?? null
parentBranch: entry.parent ?? entry.parentBranch ?? null,
}));
} catch {
// Fall back to text parsing of `gt log`
try {
const { stdout } = await execFileAsync("gt", ["log"], {
cwd: repoPath,
maxBuffer: 1024 * 1024
maxBuffer: 1024 * 1024,
});
const entries: GraphiteStackEntry[] = [];
@ -113,9 +99,7 @@ export async function graphiteGetStack(
branchStack.pop();
}
const parentBranch = branchStack.length > 0
? branchStack[branchStack.length - 1] ?? null
: null;
const parentBranch = branchStack.length > 0 ? (branchStack[branchStack.length - 1] ?? null) : null;
entries.push({ branchName, parentBranch });
branchStack.push(branchName);
@ -128,15 +112,12 @@ export async function graphiteGetStack(
}
}
export async function graphiteGetParent(
repoPath: string,
branchName: string
): Promise<string | null> {
export async function graphiteGetParent(repoPath: string, branchName: string): Promise<string | null> {
try {
// Try `gt get <branchName>` to see parent info
const { stdout } = await execFileAsync("gt", ["get", branchName], {
cwd: repoPath,
maxBuffer: 1024 * 1024
maxBuffer: 1024 * 1024,
});
// Parse output for parent branch reference

View file

@ -3,6 +3,11 @@ import type {
ListEventsRequest,
ListPage,
ListPageRequest,
ProcessCreateRequest,
ProcessInfo,
ProcessLogFollowQuery,
ProcessLogsResponse,
ProcessSignalQuery,
SessionEvent,
SessionPersistDriver,
SessionRecord
@ -118,18 +123,11 @@ export class SandboxAgentClient {
const message = err instanceof Error ? err.message : String(err);
const lowered = message.toLowerCase();
// sandbox-agent server times out long-running ACP prompts and returns a 504-like error.
return (
lowered.includes("timeout waiting for agent response") ||
lowered.includes("timed out waiting for agent response") ||
lowered.includes("504")
);
return lowered.includes("timeout waiting for agent response") || lowered.includes("timed out waiting for agent response") || lowered.includes("504");
}
async createSession(request: string | SandboxSessionCreateRequest): Promise<SandboxSession> {
const normalized: SandboxSessionCreateRequest =
typeof request === "string"
? { prompt: request }
: request;
const normalized: SandboxSessionCreateRequest = typeof request === "string" ? { prompt: request } : request;
const sdk = await this.sdk();
// Do not wrap createSession in a local Promise.race timeout. The underlying SDK
// call is not abortable, so local timeout races create overlapping ACP requests and
@ -213,6 +211,39 @@ export class SandboxAgentClient {
return sdk.getEvents(request);
}
async createProcess(request: ProcessCreateRequest): Promise<ProcessInfo> {
const sdk = await this.sdk();
return await sdk.createProcess(request);
}
async listProcesses(): Promise<{ processes: ProcessInfo[] }> {
const sdk = await this.sdk();
return await sdk.listProcesses();
}
async getProcessLogs(
processId: string,
query: ProcessLogFollowQuery = {}
): Promise<ProcessLogsResponse> {
const sdk = await this.sdk();
return await sdk.getProcessLogs(processId, query);
}
async stopProcess(processId: string, query?: ProcessSignalQuery): Promise<ProcessInfo> {
const sdk = await this.sdk();
return await sdk.stopProcess(processId, query);
}
async killProcess(processId: string, query?: ProcessSignalQuery): Promise<ProcessInfo> {
const sdk = await this.sdk();
return await sdk.killProcess(processId, query);
}
async deleteProcess(processId: string): Promise<void> {
const sdk = await this.sdk();
await sdk.deleteProcess(processId);
}
async sendPrompt(request: SandboxSessionPromptRequest): Promise<void> {
const sdk = await this.sdk();
const existing = await sdk.getSession(request.sessionId);
@ -343,18 +374,14 @@ export class SandboxAgentClient {
} while (cursor);
}
async generateCommitMessage(
dir: string,
spec: string,
task: string
): Promise<string> {
async generateCommitMessage(dir: string, spec: string, task: string): Promise<string> {
const prompt = [
"Generate a conventional commit message for the following changes.",
"Return ONLY the commit message, no explanation or markdown formatting.",
"",
`Task: ${task}`,
"",
`Spec/diff:\n${spec}`
`Spec/diff:\n${spec}`,
].join("\n");
const sdk = await this.sdk();

View file

@ -99,10 +99,10 @@ export class TerminalBellBackend implements NotifyBackend {
}
const backendFactories: Record<string, () => NotifyBackend> = {
"openclaw": () => new OpenclawBackend(),
openclaw: () => new OpenclawBackend(),
"macos-osascript": () => new MacOsNotifyBackend(),
"linux-notify-send": () => new LinuxNotifySendBackend(),
"terminal": () => new TerminalBellBackend(),
terminal: () => new TerminalBellBackend(),
};
export async function createBackends(configOrder: string[]): Promise<NotifyBackend[]> {

View file

@ -49,11 +49,7 @@ export function createNotificationService(backends: NotifyBackend[]): Notificati
},
async changesRequested(branchName: string, prNumber: number, reviewer: string): Promise<void> {
await notify(
"Changes Requested",
`Changes requested on PR #${prNumber} (${branchName}) by ${reviewer}`,
"high",
);
await notify("Changes Requested", `Changes requested on PR #${prNumber} (${branchName}) by ${reviewer}`, "high");
},
async prMerged(branchName: string, prNumber: number): Promise<void> {

View file

@ -15,14 +15,7 @@ export class PrStateTracker {
this.states = new Map();
}
update(
repoId: string,
branchName: string,
prNumber: number,
ci: CiState,
review: ReviewState,
reviewer?: string,
): PrStateTransition[] {
update(repoId: string, branchName: string, prNumber: number, ci: CiState, review: ReviewState, reviewer?: string): PrStateTransition[] {
const key = `${repoId}:${branchName}`;
const prev = this.states.get(key);
const transitions: PrStateTransition[] = [];

View file

@ -13,7 +13,7 @@ import type {
SandboxHandle,
SandboxHealth,
SandboxHealthRequest,
SandboxProvider
SandboxProvider,
} from "../provider-api/index.js";
import type { DaytonaDriver } from "../../driver.js";
import { Image } from "@daytonaio/sdk";
@ -33,7 +33,7 @@ export interface DaytonaProviderConfig {
export class DaytonaProvider implements SandboxProvider {
constructor(
private readonly config: DaytonaProviderConfig,
private readonly daytona?: DaytonaDriver
private readonly daytona?: DaytonaDriver,
) {}
private static readonly SANDBOX_AGENT_PORT = 2468;
@ -60,10 +60,7 @@ export class DaytonaProvider implements SandboxProvider {
}
private getAcpRequestTimeoutMs(): number {
const parsed = Number(
process.env.HF_SANDBOX_AGENT_ACP_REQUEST_TIMEOUT_MS
?? DaytonaProvider.DEFAULT_ACP_REQUEST_TIMEOUT_MS.toString()
);
const parsed = Number(process.env.HF_SANDBOX_AGENT_ACP_REQUEST_TIMEOUT_MS ?? DaytonaProvider.DEFAULT_ACP_REQUEST_TIMEOUT_MS.toString());
if (!Number.isFinite(parsed) || parsed <= 0) {
return DaytonaProvider.DEFAULT_ACP_REQUEST_TIMEOUT_MS;
}
@ -117,7 +114,7 @@ export class DaytonaProvider implements SandboxProvider {
throw new Error(
"daytona provider is not configured: missing apiKey. " +
"Set HF_DAYTONA_API_KEY (or DAYTONA_API_KEY). " +
"Optionally set HF_DAYTONA_ENDPOINT (or DAYTONA_ENDPOINT)."
"Optionally set HF_DAYTONA_ENDPOINT (or DAYTONA_ENDPOINT).",
);
}
@ -154,20 +151,14 @@ export class DaytonaProvider implements SandboxProvider {
return Image.base(this.config.image).runCommands(
"apt-get update && apt-get install -y curl ca-certificates git openssh-client nodejs npm",
`curl -fsSL https://releases.rivet.dev/sandbox-agent/${DaytonaProvider.SANDBOX_AGENT_VERSION}/install.sh | sh`,
`bash -lc 'export PATH="$HOME/.local/bin:$PATH"; sandbox-agent install-agent codex || true; sandbox-agent install-agent claude || true'`
`bash -lc 'export PATH="$HOME/.local/bin:$PATH"; sandbox-agent install-agent codex || true; sandbox-agent install-agent claude || true'`,
);
}
private async runCheckedCommand(
sandboxId: string,
command: string,
label: string
): Promise<void> {
private async runCheckedCommand(sandboxId: string, command: string, label: string): Promise<void> {
const client = this.requireClient();
const result = await this.withTimeout(`execute command (${label})`, () =>
client.executeCommand(sandboxId, command)
);
const result = await this.withTimeout(`execute command (${label})`, () => client.executeCommand(sandboxId, command));
if (result.exitCode !== 0) {
throw new Error(`daytona ${label} failed (${result.exitCode}): ${result.result}`);
}
@ -180,7 +171,7 @@ export class DaytonaProvider implements SandboxProvider {
capabilities(): ProviderCapabilities {
return {
remote: true,
supportsSessionReuse: true
supportsSessionReuse: true,
};
}
@ -196,7 +187,7 @@ export class DaytonaProvider implements SandboxProvider {
workspaceId: req.workspaceId,
repoId: req.repoId,
handoffId: req.handoffId,
branchName: req.branchName
branchName: req.branchName,
});
const createStartedAt = Date.now();
@ -212,12 +203,12 @@ export class DaytonaProvider implements SandboxProvider {
"openhandoff.branch": req.branchName,
},
autoStopInterval: this.config.autoStopInterval,
})
}),
);
emitDebug("daytona.createSandbox.created", {
sandboxId: sandbox.id,
durationMs: Date.now() - createStartedAt,
state: sandbox.state ?? null
state: sandbox.state ?? null,
});
const repoDir = `/home/daytona/openhandoff/${req.workspaceId}/${req.repoId}/${req.handoffId}/repo`;
@ -229,13 +220,13 @@ export class DaytonaProvider implements SandboxProvider {
[
"bash",
"-lc",
`'set -euo pipefail; export DEBIAN_FRONTEND=noninteractive; if command -v git >/dev/null 2>&1 && command -v npx >/dev/null 2>&1; then exit 0; fi; apt-get update -y >/tmp/apt-update.log 2>&1; apt-get install -y git openssh-client ca-certificates nodejs npm >/tmp/apt-install.log 2>&1'`
`'set -euo pipefail; export DEBIAN_FRONTEND=noninteractive; if command -v git >/dev/null 2>&1 && command -v npx >/dev/null 2>&1; then exit 0; fi; apt-get update -y >/tmp/apt-update.log 2>&1; apt-get install -y git openssh-client ca-certificates nodejs npm >/tmp/apt-install.log 2>&1'`,
].join(" "),
"install git + node toolchain"
"install git + node toolchain",
);
emitDebug("daytona.createSandbox.install_toolchain.done", {
sandboxId: sandbox.id,
durationMs: Date.now() - installStartedAt
durationMs: Date.now() - installStartedAt,
});
const cloneStartedAt = Date.now();
@ -260,14 +251,14 @@ export class DaytonaProvider implements SandboxProvider {
`if git show-ref --verify --quiet "refs/remotes/origin/${req.branchName}"; then git checkout -B "${req.branchName}" "origin/${req.branchName}"; else git checkout -B "${req.branchName}" "$(git branch --show-current 2>/dev/null || echo main)"; fi`,
`git config user.email "openhandoff@local" >/dev/null 2>&1 || true`,
`git config user.name "OpenHandoff" >/dev/null 2>&1 || true`,
].join("; ")
)}`
].join("; "),
)}`,
].join(" "),
"clone repo"
"clone repo",
);
emitDebug("daytona.createSandbox.clone_repo.done", {
sandboxId: sandbox.id,
durationMs: Date.now() - cloneStartedAt
durationMs: Date.now() - cloneStartedAt,
});
return {
@ -280,7 +271,7 @@ export class DaytonaProvider implements SandboxProvider {
remote: true,
state: sandbox.state ?? null,
cwd: repoDir,
}
},
};
}
@ -290,17 +281,12 @@ export class DaytonaProvider implements SandboxProvider {
await this.ensureStarted(req.sandboxId);
// Reconstruct cwd from sandbox labels written at create time.
const info = await this.withTimeout("resume get sandbox", () =>
client.getSandbox(req.sandboxId)
);
const info = await this.withTimeout("resume get sandbox", () => client.getSandbox(req.sandboxId));
const labels = info.labels ?? {};
const workspaceId = labels["openhandoff.workspace"] ?? req.workspaceId;
const repoId = labels["openhandoff.repo_id"] ?? "";
const handoffId = labels["openhandoff.handoff"] ?? "";
const cwd =
repoId && handoffId
? `/home/daytona/openhandoff/${workspaceId}/${repoId}/${handoffId}/repo`
: null;
const cwd = repoId && handoffId ? `/home/daytona/openhandoff/${workspaceId}/${repoId}/${handoffId}/repo` : null;
return {
sandboxId: req.sandboxId,
@ -309,7 +295,7 @@ export class DaytonaProvider implements SandboxProvider {
resumed: true,
endpoint: this.config.endpoint ?? null,
...(cwd ? { cwd } : {}),
}
},
};
}
@ -359,9 +345,9 @@ export class DaytonaProvider implements SandboxProvider {
[
"bash",
"-lc",
`'set -euo pipefail; if command -v curl >/dev/null 2>&1; then exit 0; fi; export DEBIAN_FRONTEND=noninteractive; apt-get update -y >/tmp/apt-update.log 2>&1; apt-get install -y curl ca-certificates >/tmp/apt-install.log 2>&1'`
`'set -euo pipefail; if command -v curl >/dev/null 2>&1; then exit 0; fi; export DEBIAN_FRONTEND=noninteractive; apt-get update -y >/tmp/apt-update.log 2>&1; apt-get install -y curl ca-certificates >/tmp/apt-install.log 2>&1'`,
].join(" "),
"install curl"
"install curl",
);
await this.runCheckedCommand(
@ -369,9 +355,9 @@ export class DaytonaProvider implements SandboxProvider {
[
"bash",
"-lc",
`'set -euo pipefail; if command -v npx >/dev/null 2>&1; then exit 0; fi; export DEBIAN_FRONTEND=noninteractive; apt-get update -y >/tmp/apt-update.log 2>&1; apt-get install -y nodejs npm >/tmp/apt-install.log 2>&1'`
`'set -euo pipefail; if command -v npx >/dev/null 2>&1; then exit 0; fi; export DEBIAN_FRONTEND=noninteractive; apt-get update -y >/tmp/apt-update.log 2>&1; apt-get install -y nodejs npm >/tmp/apt-install.log 2>&1'`,
].join(" "),
"install node toolchain"
"install node toolchain",
);
await this.runCheckedCommand(
@ -379,9 +365,9 @@ export class DaytonaProvider implements SandboxProvider {
[
"bash",
"-lc",
`'set -euo pipefail; export PATH="$HOME/.local/bin:$PATH"; if sandbox-agent --version 2>/dev/null | grep -q "${DaytonaProvider.SANDBOX_AGENT_VERSION}"; then exit 0; fi; curl -fsSL https://releases.rivet.dev/sandbox-agent/${DaytonaProvider.SANDBOX_AGENT_VERSION}/install.sh | sh'`
`'set -euo pipefail; export PATH="$HOME/.local/bin:$PATH"; if sandbox-agent --version 2>/dev/null | grep -q "${DaytonaProvider.SANDBOX_AGENT_VERSION}"; then exit 0; fi; curl -fsSL https://releases.rivet.dev/sandbox-agent/${DaytonaProvider.SANDBOX_AGENT_VERSION}/install.sh | sh'`,
].join(" "),
"install sandbox-agent"
"install sandbox-agent",
);
for (const agentId of DaytonaProvider.AGENT_IDS) {
@ -389,7 +375,7 @@ export class DaytonaProvider implements SandboxProvider {
await this.runCheckedCommand(
req.sandboxId,
["bash", "-lc", `'export PATH="$HOME/.local/bin:$PATH"; sandbox-agent install-agent ${agentId}'`].join(" "),
`install agent ${agentId}`
`install agent ${agentId}`,
);
} catch {
// Some sandbox-agent builds may not ship every agent plugin; treat this as best-effort.
@ -401,9 +387,9 @@ export class DaytonaProvider implements SandboxProvider {
[
"bash",
"-lc",
`'set -euo pipefail; export PATH="$HOME/.local/bin:$PATH"; command -v sandbox-agent >/dev/null 2>&1; if pgrep -x sandbox-agent >/dev/null; then exit 0; fi; nohup env SANDBOX_AGENT_ACP_REQUEST_TIMEOUT_MS=${acpRequestTimeoutMs} sandbox-agent server --no-token --host 0.0.0.0 --port ${DaytonaProvider.SANDBOX_AGENT_PORT} >/tmp/sandbox-agent.log 2>&1 &'`
`'set -euo pipefail; export PATH="$HOME/.local/bin:$PATH"; command -v sandbox-agent >/dev/null 2>&1; if pgrep -x sandbox-agent >/dev/null; then exit 0; fi; nohup env SANDBOX_AGENT_ACP_REQUEST_TIMEOUT_MS=${acpRequestTimeoutMs} sandbox-agent server --no-token --host 0.0.0.0 --port ${DaytonaProvider.SANDBOX_AGENT_PORT} >/tmp/sandbox-agent.log 2>&1 &'`,
].join(" "),
"start sandbox-agent"
"start sandbox-agent",
);
await this.runCheckedCommand(
@ -411,18 +397,16 @@ export class DaytonaProvider implements SandboxProvider {
[
"bash",
"-lc",
`'for i in $(seq 1 45); do curl -fsS "http://127.0.0.1:${DaytonaProvider.SANDBOX_AGENT_PORT}/v1/health" >/dev/null && exit 0; sleep 1; done; echo "sandbox-agent failed to become healthy" >&2; tail -n 80 /tmp/sandbox-agent.log >&2; exit 1'`
`'for i in $(seq 1 45); do curl -fsS "http://127.0.0.1:${DaytonaProvider.SANDBOX_AGENT_PORT}/v1/health" >/dev/null && exit 0; sleep 1; done; echo "sandbox-agent failed to become healthy" >&2; tail -n 80 /tmp/sandbox-agent.log >&2; exit 1'`,
].join(" "),
"wait for sandbox-agent health"
"wait for sandbox-agent health",
);
const preview = await this.withTimeout("get preview endpoint", () =>
client.getPreviewEndpoint(req.sandboxId, DaytonaProvider.SANDBOX_AGENT_PORT)
);
const preview = await this.withTimeout("get preview endpoint", () => client.getPreviewEndpoint(req.sandboxId, DaytonaProvider.SANDBOX_AGENT_PORT));
return {
endpoint: preview.url,
token: preview.token
token: preview.token,
};
}
@ -436,9 +420,7 @@ export class DaytonaProvider implements SandboxProvider {
}
try {
const sandbox = await this.withTimeout("health get sandbox", () =>
client.getSandbox(req.sandboxId)
);
const sandbox = await this.withTimeout("health get sandbox", () => client.getSandbox(req.sandboxId));
const state = String(sandbox.state ?? "unknown");
if (state.toLowerCase().includes("error")) {
return {
@ -461,15 +443,13 @@ export class DaytonaProvider implements SandboxProvider {
async attachTarget(req: AttachTargetRequest): Promise<AttachTarget> {
return {
target: `daytona://${req.sandboxId}`
target: `daytona://${req.sandboxId}`,
};
}
async executeCommand(req: ExecuteSandboxCommandRequest): Promise<ExecuteSandboxCommandResult> {
const client = this.requireClient();
await this.ensureStarted(req.sandboxId);
return await this.withTimeout(`execute command (${req.label ?? "command"})`, () =>
client.executeCommand(req.sandboxId, req.command)
);
return await this.withTimeout(`execute command (${req.label ?? "command"})`, () => client.executeCommand(req.sandboxId, req.command));
}
}

View file

@ -42,19 +42,25 @@ export function createProviderRegistry(config: AppConfig, driver?: BackendDriver
},
};
const local = new LocalProvider({
rootDir: config.providers.local.rootDir,
sandboxAgentPort: config.providers.local.sandboxAgentPort,
}, gitDriver);
const daytona = new DaytonaProvider({
endpoint: config.providers.daytona.endpoint,
apiKey: config.providers.daytona.apiKey,
image: config.providers.daytona.image
}, driver?.daytona);
const local = new LocalProvider(
{
rootDir: config.providers.local.rootDir,
sandboxAgentPort: config.providers.local.sandboxAgentPort,
},
gitDriver,
);
const daytona = new DaytonaProvider(
{
endpoint: config.providers.daytona.endpoint,
apiKey: config.providers.daytona.apiKey,
image: config.providers.daytona.image,
},
driver?.daytona,
);
const map: Record<ProviderId, SandboxProvider> = {
local,
daytona
daytona,
};
return {
@ -66,6 +72,6 @@ export function createProviderRegistry(config: AppConfig, driver?: BackendDriver
},
defaultProviderId(): ProviderId {
return config.providers.daytona.apiKey ? "daytona" : "local";
}
},
};
}

View file

@ -44,13 +44,7 @@ function expandHome(value: string): string {
async function branchExists(repoPath: string, branchName: string): Promise<boolean> {
try {
await execFileAsync("git", [
"-C",
repoPath,
"show-ref",
"--verify",
`refs/remotes/origin/${branchName}`,
]);
await execFileAsync("git", ["-C", repoPath, "show-ref", "--verify", `refs/remotes/origin/${branchName}`]);
return true;
} catch {
return false;
@ -59,9 +53,7 @@ async function branchExists(repoPath: string, branchName: string): Promise<boole
async function checkoutBranch(repoPath: string, branchName: string, git: GitDriver): Promise<void> {
await git.fetch(repoPath);
const targetRef = (await branchExists(repoPath, branchName))
? `origin/${branchName}`
: await git.remoteDefaultBaseRef(repoPath);
const targetRef = (await branchExists(repoPath, branchName)) ? `origin/${branchName}` : await git.remoteDefaultBaseRef(repoPath);
await execFileAsync("git", ["-C", repoPath, "checkout", "-B", branchName, targetRef], {
env: process.env as Record<string, string>,
});
@ -76,9 +68,7 @@ export class LocalProvider implements SandboxProvider {
) {}
private rootDir(): string {
return expandHome(
this.config.rootDir?.trim() || "~/.local/share/openhandoff/local-sandboxes",
);
return expandHome(this.config.rootDir?.trim() || "~/.local/share/openhandoff/local-sandboxes");
}
private sandboxRoot(workspaceId: string, sandboxId: string): string {
@ -89,11 +79,7 @@ export class LocalProvider implements SandboxProvider {
return resolve(this.sandboxRoot(workspaceId, sandboxId), "repo");
}
private sandboxHandle(
workspaceId: string,
sandboxId: string,
repoDir: string,
): SandboxHandle {
private sandboxHandle(workspaceId: string, sandboxId: string, repoDir: string): SandboxHandle {
return {
sandboxId,
switchTarget: `local://${repoDir}`,
@ -242,9 +228,7 @@ export class LocalProvider implements SandboxProvider {
const detail = error as { stdout?: string; stderr?: string; code?: number };
return {
exitCode: typeof detail.code === "number" ? detail.code : 1,
result: [detail.stdout, detail.stderr, error instanceof Error ? error.message : String(error)]
.filter(Boolean)
.join(""),
result: [detail.stdout, detail.stderr, error instanceof Error ? error.message : String(error)].filter(Boolean).join(""),
};
}
}

View file

@ -39,13 +39,14 @@ export function deriveFallbackTitle(task: string, explicitTitle?: string): strin
const lowered = source.toLowerCase();
const typePrefix = lowered.includes("fix") || lowered.includes("bug")
? "fix"
: lowered.includes("doc") || lowered.includes("readme")
? "docs"
: lowered.includes("refactor")
? "refactor"
: "feat";
const typePrefix =
lowered.includes("fix") || lowered.includes("bug")
? "fix"
: lowered.includes("doc") || lowered.includes("readme")
? "docs"
: lowered.includes("refactor")
? "refactor"
: "feat";
const cleaned = source
.split("")
@ -88,9 +89,7 @@ export function sanitizeBranchName(input: string): string {
return trimmed.slice(0, 50).replace(/-+$/g, "");
}
export function resolveCreateFlowDecision(
input: ResolveCreateFlowDecisionInput
): ResolveCreateFlowDecisionResult {
export function resolveCreateFlowDecision(input: ResolveCreateFlowDecisionInput): ResolveCreateFlowDecisionResult {
const explicitBranch = input.explicitBranchName?.trim();
const title = deriveFallbackTitle(input.task, input.explicitTitle);
const generatedBase = sanitizeBranchName(title) || "handoff";
@ -98,16 +97,11 @@ export function resolveCreateFlowDecision(
const branchBase = explicitBranch && explicitBranch.length > 0 ? explicitBranch : generatedBase;
const existingBranches = new Set(input.localBranches.map((value) => value.trim()).filter((value) => value.length > 0));
const existingHandoffBranches = new Set(
input.handoffBranches.map((value) => value.trim()).filter((value) => value.length > 0)
);
const conflicts = (name: string): boolean =>
existingBranches.has(name) || existingHandoffBranches.has(name);
const existingHandoffBranches = new Set(input.handoffBranches.map((value) => value.trim()).filter((value) => value.length > 0));
const conflicts = (name: string): boolean => existingBranches.has(name) || existingHandoffBranches.has(name);
if (explicitBranch && conflicts(branchBase)) {
throw new Error(
`Branch '${branchBase}' already exists. Choose a different --name/--branch value.`
);
throw new Error(`Branch '${branchBase}' already exists. Choose a different --name/--branch value.`);
}
if (explicitBranch) {
@ -123,6 +117,6 @@ export function resolveCreateFlowDecision(
return {
title,
branchName: candidate
branchName: candidate,
};
}

View file

@ -15,11 +15,6 @@ export function openhandoffDataDir(config: AppConfig): string {
return resolve(dirname(dbPath));
}
export function openhandoffRepoClonePath(
config: AppConfig,
workspaceId: string,
repoId: string
): string {
export function openhandoffRepoClonePath(config: AppConfig, workspaceId: string, repoId: string): string {
return resolve(join(openhandoffDataDir(config), "repos", workspaceId, repoId));
}

Some files were not shown because too many files have changed in this diff Show more