Skip to content

Commit 37e1ef7

Browse files
committed
Fix: Add --attach flag to opencode run (Fixes anomalyco#3188)
1 parent d341d26 commit 37e1ef7

2 files changed

Lines changed: 239 additions & 0 deletions

File tree

‎packages/opencode/src/cli/cmd/run.ts‎

Lines changed: 228 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import { SessionPrompt } from "../../session/prompt"
1616
import { EOL } from "os"
1717
import { Permission } from "@/permission"
1818
import { select } from "@clack/prompts"
19+
import { createOpencodeClient } from "@opencode-ai/sdk"
1920

2021
const TOOL: Record<string, [string, string]> = {
2122
todowrite: ["Todo", UI.Style.TEXT_WARNING_BOLD],
@@ -84,6 +85,10 @@ export const RunCommand = cmd({
8485
type: "string",
8586
describe: "title for the session (uses truncated prompt if no value provided)",
8687
})
88+
.option("attach", {
89+
type: "string",
90+
describe: "attach to a running opencode server (e.g., http://localhost:4096)",
91+
})
8792
},
8893
handler: async (args) => {
8994
let message = args.message.join(" ")
@@ -124,6 +129,10 @@ export const RunCommand = cmd({
124129
process.exit(1)
125130
}
126131

132+
if (args.attach) {
133+
return await runAttached()
134+
}
135+
127136
await bootstrap(process.cwd(), async () => {
128137
if (args.command) {
129138
const exists = await Command.get(args.command)
@@ -335,5 +344,224 @@ export const RunCommand = cmd({
335344
})()
336345
if (errorMsg) process.exit(1)
337346
})
347+
348+
async function runAttached() {
349+
if (!args.attach) return
350+
351+
const sdk = createOpencodeClient({
352+
baseUrl: args.attach,
353+
})
354+
355+
const agentName = args.agent || "build"
356+
const modelName = args.model
357+
358+
const sessionID = await (async () => {
359+
if (args.continue) {
360+
const result = await sdk.session.list()
361+
if (result.data) {
362+
const parentSession = result.data.find((s) => !s.parentID)
363+
return parentSession?.id
364+
}
365+
return undefined
366+
}
367+
if (args.session) return args.session
368+
369+
const title = (() => {
370+
if (args.title !== undefined) {
371+
if (args.title === "") {
372+
return message.slice(0, 50) + (message.length > 50 ? "..." : "")
373+
}
374+
return args.title
375+
}
376+
return undefined
377+
})()
378+
379+
const result = await sdk.session.create({
380+
body: title ? { title } : {},
381+
})
382+
return result.data?.id
383+
})()
384+
385+
if (!sessionID) {
386+
UI.error("Session not found")
387+
process.exit(1)
388+
}
389+
390+
const cfgResult = await sdk.config.get()
391+
const cfg = cfgResult.data
392+
if (cfg && (cfg.share === "auto" || Flag.OPENCODE_AUTO_SHARE || args.share)) {
393+
try {
394+
await sdk.session.share({ path: { id: sessionID } })
395+
UI.println(UI.Style.TEXT_INFO_BOLD + "~ https://opencode.ai/s/" + sessionID.slice(-8))
396+
} catch (error) {
397+
if (error instanceof Error && error.message.includes("disabled")) {
398+
UI.println(UI.Style.TEXT_DANGER_BOLD + "! " + error.message)
399+
} else {
400+
throw error
401+
}
402+
}
403+
}
404+
405+
function printEvent(color: string, type: string, title: string) {
406+
UI.println(
407+
color + `|`,
408+
UI.Style.TEXT_NORMAL + UI.Style.TEXT_DIM + ` ${type.padEnd(7, " ")}`,
409+
"",
410+
UI.Style.TEXT_NORMAL + title,
411+
)
412+
}
413+
414+
function outputJsonEvent(type: string, data: any) {
415+
if (args.format === "json") {
416+
const jsonEvent = {
417+
type,
418+
timestamp: Date.now(),
419+
sessionID,
420+
...data,
421+
}
422+
process.stdout.write(JSON.stringify(jsonEvent) + EOL)
423+
return true
424+
}
425+
return false
426+
}
427+
428+
const events = await sdk.event.subscribe()
429+
let errorMsg: string | undefined
430+
let isSessionComplete = false
431+
432+
const eventProcessor = (async () => {
433+
for await (const event of events.stream) {
434+
if (event.type === "message.part.updated") {
435+
const part = event.properties.part
436+
if (part.sessionID !== sessionID) continue
437+
438+
if (part.type === "tool" && part.state.status === "completed") {
439+
if (outputJsonEvent("tool_use", { part })) continue
440+
const [tool, color] = TOOL[part.tool] ?? [part.tool, UI.Style.TEXT_INFO_BOLD]
441+
const title =
442+
part.state.title ||
443+
(Object.keys(part.state.input).length > 0
444+
? JSON.stringify(part.state.input)
445+
: "Unknown")
446+
447+
printEvent(color, tool, title)
448+
449+
if (part.tool === "bash" && part.state.output && part.state.output.trim()) {
450+
UI.println()
451+
UI.println(part.state.output)
452+
}
453+
}
454+
455+
if (part.type === "step-start") {
456+
if (outputJsonEvent("step_start", { part })) continue
457+
}
458+
459+
if (part.type === "step-finish") {
460+
if (outputJsonEvent("step_finish", { part })) continue
461+
}
462+
463+
if (part.type === "text") {
464+
const text = part.text
465+
const isPiped = !process.stdout.isTTY
466+
467+
if (part.time?.end) {
468+
if (outputJsonEvent("text", { part })) continue
469+
if (!isPiped) UI.println()
470+
process.stdout.write((isPiped ? text : UI.markdown(text)) + EOL)
471+
if (!isPiped) UI.println()
472+
}
473+
}
474+
}
475+
476+
if (event.type === "session.error") {
477+
const props = event.properties
478+
if (props.sessionID !== sessionID) continue
479+
const error = props.error
480+
if (!error) continue
481+
let err = String(error.name)
482+
483+
if ("data" in error && error.data && "message" in error.data) {
484+
err = String(error.data.message)
485+
}
486+
errorMsg = errorMsg ? errorMsg + EOL + err : err
487+
488+
if (outputJsonEvent("error", { error })) continue
489+
UI.error(err)
490+
}
491+
492+
if (event.type === "session.idle") {
493+
if (event.properties.sessionID === sessionID) {
494+
isSessionComplete = true
495+
break
496+
}
497+
}
498+
499+
if (event.type === "permission.updated") {
500+
const permission = event.properties
501+
if (permission.sessionID !== sessionID) continue
502+
const permMessage = `Permission required to run: ${permission.title}`
503+
504+
const result = await select({
505+
message: permMessage,
506+
options: [
507+
{ value: "once", label: "Allow once" },
508+
{ value: "always", label: "Always allow" },
509+
{ value: "reject", label: "Reject" },
510+
],
511+
initialValue: "once",
512+
}).catch(() => "reject")
513+
const response = (result.toString().includes("cancel") ? "reject" : result) as
514+
| "once"
515+
| "always"
516+
| "reject"
517+
518+
await sdk.postSessionIdPermissionsPermissionId({
519+
path: {
520+
id: sessionID,
521+
permissionID: permission.id,
522+
},
523+
body: { response },
524+
})
525+
}
526+
}
527+
})()
528+
529+
if (args.command) {
530+
await sdk.session.command({
531+
path: { id: sessionID },
532+
body: {
533+
agent: agentName,
534+
model: modelName,
535+
command: args.command,
536+
arguments: message,
537+
},
538+
})
539+
} else {
540+
const modelParam = modelName
541+
? (() => {
542+
const [providerID, modelID] = modelName.split("/")
543+
return { providerID, modelID }
544+
})()
545+
: undefined
546+
547+
await sdk.session.prompt({
548+
path: { id: sessionID },
549+
body: {
550+
agent: agentName,
551+
model: modelParam,
552+
parts: [
553+
...fileParts,
554+
{
555+
type: "text",
556+
text: message,
557+
},
558+
],
559+
},
560+
})
561+
}
562+
563+
await eventProcessor
564+
if (errorMsg) process.exit(1)
565+
}
338566
},
339567
})

‎packages/web/src/content/docs/cli.mdx‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,16 @@ This is useful for scripting, automation, or when you want a quick answer withou
184184
opencode run Explain the use of context in Go
185185
```
186186

187+
You can also attach to a running `opencode serve` instance to avoid MCP server cold boot times on every run:
188+
189+
```bash
190+
# Start a headless server in one terminal
191+
opencode serve
192+
193+
# In another terminal, run commands that attach to it
194+
opencode run --attach http://localhost:4096 "Explain async/await in JavaScript"
195+
```
196+
187197
#### Flags
188198

189199
| Flag | Short | Description |
@@ -197,6 +207,7 @@ opencode run Explain the use of context in Go
197207
| `--file` | `-f` | File(s) to attach to message |
198208
| `--format` | | Format: default (formatted) or json (raw JSON events) |
199209
| `--title` | | Title for the session (uses truncated prompt if no value provided) |
210+
| `--attach` | | Attach to a running opencode server (e.g., http://localhost:4096) |
200211

201212
---
202213

0 commit comments

Comments
 (0)