minicode-ai 0.23.0 → 0.26.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 +5 -3
- package/cli/commands/config.ts +123 -0
- package/cli/setup.ts +107 -8
- package/cli/tui.ts +28 -2
- package/docs/README.md +2 -2
- package/docs/SUMMARY.md +10 -19
- package/docs/TERMINAL_CONTRACT.md +113 -28
- package/docs/architecture.md +1 -1
- package/docs/autonomous-scheduler.md +283 -2
- package/docs/choosing-mode.md +4 -4
- package/docs/concepts.md +39 -3
- package/docs/config.md +103 -5
- package/docs/environment.md +4 -0
- package/docs/getting-started.md +69 -5
- package/docs/repl.md +1 -1
- package/docs/security.md +49 -2
- package/docs/tools.md +2 -1
- package/package.json +2 -36
- package/src/app/provider-layer.ts +1 -1
- package/src/app/session.ts +187 -17
- package/src/config.ts +21 -8
- package/src/constants.ts +17 -1
- package/src/lib/net.ts +6 -15
- package/src/lib/public-http.ts +128 -0
- package/src/lib/safe-open.ts +21 -12
- package/src/memory/vector.ts +0 -31
- package/src/policy/auto-resume.ts +63 -0
- package/src/policy/compaction.ts +354 -70
- package/src/policy/context-budget.ts +4 -6
- package/src/policy/context-window-assign.ts +114 -0
- package/src/policy/context-window-catalog.ts +4 -1
- package/src/policy/context-window-presets.ts +165 -0
- package/src/policy/context-window.ts +19 -37
- package/src/policy/context.ts +11 -9
- package/src/policy/executor.ts +69 -27
- package/src/policy/microcompact.ts +76 -15
- package/src/policy/no-progress.ts +1 -1
- package/src/policy/permission.ts +5 -0
- package/src/policy/recovery-budget.ts +281 -0
- package/src/policy/scrub.ts +15 -2
- package/src/policy/step-escalation.ts +82 -0
- package/src/policy/tokenizer-registry.ts +1 -0
- package/src/policy/tool-contract.ts +11 -9
- package/src/presentation/reducer.ts +1 -0
- package/src/providers/anthropic.ts +3 -3
- package/src/providers/detect.ts +40 -7
- package/src/providers/provision.ts +23 -1
- package/src/runtime/child-execution.ts +4 -2
- package/src/runtime/execution-backend.ts +3 -0
- package/src/sandbox/os.ts +53 -9
- package/src/session/context-assembly.ts +11 -7
- package/src/session/persistence.ts +19 -3
- package/src/task/autonomous-policy.ts +7 -0
- package/src/task/graph-validate.ts +1 -1
- package/src/task/session-authority.ts +0 -5
- package/src/task/store.ts +0 -4
- package/src/tools/ask_user.ts +14 -1
- package/src/tools/bash.ts +68 -17
- package/src/tools/code_run.ts +19 -20
- package/src/tools/context.ts +10 -0
- package/src/tools/delete_file.ts +3 -2
- package/src/tools/edit.ts +5 -4
- package/src/tools/git.ts +70 -12
- package/src/tools/glob.ts +13 -5
- package/src/tools/grep.ts +26 -10
- package/src/tools/index.ts +3 -2
- package/src/tools/lsp.ts +15 -9
- package/src/tools/move_file.ts +4 -3
- package/src/tools/patch.ts +5 -4
- package/src/tools/read_file.ts +3 -2
- package/src/tools/read_image.ts +3 -2
- package/src/tools/task.ts +5 -1
- package/src/tools/todo.ts +4 -8
- package/src/tools/web_fetch.ts +13 -19
- package/src/tools/write_file.ts +4 -3
- package/src/ui/approval/prompt.ts +226 -77
- package/src/ui/assistant/simple.ts +61 -10
- package/src/ui/footer.ts +41 -29
- package/src/ui/i18n/en.ts +7 -0
- package/src/ui/i18n/id.ts +7 -0
- package/src/ui/input/prompt-engine.ts +53 -21
- package/src/ui/render/activity-group.ts +9 -0
- package/src/ui/render/activity-panel.ts +20 -2
- package/src/ui/render/ledger.ts +1 -9
- package/src/ui/render/logo.ts +0 -5
- package/src/ui/render/markdown-table.ts +0 -3
- package/src/ui/render/table-grid.ts +0 -3
- package/src/ui/render/theme.ts +31 -5
- package/src/ui/runtime/screen.ts +7 -1
- package/src/ui/screens/dialog.ts +45 -81
- package/src/ui/screens/form.ts +10 -10
- package/src/ui/screens/model-manager.ts +7 -10
- package/src/ui/screens/picker.ts +8 -11
- package/src/ui/screens/provider-manager.ts +9 -13
- package/src/ui/tui/app.ts +118 -20
- package/src/ui/tui/transcript.ts +179 -29
- package/vendor/minicore/src/core/loop.ts +20 -1
- package/vendor/minicore/src/core/session.ts +6 -0
- package/docs/P14_OPEN_WORK.md +0 -290
- package/docs/config-providers.md +0 -87
- package/docs/glossary.md +0 -39
- package/docs/quickstart.md +0 -60
- package/docs/security-model.md +0 -96
- package/docs/terminal.md +0 -91
|
@@ -163,6 +163,7 @@ export interface BackendHandle {
|
|
|
163
163
|
}
|
|
164
164
|
|
|
165
165
|
export interface BackendExecRequest {
|
|
166
|
+
readonly signal?: AbortSignal
|
|
166
167
|
readonly cmd: string
|
|
167
168
|
readonly cwd?: string
|
|
168
169
|
readonly timeoutMs?: number
|
|
@@ -604,6 +605,7 @@ export function createBwrapBackend(): ExecutionBackend {
|
|
|
604
605
|
"bwrap unavailable on this platform",
|
|
605
606
|
(req) =>
|
|
606
607
|
runInOsSandbox(req.cmd, req.cwd ?? process.cwd(), {
|
|
608
|
+
...(req.signal ? { signal: req.signal } : {}),
|
|
607
609
|
...(req.timeoutMs !== undefined ? { timeoutMs: req.timeoutMs } : {}),
|
|
608
610
|
...(req.env ? { env: req.env } : {}),
|
|
609
611
|
}),
|
|
@@ -617,6 +619,7 @@ export function createSeatbeltBackend(): ExecutionBackend {
|
|
|
617
619
|
"seatbelt unavailable on this platform",
|
|
618
620
|
(req) =>
|
|
619
621
|
runInOsSandbox(req.cmd, req.cwd ?? process.cwd(), {
|
|
622
|
+
...(req.signal ? { signal: req.signal } : {}),
|
|
620
623
|
...(req.timeoutMs !== undefined ? { timeoutMs: req.timeoutMs } : {}),
|
|
621
624
|
...(req.env ? { env: req.env } : {}),
|
|
622
625
|
}),
|
package/src/sandbox/os.ts
CHANGED
|
@@ -59,6 +59,7 @@ export function osSandboxTypeName(): string {
|
|
|
59
59
|
}
|
|
60
60
|
|
|
61
61
|
export interface OsSandboxOptions {
|
|
62
|
+
signal?: AbortSignal
|
|
62
63
|
env?: Record<string, string>
|
|
63
64
|
timeoutMs?: number
|
|
64
65
|
network?: "none" | "bridge"
|
|
@@ -71,6 +72,7 @@ export function runInOsSandbox(
|
|
|
71
72
|
cwd: string,
|
|
72
73
|
opts: OsSandboxOptions = {},
|
|
73
74
|
): Promise<{ code: number | null; output: string }> {
|
|
75
|
+
if (opts.signal?.aborted) return Promise.reject(opts.signal.reason)
|
|
74
76
|
const { available, type } = detectOsSandbox()
|
|
75
77
|
if (!available) {
|
|
76
78
|
// Fail-closed seam: pemanggil (bash/code_run) wajib cek osSandboxAvailable
|
|
@@ -99,7 +101,7 @@ export function runInOsSandbox(
|
|
|
99
101
|
`
|
|
100
102
|
// Use sandbox-exec with inline profile via stdin? sandbox-exec needs file, write tmp
|
|
101
103
|
const args = ["-p", profile, "sh", "-c", command]
|
|
102
|
-
return runSpawn("sandbox-exec", args, abs, sanitizedEnv, timeout)
|
|
104
|
+
return runSpawn("sandbox-exec", args, abs, sanitizedEnv, timeout, opts.signal)
|
|
103
105
|
}
|
|
104
106
|
if (type === "bwrap") {
|
|
105
107
|
const args = [
|
|
@@ -139,7 +141,7 @@ export function runInOsSandbox(
|
|
|
139
141
|
const idx = args.indexOf("--unshare-net")
|
|
140
142
|
if (idx !== -1) args.splice(idx, 1)
|
|
141
143
|
}
|
|
142
|
-
return runSpawn("bwrap", args, abs, sanitizedEnv, timeout)
|
|
144
|
+
return runSpawn("bwrap", args, abs, sanitizedEnv, timeout, opts.signal)
|
|
143
145
|
}
|
|
144
146
|
return Promise.resolve({ code: null, output: "[os-sandbox] unknown type" })
|
|
145
147
|
}
|
|
@@ -150,8 +152,10 @@ function runSpawn(
|
|
|
150
152
|
cwd: string,
|
|
151
153
|
env: Record<string, string>,
|
|
152
154
|
timeoutMs: number,
|
|
155
|
+
signal?: AbortSignal,
|
|
153
156
|
): Promise<{ code: number | null; output: string }> {
|
|
154
|
-
return new Promise((resolveResult) => {
|
|
157
|
+
return new Promise((resolveResult, reject) => {
|
|
158
|
+
signal?.throwIfAborted()
|
|
155
159
|
// F-23: bin di-resolve absolut dari PATH terpercaya di sini (satu titik
|
|
156
160
|
// untuk seatbelt/bwrap) — spawn dengan cwd workspace di Windows bisa
|
|
157
161
|
// mengeksekusi <bin>.bat repo bila hanya nama telanjang.
|
|
@@ -185,7 +189,10 @@ function runSpawn(
|
|
|
185
189
|
}
|
|
186
190
|
p.stdout.on("data", (d) => appendCapped("out", d))
|
|
187
191
|
p.stderr.on("data", (d) => appendCapped("err", d))
|
|
188
|
-
|
|
192
|
+
let aborted = false
|
|
193
|
+
let timedOut = false
|
|
194
|
+
let settled = false
|
|
195
|
+
const killGroup = (): void => {
|
|
189
196
|
// SIGKILL ke seluruh process group (bwrap + child command). Fallback ke
|
|
190
197
|
// kill tunggal bila pid tak tersedia (spawn gagal sinkron).
|
|
191
198
|
try {
|
|
@@ -196,16 +203,53 @@ function runSpawn(
|
|
|
196
203
|
p.kill("SIGKILL")
|
|
197
204
|
} catch {}
|
|
198
205
|
}
|
|
199
|
-
}
|
|
200
|
-
|
|
206
|
+
}
|
|
207
|
+
const onAbort = (): void => {
|
|
208
|
+
if (settled || aborted) return
|
|
209
|
+
aborted = true
|
|
201
210
|
clearTimeout(t)
|
|
202
|
-
|
|
203
|
-
}
|
|
204
|
-
|
|
211
|
+
killGroup()
|
|
212
|
+
}
|
|
213
|
+
const cleanup = (): void => {
|
|
214
|
+
settled = true
|
|
205
215
|
clearTimeout(t)
|
|
216
|
+
signal?.removeEventListener("abort", onAbort)
|
|
217
|
+
}
|
|
218
|
+
const t = setTimeout(() => {
|
|
219
|
+
timedOut = true
|
|
220
|
+
killGroup()
|
|
221
|
+
}, timeoutMs)
|
|
222
|
+
p.once("error", (e) => {
|
|
223
|
+
cleanup()
|
|
224
|
+
if (aborted) reject(signal?.reason)
|
|
225
|
+
else resolveResult({ code: null, output: `[os-sandbox] ${e.message}` })
|
|
226
|
+
})
|
|
227
|
+
p.once("close", (code) => {
|
|
228
|
+
if (settled) return
|
|
229
|
+
cleanup()
|
|
230
|
+
if (aborted) {
|
|
231
|
+
reject(signal?.reason)
|
|
232
|
+
return
|
|
233
|
+
}
|
|
206
234
|
const marker = truncated ? "\n… [output truncated]" : ""
|
|
207
235
|
const output = (out + (err ? `\n[stderr]\n${err}` : "")).trim() + marker
|
|
236
|
+
if (timedOut) {
|
|
237
|
+
// Kontrak lapisan ini adalah RESOLVE (bukan reject): runner hanya
|
|
238
|
+
// melaporkan hasil proses (code/output), dan pemanggil yang memutuskan
|
|
239
|
+
// arti code=null. Dulu di sini `reject` untuk timeout, sementara abort
|
|
240
|
+
// `resolve` — kontraknya campur, sehingga `code_run` (yang tidak menangkap
|
|
241
|
+
// reject) meneruskan timeout sebagai error tak terduga. Docker runner
|
|
242
|
+
// sudah resolve untuk timeout; disamakan di sini.
|
|
243
|
+
resolveResult({
|
|
244
|
+
code: null,
|
|
245
|
+
output: `[os-sandbox] timed out after ${timeoutMs}ms; effects are UNKNOWN, inspect before retrying${marker ? `\n${marker}` : ""}${output ? `\n${output}` : ""}`,
|
|
246
|
+
})
|
|
247
|
+
return
|
|
248
|
+
}
|
|
208
249
|
resolveResult({ code, output })
|
|
209
250
|
})
|
|
251
|
+
signal?.addEventListener("abort", onAbort, { once: true })
|
|
252
|
+
// Close the race between the pre-spawn check and listener registration.
|
|
253
|
+
if (signal?.aborted) onAbort()
|
|
210
254
|
})
|
|
211
255
|
}
|
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
// seq, run_id, thread_id, migrated, …) dan tidak pernah ditulis balik ke histori.
|
|
22
22
|
|
|
23
23
|
import type { Message } from "#minicore/core/types.ts"
|
|
24
|
+
import { registerCompactionSummary } from "../policy/compaction.ts"
|
|
24
25
|
import {
|
|
25
26
|
getProjection,
|
|
26
27
|
getProjectionStatus,
|
|
@@ -67,12 +68,15 @@ export interface ContextView {
|
|
|
67
68
|
* (role+content). Field persistence-only DILARANG di sini.
|
|
68
69
|
*/
|
|
69
70
|
export function syntheticSummaryMessage(summary: string, coveredSeq: number): Message {
|
|
70
|
-
return
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
71
|
+
return registerCompactionSummary(
|
|
72
|
+
{
|
|
73
|
+
role: "user",
|
|
74
|
+
// Penanda cakupan eksplisit supaya model (dan pembaca log) tahu ini
|
|
75
|
+
// ringkasan prefix [0,N), bukan pesan kanonik.
|
|
76
|
+
content: `Previous context [0,${coveredSeq}):\n${summary}`,
|
|
77
|
+
},
|
|
78
|
+
summary,
|
|
79
|
+
)
|
|
76
80
|
}
|
|
77
81
|
|
|
78
82
|
/**
|
|
@@ -161,7 +165,7 @@ function assembleViewMessages(
|
|
|
161
165
|
const combined: ContextOnlyArtifact = { role: "user", content: combinedContent }
|
|
162
166
|
const rest = messages.slice(1) // buang synthetic lama (index 0)
|
|
163
167
|
return {
|
|
164
|
-
messages: [combined as Message, ...rest],
|
|
168
|
+
messages: [registerCompactionSummary(combined as Message, summaryArtifact.content), ...rest],
|
|
165
169
|
contextOnly: combined,
|
|
166
170
|
runtimeHeader: { role: "user", content: headerText },
|
|
167
171
|
}
|
|
@@ -1212,9 +1212,18 @@ export async function saveSession(
|
|
|
1212
1212
|
// P2.5: tiap baris baru mendapat event_id fresh SATU KALI di sini;
|
|
1213
1213
|
// save ulang identik = no-op (prefixSame) sehingga id stabil.
|
|
1214
1214
|
// P2.6: baris baru dicap run_id pemanggil (bila ada).
|
|
1215
|
+
//
|
|
1216
|
+
// [T-004 OBSERVATION] `ts` WAJIB per-baris, bukan satu `now` untuk seluruh
|
|
1217
|
+
// batch. Dengan satu nilai, seluruh riwayat yang tersimpan lewat jalur ini
|
|
1218
|
+
// berbagi timestamp identik (sesi 17b6a5ff: 159 pesan / 1 nilai) sehingga
|
|
1219
|
+
// linimasa tidak bisa direkonstruksi dari DB sama sekali. Penjaga monotonic
|
|
1220
|
+
// mempertahankan invariant yang selama ini tak sengaja berlaku: ts tidak
|
|
1221
|
+
// pernah mundur terhadap seq (jam sistem bisa mundur/NTP koreksi).
|
|
1222
|
+
let stamp = now
|
|
1215
1223
|
for (let i = known; i < messages.length; i++) {
|
|
1216
1224
|
const m = messages[i] as StoredMsg
|
|
1217
1225
|
const w = normalizeMessageTupleForDedup(m)
|
|
1226
|
+
stamp = Math.max(stamp, Date.now())
|
|
1218
1227
|
ins.run(
|
|
1219
1228
|
id,
|
|
1220
1229
|
tid,
|
|
@@ -1226,7 +1235,7 @@ export async function saveSession(
|
|
|
1226
1235
|
w[4],
|
|
1227
1236
|
w[5],
|
|
1228
1237
|
w[6],
|
|
1229
|
-
|
|
1238
|
+
stamp,
|
|
1230
1239
|
allocateHistoryEventId(),
|
|
1231
1240
|
opts?.runId ?? null,
|
|
1232
1241
|
)
|
|
@@ -2825,6 +2834,12 @@ export function appendHistoryEvent(
|
|
|
2825
2834
|
opts?.runId ?? null,
|
|
2826
2835
|
)
|
|
2827
2836
|
recomputeThreadHeadInTxn(db, sessionId, threadId)
|
|
2837
|
+
// [T-005 OBSERVATION] `updated_at` sesi ikut maju di sini. Sebelumnya
|
|
2838
|
+
// hanya `saveSession` yang menyentuhnya, padahal turn berjalan pasca-
|
|
2839
|
+
// kompaksi menulis lewat jalur per-event ini — akibatnya `updated_at`
|
|
2840
|
+
// mandek di save terakhir (sesi 17b6a5ff: 10:45 vs jurnal 12:07) dan
|
|
2841
|
+
// setiap konsumen yang memakainya sebagai "terakhir aktif" salah.
|
|
2842
|
+
db.prepare("UPDATE sessions SET updated_at = ? WHERE id = ?").run(now, sessionId)
|
|
2828
2843
|
// P2.6: event + kursor dalam SATU txn yang sama. Jalur append per-event
|
|
2829
2844
|
// tak boleh jadi celah "event durable tapi kursor basi".
|
|
2830
2845
|
if (opts?.runId !== undefined) {
|
|
@@ -3675,7 +3690,7 @@ export function shrinkThreadHistory(
|
|
|
3675
3690
|
const oldHead = threadHeadInTxn(db, sessionId, threadId)
|
|
3676
3691
|
const stored = db
|
|
3677
3692
|
.prepare(
|
|
3678
|
-
"SELECT seq, role, content, toolCalls, toolCallId, name, reasoning, is_error, event_id, run_id, migrated, migrated_compacted, projection_note FROM messages WHERE session_id = ? AND thread_id = ? ORDER BY seq",
|
|
3693
|
+
"SELECT seq, role, content, toolCalls, toolCallId, name, reasoning, is_error, ts, event_id, run_id, migrated, migrated_compacted, projection_note FROM messages WHERE session_id = ? AND thread_id = ? ORDER BY seq",
|
|
3679
3694
|
)
|
|
3680
3695
|
.all(sessionId, threadId) as {
|
|
3681
3696
|
seq: number
|
|
@@ -3686,6 +3701,7 @@ export function shrinkThreadHistory(
|
|
|
3686
3701
|
name: string | null
|
|
3687
3702
|
reasoning: string | null
|
|
3688
3703
|
is_error: number | null
|
|
3704
|
+
ts: number | null
|
|
3689
3705
|
event_id: string | null
|
|
3690
3706
|
run_id: string | null
|
|
3691
3707
|
migrated: number
|
|
@@ -3726,7 +3742,7 @@ export function shrinkThreadHistory(
|
|
|
3726
3742
|
w[4],
|
|
3727
3743
|
w[5],
|
|
3728
3744
|
w[6],
|
|
3729
|
-
|
|
3745
|
+
got.ts,
|
|
3730
3746
|
got.event_id ?? allocateHistoryEventId(),
|
|
3731
3747
|
got.run_id,
|
|
3732
3748
|
got.migrated,
|
|
@@ -189,6 +189,13 @@ export const TOOL_CAPABILITIES: readonly ToolClassification[] = [
|
|
|
189
189
|
evidence:
|
|
190
190
|
"VERIFIED: writes history and identity. The existing sub-agent layer strips it for the same reason (src/tools/task.ts:309-321).",
|
|
191
191
|
},
|
|
192
|
+
{
|
|
193
|
+
name: "git_push",
|
|
194
|
+
capability: "PRIVILEGED",
|
|
195
|
+
autonomous: false,
|
|
196
|
+
evidence:
|
|
197
|
+
"VERIFIED: publishes local history to a remote - irreversible outside this machine and visible to others. Same class as git_commit; the sub-agent layer strips it too.",
|
|
198
|
+
},
|
|
192
199
|
|
|
193
200
|
// ── memory (session state) ──
|
|
194
201
|
{
|
|
@@ -212,7 +212,7 @@ export function analyseRelations(nodes: readonly GraphNode[]): RelationAnalysis
|
|
|
212
212
|
* what distinguishes "seen in this walk" (a cycle) from "seen in an earlier
|
|
213
213
|
* walk" (already settled).
|
|
214
214
|
*
|
|
215
|
-
* Fan-out is intentionally unbounded: `MAX_PARENT`
|
|
215
|
+
* Fan-out is intentionally unbounded: `MAX_PARENT` used to be declared in TaskStore but
|
|
216
216
|
* enforced nowhere, so the width of a containment forest is not bounded here
|
|
217
217
|
* either (design lock S5).
|
|
218
218
|
*/
|
|
@@ -91,11 +91,6 @@ export function newOwnerToken(): string {
|
|
|
91
91
|
return `own-${Date.now().toString(36)}-${counter.toString(36)}-${rand}`
|
|
92
92
|
}
|
|
93
93
|
|
|
94
|
-
/** Test-only: make token generation reproducible. */
|
|
95
|
-
export function resetOwnerTokenCounterForTests(): void {
|
|
96
|
-
counter = 0
|
|
97
|
-
}
|
|
98
|
-
|
|
99
94
|
/** The durable row. One per (session, incarnation). */
|
|
100
95
|
export interface SessionAuthority {
|
|
101
96
|
readonly sessionId: string
|
package/src/task/store.ts
CHANGED
|
@@ -88,8 +88,6 @@ function emitTaskTransition(
|
|
|
88
88
|
/** Bounds so the JSON columns cannot grow without limit. */
|
|
89
89
|
const MAX_DEPENDS_ON = 32
|
|
90
90
|
const MAX_EVIDENCE = 32
|
|
91
|
-
const MAX_ACCEPTANCE = 32
|
|
92
|
-
const MAX_PARENT = 64
|
|
93
91
|
|
|
94
92
|
/** Shape of the data, not of the table: this rises when column SEMANTICS
|
|
95
93
|
* change, not merely when a column is added. */
|
|
@@ -2923,5 +2921,3 @@ export function legacyDigest(raw: string): string {
|
|
|
2923
2921
|
const { createHash } = require("node:crypto") as typeof import("node:crypto")
|
|
2924
2922
|
return createHash("sha256").update(scrubSecrets(raw)).digest("hex").slice(0, 32)
|
|
2925
2923
|
}
|
|
2926
|
-
|
|
2927
|
-
export const __testing = { MAX_DEPENDS_ON, MAX_EVIDENCE, MAX_ACCEPTANCE, MAX_PARENT }
|
package/src/tools/ask_user.ts
CHANGED
|
@@ -11,6 +11,19 @@ import type { ApprovalEventHook, ApprovalHookEvent } from "../presentation/event
|
|
|
11
11
|
|
|
12
12
|
export type AskTextFn = (question: string, options?: string[]) => Promise<string | null>
|
|
13
13
|
|
|
14
|
+
/**
|
|
15
|
+
* Potong tanpa membelah pasangan surrogate: `slice` mentah menyisakan surrogate
|
|
16
|
+
* tinggi yatim → U+FFFD (AUD-010). Lapisan tool tak boleh impor src/ui.
|
|
17
|
+
*/
|
|
18
|
+
function sliceSafeChars(s: string, max: number): string {
|
|
19
|
+
if (s.length <= max) return s
|
|
20
|
+
let end = max
|
|
21
|
+
const code = s.charCodeAt(end - 1)
|
|
22
|
+
// Surrogate tinggi di posisi terakhir = pasangannya ikut terpotong; mundur 1.
|
|
23
|
+
if (code >= 0xd800 && code <= 0xdbff) end -= 1
|
|
24
|
+
return s.slice(0, Math.max(0, end))
|
|
25
|
+
}
|
|
26
|
+
|
|
14
27
|
let askTextFn: AskTextFn | undefined
|
|
15
28
|
|
|
16
29
|
export function setAskTextFn(fn: AskTextFn | undefined): void {
|
|
@@ -61,7 +74,7 @@ export const askUserTool: Tool = {
|
|
|
61
74
|
.slice(0, 2000)
|
|
62
75
|
if (!q) throw new Error("question empty")
|
|
63
76
|
const opts = Array.isArray(options)
|
|
64
|
-
? (options as unknown[]).map((o) => String(o)
|
|
77
|
+
? (options as unknown[]).map((o) => sliceSafeChars(String(o), 200)).slice(0, 8)
|
|
65
78
|
: undefined
|
|
66
79
|
// Tanpa view ter-inject atau di luar TTY: tolak, jangan gantung.
|
|
67
80
|
// Model harus melanjutkan dengan asumsi paling aman, bukan menunggu.
|
package/src/tools/bash.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { resolve as resolvePath } from "node:path"
|
|
|
4
4
|
import type { Tool, ToolContext } from "#minicore"
|
|
5
5
|
import { LIMITS } from "../constants.ts"
|
|
6
6
|
import { isCwdOutsideRoot, isPathOutsideRoot } from "../policy/jail.ts"
|
|
7
|
-
import { requireToolCwd } from "./context.ts"
|
|
7
|
+
import { contextUnrestricted, requireToolCwd } from "./context.ts"
|
|
8
8
|
|
|
9
9
|
// re-export untuk backward compat (helper kini terpusat di policy/scrub)
|
|
10
10
|
export { SECRET_ENV_RE, sanitizeSpawnEnv, stripSecretsEnv } from "../policy/scrub.ts"
|
|
@@ -88,6 +88,34 @@ interface BackgroundJob {
|
|
|
88
88
|
|
|
89
89
|
const jobs = new Map<string, BackgroundJob>()
|
|
90
90
|
|
|
91
|
+
/**
|
|
92
|
+
* Pendengar selesainya job background: lapisan cli memakainya untuk repaint
|
|
93
|
+
* badge footer + satu auto-resume terbatas. Tool hanya mengumumkan fakta
|
|
94
|
+
* "job X selesai dengan exit N" — tak tahu apa pun soal UI/prompt. Set agar
|
|
95
|
+
* unsubscribe idempoten dan aman saat listener menghapus dirinya saat emit.
|
|
96
|
+
*/
|
|
97
|
+
const finishListeners = new Set<(id: string, code: number | null) => void>()
|
|
98
|
+
|
|
99
|
+
/** Daftarkan pendengar selesai job. Return = fungsi unsubscribe (idempoten). */
|
|
100
|
+
export function onBackgroundJobFinished(
|
|
101
|
+
listener: (id: string, code: number | null) => void,
|
|
102
|
+
): () => void {
|
|
103
|
+
finishListeners.add(listener)
|
|
104
|
+
return () => {
|
|
105
|
+
finishListeners.delete(listener)
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function emitBackgroundJobFinished(id: string, code: number | null): void {
|
|
110
|
+
// Satu listener yang melempar tak boleh menahan listener lain ATAU
|
|
111
|
+
// menggagalkan handler `close` proses anak.
|
|
112
|
+
for (const listener of [...finishListeners]) {
|
|
113
|
+
try {
|
|
114
|
+
listener(id, code)
|
|
115
|
+
} catch {}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
91
119
|
// F-03 (P5 §C2): gerbang akses job. Hanya pemilik (sid sama, null==null untuk
|
|
92
120
|
// jalur legacy) yang boleh inspect/cancel. Kegagalan karena kepemilikan
|
|
93
121
|
// menghasilkan TIDAK ADA — pemanggil tak bisa membedakan "job milik sesi lain"
|
|
@@ -221,7 +249,12 @@ export function listBackgroundJobs(): { id: string; cmd: string; done: boolean }
|
|
|
221
249
|
return [...jobs.values()].map((j) => ({ id: j.id, cmd: j.cmd, done: j.done }))
|
|
222
250
|
}
|
|
223
251
|
|
|
224
|
-
function startBackground(
|
|
252
|
+
function startBackground(
|
|
253
|
+
cmd: string,
|
|
254
|
+
cwd: string | undefined,
|
|
255
|
+
ownerSid: string | null,
|
|
256
|
+
relaxed = false,
|
|
257
|
+
): string {
|
|
225
258
|
reapFinishedJobs()
|
|
226
259
|
const live = [...jobs.values()].filter((j) => !j.done).length
|
|
227
260
|
if (live >= LIMITS.BASH_BACKGROUND_MAX_JOBS) {
|
|
@@ -233,7 +266,7 @@ function startBackground(cmd: string, cwd: string | undefined, ownerSid: string
|
|
|
233
266
|
const proc = spawn(cmd, {
|
|
234
267
|
shell: true,
|
|
235
268
|
cwd,
|
|
236
|
-
env: sanitizeSpawnEnv(process.env),
|
|
269
|
+
env: sanitizeSpawnEnv(process.env, undefined, relaxed),
|
|
237
270
|
stdio: ["ignore", "pipe", "pipe"],
|
|
238
271
|
// detached agar shell jadi group leader → killTree bisa menutup SELURUH
|
|
239
272
|
// grup (POSIX kill(-pid)). Tanpa ini yang bisa dibunuh cuma wrapper shell
|
|
@@ -260,13 +293,23 @@ function startBackground(cmd: string, cwd: string | undefined, ownerSid: string
|
|
|
260
293
|
const piece = job.buffer.append("err", d)
|
|
261
294
|
if (piece) job.chunks.push(scrubSecrets(piece))
|
|
262
295
|
})
|
|
296
|
+
// Emit sekali per job: `error` biasanya disusul `close` (emit ganda =
|
|
297
|
+
// dua auto-resume). Guard lokal cukup — kedua handler berbagi closure.
|
|
298
|
+
let emitted = false
|
|
299
|
+
const emitOnce = (code: number | null): void => {
|
|
300
|
+
if (emitted) return
|
|
301
|
+
emitted = true
|
|
302
|
+
emitBackgroundJobFinished(id, code)
|
|
303
|
+
}
|
|
263
304
|
proc.on("error", (e) => {
|
|
264
305
|
job.chunks.push(`[error] ${e.message}`)
|
|
265
306
|
job.done = true
|
|
307
|
+
emitOnce(null)
|
|
266
308
|
})
|
|
267
309
|
proc.on("close", (code) => {
|
|
268
310
|
job.exitCode = code
|
|
269
311
|
job.done = true
|
|
312
|
+
emitOnce(code)
|
|
270
313
|
})
|
|
271
314
|
jobs.set(id, job)
|
|
272
315
|
return id
|
|
@@ -300,8 +343,9 @@ function makeBashTool(ownerSid: string | null): Tool {
|
|
|
300
343
|
},
|
|
301
344
|
async execute({ cmd, cwd, timeoutMs, background }, ctx) {
|
|
302
345
|
const sessionRoot = requireToolCwd(ctx)
|
|
346
|
+
const relaxed = contextUnrestricted(ctx)
|
|
303
347
|
const c = cwd as string | undefined
|
|
304
|
-
if (c && (isCwdOutsideRoot(c, sessionRoot) || isPathOutsideRoot(c, sessionRoot)))
|
|
348
|
+
if (!relaxed && c && (isCwdOutsideRoot(c, sessionRoot) || isPathOutsideRoot(c, sessionRoot)))
|
|
305
349
|
throw new Error(`cwd outside workspace: ${c}`)
|
|
306
350
|
const resolvedCwd = c ? resolvePath(sessionRoot, c) : undefined
|
|
307
351
|
const effectiveCwd = resolvedCwd ?? sessionRoot
|
|
@@ -313,7 +357,11 @@ function makeBashTool(ownerSid: string | null): Tool {
|
|
|
313
357
|
// symlink — tak bisa ditutup murah dari sini (shell mengikuti symlink by
|
|
314
358
|
// design; safe-open O_NOFOLLOW hanya untuk tool file). Mitigasi: --sandbox
|
|
315
359
|
// untuk isolasi penuh; lihat permission.ts jail + safe-open.ts.
|
|
316
|
-
|
|
360
|
+
// Unrestricted: default timeout jauh lebih lega; timeoutMs eksplisit
|
|
361
|
+
// tetap menang.
|
|
362
|
+
const timeout =
|
|
363
|
+
timeoutMs ??
|
|
364
|
+
(relaxed ? LIMITS.UNRESTRICTED_BASH_TIMEOUT_MS : LIMITS.BASH_DEFAULT_TIMEOUT_MS)
|
|
317
365
|
|
|
318
366
|
if (background === true) {
|
|
319
367
|
// Sandbox tidak diterapkan di jalur background: container/namespace
|
|
@@ -324,7 +372,7 @@ function makeBashTool(ownerSid: string | null): Tool {
|
|
|
324
372
|
"background:true is not supported while --sandbox is active (the process must outlive the turn)",
|
|
325
373
|
)
|
|
326
374
|
}
|
|
327
|
-
const id = startBackground(cmd as string,
|
|
375
|
+
const id = startBackground(cmd as string, effectiveCwd, ownerSid, relaxed)
|
|
328
376
|
// F-07: echo perintah di-scrub seperti output foreground — command line
|
|
329
377
|
// bisa membawa secret (`curl -H "Authorization: Bearer …"`), dan versi
|
|
330
378
|
// lama menaruhnya mentah ke konteks model.
|
|
@@ -336,7 +384,7 @@ function makeBashTool(ownerSid: string | null): Tool {
|
|
|
336
384
|
if (dockerAvailable()) {
|
|
337
385
|
const res = await runInDocker(cmd as string, effectiveCwd, {
|
|
338
386
|
timeoutMs: timeout,
|
|
339
|
-
env: sanitizeSpawnEnv(process.env) as Record<string, string>,
|
|
387
|
+
env: sanitizeSpawnEnv(process.env, undefined, relaxed) as Record<string, string>,
|
|
340
388
|
signal: ctx.signal,
|
|
341
389
|
})
|
|
342
390
|
ctx.signal.throwIfAborted()
|
|
@@ -362,12 +410,13 @@ function makeBashTool(ownerSid: string | null): Tool {
|
|
|
362
410
|
) {
|
|
363
411
|
if (osSandboxAvailable()) {
|
|
364
412
|
const res = await runInOsSandbox(cmd as string, effectiveCwd, {
|
|
413
|
+
signal: ctx.signal,
|
|
365
414
|
timeoutMs: timeout,
|
|
366
|
-
env: sanitizeSpawnEnv(process.env) as Record<string, string>,
|
|
415
|
+
env: sanitizeSpawnEnv(process.env, undefined, relaxed) as Record<string, string>,
|
|
367
416
|
})
|
|
368
417
|
const text = scrubSecrets(res.output)
|
|
369
|
-
if (res.code !== 0
|
|
370
|
-
return `exit ${res.code}\n${capMarked(text, LIMITS.BASH_OUTPUT_MAX_CHARS)}`
|
|
418
|
+
if (res.code !== 0)
|
|
419
|
+
return `exit ${res.code ?? "unknown"}\n${capMarked(text, LIMITS.BASH_OUTPUT_MAX_CHARS)}`
|
|
371
420
|
return capMarked(text, LIMITS.BASH_OUTPUT_MAX_CHARS)
|
|
372
421
|
}
|
|
373
422
|
if (sandboxStrict() || !sandboxExplicitFallbackAllowed()) {
|
|
@@ -394,8 +443,8 @@ function makeBashTool(ownerSid: string | null): Tool {
|
|
|
394
443
|
// undefined (= inherit process.cwd()). Jail/permission dievaluasi
|
|
395
444
|
// terhadap sessionRoot — eksekusi harus di direktori yang sama.
|
|
396
445
|
cwd: effectiveCwd,
|
|
397
|
-
env: sanitizeSpawnEnv(process.env),
|
|
398
|
-
|
|
446
|
+
env: sanitizeSpawnEnv(process.env, undefined, relaxed),
|
|
447
|
+
// Cancellation is owned below and settles only after process close.
|
|
399
448
|
// detached agar shell jadi group leader → killTree bisa bunuh
|
|
400
449
|
// seluruh grup (POSIX kill(-pid)). Tanpa ini cucu yatim menahan pipe.
|
|
401
450
|
detached: process.platform !== "win32",
|
|
@@ -418,6 +467,10 @@ function makeBashTool(ownerSid: string | null): Tool {
|
|
|
418
467
|
p.on("error", reject)
|
|
419
468
|
p.on("close", (code) => {
|
|
420
469
|
const text = buf.text()
|
|
470
|
+
if (ctx.signal.aborted) {
|
|
471
|
+
reject(ctx.signal.reason)
|
|
472
|
+
return
|
|
473
|
+
}
|
|
421
474
|
if (timedOut) {
|
|
422
475
|
// Prefix deterministik (parsing oleh jurnal/recovery) + instruksi
|
|
423
476
|
// eksplisit. `isError: true` dicapai dengan reject: kernel
|
|
@@ -459,13 +512,11 @@ function makeBashTool(ownerSid: string | null): Tool {
|
|
|
459
512
|
const onAbort = () => {
|
|
460
513
|
clearTimeout(t)
|
|
461
514
|
if (killTimer) clearTimeout(killTimer)
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
killTimer = setTimeout(() => {
|
|
465
|
-
killTree(p)
|
|
466
|
-
}, 1000)
|
|
515
|
+
// Kill the group before close can release executor quarantine.
|
|
516
|
+
killTree(p)
|
|
467
517
|
}
|
|
468
518
|
ctx.signal.addEventListener("abort", onAbort, { once: true })
|
|
519
|
+
if (ctx.signal.aborted) onAbort()
|
|
469
520
|
p.on("close", () => {
|
|
470
521
|
ctx.signal.removeEventListener("abort", onAbort)
|
|
471
522
|
clearTimeout(t)
|
package/src/tools/code_run.ts
CHANGED
|
@@ -70,28 +70,27 @@ export const codeRunTool: Tool = {
|
|
|
70
70
|
`code_run: MINICODE_SANDBOX=${sandbox} but no OS sandbox is available`,
|
|
71
71
|
)
|
|
72
72
|
}
|
|
73
|
-
return runInOsSandbox(inner, root, { timeoutMs })
|
|
73
|
+
return runInOsSandbox(inner, root, { timeoutMs, signal: ctx.signal })
|
|
74
74
|
}
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
const onAbort = (): Promise<never> =>
|
|
79
|
-
Promise.reject(ctx.signal.reason instanceof Error ? ctx.signal.reason : new Error("aborted"))
|
|
80
|
-
const settled: { code: number | null; output: string } = ctx.signal.aborted
|
|
81
|
-
? await onAbort()
|
|
82
|
-
: await Promise.race([
|
|
83
|
-
started,
|
|
84
|
-
new Promise<never>((_, rej) =>
|
|
85
|
-
ctx.signal.addEventListener(
|
|
86
|
-
"abort",
|
|
87
|
-
() =>
|
|
88
|
-
rej(ctx.signal.reason instanceof Error ? ctx.signal.reason : new Error("aborted")),
|
|
89
|
-
{ once: true },
|
|
90
|
-
),
|
|
91
|
-
),
|
|
92
|
-
])
|
|
75
|
+
// Both runners own cancellation and remove their abort listeners on completion.
|
|
76
|
+
const settled = await runSandboxed()
|
|
77
|
+
ctx.signal.throwIfAborted()
|
|
93
78
|
const text = capMarked(scrubSecrets(settled.output), LIMITS.BASH_OUTPUT_MAX_CHARS).trim()
|
|
94
|
-
|
|
79
|
+
// code=null dari runner berarti proses tidak pernah melaporkan exit sendiri:
|
|
80
|
+
// timeout (dan abort sudah dilempar di atas). Dulu hasil ini tampil sebagai
|
|
81
|
+
// `exit unknown` tanpa menyebut timeout sama sekali — model tak bisa tahu
|
|
82
|
+
// efeknya ambiguous. Sekarang dikembalikan dengan tag outcome yang sama
|
|
83
|
+
// bentuknya dengan jalur bash, bukan sebagai error tak terduga.
|
|
84
|
+
if (settled.code === null) {
|
|
85
|
+
return (
|
|
86
|
+
`[TOOL_OUTCOME state=UNKNOWN reason=TIMEOUT side_effect_tier=LOCAL_ENV_MUTATION ` +
|
|
87
|
+
`timeout_ms=${timeoutMs}]\n` +
|
|
88
|
+
`Sandboxed run was cut off by the ${timeoutMs} ms timeout. Its side effects are UNKNOWN ` +
|
|
89
|
+
`(the snippet may have partially run). Do NOT re-run before inspecting workspace state.\n` +
|
|
90
|
+
(text ? `--- partial output ---\n${text}` : "--- partial output ---\n(none)")
|
|
91
|
+
)
|
|
92
|
+
}
|
|
93
|
+
if (settled.code !== 0) return `exit ${settled.code}\n${text}`
|
|
95
94
|
return text
|
|
96
95
|
},
|
|
97
96
|
}
|
package/src/tools/context.ts
CHANGED
|
@@ -6,3 +6,13 @@ export function requireToolCwd(context: unknown): string {
|
|
|
6
6
|
}
|
|
7
7
|
return cwd
|
|
8
8
|
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* True hanya di mode `unrestricted`. Sumber: `ToolContext.permissionMode`,
|
|
12
|
+
* di-resolve LIVE per-turn oleh kernel — `/unrestric` saat runtime langsung
|
|
13
|
+
* tercermin tanpa patch vendor. Fail-closed: selain string "unrestricted"
|
|
14
|
+
* (termasuk undefined pada pemanggil library/test) = false.
|
|
15
|
+
*/
|
|
16
|
+
export function contextUnrestricted(context: unknown): boolean {
|
|
17
|
+
return (context as { permissionMode?: unknown } | null)?.permissionMode === "unrestricted"
|
|
18
|
+
}
|
package/src/tools/delete_file.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { stat } from "node:fs/promises"
|
|
|
2
2
|
import type { Tool } from "#minicore"
|
|
3
3
|
import { resolveSafePath } from "../lib/safe-open.ts"
|
|
4
4
|
import { trashFile } from "../lib/trash.ts"
|
|
5
|
-
import { requireToolCwd } from "./context.ts"
|
|
5
|
+
import { contextUnrestricted, requireToolCwd } from "./context.ts"
|
|
6
6
|
|
|
7
7
|
export const deleteFileTool: Tool = {
|
|
8
8
|
name: "delete_file",
|
|
@@ -20,8 +20,9 @@ export const deleteFileTool: Tool = {
|
|
|
20
20
|
ctx.signal.throwIfAborted()
|
|
21
21
|
const p = path as string
|
|
22
22
|
const root = requireToolCwd(ctx)
|
|
23
|
+
const relaxed = contextUnrestricted(ctx)
|
|
23
24
|
// Verifikasi path terpusat (logis + target nyata) — detail di safe-open.ts.
|
|
24
|
-
const { abs, real } = await resolveSafePath(p, root)
|
|
25
|
+
const { abs, real } = await resolveSafePath(p, root, relaxed)
|
|
25
26
|
const st = await stat(real).catch(() => null)
|
|
26
27
|
if (!st) throw new Error(`file not found: ${p}`)
|
|
27
28
|
if (st.isDirectory()) throw new Error(`path is directory, use bash rm -r: ${p}`)
|
package/src/tools/edit.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { LIMITS } from "../constants.ts"
|
|
|
3
3
|
import { atomicWriteText } from "../lib/atomic-write.ts"
|
|
4
4
|
import { assertSafeWriteTarget, resolveSafePath, safeReadFile } from "../lib/safe-open.ts"
|
|
5
5
|
import { appendLspDiagnostics } from "../policy/verifier.ts"
|
|
6
|
-
import { requireToolCwd } from "./context.ts"
|
|
6
|
+
import { contextUnrestricted, requireToolCwd } from "./context.ts"
|
|
7
7
|
import { applyHashline } from "./hashline.ts"
|
|
8
8
|
|
|
9
9
|
function normalizeLf(s: string): string {
|
|
@@ -147,11 +147,12 @@ export const editTool: Tool = {
|
|
|
147
147
|
ctx.signal.throwIfAborted()
|
|
148
148
|
const p = path as string
|
|
149
149
|
const root = requireToolCwd(ctx)
|
|
150
|
+
const relaxed = contextUnrestricted(ctx)
|
|
150
151
|
// Verifikasi path terpusat (logis + target nyata, induk symlink ikut
|
|
151
152
|
// ter-resolusi) — symlink internal tetap bisa diedit, targetnya yang dicek.
|
|
152
|
-
const { abs, real: realAbs } = await resolveSafePath(p, root)
|
|
153
|
+
const { abs, real: realAbs } = await resolveSafePath(p, root, relaxed)
|
|
153
154
|
// Tolak menimpa symlink final (swap antara cek dan tulis gagal tutup).
|
|
154
|
-
await assertSafeWriteTarget(abs, root)
|
|
155
|
+
await assertSafeWriteTarget(abs, root, relaxed)
|
|
155
156
|
// Cek ukuran sebelum baca penuh — hindari OOM 1GB via safeReadFile.
|
|
156
157
|
// Pakai byte length via stat pada realAbs (handle belum ada), fallback ke content length.
|
|
157
158
|
const { stat } = await import("node:fs/promises")
|
|
@@ -159,7 +160,7 @@ export const editTool: Tool = {
|
|
|
159
160
|
if (!st) throw new Error(`file not found: ${p}`)
|
|
160
161
|
if (st.size > LIMITS.READ_FILE_MAX_BYTES) throw new Error(`file too large: ${p} (${st.size})`)
|
|
161
162
|
// Baca via safeReadFile (O_NOFOLLOW) agar TOCTOU swap gagal ELOOP, bukan baca luar.
|
|
162
|
-
const content = await safeReadFile(abs, root).catch(() => {
|
|
163
|
+
const content = await safeReadFile(abs, root, relaxed).catch(() => {
|
|
163
164
|
throw new Error(`file not found: ${p}`)
|
|
164
165
|
})
|
|
165
166
|
const oldS = oldString as string
|