minicode-ai 0.27.0 → 0.30.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 +1 -1
- package/cli/args.ts +184 -57
- package/cli/bootstrap/presentation-bridge.ts +383 -0
- package/cli/commands/acp.ts +45 -29
- 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 +18 -15
- package/cli/commands/exec.ts +41 -89
- 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 +51 -100
- package/cli/model-manager.ts +7 -2
- package/cli/provider-manager.ts +33 -18
- package/cli/router.ts +41 -12
- package/cli/setup.ts +241 -485
- package/cli/tui.ts +303 -100
- package/docs/TERMINAL_CONTRACT.md +258 -73
- package/docs/UI_RENDER_PIPELINE.md +9 -1
- package/docs/agents.md +2 -2
- package/docs/architecture.md +17 -32
- 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 +144 -68
- package/src/app/tool-layer.ts +38 -16
- 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/atomic-write.ts +31 -59
- 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/jail.ts +6 -8
- 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/anthropic.ts +16 -5
- package/src/providers/provision.ts +6 -56
- package/src/providers/responses.ts +38 -7
- package/src/providers/sse-bounds.ts +6 -4
- 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/db/runs.ts +397 -0
- package/src/session/db/schema.ts +358 -0
- package/src/session/open-work.ts +26 -3
- package/src/session/persistence.ts +74 -998
- package/src/session/verification.ts +170 -20
- package/src/skills/loader.ts +31 -16
- package/src/task/db/schema.ts +325 -0
- package/src/task/db/types.ts +269 -0
- package/src/task/production-scheduler.ts +13 -1
- package/src/task/store.ts +92 -1021
- 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 +158 -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 +35 -19
package/src/policy/work-mode.ts
CHANGED
|
@@ -13,13 +13,16 @@
|
|
|
13
13
|
import type { PermissionHandler, ToolCall } from "#minicore"
|
|
14
14
|
import type { PermissionMode } from "./permission.ts"
|
|
15
15
|
import {
|
|
16
|
-
LOCAL_READONLY_TOOL_NAMES,
|
|
17
16
|
NETWORK_READ_TOOL_NAMES,
|
|
18
17
|
PLAN_EXTRA_TOOL_NAMES,
|
|
19
18
|
READONLY_TOOL_NAMES,
|
|
20
19
|
} from "./tool-contract.ts"
|
|
21
20
|
|
|
22
|
-
export type WorkMode = "DISCUSS" | "
|
|
21
|
+
export type WorkMode = "DISCUSS" | "EXECUTE"
|
|
22
|
+
|
|
23
|
+
export function normalizeWorkMode(mode?: WorkMode | string | null): WorkMode {
|
|
24
|
+
return mode === "EXECUTE" ? "EXECUTE" : "DISCUSS"
|
|
25
|
+
}
|
|
23
26
|
|
|
24
27
|
/**
|
|
25
28
|
* Error kebijakan startup saat `--verify` digabung dengan WorkMode non-EXECUTE
|
|
@@ -28,7 +31,7 @@ export type WorkMode = "DISCUSS" | "PLAN" | "EXECUTE"
|
|
|
28
31
|
*/
|
|
29
32
|
export class VerifyWorkModeConflictError extends Error {
|
|
30
33
|
readonly workMode: Exclude<WorkMode, "EXECUTE">
|
|
31
|
-
constructor(workMode: Exclude<WorkMode, "EXECUTE">) {
|
|
34
|
+
constructor(workMode: Exclude<WorkMode, "EXECUTE"> = "DISCUSS") {
|
|
32
35
|
super(
|
|
33
36
|
`[work-mode] --verify cannot be combined with WorkMode ${workMode} (verification runs shell commands and self-heal turns; use --work-mode BUILD or omit --verify)`,
|
|
34
37
|
)
|
|
@@ -63,7 +66,7 @@ export type WorkModePermissionHandler = PermissionHandler &
|
|
|
63
66
|
function requireModeControl(base: PermissionHandler): ModeControl {
|
|
64
67
|
const ctrl = base as Partial<ModeControl>
|
|
65
68
|
if (typeof ctrl.__getMode !== "function" || typeof ctrl.__setMode !== "function") {
|
|
66
|
-
// Fail-closed: tanpa kontrol mode, ceiling
|
|
69
|
+
// Fail-closed: tanpa kontrol mode, ceiling DISCUSS tak bisa mengikuti mode PM
|
|
67
70
|
// saat runtime — lebih baik menolak konstruksi daripada memakai snapshot
|
|
68
71
|
// basi yang bisa mencabut ceiling setelah `__setMode`.
|
|
69
72
|
throw new Error(
|
|
@@ -74,27 +77,21 @@ function requireModeControl(base: PermissionHandler): ModeControl {
|
|
|
74
77
|
}
|
|
75
78
|
|
|
76
79
|
// Seleksi ceiling per mode PM SAAT INI (bukan snapshot konstruksi):
|
|
77
|
-
// DISCUSS
|
|
78
|
-
// ketat (`allowlist`/`readonly`), selain itu ceiling plan.
|
|
79
|
-
function ceilingFor(
|
|
80
|
-
if (workMode === "DISCUSS") return "readonly"
|
|
80
|
+
// DISCUSS (gabungan diskusi + perencanaan) memakai ceiling read-only saat PM sudah
|
|
81
|
+
// lebih ketat (`allowlist`/`readonly`), selain itu ceiling plan (18 readonly + 3 plan extra).
|
|
82
|
+
function ceilingFor(_workMode: RestrictiveWorkMode, baseMode: PermissionMode): "readonly" | "plan" {
|
|
81
83
|
return baseMode === "allowlist" || baseMode === "readonly" ? "readonly" : "plan"
|
|
82
84
|
}
|
|
83
85
|
|
|
84
86
|
// Tool Access Policy — ceiling capability WorkMode dihitung LANGSUNG dari
|
|
85
|
-
// registry kontrak tool (satu sumber)
|
|
86
|
-
//
|
|
87
|
-
//
|
|
88
|
-
// - DISCUSS → tepat 16 `LOCAL_READONLY_TOOL_NAMES` (network read ditolak
|
|
89
|
-
// terpisah di check() dengan alasan khusus).
|
|
90
|
-
// - PLAN → 18 `READONLY_TOOL_NAMES` (+ `PLAN_EXTRA_TOOL_NAMES`), atau
|
|
87
|
+
// registry kontrak tool (satu sumber):
|
|
88
|
+
// - DISCUSS → 18 `READONLY_TOOL_NAMES` (+ `PLAN_EXTRA_TOOL_NAMES`), atau
|
|
91
89
|
// read-only saja bila PM sudah `readonly`/`allowlist` (lebih ketat).
|
|
92
90
|
function ceilingAllows(
|
|
93
91
|
name: string,
|
|
94
|
-
|
|
92
|
+
_workMode: RestrictiveWorkMode,
|
|
95
93
|
baseMode: PermissionMode,
|
|
96
94
|
): boolean {
|
|
97
|
-
if (workMode === "DISCUSS") return LOCAL_READONLY_TOOL_NAMES.includes(name)
|
|
98
95
|
if (baseMode === "readonly" || baseMode === "allowlist") return READONLY_TOOL_NAMES.has(name)
|
|
99
96
|
return READONLY_TOOL_NAMES.has(name) || PLAN_EXTRA_TOOL_NAMES.has(name)
|
|
100
97
|
}
|
|
@@ -105,13 +102,7 @@ export function createWorkModePermissionHandler(opts: {
|
|
|
105
102
|
root?: string
|
|
106
103
|
}): WorkModePermissionHandler {
|
|
107
104
|
const ctrl = requireModeControl(opts.base)
|
|
108
|
-
|
|
109
|
-
// mengkonsultasi handler per tool call, jadi __setWorkMode runtime menggeser
|
|
110
|
-
// ceiling tanpa mengganti handler. EXECUTE = delegasi base (perilaku identik).
|
|
111
|
-
let wm: WorkMode = opts.workMode
|
|
112
|
-
// Handler deny ceiling — hanya untuk seam describeDenial (alasan yang sama
|
|
113
|
-
// dengan perilaku lama: "read-only mode" / "plan mode"). Tidak ada lagi
|
|
114
|
-
// handler PermissionMode `readonly`/`plan` sebagai primitif ceiling.
|
|
105
|
+
let wm: WorkMode = normalizeWorkMode(opts.workMode)
|
|
115
106
|
const ceilingDenyHandlers: Record<"readonly" | "plan", PermissionHandler> = {
|
|
116
107
|
readonly: {
|
|
117
108
|
async check() {
|
|
@@ -176,41 +167,27 @@ export function createWorkModePermissionHandler(opts: {
|
|
|
176
167
|
|
|
177
168
|
const handler = {
|
|
178
169
|
async check(call: ToolCall, _deps?: unknown): Promise<"allow" | "deny"> {
|
|
179
|
-
// EXECUTE = identitas: delegasi penuh ke base tanpa ceiling (perilaku
|
|
180
|
-
// lama). Memungkinkan upgrade runtime EXECUTE→DISCUSS/PLAN walau komposisi
|
|
181
|
-
// awal EXECUTE (compose mengembalikan base) TIDAK menyediakan __setWorkMode —
|
|
182
|
-
// jalur ini dipakai createMinicodeSession yang SELALU membungkus.
|
|
183
170
|
if (wm === "EXECUTE") return opts.base.check(call, _deps as never)
|
|
184
|
-
// P0.2 (Q2): DISCUSS melarang network read (`web_fetch`, `web_search`) di
|
|
185
|
-
// SEMUA PermissionMode tanpa pernah menyentuh base (0 prompt).
|
|
186
|
-
if (wm === "DISCUSS" && NETWORK_READ_TOOL_NAMES.has(call.name)) {
|
|
187
|
-
rememberDeny(call, discussNetworkDeny)
|
|
188
|
-
return "deny"
|
|
189
|
-
}
|
|
190
|
-
// Baca mode PM sekarang: `__setMode` runtime menggeser seleksi ceiling
|
|
191
|
-
// (PLAN × allowlist/readonly = read-only), bukan membekukan yang lama.
|
|
192
|
-
// Baca WorkMode sekarang (`wm` mutable) — __setWorkMode runtime menggeser
|
|
193
|
-
// ceiling DISCUSS↔PLAN.
|
|
194
171
|
const baseMode = ctrl.__getMode()
|
|
195
172
|
const ceilingKind = ceilingFor(wm, baseMode)
|
|
196
|
-
// Ceiling DULU (Tool Access Policy): operasi di luar ceiling tak boleh
|
|
197
|
-
// memicu prompt base (requirement S2.1 #1) — ceiling tak pernah prompt.
|
|
198
173
|
if (!ceilingAllows(call.name, wm, baseMode)) {
|
|
199
174
|
rememberDeny(call, ceilingDenyHandlers[ceilingKind])
|
|
200
175
|
return "deny"
|
|
201
176
|
}
|
|
202
|
-
// Di dalam ceiling:
|
|
203
|
-
//
|
|
204
|
-
const
|
|
177
|
+
// Di dalam ceiling DISCUSS: paksa enforceJail=true agar `DISCUSS × unrestricted`
|
|
178
|
+
// tidak melompati jail workspace maupun proteksi berkas sensitif `.env` (INV-WM1).
|
|
179
|
+
const baseDeps =
|
|
180
|
+
_deps && typeof _deps === "object"
|
|
181
|
+
? { ...(_deps as Record<string, unknown>), enforceJail: true }
|
|
182
|
+
: { enforceJail: true }
|
|
183
|
+
const decision = await opts.base.check(call, baseDeps as never)
|
|
205
184
|
if (decision !== "allow") {
|
|
206
185
|
rememberDeny(call, opts.base)
|
|
207
186
|
return decision
|
|
208
187
|
}
|
|
209
|
-
//
|
|
210
|
-
//
|
|
211
|
-
|
|
212
|
-
// terjaga (WorkMode tak pernah melonggarkan penolakan base).
|
|
213
|
-
if (wm === "PLAN" && NETWORK_READ_TOOL_NAMES.has(call.name)) {
|
|
188
|
+
// Di DISCUSS, network read (`web_fetch`, `web_search`) wajib melewati
|
|
189
|
+
// gerbang approval prompt eksplisit (headless/tanpa __promptGated = fail-closed deny).
|
|
190
|
+
if (NETWORK_READ_TOOL_NAMES.has(call.name)) {
|
|
214
191
|
if (typeof ctrl.__promptGated !== "function") {
|
|
215
192
|
rememberDeny(call, discussNetworkDeny)
|
|
216
193
|
return "deny"
|
|
@@ -225,19 +202,15 @@ export function createWorkModePermissionHandler(opts: {
|
|
|
225
202
|
ctrl.__setMode(m)
|
|
226
203
|
},
|
|
227
204
|
__getMode(): PermissionMode {
|
|
228
|
-
// Metadata yang dilaporkan tetap mode PM asli; WorkMode tidak bocor.
|
|
229
205
|
return ctrl.__getMode()
|
|
230
206
|
},
|
|
231
207
|
__setWorkMode(m: WorkMode): void {
|
|
232
|
-
wm = m
|
|
208
|
+
wm = normalizeWorkMode(m)
|
|
233
209
|
},
|
|
234
210
|
__getWorkMode(): WorkMode {
|
|
235
211
|
return wm
|
|
236
212
|
},
|
|
237
213
|
describeDenial(call: ToolCall): Promise<string | undefined> | string | undefined {
|
|
238
|
-
// Cek owner map lebih dulu: bila call ditolak saat mode non-EXECUTE lalu
|
|
239
|
-
// WorkMode diubah ke EXECUTE sebelum describeDenial dipanggil, alasan
|
|
240
|
-
// deny tetap diambil dari pemilik yang mencatatnya.
|
|
241
214
|
const owner = takeDenyOwner(call)
|
|
242
215
|
if (owner) {
|
|
243
216
|
const seam = owner.describeDenial
|
|
@@ -259,9 +232,10 @@ export function composeWorkModePermissionHandler(opts: {
|
|
|
259
232
|
base: PermissionHandler
|
|
260
233
|
root?: string
|
|
261
234
|
}): PermissionHandler {
|
|
262
|
-
|
|
235
|
+
const wm = normalizeWorkMode(opts.workMode)
|
|
236
|
+
if (wm === "EXECUTE") return opts.base
|
|
263
237
|
return createWorkModePermissionHandler({
|
|
264
|
-
workMode:
|
|
238
|
+
workMode: wm,
|
|
265
239
|
base: opts.base,
|
|
266
240
|
root: opts.root,
|
|
267
241
|
})
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
|
|
15
15
|
import { type CanonicalAssignmentTable, decodeCanonicalAssignments } from "../task/assignment.ts"
|
|
16
16
|
import { classifyToolResult, denyReasonOf, summarizeArgs } from "../telemetry/trace.ts"
|
|
17
|
-
import { normalizeTodos } from "../tools/todo.ts"
|
|
17
|
+
import { extractCommittedTodoStatuses, normalizeTodos } from "../tools/todo.ts"
|
|
18
18
|
import type {
|
|
19
19
|
ApprovalEventHook,
|
|
20
20
|
ApprovalHookEvent,
|
|
@@ -483,6 +483,7 @@ export function createPresentationAdapter(
|
|
|
483
483
|
* back to the legacy positional shape rather than claim `v2`.
|
|
484
484
|
*/
|
|
485
485
|
assignment?: CanonicalAssignmentTable,
|
|
486
|
+
resultContent?: unknown,
|
|
486
487
|
):
|
|
487
488
|
| {
|
|
488
489
|
steps: PlanStep[]
|
|
@@ -501,21 +502,27 @@ export function createPresentationAdapter(
|
|
|
501
502
|
return undefined
|
|
502
503
|
}
|
|
503
504
|
if (list.length === 0) return undefined
|
|
504
|
-
const
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
t.
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
505
|
+
const committed = extractCommittedTodoStatuses(resultContent, list.length)
|
|
506
|
+
const steps: PlanStep[] = list.map((t, i) => {
|
|
507
|
+
const effectiveStatus = committed?.[i] ?? t.status
|
|
508
|
+
return {
|
|
509
|
+
stepId: String(i + 1),
|
|
510
|
+
// PHASE 4A.4 - the declared id is passed to the resolver as a HINT only. It
|
|
511
|
+
// is kept on the step solely when TaskStore confirms that row exists for
|
|
512
|
+
// this session; otherwise it is stripped below, so an unverified id can
|
|
513
|
+
// never appear on a published plan.
|
|
514
|
+
...(t.taskId ? { taskId: t.taskId } : {}),
|
|
515
|
+
title: t.content,
|
|
516
|
+
status:
|
|
517
|
+
effectiveStatus === "completed" ||
|
|
518
|
+
effectiveStatus === "cancelled" ||
|
|
519
|
+
effectiveStatus === "blocked"
|
|
520
|
+
? effectiveStatus
|
|
521
|
+
: effectiveStatus === "in_progress"
|
|
522
|
+
? "active"
|
|
523
|
+
: "pending",
|
|
524
|
+
}
|
|
525
|
+
})
|
|
519
526
|
const status = steps.every((step) => step.status === "completed")
|
|
520
527
|
? "completed"
|
|
521
528
|
: steps.every((step) => step.status === "cancelled")
|
|
@@ -946,6 +953,7 @@ export function createPresentationAdapter(
|
|
|
946
953
|
call.args,
|
|
947
954
|
planSessionId,
|
|
948
955
|
decodeCanonicalAssignments(result.content, { sessionId: planSessionId }),
|
|
956
|
+
result.content,
|
|
949
957
|
)
|
|
950
958
|
if (plan) {
|
|
951
959
|
publish({
|
|
@@ -104,13 +104,24 @@ export function createAnthropicProvider(config: AnthropicConfig): ModelProvider
|
|
|
104
104
|
const effectiveMaxTokens = legacyBudget
|
|
105
105
|
? Math.max(config.maxTokens ?? 8192, legacyBudget + 1024)
|
|
106
106
|
: (config.maxTokens ?? 8192)
|
|
107
|
-
// Fase 7:
|
|
108
|
-
// stabil terakhir (kedua dari akhir; yang terakhir = pesan user saat ini)
|
|
109
|
-
// agar tool result besar ikut ter-cache tiap turn (bukan dikirim ulang).
|
|
107
|
+
// Fase 7: sematkan cache_control pada blok konten stabil terakhir.
|
|
110
108
|
const messagesPayload = toAnthropicMessages(request.messages)
|
|
111
109
|
if (enableCache && messagesPayload.length >= 2) {
|
|
112
|
-
const lastStable = messagesPayload[messagesPayload.length - 2] as
|
|
113
|
-
|
|
110
|
+
const lastStable = messagesPayload[messagesPayload.length - 2] as {
|
|
111
|
+
role: string
|
|
112
|
+
content: unknown
|
|
113
|
+
}
|
|
114
|
+
if (Array.isArray(lastStable.content) && lastStable.content.length > 0) {
|
|
115
|
+
const lastBlock = lastStable.content[lastStable.content.length - 1] as Record<
|
|
116
|
+
string,
|
|
117
|
+
unknown
|
|
118
|
+
>
|
|
119
|
+
lastBlock.cache_control = { type: "ephemeral" }
|
|
120
|
+
} else if (typeof lastStable.content === "string") {
|
|
121
|
+
lastStable.content = [
|
|
122
|
+
{ type: "text", text: lastStable.content, cache_control: { type: "ephemeral" } },
|
|
123
|
+
]
|
|
124
|
+
}
|
|
114
125
|
}
|
|
115
126
|
const body = JSON.stringify({
|
|
116
127
|
model: request.model ?? config.defaultModel ?? config.models[0],
|
|
@@ -12,10 +12,10 @@ import {
|
|
|
12
12
|
type MinicodeConfig,
|
|
13
13
|
normalizeConfig,
|
|
14
14
|
type ProviderEntry,
|
|
15
|
+
updateConfigAtomic,
|
|
15
16
|
withConfigLock,
|
|
16
17
|
writeConfigAtomic,
|
|
17
18
|
} from "../config.ts"
|
|
18
|
-
import { atomicWriteText } from "../lib/atomic-write.ts"
|
|
19
19
|
import { getSecret } from "../lib/keystore.ts"
|
|
20
20
|
import { clearDetectCache, type DetectResult, detectModels } from "./detect.ts"
|
|
21
21
|
import { GATEWAY_PRESETS } from "./presets.ts"
|
|
@@ -39,44 +39,11 @@ export async function saveProvider(
|
|
|
39
39
|
const needsKey = entry.auth !== "oauth"
|
|
40
40
|
if (!entry.id || !entry.baseUrl || (needsKey && !entry.apiKey))
|
|
41
41
|
throw new Error("provider id/baseUrl/apiKey required")
|
|
42
|
-
//
|
|
43
|
-
|
|
44
|
-
const path =
|
|
45
|
-
(opts.global ?? true) ? globalConfigPath() : resolve(opts.cwd ?? process.cwd(), LOCAL)
|
|
46
|
-
// Kunci per-path SAMA dengan saveMcpServer/saveLspServer (audit #07):
|
|
47
|
-
// tanpa ini baca-modifikasi-tulis paralel last-wins dan menelan entri.
|
|
48
|
-
return withConfigLock(path, async () => {
|
|
49
|
-
let cfg: MinicodeConfig = { providers: [] }
|
|
50
|
-
try {
|
|
51
|
-
cfg = normalizeConfig(JSON.parse(await readFile(path, "utf8")))
|
|
52
|
-
} catch (e) {
|
|
53
|
-
// Audit #08 P1: reset diam-diam saat berkas korup MENGHAPUS semua
|
|
54
|
-
// provider + MCP/LSP/verify/allowlist lain saat tulis berikutnya.
|
|
55
|
-
// ENOENT (belum ada file) = mulai kosong; korup = backup + gagal keras
|
|
56
|
-
// seperti saveMcpServer; error lain (EACCES/…) = teruskan, jangan timpa.
|
|
57
|
-
if (e instanceof SyntaxError) {
|
|
58
|
-
const raw = await readFile(path, "utf8").catch(() => "")
|
|
59
|
-
const backup = `${path}.corrupt.${Date.now()}`
|
|
60
|
-
await atomicWriteText(backup, raw).catch(() => {})
|
|
61
|
-
throw new Error(`config corrupt: ${path} — backup to ${backup}: ${e.message}`)
|
|
62
|
-
}
|
|
63
|
-
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e
|
|
64
|
-
}
|
|
42
|
+
// Entri baru menang mutlak agar perintah `auto` bisa menghapus kunci jendela sebelumnya.
|
|
43
|
+
return updateConfigAtomic(opts, (cfg) => {
|
|
65
44
|
const idx = cfg.providers.findIndex((p) => p.id === entry.id)
|
|
66
|
-
if (idx >= 0) {
|
|
67
|
-
|
|
68
|
-
...entry,
|
|
69
|
-
// Entri baru menang MUTLAK atas nilai lama: `saveProvider` menulis apa
|
|
70
|
-
// yang diberikan pemanggil. Sengaja tanpa "selamatkan nilai lama bila
|
|
71
|
-
// entry tidak punya field ini" — versi lama melakukan itu dan membuat
|
|
72
|
-
// `auto` (hapus jendela) mustahil: `assignContextWindow` sengaja MENGHAPUS
|
|
73
|
-
// kunci, dan penyelamatan di sini membangkitkannya lagi sehingga perintah
|
|
74
|
-
// "kembali ke otomatis" sukses di layar tapi tak berefek di config.
|
|
75
|
-
// Pemanggil yang memang ingin mempertahankan nilai lama (mis. `sync`)
|
|
76
|
-
// sudah membacanya sendiri lewat `loadConfig` sebelum menyusun entry.
|
|
77
|
-
}
|
|
78
|
-
} else cfg.providers.push(entry)
|
|
79
|
-
await writeConfigAtomic(path, cfg)
|
|
45
|
+
if (idx >= 0) cfg.providers[idx] = { ...entry }
|
|
46
|
+
else cfg.providers.push(entry)
|
|
80
47
|
})
|
|
81
48
|
}
|
|
82
49
|
|
|
@@ -255,25 +222,8 @@ export async function detectAndSave(
|
|
|
255
222
|
}
|
|
256
223
|
|
|
257
224
|
export async function removeProvider(id: string, opts: { global?: boolean; cwd?: string } = {}) {
|
|
258
|
-
|
|
259
|
-
(opts.global ?? true) ? globalConfigPath() : resolve(opts.cwd ?? process.cwd(), LOCAL)
|
|
260
|
-
return withConfigLock(path, async () => {
|
|
261
|
-
let cfg: MinicodeConfig = { providers: [] }
|
|
262
|
-
try {
|
|
263
|
-
cfg = normalizeConfig(JSON.parse(await readFile(path, "utf8")))
|
|
264
|
-
} catch (e) {
|
|
265
|
-
// Sama seperti saveProvider (audit #08 P1): korup = backup + gagal
|
|
266
|
-
// keras, bukan reset diam-diam yang menghapus seluruh config.
|
|
267
|
-
if (e instanceof SyntaxError) {
|
|
268
|
-
const raw = await readFile(path, "utf8").catch(() => "")
|
|
269
|
-
const backup = `${path}.corrupt.${Date.now()}`
|
|
270
|
-
await atomicWriteText(backup, raw).catch(() => {})
|
|
271
|
-
throw new Error(`config corrupt: ${path} — backup to ${backup}: ${e.message}`)
|
|
272
|
-
}
|
|
273
|
-
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e
|
|
274
|
-
}
|
|
225
|
+
return updateConfigAtomic(opts, (cfg) => {
|
|
275
226
|
cfg.providers = cfg.providers.filter((p) => p.id !== id)
|
|
276
|
-
await writeConfigAtomic(path, cfg)
|
|
277
227
|
})
|
|
278
228
|
}
|
|
279
229
|
|
|
@@ -254,6 +254,28 @@ export function createResponsesProvider(config: ResponsesConfig): ModelProvider
|
|
|
254
254
|
// response.completed → simpan id untuk chaining turn berikut.
|
|
255
255
|
// Format nyata: {type:"response.completed", response:{id:"resp_…"}}.
|
|
256
256
|
const dtype = data.type as string | undefined
|
|
257
|
+
if (dtype === "error" || dtype === "response.failed" || data.error) {
|
|
258
|
+
if (prev) lastResponseByModel.delete(modelKey)
|
|
259
|
+
const errRec =
|
|
260
|
+
(data.error as Record<string, unknown> | undefined) ??
|
|
261
|
+
(data.response as { error?: Record<string, unknown> } | undefined)?.error ??
|
|
262
|
+
data
|
|
263
|
+
const msg = String(errRec.message ?? errRec.msg ?? JSON.stringify(errRec))
|
|
264
|
+
const code = String(errRec.code ?? errRec.type ?? "")
|
|
265
|
+
const combined = `${msg} ${code}`
|
|
266
|
+
const cat = /auth|401|403|unauthorized/i.test(combined)
|
|
267
|
+
? "auth"
|
|
268
|
+
: /quota_exceeded|insufficient_quota|balance/i.test(combined)
|
|
269
|
+
? "unknown"
|
|
270
|
+
: /rate|429/i.test(combined)
|
|
271
|
+
? "rate_limit"
|
|
272
|
+
: /context_length|maximum context|prompt is too long|context window/i.test(
|
|
273
|
+
msg,
|
|
274
|
+
)
|
|
275
|
+
? "context_length_exceeded"
|
|
276
|
+
: "server"
|
|
277
|
+
throw new ProviderError(cat, cat === "unknown" ? `402: ${msg}` : `${cat}: ${msg}`)
|
|
278
|
+
}
|
|
257
279
|
if (dtype === "response.completed" || dtype === "completed") {
|
|
258
280
|
const resp = data.response as { id?: unknown; usage?: unknown } | undefined
|
|
259
281
|
const rid = resp?.id ?? data.id
|
|
@@ -287,6 +309,7 @@ export function createResponsesProvider(config: ResponsesConfig): ModelProvider
|
|
|
287
309
|
outputTokens:
|
|
288
310
|
typeof u.output_tokens === "number" ? u.output_tokens : undefined,
|
|
289
311
|
totalTokens: typeof u.total_tokens === "number" ? u.total_tokens : undefined,
|
|
312
|
+
cacheIncluded: true,
|
|
290
313
|
...(typeof cached === "number" ? { cacheReadTokens: cached } : {}),
|
|
291
314
|
},
|
|
292
315
|
}
|
|
@@ -390,14 +413,22 @@ export function createResponsesProvider(config: ResponsesConfig): ModelProvider
|
|
|
390
413
|
typeof data.arguments === "string" ? data.arguments : "",
|
|
391
414
|
)
|
|
392
415
|
}
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
dtype === "
|
|
397
|
-
dtype
|
|
398
|
-
|
|
416
|
+
// Abaikan event lifecycle/summary `.done`/`.added` agar teks utuh di
|
|
417
|
+
// `response.output_text.done` tidak digandakan setelah `.delta`.
|
|
418
|
+
const isNonDeltaEvent =
|
|
419
|
+
typeof dtype === "string" &&
|
|
420
|
+
(dtype.endsWith(".done") ||
|
|
421
|
+
dtype.endsWith(".added") ||
|
|
422
|
+
dtype === "response.created" ||
|
|
423
|
+
dtype === "response.in_progress" ||
|
|
424
|
+
dtype === "response.completed" ||
|
|
425
|
+
dtype === "completed" ||
|
|
426
|
+
dtype === "response.incomplete" ||
|
|
427
|
+
dtype.startsWith("response.function_call") ||
|
|
428
|
+
dtype.startsWith("response.reasoning") ||
|
|
429
|
+
dtype === "function_call")
|
|
399
430
|
const text =
|
|
400
|
-
reasoningText ||
|
|
431
|
+
reasoningText || isNonDeltaEvent
|
|
401
432
|
? undefined
|
|
402
433
|
: ((typeof rawDelta === "string" ? rawDelta : undefined) ??
|
|
403
434
|
drec.text ??
|
|
@@ -51,10 +51,7 @@ export function boundedSseBody(
|
|
|
51
51
|
if (done) {
|
|
52
52
|
reachedEof = true
|
|
53
53
|
if (lineBytes !== 0 || frameBytes !== 0) {
|
|
54
|
-
throw new ProviderError(
|
|
55
|
-
"invalid_request",
|
|
56
|
-
`${provider} returned an incomplete SSE frame`,
|
|
57
|
-
)
|
|
54
|
+
throw new ProviderError("network", `${provider} returned an incomplete SSE frame`)
|
|
58
55
|
}
|
|
59
56
|
controller.close()
|
|
60
57
|
release()
|
|
@@ -68,6 +65,11 @@ export function boundedSseBody(
|
|
|
68
65
|
)
|
|
69
66
|
}
|
|
70
67
|
for (const byte of value) {
|
|
68
|
+
if (byte === 0x0d) {
|
|
69
|
+
// CRLF: 0x0D ikut dihitung frameBytes, bukan lineBytes
|
|
70
|
+
frameBytes++
|
|
71
|
+
continue
|
|
72
|
+
}
|
|
71
73
|
if (byte === 0x0a) {
|
|
72
74
|
frameBytes++
|
|
73
75
|
if (frameBytes > maxFrameBytes) {
|
|
@@ -37,6 +37,7 @@ import { createHash } from "node:crypto"
|
|
|
37
37
|
import { mkdirSync } from "node:fs"
|
|
38
38
|
import { dirname } from "node:path"
|
|
39
39
|
import { LIMITS } from "../constants.ts"
|
|
40
|
+
import { isSqliteContention, withSqliteBusyRetrySync } from "../lib/db-path.ts"
|
|
40
41
|
import type { ExecutionEvent } from "./execution-events.ts"
|
|
41
42
|
|
|
42
43
|
/** Versi skema jurnal (bentuk/encoding) — BUKAN executionVersion. */
|
|
@@ -336,36 +337,10 @@ export async function withJournalBusyRetry<T>(
|
|
|
336
337
|
throw last instanceof Error ? last : new Error(`SQLITE_BUSY after ${attempts} attempts`)
|
|
337
338
|
}
|
|
338
339
|
|
|
339
|
-
// [Phase 12.3] Predikat kontensi SQLite transien lintas-proses — SELARAS dengan
|
|
340
|
-
// persistence.ts / store.ts / vector.ts (Fase 12.2). Bun menaruh kode simbolik di
|
|
341
|
-
// `error.code` (mis. "SQLITE_IOERR_TRUNCATE") dan teks manusiawi di `error.message`
|
|
342
|
-
// ("disk I/O error"), jadi keduanya diperiksa. SENGAJA TIDAK di-retry:
|
|
343
|
-
// SQLITE_CORRUPT / SQLITE_NOTADB / constraint error.
|
|
344
|
-
const SQLITE_CONTENTION_RE =
|
|
345
|
-
/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
|
|
346
|
-
|
|
347
|
-
function isSqliteContention(e: unknown): boolean {
|
|
348
|
-
const code = (e as { code?: unknown } | null)?.code
|
|
349
|
-
if (typeof code === "string" && SQLITE_CONTENTION_RE.test(code)) return true
|
|
350
|
-
const msg = e instanceof Error ? String(e.message ?? e) : String(e)
|
|
351
|
-
return SQLITE_CONTENTION_RE.test(msg)
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
const DB_INIT_ATTEMPTS = 8
|
|
355
|
-
const DB_INIT_BACKOFF_MS = 15
|
|
356
|
-
|
|
357
340
|
/** Retry sinkron untuk setup PRAGMA/WAL saat open (jalur sinkron openExecutionJournal). */
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
return fn()
|
|
362
|
-
} catch (e) {
|
|
363
|
-
if (!isSqliteContention(e)) throw e
|
|
364
|
-
Bun.sleepSync(DB_INIT_BACKOFF_MS * 2 ** i)
|
|
365
|
-
}
|
|
366
|
-
}
|
|
367
|
-
return null
|
|
368
|
-
}
|
|
341
|
+
const DB_INIT_ATTEMPTS = 8
|
|
342
|
+
const withBusyRetrySync = <T>(fn: () => T, attempts = DB_INIT_ATTEMPTS): T | null =>
|
|
343
|
+
withSqliteBusyRetrySync(fn, { attempts })
|
|
369
344
|
|
|
370
345
|
function isCorruptionError(e: unknown): boolean {
|
|
371
346
|
const msg = (e instanceof Error ? e.message : String(e)).toLowerCase()
|
package/src/sandbox/docker.ts
CHANGED
|
@@ -4,6 +4,11 @@ import { resolve } from "node:path"
|
|
|
4
4
|
import { LIMITS } from "../constants.ts"
|
|
5
5
|
import { resolveTrustedExecutable } from "../lib/trusted-exec.ts"
|
|
6
6
|
import { sanitizeSpawnEnv } from "../policy/scrub.ts"
|
|
7
|
+
import {
|
|
8
|
+
allocateEmptyMaskFile,
|
|
9
|
+
createCappedOutputCollector,
|
|
10
|
+
discoverSandboxMaskTargets,
|
|
11
|
+
} from "./mask.ts"
|
|
7
12
|
|
|
8
13
|
let dockerOk: boolean | null = null
|
|
9
14
|
|
|
@@ -86,24 +91,26 @@ function removeContainer(name: string, env: NodeJS.ProcessEnv): Promise<boolean>
|
|
|
86
91
|
})
|
|
87
92
|
}
|
|
88
93
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
export function runInDocker(
|
|
94
|
+
/** Susun argumen `docker run` termasuk masking `.minicode/` & `.env*` sensitif. */
|
|
95
|
+
export function buildDockerRunArgs(
|
|
92
96
|
command: string,
|
|
93
97
|
cwd: string,
|
|
94
|
-
opts: DockerRunOptions
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
98
|
+
opts: DockerRunOptions,
|
|
99
|
+
mask: {
|
|
100
|
+
containerName: string
|
|
101
|
+
hasMinicode: boolean
|
|
102
|
+
envFiles: readonly string[]
|
|
103
|
+
emptyMaskHostPath: string | null
|
|
104
|
+
},
|
|
105
|
+
): string[] {
|
|
99
106
|
const image = opts.image ?? process.env.MINICODE_SANDBOX_IMAGE ?? "node:22-alpine"
|
|
100
107
|
const mount = workspaceMount(cwd)
|
|
101
|
-
const
|
|
108
|
+
const net = opts.network === "bridge" ? "bridge" : "none"
|
|
102
109
|
const args = [
|
|
103
110
|
"run",
|
|
104
111
|
"--rm",
|
|
105
112
|
"--name",
|
|
106
|
-
containerName,
|
|
113
|
+
mask.containerName,
|
|
107
114
|
"-i",
|
|
108
115
|
"--read-only",
|
|
109
116
|
"--cap-drop",
|
|
@@ -116,10 +123,22 @@ export function runInDocker(
|
|
|
116
123
|
"/tmp",
|
|
117
124
|
"-v",
|
|
118
125
|
`${mount}:${mount}`,
|
|
126
|
+
]
|
|
127
|
+
// Sembunyikan state minicode (.minicode/) dan rahasia workspace (.env*) di dalam container.
|
|
128
|
+
if (mask.hasMinicode) {
|
|
129
|
+
args.push("--tmpfs", `${mount}/.minicode:ro,size=64k`)
|
|
130
|
+
}
|
|
131
|
+
if (mask.emptyMaskHostPath) {
|
|
132
|
+
const emptyMount = workspaceMount(mask.emptyMaskHostPath)
|
|
133
|
+
for (const rel of mask.envFiles) {
|
|
134
|
+
args.push("-v", `${emptyMount}:${mount}/${rel}:ro`)
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
args.push(
|
|
119
138
|
"-w",
|
|
120
139
|
mount,
|
|
121
140
|
"--network",
|
|
122
|
-
|
|
141
|
+
net,
|
|
123
142
|
"--memory",
|
|
124
143
|
opts.memory ?? process.env.MINICODE_SANDBOX_MEMORY ?? "512m",
|
|
125
144
|
"--cpus",
|
|
@@ -130,7 +149,29 @@ export function runInDocker(
|
|
|
130
149
|
"sh",
|
|
131
150
|
"-c",
|
|
132
151
|
command,
|
|
133
|
-
|
|
152
|
+
)
|
|
153
|
+
return args
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Run command di dalam container ephemeral, terisolasi (--network none default,
|
|
157
|
+
// memori/CPU cap, masking .env/.minicode), mount workspace read-write. Return { code, output }.
|
|
158
|
+
export function runInDocker(
|
|
159
|
+
command: string,
|
|
160
|
+
cwd: string,
|
|
161
|
+
opts: DockerRunOptions = {},
|
|
162
|
+
): Promise<{ code: number | null; output: string }> {
|
|
163
|
+
if (opts.signal?.aborted) {
|
|
164
|
+
return Promise.resolve({ code: null, output: "[docker] aborted before container start" })
|
|
165
|
+
}
|
|
166
|
+
const containerName = `minicode-${randomUUID()}`
|
|
167
|
+
const targets = discoverSandboxMaskTargets(cwd)
|
|
168
|
+
const emptyMask = allocateEmptyMaskFile(targets.envFiles.length > 0)
|
|
169
|
+
const args = buildDockerRunArgs(command, cwd, opts, {
|
|
170
|
+
containerName,
|
|
171
|
+
hasMinicode: targets.hasMinicode,
|
|
172
|
+
envFiles: targets.envFiles,
|
|
173
|
+
emptyMaskHostPath: emptyMask.path,
|
|
174
|
+
})
|
|
134
175
|
|
|
135
176
|
return new Promise((resolveResult) => {
|
|
136
177
|
// env selalu disanitasi dari hasil merge final — secret (API_KEY/TOKEN/...)
|
|
@@ -141,25 +182,9 @@ export function runInDocker(
|
|
|
141
182
|
env,
|
|
142
183
|
})
|
|
143
184
|
// Cap buffer saat streaming — output container raksasa tidak menumpuk di RAM.
|
|
144
|
-
const
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
let truncated = false
|
|
148
|
-
const appendCapped = (target: "out" | "err", d: Buffer | string): void => {
|
|
149
|
-
const s = typeof d === "string" ? d : d.toString()
|
|
150
|
-
const cur = target === "out" ? out : err
|
|
151
|
-
if (cur.length >= OUT_CAP) {
|
|
152
|
-
truncated = true
|
|
153
|
-
return
|
|
154
|
-
}
|
|
155
|
-
const room = OUT_CAP - cur.length
|
|
156
|
-
if (s.length > room) truncated = true
|
|
157
|
-
const piece = s.slice(0, Math.max(0, room))
|
|
158
|
-
if (target === "out") out += piece
|
|
159
|
-
else err += piece
|
|
160
|
-
}
|
|
161
|
-
p.stdout.on("data", (d) => appendCapped("out", d))
|
|
162
|
-
p.stderr.on("data", (d) => appendCapped("err", d))
|
|
185
|
+
const collector = createCappedOutputCollector(LIMITS.DOCKER_OUTPUT_MAX_CHARS)
|
|
186
|
+
p.stdout.on("data", (d) => collector.append("out", d))
|
|
187
|
+
p.stderr.on("data", (d) => collector.append("err", d))
|
|
163
188
|
const timeout =
|
|
164
189
|
typeof opts.timeoutMs === "number" && Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0
|
|
165
190
|
? opts.timeoutMs
|
|
@@ -175,9 +200,8 @@ export function runInDocker(
|
|
|
175
200
|
settled = true
|
|
176
201
|
clearTimeout(t)
|
|
177
202
|
signal?.removeEventListener("abort", onAbort)
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
resolveResult({ code, output })
|
|
203
|
+
emptyMask.cleanup()
|
|
204
|
+
resolveResult({ code, output: collector.format().output + suffix })
|
|
181
205
|
}
|
|
182
206
|
const requestStop = (reason: "timeout" | "abort") => {
|
|
183
207
|
if (stopReason || settled) return
|