minicode-ai 0.26.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 +96 -46
- package/cli/context-command-run.ts +171 -0
- package/cli/context-command.ts +87 -0
- package/cli/index.ts +96 -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 +311 -109
- 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/config.md +16 -0
- package/docs/environment.md +3 -3
- package/docs/policy-sandbox.md +3 -3
- package/docs/repl.md +3 -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 +23 -9
- 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 +109 -0
- package/src/policy/context.ts +78 -37
- 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/guards.ts +41 -2
- package/src/providers/provision.ts +6 -60
- package/src/providers/responses.ts +1 -0
- package/src/repo/repomap.ts +180 -23
- 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 +59 -23
- package/src/ui/i18n/id.ts +88 -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 +88 -62
- 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
package/src/config.ts
CHANGED
|
@@ -282,6 +282,36 @@ export async function writeConfigAtomic(path: string, cfg: MinicodeConfig): Prom
|
|
|
282
282
|
await atomicWriteText(path, JSON.stringify(cfg, null, 2))
|
|
283
283
|
}
|
|
284
284
|
|
|
285
|
+
/** Baca `.minicode/config.json` lokal SAJA tanpa merge global. */
|
|
286
|
+
export async function loadLocalConfigOnly(cwd = process.cwd()): Promise<MinicodeConfig> {
|
|
287
|
+
try {
|
|
288
|
+
const localPath = resolve(cwd, LOCAL)
|
|
289
|
+
const raw = await readFile(localPath, "utf8")
|
|
290
|
+
return normalizeConfig(JSON.parse(raw))
|
|
291
|
+
} catch (e) {
|
|
292
|
+
// SyntaxError selalu ribut; error baca non-ENOENT (EACCES/…) ribut juga —
|
|
293
|
+
// reset diam-diam membuat override lokal "hilang" tanpa jejak.
|
|
294
|
+
const code = (e as NodeJS.ErrnoException)?.code
|
|
295
|
+
if (e instanceof SyntaxError)
|
|
296
|
+
process.stderr.write(
|
|
297
|
+
`[config] invalid JSON in ${resolve(cwd, LOCAL)}: ${(e as Error).message}\n`,
|
|
298
|
+
)
|
|
299
|
+
else if (code !== "ENOENT")
|
|
300
|
+
process.stderr.write(
|
|
301
|
+
`[config] cannot read ${resolve(cwd, LOCAL)} (${code ?? "error"}) — ignoring local\n`,
|
|
302
|
+
)
|
|
303
|
+
return { providers: [] }
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
export async function hasProviderInLocalConfig(
|
|
308
|
+
providerId: string,
|
|
309
|
+
cwd = process.cwd(),
|
|
310
|
+
): Promise<boolean> {
|
|
311
|
+
const localCfg = await loadLocalConfigOnly(cwd)
|
|
312
|
+
return localCfg.providers.some((p) => p.id === providerId)
|
|
313
|
+
}
|
|
314
|
+
|
|
285
315
|
export async function loadConfig(
|
|
286
316
|
cwd = process.cwd(),
|
|
287
317
|
opts: { allowLocal?: boolean } = {},
|
|
@@ -309,24 +339,7 @@ export async function loadConfig(
|
|
|
309
339
|
// (--allow-local-config / MINICODE_ALLOW_LOCAL_CONFIG=1); default = global
|
|
310
340
|
// saja (fail-closed). Tulis eksplisit (--local) tak terpengaruh.
|
|
311
341
|
if (opts.allowLocal) {
|
|
312
|
-
|
|
313
|
-
const localPath = resolve(cwd, LOCAL)
|
|
314
|
-
const raw = await readFile(localPath, "utf8")
|
|
315
|
-
localCfg = normalizeConfig(JSON.parse(raw))
|
|
316
|
-
} catch (e) {
|
|
317
|
-
// Sama seperti global: SyntaxError selalu ribut; error baca non-ENOENT
|
|
318
|
-
// (EACCES/…) ribut juga — reset diam-diam membuat override lokal
|
|
319
|
-
// "hilang" tanpa jejak.
|
|
320
|
-
const code = (e as NodeJS.ErrnoException)?.code
|
|
321
|
-
if (e instanceof SyntaxError)
|
|
322
|
-
process.stderr.write(
|
|
323
|
-
`[config] invalid JSON in ${resolve(cwd, LOCAL)}: ${(e as Error).message}\n`,
|
|
324
|
-
)
|
|
325
|
-
else if (code !== "ENOENT")
|
|
326
|
-
process.stderr.write(
|
|
327
|
-
`[config] cannot read ${resolve(cwd, LOCAL)} (${code ?? "error"}) — ignoring local\n`,
|
|
328
|
-
)
|
|
329
|
-
}
|
|
342
|
+
localCfg = await loadLocalConfigOnly(cwd)
|
|
330
343
|
}
|
|
331
344
|
// generic merge helper — deduplicate DRY
|
|
332
345
|
function mergeByKey<T>(global: T[], local: T[], keyFn: (v: T) => string): T[] {
|
|
@@ -378,17 +391,22 @@ export async function loadLastModel(): Promise<string | undefined> {
|
|
|
378
391
|
}
|
|
379
392
|
}
|
|
380
393
|
|
|
381
|
-
|
|
394
|
+
async function updateStateAtomic(mutate: (cur: Record<string, unknown>) => void): Promise<void> {
|
|
382
395
|
const path = statePath()
|
|
383
396
|
return withConfigLock(path, async () => {
|
|
384
397
|
await mkdir(join(homeDir(), ".minicode"), { recursive: true, mode: 0o700 }).catch(() => {})
|
|
385
|
-
// Merge (bukan timpa): state.json menampung preferensi lain (lang).
|
|
386
|
-
// Timpa utuh menghapusnya diam-diam.
|
|
387
398
|
let cur: Record<string, unknown> = {}
|
|
388
399
|
try {
|
|
389
400
|
cur = JSON.parse(await readFile(path, "utf8")) as Record<string, unknown>
|
|
390
401
|
} catch {}
|
|
391
|
-
|
|
402
|
+
mutate(cur)
|
|
403
|
+
await atomicWriteText(path, JSON.stringify(cur))
|
|
404
|
+
})
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
export async function saveLastModel(id: string): Promise<void> {
|
|
408
|
+
return updateStateAtomic((cur) => {
|
|
409
|
+
cur.lastModel = id
|
|
392
410
|
})
|
|
393
411
|
}
|
|
394
412
|
|
|
@@ -404,23 +422,16 @@ export async function loadLang(): Promise<"en" | "id" | undefined> {
|
|
|
404
422
|
}
|
|
405
423
|
|
|
406
424
|
export async function saveLang(lang: "en" | "id"): Promise<void> {
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
await mkdir(join(homeDir(), ".minicode"), { recursive: true, mode: 0o700 }).catch(() => {})
|
|
410
|
-
let cur: Record<string, unknown> = {}
|
|
411
|
-
try {
|
|
412
|
-
cur = JSON.parse(await readFile(path, "utf8")) as Record<string, unknown>
|
|
413
|
-
} catch {}
|
|
414
|
-
await atomicWriteText(path, JSON.stringify({ ...cur, lang }))
|
|
425
|
+
return updateStateAtomic((cur) => {
|
|
426
|
+
cur.lang = lang
|
|
415
427
|
})
|
|
416
428
|
}
|
|
417
429
|
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
opts: { global?: boolean; cwd?: string }
|
|
421
|
-
)
|
|
422
|
-
|
|
423
|
-
throw new Error("mcp entry needs an id + (command for stdio or url for http)")
|
|
430
|
+
/** Pembaru atomik bersama untuk file config global/lokal dengan proteksi corrupt backup. */
|
|
431
|
+
export async function updateConfigAtomic(
|
|
432
|
+
opts: { global?: boolean; cwd?: string },
|
|
433
|
+
mutate: (cfg: MinicodeConfig) => void,
|
|
434
|
+
): Promise<void> {
|
|
424
435
|
const path =
|
|
425
436
|
(opts.global ?? true) ? globalConfigPath() : resolve(opts.cwd ?? process.cwd(), LOCAL)
|
|
426
437
|
return withConfigLock(path, async () => {
|
|
@@ -435,46 +446,33 @@ export async function saveMcpServer(
|
|
|
435
446
|
await atomicWriteText(backup, raw).catch(() => {})
|
|
436
447
|
throw new Error(`config corrupt: ${path} — backup to ${backup}: ${e.message}`)
|
|
437
448
|
}
|
|
438
|
-
if ((e as
|
|
439
|
-
|
|
440
|
-
} else if ((e as Error).message?.includes("config corrupt")) {
|
|
449
|
+
if ((e as Error).message?.includes("config corrupt")) throw e
|
|
450
|
+
if ((e as NodeJS.ErrnoException).code && (e as NodeJS.ErrnoException).code !== "ENOENT") {
|
|
441
451
|
throw e
|
|
442
|
-
} else if ((e as NodeJS.ErrnoException).code) {
|
|
443
|
-
throw e
|
|
444
|
-
} else {
|
|
445
|
-
cfg = { providers: [] }
|
|
446
452
|
}
|
|
447
453
|
}
|
|
454
|
+
mutate(cfg)
|
|
455
|
+
await writeConfigAtomic(path, cfg)
|
|
456
|
+
})
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
export async function saveMcpServer(
|
|
460
|
+
entry: McpServerEntry,
|
|
461
|
+
opts: { global?: boolean; cwd?: string } = {},
|
|
462
|
+
) {
|
|
463
|
+
if (!entry.id || (!entry.command && !entry.url))
|
|
464
|
+
throw new Error("mcp entry needs an id + (command for stdio or url for http)")
|
|
465
|
+
return updateConfigAtomic(opts, (cfg) => {
|
|
448
466
|
cfg.mcpServers ??= []
|
|
449
467
|
const idx = cfg.mcpServers.findIndex((m) => m.id === entry.id)
|
|
450
468
|
if (idx >= 0) cfg.mcpServers[idx] = entry
|
|
451
469
|
else cfg.mcpServers.push(entry)
|
|
452
|
-
await writeConfigAtomic(path, cfg)
|
|
453
470
|
})
|
|
454
471
|
}
|
|
455
472
|
|
|
456
473
|
export async function removeMcpServer(id: string, opts: { global?: boolean; cwd?: string } = {}) {
|
|
457
|
-
|
|
458
|
-
(opts.global ?? true) ? globalConfigPath() : resolve(opts.cwd ?? process.cwd(), LOCAL)
|
|
459
|
-
return withConfigLock(path, async () => {
|
|
460
|
-
let cfg: MinicodeConfig = { providers: [] }
|
|
461
|
-
let raw = ""
|
|
462
|
-
try {
|
|
463
|
-
raw = await readFile(path, "utf8")
|
|
464
|
-
cfg = normalizeConfig(JSON.parse(raw))
|
|
465
|
-
} catch (e) {
|
|
466
|
-
if (e instanceof SyntaxError) {
|
|
467
|
-
const backup = `${path}.corrupt.${Date.now()}`
|
|
468
|
-
await atomicWriteText(backup, raw).catch(() => {})
|
|
469
|
-
throw new Error(`config corrupt: ${path} — backup to ${backup}: ${e.message}`)
|
|
470
|
-
}
|
|
471
|
-
if ((e as NodeJS.ErrnoException).code === "ENOENT") cfg = { providers: [] }
|
|
472
|
-
else if ((e as Error).message?.includes("config corrupt")) throw e
|
|
473
|
-
else if ((e as NodeJS.ErrnoException).code) throw e
|
|
474
|
-
else cfg = { providers: [] }
|
|
475
|
-
}
|
|
474
|
+
return updateConfigAtomic(opts, (cfg) => {
|
|
476
475
|
cfg.mcpServers = (cfg.mcpServers ?? []).filter((m) => m.id !== id)
|
|
477
|
-
await writeConfigAtomic(path, cfg)
|
|
478
476
|
})
|
|
479
477
|
}
|
|
480
478
|
|
|
@@ -487,55 +485,17 @@ export async function saveLspServer(
|
|
|
487
485
|
opts: { global?: boolean; cwd?: string } = {},
|
|
488
486
|
) {
|
|
489
487
|
if (!entry.ext || !entry.command) throw new Error("lsp ext/command required")
|
|
490
|
-
|
|
491
|
-
(opts.global ?? true) ? globalConfigPath() : resolve(opts.cwd ?? process.cwd(), LOCAL)
|
|
492
|
-
return withConfigLock(path, async () => {
|
|
493
|
-
let cfg: MinicodeConfig = { providers: [] }
|
|
494
|
-
let raw = ""
|
|
495
|
-
try {
|
|
496
|
-
raw = await readFile(path, "utf8")
|
|
497
|
-
cfg = normalizeConfig(JSON.parse(raw))
|
|
498
|
-
} catch (e) {
|
|
499
|
-
if (e instanceof SyntaxError) {
|
|
500
|
-
const backup = `${path}.corrupt.${Date.now()}`
|
|
501
|
-
await atomicWriteText(backup, raw).catch(() => {})
|
|
502
|
-
throw new Error(`config corrupt: ${path} — backup to ${backup}: ${e.message}`)
|
|
503
|
-
}
|
|
504
|
-
if ((e as NodeJS.ErrnoException).code === "ENOENT") cfg = { providers: [] }
|
|
505
|
-
else if ((e as Error).message?.includes("config corrupt")) throw e
|
|
506
|
-
else if ((e as NodeJS.ErrnoException).code) throw e
|
|
507
|
-
else cfg = { providers: [] }
|
|
508
|
-
}
|
|
488
|
+
return updateConfigAtomic(opts, (cfg) => {
|
|
509
489
|
cfg.lspServers ??= []
|
|
510
490
|
const ext = normalizeExt(entry.ext)
|
|
511
491
|
const idx = cfg.lspServers.findIndex((l) => l.ext.toLowerCase() === ext)
|
|
512
492
|
if (idx >= 0) cfg.lspServers[idx] = { ...entry, ext }
|
|
513
493
|
else cfg.lspServers.push({ ...entry, ext })
|
|
514
|
-
await writeConfigAtomic(path, cfg)
|
|
515
494
|
})
|
|
516
495
|
}
|
|
517
496
|
|
|
518
497
|
export async function removeLspServer(ext: string, opts: { global?: boolean; cwd?: string } = {}) {
|
|
519
|
-
|
|
520
|
-
(opts.global ?? true) ? globalConfigPath() : resolve(opts.cwd ?? process.cwd(), LOCAL)
|
|
521
|
-
return withConfigLock(path, async () => {
|
|
522
|
-
let cfg: MinicodeConfig = { providers: [] }
|
|
523
|
-
let raw = ""
|
|
524
|
-
try {
|
|
525
|
-
raw = await readFile(path, "utf8")
|
|
526
|
-
cfg = normalizeConfig(JSON.parse(raw))
|
|
527
|
-
} catch (e) {
|
|
528
|
-
if (e instanceof SyntaxError) {
|
|
529
|
-
const backup = `${path}.corrupt.${Date.now()}`
|
|
530
|
-
await atomicWriteText(backup, raw).catch(() => {})
|
|
531
|
-
throw new Error(`config corrupt: ${path} — backup to ${backup}: ${e.message}`)
|
|
532
|
-
}
|
|
533
|
-
if ((e as NodeJS.ErrnoException).code === "ENOENT") cfg = { providers: [] }
|
|
534
|
-
else if ((e as Error).message?.includes("config corrupt")) throw e
|
|
535
|
-
else if ((e as NodeJS.ErrnoException).code) throw e
|
|
536
|
-
else cfg = { providers: [] }
|
|
537
|
-
}
|
|
498
|
+
return updateConfigAtomic(opts, (cfg) => {
|
|
538
499
|
cfg.lspServers = (cfg.lspServers ?? []).filter((l) => l.ext.toLowerCase() !== normalizeExt(ext))
|
|
539
|
-
await writeConfigAtomic(path, cfg)
|
|
540
500
|
})
|
|
541
501
|
}
|
package/src/constants.ts
CHANGED
|
@@ -22,8 +22,10 @@ export const LIMITS = {
|
|
|
22
22
|
/** Batas untuk meminta daemon Docker menghapus container yang timeout/abort. */
|
|
23
23
|
DOCKER_CLEANUP_TIMEOUT_MS: 5_000,
|
|
24
24
|
MCP_OUTPUT_MAX_CHARS: 100_000,
|
|
25
|
-
/** Batas frame JSON-RPC stdio
|
|
25
|
+
/** Batas frame JSON-RPC stdio default (diuji kontrak); koneksi MCP produksi dapat memberi pagu lebih besar untuk screenshot/DOM. */
|
|
26
26
|
MCP_STDIO_FRAME_MAX_BYTES: 1_048_576,
|
|
27
|
+
/** Batas respons mentah MCP (HTTP body & stdio koneksi produksi = 8 MiB) agar screenshot/snapshot browser tidak terpotong atau meng-kill server. */
|
|
28
|
+
MCP_HTTP_BODY_MAX_BYTES: 8_388_608,
|
|
27
29
|
MCP_REQUEST_TIMEOUT_MS: 30_000,
|
|
28
30
|
TASK_SUB_AGENT_MAX_TOKENS: 2_000,
|
|
29
31
|
/** Context & memory */
|
|
@@ -53,10 +55,6 @@ export const LIMITS = {
|
|
|
53
55
|
* angka 0.5 tersebar inline di compaction.ts tanpa nama (magic number). */
|
|
54
56
|
COMPACTION_SUMMARY_TARGET_RATIO: 0.5,
|
|
55
57
|
COMPACTION_LLM_TIMEOUT_MS: 10_000,
|
|
56
|
-
/** Batas atas cadangan output (framing + respons minimum) saat admission
|
|
57
|
-
* request provider: `Math.min(reserve, limit/10)` — cadangan tak naik tanpa
|
|
58
|
-
* batas pada jendela raksasa (1M token tetap cukup 256 untuk framing). */
|
|
59
|
-
CONTEXT_WINDOW_RESERVE_CAP_TOKENS: 256,
|
|
60
58
|
/** BATAS ATAS ambang ukuran konteks (estimasi chars/token lokal) untuk
|
|
61
59
|
* mengklasifikasi 400 `invalid_request` generik sebagai
|
|
62
60
|
* `context_length_exceeded` alih-alih mati fatal. Di bawah ambang ini, 400
|
|
@@ -155,10 +153,26 @@ export const LIMITS = {
|
|
|
155
153
|
SUB_AGENT_TIMEOUT_MS: 120_000,
|
|
156
154
|
/** Network / providers */
|
|
157
155
|
RETRY_AFTER_MAX_MS: 30_000,
|
|
158
|
-
/** F-11:
|
|
159
|
-
* Longgar (5 mnt) karena reasoning stream sah bisa bermenit-menit;
|
|
160
|
-
* turn (default
|
|
156
|
+
/** F-11: batas TOTAL satu request provider (server hung = turn hung tanpa
|
|
157
|
+
* ini). Longgar (5 mnt) karena reasoning stream sah bisa bermenit-menit;
|
|
158
|
+
* timeout turn (default 1 jam) tetap backstop terluar.
|
|
159
|
+
*
|
|
160
|
+
* Catatan audit freeze 2026-11-16: ini BUKAN timeout idle. Provider yang
|
|
161
|
+
* menerima koneksi lalu diam tanpa satu byte pun juga menghabiskan seluruh
|
|
162
|
+
* 5 menit — itulah "macet" yang dikeluhkan. Deteksi diam ditangani
|
|
163
|
+
* `PROVIDER_IDLE_TIMEOUT_MS` di bawah; keduanya dipakai bersama. */
|
|
161
164
|
PROVIDER_REQUEST_TIMEOUT_MS: 300_000,
|
|
165
|
+
/** Batas DIAM (tidak ada byte apa pun dari provider) sebelum request
|
|
166
|
+
* dianggap mati. Timer di-reset setiap ada aktivitas (termasuk frame SSE
|
|
167
|
+
* keep-alive/thinking), jadi stream panjang TIDAK terpotong — hanya
|
|
168
|
+
* koneksi yang benar-benar berhenti bicara.
|
|
169
|
+
*
|
|
170
|
+
* 60 dtk: lebih pendek dari timeout turn mana pun, dan cukup di atas jeda
|
|
171
|
+
* wajar antar-chunk pada provider lambat + reasoning panjang saat pertama
|
|
172
|
+
* token belum keluar. Tanpa ini kegagalan "endpoint hidup tapi bisu"
|
|
173
|
+
* (proxy salah konfigurasi, TLS setengah terbuka, gateway overload) baru
|
|
174
|
+
* terlihat setelah 5 menit — user tak bisa membedakannya dari hang. */
|
|
175
|
+
PROVIDER_IDLE_TIMEOUT_MS: 60_000,
|
|
162
176
|
/** F-16: cap akumulasi teks per stream (anti-OOM); hanya memotong kasus
|
|
163
177
|
* patologis (~250rb token teks dalam satu turn). */
|
|
164
178
|
PROVIDER_TEXT_MAX_CHARS: 1_000_000,
|
|
@@ -179,7 +193,7 @@ export const LIMITS = {
|
|
|
179
193
|
DETECT_MODELS_TIMEOUT_MS: 4_000,
|
|
180
194
|
DETECT_GLOBAL_TIMEOUT_MS: 6_000,
|
|
181
195
|
DETECT_ATTEMPT_TIMEOUT_MS: 2_500,
|
|
182
|
-
MCP_HANDSHAKE_TIMEOUT_MS:
|
|
196
|
+
MCP_HANDSHAKE_TIMEOUT_MS: 15_000,
|
|
183
197
|
/** OAuth device flow: request pendek, tapi poll bisa berlangsung menit. */
|
|
184
198
|
OAUTH_REQUEST_TIMEOUT_MS: 15_000,
|
|
185
199
|
/** Pricing dari models.dev — cache agar tidak menembak jaringan tiap run. */
|
package/src/daemon/capability.ts
CHANGED
|
@@ -107,7 +107,14 @@ export function verifyCapability(
|
|
|
107
107
|
} catch {
|
|
108
108
|
return { ok: false, reason: "MALFORMED" }
|
|
109
109
|
}
|
|
110
|
-
if (
|
|
110
|
+
if (
|
|
111
|
+
payload?.v !== 1 ||
|
|
112
|
+
!Array.isArray(payload.scopes) ||
|
|
113
|
+
typeof payload.n !== "string" ||
|
|
114
|
+
payload.n.length === 0 ||
|
|
115
|
+
typeof payload.who !== "string"
|
|
116
|
+
)
|
|
117
|
+
return { ok: false, reason: "MALFORMED" }
|
|
111
118
|
if (payload.inc !== opts.incarnation) return { ok: false, reason: "STALE_INCARNATION" }
|
|
112
119
|
const now = opts.now ?? Date.now()
|
|
113
120
|
if (typeof payload.exp !== "number" || payload.exp <= now) return { ok: false, reason: "EXPIRED" }
|
package/src/daemon/control.ts
CHANGED
|
@@ -22,7 +22,7 @@ export interface HostedSessionInfo {
|
|
|
22
22
|
runStatus: string | null
|
|
23
23
|
presentationHead: number
|
|
24
24
|
/** P0.2 (Q5): WorkMode efektif sesi yang di-host (bila diketahui host). */
|
|
25
|
-
workMode?: "DISCUSS" | "
|
|
25
|
+
workMode?: "DISCUSS" | "BUILD"
|
|
26
26
|
/**
|
|
27
27
|
* P2.3: hasil recovery run terakhir yang durable (mis. UNKNOWN setelah
|
|
28
28
|
* restart). Operator dapat membedakan LIVE vs reconstructed/interrupted
|
|
@@ -273,6 +273,7 @@ function runOp(op: ControlOp, req: ControlRequest, deps: ControlDeps): ControlOu
|
|
|
273
273
|
}
|
|
274
274
|
|
|
275
275
|
case "approval.decide": {
|
|
276
|
+
if (!sid) return refuse("SESSION_MISMATCH", "args.sid wajib diisi")
|
|
276
277
|
const approvalId = typeof args.approvalId === "string" ? args.approvalId : ""
|
|
277
278
|
const decisionRaw = typeof args.decision === "string" ? args.decision : ""
|
|
278
279
|
if (!approvalId) return refuse("SESSION_MISMATCH", "args.approvalId wajib diisi")
|
|
@@ -282,7 +283,7 @@ function runOp(op: ControlOp, req: ControlRequest, deps: ControlDeps): ControlOu
|
|
|
282
283
|
// [RC-2] Cek kepemilikan session SEBELUM mutasi DB: baca baris tanpa menulis,
|
|
283
284
|
// tolak mismatch SESSION_MISMATCH tanpa membangunkan waiter/mengubah state.
|
|
284
285
|
const existing = deps.approvals.read(approvalId)
|
|
285
|
-
if (
|
|
286
|
+
if (existing && existing.sid !== sid) {
|
|
286
287
|
// Approval milik sesi lain: menolaknya menggagalkan keputusan yang
|
|
287
288
|
// sebenarnya valid, jadi jangan — laporkan kecocokan yang salah saja.
|
|
288
289
|
return refuse("SESSION_MISMATCH", "approval bukan milik sesi yang disebut", {
|
package/src/daemon/server.ts
CHANGED
|
@@ -72,6 +72,10 @@ export interface DaemonServerDeps {
|
|
|
72
72
|
maxQueuePerSubscription?: number
|
|
73
73
|
/** Seam uji: batas antrean per identitas konsumen logis (lihat host). */
|
|
74
74
|
maxQueuePerConsumer?: (consumerId: string) => number | undefined
|
|
75
|
+
/** Batas koneksi pra-handshake bersamaan (anti-slowloris). Default 32. */
|
|
76
|
+
maxPendingHandshakes?: number
|
|
77
|
+
/** Batas waktu menunggu `hello` setelah TCP tersambung. Default 5000 ms. */
|
|
78
|
+
preAuthTimeoutMs?: number
|
|
75
79
|
/** Dipanggil saat daemon menerima koneksi (diagnostik). */
|
|
76
80
|
onConnection?: (info: { remote: string; consumer: string }) => void
|
|
77
81
|
}
|
|
@@ -81,6 +85,7 @@ interface Conn {
|
|
|
81
85
|
socket: Socket
|
|
82
86
|
decoder: FrameDecoder
|
|
83
87
|
state: "new" | "ready"
|
|
88
|
+
authTimer: ReturnType<typeof setTimeout> | null
|
|
84
89
|
/**
|
|
85
90
|
* Identitas logis (dari capability `who`) untuk offset durable, idempotensi,
|
|
86
91
|
* dan label wire. Stabil lintas reconnect.
|
|
@@ -106,12 +111,15 @@ let connSeq = 0
|
|
|
106
111
|
// kendali). Scope live = identitas logis + id koneksi, sehingga dua koneksi
|
|
107
112
|
// konsumen yang sama tidak pernah berbagi kunci langganan.
|
|
108
113
|
const CONSUMER_SCOPE_SEP = String.fromCharCode(1)
|
|
114
|
+
const DEFAULT_MAX_PENDING_HANDSHAKES = 32
|
|
115
|
+
const DEFAULT_PRE_AUTH_TIMEOUT_MS = 5_000
|
|
109
116
|
|
|
110
117
|
export class DaemonServer {
|
|
111
118
|
readonly #deps: DaemonServerDeps
|
|
112
119
|
readonly #subs: SubscriptionRegistry
|
|
113
120
|
readonly #conns = new Map<number, Conn>()
|
|
114
121
|
readonly #liveUnsub = new Map<string, () => void>()
|
|
122
|
+
readonly #revokedNonces = new Map<string, number>()
|
|
115
123
|
#server: Server | null = null
|
|
116
124
|
#port = 0
|
|
117
125
|
#closing = false
|
|
@@ -154,12 +162,26 @@ export class DaemonServer {
|
|
|
154
162
|
}
|
|
155
163
|
|
|
156
164
|
#onConnection(socket: Socket): void {
|
|
165
|
+
const maxPending = this.#deps.maxPendingHandshakes ?? DEFAULT_MAX_PENDING_HANDSHAKES
|
|
166
|
+
let pendingCount = 0
|
|
167
|
+
for (const c of this.#conns.values()) {
|
|
168
|
+
if (!c.closed && c.state === "new") pendingCount++
|
|
169
|
+
}
|
|
170
|
+
if (pendingCount >= maxPending) {
|
|
171
|
+
this.#deps.telemetry.inc("connections.rejected")
|
|
172
|
+
try {
|
|
173
|
+
socket.destroy()
|
|
174
|
+
} catch {}
|
|
175
|
+
return
|
|
176
|
+
}
|
|
157
177
|
this.#deps.telemetry.inc("connections.opened")
|
|
178
|
+
const preAuthMs = this.#deps.preAuthTimeoutMs ?? DEFAULT_PRE_AUTH_TIMEOUT_MS
|
|
158
179
|
const conn: Conn = {
|
|
159
180
|
id: ++connSeq,
|
|
160
181
|
socket,
|
|
161
182
|
decoder: new FrameDecoder(),
|
|
162
183
|
state: "new",
|
|
184
|
+
authTimer: null,
|
|
163
185
|
consumerId: null,
|
|
164
186
|
subscriptionScope: null,
|
|
165
187
|
scopes: [],
|
|
@@ -167,6 +189,13 @@ export class DaemonServer {
|
|
|
167
189
|
paused: false,
|
|
168
190
|
closed: false,
|
|
169
191
|
}
|
|
192
|
+
conn.authTimer = setTimeout(() => {
|
|
193
|
+
if (conn.closed || conn.state !== "new") return
|
|
194
|
+
this.#deps.telemetry.inc("connections.rejected")
|
|
195
|
+
this.#sendError(conn, "PROTOCOL_ERROR", "timeout menunggu handshake hello")
|
|
196
|
+
this.#halt(conn, "PROTOCOL_ERROR")
|
|
197
|
+
}, preAuthMs)
|
|
198
|
+
conn.authTimer.unref?.()
|
|
170
199
|
this.#conns.set(conn.id, conn)
|
|
171
200
|
|
|
172
201
|
socket.on("data", (chunk: Buffer) => {
|
|
@@ -197,6 +226,10 @@ export class DaemonServer {
|
|
|
197
226
|
#teardown(conn: Conn): void {
|
|
198
227
|
if (conn.closed) return
|
|
199
228
|
conn.closed = true
|
|
229
|
+
if (conn.authTimer) {
|
|
230
|
+
clearTimeout(conn.authTimer)
|
|
231
|
+
conn.authTimer = null
|
|
232
|
+
}
|
|
200
233
|
this.#deps.telemetry.inc("connections.closed")
|
|
201
234
|
// Tutup HANYA langganan milik koneksi ini. Memakai consumerId logis di sini
|
|
202
235
|
// akan ikut memutus koneksi lain yang memakai identitas konsumen sama.
|
|
@@ -330,6 +363,17 @@ export class DaemonServer {
|
|
|
330
363
|
return
|
|
331
364
|
}
|
|
332
365
|
const payload: CapabilityPayload = check.payload
|
|
366
|
+
this.#pruneRevoked(Date.now())
|
|
367
|
+
if (this.#revokedNonces.has(payload.n)) {
|
|
368
|
+
this.#deps.telemetry.inc("connections.rejected")
|
|
369
|
+
this.#sendError(conn, "INVALID_CAPABILITY", "capability telah dicabut")
|
|
370
|
+
this.#teardown(conn)
|
|
371
|
+
return
|
|
372
|
+
}
|
|
373
|
+
if (conn.authTimer) {
|
|
374
|
+
clearTimeout(conn.authTimer)
|
|
375
|
+
conn.authTimer = null
|
|
376
|
+
}
|
|
333
377
|
conn.state = "ready"
|
|
334
378
|
conn.scopes = payload.scopes
|
|
335
379
|
conn.consumerId = sanitizeLabel(payload.who, 120) || `consumer-${conn.id}`
|
|
@@ -653,6 +697,19 @@ export class DaemonServer {
|
|
|
653
697
|
})
|
|
654
698
|
}
|
|
655
699
|
|
|
700
|
+
/** Cabut nonce capability yang bocor sebelum masa berlaku `exp` habis. */
|
|
701
|
+
revokeCapabilityNonce(nonce: string, expMs = Date.now() + 24 * 60 * 60 * 1000): void {
|
|
702
|
+
if (!nonce) return
|
|
703
|
+
this.#pruneRevoked(Date.now())
|
|
704
|
+
this.#revokedNonces.set(nonce, expMs)
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
#pruneRevoked(now: number): void {
|
|
708
|
+
for (const [n, exp] of this.#revokedNonces) {
|
|
709
|
+
if (exp <= now) this.#revokedNonces.delete(n)
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
|
|
656
713
|
get startedAt(): number {
|
|
657
714
|
return this.#startedAt
|
|
658
715
|
}
|
package/src/hooks/run.ts
CHANGED
|
@@ -2,6 +2,8 @@ import { spawn } from "node:child_process"
|
|
|
2
2
|
import { existsSync, readdirSync } from "node:fs"
|
|
3
3
|
import { homedir } from "node:os"
|
|
4
4
|
import { join, resolve } from "node:path"
|
|
5
|
+
import { killProcessTree, signalProcessGroupGraceful } from "../lib/process-tree.ts"
|
|
6
|
+
import { isRealPathOutsideRoot } from "../policy/jail.ts"
|
|
5
7
|
import { sanitizeSpawnEnv } from "../policy/scrub.ts"
|
|
6
8
|
|
|
7
9
|
export interface RunHookCtx {
|
|
@@ -11,6 +13,11 @@ export interface RunHookCtx {
|
|
|
11
13
|
result?: unknown
|
|
12
14
|
}
|
|
13
15
|
|
|
16
|
+
export interface RunHooksOptions {
|
|
17
|
+
/** Izinkan hook lokal `<cwd>/.minicode/hooks` (hanya bila `--allow-local-config`). */
|
|
18
|
+
allowLocal?: boolean
|
|
19
|
+
}
|
|
20
|
+
|
|
14
21
|
/**
|
|
15
22
|
* Guard mode untuk hooks (audit #10 P1): hooks berjalan di luar permission
|
|
16
23
|
* system — di mode tanpa-eksekusi (plan/readonly) hook TETAP mengeksekusi
|
|
@@ -23,32 +30,44 @@ export interface RunHookCtx {
|
|
|
23
30
|
* tulis/eksekusi). Pemanggil legacy tanpa workMode memakai keputusan murni
|
|
24
31
|
* permission mode (default undefined = perilaku lama).
|
|
25
32
|
*/
|
|
26
|
-
export function shouldRunHooks(
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
)
|
|
30
|
-
// P0.2 (Q3): hooks berjalan di luar permission system dengan akses penuh
|
|
31
|
-
// Node.js/filesystem/jaringan, sehingga DILARANG di DISCUSS maupun PLAN
|
|
32
|
-
// untuk seluruh PermissionMode. Hanya WorkMode EXECUTE (atau pemanggil
|
|
33
|
-
// legacy tanpa argumen workMode) yang boleh menjalankan hooks.
|
|
33
|
+
export function shouldRunHooks(permissionMode: string, workMode?: "DISCUSS" | "EXECUTE"): boolean {
|
|
34
|
+
// Hooks berjalan di luar permission system dengan akses penuh Node.js/FS/jaringan,
|
|
35
|
+
// sehingga DILARANG di DISCUSS untuk seluruh PermissionMode. Hanya WorkMode EXECUTE
|
|
36
|
+
// (atau pemanggil legacy tanpa argumen workMode) yang boleh menjalankan hooks.
|
|
34
37
|
if (workMode !== undefined && workMode !== "EXECUTE") return false
|
|
35
38
|
return permissionMode !== "plan" && permissionMode !== "readonly"
|
|
36
39
|
}
|
|
37
40
|
|
|
38
|
-
// 6.4 — hooks global opt-in: ~/.minicode/hooks/{pre,post}*.js dan
|
|
39
|
-
// .minicode/hooks/{pre,post}*.js
|
|
40
|
-
//
|
|
41
|
-
//
|
|
42
|
-
export function findRunHooks(
|
|
43
|
-
|
|
44
|
-
|
|
41
|
+
// 6.4 — hooks global opt-in: ~/.minicode/hooks/{pre,post}*.js, dan lokal
|
|
42
|
+
// .minicode/hooks/{pre,post}*.js (fail-closed: lokal butuh allowLocal=true
|
|
43
|
+
// agar menyalakan MINICODE_HOOKS=1 global tak mengeksekusi JS repo asing).
|
|
44
|
+
// Berjalan sebagai node script terpisah dengan konteks di env MINICODE_HOOK_CTX.
|
|
45
|
+
export function findRunHooks(
|
|
46
|
+
cwd?: string,
|
|
47
|
+
opts: RunHooksOptions = {},
|
|
48
|
+
): { pre: string[]; post: string[] } {
|
|
49
|
+
const dirs: { dir: string; jail: boolean }[] = [
|
|
50
|
+
{ dir: join(homedir(), ".minicode", "hooks"), jail: false },
|
|
51
|
+
]
|
|
52
|
+
if (cwd && opts.allowLocal === true) {
|
|
53
|
+
dirs.push({ dir: resolve(cwd, ".minicode", "hooks"), jail: true })
|
|
54
|
+
}
|
|
45
55
|
const out = { pre: [] as string[], post: [] as string[] }
|
|
46
|
-
for (const dir of dirs) {
|
|
56
|
+
for (const { dir, jail } of dirs) {
|
|
47
57
|
if (!existsSync(dir)) continue
|
|
48
|
-
|
|
58
|
+
let entries: string[]
|
|
59
|
+
try {
|
|
60
|
+
entries = readdirSync(dir)
|
|
61
|
+
} catch {
|
|
62
|
+
continue
|
|
63
|
+
}
|
|
64
|
+
for (const f of entries) {
|
|
49
65
|
if (!f.endsWith(".js")) continue
|
|
50
|
-
|
|
51
|
-
|
|
66
|
+
const full = join(dir, f)
|
|
67
|
+
// Symlink di dalam .minicode/hooks tak boleh lolos keluar direktori hook.
|
|
68
|
+
if (jail && isRealPathOutsideRoot(full, dir)) continue
|
|
69
|
+
if (f.startsWith("pre")) out.pre.push(full)
|
|
70
|
+
else if (f.startsWith("post")) out.post.push(full)
|
|
52
71
|
}
|
|
53
72
|
}
|
|
54
73
|
return out
|
|
@@ -58,15 +77,15 @@ export async function runRunHooks(
|
|
|
58
77
|
phase: "pre" | "post",
|
|
59
78
|
ctx: RunHookCtx,
|
|
60
79
|
signal?: AbortSignal,
|
|
80
|
+
opts: RunHooksOptions = {},
|
|
61
81
|
): Promise<void> {
|
|
62
82
|
if (process.env.MINICODE_HOOKS !== "1") return
|
|
63
|
-
// Hook = arbitrary Node.js di luar permission system (berjalan di
|
|
64
|
-
//
|
|
65
|
-
// perlu),
|
|
66
|
-
// MINICODE_HOOK_CTX sendiri memuat prompt user apa adanya — prompt yang
|
|
67
|
-
// ditempeli kredensial akan terlihat hook; itu inheren dari desain.
|
|
83
|
+
// Hook = arbitrary Node.js di luar permission system (berjalan di EXECUTE
|
|
84
|
+
// bila opt-in) — karenanya: tanpa secret di env (baca dari berkas bila
|
|
85
|
+
// perlu), hormati pembatalan sesi secara instan, dan tree-kill saat timeout.
|
|
68
86
|
if (signal?.aborted) return
|
|
69
|
-
const hooks = findRunHooks(ctx.cwd)
|
|
87
|
+
const hooks = findRunHooks(ctx.cwd, opts)
|
|
88
|
+
const baseKillEnv = sanitizeSpawnEnv(process.env)
|
|
70
89
|
for (const file of hooks[phase]) {
|
|
71
90
|
if (signal?.aborted) return
|
|
72
91
|
// Audit #10 P2 observability: hook adalah eksekusi di luar permission
|
|
@@ -79,25 +98,38 @@ export async function runRunHooks(
|
|
|
79
98
|
const p = spawn(process.execPath, [file], {
|
|
80
99
|
env: sanitizeSpawnEnv(process.env, { MINICODE_HOOK_CTX: JSON.stringify(ctx) }),
|
|
81
100
|
stdio: "ignore",
|
|
101
|
+
detached: process.platform !== "win32",
|
|
82
102
|
})
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
p.kill("SIGKILL")
|
|
89
|
-
} catch {}
|
|
90
|
-
}, 1000)
|
|
91
|
-
} catch {}
|
|
92
|
-
}, 5000)
|
|
93
|
-
p.on("error", () => {
|
|
103
|
+
let settled = false
|
|
104
|
+
let killTimer: ReturnType<typeof setTimeout> | undefined
|
|
105
|
+
const cleanup = (): void => {
|
|
106
|
+
if (settled) return
|
|
107
|
+
settled = true
|
|
94
108
|
clearTimeout(timer)
|
|
109
|
+
if (killTimer) clearTimeout(killTimer)
|
|
110
|
+
signal?.removeEventListener("abort", onAbort)
|
|
95
111
|
res()
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
112
|
+
}
|
|
113
|
+
const terminateHook = (): void => {
|
|
114
|
+
if (settled) return
|
|
115
|
+
if (process.platform === "win32") {
|
|
116
|
+
killProcessTree(p, { env: baseKillEnv })
|
|
117
|
+
return
|
|
118
|
+
}
|
|
119
|
+
signalProcessGroupGraceful(p.pid, p)
|
|
120
|
+
killTimer = setTimeout(() => {
|
|
121
|
+
killProcessTree(p, { env: baseKillEnv })
|
|
122
|
+
}, 1000)
|
|
123
|
+
killTimer.unref?.()
|
|
124
|
+
}
|
|
125
|
+
const onAbort = (): void => {
|
|
126
|
+
killProcessTree(p, { env: baseKillEnv })
|
|
127
|
+
}
|
|
128
|
+
const timer = setTimeout(terminateHook, 5000)
|
|
129
|
+
signal?.addEventListener("abort", onAbort, { once: true })
|
|
130
|
+
if (signal?.aborted) onAbort()
|
|
131
|
+
p.on("error", cleanup)
|
|
132
|
+
p.on("close", cleanup)
|
|
101
133
|
})
|
|
102
134
|
}
|
|
103
135
|
}
|