Skip to content

Run Goose CLI Headlessly in Daytona and Stream Its Output

View as Markdown

This guide demonstrates how to run Goose, the open source AI agent, as a headless coding agent inside a Daytona sandbox. The agent can write code in any language, install dependencies, run scripts, and start web servers you can open in your browser, all inside a secure, isolated, disposable sandbox while its output streams back to your terminal in real time.


When you launch the main module, a Daytona sandbox is created and the Goose CLI is installed inside it. The agent is driven headlessly with goose run --output-format stream-json --text "<prompt>", and its newline-delimited JSON events are parsed and printed as the agent works.

You interact with the main program via a command line chat interface. The program sends your prompts to the Goose CLI inside the sandbox, which writes code, runs commands, and streams the results back as it works. A Thinking... line marks the start of each turn, each tool call surfaces as a [tool] line with what it acts on, such as a command or a file, and the assistant’s response streams in as Goose writes it.

Once a turn completes, later turns resume the same Goose session, keeping context across the conversation. When a task needs a running server, Goose writes the start command to a script instead of running it, and the program starts that server in the background and exposes it through a Daytona preview link. You can continue interacting with your agent until you are finished. When you exit the program, the sandbox is deleted automatically.

First, clone the daytona repository and navigate to the example directory:

Terminal window
git clone https://github.com/daytona/guides.git
cd guides/typescript/goose/goose-cli

Get your API keys:

Copy .env.example to .env and add your keys:

Terminal window
DAYTONA_API_KEY=your_daytona_key
SANDBOX_OPENAI_API_KEY=your_openai_key

Alternative: Inject the Key as a Daytona Secret

Section titled “Alternative: Inject the Key as a Daytona Secret”

The default setup passes the OpenAI key into the sandbox as a plain environment variable, so anything running inside the sandbox - including the agent itself - can read the raw key with env. Daytona Secrets keep the raw value out of the sandbox entirely: the environment variable holds only an opaque placeholder (dtn_secret_<id>), and Daytona’s outbound proxy substitutes the real value into HTTPS request headers at egress - and only for requests to the hosts the Secret allows. An agent that dumps the environment or exfiltrates it never sees a usable key.

The Secret-based flow uses daytona.v0 from the @daytona/sdk version this guide pins and needs a one-time Secret setup:

  1. Create the Secret once for your organization - in the Daytona Dashboard or with a one-off script (save as create-secret.ts next to this guide’s .env and run npx tsx create-secret.ts):

    import { Daytona } from '@daytona/sdk'
    import * as dotenv from 'dotenv'
    dotenv.config()
    async function main() {
    const value = process.env.SANDBOX_OPENAI_API_KEY
    if (!value) throw new Error('SANDBOX_OPENAI_API_KEY is not set')
    const daytona = new Daytona()
    await daytona.v0.secret.create({
    name: 'openai-api-key',
    value,
    hosts: ['api.openai.com'], // the only host the real key may be sent to
    })
    }
    main()
  2. In src/index.ts, swap the OPENAI_API_KEY env var for a secrets: mapping (environment variable name to Secret name). The other GOOSE_* variables carry no credentials and stay plain env vars:

    sandbox = await daytona.v0.create({
    envVars: {
    OPENAI_API_KEY: process.env.SANDBOX_OPENAI_API_KEY,
    GOOSE_PROVIDER: 'openai',
    GOOSE_MODEL: 'gpt-4o',
    GOOSE_MODE: 'auto',
    GOOSE_DISABLE_KEYRING: '1',
    },
    secrets: {
    OPENAI_API_KEY: 'openai-api-key',
    },
    })

Inside the sandbox, env now shows OPENAI_API_KEY=dtn_secret_..., yet Goose still authenticates: it sends the key as the Authorization HTTPS request header to api.openai.com, where the proxy swaps in the real value. Substitution happens only in HTTPS request headers toward allowed hosts - requests to any other host carry the harmless placeholder. See the Secrets documentation for the full substitution scope.

Install dependencies:

Terminal window
npm install

Run the agent:

Terminal window
npm run start

The agent will start and wait for your prompt.

