forked from dirac-run/dirac
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
1391 lines (1200 loc) · 47 KB
/
index.ts
File metadata and controls
1391 lines (1200 loc) · 47 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
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Dirac CLI - TypeScript implementation with React Ink
*/
import { spawn } from "node:child_process"
import { exit } from "node:process"
import { Command } from "commander"
import { version as CLI_VERSION } from "../package.json"
import { suppressConsoleUnlessVerbose } from "./utils/console"
// CLI-only behavior: suppress console output unless verbose mode is enabled.
// Kept explicit here so importing the library bundle does not mutate global console methods.
suppressConsoleUnlessVerbose()
// Types and interfaces that don't trigger heavy module loading
import type { ApiProvider } from "@shared/api"
import type { Controller } from "@/core/controller"
import type { HistoryItem } from "@/shared/HistoryItem"
import type { OpenaiReasoningEffort } from "@/shared/storage/types"
import { CLI_LOG_FILE, shutdownEvent, window } from "./vscode-shim"
/**
* Common options shared between runTask and resumeTask
*/
interface TaskOptions {
act?: boolean
plan?: boolean
provider?: string
kanban?: boolean
model?: string
verbose?: boolean
cwd?: string
continue?: boolean
config?: string
thinking?: boolean | string
reasoningEffort?: string
maxConsecutiveMistakes?: string
yolo?: boolean
autoApproveAll?: boolean
doubleCheckCompletion?: boolean
autoCondense?: boolean
timeout?: string
json?: boolean
stdinWasPiped?: boolean
hooksDir?: string
subagents?: boolean
}
let telemetryDisposed = false
async function disposeTelemetryServices(): Promise<void> {
if (telemetryDisposed) {
return
}
telemetryDisposed = true
const { telemetryService } = await import("@/services/telemetry")
await Promise.allSettled([telemetryService.dispose()])
}
async function disposeCliContext(ctx: CliContext): Promise<void> {
const { ErrorService } = await import("@/services/error/ErrorService")
await ctx.controller.stateManager.flushPendingState()
await ctx.controller.dispose()
await ErrorService.get().dispose()
await disposeTelemetryServices()
}
async function setModeScopedState(currentMode: "act" | "plan", setter: (mode: "act" | "plan") => void): Promise<void> {
const { StateManager } = await import("@/core/storage/StateManager")
const stateManager = StateManager.get()
setter(currentMode)
const separateModels = stateManager.getGlobalSettingsKey("planActSeparateModelsSetting") ?? false
if (!separateModels) {
const otherMode: "act" | "plan" = currentMode === "act" ? "plan" : "act"
setter(otherMode)
}
}
async function normalizeReasoningEffort(value?: string): Promise<OpenaiReasoningEffort | undefined> {
if (value === undefined) {
return undefined
}
const { isOpenaiReasoningEffort } = await import("@/shared/storage/types")
const normalized = value.toLowerCase()
if (isOpenaiReasoningEffort(normalized)) {
return normalized
}
const { OPENAI_REASONING_EFFORT_OPTIONS } = await import("@/shared/storage/types")
const { printWarning } = await import("./utils/display")
printWarning(
`Invalid --reasoning-effort '${value}'. Using 'medium'. Valid values: ${OPENAI_REASONING_EFFORT_OPTIONS.join(", ")}.`,
)
return "medium"
}
async function validate_provider(provider: string): Promise<void> {
const { ALL_MODEL_MAPS, ALL_PROVIDERS } = await import("@shared/api")
const { printError } = await import("./utils/display")
const { exit } = await import("node:process")
if (provider.startsWith("http://") || provider.startsWith("https://")) {
return
}
const validProviders = ALL_PROVIDERS || Array.from(new Set(ALL_MODEL_MAPS.map(([p]) => p)))
if (!validProviders.includes(provider as any)) {
printError(`Invalid provider '${provider}'. Valid providers: ${validProviders.sort().join(", ")}`)
exit(1)
}
}
async function normalizeMaxConsecutiveMistakes(value?: string): Promise<number | undefined> {
if (value === undefined) {
return undefined
}
const parsed = Number.parseInt(value, 10)
if (Number.isNaN(parsed) || parsed < 1) {
const { printWarning } = await import("./utils/display")
printWarning(`Invalid --max-consecutive-mistakes value '${value}'. Expected integer >= 1.`)
return undefined
}
return parsed
}
async function applyTaskOptions(options: TaskOptions): Promise<void> {
const { StateManager } = await import("@/core/storage/StateManager")
const { telemetryService } = await import("@/services/telemetry")
const { getProviderModelIdKey } = await import("@/shared/storage")
const { printWarning, printError, printInfo } = await import("./utils/display")
const { exit } = await import("node:process")
const stateManager = StateManager.get()
if (process.env.OPENAI_COMPATIBLE_CUSTOM_KEY || process.env.OPENAI_API_BASE) {
const customKeyName = process.env.OPENAI_API_BASE ? "OPENAI_API_BASE" : "OPENAI_COMPATIBLE_CUSTOM_KEY"
if (!options.provider || !options.model) {
printError(`Error: ${customKeyName} requires --provider (base URL) and --model to be specified.`)
exit(1)
}
if (!options.provider || !options.provider.startsWith("http")) {
printError(`Error: When using ${customKeyName}, --provider must be a base URL (starting with http/https).`)
exit(1)
}
}
// Apply mode flag first so currentMode is correct for overrides
if (options.plan) {
stateManager.setSessionOverride("mode", "plan")
telemetryService.captureHostEvent("mode_flag", "plan")
} else if (options.act) {
stateManager.setSessionOverride("mode", "act")
telemetryService.captureHostEvent("mode_flag", "act")
}
// Validate provider/model combination
if (options.provider && !options.model) {
printError("Error: --provider requires --model to be specified.")
exit(1)
}
// Apply model override if specified
if (options.model) {
const currentMode = (stateManager.getGlobalSettingsKey("mode") || "act") as "act" | "plan"
if (options.provider) {
await validate_provider(options.provider)
}
// Determine the target provider based on current mode or explicit flag
let targetProvider: ApiProvider
if (options.provider && (options.provider.startsWith("http://") || options.provider.startsWith("https://"))) {
targetProvider = "openai"
stateManager.setSessionOverride("openAiBaseUrl", options.provider)
} else {
const providerKey = currentMode === "act" ? "actModeApiProvider" : "planModeApiProvider"
targetProvider = (options.provider as ApiProvider) || (stateManager.getGlobalSettingsKey(providerKey) as ApiProvider)
}
await setModeScopedState(currentMode, (mode) => {
const pKey = mode === "act" ? "actModeApiProvider" : "planModeApiProvider"
// Ensure the provider is synced if setModeScopedState calls us for multiple modes
stateManager.setSessionOverride(pKey, targetProvider)
const modelKey = getProviderModelIdKey(targetProvider, mode)
if (modelKey) {
stateManager.setSessionOverride(modelKey, options.model!)
}
})
telemetryService.captureHostEvent("model_flag", options.model)
if (options.provider) {
telemetryService.captureHostEvent("provider_flag", options.provider)
}
}
const currentMode = (stateManager.getGlobalSettingsKey("mode") || "act") as "act" | "plan"
// Set thinking budget based on --thinking flag (boolean or number)
if (options.thinking !== undefined) {
let thinkingBudget = 1024
if (typeof options.thinking === "string") {
const parsed = Number.parseInt(options.thinking, 10)
if (Number.isNaN(parsed) || parsed < 0) {
printWarning(`Invalid --thinking value '${options.thinking}'. Using default 1024.`)
} else {
thinkingBudget = parsed
}
}
await setModeScopedState(currentMode, (mode) => {
const thinkingKey = mode === "act" ? "actModeThinkingBudgetTokens" : "planModeThinkingBudgetTokens"
stateManager.setSessionOverride(thinkingKey, thinkingBudget)
})
telemetryService.captureHostEvent("thinking_flag", "true")
}
const reasoningEffort = await normalizeReasoningEffort(options.reasoningEffort)
if (reasoningEffort !== undefined) {
await setModeScopedState(currentMode, (mode) => {
const reasoningKey = mode === "act" ? "actModeReasoningEffort" : "planModeReasoningEffort"
stateManager.setSessionOverride(reasoningKey, reasoningEffort)
})
telemetryService.captureHostEvent("reasoning_effort_flag", reasoningEffort)
}
const maxConsecutiveMistakes = await normalizeMaxConsecutiveMistakes(options.maxConsecutiveMistakes)
if (maxConsecutiveMistakes !== undefined) {
stateManager.setSessionOverride("maxConsecutiveMistakes", maxConsecutiveMistakes)
telemetryService.captureHostEvent("max_consecutive_mistakes_flag", String(maxConsecutiveMistakes))
}
// Set yolo mode as a session-scoped override so AutoApprove picks it up,
// but it is never persisted to disk (setSessionOverride never touches pendingGlobalState).
if (options.yolo) {
stateManager.setSessionOverride("yoloModeToggled", true)
telemetryService.captureHostEvent("yolo_flag", "true")
}
// Set auto-approve-all as a session-scoped override so CLI flag does not
// persist user settings to disk.
if (options.autoApproveAll) {
stateManager.setSessionOverride("autoApproveAllToggled", true)
telemetryService.captureHostEvent("auto_approve_all_flag", "true")
}
// Set double-check completion based on flag
if (options.doubleCheckCompletion) {
stateManager.setSessionOverride("doubleCheckCompletionEnabled", true)
telemetryService.captureHostEvent("double_check_completion_flag", "true")
}
if (options.subagents) {
stateManager.setSessionOverride("subagentsEnabled", true)
}
if (options.autoCondense) {
stateManager.setSessionOverride("useAutoCondense", true)
}
}
/**
* Get mode selection result using the extracted, testable selectOutputMode function.
* This wrapper provides the current process TTY state.
*/
async function getModeSelection(options: TaskOptions) {
const { selectOutputMode } = await import("./utils/mode-selection")
return selectOutputMode({
stdoutIsTTY: process.stdout.isTTY === true,
stdinIsTTY: process.stdin.isTTY === true,
stdinWasPiped: options.stdinWasPiped ?? false,
json: options.json,
yolo: options.yolo,
})
}
/**
* Determine if plain text mode should be used based on options and environment.
*/
async function shouldUsePlainTextMode(options: TaskOptions): Promise<boolean> {
return (await getModeSelection(options)).usePlainTextMode
}
/**
* Get the reason for using plain text mode (for telemetry).
*/
async function getPlainTextModeReason(options: TaskOptions): Promise<string> {
return (await getModeSelection(options)).reason
}
function getNpxCommand(): string {
return process.platform === "win32" ? "npx.cmd" : "npx"
}
async function runKanbanAlias(): Promise<void> {
const { printWarning } = await import("./utils/display")
const child = spawn(getNpxCommand(), ["-y", "kanban", "--agent", "dirac"], {
stdio: "inherit",
})
child.on("error", () => {
printWarning("Failed to run 'npx kanban --agent dirac'. Make sure npx is installed and available in PATH.")
exit(1)
})
child.on("close", (code) => {
exit(code ?? 1)
})
}
/**
* Run a task in plain text mode (no Ink UI).
* Handles auth check, task execution, cleanup, and exit.
*/
async function runTaskInPlainTextMode(
ctx: CliContext,
options: TaskOptions,
taskConfig: {
prompt?: string
taskId?: string
imageDataUrls?: string[]
},
): Promise<never> {
const { isAuthConfigured } = await import("./utils/auth")
const { printWarning } = await import("./utils/display")
const { telemetryService } = await import("@/services/telemetry")
const { runPlainTextTask } = await import("./utils/plain-text-task")
// Set flag so shutdown handler knows not to clear Ink UI lines
isPlainTextMode = true
// Check if auth is configured before attempting to run the task
// In plain text mode we can't show the interactive auth flow
const hasAuth = await isAuthConfigured()
if (!hasAuth) {
printWarning("Not authenticated. Please run 'dirac auth' first to configure your API credentials.")
await disposeCliContext(ctx)
exit(1)
}
const reason = await getPlainTextModeReason(options)
telemetryService.captureHostEvent("plain_text_mode", reason)
// Plain text mode: no Ink rendering, just clean text output
const success = await runPlainTextTask({
controller: ctx.controller,
yolo: options.yolo || options.autoApproveAll,
prompt: taskConfig.prompt,
taskId: taskConfig.taskId,
imageDataUrls: taskConfig.imageDataUrls,
verbose: options.verbose,
jsonOutput: options.json,
timeoutSeconds: options.timeout ? Number.parseInt(options.timeout, 10) : undefined,
})
// Cleanup
await disposeCliContext(ctx)
// Ensure stdout is fully drained before exiting - critical for piping
await drainStdout()
exit(success ? 0 : 1)
}
/**
* Create the standard cleanup function for Ink apps.
*/
function createInkCleanup(ctx: CliContext, onTaskError?: () => boolean): () => Promise<void> {
return async () => {
await disposeCliContext(ctx)
if (onTaskError?.()) {
const { printWarning } = await import("./utils/display")
printWarning("Task ended with errors.")
exit(1)
}
exit(0)
}
}
// Track active context for graceful shutdown
let activeContext: CliContext | null = null
let isShuttingDown = false
// Track if we're in plain text mode (no Ink UI) - set by runTask when piped stdin detected
let isPlainTextMode = false
/**
* Wait for stdout to fully drain before exiting.
* Critical for piping - ensures data is flushed to the next command in the pipe.
*/
async function drainStdout(): Promise<void> {
return new Promise<void>((resolve) => {
// Check if stdout needs draining
if (process.stdout.writableNeedDrain) {
process.stdout.once("drain", resolve)
} else {
// Give a small delay to ensure any pending writes complete
setImmediate(resolve)
}
})
}
export async function captureUnhandledException(reason: Error, context: string) {
try {
const { ErrorService } = await import("@/services/error/ErrorService")
const { Logger } = await import("@/shared/services/Logger")
// ErrorService may not be initialized yet (e.g., error occurred before initializeCli())
// so we guard with a try/get pattern rather than letting ErrorService.get() throw
let errorService: any = null
try {
errorService = ErrorService.get()
} catch {
// ErrorService not yet initialized; skip capture
}
if (errorService) {
await errorService.captureException(reason, { context })
// dispose flushes any pending error captures to ensure they're sent before the process exits
return errorService.dispose()
}
} catch {
// Ignore errors during shutdown to avoid an infinite loop
try {
const { Logger } = await import("@/shared/services/Logger")
Logger.info("Error capturing unhandled exception. Proceeding with shutdown.")
} catch {
// Even Logger failed
}
}
}
/**
* Determines if the auth command should proceed with quick setup (non-interactive)
* based on provided flags and inferred values (from environment).
*/
export function shouldDoQuickAuth(
options: {
provider?: string
apikey?: string
modelid?: string
baseurl?: string
azureApiVersion?: string
},
inferred: {
provider?: string
apikey?: string
modelid?: string
},
): boolean {
const hasAnyAuthFlag = !!(
options.provider ||
options.apikey ||
options.modelid ||
options.baseurl ||
options.azureApiVersion
)
const hasAllRequiredFields = !!(inferred.provider && inferred.apikey && inferred.modelid)
// We do quick setup if we have all required fields AND the user provided at least one flag.
return hasAllRequiredFields && hasAnyAuthFlag
}
export function hasExplicitAuthQuickSetupFlags(options: { provider?: string; apikey?: string; modelid?: string }): boolean {
return !!(options.provider && options.apikey && options.modelid)
}
const EXIT_TIMEOUT_MS = 3000
async function onUnhandledException(reason: unknown, context: string) {
const { Logger } = await import("@/shared/services/Logger")
const { restoreConsole } = await import("./utils/console")
Logger.error("Unhandled exception:", reason)
const finalError = reason instanceof Error ? reason : new Error(String(reason))
restoreConsole()
console.error(finalError)
setTimeout(() => process.exit(1), EXIT_TIMEOUT_MS)
captureUnhandledException(finalError, context).finally(() => {
process.exit(1)
})
}
function setupSignalHandlers() {
const shutdown = async (signal: string) => {
const { printWarning } = await import("./utils/display")
if (isShuttingDown) {
// Force exit on second signal
process.exit(1)
}
isShuttingDown = true
// Notify components to hide UI before shutdown
shutdownEvent.fire()
// Only clear Ink UI lines if we're not in plain text mode
// In plain text mode, there's no Ink UI to clear and the ANSI codes
// would corrupt the streaming output
if (!isPlainTextMode) {
// Clear several lines to remove the input field and footer from display
// Move cursor up and clear lines (input box + footer rows)
const linesToClear = 8 // Input box (3 lines with border) + footer (4-5 lines)
process.stdout.write(`\x1b[${linesToClear}A\x1b[J`)
}
printWarning(`${signal} received, shutting down...`)
try {
if (activeContext) {
const task = activeContext.controller.task
if (task) {
task.abortTask()
}
await disposeCliContext(activeContext)
} else {
// Best-effort flush of restored yolo state when no active context
try {
const { StateManager } = await import("@/core/storage/StateManager")
await StateManager.get().flushPendingState()
} catch {
// StateManager may not be initialized yet
}
try {
const { ErrorService } = await import("@/services/error/ErrorService")
await ErrorService.get().dispose()
} catch {
// ErrorService may not be initialized yet
}
await disposeCliContext(activeContext as any) // This will call disposeTelemetryServices
}
} catch {
// Best effort cleanup
}
process.exit(0)
}
process.on("SIGINT", () => shutdown("SIGINT"))
process.on("SIGTERM", () => shutdown("SIGTERM"))
// Suppress known abort errors from unhandled rejections
// These occur when task is cancelled and async operations throw "Dirac instance aborted"
process.on("unhandledRejection", async (reason: unknown) => {
const message = reason instanceof Error ? reason.message : String(reason)
// Silently ignore abort-related errors - they're expected during task cancellation
if (message.includes("aborted") || message.includes("abort")) {
try {
const { Logger } = await import("@/shared/services/Logger")
Logger.info("Suppressed unhandled rejection due to abort:", message)
} catch {
// Logger not available
}
return
}
// For other unhandled rejections, capture the exception and log to file via Logger (if available)
// This won't show in terminal but will be in log files for debugging
onUnhandledException(reason, "unhandledRejection")
})
process.on("uncaughtException", (reason: unknown) => {
onUnhandledException(reason, "uncaughtException")
})
}
setupSignalHandlers()
interface CliContext {
extensionContext: any
dataDir: string
extensionDir: string
workspacePath: string
controller: Controller
}
interface InitOptions {
config?: string
cwd?: string
hooksDir?: string
verbose?: boolean
enableAuth?: boolean
}
/**
* Initialize all CLI infrastructure and return context needed for commands
*/
async function initializeCli(options: InitOptions): Promise<CliContext> {
const { setRuntimeHooksDir } = await import("@/core/storage/disk")
const { initializeCliContext } = await import("./vscode-context")
const { Logger } = await import("@/shared/services/Logger")
const { DiracEndpoint } = await import("@/config")
const { autoUpdateOnStartup } = await import("./utils/update")
const { Session } = await import("@/shared/services/Session")
const { AuthHandler } = await import("@/hosts/external/AuthHandler")
const { HostProvider } = await import("@/hosts/host-provider")
const { CliWebviewProvider } = await import("./controllers/CliWebviewProvider")
const { FileEditProvider } = await import("@/integrations/editor/FileEditProvider")
const { CliCommentReviewController } = await import("./controllers/CliCommentReviewController")
const { StandaloneTerminalManager } = await import("@/integrations/terminal/standalone/StandaloneTerminalManager")
const { createCliHostBridgeProvider } = await import("./controllers")
const { getCliBinaryPath, DIRAC_CLI_DIR } = await import("./utils/path")
const { StateManager } = await import("@/core/storage/StateManager")
const { ErrorService } = await import("@/services/error/ErrorService")
const { telemetryService } = await import("@/services/telemetry")
const { SymbolIndexService } = await import("@/services/symbol-index/SymbolIndexService")
const workspacePath = options.cwd || process.cwd()
setRuntimeHooksDir(options.hooksDir)
const { extensionContext, storageContext, DATA_DIR, EXTENSION_DIR } = initializeCliContext({
diracDir: options.config,
workspaceDir: workspacePath,
})
// Set up output channel and Logger early so DiracEndpoint.initialize logs are captured
const outputChannel = window.createOutputChannel("Dirac CLI")
const logToChannel = (message: string) => outputChannel.appendLine(message)
// Configure the shared Logging class early to capture all initialization logs
Logger.subscribe(logToChannel)
await DiracEndpoint.initialize(EXTENSION_DIR)
// Auto-update check (after endpoints initialized, so we can detect bundled configs)
autoUpdateOnStartup(CLI_VERSION)
// Initialize/reset session tracking for this CLI run
Session.reset()
if (options.enableAuth) {
AuthHandler.getInstance().setEnabled(true)
}
outputChannel.appendLine(
`Dirac CLI initialized. Data dir: ${DATA_DIR}, Extension dir: ${EXTENSION_DIR}, Log dir: ${DIRAC_CLI_DIR.log}`,
)
HostProvider.initialize(
"cli",
() => new CliWebviewProvider(extensionContext as any),
() => new FileEditProvider(),
() => new CliCommentReviewController(),
() => new StandaloneTerminalManager(),
createCliHostBridgeProvider(workspacePath),
logToChannel,
async (path: string) => (options.enableAuth ? AuthHandler.getInstance().getCallbackUrl(path) : ""),
getCliBinaryPath,
EXTENSION_DIR,
DATA_DIR,
async (_cwd: string) => undefined
)
await StateManager.initialize(storageContext)
const stateManager = StateManager.get()
const { getProviderFromEnv } = await import("@shared/storage/env-config")
const envProvider = getProviderFromEnv()
if (envProvider) {
if (!stateManager.getGlobalSettingsKey("actModeApiProvider")) {
stateManager.setSessionOverride("actModeApiProvider", envProvider)
}
if (!stateManager.getGlobalSettingsKey("planModeApiProvider")) {
stateManager.setSessionOverride("planModeApiProvider", envProvider)
}
}
await ErrorService.initialize()
const webview = HostProvider.get().createDiracWebviewProvider() as any
const controller = webview.controller as Controller
await telemetryService.captureExtensionActivated()
await telemetryService.captureHostEvent("dirac_cli", "initialized")
// =============== Symbol Index Service ===============
// Initialize symbol index for the project in background
SymbolIndexService.getInstance()
.initialize(workspacePath)
.catch((error) => {
Logger.error("[Dirac] Failed to initialize SymbolIndexService:", error)
})
const ctx = { extensionContext, dataDir: DATA_DIR, extensionDir: EXTENSION_DIR, workspacePath, controller }
activeContext = ctx
return ctx
}
/**
* Run an Ink app with proper cleanup handling
*/
async function runInkApp(element: any, cleanup: () => Promise<void>): Promise<void> {
const { render } = await import("ink")
const { restoreConsole } = await import("./utils/console")
// Clear terminal for clean UI - robot will render at row 1
process.stdout.write("\x1b[2J\x1b[3J\x1b[H")
// Note: incrementalRendering is enabled to reduce terminal bandwidth and improve responsiveness.
// We previously disabled this due to resize glitches, but our useTerminalSize hook now
// handles this by clearing the screen and forcing a full React remount on resize,
// which resets Ink's internal line tracking.
const { waitUntilExit, unmount } = render(element, {
exitOnCtrlC: true,
patchConsole: false,
// @ts-expect-error: synchronizedUpdateMode is supported by @jrichman/ink but not in the type definitions
synchronizedUpdateMode: true,
incrementalRendering: true,
})
try {
await waitUntilExit()
} finally {
try {
unmount()
} catch {
// Already unmounted
}
restoreConsole()
await cleanup()
}
}
/**
* Run a task with the given prompt - uses welcome view for consistent behavior
*/
async function runTask(prompt: string, options: TaskOptions & { images?: string[] }, existingContext?: CliContext) {
const { parseImagesFromInput, processImagePaths } = await import("./utils/parser")
const { telemetryService } = await import("@/services/telemetry")
const { StateManager } = await import("@/core/storage/StateManager")
const { checkRawModeSupport } = await import("./context/StdinContext")
const React = (await import("react")).default
const { App } = await import("./components/App")
const ctx = existingContext || (await initializeCli({ ...options, enableAuth: true }))
// Parse images from the prompt text (e.g., @/path/to/image.png)
const { prompt: cleanPrompt, imagePaths: parsedImagePaths } = parseImagesFromInput(prompt)
// Combine parsed image paths with explicit --images option
const allImagePaths = [...(options.images || []), ...parsedImagePaths]
// Convert image file paths to base64 data URLs
const imageDataUrls = await processImagePaths(allImagePaths)
// Use clean prompt (with image refs removed)
const taskPrompt = cleanPrompt || prompt
// Task without prompt starts in interactive mode
telemetryService.captureHostEvent("task_command", prompt ? "task" : "interactive")
// Capture piped stdin telemetry now that HostProvider is initialized
if (options.stdinWasPiped) {
telemetryService.captureHostEvent("piped", "detached")
}
// Apply shared task options (mode, model, thinking, yolo)
await applyTaskOptions(options)
await StateManager.get().flushPendingState()
// Use plain text mode when output is redirected, stdin was piped, JSON mode is enabled, or --yolo flag is used
if (await shouldUsePlainTextMode(options)) {
return runTaskInPlainTextMode(ctx, options, {
prompt: taskPrompt,
imageDataUrls: imageDataUrls.length > 0 ? imageDataUrls : undefined,
})
}
// Interactive mode: Render the welcome view with optional initial prompt/images
// If prompt provided (dirac task "prompt"), ChatView will auto-submit
// If no prompt (dirac interactive), user will type it in
let taskError = false
await runInkApp(
React.createElement(App, {
view: "welcome",
verbose: options.verbose,
controller: ctx.controller,
isRawModeSupported: checkRawModeSupport(),
initialPrompt: taskPrompt || undefined,
initialImages: imageDataUrls.length > 0 ? imageDataUrls : undefined,
onError: () => {
taskError = true
},
onWelcomeExit: () => {
// User pressed Esc; Ink exits and cleanup handles process exit.
},
}),
createInkCleanup(ctx, () => taskError),
)
}
/**
* List task history
*/
async function listHistory(options: { config?: string; limit?: number; page?: number }) {
const { StateManager } = await import("@/core/storage/StateManager")
const { telemetryService } = await import("@/services/telemetry")
const { printInfo } = await import("./utils/display")
const { checkRawModeSupport } = await import("./context/StdinContext")
const React = (await import("react")).default
const { App } = await import("./components/App")
const ctx = await initializeCli(options)
const taskHistory = StateManager.get().getGlobalStateKey("taskHistory") || []
// Sort by timestamp (newest first) before pagination
const sortedHistory = [...taskHistory].sort((a: any, b: any) => (b.ts || 0) - (a.ts || 0))
const limit = typeof options.limit === "string" ? Number.parseInt(options.limit, 10) : options.limit || 10
const initialPage = typeof options.page === "string" ? Number.parseInt(options.page, 10) : options.page || 1
const totalCount = sortedHistory.length
const totalPages = Math.ceil(totalCount / limit)
telemetryService.captureHostEvent("history_command", "executed")
if (sortedHistory.length === 0) {
printInfo("No task history found.")
await disposeCliContext(ctx)
exit(0)
}
await runInkApp(
React.createElement(App, {
view: "history",
historyItems: [],
historyAllItems: sortedHistory,
controller: ctx.controller,
historyPagination: { page: initialPage, totalPages, totalCount, limit },
isRawModeSupported: checkRawModeSupport(),
}),
async () => {
await disposeCliContext(ctx)
exit(0)
},
)
}
/**
* Show current configuration
*/
async function showConfig(options: { config?: string }) {
const { StateManager } = await import("@/core/storage/StateManager")
const { telemetryService } = await import("@/services/telemetry")
const { getHooksEnabledSafe } = await import("@/core/hooks/hooks-utils")
const { checkRawModeSupport } = await import("./context/StdinContext")
const React = (await import("react")).default
const ctx = await initializeCli(options)
const stateManager = StateManager.get()
// Dynamically import the wrapper to avoid circular dependencies
const { ConfigViewWrapper } = await import("./components/ConfigViewWrapper")
telemetryService.captureHostEvent("config_command", "executed")
await runInkApp(
React.createElement(ConfigViewWrapper, {
controller: ctx.controller,
dataDir: ctx.dataDir,
globalState: stateManager.getAllGlobalStateEntries(),
workspaceState: stateManager.getAllWorkspaceStateEntries(),
hooksEnabled: getHooksEnabledSafe(stateManager.getGlobalSettingsKey("hooksEnabled")),
skillsEnabled: true,
isRawModeSupported: checkRawModeSupport(),
}),
async () => {
await disposeCliContext(ctx)
exit(0)
},
)
}
/**
* Run authentication flow
*/
/**
* Perform quick auth setup without UI - validates and saves configuration directly
*/
async function performQuickAuthSetup(
ctx: CliContext,
options: { provider: string; apikey: string; modelid: string; baseurl?: string; azureApiVersion?: string },
): Promise<{ success: boolean; error?: string }> {
const { isValidCliProvider, getValidCliProviders } = await import("./utils/providers")
const { applyProviderConfig } = await import("./utils/provider-config")
const { StateManager } = await import("@/core/storage/StateManager")
const { provider, apikey, modelid, baseurl, azureApiVersion } = options
const normalizedProvider = provider.toLowerCase().trim()
if (!isValidCliProvider(normalizedProvider)) {
const validProviders = getValidCliProviders()
return { success: false, error: `Invalid provider '${provider}'. Supported providers: ${validProviders.join(", ")}` }
}
if (normalizedProvider === "bedrock") {
return {
success: false,
error: "Bedrock provider is not supported for quick setup due to complex authentication requirements. Please use interactive setup.",
}
}
if (baseurl && !["openai", "openai-native"].includes(normalizedProvider)) {
return { success: false, error: "Base URL is only supported for OpenAI and OpenAI-compatible providers" }
}
// Save configuration using shared utility
await applyProviderConfig({
providerId: normalizedProvider,
apiKey: apikey,
modelId: modelid,
baseUrl: baseurl,
azureApiVersion: azureApiVersion,
controller: ctx.controller,
})
// Mark onboarding as complete
StateManager.get().setGlobalState("welcomeViewCompleted", true)
await StateManager.get().flushPendingState()
return { success: true }
}
async function runAuth(options: {
provider?: string
apikey?: string
modelid?: string
baseurl?: string
azureApiVersion?: string
verbose?: boolean
cwd?: string
config?: string
}) {
const { telemetryService } = await import("@/services/telemetry")
const { printWarning, printInfo } = await import("./utils/display")
const { checkRawModeSupport } = await import("./context/StdinContext")
const React = (await import("react")).default
const { App } = await import("./components/App")
const ctx = await initializeCli({ ...options, enableAuth: true })
let provider = options.provider
let apikey = options.apikey
let modelid = options.modelid
let azureApiVersion = options.azureApiVersion
if (!provider || !apikey || !modelid) {
const { getSecretsFromEnv, getProviderFromEnv } = await import("@shared/storage/env-config")
const { ProviderToApiKeyMap, getProviderDefaultModelId } = await import("@shared/storage")
if (!provider) {
provider = getProviderFromEnv()
if (provider) {
printInfo(`Inferred provider "${provider}" from environment variables`)
}
}
if (provider && !apikey) {
const envSecrets = getSecretsFromEnv()
const normalizedProvider = provider.toLowerCase().trim()
const secretKeyOrKeys = (ProviderToApiKeyMap as any)[normalizedProvider]
if (secretKeyOrKeys) {
const keys = Array.isArray(secretKeyOrKeys) ? secretKeyOrKeys : [secretKeyOrKeys]
for (const key of keys) {
const value = envSecrets[key as keyof typeof envSecrets]
if (value) {
apikey = value
printInfo(`Using API key from environment for provider "${provider}"`)
break
}
}
}
}
if (provider && !modelid) {
modelid = (getProviderDefaultModelId as any)(provider) || undefined
if (modelid) {
printInfo(`Using default model "${modelid}" for provider "${provider}"`)
}
}
}
const isQuickSetup = shouldDoQuickAuth(options, { provider, apikey, modelid })
telemetryService.captureHostEvent("auth_command", isQuickSetup ? "quick_setup" : "interactive")
// Quick setup mode - no UI, just save configuration and exit
if (isQuickSetup) {
const result = await performQuickAuthSetup(ctx, {
provider: provider!,
apikey: apikey!,
modelid: modelid!,
baseurl: options.baseurl,
azureApiVersion: options.azureApiVersion,
})
if (!result.success) {
printWarning(result.error || "Quick setup failed")
await telemetryService.captureHostEvent("auth", "error")
await disposeCliContext(ctx)