minicode-ai 0.9.26
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/CHANGELOG.md +935 -0
- package/LICENSE +21 -0
- package/README.md +200 -0
- package/cli/args.ts +195 -0
- package/cli/auto-update.ts +108 -0
- package/cli/commands/auth.ts +166 -0
- package/cli/commands/config.ts +382 -0
- package/cli/commands/doctor.ts +128 -0
- package/cli/commands/exec.ts +179 -0
- package/cli/commands/mcp.ts +35 -0
- package/cli/commands/memory.ts +107 -0
- package/cli/commands/pricing.ts +100 -0
- package/cli/commands/providers.ts +162 -0
- package/cli/commands/sessions.ts +128 -0
- package/cli/commands/skills.ts +61 -0
- package/cli/commands/stats.ts +82 -0
- package/cli/commands.ts +317 -0
- package/cli/index.ts +539 -0
- package/cli/model-manager.ts +112 -0
- package/cli/provider-manager.ts +111 -0
- package/cli/repl.ts +734 -0
- package/cli/router.ts +124 -0
- package/cli/setup.ts +780 -0
- package/cli/wizard.ts +21 -0
- package/docs/ARCHITECTURE.html +1222 -0
- package/docs/README.md +109 -0
- package/docs/architecture.md +44 -0
- package/docs/changelog.md +3 -0
- package/package.json +91 -0
- package/src/agents/pool.ts +43 -0
- package/src/app/mentions.ts +50 -0
- package/src/app/provider-layer.ts +118 -0
- package/src/app/rag-layer.ts +105 -0
- package/src/app/session.ts +154 -0
- package/src/app/tool-layer.ts +56 -0
- package/src/config.ts +372 -0
- package/src/constants.ts +119 -0
- package/src/hooks/run.ts +89 -0
- package/src/lib/atomic-write.ts +88 -0
- package/src/lib/db-path.ts +36 -0
- package/src/lib/git-hardening.ts +91 -0
- package/src/lib/ignore.ts +58 -0
- package/src/lib/keystore.ts +202 -0
- package/src/lib/net.ts +70 -0
- package/src/lib/safe-open.ts +138 -0
- package/src/lib/session-id.ts +23 -0
- package/src/lib/trash.ts +38 -0
- package/src/lib/trusted-exec.ts +81 -0
- package/src/lsp/client.ts +395 -0
- package/src/mcp/client.ts +400 -0
- package/src/mcp/http-transport.ts +344 -0
- package/src/mcp/server.ts +538 -0
- package/src/mcp/transport.ts +150 -0
- package/src/memory/files.ts +159 -0
- package/src/memory/vector.ts +775 -0
- package/src/policy/allowlist.ts +67 -0
- package/src/policy/bash-guard.ts +465 -0
- package/src/policy/compaction.ts +271 -0
- package/src/policy/context.ts +161 -0
- package/src/policy/executor.ts +199 -0
- package/src/policy/jail.ts +127 -0
- package/src/policy/permission.ts +517 -0
- package/src/policy/pricing.ts +336 -0
- package/src/policy/ratelimit.ts +54 -0
- package/src/policy/sandbox-policy.ts +157 -0
- package/src/policy/scrub.ts +138 -0
- package/src/policy/update-check.ts +200 -0
- package/src/policy/usage.ts +292 -0
- package/src/policy/verifier.ts +181 -0
- package/src/providers/anthropic.ts +401 -0
- package/src/providers/auth-store.ts +139 -0
- package/src/providers/build.ts +136 -0
- package/src/providers/detect.ts +126 -0
- package/src/providers/effort.ts +165 -0
- package/src/providers/guards.ts +107 -0
- package/src/providers/oauth.ts +326 -0
- package/src/providers/presets.ts +122 -0
- package/src/providers/provision.ts +298 -0
- package/src/providers/responses.ts +371 -0
- package/src/providers/router.ts +247 -0
- package/src/repo/repomap.ts +470 -0
- package/src/sandbox/docker.ts +129 -0
- package/src/sandbox/os.ts +193 -0
- package/src/session/checkpoint.ts +543 -0
- package/src/session/journal.ts +1347 -0
- package/src/session/persistence.ts +446 -0
- package/src/session/shadow-git.ts +351 -0
- package/src/session/turn-marker.ts +118 -0
- package/src/skills/loader.ts +117 -0
- package/src/telemetry/trace.ts +283 -0
- package/src/tools/ask_user.ts +54 -0
- package/src/tools/bash.ts +400 -0
- package/src/tools/code_run.ts +96 -0
- package/src/tools/delete_file.ts +31 -0
- package/src/tools/edit.ts +204 -0
- package/src/tools/git.ts +301 -0
- package/src/tools/glob.ts +90 -0
- package/src/tools/grep.ts +281 -0
- package/src/tools/hashline.ts +66 -0
- package/src/tools/index.ts +103 -0
- package/src/tools/lsp.ts +346 -0
- package/src/tools/mcp_call.ts +163 -0
- package/src/tools/memory.ts +144 -0
- package/src/tools/move_file.ts +47 -0
- package/src/tools/patch.ts +86 -0
- package/src/tools/read_file.ts +130 -0
- package/src/tools/read_image.ts +80 -0
- package/src/tools/submit_result.ts +49 -0
- package/src/tools/task.ts +346 -0
- package/src/tools/todo.ts +201 -0
- package/src/tools/web_fetch.ts +161 -0
- package/src/tools/web_search.ts +156 -0
- package/src/tools/write_file.ts +42 -0
- package/src/ui/approval/prompt.ts +76 -0
- package/src/ui/assistant/simple.ts +568 -0
- package/src/ui/assistant/turn-status.ts +303 -0
- package/src/ui/contract.ts +55 -0
- package/src/ui/footer.ts +105 -0
- package/src/ui/input/input.ts +805 -0
- package/src/ui/input/prompt-engine.ts +606 -0
- package/src/ui/render/collapse.ts +84 -0
- package/src/ui/render/detail.ts +24 -0
- package/src/ui/render/diff.ts +181 -0
- package/src/ui/render/errors.ts +239 -0
- package/src/ui/render/format.ts +54 -0
- package/src/ui/render/highlight.ts +294 -0
- package/src/ui/render/markdown.ts +120 -0
- package/src/ui/render/money.ts +12 -0
- package/src/ui/render/reasoning.ts +20 -0
- package/src/ui/render/sanitize.ts +80 -0
- package/src/ui/render/table.ts +88 -0
- package/src/ui/render/theme.ts +339 -0
- package/src/ui/render/width.ts +256 -0
- package/src/ui/render/wrap.ts +120 -0
- package/src/ui/runtime/bus-debug.ts +83 -0
- package/src/ui/runtime/chrome.ts +301 -0
- package/src/ui/runtime/spinner.ts +77 -0
- package/src/ui/runtime/statusline.ts +227 -0
- package/src/ui/screens/model-manager.ts +434 -0
- package/src/ui/screens/overlay.ts +61 -0
- package/src/ui/screens/picker.ts +307 -0
- package/src/ui/screens/provider-manager.ts +450 -0
- package/src/ui/screens/wizard.ts +132 -0
- package/vendor/minicore/VENDOR.md +29 -0
- package/vendor/minicore/package.json +21 -0
- package/vendor/minicore/src/core/budget.ts +26 -0
- package/vendor/minicore/src/core/compact.ts +76 -0
- package/vendor/minicore/src/core/errors.ts +60 -0
- package/vendor/minicore/src/core/events.ts +74 -0
- package/vendor/minicore/src/core/executor.ts +139 -0
- package/vendor/minicore/src/core/history.ts +32 -0
- package/vendor/minicore/src/core/index.ts +42 -0
- package/vendor/minicore/src/core/loop.ts +344 -0
- package/vendor/minicore/src/core/permission.ts +24 -0
- package/vendor/minicore/src/core/provider.ts +39 -0
- package/vendor/minicore/src/core/recovery.ts +34 -0
- package/vendor/minicore/src/core/session.ts +327 -0
- package/vendor/minicore/src/core/snapshot.ts +142 -0
- package/vendor/minicore/src/core/tokens.ts +111 -0
- package/vendor/minicore/src/core/tool.ts +118 -0
- package/vendor/minicore/src/core/types.ts +50 -0
- package/vendor/minicore/src/providers/openai-compat.ts +366 -0
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import type { RecoveryAction } from "#minicore/core/errors.ts"
|
|
2
|
+
import { ProviderError } from "#minicore/core/errors.ts"
|
|
3
|
+
import type { Session, SessionConfig } from "#minicore/core/index.ts"
|
|
4
|
+
import { createSession as createCoreSession } from "#minicore/core/index.ts"
|
|
5
|
+
import { defaultRecoveryPolicy } from "#minicore/core/recovery.ts"
|
|
6
|
+
import { LIMITS } from "../constants.ts"
|
|
7
|
+
import { buildSystemPrompt, minicodeEstimator } from "../policy/context.ts"
|
|
8
|
+
import { parallelExecutor } from "../policy/executor.ts"
|
|
9
|
+
import {
|
|
10
|
+
createPermissionHandler,
|
|
11
|
+
type PermissionAsk,
|
|
12
|
+
type PermissionMode,
|
|
13
|
+
} from "../policy/permission.ts"
|
|
14
|
+
|
|
15
|
+
// P2 cap wrapper: limit retryAfter to 30s without mutating original error.
|
|
16
|
+
// F-12: sanitasi PENUH di satu titik sentral (mencakup adapter vendor yang
|
|
17
|
+
// tak boleh disentuh): non-finite (Infinity/NaN) atau negatif → buang
|
|
18
|
+
// (pakai backoff kernel); sangat besar → cap. Tanpa ini retryAfter=Infinity
|
|
19
|
+
// menjadi setTimeout(Infinity) ≈ 1ms → hot fast-retry, bukan tunggu lama.
|
|
20
|
+
// Diekspor agar teruji langsung (pola repo: pure/diekspor-untuk-test).
|
|
21
|
+
export const cappedRecovery = {
|
|
22
|
+
onError(error: ProviderError, attempt: number): RecoveryAction {
|
|
23
|
+
const ra = error.retryAfterMs
|
|
24
|
+
if (ra != null && (!Number.isFinite(ra) || ra < 0)) {
|
|
25
|
+
const clean = new ProviderError(error.category, error.message, undefined)
|
|
26
|
+
Object.assign(clean, { cause: (error as unknown as { cause?: unknown }).cause })
|
|
27
|
+
return defaultRecoveryPolicy.onError(clean, attempt)
|
|
28
|
+
}
|
|
29
|
+
if (ra != null && ra > LIMITS.RETRY_AFTER_MAX_MS) {
|
|
30
|
+
const capped = new ProviderError(error.category, error.message, LIMITS.RETRY_AFTER_MAX_MS)
|
|
31
|
+
// preserve extra fields if any
|
|
32
|
+
Object.assign(capped, { cause: (error as unknown as { cause?: unknown }).cause })
|
|
33
|
+
return defaultRecoveryPolicy.onError(capped, attempt)
|
|
34
|
+
}
|
|
35
|
+
return defaultRecoveryPolicy.onError(error, attempt)
|
|
36
|
+
},
|
|
37
|
+
onLength(compacted: boolean): RecoveryAction {
|
|
38
|
+
return defaultRecoveryPolicy.onLength(compacted)
|
|
39
|
+
},
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export type PermissionControl = {
|
|
43
|
+
setMode(m: "auto" | "readonly" | "plan" | "allow-all" | "ask" | "allowlist"): void
|
|
44
|
+
getMode(): "auto" | "readonly" | "plan" | "allow-all" | "ask" | "allowlist"
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function createMinicodeSession(
|
|
48
|
+
opts: Partial<
|
|
49
|
+
Omit<SessionConfig, "permissions" | "estimator" | "recovery" | "system" | "executor">
|
|
50
|
+
> & {
|
|
51
|
+
systemExtra?: string
|
|
52
|
+
cwd?: string
|
|
53
|
+
permissionMode?: "auto" | "readonly" | "plan" | "allow-all" | "ask" | "allowlist"
|
|
54
|
+
/** Teruskan flag --allow-local-config ke permission handler (allowlist
|
|
55
|
+
* lokal). Default deny — lihat loadAllowlist. */
|
|
56
|
+
allowLocalConfig?: boolean
|
|
57
|
+
concurrency?: number
|
|
58
|
+
writeConcurrency?: number
|
|
59
|
+
turnCount?: number
|
|
60
|
+
stepCount?: number
|
|
61
|
+
/** Menerima handle kontrol mode permission. Kernel tidak mengekspos
|
|
62
|
+
* `config`, jadi satu-satunya cara mengubah mode saat runtime (mis.
|
|
63
|
+
* Shift+Tab di TUI) adalah menangkap handler di sini. */
|
|
64
|
+
onPermissions?: (control: PermissionControl) => void
|
|
65
|
+
/** View persetujuan tool (di-inject dari cli/; tanpa ini mode interaktif
|
|
66
|
+
* menolak semua prompt — aman untuk headless/library). */
|
|
67
|
+
ask?: PermissionAsk
|
|
68
|
+
},
|
|
69
|
+
): Promise<Session> {
|
|
70
|
+
const planHint =
|
|
71
|
+
opts.permissionMode === "plan"
|
|
72
|
+
? "\n\nPLAN MODE: You are in read-only planning mode. Do NOT modify files, run bash, or use write/edit tools. Only read, search, and reason — then output a concrete implementation plan."
|
|
73
|
+
: ""
|
|
74
|
+
const system = await buildSystemPrompt({
|
|
75
|
+
cwd: opts.cwd,
|
|
76
|
+
extra: (opts.systemExtra ?? "") + planHint,
|
|
77
|
+
signal: (opts as unknown as { signal?: AbortSignal }).signal,
|
|
78
|
+
})
|
|
79
|
+
const {
|
|
80
|
+
concurrency,
|
|
81
|
+
writeConcurrency,
|
|
82
|
+
cwd,
|
|
83
|
+
permissionMode,
|
|
84
|
+
allowLocalConfig,
|
|
85
|
+
systemExtra: _extra,
|
|
86
|
+
provider,
|
|
87
|
+
onPermissions,
|
|
88
|
+
ask,
|
|
89
|
+
turnCount,
|
|
90
|
+
stepCount,
|
|
91
|
+
...rest
|
|
92
|
+
} = opts
|
|
93
|
+
if (!provider) throw new Error("createMinicodeSession: provider is required")
|
|
94
|
+
// F-09: sanitasi batas di lapisan app (mencakup pemanggil library langsung,
|
|
95
|
+
// bukan hanya CLI yang sudah sanitasi di cli/setup.ts + cli/index.ts).
|
|
96
|
+
// Tanpa ini: timeoutMs NaN/negatif = abort instan; maxSteps 0/negatif =
|
|
97
|
+
// selalu throw, Infinity = loop luar tak terbatas; concurrency 0 = zero
|
|
98
|
+
// worker → hasil undefined (korupsi diam-diam). Nilai tak valid → default
|
|
99
|
+
// kernel (hilangkan kunci), bukan error — sesi tetap jalan aman.
|
|
100
|
+
{
|
|
101
|
+
const t = (rest as Record<string, unknown>).timeoutMs
|
|
102
|
+
if (typeof t === "number" && (!Number.isFinite(t) || t < 0))
|
|
103
|
+
delete (rest as Record<string, unknown>).timeoutMs
|
|
104
|
+
const m = (rest as Record<string, unknown>).maxSteps
|
|
105
|
+
if (typeof m !== "number" || !Number.isFinite(m) || m < 1)
|
|
106
|
+
delete (rest as Record<string, unknown>).maxSteps
|
|
107
|
+
else (rest as Record<string, unknown>).maxSteps = Math.floor(m)
|
|
108
|
+
}
|
|
109
|
+
const safeConcurrency =
|
|
110
|
+
typeof concurrency === "number" && Number.isFinite(concurrency) && concurrency > 0
|
|
111
|
+
? Math.floor(concurrency)
|
|
112
|
+
: undefined
|
|
113
|
+
const safeWriteConcurrency =
|
|
114
|
+
typeof writeConcurrency === "number" &&
|
|
115
|
+
Number.isFinite(writeConcurrency) &&
|
|
116
|
+
writeConcurrency > 0
|
|
117
|
+
? Math.floor(writeConcurrency)
|
|
118
|
+
: undefined
|
|
119
|
+
const permissions = createPermissionHandler({
|
|
120
|
+
mode: permissionMode ?? "auto",
|
|
121
|
+
root: cwd,
|
|
122
|
+
ask,
|
|
123
|
+
allowLocalConfig,
|
|
124
|
+
})
|
|
125
|
+
const withMode = permissions as typeof permissions & {
|
|
126
|
+
__setMode(m: PermissionMode): void
|
|
127
|
+
__getMode(): PermissionMode
|
|
128
|
+
}
|
|
129
|
+
if (onPermissions) {
|
|
130
|
+
onPermissions({
|
|
131
|
+
setMode: (m) => withMode.__setMode(m),
|
|
132
|
+
getMode: () => withMode.__getMode(),
|
|
133
|
+
})
|
|
134
|
+
}
|
|
135
|
+
// Teruskan mode live ke kernel agar ToolContext.permissionMode selalu
|
|
136
|
+
// mencerminkan Shift+Tab saat itu (bukan snapshot saat sesi dibuat).
|
|
137
|
+
const livePermissionMode = (): PermissionMode => withMode.__getMode()
|
|
138
|
+
return createCoreSession({
|
|
139
|
+
...rest,
|
|
140
|
+
provider,
|
|
141
|
+
system,
|
|
142
|
+
permissions,
|
|
143
|
+
permissionMode: livePermissionMode,
|
|
144
|
+
estimator: minicodeEstimator,
|
|
145
|
+
recovery: cappedRecovery,
|
|
146
|
+
executor: parallelExecutor({
|
|
147
|
+
concurrency: safeConcurrency ?? LIMITS.EXECUTOR_CONCURRENCY,
|
|
148
|
+
writeConcurrency: safeWriteConcurrency ?? LIMITS.EXECUTOR_WRITE_CONCURRENCY,
|
|
149
|
+
}),
|
|
150
|
+
cwd,
|
|
151
|
+
...(turnCount !== undefined ? { turnCount } : {}),
|
|
152
|
+
...(stepCount !== undefined ? { stepCount } : {}),
|
|
153
|
+
})
|
|
154
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { Tool } from "#minicore"
|
|
2
|
+
import type { MinicodeConfig } from "../config.ts"
|
|
3
|
+
import { configureServers as lspConfigure } from "../lsp/client.ts"
|
|
4
|
+
import { connectAll as mcpConnectAll } from "../mcp/client.ts"
|
|
5
|
+
import { allTools, withMcpTools } from "../tools/index.ts"
|
|
6
|
+
import { EXPLORE_TOOL_NAMES } from "../tools/task.ts"
|
|
7
|
+
|
|
8
|
+
const errMsg = (e: unknown) => (e instanceof Error ? e.message : String(e))
|
|
9
|
+
|
|
10
|
+
export type ToolScope = "full" | "explore"
|
|
11
|
+
|
|
12
|
+
const PLAN_EXTRA = new Set(["todo_write", "delegate_task", "submit_result"])
|
|
13
|
+
|
|
14
|
+
export async function setupToolLayer(
|
|
15
|
+
cfg: MinicodeConfig,
|
|
16
|
+
scope: ToolScope = "full",
|
|
17
|
+
permissionMode?: string,
|
|
18
|
+
): Promise<{ sessionTools: Tool[] }> {
|
|
19
|
+
let sessionTools: Tool[] = allTools
|
|
20
|
+
// Harness-P2: scope explore = subset read-only (sama seperti sub-agen).
|
|
21
|
+
// MCP runtime ikut terpotong (nama bertitik tak ada di daftar) — least privilege.
|
|
22
|
+
if (scope === "explore")
|
|
23
|
+
sessionTools = allTools.filter((t) => EXPLORE_TOOL_NAMES.includes(t.name))
|
|
24
|
+
// Paket perbaikan (1): plan/readonly sembunyikan tool tulis dari daftar agar
|
|
25
|
+
// model tak buang langkah mencoba yang pasti ditolak. Daftar fixed per sesi
|
|
26
|
+
// (ikuti docs/HARNESS.md batasan sadar).
|
|
27
|
+
if (permissionMode === "readonly") {
|
|
28
|
+
sessionTools = sessionTools.filter((t) => EXPLORE_TOOL_NAMES.includes(t.name))
|
|
29
|
+
} else if (permissionMode === "plan") {
|
|
30
|
+
sessionTools = sessionTools.filter(
|
|
31
|
+
(t) => EXPLORE_TOOL_NAMES.includes(t.name) || PLAN_EXTRA.has(t.name),
|
|
32
|
+
)
|
|
33
|
+
}
|
|
34
|
+
try {
|
|
35
|
+
if (cfg.mcpServers?.length) {
|
|
36
|
+
const mcpTools = await mcpConnectAll(cfg.mcpServers)
|
|
37
|
+
if (mcpTools.length) {
|
|
38
|
+
// Plan/readonly: filter MCP juga, bukan balik ke allTools (bug lama).
|
|
39
|
+
sessionTools = withMcpTools(sessionTools, mcpTools)
|
|
40
|
+
if (permissionMode === "plan" || permissionMode === "readonly") {
|
|
41
|
+
sessionTools = sessionTools.filter(
|
|
42
|
+
(t) => !t.name.includes(".") || EXPLORE_TOOL_NAMES.includes(t.name),
|
|
43
|
+
)
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
} catch (e) {
|
|
48
|
+
process.stderr.write(`[mcp] init failed: ${errMsg(e)}\n`)
|
|
49
|
+
}
|
|
50
|
+
try {
|
|
51
|
+
if (cfg.lspServers?.length) lspConfigure(cfg.lspServers)
|
|
52
|
+
} catch (e) {
|
|
53
|
+
process.stderr.write(`[lsp] init failed: ${errMsg(e)}\n`)
|
|
54
|
+
}
|
|
55
|
+
return { sessionTools }
|
|
56
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
import { existsSync } from "node:fs"
|
|
2
|
+
import { mkdir, readFile } from "node:fs/promises"
|
|
3
|
+
import { join, resolve } from "node:path"
|
|
4
|
+
import { atomicWriteText } from "./lib/atomic-write.ts"
|
|
5
|
+
import { homeDir } from "./lib/db-path.ts"
|
|
6
|
+
|
|
7
|
+
// In-process lock per path untuk mencegah lost-update saat Pool(3) sub-agent
|
|
8
|
+
// menulis config yang sama secara paralel. Untuk lintas proses, atomicWriteText
|
|
9
|
+
// sudah cegah torn write, tapi tanpa CAS tetap last-wins; lock ini menutup
|
|
10
|
+
// kasus 99% (same-process) dengan biaya nol.
|
|
11
|
+
const configLocks = new Map<string, Promise<void>>()
|
|
12
|
+
|
|
13
|
+
// Diekspor agar provisioning (saveProvider/remove/refresh) memakai kunci yang
|
|
14
|
+
// SAMA dengan saveMcpServer/saveLspServer — tanpa ini dua penulis paralel
|
|
15
|
+
// (sesi utama + sub-agen Pool) baca-modifikasi-tulis tanpa lock dan last-wins
|
|
16
|
+
// menelan entri lain (reproducer audit #07: 8× saveProvider paralel → 1 selamat).
|
|
17
|
+
export async function withConfigLock<T>(path: string, fn: () => Promise<T>): Promise<T> {
|
|
18
|
+
const prev = configLocks.get(path) ?? Promise.resolve()
|
|
19
|
+
let release!: () => void
|
|
20
|
+
const next = new Promise<void>((res) => (release = res))
|
|
21
|
+
configLocks.set(
|
|
22
|
+
path,
|
|
23
|
+
prev.then(() => next),
|
|
24
|
+
)
|
|
25
|
+
await prev
|
|
26
|
+
try {
|
|
27
|
+
return await fn()
|
|
28
|
+
} finally {
|
|
29
|
+
release()
|
|
30
|
+
if (configLocks.get(path) === next) configLocks.delete(path)
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface ProviderEntry {
|
|
35
|
+
id: string
|
|
36
|
+
baseUrl: string
|
|
37
|
+
/** API key. Kosong bila provider memakai OAuth (`auth: "oauth"`). */
|
|
38
|
+
apiKey: string
|
|
39
|
+
models: string[]
|
|
40
|
+
providerHint?: string
|
|
41
|
+
/** Knob generik reasoning effort — dipetakan per-wire (openai reasoning_effort, anthropic thinking, gemini). */
|
|
42
|
+
reasoningEffort?: "low" | "medium" | "high"
|
|
43
|
+
/**
|
|
44
|
+
* Sumber kredensial. `oauth` = ambil access token dari `~/.minicode/auth.json`
|
|
45
|
+
* saat runtime, jangan simpan di config (config bisa ikut ter-commit).
|
|
46
|
+
*/
|
|
47
|
+
auth?: "apikey" | "oauth"
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface McpServerEntry {
|
|
51
|
+
id: string
|
|
52
|
+
/** stdio: perintah yang di-spawn. Kosong bila memakai `url` (HTTP). */
|
|
53
|
+
command?: string
|
|
54
|
+
args?: string[]
|
|
55
|
+
env?: Record<string, string>
|
|
56
|
+
/** Streamable HTTP / SSE endpoint. Bila diisi, `command` diabaikan. */
|
|
57
|
+
url?: string
|
|
58
|
+
/** Header tambahan untuk transport HTTP (mis. Authorization). */
|
|
59
|
+
headers?: Record<string, string>
|
|
60
|
+
/** Izinkan endpoint di host privat (server MCP lokal). Default: tolak (anti-SSRF). */
|
|
61
|
+
allowPrivateHost?: boolean
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface LspServerEntry {
|
|
65
|
+
ext: string // ".ts"
|
|
66
|
+
command: string
|
|
67
|
+
args: string[]
|
|
68
|
+
env?: Record<string, string>
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface MinicodeConfig {
|
|
72
|
+
providers: ProviderEntry[]
|
|
73
|
+
mcpServers?: McpServerEntry[]
|
|
74
|
+
lspServers?: LspServerEntry[]
|
|
75
|
+
verifyCommand?: string
|
|
76
|
+
bashAllowlist?: string[]
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Diekspor agar lapisan provisioning (src/providers/provision.ts) membaca dan
|
|
80
|
+
// menulis berkas config yang sama tanpa menduplikasi path/normalisasi.
|
|
81
|
+
// FUNGSI bukan const: path dibaca tiap panggil agar hormat MINICODE_HOME yang
|
|
82
|
+
// diset belakangan (test hermetic, CI hermetic via env) — konsisten dengan
|
|
83
|
+
// DB/secrets lewat homeDir(). Const beku-saat-import membuat override env
|
|
84
|
+
// tak berpengaruh (dulu provider "bocor" ke home asli saat MINICODE_HOME set).
|
|
85
|
+
export function globalConfigPath(): string {
|
|
86
|
+
return join(homeDir(), ".minicode", "config.json")
|
|
87
|
+
}
|
|
88
|
+
export const LOCAL = ".minicode/config.json"
|
|
89
|
+
|
|
90
|
+
/** Path absolut config lokal untuk cwd — untuk status/doctor tanpa membacanya. */
|
|
91
|
+
export function localConfigPath(cwd: string): string {
|
|
92
|
+
return resolve(cwd, LOCAL)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Status satu-baris saat operator mengaktifkan local config; undefined bila
|
|
96
|
+
* tak ada efek (flag mati atau berkas tak ada) agar CLI tidak berbohong. */
|
|
97
|
+
export function localConfigNotice(cwd: string, allowLocal: boolean): string | undefined {
|
|
98
|
+
if (!allowLocal) return undefined
|
|
99
|
+
const p = localConfigPath(cwd)
|
|
100
|
+
if (!existsSync(p)) return undefined
|
|
101
|
+
return `[config] local config enabled: ${p}`
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function normalizeConfig(raw: unknown): MinicodeConfig {
|
|
105
|
+
const cfg = raw as Record<string, unknown>
|
|
106
|
+
const providers = Array.isArray(cfg?.providers)
|
|
107
|
+
? (cfg.providers as ProviderEntry[]).filter(
|
|
108
|
+
(p) => p && typeof p.id === "string" && typeof p.baseUrl === "string",
|
|
109
|
+
)
|
|
110
|
+
: []
|
|
111
|
+
// Server MCP sah bila punya `command` (stdio) ATAU `url` (HTTP). Entri tanpa
|
|
112
|
+
// keduanya dibuang di sini supaya kegagalan tampak saat config dibaca, bukan
|
|
113
|
+
// sebagai error misterius saat connect.
|
|
114
|
+
const mcpServers = Array.isArray(cfg?.mcpServers)
|
|
115
|
+
? (cfg.mcpServers as McpServerEntry[]).filter(
|
|
116
|
+
(m) =>
|
|
117
|
+
m &&
|
|
118
|
+
typeof m.id === "string" &&
|
|
119
|
+
(typeof m.command === "string" || typeof m.url === "string"),
|
|
120
|
+
)
|
|
121
|
+
: undefined
|
|
122
|
+
const lspServers = Array.isArray(cfg?.lspServers)
|
|
123
|
+
? (cfg.lspServers as LspServerEntry[]).filter(
|
|
124
|
+
(l) => l && typeof l.ext === "string" && typeof l.command === "string",
|
|
125
|
+
)
|
|
126
|
+
: undefined
|
|
127
|
+
const verifyCommand =
|
|
128
|
+
typeof cfg?.verifyCommand === "string" ? (cfg.verifyCommand as string) : undefined
|
|
129
|
+
const bashAllowlist = Array.isArray(cfg?.bashAllowlist)
|
|
130
|
+
? (cfg.bashAllowlist as string[]).filter((s) => typeof s === "string")
|
|
131
|
+
: undefined
|
|
132
|
+
return {
|
|
133
|
+
providers,
|
|
134
|
+
...(mcpServers ? { mcpServers } : {}),
|
|
135
|
+
...(lspServers ? { lspServers } : {}),
|
|
136
|
+
...(verifyCommand ? { verifyCommand } : {}),
|
|
137
|
+
...(bashAllowlist ? { bashAllowlist } : {}),
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export async function writeConfigAtomic(path: string, cfg: MinicodeConfig): Promise<void> {
|
|
142
|
+
await atomicWriteText(path, JSON.stringify(cfg, null, 2))
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export async function loadConfig(
|
|
146
|
+
cwd = process.cwd(),
|
|
147
|
+
opts: { allowLocal?: boolean } = {},
|
|
148
|
+
): Promise<MinicodeConfig> {
|
|
149
|
+
let globalCfg: MinicodeConfig = { providers: [] }
|
|
150
|
+
let localCfg: MinicodeConfig = { providers: [] }
|
|
151
|
+
try {
|
|
152
|
+
const raw = await readFile(globalConfigPath(), "utf8")
|
|
153
|
+
globalCfg = normalizeConfig(JSON.parse(raw))
|
|
154
|
+
} catch (e) {
|
|
155
|
+
// ENOENT (belum ada file) = mulai kosong, diam. Error LAIN (EACCES,
|
|
156
|
+
// EISDIR, …) dulu ditelan menjadi "no providers" sehingga user menambah
|
|
157
|
+
// duplikat tanpa tahu config globalnya tak terbaca — beri tahu.
|
|
158
|
+
const code = (e as NodeJS.ErrnoException)?.code
|
|
159
|
+
if (e instanceof SyntaxError)
|
|
160
|
+
process.stderr.write(`[config] invalid JSON in ${globalConfigPath()}: ${e.message}\n`)
|
|
161
|
+
else if (code !== "ENOENT")
|
|
162
|
+
process.stderr.write(
|
|
163
|
+
`[config] cannot read ${globalConfigPath()} (${code ?? "error"}) — starting empty\n`,
|
|
164
|
+
)
|
|
165
|
+
}
|
|
166
|
+
// Local `.minicode/config.json` adalah input repo tak terpercaya (audit #07
|
|
167
|
+
// P0: mcpServers langsung di-spawn, baseUrl jahat menyedot prompt,
|
|
168
|
+
// verifyCommand dieksekusi). Ia HANYA dibaca bila operator opt-in eksplisit
|
|
169
|
+
// (--allow-local-config / MINICODE_ALLOW_LOCAL_CONFIG=1); default = global
|
|
170
|
+
// saja (fail-closed). Tulis eksplisit (--local) tak terpengaruh.
|
|
171
|
+
if (opts.allowLocal) {
|
|
172
|
+
try {
|
|
173
|
+
const localPath = resolve(cwd, LOCAL)
|
|
174
|
+
const raw = await readFile(localPath, "utf8")
|
|
175
|
+
localCfg = normalizeConfig(JSON.parse(raw))
|
|
176
|
+
} catch (e) {
|
|
177
|
+
// Sama seperti global: SyntaxError selalu ribut; error baca non-ENOENT
|
|
178
|
+
// (EACCES/…) ribut juga — reset diam-diam membuat override lokal
|
|
179
|
+
// "hilang" tanpa jejak.
|
|
180
|
+
const code = (e as NodeJS.ErrnoException)?.code
|
|
181
|
+
if (e instanceof SyntaxError)
|
|
182
|
+
process.stderr.write(
|
|
183
|
+
`[config] invalid JSON in ${resolve(cwd, LOCAL)}: ${(e as Error).message}\n`,
|
|
184
|
+
)
|
|
185
|
+
else if (code !== "ENOENT")
|
|
186
|
+
process.stderr.write(
|
|
187
|
+
`[config] cannot read ${resolve(cwd, LOCAL)} (${code ?? "error"}) — ignoring local\n`,
|
|
188
|
+
)
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
// generic merge helper — deduplicate DRY
|
|
192
|
+
function mergeByKey<T>(global: T[], local: T[], keyFn: (v: T) => string): T[] {
|
|
193
|
+
const map = new Map<string, T>()
|
|
194
|
+
for (const v of global) map.set(keyFn(v), v)
|
|
195
|
+
for (const v of local) {
|
|
196
|
+
const k = keyFn(v)
|
|
197
|
+
// Override lokal MENGGANTI nilai di posisi global, bukan pindah ke
|
|
198
|
+
// akhir: JS Map.set pada key lama mempertahankan urutan. Dulu
|
|
199
|
+
// delete-then-set memindahkan provider ter-override ke ujung sehingga
|
|
200
|
+
// providers[0] (default model sesi) berganti diam-diam tiap ada
|
|
201
|
+
// override lokal ("default flip").
|
|
202
|
+
map.set(k, v)
|
|
203
|
+
}
|
|
204
|
+
return [...map.values()]
|
|
205
|
+
}
|
|
206
|
+
const mergedProviders = mergeByKey(globalCfg.providers, localCfg.providers, (p) => p.id)
|
|
207
|
+
const mergedMcp = mergeByKey(globalCfg.mcpServers ?? [], localCfg.mcpServers ?? [], (m) => m.id)
|
|
208
|
+
const mergedLsp = mergeByKey(globalCfg.lspServers ?? [], localCfg.lspServers ?? [], (l) =>
|
|
209
|
+
l.ext.toLowerCase(),
|
|
210
|
+
)
|
|
211
|
+
return {
|
|
212
|
+
providers: mergedProviders,
|
|
213
|
+
mcpServers: mergedMcp,
|
|
214
|
+
lspServers: mergedLsp,
|
|
215
|
+
...((localCfg.verifyCommand ?? globalCfg.verifyCommand)
|
|
216
|
+
? { verifyCommand: localCfg.verifyCommand ?? globalCfg.verifyCommand }
|
|
217
|
+
: {}),
|
|
218
|
+
...((localCfg.bashAllowlist ?? globalCfg.bashAllowlist)
|
|
219
|
+
? { bashAllowlist: localCfg.bashAllowlist ?? globalCfg.bashAllowlist }
|
|
220
|
+
: {}),
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Model terakhir dipakai (satu nilai global) — default sesi berikutnya bila
|
|
225
|
+
// tanpa --model dan modelnya masih ada di config. File kecil terpisah
|
|
226
|
+
// (~/.minicode/state.json, bukan config provider) agar tak ikut ter-commit
|
|
227
|
+
// dan tak bercampur merge global/lokal. Fire-and-forget oleh pemanggil:
|
|
228
|
+
// IO gagal tak boleh menggagalkan sesi.
|
|
229
|
+
const statePath = () => join(homeDir(), ".minicode", "state.json")
|
|
230
|
+
|
|
231
|
+
export async function loadLastModel(): Promise<string | undefined> {
|
|
232
|
+
try {
|
|
233
|
+
const raw = await readFile(statePath(), "utf8")
|
|
234
|
+
const m = (JSON.parse(raw) as { lastModel?: unknown }).lastModel
|
|
235
|
+
return typeof m === "string" && m ? m : undefined
|
|
236
|
+
} catch {
|
|
237
|
+
return undefined
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
export async function saveLastModel(id: string): Promise<void> {
|
|
242
|
+
const path = statePath()
|
|
243
|
+
return withConfigLock(path, async () => {
|
|
244
|
+
await mkdir(join(homeDir(), ".minicode"), { recursive: true, mode: 0o700 }).catch(() => {})
|
|
245
|
+
await atomicWriteText(path, JSON.stringify({ lastModel: id }))
|
|
246
|
+
})
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
export async function saveMcpServer(
|
|
250
|
+
entry: McpServerEntry,
|
|
251
|
+
opts: { global?: boolean; cwd?: string } = {},
|
|
252
|
+
) {
|
|
253
|
+
if (!entry.id || (!entry.command && !entry.url))
|
|
254
|
+
throw new Error("mcp entry needs an id + (command for stdio or url for http)")
|
|
255
|
+
const path =
|
|
256
|
+
(opts.global ?? true) ? globalConfigPath() : resolve(opts.cwd ?? process.cwd(), LOCAL)
|
|
257
|
+
return withConfigLock(path, async () => {
|
|
258
|
+
let cfg: MinicodeConfig = { providers: [] }
|
|
259
|
+
let raw = ""
|
|
260
|
+
try {
|
|
261
|
+
raw = await readFile(path, "utf8")
|
|
262
|
+
cfg = normalizeConfig(JSON.parse(raw))
|
|
263
|
+
} catch (e) {
|
|
264
|
+
if (e instanceof SyntaxError) {
|
|
265
|
+
const backup = `${path}.corrupt.${Date.now()}`
|
|
266
|
+
await atomicWriteText(backup, raw).catch(() => {})
|
|
267
|
+
throw new Error(`config corrupt: ${path} — backup to ${backup}: ${e.message}`)
|
|
268
|
+
}
|
|
269
|
+
if ((e as NodeJS.ErrnoException).code === "ENOENT") {
|
|
270
|
+
cfg = { providers: [] }
|
|
271
|
+
} else if ((e as Error).message?.includes("config corrupt")) {
|
|
272
|
+
throw e
|
|
273
|
+
} else if ((e as NodeJS.ErrnoException).code) {
|
|
274
|
+
throw e
|
|
275
|
+
} else {
|
|
276
|
+
cfg = { providers: [] }
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
cfg.mcpServers ??= []
|
|
280
|
+
const idx = cfg.mcpServers.findIndex((m) => m.id === entry.id)
|
|
281
|
+
if (idx >= 0) cfg.mcpServers[idx] = entry
|
|
282
|
+
else cfg.mcpServers.push(entry)
|
|
283
|
+
await writeConfigAtomic(path, cfg)
|
|
284
|
+
})
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
export async function removeMcpServer(id: string, opts: { global?: boolean; cwd?: string } = {}) {
|
|
288
|
+
const path =
|
|
289
|
+
(opts.global ?? true) ? globalConfigPath() : resolve(opts.cwd ?? process.cwd(), LOCAL)
|
|
290
|
+
return withConfigLock(path, async () => {
|
|
291
|
+
let cfg: MinicodeConfig = { providers: [] }
|
|
292
|
+
let raw = ""
|
|
293
|
+
try {
|
|
294
|
+
raw = await readFile(path, "utf8")
|
|
295
|
+
cfg = normalizeConfig(JSON.parse(raw))
|
|
296
|
+
} catch (e) {
|
|
297
|
+
if (e instanceof SyntaxError) {
|
|
298
|
+
const backup = `${path}.corrupt.${Date.now()}`
|
|
299
|
+
await atomicWriteText(backup, raw).catch(() => {})
|
|
300
|
+
throw new Error(`config corrupt: ${path} — backup to ${backup}: ${e.message}`)
|
|
301
|
+
}
|
|
302
|
+
if ((e as NodeJS.ErrnoException).code === "ENOENT") cfg = { providers: [] }
|
|
303
|
+
else if ((e as Error).message?.includes("config corrupt")) throw e
|
|
304
|
+
else if ((e as NodeJS.ErrnoException).code) throw e
|
|
305
|
+
else cfg = { providers: [] }
|
|
306
|
+
}
|
|
307
|
+
cfg.mcpServers = (cfg.mcpServers ?? []).filter((m) => m.id !== id)
|
|
308
|
+
await writeConfigAtomic(path, cfg)
|
|
309
|
+
})
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function normalizeExt(ext: string): string {
|
|
313
|
+
return ext.startsWith(".") ? ext.toLowerCase() : `.${ext.toLowerCase()}`
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
export async function saveLspServer(
|
|
317
|
+
entry: LspServerEntry,
|
|
318
|
+
opts: { global?: boolean; cwd?: string } = {},
|
|
319
|
+
) {
|
|
320
|
+
if (!entry.ext || !entry.command) throw new Error("lsp ext/command required")
|
|
321
|
+
const path =
|
|
322
|
+
(opts.global ?? true) ? globalConfigPath() : resolve(opts.cwd ?? process.cwd(), LOCAL)
|
|
323
|
+
return withConfigLock(path, async () => {
|
|
324
|
+
let cfg: MinicodeConfig = { providers: [] }
|
|
325
|
+
let raw = ""
|
|
326
|
+
try {
|
|
327
|
+
raw = await readFile(path, "utf8")
|
|
328
|
+
cfg = normalizeConfig(JSON.parse(raw))
|
|
329
|
+
} catch (e) {
|
|
330
|
+
if (e instanceof SyntaxError) {
|
|
331
|
+
const backup = `${path}.corrupt.${Date.now()}`
|
|
332
|
+
await atomicWriteText(backup, raw).catch(() => {})
|
|
333
|
+
throw new Error(`config corrupt: ${path} — backup to ${backup}: ${e.message}`)
|
|
334
|
+
}
|
|
335
|
+
if ((e as NodeJS.ErrnoException).code === "ENOENT") cfg = { providers: [] }
|
|
336
|
+
else if ((e as Error).message?.includes("config corrupt")) throw e
|
|
337
|
+
else if ((e as NodeJS.ErrnoException).code) throw e
|
|
338
|
+
else cfg = { providers: [] }
|
|
339
|
+
}
|
|
340
|
+
cfg.lspServers ??= []
|
|
341
|
+
const ext = normalizeExt(entry.ext)
|
|
342
|
+
const idx = cfg.lspServers.findIndex((l) => l.ext.toLowerCase() === ext)
|
|
343
|
+
if (idx >= 0) cfg.lspServers[idx] = { ...entry, ext }
|
|
344
|
+
else cfg.lspServers.push({ ...entry, ext })
|
|
345
|
+
await writeConfigAtomic(path, cfg)
|
|
346
|
+
})
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
export async function removeLspServer(ext: string, opts: { global?: boolean; cwd?: string } = {}) {
|
|
350
|
+
const path =
|
|
351
|
+
(opts.global ?? true) ? globalConfigPath() : resolve(opts.cwd ?? process.cwd(), LOCAL)
|
|
352
|
+
return withConfigLock(path, async () => {
|
|
353
|
+
let cfg: MinicodeConfig = { providers: [] }
|
|
354
|
+
let raw = ""
|
|
355
|
+
try {
|
|
356
|
+
raw = await readFile(path, "utf8")
|
|
357
|
+
cfg = normalizeConfig(JSON.parse(raw))
|
|
358
|
+
} catch (e) {
|
|
359
|
+
if (e instanceof SyntaxError) {
|
|
360
|
+
const backup = `${path}.corrupt.${Date.now()}`
|
|
361
|
+
await atomicWriteText(backup, raw).catch(() => {})
|
|
362
|
+
throw new Error(`config corrupt: ${path} — backup to ${backup}: ${e.message}`)
|
|
363
|
+
}
|
|
364
|
+
if ((e as NodeJS.ErrnoException).code === "ENOENT") cfg = { providers: [] }
|
|
365
|
+
else if ((e as Error).message?.includes("config corrupt")) throw e
|
|
366
|
+
else if ((e as NodeJS.ErrnoException).code) throw e
|
|
367
|
+
else cfg = { providers: [] }
|
|
368
|
+
}
|
|
369
|
+
cfg.lspServers = (cfg.lspServers ?? []).filter((l) => l.ext.toLowerCase() !== normalizeExt(ext))
|
|
370
|
+
await writeConfigAtomic(path, cfg)
|
|
371
|
+
})
|
|
372
|
+
}
|