@thincoder/core 0.11.3 → 0.11.5

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 (183) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/advisor/compaction.mjs +40 -17
  3. package/advisor/loop.mjs +14 -6
  4. package/advisor/notice.mjs +1 -1
  5. package/advisor/timeline.mjs +4 -4
  6. package/agent/completion.mjs +19 -0
  7. package/agent/dispatch-gates.mjs +2 -0
  8. package/agent/dispatch.mjs +2 -2
  9. package/agent/family-tools.mjs +13 -9
  10. package/agent/helpers.mjs +10 -6
  11. package/agent/planning-step.mjs +453 -0
  12. package/agent/post-turn.mjs +70 -2
  13. package/agent/run-stages.mjs +22 -50
  14. package/agent/run-start.mjs +17 -0
  15. package/agent/setup-reminders.mjs +71 -8
  16. package/agent/setup.mjs +8 -39
  17. package/agent/spawn-child.mjs +6 -2
  18. package/agent/task-lifecycle.mjs +146 -0
  19. package/agent/turn-loop.mjs +73 -11
  20. package/agent-tools/batch-closeout.mjs +21 -34
  21. package/agent-tools/batch-gate.mjs +7 -5
  22. package/agent-tools/batch-ledger-bind.mjs +21 -1
  23. package/agent-tools/batch-lifecycle.mjs +7 -7
  24. package/agent-tools/batch-record-write.mjs +237 -280
  25. package/agent-tools/batch-supersede.mjs +3 -3
  26. package/agent-tools/batch.mjs +42 -9
  27. package/agent-tools/context.mjs +0 -13
  28. package/agent-tools/escalate-async.mjs +7 -1
  29. package/agent-tools/parent-channel.mjs +7 -6
  30. package/agent-tools/plan.mjs +103 -67
  31. package/agent-tools/review-facts.mjs +3 -3
  32. package/agent-tools/settings.mjs +2 -0
  33. package/agent-tools/spawn-gates.mjs +37 -11
  34. package/agent-tools/ssh-session.mjs +68 -25
  35. package/agent-tools/ssh-transfer.mjs +7 -2
  36. package/agent-tools/ssh-transport.mjs +2 -2
  37. package/agent-tools/ssh-vault.mjs +2 -2
  38. package/agent-tools/step.mjs +462 -0
  39. package/agent-tools/subagent-actions.mjs +6 -1
  40. package/agent-tools/subagent-run.mjs +7 -0
  41. package/agent-tools/subagent-spawn.mjs +1 -1
  42. package/agent-tools/subagent.mjs +17 -11
  43. package/agent-tools/task.mjs +178 -26
  44. package/agent-tools.mjs +1 -0
  45. package/agent.mjs +2 -0
  46. package/config-defaults.mjs +17 -1
  47. package/config-migrate.mjs +8 -5
  48. package/config.mjs +7 -0
  49. package/context.mjs +5 -4
  50. package/declaration.mjs +4 -4
  51. package/generate-title.mjs +0 -6
  52. package/i18n.mjs +4 -0
  53. package/ledger-cmd.mjs +11 -1
  54. package/ledger-tools.mjs +15 -4
  55. package/manifest-schema.mjs +1 -0
  56. package/model-context.mjs +34 -11
  57. package/model-specs.mjs +5 -2
  58. package/package.json +1 -1
  59. package/prompt-files.mjs +48 -11
  60. package/prompt-overlays.mjs +79 -8
  61. package/prompts/advisor-design.md +253 -206
  62. package/prompts/advisor-round1.md +151 -145
  63. package/prompts/advisor-round2.md +136 -130
  64. package/prompts/advisor-round3.md +140 -134
  65. package/prompts/common.md +244 -96
  66. package/prompts/consult-base.md +29 -30
  67. package/prompts/discipline-engineering.md +73 -519
  68. package/prompts/discipline-normal.md +28 -136
  69. package/prompts/knowledge/batch-before-write.md +8 -0
  70. package/prompts/knowledge/batch-cycle-register.md +15 -0
  71. package/prompts/knowledge/batch-progress-ledger.md +29 -0
  72. package/prompts/knowledge/business-gates.md +24 -24
  73. package/prompts/knowledge/decision-quality.md +8 -19
  74. package/prompts/knowledge/doc-discipline-d-rules.md +63 -0
  75. package/prompts/knowledge/doc-lookup.md +25 -24
  76. package/prompts/knowledge/document-writing.md +11 -32
  77. package/prompts/knowledge/documentation-evaluation.md +42 -42
  78. package/prompts/knowledge/eng-dispatch-ops.md +34 -0
  79. package/prompts/knowledge/eng-ledger-ops.md +26 -0
  80. package/prompts/knowledge/evidence-discipline.md +10 -32
  81. package/prompts/knowledge/normal-batch-discipline.md +13 -0
  82. package/prompts/knowledge/normal-coding-workflow.md +97 -99
  83. package/prompts/knowledge/normal-delivery-collaboration.md +107 -112
  84. package/prompts/knowledge/normal-work-management.md +44 -44
  85. package/prompts/knowledge/product-security.md +7 -26
  86. package/prompts/knowledge/project-records.md +69 -64
  87. package/prompts/knowledge/tool-advisor.md +17 -17
  88. package/prompts/knowledge/tool-apply-patch.md +14 -14
  89. package/prompts/knowledge/tool-bash.md +32 -31
  90. package/prompts/knowledge/tool-batch-eng-coder.md +19 -13
  91. package/prompts/knowledge/tool-batch-eng-designer.md +21 -14
  92. package/prompts/knowledge/tool-batch-review.md +18 -12
  93. package/prompts/knowledge/tool-batch.md +93 -85
  94. package/prompts/knowledge/tool-browser.md +59 -59
  95. package/prompts/knowledge/tool-code-search.md +2 -2
  96. package/prompts/knowledge/tool-consult-start.md +6 -6
  97. package/prompts/knowledge/tool-consult-stop.md +3 -3
  98. package/prompts/knowledge/tool-context.md +4 -4
  99. package/prompts/knowledge/tool-delete.md +16 -16
  100. package/prompts/knowledge/tool-doc-check.md +39 -39
  101. package/prompts/knowledge/tool-doc-graph-read.md +11 -11
  102. package/prompts/knowledge/tool-doc-graph.md +48 -48
  103. package/prompts/knowledge/tool-doc-search.md +3 -3
  104. package/prompts/knowledge/tool-edit.md +30 -30
  105. package/prompts/knowledge/tool-eng.md +1 -1
  106. package/prompts/knowledge/tool-execute.md +16 -16
  107. package/prompts/knowledge/tool-fetch.md +15 -15
  108. package/prompts/knowledge/tool-file-ops.md +15 -15
  109. package/prompts/knowledge/tool-get-current-time.md +3 -3
  110. package/prompts/knowledge/tool-git-read.md +15 -15
  111. package/prompts/knowledge/tool-git.md +26 -26
  112. package/prompts/knowledge/tool-glob.md +14 -14
  113. package/prompts/knowledge/tool-goal.md +5 -5
  114. package/prompts/knowledge/tool-grep.md +19 -18
  115. package/prompts/knowledge/tool-hashline-edit.md +13 -13
  116. package/prompts/knowledge/tool-insert-after.md +14 -14
  117. package/prompts/knowledge/tool-instance-list.md +3 -3
  118. package/prompts/knowledge/tool-instance-send.md +5 -5
  119. package/prompts/knowledge/tool-knowledge.md +12 -12
  120. package/prompts/knowledge/tool-ledger-read.md +20 -20
  121. package/prompts/knowledge/tool-ledger.md +44 -44
  122. package/prompts/knowledge/tool-lint.md +10 -10
  123. package/prompts/knowledge/tool-ls.md +11 -11
  124. package/prompts/knowledge/tool-lsp.md +8 -8
  125. package/prompts/knowledge/tool-main-history.md +1 -1
  126. package/prompts/knowledge/tool-manifest-read.md +7 -7
  127. package/prompts/knowledge/tool-manifest.md +43 -32
  128. package/prompts/knowledge/tool-memory-read.md +12 -12
  129. package/prompts/knowledge/tool-memory.md +14 -14
  130. package/prompts/knowledge/tool-notify-parent.md +10 -10
  131. package/prompts/knowledge/tool-operations.md +88 -88
  132. package/prompts/knowledge/tool-peek.md +10 -0
  133. package/prompts/knowledge/tool-peer-instances.md +1 -1
  134. package/prompts/knowledge/tool-plan.md +6 -3
  135. package/prompts/knowledge/tool-process-read.md +8 -8
  136. package/prompts/knowledge/tool-process.md +11 -11
  137. package/prompts/knowledge/tool-question.md +11 -13
  138. package/prompts/knowledge/tool-read-history-batch.md +13 -13
  139. package/prompts/knowledge/tool-read-history.md +19 -19
  140. package/prompts/knowledge/tool-read-image.md +8 -8
  141. package/prompts/knowledge/tool-read.md +17 -17
  142. package/prompts/knowledge/tool-recent-changes.md +4 -4
  143. package/prompts/knowledge/tool-repo-outline.md +2 -2
  144. package/prompts/knowledge/tool-settings-read.md +5 -7
  145. package/prompts/knowledge/tool-settings.md +10 -10
  146. package/prompts/knowledge/tool-skill.md +4 -4
  147. package/prompts/knowledge/tool-ssh.md +66 -66
  148. package/prompts/knowledge/tool-step.md +26 -0
  149. package/prompts/knowledge/tool-subagent.md +52 -50
  150. package/prompts/knowledge/tool-task.md +14 -11
  151. package/prompts/knowledge/tool-team-ledger-read.md +7 -7
  152. package/prompts/knowledge/tool-team-ledger.md +13 -13
  153. package/prompts/knowledge/tool-timer.md +14 -14
  154. package/prompts/knowledge/tool-tree.md +11 -11
  155. package/prompts/knowledge/tool-verify.md +11 -11
  156. package/prompts/knowledge/tool-wait-for.md +20 -20
  157. package/prompts/knowledge/tool-websearch.md +16 -14
  158. package/prompts/knowledge/tool-write.md +10 -10
  159. package/prompts/knowledge/upstream-protocol.md +37 -38
  160. package/prompts/persona-coder.md +22 -22
  161. package/prompts/persona-eng-coder.md +87 -81
  162. package/prompts/persona-eng-designer.md +173 -153
  163. package/prompts/persona-engineering.md +53 -554
  164. package/prompts/persona-explore.md +18 -15
  165. package/prompts/persona-normal.md +62 -63
  166. package/prompts/persona-plan.md +36 -32
  167. package/prompts/persona-tester.md +39 -39
  168. package/prompts/planning-next-moves.md +9 -0
  169. package/prompts/subagent-base.md +4 -16
  170. package/provider/errors.mjs +0 -24
  171. package/provider/list-models.mjs +20 -2
  172. package/session-lifecycle.mjs +4 -3
  173. package/tool-args.mjs +25 -0
  174. package/tool-docs/peek.md +3 -0
  175. package/tool-docs/plan.md +1 -1
  176. package/tool-docs/question.md +1 -1
  177. package/tool-docs/step.md +3 -0
  178. package/tools/edit-diff.mjs +4 -4
  179. package/tools/index.mjs +3 -2
  180. package/tools/peek.mjs +447 -0
  181. package/tools/question.mjs +87 -9
  182. package/tools/ssh.mjs +1 -1
  183. package/window-policy.mjs +107 -80
