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.
- package/README.md +1 -1
- package/cli/args.ts +184 -57
- package/cli/bootstrap/presentation-bridge.ts +383 -0
- package/cli/commands/acp.ts +45 -29
- package/cli/commands/auth.ts +17 -17
- package/cli/commands/config.ts +65 -66
- package/cli/commands/daemon.ts +44 -16
- package/cli/commands/doctor.ts +18 -15
- package/cli/commands/exec.ts +41 -89
- package/cli/commands/mcp.ts +25 -8
- package/cli/commands/memory.ts +16 -24
- package/cli/commands/openwork.ts +6 -2
- package/cli/commands/pricing.ts +14 -12
- package/cli/commands/providers.ts +36 -57
- package/cli/commands/sessions.ts +24 -18
- package/cli/commands/skills.ts +33 -18
- package/cli/commands/stats.ts +15 -30
- package/cli/commands.ts +73 -44
- package/cli/context-command-run.ts +30 -18
- package/cli/index.ts +51 -100
- package/cli/model-manager.ts +7 -2
- package/cli/provider-manager.ts +33 -18
- package/cli/router.ts +41 -12
- package/cli/setup.ts +241 -485
- package/cli/tui.ts +303 -100
- package/docs/TERMINAL_CONTRACT.md +258 -73
- package/docs/UI_RENDER_PIPELINE.md +9 -1
- package/docs/agents.md +2 -2
- package/docs/architecture.md +17 -32
- package/docs/choosing-mode.md +7 -9
- package/docs/cli.md +3 -5
- package/docs/environment.md +1 -2
- package/docs/policy-sandbox.md +3 -3
- package/docs/repl.md +2 -2
- package/docs/tools.md +1 -1
- package/package.json +1 -1
- package/src/app/mentions.ts +60 -13
- package/src/app/rag-layer.ts +17 -20
- package/src/app/session.ts +144 -68
- package/src/app/tool-layer.ts +38 -16
- package/src/config.ts +64 -104
- package/src/constants.ts +4 -6
- package/src/daemon/capability.ts +8 -1
- package/src/daemon/control.ts +3 -2
- package/src/daemon/server.ts +57 -0
- package/src/hooks/run.ts +73 -41
- package/src/lib/atomic-write.ts +31 -59
- package/src/lib/db-path.ts +47 -0
- package/src/lib/process-tree.ts +62 -0
- package/src/lib/public-http.ts +88 -23
- package/src/lib/trusted-exec.ts +48 -1
- package/src/lsp/client.ts +62 -17
- package/src/mcp/client.ts +85 -38
- package/src/mcp/http-transport.ts +28 -16
- package/src/mcp/transport.ts +42 -6
- package/src/memory/files.ts +164 -134
- package/src/memory/vector.ts +371 -420
- package/src/policy/approval-binding.ts +122 -45
- package/src/policy/bash-guard.ts +18 -7
- package/src/policy/compaction.ts +51 -18
- package/src/policy/context-window.ts +31 -8
- package/src/policy/context.ts +62 -36
- package/src/policy/executor.ts +17 -7
- package/src/policy/jail.ts +6 -8
- package/src/policy/microcompact.ts +4 -3
- package/src/policy/no-progress.ts +103 -22
- package/src/policy/permission.ts +36 -12
- package/src/policy/tool-contract.ts +74 -416
- package/src/policy/usage.ts +24 -2
- package/src/policy/verifier.ts +50 -2
- package/src/policy/work-mode.ts +28 -54
- package/src/presentation/adapter.ts +24 -16
- package/src/providers/anthropic.ts +16 -5
- package/src/providers/provision.ts +6 -56
- package/src/providers/responses.ts +38 -7
- package/src/providers/sse-bounds.ts +6 -4
- package/src/runtime/execution-journal.ts +4 -29
- package/src/sandbox/docker.ts +58 -34
- package/src/sandbox/mask.ts +157 -0
- package/src/sandbox/os.ts +107 -73
- package/src/session/authority.ts +29 -10
- package/src/session/context-projection.ts +6 -5
- package/src/session/db/runs.ts +397 -0
- package/src/session/db/schema.ts +358 -0
- package/src/session/open-work.ts +26 -3
- package/src/session/persistence.ts +74 -998
- package/src/session/verification.ts +170 -20
- package/src/skills/loader.ts +31 -16
- package/src/task/db/schema.ts +325 -0
- package/src/task/db/types.ts +269 -0
- package/src/task/production-scheduler.ts +13 -1
- package/src/task/store.ts +92 -1021
- package/src/telemetry/trace.ts +27 -0
- package/src/tools/ask_user.ts +1 -13
- package/src/tools/bash.ts +27 -92
- package/src/tools/code_run.ts +1 -1
- package/src/tools/context.ts +133 -0
- package/src/tools/delete_file.ts +3 -2
- package/src/tools/edit.ts +37 -72
- package/src/tools/git.ts +86 -9
- package/src/tools/glob.ts +26 -51
- package/src/tools/grep.ts +67 -57
- package/src/tools/hashline.ts +4 -0
- package/src/tools/lsp.ts +11 -8
- package/src/tools/mcp_call.ts +9 -6
- package/src/tools/memory.ts +56 -33
- package/src/tools/move_file.ts +36 -10
- package/src/tools/patch.ts +13 -21
- package/src/tools/read_file.ts +18 -25
- package/src/tools/read_image.ts +35 -33
- package/src/tools/submit_result.ts +29 -8
- package/src/tools/task.ts +74 -17
- package/src/tools/todo.ts +181 -74
- package/src/tools/web_fetch.ts +42 -2
- package/src/tools/web_search.ts +47 -8
- package/src/ui/approval/prompt.ts +206 -47
- package/src/ui/assistant/turn-status.ts +14 -5
- package/src/ui/footer.ts +4 -4
- package/src/ui/i18n/en.ts +47 -23
- package/src/ui/i18n/id.ts +76 -51
- package/src/ui/input/input.ts +4 -3
- package/src/ui/input/prompt-engine.ts +35 -5
- package/src/ui/render/activity-panel.ts +4 -2
- package/src/ui/render/hint.ts +7 -4
- package/src/ui/render/list.ts +32 -0
- package/src/ui/render/markdown.ts +6 -3
- package/src/ui/render/notice.ts +19 -0
- package/src/ui/render/table-grid.ts +7 -8
- package/src/ui/render/theme.ts +113 -39
- package/src/ui/runtime/screen.ts +74 -10
- package/src/ui/runtime/spinner.ts +19 -6
- package/src/ui/screens/dialog.ts +19 -1
- package/src/ui/screens/form.ts +80 -35
- package/src/ui/screens/model-manager.ts +82 -61
- package/src/ui/screens/output-window.ts +263 -0
- package/src/ui/screens/picker.ts +94 -81
- package/src/ui/screens/provider-manager.ts +100 -69
- package/src/ui/screens/wizard.ts +117 -28
- package/src/ui/tui/app.ts +196 -33
- package/src/ui/tui/transcript.ts +158 -25
- package/vendor/minicore/src/core/executor.ts +2 -0
- package/vendor/minicore/src/core/loop.ts +17 -6
- package/vendor/minicore/src/core/session.ts +3 -0
- package/vendor/minicore/src/core/tool.ts +1 -0
- package/vendor/minicore/src/providers/openai-compat.ts +35 -19
package/src/tools/move_file.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
|
-
import { mkdir, rename, stat } from "node:fs/promises"
|
|
2
|
-
import { dirname } from "node:path"
|
|
1
|
+
import { lstat, mkdir, rename, stat } from "node:fs/promises"
|
|
2
|
+
import { dirname, extname } from "node:path"
|
|
3
3
|
import type { Tool } from "#minicore"
|
|
4
|
-
import {
|
|
4
|
+
import { LIMITS } from "../constants.ts"
|
|
5
|
+
import { assertSafeWriteTarget, resolveSafePath, safeReadFile } from "../lib/safe-open.ts"
|
|
5
6
|
import { trashFile } from "../lib/trash.ts"
|
|
7
|
+
import { getConfiguredExts } from "../lsp/client.ts"
|
|
8
|
+
import { appendLspDiagnostics } from "../policy/verifier.ts"
|
|
6
9
|
import { contextUnrestricted, requireToolCwd } from "./context.ts"
|
|
7
10
|
|
|
8
11
|
export const moveFileTool: Tool = {
|
|
@@ -31,19 +34,42 @@ export const moveFileTool: Tool = {
|
|
|
31
34
|
const { abs: absFrom, real: realFrom } = await resolveSafePath(f, root, relaxed)
|
|
32
35
|
const st = await stat(realFrom).catch(() => null)
|
|
33
36
|
if (!st) throw new Error(`source not found: ${f}`)
|
|
34
|
-
const { abs: absTo } = await resolveSafePath(t, root, relaxed)
|
|
37
|
+
const { abs: absTo, real: realTo } = await resolveSafePath(t, root, relaxed)
|
|
38
|
+
await assertSafeWriteTarget(absTo, root, relaxed)
|
|
35
39
|
await mkdir(dirname(absTo), { recursive: true, mode: 0o700 }).catch(() => {})
|
|
40
|
+
|
|
41
|
+
// Deteksi rename case-only (mis. foo.ts → Foo.ts di Windows NTFS) atau
|
|
42
|
+
// alias path ke berkas fisik yang sama sebelum trashFile, agar sumber
|
|
43
|
+
// tidak dipindahkan ke .trash sebelum rename dijalankan.
|
|
44
|
+
const fromLstat = await lstat(absFrom, { bigint: true }).catch(() => null)
|
|
45
|
+
const destLstat = await lstat(absTo, { bigint: true }).catch(() => null)
|
|
46
|
+
const sameInode =
|
|
47
|
+
fromLstat !== null &&
|
|
48
|
+
destLstat !== null &&
|
|
49
|
+
fromLstat.ino !== 0n &&
|
|
50
|
+
fromLstat.dev === destLstat.dev &&
|
|
51
|
+
fromLstat.ino === destLstat.ino
|
|
52
|
+
const sameWinCasePath =
|
|
53
|
+
process.platform === "win32" &&
|
|
54
|
+
absFrom.toLowerCase() === absTo.toLowerCase() &&
|
|
55
|
+
!destLstat?.isSymbolicLink()
|
|
56
|
+
const sameFileRename = sameInode || sameWinCasePath
|
|
57
|
+
|
|
36
58
|
// S3 — dest yang sudah ada dibackup ke trash dulu (jangan timpa diam-diam).
|
|
37
|
-
//
|
|
38
|
-
// realpath ulang di sini.
|
|
59
|
+
// Pakai lstat agar symlink tujuan di-trash sebagai entry link, bukan targetnya.
|
|
39
60
|
let backup = ""
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
if (destStat.isDirectory()) throw new Error(`destination is a directory: ${t}`)
|
|
61
|
+
if (destLstat && !sameFileRename) {
|
|
62
|
+
if (destLstat.isDirectory()) throw new Error(`destination is a directory: ${t}`)
|
|
43
63
|
const trashed = await trashFile(root, absTo)
|
|
44
64
|
backup = ` (previous dest backed up to ${trashed})`
|
|
45
65
|
}
|
|
46
66
|
await rename(absFrom, absTo)
|
|
47
|
-
|
|
67
|
+
const base = `moved ${f} -> ${t}${backup}`
|
|
68
|
+
if (!st.isFile() || st.size > LIMITS.READ_FILE_MAX_BYTES) return base
|
|
69
|
+
const ext = extname(absTo).toLowerCase()
|
|
70
|
+
if (!getConfiguredExts().includes(ext)) return base
|
|
71
|
+
const text = await safeReadFile(absTo, root, relaxed).catch(() => null)
|
|
72
|
+
if (text === null) return base
|
|
73
|
+
return await appendLspDiagnostics(realTo, text, base, undefined, root)
|
|
48
74
|
},
|
|
49
75
|
}
|
package/src/tools/patch.ts
CHANGED
|
@@ -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 {
|
|
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
|
-
|
|
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 (
|
|
82
|
-
|
|
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
|
|
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
|
}
|
package/src/tools/read_file.ts
CHANGED
|
@@ -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 {
|
|
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
|
|
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
|
|
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
|
|
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 =
|
|
207
|
+
raw = buf.toString("utf8")
|
|
215
208
|
} finally {
|
|
216
209
|
await handle.close().catch(() => {})
|
|
217
210
|
}
|
package/src/tools/read_image.ts
CHANGED
|
@@ -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 {
|
|
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: "
|
|
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
|
|
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
|
|
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() ?? "
|
|
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
|
-
|
|
14
|
+
const DEFAULT_SESSION_KEY = "__default__"
|
|
15
|
+
const submittedBySession = new Map<string, SubmittedResult>()
|
|
16
|
+
let latestSessionKey: string | null = null
|
|
15
17
|
|
|
16
|
-
|
|
17
|
-
|
|
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
|
-
|
|
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
|
-
|
|
51
|
+
additionalProperties: true,
|
|
52
|
+
description: "final structured result (JSON object, not string)",
|
|
34
53
|
},
|
|
35
|
-
summary: { type: "string", description: "
|
|
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
|
-
|
|
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
|
|
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
|
-
/**
|
|
95
|
-
*
|
|
96
|
-
*
|
|
97
|
-
*
|
|
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
|
|
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
|
-
|
|
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(
|
|
213
|
-
|
|
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"
|
|
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
|
|
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
|
-
|
|
459
|
-
|
|
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
|
})
|