-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathindex.ts
More file actions
313 lines (298 loc) · 10.6 KB
/
index.ts
File metadata and controls
313 lines (298 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
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 { WorkspaceServeCommand } from "./cli/cmd/workspace-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"
// altimate_change start — trace: session trace command
import { TraceCommand } from "./cli/cmd/trace"
// altimate_change end
// altimate_change start — top-level skill command
import { SkillCommand } from "./cli/cmd/skill"
// altimate_change end
// altimate_change start — check: deterministic SQL check command
import { CheckCommand } from "./cli/cmd/check"
// altimate_change end
import path from "path"
import { Global } from "./global"
import { JsonMigration } from "./storage/json-migration"
import { Database } from "./storage/db"
// altimate_change start - telemetry import
import { Telemetry } from "./telemetry"
// altimate_change end
// altimate_change start — crash: import Trace for crash handlers
import { Trace } from "./altimate/observability/tracing"
// altimate_change end
// altimate_change start - welcome banner
import { showWelcomeBannerIfNeeded } from "./cli/welcome"
// altimate_change end
process.on("unhandledRejection", (e) => {
Log.Default.error("rejection", {
e: e instanceof Error ? e.message : e,
})
})
process.on("uncaughtException", (e) => {
Log.Default.error("exception", {
e: e instanceof Error ? e.message : e,
})
// altimate_change start — crash: flush active trace on uncaught exception
// Trace.active is set by run.ts (headless mode only — TUI traces live in
// the worker's isolated memory and are flushed via worker.terminate()).
// This is a safety net for the headless path where run.ts registers its
// own handlers but an exception could bubble past them.
try {
Trace.active?.flushSync(`Uncaught exception: ${e instanceof Error ? e.message : String(e)}`)
} catch {
// Trace module may not be initialized — best-effort
}
// altimate_change end
})
// Ensure the process exits on terminal hangup (eg. closing the terminal tab).
// Without this, long-running commands like `serve` block on a never-resolving
// promise and survive as orphaned processes.
// altimate_change start — crash: flush active trace before SIGHUP exit
process.on("SIGHUP", () => {
try {
Trace.active?.flushSync("Terminal hangup (SIGHUP)")
} catch {
// best-effort
}
process.exit()
})
// altimate_change end
let cli = yargs(hideBin(process.argv))
.parserConfiguration({ "populate--": true })
// altimate_change start - script name
.scriptName("altimate-code")
// altimate_change end
.wrap(100)
.help("help", "show help")
.alias("help", "h")
.version("version", "show version number", Installation.VERSION)
.alias("version", "v")
.option("print-logs", {
describe: "print logs to stderr",
type: "boolean",
})
.option("log-level", {
describe: "log level",
type: "string",
choices: ["DEBUG", "INFO", "WARN", "ERROR"],
})
// altimate_change start - yolo mode as global flag
.option("yolo", {
describe: "auto-approve all permission prompts (explicit deny rules still enforced)",
type: "boolean",
default: false,
})
// altimate_change end
.middleware(async (opts) => {
await Log.init({
print: process.argv.includes("--print-logs"),
dev: Installation.isLocal(),
level: (() => {
if (opts.logLevel) return opts.logLevel as Log.Level
if (Installation.isLocal()) return "DEBUG"
return "INFO"
})(),
})
process.env.AGENT = "1"
process.env.OPENCODE = "1"
process.env.OPENCODE_PID = String(process.pid)
// altimate_change start - datapilot env var
process.env.DATAPILOT = "1"
// altimate_change end
// altimate_change start - propagate --yolo flag to env var so Flag.ALTIMATE_CLI_YOLO picks it up
if ("yolo" in opts && opts.yolo) {
process.env.ALTIMATE_CLI_YOLO = "true"
}
// altimate_change end
// altimate_change start - telemetry init
// Initialize telemetry early so events from MCP, engine, auth are captured.
// init() is idempotent — safe to call again later in session prompt.
Telemetry.init().catch(() => {})
// altimate_change end
// altimate_change start - welcome banner on first run after install/upgrade
showWelcomeBannerIfNeeded()
// altimate_change end
// altimate_change start - app name in logs
Log.Default.info("altimate-code", {
// altimate_change end
version: Installation.VERSION,
args: process.argv.slice(2),
})
// altimate_change start — check: skip DB migration for stateless commands (check only needs Dispatcher)
const isStatelessCommand = process.argv[2] === "check"
// altimate_change end
// altimate_change start - db marker name
const marker = path.join(Global.Path.data, "altimate-code.db")
// altimate_change end
// altimate_change start — check: skip DB migration for stateless check command
if (!isStatelessCommand && !(await Filesystem.exists(marker))) {
// altimate_change end
const tty = process.stderr.isTTY
process.stderr.write("Performing one time database migration, may take a few minutes..." + EOL)
const width = 36
const orange = "\x1b[38;5;214m"
const muted = "\x1b[0;2m"
const reset = "\x1b[0m"
let last = -1
if (tty) process.stderr.write("\x1b[?25l")
try {
await JsonMigration.run(Database.Client().$client, {
progress: (event) => {
const percent = Math.floor((event.current / event.total) * 100)
if (percent === last && event.current !== event.total) return
last = percent
if (tty) {
const fill = Math.round((percent / 100) * width)
const bar = `${"■".repeat(fill)}${"・".repeat(width - fill)}`
process.stderr.write(
`\r${orange}${bar} ${percent.toString().padStart(3)}%${reset} ${muted}${event.label.padEnd(12)} ${event.current}/${event.total}${reset}`,
)
if (event.current === event.total) process.stderr.write("\n")
} else {
process.stderr.write(`sqlite-migration:${percent}${EOL}`)
}
},
})
} finally {
if (tty) process.stderr.write("\x1b[?25h")
else {
process.stderr.write(`sqlite-migration:done${EOL}`)
}
}
process.stderr.write("Database migration complete." + EOL)
}
})
.usage("\n" + UI.logo())
.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(DbCommand)
// altimate_change start — trace: session trace command
.command(TraceCommand)
// altimate_change end
// altimate_change start — top-level skill command
.command(SkillCommand)
// altimate_change end
// altimate_change start — check: register deterministic SQL check command
.command(CheckCommand)
// altimate_change end
if (Installation.isLocal()) {
cli = cli.command(WorkspaceServeCommand)
}
cli = cli
.fail((msg, err) => {
if (
msg?.startsWith("Unknown argument") ||
msg?.startsWith("Not enough non-option arguments") ||
msg?.startsWith("Invalid values:")
) {
if (err) throw err
cli.showHelp("log")
}
if (err) throw err
process.exit(1)
})
.strict()
try {
await cli.parse()
} catch (e) {
let data: Record<string, any> = {}
if (e instanceof NamedError) {
const obj = e.toObject()
Object.assign(data, {
...obj.data,
})
}
if (e instanceof Error) {
Object.assign(data, {
name: e.name,
message: e.message,
cause: e.cause?.toString(),
stack: e.stack,
})
}
if (e instanceof ResolveMessage) {
Object.assign(data, {
name: e.name,
message: e.message,
code: e.code,
specifier: e.specifier,
referrer: e.referrer,
position: e.position,
importKind: e.importKind,
})
}
Log.Default.error("fatal", data)
const formatted = FormatError(e)
if (formatted) UI.error(formatted)
if (formatted === undefined) {
UI.error("Unexpected error, check log file at " + Log.file() + " for more details" + EOL)
process.stderr.write((e instanceof Error ? e.message : String(e)) + EOL)
}
process.exitCode = 1
} finally {
// altimate_change start - telemetry flush
// Flush any buffered telemetry events before exiting.
// This is critical for non-session commands (auth, upgrade, mcp, etc.)
// that track events but don't go through the session prompt shutdown path.
// shutdown() is idempotent — safe even if session prompt already called it.
try {
await Telemetry.shutdown()
} catch {
// Telemetry failure must never prevent shutdown
}
// altimate_change end
// Some subprocesses don't react properly to SIGTERM and similar signals.
// Most notably, some docker-container-based MCP servers don't handle such signals unless
// run using `docker run --init`.
// Explicitly exit to avoid any hanging subprocesses.
process.exit()
}