@@ -307,12 +307,12 @@ export function computeEditEntry(content, entry, opts = {}) {
307
307
  }
308
308
  throw new Error(
309
309
  `old_string not found in ${opts.path ?? "file"}\n` +
310
- ` searched: "${preview}${entry.old_string.length > 100 ? "…" : ""}" — use grep to locate the actual content\n` +
310
+ ` searched: "${preview}${entry.old_string.length > 100 ? "…" : ""}" — read the file to copy the exact bytes; grep only locates path and line\n` +
311
311
  (opts.absPath && lastWriteOf(opts.absPath)?.type === "write"
312
- ? ` hints: this file was modified since your last read (write 全文重写后内容全变) — re-read it to refresh your copy of the content, then retry\n`
312
+ ? ` hints: this file was modified since your last read (write 全文重写后内容全变) — re-read it to refresh your copy of the content, then retry edit (do not use shell commands to write files)\n`
313
313
  : opts.absPath && isDirty(opts.absPath)
314
- ? ` hints: this file was modified since your last read (a prior write marked it dirty) — re-read it to refresh your copy of the content, then retry\n`
315
- : ` hints: whitespace mismatch? file already changed? try reading the file first\n`) +
314
+ ? ` hints: this file was modified since your last read (a prior write marked it dirty) — re-read it to refresh your copy of the content, then retry edit (do not use shell commands to write files)\n`
315
+ : ` hints: whitespace mismatch? file already changed? re-read the file and retry edit (do not use shell commands to write files)\n`) +
316
316
  candText