Ask the agent to write and run some code, then to serve a page. Here it writes and runs a Python script, answers a follow-up question from the same session, and starts a web server that it links through a preview URL:

$ npm run start
Creating sandbox...
Installing Goose CLI...
Starting Goose CLI...
Agent ready. Press Ctrl+C at any time to exit.
User: Write a Python script fib.py that prints the first 10 Fibonacci numbers on one line, run it, and show me the output
Thinking...
[tool] write: /home/daytona/fib.py
[tool] shell: python3 /home/daytona/fib.py
Here is the output of the first 10 Fibonacci numbers on one line:
```
0 1 1 2 3 5 8 13 21 34
```
User: What was the last number fib.py printed? Answer in one short sentence.
Thinking...
The last number printed by `fib.py` was 34.
User: Create an index.html that says Hello from Goose on Daytona and serve the current directory with Python's http.server on port 8000
Thinking...
[tool] write: /home/daytona/index.html
[tool] write: /home/daytona/start.sh
The `index.html` file has been created, and the server is set to run on port 8000. You can view it [here](https://8000-<sandbox-id>.daytonaproxy01.net).
Running `python3 -m http.server 8000` via session command...
User:

This example consists of two parts: a main program (src/index.ts) that manages the sandbox, server startup, and a command-line loop, and a session class (src/session.ts) that drives the Goose CLI over a PTY and parses its streaming JSON output.

On startup, the script:

  1. Creates a new Daytona sandbox with the OpenAI API key and Goose’s provider settings injected as environment variables.
  2. Installs the Goose CLI in the sandbox with the official install script.
  3. Builds a Daytona-aware system prompt with the sandbox’s preview URL pattern.
  4. Creates a PTY for streaming output from the Goose CLI.
  5. Enters a readline loop to send prompts, receive streamed responses, and start any server Goose asked for.
  6. On Ctrl+C or Ctrl+D, kills the PTY session, deletes the server sessions and the sandbox, and exits.

A fresh sandbox has no Goose configuration, and without one goose run would fall back to an interactive setup wizard that can’t be answered headlessly. Passing the OpenAI key, GOOSE_PROVIDER, and GOOSE_MODEL as sandbox environment variables at create time configures Goose non-interactively. GOOSE_MODE=auto approves tool calls automatically so a turn never blocks on a confirmation prompt, and GOOSE_DISABLE_KEYRING makes Goose store secrets in a file instead of a desktop keyring the sandbox doesn’t have:

sandbox = await daytona.v0.create({
envVars: {
OPENAI_API_KEY: process.env.SANDBOX_OPENAI_API_KEY,
GOOSE_PROVIDER: 'openai',
GOOSE_MODEL: 'gpt-4o',
GOOSE_MODE: 'auto',
GOOSE_DISABLE_KEYRING: '1',
},
})

The install script runs with CONFIGURE=false, which skips its own interactive goose configure step. Piping the script into bash would hide a failed download, so the trailing goose --version makes the command fail when Goose isn’t actually installed:

const install = await activeSandbox.process.executeCommand(
'curl -fsSL https://github.com/aaif-goose/goose/releases/download/stable/download_cli.sh | CONFIGURE=false bash && $HOME/.local/bin/goose --version',
)
if (install.exitCode !== 0) {
throw new Error('Error installing Goose CLI: ' + install.result)
}

The session uses a pseudo-terminal (PTY) for streaming output from the Goose CLI. The installer puts Goose in ~/.local/bin, so the PTY’s shell adds it to PATH once, for every turn that follows:

async initialize(options?: { systemPrompt?: string }): Promise<void> {
this.ptyHandle = await this.sandbox.process.createPty({
id: `goose-pty-${Date.now()}`,
cols: 120,
rows: 30,
onData: (data: Uint8Array) => this.handleData(data),
})
await this.ptyHandle.waitForConnection()
await this.ptyHandle.sendInput('export PATH="$HOME/.local/bin:$PATH"\n')
if (options?.systemPrompt?.trim()) {
this.systemPrompt = options.systemPrompt.trim()
}
}

Each prompt is sent as a goose run command. --text passes the prompt, and --output-format stream-json emits newline-delimited JSON events. Until a turn completes, each turn starts a new Goose session and passes the Daytona-aware system prompt with --system. Goose stores the system prompt with the session, so once a turn completes, later turns only add --resume to continue the most recent session.

After goose run, the shell prints Goose’s exit code as one more JSON line (goose_exit), however Goose exits. The turn ends on that line, so it can’t hang when Goose exits without reporting an outcome, for example on a setup error it prints as plain text. The completion handler is registered before the command is sent, so a fast turn can’t finish before anything is listening for it. Goose takes a few seconds to start and reach the model, so each turn first prints Thinking...:

async processPrompt(prompt: string): Promise<void> {
const flags = ['run', '--output-format', 'stream-json', '--text', this.shellQuote(prompt)]
if (this.resumable) {
// Goose resumes the most recent session; there is no ID to pass explicitly.
flags.push('--resume')
} else if (this.systemPrompt) {
flags.push('--system', this.shellQuote(this.systemPrompt))
}
const command = ['goose', ...flags].join(' ')
this.turnEnded = false
const turnDone = new Promise<void>((resolve) => {
this.onResponseComplete = resolve
})
this.atLineStart = true
this.writeLine('Thinking...')
await this.ptyHandle!.sendInput(`cd ${WORK_DIR} && ${command}; printf '{"type":"goose_exit","code":%d}\\n' $?\n`)
await turnDone
}

The Goose CLI outputs JSON lines that are parsed to track agent activity. The handleData method buffers incoming PTY bytes and processes each complete line, keeping any incomplete line for the next chunk. A stateful TextDecoder is reused across calls so partial multi-byte UTF-8 sequences split across PTY chunks are preserved instead of being corrupted. Lines that aren’t JSON, such as the echoed command and Goose’s startup banner, are skipped. Errors in the event handler are reported rather than thrown, because an exception escaping the PTY callback would crash the program before it deletes the sandbox:

private decoder = new TextDecoder('utf-8')
private handleData(data: Uint8Array): void {
this.buffer += this.decoder.decode(data, { stream: true })
const lines = this.buffer.split('\n')
this.buffer = lines.pop() || ''
for (const line of lines.map((l) => l.trim()).filter(Boolean)) {
let event: GooseEvent
try {
event = JSON.parse(line) as GooseEvent
} catch {
debug('non-JSON line:', line)
continue
}
try {
this.handleEvent(event)
} catch (e) {
console.error('Error handling Goose event:', e)
}
}
}

Event types from the Goose CLI’s streaming JSON (output formats):

  • message: A conversation message. Assistant messages carry the reply text, streamed one chunk per event, and toolRequest blocks for tool calls. Tool results come back as toolResponse blocks in user messages.
  • notification: Log and progress updates from Goose extensions (not printed)
  • complete: Token usage for the finished turn - marks the turn as successful
  • error: The reason a turn failed, for example a rejected API key

The session adds one event of its own, goose_exit, printed by the shell with Goose’s exit code once goose run exits. It signals response completion.

Each tool call prints as one [tool] line with the argument that says what the call does: the command for shell, the file for write, edit, tree, and analyze, or the source for read_image and load. Other keys cover common extension tools, and a tool without any of them prints its name alone. A tool can fail before it runs, with an error status, or report the failure in its own result with isError. Both print as a [tool error] line:

const TOOL_DETAIL_KEYS = ['command', 'path', 'source', 'uri', 'extension_name', 'query', 'instructions']
function describeToolCall(name: string, args: Record<string, unknown> = {}): string {
const detail = TOOL_DETAIL_KEYS.map((key) => args[key]).find((value) => typeof value === 'string' && value.trim())
return typeof detail === 'string' ? `${name}: ${formatPreview(detail)}` : name
}
function toolError(block: GooseToolResponseBlock): string | null {
const result = block.toolResult
if (result.status === 'error') return result.error
if (!result.value.isError) return null
return result.value.content
.filter((part) => part.type === 'text' && part.text)
.map((part) => part.text)
.join('\n')
}
private handleEvent(event: GooseEvent): void {
switch (event.type) {
case 'message': {
const msg = (event as GooseMessageEvent).message
for (const block of msg.content) {
if (block.type === 'text' && msg.role === 'assistant') {
this.write(block.text)
} else if (block.type === 'toolRequest' && block.toolCall.status === 'success') {
this.writeLine(`[tool] ${describeToolCall(block.toolCall.value.name, block.toolCall.value.arguments)}`)
} else if (block.type === 'toolResponse') {
const error = toolError(block)
if (error) this.writeLine(`[tool error] ${error}`)
}
}
return
}
case 'complete': {
// The turn ran to completion, so later turns can --resume its session.
this.resumable = true
this.turnEnded = true
if (!this.atLineStart) this.write('\n')
return
}
case 'error': {
this.turnEnded = true
this.writeLine(`Failed: ${(event as GooseErrorEvent).error}`, process.stderr)
return
}
case 'goose_exit': {
if (!this.turnEnded) {
const code = (event as GooseExitEvent).code
this.writeLine(`Failed: goose exited with code ${code} (set DEBUG = true in src/session.ts to see its output)`, process.stderr)
}
this.onResponseComplete?.()
return
}
}
}

Reply text is written as it arrives, while status lines go through writeLine. The session tracks whether the cursor is at the start of a line, so a status line always starts on its own line, even right after a streamed sentence, without leaving blank lines between consecutive tool calls:

private write(text: string, stream: NodeJS.WriteStream = process.stdout): void {
if (!text) return
stream.write(text)
this.atLineStart = text.endsWith('\n')
}
private writeLine(line: string, stream: NodeJS.WriteStream = process.stdout): void {
this.write(`${this.atLineStart ? '' : '\n'}${line}\n`, stream)
}

When the goose_exit line arrives, onResponseComplete resolves the promise that processPrompt is awaiting, so the readline loop can prompt for the next turn.

goose run blocks until its turn finishes, so a dev server started inside a turn would never let that turn, or the prompt loop, complete. Instead, the system prompt gives Goose the sandbox’s preview URL pattern and asks it to write the server start command to /home/daytona/start.sh:

const previewLink = await activeSandbox.getPreviewLink(1234)
const previewUrlPattern = previewLink.url.replace(/1234/, '{PORT}')
const defaultSystemPrompt = [
'You are running in a Daytona sandbox.',
`When running services on localhost, they will be accessible as: ${previewUrlPattern}`,
'When you need to start a server, DO NOT run it directly.',
'Instead, write only the server start command to /home/daytona/start.sh (one command, no markdown).',
'After writing the start command, provide the preview URL to the user.',
].join(' ')

After each turn, the script moves start.sh aside, which both detects whether Goose wrote one and keeps the same server from starting again after a later turn. It then runs the script in its own Daytona session with runAsync: true, so the server keeps running in the background while the conversation continues:

const startServerFromScript = async () => {
const startScript = `/tmp/goose-start-${Date.now()}.sh`
const claim = await activeSandbox.process.executeCommand(`mv /home/daytona/start.sh ${startScript}`)
if (claim.exitCode !== 0) {
return
}
const startScriptContents = (await activeSandbox.fs.downloadFile(startScript)).toString('utf-8')
const clippedStartScript = formatPreview(startScriptContents)
console.log(`Running \`${clippedStartScript}\` via session command...`)
const sessionId = `goose-server-session-${Date.now()}`
await activeSandbox.process.createSession(sessionId)
serverSessions.push(sessionId)
await activeSandbox.process.executeSessionCommand(sessionId, {
command: `cd /home/daytona && bash ${startScript}`,
runAsync: true,
})
}
while (true) {
const prompt = await new Promise<string>((resolve) => rl.question('User: ', resolve))
if (prompt.trim()) {
await session.processPrompt(prompt)
await startServerFromScript()
}
}

Key advantages:

  • Secure, isolated execution in Daytona sandboxes
  • Fully headless operation, with no setup wizard and no permission prompts
  • Streaming JSON output (--output-format stream-json) for real-time tool and message activity
  • Readable progress: each tool call shows what it acts on, such as a command or a file
  • PTY-based communication for low-latency streaming
  • Session-based conversation continuity across prompts (--resume)
  • Servers start outside the agent’s turn and are reachable through preview links
  • All agent code execution happens inside the sandbox
  • Automatic cleanup on exit