-
Notifications
You must be signed in to change notification settings - Fork 134
Expand file tree
/
Copy pathrun.ts
More file actions
917 lines (842 loc) · 32 KB
/
Copy pathrun.ts
File metadata and controls
917 lines (842 loc) · 32 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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
import type { Argv } from "yargs"
import path from "path"
import { pathToFileURL } from "url"
import { UI } from "../ui"
import { cmd } from "./cmd"
import { Flag } from "../../flag/flag"
import { bootstrap } from "../bootstrap"
import { EOL } from "os"
import { Filesystem } from "../../util/filesystem"
import { createOpencodeClient, type Message, type OpencodeClient, type ToolPart } from "@opencode-ai/sdk/v2"
import { Server } from "../../server/server"
import { Provider } from "../../provider/provider"
import { Agent } from "../../agent/agent"
import { PermissionNext } from "../../permission/next"
import { Tool } from "../../tool/tool"
import { GlobTool } from "../../tool/glob"
import { GrepTool } from "../../tool/grep"
import { ListTool } from "../../tool/ls"
import { ReadTool } from "../../tool/read"
import { WebFetchTool } from "../../tool/webfetch"
import { EditTool } from "../../tool/edit"
import { WriteTool } from "../../tool/write"
import { CodeSearchTool } from "../../tool/codesearch"
import { WebSearchTool } from "../../tool/websearch"
import { TaskTool } from "../../tool/task"
import { SkillTool } from "../../tool/skill"
import { BashTool } from "../../tool/bash"
import { TodoWriteTool } from "../../tool/todo"
import { Locale } from "../../util/locale"
import { Tracer, FileExporter, HttpExporter, type TraceExporter } from "../../altimate/observability/tracing"
import { Config } from "../../config/config"
type ToolProps<T extends Tool.Info> = {
input: Tool.InferParameters<T>
metadata: Tool.InferMetadata<T>
part: ToolPart
}
function props<T extends Tool.Info>(part: ToolPart): ToolProps<T> {
const state = part.state
return {
input: state.input as Tool.InferParameters<T>,
metadata: ("metadata" in state ? state.metadata : {}) as Tool.InferMetadata<T>,
part,
}
}
type Inline = {
icon: string
title: string
description?: string
}
function inline(info: Inline) {
const suffix = info.description ? UI.Style.TEXT_DIM + ` ${info.description}` + UI.Style.TEXT_NORMAL : ""
UI.println(UI.Style.TEXT_NORMAL + info.icon, UI.Style.TEXT_NORMAL + info.title + suffix)
}
function block(info: Inline, output?: string) {
UI.empty()
inline(info)
if (!output?.trim()) return
UI.println(output)
UI.empty()
}
function fallback(part: ToolPart) {
const state = part.state
const input = "input" in state ? state.input : undefined
const title =
("title" in state && state.title ? state.title : undefined) ||
(input && typeof input === "object" && Object.keys(input).length > 0 ? JSON.stringify(input) : "Unknown")
inline({
icon: "⚙",
title: `${part.tool} ${title}`,
})
}
function glob(info: ToolProps<typeof GlobTool>) {
const root = info.input.path ?? ""
const title = `Glob "${info.input.pattern}"`
const suffix = root ? `in ${normalizePath(root)}` : ""
const num = info.metadata.count
const description =
num === undefined ? suffix : `${suffix}${suffix ? " · " : ""}${num} ${num === 1 ? "match" : "matches"}`
inline({
icon: "✱",
title,
...(description && { description }),
})
}
function grep(info: ToolProps<typeof GrepTool>) {
const root = info.input.path ?? ""
const title = `Grep "${info.input.pattern}"`
const suffix = root ? `in ${normalizePath(root)}` : ""
const num = info.metadata.matches
const description =
num === undefined ? suffix : `${suffix}${suffix ? " · " : ""}${num} ${num === 1 ? "match" : "matches"}`
inline({
icon: "✱",
title,
...(description && { description }),
})
}
function list(info: ToolProps<typeof ListTool>) {
const dir = info.input.path ? normalizePath(info.input.path) : ""
inline({
icon: "→",
title: dir ? `List ${dir}` : "List",
})
}
function read(info: ToolProps<typeof ReadTool>) {
const file = normalizePath(info.input.filePath)
const pairs = Object.entries(info.input).filter(([key, value]) => {
if (key === "filePath") return false
return typeof value === "string" || typeof value === "number" || typeof value === "boolean"
})
const description = pairs.length ? `[${pairs.map(([key, value]) => `${key}=${value}`).join(", ")}]` : undefined
inline({
icon: "→",
title: `Read ${file}`,
...(description && { description }),
})
}
function write(info: ToolProps<typeof WriteTool>) {
block(
{
icon: "←",
title: `Write ${normalizePath(info.input.filePath)}`,
},
info.part.state.status === "completed" ? info.part.state.output : undefined,
)
}
function webfetch(info: ToolProps<typeof WebFetchTool>) {
inline({
icon: "%",
title: `WebFetch ${info.input.url}`,
})
}
function edit(info: ToolProps<typeof EditTool>) {
const title = normalizePath(info.input.filePath)
const diff = info.metadata.diff
block(
{
icon: "←",
title: `Edit ${title}`,
},
diff,
)
}
function codesearch(info: ToolProps<typeof CodeSearchTool>) {
inline({
icon: "◇",
title: `Exa Code Search "${info.input.query}"`,
})
}
function websearch(info: ToolProps<typeof WebSearchTool>) {
inline({
icon: "◈",
title: `Exa Web Search "${info.input.query}"`,
})
}
function task(info: ToolProps<typeof TaskTool>) {
const input = info.part.state.input
const status = info.part.state.status
const subagent =
typeof input.subagent_type === "string" && input.subagent_type.trim().length > 0 ? input.subagent_type : "unknown"
const agent = Locale.titlecase(subagent)
const desc =
typeof input.description === "string" && input.description.trim().length > 0 ? input.description : undefined
const icon = status === "error" ? "✗" : status === "running" ? "•" : "✓"
const name = desc ?? `${agent} Task`
inline({
icon,
title: name,
description: desc ? `${agent} Agent` : undefined,
})
}
function skill(info: ToolProps<typeof SkillTool>) {
inline({
icon: "→",
title: `Skill "${info.input.name}"`,
})
}
function bash(info: ToolProps<typeof BashTool>) {
const output = info.part.state.status === "completed" ? info.part.state.output?.trim() : undefined
block(
{
icon: "$",
title: `${info.input.command}`,
},
output,
)
}
function todo(info: ToolProps<typeof TodoWriteTool>) {
block(
{
icon: "#",
title: "Todos",
},
info.input.todos.map((item) => `${item.status === "completed" ? "[x]" : "[ ]"} ${item.content}`).join("\n"),
)
}
function splitSqlStatements(sql: string): string[] {
const stmts: string[] = []
const current: string[] = []
let inStr = false
let strChar = ""
for (let i = 0; i < sql.length; i++) {
const ch = sql[i]
if (!inStr && (ch === "'" || ch === '"' || ch === "`")) {
inStr = true
strChar = ch
current.push(ch)
} else if (inStr && ch === strChar) {
inStr = false
current.push(ch)
} else if (!inStr && ch === ";") {
const s = current.join("").trim()
if (s) stmts.push(s)
current.length = 0
} else {
current.push(ch)
}
}
const last = current.join("").trim()
if (last) stmts.push(last)
return stmts.length ? stmts : [sql]
}
function normalizePath(input?: string) {
if (!input) return ""
if (path.isAbsolute(input)) return path.relative(process.cwd(), input) || "."
return input
}
export const RunCommand = cmd({
command: "run [message..]",
describe: "run altimate with a message",
builder: (yargs: Argv) => {
return (
yargs
.positional("message", {
describe: "message to send",
type: "string",
array: true,
default: [],
})
.option("command", {
describe: "the command to run, use message for args",
type: "string",
})
.option("continue", {
alias: ["c"],
describe: "continue the last session",
type: "boolean",
})
.option("session", {
alias: ["s"],
describe: "session id to continue",
type: "string",
})
.option("fork", {
describe: "fork the session before continuing (requires --continue or --session)",
type: "boolean",
})
.option("share", {
type: "boolean",
describe: "share the session",
})
.option("model", {
type: "string",
alias: ["m"],
describe: "model to use in the format of provider/model",
})
.option("agent", {
type: "string",
describe: "agent to use",
})
.option("format", {
type: "string",
choices: ["default", "json"],
default: "default",
describe: "format: default (formatted) or json (raw JSON events)",
})
.option("file", {
alias: ["f"],
type: "string",
array: true,
describe: "file(s) to attach to message",
})
.option("title", {
type: "string",
describe: "title for the session (uses truncated prompt if no value provided)",
})
.option("attach", {
type: "string",
describe: "attach to a running altimate server (e.g., http://localhost:4096)",
})
.option("password", {
alias: ["p"],
type: "string",
describe: "basic auth password (defaults to OPENCODE_SERVER_PASSWORD)",
})
.option("dir", {
type: "string",
describe: "directory to run in, path on remote server if attaching",
})
.option("port", {
type: "number",
describe: "port for the local server (defaults to random port if no value provided)",
})
.option("variant", {
type: "string",
describe: "model variant (provider-specific reasoning effort, e.g., high, max, minimal)",
})
.option("thinking", {
type: "boolean",
describe: "show thinking blocks",
default: false,
})
.option("output", {
alias: ["o"],
type: "string",
describe: "write final assistant response to file (.md or .txt)",
})
.option("audience", {
type: "string",
choices: ["executive", "technical"] as const,
describe: "output calibration: executive (no SQL/jargon, business framing) or technical (default)",
})
.option("query", {
alias: ["q"],
type: "number",
describe: "when using --file with a SQL file, analyze only the Nth statement (1-indexed)",
})
.option("trace", {
type: "boolean",
describe: "enable session tracing (default: true, disable with --no-trace)",
default: true,
})
// altimate_change start — budget limits for CI/enterprise governance
.option("max-turns", {
type: "number",
describe: "maximum number of assistant turns before aborting the session",
})
// altimate_change end
// altimate_change start — backport upstream PR #21266 (dropped during v1.4.0 merge)
.option("dangerously-skip-permissions", {
type: "boolean",
describe: "auto-approve permissions that are not explicitly denied (dangerous!)",
default: false,
})
)
// altimate_change end
},
handler: async (args) => {
// altimate_change start — `run` is the only entrypoint without an answer
// channel for the question tool: no TUI is mounted and the in-process
// Server.Default() shim below does not bind a port, so a connected IDE
// or web client cannot POST /question/:requestID/reply. Without this
// flag, Question.ask() awaits a Deferred forever and the parent
// supervisor TaskStops the subprocess — looking exactly like a hang.
// Server commands (serve/web/acp/workspace-serve) intentionally leave
// this unset so their HTTP reply path stays live.
//
// Skipped when --attach is set: the agent runs on the remote server, so
// the local env var would be a no-op and would only pollute the local
// process env for other tools that may consult it.
//
// Child processes spawned by the bash tool would inherit this flag and
// misbehave if they themselves are server-mode entrypoints; bash.ts
// strips ALTIMATE_NON_INTERACTIVE from mergedEnv to prevent that leak.
//
// Users can opt out by exporting ALTIMATE_NON_INTERACTIVE=0 before
// launching `run`.
if (!args.attach && process.env["ALTIMATE_NON_INTERACTIVE"] === undefined) {
process.env["ALTIMATE_NON_INTERACTIVE"] = "1"
}
// altimate_change end
let message = [...args.message, ...(args["--"] || [])]
.map((arg) => (arg.includes(" ") ? `"${arg.replace(/"/g, '\\"')}"` : arg))
.join(" ")
const directory = (() => {
if (!args.dir) return undefined
if (args.attach) return args.dir
try {
process.chdir(args.dir)
return process.cwd()
} catch {
UI.error("Failed to change directory to " + args.dir)
process.exit(1)
}
})()
const files: { type: "file"; url: string; filename: string; mime: string }[] = []
if (args.file) {
const list = Array.isArray(args.file) ? args.file : [args.file]
for (const filePath of list) {
const resolvedPath = path.resolve(process.cwd(), filePath)
if (!(await Filesystem.exists(resolvedPath))) {
UI.error(`File not found: ${filePath}`)
process.exit(1)
}
const mime = (await Filesystem.isDir(resolvedPath)) ? "application/x-directory" : "text/plain"
files.push({
type: "file",
url: pathToFileURL(resolvedPath).href,
filename: path.basename(resolvedPath),
mime,
})
}
}
// --query N: extract the Nth SQL statement from attached file(s) as a text part
if (args.query !== undefined && args.file) {
const fileList = Array.isArray(args.file) ? args.file : [args.file]
const extractedParts: string[] = []
for (const filePath of fileList) {
const resolvedPath = path.resolve(process.cwd(), filePath)
const content = await Bun.file(resolvedPath).text()
const stmts = splitSqlStatements(content)
const n = args.query
if (n < 1 || n > stmts.length) {
UI.error(
`--query ${n} is out of range (${path.basename(filePath)} has ${stmts.length} statement${stmts.length === 1 ? "" : "s"})`,
)
process.exit(1)
}
extractedParts.push(
`[${path.basename(filePath)}, statement ${n} of ${stmts.length}]\n\`\`\`sql\n${stmts[n - 1].trim()}\n\`\`\``,
)
}
// Replace file attachments with extracted statement as inline text
files.length = 0
message = [extractedParts.join("\n\n"), message].filter(Boolean).join("\n\n")
}
// altimate_change start — null-safe stdin access. process.stdin can be
// undefined in embedded/child runtimes (see dev-punia review on PR #937).
if (!process.stdin?.isTTY) message += "\n" + (await Bun.stdin.text())
// altimate_change end
if (message.trim().length === 0 && !args.command) {
UI.error("You must provide a message or a command")
process.exit(1)
}
if (args.fork && !args.continue && !args.session) {
UI.error("--fork requires --continue or --session")
process.exit(1)
}
const rules: PermissionNext.Ruleset = [
{
permission: "question",
action: "deny",
pattern: "*",
},
{
permission: "plan_enter",
action: "deny",
pattern: "*",
},
{
permission: "plan_exit",
action: "deny",
pattern: "*",
},
]
function title() {
if (args.title === undefined) return
if (args.title !== "") return args.title
return message.slice(0, 50) + (message.length > 50 ? "..." : "")
}
async function session(sdk: OpencodeClient) {
const baseID = args.continue ? (await sdk.session.list()).data?.find((s) => !s.parentID)?.id : args.session
if (baseID && args.fork) {
const forked = await sdk.session.fork({ sessionID: baseID })
return forked.data?.id
}
if (baseID) return baseID
const name = title()
const result = await sdk.session.create({ title: name, permission: rules })
return result.data?.id
}
async function share(sdk: OpencodeClient, sessionID: string) {
const cfg = await sdk.config.get()
if (!cfg.data) return
if (cfg.data.share !== "auto" && !Flag.OPENCODE_AUTO_SHARE && !args.share) return
const res = await sdk.session.share({ sessionID }).catch((error) => {
if (error instanceof Error && error.message.includes("disabled")) {
UI.println(UI.Style.TEXT_DANGER_BOLD + "! " + error.message)
}
return { error }
})
if (!res.error && "data" in res && res.data?.share?.url) {
UI.println(UI.Style.TEXT_INFO_BOLD + "~ " + res.data.share.url)
}
}
const EXECUTIVE_DIRECTIVE = `## Output Calibration — Executive Mode
You are speaking to a non-technical business executive. Follow these rules strictly:
- NEVER show SQL queries, column names in backticks, or code blocks
- NEVER use engineering jargon (Cartesian product, referential integrity, column pruning, NULL, schema, index, CTE, predicate)
- Translate ALL technical findings to business impact: revenue, cost, risk, time, compliance exposure
- Lead with the business implication, then briefly explain the cause in plain English if needed
- Format output for a slide deck or email: short paragraphs, simple tables with business-friendly headers
- "Query Duration" not "total_elapsed_time" — "Data Processed" not "bytes_scanned" — "Monthly Cost" not "credits_used * 3.00"`
async function execute(sdk: OpencodeClient) {
const outputParts: string[] = []
function tool(part: ToolPart) {
try {
if (part.tool === "bash") return bash(props<typeof BashTool>(part))
if (part.tool === "glob") return glob(props<typeof GlobTool>(part))
if (part.tool === "grep") return grep(props<typeof GrepTool>(part))
if (part.tool === "list") return list(props<typeof ListTool>(part))
if (part.tool === "read") return read(props<typeof ReadTool>(part))
if (part.tool === "write") return write(props<typeof WriteTool>(part))
if (part.tool === "webfetch") return webfetch(props<typeof WebFetchTool>(part))
if (part.tool === "edit") return edit(props<typeof EditTool>(part))
if (part.tool === "codesearch") return codesearch(props<typeof CodeSearchTool>(part))
if (part.tool === "websearch") return websearch(props<typeof WebSearchTool>(part))
if (part.tool === "task") return task(props<typeof TaskTool>(part))
if (part.tool === "todowrite") return todo(props<typeof TodoWriteTool>(part))
if (part.tool === "skill") return skill(props<typeof SkillTool>(part))
return fallback(part)
} catch {
return fallback(part)
}
}
function emit(type: string, data: Record<string, unknown>) {
if (args.format === "json") {
process.stdout.write(JSON.stringify({ type, timestamp: Date.now(), sessionID, ...data }) + EOL)
return true
}
return false
}
const events = await sdk.event.subscribe()
let error: string | undefined
// Build tracer from config + CLI flags — must never crash the run command
const tracer = await (async () => {
try {
if (args.trace === false) return null
const cfg = await Config.get()
const tracingCfg = cfg.tracing
if (tracingCfg?.enabled === false) return null
const exporters: TraceExporter[] = [new FileExporter(tracingCfg?.dir)]
if (tracingCfg?.exporters) {
for (const exp of tracingCfg.exporters) {
exporters.push(new HttpExporter(exp.name, exp.endpoint, exp.headers))
}
}
return Tracer.withExporters(exporters, { maxFiles: tracingCfg?.maxFiles })
} catch {
// Config failure should never prevent the run command from working
return null
}
})()
async function loop() {
const toggles = new Map<string, boolean>()
// altimate_change start — max-turns budget enforcement
let turnCount = 0
const maxTurns = args.maxTurns
// altimate_change end
for await (const event of events.stream) {
if (
event.type === "message.updated" &&
event.properties.info.role === "assistant" &&
args.format !== "json" &&
toggles.get("start") !== true
) {
UI.empty()
UI.println(`> ${event.properties.info.agent} · ${event.properties.info.modelID}`)
UI.empty()
toggles.set("start", true)
// Enrich trace with resolved model/provider from the first assistant message
const info = event.properties.info
tracer?.enrichFromAssistant({
modelID: info.modelID,
providerID: info.providerID,
agent: info.agent,
variant: info.variant,
})
}
if (event.type === "message.part.updated") {
const part = event.properties.part
if (part.sessionID !== sessionID) continue
if (part.type === "tool" && (part.state.status === "completed" || part.state.status === "error")) {
tracer?.logToolCall(part as Parameters<Tracer["logToolCall"]>[0])
if (emit("tool_use", { part })) continue
if (part.state.status === "completed") {
tool(part)
continue
}
inline({
icon: "✗",
title: `${part.tool} failed`,
})
UI.error(part.state.error)
}
if (
part.type === "tool" &&
part.tool === "task" &&
part.state.status === "running" &&
args.format !== "json"
) {
if (toggles.get(part.id) === true) continue
task(props<typeof TaskTool>(part))
toggles.set(part.id, true)
}
if (part.type === "step-start") {
tracer?.logStepStart(part)
// altimate_change start — enforce max-turns budget
turnCount++
if (maxTurns && turnCount > maxTurns) {
error = `Budget exceeded: reached ${maxTurns} assistant turn${maxTurns !== 1 ? "s" : ""} limit`
UI.println(UI.Style.TEXT_DANGER_BOLD + "!", UI.Style.TEXT_NORMAL + ` ${error}. Aborting session.`)
await sdk.session.abort({ sessionID })
break
}
// altimate_change end
if (emit("step_start", { part })) continue
}
if (part.type === "step-finish") {
tracer?.logStepFinish(part)
if (emit("step_finish", { part })) continue
}
if (part.type === "text" && part.time?.end) {
tracer?.logText(part)
if (emit("text", { part })) continue
const text = part.text.trim()
if (!text) continue
if (args.output) outputParts.push(text)
if (!process.stdout.isTTY) {
process.stdout.write(text + EOL)
continue
}
UI.empty()
UI.println(text)
UI.empty()
}
if (part.type === "reasoning" && part.time?.end && args.thinking) {
if (emit("reasoning", { part })) continue
const text = part.text.trim()
if (!text) continue
const line = `Thinking: ${text}`
if (process.stdout.isTTY) {
UI.empty()
UI.println(`${UI.Style.TEXT_DIM}\u001b[3m${line}\u001b[0m${UI.Style.TEXT_NORMAL}`)
UI.empty()
continue
}
process.stdout.write(line + EOL)
}
}
if (event.type === "session.error") {
const props = event.properties
if (props.sessionID !== sessionID || !props.error) continue
let err = String(props.error.name)
if ("data" in props.error && props.error.data && "message" in props.error.data) {
err = String(props.error.data.message)
}
error = error ? error + EOL + err : err
if (emit("error", { error: props.error })) continue
UI.error(err)
}
if (
event.type === "session.status" &&
event.properties.sessionID === sessionID &&
event.properties.status.type === "idle"
) {
break
}
if (event.type === "permission.asked") {
const permission = event.properties
if (permission.sessionID !== sessionID) continue
// altimate_change start - yolo mode: auto-approve but respect explicit deny rules.
// --dangerously-skip-permissions (backport of upstream PR #21266) is treated as
// an alias — same auto-approve behavior, plus our deny-rule safety net which
// the upstream implementation lacks.
const yolo = args.yolo || Flag.ALTIMATE_CLI_YOLO || args["dangerously-skip-permissions"]
if (yolo) {
// Check if any pattern matches an explicit deny rule from the session config
const isDenied = rules.some(
(r) =>
r.action === "deny" &&
r.permission === permission.permission &&
permission.patterns.some((p) => {
if (r.pattern === "*") return true
return p.includes(r.pattern) || r.pattern.includes(p)
}),
)
if (isDenied) {
UI.println(
UI.Style.TEXT_DANGER_BOLD + "!",
UI.Style.TEXT_NORMAL +
`yolo mode: BLOCKED by deny rule: ${permission.permission} (${permission.patterns.join(", ")})`,
)
await sdk.permission.reply({
requestID: permission.id,
reply: "reject",
})
} else {
UI.println(
UI.Style.TEXT_WARNING_BOLD + "!",
UI.Style.TEXT_NORMAL +
`yolo mode: auto-approved ${permission.permission} (${permission.patterns.join(", ")})`,
)
await sdk.permission.reply({
requestID: permission.id,
reply: "once",
})
}
} else {
UI.println(
UI.Style.TEXT_WARNING_BOLD + "!",
UI.Style.TEXT_NORMAL +
`permission requested: ${permission.permission} (${permission.patterns.join(", ")}); auto-rejecting`,
)
await sdk.permission.reply({
requestID: permission.id,
reply: "reject",
})
}
// altimate_change end
}
}
}
// Validate agent if specified; capture audience option from agent definition
const { agent, agentAudience } = await (async () => {
if (!args.agent) return { agent: undefined, agentAudience: undefined }
const entry = await Agent.get(args.agent)
if (!entry) {
UI.println(
UI.Style.TEXT_WARNING_BOLD + "!",
UI.Style.TEXT_NORMAL,
`agent "${args.agent}" not found. Falling back to default agent`,
)
return { agent: undefined, agentAudience: undefined }
}
if (entry.mode === "subagent") {
UI.println(
UI.Style.TEXT_WARNING_BOLD + "!",
UI.Style.TEXT_NORMAL,
`agent "${args.agent}" is a subagent, not a primary agent. Falling back to default agent`,
)
return { agent: undefined, agentAudience: undefined }
}
const aud = entry.options?.audience as string | undefined
return { agent: args.agent, agentAudience: aud }
})()
// Build audience system directive (--audience flag overrides agent-level setting)
const audienceMode = args.audience ?? agentAudience
const audienceSystem = audienceMode === "executive" ? EXECUTIVE_DIRECTIVE : undefined
const sessionID = await session(sdk)
if (!sessionID) {
UI.error("Session not found")
process.exit(1)
}
await share(sdk, sessionID)
// Start trace now that sessionID is available
tracer?.startTrace(sessionID, {
title: title() || message.slice(0, 80),
model: args.model,
agent,
variant: args.variant,
prompt: message,
})
// altimate_change start - activate tracer for session
if (tracer) Tracer.setActive(tracer)
// altimate_change end
// Register crash handlers to flush the trace on unexpected exit
const onSigint = () => {
tracer?.flushSync("Process interrupted")
process.exit(130)
}
const onSigterm = () => {
tracer?.flushSync("Process interrupted")
process.exit(143)
}
const onBeforeExit = () => {
tracer?.flushSync("Process exited")
}
process.on("SIGINT", onSigint)
process.on("SIGTERM", onSigterm)
process.on("beforeExit", onBeforeExit)
// Start event listener before sending the prompt so no events are missed
const loopPromise = loop().catch((e) => {
console.error(e)
process.exit(1)
})
if (args.command) {
await sdk.session.command({
sessionID,
agent,
model: args.model,
command: args.command,
arguments: message,
variant: args.variant,
})
} else {
const model = args.model ? Provider.parseModel(args.model) : undefined
await sdk.session.prompt({
sessionID,
agent,
model,
variant: args.variant,
parts: [...files, { type: "text", text: message }],
...(audienceSystem ? { system: audienceSystem } : {}),
})
}
// Wait for the event loop to drain (breaks when session reaches idle)
await loopPromise
// Remove crash handlers — trace will be finalized cleanly
process.removeListener("SIGINT", onSigint)
process.removeListener("SIGTERM", onSigterm)
process.removeListener("beforeExit", onBeforeExit)
// Finalize trace and save to disk
if (tracer) {
Tracer.setActive(null)
const tracePath = await tracer.endTrace(error)
if (tracePath) {
emit("trace_saved", { path: tracePath })
if (args.format !== "json" && process.stdout.isTTY) {
UI.println(UI.Style.TEXT_DIM + `Trace saved: ${tracePath}` + UI.Style.TEXT_NORMAL)
}
}
}
// Write accumulated text output to file if --output was specified
if (args.output) {
const outputPath = path.resolve(args.output)
const content = outputParts.join("\n\n") || "(no text output — tool-only response)"
await Bun.write(outputPath, content)
process.stderr.write(`\n✓ Output saved to: ${outputPath}\n`)
}
}
if (args.attach) {
const headers = (() => {
const password = args.password ?? process.env.OPENCODE_SERVER_PASSWORD
if (!password) return undefined
const username = process.env.OPENCODE_SERVER_USERNAME ?? "opencode"
const auth = `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`
return { Authorization: auth }
})()
const sdk = createOpencodeClient({ baseUrl: args.attach, directory, headers })
return await execute(sdk)
}
await bootstrap(process.cwd(), async () => {
const fetchFn = (async (input: RequestInfo | URL, init?: RequestInit) => {
const request = new Request(input, init)
return Server.Default().fetch(request)
}) as typeof globalThis.fetch
const sdk = createOpencodeClient({ baseUrl: "http://altimate-code.internal", fetch: fetchFn })
await execute(sdk)
})
},
})