minicode-ai 0.27.0 → 0.30.0

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 (145) hide show
  1. package/README.md +1 -1
  2. package/cli/args.ts +184 -57
  3. package/cli/bootstrap/presentation-bridge.ts +383 -0
  4. package/cli/commands/acp.ts +45 -29
  5. package/cli/commands/auth.ts +17 -17
  6. package/cli/commands/config.ts +65 -66
  7. package/cli/commands/daemon.ts +44 -16
  8. package/cli/commands/doctor.ts +18 -15
  9. package/cli/commands/exec.ts +41 -89
  10. package/cli/commands/mcp.ts +25 -8
  11. package/cli/commands/memory.ts +16 -24
  12. package/cli/commands/openwork.ts +6 -2
  13. package/cli/commands/pricing.ts +14 -12
  14. package/cli/commands/providers.ts +36 -57
  15. package/cli/commands/sessions.ts +24 -18
  16. package/cli/commands/skills.ts +33 -18
  17. package/cli/commands/stats.ts +15 -30
  18. package/cli/commands.ts +73 -44
  19. package/cli/context-command-run.ts +30 -18
  20. package/cli/index.ts +51 -100
  21. package/cli/model-manager.ts +7 -2
  22. package/cli/provider-manager.ts +33 -18
  23. package/cli/router.ts +41 -12
  24. package/cli/setup.ts +241 -485
  25. package/cli/tui.ts +303 -100
  26. package/docs/TERMINAL_CONTRACT.md +258 -73
  27. package/docs/UI_RENDER_PIPELINE.md +9 -1
  28. package/docs/agents.md +2 -2
  29. package/docs/architecture.md +17 -32
  30. package/docs/choosing-mode.md +7 -9
  31. package/docs/cli.md +3 -5
  32. package/docs/environment.md +1 -2
  33. package/docs/policy-sandbox.md +3 -3
  34. package/docs/repl.md +2 -2
  35. package/docs/tools.md +1 -1
  36. package/package.json +1 -1
  37. package/src/app/mentions.ts +60 -13
  38. package/src/app/rag-layer.ts +17 -20
  39. package/src/app/session.ts +144 -68
  40. package/src/app/tool-layer.ts +38 -16
  41. package/src/config.ts +64 -104
  42. package/src/constants.ts +4 -6
  43. package/src/daemon/capability.ts +8 -1
  44. package/src/daemon/control.ts +3 -2
  45. package/src/daemon/server.ts +57 -0
  46. package/src/hooks/run.ts +73 -41
  47. package/src/lib/atomic-write.ts +31 -59
  48. package/src/lib/db-path.ts +47 -0
  49. package/src/lib/process-tree.ts +62 -0
  50. package/src/lib/public-http.ts +88 -23
  51. package/src/lib/trusted-exec.ts +48 -1
  52. package/src/lsp/client.ts +62 -17
  53. package/src/mcp/client.ts +85 -38
  54. package/src/mcp/http-transport.ts +28 -16
  55. package/src/mcp/transport.ts +42 -6
  56. package/src/memory/files.ts +164 -134
  57. package/src/memory/vector.ts +371 -420
  58. package/src/policy/approval-binding.ts +122 -45
  59. package/src/policy/bash-guard.ts +18 -7
  60. package/src/policy/compaction.ts +51 -18
  61. package/src/policy/context-window.ts +31 -8
  62. package/src/policy/context.ts +62 -36
  63. package/src/policy/executor.ts +17 -7
  64. package/src/policy/jail.ts +6 -8
  65. package/src/policy/microcompact.ts +4 -3
  66. package/src/policy/no-progress.ts +103 -22
  67. package/src/policy/permission.ts +36 -12
  68. package/src/policy/tool-contract.ts +74 -416
  69. package/src/policy/usage.ts +24 -2
  70. package/src/policy/verifier.ts +50 -2
  71. package/src/policy/work-mode.ts +28 -54
  72. package/src/presentation/adapter.ts +24 -16
  73. package/src/providers/anthropic.ts +16 -5
  74. package/src/providers/provision.ts +6 -56
  75. package/src/providers/responses.ts +38 -7
  76. package/src/providers/sse-bounds.ts +6 -4
  77. package/src/runtime/execution-journal.ts +4 -29
  78. package/src/sandbox/docker.ts +58 -34
  79. package/src/sandbox/mask.ts +157 -0
  80. package/src/sandbox/os.ts +107 -73
  81. package/src/session/authority.ts +29 -10
  82. package/src/session/context-projection.ts +6 -5
  83. package/src/session/db/runs.ts +397 -0
  84. package/src/session/db/schema.ts +358 -0
  85. package/src/session/open-work.ts +26 -3
  86. package/src/session/persistence.ts +74 -998
  87. package/src/session/verification.ts +170 -20
  88. package/src/skills/loader.ts +31 -16
  89. package/src/task/db/schema.ts +325 -0
  90. package/src/task/db/types.ts +269 -0
  91. package/src/task/production-scheduler.ts +13 -1
  92. package/src/task/store.ts +92 -1021
  93. package/src/telemetry/trace.ts +27 -0
  94. package/src/tools/ask_user.ts +1 -13
  95. package/src/tools/bash.ts +27 -92
  96. package/src/tools/code_run.ts +1 -1
  97. package/src/tools/context.ts +133 -0
  98. package/src/tools/delete_file.ts +3 -2
  99. package/src/tools/edit.ts +37 -72
  100. package/src/tools/git.ts +86 -9
  101. package/src/tools/glob.ts +26 -51
  102. package/src/tools/grep.ts +67 -57
  103. package/src/tools/hashline.ts +4 -0
  104. package/src/tools/lsp.ts +11 -8
  105. package/src/tools/mcp_call.ts +9 -6
  106. package/src/tools/memory.ts +56 -33
  107. package/src/tools/move_file.ts +36 -10
  108. package/src/tools/patch.ts +13 -21
  109. package/src/tools/read_file.ts +18 -25
  110. package/src/tools/read_image.ts +35 -33
  111. package/src/tools/submit_result.ts +29 -8
  112. package/src/tools/task.ts +74 -17
  113. package/src/tools/todo.ts +181 -74
  114. package/src/tools/web_fetch.ts +42 -2
  115. package/src/tools/web_search.ts +47 -8
  116. package/src/ui/approval/prompt.ts +206 -47
  117. package/src/ui/assistant/turn-status.ts +14 -5
  118. package/src/ui/footer.ts +4 -4
  119. package/src/ui/i18n/en.ts +47 -23
  120. package/src/ui/i18n/id.ts +76 -51
  121. package/src/ui/input/input.ts +4 -3
  122. package/src/ui/input/prompt-engine.ts +35 -5
  123. package/src/ui/render/activity-panel.ts +4 -2
  124. package/src/ui/render/hint.ts +7 -4
  125. package/src/ui/render/list.ts +32 -0
  126. package/src/ui/render/markdown.ts +6 -3
  127. package/src/ui/render/notice.ts +19 -0
  128. package/src/ui/render/table-grid.ts +7 -8
  129. package/src/ui/render/theme.ts +113 -39
  130. package/src/ui/runtime/screen.ts +74 -10
  131. package/src/ui/runtime/spinner.ts +19 -6
  132. package/src/ui/screens/dialog.ts +19 -1
  133. package/src/ui/screens/form.ts +80 -35
  134. package/src/ui/screens/model-manager.ts +82 -61
  135. package/src/ui/screens/output-window.ts +263 -0
  136. package/src/ui/screens/picker.ts +94 -81
  137. package/src/ui/screens/provider-manager.ts +100 -69
  138. package/src/ui/screens/wizard.ts +117 -28
  139. package/src/ui/tui/app.ts +196 -33
  140. package/src/ui/tui/transcript.ts +158 -25
  141. package/vendor/minicore/src/core/executor.ts +2 -0
  142. package/vendor/minicore/src/core/loop.ts +17 -6
  143. package/vendor/minicore/src/core/session.ts +3 -0
  144. package/vendor/minicore/src/core/tool.ts +1 -0
  145. package/vendor/minicore/src/providers/openai-compat.ts +35 -19
