@thincoder/core 0.11.4 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/abort-provenance.mjs +23 -0
  3. package/advisor/citations.mjs +5 -1
  4. package/advisor/compaction.mjs +13 -10
  5. package/advisor/history.mjs +6 -1
  6. package/advisor/loop.mjs +35 -10
  7. package/advisor/messages.mjs +31 -43
  8. package/advisor/project-context.mjs +49 -45
  9. package/advisor/run.mjs +82 -26
  10. package/advisor.mjs +40 -11
  11. package/agent/assemble.mjs +5 -5
  12. package/agent/chat-call.mjs +21 -1
  13. package/agent/completion.mjs +1 -20
  14. package/agent/dispatch-gates.mjs +8 -3
  15. package/agent/dispatch-run.mjs +131 -20
  16. package/agent/dispatch.mjs +23 -22
  17. package/agent/family-tools.mjs +4 -7
  18. package/agent/goal-judge.mjs +99 -0
  19. package/agent/goal-state.mjs +96 -0
  20. package/agent/helpers.mjs +13 -4
  21. package/agent/offload.mjs +1 -1
  22. package/agent/planning-graph-guardrail.mjs +224 -0
  23. package/agent/planning-prompt.mjs +179 -0
  24. package/agent/planning-step.mjs +460 -173
  25. package/agent/post-turn.mjs +23 -33
  26. package/agent/record-results.mjs +8 -5
  27. package/agent/run-stages.mjs +22 -41
  28. package/agent/run-start.mjs +26 -19
  29. package/agent/setup-reminders.mjs +16 -14
  30. package/agent/setup.mjs +3 -2
  31. package/agent/spawn-child.mjs +17 -4
  32. package/agent/suspension.mjs +42 -21
  33. package/agent/task-lifecycle.mjs +165 -52
  34. package/agent/timers.mjs +9 -1
  35. package/agent/turn-loop.mjs +160 -69
  36. package/agent/turn-projection.mjs +26 -15
  37. package/agent/turn-task-state.mjs +4 -4
  38. package/agent/write-gate-ledger.mjs +1 -1
  39. package/agent/write-gate.mjs +14 -11
  40. package/agent-tools/advisor-async.mjs +2 -0
  41. package/agent-tools/advisor-launch.mjs +27 -13
  42. package/agent-tools/advisor-settle.mjs +19 -18
  43. package/agent-tools/advisor.mjs +90 -13
  44. package/agent-tools/bash-async.mjs +3 -3
  45. package/agent-tools/batch-ledger-bind.mjs +8 -5
  46. package/agent-tools/batch-read.mjs +42 -0
  47. package/agent-tools/batch-record-write.mjs +20 -12
  48. package/agent-tools/batch-segment-vocab.mjs +6 -4
  49. package/agent-tools/batch-skeleton.mjs +43 -12
  50. package/agent-tools/consult.mjs +5 -1
  51. package/agent-tools/context.mjs +5 -4
  52. package/agent-tools/design-slots.mjs +7 -4
  53. package/agent-tools/design-token.mjs +3 -2
  54. package/agent-tools/doc-graph.mjs +257 -95
  55. package/agent-tools/escalate-async.mjs +4 -1
  56. package/agent-tools/goal.mjs +28 -95
  57. package/agent-tools/plan.mjs +1 -1
  58. package/agent-tools/review-facts.mjs +56 -7
  59. package/agent-tools/settings.mjs +35 -1
  60. package/agent-tools/ssh-transport.mjs +23 -22
  61. package/agent-tools/step.mjs +24 -4
  62. package/agent-tools/subagent-actions.mjs +6 -2
  63. package/agent-tools/subagent-async.mjs +4 -2
  64. package/agent-tools/subagent.mjs +1 -1
  65. package/agent-tools/task.mjs +73 -65
  66. package/agent-tools.mjs +3 -3
  67. package/agent.mjs +12 -3
  68. package/auto-think.mjs +16 -3
  69. package/browser/actions.mjs +5 -1
  70. package/browser/cdp.mjs +1 -1
  71. package/browser/pool.mjs +110 -17
  72. package/compaction-work-state.mjs +103 -13
  73. package/compress-form.mjs +29 -3
  74. package/config-defaults.mjs +27 -3
  75. package/config-io.mjs +3 -14
  76. package/config-normalize.mjs +24 -4
  77. package/config-presets.mjs +40 -26
  78. package/config-warn.mjs +30 -0
  79. package/config.mjs +139 -63
  80. package/context-degrade.mjs +4 -4
  81. package/context-push.mjs +20 -9
  82. package/context.mjs +65 -20
  83. package/doc-graph/anchors.mjs +39 -40
  84. package/doc-graph/clusters.mjs +49 -0
  85. package/doc-graph/code-parsers.mjs +494 -0
  86. package/doc-graph/context-pack.mjs +392 -0
  87. package/doc-graph/dir-signals.mjs +228 -0
  88. package/doc-graph/edges.mjs +231 -0
  89. package/doc-graph/format.mjs +70 -0
  90. package/doc-graph/gc-cmd.mjs +104 -0
  91. package/doc-graph/gc.mjs +112 -0
  92. package/doc-graph/glob-work-graph.mjs +307 -0
  93. package/doc-graph/golden-set.mjs +131 -0
  94. package/doc-graph/ls-work-graph.mjs +534 -0
  95. package/doc-graph/outline.mjs +377 -0
  96. package/doc-graph/output-annotations.mjs +85 -0
  97. package/doc-graph/process-docs.mjs +68 -0
  98. package/doc-graph/read-work-graph.mjs +91 -0
  99. package/doc-graph/rebuild-cmd.mjs +75 -0
  100. package/doc-graph/resolvers.mjs +322 -0
  101. package/doc-graph/roots.mjs +86 -0
  102. package/doc-graph/schema.mjs +110 -0
  103. package/doc-graph/search-augment.mjs +418 -0
  104. package/doc-graph/store.mjs +231 -0
  105. package/doc-graph/target-resolve.mjs +352 -0
  106. package/doc-graph/walk.mjs +87 -0
  107. package/doc-graph.mjs +583 -707
  108. package/explore-distill.mjs +52 -17
  109. package/generate-title.mjs +7 -4
  110. package/ledger-close.mjs +6 -6
  111. package/ledger-cmd.mjs +3 -3
  112. package/ledger-consistency.mjs +8 -6
  113. package/ledger-db.mjs +45 -10
  114. package/ledger-migrate.mjs +25 -10
  115. package/ledger-read.mjs +1 -1
  116. package/ledger-write-ops.mjs +6 -6
  117. package/ledger.mjs +2 -2
  118. package/model-context.mjs +54 -18
  119. package/model-specs.mjs +86 -67
  120. package/package.json +1 -1
  121. package/prompt-overlays.mjs +3 -3
  122. package/prompts/advisor-round1.md +6 -5
  123. package/prompts/common.md +16 -6
  124. package/prompts/consult-base.md +2 -1
  125. package/prompts/discipline-engineering.md +1 -1
  126. package/prompts/discipline-normal.md +12 -8
  127. package/prompts/knowledge/doc-lookup.md +2 -2
  128. package/prompts/knowledge/normal-batch-discipline.md +2 -2
  129. package/prompts/knowledge/normal-delivery-collaboration.md +3 -3
  130. package/prompts/knowledge/tool-advisor.md +2 -2
  131. package/prompts/knowledge/tool-apply-patch.md +1 -1
  132. package/prompts/knowledge/tool-bash.md +2 -2
  133. package/prompts/knowledge/tool-batch.md +4 -4
  134. package/prompts/knowledge/tool-glob.md +9 -2
  135. package/prompts/knowledge/tool-goal.md +9 -6
  136. package/prompts/knowledge/tool-grep.md +7 -2
  137. package/prompts/knowledge/tool-ls.md +11 -5
  138. package/prompts/knowledge/tool-lsp.md +1 -1
  139. package/prompts/knowledge/tool-operations.md +3 -2
  140. package/prompts/knowledge/tool-plan.md +1 -1
  141. package/prompts/knowledge/tool-read.md +7 -6
  142. package/prompts/knowledge/tool-repo-graph-read.md +12 -0
  143. package/prompts/knowledge/tool-repo-graph.md +12 -0
  144. package/prompts/knowledge/tool-step.md +1 -1
  145. package/prompts/knowledge/tool-subagent.md +2 -2
  146. package/prompts/knowledge/tool-task.md +10 -9
  147. package/prompts/knowledge/tool-tree.md +7 -1
  148. package/prompts/persona-eng-coder.md +1 -1
  149. package/prompts/persona-eng-designer.md +1 -1
  150. package/prompts/persona-engineering.md +2 -1
  151. package/prompts/persona-explore.md +1 -1
  152. package/prompts/persona-normal.md +7 -6
  153. package/prompts/persona-plan.md +2 -2
  154. package/prompts/planning-next-moves.md +7 -8
  155. package/provider/anthropic.mjs +53 -51
  156. package/provider/core.mjs +85 -34
  157. package/provider/errors.mjs +33 -10
  158. package/provider/google.mjs +244 -37
  159. package/provider/list-models.mjs +28 -14
  160. package/provider/responses-request.mjs +15 -9
  161. package/provider/responses.mjs +10 -8
  162. package/provider/sse.mjs +3 -6
  163. package/proxy-transport.mjs +228 -119
  164. package/rules-file.mjs +79 -0
  165. package/rules.mjs +13 -51
  166. package/session-lifecycle.mjs +32 -20
  167. package/team-ledger.mjs +7 -7
  168. package/think-off.mjs +37 -18
  169. package/token-window.mjs +48 -31
  170. package/tool-args.mjs +8 -8
  171. package/tool-docs/bash.md +1 -1
  172. package/tool-docs/glob.md +3 -1
  173. package/tool-docs/goal.md +2 -2
  174. package/tool-docs/grep.md +3 -1
  175. package/tool-docs/ls.md +7 -1
  176. package/tool-docs/read.md +1 -1
  177. package/tool-docs/repo_graph-read.md +3 -0
  178. package/tool-docs/repo_graph.md +3 -0
  179. package/tool-docs/tree.md +1 -1
  180. package/tools/bash.mjs +53 -8
  181. package/tools/browser.mjs +4 -4
  182. package/tools/file.mjs +34 -7
  183. package/tools/glob-dialect.mjs +57 -7
  184. package/tools/index.mjs +3 -7
  185. package/tools/patch.mjs +8 -7
  186. package/tools/process-doc-mark.mjs +13 -0
  187. package/tools/search.mjs +152 -37
  188. package/tools/shared.mjs +6 -0
  189. package/tools/tree.mjs +211 -8
  190. package/window-policy.mjs +205 -126
  191. package/prompts/knowledge/tool-doc-graph-read.md +0 -20
  192. package/prompts/knowledge/tool-doc-graph.md +0 -49
  193. package/prompts/knowledge/tool-peek.md +0 -10
  194. package/prompts/knowledge/tool-repo-outline.md +0 -4
  195. package/tool-docs/doc_graph-read.md +0 -3
  196. package/tool-docs/doc_graph.md +0 -3
  197. package/tool-docs/peek.md +0 -3
  198. package/tool-docs/repo_outline.md +0 -3
  199. package/tools/peek.mjs +0 -447