317
317
  )
318
318
  }
package/tools/index.mjs CHANGED
@@ -13,6 +13,7 @@ import { lspTool } from "./lsp.mjs";
13
13
  import { executeTool } from "./execute.mjs";
14
14
  import { fileOpsTool, processTool, getCurrentTimeTool, waitForTool } from "./ops.mjs";
15
15
  import { treeTool } from "./tree.mjs";
16
+ import { peekTool } from "./peek.mjs";
16
17
  import { browserTool } from "./browser.mjs";
17
18
  import { sshTool } from "./ssh.mjs";
18
19
 
@@ -25,7 +26,7 @@ export const builtinTools = [
25
26
  gitTool, questionTool,
26
27
  lintTool, lspTool, executeTool,
27
28
  fileOpsTool, processTool, getCurrentTimeTool, waitForTool,
28
- treeTool,
29
+ treeTool, peekTool,
29
30
  browserTool,
30
31
  sshTool,
31
32
  ];
@@ -37,7 +38,7 @@ export {
37
38
  gitTool, questionTool,
38
39
  lintTool, lspTool, executeTool,
39
40
  fileOpsTool, processTool, getCurrentTimeTool, waitForTool,
40
- treeTool,
41
+ treeTool, peekTool,
41
42
  browserTool,
42
43
  sshTool,
43
44
  };
