minicode-ai 0.14.1 → 0.14.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/cli/auto-update.ts +32 -2
- package/cli/index.ts +10 -2
- package/cli/setup.ts +8 -3
- package/cli/tui.ts +18 -15
- package/docs/OUTPUT_PROTOCOL_SPEC.md +6 -0
- package/docs/OUTPUT_RENDERING_SPEC.md +28 -4
- package/docs/README.md +2 -2
- package/docs/TERMINAL_CONTRACT.md +52 -26
- package/docs/getting-started.md +14 -12
- package/docs/glossary.md +1 -1
- package/docs/mcp-lsp.md +1 -1
- package/docs/policy-sandbox.md +7 -1
- package/docs/security-model.md +2 -2
- package/docs/security.md +7 -1
- package/docs/tools.md +4 -4
- package/docs/verify-benchmark.md +16 -0
- package/package.json +1 -3
- package/src/app/mentions.ts +4 -3
- package/src/app/session.ts +13 -9
- package/src/app/tool-layer.ts +6 -0
- package/src/constants.ts +17 -0
- package/src/lib/git-hardening.ts +27 -22
- package/src/lib/safe-open.ts +73 -19
- package/src/lib/trusted-exec.ts +7 -4
- package/src/mcp/client.ts +34 -9
- package/src/mcp/transport.ts +96 -42
- package/src/memory/files.ts +15 -4
- package/src/memory/vector.ts +5 -1
- package/src/policy/context.ts +21 -13
- package/src/policy/tool-contract.ts +4 -10
- package/src/policy/update-check.ts +83 -6
- package/src/policy/usage.ts +17 -7
- package/src/presentation/adapter.ts +64 -2
- package/src/presentation/events.ts +6 -0
- package/src/presentation/model.ts +1 -0
- package/src/presentation/projection.ts +2 -0
- package/src/presentation/reducer.ts +1 -0
- package/src/providers/anthropic.ts +52 -19
- package/src/providers/guards.ts +98 -13
- package/src/providers/responses.ts +61 -23
- package/src/providers/sse-bounds.ts +170 -0
- package/src/repo/repomap.ts +10 -11
- package/src/runtime/execution-backend.ts +7 -8
- package/src/sandbox/docker.ts +113 -9
- package/src/session/checkpoint.ts +9 -2
- package/src/session/persistence.ts +5 -2
- package/src/session/verification.ts +55 -16
- package/src/skills/loader.ts +16 -3
- package/src/tools/bash.ts +6 -3
- package/src/tools/code_run.ts +6 -5
- package/src/tools/context.ts +8 -0
- package/src/tools/delete_file.ts +2 -1
- package/src/tools/edit.ts +2 -1
- package/src/tools/git.ts +128 -54
- package/src/tools/glob.ts +2 -1
- package/src/tools/grep.ts +31 -6
- package/src/tools/lsp.ts +5 -4
- package/src/tools/mcp_call.ts +3 -1
- package/src/tools/memory.ts +175 -180
- package/src/tools/move_file.ts +2 -1
- package/src/tools/patch.ts +2 -1
- package/src/tools/read_file.ts +94 -1
- package/src/tools/read_image.ts +2 -1
- package/src/tools/task.ts +2 -1
- package/src/tools/todo.ts +4 -5
- package/src/tools/web_fetch.ts +28 -12
- package/src/tools/web_search.ts +28 -9
- package/src/tools/write_file.ts +2 -1
- package/src/ui/assistant/simple.ts +72 -3
- package/src/ui/i18n/en.ts +3 -0
- package/src/ui/i18n/id.ts +3 -0
- package/src/ui/render/width.ts +107 -79
- package/src/ui/runtime/screen.ts +49 -37
- package/src/ui/tui/app.ts +255 -205
- package/src/ui/tui/transcript.ts +39 -0
- package/CHANGELOG.md +0 -1185
- package/docs/PLAN_UIUX_V6.md +0 -209
- package/docs/changelog.md +0 -3
package/src/mcp/transport.ts
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
import { type ChildProcess, spawn } from "node:child_process"
|
|
2
|
-
import { createInterface } from "node:readline"
|
|
3
2
|
import { LIMITS } from "../constants.ts"
|
|
4
3
|
import { sanitizeSpawnEnv } from "../policy/scrub.ts"
|
|
5
4
|
|
|
6
5
|
export class McpTransport {
|
|
7
6
|
private proc: ChildProcess | null = null
|
|
8
|
-
private
|
|
7
|
+
private stdoutFrame = Buffer.alloc(0)
|
|
9
8
|
private pending = new Map<
|
|
10
9
|
string | number,
|
|
11
10
|
{
|
|
@@ -37,35 +36,22 @@ export class McpTransport {
|
|
|
37
36
|
})
|
|
38
37
|
|
|
39
38
|
this.proc.on("error", (err) => this.failAll(err))
|
|
39
|
+
this.proc.stdin?.on("error", (err) => {
|
|
40
|
+
// Server dapat keluar tepat sebelum request ditulis. EPIPE pada stdin
|
|
41
|
+
// tetap harus menjadi penolakan request, bukan uncaught exception proses.
|
|
42
|
+
this.closed = true
|
|
43
|
+
this.writeQueue = []
|
|
44
|
+
this.draining = false
|
|
45
|
+
this.failAll(err)
|
|
46
|
+
})
|
|
40
47
|
this.proc.on("exit", (code) => {
|
|
41
48
|
if (!this.closed) this.failAll(new Error(`MCP server exited with code ${code}`))
|
|
42
49
|
})
|
|
43
50
|
this.proc.stderr?.on("data", (d: Buffer) =>
|
|
44
51
|
process.stderr.write(`[mcp:${command}] ${d.toString().trim()}\n`),
|
|
45
52
|
)
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
try {
|
|
49
|
-
this.rl.close()
|
|
50
|
-
} catch {}
|
|
51
|
-
|
|
52
|
-
this.rl = createInterface({ input: this.proc.stdout! })
|
|
53
|
-
this.rl.on("line", (line) => {
|
|
54
|
-
if (!line.trim()) return
|
|
55
|
-
try {
|
|
56
|
-
const msg = JSON.parse(line)
|
|
57
|
-
if (msg.id != null && this.pending.has(msg.id)) {
|
|
58
|
-
const p = this.pending.get(msg.id)!
|
|
59
|
-
clearTimeout(p.timer)
|
|
60
|
-
p.unsubscribe?.()
|
|
61
|
-
this.pending.delete(msg.id)
|
|
62
|
-
if (msg.error) p.reject(new Error(msg.error.message || JSON.stringify(msg.error)))
|
|
63
|
-
else p.resolve(msg.result)
|
|
64
|
-
}
|
|
65
|
-
} catch (e) {
|
|
66
|
-
process.stderr.write(`[mcp] ignoring invalid JSON from server: ${(e as Error).message}\n`)
|
|
67
|
-
}
|
|
68
|
-
})
|
|
53
|
+
this.stdoutFrame = Buffer.alloc(0)
|
|
54
|
+
this.proc.stdout!.on("data", (chunk: Buffer) => this.consumeStdout(chunk))
|
|
69
55
|
}
|
|
70
56
|
|
|
71
57
|
async request(
|
|
@@ -107,36 +93,43 @@ export class McpTransport {
|
|
|
107
93
|
}
|
|
108
94
|
|
|
109
95
|
async close(): Promise<void> {
|
|
110
|
-
if (this.closed) return
|
|
96
|
+
if (this.closed && !this.proc) return
|
|
111
97
|
this.closed = true
|
|
112
98
|
this.writeQueue = []
|
|
113
99
|
this.draining = false
|
|
114
100
|
this.failAll(new Error("transport closed"))
|
|
115
|
-
if (this.rl) this.rl.close()
|
|
116
101
|
try {
|
|
117
102
|
this.proc?.stdin?.end()
|
|
118
103
|
} catch {}
|
|
119
104
|
this.killSignal.abort()
|
|
120
105
|
if (this.proc) {
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
106
|
+
const p = this.proc
|
|
107
|
+
if (p.exitCode === null && p.signalCode === null) {
|
|
108
|
+
await new Promise<void>((r) => {
|
|
109
|
+
const t = setTimeout(() => {
|
|
110
|
+
try {
|
|
111
|
+
p.kill("SIGKILL")
|
|
112
|
+
} catch {}
|
|
113
|
+
r()
|
|
114
|
+
}, 2_000)
|
|
115
|
+
p.once("exit", () => {
|
|
116
|
+
clearTimeout(t)
|
|
117
|
+
r()
|
|
118
|
+
})
|
|
132
119
|
})
|
|
133
|
-
}
|
|
120
|
+
}
|
|
134
121
|
}
|
|
135
122
|
this.proc = null
|
|
136
123
|
}
|
|
137
124
|
|
|
138
125
|
private write(msg: unknown) {
|
|
139
|
-
|
|
126
|
+
const proc = this.proc
|
|
127
|
+
if (!proc?.stdin) throw new Error("transport not connected")
|
|
128
|
+
if (this.closed || proc.exitCode !== null || proc.stdin.destroyed) {
|
|
129
|
+
throw new Error(
|
|
130
|
+
`MCP transport is closed${proc.exitCode === null ? "" : ` (exit ${proc.exitCode})`}`,
|
|
131
|
+
)
|
|
132
|
+
}
|
|
140
133
|
let line: string
|
|
141
134
|
try {
|
|
142
135
|
line = `${JSON.stringify(msg)}\n`
|
|
@@ -147,10 +140,10 @@ export class McpTransport {
|
|
|
147
140
|
this.writeQueue.push(line)
|
|
148
141
|
return
|
|
149
142
|
}
|
|
150
|
-
const ok =
|
|
143
|
+
const ok = proc.stdin.write(line)
|
|
151
144
|
if (!ok) {
|
|
152
145
|
this.draining = true
|
|
153
|
-
|
|
146
|
+
proc.stdin.once("drain", () => {
|
|
154
147
|
this.draining = false
|
|
155
148
|
this.flushQueue()
|
|
156
149
|
})
|
|
@@ -173,6 +166,67 @@ export class McpTransport {
|
|
|
173
166
|
}
|
|
174
167
|
}
|
|
175
168
|
|
|
169
|
+
/** Frame parsing stays incremental so a peer cannot make readline buffer an unlimited line. */
|
|
170
|
+
private consumeStdout(chunk: Buffer): void {
|
|
171
|
+
let start = 0
|
|
172
|
+
for (let i = 0; i < chunk.length; i++) {
|
|
173
|
+
if (chunk[i] !== 0x0a) continue
|
|
174
|
+
const part = chunk.subarray(start, i)
|
|
175
|
+
if (this.stdoutFrame.length + part.length > LIMITS.MCP_STDIO_FRAME_MAX_BYTES) {
|
|
176
|
+
this.rejectOversizedFrame(this.stdoutFrame.length + part.length)
|
|
177
|
+
return
|
|
178
|
+
}
|
|
179
|
+
const frame = this.stdoutFrame.length === 0 ? part : Buffer.concat([this.stdoutFrame, part])
|
|
180
|
+
this.stdoutFrame = Buffer.alloc(0)
|
|
181
|
+
this.handleFrame(frame)
|
|
182
|
+
if (this.closed) return
|
|
183
|
+
start = i + 1
|
|
184
|
+
}
|
|
185
|
+
if (start < chunk.length) {
|
|
186
|
+
const remainder = chunk.subarray(start)
|
|
187
|
+
if (this.stdoutFrame.length + remainder.length > LIMITS.MCP_STDIO_FRAME_MAX_BYTES) {
|
|
188
|
+
this.rejectOversizedFrame(this.stdoutFrame.length + remainder.length)
|
|
189
|
+
return
|
|
190
|
+
}
|
|
191
|
+
this.stdoutFrame =
|
|
192
|
+
this.stdoutFrame.length === 0
|
|
193
|
+
? Buffer.from(remainder)
|
|
194
|
+
: Buffer.concat([this.stdoutFrame, remainder])
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
private handleFrame(frame: Buffer): void {
|
|
199
|
+
if (frame.length === 0) return
|
|
200
|
+
try {
|
|
201
|
+
const msg = JSON.parse(frame.toString("utf8"))
|
|
202
|
+
if (msg.id != null && this.pending.has(msg.id)) {
|
|
203
|
+
const p = this.pending.get(msg.id)!
|
|
204
|
+
clearTimeout(p.timer)
|
|
205
|
+
p.unsubscribe?.()
|
|
206
|
+
this.pending.delete(msg.id)
|
|
207
|
+
if (msg.error) p.reject(new Error(msg.error.message || "MCP server returned an error"))
|
|
208
|
+
else p.resolve(msg.result)
|
|
209
|
+
}
|
|
210
|
+
} catch {
|
|
211
|
+
process.stderr.write("[mcp] ignoring invalid JSON from server\n")
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
private rejectOversizedFrame(size: number): void {
|
|
216
|
+
const error = new Error(
|
|
217
|
+
`MCP stdio frame exceeds ${LIMITS.MCP_STDIO_FRAME_MAX_BYTES} bytes (at least ${size})`,
|
|
218
|
+
)
|
|
219
|
+
this.closed = true
|
|
220
|
+
this.stdoutFrame = Buffer.alloc(0)
|
|
221
|
+
this.writeQueue = []
|
|
222
|
+
this.draining = false
|
|
223
|
+
this.failAll(error)
|
|
224
|
+
this.killSignal.abort(error)
|
|
225
|
+
try {
|
|
226
|
+
this.proc?.kill("SIGKILL")
|
|
227
|
+
} catch {}
|
|
228
|
+
}
|
|
229
|
+
|
|
176
230
|
private failAll(err: Error) {
|
|
177
231
|
for (const p of this.pending.values()) {
|
|
178
232
|
clearTimeout(p.timer)
|
package/src/memory/files.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { homedir } from "node:os"
|
|
|
3
3
|
import { dirname, join, resolve } from "node:path"
|
|
4
4
|
import { LIMITS } from "../constants.ts"
|
|
5
5
|
import { homeDir } from "../lib/db-path.ts"
|
|
6
|
+
import { safeReadFileCapped } from "../lib/safe-open.ts"
|
|
6
7
|
import { isRealPathOutsideRoot } from "../policy/jail.ts"
|
|
7
8
|
import { scrubSecrets } from "../policy/scrub.ts"
|
|
8
9
|
|
|
@@ -36,8 +37,15 @@ export async function loadMemoryFiles(cwd = process.cwd()): Promise<string> {
|
|
|
36
37
|
// symlink keluar workspace. globalMem (home) sengaja dikecualikan —
|
|
37
38
|
// di luar cwd by design. Samakan rules/ di bawah ke realpath.
|
|
38
39
|
if (p !== globalMem && isRealPathOutsideRoot(p, cwd)) continue
|
|
39
|
-
const
|
|
40
|
-
|
|
40
|
+
const { text, truncated } = await safeReadFileCapped(
|
|
41
|
+
p,
|
|
42
|
+
p === globalMem ? dirname(p) : cwd,
|
|
43
|
+
6000,
|
|
44
|
+
)
|
|
45
|
+
if (text.trim())
|
|
46
|
+
parts.push(
|
|
47
|
+
`# ${tildePath(p)}\n${scrubSecrets(text)}${truncated ? "\n… [truncated: showing first 6000 bytes]" : ""}`,
|
|
48
|
+
)
|
|
41
49
|
} catch {}
|
|
42
50
|
}
|
|
43
51
|
// Load .minicode/rules/*.md (Kiro steering style)
|
|
@@ -57,8 +65,11 @@ export async function loadMemoryFiles(cwd = process.cwd()): Promise<string> {
|
|
|
57
65
|
try {
|
|
58
66
|
const full = join(rulesDir, f as string)
|
|
59
67
|
if (isRealPathOutsideRoot(full, cwd)) continue
|
|
60
|
-
const
|
|
61
|
-
if (
|
|
68
|
+
const { text, truncated } = await safeReadFileCapped(full, cwd, 3000)
|
|
69
|
+
if (text.trim())
|
|
70
|
+
parts.push(
|
|
71
|
+
`# rules/${f}\n${scrubSecrets(text)}${truncated ? "\n… [truncated: showing first 3000 bytes]" : ""}`,
|
|
72
|
+
)
|
|
62
73
|
} catch {}
|
|
63
74
|
}
|
|
64
75
|
} catch {}
|
package/src/memory/vector.ts
CHANGED
|
@@ -1278,7 +1278,11 @@ export async function searchHybrid(
|
|
|
1278
1278
|
if (rows.length === 0) return []
|
|
1279
1279
|
|
|
1280
1280
|
let queryVec: number[] | null = null
|
|
1281
|
-
|
|
1281
|
+
// F-07: bila semua kandidat hanya memiliki teks (mis. memori manual atau
|
|
1282
|
+
// fallback provider tanpa embedding), vektor query tidak dapat mengubah
|
|
1283
|
+
// skor satu pun. Jangan melakukan DNS/HTTP embedding yang hasilnya tak dipakai.
|
|
1284
|
+
const hasVectorCandidates = rows.some((row) => row.embedding !== null)
|
|
1285
|
+
if (hasVectorCandidates && opts.baseUrl && opts.apiKey) {
|
|
1282
1286
|
const vecs = await embedTexts(opts.baseUrl, opts.apiKey, [query], opts.embeddingModel)
|
|
1283
1287
|
if (vecs?.[0]) queryVec = vecs[0]
|
|
1284
1288
|
}
|
package/src/policy/context.ts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { execFile } from "node:child_process"
|
|
2
|
-
import {
|
|
3
|
-
import { resolve } from "node:path"
|
|
2
|
+
import { readdir, realpath } from "node:fs/promises"
|
|
3
|
+
import { join, resolve } from "node:path"
|
|
4
4
|
import { promisify } from "node:util"
|
|
5
5
|
import type { TokenEstimator } from "#minicore"
|
|
6
6
|
import { DEFAULT_CHARS_PER_TOKEN } from "#minicore/core/tokens.ts"
|
|
7
7
|
import { LIMITS } from "../constants.ts"
|
|
8
8
|
import { GIT_SAFE_BASE } from "../lib/git-hardening.ts"
|
|
9
|
+
import { safeReadFileCapped } from "../lib/safe-open.ts"
|
|
9
10
|
import { resolveTrustedExecutable } from "../lib/trusted-exec.ts"
|
|
10
11
|
import { loadMemoryFiles } from "../memory/files.ts"
|
|
11
12
|
import { loadRepoMap } from "../repo/repomap.ts"
|
|
@@ -259,13 +260,13 @@ export async function buildSystemPrompt(
|
|
|
259
260
|
for (const p of agentFiles) {
|
|
260
261
|
if (signal.aborted) throw new Error("aborted")
|
|
261
262
|
try {
|
|
262
|
-
// Symlink escape (temuan audit #06): AGENTS.md symlink keluar workspace
|
|
263
|
-
// ikut terbaca tanpa ini. Samakan dengan guard rules/ di bawah.
|
|
264
263
|
const full = resolve(cwd, p)
|
|
265
|
-
|
|
266
|
-
const txt = await readFile(full, "utf8")
|
|
264
|
+
const loaded = await safeReadFileCapped(full, cwd, 3000)
|
|
267
265
|
if (signal.aborted) throw new Error("aborted")
|
|
268
|
-
|
|
266
|
+
const body = loaded.truncated
|
|
267
|
+
? `${loaded.text}\n… [truncated: showing first 3000 bytes]`
|
|
268
|
+
: loaded.text
|
|
269
|
+
parts.push(`\n# ${p}\n${cutMarked(body, 3000)}`)
|
|
269
270
|
loadedAgent = true
|
|
270
271
|
if (p === "AGENTS.md") break // prefer AGENTS.md, else collect all
|
|
271
272
|
} catch (e) {
|
|
@@ -275,13 +276,20 @@ export async function buildSystemPrompt(
|
|
|
275
276
|
// Also load steering if not already
|
|
276
277
|
if (!loadedAgent) {
|
|
277
278
|
try {
|
|
278
|
-
const
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
279
|
+
const steeringDir = resolve(cwd, ".minicode/steering")
|
|
280
|
+
// Resolve direktori sebelum enumerasi: junction/reparse yang keluar
|
|
281
|
+
// workspace tidak boleh menjadi sumber instruksi fallback.
|
|
282
|
+
const realSteeringDir = await realpath(steeringDir)
|
|
283
|
+
if (isRealPathOutsideRoot(realSteeringDir, cwd))
|
|
284
|
+
throw new Error("steering directory outside workspace")
|
|
285
|
+
const files = (await readdir(realSteeringDir)).sort().slice(0, 3)
|
|
286
|
+
for (const f of files) {
|
|
282
287
|
try {
|
|
283
|
-
const
|
|
284
|
-
|
|
288
|
+
const loaded = await safeReadFileCapped(join(realSteeringDir, f), cwd, 2000)
|
|
289
|
+
const body = loaded.truncated
|
|
290
|
+
? `${loaded.text}\n… [truncated: showing first 2000 bytes]`
|
|
291
|
+
: loaded.text
|
|
292
|
+
parts.push(`\n# steering file\n${cutMarked(body, 2000)}`)
|
|
285
293
|
} catch {}
|
|
286
294
|
}
|
|
287
295
|
} catch {}
|
|
@@ -22,13 +22,8 @@
|
|
|
22
22
|
// keduanya akan mengubah perilaku recovery yang sudah teruji. Karena itu
|
|
23
23
|
// `journalMutation` dieksplisitkan, bukan disimpulkan.
|
|
24
24
|
//
|
|
25
|
-
//
|
|
26
|
-
//
|
|
27
|
-
// Executor hari ini memperlakukan `code_run` sebagai non-write (bukan anggota
|
|
28
|
-
// WRITE_TOOLS/EXCLUSIVE_TOOLS), sehingga batch membacanya paralel. Mengubahnya
|
|
29
|
-
// menjadi `exclusive` di sini akan mengubah penjadwalan yang sudah teruji, yang
|
|
30
|
-
// bukan tujuan Fase 2. Klasifikasi disamakan dengan perilaku nyata; perbaikan
|
|
31
|
-
// penjadwalan (bila diinginkan) harus menjadi perubahan terpisah dengan bukti.
|
|
25
|
+
// `code_run` mutasi workspace melalui sandbox RW. Karena itu ia harus menjadi
|
|
26
|
+
// exclusive di batch yang juga dapat membaca atau menulis file yang sama.
|
|
32
27
|
|
|
33
28
|
/** Kelas efek samping yang dideklarasikan sebuah tool. */
|
|
34
29
|
export type SideEffectTier =
|
|
@@ -348,11 +343,10 @@ export const TOOL_CONTRACTS: readonly ToolContractMetadata[] = [
|
|
|
348
343
|
idempotent: false,
|
|
349
344
|
journalMutation: false,
|
|
350
345
|
}),
|
|
351
|
-
// Lihat catatan modul: perilaku paralel `code_run` dipertahankan apa adanya.
|
|
352
346
|
C({
|
|
353
347
|
name: "code_run",
|
|
354
348
|
sideEffectTier: "LOCAL_ENV_MUTATION",
|
|
355
|
-
concurrencyClass: "
|
|
349
|
+
concurrencyClass: "exclusive",
|
|
356
350
|
gatedByDefault: false,
|
|
357
351
|
allowedInExplore: false,
|
|
358
352
|
allowedInAutonomous: false,
|
|
@@ -420,7 +414,7 @@ export const TOOL_CONTRACTS: readonly ToolContractMetadata[] = [
|
|
|
420
414
|
C({
|
|
421
415
|
name: "git_commit",
|
|
422
416
|
sideEffectTier: "EXTERNAL_IRREVERSIBLE",
|
|
423
|
-
concurrencyClass: "
|
|
417
|
+
concurrencyClass: "exclusive",
|
|
424
418
|
gatedByDefault: true,
|
|
425
419
|
allowedInExplore: false,
|
|
426
420
|
allowedInAutonomous: false,
|
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
// Hormat offline: gagal fetch = diam. Hormat NO_UPDATE_CHECK=1 / CI=1.
|
|
4
4
|
|
|
5
5
|
import { spawnSync } from "node:child_process"
|
|
6
|
-
import {
|
|
6
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
|
|
7
|
+
import { homedir, tmpdir } from "node:os"
|
|
7
8
|
import { join } from "node:path"
|
|
8
9
|
|
|
9
10
|
const PKG_NAME = "minicode-ai"
|
|
@@ -175,14 +176,38 @@ export async function checkForUpdateFresh(
|
|
|
175
176
|
return isNewer(currentVersion, eff) ? eff : null
|
|
176
177
|
}
|
|
177
178
|
|
|
178
|
-
export type InstallRunner = (
|
|
179
|
+
export type InstallRunner = (
|
|
180
|
+
cmd: string,
|
|
181
|
+
args: string[],
|
|
182
|
+
opts?: { cwd?: string },
|
|
183
|
+
) => { status: number | null }
|
|
179
184
|
|
|
180
|
-
|
|
181
|
-
|
|
185
|
+
const NPM_REGISTRY = "https://registry.npmjs.org/"
|
|
186
|
+
|
|
187
|
+
export function verifyInstalledVersion(expected: string, readVersion: () => string): boolean {
|
|
188
|
+
try {
|
|
189
|
+
return readVersion() === expected
|
|
190
|
+
} catch {
|
|
191
|
+
return false
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const SEMVER_VERSION_RE =
|
|
196
|
+
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Verifikasi versi dari registry (signature + provenance) di prefix sementara,
|
|
200
|
+
* lalu pasang versi persis dari registry yang sama secara global. Skrip paket
|
|
201
|
+
* tidak dijalankan. Npm lama atau paket tanpa bukti registry tepercaya = gagal
|
|
202
|
+
* tertutup; pemanggil tetap melanjutkan versi yang sedang berjalan.
|
|
203
|
+
*/
|
|
204
|
+
export function installUpdate(version: string, runner?: InstallRunner): boolean {
|
|
205
|
+
if (version.length > 128 || !SEMVER_VERSION_RE.test(version)) return false
|
|
206
|
+
let verifyRoot: string | undefined
|
|
182
207
|
try {
|
|
183
208
|
const run: InstallRunner =
|
|
184
209
|
runner ??
|
|
185
|
-
((cmd, args) => {
|
|
210
|
+
((cmd, args, opts) => {
|
|
186
211
|
// Windows: npm adalah .cmd → butuh shell; stdio inherit agar user
|
|
187
212
|
// melihat progres install (interaktif, bukan CI).
|
|
188
213
|
// Timeout 120 dtk: tanpa ini spawnSync memblokir event-loop selamanya
|
|
@@ -192,12 +217,64 @@ export function installUpdate(runner?: InstallRunner): boolean {
|
|
|
192
217
|
const r = spawnSync(cmd, args, {
|
|
193
218
|
stdio: "inherit",
|
|
194
219
|
shell: process.platform === "win32",
|
|
220
|
+
...(opts?.cwd ? { cwd: opts.cwd } : {}),
|
|
195
221
|
timeout: 120_000,
|
|
196
222
|
})
|
|
197
223
|
return { status: typeof r.status === "number" ? r.status : null }
|
|
198
224
|
})
|
|
199
|
-
|
|
225
|
+
verifyRoot = mkdtempSync(join(tmpdir(), "minicode-update-verify-"))
|
|
226
|
+
writeFileSync(
|
|
227
|
+
join(verifyRoot, "package.json"),
|
|
228
|
+
JSON.stringify({ name: "minicode-update-verification", version: "1.0.0", private: true }),
|
|
229
|
+
"utf8",
|
|
230
|
+
)
|
|
231
|
+
const verifiedInstall = run(
|
|
232
|
+
"npm",
|
|
233
|
+
[
|
|
234
|
+
"install",
|
|
235
|
+
"--ignore-scripts",
|
|
236
|
+
"--no-audit",
|
|
237
|
+
"--save-exact",
|
|
238
|
+
"--package-lock=true",
|
|
239
|
+
"--registry",
|
|
240
|
+
NPM_REGISTRY,
|
|
241
|
+
`${PKG_NAME}@${version}`,
|
|
242
|
+
],
|
|
243
|
+
{ cwd: verifyRoot },
|
|
244
|
+
)
|
|
245
|
+
if (verifiedInstall.status !== 0) return false
|
|
246
|
+
const lock = JSON.parse(readFileSync(join(verifyRoot, "package-lock.json"), "utf8")) as {
|
|
247
|
+
packages?: Record<string, unknown>
|
|
248
|
+
}
|
|
249
|
+
const installedPackages = Object.keys(lock.packages ?? {}).filter((path) =>
|
|
250
|
+
path.startsWith("node_modules/"),
|
|
251
|
+
)
|
|
252
|
+
// Global npm install does not consume this local lockfile. Today this CLI
|
|
253
|
+
// has no runtime dependencies; refuse silent graph drift until updater can
|
|
254
|
+
// install and verify every locked dependency identically.
|
|
255
|
+
if (installedPackages.length !== 1 || installedPackages[0] !== `node_modules/${PKG_NAME}`)
|
|
256
|
+
return false
|
|
257
|
+
const signatures = run("npm", ["audit", "signatures", "--registry", NPM_REGISTRY], {
|
|
258
|
+
cwd: verifyRoot,
|
|
259
|
+
})
|
|
260
|
+
if (signatures.status !== 0) return false
|
|
261
|
+
return (
|
|
262
|
+
run("npm", [
|
|
263
|
+
"install",
|
|
264
|
+
"-g",
|
|
265
|
+
"--ignore-scripts",
|
|
266
|
+
"--registry",
|
|
267
|
+
NPM_REGISTRY,
|
|
268
|
+
`${PKG_NAME}@${version}`,
|
|
269
|
+
]).status === 0
|
|
270
|
+
)
|
|
200
271
|
} catch {
|
|
201
272
|
return false
|
|
273
|
+
} finally {
|
|
274
|
+
if (verifyRoot && existsSync(verifyRoot)) {
|
|
275
|
+
try {
|
|
276
|
+
rmSync(verifyRoot, { recursive: true, force: true })
|
|
277
|
+
} catch {}
|
|
278
|
+
}
|
|
202
279
|
}
|
|
203
280
|
}
|
package/src/policy/usage.ts
CHANGED
|
@@ -237,10 +237,8 @@ export function watchContextWindowLimit(opts: {
|
|
|
237
237
|
bus: EventBus
|
|
238
238
|
/** Batas window konteks (W). Bila 0/undefined → no-op. */
|
|
239
239
|
windowTokens: number
|
|
240
|
-
/**
|
|
241
|
-
|
|
242
|
-
/** Token output turn berjalan (dari usage collector). */
|
|
243
|
-
getOutputTokens: () => number
|
|
240
|
+
/** Snapshot token request provider aktif; window berlaku per request. */
|
|
241
|
+
getRequestTokens: () => { inputTokens: number; outputTokens: number } | null
|
|
244
242
|
onOver: (allowed: number, actual: number) => void
|
|
245
243
|
}): () => void {
|
|
246
244
|
const W = opts.windowTokens
|
|
@@ -248,9 +246,12 @@ export function watchContextWindowLimit(opts: {
|
|
|
248
246
|
let fired = false
|
|
249
247
|
const check = () => {
|
|
250
248
|
if (fired) return
|
|
251
|
-
const
|
|
252
|
-
|
|
253
|
-
|
|
249
|
+
const request = opts.getRequestTokens()
|
|
250
|
+
// Belum ada usage untuk request aktif: jangan memakai snapshot request
|
|
251
|
+
// sebelumnya atau total token kumulatif turn sebagai pengganti.
|
|
252
|
+
if (!request) return
|
|
253
|
+
const allowedOutput = Math.max(256, Math.floor(W - request.inputTokens))
|
|
254
|
+
const output = request.outputTokens
|
|
254
255
|
if (output > allowedOutput) {
|
|
255
256
|
fired = true
|
|
256
257
|
opts.onOver(allowedOutput, output)
|
|
@@ -556,6 +557,15 @@ export function createUsageCollector(
|
|
|
556
557
|
getTurnCount: () => sessionTurns,
|
|
557
558
|
/** [Fase 3 / CTX-03] Laporan token terakhir dari provider untuk kalibrasi. */
|
|
558
559
|
lastProviderTokens: () => lastProviderUsage,
|
|
560
|
+
/** Snapshot request provider aktif; null di antara request agar watcher
|
|
561
|
+
* window tidak keliru memakai total kumulatif turn/sesi. */
|
|
562
|
+
currentRequestTokens: () =>
|
|
563
|
+
pendingRequestTokens
|
|
564
|
+
? {
|
|
565
|
+
inputTokens: pendingRequestTokens.inputTokens,
|
|
566
|
+
outputTokens: pendingRequestTokens.outputTokens,
|
|
567
|
+
}
|
|
568
|
+
: null,
|
|
559
569
|
modelUsed: () => ({ effective: effectiveModel, provider: effectiveProvider }),
|
|
560
570
|
reset: () => {
|
|
561
571
|
// [Fase 7 / Live #2] reset() = batas turn. `pendingRequestTokens` masih
|
|
@@ -355,6 +355,11 @@ export function createPresentationAdapter(
|
|
|
355
355
|
let currentStep = 0
|
|
356
356
|
let reasoningText = ""
|
|
357
357
|
let reasoningTruncated = false
|
|
358
|
+
let activeProviderAttempt: {
|
|
359
|
+
id: number
|
|
360
|
+
reasoningLength: number
|
|
361
|
+
reasoningTruncated: boolean
|
|
362
|
+
} | null = null
|
|
358
363
|
const toolStarts = new Map<string, number>()
|
|
359
364
|
const openTools = new Map<
|
|
360
365
|
string,
|
|
@@ -445,6 +450,7 @@ export function createPresentationAdapter(
|
|
|
445
450
|
})
|
|
446
451
|
reasoningText = ""
|
|
447
452
|
reasoningTruncated = false
|
|
453
|
+
activeProviderAttempt = null
|
|
448
454
|
}
|
|
449
455
|
// Pemetaan task domain → plan presentational. Sengaja memakai
|
|
450
456
|
// `normalizeTodos` (pemilik semantik domain) alih-alih memetakan status
|
|
@@ -729,6 +735,7 @@ export function createPresentationAdapter(
|
|
|
729
735
|
currentStep = 0
|
|
730
736
|
reasoningText = ""
|
|
731
737
|
reasoningTruncated = false
|
|
738
|
+
activeProviderAttempt = null
|
|
732
739
|
turnStartTs = Date.now()
|
|
733
740
|
resetTurnCounters()
|
|
734
741
|
publish({
|
|
@@ -1023,10 +1030,59 @@ export function createPresentationAdapter(
|
|
|
1023
1030
|
|
|
1024
1031
|
sub("provider:text", (e: { text?: unknown }) => {
|
|
1025
1032
|
if (typeof e?.text !== "string" || !e.text) return
|
|
1026
|
-
publish({
|
|
1033
|
+
publish({
|
|
1034
|
+
...base(currentTurn),
|
|
1035
|
+
type: "model.delta",
|
|
1036
|
+
turnId: currentTurn,
|
|
1037
|
+
delta: e.text,
|
|
1038
|
+
...(activeProviderAttempt ? { attemptId: activeProviderAttempt.id } : {}),
|
|
1039
|
+
})
|
|
1027
1040
|
})
|
|
1028
1041
|
|
|
1029
1042
|
sub("provider:extension", (e: { kind?: unknown; data?: unknown }) => {
|
|
1043
|
+
if (e?.kind === "minicode:attempt") {
|
|
1044
|
+
const data = e.data as {
|
|
1045
|
+
phase?: unknown
|
|
1046
|
+
attemptId?: unknown
|
|
1047
|
+
hadVisibleOutput?: unknown
|
|
1048
|
+
} | null
|
|
1049
|
+
if (
|
|
1050
|
+
typeof data?.attemptId === "number" &&
|
|
1051
|
+
Number.isSafeInteger(data.attemptId) &&
|
|
1052
|
+
data.attemptId > 0
|
|
1053
|
+
) {
|
|
1054
|
+
if (data.phase === "started") {
|
|
1055
|
+
activeProviderAttempt = {
|
|
1056
|
+
id: data.attemptId,
|
|
1057
|
+
reasoningLength: reasoningText.length,
|
|
1058
|
+
reasoningTruncated,
|
|
1059
|
+
}
|
|
1060
|
+
} else if (activeProviderAttempt?.id === data.attemptId && data.phase === "completed") {
|
|
1061
|
+
activeProviderAttempt = null
|
|
1062
|
+
} else if (activeProviderAttempt?.id === data.attemptId && data.phase === "invalidated") {
|
|
1063
|
+
reasoningText = reasoningText.slice(0, activeProviderAttempt.reasoningLength)
|
|
1064
|
+
reasoningTruncated = activeProviderAttempt.reasoningTruncated
|
|
1065
|
+
activeProviderAttempt = null
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
if (
|
|
1069
|
+
data?.phase === "invalidated" &&
|
|
1070
|
+
data.hadVisibleOutput === true &&
|
|
1071
|
+
typeof data.attemptId === "number" &&
|
|
1072
|
+
Number.isSafeInteger(data.attemptId)
|
|
1073
|
+
) {
|
|
1074
|
+
publish({
|
|
1075
|
+
...base(currentTurn),
|
|
1076
|
+
type: "diagnostic.raised",
|
|
1077
|
+
turnId: currentTurn,
|
|
1078
|
+
category: "PROVIDER_ATTEMPT_INVALIDATED",
|
|
1079
|
+
severity: "warning",
|
|
1080
|
+
message: `Provider attempt ${data.attemptId} streamed partial output; it was discarded and is excluded from the final answer.`,
|
|
1081
|
+
attemptId: data.attemptId,
|
|
1082
|
+
})
|
|
1083
|
+
}
|
|
1084
|
+
return
|
|
1085
|
+
}
|
|
1030
1086
|
if (e?.kind === "error") {
|
|
1031
1087
|
const data = e.data as { message?: unknown; error?: unknown } | null
|
|
1032
1088
|
const message =
|
|
@@ -1055,7 +1111,13 @@ export function createPresentationAdapter(
|
|
|
1055
1111
|
} else {
|
|
1056
1112
|
reasoningTruncated = true
|
|
1057
1113
|
}
|
|
1058
|
-
publish({
|
|
1114
|
+
publish({
|
|
1115
|
+
...base(currentTurn),
|
|
1116
|
+
type: "reasoning.delta",
|
|
1117
|
+
turnId: currentTurn,
|
|
1118
|
+
delta: text,
|
|
1119
|
+
...(activeProviderAttempt ? { attemptId: activeProviderAttempt.id } : {}),
|
|
1120
|
+
})
|
|
1059
1121
|
})
|
|
1060
1122
|
|
|
1061
1123
|
sub("context:compacted", (e: { reason?: unknown }) => {
|
|
@@ -196,6 +196,8 @@ export interface TurnCancelledEvent extends Base {
|
|
|
196
196
|
export interface ModelDeltaEvent extends Base {
|
|
197
197
|
type: "model.delta"
|
|
198
198
|
delta: string
|
|
199
|
+
/** Guard-local provider stream attempt; invalidation diagnostics reference it. */
|
|
200
|
+
attemptId?: number
|
|
199
201
|
}
|
|
200
202
|
export interface ModelCompletedEvent extends Base {
|
|
201
203
|
type: "model.completed"
|
|
@@ -206,6 +208,8 @@ export interface ModelCompletedEvent extends Base {
|
|
|
206
208
|
export interface ReasoningDeltaEvent extends Base {
|
|
207
209
|
type: "reasoning.delta"
|
|
208
210
|
delta: string
|
|
211
|
+
/** Guard-local provider stream attempt; failed reasoning is rolled back. */
|
|
212
|
+
attemptId?: number
|
|
209
213
|
}
|
|
210
214
|
export interface ReasoningCompletedEvent extends Base {
|
|
211
215
|
type: "reasoning.completed"
|
|
@@ -374,6 +378,8 @@ export interface DiagnosticRaisedEvent extends Base {
|
|
|
374
378
|
category: string
|
|
375
379
|
severity: SemanticSeverity
|
|
376
380
|
message: string
|
|
381
|
+
/** Provider attempt whose live output was invalidated, when applicable. */
|
|
382
|
+
attemptId?: number
|
|
377
383
|
cause?: string
|
|
378
384
|
action?: string
|
|
379
385
|
}
|
|
@@ -546,6 +546,7 @@ export interface MachineEventInput {
|
|
|
546
546
|
summary?: unknown
|
|
547
547
|
promptRef?: string
|
|
548
548
|
delta?: unknown
|
|
549
|
+
attemptId?: unknown
|
|
549
550
|
text?: unknown
|
|
550
551
|
truncated?: boolean
|
|
551
552
|
toolSummary?: unknown
|
|
@@ -780,6 +781,7 @@ export function machinePayload(event: MachineEventInput): Record<string, unknown
|
|
|
780
781
|
put("truncated", typeof event.truncated === "boolean" ? event.truncated : undefined)
|
|
781
782
|
put("toolSummary", asString(event.toolSummary))
|
|
782
783
|
put("durationMs", asNumber(event.durationMs))
|
|
784
|
+
put("attemptId", asNumber(event.attemptId))
|
|
783
785
|
put("tsStart", asNumber(event.tsStart))
|
|
784
786
|
put(
|
|
785
787
|
"paths",
|