minicode-ai 0.27.0 → 0.28.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/cli/args.ts +120 -16
- package/cli/commands/acp.ts +38 -28
- package/cli/commands/auth.ts +17 -17
- package/cli/commands/config.ts +65 -66
- package/cli/commands/daemon.ts +44 -16
- package/cli/commands/doctor.ts +11 -12
- package/cli/commands/exec.ts +35 -73
- package/cli/commands/mcp.ts +25 -8
- package/cli/commands/memory.ts +16 -24
- package/cli/commands/openwork.ts +6 -2
- package/cli/commands/pricing.ts +14 -12
- package/cli/commands/providers.ts +36 -57
- package/cli/commands/sessions.ts +24 -18
- package/cli/commands/skills.ts +33 -18
- package/cli/commands/stats.ts +15 -30
- package/cli/commands.ts +73 -44
- package/cli/context-command-run.ts +30 -18
- package/cli/index.ts +48 -98
- package/cli/model-manager.ts +7 -2
- package/cli/provider-manager.ts +33 -18
- package/cli/router.ts +41 -12
- package/cli/setup.ts +246 -123
- package/cli/tui.ts +303 -100
- package/docs/TERMINAL_CONTRACT.md +254 -69
- package/docs/UI_RENDER_PIPELINE.md +9 -1
- package/docs/agents.md +2 -2
- package/docs/architecture.md +3 -3
- package/docs/choosing-mode.md +7 -9
- package/docs/cli.md +3 -5
- package/docs/environment.md +1 -2
- package/docs/policy-sandbox.md +3 -3
- package/docs/repl.md +2 -2
- package/docs/tools.md +1 -1
- package/package.json +1 -1
- package/src/app/mentions.ts +60 -13
- package/src/app/rag-layer.ts +17 -20
- package/src/app/session.ts +119 -66
- package/src/app/tool-layer.ts +12 -17
- package/src/config.ts +64 -104
- package/src/constants.ts +4 -6
- package/src/daemon/capability.ts +8 -1
- package/src/daemon/control.ts +3 -2
- package/src/daemon/server.ts +57 -0
- package/src/hooks/run.ts +73 -41
- package/src/lib/db-path.ts +47 -0
- package/src/lib/process-tree.ts +62 -0
- package/src/lib/public-http.ts +88 -23
- package/src/lib/trusted-exec.ts +48 -1
- package/src/lsp/client.ts +62 -17
- package/src/mcp/client.ts +85 -38
- package/src/mcp/http-transport.ts +28 -16
- package/src/mcp/transport.ts +42 -6
- package/src/memory/files.ts +164 -134
- package/src/memory/vector.ts +371 -420
- package/src/policy/approval-binding.ts +122 -45
- package/src/policy/bash-guard.ts +18 -7
- package/src/policy/compaction.ts +51 -18
- package/src/policy/context-window.ts +31 -8
- package/src/policy/context.ts +62 -36
- package/src/policy/executor.ts +17 -7
- package/src/policy/microcompact.ts +4 -3
- package/src/policy/no-progress.ts +103 -22
- package/src/policy/permission.ts +36 -12
- package/src/policy/tool-contract.ts +74 -416
- package/src/policy/usage.ts +24 -2
- package/src/policy/verifier.ts +50 -2
- package/src/policy/work-mode.ts +28 -54
- package/src/presentation/adapter.ts +24 -16
- package/src/providers/provision.ts +6 -56
- package/src/providers/responses.ts +1 -0
- package/src/runtime/execution-journal.ts +4 -29
- package/src/sandbox/docker.ts +58 -34
- package/src/sandbox/mask.ts +157 -0
- package/src/sandbox/os.ts +107 -73
- package/src/session/authority.ts +29 -10
- package/src/session/context-projection.ts +6 -5
- package/src/session/open-work.ts +26 -3
- package/src/session/persistence.ts +25 -58
- package/src/session/verification.ts +170 -20
- package/src/skills/loader.ts +31 -16
- package/src/task/production-scheduler.ts +13 -1
- package/src/task/store.ts +20 -37
- package/src/telemetry/trace.ts +27 -0
- package/src/tools/ask_user.ts +1 -13
- package/src/tools/bash.ts +27 -92
- package/src/tools/code_run.ts +1 -1
- package/src/tools/context.ts +133 -0
- package/src/tools/delete_file.ts +3 -2
- package/src/tools/edit.ts +37 -72
- package/src/tools/git.ts +86 -9
- package/src/tools/glob.ts +26 -51
- package/src/tools/grep.ts +67 -57
- package/src/tools/hashline.ts +4 -0
- package/src/tools/lsp.ts +11 -8
- package/src/tools/mcp_call.ts +9 -6
- package/src/tools/memory.ts +56 -33
- package/src/tools/move_file.ts +36 -10
- package/src/tools/patch.ts +13 -21
- package/src/tools/read_file.ts +18 -25
- package/src/tools/read_image.ts +35 -33
- package/src/tools/submit_result.ts +29 -8
- package/src/tools/task.ts +74 -17
- package/src/tools/todo.ts +181 -74
- package/src/tools/web_fetch.ts +42 -2
- package/src/tools/web_search.ts +47 -8
- package/src/ui/approval/prompt.ts +206 -47
- package/src/ui/assistant/turn-status.ts +14 -5
- package/src/ui/footer.ts +4 -4
- package/src/ui/i18n/en.ts +47 -23
- package/src/ui/i18n/id.ts +76 -51
- package/src/ui/input/input.ts +4 -3
- package/src/ui/input/prompt-engine.ts +35 -5
- package/src/ui/render/activity-panel.ts +4 -2
- package/src/ui/render/hint.ts +7 -4
- package/src/ui/render/list.ts +32 -0
- package/src/ui/render/markdown.ts +6 -3
- package/src/ui/render/notice.ts +19 -0
- package/src/ui/render/table-grid.ts +7 -8
- package/src/ui/render/theme.ts +113 -39
- package/src/ui/runtime/screen.ts +74 -10
- package/src/ui/runtime/spinner.ts +19 -6
- package/src/ui/screens/dialog.ts +19 -1
- package/src/ui/screens/form.ts +80 -35
- package/src/ui/screens/model-manager.ts +82 -61
- package/src/ui/screens/output-window.ts +263 -0
- package/src/ui/screens/picker.ts +94 -81
- package/src/ui/screens/provider-manager.ts +100 -69
- package/src/ui/screens/wizard.ts +117 -28
- package/src/ui/tui/app.ts +196 -33
- package/src/ui/tui/transcript.ts +154 -25
- package/vendor/minicore/src/core/executor.ts +2 -0
- package/vendor/minicore/src/core/loop.ts +17 -6
- package/vendor/minicore/src/core/session.ts +3 -0
- package/vendor/minicore/src/core/tool.ts +1 -0
- package/vendor/minicore/src/providers/openai-compat.ts +28 -19
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import {
|
|
2
|
+
chmodSync,
|
|
3
|
+
existsSync,
|
|
4
|
+
lstatSync,
|
|
5
|
+
mkdtempSync,
|
|
6
|
+
readdirSync,
|
|
7
|
+
rmSync,
|
|
8
|
+
writeFileSync,
|
|
9
|
+
} from "node:fs"
|
|
10
|
+
import { tmpdir } from "node:os"
|
|
11
|
+
import { join, relative, resolve } from "node:path"
|
|
12
|
+
|
|
13
|
+
/** Template env publik non-rahasia yang tetap diizinkan terbaca di sandbox (Opsi A). */
|
|
14
|
+
export const SAFE_ENV_TEMPLATES: ReadonlySet<string> = new Set([
|
|
15
|
+
".env.example",
|
|
16
|
+
".env.sample",
|
|
17
|
+
".env.template",
|
|
18
|
+
])
|
|
19
|
+
|
|
20
|
+
const SKIP_DIRS: ReadonlySet<string> = new Set([
|
|
21
|
+
".git",
|
|
22
|
+
"node_modules",
|
|
23
|
+
".minicode",
|
|
24
|
+
"dist",
|
|
25
|
+
"build",
|
|
26
|
+
])
|
|
27
|
+
const MAX_SCAN_DIRS = 500
|
|
28
|
+
const MAX_SCAN_DEPTH = 3
|
|
29
|
+
|
|
30
|
+
/** Apakah nama file termasuk berkas `.env*` sensitif yang wajib dimasking. */
|
|
31
|
+
export function isSensitiveEnvFileName(name: string): boolean {
|
|
32
|
+
const lower = name.toLowerCase()
|
|
33
|
+
if (SAFE_ENV_TEMPLATES.has(lower)) return false
|
|
34
|
+
return lower === ".env" || lower.startsWith(".env.")
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface SandboxMaskTargets {
|
|
38
|
+
readonly hasMinicode: boolean
|
|
39
|
+
/** Path relatif berformat POSIX terhadap workspace root (`".env"`, `"apps/a/.env.local"`). */
|
|
40
|
+
readonly envFiles: readonly string[]
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Temukan `.minicode/` dan file `.env*` sensitif yang BENAR-BENAR ada di workspace.
|
|
45
|
+
* Hanya mengembalikan path yang sudah eksis agar bind-mount read-only tidak pernah
|
|
46
|
+
* menciptakan entri `.env` kosong di host.
|
|
47
|
+
*/
|
|
48
|
+
export function discoverSandboxMaskTargets(cwd: string): SandboxMaskTargets {
|
|
49
|
+
const abs = resolve(cwd)
|
|
50
|
+
let hasMinicode = false
|
|
51
|
+
try {
|
|
52
|
+
hasMinicode = existsSync(join(abs, ".minicode"))
|
|
53
|
+
} catch {
|
|
54
|
+
hasMinicode = false
|
|
55
|
+
}
|
|
56
|
+
const envFiles: string[] = []
|
|
57
|
+
const queue: { dir: string; depth: number }[] = [{ dir: abs, depth: 0 }]
|
|
58
|
+
let visitedDirs = 0
|
|
59
|
+
|
|
60
|
+
while (queue.length > 0 && visitedDirs < MAX_SCAN_DIRS) {
|
|
61
|
+
const { dir, depth } = queue.shift()!
|
|
62
|
+
visitedDirs++
|
|
63
|
+
let entries: string[]
|
|
64
|
+
try {
|
|
65
|
+
entries = readdirSync(dir)
|
|
66
|
+
} catch {
|
|
67
|
+
continue
|
|
68
|
+
}
|
|
69
|
+
for (const name of entries) {
|
|
70
|
+
const full = join(dir, name)
|
|
71
|
+
let st: ReturnType<typeof lstatSync>
|
|
72
|
+
try {
|
|
73
|
+
st = lstatSync(full)
|
|
74
|
+
} catch {
|
|
75
|
+
continue
|
|
76
|
+
}
|
|
77
|
+
if (st.isDirectory()) {
|
|
78
|
+
if (depth < MAX_SCAN_DEPTH && !SKIP_DIRS.has(name)) {
|
|
79
|
+
queue.push({ dir: full, depth: depth + 1 })
|
|
80
|
+
}
|
|
81
|
+
continue
|
|
82
|
+
}
|
|
83
|
+
if ((st.isFile() || st.isSymbolicLink()) && isSensitiveEnvFileName(name)) {
|
|
84
|
+
const rel = relative(abs, full).replace(/\\/g, "/")
|
|
85
|
+
if (rel && !rel.startsWith("..")) envFiles.push(rel)
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
envFiles.sort()
|
|
90
|
+
return { hasMinicode, envFiles }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Buat satu berkas kosong read-only (0 byte) di tempdir host untuk memasking
|
|
95
|
+
* file `.env*` di dalam Docker/bwrap, lengkap dengan fungsi pembersihan idempoten.
|
|
96
|
+
*/
|
|
97
|
+
export function allocateEmptyMaskFile(needed: boolean): {
|
|
98
|
+
path: string | null
|
|
99
|
+
cleanup: () => void
|
|
100
|
+
} {
|
|
101
|
+
if (!needed) return { path: null, cleanup: () => {} }
|
|
102
|
+
let tempDir: string | null = null
|
|
103
|
+
let cleaned = false
|
|
104
|
+
try {
|
|
105
|
+
tempDir = mkdtempSync(join(tmpdir(), "mc-sb-mask-"))
|
|
106
|
+
const maskFile = join(tempDir, "empty-mask")
|
|
107
|
+
writeFileSync(maskFile, "", { mode: 0o444 })
|
|
108
|
+
try {
|
|
109
|
+
chmodSync(maskFile, 0o444)
|
|
110
|
+
} catch {}
|
|
111
|
+
return {
|
|
112
|
+
path: maskFile,
|
|
113
|
+
cleanup: () => {
|
|
114
|
+
if (cleaned || !tempDir) return
|
|
115
|
+
cleaned = true
|
|
116
|
+
try {
|
|
117
|
+
rmSync(tempDir, { recursive: true, force: true })
|
|
118
|
+
} catch {}
|
|
119
|
+
},
|
|
120
|
+
}
|
|
121
|
+
} catch {
|
|
122
|
+
if (tempDir) {
|
|
123
|
+
try {
|
|
124
|
+
rmSync(tempDir, { recursive: true, force: true })
|
|
125
|
+
} catch {}
|
|
126
|
+
}
|
|
127
|
+
return { path: null, cleanup: () => {} }
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Kolektor output proses (stdout+stderr) berbatas karakter untuk runner sandbox. */
|
|
132
|
+
export function createCappedOutputCollector(cap: number) {
|
|
133
|
+
let out = ""
|
|
134
|
+
let err = ""
|
|
135
|
+
let truncated = false
|
|
136
|
+
const append = (target: "out" | "err", d: Buffer | string): void => {
|
|
137
|
+
const s = typeof d === "string" ? d : d.toString()
|
|
138
|
+
const cur = target === "out" ? out : err
|
|
139
|
+
if (cur.length >= cap) {
|
|
140
|
+
truncated = true
|
|
141
|
+
return
|
|
142
|
+
}
|
|
143
|
+
const room = cap - cur.length
|
|
144
|
+
if (s.length > room) truncated = true
|
|
145
|
+
const piece = s.slice(0, Math.max(0, room))
|
|
146
|
+
if (target === "out") out += piece
|
|
147
|
+
else err += piece
|
|
148
|
+
}
|
|
149
|
+
const format = () => {
|
|
150
|
+
const marker = truncated ? "\n… [output truncated]" : ""
|
|
151
|
+
return {
|
|
152
|
+
marker,
|
|
153
|
+
output: (out + (err ? `\n[stderr]\n${err}` : "")).trim() + marker,
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return { append, format }
|
|
157
|
+
}
|
package/src/sandbox/os.ts
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
import { spawn, spawnSync } from "node:child_process"
|
|
2
|
-
import { resolve } from "node:path"
|
|
2
|
+
import { join, resolve } from "node:path"
|
|
3
3
|
import { LIMITS } from "../constants.ts"
|
|
4
4
|
import { resolveTrustedExecutable } from "../lib/trusted-exec.ts"
|
|
5
5
|
import { sanitizeSpawnEnv } from "../policy/scrub.ts"
|
|
6
|
+
import {
|
|
7
|
+
allocateEmptyMaskFile,
|
|
8
|
+
createCappedOutputCollector,
|
|
9
|
+
discoverSandboxMaskTargets,
|
|
10
|
+
} from "./mask.ts"
|
|
6
11
|
|
|
7
12
|
let osSandboxOk: boolean | null = null
|
|
8
13
|
let osSandboxType: "seatbelt" | "bwrap" | "none" | null = null
|
|
@@ -65,8 +70,92 @@ export interface OsSandboxOptions {
|
|
|
65
70
|
network?: "none" | "bridge"
|
|
66
71
|
}
|
|
67
72
|
|
|
68
|
-
|
|
69
|
-
|
|
73
|
+
function escapeSeatbelt(s: string): string {
|
|
74
|
+
return s.replace(/\\/g, "\\\\").replace(/"/g, '\\"')
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Susun profil macOS Seatbelt dengan penolakan `.minicode/` dan berkas `.env*` sensitif. */
|
|
78
|
+
export function buildSeatbeltProfile(
|
|
79
|
+
absCwd: string,
|
|
80
|
+
envFiles: readonly string[] = [],
|
|
81
|
+
opts: { network?: "none" | "bridge" } = {},
|
|
82
|
+
): string {
|
|
83
|
+
const escapedAbs = escapeSeatbelt(absCwd)
|
|
84
|
+
const deniedPaths = new Set<string>([
|
|
85
|
+
...envFiles.map((rel) => join(absCwd, rel)),
|
|
86
|
+
...([".env", ".env.local", ".env.production", ".env.development", ".env.test"] as const).map(
|
|
87
|
+
(f) => join(absCwd, f),
|
|
88
|
+
),
|
|
89
|
+
])
|
|
90
|
+
const envDenyRules = [...deniedPaths]
|
|
91
|
+
.sort()
|
|
92
|
+
.map((p) => `(deny file-read* file-write* (literal "${escapeSeatbelt(p)}"))`)
|
|
93
|
+
.join("\n")
|
|
94
|
+
const escapedMinicode = escapeSeatbelt(join(absCwd, ".minicode"))
|
|
95
|
+
return `(version 1)
|
|
96
|
+
(deny default)
|
|
97
|
+
(allow process-exec)
|
|
98
|
+
(allow file-read* file-write* (subpath "${escapedAbs}"))
|
|
99
|
+
(deny file-read* file-write* (subpath "${escapedMinicode}"))
|
|
100
|
+
${envDenyRules}
|
|
101
|
+
(allow file-read* (subpath "/usr") (subpath "/bin") (subpath "/private/tmp"))
|
|
102
|
+
(allow sysctl-read)
|
|
103
|
+
${opts.network === "bridge" ? "(allow network*)" : "(deny network*)"}
|
|
104
|
+
`
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Susun argumen `bwrap` dengan isolasi namespace penuh dan masking `.minicode/` & `.env*`. */
|
|
108
|
+
export function buildBwrapArgs(
|
|
109
|
+
command: string,
|
|
110
|
+
absCwd: string,
|
|
111
|
+
opts: OsSandboxOptions,
|
|
112
|
+
mask: {
|
|
113
|
+
hasMinicode: boolean
|
|
114
|
+
envFiles: readonly string[]
|
|
115
|
+
emptyMaskPath: string | null
|
|
116
|
+
},
|
|
117
|
+
): string[] {
|
|
118
|
+
const args = [
|
|
119
|
+
"--ro-bind",
|
|
120
|
+
"/usr",
|
|
121
|
+
"/usr",
|
|
122
|
+
"--ro-bind",
|
|
123
|
+
"/bin",
|
|
124
|
+
"/bin",
|
|
125
|
+
"--ro-bind",
|
|
126
|
+
"/lib",
|
|
127
|
+
"/lib",
|
|
128
|
+
"--ro-bind-try",
|
|
129
|
+
"/lib64",
|
|
130
|
+
"/lib64",
|
|
131
|
+
"--proc",
|
|
132
|
+
"/proc",
|
|
133
|
+
"--dev",
|
|
134
|
+
"/dev",
|
|
135
|
+
"--tmpfs",
|
|
136
|
+
"/tmp",
|
|
137
|
+
"--bind",
|
|
138
|
+
absCwd,
|
|
139
|
+
absCwd,
|
|
140
|
+
]
|
|
141
|
+
if (mask.hasMinicode) {
|
|
142
|
+
args.push("--tmpfs", join(absCwd, ".minicode"))
|
|
143
|
+
}
|
|
144
|
+
if (mask.emptyMaskPath) {
|
|
145
|
+
for (const rel of mask.envFiles) {
|
|
146
|
+
args.push("--ro-bind", mask.emptyMaskPath, join(absCwd, rel))
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
args.push("--chdir", absCwd, "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--new-session")
|
|
150
|
+
if (opts.network !== "bridge") {
|
|
151
|
+
args.push("--unshare-net")
|
|
152
|
+
}
|
|
153
|
+
args.push("--die-with-parent", "--cap-drop", "ALL", "sh", "-c", command)
|
|
154
|
+
return args
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Seatbelt profile minimal (deny network, restrict writes outside cwd + .env/.minicode)
|
|
158
|
+
// bwrap: bubblewrap with --ro-bind / --bind cwd, namespace unshare + masking
|
|
70
159
|
export function runInOsSandbox(
|
|
71
160
|
command: string,
|
|
72
161
|
cwd: string,
|
|
@@ -87,61 +176,23 @@ export function runInOsSandbox(
|
|
|
87
176
|
const abs = resolve(cwd)
|
|
88
177
|
const sanitizedEnv = sanitizeSpawnEnv(process.env, opts.env) as Record<string, string>
|
|
89
178
|
const timeout = opts.timeoutMs ?? LIMITS.DOCKER_TIMEOUT_MS
|
|
179
|
+
const targets = discoverSandboxMaskTargets(abs)
|
|
90
180
|
|
|
91
181
|
if (type === "seatbelt") {
|
|
92
|
-
|
|
93
|
-
const escapedAbs = abs.replace(/\\/g, "\\\\").replace(/"/g, '\\"')
|
|
94
|
-
const profile = `(version 1)
|
|
95
|
-
(deny default)
|
|
96
|
-
(allow process-exec)
|
|
97
|
-
(allow file-read* file-write* (subpath "${escapedAbs}"))
|
|
98
|
-
(allow file-read* (subpath "/usr") (subpath "/bin") (subpath "/private/tmp"))
|
|
99
|
-
(allow sysctl-read)
|
|
100
|
-
(deny network*)
|
|
101
|
-
`
|
|
102
|
-
// Use sandbox-exec with inline profile via stdin? sandbox-exec needs file, write tmp
|
|
182
|
+
const profile = buildSeatbeltProfile(abs, targets.envFiles, { network: opts.network })
|
|
103
183
|
const args = ["-p", profile, "sh", "-c", command]
|
|
104
184
|
return runSpawn("sandbox-exec", args, abs, sanitizedEnv, timeout, opts.signal)
|
|
105
185
|
}
|
|
106
186
|
if (type === "bwrap") {
|
|
107
|
-
const
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
"/lib",
|
|
117
|
-
"--ro-bind-try",
|
|
118
|
-
"/lib64",
|
|
119
|
-
"/lib64",
|
|
120
|
-
"--proc",
|
|
121
|
-
"/proc",
|
|
122
|
-
"--dev",
|
|
123
|
-
"/dev",
|
|
124
|
-
"--tmpfs",
|
|
125
|
-
"/tmp",
|
|
126
|
-
"--bind",
|
|
127
|
-
abs,
|
|
128
|
-
abs,
|
|
129
|
-
"--chdir",
|
|
130
|
-
abs,
|
|
131
|
-
"--unshare-net",
|
|
132
|
-
"--die-with-parent",
|
|
133
|
-
"--cap-drop",
|
|
134
|
-
"ALL",
|
|
135
|
-
"sh",
|
|
136
|
-
"-c",
|
|
137
|
-
command,
|
|
138
|
-
]
|
|
139
|
-
// best-effort: if network bridge requested, omit --unshare-net
|
|
140
|
-
if (opts.network === "bridge") {
|
|
141
|
-
const idx = args.indexOf("--unshare-net")
|
|
142
|
-
if (idx !== -1) args.splice(idx, 1)
|
|
143
|
-
}
|
|
144
|
-
return runSpawn("bwrap", args, abs, sanitizedEnv, timeout, opts.signal)
|
|
187
|
+
const emptyMask = allocateEmptyMaskFile(targets.envFiles.length > 0)
|
|
188
|
+
const args = buildBwrapArgs(command, abs, opts, {
|
|
189
|
+
hasMinicode: targets.hasMinicode,
|
|
190
|
+
envFiles: targets.envFiles,
|
|
191
|
+
emptyMaskPath: emptyMask.path,
|
|
192
|
+
})
|
|
193
|
+
return runSpawn("bwrap", args, abs, sanitizedEnv, timeout, opts.signal).finally(() =>
|
|
194
|
+
emptyMask.cleanup(),
|
|
195
|
+
)
|
|
145
196
|
}
|
|
146
197
|
return Promise.resolve({ code: null, output: "[os-sandbox] unknown type" })
|
|
147
198
|
}
|
|
@@ -170,25 +221,9 @@ function runSpawn(
|
|
|
170
221
|
stdio: ["ignore", "pipe", "pipe"],
|
|
171
222
|
detached: true,
|
|
172
223
|
})
|
|
173
|
-
const
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
let truncated = false
|
|
177
|
-
const appendCapped = (target: "out" | "err", d: Buffer | string): void => {
|
|
178
|
-
const s = typeof d === "string" ? d : d.toString()
|
|
179
|
-
const cur = target === "out" ? out : err
|
|
180
|
-
if (cur.length >= OUT_CAP) {
|
|
181
|
-
truncated = true
|
|
182
|
-
return
|
|
183
|
-
}
|
|
184
|
-
const room = OUT_CAP - cur.length
|
|
185
|
-
if (s.length > room) truncated = true
|
|
186
|
-
const piece = s.slice(0, Math.max(0, room))
|
|
187
|
-
if (target === "out") out += piece
|
|
188
|
-
else err += piece
|
|
189
|
-
}
|
|
190
|
-
p.stdout.on("data", (d) => appendCapped("out", d))
|
|
191
|
-
p.stderr.on("data", (d) => appendCapped("err", d))
|
|
224
|
+
const collector = createCappedOutputCollector(LIMITS.DOCKER_OUTPUT_MAX_CHARS)
|
|
225
|
+
p.stdout.on("data", (d) => collector.append("out", d))
|
|
226
|
+
p.stderr.on("data", (d) => collector.append("err", d))
|
|
192
227
|
let aborted = false
|
|
193
228
|
let timedOut = false
|
|
194
229
|
let settled = false
|
|
@@ -231,8 +266,7 @@ function runSpawn(
|
|
|
231
266
|
reject(signal?.reason)
|
|
232
267
|
return
|
|
233
268
|
}
|
|
234
|
-
const marker
|
|
235
|
-
const output = (out + (err ? `\n[stderr]\n${err}` : "")).trim() + marker
|
|
269
|
+
const { marker, output } = collector.format()
|
|
236
270
|
if (timedOut) {
|
|
237
271
|
// Kontrak lapisan ini adalah RESOLVE (bukan reject): runner hanya
|
|
238
272
|
// melaporkan hasil proses (code/output), dan pemanggil yang memutuskan
|
package/src/session/authority.ts
CHANGED
|
@@ -80,21 +80,40 @@ export function acquireSessionWriter(opts: {
|
|
|
80
80
|
const now = opts.now ?? Date.now()
|
|
81
81
|
const token = opts.token ?? writerTokenFor(bootId)
|
|
82
82
|
const store = new TaskStore(cwd)
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
83
|
+
// Baca status lease sebelumnya dan akuisisi secara atomik dalam transaksi IMMEDIATE
|
|
84
|
+
// agar `pre` selalu mencerminkan pemilik tepat sebelum pengambilalihan tanpa TOCTOU.
|
|
85
|
+
const leaseOutcome = store.withTransaction((tx) => {
|
|
86
|
+
const pre = tx.getSessionAuthority(sessionId)
|
|
87
|
+
if (pre && pre.ownerToken !== token && isLeaseActive(pre.leaseExpiresAt, now)) {
|
|
88
|
+
return {
|
|
89
|
+
ok: false as const,
|
|
90
|
+
holder: { pid: pre.ownerPid, expiresAt: pre.leaseExpiresAt },
|
|
91
|
+
}
|
|
88
92
|
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
+
const acquired = tx.acquireSessionAuthority(sessionId, token, SESSION_LEASE_MS, now)
|
|
94
|
+
if (acquired === "REFUSED_LEASE_HELD") {
|
|
95
|
+
const cur = tx.getSessionAuthority(sessionId)
|
|
96
|
+
return {
|
|
97
|
+
ok: false as const,
|
|
98
|
+
holder: {
|
|
99
|
+
pid: cur?.ownerPid ?? null,
|
|
100
|
+
expiresAt: cur?.leaseExpiresAt ?? null,
|
|
101
|
+
},
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return { ok: true as const, pre }
|
|
105
|
+
}, true)
|
|
106
|
+
if (!leaseOutcome.ok) {
|
|
93
107
|
return {
|
|
94
108
|
ok: false,
|
|
95
|
-
error: new SessionBusyError(
|
|
109
|
+
error: new SessionBusyError(
|
|
110
|
+
sessionId,
|
|
111
|
+
leaseOutcome.holder.pid,
|
|
112
|
+
leaseOutcome.holder.expiresAt,
|
|
113
|
+
),
|
|
96
114
|
}
|
|
97
115
|
}
|
|
116
|
+
const { pre } = leaseOutcome
|
|
98
117
|
// Kita pemegang lease. Takeover (bump epoch) HANYA bila baris lease
|
|
99
118
|
// sebelumnya milik token LAIN (aktif/expired) — akuisisi fresh atau
|
|
100
119
|
// re-acquire token sendiri tak menyentuh epoch (§16).
|
|
@@ -97,13 +97,10 @@ export function deriveSummaryFromCanonical(
|
|
|
97
97
|
// dilihat model saat kompaksi. baseSeq=1: ringkasan mewakili baris indeks 0,
|
|
98
98
|
// ekor [1, N) verbatim.
|
|
99
99
|
const first = messages[0] as { role?: unknown; content?: unknown } | undefined
|
|
100
|
-
|
|
100
|
+
const isKernelSummary =
|
|
101
101
|
first?.role === "user" &&
|
|
102
102
|
typeof first.content === "string" &&
|
|
103
|
-
first.content.startsWith("Previous context")
|
|
104
|
-
) {
|
|
105
|
-
return { summaryText: first.content, baseSeq: 1 }
|
|
106
|
-
}
|
|
103
|
+
first.content.startsWith("Previous context (")
|
|
107
104
|
const keep =
|
|
108
105
|
Number.isInteger(policy.keepRecentTurns) && policy.keepRecentTurns >= 1
|
|
109
106
|
? policy.keepRecentTurns
|
|
@@ -111,6 +108,10 @@ export function deriveSummaryFromCanonical(
|
|
|
111
108
|
const store = new ContextStore()
|
|
112
109
|
store.appendAll(messages)
|
|
113
110
|
const folded = mechanicalKeepResults(store, keep)
|
|
111
|
+
// Reuse ringkasan kernel apa adanya HANYA bila belum ada turn baru di luar `keepRecentTurns`.
|
|
112
|
+
if (isKernelSummary && folded.length >= messages.length) {
|
|
113
|
+
return { summaryText: first.content as string, baseSeq: 1 }
|
|
114
|
+
}
|
|
114
115
|
// Tak ada fold (prefix kosong) → tak ada cakupan untuk proyeksi.
|
|
115
116
|
if (folded.length >= messages.length) return null
|
|
116
117
|
const kept = folded.length - 1
|
package/src/session/open-work.ts
CHANGED
|
@@ -35,7 +35,8 @@
|
|
|
35
35
|
// brainstorming sebagai tugas.
|
|
36
36
|
|
|
37
37
|
import { resolve as resolvePath } from "node:path"
|
|
38
|
-
import
|
|
38
|
+
import { TaskGraph } from "../task/graph.ts"
|
|
39
|
+
import type { Task, TaskStatus, TaskVerification } from "../task/model.ts"
|
|
39
40
|
import type { ExecutionOwner, TaskMerge, TaskTransfer, UnfinishedWorkItem } from "../task/store.ts"
|
|
40
41
|
import { TaskStore } from "../task/store.ts"
|
|
41
42
|
import { readCheckpointInventorySync } from "./checkpoint.ts"
|
|
@@ -393,14 +394,27 @@ export function projectOpenWork(opts: ProjectOpenWorkOptions = {}): OpenWorkRepo
|
|
|
393
394
|
keyCounts.set(key, (keyCounts.get(key) ?? 0) + 1)
|
|
394
395
|
}
|
|
395
396
|
|
|
397
|
+
// Indeks snapshot & graf per sesi SEKALI di depan untuk membuang query SQL
|
|
398
|
+
// berulang (N+1) sekaligus mendeteksi blocker graf seperti siklus/parent hilang.
|
|
399
|
+
const tasksBySession = new Map<string, Map<string, Task>>()
|
|
400
|
+
const graphsBySession = new Map<string, TaskGraph>()
|
|
401
|
+
for (const item of items) {
|
|
402
|
+
if (tasksBySession.has(item.sessionId)) continue
|
|
403
|
+
const snap = store.getSnapshot(item.sessionId)
|
|
404
|
+
tasksBySession.set(item.sessionId, new Map(snap.tasks.map((t) => [t.id, t])))
|
|
405
|
+
graphsBySession.set(item.sessionId, new TaskGraph(snap))
|
|
406
|
+
}
|
|
407
|
+
|
|
396
408
|
const open: OpenWorkEntry[] = items.map((item, idx) => {
|
|
397
409
|
const meta = sessionMeta.get(item.sessionId)
|
|
398
410
|
const ageMs = Math.max(0, now - toMs(item.task.updatedAt))
|
|
399
411
|
const titleKey = titleKeys[idx] ?? ""
|
|
412
|
+
const sessionTasks = tasksBySession.get(item.sessionId)
|
|
413
|
+
const graph = graphsBySession.get(item.sessionId)
|
|
400
414
|
|
|
401
415
|
// ── P14.4: dependensi direkonsiliasi ke status kanonik saat baca ──
|
|
402
416
|
const dependencies: WorkDependency[] = item.task.dependsOn.map((depId) => {
|
|
403
|
-
const dep =
|
|
417
|
+
const dep = sessionTasks?.get(depId)
|
|
404
418
|
const status: TaskStatus | "MISSING" = dep?.status ?? "MISSING"
|
|
405
419
|
return {
|
|
406
420
|
taskId: depId,
|
|
@@ -409,12 +423,18 @@ export function projectOpenWork(opts: ProjectOpenWorkOptions = {}): OpenWorkRepo
|
|
|
409
423
|
satisfied: status === "COMPLETED",
|
|
410
424
|
}
|
|
411
425
|
})
|
|
426
|
+
const structuralBlockers = (graph?.blockers(item.task.id) ?? []).filter(
|
|
427
|
+
(b) =>
|
|
428
|
+
b.kind !== "DEPENDENCY_UNSATISFIED" &&
|
|
429
|
+
b.kind !== "DEPENDENCY_TERMINAL" &&
|
|
430
|
+
b.kind !== "DANGLING_DEPENDENCY",
|
|
431
|
+
)
|
|
412
432
|
|
|
413
433
|
// ── P14.1: state berbasis bukti, bukan tebakan ──
|
|
414
434
|
const unresolvedDep = dependencies.find((d) => !d.satisfied)
|
|
415
435
|
const { state, reason: stateReason } = taskWorkState(item.task.status, {
|
|
416
436
|
verification: item.task.verification,
|
|
417
|
-
unresolvedDependency: unresolvedDep !== undefined,
|
|
437
|
+
unresolvedDependency: unresolvedDep !== undefined || structuralBlockers.length > 0,
|
|
418
438
|
})
|
|
419
439
|
|
|
420
440
|
// ── P14.4: blocker eksplisit (blocker kosong = tidak ada yang diklaim) ──
|
|
@@ -427,6 +447,9 @@ export function projectOpenWork(opts: ProjectOpenWorkOptions = {}): OpenWorkRepo
|
|
|
427
447
|
blockers.push({ kind: "DEPENDENCY", detail: `${d.taskId} (${d.status})` })
|
|
428
448
|
}
|
|
429
449
|
}
|
|
450
|
+
for (const b of structuralBlockers) {
|
|
451
|
+
blockers.push({ kind: "DEPENDENCY", detail: `${b.kind}: ${b.detail}` })
|
|
452
|
+
}
|
|
430
453
|
if (item.task.verification?.verdict === "failed") {
|
|
431
454
|
blockers.push({
|
|
432
455
|
kind: "VERIFICATION",
|
|
@@ -2,7 +2,12 @@ import { Database } from "bun:sqlite"
|
|
|
2
2
|
import { createHash, randomUUID } from "node:crypto"
|
|
3
3
|
import { existsSync } from "node:fs"
|
|
4
4
|
import { LIMITS } from "../constants.ts"
|
|
5
|
-
import {
|
|
5
|
+
import {
|
|
6
|
+
isSqliteContention,
|
|
7
|
+
resolveDbPath,
|
|
8
|
+
resolveLocalDbPath,
|
|
9
|
+
withSqliteBusyRetrySync,
|
|
10
|
+
} from "../lib/db-path.ts"
|
|
6
11
|
import { scrubSecrets } from "../policy/scrub.ts"
|
|
7
12
|
import { type DomainEvent, DURABILITY, EVENT_SCHEMA_VERSION } from "../presentation/events.ts"
|
|
8
13
|
|
|
@@ -64,56 +69,17 @@ function daemonApprovalsMigrated(db: Database): boolean {
|
|
|
64
69
|
// startup. Jitter memecah sinkronisasi antar-proses yang mencoba ulang
|
|
65
70
|
// pada waktu yang sama (thundering herd).
|
|
66
71
|
const DB_INIT_ATTEMPTS = 8
|
|
67
|
-
const DB_INIT_BACKOFF_MS = 15
|
|
68
|
-
|
|
69
|
-
function dbInitBackoffMs(attempt: number): number {
|
|
70
|
-
const base = DB_INIT_BACKOFF_MS * 2 ** attempt
|
|
71
|
-
// jitter deterministik kecil (±20%) dari attempt ke-2 dst; attempt pertama
|
|
72
|
-
// (i=0) tidak dijitter agar kasus SQLITE_BUSY tunggal tetap selesai secepat
|
|
73
|
-
// mungkin (tanpa menambah latensi startup untuk jalur yang TIDAK balapan).
|
|
74
|
-
if (attempt === 0) return base
|
|
75
|
-
return base + ((attempt * 7919 + 3) % Math.max(1, Math.floor(base * 0.2)))
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
// [Phase 12.2] Predikat kontensi SQLite transien lintas-proses (buka/WAL di
|
|
79
|
-
// Windows). Sebelumnya hanya SQLITE_BUSY/"database is locked" yang di-retry; di
|
|
80
|
-
// Windows, dua proses yang membuka WAL bersamaan di bawah beban disk tinggi juga
|
|
81
|
-
// melempar SQLITE_IOERR_TRUNCATE / SQLITE_IOERR_SHMOPEN / SQLITE_IOERR_LOCK /
|
|
82
|
-
// SQLITE_PROTOCOL / SQLITE_LOCKED — semuanya transien (kompetisi lock), bukan
|
|
83
|
-
// korupsi, dan AMAN di-retry. Bun menaruh kode simbolik di `error.code` dan teks
|
|
84
|
-
// manusiawi di `error.message` (mis. SQLITE_BUSY = "database is locked",
|
|
85
|
-
// SQLITE_IOERR_* = "disk I/O error" atau kode extended), jadi keduanya diperiksa.
|
|
86
|
-
// SENGAJA TIDAK di-retry: SQLITE_CORRUPT / SQLITE_NOTADB / constraint error — retry
|
|
87
|
-
// buta hanya menyembunyikan korupsi skema/data yang nyata.
|
|
88
|
-
const SQLITE_CONTENTION_RE =
|
|
89
|
-
/SQLITE_BUSY|database is locked|database table is locked|SQLITE_LOCKED|SQLITE_PROTOCOL|SQLITE_IOERR_TRUNCATE|SQLITE_IOERR_SHMOPEN|SQLITE_IOERR_LOCK|disk I\/O error/i
|
|
90
|
-
|
|
91
|
-
function isSqliteContention(e: unknown): boolean {
|
|
92
|
-
const code = (e as { code?: unknown } | null)?.code
|
|
93
|
-
if (typeof code === "string" && SQLITE_CONTENTION_RE.test(code)) return true
|
|
94
|
-
const msg = e instanceof Error ? String(e.message ?? e) : String(e)
|
|
95
|
-
return SQLITE_CONTENTION_RE.test(msg)
|
|
96
|
-
}
|
|
97
72
|
|
|
98
73
|
export function withBusyRetrySync<T>(fn: () => T, attempts = DB_INIT_ATTEMPTS): T | null {
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
last = e
|
|
109
|
-
// Backoff sinkron eksponensial + jitter kecil (lihat dbInitBackoffMs).
|
|
110
|
-
Bun.sleepSync(dbInitBackoffMs(i))
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
process.stderr.write(
|
|
114
|
-
`[warn] persistence: schema setup gave up after ${attempts} attempts: ${String((last as Error)?.message ?? last)}\n`,
|
|
115
|
-
)
|
|
116
|
-
return null
|
|
74
|
+
return withSqliteBusyRetrySync(fn, {
|
|
75
|
+
attempts,
|
|
76
|
+
deterministicJitter: true,
|
|
77
|
+
onGiveUp: (last, n) => {
|
|
78
|
+
process.stderr.write(
|
|
79
|
+
`[warn] persistence: schema setup gave up after ${n} attempts: ${String((last as Error)?.message ?? last)}\n`,
|
|
80
|
+
)
|
|
81
|
+
},
|
|
82
|
+
})
|
|
117
83
|
}
|
|
118
84
|
|
|
119
85
|
function open(cwd?: string, local = false): Database {
|
|
@@ -1132,7 +1098,7 @@ export async function saveSession(
|
|
|
1132
1098
|
opts?: {
|
|
1133
1099
|
expectedEpoch?: number
|
|
1134
1100
|
runId?: string
|
|
1135
|
-
workMode?: "DISCUSS" | "
|
|
1101
|
+
workMode?: "DISCUSS" | "EXECUTE"
|
|
1136
1102
|
},
|
|
1137
1103
|
) {
|
|
1138
1104
|
const db = open(cwd)
|
|
@@ -1374,6 +1340,7 @@ export function purgeExpired(db: Database, now = Date.now()): number {
|
|
|
1374
1340
|
|
|
1375
1341
|
if (expiring.length > 0) {
|
|
1376
1342
|
const { TaskStore } = require("../task/store.ts") as typeof import("../task/store.ts")
|
|
1343
|
+
const { deleteTodoFilesSync } = require("../tools/todo.ts") as typeof import("../tools/todo.ts")
|
|
1377
1344
|
const fallbackCwd = sessionCwdOf(db, expiring)
|
|
1378
1345
|
const byCwd = new Map<string | undefined, string[]>()
|
|
1379
1346
|
for (const row of expiring) {
|
|
@@ -1384,10 +1351,12 @@ export function purgeExpired(db: Database, now = Date.now()): number {
|
|
|
1384
1351
|
}
|
|
1385
1352
|
for (const [cwd, ids] of byCwd) {
|
|
1386
1353
|
const tasks = new TaskStore(cwd)
|
|
1354
|
+
const resolvedCwd = cwd ?? process.cwd()
|
|
1387
1355
|
for (const sid of ids) {
|
|
1388
|
-
// 1. invalidate in-flight executions, 2. remove task rows.
|
|
1356
|
+
// 1. invalidate in-flight executions, 2. remove task rows, 3. remove derived todo/plan files.
|
|
1389
1357
|
tasks.bumpSessionIncarnation(sid)
|
|
1390
1358
|
tasks.deleteSessionTasks(sid)
|
|
1359
|
+
deleteTodoFilesSync(sid, resolvedCwd)
|
|
1391
1360
|
}
|
|
1392
1361
|
}
|
|
1393
1362
|
}
|
|
@@ -1489,15 +1458,13 @@ function decodeMessageRows(rows: StoredMessageRow[]): unknown[] {
|
|
|
1489
1458
|
})
|
|
1490
1459
|
}
|
|
1491
1460
|
|
|
1492
|
-
function parseStoredWorkMode(raw: unknown): "DISCUSS" | "
|
|
1493
|
-
if (raw === "DISCUSS" || raw === "PLAN"
|
|
1461
|
+
function parseStoredWorkMode(raw: unknown): "DISCUSS" | "EXECUTE" | undefined {
|
|
1462
|
+
if (raw === "DISCUSS" || raw === "PLAN") return "DISCUSS"
|
|
1463
|
+
if (raw === "EXECUTE") return "EXECUTE"
|
|
1494
1464
|
return undefined
|
|
1495
1465
|
}
|
|
1496
1466
|
|
|
1497
|
-
export function loadSessionWorkMode(
|
|
1498
|
-
id: string,
|
|
1499
|
-
cwd?: string,
|
|
1500
|
-
): "DISCUSS" | "PLAN" | "EXECUTE" | undefined {
|
|
1467
|
+
export function loadSessionWorkMode(id: string, cwd?: string): "DISCUSS" | "EXECUTE" | undefined {
|
|
1501
1468
|
const db = open(cwd)
|
|
1502
1469
|
try {
|
|
1503
1470
|
const row = db.prepare("SELECT work_mode FROM sessions WHERE id = ?").get(id) as {
|
|
@@ -1511,7 +1478,7 @@ export function loadSessionWorkMode(
|
|
|
1511
1478
|
|
|
1512
1479
|
export function saveSessionWorkMode(
|
|
1513
1480
|
id: string,
|
|
1514
|
-
workMode: "DISCUSS" | "
|
|
1481
|
+
workMode: "DISCUSS" | "EXECUTE",
|
|
1515
1482
|
cwd?: string,
|
|
1516
1483
|
opts?: { expectedEpoch?: number },
|
|
1517
1484
|
): void {
|