minicode-ai 0.9.26

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 (162) hide show
  1. package/CHANGELOG.md +935 -0
  2. package/LICENSE +21 -0
  3. package/README.md +200 -0
  4. package/cli/args.ts +195 -0
  5. package/cli/auto-update.ts +108 -0
  6. package/cli/commands/auth.ts +166 -0
  7. package/cli/commands/config.ts +382 -0
  8. package/cli/commands/doctor.ts +128 -0
  9. package/cli/commands/exec.ts +179 -0
  10. package/cli/commands/mcp.ts +35 -0
  11. package/cli/commands/memory.ts +107 -0
  12. package/cli/commands/pricing.ts +100 -0
  13. package/cli/commands/providers.ts +162 -0
  14. package/cli/commands/sessions.ts +128 -0
  15. package/cli/commands/skills.ts +61 -0
  16. package/cli/commands/stats.ts +82 -0
  17. package/cli/commands.ts +317 -0
  18. package/cli/index.ts +539 -0
  19. package/cli/model-manager.ts +112 -0
  20. package/cli/provider-manager.ts +111 -0
  21. package/cli/repl.ts +734 -0
  22. package/cli/router.ts +124 -0
  23. package/cli/setup.ts +780 -0
  24. package/cli/wizard.ts +21 -0
  25. package/docs/ARCHITECTURE.html +1222 -0
  26. package/docs/README.md +109 -0
  27. package/docs/architecture.md +44 -0
  28. package/docs/changelog.md +3 -0
  29. package/package.json +91 -0
  30. package/src/agents/pool.ts +43 -0
  31. package/src/app/mentions.ts +50 -0
  32. package/src/app/provider-layer.ts +118 -0
  33. package/src/app/rag-layer.ts +105 -0
  34. package/src/app/session.ts +154 -0
  35. package/src/app/tool-layer.ts +56 -0
  36. package/src/config.ts +372 -0
  37. package/src/constants.ts +119 -0
  38. package/src/hooks/run.ts +89 -0
  39. package/src/lib/atomic-write.ts +88 -0
  40. package/src/lib/db-path.ts +36 -0
  41. package/src/lib/git-hardening.ts +91 -0
  42. package/src/lib/ignore.ts +58 -0
  43. package/src/lib/keystore.ts +202 -0
  44. package/src/lib/net.ts +70 -0
  45. package/src/lib/safe-open.ts +138 -0
  46. package/src/lib/session-id.ts +23 -0
  47. package/src/lib/trash.ts +38 -0
  48. package/src/lib/trusted-exec.ts +81 -0
  49. package/src/lsp/client.ts +395 -0
  50. package/src/mcp/client.ts +400 -0
  51. package/src/mcp/http-transport.ts +344 -0
  52. package/src/mcp/server.ts +538 -0
  53. package/src/mcp/transport.ts +150 -0
  54. package/src/memory/files.ts +159 -0
  55. package/src/memory/vector.ts +775 -0
  56. package/src/policy/allowlist.ts +67 -0
  57. package/src/policy/bash-guard.ts +465 -0
  58. package/src/policy/compaction.ts +271 -0
  59. package/src/policy/context.ts +161 -0
  60. package/src/policy/executor.ts +199 -0
  61. package/src/policy/jail.ts +127 -0
  62. package/src/policy/permission.ts +517 -0
  63. package/src/policy/pricing.ts +336 -0
  64. package/src/policy/ratelimit.ts +54 -0
  65. package/src/policy/sandbox-policy.ts +157 -0
  66. package/src/policy/scrub.ts +138 -0
  67. package/src/policy/update-check.ts +200 -0
  68. package/src/policy/usage.ts +292 -0
  69. package/src/policy/verifier.ts +181 -0
  70. package/src/providers/anthropic.ts +401 -0
  71. package/src/providers/auth-store.ts +139 -0
  72. package/src/providers/build.ts +136 -0
  73. package/src/providers/detect.ts +126 -0
  74. package/src/providers/effort.ts +165 -0
  75. package/src/providers/guards.ts +107 -0
  76. package/src/providers/oauth.ts +326 -0
  77. package/src/providers/presets.ts +122 -0
  78. package/src/providers/provision.ts +298 -0
  79. package/src/providers/responses.ts +371 -0
  80. package/src/providers/router.ts +247 -0
  81. package/src/repo/repomap.ts +470 -0
  82. package/src/sandbox/docker.ts +129 -0
  83. package/src/sandbox/os.ts +193 -0
  84. package/src/session/checkpoint.ts +543 -0
  85. package/src/session/journal.ts +1347 -0
  86. package/src/session/persistence.ts +446 -0
  87. package/src/session/shadow-git.ts +351 -0
  88. package/src/session/turn-marker.ts +118 -0
  89. package/src/skills/loader.ts +117 -0
  90. package/src/telemetry/trace.ts +283 -0
  91. package/src/tools/ask_user.ts +54 -0
  92. package/src/tools/bash.ts +400 -0
  93. package/src/tools/code_run.ts +96 -0
  94. package/src/tools/delete_file.ts +31 -0
  95. package/src/tools/edit.ts +204 -0
  96. package/src/tools/git.ts +301 -0
  97. package/src/tools/glob.ts +90 -0
  98. package/src/tools/grep.ts +281 -0
  99. package/src/tools/hashline.ts +66 -0
  100. package/src/tools/index.ts +103 -0
  101. package/src/tools/lsp.ts +346 -0
  102. package/src/tools/mcp_call.ts +163 -0
  103. package/src/tools/memory.ts +144 -0
  104. package/src/tools/move_file.ts +47 -0
  105. package/src/tools/patch.ts +86 -0
  106. package/src/tools/read_file.ts +130 -0
  107. package/src/tools/read_image.ts +80 -0
  108. package/src/tools/submit_result.ts +49 -0
  109. package/src/tools/task.ts +346 -0
  110. package/src/tools/todo.ts +201 -0
  111. package/src/tools/web_fetch.ts +161 -0
  112. package/src/tools/web_search.ts +156 -0
  113. package/src/tools/write_file.ts +42 -0
  114. package/src/ui/approval/prompt.ts +76 -0
  115. package/src/ui/assistant/simple.ts +568 -0
  116. package/src/ui/assistant/turn-status.ts +303 -0
  117. package/src/ui/contract.ts +55 -0
  118. package/src/ui/footer.ts +105 -0
  119. package/src/ui/input/input.ts +805 -0
  120. package/src/ui/input/prompt-engine.ts +606 -0
  121. package/src/ui/render/collapse.ts +84 -0
  122. package/src/ui/render/detail.ts +24 -0
  123. package/src/ui/render/diff.ts +181 -0
  124. package/src/ui/render/errors.ts +239 -0
  125. package/src/ui/render/format.ts +54 -0
  126. package/src/ui/render/highlight.ts +294 -0
  127. package/src/ui/render/markdown.ts +120 -0
  128. package/src/ui/render/money.ts +12 -0
  129. package/src/ui/render/reasoning.ts +20 -0
  130. package/src/ui/render/sanitize.ts +80 -0
  131. package/src/ui/render/table.ts +88 -0
  132. package/src/ui/render/theme.ts +339 -0
  133. package/src/ui/render/width.ts +256 -0
  134. package/src/ui/render/wrap.ts +120 -0
  135. package/src/ui/runtime/bus-debug.ts +83 -0
  136. package/src/ui/runtime/chrome.ts +301 -0
  137. package/src/ui/runtime/spinner.ts +77 -0
  138. package/src/ui/runtime/statusline.ts +227 -0
  139. package/src/ui/screens/model-manager.ts +434 -0
  140. package/src/ui/screens/overlay.ts +61 -0
  141. package/src/ui/screens/picker.ts +307 -0
  142. package/src/ui/screens/provider-manager.ts +450 -0
  143. package/src/ui/screens/wizard.ts +132 -0
  144. package/vendor/minicore/VENDOR.md +29 -0
  145. package/vendor/minicore/package.json +21 -0
  146. package/vendor/minicore/src/core/budget.ts +26 -0
  147. package/vendor/minicore/src/core/compact.ts +76 -0
  148. package/vendor/minicore/src/core/errors.ts +60 -0
  149. package/vendor/minicore/src/core/events.ts +74 -0
  150. package/vendor/minicore/src/core/executor.ts +139 -0
  151. package/vendor/minicore/src/core/history.ts +32 -0
  152. package/vendor/minicore/src/core/index.ts +42 -0
  153. package/vendor/minicore/src/core/loop.ts +344 -0
  154. package/vendor/minicore/src/core/permission.ts +24 -0
  155. package/vendor/minicore/src/core/provider.ts +39 -0
  156. package/vendor/minicore/src/core/recovery.ts +34 -0
  157. package/vendor/minicore/src/core/session.ts +327 -0
  158. package/vendor/minicore/src/core/snapshot.ts +142 -0
  159. package/vendor/minicore/src/core/tokens.ts +111 -0
  160. package/vendor/minicore/src/core/tool.ts +118 -0
  161. package/vendor/minicore/src/core/types.ts +50 -0
  162. package/vendor/minicore/src/providers/openai-compat.ts +366 -0
