-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutor.ts
More file actions
2484 lines (2273 loc) · 106 KB
/
Copy pathexecutor.ts
File metadata and controls
2484 lines (2273 loc) · 106 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
/**
* Headless tool executor.
*
* Implements the Phase 1 core tools using plain `fs` + `child_process` — NO
* `vscode.*` anywhere. Argument names match the vendored native-tool schemas
* exactly (see `src/vendor/zoo-code/src/core/prompts/tools/native-tools/`):
*
* - read_file { path, offset?, limit? }
* - write_to_file { path, content }
* - apply_diff { path, diff }
* - search_replace { file_path, old_string, new_string }
* - edit_file { file_path, old_string, new_string, expected_replacements? }
* - execute_command { command, cwd?, timeout? }
* - list_files { path?, recursive? }
* - browser_action { action, url?, selector?, text? } — Playwright-backed
* headless browser inspection (launch/screenshot/click/type/getConsoleLogs/
* getNetworkErrors/close); NEW work, no upstream port (see src/tools/browser/).
* - outline / go_to_definition / find_references / import_graph — the four
* code-intelligence tools (TS Compiler API backed, src/codeintel/): one
* cached ts.Program per workspace serves all four. NEW work, no upstream
* port (see src/codeintel/).
*
* Every file operation resolves relative to the configured workspace root and
* is rejected if it escapes the workspace — both lexically (`../` traversal)
* and after following symlinks (a symlink whose real location is outside the
* workspace is refused; see resolveWithinWorkspace). Results are plain strings
* + an { isError } flag; long outputs are truncated to keep the model context
* bounded.
*
* The three surgical edit tools are backed by the vendored Zoo Code diff
* logic: `apply_diff` uses the fuzzy MultiSearchReplaceDiffStrategy
* (src/vendor/zoo-code/src/core/diff/strategies/multi-search-replace.ts),
* `search_replace` is a strict one-occurrence literal match, and `edit_file`
* falls back exact → whitespace-tolerant → token-based matching (plus
* file-creation when old_string is "").
*
* read_file carries a session-scoped cache (see the readFileCache comment
* below): the exact same effective args served against byte-identical content
* earlier in THIS session get a short cache-hit message instead of the full
* content, because re-sending identical content is pure output-token waste.
*
* OPT-IN local summarization (see src/tools/output-summarizer.ts): when
* HEADLESSCODE_LOCAL_SUMMARIZATION=1, oversized execute_command output that
* would exceed MAX_RESULT_CHARS is compressed by a small local Ollama model
* before reaching the cloud model (with a "[Output summarized by local
* model…]" transparency header). OFF by default; on ANY failure the result
* falls back to today's exact blunt truncation. Deliberately limited to
* execute_command output — read_file / write_to_file / diff content always
* stays verbatim (summarizing code a model is about to edit would be a
* correctness hazard).
*
* KNOWN LIMITATION (issue #88) — edit-tool read-modify-write is NOT atomic:
* `apply_diff`, `search_replace`, `edit_file`, and `write_to_file` each read
* the current file, compute the new content, and write it back with a plain
* `fs.writeFile` — no mtime re-check, no lock, no compare-and-swap. Within
* one session this is safe: the loop serializes edits to the same file and
* restricts the parallel read-only tool-call group to paths that aren't
* being edited (see loop.ts's same-file batching / parallel-group
* restriction). It is NOT safe across an external editor or a second,
* concurrent headlesscode session touching the same file — whichever write
* lands last silently wins and the other one's changes are lost (classic
* TOCTOU). No fix is planned; this is accepted as a known limitation rather
* than adding locking complexity for a single-session tool.
*/
import * as fs from "node:fs"
import * as fsp from "node:fs/promises"
import * as path from "node:path"
import { createHash } from "node:crypto"
import { spawn, type ChildProcess } from "node:child_process"
import { setTimeout as sleep } from "node:timers/promises"
import { isTypeScriptWorkspace } from "./language-detect.js"
import type { Logger } from "../engine/logger.js"
// Side effect: installs String.prototype.toPosix() used by path formatting.
import "../vendor/zoo-code/src/utils/path.js"
import { MultiSearchReplaceDiffStrategy } from "../vendor/zoo-code/src/core/diff/strategies/multi-search-replace.js"
import { browserActionHandler, disposeBrowserSessions } from "./browser/handler.js"
import { describeImageHandler } from "../vision/tool.js"
import {
goToDefinitionHandler,
findReferencesHandler,
importGraphHandler,
outlineHandler,
renameSymbolHandler,
} from "../codeintel/handlers.js"
import { runTestsHandler } from "./run-tests.js"
import type { AuxLlmUsage, ToolContext, ToolHandler, ToolResult } from "../engine/types.js"
import {
checkCommand,
checkRedirectEscape,
describeRedirect,
type CommandRefusal,
type RedirectTarget,
} from "../permissions/commands.js"
import {
OllamaOutputSummarizer,
isLocalSummarizationEnabled,
summarizeToolResult,
MAX_SUMMARIZER_INPUT_CHARS as SUMMARIZER_INPUT_CAP,
} from "./output-summarizer.js"
import { findMatchingPattern } from "../permissions/protected-files.js"
import { resolvePermissions, type PermissionsConfig } from "../permissions/config.js"
import { createEmbedder, EMBEDDING_BACKEND_ENV, resolveEmbeddingBackend } from "../codesearch/embedder.js"
import { indexFilePath, loadIndexMetadata } from "../codesearch/index.js"
import { formatSearchResults, searchIndex } from "../codesearch/search.js"
/**
* Absolute path to bash, if present, for execute_command's shell (see the
* spawn() call below) — `undefined` falls back to `spawn`'s own default
* (`/bin/sh`) on a host without bash, rather than failing to spawn at all.
*
* That fallback must never be SILENT: it reintroduces the exact class of bug
* fixed in issue #35 (bash-only syntax like `${PIPESTATUS[0]}` silently
* failing the whole command line under `/bin/sh`, which produced a real
* false QA_VERDICT: FAIL). A future environment (e.g. a minimal Alpine-based
* Docker image shipping only `ash`) that lacks bash would quietly bring this
* back with no signal — so warn loudly, once, at module load, instead of
* letting it fail silently again.
*/
export const BASH_PATH: string | undefined = fs.existsSync("/bin/bash")
? "/bin/bash"
: fs.existsSync("/usr/bin/bash")
? "/usr/bin/bash"
: undefined
if (BASH_PATH === undefined) {
process.stderr.write(
"[executor] WARNING: bash not found (checked /bin/bash, /usr/bin/bash) — execute_command falls back to " +
"/bin/sh, which does NOT support bash-only syntax (${PIPESTATUS[0]}, [[ ]], arrays). This previously " +
"caused a real false QA_VERDICT: FAIL (issue #35). Install bash in this environment to avoid it.\n",
)
}
/** Cap on tool-result text fed back to the model (keep context bounded). */
export const MAX_RESULT_CHARS = 30_000
/**
* Per-stream accumulation cap for execute_command output. The small margin
* above MAX_RESULT_CHARS guarantees the final combined string always exceeds
* the cap, so truncate()'s "output truncated" trailer still fires (a combined
* string exactly at the cap would be returned unchanged, silently losing it).
*/
const MAX_COMMAND_STREAM_CHARS = MAX_RESULT_CHARS + 1024
/**
* Default read_file slice-mode line limit when the model passes no explicit
* `limit`. 600 lines, down from the vendored tool-schema default of 2000: a
* no-arg broad read historically pulled up to ~30k chars (~7-8k tokens) of
* history per call, and the truncation header already tells the model to page
* with `offset` for anything bigger. An explicit `limit` arg always wins, so
* 2000 stays available as an opt-in. Measured from real session logs: ~29% of
* read_file calls were no-arg broad reads.
*/
export const DEFAULT_READ_LIMIT = 600
/** Resolve the read_file slice-mode default limit (env-overridable). */
export function readLimitFromEnv(env: NodeJS.ProcessEnv = process.env): number {
const raw = env.HEADLESSCODE_READ_LIMIT
if (raw === undefined || raw === "") {
return DEFAULT_READ_LIMIT
}
const n = Number(raw)
return Number.isInteger(n) && n > 0 ? n : DEFAULT_READ_LIMIT
}
/** Default execute_command timeout in seconds (matches vendored default ~120s). */
export const DEFAULT_COMMAND_TIMEOUT_S = 120
/** Max entries returned by list_files before truncation. */
export const MAX_LIST_FILES = 500
/** Options that configure a ToolExecutor's decision-escalation behavior. */
export interface ToolExecutorOptions {
/** ask_followup_question escalation timeout, ms (default 30 min — see DEFAULT_DECISION_TIMEOUT_MS). */
decisionTimeoutMs?: number
/** ask_followup_question poll interval, ms (default 5s — override in tests). */
decisionPollIntervalMs?: number
/**
* Resolved permissions (command allow/deny + protected files). When absent
* the executor resolves them itself from env vars +
* `<workspaceRoot>/.headlesscode/permissions.json` + built-in defaults, so
* executors constructed without CLI flags (reviewer/QA, tests) still
* enforce the repo's committed policy.
*/
permissions?: PermissionsConfig
/** See ToolContext.guardLargeOverwrites (types.ts) for the full writeup. */
guardLargeOverwrites?: boolean
/**
* Live worker monitoring: fired at the same lifecycle points where the
* `.harness.needs-decision` marker is written/cleared, so the session can
* mirror them on its event feed (see ToolContext.onDecisionEvent).
*/
onDecisionEvent?: (eventType: "decision_blocked" | "decision_answered", fields: Record<string, unknown>) => void
/**
* Live todo-list monitoring: fired each time update_todo_list replaces the
* session's checklist (see ToolContext.onTodoEvent). The session mirrors
* it on its event feed as `todo_updated`.
*/
onTodoEvent?: (fields: { todos: string; done: number; inProgress: number; pending: number }) => void
/**
* Test-selection (run_tests): optional session-provided inference of the
* files changed since the session's baseline. Wired by HeadlessSession to
* diff the shadow-checkpoint repo's baseline commit against the current
* working tree (see src/checkpoints/service.ts) — the checkpoint service
* tracks a baseline per task, so this works even when the workspace
* itself has no git repo. Returning `undefined` makes the run_tests
* handler fall back to the workspace's own `git status`. Absent for bare
* executors (tests, reviewer/QA — which don't register run_tests anyway).
*/
getSessionChangedFiles?: () => Promise<string[] | undefined>
/**
* Auxiliary LLM usage reporting (cloud vision captioning — see
* src/vision/describe.ts). Wired by HeadlessSession right after it
* constructs a BudgetTracker (same place as setBudgetClockHooks), so every
* captioning call's tokens/cost lands in the SAME BudgetTracker + running
* session totals as a main call — never an untracked side channel. Absent
* for bare executors (tests, reviewer/QA) — which also disables the
* screenshot action's automatic captioning, so an un-accounted executor
* never spends money behind the session's back (the model can still call
* `describe_image` explicitly).
*/
onAuxLlmUsage?: (usage: AuxLlmUsage) => void
}
export class ToolExecutor {
private readonly handlers = new Map<string, ToolHandler>()
private pauseBudgetClock: (() => void) | undefined
private resumeBudgetClock: (() => void) | undefined
private onAuxLlmUsage: ((usage: AuxLlmUsage) => void) | undefined
/**
* Session-scoped read_file cache (see readFileCache below). One executor
* serves one session, so per-instance state is exactly per-session state.
* Keyed by a serialized string (see makeReadFileCacheKey) — the map must
* never be keyed by object identity, or no two calls would ever collide.
*/
private readonly readCache = new Map<string, ReadFileCacheEntry>()
/**
* Session-scoped todo list state (see TodoListState below). update_todo_list
* always REPLACES the whole checklist, so this holds only the latest one.
* Conversational/session state — NEVER written to a workspace file.
*/
private readonly todoList = new TodoListState()
/**
* Session-scoped repeat-call guard for list_files (see listFilesHandler's
* doc comment). Keyed by the call's effective (path, recursive) — value is
* the condensationGeneration this key was last listed at, so a repeat is
* only refused when nothing has been condensed since (the earlier result
* might have been evicted from context, in which case re-listing is the
* only way to see it again).
*/
private readonly listFilesCalls = new Map<string, ListFilesCallEntry>()
/**
* Incremented by notifyCondensed() every time HeadlessSession applies a
* condensation (sync or background) — see listFilesCalls above.
*/
private condensationGeneration = 0
/** Resolved permissions handed to every handler call (see ToolExecutorOptions.permissions). */
readonly permissions: PermissionsConfig
constructor(
readonly workspaceRoot: string,
private readonly options: ToolExecutorOptions = {},
) {
this.permissions =
options.permissions ?? resolvePermissions({ workspaceRoot: this.workspaceRoot, env: process.env })
this.onAuxLlmUsage = options.onAuxLlmUsage
}
register(name: string, handler: ToolHandler): void {
this.handlers.set(name, handler)
}
has(name: string): boolean {
return this.handlers.has(name)
}
names(): string[] {
return [...this.handlers.keys()]
}
/**
* Wired by HeadlessSession right after it constructs a BudgetTracker, so
* ask_followup_question (and any future blocking tool) can pause the
* session's budget-duration clock while waiting on an external answer.
* Never called when no budget is configured.
*/
setBudgetClockHooks(pause: () => void, resume: () => void): void {
this.pauseBudgetClock = pause
this.resumeBudgetClock = resume
}
/**
* Register read_file wired to THIS executor's session-scoped cache. Must be
* called by every construction path that wants the cache (headless,
* reviewer, QA) — each executor instance gets its own independent cache.
*/
registerReadFile(): void {
this.register("read_file", (args, ctx) =>
readFileHandler(args, ctx, this.readCache.get(readFileKey(args, ctx)), this.readCache),
)
}
/**
* Register list_files wired to THIS executor's session-scoped repeat-call
* guard (see listFilesCalls above and listFilesHandler's doc comment).
* Every construction path that offers list_files should call this instead
* of a bare `register("list_files", listFilesHandler)`.
*/
registerListFiles(): void {
this.register("list_files", (args, ctx) => listFilesHandler(args, ctx, this.listFilesCalls, this.condensationGeneration))
}
/**
* Called by HeadlessSession right after it splices a condensation into the
* live history (both the synchronous and background paths) — advances the
* generation the list_files repeat-call guard checks against, so a call
* repeated after a condensation is allowed again instead of refused.
*/
notifyCondensed(): void {
this.condensationGeneration++
}
/**
* Register update_todo_list wired to THIS executor's session-scoped todo
* state, surfacing each state change via the onTodoEvent option (the
* session mirrors it as a `todo_updated` feed event). Must be called by
* the headless construction path; read-only executors (reviewer/QA/local
* explore) deliberately leave it unregistered — their tool lists never
* advertise it either, so it stays an inert stub there.
*/
registerTodoList(): void {
this.register("update_todo_list", (args, ctx) => updateTodoListHandler(args, ctx, this.todoList))
}
/**
* Snapshot of the session's current todo list, or undefined before the
* first update_todo_list call. Read-only accessor — the dashboard /
* observability side can query live planning state without touching it.
*/
getTodoList(): TodoListSnapshot | undefined {
return this.todoList.snapshot()
}
async execute(name: string, args: Record<string, unknown>): Promise<ToolResult> {
const handler = this.handlers.get(name)
if (!handler) {
return {
content: `[Error] Unknown tool: ${name}. This harness has no handler registered for it.`,
isError: true,
}
}
try {
return await handler(args, {
workspaceRoot: this.workspaceRoot,
permissions: this.permissions,
guardLargeOverwrites: this.options.guardLargeOverwrites,
decisionTimeoutMs: this.options.decisionTimeoutMs,
decisionPollIntervalMs: this.options.decisionPollIntervalMs,
pauseBudgetClock: this.pauseBudgetClock,
resumeBudgetClock: this.resumeBudgetClock,
onDecisionEvent: this.options.onDecisionEvent,
onTodoEvent: this.options.onTodoEvent,
// Auxiliary LLM usage (cloud vision captioning): forwarded so
// handlers can report spend into the session's BudgetTracker.
onAuxLlmUsage: this.onAuxLlmUsage,
})
} catch (err) {
return {
content: `[Error] Tool '${name}' failed: ${err instanceof Error ? err.message : String(err)}`,
isError: true,
}
}
}
/**
* Session teardown: hard-kill any execute_command children that a timeout
* left running in the background (see executeCommandHandler), AND close
* any launched browser (see disposeBrowserSessions — a model may never
* call browser_action's close(), so the browser is torn down here at true
* session end, exactly like the backgrounded children). A single tool
* call timing out mid-session does NOT trigger this — the backgrounded
* process is exactly what the model asked for and must keep running until
* the model cleans it up or the session truly ends. Only calling this at
* true session end does, so nothing is orphaned past its session.
*/
dispose(): void {
killBackgroundCommands()
disposeBrowserSessions()
}
}
// ─── Path safety ─────────────────────────────────────────────────────────────
export class PathTraversalError extends Error {
constructor(requested: string, root: string) {
super(`Path escapes the workspace root (${root}): ${requested}`)
this.name = "PathTraversalError"
}
}
/**
* A path whose REAL location (after following symlinks) escapes the workspace
* even though its lexical path stays inside it (issue #64). Subclasses
* PathTraversalError so existing callers that catch the base class (e.g. the
* dashboard's HTTP layer, which maps it to a 400) keep treating it the same
* way.
*/
export class SymlinkEscapeError extends PathTraversalError {
constructor(requested: string, root: string, resolvedTo: string) {
super(requested, root)
this.name = "SymlinkEscapeError"
this.message = `Path escapes the workspace root through a symlink (${root}): ${requested} — it resolves to ${resolvedTo}`
}
}
/**
* Resolve `p` against the workspace root and reject anything that escapes it.
*
* Two layers of containment (issue #64):
* 1. Lexical: path.resolve + a prefix check — the classic `../` traversal
* guard. This alone is NOT sufficient: every `fsp` call in the file tools
* FOLLOWS symlinks, so an agent can `ln -s ~/.ssh <ws>/sshlink` and then
* read AND write outside the workspace through it. The protected-files
* guard is bypassed the same way — it only ever sees the
* workspace-relative lexical path.
* 2. Symlink-following (assertNoSymlinkEscape): the real path of the deepest
* resolvable ancestor must stay inside the workspace root's own real
* path. An escaping symlink — as a directory component, as the target
* itself, or as a dangling symlink a later write would create THROUGH —
* is refused with SymlinkEscapeError. The ancestor walk keeps writes to
* not-yet-existing paths working (realpath on a nonexistent path throws).
*
* Documented boundary: a path is usable only if every existing component of
* it really lives inside the workspace. A symlink that escapes is refused
* even when it points somewhere "useful" (e.g. a node_modules symlinked to a
* sibling checkout) — the model can still reach such paths through
* execute_command, which has its own permission gate.
*/
export function resolveWithinWorkspace(root: string, p: string): string {
const rootAbs = path.resolve(root)
const target = path.resolve(rootAbs, p)
if (target !== rootAbs && !target.startsWith(rootAbs + path.sep)) {
throw new PathTraversalError(p, rootAbs)
}
assertNoSymlinkEscape(rootAbs, target, p)
return target
}
/**
* Reject a `target` whose real location (after following symlinks) escapes
* `rootAbs`. Called by resolveWithinWorkspace after the lexical check.
*
* Walk up from `target` until an existing path is found, realpath it, and
* require the result to stay inside the root's own realpath. Three cases
* realpath can't answer directly, each handled explicitly:
* - Path doesn't exist yet (a write to a new file): walk up to the deepest
* existing ancestor — its real location decides where the write lands.
* - A component is a DANGLING symlink: realpath fails, but a write through
* it would create the target AT THE SYMLINK'S DESTINATION, so follow the
* chain (re-running the containment check on each hop) instead of walking
* past it.
* - A symlink cycle (realpath throws ELOOP): unresolvable — the kernel
* refuses reads/writes through it too, so nothing can escape; walk up.
*/
function assertNoSymlinkEscape(rootAbs: string, target: string, requested: string): void {
const rootReal = realpathOrSelf(rootAbs)
const seen = new Set<string>()
let probe = target
for (;;) {
if (seen.has(probe)) {
// Symlink cycle: unresolvable, so no read/write can escape through
// it — walk up and keep checking the ancestors.
const parent = path.dirname(probe)
if (parent === probe) {
return
}
probe = parent
continue
}
seen.add(probe)
let real: string
try {
real = fs.realpathSync(probe)
} catch {
let st: fs.Stats | undefined
try {
st = fs.lstatSync(probe)
} catch {
st = undefined
}
if (st?.isSymbolicLink()) {
// Dangling symlink: a later write would create the target at
// the symlink's destination, so verify the destination chain
// instead of skipping the symlink.
probe = path.resolve(path.dirname(probe), fs.readlinkSync(probe))
continue
}
const parent = path.dirname(probe)
if (parent === probe) {
return
}
probe = parent
continue
}
if (real !== rootReal && !real.startsWith(rootReal + path.sep)) {
throw new SymlinkEscapeError(requested, rootAbs, real)
}
return
}
}
/** realpath of `p`, falling back to the lexical path when it can't resolve. */
function realpathOrSelf(p: string): string {
try {
return fs.realpathSync(p)
} catch {
return p
}
}
/** Build a path-safety-checked absolute path, catching traversal errors. */
function safeTarget(ctx: ToolContext, p: string): string {
return resolveWithinWorkspace(ctx.workspaceRoot, p)
}
// ─── Result helpers ──────────────────────────────────────────────────────────
function ok(content: string): ToolResult {
return { content: truncate(content), isError: false }
}
function err(content: string): ToolResult {
return { content: truncate(`[Error] ${content}`), isError: true }
}
/**
* Build the model-facing refusal message for a blocked execute_command. The
* tone matches the other err(...) messages in this file: name what was
* refused and why, and give a well-behaved model a concrete way to adjust.
*/
function refusalMessage(command: string, refusal: CommandRefusal): ToolResult {
switch (refusal.kind) {
case "dangerous":
return err(
`execute_command: refusing to run '${command}': it contains a dangerous shell substitution pattern ` +
`(e.g. \${var@P}, \${!var}, <<<\$(...), =(...), or *(e:...:)) which is ALWAYS blocked and cannot be ` +
`allow-listed or configured away. Rewrite the command without shell parameter-expansion tricks.`,
)
case "malformed":
return err(
`execute_command: refusing to run '${command}': malformed command (` +
`${refusal.parseError?.message ?? "shell syntax error"}) — a shell syntax error is never auto-approved. ` +
`Fix the quoting and retry.`,
)
case "denied":
return err(
`execute_command: refusing to run '${command}': sub-command '${refusal.subCommand}' is denied by the ` +
`permissions policy (matches denied pattern '${refusal.pattern}'). Adjust your approach; this command ` +
`is not permitted even if other parts of the chain are allowed.`,
)
case "not_allowed":
return err(
`execute_command: refusing to run '${command}': sub-command '${refusal.subCommand}' is not in the ` +
`allowed-commands list and cannot be auto-approved in this headless session. Add it via ` +
`--allowed-commands, HEADLESSCODE_ALLOWED_COMMANDS, or <workspaceRoot>/.headlesscode/permissions.json, ` +
`or adjust your approach.`,
)
case "protected_store":
return err(
`execute_command: refusing to run '${command}': sub-command '${refusal.subCommand}' is a recursive delete ` +
`targeting the shared central store at '${refusal.storeRoot}' (resolved target '${refusal.target}'). ` +
`The central store is protected BY DEFAULT and this cannot be overridden via --allowed-commands or ` +
`permissions.json — it is shared across every project on this machine, and no single workspace may ` +
`delete it. Do not attempt to reset it from inside the harness.`,
)
case "redirect_escape": {
const redirect = refusal.redirect
const shown = redirect !== undefined ? describeRedirect(redirect) : "an output redirect"
return err(
`execute_command: refusing to run '${command}': it redirects output outside the workspace root ` +
`('${shown}') — the resolved target is outside the workspace and cannot be written from a harness ` +
`session. This is the same boundary every file tool enforces (write_to_file/apply_diff/... reject ` +
`outside-workspace paths) and cannot be overridden via --allowed-commands or permissions.json. ` +
`Write scratch files under <workspaceRoot>/.headlesscode/scratch/ instead.`,
)
}
}
}
function truncate(content: string): string {
if (content.length <= MAX_RESULT_CHARS) {
return content
}
return (
content.slice(0, MAX_RESULT_CHARS) +
`\n…[output truncated at ${MAX_RESULT_CHARS} chars to keep context bounded]`
)
}
/**
* Apply the tool-result size discipline to raw handler output.
*
* With local summarization OFF (default) this is EXACTLY today's behavior:
* blunt-truncate over `MAX_RESULT_CHARS`. With it ON, a result that would
* exceed the cap is instead sent to the local model for compression; on ANY
* summarizer failure we fall back to the same blunt truncation, so an
* opted-in session with a broken Ollama behaves identically to a non-opted-in
* one. Small results never reach the summarizer (that would be pure latency
* and risk for zero benefit).
*
* NOTE: deliberately used ONLY for execute_command output (the large,
* mostly-noisy command-output case). read_file / write_to_file / diff
* content must stay verbatim — a summarized diff or file body would be a
* correctness hazard for the cloud model.
*/
async function summarizeCommandOutput(content: string): Promise<string> {
if (content.length <= MAX_RESULT_CHARS) {
return content
}
if (!isLocalSummarizationEnabled()) {
return truncate(content)
}
const summarizer = makeSummarizer()
if (summarizer === undefined) {
return truncate(content)
}
const input = content.length > SUMMARIZER_INPUT_CAP ? content.slice(0, SUMMARIZER_INPUT_CAP) : content
return summarizeToolResult(input, summarizer, summarizerLogger)
}
/**
* The one place summarization is actually performed, and the ONLY reason the
* executor module imports OllamaOutputSummarizer. Wired in the constructor.
*/
let summarizerLogger: Pick<Logger, "debug" | "warn"> = {
debug: () => {},
warn: (message) => process.stderr.write(`[local-summ] ${message}\n`),
}
/**
* Module-level session summarizer (one per process). Constructed lazily on the
* first oversized result of an opted-in session; never constructed for a
* non-opted-in session. Process-level rather than executor-level because the
* Ollama client is stateless; one process = one summarizer.
*/
let toolSummarizer: OllamaOutputSummarizer | undefined
/** Bind the session logger (used by the summarizer for non-fatal warnings). */
export function bindSummarizerLogger(logger: Pick<Logger, "debug" | "warn">): void {
summarizerLogger = logger
}
function requireString(args: Record<string, unknown>, key: string): string {
const v = args[key]
if (typeof v !== "string") {
throw new Error(`Missing or invalid string argument '${key}' for tool`)
}
return v
}
function toNonNegativeInt(v: unknown, fallback: number): number {
if (typeof v === "number" && Number.isFinite(v)) {
return Math.max(0, Math.floor(v))
}
if (typeof v === "string" && v.trim() !== "" && Number.isFinite(Number(v))) {
return Math.max(0, Math.floor(Number(v)))
}
return fallback
}
// ─── read_file session cache ─────────────────────────────────────────────────
/**
* Session-scoped read_file cache.
*
* read_file is the one tool with measured, real waste: a real session re-read
* the same path with identical args 14-16 times, re-sending byte-identical
* content at full output-token cost every time (see the DEFAULT_WINDOW_SIZE
* story in src/engine/loop.ts). Even with that history bug fixed, a model will
* legitimately re-read a file it saw earlier in a long session — there is no
* reason to pay full output tokens for content the conversation already has.
*
* Correctness: a cache hit requires BOTH (a) the exact effective args that
* produce byte-identical output, AND (b) the current on-disk content hashing
* identically to the prior read. (b) is checked by hashing the file at
* cache-check time — never by tracking "did a write-shaped tool get called",
* because a file can change for reasons the executor doesn't directly control
* (execute_command running a formatter/build/codegen, an external editor,
* anything else). The hash is cheap (node:crypto sha256, no new dependency).
*
* The hit short-circuit applies once per "unchanged streak": the first
* identical call after real content was served returns the short cache-hit
* message, the SECOND consecutive identical call serves real content again, so
* a model that is confused or insistent is never stuck being told "it's
* cached" with no way to actually get the content back.
*
* Scope: per ToolExecutor instance, i.e. per session (executors are
* constructed per-session — see createHeadlessExecutor and its read-only
* siblings). Deliberately NOT persisted to disk and NOT shared across
* instances: a reviewer/QA executor gets its own independent cache.
*/
/**
* Everything about a read_file call that affects its output, serialized into a
* stable string so two calls that produce byte-identical output always collide
* (see makeReadFileCacheKey).
*/
type ReadFileCacheKey = {
/** Resolved absolute path (path.resolve'd, so ./a.ts and a.ts collide). */
target: string
/** 'slice' or 'indentation'. */
mode: string
/** Effective 1-based offset (default 1). */
offset: number
/** Effective limit (default readLimitFromEnv()). */
limit: number
/** Effective indentation-mode max_lines (default 60); undefined in slice mode. */
windowLines?: number
}
/** One cache entry: content identity (hash + size + mtime) + streak state. */
type ReadFileCacheEntry = {
/** sha256 of the file content as of the last real read of this key. */
hash: string
/** File size at the last real read — half of the fast-path identity. */
size: number
/**
* mtime at the last real read — the other half of the fast-path identity.
* mtimeMs (float, sub-ms precision) is the highest-resolution mtime this
* Node exposes on a non-bigint stat (mtimeNs needs { bigint: true }).
*/
mtimeMs: number
/**
* Whether the last read of this key was already served as a cache-hit
* message. When true, the next identical call serves real content again
* (resetting this flag), so the hit message never loops forever.
*/
toldUnchanged: boolean
}
/**
* Serialize a read_file cache key to a stable string. Map keys must be
* primitives (object keys compare by identity, so two structurally-identical
* fresh objects would never collide); a JSON string of the fully-resolved
* effective args is both stable and collision-free.
*/
function makeReadFileCacheKey(key: ReadFileCacheKey): string {
return JSON.stringify(key)
}
/** Cache-hit message shown instead of the full file content. */
const READ_FILE_CACHE_HIT_MESSAGE =
"[cache] this file is unchanged since your last read of it earlier in this session (identical content, same range). Re-read the earlier tool result for the content, or call read_file again if you specifically need it re-sent."
function hashFileContent(content: string): string {
return createHash("sha256").update(content).digest("hex")
}
/** The indentation-mode window size this harness actually uses (Phase 1 minimal). */
const DEFAULT_INDENTATION_WINDOW_LINES = 60
/** read_file — slice mode with offset/limit pagination (offset is 1-based). */
function readFileHandler(
args: Record<string, unknown>,
ctx: ToolContext,
cache: ReadFileCacheEntry | undefined,
entry: Map<string, ReadFileCacheEntry>,
): Promise<ToolResult> {
const filePath = requireString(args, "path")
return (async () => {
const target = safeTarget(ctx, filePath)
const rel = path.relative(ctx.workspaceRoot, target).toPosix() || path.basename(target)
let stat: fs.Stats
try {
stat = await fsp.stat(target)
} catch (error) {
return err(`read_file: cannot stat '${rel}': ${errorMessage(error)}`)
}
if (!stat.isFile()) {
return err(`read_file: '${rel}' is not a file`)
}
const mode = typeof args.mode === "string" ? args.mode : "slice"
const offset = toNonNegativeInt(args.offset, 1) // 1-based
const limit = toNonNegativeInt(args.limit, readLimitFromEnv())
const indentation = args.indentation as Record<string, unknown> | undefined
const windowLines = mode === "indentation" ? toNonNegativeInt(indentation?.["max_lines"], DEFAULT_INDENTATION_WINDOW_LINES) : undefined
const key = makeReadFileCacheKey({ target, mode, offset, limit, windowLines })
// Trust model: unchanged size AND mtime ⇒ identical content, so the
// cached hash can be reused without re-reading the file; any mismatch
// (including a same-length rewrite, which changes mtime) falls back to
// a full read + sha256 below.
if (
cache !== undefined &&
!cache.toldUnchanged &&
cache.size === stat.size &&
cache.mtimeMs === stat.mtimeMs
) {
cache.toldUnchanged = true
return ok(READ_FILE_CACHE_HIT_MESSAGE)
}
let content: string
try {
content = await fsp.readFile(target, "utf-8")
} catch (error) {
return err(`read_file: cannot read '${rel}': ${errorMessage(error)}`)
}
// Cache-check the CURRENT on-disk content (never "no write tool was
// called"): identical args + identical hash => byte-identical output.
const currentHash = hashFileContent(content)
if (cache !== undefined && cache.hash === currentHash && !cache.toldUnchanged) {
cache.toldUnchanged = true
return ok(READ_FILE_CACHE_HIT_MESSAGE)
}
const allLines = content.split(/\r?\n/)
let result: ToolResult
if (mode === "indentation") {
// Phase 1 minimal: indentation mode falls back to a window around the
// anchor line (anchor_line 1-based), which is good enough for the loop.
const anchor = toNonNegativeInt(indentation?.["anchor_line"], offset)
result = ok(formatFileSlice(rel, allLines, Math.max(1, anchor), windowLines ?? DEFAULT_INDENTATION_WINDOW_LINES))
} else {
result = ok(formatFileSlice(rel, allLines, Math.max(1, offset), limit))
}
// Serve (or re-serve) real content; record identity + reset the hit
// flag so the next identical call may short-circuit once more.
entry.set(key, { hash: currentHash, size: stat.size, mtimeMs: stat.mtimeMs, toldUnchanged: false })
return result
})()
}
/**
* Compute the stable string cache key for a read_file call, mirroring exactly
* how readFileHandler resolves its args (defaults and all) so two calls that
* produce byte-identical output always collide on the same key. Path safety is
* enforced identically to the handler itself, so an escaping path errors here
* exactly as it would in the handler (and caches nothing).
*/
function readFileKey(args: Record<string, unknown>, ctx: ToolContext): string {
const filePath = requireString(args, "path")
const target = safeTarget(ctx, filePath)
const mode = typeof args.mode === "string" ? args.mode : "slice"
const offset = toNonNegativeInt(args.offset, 1) // 1-based
const limit = toNonNegativeInt(args.limit, readLimitFromEnv())
const indentation = args.indentation as Record<string, unknown> | undefined
const windowLines =
mode === "indentation" ? toNonNegativeInt(indentation?.["max_lines"], DEFAULT_INDENTATION_WINDOW_LINES) : undefined
return makeReadFileCacheKey({ target, mode, offset, limit, windowLines })
}
function formatFileSlice(rel: string, allLines: string[], offset: number, limit: number): string {
const start = Math.max(1, offset)
const slice = allLines.slice(start - 1, start - 1 + limit)
const totalLines = allLines.length
const body = slice.map((line, i) => `${start + i} | ${line}`).join("\n")
const header = `File: ${rel}`
if (totalLines > start - 1 + limit) {
return `${header}\nShowing lines ${start}-${start + slice.length - 1} of ${totalLines} total lines (use read_file with offset=${start + limit} to read more).\n${body}`
}
return `${header}\n${body}`.replace(/\n$/, "")
}
/**
* Shared protected-files guard for every write tool. Returns a refusal
* ToolResult when `rel` (workspace-relative, POSIX-separated) matches a
* protected pattern and the escape hatch — --allow-protected-writes or
* "allowProtectedWrites": true in .headlesscode/permissions.json — is
* explicitly on (OFF by default). Naming the matched pattern gives a
* well-behaved model a concrete reason to stop. A refusal is a real tool
* error (isError: true) and counts toward the consecutive-mistake bound,
* exactly like any other tool failure.
*/
function protectedWriteRefusal(toolName: string, rel: string, permissions: PermissionsConfig): ToolResult | null {
if (permissions.allowProtectedWrites) {
return null
}
const matchedPattern = findMatchingPattern(rel, permissions.protectedFiles)
if (matchedPattern === null) {
return null
}
return err(
`${toolName}: refusing to write protected file '${rel}' (matches protected pattern '${matchedPattern}'). ` +
`This file is protected by the harness permissions policy and cannot be overwritten. If this write is ` +
`genuinely required, re-run with --allow-protected-writes (or set "allowProtectedWrites": true in ` +
`<workspaceRoot>/.headlesscode/permissions.json); it is OFF by default.`,
)
}
/**
* Existing-file content length (bytes) above which write_to_file refuses to
* overwrite when ctx.guardLargeOverwrites is on. Chosen well above trivial
* stub/placeholder content (empty scaffolds, one-liners) so the common
* legitimate case — write_to_file creating or replacing a small/new file —
* is never affected; see largeOverwriteRefusal's doc comment.
*/
const LARGE_OVERWRITE_GUARD_BYTES = 200
/**
* guardLargeOverwrites (see ToolContext.guardLargeOverwrites, types.ts):
* refuse write_to_file against a file that already exists and has
* substantial content, mirroring edit_file's empty-old_string refusal in
* the other direction. Verified live 2026-08-20 against Qwen2.5-Coder-14B
* and Qwen3-14B: given a real ~500-line file and a one-function-add task,
* both had a strong bias toward regenerating the ENTIRE file from scratch
* via write_to_file instead of a targeted diff — and since a full
* regeneration needs far more output budget than a precise edit, this
* reliably truncates mid-file, silently destroying everything after the
* cutoff. The escape hatch (delete-then-write) is deliberate: it requires a
* SEPARATE, explicit destructive action instead of one accidental call, so
* a genuine full-file rewrite is still possible without disabling the
* guard.
*/
async function largeOverwriteRefusal(target: string, rel: string, ctx: ToolContext): Promise<ToolResult | null> {
if (!ctx.guardLargeOverwrites) {
return null
}
let existingSize: number
try {
existingSize = (await fsp.stat(target)).size
} catch {
return null // Target doesn't exist yet — the legitimate new-file case.
}
if (existingSize <= LARGE_OVERWRITE_GUARD_BYTES) {
return null
}
return err(
`write_to_file: refusing to overwrite '${rel}' (${existingSize} bytes of existing content).\n\n` +
`<error_details>\nwrite_to_file replaces this file's ENTIRE content. For an existing file of this size, ` +
`regenerating it from scratch instead of making a targeted change risks silently losing content that ` +
`isn't reproduced (especially if generation is cut off before finishing the full file).\n\n` +
`Recovery suggestions:\n1. Use edit_file or search_replace to make a precise, targeted change instead\n` +
`2. Use read_file first if you haven't seen the file's current contents\n3. If a full-file rewrite is ` +
`genuinely intended, delete the file first (execute_command) — write_to_file always succeeds against a ` +
`path that doesn't exist\n</error_details>`,
)
}
/** write_to_file — create parent dirs as needed, overwrite existing files. */
function writeToFileHandler(args: Record<string, unknown>, ctx: ToolContext): Promise<ToolResult> {
const filePath = requireString(args, "path")
const content = requireString(args, "content")
return (async () => {
const target = safeTarget(ctx, filePath)
const rel = path.relative(ctx.workspaceRoot, target).toPosix() || path.basename(target)
// Permissions: refuse writes to protected files (secret/credential
// patterns) unless the escape hatch — --allow-protected-writes or
// "allowProtectedWrites": true in .headlesscode/permissions.json — is
// explicitly on (OFF by default). All four write tools share the
// protectedWriteRefusal helper below, so no write path can bypass it.
const refusal = protectedWriteRefusal("write_to_file", rel, ctx.permissions)
if (refusal !== null) {
return refusal
}
const overwriteRefusal = await largeOverwriteRefusal(target, rel, ctx)
if (overwriteRefusal !== null) {
return overwriteRefusal
}
try {
await fsp.mkdir(path.dirname(target), { recursive: true })
await fsp.writeFile(target, content, "utf-8")
} catch (error) {
return err(`write_to_file: failed to write '${rel}': ${errorMessage(error)}`)
}
return ok(`File written: ${rel} (${Buffer.byteLength(content, "utf-8")} bytes)`)
})()
}
// ─── execute_command backgrounded-child registry ─────────────────────────────
/**
* Children that timed out and were intentionally left running in the
* background (see executeCommandHandler). Tracked for exactly two reasons:
* (a) their stdout/stderr pipes keep being drained so a long-running child
* never blocks on a full pipe buffer, and
* (b) `ToolExecutor.dispose()` can hard-kill anything still running when a
* session truly ends, so the harness never orphans a process.
* A later `execute_command` mid-session (e.g. `pkill`, `docker compose down`)
* works unchanged — the model targets the process by port/name/pattern, same
* as a human would.
*/
const backgroundCommands = new Set<ChildProcess>()
/** Best-effort unref of a stdio pipe so it can't keep the event loop alive. */