minicode-ai 0.14.0 → 0.14.2
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 +16 -3
- package/cli/auto-update.ts +32 -2
- package/cli/commands/exec.ts +9 -0
- package/cli/index.ts +31 -13
- package/cli/setup.ts +31 -19
- package/cli/tui.ts +63 -40
- package/docs/OUTPUT_PROTOCOL_SPEC.md +6 -0
- package/docs/OUTPUT_RENDERING_SPEC.md +28 -4
- package/docs/README.md +2 -2
- package/docs/TERMINAL_CONTRACT.md +52 -26
- package/docs/agents.md +2 -2
- package/docs/choosing-mode.md +20 -13
- package/docs/cli.md +11 -11
- package/docs/environment.md +3 -3
- package/docs/getting-started.md +14 -12
- package/docs/glossary.md +1 -1
- package/docs/mcp-lsp.md +1 -1
- package/docs/policy-sandbox.md +7 -1
- package/docs/security-model.md +2 -2
- package/docs/security.md +7 -1
- package/docs/tools.md +4 -4
- package/docs/verify-benchmark.md +16 -0
- package/package.json +1 -3
- package/src/app/mentions.ts +4 -3
- package/src/app/session.ts +19 -9
- package/src/app/tool-layer.ts +10 -3
- package/src/constants.ts +17 -0
- package/src/lib/git-hardening.ts +27 -22
- package/src/lib/safe-open.ts +73 -19
- package/src/lib/trusted-exec.ts +7 -4
- package/src/mcp/client.ts +34 -9
- package/src/mcp/transport.ts +96 -42
- package/src/memory/files.ts +15 -4
- package/src/memory/vector.ts +5 -1
- package/src/policy/context.ts +21 -13
- package/src/policy/permission.ts +75 -16
- package/src/policy/tool-contract.ts +21 -10
- package/src/policy/update-check.ts +83 -6
- package/src/policy/usage.ts +17 -7
- package/src/policy/work-mode.ts +51 -17
- package/src/presentation/adapter.ts +64 -2
- package/src/presentation/events.ts +6 -0
- package/src/presentation/model.ts +1 -0
- package/src/presentation/projection.ts +2 -0
- package/src/presentation/reducer.ts +1 -0
- package/src/providers/anthropic.ts +52 -19
- package/src/providers/guards.ts +98 -13
- package/src/providers/responses.ts +61 -23
- package/src/providers/sse-bounds.ts +170 -0
- package/src/repo/repomap.ts +10 -11
- package/src/runtime/execution-backend.ts +7 -8
- package/src/sandbox/docker.ts +113 -9
- package/src/session/checkpoint.ts +9 -2
- package/src/session/persistence.ts +5 -2
- package/src/session/verification.ts +55 -16
- package/src/skills/loader.ts +16 -3
- package/src/tools/bash.ts +6 -3
- package/src/tools/code_run.ts +6 -5
- package/src/tools/context.ts +8 -0
- package/src/tools/delete_file.ts +2 -1
- package/src/tools/edit.ts +2 -1
- package/src/tools/git.ts +128 -54
- package/src/tools/glob.ts +2 -1
- package/src/tools/grep.ts +31 -6
- package/src/tools/lsp.ts +5 -4
- package/src/tools/mcp_call.ts +3 -1
- package/src/tools/memory.ts +175 -180
- package/src/tools/move_file.ts +2 -1
- package/src/tools/patch.ts +2 -1
- package/src/tools/read_file.ts +94 -1
- package/src/tools/read_image.ts +2 -1
- package/src/tools/task.ts +2 -1
- package/src/tools/todo.ts +4 -5
- package/src/tools/web_fetch.ts +28 -12
- package/src/tools/web_search.ts +28 -9
- package/src/tools/write_file.ts +2 -1
- package/src/ui/assistant/simple.ts +72 -3
- package/src/ui/footer.ts +17 -12
- package/src/ui/i18n/en.ts +6 -3
- package/src/ui/i18n/id.ts +6 -3
- package/src/ui/render/width.ts +107 -79
- package/src/ui/runtime/screen.ts +49 -37
- package/src/ui/tui/app.ts +261 -209
- package/src/ui/tui/transcript.ts +39 -0
- package/CHANGELOG.md +0 -1167
- package/docs/PLAN_UIUX_V6.md +0 -209
- package/docs/changelog.md +0 -3
package/src/app/session.ts
CHANGED
|
@@ -201,6 +201,8 @@ export async function createMinicodeSession(
|
|
|
201
201
|
beforeToolEffect?: (call: { id: string; name: string; args: unknown }) => Promise<void>
|
|
202
202
|
},
|
|
203
203
|
): Promise<Session> {
|
|
204
|
+
// Normalisasi root sekali di composition agar ToolContext selalu memiliki path tepercaya.
|
|
205
|
+
const defaultCwd = resolve(opts.cwd ?? process.cwd())
|
|
204
206
|
// Fail-closed lebih awal (sebelum provider/system prompt): WorkMode non-
|
|
205
207
|
// EXECUTE di atas handler terinjeksi belum punya komposisi yang terbukti
|
|
206
208
|
// aman — jangan pernah membungkus atau melewati policy yang diinjeksi 6S.
|
|
@@ -217,14 +219,13 @@ export async function createMinicodeSession(
|
|
|
217
219
|
// pembungkus provider supaya transisi runtime `/work-mode` maupun `/mode`
|
|
218
220
|
// tercermin langsung di StreamRequest.system tanpa mengedit vendor/minicore.
|
|
219
221
|
const baseSystem = await buildSystemPrompt({
|
|
220
|
-
cwd:
|
|
222
|
+
cwd: defaultCwd,
|
|
221
223
|
extra: opts.systemExtra ?? "",
|
|
222
224
|
signal: (opts as unknown as { signal?: AbortSignal }).signal,
|
|
223
225
|
})
|
|
224
226
|
const {
|
|
225
227
|
concurrency,
|
|
226
228
|
writeConcurrency,
|
|
227
|
-
cwd,
|
|
228
229
|
permissionMode,
|
|
229
230
|
workMode: _workMode,
|
|
230
231
|
allowLocalConfig,
|
|
@@ -249,8 +250,7 @@ export async function createMinicodeSession(
|
|
|
249
250
|
// Dibuat di sini (bukan global) supaya dua sesi dalam satu proses tak
|
|
250
251
|
// saling memakai bukti persetujuan. Root = cwd sesi (sama dengan yang
|
|
251
252
|
// dipakai tool untuk resolve path target).
|
|
252
|
-
const approvalBindings =
|
|
253
|
-
_approvalBindings ?? new ApprovalBindingStore(resolve(cwd ?? process.cwd()))
|
|
253
|
+
const approvalBindings = _approvalBindings ?? new ApprovalBindingStore(defaultCwd)
|
|
254
254
|
// F-09: sanitasi batas di lapisan app (mencakup pemanggil library langsung,
|
|
255
255
|
// bukan hanya CLI yang sudah sanitasi di cli/setup.ts + cli/index.ts).
|
|
256
256
|
// Tanpa ini: timeoutMs NaN/negatif = abort instan; maxSteps 0/negatif =
|
|
@@ -286,21 +286,27 @@ export async function createMinicodeSession(
|
|
|
286
286
|
// menggeser EXECUTE→DISCUSS/PLAN di sesi yang sama. Wrapper EXECUTE
|
|
287
287
|
// mendelegasikan keputusan ke base apa adanya (perilaku identik) tetapi
|
|
288
288
|
// tetap menyediakan __setWorkMode.
|
|
289
|
+
//
|
|
290
|
+
// Tool Access Policy: set tool terotorisasi = tool yang terlihat/terdaftar
|
|
291
|
+
// (termasuk MCP runtime dari server terkonfigurasi). Dipakai `auto` untuk
|
|
292
|
+
// membedakan MCP sah dari MCP tak-terkonfigurasi (fail-closed deny).
|
|
293
|
+
const authorizedTools = new Set((rest.tools ?? []).map((t) => t.name))
|
|
289
294
|
const permissions =
|
|
290
295
|
opts.permissionHandler ??
|
|
291
296
|
createWorkModePermissionHandler({
|
|
292
297
|
workMode: resolvedWorkMode,
|
|
293
298
|
base: createPermissionHandler({
|
|
294
299
|
mode: permissionMode ?? "auto",
|
|
295
|
-
root:
|
|
300
|
+
root: defaultCwd,
|
|
296
301
|
ask,
|
|
297
302
|
allowLocalConfig,
|
|
298
303
|
onApprovalEvent,
|
|
304
|
+
authorizedTools,
|
|
299
305
|
// [Area B · PROMPT 06] Store per-sesi: persetujuan dari sesi A tak
|
|
300
306
|
// bisa dipakai sebagai bukti di sesi B.
|
|
301
307
|
approvalBindings,
|
|
302
308
|
}),
|
|
303
|
-
root:
|
|
309
|
+
root: defaultCwd,
|
|
304
310
|
})
|
|
305
311
|
const injected = opts.permissionHandler !== undefined
|
|
306
312
|
const withMode = permissions as typeof permissions & {
|
|
@@ -326,7 +332,7 @@ export async function createMinicodeSession(
|
|
|
326
332
|
if (isAllToolsPureRead()) return "explore"
|
|
327
333
|
return "active"
|
|
328
334
|
}
|
|
329
|
-
const effectiveRoot =
|
|
335
|
+
const effectiveRoot = defaultCwd
|
|
330
336
|
const detector: NoProgressDetector | null =
|
|
331
337
|
noProgress === false
|
|
332
338
|
? null
|
|
@@ -361,7 +367,11 @@ export async function createMinicodeSession(
|
|
|
361
367
|
...permissions,
|
|
362
368
|
check: async (call, deps) => {
|
|
363
369
|
const decision = await permissions.check(call, deps)
|
|
364
|
-
|
|
370
|
+
// Kernel vendored saat ini hanya memblokir literal "deny". Validasi di
|
|
371
|
+
// composition root ini menjaga production dispatch fail-closed tanpa
|
|
372
|
+
// mengubah salinan MiniCore yang wajib disinkronkan dari repo sumber.
|
|
373
|
+
// Handler ASK yang sah tetap menunggu approval lalu mengembalikan allow/deny.
|
|
374
|
+
if (decision !== "allow") return "deny"
|
|
365
375
|
// Ambil (konsumsi) bukti persetujuan milik call ini — sekali saja.
|
|
366
376
|
// Diambil SEBELUM await supaya tak ada binding tersisa kalau barrier
|
|
367
377
|
// memblokir call (tak ada deny lalu tak ada jejak).
|
|
@@ -463,7 +473,7 @@ export async function createMinicodeSession(
|
|
|
463
473
|
concurrency: safeConcurrency ?? LIMITS.EXECUTOR_CONCURRENCY,
|
|
464
474
|
writeConcurrency: safeWriteConcurrency ?? LIMITS.EXECUTOR_WRITE_CONCURRENCY,
|
|
465
475
|
}),
|
|
466
|
-
cwd,
|
|
476
|
+
cwd: defaultCwd,
|
|
467
477
|
...(turnCount !== undefined ? { turnCount } : {}),
|
|
468
478
|
...(stepCount !== undefined ? { stepCount } : {}),
|
|
469
479
|
})
|
package/src/app/tool-layer.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { connectAll as mcpConnectAll } from "../mcp/client.ts"
|
|
|
5
5
|
import {
|
|
6
6
|
EXPLORE_TOOL_NAMES,
|
|
7
7
|
LOCAL_READONLY_TOOL_NAMES,
|
|
8
|
+
PLAN_EXTRA_TOOL_NAMES,
|
|
8
9
|
READONLY_TOOL_NAMES,
|
|
9
10
|
} from "../policy/tool-contract.ts"
|
|
10
11
|
import { isMcpToolName } from "../presentation/label.ts"
|
|
@@ -12,12 +13,12 @@ import type { CanonicalScope } from "../session/verification.ts"
|
|
|
12
13
|
import { createBashJobTools } from "../tools/bash.ts"
|
|
13
14
|
import { withEvidence } from "../tools/evidence.ts"
|
|
14
15
|
import { allTools, withMcpTools } from "../tools/index.ts"
|
|
16
|
+
import { createWriteMemoryTool } from "../tools/memory.ts"
|
|
15
17
|
|
|
16
18
|
const errMsg = (e: unknown) => (e instanceof Error ? e.message : String(e))
|
|
17
19
|
|
|
18
20
|
export type ToolScope = "full" | "explore"
|
|
19
21
|
|
|
20
|
-
const PLAN_EXTRA = new Set(["todo_write", "delegate_task", "submit_result"])
|
|
21
22
|
const LOCAL_READONLY_SET: ReadonlySet<string> = new Set(LOCAL_READONLY_TOOL_NAMES)
|
|
22
23
|
|
|
23
24
|
// WorkMode ceiling (P12 S2.2 + P0.2) — lapisan intent di ATAS permission mode.
|
|
@@ -42,11 +43,12 @@ export function workModeVisible(
|
|
|
42
43
|
if (permissionMode === "readonly" || permissionMode === "allowlist") {
|
|
43
44
|
return READONLY_TOOL_NAMES.has(name)
|
|
44
45
|
}
|
|
45
|
-
return READONLY_TOOL_NAMES.has(name) ||
|
|
46
|
+
return READONLY_TOOL_NAMES.has(name) || PLAN_EXTRA_TOOL_NAMES.has(name)
|
|
46
47
|
}
|
|
47
48
|
// EXECUTE = tanpa ceiling WorkMode tambahan; hormati filter PermissionMode.
|
|
48
49
|
if (permissionMode === "readonly") return READONLY_TOOL_NAMES.has(name)
|
|
49
|
-
if (permissionMode === "plan")
|
|
50
|
+
if (permissionMode === "plan")
|
|
51
|
+
return READONLY_TOOL_NAMES.has(name) || PLAN_EXTRA_TOOL_NAMES.has(name)
|
|
50
52
|
return true
|
|
51
53
|
}
|
|
52
54
|
|
|
@@ -77,6 +79,11 @@ export async function setupToolLayer(
|
|
|
77
79
|
setPermissionMode?: (pm: string) => void
|
|
78
80
|
}> {
|
|
79
81
|
let sessionTools: Tool[] = allTools
|
|
82
|
+
if (jobOwnerSid) {
|
|
83
|
+
sessionTools = sessionTools.map((tool) =>
|
|
84
|
+
tool.name === "write_memory" ? createWriteMemoryTool(jobOwnerSid) : tool,
|
|
85
|
+
)
|
|
86
|
+
}
|
|
80
87
|
// Harness-P2: scope explore = subset read-only sub-agen (tetap 12 EXPLORE_TOOL_NAMES).
|
|
81
88
|
if (scope === "explore")
|
|
82
89
|
sessionTools = allTools.filter((t) => EXPLORE_TOOL_NAMES.includes(t.name))
|
package/src/constants.ts
CHANGED
|
@@ -14,11 +14,17 @@ export const LIMITS = {
|
|
|
14
14
|
BASH_BACKGROUND_MAX_JOBS: 8,
|
|
15
15
|
BASH_BACKGROUND_MAX_LIFETIME_MS: 3_600_000,
|
|
16
16
|
DOCKER_OUTPUT_MAX_CHARS: 100_000,
|
|
17
|
+
/** Batas untuk meminta daemon Docker menghapus container yang timeout/abort. */
|
|
18
|
+
DOCKER_CLEANUP_TIMEOUT_MS: 5_000,
|
|
17
19
|
MCP_OUTPUT_MAX_CHARS: 100_000,
|
|
20
|
+
/** Batas frame JSON-RPC stdio sebelum decode/parse; satu respons tools/list bisa besar. */
|
|
21
|
+
MCP_STDIO_FRAME_MAX_BYTES: 1_048_576,
|
|
18
22
|
MCP_REQUEST_TIMEOUT_MS: 30_000,
|
|
19
23
|
TASK_SUB_AGENT_MAX_TOKENS: 2_000,
|
|
20
24
|
/** Context & memory */
|
|
21
25
|
SYSTEM_PROMPT_MAX_CHARS: 8_000,
|
|
26
|
+
/** Batas baca per skill sebelum dirender sebagai instruksi pada prompt. */
|
|
27
|
+
SKILL_FILE_MAX_BYTES: 32_000,
|
|
22
28
|
MEMORY_FILE_MAX_CHARS: 4_000,
|
|
23
29
|
MEMORY_FILE_MAX_BYTES: 200_000,
|
|
24
30
|
MEMORY_TRUNCATE_KEEP_BYTES: 150_000,
|
|
@@ -85,6 +91,16 @@ export const LIMITS = {
|
|
|
85
91
|
/** Investigasi Phase 5: cap reasoning stream (terbukti TANPA cap = akumulasi
|
|
86
92
|
* tak terbatas — satu-satunya jalur loop `reasoning +=` tanpa batas). */
|
|
87
93
|
PROVIDER_REASON_MAX_CHARS: 2_000_000,
|
|
94
|
+
/** Frame SSE provider longgar untuk JSON tool besar (write_file menerima 5 MB chars). */
|
|
95
|
+
PROVIDER_SSE_FRAME_MAX_BYTES: 16_777_216,
|
|
96
|
+
/** Batas total satu respons stream provider, termasuk reasoning/tool args. */
|
|
97
|
+
PROVIDER_SSE_TOTAL_MAX_BYTES: 67_108_864,
|
|
98
|
+
/** Argumen tool besar tetap didukung; envelope JSON dapat menggandakan escape chars. */
|
|
99
|
+
PROVIDER_TOOL_ARGS_MAX_BYTES: 12_582_912,
|
|
100
|
+
/** Batas agregat argumen yang masih tertahan dari beberapa tool call. */
|
|
101
|
+
PROVIDER_TOOL_ARGS_PENDING_MAX_BYTES: 25_165_824,
|
|
102
|
+
/** Respons error provider cukup untuk diagnosis tanpa membaca body arbitrer. */
|
|
103
|
+
PROVIDER_ERROR_BODY_MAX_BYTES: 65_536,
|
|
88
104
|
DOCKER_TIMEOUT_MS: 30_000,
|
|
89
105
|
DETECT_MODELS_TIMEOUT_MS: 4_000,
|
|
90
106
|
DETECT_GLOBAL_TIMEOUT_MS: 6_000,
|
|
@@ -99,6 +115,7 @@ export const LIMITS = {
|
|
|
99
115
|
LSP_INIT_TIMEOUT_MS: 15_000,
|
|
100
116
|
VERIFY_DEFAULT_TIMEOUT_MS: 30_000,
|
|
101
117
|
WEB_FETCH_BODY_HARD_CAP_CHARS: 2_000_000,
|
|
118
|
+
WEB_RESPONSE_BODY_HARD_CAP_BYTES: 2_000_000,
|
|
102
119
|
WEB_FETCH_MAX_REDIRECTS: 5,
|
|
103
120
|
/** Glob/grep */
|
|
104
121
|
SEARCH_DEFAULT_LIMIT: 100,
|
package/src/lib/git-hardening.ts
CHANGED
|
@@ -17,7 +17,7 @@ import { resolveTrustedExecutable } from "./trusted-exec.ts"
|
|
|
17
17
|
// index user (LFS/semantik clean milik user, lihat git.ts). Pengecualian:
|
|
18
18
|
// protokol `filter.<d>.process` diutamakan git di atas clean/smudge, jadi
|
|
19
19
|
// neutralizer selalu mematikannya (nilai kosong = fallback ke clean/smudge)
|
|
20
|
-
// di SEMUA jalur plumbing;
|
|
20
|
+
// di SEMUA jalur plumbing; `git_commit` menolak filter sebelum staging.
|
|
21
21
|
|
|
22
22
|
/** Netralisasi universal: tanpa hooks, tanpa fsmonitor, tanpa pager. */
|
|
23
23
|
export const GIT_SAFE_BASE: readonly string[] = [
|
|
@@ -31,7 +31,7 @@ export const GIT_SAFE_BASE: readonly string[] = [
|
|
|
31
31
|
/** Netralisasi driver konten untuk diff/log (tanpa eksekusi repo). */
|
|
32
32
|
export const GIT_NO_DIFF_DRIVERS: readonly string[] = ["--no-ext-diff", "--no-textconv"]
|
|
33
33
|
|
|
34
|
-
const DRIVER_RE = /^filter\.([A-Za-z0-9_.-]+)\.(
|
|
34
|
+
const DRIVER_RE = /^filter\.([A-Za-z0-9_.-]+)\.(clean|smudge|process)$/i
|
|
35
35
|
|
|
36
36
|
export interface FilterDriver {
|
|
37
37
|
name: string
|
|
@@ -42,30 +42,35 @@ export interface FilterDriver {
|
|
|
42
42
|
|
|
43
43
|
/**
|
|
44
44
|
* Daftar driver filter yang TERKONFIGURASI di repo (discovery read-only via
|
|
45
|
-
* `git config`, tanpa hook/filter/pager).
|
|
46
|
-
*
|
|
47
|
-
*
|
|
45
|
+
* `git config`, tanpa hook/filter/pager). Kegagalan discovery melempar error:
|
|
46
|
+
* pemanggil tidak boleh menganggap ketidakmampuan memeriksa sebagai tidak ada
|
|
47
|
+
* filter. Dipakai neutralizer plumbing dan preflight `git_commit`.
|
|
48
48
|
*/
|
|
49
49
|
export async function discoverFilterDrivers(cwd: string): Promise<FilterDriver[]> {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
50
|
+
const r = spawnSync(
|
|
51
|
+
resolveTrustedExecutable("git"),
|
|
52
|
+
["config", "--name-only", "--get-regexp", "^filter\\..*\\.(clean|smudge|process)$"],
|
|
53
|
+
{ cwd, encoding: "utf8", timeout: 10_000 },
|
|
54
|
+
)
|
|
55
|
+
if (r.error) throw new Error(`unable to inspect Git filter configuration: ${r.error.message}`)
|
|
56
|
+
if (r.status === 1 && !r.stdout?.trim()) return []
|
|
57
|
+
if (r.status !== 0) {
|
|
58
|
+
throw new Error(`unable to inspect Git filter configuration (git exited ${String(r.status)})`)
|
|
59
|
+
}
|
|
60
|
+
if (!r.stdout?.trim()) return []
|
|
61
|
+
const drivers = new Map<string, FilterDriver>()
|
|
62
|
+
for (const line of r.stdout.split("\n")) {
|
|
63
|
+
const key = line.trim()
|
|
64
|
+
if (!key) continue
|
|
65
|
+
const m = DRIVER_RE.exec(key)
|
|
66
|
+
if (!m?.[1] || !m[2]) {
|
|
67
|
+
throw new Error("unable to safely parse Git filter configuration")
|
|
64
68
|
}
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
69
|
+
const d = drivers.get(m[1]) ?? { name: m[1], hasProcess: false }
|
|
70
|
+
if (m[2].toLowerCase() === "process") d.hasProcess = true
|
|
71
|
+
drivers.set(m[1], d)
|
|
68
72
|
}
|
|
73
|
+
return [...drivers.values()].sort((a, b) => (a.name < b.name ? -1 : 1))
|
|
69
74
|
}
|
|
70
75
|
|
|
71
76
|
/**
|
package/src/lib/safe-open.ts
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import { constants } from "node:fs"
|
|
2
2
|
import type { FileHandle } from "node:fs/promises"
|
|
3
|
-
import { open, realpath } from "node:fs/promises"
|
|
3
|
+
import { open, realpath, stat as statPath } from "node:fs/promises"
|
|
4
4
|
import { homedir, tmpdir } from "node:os"
|
|
5
5
|
import { basename, dirname, isAbsolute, join, parse, relative, resolve } from "node:path"
|
|
6
6
|
import { isPathOutsideRoot, isSensitive } from "../policy/jail.ts"
|
|
7
7
|
|
|
8
|
-
// O_NOFOLLOW mencegah open mengikuti symlink
|
|
9
|
-
//
|
|
10
|
-
|
|
8
|
+
// O_NOFOLLOW mencegah open mengikuti symlink pada POSIX. Windows tidak
|
|
9
|
+
// menyediakan flag Node yang setara; semua platform juga membandingkan dev+ino
|
|
10
|
+
// stat sebelum open dengan identitas handle setelah open.
|
|
11
|
+
const O_NOFOLLOW: number = (constants as unknown as { O_NOFOLLOW?: number }).O_NOFOLLOW ?? 0
|
|
11
12
|
const O_RDONLY = constants.O_RDONLY
|
|
12
13
|
|
|
13
14
|
/**
|
|
@@ -39,17 +40,19 @@ export async function resolveSafePath(
|
|
|
39
40
|
}
|
|
40
41
|
|
|
41
42
|
/**
|
|
42
|
-
* Buka file dengan O_NOFOLLOW pada
|
|
43
|
+
* Buka file dengan O_NOFOLLOW pada POSIX dan pemeriksaan identitas handle pada
|
|
44
|
+
* semua platform.
|
|
43
45
|
*
|
|
44
|
-
* Urutan: realpath
|
|
46
|
+
* Urutan: realpath + boundary check → stat identitas → realpath ulang +
|
|
47
|
+
* boundary check → open target canonical → fstat dan cocokkan dev+ino.
|
|
45
48
|
* Membuka hasil resolusi (bukan abs asli) berarti symlink internal tetap bisa
|
|
46
|
-
* dibaca
|
|
47
|
-
*
|
|
49
|
+
* dibaca. O_NOFOLLOW menutup swap leaf pada POSIX; pencocokan identitas handle
|
|
50
|
+
* menolak target berbeda yang terbuka setelah komponen path berubah, termasuk
|
|
51
|
+
* pada Windows yang tidak memiliki O_NOFOLLOW di API Node.
|
|
48
52
|
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
* POSIX — lihat test/tool-toctou.test.ts (skip bila symlink EPERM).
|
|
53
|
+
* File system yang tidak menyediakan inode non-zero ditolak karena identitas
|
|
54
|
+
* handle tidak dapat dibuktikan. Stress test symlink tetap bergantung pada
|
|
55
|
+
* privilege platform; lihat test/tool-toctou.test.ts.
|
|
53
56
|
*/
|
|
54
57
|
export async function safeOpenRead(
|
|
55
58
|
abs: string,
|
|
@@ -64,31 +67,50 @@ export async function safeOpenRead(
|
|
|
64
67
|
// di sini agar semua pembaca via open (read_file/read_image/stat) mewarisinya.
|
|
65
68
|
if (isSensitive(preReal)) throw new Error(`blocked sensitive file: ${abs}`)
|
|
66
69
|
|
|
70
|
+
// Ambil identitas sebelum open, lalu periksa kembali boundary setelah stat.
|
|
71
|
+
// Ini menutup race di mana parent directory berubah menjadi junction/symlink
|
|
72
|
+
// keluar sesudah realpath pertama tetapi sebelum open.
|
|
73
|
+
const expected = await statPath(preReal, { bigint: true })
|
|
74
|
+
const checkedReal = await realpath(preReal)
|
|
75
|
+
if (isPathOutsideRoot(checkedReal, realRoot))
|
|
76
|
+
throw new Error(`symlink points outside workspace: ${abs}`)
|
|
77
|
+
if (isSensitive(checkedReal)) throw new Error(`blocked sensitive file: ${abs}`)
|
|
78
|
+
if (expected.ino === 0n)
|
|
79
|
+
throw new Error(`unable to verify opened file identity on this filesystem: ${abs}`)
|
|
80
|
+
|
|
67
81
|
// Buka path terverifikasi — bukan abs (yang bisa di-swap setelah realpath).
|
|
68
82
|
let handle: FileHandle
|
|
69
83
|
try {
|
|
70
|
-
handle = await open(
|
|
84
|
+
handle = await open(checkedReal, O_RDONLY | O_NOFOLLOW)
|
|
71
85
|
} catch (e) {
|
|
72
86
|
const code = (e as NodeJS.ErrnoException).code
|
|
73
87
|
if (code === "ELOOP") throw new Error(`symlink swapped during open (O_NOFOLLOW): ${abs}`)
|
|
74
|
-
// EINVAL: O_NOFOLLOW tidak didukung → buka biasa
|
|
88
|
+
// EINVAL: O_NOFOLLOW tidak didukung → buka biasa; fstat di bawah tetap
|
|
89
|
+
// memastikan file yang dibuka sama dengan identitas yang sudah diperiksa.
|
|
75
90
|
if (code === "EINVAL" && O_NOFOLLOW !== 0) {
|
|
76
|
-
handle = await open(
|
|
91
|
+
handle = await open(checkedReal, O_RDONLY)
|
|
77
92
|
} else throw e
|
|
78
93
|
}
|
|
94
|
+
const opened = await handle.stat({ bigint: true }).catch(async (error: unknown) => {
|
|
95
|
+
await handle.close().catch(() => {})
|
|
96
|
+
throw error
|
|
97
|
+
})
|
|
98
|
+
if (opened.ino === 0n || opened.dev !== expected.dev || opened.ino !== expected.ino) {
|
|
99
|
+
await handle.close().catch(() => {})
|
|
100
|
+
throw new Error(`file changed during safe open; refusing to read unverified target: ${abs}`)
|
|
101
|
+
}
|
|
79
102
|
// Hardlink ke luar workspace tak terlihat oleh realpath (semua nama setara)
|
|
80
103
|
// — baca via hardlink = baca konten luar. fstat pada handle yang SUDAH
|
|
81
104
|
// terbuka: tepat untuk file ini, bebas race dengan swap nama. File normal
|
|
82
105
|
// nlink=1; tolak sisanya dengan pesan yang bisa ditindaklanjuti.
|
|
83
|
-
const st = await handle.stat().catch(() => null)
|
|
84
106
|
// Hardlink check hanya untuk file regular: direktori punya nlink >= 2
|
|
85
107
|
// (`.` dan `..`) dan bukan target hardlink — biarkan tool yang menolak
|
|
86
108
|
// direktori dengan pesan yang user-friendly.
|
|
87
|
-
if (
|
|
109
|
+
if (!opened.isDirectory() && opened.nlink > 1n) {
|
|
88
110
|
await handle.close().catch(() => {})
|
|
89
|
-
throw new Error(`refusing to read file with multiple hardlinks (nlink=${
|
|
111
|
+
throw new Error(`refusing to read file with multiple hardlinks (nlink=${opened.nlink}): ${abs}`)
|
|
90
112
|
}
|
|
91
|
-
return { handle, realPath:
|
|
113
|
+
return { handle, realPath: checkedReal }
|
|
92
114
|
}
|
|
93
115
|
|
|
94
116
|
export async function safeReadFile(abs: string, root: string): Promise<string> {
|
|
@@ -100,6 +122,38 @@ export async function safeReadFile(abs: string, root: string): Promise<string> {
|
|
|
100
122
|
}
|
|
101
123
|
}
|
|
102
124
|
|
|
125
|
+
/**
|
|
126
|
+
* Baca file tepercaya dengan batas byte sebelum alokasi tumbuh mengikuti file.
|
|
127
|
+
* Satu byte tambahan membedakan file tepat pada batas dari file yang dipotong.
|
|
128
|
+
*/
|
|
129
|
+
export async function safeReadFileCapped(
|
|
130
|
+
abs: string,
|
|
131
|
+
root: string,
|
|
132
|
+
maxBytes: number,
|
|
133
|
+
): Promise<{ text: string; truncated: boolean }> {
|
|
134
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1)
|
|
135
|
+
throw new RangeError("maxBytes must be a positive safe integer")
|
|
136
|
+
const { handle } = await safeOpenRead(abs, root)
|
|
137
|
+
try {
|
|
138
|
+
const st = await handle.stat()
|
|
139
|
+
if (!st.isFile()) throw new Error(`refusing to read non-regular file: ${abs}`)
|
|
140
|
+
const buffer = Buffer.alloc(maxBytes + 1)
|
|
141
|
+
let bytesRead = 0
|
|
142
|
+
while (bytesRead < buffer.length) {
|
|
143
|
+
const result = await handle.read(buffer, bytesRead, buffer.length - bytesRead, bytesRead)
|
|
144
|
+
if (result.bytesRead === 0) break
|
|
145
|
+
bytesRead += result.bytesRead
|
|
146
|
+
}
|
|
147
|
+
const truncated = bytesRead > maxBytes || st.size > maxBytes
|
|
148
|
+
return {
|
|
149
|
+
text: buffer.subarray(0, Math.min(bytesRead, maxBytes)).toString("utf8"),
|
|
150
|
+
truncated,
|
|
151
|
+
}
|
|
152
|
+
} finally {
|
|
153
|
+
await handle.close().catch(() => {})
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
103
157
|
export async function safeStat(abs: string, root: string) {
|
|
104
158
|
const { handle } = await safeOpenRead(abs, root)
|
|
105
159
|
try {
|
package/src/lib/trusted-exec.ts
CHANGED
|
@@ -15,7 +15,9 @@ import { delimiter, isAbsolute, join } from "node:path"
|
|
|
15
15
|
// nama telanjang (perilaku lama) supaya kegagalan tetap fail-open seperti
|
|
16
16
|
// semula, tetapi kasus umum (git terpasang di PATH) jadi aman dari hijack.
|
|
17
17
|
|
|
18
|
-
|
|
18
|
+
function isWindows(): boolean {
|
|
19
|
+
return process.platform === "win32"
|
|
20
|
+
}
|
|
19
21
|
|
|
20
22
|
function validPathEntries(): string[] {
|
|
21
23
|
const raw = process.env.PATH ?? process.env.Path ?? ""
|
|
@@ -32,7 +34,7 @@ function isExecutableFile(p: string): boolean {
|
|
|
32
34
|
try {
|
|
33
35
|
const st = statSync(p)
|
|
34
36
|
if (!st.isFile()) return false
|
|
35
|
-
if (
|
|
37
|
+
if (isWindows()) return true
|
|
36
38
|
accessSync(p, constants.X_OK)
|
|
37
39
|
return true
|
|
38
40
|
} catch {
|
|
@@ -60,14 +62,15 @@ function resolveUncached(name: string): string {
|
|
|
60
62
|
// "tools\\run.exe") adalah pilihan eksplisit pemanggil — jangan diubah.
|
|
61
63
|
if (isAbsolute(name)) return name
|
|
62
64
|
if (name.includes("/") || name.includes("\\")) return name
|
|
63
|
-
const
|
|
65
|
+
const windows = isWindows()
|
|
66
|
+
const exts = windows
|
|
64
67
|
? (process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD")
|
|
65
68
|
.split(";")
|
|
66
69
|
.map((e) => e.trim())
|
|
67
70
|
.filter(Boolean)
|
|
68
71
|
: [""]
|
|
69
72
|
for (const dir of validPathEntries()) {
|
|
70
|
-
if (
|
|
73
|
+
if (windows) {
|
|
71
74
|
for (const ext of exts) {
|
|
72
75
|
const candidate = join(dir, name.endsWith(ext.toLowerCase()) ? name : name + ext)
|
|
73
76
|
if (isExecutableFile(candidate)) return candidate
|
package/src/mcp/client.ts
CHANGED
|
@@ -7,6 +7,22 @@ import { scrubSecrets } from "../policy/scrub.ts"
|
|
|
7
7
|
import { McpHttpTransport, type McpTransportLike } from "./http-transport.ts"
|
|
8
8
|
import { McpTransport } from "./transport.ts"
|
|
9
9
|
|
|
10
|
+
/**
|
|
11
|
+
* Transport interruption after a tools/call request can race with remote
|
|
12
|
+
* execution. Callers must not report this as a clean failure or retry blindly.
|
|
13
|
+
*/
|
|
14
|
+
export class McpCallOutcomeUnknownError extends Error {
|
|
15
|
+
readonly code = "MCP_CALL_OUTCOME_UNKNOWN"
|
|
16
|
+
|
|
17
|
+
constructor(toolName: string, cause: unknown) {
|
|
18
|
+
const detail = scrubSecrets(cause instanceof Error ? cause.message : String(cause))
|
|
19
|
+
super(
|
|
20
|
+
`MCP tool ${toolName} outcome is unknown: ${detail}. The server may have accepted or completed the operation; inspect remote state before retrying.`,
|
|
21
|
+
)
|
|
22
|
+
this.name = "McpCallOutcomeUnknownError"
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
10
26
|
// [Fase 8 / 8.2] MCP Schema Fingerprint Pinning.
|
|
11
27
|
//
|
|
12
28
|
// Bahaya yang ditutup: server MCP bisa mengubah skema toolnya SETELAH pin
|
|
@@ -515,15 +531,24 @@ class McpConnection {
|
|
|
515
531
|
args: Record<string, unknown>,
|
|
516
532
|
signal?: AbortSignal,
|
|
517
533
|
): Promise<unknown> {
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
534
|
+
// Abort before entering transport is known not to have sent a request.
|
|
535
|
+
signal?.throwIfAborted()
|
|
536
|
+
let result: Record<string, unknown>
|
|
537
|
+
try {
|
|
538
|
+
result = (await this.transport.request(
|
|
539
|
+
"tools/call",
|
|
540
|
+
{
|
|
541
|
+
name,
|
|
542
|
+
arguments: args,
|
|
543
|
+
},
|
|
544
|
+
undefined,
|
|
545
|
+
signal,
|
|
546
|
+
)) as Record<string, unknown>
|
|
547
|
+
} catch (error) {
|
|
548
|
+
// Once the transport call begins, timeout/abort/connection failure does
|
|
549
|
+
// not prove the remote server stopped or rolled back the operation.
|
|
550
|
+
throw new McpCallOutcomeUnknownError(name, error)
|
|
551
|
+
}
|
|
527
552
|
if (result && typeof result.isError === "boolean" && result.isError) {
|
|
528
553
|
const content = Array.isArray(result.content)
|
|
529
554
|
? result.content.map((c: any) => c.text ?? JSON.stringify(c)).join("\n")
|