@@ -0,0 +1,204 @@
1
+ import type { Tool } from "#minicore"
2
+ import { LIMITS } from "../constants.ts"
3
+ import { atomicWriteText } from "../lib/atomic-write.ts"
4
+ import { assertSafeWriteTarget, resolveSafePath, safeReadFile } from "../lib/safe-open.ts"
5
+ import { appendLspDiagnostics } from "../policy/verifier.ts"
6
+ import { applyHashline } from "./hashline.ts"
7
+
8
+ function normalizeLf(s: string): string {
9
+ return s.replace(/\r\n/g, "\n")
10
+ }
11
+
12
+ function stripTrailingWhitespace(s: string): string {
13
+ return s
14
+ .split("\n")
15
+ .map((l) => l.trimEnd())
16
+ .join("\n")
17
+ }
18
+
19
+ // Petakan index di string ternormalisasi (LF) kembali ke index string asli.
20
+ function mapOriginalIndex(original: string, nIdx: number): number {
21
+ let oi = 0,
22
+ ni = 0
23
+ while (ni < nIdx && oi < original.length) {
24
+ if (original[oi] === "\r" && original[oi + 1] === "\n")
25
+ oi += 2 // \r\n = 1 unit LF
26
+ else oi += 1
27
+ ni += 1
28
+ }
29
+ return oi
30
+ }
31
+
32
+ export interface MatchResult {
33
+ start: number
34
+ end: number
35
+ mode: "exact" | "crlf" | "trimmed" | "fuzzy"
36
+ }
37
+
38
+ // Helper: hitung range byte di cLf dari indeks baris — dipakai trimmed & fuzzy
39
+ function lineRange(
40
+ cLfLines: string[],
41
+ startLine: number,
42
+ lineCount: number,
43
+ content: string,
44
+ ): { start: number; end: number } {
45
+ const startInLf = cLfLines.slice(0, startLine).join("\n").length + (startLine > 0 ? 1 : 0)
46
+ const endInLf = startInLf + cLfLines.slice(startLine, startLine + lineCount).join("\n").length
47
+ return { start: mapOriginalIndex(content, startInLf), end: mapOriginalIndex(content, endInLf) }
48
+ }
49
+
50
+ // Search needle dengan toleransi bertingkat:
51
+ // 1. Exact match
52
+ // 2. CRLF vs LF match
53
+ // 3. Trimmed trailing whitespace line match
54
+ // 4. Line-by-line normalized whitespace match
55
+ export function flexibleMatch(content: string, needle: string): MatchResult | null {
56
+ // 1. Exact match
57
+ const direct = content.indexOf(needle)
58
+ if (direct !== -1) return { start: direct, end: direct + needle.length, mode: "exact" }
59
+
60
+ const cLf = normalizeLf(content)
61
+ const nLf = normalizeLf(needle)
62
+
63
+ // 2. CRLF vs LF match
64
+ const nStart = cLf.indexOf(nLf)
65
+ if (nStart !== -1)
66
+ return {
67
+ start: mapOriginalIndex(content, nStart),
68
+ end: mapOriginalIndex(content, nStart + nLf.length),
69
+ mode: "crlf",
70
+ }
71
+
72
+ const cLfLines = cLf.split("\n")
73
+ // 3. Trailing whitespace tolerance
74
+ const cTrimmed = stripTrailingWhitespace(cLf)
75
+ const nTrimmed = stripTrailingWhitespace(nLf)
76
+ const trimStart = cTrimmed.indexOf(nTrimmed)
77
+ if (trimStart !== -1) {
78
+ const lineCountBefore = cTrimmed.slice(0, trimStart).split("\n").length - 1
79
+ const needleLineCount = nTrimmed.split("\n").length
80
+ if (lineCountBefore + needleLineCount <= cLfLines.length) {
81
+ const r = lineRange(cLfLines, lineCountBefore, needleLineCount, content)
82
+ return { ...r, mode: "trimmed" }
83
+ }
84
+ }
85
+
86
+ // 4. Fuzzy line-by-line match (ignoring leading/trailing whitespace per line)
87
+ const cLines = cLfLines
88
+ const nLines = nLf.split("\n")
89
+ if (nLines.length > 0 && nLines.length <= cLines.length) {
90
+ const nStripped = nLines.map((l) => l.trim())
91
+ let matchLineIdx = -1
92
+ for (let i = 0; i <= cLines.length - nLines.length; i++) {
93
+ let ok = true
94
+ for (let j = 0; j < nLines.length; j++)
95
+ if (cLines[i + j]?.trim() !== nStripped[j]) {
96
+ ok = false
97
+ break
98
+ }
99
+ if (ok) {
100
+ if (matchLineIdx !== -1) return null // ambiguous
101
+ matchLineIdx = i
102
+ }
103
+ }
104
+ if (matchLineIdx !== -1) {
105
+ const r = lineRange(cLfLines, matchLineIdx, nLines.length, content)
106
+ return { ...r, mode: "fuzzy" }
107
+ }
108
+ }
109
+ return null
110
+ }
111
+
112
+ export const editTool: Tool = {
113
+ name: "edit",
114
+ description:
115
+ "Edit a file with a string replacement. oldString must appear exactly once in the file — include surrounding lines to make it unique. Whitespace/indentation mismatch is tolerated (fuzzy). Prefer edit for small targeted changes; use apply_patch for multiple changes. Cannot edit files outside the workspace or .minicode/ state.",
116
+ parameters: {
117
+ type: "object",
118
+ properties: {
119
+ path: { type: "string", description: "path relative to the workspace (e.g. src/a.ts)" },
120
+ oldString: {
121
+ type: "string",
122
+ description: "exact existing text to be replaced (must match once)",
123
+ },
124
+ newString: {
125
+ type: "string",
126
+ description: "replacement text (empty string deletes the matched text)",
127
+ },
128
+ },
129
+ required: ["path", "oldString", "newString"],
130
+ additionalProperties: false,
131
+ },
132
+ async execute({ path, oldString, newString }, ctx) {
133
+ ctx.signal.throwIfAborted()
134
+ const p = path as string
135
+ const root = (ctx as { cwd?: string }).cwd ?? process.cwd()
136
+ // Verifikasi path terpusat (logis + target nyata, induk symlink ikut
137
+ // ter-resolusi) — symlink internal tetap bisa diedit, targetnya yang dicek.
138
+ const { abs, real: realAbs } = await resolveSafePath(p, root)
139
+ // Tolak menimpa symlink final (swap antara cek dan tulis gagal tutup).
140
+ await assertSafeWriteTarget(abs, root)
141
+ // Cek ukuran sebelum baca penuh — hindari OOM 1GB via safeReadFile.
142
+ // Pakai byte length via stat pada realAbs (handle belum ada), fallback ke content length.
143
+ const { stat } = await import("node:fs/promises")
144
+ const st = await stat(realAbs).catch(() => null)
145
+ if (!st) throw new Error(`file not found: ${p}`)
146
+ if (st.size > LIMITS.READ_FILE_MAX_BYTES) throw new Error(`file too large: ${p} (${st.size})`)
147
+ // Baca via safeReadFile (O_NOFOLLOW) agar TOCTOU swap gagal ELOOP, bukan baca luar.
148
+ const content = await safeReadFile(abs, root).catch(() => {
149
+ throw new Error(`file not found: ${p}`)
150
+ })
151
+ const oldS = oldString as string
152
+ const newS = newString as string
153
+ if (oldS === newS) throw new Error("oldString == newString (no change)")
154
+ // Hashline fast path (OpenCode): hanya bila line endings konsisten (hindari CRLF→LF corrupt)
155
+ // CRLF vs LF ditangani oleh flexibleMatch mode "crlf" yang preservasi original.
156
+ const canHashline = content.includes("\r\n") === oldS.includes("\r\n")
157
+ let hashApply: string | null = null
158
+ if (canHashline) {
159
+ const hunk = applyHashline(content, oldS, newS)
160
+ if (hunk !== null) {
161
+ // uniqueness: if exact oldString occurs >1 times, require more context (mirror flexibleMatch)
162
+ const firstIdx = content.indexOf(oldS)
163
+ if (firstIdx !== -1 && content.indexOf(oldS, firstIdx + oldS.length) !== -1) {
164
+ throw new Error(
165
+ `oldString found multiple times in ${p} — provide more surrounding lines to make it unique`,
166
+ )
167
+ }
168
+ hashApply = hunk
169
+ }
170
+ }
171
+ if (hashApply !== null) {
172
+ if (hashApply.length > LIMITS.WRITE_FILE_MAX_CHARS)
173
+ throw new Error(`result too large: ${hashApply.length} chars (max 5M)`)
174
+ await atomicWriteText(realAbs, hashApply)
175
+ return await appendLspDiagnostics(
176
+ realAbs,
177
+ hashApply,
178
+ `edited ${realAbs} (hashline match) (${oldS.length} → ${newS.length} chars)`,
179
+ undefined,
180
+ root,
181
+ )
182
+ }
183
+ const match = flexibleMatch(content, oldS)
184
+ if (!match) throw new Error(`oldString not found in ${p}`)
185
+
186
+ // ensure uniqueness untuk semua mode (exact/crlf/trimmed/fuzzy) — trimmed/fuzzy
187
+ // sebelumnya hanya dicek untuk exact/crlf sehingga duplikat diam-diam edit blok pertama
188
+ const second = flexibleMatch(content.slice(match.end), oldS)
189
+ if (second) {
190
+ throw new Error(
191
+ `oldString found multiple times in ${p} — provide more surrounding lines to make it unique`,
192
+ )
193
+ }
194
+
195
+ const next = content.slice(0, match.start) + newS + content.slice(match.end)
196
+ if (next.length > LIMITS.WRITE_FILE_MAX_CHARS)
197
+ throw new Error(`result too large: ${next.length} chars (max 5M)`)
198
+ // atomic (O_EXCL + randomUUID tmp)
199
+ await atomicWriteText(realAbs, next)
200
+ const note = match.mode !== "exact" ? ` (${match.mode} match)` : ""
201
+ const base = `edited ${realAbs}${note} (${oldS.length} → ${newS.length} chars)`
202
+ return await appendLspDiagnostics(realAbs, next, base, undefined, root)
203
+ },
204
+ }
@@ -0,0 +1,301 @@
1
+ import { spawn } from "node:child_process"
2
+ import { resolve } from "node:path"
3
+ import type { Tool } from "#minicore"
4
+ import { LIMITS } from "../constants.ts"
5
+ import {
6
+ discoverFilterDrivers,
7
+ GIT_NO_DIFF_DRIVERS,
8
+ GIT_SAFE_BASE,
9
+ gitFilterNeutralizers,
10
+ } from "../lib/git-hardening.ts"
11
+ import { resolveTrustedExecutable } from "../lib/trusted-exec.ts"
12
+ import { isCwdOutsideRoot, isPathOutsideRoot } from "../policy/jail.ts"
13
+ import { sanitizeSpawnEnv, scrubSecrets } from "../policy/scrub.ts"
14
+
15
+ function runGit(args: string[], cwd: string | undefined, signal: AbortSignal): Promise<string> {
16
+ return new Promise((resolve, reject) => {
17
+ // Audit #10 P0: SEMUA pemanggilan git lewat sini membawa netralisasi
18
+ // repo-controlled execution (hooks/fsmonitor/pager via GIT_SAFE_BASE).
19
+ // Executable di-resolve absolut dari PATH terpercaya karena Windows
20
+ // mencari CWD lebih dulu: `git.bat` di repo akan dieksekusi tanpa ini.
21
+ const p = spawn(resolveTrustedExecutable("git"), [...GIT_SAFE_BASE, ...args], {
22
+ cwd,
23
+ // Repo hooks (pre-commit/commit-msg/...) berjalan sebagai child dengan
24
+ // env ini — kredensial (API_KEY/TOKEN/...) di-strip agar hook nakal tak
25
+ // bisa memanen secret dari env. Auth tetap via credential helper / agen
26
+ // SSH (SSH_AUTH_SOCK bukan pola secret) — lihat policy/scrub.ts.
27
+ env: sanitizeSpawnEnv(process.env),
28
+ // Timeout dari LIMITS, bukan hardcode: `git_commit` menjalankan beberapa
29
+ // operasi berurutan (rev-parse → add → commit → log), dan di mesin yang
30
+ // sibuk (mis. CI menjalankan test dengan coverage) spawn git bisa jauh
31
+ // lebih lambat dari batas 8s yang dulu dipakai — kegagalannya muncul
32
+ // sebagai flake, bukan bug nyata.
33
+ signal: AbortSignal.any([signal, AbortSignal.timeout(LIMITS.GIT_TIMEOUT_MS)]),
34
+ })
35
+ // F-15: cap SAAT streaming (bukan slice di akhir): `git diff`/`git log`
36
+ // di repo raksasa bisa ratusan MB — buffer tak terbatas = OOM sebelum
37
+ // truncate kernel sempat jalan. Satu-satunya tool tanpa cap sebelumnya.
38
+ const cap = LIMITS.GIT_OUTPUT_MAX_CHARS
39
+ let out = "",
40
+ err = "",
41
+ truncated = false
42
+ const push = (cur: string, d: Buffer): string => {
43
+ if (cur.length >= cap) {
44
+ truncated = true
45
+ return cur
46
+ }
47
+ const room = cap - cur.length
48
+ const s = d.toString()
49
+ if (s.length > room) truncated = true
50
+ return cur + s.slice(0, Math.max(0, room))
51
+ }
52
+ p.stdout.on("data", (d) => (out = push(out, d)))
53
+ p.stderr.on("data", (d) => (err = push(err, d)))
54
+ p.on("error", reject)
55
+ p.on("close", (code) => {
56
+ const text = scrubSecrets((out + (err ? `\n${err}` : "")).trim())
57
+ const marked = truncated ? `${text}\n… [git output truncated]` : text
58
+ if (code !== 0 && !marked) reject(new Error(`git ${args.join(" ")} exit ${code}`))
59
+ else resolve(marked || `(exit ${code})`)
60
+ })
61
+ signal.addEventListener("abort", () => p.kill("SIGTERM"), { once: true })
62
+ })
63
+ }
64
+
65
+ /** cwd tool harus di dalam workspace — sama seperti bash/glob/grep. */
66
+ function assertCwd(cwd: string | undefined, sessionRoot: string): void {
67
+ if (!cwd) return
68
+ const abs = resolve(sessionRoot, cwd)
69
+ if (isCwdOutsideRoot(abs, sessionRoot) || isPathOutsideRoot(abs, sessionRoot)) {
70
+ throw new Error(`cwd outside workspace: ${cwd}`)
71
+ }
72
+ }
73
+
74
+ async function isGitRepo(cwd: string, signal: AbortSignal): Promise<boolean> {
75
+ try {
76
+ const out = await runGit(["rev-parse", "--is-inside-work-tree"], cwd, signal)
77
+ return out.trim() === "true"
78
+ } catch {
79
+ return false
80
+ }
81
+ }
82
+
83
+ export const gitStatusTool: Tool = {
84
+ name: "git_status",
85
+ description:
86
+ "git status --porcelain + diff --stat + log --oneline -10 (hardened: ignores repository hooks, filters and diff drivers — prefer over raw `git` in bash)",
87
+ parameters: {
88
+ type: "object",
89
+ properties: { cwd: { type: "string" } },
90
+ required: [],
91
+ additionalProperties: false,
92
+ },
93
+ async execute({ cwd }, ctx) {
94
+ const c = cwd as string | undefined
95
+ const sessionRoot = (ctx as { cwd?: string }).cwd ?? process.cwd()
96
+ assertCwd(c, sessionRoot)
97
+ const resolvedCwd = c ? resolve(sessionRoot, c) : sessionRoot
98
+ if (!(await isGitRepo(resolvedCwd, ctx.signal))) return "not a git repository"
99
+ // Audit #10 P0: `git diff` menjalankan clean filter pada berkas dirty
100
+ // (banding konten worktree vs index) — netralkan seperti shadow ops.
101
+ // Efek samping: repo dengan filter konversi legitim (mis. LFS) bisa
102
+ // menampilkan phantom diff; itu display-only dan aman.
103
+ const neutral = await gitFilterNeutralizers(resolvedCwd)
104
+ // Audit #13 chain 6: `git status --porcelain` pun menerapkan clean filter
105
+ // untuk entri racy (file baru diubah vs index) — tanpa neutral, review
106
+ // status di repo jahat mengeksekusi perintah repo (reproducer:
107
+ // PWNED-clean.txt muncul dari git_status). Neutral ikut ke status.
108
+ const [a, b, d] = await Promise.all([
109
+ runGit([...neutral, "status", "--porcelain"], resolvedCwd, ctx.signal),
110
+ // Pasangan -c WAJIB sebelum subcommand "diff" (runGit menaruh BASE di
111
+ // depan; neutral di sini tepat setelahnya). Tanpa ini driver konten
112
+ // repo ikut jalan saat diff membandingkan worktree.
113
+ runGit([...neutral, "diff", ...GIT_NO_DIFF_DRIVERS, "--stat"], resolvedCwd, ctx.signal),
114
+ runGit(["log", "--oneline", "-10"], resolvedCwd, ctx.signal),
115
+ ])
116
+ return `status:\n${a || "(clean)"}\n\ndiff --stat:\n${b || "(no diff)"}\n\nlog -10:\n${d || "(no log)"}`
117
+ },
118
+ }
119
+
120
+ export const gitDiffTool: Tool = {
121
+ name: "git_diff",
122
+ description:
123
+ "git diff (unstaged) or git diff --staged (hardened: ignores repository hooks, filters and diff drivers — prefer over raw `git diff` in bash)",
124
+ parameters: {
125
+ type: "object",
126
+ properties: {
127
+ cwd: { type: "string" },
128
+ staged: { type: "boolean", description: "true = --staged" },
129
+ },
130
+ required: [],
131
+ additionalProperties: false,
132
+ },
133
+ async execute({ cwd, staged }, ctx) {
134
+ const sessionRoot = (ctx as { cwd?: string }).cwd ?? process.cwd()
135
+ assertCwd(cwd as string | undefined, sessionRoot)
136
+ const resolvedCwd = (cwd as string | undefined)
137
+ ? resolve(sessionRoot, cwd as string)
138
+ : sessionRoot
139
+ if (!(await isGitRepo(resolvedCwd, ctx.signal))) return "not a git repository"
140
+ // Netralisasi clean seperti git_status (lihat di atas): diff full-content
141
+ // lebih-lebih memicu filter. -c sebelum subcommand.
142
+ const neutral = await gitFilterNeutralizers(resolvedCwd)
143
+ const args = staged
144
+ ? [...neutral, "diff", ...GIT_NO_DIFF_DRIVERS, "--staged"]
145
+ : [...neutral, "diff", ...GIT_NO_DIFF_DRIVERS]
146
+ return await runGit(args, resolvedCwd, ctx.signal)
147
+ },
148
+ }
149
+
150
+ export const gitLogTool: Tool = {
151
+ name: "git_log",
152
+ description: "git log --oneline -n (hardened: ignores repository hooks and pager)",
153
+ parameters: {
154
+ type: "object",
155
+ properties: {
156
+ cwd: { type: "string" },
157
+ limit: { type: "number", description: "number of commits, default 20" },
158
+ },
159
+ required: [],
160
+ additionalProperties: false,
161
+ },
162
+ async execute({ cwd, limit }, ctx) {
163
+ const sessionRoot = (ctx as { cwd?: string }).cwd ?? process.cwd()
164
+ assertCwd(cwd as string | undefined, sessionRoot)
165
+ const resolvedCwd = (cwd as string | undefined)
166
+ ? resolve(sessionRoot, cwd as string)
167
+ : sessionRoot
168
+ if (!(await isGitRepo(resolvedCwd, ctx.signal))) return "not a git repository"
169
+ const n = String(Math.min(Math.max((limit as number) ?? 20, 1), 100))
170
+ return await runGit(["log", "--oneline", `-${n}`], resolvedCwd, ctx.signal)
171
+ },
172
+ }
173
+
174
+ // ── Tool tulis ──
175
+ //
176
+ // `git_commit` di-GATE di permission layer (setara `delegate_task`/`mcp_call`):
177
+ // commit mengubah riwayat yang dibagikan, jadi butuh persetujuan sekali per
178
+ // pemakaian di mode `auto`, dan ditolak di `readonly`/`plan`/`allowlist`.
179
+ //
180
+ // Yang SENGAJA tidak disediakan: `push`, `reset --hard`, `rebase`, `checkout`,
181
+ // `branch -D`, `stash drop`, dan amend. Semuanya sulit dibalikkan atau
182
+ // mempengaruhi remote/repo orang lain — agent tidak perlu itu untuk
183
+ // menyelesaikan task, dan menyediakannya memindahkan risiko besar ke tangan
184
+ // yang tidak bisa menilai konteksnya.
185
+
186
+ /** Nama file di argumen `paths` harus di dalam workspace. */
187
+ function assertPaths(paths: unknown, cwd: string | undefined, sessionRoot: string): string[] {
188
+ if (paths == null) return []
189
+ if (!Array.isArray(paths)) throw new Error("paths must be an array of strings")
190
+ const root = cwd ? resolve(sessionRoot, cwd) : sessionRoot
191
+ const out: string[] = []
192
+ for (const p of paths) {
193
+ if (typeof p !== "string" || !p.trim()) continue
194
+ if (isPathOutsideRoot(p, root)) throw new Error(`path outside workspace: ${p}`)
195
+ out.push(p)
196
+ }
197
+ return out
198
+ }
199
+
200
+ export const gitCommitTool: Tool = {
201
+ name: "git_commit",
202
+ description:
203
+ "Create a git commit. Stage specific paths (paths) or all tracked changes (all:true). Does not support push/amend/reset — that is beyond the agent's authority. Never runs repository hooks (--no-verify + isolated hooks path), unlike terminal git commit.",
204
+ parameters: {
205
+ type: "object",
206
+ properties: {
207
+ message: { type: "string", description: "commit message (first line = subject)" },
208
+ paths: {
209
+ type: "array",
210
+ items: { type: "string" },
211
+ description: "files to stage; leave empty when using all",
212
+ },
213
+ all: {
214
+ type: "boolean",
215
+ description: "stage all files ALREADY tracked by git (equivalent to git commit -a)",
216
+ },
217
+ cwd: { type: "string" },
218
+ },
219
+ required: ["message"],
220
+ additionalProperties: false,
221
+ },
222
+ async execute({ message, paths, all, cwd }, ctx) {
223
+ ctx.signal.throwIfAborted()
224
+ const c = cwd as string | undefined
225
+ const sessionRoot = (ctx as { cwd?: string }).cwd ?? process.cwd()
226
+ assertCwd(c, sessionRoot)
227
+ const resolvedCwd = c ? resolve(sessionRoot, c) : sessionRoot
228
+ const msg = String(message ?? "").trim()
229
+ if (!msg) throw new Error("message is required")
230
+ if (msg.length > 4000) throw new Error("message terlalu panjang (max 4000 char)")
231
+
232
+ const files = assertPaths(paths, c, sessionRoot)
233
+ if (files.length === 0 && all !== true) {
234
+ throw new Error(
235
+ "provide `paths` (specific files) or `all: true` — an empty commit is useless",
236
+ )
237
+ }
238
+
239
+ // Repo check dulu supaya errornya jelas, bukan "exit 128".
240
+ const inside = await runGit(
241
+ ["rev-parse", "--is-inside-work-tree"],
242
+ resolvedCwd,
243
+ ctx.signal,
244
+ ).catch(() => "")
245
+ if (!inside.startsWith("true")) throw new Error("not a git repository (git rev-parse failed)")
246
+
247
+ if (files.length > 0) {
248
+ // `--` memisahkan path dari opsi: nama file bernama `-f` tak jadi flag.
249
+ await runGit(["add", "--", ...files], resolvedCwd, ctx.signal)
250
+ }
251
+ // F-04: clean/smudge TIDAK dinetralkan di add/commit — semantik clean
252
+ // milik user (LFS), lihat git-hardening.ts. Sebagai gantinya, staging yang
253
+ // melewati filter repo yang DITEMUKAN dilaporkan eksplisit di hasil (bukan
254
+ // diam-diam): approval gate permission + peringatan ini adalah kontrolnya.
255
+ // Berlaku untuk paths MAUPUN all:true (`commit -a` juga menjalankan clean).
256
+ let filterWarning = ""
257
+ try {
258
+ const drivers = await discoverFilterDrivers(resolvedCwd)
259
+ if (drivers.length > 0) {
260
+ const names = drivers.map((d) => `filter.${d.name}`).join(", ")
261
+ filterWarning =
262
+ `\n\n[warn] repo defines custom git filters (${names}) that ran during staging — ` +
263
+ `review .gitattributes/.git/config in untrusted repos before committing.`
264
+ }
265
+ } catch {}
266
+
267
+ // `-m` dengan pesan sebagai satu argumen: tak ada shell yang menginterpretasi
268
+ // isinya, jadi backtick/`$()` di pesan commit tidak dieksekusi.
269
+ // Audit #10 P0: `--no-verify` mematikan pre-commit/commit-msg repo;
270
+ // post-commit (+ override hooksPath repo) dimatikan GIT_SAFE_BASE di
271
+ // runGit. Commit agen tak pernah menjalankan kode repo — bedakan dari
272
+ // `git commit` terminal yang menjalankan hooks.
273
+ const args = ["commit", "--no-verify", "-m", msg]
274
+ if (files.length === 0 && all === true) args.push("-a")
275
+
276
+ const out = await runGit(args, resolvedCwd, ctx.signal)
277
+ // `git commit` keluar non-zero saat tak ada perubahan; runGit sudah
278
+ // meneruskan teksnya, jadi model membaca alasan sebenarnya.
279
+ if (/nothing to commit|no changes added/i.test(out)) {
280
+ // Audit #08 P1 (retry setelah sukses-yang-responsnya-hilang): tree
281
+ // bersih + subjek HEAD sama dengan pesan yang diminta = commit pertama
282
+ // sudah durable. Kembalikan SHA-nya (tanpa commit baru) agar pemanggil
283
+ // tak mengira tak ada yang ter-commit. Beda subjek = kondisi orang
284
+ // lain yang commit duluan → perilaku lama (tanpa klaim palsu).
285
+ try {
286
+ const subject = (
287
+ await runGit(["log", "-1", "--format=%s"], resolvedCwd, ctx.signal).catch(() => "")
288
+ ).trim()
289
+ if (subject && subject === msg.split("\n")[0]?.trim()) {
290
+ const head = await runGit(["log", "--oneline", "-1"], resolvedCwd, ctx.signal).catch(
291
+ () => "",
292
+ )
293
+ return `already committed (retry aman — tanpa commit baru):\n${out}${head ? `\n\nHEAD: ${head}` : ""}${filterWarning}`
294
+ }
295
+ } catch {}
296
+ return `nothing to commit:\n${out}${filterWarning}`
297
+ }
298
+ const head = await runGit(["log", "--oneline", "-1"], resolvedCwd, ctx.signal).catch(() => "")
299
+ return `${out}${head ? `\n\nHEAD: ${head}` : ""}${filterWarning}`
300
+ },
301
+ }
@@ -0,0 +1,90 @@
1
+ import { readdir, realpath, stat } from "node:fs/promises"
2
+ import { join, relative, resolve } from "node:path"
3
+ import type { Tool } from "#minicore"
4
+ import { LIMITS } from "../constants.ts"
5
+ import { isIgnored, loadIgnoreMatchers } from "../lib/ignore.ts"
6
+ import { isPathOutsideRoot, isSensitive } from "../policy/jail.ts"
7
+
8
+ async function walk(
9
+ dir: string,
10
+ pattern: RegExp,
11
+ out: string[],
12
+ root: string,
13
+ limit: number,
14
+ signal: AbortSignal,
15
+ ignoreMatchers: ((rel: string) => boolean)[],
16
+ ) {
17
+ if (signal.aborted) throw new Error("aborted")
18
+ if (out.length >= limit) return
19
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => [])
20
+ for (const e of entries) {
21
+ if (out.length >= limit) break
22
+ if (e.name.startsWith(".") || e.name === "node_modules" || e.name === ".git") continue
23
+ const full = join(dir, e.name)
24
+ const rel = relative(root, full).replace(/\\/g, "/")
25
+ // Hormati .gitignore subset (bukan hard-coded saja).
26
+ if (isIgnored(rel, ignoreMatchers)) continue
27
+ if (e.isDirectory()) {
28
+ await walk(full, pattern, out, root, limit, signal, ignoreMatchers)
29
+ } else if (pattern.test(rel) || pattern.test(e.name)) {
30
+ const real = await realpath(full).catch(() => full)
31
+ if (isPathOutsideRoot(real, resolve(root)) || isSensitive(real) || isSensitive(rel)) continue
32
+ out.push(rel)
33
+ }
34
+ }
35
+ }
36
+
37
+ function globToRegExp(glob: string): RegExp {
38
+ let esc = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&")
39
+ // handle {a,b} → (a|b)
40
+ esc = esc.replace(
41
+ /\\\{([^}]+)\\\}/g,
42
+ (_m, inner: string) =>
43
+ `(${inner
44
+ .split(",")
45
+ .map((s) => s.trim().replace(/[.+^${}()|[\]\\]/g, "\\$&"))
46
+ .join("|")})`,
47
+ )
48
+ esc = esc.replace(/\*\*/g, "§§")
49
+ // **/ di awal/pola rekursif harus cocok file root juga: **/* sekarang jadi
50
+ // (.*/)?[^/]*, bukan .*/[^/]* yang butuh slash dan membuat root kosong.
51
+ esc = esc.replace(/§§\//g, "(.*/)?")
52
+ esc = esc.replace(/\*/g, "[^/]*")
53
+ esc = esc.replace(/§§/g, ".*")
54
+ esc = esc.replace(/\?/g, ".")
55
+ return new RegExp(`^${esc}$`)
56
+ }
57
+
58
+ export const globTool: Tool = {
59
+ name: "glob",
60
+ description:
61
+ "Search files with a glob pattern (e.g. **/*.ts, src/**/*.js). Returns relative paths, capped at 100 by default. Skips .git, node_modules, and dotfiles.",
62
+ parameters: {
63
+ type: "object",
64
+ properties: {
65
+ pattern: { type: "string", description: "glob pattern (e.g. **/*.ts)" },
66
+ cwd: { type: "string", description: "root directory (default: workspace root)" },
67
+ limit: { type: "number", description: "max results (default 100)" },
68
+ },
69
+ required: ["pattern"],
70
+ additionalProperties: false,
71
+ },
72
+ async execute({ pattern, cwd, limit }, ctx) {
73
+ const sessionRoot = (ctx as { cwd?: string }).cwd ?? process.cwd()
74
+ const rawRoot = (cwd as string) ?? "."
75
+ const root = resolve(sessionRoot, rawRoot)
76
+ if (isPathOutsideRoot(root, sessionRoot)) throw new Error(`cwd outside workspace: ${rawRoot}`)
77
+ const rawLim = limit as number | undefined
78
+ const lim = Number.isFinite(rawLim)
79
+ ? Math.min(Math.max(Math.floor(rawLim!), 1), LIMITS.SEARCH_MAX_LIMIT)
80
+ : LIMITS.SEARCH_DEFAULT_LIMIT
81
+ const re = globToRegExp(pattern as string)
82
+ const ignoreMatchers = await loadIgnoreMatchers(root)
83
+ const out: string[] = []
84
+ await walk(root, re, out, root, lim, ctx.signal, ignoreMatchers)
85
+ const st = await stat(root).catch(() => null)
86
+ if (!st) return `cwd not found: ${rawRoot}`
87
+ if (out.length === 0) return `no files match ${pattern} in ${rawRoot}`
88
+ return out.slice(0, lim).join("\n")
89
+ },
90
+ }