@@ -1,9 +1,36 @@
1
+ import { readFileSync } from "node:fs"
1
2
  import { appendFile, chmod, mkdir, readFile, unlink } from "node:fs/promises"
2
3
  import { join, resolve } from "node:path"
3
4
  import { LIMITS } from "../constants.ts"
4
5
  import { atomicWriteText } from "../lib/atomic-write.ts"
5
6
  import { scrubSecrets } from "../policy/scrub.ts"
6
7
 
8
+ /**
9
+ * Baca berkas JSONL trace (`.minicode/traces.jsonl` atau `step-traces.jsonl`)
10
+ * secara toleran: baris kosong/korup dilewati, berkas tak ada -> `[]`.
11
+ * Dipakai bersama oleh `stats`, `providers`, dan `memory` agar tidak ada
12
+ * tiga duplikat parser JSONL manual di `cli/commands/*.ts`.
13
+ */
14
+ export function readTraceRows<T = RunTrace>(
15
+ cwd?: string,
16
+ filename: "traces.jsonl" | "step-traces.jsonl" = "traces.jsonl",
17
+ ): T[] {
18
+ try {
19
+ return readFileSync(resolve(cwd ?? ".", ".minicode", filename), "utf8")
20
+ .split("\n")
21
+ .filter(Boolean)
22
+ .flatMap((line) => {
23
+ try {
24
+ return [JSON.parse(line) as T]
25
+ } catch {
26
+ return []
27
+ }
28
+ })
29
+ } catch {
30
+ return []
31
+ }
32
+ }
33
+
7
34
  export interface RunTrace {
8
35
  sessionId: string
9
36
  timestamp: string
@@ -1,5 +1,6 @@
1
1
  import type { Tool } from "#minicore"
2
2
  import type { ApprovalEventHook, ApprovalHookEvent } from "../presentation/events.ts"
3
+ import { sliceSafeChars } from "./context.ts"
3
4
 
4
5
  // Tanya user di tengah run — untuk pilihan yang tidak bisa diputuskan model
5
6
  // sendiri (ambiguitas kebutuhan, kredensial, "lanjut/tidak").
@@ -11,19 +12,6 @@ import type { ApprovalEventHook, ApprovalHookEvent } from "../presentation/event
11
12
 
12
13
  export type AskTextFn = (question: string, options?: string[]) => Promise<string | null>
13
14
 
14
- /**
15
- * Potong tanpa membelah pasangan surrogate: `slice` mentah menyisakan surrogate
16
- * tinggi yatim → U+FFFD (AUD-010). Lapisan tool tak boleh impor src/ui.
17
- */
18
- function sliceSafeChars(s: string, max: number): string {
19
- if (s.length <= max) return s
20
- let end = max
21
- const code = s.charCodeAt(end - 1)
22
- // Surrogate tinggi di posisi terakhir = pasangannya ikut terpotong; mundur 1.
23
- if (code >= 0xd800 && code <= 0xdbff) end -= 1
24
- return s.slice(0, Math.max(0, end))
25
- }
26
-
27
15
  let askTextFn: AskTextFn | undefined
28
16
 
29
17
  export function setAskTextFn(fn: AskTextFn | undefined): void {
package/src/tools/bash.ts CHANGED
@@ -1,15 +1,20 @@
1
- import { spawn, spawnSync } from "node:child_process"
1
+ import { spawn } from "node:child_process"
2
2
  import { randomUUID } from "node:crypto"
3
3
  import { resolve as resolvePath } from "node:path"
4
4
  import type { Tool, ToolContext } from "#minicore"
5
5
  import { LIMITS } from "../constants.ts"
6
+ import {
7
+ killProcessTree,
8
+ signalProcessGroup,
9
+ signalProcessGroupGraceful,
10
+ } from "../lib/process-tree.ts"
6
11
  import { isCwdOutsideRoot, isPathOutsideRoot } from "../policy/jail.ts"
7
12
  import { contextUnrestricted, requireToolCwd } from "./context.ts"
8
13
 
9
- // re-export untuk backward compat (helper kini terpusat di policy/scrub)
10
14
  export { SECRET_ENV_RE, sanitizeSpawnEnv, stripSecretsEnv } from "../policy/scrub.ts"
15
+ // re-export untuk backward compat (helper kini terpusat di policy/scrub & lib/process-tree)
16
+ export { signalProcessGroupGraceful }
11
17
 
12
- import { resolveTrustedExecutable } from "../lib/trusted-exec.ts"
13
18
  import { sandboxExplicitFallbackAllowed, sandboxStrict } from "../policy/sandbox-policy.ts"
14
19
  import { sanitizeSpawnEnv, scrubSecrets } from "../policy/scrub.ts"
15
20
  import { dockerAvailable, runInDocker } from "../sandbox/docker.ts"
@@ -140,90 +145,8 @@ function reapFinishedJobs(): void {
140
145
  }
141
146
  }
142
147
 
143
- /**
144
- * Sinyal ke SELURUH grup proses (POSIX). Butuh spawn `detached:true` agar
145
- * shell jadi group leader — tanpa itu `-pid` bukan grup yang valid dan
146
- * group-kill jadi tak mungkin (cucu selamat). true = sinyal sampai ke grup.
147
- */
148
- function signalProcessGroup(p: ReturnType<typeof spawn>, signal: NodeJS.Signals): boolean {
149
- if (process.platform === "win32" || p.pid === undefined) return false
150
- try {
151
- process.kill(-p.pid, signal)
152
- return true
153
- } catch {
154
- return false
155
- }
156
- }
157
-
158
- /**
159
- * [Fase 2 / LOOP-INV-10] Eskalasi AWAL yang sopan: SIGTERM ke seluruh process
160
- * group, bukan hanya shell induk.
161
- *
162
- * Kenapa penting: `p.kill("SIGTERM")` hanya menyentuh shell wrapper. Cucu
163
- * (`node -e`, dev server) tetap hidup, menahan pipe, dan baru mati 2 detik
164
- * kemudian oleh SIGKILL grup — padahal banyak proses menangani SIGTERM dengan
165
- * flush/cleanup yang benar bila sinyalnya sampai. Helper ini dipakai sebelum
166
- * timer eskalasi `killTree` (SIGKILL), di jalur timeout DAN abort.
167
- *
168
- * `opts` adalah seam deterministik untuk test: perilaku POSIX dapat diuji di
169
- * Windows tanpa benar-benar mengirim sinyal ke proses nyata.
170
- */
171
- export function signalProcessGroupGraceful(
172
- pid: number | undefined,
173
- fallback: { kill: (signal?: NodeJS.Signals | number) => boolean },
174
- opts: {
175
- platform?: NodeJS.Platform
176
- killGroup?: (pid: number, signal: NodeJS.Signals) => boolean
177
- } = {},
178
- ): "group" | "fallback" {
179
- const platform = opts.platform ?? process.platform
180
- if (platform !== "win32" && typeof pid === "number" && pid > 0) {
181
- const killGroup =
182
- opts.killGroup ??
183
- ((target: number, signal: NodeJS.Signals): boolean => process.kill(target, signal))
184
- try {
185
- // Negatif = process group id (shell adalah group leader karena detached).
186
- if (killGroup(-pid, "SIGTERM")) return "group"
187
- } catch {
188
- // Grup sudah hilang / ESRCH: jatuh ke sinyal proses tunggal di bawah.
189
- }
190
- }
191
- try {
192
- fallback.kill("SIGTERM")
193
- } catch {}
194
- return "fallback"
195
- }
196
-
197
- /**
198
- * Bunuh proses + seluruh subtree-nya. Di Windows `p.kill()` hanya membunuh
199
- * wrapper `cmd.exe` — cucu seperti `node -e "while(true){}"` tetap hidup,
200
- * menahan pipe stdio sehingga event `close` tidak pernah datang (hang
201
- * selamanya walau timeout sudah lewat). `taskkill /T` menutup tree-nya.
202
- */
203
148
  function killTree(p: ReturnType<typeof spawn>): void {
204
- try {
205
- if (process.platform === "win32" && p.pid !== undefined) {
206
- // F-23: resolve absolut dari PATH terpercaya — spawn dengan cwd
207
- // workspace bisa mengeksekusi taskkill.bat repo (hijack CWD Windows).
208
- // Env juga disanitasi: proses ini berjalan di timeout dengan hak penuh.
209
- const r = spawnSync(
210
- resolveTrustedExecutable("taskkill"),
211
- ["/pid", String(p.pid), "/T", "/F"],
212
- {
213
- stdio: "ignore",
214
- env: sanitizeSpawnEnv(process.env),
215
- },
216
- )
217
- if (r.status === 0) return
218
- } else if (signalProcessGroup(p, "SIGKILL")) {
219
- // POSIX: bunuh seluruh grup proses (shell wrapper + cucu seperti
220
- // `node -e`). Spawn memakai detached:true agar shell jadi group leader.
221
- return
222
- }
223
- } catch {}
224
- try {
225
- p.kill("SIGKILL")
226
- } catch {}
149
+ killProcessTree(p, { env: sanitizeSpawnEnv(process.env) })
227
150
  }
228
151
 
229
152
  /**
@@ -256,10 +179,19 @@ function startBackground(
256
179
  relaxed = false,
257
180
  ): string {
258
181
  reapFinishedJobs()
259
- const live = [...jobs.values()].filter((j) => !j.done).length
260
- if (live >= LIMITS.BASH_BACKGROUND_MAX_JOBS) {
182
+ // Isolasi kuota per pemilik sesi agar satu sesi tidak menghabiskan slot sesi lain,
183
+ // tetap dibatasi backstop global proses agar jumlah anak OS terkendali.
184
+ const ownerLive = [...jobs.values()].filter((j) => !j.done && j.ownerSid === ownerSid).length
185
+ if (ownerLive >= LIMITS.BASH_BACKGROUND_MAX_JOBS) {
186
+ throw new Error(
187
+ `too many background jobs (${ownerLive}/${LIMITS.BASH_BACKGROUND_MAX_JOBS}) — stop one with bash_kill first`,
188
+ )
189
+ }
190
+ const totalLive = [...jobs.values()].filter((j) => !j.done).length
191
+ const totalCap = LIMITS.BASH_BACKGROUND_MAX_JOBS * 4
192
+ if (totalLive >= totalCap) {
261
193
  throw new Error(
262
- `too many background jobs (${live}/${LIMITS.BASH_BACKGROUND_MAX_JOBS}) — stop one with bash_kill first`,
194
+ `too many active background jobs (${totalLive}/${totalCap}) — stop one with bash_kill first`,
263
195
  )
264
196
  }
265
197
  const id = `bg_${randomUUID().slice(0, 8)}`
@@ -360,8 +292,11 @@ function makeBashTool(ownerSid: string | null): Tool {
360
292
  // Unrestricted: default timeout jauh lebih lega; timeoutMs eksplisit
361
293
  // tetap menang.
362
294
  const timeout =
363
- timeoutMs ??
364
- (relaxed ? LIMITS.UNRESTRICTED_BASH_TIMEOUT_MS : LIMITS.BASH_DEFAULT_TIMEOUT_MS)
295
+ typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0
296
+ ? timeoutMs
297
+ : relaxed
298
+ ? LIMITS.UNRESTRICTED_BASH_TIMEOUT_MS
299
+ : LIMITS.BASH_DEFAULT_TIMEOUT_MS
365
300
 
366
301
  if (background === true) {
367
302
  // Sandbox tidak diterapkan di jalur background: container/namespace
@@ -535,7 +470,7 @@ function makeBashOutputTool(ownerSid: string | null): Tool {
535
470
  parameters: {
536
471
  type: "object",
537
472
  properties: {
538
- id: { type: "string", description: "job id dari bash background:true" },
473
+ id: { type: "string", description: "job id from bash with background:true" },
539
474
  },
540
475
  required: ["id"],
541
476
  additionalProperties: false,
@@ -26,7 +26,7 @@ export function shSingleQuote(s: string): string {
26
26
  export const codeRunTool: Tool = {
27
27
  name: "code_run",
28
28
  description:
29
- "Run a code snippet (python -c / node -e) inside the configured sandbox (docker or OS sandbox, network-isolated). Requires MINICODE_SANDBOX=os|docker with a working backend; refuses otherwise. Python needs an image containing python3.",
29
+ "Run a code snippet (python -c / node -e) inside the configured sandbox (Docker, Linux bwrap, or macOS seatbelt — network-isolated). Requires MINICODE_SANDBOX=os|docker with an available backend (unavailable natively on Windows without Docker); refuses otherwise. Python needs an image/environment containing python3.",
30
30
  parameters: {
31
31
  type: "object",
32
32
  properties: {
@@ -1,3 +1,17 @@
1
+ import { readdir, realpath, stat } from "node:fs/promises"
2
+ import { isAbsolute, join, relative, resolve } from "node:path"
3
+ import { LIMITS } from "../constants.ts"
4
+ import { atomicWriteText } from "../lib/atomic-write.ts"
5
+ import { isIgnored } from "../lib/ignore.ts"
6
+ import {
7
+ assertSafeWriteTarget,
8
+ resolveSafePath,
9
+ safeOpenRead,
10
+ safeReadFile,
11
+ } from "../lib/safe-open.ts"
12
+ import { isCwdOutsideRoot, isPathOutsideRoot, isSensitive } from "../policy/jail.ts"
13
+ import { appendLspDiagnostics } from "../policy/verifier.ts"
14
+
1
15
  /** Workspace root wajib datang dari context eksekusi yang dirakit runtime. */
2
16
  export function requireToolCwd(context: unknown): string {
3
17
  const cwd = (context as { cwd?: unknown } | null)?.cwd
@@ -16,3 +30,122 @@ export function requireToolCwd(context: unknown): string {
16
30
  export function contextUnrestricted(context: unknown): boolean {
17
31
  return (context as { permissionMode?: unknown } | null)?.permissionMode === "unrestricted"
18
32
  }
33
+
34
+ /**
35
+ * Potong string tanpa membelah pasangan surrogate UTF-16: `slice` mentah pada
36
+ * batas tinggi menghasilkan kode pengganti `U+FFFD`. Dipakai bersama oleh tool
37
+ * yang memotong baris/teks panjang (`read_file`, `ask_user`).
38
+ */
39
+ export function sliceSafeChars(s: string, max: number): string {
40
+ if (s.length <= max) return s
41
+ let end = max
42
+ const code = s.charCodeAt(end - 1)
43
+ if (code >= 0xd800 && code <= 0xdbff) end -= 1
44
+ return s.slice(0, Math.max(0, end))
45
+ }
46
+
47
+ export async function openSafeToolReadHandle(rawPath: string, ctx: unknown) {
48
+ const root = requireToolCwd(ctx)
49
+ const relaxed = contextUnrestricted(ctx)
50
+ const abs = isAbsolute(rawPath) ? resolve(rawPath) : resolve(root, rawPath)
51
+ let handle: Awaited<ReturnType<typeof safeOpenRead>>["handle"]
52
+ try {
53
+ ;({ handle } = await safeOpenRead(abs, root, relaxed))
54
+ } catch (e) {
55
+ const msg = (e as Error).message ?? ""
56
+ if ((e as NodeJS.ErrnoException).code === "ENOENT" || msg.includes("ENOENT"))
57
+ throw new Error(`file not found: ${rawPath}`)
58
+ throw e
59
+ }
60
+ const st = await handle.stat().catch(() => null)
61
+ if (!st) {
62
+ await handle.close().catch(() => {})
63
+ throw new Error(`file not found: ${rawPath}`)
64
+ }
65
+ return { handle, st, root, relaxed, abs }
66
+ }
67
+
68
+ /** Baca teks siap-edit dengan cek jail, anti-symlink overwrite, cap ukuran, & O_NOFOLLOW. */
69
+ export async function readSafeTextForEdit(rawPath: string, ctx: unknown) {
70
+ const root = requireToolCwd(ctx)
71
+ const relaxed = contextUnrestricted(ctx)
72
+ const { abs, real: realAbs } = await resolveSafePath(rawPath, root, relaxed)
73
+ await assertSafeWriteTarget(abs, root, relaxed)
74
+ const st = await stat(realAbs).catch(() => null)
75
+ if (!st) throw new Error(`file not found: ${rawPath}`)
76
+ if (st.size > LIMITS.READ_FILE_MAX_BYTES)
77
+ throw new Error(`file too large: ${rawPath} (${st.size})`)
78
+ const content = await safeReadFile(abs, root, relaxed).catch(() => {
79
+ throw new Error(`file not found: ${rawPath}`)
80
+ })
81
+ return { root, realAbs, content }
82
+ }
83
+
84
+ /** Tulis hasil edit dengan cek batas char + atomic write + LSP diagnostics. */
85
+ export async function commitSafeTextEdit(
86
+ realAbs: string,
87
+ root: string,
88
+ content: string,
89
+ message: string,
90
+ ): Promise<string> {
91
+ if (content.length > LIMITS.WRITE_FILE_MAX_CHARS)
92
+ throw new Error(`result too large: ${content.length} chars (max 5M)`)
93
+ await atomicWriteText(realAbs, content)
94
+ return await appendLspDiagnostics(realAbs, content, message, undefined, root)
95
+ }
96
+
97
+ /** Validasi dan resolve `cwd` tool terhadap batas workspace. */
98
+ export function resolveSearchRoot(
99
+ cwdArg: unknown,
100
+ ctx: unknown,
101
+ ): { root: string; rawRoot: string; relaxed: boolean } {
102
+ const sessionRoot = requireToolCwd(ctx)
103
+ const relaxed = contextUnrestricted(ctx)
104
+ const rawRoot = (cwdArg as string) ?? "."
105
+ const root = resolve(sessionRoot, rawRoot)
106
+ if (
107
+ !relaxed &&
108
+ (isPathOutsideRoot(root, sessionRoot) || isCwdOutsideRoot(rawRoot, sessionRoot))
109
+ ) {
110
+ throw new Error(`cwd outside workspace: ${rawRoot}`)
111
+ }
112
+ return { root, rawRoot, relaxed }
113
+ }
114
+
115
+ /** Walk workspace aman (hormat .gitignore, skip dotfile default & symlink escape/sensitif). */
116
+ export async function walkWorkspaceFiles(
117
+ opts: {
118
+ dir: string
119
+ root: string
120
+ signal: AbortSignal
121
+ ignoreMatchers: ((rel: string) => boolean)[]
122
+ relaxed?: boolean
123
+ includeDotfiles?: boolean
124
+ shouldStop?: () => boolean
125
+ },
126
+ onFile: (info: { full: string; rel: string; name: string; real: string }) => Promise<void> | void,
127
+ ): Promise<void> {
128
+ if (opts.signal.aborted) throw new Error("aborted")
129
+ if (opts.shouldStop?.()) return
130
+ const entries = await readdir(opts.dir, { withFileTypes: true }).catch(() => [])
131
+ for (const e of entries) {
132
+ if (opts.shouldStop?.()) break
133
+ if (e.name === "node_modules" || e.name === ".git") continue
134
+ if (!opts.includeDotfiles && e.name.startsWith(".")) continue
135
+ const full = join(opts.dir, e.name)
136
+ const rel = relative(opts.root, full).replace(/\\/g, "/")
137
+ if (isIgnored(rel, opts.ignoreMatchers)) continue
138
+ if (e.isDirectory()) {
139
+ await walkWorkspaceFiles({ ...opts, dir: full }, onFile)
140
+ } else {
141
+ const real = await realpath(full).catch(() => full)
142
+ if (
143
+ (!opts.relaxed && isPathOutsideRoot(real, resolve(opts.root))) ||
144
+ isSensitive(real) ||
145
+ isSensitive(rel)
146
+ )
147
+ continue
148
+ await onFile({ full, rel, name: e.name, real })
149
+ }
150
+ }
151
+ }
@@ -11,7 +11,7 @@ export const deleteFileTool: Tool = {
11
11
  parameters: {
12
12
  type: "object",
13
13
  properties: {
14
- path: { type: "string", description: "path file relatif" },
14
+ path: { type: "string", description: "relative file path" },
15
15
  },
16
16
  required: ["path"],
17
17
  additionalProperties: false,
@@ -25,7 +25,8 @@ export const deleteFileTool: Tool = {
25
25
  const { abs, real } = await resolveSafePath(p, root, relaxed)
26
26
  const st = await stat(real).catch(() => null)
27
27
  if (!st) throw new Error(`file not found: ${p}`)
28
- if (st.isDirectory()) throw new Error(`path is directory, use bash rm -r: ${p}`)
28
+ if (st.isDirectory())
29
+ throw new Error(`path is a directory, cannot delete directories with delete_file: ${p}`)
29
30
  // soft-delete ke .minicode/.trash (gitignored, cap 100) — restore via move_file
30
31
  const dest = await trashFile(root, abs)
31
32
  return `deleted ${p} -> ${dest} (soft-delete, restore via move_file if needed)`
package/src/tools/edit.ts CHANGED
@@ -1,9 +1,5 @@
1
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 { contextUnrestricted, requireToolCwd } from "./context.ts"
2
+ import { commitSafeTextEdit, readSafeTextForEdit } from "./context.ts"
7
3
  import { applyHashline } from "./hashline.ts"
8
4
 
9
5
  function normalizeLf(s: string): string {
@@ -71,16 +67,29 @@ export function flexibleMatch(content: string, needle: string): MatchResult | nu
71
67
  }
72
68
 
73
69
  const cLfLines = cLf.split("\n")
74
- // 3. Trailing whitespace tolerance
70
+ // 3. Trailing whitespace tolerance — hanya terima kecocokan yang menempel di
71
+ // batas baris utuh, karena lineRange() mengganti seluruh baris awal..akhir.
72
+ // Match substring di tengah baris bisa menelan token sebelum/sesudah match.
75
73
  const cTrimmed = stripTrailingWhitespace(cLf)
76
74
  const nTrimmed = stripTrailingWhitespace(nLf)
77
- const trimStart = cTrimmed.indexOf(nTrimmed)
78
- if (trimStart !== -1) {
79
- const lineCountBefore = cTrimmed.slice(0, trimStart).split("\n").length - 1
80
- const needleLineCount = nTrimmed.split("\n").length
81
- if (lineCountBefore + needleLineCount <= cLfLines.length) {
82
- const r = lineRange(cLfLines, lineCountBefore, needleLineCount, content)
83
- return { ...r, mode: "trimmed" }
75
+ if (nTrimmed.length > 0) {
76
+ let searchFrom = 0
77
+ while (searchFrom <= cTrimmed.length - nTrimmed.length) {
78
+ const trimStart = cTrimmed.indexOf(nTrimmed, searchFrom)
79
+ if (trimStart === -1) break
80
+ const trimEnd = trimStart + nTrimmed.length
81
+ const atLineStart = trimStart === 0 || cTrimmed[trimStart - 1] === "\n"
82
+ const atLineEnd = trimEnd === cTrimmed.length || cTrimmed[trimEnd] === "\n"
83
+ if (atLineStart && atLineEnd) {
84
+ const lineCountBefore =
85
+ trimStart === 0 ? 0 : cTrimmed.slice(0, trimStart).split("\n").length - 1
86
+ const needleLineCount = nTrimmed.split("\n").length
87
+ if (lineCountBefore + needleLineCount <= cLfLines.length) {
88
+ const r = lineRange(cLfLines, lineCountBefore, needleLineCount, content)
89
+ return { ...r, mode: "trimmed" }
90
+ }
91
+ }
92
+ searchFrom = trimStart + 1
84
93
  }
85
94
  }
86
95
 
@@ -146,88 +155,44 @@ export const editTool: Tool = {
146
155
  async execute({ path, oldString, newString }, ctx) {
147
156
  ctx.signal.throwIfAborted()
148
157
  const p = path as string
149
- const root = requireToolCwd(ctx)
150
- const relaxed = contextUnrestricted(ctx)
151
- // Verifikasi path terpusat (logis + target nyata, induk symlink ikut
152
- // ter-resolusi) — symlink internal tetap bisa diedit, targetnya yang dicek.
153
- const { abs, real: realAbs } = await resolveSafePath(p, root, relaxed)
154
- // Tolak menimpa symlink final (swap antara cek dan tulis gagal tutup).
155
- await assertSafeWriteTarget(abs, root, relaxed)
156
- // Cek ukuran sebelum baca penuh — hindari OOM 1GB via safeReadFile.
157
- // Pakai byte length via stat pada realAbs (handle belum ada), fallback ke content length.
158
- const { stat } = await import("node:fs/promises")
159
- const st = await stat(realAbs).catch(() => null)
160
- if (!st) throw new Error(`file not found: ${p}`)
161
- if (st.size > LIMITS.READ_FILE_MAX_BYTES) throw new Error(`file too large: ${p} (${st.size})`)
162
- // Baca via safeReadFile (O_NOFOLLOW) agar TOCTOU swap gagal ELOOP, bukan baca luar.
163
- const content = await safeReadFile(abs, root, relaxed).catch(() => {
164
- throw new Error(`file not found: ${p}`)
165
- })
158
+ const { root, realAbs, content } = await readSafeTextForEdit(p, ctx)
166
159
  const oldS = oldString as string
167
160
  const newS = newString as string
168
161
  if (oldS === newS) throw new Error("oldString == newString (no change)")
169
- // Hashline fast path (OpenCode): hanya bila line endings konsisten (hindari CRLF→LF corrupt)
170
- // CRLF vs LF ditangani oleh flexibleMatch mode "crlf" yang preservasi original.
162
+ // Hashline fast path: hanya bila line endings konsisten (CRLF vs LF dijaga flexibleMatch).
171
163
  const canHashline = content.includes("\r\n") === oldS.includes("\r\n")
172
- let hashApply: string | null = null
173
164
  if (canHashline) {
174
165
  const hunk = applyHashline(content, oldS, newS)
175
166
  if (hunk !== null) {
176
- // Uniqueness: aturan YANG SAMA dengan jalur flexibleMatch di bawah
177
- // (exact → crlf → trimmed → fuzzy). Pemeriksaan lama hanya mencari
178
- // duplikat SUBSTRING PERSIS, jadi needle yang unik-persis tapi
179
- // ambigu-fuzzy (mis. "\tfoo" vs " foo") lolos dan blok PERTAMA
180
- // diedit diam-diam — kelas bug yang sama dengan "duplikat diam-diam
181
- // edit blok pertama" yang sudah ditutup di jalur bawah.
182
- //
183
- // flexibleMatch di sini TIDAK memilih target (itu tetap hashline) —
184
- // hanya menjawab "apakah needle ini unik?", supaya kedua jalur
185
- // menjawab pertanyaan yang sama.
186
167
  const first = flexibleMatch(content, oldS)
187
- if (!first) {
188
- // Hashline menemukan, flexibleMatch tidak (atau fuzzy-nya ambigu →
189
- // flexibleMatch sengaja null). Jalur bawah menolak dengan "not
190
- // found"; jalur cepat tidak boleh lebih longgar.
191
- throw new Error(`oldString not found in ${p}`)
192
- }
168
+ if (!first) throw new Error(`oldString not found in ${p}`)
193
169
  if (isAmbiguousMatch(content, oldS, first)) {
194
170
  throw new Error(
195
171
  `oldString found multiple times in ${p} — provide more surrounding lines to make it unique`,
196
172
  )
197
173
  }
198
- hashApply = hunk
174
+ return await commitSafeTextEdit(
175
+ realAbs,
176
+ root,
177
+ hunk,
178
+ `edited ${realAbs} (hashline match) (${oldS.length} → ${newS.length} chars)`,
179
+ )
199
180
  }
200
181
  }
201
- if (hashApply !== null) {
202
- if (hashApply.length > LIMITS.WRITE_FILE_MAX_CHARS)
203
- throw new Error(`result too large: ${hashApply.length} chars (max 5M)`)
204
- await atomicWriteText(realAbs, hashApply)
205
- return await appendLspDiagnostics(
206
- realAbs,
207
- hashApply,
208
- `edited ${realAbs} (hashline match) (${oldS.length} → ${newS.length} chars)`,
209
- undefined,
210
- root,
211
- )
212
- }
213
182
  const match = flexibleMatch(content, oldS)
214
183
  if (!match) throw new Error(`oldString not found in ${p}`)
215
-
216
- // ensure uniqueness untuk semua mode (exact/crlf/trimmed/fuzzy) — trimmed/fuzzy
217
- // sebelumnya hanya dicek untuk exact/crlf sehingga duplikat diam-diam edit blok pertama
218
184
  if (isAmbiguousMatch(content, oldS, match)) {
219
185
  throw new Error(
220
186
  `oldString found multiple times in ${p} — provide more surrounding lines to make it unique`,
221
187
  )
222
188
  }
223
-
224
189
  const next = content.slice(0, match.start) + newS + content.slice(match.end)
225
- if (next.length > LIMITS.WRITE_FILE_MAX_CHARS)
226
- throw new Error(`result too large: ${next.length} chars (max 5M)`)
227
- // atomic (O_EXCL + randomUUID tmp)
228
- await atomicWriteText(realAbs, next)
229
190
  const note = match.mode !== "exact" ? ` (${match.mode} match)` : ""
230
- const base = `edited ${realAbs}${note} (${oldS.length} → ${newS.length} chars)`
231
- return await appendLspDiagnostics(realAbs, next, base, undefined, root)
191
+ return await commitSafeTextEdit(
192
+ realAbs,
193
+ root,
194
+ next,
195
+ `edited ${realAbs}${note} (${oldS.length} → ${newS.length} chars)`,
196
+ )
232
197
  },
233
198
  }
package/src/tools/git.ts CHANGED
@@ -337,19 +337,96 @@ export const gitCommitTool: Tool = {
337
337
  const args = ["commit", "--no-verify", "-m", msg]
338
338
  if (files.length === 0 && all === true) args.push("-a")
339
339
  const out = await runGit(args, resolvedCwd, ctx.signal, indexEnv)
340
+ const firstLine = msg.split("\n")[0]?.trim()
341
+ // runGit mengembalikan "(exit 0)" saat stdout+stderr kosong (lihat baris 82).
342
+ const isCleanGitOut = (s: string): boolean => !s || /^\(exit \d+\)$/.test(s)
340
343
  if (/nothing to commit|no changes added/i.test(out)) {
341
344
  try {
342
- const subject = (
343
- await runGit(["log", "-1", "--format=%s"], resolvedCwd, ctx.signal).catch(() => "")
344
- ).trim()
345
- if (subject && subject === msg.split("\n")[0]?.trim()) {
346
- const head = await runGit(["log", "--oneline", "-1"], resolvedCwd, ctx.signal).catch(
347
- () => "",
348
- )
349
- return `already committed (retry aman — tanpa commit baru):\n${out}${head ? `\n\nHEAD: ${head}` : ""}`
345
+ if (files.length > 0) {
346
+ // Hanya klaim "already committed" bila file target bersih sekarang,
347
+ // benar-benar tersentuh di HEAD, DAN subjek commit terakhir atas
348
+ // file tersebut cocok — mencegah false positive saat staging gagal.
349
+ const pending = (
350
+ await runGit(
351
+ ["status", "--porcelain", "--", ...files],
352
+ resolvedCwd,
353
+ ctx.signal,
354
+ ).catch(() => "DIRTY")
355
+ ).trim()
356
+ const inHead = (
357
+ await runGit(
358
+ [
359
+ "--literal-pathspecs",
360
+ "diff-tree",
361
+ "--root",
362
+ "--no-renames",
363
+ "--no-commit-id",
364
+ "--name-only",
365
+ "-r",
366
+ "HEAD",
367
+ "--",
368
+ ...files,
369
+ ],
370
+ resolvedCwd,
371
+ ctx.signal,
372
+ ).catch(() => "")
373
+ ).trim()
374
+ const subject = (
375
+ await runGit(
376
+ ["log", "-1", "--format=%s", "--", ...files],
377
+ resolvedCwd,
378
+ ctx.signal,
379
+ ).catch(() => "")
380
+ ).trim()
381
+ if (
382
+ isCleanGitOut(pending) &&
383
+ !isCleanGitOut(inHead) &&
384
+ subject &&
385
+ subject === firstLine
386
+ ) {
387
+ const head = await runGit(
388
+ ["log", "--oneline", "-1"],
389
+ resolvedCwd,
390
+ ctx.signal,
391
+ ).catch(() => "")
392
+ return `already committed (retry aman — tanpa commit baru):\n${out}${head ? `\n\nHEAD: ${head}` : ""}`
393
+ }
394
+ } else {
395
+ const trackedDirty = (
396
+ await runGit(
397
+ ["status", "--porcelain", "--untracked-files=no"],
398
+ resolvedCwd,
399
+ ctx.signal,
400
+ ).catch(() => "DIRTY")
401
+ ).trim()
402
+ const subject = (
403
+ await runGit(["log", "-1", "--format=%s"], resolvedCwd, ctx.signal).catch(() => "")
404
+ ).trim()
405
+ if (isCleanGitOut(trackedDirty) && subject && subject === firstLine) {
406
+ const head = await runGit(
407
+ ["log", "--oneline", "-1"],
408
+ resolvedCwd,
409
+ ctx.signal,
410
+ ).catch(() => "")
411
+ return `already committed (retry aman — tanpa commit baru):\n${out}${head ? `\n\nHEAD: ${head}` : ""}`
412
+ }
350
413
  }
351
414
  } catch {}
352
- return `nothing to commit:\n${out}`
415
+ let untrackedHint = ""
416
+ if (files.length === 0 && all === true) {
417
+ const untracked = (
418
+ await runGit(
419
+ ["ls-files", "--others", "--exclude-standard"],
420
+ resolvedCwd,
421
+ ctx.signal,
422
+ ).catch(() => "")
423
+ ).trim()
424
+ if (!isCleanGitOut(untracked)) {
425
+ untrackedHint =
426
+ "\n(note: `all: true` only stages modified tracked files; pass `paths` explicitly to commit untracked files)"
427
+ }
428
+ }
429
+ return `nothing to commit:\n${out}${untrackedHint}`
353
430
  }
354
431
  let indexWarning = ""
355
432
  const newHead = await runGit(