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,179 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto"
|
|
2
|
+
import { resolve as resolvePath } from "node:path"
|
|
3
|
+
import { createRateLimiter } from "../../src/policy/ratelimit.ts"
|
|
4
|
+
import { resolveSandbox, sandboxRefusalReason } from "../../src/policy/sandbox-policy.ts"
|
|
5
|
+
import { scrubSecrets } from "../../src/policy/scrub.ts"
|
|
6
|
+
import { budgetStatus } from "../../src/policy/usage.ts"
|
|
7
|
+
import { getSubmittedResult } from "../../src/tools/submit_result.ts"
|
|
8
|
+
import { formatError } from "../../src/ui/assistant/simple.ts"
|
|
9
|
+
import { formatUsd } from "../../src/ui/render/money.ts"
|
|
10
|
+
import { allowLocalConfig, hasFlag, promptFromArgs, getArg as rawGetArg } from "../args.ts"
|
|
11
|
+
import { createCliSession } from "../setup.ts"
|
|
12
|
+
|
|
13
|
+
export async function handleExec(
|
|
14
|
+
args: string[],
|
|
15
|
+
getArg: (name: string) => string | undefined,
|
|
16
|
+
): Promise<never> {
|
|
17
|
+
// minicode exec "prompt" [--json] [--cwd <dir>] [--model <m>] [--sandbox docker|os] ...
|
|
18
|
+
//
|
|
19
|
+
// Prompt diambil lewat promptFromArgs() — satu implementasi yang sama dengan
|
|
20
|
+
// jalur non-exec. Versi sebelumnya menyaring dengan `a !== getArg("--model")`,
|
|
21
|
+
// yang hanya membuang NILAI dari dua flag (`--model`, `--cwd`); nilai flag lain
|
|
22
|
+
// ikut masuk ke prompt. `exec "tes" --provider gorouter --timeout 60000` benar-
|
|
23
|
+
// benar mengirim "tes gorouter 60000" ke model, dan model membalas dengan
|
|
24
|
+
// menebak-nebak soal "gorouter" dan "60000".
|
|
25
|
+
const prompt = promptFromArgs(args.slice(1)) || (rawGetArg(args, "--prompt") ?? "")
|
|
26
|
+
const jsonMode = hasFlag(args, "--json") || rawGetArg(args, "--output-format") === "json"
|
|
27
|
+
const cwdRaw = getArg("--cwd")
|
|
28
|
+
const cwd = cwdRaw ? resolvePath(cwdRaw) : undefined
|
|
29
|
+
const modelOverride = getArg("--model")
|
|
30
|
+
const providerOverride = getArg("--provider")
|
|
31
|
+
const sessionId =
|
|
32
|
+
getArg("--session")
|
|
33
|
+
?.replace(/[^A-Za-z0-9._-]/g, "-")
|
|
34
|
+
.slice(0, 64) || randomUUID().slice(0, 8)
|
|
35
|
+
const allowAll = hasFlag(args, "--allow-all")
|
|
36
|
+
const ask = hasFlag(args, "--ask")
|
|
37
|
+
const plan = hasFlag(args, "--plan")
|
|
38
|
+
const allowlistFlag = hasFlag(args, "--allowlist")
|
|
39
|
+
// Sama seperti jalur interaktif: OS sandbox otomatis, dan tanpa isolasi nyata
|
|
40
|
+
// permission default turun ke allowlist. Headless CI justru paling butuh ini —
|
|
41
|
+
// di sana tak ada manusia yang bisa menyetujui prompt.
|
|
42
|
+
const requestedSandbox = getArg("--sandbox") ?? process.env.MINICODE_SANDBOX
|
|
43
|
+
// F-03: sama seperti jalur interaktif — permintaan eksplisit tanpa backend
|
|
44
|
+
// = tolak sebelum jalan (fail-closed).
|
|
45
|
+
const sandboxRefusal = sandboxRefusalReason(requestedSandbox)
|
|
46
|
+
if (sandboxRefusal) {
|
|
47
|
+
console.error(sandboxRefusal)
|
|
48
|
+
process.exit(1)
|
|
49
|
+
}
|
|
50
|
+
const sandbox = resolveSandbox(requestedSandbox, allowAll || ask || plan || allowlistFlag)
|
|
51
|
+
if (sandbox.mode === "none") delete process.env.MINICODE_SANDBOX
|
|
52
|
+
else process.env.MINICODE_SANDBOX = sandbox.mode
|
|
53
|
+
const allowlist = allowlistFlag || sandbox.fallbackPermission === "allowlist"
|
|
54
|
+
// Audit #07 P0: local config repo tak dipercaya kecuali operator opt-in.
|
|
55
|
+
const allowLocal = allowLocalConfig(args)
|
|
56
|
+
const budgetRaw = getArg("--budget")
|
|
57
|
+
const parsedBudget = budgetRaw ? Number(budgetRaw) : undefined
|
|
58
|
+
const budget =
|
|
59
|
+
parsedBudget !== undefined && Number.isFinite(parsedBudget) && parsedBudget >= 0
|
|
60
|
+
? parsedBudget
|
|
61
|
+
: undefined
|
|
62
|
+
// Harness-P1: sama seperti one-shot — strict fail-closed bila cost tak dikenal.
|
|
63
|
+
const budgetStrict =
|
|
64
|
+
hasFlag(args, "--budget-strict") || process.env.MINICODE_BUDGET_STRICT === "1"
|
|
65
|
+
// Harness-P2: scope tool sesi.
|
|
66
|
+
const toolScopeRaw = (
|
|
67
|
+
getArg("--tool-scope") ??
|
|
68
|
+
process.env.MINICODE_TOOL_SCOPE ??
|
|
69
|
+
""
|
|
70
|
+
).toLowerCase()
|
|
71
|
+
const toolScope = toolScopeRaw === "explore" ? ("explore" as const) : ("full" as const)
|
|
72
|
+
const ratelimitRaw = getArg("--ratelimit")
|
|
73
|
+
const rateLimiter = ratelimitRaw ? createRateLimiter(Number(ratelimitRaw)) : undefined
|
|
74
|
+
|
|
75
|
+
const effectivePrompt = prompt.trim()
|
|
76
|
+
if (!effectivePrompt) {
|
|
77
|
+
console.error(
|
|
78
|
+
'usage: minicode exec "prompt" [--json] [--cwd <dir>] [--model <m>] [--sandbox docker|os]',
|
|
79
|
+
)
|
|
80
|
+
process.exit(1)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const ctx = await createCliSession({
|
|
84
|
+
cwd,
|
|
85
|
+
sessionId,
|
|
86
|
+
modelOverride,
|
|
87
|
+
providerOverride,
|
|
88
|
+
prompt: effectivePrompt,
|
|
89
|
+
enterRepl: false,
|
|
90
|
+
verbose: false,
|
|
91
|
+
allowAll,
|
|
92
|
+
ask,
|
|
93
|
+
plan,
|
|
94
|
+
allowlist,
|
|
95
|
+
verify: hasFlag(args, "--verify"),
|
|
96
|
+
allowLocalConfig: allowLocal,
|
|
97
|
+
budget,
|
|
98
|
+
budgetStrict,
|
|
99
|
+
toolScope,
|
|
100
|
+
rateLimiter,
|
|
101
|
+
// Notice hanya bila user eksplisit meminta mode (daemon mati / tak dikenal).
|
|
102
|
+
sandboxNotice: requestedSandbox ? sandbox.notice : undefined,
|
|
103
|
+
})
|
|
104
|
+
const t0 = Date.now()
|
|
105
|
+
const events: unknown[] = []
|
|
106
|
+
// EventBus kernel butuh (type, handler). Memanggil on(handler) 1-argumen
|
|
107
|
+
// mendaftarkan listener di bawah key "function" → tidak pernah terpanggil,
|
|
108
|
+
// sehingga --json tidak pernah stream apa pun. "*" = semua event.
|
|
109
|
+
const unsub = ctx.session.events.on("*", (ev) => {
|
|
110
|
+
events.push(ev)
|
|
111
|
+
if (jsonMode) {
|
|
112
|
+
// stream JSON lines like Codex/Gemini — di-scrub dulu: event bisa
|
|
113
|
+
// membawa tool output berisi secret ke stdout pipeline CI, sementara
|
|
114
|
+
// trace file sudah di-scrub sejak awal.
|
|
115
|
+
process.stdout.write(`${scrubSecrets(JSON.stringify(ev))}\n`)
|
|
116
|
+
}
|
|
117
|
+
})
|
|
118
|
+
try {
|
|
119
|
+
await ctx.runPromptWithVerify(effectivePrompt)
|
|
120
|
+
// Harness-P1: exec sebelumnya mengabaikan --budget total (flag diteruskan
|
|
121
|
+
// tapi tak pernah diperiksa). Samakan dengan one-shot: over → exit 1.
|
|
122
|
+
const ue = ctx.usage.getSession(ctx.modelRef.current)
|
|
123
|
+
const bStatus = budgetStatus(budget, ue.cost, budgetStrict, ue.totalTokens)
|
|
124
|
+
if (bStatus !== "ok") {
|
|
125
|
+
const msg =
|
|
126
|
+
bStatus === "over" && ue.cost != null && budget != null
|
|
127
|
+
? `[budget] ${formatUsd(ue.cost)} > ${formatUsd(budget)} - over budget, stopping.`
|
|
128
|
+
: `[budget] cost unknown (model without pricing) with ${ue.totalTokens} tokens spent - over budget, stopping.`
|
|
129
|
+
unsub()
|
|
130
|
+
await ctx.close()
|
|
131
|
+
if (jsonMode)
|
|
132
|
+
process.stdout.write(
|
|
133
|
+
`${scrubSecrets(JSON.stringify({ type: "summary", ok: false, error: msg, prompt: effectivePrompt }))}\n`,
|
|
134
|
+
)
|
|
135
|
+
else process.stderr.write(`${msg}\n`)
|
|
136
|
+
process.exit(1)
|
|
137
|
+
}
|
|
138
|
+
// Ringkasan memakai total SESI (ue), bukan turn terakhir: dengan --verify
|
|
139
|
+
// (multi-turn + reset antar-siklus) angka turn mengecilkan pemakaian nyata.
|
|
140
|
+
if (jsonMode) {
|
|
141
|
+
// submit_result dari model (bila dipanggil) ikut verbatim — pipeline CI
|
|
142
|
+
// tak perlu menebak batas JSON dari prosa turn terakhir.
|
|
143
|
+
const submitted = getSubmittedResult()
|
|
144
|
+
const result = {
|
|
145
|
+
type: "summary" as const,
|
|
146
|
+
ok: true,
|
|
147
|
+
sessionId,
|
|
148
|
+
model: ctx.modelRef.current,
|
|
149
|
+
prompt: effectivePrompt,
|
|
150
|
+
durationMs: Date.now() - t0,
|
|
151
|
+
steps: ctx.session.state.stepCount,
|
|
152
|
+
turns: ctx.session.state.turnCount,
|
|
153
|
+
usage: ue,
|
|
154
|
+
eventCount: events.length,
|
|
155
|
+
...(submitted ? { submitted: submitted.result } : {}),
|
|
156
|
+
}
|
|
157
|
+
// Event sudah di-stream sebagai JSONL di stdout; summary jadi baris
|
|
158
|
+
// terakhir di stdout juga (bukan stderr) supaya pipeline CI bisa
|
|
159
|
+
// membaca satu stream saja.
|
|
160
|
+
process.stdout.write(`${scrubSecrets(JSON.stringify(result))}\n`)
|
|
161
|
+
} else {
|
|
162
|
+
process.stdout.write(
|
|
163
|
+
`\n[exec] done model=${ctx.modelRef.current} steps=${ctx.session.state.stepCount} tokens=${ue.totalTokens} ${Date.now() - t0}ms\n`,
|
|
164
|
+
)
|
|
165
|
+
}
|
|
166
|
+
unsub()
|
|
167
|
+
await ctx.close()
|
|
168
|
+
process.exit(0)
|
|
169
|
+
} catch (e) {
|
|
170
|
+
if (jsonMode)
|
|
171
|
+
process.stdout.write(
|
|
172
|
+
`${scrubSecrets(JSON.stringify({ type: "summary", ok: false, error: formatError(e), prompt: effectivePrompt }))}\n`,
|
|
173
|
+
)
|
|
174
|
+
else process.stderr.write(`\n${formatError(e)}\n`)
|
|
175
|
+
unsub()
|
|
176
|
+
await ctx.close()
|
|
177
|
+
process.exit(1)
|
|
178
|
+
}
|
|
179
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { resolve as resolvePath } from "node:path"
|
|
2
|
+
|
|
3
|
+
const MCP_HELP = `minicode mcp — run minicode as an MCP server
|
|
4
|
+
|
|
5
|
+
minicode mcp serve [--allow-all] [--all-tools] [--cwd <dir>]
|
|
6
|
+
|
|
7
|
+
--allow-all allow all tools without permission gating
|
|
8
|
+
--all-tools expose all tools, not only safe ones
|
|
9
|
+
--cwd <dir> workspace root to expose
|
|
10
|
+
|
|
11
|
+
MCP servers USED by minicode are configured via:
|
|
12
|
+
minicode config mcp <add|list|remove>`
|
|
13
|
+
|
|
14
|
+
export async function handleMcp(
|
|
15
|
+
args: string[],
|
|
16
|
+
getArg: (name: string) => string | undefined,
|
|
17
|
+
_help: string,
|
|
18
|
+
): Promise<never> {
|
|
19
|
+
const sub = args[1]
|
|
20
|
+
if (sub === "serve") {
|
|
21
|
+
const { serveMcp } = await import("../../src/mcp/server.ts")
|
|
22
|
+
const cwdArg = getArg("--cwd")
|
|
23
|
+
await serveMcp({
|
|
24
|
+
allowAll: args.includes("--allow-all"),
|
|
25
|
+
allTools: args.includes("--all-tools"),
|
|
26
|
+
root: cwdArg ? resolvePath(cwdArg) : undefined,
|
|
27
|
+
})
|
|
28
|
+
process.exit(0)
|
|
29
|
+
}
|
|
30
|
+
// Help kontekstual, bukan HELP global 45 baris. Subcommand asing = exit 1.
|
|
31
|
+
const asking = sub === undefined || sub === "--help" || sub === "-h"
|
|
32
|
+
if (!asking) console.error(`unknown mcp subcommand: ${sub}\n`)
|
|
33
|
+
console.log(MCP_HELP)
|
|
34
|
+
process.exit(asking ? 0 : 1)
|
|
35
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs"
|
|
2
|
+
import { resolve } from "node:path"
|
|
3
|
+
import { getMemoryStats } from "../../src/memory/vector.ts"
|
|
4
|
+
import { c } from "../../src/ui/render/theme.ts"
|
|
5
|
+
|
|
6
|
+
const MEMORY_HELP = `minicode memory — vector RAG store stats
|
|
7
|
+
|
|
8
|
+
minicode memory status [--json] rows, size, models, hit-rate (default)`
|
|
9
|
+
|
|
10
|
+
interface MemoryTraceRow {
|
|
11
|
+
memoryHits?: number
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function fmtBytes(n: number): string {
|
|
15
|
+
if (n < 1024) return `${n} B`
|
|
16
|
+
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`
|
|
17
|
+
return `${(n / (1024 * 1024)).toFixed(2)} MB`
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function fmtDate(ts: number | null): string {
|
|
21
|
+
if (ts == null) return "-"
|
|
22
|
+
try {
|
|
23
|
+
return new Date(ts).toISOString().slice(0, 10)
|
|
24
|
+
} catch {
|
|
25
|
+
return "-"
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Hit-rate RAG dari traces.jsonl: rata-rata memoryHits per run yang mencatatnya.
|
|
30
|
+
function readHitRate(cwd?: string): { runs: number; avgHits: number } {
|
|
31
|
+
let runs = 0
|
|
32
|
+
let total = 0
|
|
33
|
+
try {
|
|
34
|
+
const lines = readFileSync(resolve(cwd ?? ".", ".minicode", "traces.jsonl"), "utf8")
|
|
35
|
+
.split("\n")
|
|
36
|
+
.filter(Boolean)
|
|
37
|
+
for (const l of lines) {
|
|
38
|
+
try {
|
|
39
|
+
const t = JSON.parse(l) as MemoryTraceRow
|
|
40
|
+
if (typeof t.memoryHits === "number") {
|
|
41
|
+
runs++
|
|
42
|
+
total += t.memoryHits
|
|
43
|
+
}
|
|
44
|
+
} catch {}
|
|
45
|
+
}
|
|
46
|
+
} catch {}
|
|
47
|
+
return { runs, avgHits: runs ? total / runs : 0 }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function handleMemory(
|
|
51
|
+
args: string[],
|
|
52
|
+
getArg: (name: string) => string | undefined,
|
|
53
|
+
): Promise<never> {
|
|
54
|
+
const sub = args[1]
|
|
55
|
+
if (sub === "--help" || sub === "-h") {
|
|
56
|
+
console.log(MEMORY_HELP)
|
|
57
|
+
process.exit(0)
|
|
58
|
+
}
|
|
59
|
+
if (sub && sub !== "status" && !sub.startsWith("-")) {
|
|
60
|
+
console.error(`unknown memory subcommand "${sub}" — see: minicode memory status`)
|
|
61
|
+
process.exit(1)
|
|
62
|
+
}
|
|
63
|
+
const cwdArg = getArg("--cwd")
|
|
64
|
+
const asJson = getArg("--json") !== undefined || args.includes("--json")
|
|
65
|
+
const s = getMemoryStats(cwdArg)
|
|
66
|
+
const { runs, avgHits } = readHitRate(cwdArg)
|
|
67
|
+
// P13 P1 DoD: scope efektif ikut tampil agar silent shadowing terlihat.
|
|
68
|
+
const scope = process.env.MINICODE_MEMORY_SCOPE ?? "cwd"
|
|
69
|
+
if (asJson) {
|
|
70
|
+
console.log(
|
|
71
|
+
JSON.stringify({
|
|
72
|
+
rows: s.rows,
|
|
73
|
+
dbBytes: s.dbBytes,
|
|
74
|
+
walBytes: s.walBytes,
|
|
75
|
+
shmBytes: s.shmBytes,
|
|
76
|
+
models: s.models,
|
|
77
|
+
dims: s.dims,
|
|
78
|
+
categories: s.categories,
|
|
79
|
+
scope,
|
|
80
|
+
oldest: s.oldest,
|
|
81
|
+
newest: s.newest,
|
|
82
|
+
traceRuns: runs,
|
|
83
|
+
avgMemoryHits: Math.round(avgHits * 100) / 100,
|
|
84
|
+
}),
|
|
85
|
+
)
|
|
86
|
+
process.exit(0)
|
|
87
|
+
}
|
|
88
|
+
const dot = "\u00b7"
|
|
89
|
+
console.log(
|
|
90
|
+
`\n${c.bold("Memory")} ${s.rows} rows ${dot} ${fmtBytes(s.dbBytes + s.walBytes + s.shmBytes)} ` +
|
|
91
|
+
`(db ${fmtBytes(s.dbBytes)} ${dot} wal ${fmtBytes(s.walBytes)} ${dot} shm ${fmtBytes(s.shmBytes)})`,
|
|
92
|
+
)
|
|
93
|
+
if (s.models.length)
|
|
94
|
+
console.log(` models: ${s.models.map((m) => `${m.model}×${m.count}`).join(", ")}`)
|
|
95
|
+
if (s.dims.length)
|
|
96
|
+
console.log(` dims: ${s.dims.map((d) => `${d.dim || "none"}×${d.count}`).join(", ")}`)
|
|
97
|
+
if (s.categories.length)
|
|
98
|
+
console.log(
|
|
99
|
+
` categories: ${s.categories.map((m) => `${m.category}×${m.count}`).join(", ")} (scope: ${scope})`,
|
|
100
|
+
)
|
|
101
|
+
console.log(` range: ${fmtDate(s.oldest)} → ${fmtDate(s.newest)}`)
|
|
102
|
+
if (runs > 0)
|
|
103
|
+
console.log(` RAG hit-rate: ${avgHits.toFixed(2)} hits/run over ${runs} traced runs`)
|
|
104
|
+
else console.log(c.dim(` (no memoryHits in traces yet — run once to measure hit-rate)`))
|
|
105
|
+
console.log("")
|
|
106
|
+
process.exit(0)
|
|
107
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises"
|
|
2
|
+
import {
|
|
3
|
+
BUILTIN_PRICING,
|
|
4
|
+
findPrice,
|
|
5
|
+
loadPricingOverlay,
|
|
6
|
+
pricingCachePath,
|
|
7
|
+
pricingOverlayMeta,
|
|
8
|
+
syncPricing,
|
|
9
|
+
} from "../../src/policy/pricing.ts"
|
|
10
|
+
import { c, glyphs } from "../../src/ui/render/theme.ts"
|
|
11
|
+
|
|
12
|
+
const PRICING_HELP = `minicode pricing — price table for cost estimation
|
|
13
|
+
|
|
14
|
+
minicode pricing status active price sources (default)
|
|
15
|
+
minicode pricing sync pull from models.dev (explicit, not automatic)
|
|
16
|
+
minicode pricing show <model> show one model price
|
|
17
|
+
minicode pricing clear clear cache and use built-in data`
|
|
18
|
+
|
|
19
|
+
export async function handlePricing(args: string[]): Promise<never> {
|
|
20
|
+
const raw = args[1]
|
|
21
|
+
if (raw === "--help" || raw === "-h") {
|
|
22
|
+
console.log(PRICING_HELP)
|
|
23
|
+
process.exit(0)
|
|
24
|
+
}
|
|
25
|
+
const sub = (raw ?? "status").toLowerCase()
|
|
26
|
+
|
|
27
|
+
if (sub === "sync") {
|
|
28
|
+
process.stderr.write("fetching prices from models.dev…\n")
|
|
29
|
+
try {
|
|
30
|
+
const res = await syncPricing()
|
|
31
|
+
console.log(
|
|
32
|
+
`${c.green(glyphs.check)} saved ${res.count} models (${Math.round(res.bytes / 1024)} KB)\n ${c.dim(res.path)}`,
|
|
33
|
+
)
|
|
34
|
+
process.exit(0)
|
|
35
|
+
} catch (e) {
|
|
36
|
+
console.error(`${c.red(glyphs.cross)} failed: ${(e as Error).message}`)
|
|
37
|
+
console.error(c.dim(" built-in price table is still used — nothing is broken"))
|
|
38
|
+
process.exit(1)
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (sub === "status") {
|
|
43
|
+
await loadPricingOverlay()
|
|
44
|
+
const meta = pricingOverlayMeta()
|
|
45
|
+
console.log(`\n${c.bold("Model pricing")}`)
|
|
46
|
+
console.log(
|
|
47
|
+
` built-in ${Object.keys(BUILTIN_PRICING).length} models (offline, always available)`,
|
|
48
|
+
)
|
|
49
|
+
if (!meta) {
|
|
50
|
+
console.log(` models.dev ${c.dim("not synced yet")} — run: minicode pricing sync`)
|
|
51
|
+
} else {
|
|
52
|
+
const age = Math.round((Date.now() - meta.fetchedAt) / 3_600_000)
|
|
53
|
+
console.log(
|
|
54
|
+
` models.dev ${meta.count} models, ${age}h ago${meta.stale ? c.yellow(" (stale, still in use)") : ""}`,
|
|
55
|
+
)
|
|
56
|
+
console.log(` ${c.dim(pricingCachePath())}`)
|
|
57
|
+
}
|
|
58
|
+
console.log(`\n ${c.dim("No automatic fetch: sync only runs when you ask.")}\n`)
|
|
59
|
+
process.exit(0)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if (sub === "show") {
|
|
63
|
+
const model = args[2]
|
|
64
|
+
if (!model) {
|
|
65
|
+
console.error("usage: minicode pricing show <model>")
|
|
66
|
+
process.exit(1)
|
|
67
|
+
}
|
|
68
|
+
const overlay = await loadPricingOverlay()
|
|
69
|
+
const p = findPrice(model, overlay)
|
|
70
|
+
if (!p) {
|
|
71
|
+
console.log(`(price for "${model}" is unknown — cost will show N/A)`)
|
|
72
|
+
process.exit(0)
|
|
73
|
+
}
|
|
74
|
+
const src = findPrice(model, {}) === p ? "built-in" : "models.dev"
|
|
75
|
+
console.log(`\n${c.bold(model)} ${c.dim(`(${src})`)}`)
|
|
76
|
+
console.log(` input $${p.input}/M token`)
|
|
77
|
+
console.log(` output $${p.output}/M token`)
|
|
78
|
+
if (p.cacheRead != null) console.log(` cache read $${p.cacheRead}/M`)
|
|
79
|
+
if (p.cacheWrite != null) console.log(` cache write $${p.cacheWrite}/M`)
|
|
80
|
+
console.log("")
|
|
81
|
+
process.exit(0)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (sub === "clear") {
|
|
85
|
+
try {
|
|
86
|
+
await readFile(pricingCachePath(), "utf8")
|
|
87
|
+
const { rm } = await import("node:fs/promises")
|
|
88
|
+
await rm(pricingCachePath(), { force: true })
|
|
89
|
+
console.log(`${c.green(glyphs.check)} pricing cache cleared`)
|
|
90
|
+
} catch {
|
|
91
|
+
console.log("(no pricing cache)")
|
|
92
|
+
}
|
|
93
|
+
process.exit(0)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Subcommand asing = salah pakai: exit 1 supaya skrip bisa mendeteksinya.
|
|
97
|
+
console.error(`unknown pricing subcommand: ${sub}\n`)
|
|
98
|
+
console.log(PRICING_HELP)
|
|
99
|
+
process.exit(1)
|
|
100
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs"
|
|
2
|
+
import { resolve } from "node:path"
|
|
3
|
+
import { loadConfig, type MinicodeConfig } from "../../src/config.ts"
|
|
4
|
+
import { refreshProviderModels } from "../../src/providers/provision.ts"
|
|
5
|
+
import { renderTable } from "../../src/ui/render/table.ts"
|
|
6
|
+
import { c, glyphs } from "../../src/ui/render/theme.ts"
|
|
7
|
+
|
|
8
|
+
interface TraceRow {
|
|
9
|
+
model?: string
|
|
10
|
+
ok?: boolean
|
|
11
|
+
error?: string
|
|
12
|
+
timestamp?: string
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// 6.3 — health tanpa jaringan: ambil dari traces.jsonl (last run per provider)
|
|
16
|
+
function readTraces(cwd?: string): TraceRow[] {
|
|
17
|
+
try {
|
|
18
|
+
return readFileSync(resolve(cwd ?? ".", ".minicode", "traces.jsonl"), "utf8")
|
|
19
|
+
.split("\n")
|
|
20
|
+
.filter(Boolean)
|
|
21
|
+
.flatMap((l) => {
|
|
22
|
+
try {
|
|
23
|
+
return [JSON.parse(l) as TraceRow]
|
|
24
|
+
} catch {
|
|
25
|
+
return []
|
|
26
|
+
}
|
|
27
|
+
})
|
|
28
|
+
} catch {
|
|
29
|
+
return []
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function providerOfTrace(cfg: MinicodeConfig, t: TraceRow): string | undefined {
|
|
34
|
+
const m = t.model ?? ""
|
|
35
|
+
if (m.includes("::")) return m.slice(0, m.indexOf("::"))
|
|
36
|
+
const byModel = cfg.providers.find((p) => p.models.includes(m))
|
|
37
|
+
if (byModel) return byModel.id
|
|
38
|
+
const byId = cfg.providers.find((p) => p.id === m)
|
|
39
|
+
if (byId) return byId.id
|
|
40
|
+
return undefined
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function healthMap(
|
|
44
|
+
cfg: MinicodeConfig,
|
|
45
|
+
traces: TraceRow[],
|
|
46
|
+
): Map<string, { ok: boolean; model: string; ts: string }> {
|
|
47
|
+
const out = new Map<string, { ok: boolean; model: string; ts: string }>()
|
|
48
|
+
for (const t of traces) {
|
|
49
|
+
const pid = providerOfTrace(cfg, t)
|
|
50
|
+
if (!pid) continue
|
|
51
|
+
const prev = out.get(pid)
|
|
52
|
+
if (prev && prev.ts > (t.timestamp ?? "")) continue
|
|
53
|
+
out.set(pid, { ok: t.ok !== false, model: t.model ?? "-", ts: t.timestamp ?? "" })
|
|
54
|
+
}
|
|
55
|
+
return out
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function handleProviders(
|
|
59
|
+
args: string[],
|
|
60
|
+
getArg: (name: string) => string | undefined,
|
|
61
|
+
): Promise<never> {
|
|
62
|
+
const firstArg = args[0]
|
|
63
|
+
if (firstArg !== "providers" && firstArg !== "models" && firstArg !== "sync") {
|
|
64
|
+
process.exit(0)
|
|
65
|
+
}
|
|
66
|
+
const cwdArg = getArg("--cwd")
|
|
67
|
+
// Audit #07: local hanya bila operator opt-in (aturan universal — sync
|
|
68
|
+
// tanpa flag tak boleh menghubungi endpoint repo tak dikenal). argv
|
|
69
|
+
// subcommand diawali positional sehingga pakai includes + env (gaya --local).
|
|
70
|
+
const allowLocal =
|
|
71
|
+
args.includes("--allow-local-config") || process.env.MINICODE_ALLOW_LOCAL_CONFIG === "1"
|
|
72
|
+
const cfg = await loadConfig(cwdArg, { allowLocal })
|
|
73
|
+
if (firstArg === "providers") {
|
|
74
|
+
if (cfg.providers.length === 0) {
|
|
75
|
+
console.log(
|
|
76
|
+
"(no providers yet - run `minicode` for the wizard, `minicode auth login` (free, no API key),\nor `minicode config add --baseUrl <url> --apiKey <key>`)",
|
|
77
|
+
)
|
|
78
|
+
process.exit(0)
|
|
79
|
+
}
|
|
80
|
+
// renderTable menjaga kolom tetap berbaris untuk id sepanjang apa pun;
|
|
81
|
+
// padEnd(16) manual sebelumnya rusak begitu id lebih dari 16 karakter.
|
|
82
|
+
const health = healthMap(cfg, readTraces(cwdArg))
|
|
83
|
+
const rows = cfg.providers.map((p) => {
|
|
84
|
+
const h = health.get(p.id)
|
|
85
|
+
const status = !h
|
|
86
|
+
? c.dim("not used yet")
|
|
87
|
+
: `${h.ok ? c.green("ok") : c.red("ERR")} ${c.dim(
|
|
88
|
+
h.ts ? new Date(h.ts).toISOString().slice(0, 10) : "-",
|
|
89
|
+
)}`
|
|
90
|
+
return {
|
|
91
|
+
id: c.cyan(p.id),
|
|
92
|
+
models: String(p.models.length),
|
|
93
|
+
url: p.baseUrl,
|
|
94
|
+
status,
|
|
95
|
+
}
|
|
96
|
+
})
|
|
97
|
+
console.log(
|
|
98
|
+
`\n${c.bold("LLM Providers")}\n` +
|
|
99
|
+
renderTable(
|
|
100
|
+
[
|
|
101
|
+
{ header: "ID", key: "id", width: 24 },
|
|
102
|
+
{ header: "Models", key: "models", width: 6, align: "right" },
|
|
103
|
+
{ header: "Base URL", key: "url", width: 34 },
|
|
104
|
+
{ header: "Status", key: "status", width: 18 },
|
|
105
|
+
],
|
|
106
|
+
rows,
|
|
107
|
+
) +
|
|
108
|
+
"\n",
|
|
109
|
+
)
|
|
110
|
+
console.log(
|
|
111
|
+
` ${c.dim("next: minicode models | minicode sync | minicode config add --baseUrl <url> --apiKey <key>")}\n`,
|
|
112
|
+
)
|
|
113
|
+
process.exit(0)
|
|
114
|
+
}
|
|
115
|
+
if (firstArg === "models") {
|
|
116
|
+
const pid = args[1] && !args[1]!.startsWith("--") ? args[1] : undefined
|
|
117
|
+
const matchIdx = args.indexOf("--match")
|
|
118
|
+
const filter = (matchIdx >= 0 && args[matchIdx + 1] ? args[matchIdx + 1]! : "").toLowerCase()
|
|
119
|
+
const match = (s: string) => (filter ? s.toLowerCase().includes(filter) : true)
|
|
120
|
+
if (pid) {
|
|
121
|
+
const p = cfg.providers.find((x) => x.id === pid)
|
|
122
|
+
if (!p) {
|
|
123
|
+
console.error(`provider "${pid}" not found - see: minicode providers`)
|
|
124
|
+
process.exit(1)
|
|
125
|
+
}
|
|
126
|
+
const list = p.models.filter(match)
|
|
127
|
+
if (!list.length) console.log(` (no matches for "${filter}")`)
|
|
128
|
+
for (const [i, m] of list.entries()) console.log(` [${i}] ${m}`)
|
|
129
|
+
} else {
|
|
130
|
+
if (cfg.providers.length === 0) console.log("(no providers yet)")
|
|
131
|
+
let shown = 0
|
|
132
|
+
for (const p of cfg.providers) {
|
|
133
|
+
const list = p.models.filter(match)
|
|
134
|
+
if (!list.length) continue
|
|
135
|
+
console.log(`${p.id} (${p.baseUrl})${filter ? ` - matches "${filter}"` : ""}`)
|
|
136
|
+
shown += list.length
|
|
137
|
+
for (const m of list.slice(0, 10)) console.log(` ${m}`)
|
|
138
|
+
if (filter && list.length > 10) console.log(` … +${list.length - 10} more`)
|
|
139
|
+
if (!filter && p.models.length > 10) console.log(` … +${p.models.length - 10} more`)
|
|
140
|
+
}
|
|
141
|
+
// Header provider hanya bila ada yang cocok — tanpa ini filter kosong
|
|
142
|
+
// mencetak judul lalu "(no matches)", dua baris untuk nol informasi.
|
|
143
|
+
if (filter && shown === 0) console.log(` (no matches for "${filter}")`)
|
|
144
|
+
}
|
|
145
|
+
process.exit(0)
|
|
146
|
+
}
|
|
147
|
+
if (firstArg === "sync") {
|
|
148
|
+
console.log("Syncing model list from providers…")
|
|
149
|
+
const { updated, failed } = await refreshProviderModels({ cwd: cwdArg, allowLocal })
|
|
150
|
+
for (const r of updated)
|
|
151
|
+
console.log(` ${c.green(glyphs.check)} ${r.id}: ${r.from} -> ${r.to} model`)
|
|
152
|
+
for (const f of failed) console.log(` ${c.red(glyphs.cross)} ${f.id}: ${f.reason}`)
|
|
153
|
+
if (!updated.length && !failed.length) {
|
|
154
|
+
const cfgHere = await loadConfig(cwdArg, { allowLocal })
|
|
155
|
+
if (cfgHere.providers.length === 0)
|
|
156
|
+
console.log(" (no providers yet - run `minicode config add` first)")
|
|
157
|
+
else console.log(" (no changes — check API key and network, then retry)")
|
|
158
|
+
}
|
|
159
|
+
process.exit(0)
|
|
160
|
+
}
|
|
161
|
+
process.exit(0)
|
|
162
|
+
}
|