-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.ts
More file actions
1406 lines (1343 loc) · 64.3 KB
/
Copy pathcli.ts
File metadata and controls
1406 lines (1343 loc) · 64.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
#!/usr/bin/env tsx
/**
* headlesscode — Phase 1 headless CLI entry.
*
* Exit codes:
* 0 success
* 1 task failed / max iterations / bounded failure
* 2 usage or configuration error (bad args, missing API key)
*/
import * as fs from "node:fs"
import * as path from "node:path"
import { LocalMemoryStore } from "./memory/local.js"
import type { MemoryStore } from "./memory/types.js"
import { OpenRouterClient, parseReasoningEffort } from "./llm/openrouter.js"
import { OllamaClient } from "./llm/ollama.js"
import type { LlmClient } from "./engine/types.js"
import { HeadlessSession } from "./engine/loop.js"
import { chownWorktreeWorkspace } from "./dashboard/session-launch.js"
import { isLocalExploreEnabled } from "./engine/local-explore.js"
import { Logger } from "./engine/logger.js"
import {
appendCodeIntelTools,
appendDescribeImageTool,
buildSystemPrompt,
loadCustomModes,
selectToolsForMode,
} from "./engine/prompt.js"
import { orchestrateMain } from "./orchestrator/cli.js"
import { watchMain } from "./watcher/cli.js"
import { checkpointsMain } from "./checkpoints/cli.js"
import { dashboardMain } from "./dashboard/cli.js"
import { trendMain } from "./dashboard/trend-cli.js"
import { indexMain } from "./codesearch/cli.js"
import { codemapMain } from "./codemap/cli.js"
import { initMain } from "./init/cli.js"
import { provisionMain, pushPrMain } from "./github/cli.js"
import { decisionProxyMain } from "./decision-proxy/cli.js"
import { migrateMain } from "./migrate/cli.js"
import { projectsMain } from "./projects/cli.js"
import { analyzeCliMain } from "./orchestrator/analyze-cli.js"
import { costHistoryCliMain } from "./orchestrator/cost-history-cli.js"
import { resolvePermissions, type PermissionsConfig } from "./permissions/config.js"
import { resolveModelForMode, resolveReasoningEffortForMode } from "./config/mode-models.js"
const VERSION = "0.1.0"
interface CliOptions {
mode: string
task?: string
taskFile?: string
workspace?: string
/** Explicit session id override (set by the dashboard's session-launch endpoint). */
sessionId?: string
/** See HeadlessSessionConfig.requireArtifactPathPattern (loop.ts) — a research-harness primitive. */
requireArtifactPath?: string
/** See HeadlessSessionConfig.requireArtifactMinCitations (loop.ts). */
requireArtifactMinCitations?: number
/** See HeadlessSessionConfig.requireArtifactSections (loop.ts) — pipe-separated on the CLI. */
requireArtifactSections?: string[]
model?: string
maxIterations?: number
consecutiveErrorLimit?: number
/**
* Recursive task decomposition (`new_task`): hard cap on how deep a single
* root session may delegate (default DEFAULT_MAX_RECURSION_DEPTH = 2;
* also $HEADLESSCODE_MAX_RECURSION_DEPTH). See src/engine/loop.ts.
*/
maxRecursionDepth?: number
/**
* Recursive task decomposition (`new_task`): a child's default
* maxIterations as a fraction of the parent's REMAINING iterations
* (default DEFAULT_CHILD_ITERATION_FRACTION = 0.5; also
* $HEADLESSCODE_CHILD_ITERATION_FRACTION). See src/engine/loop.ts.
*/
childIterationFraction?: number
/**
* Hard cap on tokens the model may generate per LLM call (default
* DEFAULT_MAX_TOKENS = 32768; also $HEADLESSCODE_MAX_TOKENS). See
* src/engine/loop.ts.
*/
maxTokens?: number
/** Sliding-window history cap, in messages (also see DEFAULT_WINDOW_SIZE in engine/loop.ts). */
windowSize?: number
/**
* Phase 3 context condensation: the model's real context window in
* tokens (default: live OpenRouter lookup, else
* DEFAULT_CONTEXT_WINDOW_TOKENS in src/engine/condense.ts).
*/
contextWindowTokens?: number
/**
* Phase 3 context condensation: fraction of the context window at which
* the oldest turns are condensed (default
* DEFAULT_CONDENSE_THRESHOLD_FRACTION in src/engine/condense.ts).
*/
condenseThreshold?: number
/**
* Async/background condensation: fraction of the context window at which
* the condensation LLM call fires EARLY in the background (default
* DEFAULT_CONDENSE_EARLY_FIRE_FRACTION in src/engine/condense.ts). Must be
* below the hard `condenseThreshold`; when it isn't, the async path is off
* and only the synchronous hard-threshold path runs.
*/
condenseEarlyFire?: number
/**
* Phase 3 context condensation: model id for the condensation call
* (default: the session model, or the `_condensation` key in
* .headlesscode/mode-models.json).
*/
condenseModel?: string
/** Per-LLM-call abort timeout, ms (default: DEFAULT_LLM_TIMEOUT_MS in engine/loop.ts). */
llmTimeoutMs?: number
/**
* Streaming-and-reasoning: opt-in SSE streaming (default OFF — the
* blocking request path is unchanged). Also settable via
* $HEADLESSCODE_STREAM ("1"/"true"/"yes"/"on").
*/
stream: boolean
/** Phase 6: per-session cost cap, USD (also $HEADLESSCODE_MAX_COST_USD). */
maxCostUsd?: number
/** Phase 6: per-session duration cap, ms (also $HEADLESSCODE_MAX_DURATION_MS). */
maxDurationMs?: number
logFile?: string
memoryDir?: string
noMemory: boolean
dryRun: boolean
version: boolean
help: boolean
/** Checkpoints on by default; --no-checkpoints opts out. */
noCheckpoints: boolean
checkpointDir?: string
/** Decision escalation timeout, ms (also $HEADLESSCODE_DECISION_TIMEOUT_MS). */
decisionTimeoutMs?: number
/** Pause/resume max duration, ms (also $HEADLESSCODE_MAX_PAUSE_MS). */
maxPauseMs?: number
/** Permissions: comma-separated command prefixes allowed to run (also $HEADLESSCODE_ALLOWED_COMMANDS). */
allowedCommands?: string
/** Permissions: comma-separated command prefixes never allowed (also $HEADLESSCODE_DENIED_COMMANDS). */
deniedCommands?: string
/** Permissions: comma-separated protected-file globs (also $HEADLESSCODE_PROTECTED_FILES). */
protectedFiles?: string
/** Permissions escape hatch: allow writes to protected files (default: false). */
allowProtectedWrites: boolean
/**
* OPT-IN local exploration phase (default OFF): a bounded, read-only local
* Ollama pass runs before the cloud model's first turn and folds its
* findings into a labeled synthetic message. Also settable via
* $HEADLESSCODE_LOCAL_EXPLORE. Experimental — see plans/local-explore-phase-experiment.md.
*/
localExplore: boolean
/**
* switch_mode (plans/switch-mode-headless.md): opt-in auto-approval of
* in-place mode switches — OFF by default because the approval gate is the
* security boundary that keeps a restricted mode from silently granting
* itself a broader mode's permissions. Also settable via
* $HEADLESSCODE_AUTO_APPROVE_MODE_SWITCH.
*/
autoApproveModeSwitch: boolean
/** switch_mode: hard cap on total in-place mode switches per session (default 5). */
maxModeSwitches?: number
}
const USAGE = `headlesscode — headless coding-agent harness (Phase 1 engine)
Usage:
headlesscode --task "<task text>" [options]
headlesscode --task-file <path> [options]
headlesscode --dry-run [options] # build system prompt + validate config, no LLM call
Subcommands:
headlesscode orchestrate --repo <path> --issue <n>... [--qa] [--deploy] [--dry-run]
Run a full parallel orchestration round
(split → spawn → review → QA → deploy gate). See
\`npx tsx src/cli.ts orchestrate --help\` for full options.
headlesscode orchestrate status --repo <path> [--wait] [--timeout-ms <n>] [--json]
Print a compact per-group status of a round, or block inside one
call until every group is terminal (--wait) — replaces
hand-rolled poll loops over the state file / harness.log. See
\`npx tsx src/cli.ts orchestrate status --help\` for full options.
headlesscode orchestrate stop --repo <path> --group <name> [--group <name> ...]
Stop a group's worker COMPLETELY (whole process tree via
scripts/stop-worker.sh — issue #20) and mark it needs-human. See
\`npx tsx src/cli.ts orchestrate stop --help\` for full options.
headlesscode watch --owner <o> --repo <r> --label <label> [--run-once]
Poll GitHub for labeled issues and fan out into orchestration
batches (idempotent). See
\`npx tsx src/cli.ts watch --help\` for full options.
headlesscode checkpoints --workspace <path> [list | restore <hash> | diff <hash>]
List/restore/diff shadow-git checkpoints for a workspace. See
\`npx tsx src/cli.ts checkpoints --help\` for full options.
headlesscode dashboard [--port 4390] [--repo <path>]
Serve a local cost/token dashboard with a live per-session
event feed and pause/resume control (Phase 3: no longer purely
read-only — see src/dashboard/server.ts). See
\`npx tsx src/cli.ts dashboard --help\` for full options.
headlesscode trend --repo <path> [--repo <path> ...] [--port 4460]
Serve a local, auto-refreshing page comparing multiple repos'
cost-efficiency trends side by side (wasted-session tracking,
cost/iteration vs. round-size correlation, rework rate). See
\`npx tsx src/cli.ts trend --help\` for full options.
headlesscode index --workspace <path> [--model <id>] [--embedding-backend <b>]
Build/refresh the codebase semantic-search index for a workspace
(used by the codebase_search tool). A separate, explicit step —
never auto-triggered mid-session. --embedding-backend picks
openrouter (default), ollama (local), or airunner (local
AIRunner server). See \`npx tsx src/cli.ts index --help\` for
full options.
headlesscode codemap --workspace <path> [--force] [--watch] [--interval-ms <n>]
Build/refresh a project's deterministic module/import map
(codemap.json/codemap.lock/codemap.html in the central project
store). No LLM anywhere in the pipeline; regeneration is
fingerprint-aware (an unchanged repo writes nothing). --watch
turns it into a long-running poll loop. See
\`npx tsx src/cli.ts codemap --help\` for full options.
headlesscode init --workspace <path> [--skip-index] [--skip-codemap]
Register a new project in one step: resolves the central data
dir, detects the stack(s) (drives per-session instruction
selection), ensures .gitignore excludes .headlesscode/, then
builds the codesearch index + codemap. See
\`npx tsx src/cli.ts init --help\` for full options.
headlesscode provision --installation-id <id> --owner <o> --repo <r> --target <dir>
Clone a GitHub repo the App installation can access into a local
dir (token stripped from the remote URL), ready as a
--workspace value. Also --list-repos <id>. See
\`npx tsx src/cli.ts provision --help\` for full options.
headlesscode push-pr --installation-id <id> --owner <o> --repo <r> \\
--local-dir <path> --branch <name> --title <title> --body <text> [--base <branch>]
Push a local branch to a GitHub repo with the App installation
token (token scrubbed from .git/config immediately), then open
a pull request from it — never to the repo's default branch,
never auto-merged. See
\`npx tsx src/cli.ts push-pr --help\` for full options.
headlesscode decision-proxy --workspace <path> [--task <text>] [--task-file <path>]
OPT-IN (HEADLESSCODE_DECISION_PROXY=1) LLM stand-in for the
human on ask_followup_question: watches <path> for
.harness.needs-decision and answers via .harness.decision-answer,
grounded in the session's ORIGINAL task text. Writes nothing
when uncertain/errored — the existing timeout fallback fires
as today. See \`npx tsx src/cli.ts decision-proxy --help\` for
full options.
headlesscode migrate [--workspace <path>]
One-time central-store migrations: moves global shared
instructions (~/.roo/) and the checkpoint store
(~/.headlesscode/checkpoints) into ~/.local/share/headlesscode/,
plus a workspace's legacy .headlesscode/ content (index,
mode-models.json, permissions.json) into the central project
store. Idempotent; each move is verified before the source is
removed. See \`npx tsx src/cli.ts migrate --help\`.
headlesscode projects list [--json] [--registered-only] [--stale] [--size]
Enumerate the central per-project store as a table (or JSON),
optionally filtered to registered/stale entries, with an
opt-in size column. See
\`npx tsx src/cli.ts projects list --help\` for full options.
headlesscode projects prune [--dry-run] [--yes] [--include-registered]
Reclaim orphaned store entries (missing paths that were never
registered, plus pre-registry no-project.json litter). Never
deletes a registered project without --include-registered; the
escape hatch for a deleted repo / unmounted drive. See
\`npx tsx src/cli.ts projects prune --help\` for full options.
Options:
--mode <slug> Mode to run in (built-in or from .roomodes). Default: code
--task <text> The task description for the agent
--task-file <path> Read the task from a file (relative to workspace)
--workspace <root> Workspace root (default: $HEADLESSCODE_WORKSPACE_ROOT or cwd)
--session-id <id> Explicit session id override (default: a fresh UUID).
Used by the dashboard's session-launch endpoint so
the browser can open the session's event view
immediately; rarely needed from a terminal.
--model <id> OpenRouter model id (default: $OPENROUTER_MODEL or deepseek/deepseek-v4-flash-0731)
--max-iterations <n> Loop iteration cap (default: 250 — see DEFAULT_MAX_ITERATIONS
in src/engine/loop.ts)
--max-recursion-depth <n> Recursive task decomposition (new_task): hard cap
on how deep one root session may delegate
(default: 2 = root → child → grandchild; a
deeper new_task call is refused as a normal
tool error). Default:
$HEADLESSCODE_MAX_RECURSION_DEPTH
--child-iteration-fraction <f> Recursive task decomposition: a child's
default maxIterations as a fraction of the
parent's REMAINING iterations (default: 0.5,
floor 3 — a child never exceeds what its parent
has left). Default:
$HEADLESSCODE_CHILD_ITERATION_FRACTION
--max-tokens <n> Hard cap on tokens the model may generate per LLM
call (default: 32768 — see DEFAULT_MAX_TOKENS in
src/engine/loop.ts). Default: $HEADLESSCODE_MAX_TOKENS
--consecutive-error-limit <n> Consecutive mistakes before giving up (default: 3)
--window-size <n> Sliding-window history cap, in messages, before the
oldest are evicted (default: 300; see DEFAULT_WINDOW_SIZE
in src/engine/loop.ts for why)
--context-window <n> Phase 3 context condensation: the model's real context
window in tokens (default: live OpenRouter lookup, else
128000; see DEFAULT_CONTEXT_WINDOW_TOKENS in
src/engine/condense.ts)
--condense-threshold <f> Phase 3 context condensation: fraction of the context
window at which the oldest turns are condensed into one
summary (default: 0.75, or 0.92 for the local code-mode
backend — see cli.ts's LOCAL_CONDENSE_THRESHOLD_FRACTION;
must be between 0 and 1)
--condense-early-fire <f> Async condensation: fraction of the context window at
which the condensation LLM call fires EARLY, in the
background against a snapshot, while the loop keeps
running (default: 0.6, provisional; DISABLED for the
local code-mode backend — a second concurrent call
against a single locally-loaded model has no latency to
hide and only adds GPU contention — must be below
--condense-threshold or the async path is off)
--condense-model <id> Phase 3 context condensation: model id for the
condensation call (default: the session model, or the
_condensation key in .headlesscode/mode-models.json)
--llm-timeout-ms <n> Per-LLM-call abort timeout, ms (default: 300000 / 5 min
— reasoning models can take a while on a heavy turn)
--log-file <path> Also append structured logs to this file
--memory-dir <path> Store project memory (facts + session summaries) under
<path>. Enables Phase 3 memory. Default (when enabled):
$HEADLESSCODE_MEMORY_DIR or <workspace>/.headlesscode/memory
--no-memory Explicitly disable memory even if HEADLESSCODE_MEMORY_DIR is set
--max-cost-usd <n> Phase 6: per-session cost cap in USD (decimal, e.g. 0.05).
Default: $HEADLESSCODE_MAX_COST_USD; off when neither is set
--max-duration-ms <n> Phase 6: per-session wall-clock cap in ms. Default:
$HEADLESSCODE_MAX_DURATION_MS; off when neither is set.
When a cap trips the session aborts with reason "budget"
--dry-run Build the system prompt, validate .roomodes/rules loading,
then exit without calling the LLM (no API key needed)
--no-checkpoints Disable shadow-git checkpoints (on by default; see
\`headlesscode checkpoints --help\`). No effect for
read-only sessions (reviewer/QA), which never checkpoint
--checkpoint-dir <path> Shadow-git storage root override (default:
~/.headlesscode/checkpoints — MUST be outside the
workspace; see docs/checkpoints.md)
--decision-timeout-ms <n> How long ask_followup_question blocks waiting for
a human/orchestrator answer before falling back
to autonomous decision, ms (default 1800000 / 30
min). Default: $HEADLESSCODE_DECISION_TIMEOUT_MS
--max-pause-ms <n> Max duration a dashboard-initiated pause may hold
the loop before it auto-resumes, ms (default
7200000 / 2h — matches the orchestrator's stall
guard). Default: $HEADLESSCODE_MAX_PAUSE_MS
--allowed-commands <list> Comma-separated command prefixes the agent may run.
Default: $HEADLESSCODE_ALLOWED_COMMANDS, else
.headlesscode/permissions.json, else empty (=
allow everything except --denied-commands)
--denied-commands <list> Comma-separated command prefixes that are ALWAYS
refused (deny wins over allow; dangerous shell
substitutions are always blocked regardless).
Default: $HEADLESSCODE_DENIED_COMMANDS, else
.headlesscode/permissions.json, else empty
--protected-files <list> Comma-separated glob patterns of files the agent may
not write. Default: $HEADLESSCODE_PROTECTED_FILES,
else .headlesscode/permissions.json, else
".env,.env.*,*.pem,*.key,id_rsa*"
--allow-protected-writes Escape hatch: permit writes to protected files
(default: OFF). Also settable via
"allowProtectedWrites": true in
.headlesscode/permissions.json
--stream Opt-in SSE streaming (streaming-and-reasoning):
stream token/reasoning deltas and emit
llm_stream_chunk events for live-typing view.
Default: OFF (blocking requests unchanged).
Also settable via $HEADLESSCODE_STREAM
--local-explore OPT-IN local exploration phase (experimental,
default OFF): run a bounded, strictly read-only
local Ollama pass (qwen3.5:9b — read_file +
list_files only) before the cloud model's first
turn and fold its findings into the cloud
context as a labeled synthetic message. Fails
open to cloud-only on any local error. Also
settable via $HEADLESSCODE_LOCAL_EXPLORE
--auto-approve-mode-switch switch_mode: auto-approve in-place mode switches
WITHOUT escalating to a human/orchestrator.
OFF by default — the approval gate is the
security boundary that keeps a restricted mode
(e.g. architect, read+md-only) from silently
granting itself a broader mode's edit
permissions. Also settable via
$HEADLESSCODE_AUTO_APPROVE_MODE_SWITCH
--max-mode-switches <n> switch_mode: hard cap on total in-place mode
switches per session (default: 5 — see
DEFAULT_MAX_MODE_SWITCHES in src/engine/loop.ts).
Also settable via
$HEADLESSCODE_MAX_MODE_SWITCHES
--version Print version and exit
--help Show this help and exit
Environment:
HEADLESSCODE_OPENROUTER_API_KEY Required (except --dry-run)
OPENROUTER_MODEL Default model id
OPENROUTER_HTTP_REFERER Optional HTTP-Referer header
OPENROUTER_APP_TITLE Optional X-Title header
HEADLESSCODE_WORKSPACE_ROOT Default workspace root
HEADLESSCODE_MEMORY_DIR Default memory dir (memory enabled when set)
HEADLESSCODE_PROJECT Project scope for memory (default: workspace basename)
HEADLESSCODE_ALLOWED_COMMANDS Default --allowed-commands (comma-separated)
HEADLESSCODE_DENIED_COMMANDS Default --denied-commands (comma-separated)
HEADLESSCODE_PROTECTED_FILES Default --protected-files (comma-separated globs)
HEADLESSCODE_ALLOW_PROTECTED_WRITES Allow protected-file writes ("1"/"true")
HEADLESSCODE_MAX_RECURSION_DEPTH Default --max-recursion-depth (positive int)
HEADLESSCODE_CHILD_ITERATION_FRACTION Default --child-iteration-fraction (0 < f <= 1)
HEADLESSCODE_MAX_TOKENS Default --max-tokens (positive int)
HEADLESSCODE_STREAM Opt-in SSE streaming ("1"/"true"/"yes"/"on")
HEADLESSCODE_LOCAL_EXPLORE Opt-in local exploration phase ("1"/"true")
HEADLESSCODE_AUTO_APPROVE_MODE_SWITCH Auto-approve switch_mode calls ("1"/"true"/"yes"/"on")
HEADLESSCODE_MAX_MODE_SWITCHES switch_mode: hard cap on total in-place
mode switches per session (positive int)
HEADLESSCODE_LOCAL_EXPLORE_MODEL Local model (default qwen3.5:9b)
HEADLESSCODE_LOCAL_EXPLORE_MAX_ITERATIONS Iteration cap (default 15)
HEADLESSCODE_LOCAL_EXPLORE_CONTEXT_TOKENS Context-token budget (default 131072)
HEADLESSCODE_LOCAL_EXPLORE_TIMEOUT_MS Per-call timeout ms (default 120000)
HEADLESSCODE_OLLAMA_URL Ollama base URL (default http://localhost:11434)
HEADLESSCODE_DECISION_PROXY Opt-in decision-proxy agent ("1"/"true") — an
LLM stand-in for the human on
ask_followup_question (headlesscode
decision-proxy subcommand; see
plans/decision-proxy-agent.md)
`
export function parseArgs(argv: string[]): { options: CliOptions; error?: string } {
const options: CliOptions = {
mode: "code",
noMemory: false,
dryRun: false,
version: false,
help: false,
noCheckpoints: false,
allowProtectedWrites: false,
stream: false,
localExplore: false,
autoApproveModeSwitch: false,
}
for (let i = 0; i < argv.length; i++) {
const arg = argv[i]
const eq = arg.indexOf("=")
const flag = eq === -1 ? arg : arg.slice(0, eq)
const inlineValue = eq === -1 ? undefined : arg.slice(eq + 1)
const next = (): string | undefined => {
if (inlineValue !== undefined) {
return inlineValue
}
const v = argv[i + 1]
if (v === undefined || v.startsWith("--")) {
return undefined
}
i++
return v
}
switch (flag) {
case "--mode":
case "--task":
case "--task-file":
case "--workspace":
case "--model":
case "--log-file":
case "--session-id":
case "--require-artifact-path":
case "--require-artifact-sections": {
const value = next()
if (value === undefined) {
return { options, error: `Missing value for ${flag}` }
}
switch (flag) {
case "--mode":
options.mode = value
break
case "--task":
options.task = value
break
case "--task-file":
options.taskFile = value
break
case "--workspace":
options.workspace = value
break
case "--model":
options.model = value
break
case "--log-file":
options.logFile = value
break
case "--session-id":
options.sessionId = value
break
case "--require-artifact-path":
options.requireArtifactPath = value
break
case "--require-artifact-sections":
options.requireArtifactSections = value
.split("|")
.map((s) => s.trim())
.filter(Boolean)
break
}
break
}
case "--max-iterations":
case "--consecutive-error-limit":
case "--window-size":
case "--context-window":
case "--llm-timeout-ms":
case "--max-recursion-depth":
case "--max-mode-switches":
case "--max-tokens":
case "--require-artifact-min-citations": {
const value = next()
const num = value === undefined ? Number.NaN : Number(value)
if (!Number.isInteger(num) || num <= 0) {
return { options, error: `${flag} requires a positive integer` }
}
if (flag === "--max-iterations") {
options.maxIterations = num
} else if (flag === "--consecutive-error-limit") {
options.consecutiveErrorLimit = num
} else if (flag === "--window-size") {
options.windowSize = num
} else if (flag === "--context-window") {
options.contextWindowTokens = num
} else if (flag === "--max-recursion-depth") {
options.maxRecursionDepth = num
} else if (flag === "--max-mode-switches") {
options.maxModeSwitches = num
} else if (flag === "--max-tokens") {
options.maxTokens = num
} else if (flag === "--require-artifact-min-citations") {
options.requireArtifactMinCitations = num
} else {
options.llmTimeoutMs = num
}
break
}
case "--child-iteration-fraction": {
const value = next()
const num = value === undefined ? Number.NaN : Number(value)
if (!Number.isFinite(num) || num <= 0 || num > 1) {
return { options, error: "--child-iteration-fraction requires a fraction between 0 and 1 (e.g. 0.5)" }
}
options.childIterationFraction = num
break
}
case "--condense-threshold": {
const value = next()
const num = value === undefined ? Number.NaN : Number(value)
if (!Number.isFinite(num) || num <= 0 || num >= 1) {
return { options, error: "--condense-threshold requires a fraction between 0 and 1 (e.g. 0.75)" }
}
options.condenseThreshold = num
break
}
case "--condense-early-fire": {
const value = next()
const num = value === undefined ? Number.NaN : Number(value)
if (!Number.isFinite(num) || num <= 0 || num >= 1) {
return { options, error: "--condense-early-fire requires a fraction between 0 and 1 (e.g. 0.6)" }
}
options.condenseEarlyFire = num
break
}
case "--condense-model": {
const value = next()
if (value === undefined) {
return { options, error: "Missing value for --condense-model" }
}
options.condenseModel = value
break
}
case "--max-cost-usd": {
const value = next()
const num = value === undefined ? Number.NaN : Number(value)
if (!Number.isFinite(num) || num <= 0) {
return { options, error: "--max-cost-usd requires a positive number (USD, decimal allowed)" }
}
options.maxCostUsd = num
break
}
case "--max-duration-ms": {
const value = next()
const num = value === undefined ? Number.NaN : Number(value)
if (!Number.isInteger(num) || num <= 0) {
return { options, error: "--max-duration-ms requires a positive integer" }
}
options.maxDurationMs = num
break
}
case "--decision-timeout-ms": {
const value = next()
const num = value === undefined ? Number.NaN : Number(value)
if (!Number.isInteger(num) || num <= 0) {
return { options, error: "--decision-timeout-ms requires a positive integer" }
}
options.decisionTimeoutMs = num
break
}
case "--max-pause-ms": {
const value = next()
const num = value === undefined ? Number.NaN : Number(value)
if (!Number.isInteger(num) || num <= 0) {
return { options, error: "--max-pause-ms requires a positive integer" }
}
options.maxPauseMs = num
break
}
case "--memory-dir":
case "--allowed-commands":
case "--denied-commands":
case "--protected-files": {
const value = next()
if (value === undefined) {
return { options, error: `Missing value for ${flag}` }
}
switch (flag) {
case "--memory-dir":
options.memoryDir = value
break
case "--allowed-commands":
options.allowedCommands = value
break
case "--denied-commands":
options.deniedCommands = value
break
case "--protected-files":
options.protectedFiles = value
break
}
break
}
case "--allow-protected-writes":
options.allowProtectedWrites = true
break
case "--stream":
options.stream = true
break
case "--local-explore":
options.localExplore = true
break
case "--auto-approve-mode-switch":
options.autoApproveModeSwitch = true
break
case "--checkpoint-dir": {
const value = next()
if (value === undefined) {
return { options, error: "Missing value for --checkpoint-dir" }
}
options.checkpointDir = value
break
}
case "--no-memory":
options.noMemory = true
break
case "--no-checkpoints":
options.noCheckpoints = true
break
case "--dry-run":
options.dryRun = true
break
case "--version":
options.version = true
break
case "--help":
case "-h":
options.help = true
break
default:
return { options, error: `Unknown argument: ${arg}` }
}
}
return { options }
}
export async function main(argv: string[] = process.argv.slice(2)): Promise<number> {
// Phase 2 subcommand: `headlesscode orchestrate ...` — delegates to the
// orchestrator module (split → spawn → watch → review). Keeps the Phase 1
// run path untouched.
if (argv[0] === "orchestrate") {
return orchestrateMain(argv.slice(1))
}
// Issue #148 subcommand: `headlesscode pipeline ...` — run the stage-
// isolated research→filing pipeline (each stage a fresh session taking the
// prior stage's artifact as input).
if (argv[0] === "pipeline") {
const { pipelineMain } = await import("./orchestrator/cli.js")
return pipelineMain(argv.slice(1))
}
// Phase 5 subcommand: `headlesscode watch ...` — GitHub issue watcher
// (poll label → split → spawn → durable idempotency state).
if (argv[0] === "watch") {
return watchMain(argv.slice(1))
}
// Checkpoints subcommand: `headlesscode checkpoints ...` — list/restore/diff
// shadow-git checkpoints for a workspace (see src/checkpoints/).
if (argv[0] === "checkpoints") {
return checkpointsMain(argv.slice(1))
}
// Cost/token dashboard subcommand: `headlesscode dashboard ...` — local
// HTML dashboard with live per-session events + pause/resume control
// (Phase 3 — see src/dashboard/; no longer purely read-only).
if (argv[0] === "dashboard") {
return dashboardMain(argv.slice(1))
}
// Cross-repo cost-efficiency trend subcommand: `headlesscode trend ...` —
// a local, auto-refreshing page comparing multiple repos' cost-history
// side by side (see src/dashboard/trend.ts). Distinct from `dashboard`'s
// single-repo "Cost history" section: reads live on every request, no
// cached snapshot.
if (argv[0] === "trend") {
return trendMain(argv.slice(1))
}
// Codebase semantic-search index subcommand: `headlesscode index ...` —
// build/refresh <workspace>/.headlesscode/codesearch/index.jsonl for the
// codebase_search tool (see src/codesearch/). A separate, EXPLICIT step —
// never auto-triggered mid-session (it costs real money and takes time).
if (argv[0] === "index") {
return indexMain(argv.slice(1))
}
// Deterministic per-project codemap subcommand: `headlesscode codemap ...` —
// generate the module/import map (codemap.json/codemap.lock/codemap.html)
// into the central project store; `--watch` becomes a long-running poll
// loop (see src/codemap/ + docs/codemap.md). No LLM anywhere in the
// pipeline — mechanical, deterministic, cheap to regenerate.
if (argv[0] === "codemap") {
return codemapMain(argv.slice(1))
}
// One-command project registration subcommand: `headlesscode init ...` —
// resolve central data dir + detect stacks + ensure .gitignore excludes
// .headlesscode/ + build index + codemap in one step (see src/init/).
if (argv[0] === "init") {
return initMain(argv.slice(1))
}
// GitHub App repo provisioning subcommand: `headlesscode provision ...` —
// clone a repo the App installation can access into a local dir (token
// stripped from the remote), ready as a --workspace value. Also
// `--list-repos <id>` (see src/github/cli.ts + docs/github-app-setup.md).
if (argv[0] === "provision") {
return provisionMain(argv.slice(1))
}
// GitHub push-back subcommand: `headlesscode push-pr ...` — push a local
// branch to a repo the App installation can access (token scrubbed from
// .git/config immediately), then open a PR from it. The "write" half of
// provisioning (see src/github/cli.ts + docs/github-app-setup.md).
if (argv[0] === "push-pr") {
return pushPrMain(argv.slice(1))
}
// Decision-proxy subcommand: `headlesscode decision-proxy ...` — an
// OPT-IN (HEADLESSCODE_DECISION_PROXY=1) LLM stand-in for the human on
// ask_followup_question. Watches a workspace for .harness.needs-decision
// and writes .harness.decision-answer grounded in the session's original
// task text (see src/decision-proxy/ + plans/decision-proxy-agent.md).
if (argv[0] === "decision-proxy") {
return decisionProxyMain(argv.slice(1))
}
// Migration subcommand: `headlesscode migrate ...` — the explicit,
// human-triggered version of the one-time central-store migrations
// (shared instructions, checkpoint store, legacy workspace
// `.headlesscode/`). See src/migrate/ + src/project-store.ts.
if (argv[0] === "migrate") {
return migrateMain(argv.slice(1))
}
// Ad-hoc session log analysis: `headlesscode analyze-worktree ...` — the
// orchestrator already runs this automatically per group (see
// src/orchestrator/log-analysis.ts + cli.ts's onGroupUpdate); this
// subcommand lets a human point it at any worktree by hand.
if (argv[0] === "analyze-worktree") {
return analyzeCliMain(argv.slice(1))
}
// Cost/token history: `headlesscode cost-history ...` — read-side for
// the mandatory, automatic recording in watch.ts (recordCostIfTerminal).
if (argv[0] === "cost-history") {
return costHistoryCliMain(argv.slice(1))
}
// Central-store project registry: `headlesscode projects ...` — enumerate
// (`list`) and reclaim (`prune`) the central per-project store
// (~/.local/share/headlesscode/projects/; see src/projects/ + src/project-store.ts).
if (argv[0] === "projects") {
return projectsMain(argv.slice(1))
}
const { options, error } = parseArgs(argv)
if (error) {
process.stderr.write(`headlesscode: ${error}\n\n${USAGE}`)
return 2
}
if (options.help) {
process.stdout.write(USAGE)
return 0
}
if (options.version) {
process.stdout.write(`headlesscode ${VERSION}\n`)
return 0
}
const workspaceRoot = path.resolve(options.workspace ?? process.env.HEADLESSCODE_WORKSPACE_ROOT ?? process.cwd())
const logger = new Logger({ level: "info", filePath: options.logFile })
// Silent-death observability (issue #150): live-verified 2026-08-21
// (twice, across two different models) that this process can disappear
// entirely mid-run — no exit code, no error log, no trace, not even the
// wrapping shell's own `echo "exited with code $?"`. Confirmed via
// `grep -rn` across this file and loop.ts before this fix: zero
// process-level handlers existed for any of these events. Logger.error/
// warn write via fs.appendFileSync (synchronous — see logger.ts), so
// these are safe to call immediately before process.exit without an
// async flush race. This does NOT catch SIGKILL (uncatchable by
// definition — the suspected OOM-kill case in #150 may still be
// SIGKILL, not SIGTERM) or a hard crash inside a native addon, but it
// closes every JS-level silent-exit path: an uncaught throw, a rejected
// promise nobody awaited, or a graceful termination request.
process.on("uncaughtException", (err) => {
logger.error("[cli] uncaughtException — process terminating", {
message: err instanceof Error ? err.message : String(err),
stack: err instanceof Error ? err.stack : undefined,
})
process.exit(3)
})
process.on("unhandledRejection", (reason) => {
logger.error("[cli] unhandledRejection — process terminating", {
reason:
reason instanceof Error
? (reason.stack ?? reason.message)
: (() => {
try {
return JSON.stringify(reason)
} catch {
return String(reason)
}
})(),
})
process.exit(3)
})
process.on("SIGTERM", () => {
logger.warn("[cli] SIGTERM received — process terminating", {
rssMb: Math.round(process.memoryUsage().rss / 1024 / 1024),
})
process.exit(143)
})
// Cheap postmortem diagnostic for the #150 OOM hypothesis (unconfirmed —
// dmesg showed no OOM-killer entries when checked live, but access may
// have been permission-limited): RSS at session start costs one log
// line and needs no periodic timer, unlike full memory-pressure polling.
logger.info("[cli] session process started", {
pid: process.pid,
rssMb: Math.round(process.memoryUsage().rss / 1024 / 1024),
})
// Fresh-session memory trap (issue #138): every `npx tsx src/cli.ts`
// invocation is a COMPLETELY fresh process with zero memory of any
// prior invocation's model reads/edits, even against the same
// --workspace and --task-file. A task file written/edited across a
// restart can easily (and wrongly) claim "you already read X, don't
// re-read it" — live-verified 2026-08-21: a local model trusted
// exactly that kind of false claim and hallucinated a plausible-but-
// wrong edit_file call from the claim alone. Cheapest mitigation (the
// issue's own "direction 1"): a marker file this process itself
// writes/updates on every run against a workspace, so the NEXT
// invocation can print a loud, impossible-to-miss note when one
// existed already. Doesn't stop a bad task file from lying — makes
// the failure mode visible in the log for whoever's supervising.
// Scoped to --task-file specifically: the trap is about a task file's
// own false claims, not sessions in general.
if (options.taskFile) {
const markerPath = path.join(workspaceRoot, ".headlesscode", "last-session.json")
try {
const prior = JSON.parse(fs.readFileSync(markerPath, "utf-8")) as {
sessionId?: string
taskFile?: string
startedAt?: string
}
logger.warn(
"[cli] NOTE: this is a FRESH process with ZERO memory of any prior run against this workspace, even if the task file references one",
{
priorSessionId: prior.sessionId,
priorTaskFile: prior.taskFile,
priorStartedAt: prior.startedAt,
guidance:
"If the task file claims you already read/did something in an earlier turn, that claim is about a DIFFERENT process — verify everything yourself before acting on it.",
},
)
} catch {
// No marker (first run against this workspace) or unreadable/
// corrupt — either way, nothing to warn about, proceed silently.
}
try {
fs.mkdirSync(path.join(workspaceRoot, ".headlesscode"), { recursive: true })
fs.writeFileSync(
markerPath,
JSON.stringify({ sessionId: options.sessionId, taskFile: options.taskFile, startedAt: new Date().toISOString() }),
"utf-8",
)
} catch (err) {
// Non-fatal: the marker is a best-effort diagnostic, never a
// reason to abort a real session over a write failure.
logger.warn("[cli] failed to write last-session marker (non-fatal)", { error: String(err) })
}
}
// ── dry-run: no API key required ──────────────────────────────────────────
if (options.dryRun) {
try {
const customModes = await loadCustomModes(workspaceRoot)
const built = await buildSystemPrompt({
workspaceRoot,
mode: options.mode,
customModes,
})
// Dry-run advertises the same non-vendored tools a real session
// appends (code-intelligence + describe_image; browser_action is
// deliberately omitted here — the loop appends it, but this
// listing is a prompt/config check, not a live session).
const tools = appendCodeIntelTools(
appendDescribeImageTool(selectToolsForMode(options.mode, customModes)),
)
// Per-mode model assignment: dry-run resolves the model exactly
// like a real run (mode-models.json / _default / OPENROUTER_MODEL,
// with an explicit --model always winning) so the effective model
// is visible without an LLM call. undefined -> the client default.
const dryRunModel = resolveModelForMode({
workspaceRoot,
mode: options.mode,
explicitModel: options.model,
env: process.env,
})
// Reasoning effort (issue #30): resolved + validated here too so
// --dry-run catches a bad value (e.g. a typo in the env var or
// mode-models.json `_reasoning_effort` key) BEFORE the experiment
// burns any real LLM calls. A throw lands in the catch below.
const dryRunEffort = resolveReasoningEffortForMode({ workspaceRoot, env: process.env })
parseReasoningEffort(dryRunEffort)
process.stdout.write(built.prompt + "\n")
process.stdout.write(
`\n───── dry-run summary ─────\n` +
`mode: ${options.mode}\n` +
`model: ${dryRunModel ?? "deepseek/deepseek-v4-flash-0731 (client default)"}\n` +
`reasoning effort: ${dryRunEffort ?? "(unset — endpoint default)"}\n` +
`workspace: ${workspaceRoot}\n` +
`custom modes: ${customModes.length ? customModes.map((m) => m.slug).join(", ") : "(none, using built-ins)"}\n` +
`exposed tools: ${tools.map((t) => (t.type === "function" ? t.function.name : t.type)).join(", ")}\n` +
`system prompt: ${built.prompt.length} chars\n`,
)
logger.info("dry-run complete", { mode: options.mode, workspaceRoot })
return 0
} catch (err) {
process.stderr.write(`headlesscode: dry-run failed: ${err instanceof Error ? err.message : String(err)}\n`)
return 2
}
}
// ── real run: API key required ────────────────────────────────────────────
const apiKey = process.env.HEADLESSCODE_OPENROUTER_API_KEY
if (!apiKey) {
process.stderr.write(
"headlesscode: HEADLESSCODE_OPENROUTER_API_KEY is not set.\n" +
" Export it (e.g. export HEADLESSCODE_OPENROUTER_API_KEY=sk-or-...) or use --dry-run to\n" +
" validate the prompt/config without calling the LLM.\n",
)
return 2
}
if (!options.task && !options.taskFile) {
process.stderr.write(`headlesscode: provide a task with --task <text> or --task-file <path>\n\n${USAGE}`)
return 2
}
if (options.task && options.taskFile) {
process.stderr.write("headlesscode: use either --task or --task-file, not both\n")
return 2
}
let taskText = options.task ?? ""
if (options.taskFile) {
const taskFilePath = path.resolve(workspaceRoot, options.taskFile)
try {
taskText = fs.readFileSync(taskFilePath, "utf-8")
} catch (err) {
process.stderr.write(
`headlesscode: cannot read task file '${taskFilePath}': ${err instanceof Error ? err.message : String(err)}\n`,
)
return 2
}
}
if (taskText.trim() === "") {
process.stderr.write("headlesscode: task text is empty\n")
return 2
}