minicode-ai 0.9.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +935 -0
- package/LICENSE +21 -0
- package/README.md +200 -0
- package/cli/args.ts +195 -0
- package/cli/auto-update.ts +108 -0
- package/cli/commands/auth.ts +166 -0
- package/cli/commands/config.ts +382 -0
- package/cli/commands/doctor.ts +128 -0
- package/cli/commands/exec.ts +179 -0
- package/cli/commands/mcp.ts +35 -0
- package/cli/commands/memory.ts +107 -0
- package/cli/commands/pricing.ts +100 -0
- package/cli/commands/providers.ts +162 -0
- package/cli/commands/sessions.ts +128 -0
- package/cli/commands/skills.ts +61 -0
- package/cli/commands/stats.ts +82 -0
- package/cli/commands.ts +317 -0
- package/cli/index.ts +539 -0
- package/cli/model-manager.ts +112 -0
- package/cli/provider-manager.ts +111 -0
- package/cli/repl.ts +734 -0
- package/cli/router.ts +124 -0
- package/cli/setup.ts +780 -0
- package/cli/wizard.ts +21 -0
- package/docs/ARCHITECTURE.html +1222 -0
- package/docs/README.md +109 -0
- package/docs/architecture.md +44 -0
- package/docs/changelog.md +3 -0
- package/package.json +91 -0
- package/src/agents/pool.ts +43 -0
- package/src/app/mentions.ts +50 -0
- package/src/app/provider-layer.ts +118 -0
- package/src/app/rag-layer.ts +105 -0
- package/src/app/session.ts +154 -0
- package/src/app/tool-layer.ts +56 -0
- package/src/config.ts +372 -0
- package/src/constants.ts +119 -0
- package/src/hooks/run.ts +89 -0
- package/src/lib/atomic-write.ts +88 -0
- package/src/lib/db-path.ts +36 -0
- package/src/lib/git-hardening.ts +91 -0
- package/src/lib/ignore.ts +58 -0
- package/src/lib/keystore.ts +202 -0
- package/src/lib/net.ts +70 -0
- package/src/lib/safe-open.ts +138 -0
- package/src/lib/session-id.ts +23 -0
- package/src/lib/trash.ts +38 -0
- package/src/lib/trusted-exec.ts +81 -0
- package/src/lsp/client.ts +395 -0
- package/src/mcp/client.ts +400 -0
- package/src/mcp/http-transport.ts +344 -0
- package/src/mcp/server.ts +538 -0
- package/src/mcp/transport.ts +150 -0
- package/src/memory/files.ts +159 -0
- package/src/memory/vector.ts +775 -0
- package/src/policy/allowlist.ts +67 -0
- package/src/policy/bash-guard.ts +465 -0
- package/src/policy/compaction.ts +271 -0
- package/src/policy/context.ts +161 -0
- package/src/policy/executor.ts +199 -0
- package/src/policy/jail.ts +127 -0
- package/src/policy/permission.ts +517 -0
- package/src/policy/pricing.ts +336 -0
- package/src/policy/ratelimit.ts +54 -0
- package/src/policy/sandbox-policy.ts +157 -0
- package/src/policy/scrub.ts +138 -0
- package/src/policy/update-check.ts +200 -0
- package/src/policy/usage.ts +292 -0
- package/src/policy/verifier.ts +181 -0
- package/src/providers/anthropic.ts +401 -0
- package/src/providers/auth-store.ts +139 -0
- package/src/providers/build.ts +136 -0
- package/src/providers/detect.ts +126 -0
- package/src/providers/effort.ts +165 -0
- package/src/providers/guards.ts +107 -0
- package/src/providers/oauth.ts +326 -0
- package/src/providers/presets.ts +122 -0
- package/src/providers/provision.ts +298 -0
- package/src/providers/responses.ts +371 -0
- package/src/providers/router.ts +247 -0
- package/src/repo/repomap.ts +470 -0
- package/src/sandbox/docker.ts +129 -0
- package/src/sandbox/os.ts +193 -0
- package/src/session/checkpoint.ts +543 -0
- package/src/session/journal.ts +1347 -0
- package/src/session/persistence.ts +446 -0
- package/src/session/shadow-git.ts +351 -0
- package/src/session/turn-marker.ts +118 -0
- package/src/skills/loader.ts +117 -0
- package/src/telemetry/trace.ts +283 -0
- package/src/tools/ask_user.ts +54 -0
- package/src/tools/bash.ts +400 -0
- package/src/tools/code_run.ts +96 -0
- package/src/tools/delete_file.ts +31 -0
- package/src/tools/edit.ts +204 -0
- package/src/tools/git.ts +301 -0
- package/src/tools/glob.ts +90 -0
- package/src/tools/grep.ts +281 -0
- package/src/tools/hashline.ts +66 -0
- package/src/tools/index.ts +103 -0
- package/src/tools/lsp.ts +346 -0
- package/src/tools/mcp_call.ts +163 -0
- package/src/tools/memory.ts +144 -0
- package/src/tools/move_file.ts +47 -0
- package/src/tools/patch.ts +86 -0
- package/src/tools/read_file.ts +130 -0
- package/src/tools/read_image.ts +80 -0
- package/src/tools/submit_result.ts +49 -0
- package/src/tools/task.ts +346 -0
- package/src/tools/todo.ts +201 -0
- package/src/tools/web_fetch.ts +161 -0
- package/src/tools/web_search.ts +156 -0
- package/src/tools/write_file.ts +42 -0
- package/src/ui/approval/prompt.ts +76 -0
- package/src/ui/assistant/simple.ts +568 -0
- package/src/ui/assistant/turn-status.ts +303 -0
- package/src/ui/contract.ts +55 -0
- package/src/ui/footer.ts +105 -0
- package/src/ui/input/input.ts +805 -0
- package/src/ui/input/prompt-engine.ts +606 -0
- package/src/ui/render/collapse.ts +84 -0
- package/src/ui/render/detail.ts +24 -0
- package/src/ui/render/diff.ts +181 -0
- package/src/ui/render/errors.ts +239 -0
- package/src/ui/render/format.ts +54 -0
- package/src/ui/render/highlight.ts +294 -0
- package/src/ui/render/markdown.ts +120 -0
- package/src/ui/render/money.ts +12 -0
- package/src/ui/render/reasoning.ts +20 -0
- package/src/ui/render/sanitize.ts +80 -0
- package/src/ui/render/table.ts +88 -0
- package/src/ui/render/theme.ts +339 -0
- package/src/ui/render/width.ts +256 -0
- package/src/ui/render/wrap.ts +120 -0
- package/src/ui/runtime/bus-debug.ts +83 -0
- package/src/ui/runtime/chrome.ts +301 -0
- package/src/ui/runtime/spinner.ts +77 -0
- package/src/ui/runtime/statusline.ts +227 -0
- package/src/ui/screens/model-manager.ts +434 -0
- package/src/ui/screens/overlay.ts +61 -0
- package/src/ui/screens/picker.ts +307 -0
- package/src/ui/screens/provider-manager.ts +450 -0
- package/src/ui/screens/wizard.ts +132 -0
- package/vendor/minicore/VENDOR.md +29 -0
- package/vendor/minicore/package.json +21 -0
- package/vendor/minicore/src/core/budget.ts +26 -0
- package/vendor/minicore/src/core/compact.ts +76 -0
- package/vendor/minicore/src/core/errors.ts +60 -0
- package/vendor/minicore/src/core/events.ts +74 -0
- package/vendor/minicore/src/core/executor.ts +139 -0
- package/vendor/minicore/src/core/history.ts +32 -0
- package/vendor/minicore/src/core/index.ts +42 -0
- package/vendor/minicore/src/core/loop.ts +344 -0
- package/vendor/minicore/src/core/permission.ts +24 -0
- package/vendor/minicore/src/core/provider.ts +39 -0
- package/vendor/minicore/src/core/recovery.ts +34 -0
- package/vendor/minicore/src/core/session.ts +327 -0
- package/vendor/minicore/src/core/snapshot.ts +142 -0
- package/vendor/minicore/src/core/tokens.ts +111 -0
- package/vendor/minicore/src/core/tool.ts +118 -0
- package/vendor/minicore/src/core/types.ts +50 -0
- package/vendor/minicore/src/providers/openai-compat.ts +366 -0
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
import { spawn, spawnSync } from "node:child_process"
|
|
2
|
+
import { randomUUID } from "node:crypto"
|
|
3
|
+
import { resolve as resolvePath } from "node:path"
|
|
4
|
+
import type { Tool, ToolContext } from "#minicore"
|
|
5
|
+
import { LIMITS } from "../constants.ts"
|
|
6
|
+
import { isCwdOutsideRoot, isPathOutsideRoot } from "../policy/jail.ts"
|
|
7
|
+
|
|
8
|
+
// re-export untuk backward compat (helper kini terpusat di policy/scrub)
|
|
9
|
+
export { SECRET_ENV_RE, sanitizeSpawnEnv, stripSecretsEnv } from "../policy/scrub.ts"
|
|
10
|
+
|
|
11
|
+
import { resolveTrustedExecutable } from "../lib/trusted-exec.ts"
|
|
12
|
+
import { sandboxExplicitFallbackAllowed, sandboxStrict } from "../policy/sandbox-policy.ts"
|
|
13
|
+
import { sanitizeSpawnEnv, scrubSecrets } from "../policy/scrub.ts"
|
|
14
|
+
import { dockerAvailable, runInDocker } from "../sandbox/docker.ts"
|
|
15
|
+
import { osSandboxAvailable, runInOsSandbox } from "../sandbox/os.ts"
|
|
16
|
+
|
|
17
|
+
// ── Output buffer dengan cap saat streaming ──
|
|
18
|
+
// Cap diterapkan SAAT data masuk, bukan slice di akhir: command dengan output
|
|
19
|
+
// raksasa (`yes`, `cat file-1GB`) tidak boleh membawa proses ke OOM.
|
|
20
|
+
class CappedBuffer {
|
|
21
|
+
private out = ""
|
|
22
|
+
private err = ""
|
|
23
|
+
truncated = false
|
|
24
|
+
constructor(private readonly cap: number) {}
|
|
25
|
+
|
|
26
|
+
append(target: "out" | "err", chunk: Buffer | string): string {
|
|
27
|
+
const s = typeof chunk === "string" ? chunk : chunk.toString()
|
|
28
|
+
const cur = target === "out" ? this.out : this.err
|
|
29
|
+
if (cur.length >= this.cap) {
|
|
30
|
+
this.truncated = true
|
|
31
|
+
return ""
|
|
32
|
+
}
|
|
33
|
+
const room = this.cap - cur.length
|
|
34
|
+
if (s.length > room) this.truncated = true
|
|
35
|
+
const piece = s.slice(0, Math.max(0, room))
|
|
36
|
+
if (target === "out") this.out += piece
|
|
37
|
+
else this.err += piece
|
|
38
|
+
return piece
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Teks gabungan, sudah di-scrub, dengan marker truncation. */
|
|
42
|
+
text(): string {
|
|
43
|
+
const joined = (this.out + (this.err ? `\n[stderr]\n${this.err}` : "")).trim()
|
|
44
|
+
return scrubSecrets(joined) + (this.truncated ? "\n… [output truncated]" : "")
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// F-03: request sandbox EKSPLISIT (MINICODE_SANDBOX=docker/os/...) tanpa
|
|
49
|
+
// backend juga fail-closed secara default — lihat sandboxRefusalReason di
|
|
50
|
+
// policy/sandbox-policy.ts (dipakai CLI) + cabang di bawah (dipakai jalur
|
|
51
|
+
// env-langsung seperti MCP/sub-agen). Downgrade diam-diam ke host membuat
|
|
52
|
+
// operator yakin terisolasi padahal tidak — satu baris [warn] bukan
|
|
53
|
+
// persetujuan. Fallback eksplisit tetap tersedia via
|
|
54
|
+
// MINICODE_SANDBOX_ALLOW_FALLBACK=1 (untuk mesin tanpa backend yang operator
|
|
55
|
+
// sadari), dan tanpa MINICODE_SANDBOX sama sekali perilaku tetap direct.
|
|
56
|
+
|
|
57
|
+
// Penanda truncation: output yang dipotong diam-diam tampak lengkap dan
|
|
58
|
+
// menyesatkan model (temuan audit #02). Selalu tandai bila dipotong.
|
|
59
|
+
export function capMarked(text: string, cap: number): string {
|
|
60
|
+
return text.length > cap
|
|
61
|
+
? `${text.slice(0, cap)}\n… [truncated: showing first ${cap} chars]`
|
|
62
|
+
: text
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// ── Background jobs ──
|
|
66
|
+
// Perlu untuk dev server / watcher / test panjang: proses hidup melewati batas
|
|
67
|
+
// satu turn, output-nya diambil bertahap lewat bash_output.
|
|
68
|
+
interface BackgroundJob {
|
|
69
|
+
id: string
|
|
70
|
+
cmd: string
|
|
71
|
+
startedAt: number
|
|
72
|
+
proc: ReturnType<typeof spawn>
|
|
73
|
+
buffer: CappedBuffer
|
|
74
|
+
/** Offset baca terakhir supaya bash_output hanya mengembalikan yang baru. */
|
|
75
|
+
cursor: number
|
|
76
|
+
chunks: string[]
|
|
77
|
+
exitCode: number | null
|
|
78
|
+
done: boolean
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const jobs = new Map<string, BackgroundJob>()
|
|
82
|
+
|
|
83
|
+
function reapFinishedJobs(): void {
|
|
84
|
+
const now = Date.now()
|
|
85
|
+
for (const [id, j] of jobs) {
|
|
86
|
+
if (j.done && now - j.startedAt > LIMITS.BASH_BACKGROUND_MAX_LIFETIME_MS) jobs.delete(id)
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Bunuh proses + seluruh subtree-nya. Di Windows `p.kill()` hanya membunuh
|
|
92
|
+
* wrapper `cmd.exe` — cucu seperti `node -e "while(true){}"` tetap hidup,
|
|
93
|
+
* menahan pipe stdio sehingga event `close` tidak pernah datang (hang
|
|
94
|
+
* selamanya walau timeout sudah lewat). `taskkill /T` menutup tree-nya.
|
|
95
|
+
*/
|
|
96
|
+
function killTree(p: ReturnType<typeof spawn>): void {
|
|
97
|
+
try {
|
|
98
|
+
if (process.platform === "win32" && p.pid !== undefined) {
|
|
99
|
+
// F-23: resolve absolut dari PATH terpercaya — spawn dengan cwd
|
|
100
|
+
// workspace bisa mengeksekusi taskkill.bat repo (hijack CWD Windows).
|
|
101
|
+
// Env juga disanitasi: proses ini berjalan di timeout dengan hak penuh.
|
|
102
|
+
const r = spawnSync(
|
|
103
|
+
resolveTrustedExecutable("taskkill"),
|
|
104
|
+
["/pid", String(p.pid), "/T", "/F"],
|
|
105
|
+
{
|
|
106
|
+
stdio: "ignore",
|
|
107
|
+
env: sanitizeSpawnEnv(process.env),
|
|
108
|
+
},
|
|
109
|
+
)
|
|
110
|
+
if (r.status === 0) return
|
|
111
|
+
} else if (p.pid !== undefined) {
|
|
112
|
+
// POSIX: bunuh seluruh grup proses (shell wrapper + cucu seperti
|
|
113
|
+
// `node -e`). Spawn foreground memakai detached:true agar shell jadi
|
|
114
|
+
// group leader; kill(-pid) menutup tree-nya.
|
|
115
|
+
try {
|
|
116
|
+
process.kill(-p.pid, "SIGKILL")
|
|
117
|
+
return
|
|
118
|
+
} catch {}
|
|
119
|
+
}
|
|
120
|
+
} catch {}
|
|
121
|
+
try {
|
|
122
|
+
p.kill("SIGKILL")
|
|
123
|
+
} catch {}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Hentikan semua job — dipanggil saat CLI keluar agar tidak ada proses yatim. */
|
|
127
|
+
export function killAllBackgroundJobs(): void {
|
|
128
|
+
for (const [id, j] of jobs) {
|
|
129
|
+
try {
|
|
130
|
+
if (!j.done) j.proc.kill("SIGKILL")
|
|
131
|
+
} catch {}
|
|
132
|
+
jobs.delete(id)
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function listBackgroundJobs(): { id: string; cmd: string; done: boolean }[] {
|
|
137
|
+
return [...jobs.values()].map((j) => ({ id: j.id, cmd: j.cmd, done: j.done }))
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function startBackground(cmd: string, cwd: string | undefined): string {
|
|
141
|
+
reapFinishedJobs()
|
|
142
|
+
const live = [...jobs.values()].filter((j) => !j.done).length
|
|
143
|
+
if (live >= LIMITS.BASH_BACKGROUND_MAX_JOBS) {
|
|
144
|
+
throw new Error(
|
|
145
|
+
`too many background jobs (${live}/${LIMITS.BASH_BACKGROUND_MAX_JOBS}) — stop one with bash_kill first`,
|
|
146
|
+
)
|
|
147
|
+
}
|
|
148
|
+
const id = `bg_${randomUUID().slice(0, 8)}`
|
|
149
|
+
const proc = spawn(cmd, {
|
|
150
|
+
shell: true,
|
|
151
|
+
cwd,
|
|
152
|
+
env: sanitizeSpawnEnv(process.env),
|
|
153
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
154
|
+
})
|
|
155
|
+
const job: BackgroundJob = {
|
|
156
|
+
id,
|
|
157
|
+
cmd,
|
|
158
|
+
startedAt: Date.now(),
|
|
159
|
+
proc,
|
|
160
|
+
buffer: new CappedBuffer(LIMITS.BASH_OUTPUT_MAX_CHARS),
|
|
161
|
+
cursor: 0,
|
|
162
|
+
chunks: [],
|
|
163
|
+
exitCode: null,
|
|
164
|
+
done: false,
|
|
165
|
+
}
|
|
166
|
+
proc.stdout?.on("data", (d: Buffer) => {
|
|
167
|
+
const piece = job.buffer.append("out", d)
|
|
168
|
+
if (piece) job.chunks.push(scrubSecrets(piece))
|
|
169
|
+
})
|
|
170
|
+
proc.stderr?.on("data", (d: Buffer) => {
|
|
171
|
+
const piece = job.buffer.append("err", d)
|
|
172
|
+
if (piece) job.chunks.push(scrubSecrets(piece))
|
|
173
|
+
})
|
|
174
|
+
proc.on("error", (e) => {
|
|
175
|
+
job.chunks.push(`[error] ${e.message}`)
|
|
176
|
+
job.done = true
|
|
177
|
+
})
|
|
178
|
+
proc.on("close", (code) => {
|
|
179
|
+
job.exitCode = code
|
|
180
|
+
job.done = true
|
|
181
|
+
})
|
|
182
|
+
jobs.set(id, job)
|
|
183
|
+
return id
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export const bashTool: Tool = {
|
|
187
|
+
name: "bash",
|
|
188
|
+
description:
|
|
189
|
+
"Run a shell command (default timeout 30s, max output 20k chars, exit code prefixed). Set background:true for long-running processes (dev server, watcher), then collect output via bash_output and stop with bash_kill. Prefer git_status/git_diff/git_log tools over raw `git` commands: raw git executes repository-configured hooks, filters and diff drivers. Destructive, network-exfiltrating, env-dumping, and inline-interpreter commands are blocked. If the shell allowlist denies a command: do NOT retry blindly — file reads/writes belong to read_file/write_file/edit, and a full shell needs the operator to rerun with --allow-all or --sandbox docker. On Windows the shell is cmd.exe (use dir, echo %VAR%, type).",
|
|
190
|
+
parameters: {
|
|
191
|
+
type: "object",
|
|
192
|
+
properties: {
|
|
193
|
+
cmd: { type: "string", description: "command to run (shell: cmd.exe on Windows)" },
|
|
194
|
+
cwd: {
|
|
195
|
+
type: "string",
|
|
196
|
+
description: "working directory relative to the workspace (default: workspace root)",
|
|
197
|
+
},
|
|
198
|
+
timeoutMs: { type: "number", description: "timeout in ms (default 30000)" },
|
|
199
|
+
background: {
|
|
200
|
+
type: "boolean",
|
|
201
|
+
description:
|
|
202
|
+
"run without waiting for completion; returns a job id for bash_output/bash_kill",
|
|
203
|
+
},
|
|
204
|
+
},
|
|
205
|
+
required: ["cmd"],
|
|
206
|
+
additionalProperties: false,
|
|
207
|
+
},
|
|
208
|
+
async execute({ cmd, cwd, timeoutMs, background }, ctx) {
|
|
209
|
+
const sessionRoot = (ctx as { cwd?: string }).cwd ?? process.cwd()
|
|
210
|
+
const c = cwd as string | undefined
|
|
211
|
+
if (c && (isCwdOutsideRoot(c, sessionRoot) || isPathOutsideRoot(c, sessionRoot)))
|
|
212
|
+
throw new Error(`cwd outside workspace: ${c}`)
|
|
213
|
+
const resolvedCwd = c ? resolvePath(sessionRoot, c) : undefined
|
|
214
|
+
const effectiveCwd = resolvedCwd ?? sessionRoot
|
|
215
|
+
const timeout = timeoutMs ?? LIMITS.BASH_DEFAULT_TIMEOUT_MS
|
|
216
|
+
|
|
217
|
+
if (background === true) {
|
|
218
|
+
// Sandbox tidak diterapkan di jalur background: container/namespace
|
|
219
|
+
// ephemeral mati bersama call-nya, jadi menjanjikan isolasi di sini
|
|
220
|
+
// akan menyesatkan. Tolak eksplisit daripada diam-diam tanpa sandbox.
|
|
221
|
+
if (process.env.MINICODE_SANDBOX) {
|
|
222
|
+
throw new Error(
|
|
223
|
+
"background:true is not supported while --sandbox is active (the process must outlive the turn)",
|
|
224
|
+
)
|
|
225
|
+
}
|
|
226
|
+
const id = startBackground(cmd as string, resolvedCwd)
|
|
227
|
+
// F-07: echo perintah di-scrub seperti output foreground — command line
|
|
228
|
+
// bisa membawa secret (`curl -H "Authorization: Bearer …"`), dan versi
|
|
229
|
+
// lama menaruhnya mentah ke konteks model.
|
|
230
|
+
return `background job started: ${id}\ncmd: ${scrubSecrets(String(cmd)).slice(0, 200)}\ncollect output: bash_output({ id: "${id}" })`
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// Docker sandbox mode — run in ephemeral isolated container
|
|
234
|
+
if (process.env.MINICODE_SANDBOX === "docker") {
|
|
235
|
+
if (dockerAvailable()) {
|
|
236
|
+
const res = await runInDocker(cmd as string, effectiveCwd, {
|
|
237
|
+
timeoutMs: timeout,
|
|
238
|
+
env: sanitizeSpawnEnv(process.env) as Record<string, string>,
|
|
239
|
+
})
|
|
240
|
+
const text = scrubSecrets(res.output)
|
|
241
|
+
if (res.code !== 0 && res.code !== null)
|
|
242
|
+
return `exit ${res.code}\n${capMarked(text, 20000)}`
|
|
243
|
+
return capMarked(text, 20000)
|
|
244
|
+
}
|
|
245
|
+
if (sandboxStrict() || !sandboxExplicitFallbackAllowed()) {
|
|
246
|
+
throw new Error(
|
|
247
|
+
"[sandbox] MINICODE_SANDBOX=docker but docker unavailable — refusing direct execution (explicit sandbox request must not silently downgrade; set MINICODE_SANDBOX_ALLOW_FALLBACK=1 to allow host fallback explicitly)",
|
|
248
|
+
)
|
|
249
|
+
}
|
|
250
|
+
process.stderr.write(
|
|
251
|
+
"[warn] MINICODE_SANDBOX=docker but docker unavailable — falling back to direct execution (explicit MINICODE_SANDBOX_ALLOW_FALLBACK=1)\n",
|
|
252
|
+
)
|
|
253
|
+
}
|
|
254
|
+
// OS-native sandbox (Seatbelt macOS / bubblewrap Linux) — Codex/Gemini-like without Docker
|
|
255
|
+
if (
|
|
256
|
+
process.env.MINICODE_SANDBOX === "os" ||
|
|
257
|
+
process.env.MINICODE_SANDBOX === "seatbelt" ||
|
|
258
|
+
process.env.MINICODE_SANDBOX === "bwrap"
|
|
259
|
+
) {
|
|
260
|
+
if (osSandboxAvailable()) {
|
|
261
|
+
const res = await runInOsSandbox(cmd as string, effectiveCwd, {
|
|
262
|
+
timeoutMs: timeout,
|
|
263
|
+
env: sanitizeSpawnEnv(process.env) as Record<string, string>,
|
|
264
|
+
})
|
|
265
|
+
const text = scrubSecrets(res.output)
|
|
266
|
+
if (res.code !== 0 && res.code !== null)
|
|
267
|
+
return `exit ${res.code}\n${capMarked(text, 20000)}`
|
|
268
|
+
return capMarked(text, 20000)
|
|
269
|
+
}
|
|
270
|
+
if (sandboxStrict() || !sandboxExplicitFallbackAllowed()) {
|
|
271
|
+
throw new Error(
|
|
272
|
+
"[sandbox] OS sandbox unavailable — refusing direct execution (explicit sandbox request must not silently downgrade; set MINICODE_SANDBOX_ALLOW_FALLBACK=1 to allow host fallback explicitly)",
|
|
273
|
+
)
|
|
274
|
+
}
|
|
275
|
+
process.stderr.write(
|
|
276
|
+
"[warn] MINICODE_SANDBOX=os but OS sandbox unavailable — falling back to direct execution (explicit MINICODE_SANDBOX_ALLOW_FALLBACK=1)\n",
|
|
277
|
+
)
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
return await new Promise((resolveOut, reject) => {
|
|
281
|
+
const p = spawn(cmd as string, {
|
|
282
|
+
shell: true,
|
|
283
|
+
// F-24: selalu effectiveCwd (sessionRoot bila arg cwd absen), bukan
|
|
284
|
+
// undefined (= inherit process.cwd()). Jail/permission dievaluasi
|
|
285
|
+
// terhadap sessionRoot — eksekusi harus di direktori yang sama.
|
|
286
|
+
cwd: effectiveCwd,
|
|
287
|
+
env: sanitizeSpawnEnv(process.env),
|
|
288
|
+
signal: ctx.signal,
|
|
289
|
+
// detached agar shell jadi group leader → killTree bisa bunuh
|
|
290
|
+
// seluruh grup (POSIX kill(-pid)). Tanpa ini cucu yatim menahan pipe.
|
|
291
|
+
detached: process.platform !== "win32",
|
|
292
|
+
})
|
|
293
|
+
const buf = new CappedBuffer(LIMITS.BASH_OUTPUT_MAX_CHARS)
|
|
294
|
+
// Progres inkremental: command panjang (bun test, build) tidak lagi
|
|
295
|
+
// membisu sampai selesai. Event ini opsional bagi UI.
|
|
296
|
+
const emitChunk = (piece: string) => {
|
|
297
|
+
if (!piece) return
|
|
298
|
+
try {
|
|
299
|
+
ctx.emit?.({
|
|
300
|
+
type: "provider:extension",
|
|
301
|
+
kind: "bash-output",
|
|
302
|
+
data: { text: scrubSecrets(piece) },
|
|
303
|
+
})
|
|
304
|
+
} catch {}
|
|
305
|
+
}
|
|
306
|
+
p.stdout.on("data", (d: Buffer) => emitChunk(buf.append("out", d)))
|
|
307
|
+
p.stderr.on("data", (d: Buffer) => emitChunk(buf.append("err", d)))
|
|
308
|
+
p.on("error", reject)
|
|
309
|
+
p.on("close", (code) => {
|
|
310
|
+
const text = buf.text()
|
|
311
|
+
if (code !== 0) resolveOut(`exit ${code}\n${text}`)
|
|
312
|
+
else resolveOut(text)
|
|
313
|
+
})
|
|
314
|
+
let killTimer: ReturnType<typeof setTimeout> | undefined
|
|
315
|
+
const t = setTimeout(() => {
|
|
316
|
+
// Windows: SIGTERM hanya membunuh cmd.exe wrapper — cucu (node -e)
|
|
317
|
+
// bisa belum lahir (spawn lambat) atau yatim sambil menahan pipe.
|
|
318
|
+
// Eskalasi taskkill /pid-shell-yang-sudah-mati lalu gagal total.
|
|
319
|
+
// Jadi di win32 langsung tree-kill saat timeout, tanpa jeda.
|
|
320
|
+
if (process.platform === "win32") killTree(p)
|
|
321
|
+
else p.kill("SIGTERM")
|
|
322
|
+
killTimer = setTimeout(() => {
|
|
323
|
+
killTree(p)
|
|
324
|
+
}, 2000)
|
|
325
|
+
}, timeout)
|
|
326
|
+
ctx.signal.addEventListener(
|
|
327
|
+
"abort",
|
|
328
|
+
() => {
|
|
329
|
+
clearTimeout(t)
|
|
330
|
+
if (killTimer) clearTimeout(killTimer)
|
|
331
|
+
if (process.platform === "win32") killTree(p)
|
|
332
|
+
else p.kill("SIGTERM")
|
|
333
|
+
killTimer = setTimeout(() => {
|
|
334
|
+
killTree(p)
|
|
335
|
+
}, 1000)
|
|
336
|
+
},
|
|
337
|
+
{ once: true },
|
|
338
|
+
)
|
|
339
|
+
p.on("close", () => {
|
|
340
|
+
clearTimeout(t)
|
|
341
|
+
if (killTimer) clearTimeout(killTimer)
|
|
342
|
+
})
|
|
343
|
+
})
|
|
344
|
+
},
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
export const bashOutputTool: Tool = {
|
|
348
|
+
name: "bash_output",
|
|
349
|
+
description:
|
|
350
|
+
"Get NEW output from a background job (since the last read). Includes the exit status once it has finished.",
|
|
351
|
+
parameters: {
|
|
352
|
+
type: "object",
|
|
353
|
+
properties: {
|
|
354
|
+
id: { type: "string", description: "job id dari bash background:true" },
|
|
355
|
+
},
|
|
356
|
+
required: ["id"],
|
|
357
|
+
additionalProperties: false,
|
|
358
|
+
},
|
|
359
|
+
async execute({ id }, ctx: ToolContext) {
|
|
360
|
+
ctx.signal.throwIfAborted()
|
|
361
|
+
const job = jobs.get(String(id))
|
|
362
|
+
if (!job) {
|
|
363
|
+
const live = listBackgroundJobs()
|
|
364
|
+
throw new Error(
|
|
365
|
+
`job "${id}" not found${live.length ? ` — active: ${live.map((j) => j.id).join(", ")}` : ""}`,
|
|
366
|
+
)
|
|
367
|
+
}
|
|
368
|
+
const fresh = job.chunks.slice(job.cursor)
|
|
369
|
+
job.cursor = job.chunks.length
|
|
370
|
+
const status = job.done ? `finished (exit ${job.exitCode ?? "?"})` : "running"
|
|
371
|
+
if (fresh.length === 0) return `[${job.id}] ${status} — no new output yet`
|
|
372
|
+
return capMarked(`[${job.id}] ${status}\n${fresh.join("")}`, LIMITS.BASH_OUTPUT_MAX_CHARS)
|
|
373
|
+
},
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
export const bashKillTool: Tool = {
|
|
377
|
+
name: "bash_kill",
|
|
378
|
+
description: "Stop a background job (SIGTERM then SIGKILL).",
|
|
379
|
+
parameters: {
|
|
380
|
+
type: "object",
|
|
381
|
+
properties: { id: { type: "string", description: "job id" } },
|
|
382
|
+
required: ["id"],
|
|
383
|
+
additionalProperties: false,
|
|
384
|
+
},
|
|
385
|
+
async execute({ id }, ctx: ToolContext) {
|
|
386
|
+
ctx.signal.throwIfAborted()
|
|
387
|
+
const job = jobs.get(String(id))
|
|
388
|
+
if (!job) throw new Error(`job "${id}" not found`)
|
|
389
|
+
if (job.done) return `[${job.id}] already finished (exit ${job.exitCode ?? "?"})`
|
|
390
|
+
try {
|
|
391
|
+
job.proc.kill("SIGTERM")
|
|
392
|
+
} catch {}
|
|
393
|
+
setTimeout(() => {
|
|
394
|
+
try {
|
|
395
|
+
if (!job.done) job.proc.kill("SIGKILL")
|
|
396
|
+
} catch {}
|
|
397
|
+
}, 1000)
|
|
398
|
+
return `[${job.id}] stopped`
|
|
399
|
+
},
|
|
400
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import type { Tool } from "#minicore"
|
|
2
|
+
import { LIMITS } from "../constants.ts"
|
|
3
|
+
import { scrubSecrets } from "../policy/scrub.ts"
|
|
4
|
+
import { dockerAvailable, runInDocker } from "../sandbox/docker.ts"
|
|
5
|
+
import { osSandboxAvailable, runInOsSandbox } from "../sandbox/os.ts"
|
|
6
|
+
import { capMarked } from "./bash.ts"
|
|
7
|
+
|
|
8
|
+
// code_run: snippet python/node dieksekusi LEWAT sandbox runner (docker atau
|
|
9
|
+
// OS sandbox), bukan spawn host langsung — versi lama hanya mengecek env flag
|
|
10
|
+
// lalu spawn host tanpa isolasi (klaim "sandboxed" yang salah).
|
|
11
|
+
//
|
|
12
|
+
// Batasan jujur:
|
|
13
|
+
// - Backend HARUS tersedia; flag tanpa backend = tolak (fail-closed, tanpa
|
|
14
|
+
// fallback diam-diam ke host).
|
|
15
|
+
// - docker image default (node:22-alpine) membawa node, bukan python3 —
|
|
16
|
+
// python butuh MINICODE_SANDBOX_IMAGE yang menyediakannya.
|
|
17
|
+
// - Pembatalan menghentikan PENUNGGUAN; container/proses bisa hidup sampai
|
|
18
|
+
// timeout runner-nya sendiri (terdokumentasi, sama seperti MCP stdio).
|
|
19
|
+
|
|
20
|
+
/** Escape untuk disisip sebagai satu argumen single-quoted di `sh -c`. */
|
|
21
|
+
export function shSingleQuote(s: string): string {
|
|
22
|
+
return `'${s.replace(/'/g, `'\\''`)}'`
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export const codeRunTool: Tool = {
|
|
26
|
+
name: "code_run",
|
|
27
|
+
description:
|
|
28
|
+
"Run a code snippet (python -c / node -e) inside the configured sandbox (docker or OS sandbox, network-isolated). Requires MINICODE_SANDBOX=os|docker with a working backend; refuses otherwise. Python needs an image containing python3.",
|
|
29
|
+
parameters: {
|
|
30
|
+
type: "object",
|
|
31
|
+
properties: {
|
|
32
|
+
lang: { type: "string", enum: ["python", "node"], description: "runtime" },
|
|
33
|
+
code: { type: "string", description: "snippet to run" },
|
|
34
|
+
timeout: { type: "number", description: "ms, default 10000" },
|
|
35
|
+
},
|
|
36
|
+
required: ["lang", "code"],
|
|
37
|
+
additionalProperties: false,
|
|
38
|
+
},
|
|
39
|
+
async execute({ lang, code, timeout }, ctx) {
|
|
40
|
+
ctx.signal.throwIfAborted()
|
|
41
|
+
const sandbox = process.env.MINICODE_SANDBOX ?? ""
|
|
42
|
+
if (sandbox !== "os" && sandbox !== "docker" && sandbox !== "bwrap" && sandbox !== "seatbelt") {
|
|
43
|
+
throw new Error(
|
|
44
|
+
`code_run requires MINICODE_SANDBOX=os|docker (current: ${sandbox || "none"})`,
|
|
45
|
+
)
|
|
46
|
+
}
|
|
47
|
+
const src = code as string
|
|
48
|
+
if (src.includes("\0")) throw new Error("code contains NUL byte")
|
|
49
|
+
const root = (ctx as { cwd?: string }).cwd ?? process.cwd()
|
|
50
|
+
const timeoutMs =
|
|
51
|
+
typeof timeout === "number" && Number.isFinite(timeout) && timeout > 0 ? timeout : 10000
|
|
52
|
+
// Tanpa shell perantara di sisi kita: kode jadi SATU argumen single-quoted
|
|
53
|
+
// untuk `sh -c` runner — $()/backtick milik snippet, bukan shell luar.
|
|
54
|
+
const inner =
|
|
55
|
+
lang === "python" ? `python3 -c ${shSingleQuote(src)}` : `node -e ${shSingleQuote(src)}`
|
|
56
|
+
// Fail-closed: backend yang diminta harus benar-benar ada. Fallback diam
|
|
57
|
+
// ke eksekusi host akan mengkhianati janji sandbox.
|
|
58
|
+
const runSandboxed =
|
|
59
|
+
sandbox === "docker"
|
|
60
|
+
? () => {
|
|
61
|
+
if (!dockerAvailable()) {
|
|
62
|
+
throw new Error("code_run: MINICODE_SANDBOX=docker but docker is not available")
|
|
63
|
+
}
|
|
64
|
+
return runInDocker(inner, root, { timeoutMs })
|
|
65
|
+
}
|
|
66
|
+
: () => {
|
|
67
|
+
if (!osSandboxAvailable()) {
|
|
68
|
+
throw new Error(
|
|
69
|
+
`code_run: MINICODE_SANDBOX=${sandbox} but no OS sandbox is available`,
|
|
70
|
+
)
|
|
71
|
+
}
|
|
72
|
+
return runInOsSandbox(inner, root, { timeoutMs })
|
|
73
|
+
}
|
|
74
|
+
const started = runSandboxed()
|
|
75
|
+
// Runner tak menerima signal: balapan agar pembatalan menolak menunggu.
|
|
76
|
+
// (Container/proses bisa hidup sampai timeout runner — lihat komentar atas.)
|
|
77
|
+
const onAbort = (): Promise<never> =>
|
|
78
|
+
Promise.reject(ctx.signal.reason instanceof Error ? ctx.signal.reason : new Error("aborted"))
|
|
79
|
+
const settled: { code: number | null; output: string } = ctx.signal.aborted
|
|
80
|
+
? await onAbort()
|
|
81
|
+
: await Promise.race([
|
|
82
|
+
started,
|
|
83
|
+
new Promise<never>((_, rej) =>
|
|
84
|
+
ctx.signal.addEventListener(
|
|
85
|
+
"abort",
|
|
86
|
+
() =>
|
|
87
|
+
rej(ctx.signal.reason instanceof Error ? ctx.signal.reason : new Error("aborted")),
|
|
88
|
+
{ once: true },
|
|
89
|
+
),
|
|
90
|
+
),
|
|
91
|
+
])
|
|
92
|
+
const text = capMarked(scrubSecrets(settled.output), LIMITS.BASH_OUTPUT_MAX_CHARS).trim()
|
|
93
|
+
if (settled.code !== 0) return `exit ${settled.code}\n${text}`
|
|
94
|
+
return text
|
|
95
|
+
},
|
|
96
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { stat } from "node:fs/promises"
|
|
2
|
+
import type { Tool } from "#minicore"
|
|
3
|
+
import { resolveSafePath } from "../lib/safe-open.ts"
|
|
4
|
+
import { trashFile } from "../lib/trash.ts"
|
|
5
|
+
|
|
6
|
+
export const deleteFileTool: Tool = {
|
|
7
|
+
name: "delete_file",
|
|
8
|
+
description:
|
|
9
|
+
"Delete a file (soft-delete to .minicode/.trash/ with undo via move). Use for removing files.",
|
|
10
|
+
parameters: {
|
|
11
|
+
type: "object",
|
|
12
|
+
properties: {
|
|
13
|
+
path: { type: "string", description: "path file relatif" },
|
|
14
|
+
},
|
|
15
|
+
required: ["path"],
|
|
16
|
+
additionalProperties: false,
|
|
17
|
+
},
|
|
18
|
+
async execute({ path }, ctx) {
|
|
19
|
+
ctx.signal.throwIfAborted()
|
|
20
|
+
const p = path as string
|
|
21
|
+
const root = (ctx as { cwd?: string }).cwd ?? process.cwd()
|
|
22
|
+
// Verifikasi path terpusat (logis + target nyata) — detail di safe-open.ts.
|
|
23
|
+
const { abs, real } = await resolveSafePath(p, root)
|
|
24
|
+
const st = await stat(real).catch(() => null)
|
|
25
|
+
if (!st) throw new Error(`file not found: ${p}`)
|
|
26
|
+
if (st.isDirectory()) throw new Error(`path is directory, use bash rm -r: ${p}`)
|
|
27
|
+
// soft-delete ke .minicode/.trash (gitignored, cap 100) — restore via move_file
|
|
28
|
+
const dest = await trashFile(root, abs)
|
|
29
|
+
return `deleted ${p} -> ${dest} (soft-delete, restore via move_file if needed)`
|
|
30
|
+
},
|
|
31
|
+
}
|