minicode-ai 0.26.0 → 0.28.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 (139) hide show
  1. package/cli/args.ts +120 -16
  2. package/cli/commands/acp.ts +38 -28
  3. package/cli/commands/auth.ts +17 -17
  4. package/cli/commands/config.ts +65 -66
  5. package/cli/commands/daemon.ts +44 -16
  6. package/cli/commands/doctor.ts +11 -12
  7. package/cli/commands/exec.ts +35 -73
  8. package/cli/commands/mcp.ts +25 -8
  9. package/cli/commands/memory.ts +16 -24
  10. package/cli/commands/openwork.ts +6 -2
  11. package/cli/commands/pricing.ts +14 -12
  12. package/cli/commands/providers.ts +36 -57
  13. package/cli/commands/sessions.ts +24 -18
  14. package/cli/commands/skills.ts +33 -18
  15. package/cli/commands/stats.ts +15 -30
  16. package/cli/commands.ts +96 -46
  17. package/cli/context-command-run.ts +171 -0
  18. package/cli/context-command.ts +87 -0
  19. package/cli/index.ts +96 -98
  20. package/cli/model-manager.ts +7 -2
  21. package/cli/provider-manager.ts +33 -18
  22. package/cli/router.ts +41 -12
  23. package/cli/setup.ts +246 -123
  24. package/cli/tui.ts +311 -109
  25. package/docs/TERMINAL_CONTRACT.md +254 -69
  26. package/docs/UI_RENDER_PIPELINE.md +9 -1
  27. package/docs/agents.md +2 -2
  28. package/docs/architecture.md +3 -3
  29. package/docs/choosing-mode.md +7 -9
  30. package/docs/cli.md +3 -5
  31. package/docs/config.md +16 -0
  32. package/docs/environment.md +3 -3
  33. package/docs/policy-sandbox.md +3 -3
  34. package/docs/repl.md +3 -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 +119 -66
  40. package/src/app/tool-layer.ts +12 -17
  41. package/src/config.ts +64 -104
  42. package/src/constants.ts +23 -9
  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/db-path.ts +47 -0
  48. package/src/lib/process-tree.ts +62 -0
  49. package/src/lib/public-http.ts +88 -23
  50. package/src/lib/trusted-exec.ts +48 -1
  51. package/src/lsp/client.ts +62 -17
  52. package/src/mcp/client.ts +85 -38
  53. package/src/mcp/http-transport.ts +28 -16
  54. package/src/mcp/transport.ts +42 -6
  55. package/src/memory/files.ts +164 -134
  56. package/src/memory/vector.ts +371 -420
  57. package/src/policy/approval-binding.ts +122 -45
  58. package/src/policy/bash-guard.ts +18 -7
  59. package/src/policy/compaction.ts +51 -18
  60. package/src/policy/context-window.ts +109 -0
  61. package/src/policy/context.ts +78 -37
  62. package/src/policy/executor.ts +17 -7
  63. package/src/policy/microcompact.ts +4 -3
  64. package/src/policy/no-progress.ts +103 -22
  65. package/src/policy/permission.ts +36 -12
  66. package/src/policy/tool-contract.ts +74 -416
  67. package/src/policy/usage.ts +24 -2
  68. package/src/policy/verifier.ts +50 -2
  69. package/src/policy/work-mode.ts +28 -54
  70. package/src/presentation/adapter.ts +24 -16
  71. package/src/providers/guards.ts +41 -2
  72. package/src/providers/provision.ts +6 -60
  73. package/src/providers/responses.ts +1 -0
  74. package/src/repo/repomap.ts +180 -23
  75. package/src/runtime/execution-journal.ts +4 -29
  76. package/src/sandbox/docker.ts +58 -34
  77. package/src/sandbox/mask.ts +157 -0
  78. package/src/sandbox/os.ts +107 -73
  79. package/src/session/authority.ts +29 -10
  80. package/src/session/context-projection.ts +6 -5
  81. package/src/session/open-work.ts +26 -3
  82. package/src/session/persistence.ts +25 -58
  83. package/src/session/verification.ts +170 -20
  84. package/src/skills/loader.ts +31 -16
  85. package/src/task/production-scheduler.ts +13 -1
  86. package/src/task/store.ts +20 -37
  87. package/src/telemetry/trace.ts +27 -0
  88. package/src/tools/ask_user.ts +1 -13
  89. package/src/tools/bash.ts +27 -92
  90. package/src/tools/code_run.ts +1 -1
  91. package/src/tools/context.ts +133 -0
  92. package/src/tools/delete_file.ts +3 -2
  93. package/src/tools/edit.ts +37 -72
  94. package/src/tools/git.ts +86 -9
  95. package/src/tools/glob.ts +26 -51
  96. package/src/tools/grep.ts +67 -57
  97. package/src/tools/hashline.ts +4 -0
  98. package/src/tools/lsp.ts +11 -8
  99. package/src/tools/mcp_call.ts +9 -6
  100. package/src/tools/memory.ts +56 -33
  101. package/src/tools/move_file.ts +36 -10
  102. package/src/tools/patch.ts +13 -21
  103. package/src/tools/read_file.ts +18 -25
  104. package/src/tools/read_image.ts +35 -33
  105. package/src/tools/submit_result.ts +29 -8
  106. package/src/tools/task.ts +74 -17
  107. package/src/tools/todo.ts +181 -74
  108. package/src/tools/web_fetch.ts +42 -2
  109. package/src/tools/web_search.ts +47 -8
  110. package/src/ui/approval/prompt.ts +206 -47
  111. package/src/ui/assistant/turn-status.ts +14 -5
  112. package/src/ui/footer.ts +4 -4
  113. package/src/ui/i18n/en.ts +59 -23
  114. package/src/ui/i18n/id.ts +88 -51
  115. package/src/ui/input/input.ts +4 -3
  116. package/src/ui/input/prompt-engine.ts +35 -5
  117. package/src/ui/render/activity-panel.ts +4 -2
  118. package/src/ui/render/hint.ts +7 -4
  119. package/src/ui/render/list.ts +32 -0
  120. package/src/ui/render/markdown.ts +6 -3
  121. package/src/ui/render/notice.ts +19 -0
  122. package/src/ui/render/table-grid.ts +7 -8
  123. package/src/ui/render/theme.ts +113 -39
  124. package/src/ui/runtime/screen.ts +74 -10
  125. package/src/ui/runtime/spinner.ts +19 -6
  126. package/src/ui/screens/dialog.ts +19 -1
  127. package/src/ui/screens/form.ts +80 -35
  128. package/src/ui/screens/model-manager.ts +88 -62
  129. package/src/ui/screens/output-window.ts +263 -0
  130. package/src/ui/screens/picker.ts +94 -81
  131. package/src/ui/screens/provider-manager.ts +100 -69
  132. package/src/ui/screens/wizard.ts +117 -28
  133. package/src/ui/tui/app.ts +196 -33
  134. package/src/ui/tui/transcript.ts +154 -25
  135. package/vendor/minicore/src/core/executor.ts +2 -0
  136. package/vendor/minicore/src/core/loop.ts +17 -6
  137. package/vendor/minicore/src/core/session.ts +3 -0
  138. package/vendor/minicore/src/core/tool.ts +1 -0
  139. package/vendor/minicore/src/providers/openai-compat.ts +28 -19
