minicode-ai 0.14.1 → 0.14.4
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 +34 -178
- package/cli/args.ts +10 -18
- package/cli/auto-update.ts +32 -2
- package/cli/commands/acp.ts +20 -27
- package/cli/commands/daemon.ts +6 -7
- package/cli/commands/exec.ts +12 -10
- package/cli/commands.ts +6 -9
- package/cli/index.ts +40 -17
- package/cli/provider-manager.ts +1 -3
- package/cli/setup.ts +174 -145
- package/cli/tui.ts +33 -38
- package/docs/CONTROL-PLANE-MAP.md +145 -0
- package/docs/OUTPUT_EVENT_MODEL.md +1 -1
- package/docs/OUTPUT_PROTOCOL_SPEC.md +8 -2
- package/docs/OUTPUT_RENDERING_SPEC.md +35 -6
- package/docs/OUTPUT_UX_RULES.md +1 -1
- package/docs/README.md +14 -102
- package/docs/SUMMARY.md +53 -0
- package/docs/TERMINAL_CONTRACT.md +136 -77
- package/docs/UI_RENDER_PIPELINE.md +204 -0
- package/docs/agents.md +5 -5
- package/docs/architecture.md +23 -12
- package/docs/choosing-mode.md +7 -7
- package/docs/cli.md +22 -29
- package/docs/concepts.md +1 -1
- package/docs/config.md +10 -5
- package/docs/contributing.md +6 -6
- package/docs/environment.md +3 -1
- package/docs/exec.md +5 -5
- package/docs/getting-started.md +14 -12
- package/docs/glossary.md +9 -7
- package/docs/mcp-lsp.md +1 -1
- package/docs/memory-sessions.md +7 -5
- package/docs/policy-sandbox.md +23 -15
- package/docs/quickstart.md +2 -2
- package/docs/repl.md +4 -3
- package/docs/security-model.md +16 -17
- package/docs/security.md +15 -30
- package/docs/skills.md +1 -1
- package/docs/tools.md +6 -6
- package/docs/verify-benchmark.md +16 -0
- package/package.json +5 -5
- package/scripts/vendor-overlays/minicode-context.patch +109 -0
- package/src/app/mentions.ts +4 -3
- package/src/app/provider-layer.ts +13 -1
- package/src/app/session.ts +229 -22
- package/src/app/tool-layer.ts +6 -0
- package/src/config.ts +30 -3
- package/src/constants.ts +19 -0
- package/src/daemon/control.ts +1 -1
- 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/server.ts +2 -3
- package/src/mcp/transport.ts +96 -42
- package/src/memory/files.ts +15 -4
- package/src/memory/vector.ts +5 -1
- package/src/policy/compaction.ts +272 -16
- package/src/policy/context-window.ts +73 -0
- package/src/policy/context.ts +76 -16
- package/src/policy/ratelimit.ts +47 -18
- package/src/policy/tool-contract.ts +4 -10
- package/src/policy/update-check.ts +83 -6
- package/src/policy/usage.ts +31 -14
- package/src/policy/work-mode.ts +1 -1
- 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 +158 -16
- package/src/providers/provision.ts +12 -3
- package/src/providers/responses.ts +61 -23
- package/src/providers/router.ts +56 -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/context-projection.ts +14 -0
- package/src/session/context-selector.ts +58 -20
- package/src/session/persistence.ts +6 -3
- package/src/session/verification.ts +55 -16
- package/src/skills/loader.ts +16 -3
- package/src/task/model.ts +21 -70
- 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 +9 -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 +131 -66
- package/src/ui/i18n/en.ts +3 -11
- package/src/ui/i18n/id.ts +3 -11
- package/src/ui/input/input.ts +2 -3
- package/src/ui/input/prompt-engine.ts +2 -5
- package/src/ui/render/width.ts +107 -79
- package/src/ui/runtime/screen.ts +49 -37
- package/src/ui/screens/model-manager.ts +3 -10
- package/src/ui/screens/picker.ts +23 -40
- package/src/ui/screens/provider-manager.ts +12 -33
- package/src/ui/screens/wizard.ts +0 -1
- package/src/ui/tui/app.ts +265 -211
- package/src/ui/tui/transcript.ts +87 -8
- package/vendor/minicore/VENDOR.md +9 -5
- package/vendor/minicore/src/core/loop.ts +47 -12
- package/vendor/minicore/src/core/provider.ts +4 -0
- package/vendor/minicore/src/core/session.ts +14 -1
- package/CHANGELOG.md +0 -1185
- package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +0 -489
- package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +0 -391
- package/docs/PLAN_UIUX_V6.md +0 -209
- package/docs/changelog.md +0 -3
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { Buffer } from "node:buffer"
|
|
2
|
+
import { abortError, ProviderError } from "#minicore/core/errors.ts"
|
|
3
|
+
import { LIMITS } from "../constants.ts"
|
|
4
|
+
|
|
5
|
+
export interface SseBounds {
|
|
6
|
+
maxFrameBytes?: number
|
|
7
|
+
maxTotalBytes?: number
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface ToolArgumentBounds {
|
|
11
|
+
maxArgumentBytes?: number
|
|
12
|
+
maxPendingBytes?: number
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Baca stream per chunk dengan batas byte sebelum parser SSE membangun buffer baris. */
|
|
16
|
+
export function boundedSseBody(
|
|
17
|
+
body: ReadableStream<Uint8Array>,
|
|
18
|
+
signal: AbortSignal,
|
|
19
|
+
provider: string,
|
|
20
|
+
bounds: SseBounds = {},
|
|
21
|
+
): ReadableStream<Uint8Array> {
|
|
22
|
+
const maxFrameBytes = bounds.maxFrameBytes ?? LIMITS.PROVIDER_SSE_FRAME_MAX_BYTES
|
|
23
|
+
const maxTotalBytes = bounds.maxTotalBytes ?? LIMITS.PROVIDER_SSE_TOTAL_MAX_BYTES
|
|
24
|
+
if (signal.aborted) throw abortError(signal)
|
|
25
|
+
const reader = body.getReader()
|
|
26
|
+
let streamBytes = 0
|
|
27
|
+
let lineBytes = 0
|
|
28
|
+
let frameBytes = 0
|
|
29
|
+
let reachedEof = false
|
|
30
|
+
let released = false
|
|
31
|
+
const release = () => {
|
|
32
|
+
if (released) return
|
|
33
|
+
released = true
|
|
34
|
+
signal.removeEventListener("abort", onAbort)
|
|
35
|
+
reader.releaseLock()
|
|
36
|
+
}
|
|
37
|
+
const onAbort = () => {
|
|
38
|
+
void reader.cancel(signal.reason).catch(() => {})
|
|
39
|
+
}
|
|
40
|
+
signal.addEventListener("abort", onAbort, { once: true })
|
|
41
|
+
const cancelSource = async (reason?: unknown) => {
|
|
42
|
+
if (!reachedEof) await reader.cancel(reason).catch(() => {})
|
|
43
|
+
release()
|
|
44
|
+
}
|
|
45
|
+
return new ReadableStream<Uint8Array>({
|
|
46
|
+
async pull(controller) {
|
|
47
|
+
try {
|
|
48
|
+
if (signal.aborted) throw abortError(signal)
|
|
49
|
+
const { done, value } = await reader.read()
|
|
50
|
+
if (signal.aborted) throw abortError(signal)
|
|
51
|
+
if (done) {
|
|
52
|
+
reachedEof = true
|
|
53
|
+
if (lineBytes !== 0 || frameBytes !== 0) {
|
|
54
|
+
throw new ProviderError(
|
|
55
|
+
"invalid_request",
|
|
56
|
+
`${provider} returned an incomplete SSE frame`,
|
|
57
|
+
)
|
|
58
|
+
}
|
|
59
|
+
controller.close()
|
|
60
|
+
release()
|
|
61
|
+
return
|
|
62
|
+
}
|
|
63
|
+
streamBytes += value.byteLength
|
|
64
|
+
if (streamBytes > maxTotalBytes) {
|
|
65
|
+
throw new ProviderError(
|
|
66
|
+
"invalid_request",
|
|
67
|
+
`${provider} SSE stream exceeds ${maxTotalBytes} bytes`,
|
|
68
|
+
)
|
|
69
|
+
}
|
|
70
|
+
for (const byte of value) {
|
|
71
|
+
if (byte === 0x0a) {
|
|
72
|
+
frameBytes++
|
|
73
|
+
if (frameBytes > maxFrameBytes) {
|
|
74
|
+
throw new ProviderError(
|
|
75
|
+
"invalid_request",
|
|
76
|
+
`${provider} SSE frame exceeds ${maxFrameBytes} bytes`,
|
|
77
|
+
)
|
|
78
|
+
}
|
|
79
|
+
if (lineBytes === 0) frameBytes = 0
|
|
80
|
+
lineBytes = 0
|
|
81
|
+
} else {
|
|
82
|
+
lineBytes++
|
|
83
|
+
frameBytes++
|
|
84
|
+
if (lineBytes > maxFrameBytes || frameBytes > maxFrameBytes) {
|
|
85
|
+
throw new ProviderError(
|
|
86
|
+
"invalid_request",
|
|
87
|
+
`${provider} SSE frame exceeds ${maxFrameBytes} bytes`,
|
|
88
|
+
)
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
controller.enqueue(value)
|
|
93
|
+
} catch (error) {
|
|
94
|
+
await cancelSource(error)
|
|
95
|
+
controller.error(error)
|
|
96
|
+
}
|
|
97
|
+
},
|
|
98
|
+
cancel: cancelSource,
|
|
99
|
+
})
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Body error dibaca secukupnya untuk kategori/pesan, lalu sisa stream dibuang. */
|
|
103
|
+
export async function readProviderErrorBody(response: Response): Promise<string> {
|
|
104
|
+
if (!response.body) return ""
|
|
105
|
+
const reader = response.body.getReader()
|
|
106
|
+
const chunks: Uint8Array[] = []
|
|
107
|
+
let size = 0
|
|
108
|
+
let reachedEof = false
|
|
109
|
+
try {
|
|
110
|
+
while (size < LIMITS.PROVIDER_ERROR_BODY_MAX_BYTES) {
|
|
111
|
+
const { done, value } = await reader.read()
|
|
112
|
+
if (done) {
|
|
113
|
+
reachedEof = true
|
|
114
|
+
break
|
|
115
|
+
}
|
|
116
|
+
const remaining = LIMITS.PROVIDER_ERROR_BODY_MAX_BYTES - size
|
|
117
|
+
const part = value.byteLength > remaining ? value.subarray(0, remaining) : value
|
|
118
|
+
chunks.push(part)
|
|
119
|
+
size += part.byteLength
|
|
120
|
+
if (part.byteLength < value.byteLength) break
|
|
121
|
+
}
|
|
122
|
+
return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))).toString("utf8")
|
|
123
|
+
} finally {
|
|
124
|
+
if (!reachedEof) await reader.cancel().catch(() => {})
|
|
125
|
+
reader.releaseLock()
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function appendToolArgument(
|
|
130
|
+
current: string,
|
|
131
|
+
currentBytes: number,
|
|
132
|
+
delta: string,
|
|
133
|
+
pendingBytes: number,
|
|
134
|
+
provider: string,
|
|
135
|
+
bounds: ToolArgumentBounds = {},
|
|
136
|
+
): { value: string; bytes: number; pendingBytes: number } {
|
|
137
|
+
const deltaBytes = Buffer.byteLength(delta, "utf8")
|
|
138
|
+
const bytes = currentBytes + deltaBytes
|
|
139
|
+
const nextPendingBytes = pendingBytes + deltaBytes
|
|
140
|
+
const maxArgumentBytes = bounds.maxArgumentBytes ?? LIMITS.PROVIDER_TOOL_ARGS_MAX_BYTES
|
|
141
|
+
const maxPendingBytes = bounds.maxPendingBytes ?? LIMITS.PROVIDER_TOOL_ARGS_PENDING_MAX_BYTES
|
|
142
|
+
if (bytes > maxArgumentBytes) {
|
|
143
|
+
throw new ProviderError(
|
|
144
|
+
"invalid_request",
|
|
145
|
+
`${provider} tool arguments exceed ${maxArgumentBytes} bytes`,
|
|
146
|
+
)
|
|
147
|
+
}
|
|
148
|
+
if (nextPendingBytes > maxPendingBytes) {
|
|
149
|
+
throw new ProviderError(
|
|
150
|
+
"invalid_request",
|
|
151
|
+
`${provider} pending tool arguments exceed ${maxPendingBytes} bytes`,
|
|
152
|
+
)
|
|
153
|
+
}
|
|
154
|
+
return { value: current + delta, bytes, pendingBytes: nextPendingBytes }
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function parseProviderToolArguments(raw: string, provider: string): unknown {
|
|
158
|
+
if (Buffer.byteLength(raw, "utf8") > LIMITS.PROVIDER_TOOL_ARGS_MAX_BYTES) {
|
|
159
|
+
throw new ProviderError(
|
|
160
|
+
"invalid_request",
|
|
161
|
+
`${provider} tool arguments exceed ${LIMITS.PROVIDER_TOOL_ARGS_MAX_BYTES} bytes`,
|
|
162
|
+
)
|
|
163
|
+
}
|
|
164
|
+
if (!raw) return {}
|
|
165
|
+
try {
|
|
166
|
+
return JSON.parse(raw)
|
|
167
|
+
} catch {
|
|
168
|
+
throw new ProviderError("invalid_request", `${provider} returned malformed tool arguments`)
|
|
169
|
+
}
|
|
170
|
+
}
|
package/src/repo/repomap.ts
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import { execFile } from "node:child_process"
|
|
2
2
|
import { createHash } from "node:crypto"
|
|
3
|
-
import { mkdirSync, readFileSync,
|
|
4
|
-
import { readdir
|
|
3
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs"
|
|
4
|
+
import { readdir } from "node:fs/promises"
|
|
5
5
|
import { join, relative, resolve } from "node:path"
|
|
6
6
|
import { fileURLToPath } from "node:url"
|
|
7
7
|
import { promisify } from "node:util"
|
|
8
8
|
import { LIMITS, LSP_SYMBOL_KINDS } from "../constants.ts"
|
|
9
9
|
import { homeDir } from "../lib/db-path.ts"
|
|
10
10
|
import { GIT_SAFE_BASE } from "../lib/git-hardening.ts"
|
|
11
|
+
import { safeReadFileCapped } from "../lib/safe-open.ts"
|
|
11
12
|
import { resolveTrustedExecutable } from "../lib/trusted-exec.ts"
|
|
12
13
|
import { isRealPathOutsideRoot } from "../policy/jail.ts"
|
|
13
14
|
|
|
@@ -233,10 +234,8 @@ async function readSourceContents(
|
|
|
233
234
|
for (const f of files) {
|
|
234
235
|
try {
|
|
235
236
|
const abs = resolve(cwd, f)
|
|
236
|
-
const
|
|
237
|
-
if (!
|
|
238
|
-
const content = await readFile(abs, "utf8")
|
|
239
|
-
out.push({ path: f, content })
|
|
237
|
+
const loaded = await safeReadFileCapped(abs, cwd, MAX_FILE_BYTES)
|
|
238
|
+
if (!loaded.truncated) out.push({ path: f, content: loaded.text })
|
|
240
239
|
} catch {}
|
|
241
240
|
}
|
|
242
241
|
return out
|
|
@@ -358,15 +357,15 @@ export async function buildRepoMap(
|
|
|
358
357
|
// disajikan tanpa baca ulang. Dengan sig isi, cache palsu hanya cocok bila
|
|
359
358
|
// isinya benar-benar sama — dan bila sama, petanya pun benar. Cache lama
|
|
360
359
|
// (format mtime) otomatis miss → dibangun ulang sekali, tanpa migrasi.
|
|
361
|
-
function signature(files: string[], cwd: string): string {
|
|
360
|
+
async function signature(files: string[], cwd: string): Promise<string> {
|
|
362
361
|
const h = createHash("sha256")
|
|
363
362
|
for (const f of files.slice(0, 80)) {
|
|
364
363
|
try {
|
|
365
364
|
const abs = resolve(cwd, f)
|
|
366
|
-
const
|
|
367
|
-
if (
|
|
365
|
+
const loaded = await safeReadFileCapped(abs, cwd, MAX_FILE_BYTES)
|
|
366
|
+
if (loaded.truncated) continue
|
|
368
367
|
h.update(f)
|
|
369
|
-
h.update(
|
|
368
|
+
h.update(loaded.text)
|
|
370
369
|
} catch {}
|
|
371
370
|
}
|
|
372
371
|
return `v2:${h.digest("hex")}`
|
|
@@ -412,7 +411,7 @@ export async function loadRepoMap(cwd: string = process.cwd()): Promise<string>
|
|
|
412
411
|
const forceRegex = process.env.MINICODE_REPOMAP === "regex"
|
|
413
412
|
const files = await listSourceFiles(cwd, MAX_FILES)
|
|
414
413
|
if (files.length === 0) return ""
|
|
415
|
-
const sig = signature(files, cwd)
|
|
414
|
+
const sig = await signature(files, cwd)
|
|
416
415
|
const cp = cachePath(cwd)
|
|
417
416
|
// Cache hit → langsung pakai (tanpa LSP, cepat)
|
|
418
417
|
try {
|
|
@@ -16,10 +16,9 @@
|
|
|
16
16
|
// - Backend tak membuat executionId (M1); handle `be_*` = namespace backend
|
|
17
17
|
// sendiri, opaque, non-user-controlled, bukan lifecycle authority.
|
|
18
18
|
// - Opaque handle: caller tak pernah memegang raw ChildProcess.
|
|
19
|
-
// - Sandbox shims membungkus runner existing run-to-completion
|
|
20
|
-
//
|
|
21
|
-
//
|
|
22
|
-
// timeout runner). Jangan klaim D untuk container.
|
|
19
|
+
// - Sandbox shims membungkus runner existing run-to-completion. Docker runner
|
|
20
|
+
// meminta daemon menghapus container saat timeout; cancel dari backend tetap
|
|
21
|
+
// belum mengirim signal fisik ke runner. Jangan klaim D untuk container.
|
|
23
22
|
// - MCP/LSP/background-jobs TIDAK dibungkus di sini (lifecycle berbeda:
|
|
24
23
|
// closeAll/closeAllLsp tetap pemilik; background = tool scope, detached = M7).
|
|
25
24
|
// - Security parity: spawn SELALU via sanitizeSpawnEnv + resolveTrustedExecutable
|
|
@@ -72,7 +71,7 @@ export interface BackendCapability {
|
|
|
72
71
|
* - host: killTree grup/taskkill ADA (bash.ts:96-124); tanpa flag CPU/mem/pids;
|
|
73
72
|
* network hanya guard; FS hanya jail pre-check (TOCTOU terdokumentasi).
|
|
74
73
|
* - docker: invocation --cpus/--memory/--pids-limit/--network/--read-only ADA
|
|
75
|
-
* (docker.ts:58-87);
|
|
74
|
+
* (docker.ts:58-87); timeout meminta daemon menjalankan `docker rm --force`.
|
|
76
75
|
* - bwrap: --unshare-net/--die-with-parent/--cap-drop/bind ADA, tanpa limit
|
|
77
76
|
* CPU/mem/pids (os.ts:104-135). seatbelt: deny default + deny network* ADA,
|
|
78
77
|
* policy = restriksi BUKAN kill guarantee (os.ts:91-98).
|
|
@@ -109,10 +108,10 @@ export const BACKEND_CAPABILITIES: Record<BackendKind, BackendCapability> = {
|
|
|
109
108
|
network: "SUPPORTED",
|
|
110
109
|
fs: "SUPPORTED",
|
|
111
110
|
notes: [
|
|
112
|
-
"A: timeout wrapper
|
|
111
|
+
"A: timeout wrapper meminta daemon remove lalu menunggu close Docker CLI (docker.ts).",
|
|
113
112
|
"B: DELEGATED_TO_RUNTIME — logical stop diputuskan runtime.",
|
|
114
|
-
"C: BEST_EFFORT —
|
|
115
|
-
"D: BEST_EFFORT —
|
|
113
|
+
"C: BEST_EFFORT — timeout meminta docker rm --force; kegagalan daemon dilaporkan.",
|
|
114
|
+
"D: BEST_EFFORT — permintaan remove bukan bukti fisik mandiri; jangan klaim D container.",
|
|
116
115
|
"CPU/mem/PID/net/FS: --cpus/--memory/--pids-limit 32/--network none/--read-only+cap-drop+user (docker.ts:58-87).",
|
|
117
116
|
],
|
|
118
117
|
},
|
package/src/sandbox/docker.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { spawn, spawnSync } from "node:child_process"
|
|
2
|
+
import { randomUUID } from "node:crypto"
|
|
2
3
|
import { resolve } from "node:path"
|
|
3
4
|
import { LIMITS } from "../constants.ts"
|
|
4
5
|
import { resolveTrustedExecutable } from "../lib/trusted-exec.ts"
|
|
@@ -44,6 +45,45 @@ export interface DockerRunOptions {
|
|
|
44
45
|
cpus?: number
|
|
45
46
|
env?: Record<string, string>
|
|
46
47
|
timeoutMs?: number
|
|
48
|
+
signal?: AbortSignal
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
let dockerSpawnForTest: typeof spawn | null = null
|
|
52
|
+
|
|
53
|
+
/** Seam untuk mensimulasikan lifecycle Docker tanpa daemon dalam tes. */
|
|
54
|
+
export function setDockerSpawnForTest(spawner: typeof spawn | null): void {
|
|
55
|
+
dockerSpawnForTest = spawner
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function dockerExecutable(): string {
|
|
59
|
+
return dockerSpawnForTest ? "docker" : resolveTrustedExecutable("docker")
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function spawnDocker(args: string[], env: NodeJS.ProcessEnv) {
|
|
63
|
+
return (dockerSpawnForTest ?? spawn)(dockerExecutable(), args, {
|
|
64
|
+
stdio: "ignore",
|
|
65
|
+
env,
|
|
66
|
+
})
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Minta daemon menghapus container; timeout membuat kegagalan cleanup eksplisit. */
|
|
70
|
+
function removeContainer(name: string, env: NodeJS.ProcessEnv): Promise<boolean> {
|
|
71
|
+
return new Promise((resolveResult) => {
|
|
72
|
+
let done = false
|
|
73
|
+
const p = spawnDocker(["rm", "--force", name], env)
|
|
74
|
+
const finish = (removed: boolean) => {
|
|
75
|
+
if (done) return
|
|
76
|
+
done = true
|
|
77
|
+
clearTimeout(timer)
|
|
78
|
+
resolveResult(removed)
|
|
79
|
+
}
|
|
80
|
+
const timer = setTimeout(() => {
|
|
81
|
+
p.kill("SIGKILL")
|
|
82
|
+
finish(false)
|
|
83
|
+
}, LIMITS.DOCKER_CLEANUP_TIMEOUT_MS)
|
|
84
|
+
p.on("error", () => finish(false))
|
|
85
|
+
p.on("close", (code) => finish(code === 0))
|
|
86
|
+
})
|
|
47
87
|
}
|
|
48
88
|
|
|
49
89
|
// Run command di dalam container ephemeral, terisolasi (--network none,
|
|
@@ -53,11 +93,17 @@ export function runInDocker(
|
|
|
53
93
|
cwd: string,
|
|
54
94
|
opts: DockerRunOptions = {},
|
|
55
95
|
): Promise<{ code: number | null; output: string }> {
|
|
96
|
+
if (opts.signal?.aborted) {
|
|
97
|
+
return Promise.resolve({ code: null, output: "[docker] aborted before container start" })
|
|
98
|
+
}
|
|
56
99
|
const image = opts.image ?? process.env.MINICODE_SANDBOX_IMAGE ?? "node:22-alpine"
|
|
57
100
|
const mount = workspaceMount(cwd)
|
|
101
|
+
const containerName = `minicode-${randomUUID()}`
|
|
58
102
|
const args = [
|
|
59
103
|
"run",
|
|
60
104
|
"--rm",
|
|
105
|
+
"--name",
|
|
106
|
+
containerName,
|
|
61
107
|
"-i",
|
|
62
108
|
"--read-only",
|
|
63
109
|
"--cap-drop",
|
|
@@ -89,9 +135,10 @@ export function runInDocker(
|
|
|
89
135
|
return new Promise((resolveResult) => {
|
|
90
136
|
// env selalu disanitasi dari hasil merge final — secret (API_KEY/TOKEN/...)
|
|
91
137
|
// tidak pernah diwarisi container walau caller lupa strip.
|
|
92
|
-
const
|
|
138
|
+
const env = sanitizeSpawnEnv(process.env, opts.env)
|
|
139
|
+
const p = (dockerSpawnForTest ?? spawn)(dockerExecutable(), args, {
|
|
93
140
|
stdio: ["ignore", "pipe", "pipe"],
|
|
94
|
-
env
|
|
141
|
+
env,
|
|
95
142
|
})
|
|
96
143
|
// Cap buffer saat streaming — output container raksasa tidak menumpuk di RAM.
|
|
97
144
|
const OUT_CAP = LIMITS.DOCKER_OUTPUT_MAX_CHARS
|
|
@@ -113,17 +160,74 @@ export function runInDocker(
|
|
|
113
160
|
}
|
|
114
161
|
p.stdout.on("data", (d) => appendCapped("out", d))
|
|
115
162
|
p.stderr.on("data", (d) => appendCapped("err", d))
|
|
116
|
-
const timeout =
|
|
117
|
-
|
|
118
|
-
|
|
163
|
+
const timeout =
|
|
164
|
+
typeof opts.timeoutMs === "number" && Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0
|
|
165
|
+
? opts.timeoutMs
|
|
166
|
+
: LIMITS.DOCKER_TIMEOUT_MS
|
|
167
|
+
let settled = false
|
|
168
|
+
let closed = false
|
|
169
|
+
let stopReason: "timeout" | "abort" | undefined
|
|
170
|
+
let stopPromise: Promise<boolean> | undefined
|
|
171
|
+
let t: ReturnType<typeof setTimeout>
|
|
172
|
+
const signal = opts.signal
|
|
173
|
+
const finalize = (code: number | null, suffix = "") => {
|
|
174
|
+
if (settled) return
|
|
175
|
+
settled = true
|
|
119
176
|
clearTimeout(t)
|
|
120
|
-
|
|
177
|
+
signal?.removeEventListener("abort", onAbort)
|
|
178
|
+
const marker = truncated ? "\n… [output truncated]" : ""
|
|
179
|
+
const output = (out + (err ? `\n[stderr]\n${err}` : "")).trim() + marker + suffix
|
|
180
|
+
resolveResult({ code, output })
|
|
181
|
+
}
|
|
182
|
+
const requestStop = (reason: "timeout" | "abort") => {
|
|
183
|
+
if (stopReason || settled) return
|
|
184
|
+
stopReason = reason
|
|
185
|
+
clearTimeout(t)
|
|
186
|
+
stopPromise = removeContainer(containerName, env).catch(() => false)
|
|
187
|
+
void stopPromise.then((removed) => {
|
|
188
|
+
if (!closed) p.kill("SIGKILL")
|
|
189
|
+
if (closed) {
|
|
190
|
+
const detail = removed
|
|
191
|
+
? "daemon container removal confirmed"
|
|
192
|
+
: "daemon cleanup unconfirmed"
|
|
193
|
+
const reasonText = reason === "timeout" ? `timed out after ${timeout}ms` : "aborted"
|
|
194
|
+
finalize(null, `\n[docker] ${reasonText}; ${detail}`)
|
|
195
|
+
}
|
|
196
|
+
})
|
|
197
|
+
}
|
|
198
|
+
const onAbort = () => requestStop("abort")
|
|
199
|
+
t = setTimeout(() => requestStop("timeout"), timeout)
|
|
200
|
+
if (signal) {
|
|
201
|
+
signal.addEventListener("abort", onAbort, { once: true })
|
|
202
|
+
if (signal.aborted) requestStop("abort")
|
|
203
|
+
}
|
|
204
|
+
p.on("error", (e) => {
|
|
205
|
+
closed = true
|
|
206
|
+
if (stopReason) {
|
|
207
|
+
void (stopPromise ?? Promise.resolve(false)).then((removed) => {
|
|
208
|
+
const detail = removed
|
|
209
|
+
? "daemon container removal confirmed"
|
|
210
|
+
: "daemon cleanup unconfirmed"
|
|
211
|
+
finalize(null, `\n[docker] ${stopReason}; ${detail}`)
|
|
212
|
+
})
|
|
213
|
+
} else {
|
|
214
|
+
finalize(null, `[docker] ${e.message}`)
|
|
215
|
+
}
|
|
121
216
|
})
|
|
122
217
|
p.on("close", (code) => {
|
|
218
|
+
closed = true
|
|
123
219
|
clearTimeout(t)
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
220
|
+
if (stopReason) {
|
|
221
|
+
void (stopPromise ?? Promise.resolve(false)).then((removed) => {
|
|
222
|
+
const detail = removed
|
|
223
|
+
? "daemon container removal confirmed"
|
|
224
|
+
: "daemon cleanup unconfirmed"
|
|
225
|
+
const reasonText = stopReason === "timeout" ? `timed out after ${timeout}ms` : "aborted"
|
|
226
|
+
finalize(null, `\n[docker] ${reasonText}; ${detail}`)
|
|
227
|
+
})
|
|
228
|
+
} else {
|
|
229
|
+
finalize(code)
|
|
230
|
+
}
|
|
127
231
|
})
|
|
128
232
|
})
|
|
129
233
|
}
|
|
@@ -8,7 +8,7 @@ import { GIT_SAFE_BASE } from "../lib/git-hardening.ts"
|
|
|
8
8
|
import { sanitizeSessionPart } from "../lib/session-id.ts"
|
|
9
9
|
import { isPathOutsideRoot } from "../policy/jail.ts"
|
|
10
10
|
import { appendUndoMarker, loadJournal } from "./journal.ts"
|
|
11
|
-
import { diffTrees, ephemeralTree, restoreTree, snapshotTree } from "./shadow-git.ts"
|
|
11
|
+
import { diffTrees, ephemeralTree, isGitRepo, restoreTree, snapshotTree } from "./shadow-git.ts"
|
|
12
12
|
|
|
13
13
|
/** Alias back-compat: satu-satunya sanitizer kini di lib/session-id.ts (F-17). */
|
|
14
14
|
export function sanitizeSessionId(id: string): string {
|
|
@@ -335,9 +335,16 @@ export async function snapshotWorkspace(
|
|
|
335
335
|
export async function beginTurnSnapshot(
|
|
336
336
|
sessionId: string,
|
|
337
337
|
cwd: string = process.cwd(),
|
|
338
|
-
): Promise<
|
|
338
|
+
): Promise<
|
|
339
|
+
| { mode: "git"; tree: string }
|
|
340
|
+
| { mode: "files"; snapshots: FileSnapshot[] }
|
|
341
|
+
| { mode: "unavailable"; reason: "git-snapshot-failed" }
|
|
342
|
+
> {
|
|
339
343
|
const shadow = await snapshotTree(cwd, sessionId, "pre")
|
|
340
344
|
if (shadow) return { mode: "git", tree: shadow.tree }
|
|
345
|
+
// Fallback file snapshot dibatasi 200 path. Memakainya saat repo Git gagal
|
|
346
|
+
// membuat snapshot dapat memberi kesan rollback lengkap padahal parsial.
|
|
347
|
+
if (await isGitRepo(cwd)) return { mode: "unavailable", reason: "git-snapshot-failed" }
|
|
341
348
|
return { mode: "files", snapshots: await snapshotWorkspace(cwd, LIMITS.WORKSPACE_SNAPSHOT_LIMIT) }
|
|
342
349
|
}
|
|
343
350
|
|
|
@@ -29,6 +29,7 @@
|
|
|
29
29
|
|
|
30
30
|
import { ContextStore, mechanicalCompaction } from "#minicore"
|
|
31
31
|
import type { Message } from "#minicore/core/types.ts"
|
|
32
|
+
import { LIMITS } from "../constants.ts"
|
|
32
33
|
import { renderFullHistoryFold } from "./full-history-fold.ts"
|
|
33
34
|
import {
|
|
34
35
|
buildProjection,
|
|
@@ -100,6 +101,18 @@ export function deriveSummaryFromCanonical(
|
|
|
100
101
|
return { summaryText, baseSeq }
|
|
101
102
|
}
|
|
102
103
|
|
|
104
|
+
function boundProjectionSummary(text: string): string {
|
|
105
|
+
const cap = LIMITS.COMPACTION_SUMMARY_MAX_CHARS
|
|
106
|
+
if (text.length <= cap) return text
|
|
107
|
+
const marker = "\n[projection summary truncated; older details may be missing]"
|
|
108
|
+
let head = text.slice(0, Math.max(0, cap - marker.length))
|
|
109
|
+
if (head.length > 0) {
|
|
110
|
+
const code = head.charCodeAt(head.length - 1)
|
|
111
|
+
if (code >= 0xd800 && code <= 0xdbff) head = head.slice(0, -1)
|
|
112
|
+
}
|
|
113
|
+
return `${head}${marker}`
|
|
114
|
+
}
|
|
115
|
+
|
|
103
116
|
/**
|
|
104
117
|
* Bungkus P3.7 `renderFullHistoryFold` untuk seam produsen: ubah baris thread
|
|
105
118
|
* menjadi input renderer, dan ubah `FoldError` (cakupan tak-terbukti) menjadi
|
|
@@ -182,6 +195,7 @@ export function produceSummaryProjection(
|
|
|
182
195
|
if (baseSeq === undefined || baseSeq <= 0) {
|
|
183
196
|
return { produced: false, detail: "no explicit/derivable baseSeq — refusing empty projection" }
|
|
184
197
|
}
|
|
198
|
+
summaryText = boundProjectionSummary(summaryText)
|
|
185
199
|
// Tulis lewat primitif P2.7 (epoch-fenced, satu txn, delete+insert, sumber
|
|
186
200
|
// kanonik UTUH). Satu-satunya efek tulis produsen = history_projections.
|
|
187
201
|
const row = buildProjection(sessionId, threadId, summaryText, cwd, {
|
|
@@ -315,7 +315,7 @@ function selectionFreshness(
|
|
|
315
315
|
*
|
|
316
316
|
* Urutan strategi (audit §7):
|
|
317
317
|
* 1. summary-plus-tail — ringkasan durable [0,B) + ekor [B, head] (bila aman)
|
|
318
|
-
* 2. fallback-unknown —
|
|
318
|
+
* 2. fallback-unknown — histori kanonik berlabel jujur bila muat
|
|
319
319
|
* 3. full-history — histori kanonik penuh bila muat budget
|
|
320
320
|
* 4. budget-tail — ekor kanonik terbaru yang muat budget
|
|
321
321
|
*/
|
|
@@ -359,36 +359,75 @@ export function selectContext(input: SelectContextInput): ContextSelection {
|
|
|
359
359
|
const summaryText = input.projection.summaryText
|
|
360
360
|
if (b > 0 && typeof summaryText === "string" && summaryText.length > 0) {
|
|
361
361
|
const { frontier, messages: tail } = coverageOf(input, rows, b)
|
|
362
|
-
const
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
362
|
+
const makeProjectionSelection = (text: string, truncated: boolean): ContextSelection => {
|
|
363
|
+
const synthetic = syntheticSummaryMessage(text, b)
|
|
364
|
+
const msgs: Message[] = [synthetic, ...tail]
|
|
365
|
+
const artifact: ContextOnlyArtifact = { role: "user", content: synthetic.content as string }
|
|
366
|
+
return Object.freeze({
|
|
367
|
+
sessionId: input.sessionId,
|
|
368
|
+
threadId: input.threadId,
|
|
369
|
+
frontier,
|
|
370
|
+
messages: msgs,
|
|
371
|
+
source: "projection" as ContextSource,
|
|
372
|
+
coveredSeq: b,
|
|
373
|
+
selectionBasis: "summary-plus-tail" as SelectionBasis,
|
|
374
|
+
freshness: selectionFreshness(frontier, input.canonicalFrontier),
|
|
375
|
+
budget: report(msgs),
|
|
376
|
+
detail: truncated
|
|
377
|
+
? `durable summary covers [0,${b}) + canonical tail [${b},${headSeq}]; summary tail truncated to fit budget`
|
|
378
|
+
: `durable summary covers [0,${b}) + canonical tail [${b},${headSeq}]`,
|
|
379
|
+
contextOnly: artifact,
|
|
380
|
+
})
|
|
381
|
+
}
|
|
382
|
+
const complete = makeProjectionSelection(summaryText, false)
|
|
383
|
+
if (complete.budget.fits) return complete
|
|
384
|
+
|
|
385
|
+
// Projection texts can grow independently of the model window. Keep the
|
|
386
|
+
// most recent portion of the old summary and preserve the canonical tail
|
|
387
|
+
// only when the resulting pair fits; otherwise continue to budget-tail.
|
|
388
|
+
const marker = "[older projection prefix omitted for context budget]\n"
|
|
389
|
+
const tailTokens = sumTokens(tail, est)
|
|
390
|
+
if (tailTokens < limit) {
|
|
391
|
+
let low = 0
|
|
392
|
+
let high = summaryText.length
|
|
393
|
+
let best: ContextSelection | undefined
|
|
394
|
+
while (low <= high) {
|
|
395
|
+
const keep = Math.floor((low + high) / 2)
|
|
396
|
+
let suffix = summaryText.slice(summaryText.length - keep)
|
|
397
|
+
if (suffix.length > 0) {
|
|
398
|
+
const code = suffix.charCodeAt(0)
|
|
399
|
+
if (code >= 0xdc00 && code <= 0xdfff) suffix = suffix.slice(1)
|
|
400
|
+
}
|
|
401
|
+
const text = `${marker}${suffix}`
|
|
402
|
+
const candidate = makeProjectionSelection(text, true)
|
|
403
|
+
if (candidate.budget.fits) {
|
|
404
|
+
best = candidate
|
|
405
|
+
low = keep + 1
|
|
406
|
+
} else {
|
|
407
|
+
high = keep - 1
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
if (best) return best
|
|
411
|
+
}
|
|
378
412
|
}
|
|
379
413
|
// batas tak aman / ringkasan kosong → lanjut sebagai histori kanonik penuh.
|
|
380
414
|
}
|
|
381
415
|
|
|
382
416
|
const full = coverageOf(input, rows, 0)
|
|
383
417
|
const fullFreshness = selectionFreshness(full.frontier, input.canonicalFrontier)
|
|
418
|
+
const fullTokens = sumTokens(full.messages, est)
|
|
384
419
|
|
|
385
420
|
// ── Strategi 2: fallback-unknown (STALE/DIVERGED/UNKNOWN) ──────────────────
|
|
386
421
|
// N3: baris BASI (view di belakang kanonis) TIDAK boleh dilabeli
|
|
387
422
|
// "full-history" — label itu menyiratkan representasi kanonik yang trusted,
|
|
388
423
|
// padahal view ini tak memutakhirkan diri ke head kanonis. Pakai
|
|
389
|
-
// `fallback-unknown`
|
|
424
|
+
// `fallback-unknown` bila histori penuh muat; bila tidak, teruskan ke
|
|
425
|
+
// budget-tail dengan status freshness tetap dihitung dari frontier terpilih.
|
|
390
426
|
// Coverage completeness (semua baris tersedia diikutkan) ≠ freshness/trust.
|
|
391
|
-
if (
|
|
427
|
+
if (
|
|
428
|
+
(fullFreshness === "unknown" || fullFreshness === "diverged" || fullFreshness === "stale") &&
|
|
429
|
+
fullTokens <= limit
|
|
430
|
+
) {
|
|
392
431
|
return Object.freeze({
|
|
393
432
|
sessionId: input.sessionId,
|
|
394
433
|
threadId: input.threadId,
|
|
@@ -404,7 +443,6 @@ export function selectContext(input: SelectContextInput): ContextSelection {
|
|
|
404
443
|
}
|
|
405
444
|
|
|
406
445
|
// ── Strategi 3: full-history (muat budget) ─────────────────────────────────
|
|
407
|
-
const fullTokens = sumTokens(full.messages, est)
|
|
408
446
|
if (fullTokens <= limit) {
|
|
409
447
|
return Object.freeze({
|
|
410
448
|
sessionId: input.sessionId,
|
|
@@ -217,7 +217,7 @@ function open(cwd?: string, local = false): Database {
|
|
|
217
217
|
db.exec("ALTER TABLE sessions ADD COLUMN parent_run_id TEXT NULL")
|
|
218
218
|
}
|
|
219
219
|
// P0.2 (Q5): persistensi WorkMode di metadata sesi lintas `--resume`.
|
|
220
|
-
// NULL = sesi legacy
|
|
220
|
+
// NULL = sesi legacy tanpa WorkMode tersimpan (resume fallback DISCUSS).
|
|
221
221
|
if (!cols.some((c) => c.name === "work_mode")) {
|
|
222
222
|
db.exec("ALTER TABLE sessions ADD COLUMN work_mode TEXT NULL")
|
|
223
223
|
}
|
|
@@ -739,6 +739,9 @@ function isValidEventShape(value: Record<string, unknown>): boolean {
|
|
|
739
739
|
const isStr = (k: string): boolean => typeof value[k] === "string"
|
|
740
740
|
const isNum = (k: string): boolean => typeof value[k] === "number"
|
|
741
741
|
const isArr = (k: string): boolean => Array.isArray(value[k])
|
|
742
|
+
const validAttemptId =
|
|
743
|
+
value.attemptId === undefined ||
|
|
744
|
+
(Number.isSafeInteger(value.attemptId) && (value.attemptId as number) > 0)
|
|
742
745
|
if (!isValidParentLink(value.parentLink)) return false
|
|
743
746
|
switch (value.type) {
|
|
744
747
|
case "plan.updated":
|
|
@@ -778,7 +781,7 @@ function isValidEventShape(value: Record<string, unknown>): boolean {
|
|
|
778
781
|
return true
|
|
779
782
|
case "model.delta":
|
|
780
783
|
case "reasoning.delta":
|
|
781
|
-
return isStr("delta")
|
|
784
|
+
return isStr("delta") && validAttemptId
|
|
782
785
|
case "model.completed":
|
|
783
786
|
case "reasoning.completed":
|
|
784
787
|
return isStr("text")
|
|
@@ -805,7 +808,7 @@ function isValidEventShape(value: Record<string, unknown>): boolean {
|
|
|
805
808
|
case "result.produced":
|
|
806
809
|
return isStr("resultId") && !!value.status
|
|
807
810
|
case "diagnostic.raised":
|
|
808
|
-
return isStr("category") && isStr("message")
|
|
811
|
+
return isStr("category") && isStr("message") && validAttemptId
|
|
809
812
|
case "consequence.decided":
|
|
810
813
|
return isStr("verdict") && isStr("failureClass") && isStr("nextAction") && isStr("rationale")
|
|
811
814
|
case "context.cutoff":
|