Compare commits

..

1 Commits

Author SHA1 Message Date
Simon Klee 75666b271b opencode: lazy-load top-level CLI commands
The CLI imports every top-level command before argument parsing has
decided which handler will run. This makes simple invocations pay for
the full command graph up front and slows down the default startup path.

Parse the root argv first and load only the command module that matches
the selected top-level command. Keep falling back to the default TUI
path for non-command positionals, and preserve root help, version and
completion handling
2026-04-12 11:25:35 +02:00
9 changed files with 280 additions and 230 deletions
-1
View File
@@ -26,7 +26,6 @@ kommander
r44vc0rp
rekram1-node
-robinmordasiewicz
simonklee
-spider-yamet clawdbot/llm psychosis, spam pinging the team
thdxr
-toastythebot
+2 -1
View File
@@ -114,7 +114,7 @@ jobs:
- build-cli
- version
runs-on: blacksmith-4vcpu-windows-2025
if: github.repository == 'anomalyco/opencode'
if: github.repository == 'anomalyco/opencode' && github.ref_name != 'beta'
env:
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
@@ -591,6 +591,7 @@ jobs:
path: packages/opencode/dist
- uses: actions/download-artifact@v4
if: github.ref_name != 'beta'
with:
name: opencode-cli-signed-windows
path: packages/opencode/dist
@@ -31,16 +31,6 @@ import { batch, createEffect, on } from "solid-js"
import { Log } from "@/util/log"
import { ConsoleState, emptyConsoleState, type ConsoleState as ConsoleStateType } from "@/config/console-state"
type SessionDiffSummary = Pick<Snapshot.FileDiff, "file" | "additions" | "deletions">
function summarizeDiff(diff?: Snapshot.FileDiff[]): SessionDiffSummary[] {
return (diff ?? []).map((item) => ({
file: item.file,
additions: item.additions,
deletions: item.deletions,
}))
}
export const { use: useSync, provider: SyncProvider } = createSimpleContext({
name: "Sync",
init: () => {
@@ -65,7 +55,7 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({
[sessionID: string]: SessionStatus
}
session_diff: {
[sessionID: string]: SessionDiffSummary[]
[sessionID: string]: Snapshot.FileDiff[]
}
todo: {
[sessionID: string]: Todo[]
@@ -203,7 +193,7 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({
break
case "session.diff":
setStore("session_diff", event.properties.sessionID, summarizeDiff(event.properties.diff))
setStore("session_diff", event.properties.sessionID, event.properties.diff)
break
case "session.deleted": {
@@ -513,7 +503,7 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({
for (const message of messages.data!) {
draft.part[message.info.id] = message.parts
}
draft.session_diff[sessionID] = summarizeDiff(diff.data)
draft.session_diff[sessionID] = diff.data ?? []
}),
)
fullSyncedSessions.add(sessionID)
+244 -46
View File
@@ -1,40 +1,17 @@
import yargs from "yargs"
import { hideBin } from "yargs/helpers"
import { RunCommand } from "./cli/cmd/run"
import { GenerateCommand } from "./cli/cmd/generate"
import { Log } from "./util/log"
import { ConsoleCommand } from "./cli/cmd/account"
import { ProvidersCommand } from "./cli/cmd/providers"
import { AgentCommand } from "./cli/cmd/agent"
import { UpgradeCommand } from "./cli/cmd/upgrade"
import { UninstallCommand } from "./cli/cmd/uninstall"
import { ModelsCommand } from "./cli/cmd/models"
import { UI } from "./cli/ui"
import { Installation } from "./installation"
import { NamedError } from "@opencode-ai/util/error"
import { FormatError } from "./cli/error"
import { ServeCommand } from "./cli/cmd/serve"
import { Filesystem } from "./util/filesystem"
import { DebugCommand } from "./cli/cmd/debug"
import { StatsCommand } from "./cli/cmd/stats"
import { McpCommand } from "./cli/cmd/mcp"
import { GithubCommand } from "./cli/cmd/github"
import { ExportCommand } from "./cli/cmd/export"
import { ImportCommand } from "./cli/cmd/import"
import { AttachCommand } from "./cli/cmd/tui/attach"
import { TuiThreadCommand } from "./cli/cmd/tui/thread"
import { AcpCommand } from "./cli/cmd/acp"
import { EOL } from "os"
import { WebCommand } from "./cli/cmd/web"
import { PrCommand } from "./cli/cmd/pr"
import { SessionCommand } from "./cli/cmd/session"
import { DbCommand } from "./cli/cmd/db"
import path from "path"
import { Global } from "./global"
import { JsonMigration } from "./storage/json-migration"
import { Database } from "./storage/db"
import { errorMessage } from "./util/error"
import { PluginCommand } from "./cli/cmd/plug"
import { Heap } from "./cli/heap"
import { drizzle } from "drizzle-orm/bun-sqlite"
@@ -52,6 +29,156 @@ process.on("uncaughtException", (e) => {
const args = hideBin(process.argv)
type Mode =
| "all"
| "none"
| "tui"
| "attach"
| "run"
| "acp"
| "mcp"
| "generate"
| "debug"
| "console"
| "providers"
| "agent"
| "upgrade"
| "uninstall"
| "serve"
| "web"
| "models"
| "stats"
| "export"
| "import"
| "github"
| "pr"
| "session"
| "plugin"
| "db"
const map = new Map<string, Mode>([
["attach", "attach"],
["run", "run"],
["acp", "acp"],
["mcp", "mcp"],
["generate", "generate"],
["debug", "debug"],
["console", "console"],
["providers", "providers"],
["auth", "providers"],
["agent", "agent"],
["upgrade", "upgrade"],
["uninstall", "uninstall"],
["serve", "serve"],
["web", "web"],
["models", "models"],
["stats", "stats"],
["export", "export"],
["import", "import"],
["github", "github"],
["pr", "pr"],
["session", "session"],
["plugin", "plugin"],
["plug", "plugin"],
["db", "db"],
])
function flag(arg: string, name: string) {
return arg === `--${name}` || arg === `--no-${name}` || arg.startsWith(`--${name}=`)
}
function value(arg: string, name: string) {
return arg === `--${name}` || arg.startsWith(`--${name}=`)
}
// Match the root parser closely enough to decide which top-level module to load.
function pick(argv: string[]): Mode {
for (let i = 0; i < argv.length; i++) {
const arg = argv[i]
if (!arg) continue
if (arg === "--") return "tui"
if (arg === "completion") return "all"
if (arg === "--help" || arg === "-h") return "all"
if (arg === "--version" || arg === "-v") return "none"
if (flag(arg, "print-logs") || flag(arg, "pure")) continue
if (value(arg, "log-level")) {
if (arg === "--log-level") i += 1
continue
}
if (arg.startsWith("-") && !arg.startsWith("--")) {
if (arg.includes("h")) return "all"
if (arg.includes("v")) return "none"
return "tui"
}
if (arg.startsWith("-")) return "tui"
return map.get(arg) ?? "tui"
}
return "tui"
}
const mode = pick(args)
const all = mode === "all"
const none = mode === "none"
function load<T>(on: boolean, get: () => Promise<T>): Promise<T | undefined> {
if (!on) {
return Promise.resolve(undefined)
}
return get()
}
const [
TuiThreadCommand,
AttachCommand,
RunCommand,
AcpCommand,
McpCommand,
GenerateCommand,
DebugCommand,
ConsoleCommand,
ProvidersCommand,
AgentCommand,
UpgradeCommand,
UninstallCommand,
ServeCommand,
WebCommand,
ModelsCommand,
StatsCommand,
ExportCommand,
ImportCommand,
GithubCommand,
PrCommand,
SessionCommand,
PluginCommand,
DbCommand,
] = await Promise.all([
load(!none && (all || mode === "tui"), () => import("./cli/cmd/tui/thread").then((x) => x.TuiThreadCommand)),
load(!none && (all || mode === "attach"), () => import("./cli/cmd/tui/attach").then((x) => x.AttachCommand)),
load(!none && (all || mode === "run"), () => import("./cli/cmd/run").then((x) => x.RunCommand)),
load(!none && (all || mode === "acp"), () => import("./cli/cmd/acp").then((x) => x.AcpCommand)),
load(!none && (all || mode === "mcp"), () => import("./cli/cmd/mcp").then((x) => x.McpCommand)),
load(!none && (all || mode === "generate"), () => import("./cli/cmd/generate").then((x) => x.GenerateCommand)),
load(!none && (all || mode === "debug"), () => import("./cli/cmd/debug").then((x) => x.DebugCommand)),
load(!none && (all || mode === "console"), () => import("./cli/cmd/account").then((x) => x.ConsoleCommand)),
load(!none && (all || mode === "providers"), () => import("./cli/cmd/providers").then((x) => x.ProvidersCommand)),
load(!none && (all || mode === "agent"), () => import("./cli/cmd/agent").then((x) => x.AgentCommand)),
load(!none && (all || mode === "upgrade"), () => import("./cli/cmd/upgrade").then((x) => x.UpgradeCommand)),
load(!none && (all || mode === "uninstall"), () => import("./cli/cmd/uninstall").then((x) => x.UninstallCommand)),
load(!none && (all || mode === "serve"), () => import("./cli/cmd/serve").then((x) => x.ServeCommand)),
load(!none && (all || mode === "web"), () => import("./cli/cmd/web").then((x) => x.WebCommand)),
load(!none && (all || mode === "models"), () => import("./cli/cmd/models").then((x) => x.ModelsCommand)),
load(!none && (all || mode === "stats"), () => import("./cli/cmd/stats").then((x) => x.StatsCommand)),
load(!none && (all || mode === "export"), () => import("./cli/cmd/export").then((x) => x.ExportCommand)),
load(!none && (all || mode === "import"), () => import("./cli/cmd/import").then((x) => x.ImportCommand)),
load(!none && (all || mode === "github"), () => import("./cli/cmd/github").then((x) => x.GithubCommand)),
load(!none && (all || mode === "pr"), () => import("./cli/cmd/pr").then((x) => x.PrCommand)),
load(!none && (all || mode === "session"), () => import("./cli/cmd/session").then((x) => x.SessionCommand)),
load(!none && (all || mode === "plugin"), () => import("./cli/cmd/plug").then((x) => x.PluginCommand)),
load(!none && (all || mode === "db"), () => import("./cli/cmd/db").then((x) => x.DbCommand)),
])
function show(out: string) {
const text = out.trimStart()
if (!text.startsWith("opencode ")) {
@@ -148,29 +275,100 @@ const cli = yargs(args)
})
.usage("")
.completion("completion", "generate shell completion script")
.command(AcpCommand)
.command(McpCommand)
.command(TuiThreadCommand)
.command(AttachCommand)
.command(RunCommand)
.command(GenerateCommand)
.command(DebugCommand)
.command(ConsoleCommand)
.command(ProvidersCommand)
.command(AgentCommand)
.command(UpgradeCommand)
.command(UninstallCommand)
.command(ServeCommand)
.command(WebCommand)
.command(ModelsCommand)
.command(StatsCommand)
.command(ExportCommand)
.command(ImportCommand)
.command(GithubCommand)
.command(PrCommand)
.command(SessionCommand)
.command(PluginCommand)
.command(DbCommand)
if (TuiThreadCommand) {
cli.command(TuiThreadCommand)
}
if (AttachCommand) {
cli.command(AttachCommand)
}
if (AcpCommand) {
cli.command(AcpCommand)
}
if (McpCommand) {
cli.command(McpCommand)
}
if (RunCommand) {
cli.command(RunCommand)
}
if (GenerateCommand) {
cli.command(GenerateCommand)
}
if (DebugCommand) {
cli.command(DebugCommand)
}
if (ConsoleCommand) {
cli.command(ConsoleCommand)
}
if (ProvidersCommand) {
cli.command(ProvidersCommand)
}
if (AgentCommand) {
cli.command(AgentCommand)
}
if (UpgradeCommand) {
cli.command(UpgradeCommand)
}
if (UninstallCommand) {
cli.command(UninstallCommand)
}
if (ServeCommand) {
cli.command(ServeCommand)
}
if (WebCommand) {
cli.command(WebCommand)
}
if (ModelsCommand) {
cli.command(ModelsCommand)
}
if (StatsCommand) {
cli.command(StatsCommand)
}
if (ExportCommand) {
cli.command(ExportCommand)
}
if (ImportCommand) {
cli.command(ImportCommand)
}
if (GithubCommand) {
cli.command(GithubCommand)
}
if (PrCommand) {
cli.command(PrCommand)
}
if (SessionCommand) {
cli.command(SessionCommand)
}
if (PluginCommand) {
cli.command(PluginCommand)
}
if (DbCommand) {
cli.command(DbCommand)
}
cli
.fail((msg, err) => {
if (
msg?.startsWith("Unknown argument") ||
@@ -5,7 +5,6 @@ import { iife } from "@/util/iife"
import { Log } from "../../util/log"
import { setTimeout as sleep } from "node:timers/promises"
import { CopilotModels } from "./models"
import { MessageV2 } from "@/session/message-v2"
const log = Log.create({ service: "plugin.copilot" })
@@ -28,21 +27,6 @@ function base(enterpriseUrl?: string) {
return enterpriseUrl ? `https://copilot-api.${normalizeDomain(enterpriseUrl)}` : "https://api.githubcopilot.com"
}
// Check if a message is a synthetic user msg used to attach an image from a tool call
function imgMsg(msg: any): boolean {
if (msg?.role !== "user") return false
// Handle the 3 api formats
const content = msg.content
if (typeof content === "string") return content === MessageV2.SYNTHETIC_ATTACHMENT_PROMPT
if (!Array.isArray(content)) return false
return content.some(
(part: any) =>
(part?.type === "text" || part?.type === "input_text") && part.text === MessageV2.SYNTHETIC_ATTACHMENT_PROMPT,
)
}
function fix(model: Model, url: string): Model {
return {
...model,
@@ -106,7 +90,7 @@ export async function CopilotAuthPlugin(input: PluginInput): Promise<Hooks> {
(msg: any) =>
Array.isArray(msg.content) && msg.content.some((part: any) => part.type === "image_url"),
),
isAgent: last?.role !== "user" || imgMsg(last),
isAgent: last?.role !== "user",
}
}
@@ -118,7 +102,7 @@ export async function CopilotAuthPlugin(input: PluginInput): Promise<Hooks> {
(item: any) =>
Array.isArray(item?.content) && item.content.some((part: any) => part.type === "input_image"),
),
isAgent: last?.role !== "user" || imgMsg(last),
isAgent: last?.role !== "user",
}
}
@@ -140,7 +124,7 @@ export async function CopilotAuthPlugin(input: PluginInput): Promise<Hooks> {
part.content.some((nested: any) => nested?.type === "image")),
),
),
isAgent: !(last?.role === "user" && hasNonToolCalls) || imgMsg(last),
isAgent: !(last?.role === "user" && hasNonToolCalls),
}
}
} catch {}
+1 -3
View File
@@ -25,8 +25,6 @@ interface FetchDecompressionError extends Error {
}
export namespace MessageV2 {
export const SYNTHETIC_ATTACHMENT_PROMPT = "Attached image(s) from tool result:"
export function isMedia(mime: string) {
return mime.startsWith("image/") || mime === "application/pdf"
}
@@ -810,7 +808,7 @@ export namespace MessageV2 {
parts: [
{
type: "text" as const,
text: SYNTHETIC_ATTACHMENT_PROMPT,
text: "Attached image(s) from tool result:",
},
...media.map((attachment) => ({
type: "file" as const,
+27 -74
View File
@@ -10,106 +10,59 @@ export namespace Message {
})),
)
export class Source extends Schema.Class<Source>("Message.Source")({
start: Schema.Number,
end: Schema.Number,
text: Schema.String,
}) {}
export class FileAttachment extends Schema.Class<FileAttachment>("Message.File.Attachment")({
uri: Schema.String,
export class File extends Schema.Class<File>("Message.File")({
url: Schema.String,
mime: Schema.String,
name: Schema.String.pipe(Schema.optional),
description: Schema.String.pipe(Schema.optional),
source: Source.pipe(Schema.optional),
}) {
static create(url: string) {
return new FileAttachment({
uri: url,
return new File({
url,
mime: "text/plain",
})
}
}
export class AgentAttachment extends Schema.Class<AgentAttachment>("Message.Agent.Attachment")({
name: Schema.String,
source: Source.pipe(Schema.optional),
export class UserContent extends Schema.Class<UserContent>("Message.User.Content")({
text: Schema.String,
synthetic: Schema.Boolean.pipe(Schema.optional),
agent: Schema.String.pipe(Schema.optional),
files: Schema.Array(File).pipe(Schema.optional),
}) {}
export class User extends Schema.Class<User>("Message.User")({
id: ID,
type: Schema.Literal("user"),
text: Schema.String,
files: Schema.Array(FileAttachment).pipe(Schema.optional),
agents: Schema.Array(AgentAttachment).pipe(Schema.optional),
time: Schema.Struct({
created: Schema.DateTimeUtc,
}),
content: UserContent,
}) {
static create(input: { text: User["text"]; files?: User["files"]; agents?: User["agents"] }) {
static create(content: Schema.Schema.Type<typeof UserContent>) {
const msg = new User({
id: ID.create(),
type: "user",
...input,
time: {
created: Effect.runSync(DateTime.now),
},
content,
})
return msg
}
static file(url: string) {
return new File({
url,
mime: "text/plain",
})
}
}
export class Synthetic extends Schema.Class<Synthetic>("Message.Synthetic")({
id: ID,
type: Schema.Literal("synthetic"),
text: Schema.String,
time: Schema.Struct({
created: Schema.DateTimeUtc,
}),
}) {}
export class Request extends Schema.Class<Request>("Message.Request")({
id: ID,
type: Schema.Literal("start"),
model: Schema.Struct({
id: Schema.String,
providerID: Schema.String,
variant: Schema.String.pipe(Schema.optional),
}),
time: Schema.Struct({
created: Schema.DateTimeUtc,
}),
}) {}
export class Text extends Schema.Class<Text>("Message.Text")({
id: ID,
type: Schema.Literal("text"),
text: Schema.String,
time: Schema.Struct({
created: Schema.DateTimeUtc,
completed: Schema.DateTimeUtc.pipe(Schema.optional),
}),
}) {}
export class Complete extends Schema.Class<Complete>("Message.Complete")({
id: ID,
type: Schema.Literal("complete"),
time: Schema.Struct({
created: Schema.DateTimeUtc,
}),
cost: Schema.Number,
tokens: Schema.Struct({
total: Schema.Number,
input: Schema.Number,
output: Schema.Number,
reasoning: Schema.Number,
cache: Schema.Struct({
read: Schema.Number,
write: Schema.Number,
}),
}),
}) {}
export const Info = Schema.Union([User, Text])
export type Info = Schema.Schema.Type<typeof Info>
export namespace User {}
}
const msg = Message.User.create({
text: "Hello world",
files: [Message.File.create("file://example.com/file.txt")],
})
console.log(JSON.stringify(msg, null, 2))
-71
View File
@@ -1,71 +0,0 @@
import { Context, Layer, Schema, Effect } from "effect"
import { Message } from "./message"
import { Struct } from "effect"
import { Identifier } from "@/id/id"
import { withStatics } from "@/util/schema"
import { Session } from "@/session"
import { SessionID } from "@/session/schema"
export namespace SessionV2 {
export const ID = SessionID
export type ID = Schema.Schema.Type<typeof ID>
export class PromptInput extends Schema.Class<PromptInput>("Session.PromptInput")({
...Struct.omit(Message.User.fields, ["time", "type"]),
id: Schema.optionalKey(Message.ID),
sessionID: SessionV2.ID,
}) {}
export class CreateInput extends Schema.Class<CreateInput>("Session.CreateInput")({
id: Schema.optionalKey(SessionV2.ID),
}) {}
export class Info extends Schema.Class<Info>("Session.Info")({
id: SessionV2.ID,
model: Schema.Struct({
id: Schema.String,
providerID: Schema.String,
modelID: Schema.String,
}).pipe(Schema.optional),
}) {}
export interface Interface {
fromID: (id: SessionV2.ID) => Effect.Effect<Info>
create: (input: CreateInput) => Effect.Effect<Info>
prompt: (input: PromptInput) => Effect.Effect<Message.User>
}
export class Service extends Context.Service<Service, Interface>()("Session.Service") {}
export const layer = Layer.effect(Service)(
Effect.gen(function* () {
const session = yield* Session.Service
const create: Interface["create"] = Effect.fn("Session.create")(function* (input) {
throw new Error("Not implemented")
})
const prompt: Interface["prompt"] = Effect.fn("Session.prompt")(function* (input) {
throw new Error("Not implemented")
})
const fromID: Interface["fromID"] = Effect.fn("Session.fromID")(function* (id) {
const match = yield* session.get(id)
return fromV1(match)
})
return Service.of({
create,
prompt,
fromID,
})
}),
)
function fromV1(input: Session.Info): Info {
return new Info({
id: SessionV2.ID.make(input.id),
})
}
}
@@ -270,7 +270,6 @@ describe("SyncProvider", () => {
expect(sync.data.message.ses_1[0]?.id).toBe("msg_1")
expect(sync.data.part.msg_1[0]).toMatchObject({ type: "text", text: "part-ws_a" })
expect(sync.data.session_diff.ses_1[0]?.file).toBe("ws_a.ts")
expect(sync.data.session_diff.ses_1[0]).not.toHaveProperty("patch")
log.length = 0
project.workspace.set("ws_b")
@@ -286,7 +285,6 @@ describe("SyncProvider", () => {
expect(sync.data.message.ses_1[0]?.id).toBe("msg_1")
expect(sync.data.part.msg_1[0]).toMatchObject({ type: "text", text: "part-ws_b" })
expect(sync.data.session_diff.ses_1[0]?.file).toBe("ws_b.ts")
expect(sync.data.session_diff.ses_1[0]).not.toHaveProperty("patch")
} finally {
app.renderer.destroy()
}