@@ -1,9 +1,6 @@
1
- import { stat } from "node:fs/promises"
2
1
  import type { Tool } from "#minicore"
3
2
  import { LIMITS } from "../constants.ts"
4
- import { atomicWriteText } from "../lib/atomic-write.ts"
5
- import { assertSafeWriteTarget, resolveSafePath, safeReadFile } from "../lib/safe-open.ts"
6
- import { contextUnrestricted, requireToolCwd } from "./context.ts"
3
+ import { commitSafeTextEdit, readSafeTextForEdit } from "./context.ts"
7
4
  import { flexibleMatch } from "./edit.ts"
8
5
 
9
6
  // Apply SEARCH/REPLACE block (a la Aider) ke file. Search block harus match
@@ -39,21 +36,11 @@ export const applyPatchTool: Tool = {
39
36
  async execute({ path, patches }, ctx) {
40
37
  ctx.signal.throwIfAborted()
41
38
  const p = path as string
42
- const root = requireToolCwd(ctx)
43
- const relaxed = contextUnrestricted(ctx)
44
- // Verifikasi path terpusat (logis + target nyata) — detail di safe-open.ts.
45
- const { abs, real: realAbs } = await resolveSafePath(p, root, relaxed)
46
- // Tolak menimpa symlink final (swap antara cek dan tulis gagal tutup).
47
- await assertSafeWriteTarget(abs, root, relaxed)
48
- const st = await stat(realAbs).catch(() => null)
49
- if (!st) throw new Error(`file not found: ${p}`)
50
- if (st.size > LIMITS.READ_FILE_MAX_BYTES) throw new Error(`file too large: ${p} (${st.size})`)
51
-
52
- // Pakai safeReadFile (O_NOFOLLOW) agar swap symlink di antara cek dan baca gagal ELOOP.
53
- let content = await safeReadFile(abs, root, relaxed)
39
+ let { root, realAbs, content } = await readSafeTextForEdit(p, ctx)
54
40
  const patchList = patches as { search: string; replace: string }[]
55
41
  if (patchList.length > 50) throw new Error(`too many patches: ${patchList.length} (max 50)`)
56
42
  const applied: string[] = []
43
+ let changedCount = 0
57
44
 
58
45
  for (let i = 0; i < patchList.length; i++) {
59
46
  ctx.signal.throwIfAborted()
@@ -76,13 +63,18 @@ export const applyPatchTool: Tool = {
76
63
  throw new Error(`result too large after patch[${i}]: ${content.length} chars (max 5M)`)
77
64
  const note = match.mode !== "exact" ? ` (${match.mode} match)` : ""
78
65
  applied.push(`[${i}] replaced ${oldS.length} → ${newS.length} chars${note}`)
66
+ changedCount++
79
67
  }
80
68
 
81
- if (content.length > LIMITS.WRITE_FILE_MAX_CHARS)
82
- throw new Error(`result too large: ${content.length} chars (max 5M)`)
83
-
84
- await atomicWriteText(realAbs, content)
69
+ if (changedCount === 0) {
70
+ return `no changes written to ${realAbs} (all patches skipped):\n${applied.join("\n")}`
71
+ }
85
72
 
86
- return `applied ${applied.length} patch(es) to ${realAbs}:\n${applied.join("\n")}`
73
+ return await commitSafeTextEdit(
74
+ realAbs,
75
+ root,
76
+ content,
77
+ `applied ${applied.length} patch(es) to ${realAbs}:\n${applied.join("\n")}`,
78
+ )
87
79
  },
88
80
  }
@@ -1,10 +1,8 @@
1
1
  import type { FileHandle } from "node:fs/promises"
2
- import { isAbsolute, resolve } from "node:path"
3
2
  import type { Tool } from "#minicore"
4
3
  import { LIMITS } from "../constants.ts"
5
- import { safeOpenRead } from "../lib/safe-open.ts"
6
4
  import { scrubSecrets } from "../policy/scrub.ts"
7
- import { contextUnrestricted, requireToolCwd } from "./context.ts"
5
+ import { openSafeToolReadHandle, sliceSafeChars } from "./context.ts"
8
6
 
9
7
  // defense-in-depth: also jail inside tool (permission layer is primary)
10
8
 
@@ -52,7 +50,7 @@ export function formatLines(
52
50
  const n = String(from + i).padStart(width, " ")
53
51
  const capped =
54
52
  line.length > LIMITS.READ_FILE_MAX_LINE_CHARS
55
- ? `${line.slice(0, LIMITS.READ_FILE_MAX_LINE_CHARS)}… [line truncated]`
53
+ ? `${sliceSafeChars(line, LIMITS.READ_FILE_MAX_LINE_CHARS)}… [line truncated]`
56
54
  : line
57
55
  return `${n}: ${capped}`
58
56
  })
