-
Notifications
You must be signed in to change notification settings - Fork 192
Expand file tree
/
Copy pathoracle-cli.ts
More file actions
executable file
·2213 lines (2123 loc) · 75.9 KB
/
oracle-cli.ts
File metadata and controls
executable file
·2213 lines (2123 loc) · 75.9 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
#!/usr/bin/env node
import "dotenv/config";
import { spawn } from "node:child_process";
import { fileURLToPath } from "node:url";
import { once } from "node:events";
import { Command, Option } from "commander";
import type { OptionValues } from "commander";
// Allow `npx @steipete/oracle oracle-mcp` to resolve the MCP server even though npx runs the default binary.
if (process.argv[2] === "oracle-mcp") {
const { startMcpServer } = await import("../src/mcp/server.js");
await startMcpServer();
process.exit(0);
}
import { resolveEngine, type EngineMode, defaultWaitPreference } from "../src/cli/engine.js";
import { shouldRequirePrompt } from "../src/cli/promptRequirement.js";
import { resolveDashPrompt } from "../src/cli/stdin.js";
import chalk from "chalk";
import type { SessionMetadata, SessionMode, BrowserSessionConfig } from "../src/sessionStore.js";
import { sessionStore, pruneOldSessions } from "../src/sessionStore.js";
import {
DEFAULT_MODEL,
MODEL_CONFIGS,
readFiles,
estimateRequestTokens,
buildRequestBody,
} from "../src/oracle.js";
import { isKnownModel } from "../src/oracle/modelResolver.js";
import type { ModelName, PreviewMode, RunOracleOptions } from "../src/oracle.js";
import { CHATGPT_URL } from "../src/browserMode.js";
import { createRemoteBrowserExecutor } from "../src/remote/client.js";
import { createGeminiWebExecutor } from "../src/gemini-web/index.js";
import { applyHelpStyling } from "../src/cli/help.js";
import {
collectPaths,
collectModelList,
parseFloatOption,
parseIntOption,
parseSearchOption,
usesDefaultStatusFilters,
resolvePreviewMode,
normalizeModelOption,
normalizeBaseUrl,
resolveApiModel,
inferModelFromLabel,
parseHeartbeatOption,
parseTimeoutOption,
parseDurationOption,
mergePathLikeOptions,
dedupePathInputs,
} from "../src/cli/options.js";
import { copyToClipboard } from "../src/cli/clipboard.js";
import { buildMarkdownBundle } from "../src/cli/markdownBundle.js";
import { shouldDetachSession } from "../src/cli/detach.js";
import { applyHiddenAliases } from "../src/cli/hiddenAliases.js";
import { buildBrowserConfig, resolveBrowserModelLabel } from "../src/cli/browserConfig.js";
import { performSessionRun } from "../src/cli/sessionRunner.js";
import type { BrowserSessionRunnerDeps } from "../src/browser/sessionRunner.js";
import { isMediaFile } from "../src/browser/prompt.js";
import { attachSession, showStatus, formatCompletionSummary } from "../src/cli/sessionDisplay.js";
import { formatCompactNumber } from "../src/cli/format.js";
import { formatIntroLine } from "../src/cli/tagline.js";
import { warnIfOversizeBundle } from "../src/cli/bundleWarnings.js";
import { formatRenderedMarkdown } from "../src/cli/renderOutput.js";
import { resolveRenderFlag, resolveRenderPlain } from "../src/cli/renderFlags.js";
import { resolveGeminiModelId } from "../src/oracle/gemini.js";
import {
handleSessionCommand,
type StatusOptions,
formatSessionCleanupMessage,
} from "../src/cli/sessionCommand.js";
import { isErrorLogged } from "../src/cli/errorUtils.js";
import { handleSessionAlias, handleStatusFlag } from "../src/cli/rootAlias.js";
import { resolveOutputPath } from "../src/cli/writeOutputPath.js";
import { getCliVersion } from "../src/version.js";
import { runDryRunSummary, runBrowserPreview } from "../src/cli/dryRun.js";
import { launchTui } from "../src/cli/tui/index.js";
import {
resolveNotificationSettings,
deriveNotificationSettingsFromMetadata,
type NotificationSettings,
} from "../src/cli/notifier.js";
import { loadUserConfig, type UserConfig } from "../src/config.js";
import { applyBrowserDefaultsFromConfig } from "../src/cli/browserDefaults.js";
import { shouldBlockDuplicatePrompt } from "../src/cli/duplicatePromptGuard.js";
import { resolveRemoteServiceConfig } from "../src/remote/remoteServiceConfig.js";
import { resolveConfiguredMaxFileSizeBytes } from "../src/cli/fileSize.js";
interface CliOptions extends OptionValues {
prompt?: string;
message?: string;
file?: string[];
maxFileSizeBytes?: number;
include?: string[];
files?: string[];
path?: string[];
paths?: string[];
render?: boolean;
model: string;
models?: string[];
force?: boolean;
slug?: string;
filesReport?: boolean;
maxInput?: number;
maxOutput?: number;
system?: string;
silent?: boolean;
search?: boolean;
preview?: boolean | string;
previewMode?: PreviewMode;
apiKey?: string;
session?: string;
execSession?: string;
followup?: string;
followupModel?: string;
notify?: boolean;
notifySound?: boolean;
renderMarkdown?: boolean;
sessionId?: string;
engine?: EngineMode;
browser?: boolean;
timeout?: number | "auto";
background?: boolean;
httpTimeout?: number;
zombieTimeout?: number;
zombieLastActivity?: boolean;
browserChromeProfile?: string;
browserChromePath?: string;
browserCookiePath?: string;
chatgptUrl?: string;
browserUrl?: string;
browserTimeout?: string;
browserInputTimeout?: string;
browserProfileLockTimeout?: string;
browserCookieWait?: string;
browserNoCookieSync?: boolean;
browserInlineCookiesFile?: string;
browserCookieNames?: string;
browserInlineCookies?: string;
browserHeadless?: boolean;
browserHideWindow?: boolean;
browserKeepBrowser?: boolean;
browserModelStrategy?: "select" | "current" | "ignore";
browserManualLogin?: boolean;
browserManualLoginProfileDir?: string;
browserThinkingTime?: "light" | "standard" | "extended" | "heavy";
browserAllowCookieErrors?: boolean;
browserAttachments?: string;
browserInlineFiles?: boolean;
browserBundleFiles?: boolean;
remoteChrome?: string;
browserPort?: number;
browserDebugPort?: number;
remoteHost?: string;
remoteToken?: string;
youtube?: string;
generateImage?: string;
editImage?: string;
output?: string;
aspect?: string;
geminiShowThoughts?: boolean;
copyMarkdown?: boolean;
copy?: boolean;
verbose?: boolean;
debugHelp?: boolean;
heartbeat?: number;
status?: boolean;
dryRun?: boolean;
// tri-state: `true` (forced wait), `false` (forced detach), `undefined` (auto)
wait?: boolean;
baseUrl?: string;
azureEndpoint?: string;
azureDeployment?: string;
azureApiVersion?: string;
showModelId?: boolean;
retainHours?: number;
writeOutput?: string;
writeOutputPath?: string;
}
type ResolvedCliOptions = Omit<CliOptions, "model"> & {
model: ModelName;
models?: ModelName[];
effectiveModelId?: string;
writeOutputPath?: string;
previousResponseId?: string;
followupSessionId?: string;
followupModel?: string;
};
interface RestartCommandOptions {
// tri-state: `true` (forced wait), `false` (forced detach), `undefined` (auto)
wait?: boolean;
remoteHost?: string;
remoteToken?: string;
}
const VERSION = getCliVersion();
const CLI_ENTRYPOINT = fileURLToPath(import.meta.url);
const LEGACY_FLAG_ALIASES = new Map<string, string>([
["--[no-]notify", "--notify"],
["--[no-]notify-sound", "--notify-sound"],
["--[no-]background", "--background"],
]);
const normalizedArgv = process.argv.map((arg, index) => {
if (index < 2) return arg;
return LEGACY_FLAG_ALIASES.get(arg) ?? arg;
});
const rawCliArgs = normalizedArgv.slice(2);
const userCliArgs = rawCliArgs[0] === CLI_ENTRYPOINT ? rawCliArgs.slice(1) : rawCliArgs;
const isTty = process.stdout.isTTY;
const program = new Command();
let introPrinted = false;
program.hook("preAction", () => {
if (introPrinted) return;
console.log(formatIntroLine(VERSION, { env: process.env, richTty: isTty }));
introPrinted = true;
});
applyHelpStyling(program, VERSION, isTty);
program.hook("preAction", async (thisCommand) => {
if (thisCommand !== program) {
return;
}
if (userCliArgs.some((arg) => arg === "--help" || arg === "-h")) {
return;
}
if (userCliArgs.length === 0) {
// Let the root action handle zero-arg entry (help + hint to `oracle tui`).
return;
}
const opts = thisCommand.optsWithGlobals() as CliOptions;
applyHiddenAliases(opts, (key, value) => thisCommand.setOptionValue(key, value));
const positional = thisCommand.args?.[0] as string | undefined;
if (!opts.prompt && positional) {
opts.prompt = positional;
thisCommand.setOptionValue("prompt", positional);
}
const resolvedPrompt = await resolveDashPrompt(opts.prompt);
if (resolvedPrompt !== opts.prompt) {
opts.prompt = resolvedPrompt;
thisCommand.setOptionValue("prompt", resolvedPrompt);
}
if (shouldRequirePrompt(userCliArgs, opts)) {
console.log(
chalk.yellow('Prompt is required. Provide it via --prompt "<text>" or positional [prompt].'),
);
thisCommand.help({ error: false });
process.exitCode = 1;
return;
}
});
program
.name("oracle")
.description(
"One-shot GPT-5.4 Pro / GPT-5.4 / GPT-5.1 Codex tool for hard questions that benefit from large file context and server-side search.",
)
.version(VERSION)
.argument("[prompt]", "Prompt text (shorthand for --prompt).")
.option("-p, --prompt <text>", "User prompt to send to the model.")
.addOption(new Option("--message <text>", "Alias for --prompt.").hideHelp())
.option(
"--followup <sessionId|responseId>",
"Continue an OpenAI/Azure Responses API run from a stored response id (resp_...) or from a stored oracle session id.",
)
.option(
"--followup-model <model>",
"When following up a multi-model session, choose which model response to continue from.",
)
.option(
"-f, --file <paths...>",
"Files/directories or glob patterns to attach (prefix with !pattern to exclude). Oversized files are rejected automatically (default cap: 1 MB; configurable via ORACLE_MAX_FILE_SIZE_BYTES or config.maxFileSizeBytes).",
collectPaths,
[],
)
.addOption(
new Option("--include <paths...>", "Alias for --file.")
.argParser(collectPaths)
.default([])
.hideHelp(),
)
.addOption(
new Option("--files <paths...>", "Alias for --file.")
.argParser(collectPaths)
.default([])
.hideHelp(),
)
.addOption(
new Option("--path <paths...>", "Alias for --file.")
.argParser(collectPaths)
.default([])
.hideHelp(),
)
.addOption(
new Option("--paths <paths...>", "Alias for --file.")
.argParser(collectPaths)
.default([])
.hideHelp(),
)
.addOption(
new Option(
"--copy-markdown",
"Copy the assembled markdown bundle to the clipboard; pair with --render to print it too.",
).default(false),
)
.addOption(new Option("--copy").hideHelp().default(false))
.option("-s, --slug <words>", "Custom session slug (3-5 words).")
.option(
"-m, --model <model>",
'Model to target (gpt-5.4-pro default). Also gpt-5.4, gpt-5.1-pro, gpt-5-pro, gpt-5.1, gpt-5.1-codex API-only, gpt-5.2, gpt-5.2-instant, gpt-5.2-pro, gemini-3.1-pro API-only, gemini-3-pro, claude-4.5-sonnet, claude-4.1-opus, or ChatGPT labels like "5.2 Thinking" for browser runs).',
normalizeModelOption,
)
.addOption(
new Option(
"--models <models>",
'Comma-separated API model list to query in parallel (e.g., "gpt-5.4-pro,gemini-3-pro").',
)
.argParser(collectModelList)
.default([]),
)
.addOption(
new Option(
"-e, --engine <mode>",
"Execution engine (api | browser). Browser engine: GPT models automate ChatGPT; Gemini models use a cookie-based client for gemini.google.com. If omitted, oracle picks api when OPENAI_API_KEY is set, otherwise browser.",
).choices(["api", "browser"]),
)
.addOption(
new Option("--mode <mode>", "Alias for --engine (api | browser).")
.choices(["api", "browser"])
.hideHelp(),
)
.option(
"--files-report",
"Show token usage per attached file (also prints automatically when files exceed the token budget).",
false,
)
.option("-v, --verbose", "Enable verbose logging for all operations.", false)
.addOption(
new Option(
"--notify",
"Desktop notification when a session finishes (default on unless CI/SSH).",
).default(undefined),
)
.addOption(new Option("--no-notify", "Disable desktop notifications.").default(undefined))
.addOption(
new Option("--notify-sound", "Play a notification sound on completion (default off).").default(
undefined,
),
)
.addOption(new Option("--no-notify-sound", "Disable notification sounds.").default(undefined))
.addOption(
new Option(
"--timeout <seconds|auto>",
"Overall timeout before aborting the API call (auto = 60m for gpt-5.4-pro, 120s otherwise).",
)
.argParser(parseTimeoutOption)
.default("auto"),
)
.addOption(
new Option(
"--background",
"Use Responses API background mode (create + retrieve) for API runs.",
).default(undefined),
)
.addOption(
new Option("--no-background", "Disable Responses API background mode.").default(undefined),
)
.addOption(
new Option("--http-timeout <ms|s|m|h>", "HTTP client timeout for API requests (default 20m).")
.argParser((value) => parseDurationOption(value, "HTTP timeout"))
.default(undefined),
)
.addOption(
new Option(
"--zombie-timeout <ms|s|m|h>",
"Override stale-session cutoff used by `oracle status` (default 60m).",
)
.argParser((value) => parseDurationOption(value, "Zombie timeout"))
.default(undefined),
)
.option(
"--zombie-last-activity",
"Base stale-session detection on last log activity instead of start time.",
false,
)
.addOption(
new Option(
"--preview [mode]",
"(alias) Preview the request without calling the model (summary | json | full). Deprecated: use --dry-run instead.",
)
.hideHelp()
.choices(["summary", "json", "full"])
.preset("summary"),
)
.addOption(
new Option("--dry-run [mode]", "Preview without calling the model (summary | json | full).")
.choices(["summary", "json", "full"])
.preset("summary")
.default(false),
)
.addOption(new Option("--exec-session <id>").hideHelp())
.addOption(new Option("--session <id>").hideHelp())
.addOption(
new Option("--status", "Show stored sessions (alias for `oracle status`).")
.default(false)
.hideHelp(),
)
.option(
"--render-markdown",
"Print the assembled markdown bundle for prompt + files and exit; pair with --copy to put it on the clipboard.",
false,
)
.option("--render", "Alias for --render-markdown.", false)
.option(
"--render-plain",
"Render markdown without ANSI/highlighting (use plain text even in a TTY).",
false,
)
.option(
"--write-output <path>",
"Write only the final assistant message to this file (overwrites; multi-model appends .<model> before the extension).",
)
.option("--verbose-render", "Show render/TTY diagnostics when replaying sessions.", false)
.addOption(
new Option("--search <mode>", "Set server-side search behavior (on/off).")
.argParser(parseSearchOption)
.hideHelp(),
)
.addOption(
new Option("--max-input <tokens>", "Override the input token budget for the selected model.")
.argParser(parseIntOption)
.hideHelp(),
)
.addOption(
new Option("--max-output <tokens>", "Override the max output tokens for the selected model.")
.argParser(parseIntOption)
.hideHelp(),
)
.option(
"--base-url <url>",
"Override the OpenAI-compatible base URL for API runs (e.g. LiteLLM proxy endpoint).",
)
.option(
"--azure-endpoint <url>",
"Azure OpenAI Endpoint (e.g. https://resource.openai.azure.com/).",
)
.option("--azure-deployment <name>", "Azure OpenAI Deployment Name.")
.option("--azure-api-version <version>", "Azure OpenAI API Version.")
.addOption(
new Option("--browser", "(deprecated) Use --engine browser instead.").default(false).hideHelp(),
)
.addOption(
new Option(
"--browser-chrome-profile <name>",
"Chrome profile name/path for cookie reuse.",
).hideHelp(),
)
.addOption(
new Option(
"--browser-chrome-path <path>",
"Explicit Chrome or Chromium executable path.",
).hideHelp(),
)
.addOption(
new Option(
"--browser-cookie-path <path>",
"Explicit Chrome/Chromium cookie DB path for session reuse.",
),
)
.addOption(
new Option(
"--chatgpt-url <url>",
`Override the ChatGPT web URL (e.g., workspace/folder like https://chatgpt.com/g/.../project; default ${CHATGPT_URL}).`,
),
)
.addOption(
new Option(
"--browser-url <url>",
`Alias for --chatgpt-url (default ${CHATGPT_URL}).`,
).hideHelp(),
)
.addOption(
new Option(
"--browser-timeout <ms|s|m>",
"Maximum time to wait for an answer (default 1200s / 20m).",
).hideHelp(),
)
.addOption(
new Option(
"--browser-input-timeout <ms|s|m>",
"Maximum time to wait for the prompt textarea (default 60s).",
).hideHelp(),
)
.addOption(
new Option(
"--browser-recheck-delay <ms|s|m|h>",
"After an assistant timeout, wait this long then revisit the conversation to retry capture.",
).hideHelp(),
)
.addOption(
new Option(
"--browser-recheck-timeout <ms|s|m|h>",
"Time budget for the delayed recheck attempt (default 120s).",
).hideHelp(),
)
.addOption(
new Option(
"--browser-reuse-wait <ms|s|m|h>",
"Wait for a shared Chrome profile to appear before launching a new one (helps parallel runs).",
).hideHelp(),
)
.addOption(
new Option(
"--browser-profile-lock-timeout <ms|s|m|h>",
"Wait for the shared manual-login profile lock before sending (serializes parallel runs).",
).hideHelp(),
)
.addOption(
new Option(
"--browser-auto-reattach-delay <ms|s|m|h>",
"Delay before starting periodic auto-reattach attempts after a timeout.",
).hideHelp(),
)
.addOption(
new Option(
"--browser-auto-reattach-interval <ms|s|m|h>",
"Interval between auto-reattach attempts (0 disables).",
).hideHelp(),
)
.addOption(
new Option(
"--browser-auto-reattach-timeout <ms|s|m|h>",
"Time budget for each auto-reattach attempt (default 120s).",
).hideHelp(),
)
.addOption(
new Option(
"--browser-cookie-wait <ms|s|m>",
"Wait before retrying cookie sync when Chrome cookies are empty or locked.",
).hideHelp(),
)
.addOption(
new Option(
"--browser-port <port>",
"Use a fixed Chrome DevTools port (helpful on WSL firewalls).",
).argParser(parseIntOption),
)
.addOption(
new Option("--browser-debug-port <port>", "(alias) Use a fixed Chrome DevTools port.")
.argParser(parseIntOption)
.hideHelp(),
)
.addOption(
new Option(
"--browser-cookie-names <names>",
"Comma-separated cookie allowlist for sync.",
).hideHelp(),
)
.addOption(
new Option(
"--browser-inline-cookies <jsonOrBase64>",
"Inline cookies payload (JSON array or base64-encoded JSON).",
).hideHelp(),
)
.addOption(
new Option(
"--browser-inline-cookies-file <path>",
"Load inline cookies from file (JSON or base64 JSON).",
).hideHelp(),
)
.addOption(new Option("--browser-no-cookie-sync", "Skip copying cookies from Chrome.").hideHelp())
.addOption(
new Option(
"--browser-manual-login",
"Skip cookie copy; reuse a persistent automation profile and wait for manual ChatGPT login.",
).hideHelp(),
)
.addOption(new Option("--browser-headless", "Launch Chrome in headless mode.").hideHelp())
.addOption(
new Option(
"--browser-hide-window",
"Hide the Chrome window after launch (macOS headful only).",
).hideHelp(),
)
.addOption(
new Option("--browser-keep-browser", "Keep Chrome running after completion.").hideHelp(),
)
.addOption(
new Option(
"--browser-model-strategy <mode>",
"ChatGPT model picker strategy: select (default) switches to the requested model, current keeps the active model, ignore skips the picker entirely.",
).choices(["select", "current", "ignore"]),
)
.addOption(
new Option(
"--browser-thinking-time <level>",
"Thinking time intensity for Thinking/Pro models: light, standard, extended, heavy.",
)
.choices(["light", "standard", "extended", "heavy"])
.hideHelp(),
)
.addOption(
new Option(
"--browser-allow-cookie-errors",
"Continue even if Chrome cookies cannot be copied.",
).hideHelp(),
)
.addOption(
new Option(
"--browser-attachments <mode>",
"How to deliver --file inputs in browser mode: auto (default) pastes inline up to ~60k chars then uploads; never always paste inline; always always upload.",
)
.choices(["auto", "never", "always"])
.default("auto"),
)
.addOption(
new Option(
"--remote-chrome <host:port>",
"Connect to remote Chrome DevTools Protocol (e.g., 192.168.1.10:9222 or [2001:db8::1]:9222 for IPv6).",
),
)
.addOption(
new Option(
"--remote-host <host:port>",
"Delegate browser runs to a remote `oracle serve` instance.",
),
)
.addOption(
new Option("--remote-token <token>", "Access token for the remote `oracle serve` instance."),
)
.addOption(
new Option(
"--browser-inline-files",
"Alias for --browser-attachments never (force pasting file contents inline).",
).default(false),
)
.addOption(
new Option(
"--browser-bundle-files",
"Bundle all attachments into a single archive before uploading.",
).default(false),
)
.addOption(
new Option(
"--youtube <url>",
"YouTube video URL to analyze (Gemini web/cookie mode only; uses your signed-in Chrome cookies for gemini.google.com).",
),
)
.addOption(
new Option(
"--generate-image <file>",
"Generate image and save to file (Gemini web/cookie mode only; requires gemini.google.com Chrome cookies).",
),
)
.addOption(
new Option(
"--edit-image <file>",
"Edit existing image (use with --output, Gemini web/cookie mode only).",
),
)
.addOption(
new Option(
"--output <file>",
"Output file path for image operations (Gemini web/cookie mode only).",
),
)
.addOption(
new Option(
"--aspect <ratio>",
"Aspect ratio for image generation: 16:9, 1:1, 4:3, 3:4 (Gemini web/cookie mode only).",
),
)
.addOption(
new Option(
"--gemini-show-thoughts",
"Display Gemini thinking process (Gemini web/cookie mode only).",
).default(false),
)
.option(
"--retain-hours <hours>",
"Prune stored sessions older than this many hours before running (set 0 to disable).",
parseFloatOption,
)
.option(
"--force",
"Force start a new session even if an identical prompt is already running.",
false,
)
.option("--debug-help", "Show the advanced/debug option set and exit.", false)
.option(
"--heartbeat <seconds>",
"Emit periodic in-progress updates (0 to disable).",
parseHeartbeatOption,
30,
)
.addOption(new Option("--wait").default(undefined))
.addOption(new Option("--no-wait").default(undefined).hideHelp())
.showHelpAfterError("(use --help for usage)");
program.addHelpText(
"after",
`
Examples:
# Quick API run with two files
oracle --prompt "Summarize the risk register" --file docs/risk-register.md docs/risk-matrix.md
# Browser run (no API key) + globbed TypeScript sources, excluding tests
oracle --engine browser --prompt "Review the TS data layer" \\
--file "src/**/*.ts" --file "!src/**/*.test.ts"
# Build, print, and copy a markdown bundle (semi-manual)
oracle --render --copy -p "Review the TS data layer" --file "src/**/*.ts" --file "!src/**/*.test.ts"
`,
);
program
.command("serve")
.description("Run Oracle browser automation as a remote service for other machines.")
.option("--host <address>", "Interface to bind (default 0.0.0.0).")
.option("--port <number>", "Port to listen on (default random).", parseIntOption)
.option("--token <value>", "Access token clients must provide (random if omitted).")
.option(
"--manual-login",
"Use a dedicated Chrome profile for manual login (recommended when cookie sync is unavailable).",
false,
)
.option(
"--manual-login-profile-dir <path>",
"Chrome profile directory for manual login (default ~/.oracle/browser-profile).",
)
.action(async (commandOptions) => {
const { serveRemote } = await import("../src/remote/server.js");
await serveRemote({
host: commandOptions.host,
port: commandOptions.port,
token: commandOptions.token,
manualLoginDefault: commandOptions.manualLogin,
manualLoginProfileDir: commandOptions.manualLoginProfileDir,
});
});
const bridgeCommand = program
.command("bridge")
.description("Bridge a Windows-hosted ChatGPT session to Linux clients.");
bridgeCommand
.command("host")
.description("Start a secure oracle serve host (optionally with an SSH reverse tunnel).")
.option("--bind <host:port>", "Local bind address for the host service (default 127.0.0.1:9473).")
.option("--token <token|auto>", "Service access token (default auto).", "auto")
.option(
"--write-connection <path>",
"Write a connection artifact JSON (default ~/.oracle/bridge-connection.json).",
)
.option("--ssh <user@host>", "Maintain an SSH reverse tunnel to the Linux host (ssh -N -R ...).")
.option(
"--ssh-remote-port <port>",
"Remote port to bind on the Linux host (default matches --bind port).",
parseIntOption,
)
.option("--ssh-identity <path>", "SSH identity file (ssh -i).")
.option("--ssh-extra-args <args>", "Extra args passed to ssh (quoted string).")
.option("--background", "Run the host in the background and write pid/log files.", false)
.option("--foreground", "Run the host in the foreground (default).", false)
.option("--print", "Print the client connection string (includes token).", false)
.option("--print-token", "Print only the token.", false)
.action(async (commandOptions) => {
const { runBridgeHost } = await import("../src/cli/bridge/host.js");
await runBridgeHost(commandOptions);
});
bridgeCommand
.command("client")
.description("Configure this machine to use a remote oracle serve host.")
.requiredOption("--connect <connection>", "Connection string or path to bridge-connection.json.")
.option(
"--config <path>",
"Override the oracle config file location (default ~/.oracle/config.json).",
)
.option("--no-write-config", "Do not write ~/.oracle/config.json (just validate).")
.option("--no-test", "Skip remote /health check.")
.option("--print-env", "Print env var exports (includes token).", false)
.action(async (commandOptions) => {
const { runBridgeClient } = await import("../src/cli/bridge/client.js");
await runBridgeClient(commandOptions);
});
bridgeCommand
.command("doctor")
.description("Diagnose bridge connectivity and browser engine prerequisites.")
.option("--verbose", "Show extra diagnostics.", false)
.action(async (commandOptions) => {
const { runBridgeDoctor } = await import("../src/cli/bridge/doctor.js");
await runBridgeDoctor(commandOptions);
});
bridgeCommand
.command("codex-config")
.description("Print a Codex CLI MCP server config snippet for oracle-mcp.")
.option("--print-token", "Include ORACLE_REMOTE_TOKEN in the snippet.", false)
.action(async (commandOptions) => {
const { runBridgeCodexConfig } = await import("../src/cli/bridge/codexConfig.js");
await runBridgeCodexConfig(commandOptions);
});
bridgeCommand
.command("claude-config")
.description("Print a Claude Code MCP config snippet (.mcp.json) for oracle-mcp.")
.option("--print-token", "Include ORACLE_REMOTE_TOKEN in the snippet.", false)
.action(async (commandOptions) => {
const { runBridgeClaudeConfig } = await import("../src/cli/bridge/claudeConfig.js");
await runBridgeClaudeConfig(commandOptions);
});
program
.command("tui")
.description("Launch the interactive terminal UI for humans (no automation).")
.action(async () => {
await sessionStore.ensureStorage();
await launchTui({ version: VERSION, printIntro: false });
});
program
.command("session [id]")
.description("Attach to a stored session or list recent sessions when no ID is provided.")
.option(
"--hours <hours>",
"Look back this many hours when listing sessions (default 24).",
parseFloatOption,
24,
)
.option(
"--limit <count>",
"Maximum sessions to show when listing (max 1000).",
parseIntOption,
100,
)
.option("--all", "Include all stored sessions regardless of age.", false)
.option("--clear", "Delete stored sessions older than the provided window (24h default).", false)
.option("--hide-prompt", "Hide stored prompt when displaying a session.", false)
.option("--render", "Render completed session output as markdown (rich TTY only).", false)
.option("--render-markdown", "Alias for --render.", false)
.option("--model <name>", "Filter sessions/output for a specific model.", "")
.option("--path", "Print the stored session paths instead of attaching.", false)
.addOption(new Option("--clean", "Deprecated alias for --clear.").default(false).hideHelp())
.action(async (sessionId, _options: StatusOptions, cmd: Command) => {
await handleSessionCommand(sessionId, cmd);
});
program
.command("status [id]")
.description(
"List recent sessions (24h window by default) or attach to a session when an ID is provided.",
)
.option("--hours <hours>", "Look back this many hours (default 24).", parseFloatOption, 24)
.option("--limit <count>", "Maximum sessions to show (max 1000).", parseIntOption, 100)
.option("--all", "Include all stored sessions regardless of age.", false)
.option("--clear", "Delete stored sessions older than the provided window (24h default).", false)
.option("--render", "Render completed session output as markdown (rich TTY only).", false)
.option("--render-markdown", "Alias for --render.", false)
.option("--model <name>", "Filter sessions/output for a specific model.", "")
.option("--hide-prompt", "Hide stored prompt when displaying a session.", false)
.addOption(new Option("--clean", "Deprecated alias for --clear.").default(false).hideHelp())
.action(async (sessionId: string | undefined, _options: StatusOptions, command: Command) => {
const statusOptions = command.opts<StatusOptions>();
const clearRequested = Boolean(statusOptions.clear || statusOptions.clean);
if (clearRequested) {
if (sessionId) {
console.error(
"Cannot combine a session ID with --clear. Remove the ID to delete cached sessions.",
);
process.exitCode = 1;
return;
}
const hours = statusOptions.hours;
const includeAll = statusOptions.all;
const result = await sessionStore.deleteOlderThan({ hours, includeAll });
const scope = includeAll ? "all stored sessions" : `sessions older than ${hours}h`;
console.log(formatSessionCleanupMessage(result, scope));
return;
}
if (sessionId === "clear" || sessionId === "clean") {
console.error(
'Session cleanup now uses --clear. Run "oracle status --clear --hours <n>" instead.',
);
process.exitCode = 1;
return;
}
if (sessionId) {
const autoRender =
!command.getOptionValueSource?.("render") &&
!command.getOptionValueSource?.("renderMarkdown")
? process.stdout.isTTY
: false;
const renderMarkdown = Boolean(
statusOptions.render || statusOptions.renderMarkdown || autoRender,
);
await attachSession(sessionId, { renderMarkdown, renderPrompt: !statusOptions.hidePrompt });
return;
}
const showExamples = usesDefaultStatusFilters(command);
await showStatus({
hours: statusOptions.all ? Infinity : statusOptions.hours,
includeAll: statusOptions.all,
limit: statusOptions.limit,
showExamples,
});
});
program
.command("restart <id>")
.description("Re-run a stored session as a new session (clones options).")
.addOption(new Option("--wait").default(undefined))
.addOption(new Option("--no-wait").default(undefined).hideHelp())
.option("--remote-host <host:port>", "Delegate browser runs to a remote `oracle serve` instance.")
.option("--remote-token <token>", "Access token for the remote `oracle serve` instance.")
.action(async (sessionId: string, _options: RestartCommandOptions, cmd: Command) => {
const restartOptions = cmd.opts<RestartCommandOptions>();
await restartSession(sessionId, restartOptions);
});
function buildRunOptions(
options: ResolvedCliOptions,
overrides: Partial<RunOracleOptions> = {},
): RunOracleOptions {
if (!options.prompt) {
throw new Error("Prompt is required.");
}
const normalizedBaseUrl = normalizeBaseUrl(overrides.baseUrl ?? options.baseUrl);
const azure =
options.azureEndpoint || overrides.azure?.endpoint
? {
endpoint: overrides.azure?.endpoint ?? options.azureEndpoint,
deployment: overrides.azure?.deployment ?? options.azureDeployment,
apiVersion: overrides.azure?.apiVersion ?? options.azureApiVersion,
}
: undefined;
return {
prompt: options.prompt,
model: options.model,
models: overrides.models ?? options.models,
previousResponseId: overrides.previousResponseId ?? options.previousResponseId,
effectiveModelId: overrides.effectiveModelId ?? options.effectiveModelId ?? options.model,
file: overrides.file ?? options.file ?? [],
maxFileSizeBytes: overrides.maxFileSizeBytes ?? options.maxFileSizeBytes,
slug: overrides.slug ?? options.slug,
filesReport: overrides.filesReport ?? options.filesReport,
maxInput: overrides.maxInput ?? options.maxInput,
maxOutput: overrides.maxOutput ?? options.maxOutput,
system: overrides.system ?? options.system,
timeoutSeconds: overrides.timeoutSeconds ?? (options.timeout as number | "auto" | undefined),
httpTimeoutMs: overrides.httpTimeoutMs ?? options.httpTimeout,
zombieTimeoutMs: overrides.zombieTimeoutMs ?? options.zombieTimeout,
zombieUseLastActivity: overrides.zombieUseLastActivity ?? options.zombieLastActivity,
silent: overrides.silent ?? options.silent,
search: overrides.search ?? options.search,
preview: overrides.preview ?? undefined,
previewMode: overrides.previewMode ?? options.previewMode,
apiKey: overrides.apiKey ?? options.apiKey,
baseUrl: normalizedBaseUrl,
azure,
sessionId: overrides.sessionId ?? options.sessionId,
verbose: overrides.verbose ?? options.verbose,
heartbeatIntervalMs:
overrides.heartbeatIntervalMs ?? resolveHeartbeatIntervalMs(options.heartbeat),
browserAttachments:
overrides.browserAttachments ??
(options.browserAttachments as "auto" | "never" | "always" | undefined) ??
"auto",
browserInlineFiles: overrides.browserInlineFiles ?? options.browserInlineFiles ?? false,
browserBundleFiles: overrides.browserBundleFiles ?? options.browserBundleFiles ?? false,
background: overrides.background ?? undefined,
renderPlain: overrides.renderPlain ?? options.renderPlain ?? false,
writeOutputPath: overrides.writeOutputPath ?? options.writeOutputPath,
};
}
export function enforceBrowserSearchFlag(
runOptions: RunOracleOptions,
sessionMode: SessionMode,
logFn: (message: string) => void = console.log,
): void {
if (sessionMode === "browser" && runOptions.search === false) {
logFn(chalk.dim("Note: search is not available in browser engine; ignoring search=false."));
runOptions.search = undefined;
}
}
function resolveHeartbeatIntervalMs(seconds: number | undefined): number | undefined {
if (typeof seconds !== "number" || seconds <= 0) {
return undefined;
}
return Math.round(seconds * 1000);
}
interface FollowupResolution {
responseId: string;
sessionId?: string;
}