package/tools/peek.mjs ADDED
@@ -0,0 +1,447 @@
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
+ }
@@ -1,26 +1,104 @@
1
1
  import { DESC } from "./shared.mjs";
2
2
 
3
+ export const MAX_QUESTION_CHARS = 100;
4
+ export const MAX_OPTIONS_PER_QUESTION = 4;
5
+ export const MAX_QUESTIONS_PER_BATCH = 4;
6
+
7
+ function optionText(opt) {
8
+ if (typeof opt === "string") return opt.trim();
9
+ if (opt && typeof opt === "object") {
10
+ const raw = opt.label ?? opt.text ?? opt.title ?? "";
11
+ return typeof raw === "string" ? raw.trim() : String(raw).trim();
12
+ }
13
+ return opt == null ? "" : String(opt).trim();
14
+ }
15
+
16
+ /** 格式化多题表单作答结果为模型与人类均易读的 Q&A 文本。 */
17
+ export function formatMultiQuestionAnswers(items, answers) {
18
+ return items.map((it, i) => {
19
+ const raw = answers?.[i];
20
+ const ans = typeof raw === "string" && raw.trim() ? raw.trim() : "(skipped)";
21
+ return `${i + 1}. ${it.question}\n → ${ans}`;
22
+ }).join("\n");
23
+ }
24
+
3
25
  export const questionTool = {
4
26
  name: "question",
5
27
  description: DESC("question"),
6
28
  parameters: {
7
29
  type: "object",
8
30
  properties: {
9
- question: { type: "string", description: "The question to ask the user" },
31
+ question: {
32
+ type: "string",
33
+ description: "Single short question to ask the user (<=100 chars). Omit when using `questions`.",
34
+ },
10
35
  options: {
11
36
  type: "array",
12
37
  items: { type: "string" },
13
- description: "Single-choice options for the user to pick from (optional)",
38
+ description: "Single-choice options for `question` (optional, max 4 plain strings; user can always type a custom answer)",
39
+ },
40
+ questions: {
41
+ type: "array",
42
+ description: "Optional batch of 1-4 independent short questions rendered together in one form card. Each item supports optional preset options and always allows a custom free-text answer.",
43
+ items: {
44
+ type: "object",
45
+ properties: {
46
+ question: { type: "string", description: "Short question text (<=100 chars)" },
47
+ options: {
48
+ type: "array",
49
+ items: { type: "string" },
50
+ description: "Optional preset single-choice options (max 4 plain strings; user can always type a custom answer)",
51
+ },
52
+ },
53
+ required: ["question"],
54
+ },
14
55
  },
15
56
  },
16
- required: ["question"],
17
57
  },
18
58
  readonly: true,
19
- async execute(args, ctx) {
20
- if (!ctx.onQuestion) throw new Error("question tool not supported in this context (no UI to ask)")
59
+ async execute(args = {}, ctx = {}) {
60
+ if (!ctx.onQuestion) throw new Error("question tool not supported in this context (no UI to ask)");
61
+ if (Array.isArray(args.questions)) {
62
+ if (args.questions.length === 0) {
63
+ return "(error: questions array must not be empty)";
64
+ }
65
+ if (args.questions.length > MAX_QUESTIONS_PER_BATCH) {
66
+ return `(error: too many questions (>${MAX_QUESTIONS_PER_BATCH}) — ask at most ${MAX_QUESTIONS_PER_BATCH} short questions in one card)`;
67
+ }
68
+ const items = [];
69
+ for (let i = 0; i < args.questions.length; i++) {
70
+ const entry = args.questions[i];
71
+ const qText = typeof entry?.question === "string" ? entry.question.trim() : "";
72
+ if (!qText) {
73
+ return `(error: question #${i + 1} is missing a non-empty question string)`;
74
+ }
75
+ if (qText.length > MAX_QUESTION_CHARS) {
76
+ return `(error: question #${i + 1} too long (>${MAX_QUESTION_CHARS} chars) — keep each question short; background belongs in your normal reply text)`;
77
+ }
78
+ if (Array.isArray(entry.options) && entry.options.length > MAX_OPTIONS_PER_QUESTION) {
79
+ return `(error: question #${i + 1} has too many options (>${MAX_OPTIONS_PER_QUESTION}) — offer at most ${MAX_OPTIONS_PER_QUESTION} plain-string options)`;
80
+ }
81
+ const opts = Array.isArray(entry.options) ? entry.options.map(optionText).filter(Boolean) : [];
82
+ items.push({ question: qText, options: opts });
83
+ }
84
+ if (items.length === 1) {
85
+ return ctx.onQuestion(items[0].question, items[0].options);
86
+ }
87
+ const summary = items.map((it, i) => `${i + 1}. ${it.question}`).join("\n");
88
+ return ctx.onQuestion(summary, [], { questions: items });
89
+ }
90
+
91
+ const qText = typeof args.question === "string" ? args.question : "";
92
+ if (!qText.trim()) {
93
+ return "(error: provide either a non-empty question string or a questions array)";
94
+ }
21
95
  // §22 D-Q3 机械限制(2026-09-06 用户裁定:100 字符 / 4 条——超限拒绝回模型,不弹卡、不调 onQuestion)
22
- if (args.question.length > 100) return "(error: question too long (>100 chars) — ask ONE short question; background belongs in your normal reply text)"
23
- if (Array.isArray(args.options) && args.options.length > 4) return "(error: too many options (>4) — offer at most 4 plain-string options)"
24
- return ctx.onQuestion(args.question, args.options ?? [])
96
+ if (qText.length > MAX_QUESTION_CHARS) {
97
+ return "(error: question too long (>100 chars) — ask ONE short question; background belongs in your normal reply text)";
98
+ }
99
+ if (Array.isArray(args.options) && args.options.length > MAX_OPTIONS_PER_QUESTION) {
100
+ return "(error: too many options (>4) — offer at most 4 plain-string options)";
101
+ }
102
+ return ctx.onQuestion(qText, Array.isArray(args.options) ? args.options : []);
25
103
  },
26
- }
104
+ };
package/tools/ssh.mjs CHANGED
@@ -9,7 +9,7 @@
9
9
  *
10
10
  * 失败回执**返回**(不 throw)——首行 `Error: …` = 模型面失败形(`bash` / `browser` 既例);
11
11
  * 无 UI 考(缺 `ctx.onSecretInput` 回调)⇒ 机制档抛可读错(`question.mjs` 无 UI 抛例同旨)。
12
- * 会话跨调用存活于池(非本档持有);depth>0 排除(`agent/helpers.mjs` `SUBAGENT_TOOL_EXCLUSIONS`)。
12
+ * 会话跨调用存活于池(非本档持有);depth>0 **提供**——子代理自建池,结清时由 `discardSshSessions` 排空(`agent/helpers.mjs` `SUBAGENT_TOOL_EXCLUSIONS` 只剩 `question`)。
13
13
  * 动态 import(W8 契约②:agent-tools 静态链达 node:sqlite——端壳静态闭包须保持零命中)。
14
14
  */
15
15
  import { DESC, LEDGER_PARAM_DESC } from "./shared.mjs"