@@ -73,6 +71,7 @@ async function formatHandleRange(
73
71
  from: number,
74
72
  limit: number,
75
73
  signal: AbortSignal,
74
+ fileLabel: string,
76
75
  ): Promise<string> {
77
76
  const chunk = Buffer.alloc(64 * 1024)
78
77
  const decoder = new TextDecoder()
@@ -83,6 +82,7 @@ async function formatHandleRange(
83
82
  let totalLines = 0
84
83
  let position = 0
85
84
  let sawBytes = false
85
+ let checkedBinary = false
86
86
  let endedWithNewline = false
87
87
 
88
88
  const appendSegment = (segment: string): void => {
@@ -117,6 +117,12 @@ async function formatHandleRange(
117
117
  const { bytesRead } = await handle.read(chunk, 0, chunk.length, position)
118
118
  if (bytesRead === 0) break
119
119
  sawBytes = true
120
+ if (!checkedBinary) {
121
+ checkedBinary = true
122
+ if (chunk.subarray(0, Math.min(bytesRead, 8192)).includes(0)) {
123
+ throw new Error(`cannot read binary file (NUL byte detected): ${fileLabel}`)
124
+ }
125
+ }
120
126
  position += bytesRead
121
127
  consume(decoder.decode(chunk.subarray(0, bytesRead), { stream: true }))
122
128
  }
@@ -135,7 +141,7 @@ async function formatHandleRange(
135
141
  .map((raw, index) => {
136
142
  const capped =
137
143
  raw.length > LIMITS.READ_FILE_MAX_LINE_CHARS
138
- ? `${raw.slice(0, LIMITS.READ_FILE_MAX_LINE_CHARS)}… [line truncated]`
144
+ ? `${sliceSafeChars(raw, LIMITS.READ_FILE_MAX_LINE_CHARS)}… [line truncated]`
139
145
  : raw
140
146
  return `${String(from + index).padStart(width, " ")}: ${capped}`
141
147
  })
@@ -167,26 +173,9 @@ export const readFileTool: Tool = {
167
173
  async execute({ path, offset, limit }, ctx) {
168
174
  ctx.signal.throwIfAborted()
169
175
  const p = path as string
170
- const root = requireToolCwd(ctx)
171
- const relaxed = contextUnrestricted(ctx)
172
- const abs = isAbsolute(p) ? resolve(p) : resolve(root, p)
173
- // Semua verifikasi path (jail + sensitif + O_NOFOLLOW) terjadi di SATU
174
- // titik saat open — detail di safe-open.ts. Tidak ada resolve/stat
175
- // terpisah: handle dipakai untuk stat (cap ukuran) lalu baca.
176
- let handle: Awaited<ReturnType<typeof safeOpenRead>>["handle"]
177
- try {
178
- ;({ handle } = await safeOpenRead(abs, root, relaxed))
179
- } catch (e) {
180
- // ENOENT → pesan seragam; sisanya (jail/sensitif/ELOOP/raw IO) apa adanya
181
- const msg = (e as Error).message ?? ""
182
- if ((e as NodeJS.ErrnoException).code === "ENOENT" || msg.includes("ENOENT"))
183
- throw new Error(`file not found: ${p}`)
184
- throw e
185
- }
176
+ const { handle, st } = await openSafeToolReadHandle(p, ctx)
186
177
  let raw: string
187
178
  try {
188
- const st = await handle.stat().catch(() => null)
189
- if (!st) throw new Error(`file not found: ${p}`)
190
179
  if (st.isDirectory()) throw new Error(`path is a directory, not a file: ${p}`)
191
180
 
192
181
  const paged = offset != null || limit != null
@@ -209,9 +198,13 @@ export const readFileTool: Tool = {
209
198
  const pageLimit = Number.isFinite(rawLimit)
210
199
  ? Math.min(Math.max(1, Math.floor(rawLimit)), LIMITS.READ_FILE_MAX_LINE_LIMIT)
211
200
  : LIMITS.READ_FILE_DEFAULT_LINE_LIMIT
212
- return scrubSecrets(await formatHandleRange(handle, from, pageLimit, ctx.signal))
201
+ return scrubSecrets(await formatHandleRange(handle, from, pageLimit, ctx.signal, p))
202
+ }
203
+ const buf = await handle.readFile()
204
+ if (buf.subarray(0, 8192).includes(0)) {
205
+ throw new Error(`cannot read binary file (NUL byte detected): ${p}`)
213
206
  }
214
- raw = await handle.readFile("utf8")
207
+ raw = buf.toString("utf8")
215
208
  } finally {
216
209
  await handle.close().catch(() => {})
217
210
  }
@@ -1,9 +1,7 @@
1
- import { isAbsolute, resolve } from "node:path"
2
1
  import type { Tool } from "#minicore"
3
2
  import { LIMITS } from "../constants.ts"
4
- import { safeOpenRead } from "../lib/safe-open.ts"
5
3
  import { estimateImageTokens } from "../policy/context.ts"
6
- import { contextUnrestricted, requireToolCwd } from "./context.ts"
4
+ import { openSafeToolReadHandle } from "./context.ts"
7
5
 
8
6
  // Batas b64 = batas truncate kernel yang sebenarnya: toolResultMaxTokens
9
7
  // (default 4096) × DEFAULT_CHARS_PER_TOKEN (4) = 16.384 chars, dengan margin
@@ -11,6 +9,35 @@ import { contextUnrestricted, requireToolCwd } from "./context.ts"
11
9
  // vendor tokens.ts — angka lain (BASH_OUTPUT×5) melanggar intent anti-korup.
12
10
  const IMAGE_B64_MAX_CHARS = 4096 * 4 - 200
13
11
 
12
+ function detectImageMime(ext: string, buf: Buffer): string {
13
+ if (ext === "jpg" || ext === "jpeg") return "image/jpeg"
14
+ if (ext === "webp") return "image/webp"
15
+ if (ext === "gif") return "image/gif"
16
+ if (ext === "png") return "image/png"
17
+ // Fallback ke magic bytes bila ekstensi tidak dikenal/absen.
18
+ if (buf.length >= 8 && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) {
19
+ return "image/png"
20
+ }
21
+ if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) {
22
+ return "image/jpeg"
23
+ }
24
+ if (
25
+ buf.length >= 6 &&
26
+ (buf.subarray(0, 6).toString("ascii") === "GIF87a" ||
27
+ buf.subarray(0, 6).toString("ascii") === "GIF89a")
28
+ ) {
29
+ return "image/gif"
30
+ }
31
+ if (
32
+ buf.length >= 12 &&
33
+ buf.subarray(0, 4).toString("ascii") === "RIFF" &&
34
+ buf.subarray(8, 12).toString("ascii") === "WEBP"
35
+ ) {
36
+ return "image/webp"
37
+ }
38
+ return "image/png"
39
+ }
40
+
14
41
  export const readImageTool: Tool = {
15
42
  name: "read_image",
16
43
  description:
@@ -18,7 +45,7 @@ export const readImageTool: Tool = {
18
45
  parameters: {
19
46
  type: "object",
20
47
  properties: {
21
- path: { type: "string", description: "path image relatif" },
48
+ path: { type: "string", description: "relative image file path" },
22
49
  },
23
50
  required: ["path"],
24
51
  additionalProperties: false,
@@ -26,27 +53,9 @@ export const readImageTool: Tool = {
26
53
  async execute({ path }, ctx) {
27
54
  ctx.signal.throwIfAborted()
28
55
  const p = path as string
29
- const root = requireToolCwd(ctx)
30
- const relaxed = contextUnrestricted(ctx)
31
- const abs = isAbsolute(p) ? resolve(p) : resolve(root, p)
32
- // TOCTOU-safe: safeOpenRead = realpath(abs) → cek jail+sensitif di dalam
33
- // root → open(preReal, O_NOFOLLOW). Bukan open(abs) yang bisa di-swap jadi
34
- // symlink luar di antara cek dan open — semua verifikasi ada di titik ini.
35
- let handle: Awaited<ReturnType<typeof safeOpenRead>>["handle"]
36
- try {
37
- ;({ handle } = await safeOpenRead(abs, root, relaxed))
38
- } catch (e) {
39
- // ENOENT → pesan seragam; sisanya (jail/sensitif/ELOOP/raw IO) apa adanya
40
- const msg = (e as Error).message ?? ""
41
- if ((e as NodeJS.ErrnoException).code === "ENOENT" || msg.includes("ENOENT"))
42
- throw new Error(`file not found: ${p}`)
43
- throw e
44
- }
56
+ const { handle, st } = await openSafeToolReadHandle(p, ctx)
45
57
  let buf: Buffer
46
- let st: { size: number } | null = null
47
58
  try {
48
- st = await handle.stat().catch(() => null)
49
- if (!st) throw new Error(`file not found: ${p}`)
50
59
  if (st.size > LIMITS.READ_FILE_MAX_BYTES)
51
60
  throw new Error(`image too large: ${st.size} bytes (max 2M)`)
52
61
  buf = await handle.readFile()
@@ -59,21 +68,14 @@ export const readImageTool: Tool = {
59
68
  const estB64 = Math.ceil((buf.byteLength * 4) / 3) + 30
60
69
  if (estB64 > IMAGE_B64_MAX_CHARS)
61
70
  throw new Error(
62
- `image too large: base64 ~${estB64} chars exceeds the ${IMAGE_B64_MAX_CHARS}-char context limit — compress first (e.g. via code_run sharp)`,
71
+ `image too large: base64 ~${estB64} chars exceeds the ${IMAGE_B64_MAX_CHARS}-char context limit — compress or resize it first`,
63
72
  )
64
73
  } finally {
65
74
  await handle.close().catch(() => {})
66
75
  }
67
76
  const b64 = buf.toString("base64")
68
- const ext = p.split(".").pop()?.toLowerCase() ?? "png"
69
- const mime =
70
- ext === "jpg" || ext === "jpeg"
71
- ? "image/jpeg"
72
- : ext === "webp"
73
- ? "image/webp"
74
- : ext === "gif"
75
- ? "image/gif"
76
- : "image/png"
77
+ const ext = p.split(".").pop()?.toLowerCase() ?? ""
78
+ const mime = detectImageMime(ext, buf)
77
79
  const tokens = estimateImageTokens(buf.byteLength)
78
80
  // S4 — kirim utuh + laporkan bytes (dulu slice 200k diam-diam → gambar korup).
79
81
  // File sudah di-cap (READ_FILE_MAX_BYTES + IMAGE_B64_MAX_CHARS) di atas,
@@ -11,14 +11,32 @@ export interface SubmittedResult {
11
11
  at: number
12
12
  }
13
13
 
14
- let last: SubmittedResult | null = null
14
+ const DEFAULT_SESSION_KEY = "__default__"
15
+ const submittedBySession = new Map<string, SubmittedResult>()
16
+ let latestSessionKey: string | null = null
15
17
 
16
- export function getSubmittedResult(): SubmittedResult | null {
17
- return last
18
+ const scopeKey = (sessionId?: string): string =>
19
+ typeof sessionId === "string" && sessionId.length > 0 ? sessionId : DEFAULT_SESSION_KEY
20
+
21
+ export function getSubmittedResult(sessionId?: string): SubmittedResult | null {
22
+ if (sessionId !== undefined) {
23
+ return submittedBySession.get(scopeKey(sessionId)) ?? null
24
+ }
25
+ if (latestSessionKey !== null && submittedBySession.has(latestSessionKey)) {
26
+ return submittedBySession.get(latestSessionKey) ?? null
27
+ }
28
+ return submittedBySession.get(DEFAULT_SESSION_KEY) ?? null
18
29
  }
19
30
 
20
- export function clearSubmittedResult(): void {
21
- last = null
31
+ export function clearSubmittedResult(sessionId?: string): void {
32
+ if (sessionId !== undefined) {
33
+ const key = scopeKey(sessionId)
34
+ submittedBySession.delete(key)
35
+ if (latestSessionKey === key) latestSessionKey = null
36
+ return
37
+ }
38
+ submittedBySession.clear()
39
+ latestSessionKey = null
22
40
  }
23
41
 
24
42
  export const submitResultTool: Tool = {
@@ -30,9 +48,10 @@ export const submitResultTool: Tool = {
30
48
  properties: {
31
49
  result: {
32
50
  type: "object",
33
- description: "hasil akhir terstruktur (object JSON, bukan string)",
51
+ additionalProperties: true,
52
+ description: "final structured result (JSON object, not string)",
34
53
  },
35
- summary: { type: "string", description: "ringkasan satu baris untuk log" },
54
+ summary: { type: "string", description: "one-line summary for logs" },
36
55
  },
37
56
  required: ["result"],
38
57
  additionalProperties: false,
@@ -42,7 +61,9 @@ export const submitResultTool: Tool = {
42
61
  if (!result || typeof result !== "object" || Array.isArray(result))
43
62
  throw new Error("result must be a JSON object")
44
63
  const s = typeof summary === "string" ? summary.slice(0, 300) : undefined
45
- last = { result, ...(s ? { summary: s } : {}), at: Date.now() }
64
+ const sid = scopeKey((ctx as unknown as { sessionId?: string }).sessionId)
65
+ submittedBySession.set(sid, { result, ...(s ? { summary: s } : {}), at: Date.now() })
66
+ latestSessionKey = sid
46
67
  const bytes = JSON.stringify(result).length
47
68
  return `submitted (${bytes} bytes)${s ? `: ${s}` : ""}`
48
69
  },
package/src/tools/task.ts CHANGED
@@ -43,7 +43,7 @@ const pool = new Pool(LIMITS.SUB_AGENT_POOL_SIZE)
43
43
 
44
44
  // Harness-P2: scope read-only bersama untuk sub-agen explore DAN sesi utama
45
45
  // (--tool-scope explore). Satu daftar, satu makna: scoping per fase (pelajaran
46
- // Vercel: tool minimum per fase, bukan semua 37 sekaligus). Diuji oleh
46
+ // Vercel: tool minimum per fase, bukan semua 38 sekaligus). Diuji oleh
47
47
  // test/harness-p2 + audit invariant bench/harness-audit.
48
48
  // [Fase 2 / TOOL-01] Diimpor dari registry kontrak tool — dulu daftar manual
49
49
  // di sini yang harus disinkronkan dengan tool-layer.
@@ -84,6 +84,8 @@ export interface SubAgentSpec {
84
84
  sessionId: string
85
85
  parentSessionId?: string
86
86
  }
87
+ /** Canonical session id of this child sub-agent (passed to ToolContext). */
88
+ sessionId?: string
87
89
  /**
88
90
  * Model warisan sesi parent (audit #14): anak jalan di model yang sama
89
91
  * dengan parent — tanpa ini anak diam-diam memakai default router yang
@@ -91,11 +93,17 @@ export interface SubAgentSpec {
91
93
  * (live, ikut /model mid-session); opsional agar factory lama tetap jalan.
92
94
  */
93
95
  model?: string
94
- /** [Fase 7 / LOOP-INV-15] Konfigurasi NoProgressDetector anak. Default =
95
- * aktif (createMinicodeSession aktif secara default); field ini
96
- * memungkinkan factory menurunkan ambang thrashing read-only karena anak
97
- * explore/plan memang read-only (stagnasi = perulangan grep/glob). */
96
+ /**
97
+ * [Fase 7 / LOOP-INV-15] Konfigurasi NoProgressDetector anak. Default =
98
+ * aktif (createMinicodeSession aktif secara default); field ini
99
+ * memungkinkan factory menurunkan ambang thrashing read-only karena anak
100
+ * explore/plan memang read-only (stagnasi = perulangan grep/glob).
101
+ */
98
102
  noProgress?: NoProgressOptions
103
+ /** Warisan pengetatan bash-allowlist dari parent saat restrictBash aktif. */
104
+ restrictBash?: boolean
105
+ /** Warisan opt-in local config dari parent (fail-closed default false). */
106
+ allowLocalConfig?: boolean
99
107
  }
100
108
 
101
109
  /** Subset struktural sesi yang dibutuhkan tool ini — tanpa tipe lapisan app. */
@@ -138,8 +146,9 @@ export function clearSubAgentSessionFactory(): void {
138
146
  parentRouting = {}
139
147
  childExecutionRunner = undefined
140
148
  parentRunIdFn = () => null
141
- // P12 S2.2 — reset WorkMode induk agar test terisolasi (pola reset lain).
149
+ // P12 S2.2 — reset WorkMode & governance induk agar test terisolasi.
142
150
  subAgentWorkModeFn = () => undefined
151
+ subAgentGovernanceFn = () => ({})
143
152
  }
144
153
 
145
154
  /**
@@ -193,12 +202,33 @@ export function setSubAgentWorkMode(fn: () => WorkMode | undefined): void {
193
202
  /** WorkMode induk saat ini (live), undefined = EXECUTE (perilaku lama). */
194
203
  export function subAgentWorkMode(): WorkMode {
195
204
  try {
196
- return subAgentWorkModeFn() ?? "EXECUTE"
205
+ const v = subAgentWorkModeFn()
206
+ return v === undefined ? "EXECUTE" : v === "EXECUTE" ? "EXECUTE" : "DISCUSS"
197
207
  } catch {
198
208
  return "EXECUTE"
199
209
  }
200
210
  }
201
211
 
212
+ export interface SubAgentGovernance {
213
+ readonly restrictBash?: boolean
214
+ readonly allowLocalConfig?: boolean
215
+ }
216
+
217
+ let subAgentGovernanceFn: () => SubAgentGovernance = () => ({})
218
+
219
+ /** Suntikkan governance live dari composition root agar anak mewarisi restrictBash & allowLocalConfig. */
220
+ export function setSubAgentGovernance(fn: () => SubAgentGovernance): void {
221
+ subAgentGovernanceFn = fn
222
+ }
223
+
224
+ export function subAgentGovernance(): SubAgentGovernance {
225
+ try {
226
+ return subAgentGovernanceFn() ?? {}
227
+ } catch {
228
+ return {}
229
+ }
230
+ }
231
+
202
232
  export function setSubAgentParentRouting(c: SubAgentParentRouting): void {
203
233
  parentRouting = {
204
234
  ...(c.rateLimiter ? { rateLimiter: c.rateLimiter } : {}),
@@ -209,8 +239,14 @@ export function setSubAgentParentRouting(c: SubAgentParentRouting): void {
209
239
  }
210
240
  }
211
241
 
212
- async function getProvider(overrides: SubAgentParentRouting = parentRouting) {
213
- const cfg = await loadConfig()
242
+ async function getProvider(
243
+ overrides: SubAgentParentRouting = parentRouting,
244
+ cfgOpts?: { cwd?: string; allowLocalConfig?: boolean },
245
+ ) {
246
+ const cfg = await loadConfig(
247
+ cfgOpts?.cwd,
248
+ cfgOpts?.allowLocalConfig ? { allowLocal: true } : undefined,
249
+ )
214
250
  // Async: sub-agent juga harus bisa memakai provider OAuth milik parent.
215
251
  const providers = await buildProviderListAsync(cfg)
216
252
  if (providers.length === 0) {
@@ -336,7 +372,7 @@ export const delegateTaskTool: Tool = {
336
372
  // sesi utama (tool-layer), jadi anak memakai set yang sama — tanpa
337
373
  // menduplikasi daftar.
338
374
  const subToolsFiltered =
339
- childWorkMode === "DISCUSS" || childWorkMode === "PLAN"
375
+ childWorkMode === "DISCUSS"
340
376
  ? subTools.filter((t) => EXPLORE_TOOL_NAMES.includes(t.name))
341
377
  : subTools
342
378
  // F-07: anak tidak punya bash_output/bash_kill (diamputasi di atas),
@@ -360,7 +396,11 @@ export const delegateTaskTool: Tool = {
360
396
  // Child tools are wrapped with canonical P2.10 evidence after the child
361
397
  // identity and authoritative domain exist (see below).
362
398
  const parentCwd = requireToolCwd(ctx)
363
- const parentId = todoSession.id || "main"
399
+ const ctxSessionId = (ctx as unknown as { sessionId?: unknown })?.sessionId
400
+ const parentId =
401
+ (typeof ctxSessionId === "string" && ctxSessionId ? ctxSessionId : "") ||
402
+ todoSession.id ||
403
+ "main"
364
404
  // P2.9: id anak = identitas Session KANONIK (128-bit). Id P1 lawas
365
405
  // `sub_<8hex>` (32-bit) tidak cukup untuk durable authority; prefix `sub_`
366
406
  // dipertahankan agar jurnal/presentasi/diagnostik tetap kompatibel.
@@ -455,14 +495,24 @@ export const delegateTaskTool: Tool = {
455
495
  }
456
496
  // P2.10 canonical coverage for plain child tools. Delegate itself keeps
457
497
  // its explicit parent-side intent; dotted tools are excluded by design.
458
- const verifiedSubTools = subToolsGuarded.map((tool) =>
459
- withEvidence(tool, {
498
+ // Child `todo_read` tetap terikat ke namespace `parentId` agar subagent
499
+ // melihat daftar tugas induk meskipun sesi anak punya `sessionId: childId`.
500
+ const verifiedSubTools = subToolsGuarded.map((tool) => {
501
+ const bound =
502
+ tool.name === "todo_read"
503
+ ? {
504
+ ...tool,
505
+ execute: (args: unknown, subCtx: import("#minicore").ToolContext) =>
506
+ tool.execute(args, { ...subCtx, sessionId: parentId }),
507
+ }
508
+ : tool
509
+ return withEvidence(bound, {
460
510
  sessionId: childId,
461
511
  threadId: DEFAULT_THREAD_ID,
462
512
  cwd: parentCwd,
463
513
  childOf: parentId,
464
- }),
465
- )
514
+ })
515
+ })
466
516
  const intent: EffectIntentResult = await persistEffectIntent({
467
517
  sessionId: parentId,
468
518
  threadId: DEFAULT_THREAD_ID,
@@ -501,24 +551,30 @@ export const delegateTaskTool: Tool = {
501
551
  observedSummary = "[sub-agent error] session factory not configured"
502
552
  return observedSummary
503
553
  }
554
+ const gov = subAgentGovernance()
504
555
  let provider: Awaited<ReturnType<typeof getProvider>>
505
556
  try {
506
- provider = await getProvider()
557
+ provider = await getProvider(parentRouting, {
558
+ cwd: parentCwd,
559
+ allowLocalConfig: gov.allowLocalConfig === true,
560
+ })
507
561
  } catch (e) {
508
562
  observedSummary = `[sub-agent error] provider: ${(e as Error).message}`
509
563
  return observedSummary
510
564
  }
511
-
512
565
  const session = await factory({
513
566
  provider,
514
567
  tools: verifiedSubTools,
515
568
  cwd: parentCwd,
569
+ sessionId: childId,
516
570
  // Parent allowlist → anak allowlist (lihat komentar tipe di atas).
517
571
  permissionMode: parentMode === "allowlist" ? "allowlist" : "auto",
518
572
  // P12 S2.2 — child mewarisi WorkMode induk (ceiling WorkMode anak
519
573
  // dipasang di createMinicodeSession oleh factory). EXECUTE = perilaku
520
574
  // lama (tanpa ceiling tambahan).
521
575
  workMode: childWorkMode,
576
+ ...(gov.restrictBash ? { restrictBash: true } : {}),
577
+ ...(gov.allowLocalConfig ? { allowLocalConfig: true } : {}),
522
578
  maxSteps: cap,
523
579
  timeoutMs: LIMITS.SUB_AGENT_TIMEOUT_MS,
524
580
  // [Fase 7 / LOOP-INV-15] NoProgressDetector anak EKSPLISIT (bukan
@@ -575,6 +631,7 @@ export const delegateTaskTool: Tool = {
575
631
  }
576
632
  const offUsage = session.events.on("provider:extension", (e) => {
577
633
  try {
634
+ tagForwarded(e)
578
635
  ctx.emit(e)
579
636
  } catch {}
580
637
  })