package/tools/peek.mjs DELETED
@@ -1,447 +0,0 @@
1
- /**
2
- * tools/peek.mjs — Lightweight local batch structural inspection tool (`peek`).
3
- *
4
- * Pure local Node.js (~30–80ms, 0 LLM calls): extracts markdown outlines/sections
5
- * and code symbol outlines/definitions across multiple files so the main agent can
6
- * run fast Explore → Plan → Act → Verify micro-loops without spawning heavy
7
- * explore subagents just to scan file structure.
8
- */
9
- import { readFile, readdir, stat } from "node:fs/promises"
10
- import { extname, join, relative } from "node:path"
11
- import {
12
- DESC,
13
- truncate,
14
- resolveInCwd,
15
- splitGlobPatterns,
16
- compileGlobMatchers,
17
- normalizeEOL,
18
- } from "./shared.mjs"
19
- import { SKIP_DIRS } from "../skip-dirs.mjs"
20
- import { isProcessDocPath, docLayerName, processDocsReport } from "./process-doc-mark.mjs"
21
-
22
- const INCLUDE_PROCESS_DOCS_DESC =
23
- "Include process-layer docs (batch records, archived material) — omitted = excluded by default; true = include them"
24
-
25
- const DEFAULT_MAX_FILES = 30
26
- const HARD_MAX_FILES = 80
27
- const MAX_FILE_BYTES = 2_000_000
28
- const DEFAULT_PER_FILE_CHARS = 4500
29
-
30
- const MARKDOWN_EXTS = new Set([".md", ".mdx", ".markdown"])
31
- const PYTHON_EXTS = new Set([".py", ".pyi"])
32
- const CODE_EXTS = new Set([
33
- ".mjs", ".cjs", ".js", ".jsx", ".ts", ".tsx", ".mts", ".cts",
34
- ".py", ".pyi", ".cs", ".java", ".kt", ".go", ".rs", ".c", ".h", ".cpp", ".hpp",
35
- ".rb", ".php", ".sh", ".ps1",
36
- ])
37
-
38
- /** Walk directory recursively while skipping SKIP_DIRS and symlinks. */
39
- async function* walkFiles(dir, rel = "") {
40
- let entries
41
- try {
42
- entries = await readdir(dir, { withFileTypes: true })
43
- } catch {
44
- return
45
- }
46
- for (const e of entries) {
47
- if (e.isSymbolicLink()) continue
48
- if (e.isDirectory() && SKIP_DIRS.has(e.name)) continue
49
- const relPath = rel ? `${rel}/${e.name}` : e.name
50
- if (e.isDirectory()) yield* walkFiles(join(dir, e.name), relPath)
51
- else yield relPath
52
- }
53
- }
54
-
55
- /** Parse markdown heading blocks while ignoring headings inside fenced code blocks. */
56
- function parseMarkdownSections(lines) {
57
- const sections = []
58
- let fence = null
59
- for (let i = 0; i < lines.length; i++) {
60
- const line = lines[i]
61
- const fm = line.match(/^\s*(`{3,}|~{3,})/)
62
- if (fm) {
63
- if (!fence) fence = fm[1][0]
64
- else if (line.trimStart().startsWith(fence.repeat(3))) fence = null
65
- continue
66
- }
67
- if (fence) continue
68
- const hm = line.match(/^(#{1,4})\s+(.+?)\s*#*\s*$/)
69
- if (!hm) continue
70
- sections.push({ level: hm[1].length, title: hm[2].trim(), startIdx: i, endIdx: lines.length })
71
- }
72
- for (let i = 0; i < sections.length; i++) {
73
- sections[i].nextHeadingIdx = i + 1 < sections.length ? sections[i + 1].startIdx : lines.length
74
- let end = lines.length
75
- for (let j = i + 1; j < sections.length; j++) {
76
- if (sections[j].level <= sections[i].level) {
77
- end = sections[j].startIdx
78
- break
79
- }
80
- }
81
- sections[i].endIdx = end
82
- }
83
- return sections
84
- }
85
-
86
- /** Extract compact markdown outline: top note + H1–H4 tree with line counts and brief lead. */
87
- export function peekMarkdownOutline(content, { maxHeadings = 45 } = {}) {
88
- const lines = normalizeEOL(content).split("\n")
89
- const sections = parseMarkdownSections(lines)
90
- const out = []
91
-
92
- // Capture leading metadata / quote lines before first heading (or first 8 lines)
93
- const metaLimit = sections.length > 0 ? Math.min(sections[0].startIdx, 8) : Math.min(lines.length, 8)
94
- for (let i = 0; i < metaLimit; i++) {
95
- const t = lines[i].trim()
96
- if (t && (t.startsWith(">") || /^(status|状态|版本|aliases|owner|权威)/i.test(t))) {
97
- out.push(` ${t.slice(0, 140)}`)
98
- }
99
- }
100
-
101
- if (sections.length === 0) {
102
- const preview = lines.map((l) => l.trim()).filter(Boolean).slice(0, 4).join(" / ").slice(0, 220)
103
- out.push(` (${lines.length} lines, no headings)${preview ? ` — ${preview}` : ""}`)
104
- return out.join("\n")
105
- }
106
-
107
- const shown = sections.slice(0, maxHeadings)
108
- for (const s of shown) {
109
- const bodyStart = s.startIdx + 1
110
- const bodyEnd = s.nextHeadingIdx
111
- const spanLines = s.endIdx - s.startIdx
112
- let lead = ""
113
- let tableHeader = ""
114
- let inCode = false
115
- for (let i = bodyStart; i < bodyEnd; i++) {
116
- const t = lines[i].trim()
117
- if (!t) continue
118
- if (t.startsWith("```") || t.startsWith("~~~")) { inCode = !inCode; continue }
119
- if (inCode) continue
120
- if (!tableHeader && t.startsWith("|") && t.endsWith("|") && !/^\|[\s:-]+\|$/.test(t)) {
121
- tableHeader = t.replace(/^\||\|$/g, "").split("|").map((c) => c.trim()).filter(Boolean).slice(0, 6).join(" | ")
122
- continue
123
- }
124
- if (!lead && !t.startsWith("|") && !t.startsWith("---")) {
125
- lead = t.replace(/^[-*>\s]+/, "").slice(0, 100)
126
- }
127
- if (lead && tableHeader) break
128
- }
129
- const indent = " ".repeat(s.level - 1)
130
- const meta = [`${spanLines}L`]
131
- if (tableHeader) meta.push(`table: ${tableHeader}`)
132
- const suffix = lead ? ` — ${lead}` : ""
133
- out.push(`${indent}${"#".repeat(s.level)} ${s.title} (${meta.join("; ")})${suffix}`)
134
- }
135
- if (sections.length > maxHeadings) {
136
- out.push(` ... (+${sections.length - maxHeadings} more headings)`)
137
- }
138
- return out.join("\n")
139
- }
140
-
141
- /** Extract markdown sections matching query terms (case-insensitive substring match). */
142
- export function extractMarkdownSections(content, query, { maxChars = DEFAULT_PER_FILE_CHARS } = {}) {
143
- const terms = String(query ?? "").split(/[,|]/).map((s) => s.trim().toLowerCase()).filter(Boolean)
144
- if (terms.length === 0) return null
145
- const lines = normalizeEOL(content).split("\n")
146
- const sections = parseMarkdownSections(lines)
147
- const matched = []
148
- let coveredEnd = -1
149
- for (const s of sections) {
150
- const titleLc = s.title.toLowerCase()
151
- if (!terms.some((t) => titleLc.includes(t))) continue
152
- // Avoid duplicating child sections already included inside a matched parent section
153
- if (s.startIdx < coveredEnd) continue
154
- coveredEnd = s.endIdx
155
- const block = lines.slice(s.startIdx, s.endIdx).join("\n").trimEnd()
156
- matched.push(block)
157
- }
158
- if (matched.length === 0) return null
159
- const joined = matched.join("\n\n")
160
- return joined.length > maxChars ? `${joined.slice(0, maxChars)}\n... (truncated, ${joined.length} chars total)` : joined
161
- }
162
-
163
- const CODE_SYMBOL_PATTERNS = [
164
- // JS / TS exports and top-level declarations
165
- { re: /^(export\s+(?:default\s+)?(?:async\s+)?(?:function\*?|class|const|let|var|interface|type|enum)\s+([A-Za-z_$][\w$]*).*)/, nameIdx: 2 },
166
- { re: /^((?:async\s+)?function\*?\s+([A-Za-z_$][\w$]*)\s*\(.*)/, nameIdx: 2 },
167
- { re: /^(class\s+([A-Za-z_$][\w$]*).*)/, nameIdx: 2 },
168
- // Python
169
- { re: /^((?:async\s+)?def\s+([A-Za-z_]\w*)\s*\(.*)/, nameIdx: 2 },
170
- // Go
171
- { re: /^(func\s+(?:\([^)]+\)\s*)?([A-Za-z_]\w*)\s*\(.*)/, nameIdx: 2 },
172
- { re: /^(type\s+([A-Za-z_]\w*)\s+(?:struct|interface)\b.*)/, nameIdx: 2 },
173
- // Rust
174
- { re: /^((?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?(?:fn|struct|enum|trait|type)\s+([A-Za-z_]\w*).*)/, nameIdx: 2 },
175
- // C# / Java
176
- { re: /^(\s*(?:public|internal|protected|private)\s+(?:static\s+|abstract\s+|sealed\s+|partial\s+|async\s+|virtual\s+|override\s+)*(?:class|interface|record|struct|enum|[\w<>[\]?.,\s]+)\s+([A-Za-z_]\w*)\s*(?:\(|[:{<]|$).*)/, nameIdx: 2 },
177
- ]
178
-
179
- function scanCodeSymbols(lines) {
180
- const found = []
181
- for (let i = 0; i < lines.length; i++) {
182
- const line = lines[i]
183
- if (!line.trim() || /^\s*(\/\/|\/\*|\*|#)/.test(line)) continue
184
- for (const { re, nameIdx } of CODE_SYMBOL_PATTERNS) {
185
- const m = line.match(re)
186
- if (m) {
187
- const sig = m[1].trim().replace(/\s*\{\s*$/, "").slice(0, 120)
188
- found.push({ name: m[nameIdx], lineIdx: i, signature: sig })
189
- break
190
- }
191
- }
192
- }
193
- return found
194
- }
195
-
196
- /** Extract compact code outline: leading comment + exported/top-level declarations. */
197
- export function peekCodeOutline(content, ext = ".mjs", { maxSymbols = 50 } = {}) {
198
- const lines = normalizeEOL(content).split("\n")
199
- const out = []
200
-
201
- // First meaningful header comment line
202
- for (let i = 0; i < Math.min(lines.length, 12); i++) {
203
- const t = lines[i].trim()
204
- if (!t || t === "/**" || t === "/*" || t === "*/") continue
205
- if (t.startsWith("//") || t.startsWith("*") || t.startsWith("#!")) {
206
- const cleaned = t.replace(/^(\/\/|\*|#!)\s*/, "").trim()
207
- if (cleaned && !cleaned.startsWith("/usr/bin/env")) {
208
- out.push(` // ${cleaned.slice(0, 140)}`)
209
- break
210
- }
211
- } else {
212
- break
213
- }
214
- }
215
-
216
- const symbols = scanCodeSymbols(lines)
217
- if (symbols.length === 0) {
218
- out.push(` (${lines.length} lines, no top-level symbols matched)`)
219
- return out.join("\n")
220
- }
221
- for (const s of symbols.slice(0, maxSymbols)) {
222
- out.push(` L${s.lineIdx + 1}: ${s.signature}`)
223
- }
224
- if (symbols.length > maxSymbols) {
225
- out.push(` ... (+${symbols.length - maxSymbols} more symbols)`)
226
- }
227
- return out.join("\n")
228
- }
229
-
230
- /** Extract definition bodies for matching code symbols. */
231
- export function extractCodeSymbols(content, query, ext = ".mjs", { maxChars = DEFAULT_PER_FILE_CHARS, maxLinesPerSymbol = 80 } = {}) {
232
- const terms = String(query ?? "").split(/[,|\s]+/).map((s) => s.trim().toLowerCase()).filter(Boolean)
233
- if (terms.length === 0) return null
234
- const lines = normalizeEOL(content).split("\n")
235
- const symbols = scanCodeSymbols(lines)
236
- const isPy = PYTHON_EXTS.has(ext.toLowerCase())
237
- const blocks = []
238
-
239
- for (const s of symbols) {
240
- const nameLc = s.name.toLowerCase()
241
- if (!terms.some((t) => nameLc === t || nameLc.includes(t))) continue
242
- const start = s.lineIdx
243
- let end = Math.min(lines.length, start + maxLinesPerSymbol)
244
-
245
- if (isPy) {
246
- const baseIndent = (lines[start].match(/^(\s*)/)?.[1] ?? "").length
247
- for (let i = start + 1; i < end; i++) {
248
- const l = lines[i]
249
- if (!l.trim()) continue
250
- const ind = (l.match(/^(\s*)/)?.[1] ?? "").length
251
- if (ind <= baseIndent) { end = i; break }
252
- }
253
- } else {
254
- let depth = 0
255
- let opened = false
256
- for (let i = start; i < end; i++) {
257
- for (const ch of lines[i]) {
258
- if (ch === "{") { depth++; opened = true }
259
- else if (ch === "}") { depth-- }
260
- }
261
- if (opened && depth <= 0) { end = i + 1; break }
262
- if (!opened && i > start && /;\s*$/.test(lines[i - 1])) { end = i; break }
263
- }
264
- }
265
-
266
- const body = lines.slice(start, end).map((l, idx) => `${start + idx + 1}\t${l}`).join("\n")
267
- blocks.push(body)
268
- }
269
-
270
- if (blocks.length === 0) return null
271
- const joined = blocks.join("\n---\n")
272
- return joined.length > maxChars ? `${joined.slice(0, maxChars)}\n... (truncated, ${joined.length} chars total)` : joined
273
- }
274
-
275
- /** Pure single-file dispatcher shared by peekTool and eval sandboxes. */
276
- export function peekContent(relPath, content, { mode = "outline", query = "", maxChars = DEFAULT_PER_FILE_CHARS } = {}) {
277
- const ext = extname(relPath).toLowerCase()
278
- const isMd = MARKDOWN_EXTS.has(ext)
279
- if (mode === "sections") {
280
- if (!isMd) return null
281
- return extractMarkdownSections(content, query, { maxChars })
282
- }
283
- if (mode === "symbols") {
284
- if (isMd) return extractMarkdownSections(content, query, { maxChars })
285
- return extractCodeSymbols(content, query, ext, { maxChars })
286
- }
287
- if (isMd) return peekMarkdownOutline(content)
288
- if (CODE_EXTS.has(ext)) return peekCodeOutline(content, ext)
289
- const lines = normalizeEOL(content).split("\n")
290
- const head = lines.slice(0, 6).map((l) => ` ${l.slice(0, 120)}`).join("\n")
291
- return ` (${lines.length} lines)\n${head}`
292
- }
293
-
294
- async function collectTargets(args, ctx) {
295
- const includeProcessDocs = args.includeProcessDocs === true
296
- const maxFiles = Math.max(1, Math.min(Number(args.maxFiles) || DEFAULT_MAX_FILES, HARD_MAX_FILES))
297
- const procCache = new Map()
298
- const targets = []
299
- const seen = new Set()
300
- let excluded = 0
301
-
302
- const addFile = (abs, display, explicit = false) => {
303
- const key = process.platform === "win32" ? abs.toLowerCase() : abs
304
- if (seen.has(key)) return
305
- if (!explicit && !includeProcessDocs && isProcessDocPath(abs, procCache)) {
306
- excluded += 1
307
- return
308
- }
309
- seen.add(key)
310
- targets.push({ abs, display })
311
- }
312
-
313
- if (Array.isArray(args.paths) && args.paths.length > 0) {
314
- for (const p of args.paths) {
315
- if (targets.length >= maxFiles) break
316
- const abs = resolveInCwd(ctx, p)
317
- const st = await stat(abs).catch(() => null)
318
- if (!st) continue
319
- if (st.isDirectory()) {
320
- for await (const rel of walkFiles(abs)) {
321
- if (targets.length >= maxFiles) break
322
- addFile(join(abs, rel), relative(ctx.cwd, join(abs, rel)).replace(/\\/g, "/"), false)
323
- }
324
- } else if (st.isFile()) {
325
- addFile(abs, relative(ctx.cwd, abs).replace(/\\/g, "/") || p, true)
326
- }
327
- }
328
- }
329
-
330
- if (args.glob) {
331
- const base = resolveInCwd(ctx, args.path ?? ".")
332
- const st = await stat(base).catch(() => null)
333
- if (!st) return { error: `peek error: path not found: ${base}` }
334
- const parts = splitGlobPatterns(args.glob)
335
- if (parts.length === 0) return { error: "peek error: invalid glob pattern" }
336
- let match
337
- try {
338
- match = compileGlobMatchers(parts).test
339
- } catch (e) {
340
- return { error: `peek error: invalid glob "${args.glob}": ${e.message}` }
341
- }
342
- for await (const rel of walkFiles(base)) {
343
- if (targets.length >= maxFiles) break
344
- if (!match(rel)) continue
345
- const abs = join(base, rel)
346
- addFile(abs, relative(ctx.cwd, abs).replace(/\\/g, "/") || rel, false)
347
- }
348
- } else if ((!args.paths || args.paths.length === 0) && args.path) {
349
- const abs = resolveInCwd(ctx, args.path)
350
- const st = await stat(abs).catch(() => null)
351
- if (!st) return { error: `peek error: path not found: ${abs}` }
352
- if (st.isFile()) {
353
- addFile(abs, relative(ctx.cwd, abs).replace(/\\/g, "/") || args.path, true)
354
- } else if (st.isDirectory()) {
355
- for await (const rel of walkFiles(abs)) {
356
- if (targets.length >= maxFiles) break
357
- addFile(join(abs, rel), relative(ctx.cwd, join(abs, rel)).replace(/\\/g, "/"), false)
358
- }
359
- }
360
- }
361
-
362
- return { targets, excluded, includeProcessDocs, maxFiles }
363
- }
364
-
365
- export const peekTool = {
366
- name: "peek",
367
- description: DESC("peek"),
368
- parameters: {
369
- type: "object",
370
- properties: {
371
- paths: {
372
- type: "array",
373
- items: { type: "string" },
374
- description: "Explicit file or directory paths to inspect.",
375
- },
376
- glob: {
377
- type: "string",
378
- description: "Glob pattern for batch inspection (supports **, {a,b}, and space-separated !exclude).",
379
- },
380
- path: {
381
- type: "string",
382
- description: "Single file or base directory for glob (defaults to cwd).",
383
- },
384
- mode: {
385
- type: "string",
386
- enum: ["outline", "sections", "symbols"],
387
- description: "Inspection shape: defaults to structural summary; pick heading extraction for markdown bodies or definition extraction for code.",
388
- },
389
- query: {
390
- type: "string",
391
- description: "Comma-separated heading keywords (section mode) or symbol names (symbol mode). Required outside outline mode.",
392
- },
393
- maxFiles: {
394
- type: "integer",
395
- description: `Max files to inspect in one call (default ${DEFAULT_MAX_FILES}, cap ${HARD_MAX_FILES}).`,
396
- },
397
- includeProcessDocs: {
398
- type: "boolean",
399
- description: INCLUDE_PROCESS_DOCS_DESC,
400
- },
401
- },
402
- },
403
- readonly: true,
404
- async execute(args, ctx) {
405
- const mode = args.mode || "outline"
406
- if (mode !== "outline" && !String(args.query ?? "").trim()) {
407
- return `peek error: query is required when mode="${mode}".`
408
- }
409
- if (!args.glob && !args.path && (!Array.isArray(args.paths) || args.paths.length === 0)) {
410
- return "peek error: provide paths, glob, or path."
411
- }
412
-
413
- const collected = await collectTargets(args, ctx)
414
- if (collected.error) return collected.error
415
- const { targets, excluded, includeProcessDocs, maxFiles } = collected
416
- if (targets.length === 0) {
417
- return excluded > 0
418
- ? `(no matching files)\n${processDocsReport(excluded, includeProcessDocs)}`
419
- : "(no matching files)"
420
- }
421
-
422
- const layerCache = new Map()
423
- const blocks = []
424
- let matchedCount = 0
425
- for (const { abs, display } of targets) {
426
- const st = await stat(abs).catch(() => null)
427
- if (!st || !st.isFile()) continue
428
- if (st.size > MAX_FILE_BYTES) {
429
- blocks.push(`=== [${docLayerName(abs, layerCache)}] ${display} ===\n (skipped: ${Math.round(st.size / 1024)}KB > limit)`)
430
- continue
431
- }
432
- const raw = await readFile(abs, "utf8").catch(() => null)
433
- if (raw === null) continue
434
- const piece = peekContent(display, raw, { mode, query: args.query ?? "" })
435
- if (!piece) continue
436
- matchedCount += 1
437
- blocks.push(`=== [${docLayerName(abs, layerCache)}] ${display} ===\n${piece}`)
438
- }
439
-
440
- const header = `peek(${mode}): scanned ${targets.length} file(s)` +
441
- (mode !== "outline" ? `, ${matchedCount} matched "${args.query}"` : "") +
442
- (targets.length >= maxFiles ? ` (capped at maxFiles=${maxFiles})` : "")
443
- const body = blocks.length > 0 ? `${header}\n\n${blocks.join("\n\n")}` : `${header}\n(no matches)`
444
- const suffix = excluded > 0 ? `\n${processDocsReport(excluded, includeProcessDocs)}` : ""
445
- return truncate(body + suffix)
446
- },
447
- }