Repository navigation
Expand file tree
/
Copy paththreecode.nim
More file actions
1729 lines (1675 loc) · 83.3 KB
/
Copy paththreecode.nim
File metadata and controls
1729 lines (1675 loc) · 83.3 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
## Entry point and outer REPL loop.
##
## `main` parses CLI args, sets up the session, and runs the interactive loop.
## `turns.runTurns` is the inner driver: it calls the model, dispatches
## tool calls, updates the session, and handles compaction - repeating until
## the model emits no tool calls.
##
## Module graph overview::
##
## threecode (entry)
## ├── turns turn lifecycle + API/tool orchestration
## ├── api HTTP + SSE streaming + spinner
## ├── actions tool_call JSON → Action → execute
## ├── compact supersede elision + LLM summarization
## ├── session .3log persistence (save + load)
## ├── display terminal rendering (markdown, token bar, replays)
## ├── ui REPL :commands + provider wizard
## ├── config config file parse + profile resolution
## ├── prompts KnownGoodCombos + per-family (prompt, tools)
## ├── shell shell command parsing for the read cache
## ├── web native web search + URL fetch
## ├── update background auto-update
## ├── fatprompt volatile prompt/token/ticker state and frame bytes
## ├── util string utils, ANSI palette, markdown helpers
## ├── types shared types + globals
## └── minline readline-style input
import std/[json, locks, os, parseopt, strformat, strutils, tables, terminal, times]
when not defined(windows):
import std/atomics
import std/exitprocs
when defined(posix):
import std/posix
import threecode/runtime
import threecode/[types, util, prompts, shell, session, compact,
config, actions, api, display, ui, update, fatprompt,
toolstream, turns, transcript, sandbox, box, wall,
auth_xai, auth_openai, auth_google, auth_anthropic,
streamexec, cli, search, tabtitle, plugins, goal,
dirsettings]
import threecode/acp
import threecode/headless
import threecode/pluginagent
import threecode/rpc
import threecode/signals
when not defined(android):
import tinotify
else:
# Termux/Android has no desktop notification service; tinotify
# hard-errors on the OS family, so notifications no-op there.
proc notify(app, title, body: string) = discard
import threecode/minline
import threecode/engine as termengine
import threecode/library
export types, util, prompts, shell, session, compact,
config, actions, api, display, ui, fatprompt, toolstream, turns,
transcript, library
when defined(startupTrace):
# Runtime-initialized at module load so the baseline is process start;
# const would demand a compile-time epochTime (fails on Windows cross).
let StartupT0 = epochTime()
# When [settings] trace_file is set, milestones append there instead of
# stderr, so timing is captured even when stderr is a console that the
# caller can't easily scrape (e.g. a manual launch in Windows Terminal).
# Resolved lazily on the first milestone: the flag fires before the full
# config load, so the probe reads the key itself from the resolved
# config path (-c honored).
var startupTraceFile = ""
var startupTraceResolved = false
template startupTrace(label: string) =
## stderr timing probe, compiled in only with -d:startupTrace.
let line = "[trace] " & label & " " &
formatFloat(epochTime() - StartupT0, ffDecimal, 3) & "\n"
if not startupTraceResolved:
startupTraceResolved = true
startupTraceFile = startupTraceFileTarget()
if startupTraceFile.len > 0:
try:
let f = open(startupTraceFile, fmAppend)
f.write(line)
f.close()
except CatchableError: discard
else:
stderr.write(line)
else:
template startupTrace(label: string) = discard
proc expandAttachedValues(args: seq[string]): seq[string] =
## Value-taking options accept their value attached to the flag
## (`-rID`, `-mID`, `-r=ID`, `-r:ID`) as well as space-separated
## (`-r ID`). parseopt splits short clusters per letter and only
## recognizes `=`/`:` separators, so `-rabc` would arrive as the four
## flags r, a, b, c. Rewrite any cluster whose value-taking option
## carries trailing characters into the equivalent `-x=v` form; the
## space-separated case is handled by the `pending` mechanism in the
## parse loop. Boolean-only clusters (`-la`) pass through unchanged.
## Must stay in sync with the option table below: every short option
## listed with a value belongs in `valueOpts`, plus the short forms of
## value-taking options registered by plugins (known by the time this
## runs: plugins register their CLI surface before argv is parsed).
let valueOpts = {'m', 's', 'c', 'C', 'r'} + pluginCliValueShorts()
for a in args:
var expanded = false
if a.len > 2 and a[0] == '-' and a[1] != '-':
for i in 1 ..< a.len:
if a[i] notin valueOpts: continue
var rest = a[i + 1 ..< a.len]
if rest.len == 0: break # value is the next token; pending covers it
if rest[0] in {'=', ':'}: rest = rest[1 ..< rest.len]
if rest.len > 0:
result.add a[0 .. i] & "=" & rest
expanded = true
break
if not expanded: result.add a
proc usage() {.noreturn.} =
stderr.writeLine """usage: 3code [options] [prompt...]
3code good # list known-good provider/variant combos
3code provider add <name|url|api-key> [--key KEY] [--models "a b c"]
# configure a provider without the wizard
3code sandbox restrict DIR -- CMD # run CMD sandboxed (alias: sb)
3code setup # one-time elevated sandbox setup (Windows)
3code --headless [opts] [prompt...]
# run the agent with ZERO output (exit code only)
3code --gui [opts] # headless + an in-process plugin GUI frontend
# (--headless/--gui must be the first argument)
-m, --model PROVIDER[.MODEL] pick model from config (overrides [settings])
-c, --config FILE read providers and settings from FILE instead of
the user config; repeatable, later files win per key
-C, --config-clear [FILE]
clear the config stack (user config and project
.3code/config are not read), then read FILE if given;
later -c layers stack on top of it
-r, --resume[=ID] resume latest session from this directory, or one by
id, unique id prefix, name (set with :rename), or
position in the --list order (0 = latest, 1 = the one
before, ...; so -r1 resumes the previous session)
(value options take -r ID | -rID | -r=ID | -r:ID | --resume=ID;
quote names containing spaces)
-i, --interactive drop into the REPL after running an initial prompt
(without it, a prompt runs once and exits)
-l, --list list recent sessions for this directory (max 20) and exit
-a, --all with -l / -f: every directory, not just this one
-f, --find TERM... search session transcripts for TERM... and exit
(case-insensitive; a quoted arg is a phrase)
--page N later screenful of --list / --find results
-g, --good list known-good provider/variant combos and exit
-x, --experimental allow combos outside the known-good list
-p, --private private mode: only allow-private providers/models run
(zero-training providers; the token bar repaints to show it)
--computer computer use for this run: vision models get the
screenshot tool + the shot desktop driver (X11)
--no-sandbox disable sandbox enforcement (bash runs unconfined)
-D, --debug colored debug trace to stderr
-v, --version print version
-h, --help this message
config read (later wins): """ & configReadPaths().join(", ") & """
config write: """ & configPath()
# Plugin-registered CLI surface: listed only when plugins added one,
# so a stock install sees exactly the built-in usage. Same alignment
# shape as the built-in rows above (24-col gutter).
let cliCmds = pluginCliCommands()
let cliOpts = pluginCliOptions()
if cliCmds.len > 0 or cliOpts.len > 0:
stderr.writeLine ""
stderr.writeLine "added by plugins (" & userDataRoot() / "lib & system dirs):"
for c in cliCmds:
stderr.writeLine alignLeft(" " & c.name, 24) & "# " & c.help
for o in cliOpts:
var left = " --" & o.longName
if o.shortName != '\0': left.add ", -" & o.shortName
if o.takesValue: left.add " VALUE"
stderr.writeLine alignLeft(left, 30) & " # " & o.help
quit ExitUsage
proc pageSkip(page, total: int): int =
## First index of page `page` over `total` items in `SessionListCap`
## chunks. A page past the end is a usage error, not an empty listing,
## so a typo'd page number can't masquerade as "nothing here".
let skip = (page - 1) * SessionListCap
if skip >= total:
let pages = (total + SessionListCap - 1) div SessionListCap
die(&"page {page} out of range (1..{pages})", ExitUsage)
skip
proc refuseRoot() =
## 3code runs arbitrary shell commands the model proposes — root
## blast radius is unacceptable. The install script also refuses, so
## a normal `curl | sh` user shouldn't ever see this; it's the safety
## net for `sudo 3code`, root containers, etc.
when defined(posix):
if geteuid() == 0 and not runtime.on("allow_root"):
stderr.writeLine "3code: refusing to run as root. " &
"Run as your normal user. (override: [settings] allow_root = on)"
quit ExitUsage
proc warnNoBash() =
## Windows startup warning: 3code depends on bash. resolveBash checks
## the installer's own PortableGit tree (`%LOCALAPPDATA%\3code\git`),
## Git for Windows, a standalone MSYS2, and the legacy 3code-installed
## MSYS2 tree, once at startup (after the first-run provider wizard, so
## a fresh
## user saves their provider first). When none is found the bash/shell
## tool is dropped from the advertised tool list for the session (a
## ```bash fence in a reply still returns the install one-liner via the
## streamexec guard) and this one-line warning says how to fix it. POSIX
## resolves its shell in shPath, which halts when no bash-compatible
## shell exists, so this is a no-op there.
##
## The provider-stub binary (the tty test harness) skips this: those tests
## drive REPL rendering, not bash enforcement, and CI has no bundled MSYS2
## so the warning would fire before the prompt appears. Bash enforcement
## is covered by the cli_args `sandbox` suite and by production. Same gate as
## initSandbox.
when defined(windows) and not defined(providerStub):
if resolveBash().len == 0:
bashToolDisabled = true
let msg = " · bash tool disabled: no bash found. Install Git for " &
"Windows as your user: https://git-scm.com/download/win"
try:
stderr.write(MagentaFg & msg & Reset & "\n")
except CatchableError:
try: stderr.writeLine msg
except CatchableError: discard
proc initSandbox(cwd: string) =
## Load the sandbox policy into the global state and resolve this
## binary's own path for bash wrapping. Exactly one file is active:
## the repo `.sandbox` when it exists, else the user file
## `~/.config/3code/sandbox` when the user wrote one, else the
## built-in default in memory, so the sandbox is always on without
## 3code ever creating the user file. When `sandboxEnabled` is false
## (the `[settings] sandbox = off` switch), this does nothing: bash
## runs unconfined and the in-process checks pass through (`active`
## stays false).
# The provider stub binary (the tty/visual test harness) skips sandbox
# setup entirely so its behaviour matches the pre-sandbox binary. Those
# tests drive REPL rendering, not enforcement, and `active=true` plus the
# startup probe shift the wall-clock timing the spinner/SIGWINCH
# assertions depend on. Enforcement is covered by the cli_args `box`
# suite and by production. The [test] stub_sandbox = on key opts a stub
# run back in (the sandbox-ask tty tests need a live policy with the
# harness's deterministic timing).
when defined(providerStub):
if not runtime.on("stub_sandbox"):
return
if not sandboxEnabled:
return
# The same steps a mid-session `:sandbox on` runs (see sandbox.arm).
# The bash tool re-execs this binary as `3code sandbox restrict ...`;
# when the OS-native backend cannot restrict (a kernel without
# Landlock, a CI runner under a seccomp filter that blocks the
# syscall), arm clears procboxExe so the bash tool degrades to the
# unconfined setsid path instead of failing every command. The
# in-process read/write/patch checks stay in force via `active`
# regardless. The probe runs silently; the backend being unavailable
# is a host limitation, not an error the user can act on.
sandbox.arm(cwd)
proc setupTlsEnv() =
## macOS packaging builds link OpenSSL statically (config.nims
## `-d:staticSsl`) and this proc compiles to nothing. Dev builds run
## from a source tree: stock LibreSSL at `/usr/lib/libssl.dylib` fails
## handshakes against most modern endpoints, so if Homebrew OpenSSL 3
## dylibs sit alongside the binary, prepend the binary's directory to
## DYLD_LIBRARY_PATH so `dlopen("libssl.dylib")` (from Nim's std/net
## openssl wrapper) hits ours first. dyld consults the env var on
## every dlopen, so updating it from inside the process before any
## TLS code runs is sufficient.
##
## Windows: static in packaging builds; dynamic dev builds find DLLs
## next to the .exe by the app-directory rule, no path manipulation
## needed.
##
## CA bundle: bundled OpenSSL on both platforms has its OPENSSLDIR
## baked to a build-runner path that doesn't exist on user systems,
## so verifyMode=CVerifyPeer can't scan default locations. Code that
## opens a TLS context calls `bundledCaFile()` (in util.nim), which
## prefers an adjacent `cacert.pem` and falls back to the bundle
## embedded at compile time (release builds pass
## `-d:embeddedCaCertPath=...`; it is written to the data dir on
## first use). Linux uses the system trust store and needs nothing
## here.
## Termux's openssl libs are found via DT_RUNPATH baked in at link
## time (see config.nims); LD_LIBRARY_PATH can't help because the
## openssl wrapper dlopens at module init, before main runs.
## CI packaging builds link OpenSSL statically (-d:staticSsl, see
## config.nims) and bundle no dylibs, so the env dance is dead there.
when defined(macosx) and not defined(staticSsl):
let dir = parentDir(getAppFilename())
let cur = getEnv("DYLD_LIBRARY_PATH")
let newVal = if cur.len > 0: dir & ":" & cur else: dir
putEnv("DYLD_LIBRARY_PATH", newVal)
const NotifyMinSeconds = 5.0
when defined(macosx):
type NotifyJob = object
bodyBuf: cstring
bodyLen: int
titleBuf: cstring
titleLen: int
var
notifyThread: Thread[NotifyJob]
notifyThreadStarted = false
proc notifyThreaded(job: NotifyJob) {.thread, gcsafe.} =
## Runs the macOS notification helper on a managed worker thread with
## shared-heap body bytes (never sharing ORC JsonNodes or stack
## Thread handles across threads).
var (title, body) = ("", "")
if job.bodyBuf != nil:
body = newString(job.bodyLen)
copyMem(addr body[0], job.bodyBuf, job.bodyLen)
deallocShared(job.bodyBuf)
title = newString(job.titleLen)
copyMem(addr title[0], job.titleBuf, job.titleLen)
deallocShared(job.titleBuf)
if body.len > 0:
{.cast(gcsafe).}:
notify("3code", title, body)
proc notifyDesktop(title, body: string) {.gcsafe.} =
## Fire-and-forget desktop notification. The macOS backend compiles and
## runs a Swift helper on first use; a consent-waiting helper must never
## park the controller, so the call rides a reusable worker thread.
## Linux's dbus path is a fast direct call and stays synchronous.
if body.len == 0: return
when defined(macosx):
{.cast(gcsafe).}:
if notifyThreadStarted:
joinThread(notifyThread)
notifyThreadStarted = false
let buf = cast[cstring](allocShared0(body.len + 1))
copyMem(buf, unsafeAddr body[0], body.len)
let tbuf = cast[cstring](allocShared0(title.len + 1))
copyMem(tbuf, unsafeAddr title[0], title.len)
try:
createThread(notifyThread, notifyThreaded,
NotifyJob(bodyBuf: buf, bodyLen: body.len,
titleBuf: tbuf, titleLen: title.len))
notifyThreadStarted = true
except CatchableError:
deallocShared(buf)
deallocShared(tbuf)
else:
{.cast(gcsafe).}:
notify("3code", title, body)
proc notifyTurnFinished(messages: JsonNode) {.gcsafe.} =
notifyDesktop("Turn finished", turnFinishedBody(messages))
proc commitUserPromptTranscript(line: string) =
## Controller-owned transcript append for user prompt items submitted
## mid-turn (the queued-prompt path). Delegates to emitUserSubmit so both
## the normal and queued submit paths share one separator/spacing model.
emitUserSubmit(line)
proc cleanup() {.noconv.} =
## Single point of process teardown. Restores terminal state and
## releases the session lock. Registered as the only exit proc and called
## directly from signal handlers and the REPL's quit paths, so every way
## out (Ctrl-C, Ctrl-D, :q, SIGTERM, SIGHUP, uncaught exception) runs the
## same restore sequence.
##
## Idempotent: each step is guarded against double-invocation so an exit
## proc firing after a signal handler (or vice versa) does no harm.
##
## The persistent input thread is deliberately NOT joined here: it owns
## closures whose ORC cycle-collection crosses threads and segfaults if
## the thread returns while the editor is still live. We restore its
## termios snapshot directly instead; `exit()` kills the thread without
## running its epilogue, avoiding the cross-thread teardown.
fatprompt.restoreInputTermios()
minline.restoreTerminal()
restoreCancelTermios()
when defined(posix):
sandbox.stopWall()
# Final best-effort save of the prompt draft so a kill/power-off/SIGTERM
# never loses a half-typed prompt. flushDraftNow uses tryAcquire inside so it
# is safe to call from a signal handler on any thread. Mid-typing saves are
# key-press debounced on the input thread (see the draft debounce block in
# fatprompt/runtime.nim); this is the unconditional last word.
fatprompt.flushDraftNow()
releaseActiveSessionLock()
releaseActiveDirLock()
# Unhandled exceptions (including Defects like AssertionDefect) go through
# reportUnhandledError then rawQuit, which skips exit procs. Restore the
# terminal here so a crash never leaves stdin in raw mode. Full cleanup is
# too raise-heavy for this hook; termios restore is the part the user feels.
unhandledExceptionHook = proc(e: ref Exception) {.nimcall, gcsafe, raises: [], tags: [].} =
{.cast(raises: []), cast(tags: []).}:
fatprompt.restoreInputTermios()
minline.restoreTerminal()
restoreCancelTermios()
when defined(tcNativeGui):
proc nativeGuiAlert(msg: string) =
## The native GUI-subsystem build has no console on Windows: stderr
## goes nowhere, so a misuse notice is a real alert box there. On
## macOS/Linux the same build is a plain binary and stderr works.
when defined(windows):
proc MessageBoxW(hWnd: pointer, text, caption: WideCString,
uType: uint32): int32 {.importc, stdcall, dynlib: "user32", discardable.}
proc toWide(s: string): WideCString =
result = newWideCString(s)
discard MessageBoxW(nil, toWide(msg), toWide("3code"), 0x30'u32)
else:
stderr.writeLine "3code: " & msg
proc main() =
startupTrace("main-enter")
turns.onAskNotification = proc(shown: string) {.gcsafe.} =
if notifyEnabled:
notifyDesktop("Permission needed", shown)
when defined(tcNativeGui):
# Native GUI-subsystem build (`nimble gui`): headless only. A
# GUI-subsystem Windows binary has no console attached, so anything
# but the headless frontends would run blind; refuse loudly instead.
block:
let gp = commandLineParams()
if gp.len == 0 or gp[0] notin ["--headless", "--gui"]:
nativeGuiAlert("3code-gui is the native GUI build and runs " &
"headless only. Start it with --gui (a plugin frontend) or " &
"--headless; the terminal UI lives in the console 3code binary.")
quit(ExitUsage)
# `sandbox` is the built-in sandwall CLI: the bash tool re-execs this
# binary as `3code sandbox restrict ...`. Dispatch before any other
# startup so the sandboxed command isn't weighed down by 3code's
# TLS/config/session init and so refuseRoot etc. don't run inside the
# confined child. `box` stays as a hidden alias for binaries already
# running under the old name.
let rawParams = commandLineParams()
# The config layer stack (-c / -C) is applied from the raw argv once,
# before any dispatch: every subcommand, frontend, and parser below
# (provider, --headless, --rpc, --acp, the main getopt loop) consumes
# the tokens without touching the state, so they can never disagree
# about the stack the way the old first-vs-last pre-scans did.
applyConfigFlags(rawParams)
# Project-local config discovery: the nearest `.3code/config` up from
# the working directory joins the read stack as its last (strongest)
# layer. Runs before every dispatch so the provider subcommand,
# headless, rpc and acp all see it; a `-C` skips the walk entirely.
projectLayer = discoverProjectConfig(safeCwd())
# All the early-dispatch subcommands below run with redirected or
# piped stdio (box children, the stdio relay, elevated setup); their
# exit procs must not splice terminal-restore escapes into the stream.
if rawParams.len > 0 and rawParams[0] in
["sandbox", "sb", "box", "wall", "stdio-relay", "setup", "unsetup"]:
minline.terminalRestoreSuppressed = true
if rawParams.len > 0 and rawParams[0] in ["sandbox", "sb", "box"]:
quit(boxMain(rawParams[1 .. ^1]))
# `wall` is the network half of sandwall, same early-dispatch
# rationale: proxy/connect children skip all of 3code's startup.
# Internal: the user-facing names are `3code setup` / `3code unsetup`.
if rawParams.len > 0 and rawParams[0] == "wall":
quit(wallMain(rawParams[1 .. ^1]))
# The CPLW stdio relay hop: sandwall's Windows backend prefixes the
# sandboxed command with `<self> stdio-relay --`. Must dispatch before
# anything interactive or the relay child would hang in the TUI.
# wallMain accepts the arg shape `stdio-relay -- CMD ...` directly.
when defined(windows):
if rawParams.len > 0 and rawParams[0] == "stdio-relay":
quit(wallMain(rawParams))
# One-time elevated sandbox setup / teardown (see wall.nim). The
# commands exist on every platform; POSIX reports "Windows only".
if rawParams.len > 0 and rawParams[0] == "setup":
quit(setupMain(rawParams[1 .. ^1]))
if rawParams.len > 0 and rawParams[0] == "unsetup":
quit(unsetupMain(rawParams[1 .. ^1]))
# ACP frontend: `3code --acp` speaks Agent Client Protocol v1 over
# stdio (editors, custom clients). Early dispatch like the subcommands
# above: piped stdio, no terminal setup may run.
if rawParams.len > 0 and rawParams[0] == "--acp":
minline.terminalRestoreSuppressed = true
quit(acpMain(rawParams[1 .. ^1]))
# Headless REST frontend: `3code --rpc[=PORT]` serves the plain-text
# RPC surface 3code-app talks to (see threecode/rpc.nim). Same early
# dispatch as --acp: no terminal setup may run.
if rawParams.len > 0 and (rawParams[0] == "--rpc" or
rawParams[0].startsWith("--rpc=")):
minline.terminalRestoreSuppressed = true
quit(rpcMain(rawParams))
# -v must not pay for TLS env, stale-binary walk, or sandbox sweep.
# On Windows a debug 3code.exe is tens of MB and those walks dominate
# `--version`. -h waits until plugins have registered their CLI
# surface so usage lists it, which is why it sits below the load.
for a in rawParams:
if a in ["-v", "--version"]: echo Version; return
# Root blast radius: plugins are native code loaded before argv is
# parsed now (their subcommands and options must be known up front),
# so the root refusal has to come before their load. -v above and the
# early subcommands above still answer as root on purpose. The stack
# is read (tolerantly) first so `[settings] allow_root` is honored; the
# full (dying) config parse still runs later at its old spot.
discard tryLoadStackOrEmpty()
refuseRoot()
# Plugins register their CLI surface (subcommands, options) at load,
# so they load before argv is parsed — much earlier than their hooks
# used to fire. The tolerant stack read above already gated this load
# (`[plugins] disable` and `lib`) exactly as the late one did.
pluginsDiscoverAndLoad()
# Headless frontends: `--headless` runs turns with zero output,
# `--gui` keeps the process alive for a plugin's in-process GUI
# (both see headless.nim). Dispatched here, after the load above: a
# `--gui` run needs the frontend registered, and a plugin's config
# defaults land in the same window as every other run.
if rawParams.len > 0 and rawParams[0] in ["--headless", "--gui"]:
quit(headlessMain(rawParams))
for a in rawParams:
if a in ["-h", "--help"]: usage()
# Non-interactive provider management (see cli.nim). Dispatches with
# the other early subcommands so its own flags (--key, --models) never
# hit the main option parser. `-c/-x` may precede the subcommand; they
# are picked out here and the rest goes to providerMain verbatim.
block:
var rest: seq[string]
var isProvider = false
var sawBare = false
var i = 0
while i < rawParams.len:
case rawParams[i]
of "-c", "--config":
# Already applied to the stack by applyConfigFlags; skip the
# pair so the operand never reaches providerMain as a word.
if i + 1 >= rawParams.len:
if rawParams[0] == "provider":
die("option " & rawParams[i] & " requires a value", ExitUsage)
break
inc i
of "-x", "--experimental":
experimentalEnabled = true
else:
# Only a LEADING bare `provider` dispatches (after any -c/-x);
# a prompt word like `3code add a provider for x` must not.
if not sawBare and not rawParams[i].startsWith("-"):
sawBare = true
if rawParams[i] == "provider":
isProvider = true
else:
rest.add rawParams[i]
inc i
if isProvider:
var colorKeys: Table[string, string]
(activeCurrent, activeProviders, colorKeys) = loadStackOrEmpty()
quit(providerMain(rest))
startupTrace("early-dispatch-done")
setupTlsEnv()
startupTrace("setupTlsEnv")
cleanupStaleBinaries()
startupTrace("cleanupStaleBinaries")
when defined(posix):
sandbox.sweepStaleWallDirs()
streamexec.sweepStaleBashDirs()
display.sweepStaleToolOutDirs()
# Internal flag for the detached background worker. Run silently and
# exit before any other startup work (skill extraction, config load).
let cl = commandLineParams()
if cl.len == 1 and cl[0] == "--self-update-check":
selfUpdateCheck()
return
# ── CLI parse: run before any dependency checks so -h / -v / --list
# work on Windows even when bash is not installed yet ──
var model = ""
var args: seq[string]
var pending = "" # flag awaiting a space-separated value
var resume = false
var resumeId = ""
var sessionOut = ""
var listSessions = false
var allDirs = false
var findSessions = false
var findTerms: seq[string]
var pageOpt = ""
var page = 1
var interactive = false
var pluginOptVals: seq[(string, string)] # plugin option name -> value
var p = initOptParser(expandAttachedValues(commandLineParams()))
for kind, k, v in p.getopt():
case kind
of cmdShortOption, cmdLongOption:
case k
of "v", "version": echo Version; return
of "h", "help": usage()
of "g", "good": printKnownGood(); return
of "x", "experimental": experimentalEnabled = true
of "p", "private": privateMode = true
of "computer":
if computerUseBuild: computerUseEnabled = true
of "no-sandbox": sandboxEnabled = false
of "D", "debug": debugEnabled = true
of "i", "interactive": interactive = true
of "m", "model":
if v != "": model = v
else: pending = "model"
of "s", "session":
if v != "": sessionOut = v
else: pending = "session"
of "c", "config":
# Stack applied up front by applyConfigFlags; the token only
# keeps its operand out of the prompt words.
if v == "": pending = "config"
of "C", "config-clear":
# Optional operand: an unconsumed pending at the end is a bare
# clear, not a usage error (same tolerance as -r).
if v == "": pending = "config-clear"
of "r", "resume":
resume = true
if v != "": resumeId = v
else: pending = "resume"
of "l", "list":
# Short flags accumulate, so `-la` / `-al` both set this true
# (parseopt emits one cmdShortOption per clustered letter).
# Listing is directory-scoped by default; `-a` widens it.
listSessions = true
of "a", "all":
# Scope modifier for -l / -f: every directory, not just this one.
# Alone it still implies -l, so bare `-a` lists everything.
allDirs = true
listSessions = true
of "f", "find":
findSessions = true
if v != "": findTerms.add v
of "page":
if v != "": pageOpt = v
else: pending = "page"
else:
# Plugin-registered options: accepted like builtins, collected
# here, delivered to the plugins once parsing is done.
let pi = if kind == cmdLongOption: pluginCliFindOption(k, '\0')
elif k.len == 1: pluginCliFindOption("", k[0])
else: -1
if pi >= 0:
let o = pluginCliOptions()[pi]
if o.takesValue:
if v != "": pluginOptVals.add (o.longName, v)
else: pending = "plugin:" & o.longName
else:
pluginOptVals.add (o.longName, "")
else: die("unknown option: -" & (if k.len == 1: "" else: "-") & k, ExitUsage)
of cmdArgument:
if pending == "model":
model = k
pending = ""
elif pending == "session":
sessionOut = k
pending = ""
elif pending == "config" or pending == "config-clear":
pending = ""
elif pending == "page":
pageOpt = k
pending = ""
elif pending == "resume":
resumeId = k
pending = ""
elif pending.startsWith("plugin:"):
pluginOptVals.add (pending[7 ..^ 1], k)
pending = ""
else:
# A LEADING bare word that names a plugin subcommand dispatches
# verbatim: everything after it is the plugin's to parse (its
# own flags, `--` and all), like `provider` above. Later bare
# words stay prompt text, so `3code fix the deploy tool` only
# dispatches when a plugin claimed the exact first word.
if args.len == 0 and pluginCliHasCommand(k):
pluginsDeliverCliOptions(pluginOptVals)
let (outp, code) = pluginCliRunCommand(k, p.remainingArgs())
if outp.len > 0: stdout.writeLine outp
quit code
args.add k
of cmdEnd: discard
# --resume's value is optional: bare `-r` still means "resume the
# latest session for this directory", so an unconsumed pending value
# (nothing followed, or the next token was another option) is not a
# usage error.
if pending.startsWith("plugin:"):
die("option --" & pending[7 ..^ 1] & " requires a value", ExitUsage)
if pending != "" and pending != "resume" and pending != "config-clear":
die("option --" & pending & " requires a value", ExitUsage)
if pageOpt != "":
try: page = parseInt(pageOpt)
except ValueError: die("page: not a number: " & pageOpt, ExitUsage)
if page < 1: die("page: must be 1 or more", ExitUsage)
# Plugin options collected above reach their owners now, before any
# session work: the fast-exit dispatches below (-l/-f) still deliver,
# and a prompt run has them in place before the first hook fires.
pluginsDeliverCliOptions(pluginOptVals)
# Apply a provisional palette before any colored output (update notices,
# onboarding). The mode can only be forced to dark/light here; full
# detection runs after the config file is read so `[settings] mode` can
# pin a palette, then `[colors]` overrides are layered on top.
applyPalette(cmDark)
minline.CaretCellFg = OffWhiteFg
if findSessions:
for a in args: findTerms.add a
var terms: seq[string]
for t in findTerms:
let n = normalizeTerm(t)
if n.len > 0 and n notin terms: terms.add n
if terms.len == 0:
die("find: no search terms", ExitUsage)
let paths =
if allDirs: listSessionPaths()
else: listSessionPathsForCwd(safeCwd())
let hits = searchSessions(paths, terms)
if hits.len == 0:
stderr.writeLine "3code: no sessions matching " & terms.join(" ")
quit ExitConfig
let skip = pageSkip(page, hits.len)
let more = if skip + SessionListCap < hits.len:
"--page " & $(page + 1) & " for more" else: ""
printSearchList(hits, hits.len, showCwd = allDirs, skip, more)
return
if listSessions:
let paths =
if allDirs: listSessionPaths()
else: listSessionPathsForCwd(safeCwd())
if paths.len == 0:
if allDirs: stderr.writeLine "3code: no saved sessions"
else: stderr.writeLine "3code: no saved sessions for " & safeCwd()
quit ExitConfig
let skip = pageSkip(page, paths.len)
let more = if skip + SessionListCap < paths.len:
"--page " & $(page + 1) & " for more" else: ""
printSessionList(paths, "", showCwd = allDirs, skip, more)
return
if args.len > 0:
case args[0]
of "good": printKnownGood(); return
else: discard
# Everything below roots a session at the process cwd: sandbox policy,
# dir settings, session files, locks. With that directory deleted the
# launch must refuse here rather than crash on getcwd mid-startup or
# run the whole session against "/" (safeCwd's fallback). The fast
# exits above (-v, -h, -l, -f, good, provider, plugins) never needed a
# cwd and still answer from a deleted one.
requireLiveCwd()
# Validate --resume targets before side-effecting startup work so a
# bogus id fails fast (no skill extraction, no lock) the same way a
# usage error does. A prompt alongside --resume is now legitimate
# (run it once resumed), so only the id is checked here.
var resolved = ""
if resume:
# A running 3code wins over session availability: when another live
# process holds this directory, `-r` must report the holder even if
# the holder has not saved its first session yet (which would
# otherwise die "no saved sessions"). Advisory only: the real claim
# still happens in acquireDirLock below.
let held = probeDirLockHeld(safeCwd())
if held != "": die(held, ExitConfig)
# Same lookup `:resume` runs: exact id, then unique id prefix, then a
# `:rename` name (case-insensitive). Several matches at one stage die
# listing the candidates.
try:
resolved = resolveSessionPath(resumeId, safeCwd())
except SessionAmbiguous as e:
die(e.msg, ExitConfig)
if resolved == "":
if resumeId == "":
die("no saved sessions for " & safeCwd(), ExitConfig)
else:
die("session not found: " & resumeId, ExitConfig)
# ── All syntax validation and fast-exit dispatches are done; only now
# do we run the side-effecting startup work (global interrupt hook,
# skill extraction disk I/O, background auto-update fork). A usage
# error must bail before any of it, and a session load must not pay
# for it twice. ──
startupTrace("cli-parse-done")
installInterruptHook()
startupTrace("installInterruptHook")
# ESC / Ctrl-C cancel an ongoing request even with a draft typed; the
# input thread's InputCancelled handler stashes the draft and it
# returns with the next prompt. At the idle prompt the keys keep their
# readline editing meaning (clear the draft; cancel only an empty
# line). Plain global read lock-free by the input threads, assigned
# once here before any of them exist.
minline.cancelInterruptsTurn = proc(): bool = fatprompt.turnActive()
materializeBuiltinSkills()
startupTrace("materializeBuiltinSkills")
showUpdateNoticeMaybe()
startupTrace("showUpdateNoticeMaybe")
spawnBackgroundUpdateMaybe()
startupTrace("spawnBackgroundUpdateMaybe")
let prompt = args.join(" ")
var session: Session
var messages: JsonNode
var restoredDraft = ""
# Heal the drafts store before any restore reads it: quit-command sidecars
# the old teardown flush left behind must never prefill the prompt.
sweepQuitDrafts()
if resume:
# `resolveSessionPath` already ran (and bailed) above; recompute the
# resolved path here without re-validating, since nothing between the two
# points can change the on-disk set.
(session, messages) = loadSessionFile(resolved)
# Recover any prompt that was in-flight when the previous process ended
# (kill, power-off, Ctrl-C). Only restored when no explicit --prompt was
# passed: the user's command-line intent wins over the recovered draft.
if prompt == "":
restoredDraft = loadDraft(session.savePath)
else:
messages = %* [{"role": "system", "content": DefaultSystemPrompt}]
session.created = $now()
session.cwd = safeCwd()
session.savePath = if sessionOut != "": sessionOut else: newSessionPath()
# Recover a prompt drafted by a previous run in this directory that was
# killed before its first turn (so no `.3log` / session draft exists for
# it). It was saved under a cwd-keyed pending path; restore it here so the
# next fresh session picks it up. Skipped when an explicit --prompt was
# passed — the user's command-line intent wins over the recovered draft.
if prompt == "":
restoredDraft = loadPendingDraft(session.cwd)
# The pre-prompt sandbox warnings below print before the full config
# parse (which happens after the locks); pull the two switches they
# consult forward so `sandbox_wall_warn = off` works on the first
# print. The full parse re-applies them unchanged.
for layerPath in configReadPaths():
# The project layer's security switches are owned by
# dirsettings.applyDirConfig (the clamp runs right below); applying
# them here would let a repo file weaken an enabled sandbox.
if layerPath == projectLayer: continue
applyEarlySandboxSettings(layerPath)
# Directory-specific settings overlay: a `.3code/config` in the
# session dir (or any parent, nearest wins) may tighten the sandbox
# switches (an off sandbox can be turned on) but never weaken them,
# so it runs before initSandbox like the early global parse above.
dirsettings.applyDirConfig(session.cwd)
# Sandbox is mandatory: the single active policy (repo
# `.sandbox`, user file, else the built-in default) is loaded.
# Paths resolve relative to the session cwd so the policy follows
# the project, not the binary.
initSandbox(session.cwd)
startupTrace("initSandbox")
# When the OS sandbox backend cannot actually confine bash (Landlock
# probe failed on POSIX: old kernel, a container's seccomp profile
# blocking it; or on Windows the dedicated sandbox user/creds were
# never set up via `3code setup`), every bash tool call this session
# runs with no filesystem or network boundary. Warn once here, before
# the fat prompt opens, in the same slot and shape as the auto-update
# notice (`· updated to v...`), but error-magenta so it reads as an
# error, not an FYI. Read/write/patch tools stay confined; those are
# enforced in-process regardless of the OS backend. Cheap: on Windows
# backendWorks is a user+creds check (no WFP engine open, no spawn);
# on POSIX initSandbox already paid for the probe above.
when not defined(providerStub):
if sandboxEnabled and sandbox.active and sandboxWallWarn and
sandbox.procboxExe.len == 0:
let msg = " · sandbox backend unavailable: bash runs unconfined " &
"this session (old kernel / container seccomp / on Windows " &
"`3code setup` not run); read/write/patch tools stay confined " &
"(disable this warning: [settings] sandbox_wall_warn = off)"
try:
stderr.write(MagentaFg & msg & Reset & "\n")
except CatchableError:
try: stderr.writeLine msg
except CatchableError: discard
when defined(windows):
# The other half of the same warning. `3code unsetup` (or a
# setup whose fence install failed) leaves the sandwall user and
# credentials in place, so the backend check above still passes
# and bash keeps its filesystem confinement - but the WFP net
# fence is gone and every sandboxed command has open network
# egress. netFenceState costs an engine enum (milliseconds) on an
# elevated token, and only for a standard user pays the one
# behavioral probe.
if sandboxEnabled and sandbox.active and sandboxWallWarn and
sandbox.procboxExe.len > 0 and
sandbox.netFenceState() == sandbox.nfsMissing:
let msg = " · 3code has open network access, run '3code setup' " &
"to sandbox"
try:
stderr.write(MagentaFg & msg & Reset & "\n")
except CatchableError:
try: stderr.writeLine msg
except CatchableError: discard
startupTrace("sandbox-setup-warn")
try:
acquireDirLock(session.cwd, session.savePath)
except DirLocked as e:
die(e.msg, ExitConfig)
try:
acquireSessionLock(session.savePath)
except SessionLocked as e:
releaseDirLock(session.cwd)
die(e.msg, ExitConfig)
# `-p --resume <plain-id>` continues the conversation privately, which
# means the transcript continues in the private directory. Resuming a
# private session keeps its file (private transcripts never move out).
# Runs after the startup locks for the same reason `:clear`'s fork does
# its own lock swap mid-session: adopting releases and re-acquires the
# session lock itself, so it must not race the one acquired above.
discard adoptPrivateTranscriptDir(session)
# Subscription auth: oauth-marked providers resolve their bearer
# through the token store (auto-refresh) instead of a static key.
# ChatGPT additionally needs its Codex-backend headers on every call.
subscriptionTokenForImpl = proc(provider: string): string {.closure.} =
result = auth_xai.subscriptionTokenFor(provider)
if result == "":
result = auth_openai.subscriptionTokenFor(provider)
if result == "":
result = auth_google.subscriptionTokenFor(provider)
if result == "":
result = auth_anthropic.subscriptionTokenFor(provider)
extraHeadersImpl = chatgptExtraHeaders
api.codexModelsHook = auth_openai.fetchCodexModels
api.bearerHook = subscriptionBearer
api.extraHeadersHook = extraHeadersFor
var activeColorKeys: Table[string, string]
(activeCurrent, activeProviders, activeColorKeys) = loadStackOrEmpty()
# Re-apply the directory overlay after the full parse: every
# [settings] key cascades (compiled default < user config < nearest
# store), and the parse just re-applied the user config's own values,
# which would otherwise undo a directory's setting. The
# default-provider ladder (directory store cascade, config current,
# most-used ledger, first section) lives in
# config.resolveDefaultCurrent; selectableProviders() keeps a
# limitproviders whitelist ahead of every rung — unless the project
# layer pinned `current`: the repo pin owns selection, and the
# per-directory sticky must not defeat it on every later start (an
# accidental switch in one directory would move every start off the
# pin).
applyDirSettingsOverlay(safeCwd())
dirsettings.dirCurrentBaseline = dirsettings.dirCurrentFor(safeCwd())
if not (projectLayer != "" and currentOriginLayer == projectLayer):
activeCurrent = resolveDefaultCurrent(safeCwd(), activeCurrent,
selectableProviders())
if activeProviders.len == 0 and activeCurrent != "":
# A config that sets `current` but has no [provider] section used to
# fall through to the first-run wizard, which then refused every name
# with "already configured" (the wizard's ledger check reads the same
# `current`). Diagnose the config instead of pretending it's a first
# run.
let origin = if currentOriginLayer != "": currentOriginLayer else: configPath()
die(origin & ": no [provider] section; add one or remove " &
"'current' from [settings]", ExitConfig)
# Resolve the real mode now that `[settings] mode` has been read: detect
# the terminal background unless the config pinned a palette. The palette
# is re-applied so the welcome screen (rendered next) uses the resolved
# colors before `[colors]` overrides are layered on top.
startupTrace("locks-acquired")
applyPalette(detectColorMode(colorModePref))
minline.CaretCellFg = OffWhiteFg
startupTrace("palette-detect")
if activeColorKeys.len > 0:
let (both, lightOnly) = splitColorOverrides(activeColorKeys)
applyColorOverrides(both, lightOnly)
minline.CaretCellFg = OffWhiteFg
let wantedProfile =
if model != "": model
elif resume and session.profileName != "": session.profileName
else: ""
var prof = resolveSessionProfile(wantedProfile, session.profileName)
if prof.name.len > 0:
bumpProviderUsage(prof.name)
var editor = welcome(prof)
startupTrace("welcome")
# Terminal, session lock, and thread cleanup all funnel through a single
# exit proc so every exit path restores the same state. SIGTERM/SIGHUP get
# their own handler because the default disposition skips exit procs.
addExitProc(cleanup)
when defined(posix):
# Fatal-signal terminal restore: termios restore plus one write(2)
# of the mode-reset escapes only - the stdio lock may be held by
# whichever thread crashed, so buffered output would hang instead of
# dying. Registration policy (which signals) lives in signals.nim.
proc fatalSignalRestore(sig: cint) {.noconv, gcsafe.} =
signal(sig, SIG_DFL) # first: no recursive re-entry
fatprompt.restoreCancelTermios()
fatprompt.restoreInputTermios()
# One literal, one write: no allocation on a possibly-corrupt heap.
# Mirrors minline.restoreTerminal (cursor, attrs, bracketed paste,
# kitty pop) plus DECSET 2026l, which restoreTerminal balances only
# on balanced paints - a crash mid-paint would otherwise leave the