minicode-ai 0.27.0 → 0.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli/args.ts +120 -16
- package/cli/commands/acp.ts +38 -28
- package/cli/commands/auth.ts +17 -17
- package/cli/commands/config.ts +65 -66
- package/cli/commands/daemon.ts +44 -16
- package/cli/commands/doctor.ts +11 -12
- package/cli/commands/exec.ts +35 -73
- package/cli/commands/mcp.ts +25 -8
- package/cli/commands/memory.ts +16 -24
- package/cli/commands/openwork.ts +6 -2
- package/cli/commands/pricing.ts +14 -12
- package/cli/commands/providers.ts +36 -57
- package/cli/commands/sessions.ts +24 -18
- package/cli/commands/skills.ts +33 -18
- package/cli/commands/stats.ts +15 -30
- package/cli/commands.ts +73 -44
- package/cli/context-command-run.ts +30 -18
- package/cli/index.ts +48 -98
- package/cli/model-manager.ts +7 -2
- package/cli/provider-manager.ts +33 -18
- package/cli/router.ts +41 -12
- package/cli/setup.ts +246 -123
- package/cli/tui.ts +303 -100
- package/docs/TERMINAL_CONTRACT.md +254 -69
- package/docs/UI_RENDER_PIPELINE.md +9 -1
- package/docs/agents.md +2 -2
- package/docs/architecture.md +3 -3
- package/docs/choosing-mode.md +7 -9
- package/docs/cli.md +3 -5
- package/docs/environment.md +1 -2
- package/docs/policy-sandbox.md +3 -3
- package/docs/repl.md +2 -2
- package/docs/tools.md +1 -1
- package/package.json +1 -1
- package/src/app/mentions.ts +60 -13
- package/src/app/rag-layer.ts +17 -20
- package/src/app/session.ts +119 -66
- package/src/app/tool-layer.ts +12 -17
- package/src/config.ts +64 -104
- package/src/constants.ts +4 -6
- package/src/daemon/capability.ts +8 -1
- package/src/daemon/control.ts +3 -2
- package/src/daemon/server.ts +57 -0
- package/src/hooks/run.ts +73 -41
- package/src/lib/db-path.ts +47 -0
- package/src/lib/process-tree.ts +62 -0
- package/src/lib/public-http.ts +88 -23
- package/src/lib/trusted-exec.ts +48 -1
- package/src/lsp/client.ts +62 -17
- package/src/mcp/client.ts +85 -38
- package/src/mcp/http-transport.ts +28 -16
- package/src/mcp/transport.ts +42 -6
- package/src/memory/files.ts +164 -134
- package/src/memory/vector.ts +371 -420
- package/src/policy/approval-binding.ts +122 -45
- package/src/policy/bash-guard.ts +18 -7
- package/src/policy/compaction.ts +51 -18
- package/src/policy/context-window.ts +31 -8
- package/src/policy/context.ts +62 -36
- package/src/policy/executor.ts +17 -7
- package/src/policy/microcompact.ts +4 -3
- package/src/policy/no-progress.ts +103 -22
- package/src/policy/permission.ts +36 -12
- package/src/policy/tool-contract.ts +74 -416
- package/src/policy/usage.ts +24 -2
- package/src/policy/verifier.ts +50 -2
- package/src/policy/work-mode.ts +28 -54
- package/src/presentation/adapter.ts +24 -16
- package/src/providers/provision.ts +6 -56
- package/src/providers/responses.ts +1 -0
- package/src/runtime/execution-journal.ts +4 -29
- package/src/sandbox/docker.ts +58 -34
- package/src/sandbox/mask.ts +157 -0
- package/src/sandbox/os.ts +107 -73
- package/src/session/authority.ts +29 -10
- package/src/session/context-projection.ts +6 -5
- package/src/session/open-work.ts +26 -3
- package/src/session/persistence.ts +25 -58
- package/src/session/verification.ts +170 -20
- package/src/skills/loader.ts +31 -16
- package/src/task/production-scheduler.ts +13 -1
- package/src/task/store.ts +20 -37
- package/src/telemetry/trace.ts +27 -0
- package/src/tools/ask_user.ts +1 -13
- package/src/tools/bash.ts +27 -92
- package/src/tools/code_run.ts +1 -1
- package/src/tools/context.ts +133 -0
- package/src/tools/delete_file.ts +3 -2
- package/src/tools/edit.ts +37 -72
- package/src/tools/git.ts +86 -9
- package/src/tools/glob.ts +26 -51
- package/src/tools/grep.ts +67 -57
- package/src/tools/hashline.ts +4 -0
- package/src/tools/lsp.ts +11 -8
- package/src/tools/mcp_call.ts +9 -6
- package/src/tools/memory.ts +56 -33
- package/src/tools/move_file.ts +36 -10
- package/src/tools/patch.ts +13 -21
- package/src/tools/read_file.ts +18 -25
- package/src/tools/read_image.ts +35 -33
- package/src/tools/submit_result.ts +29 -8
- package/src/tools/task.ts +74 -17
- package/src/tools/todo.ts +181 -74
- package/src/tools/web_fetch.ts +42 -2
- package/src/tools/web_search.ts +47 -8
- package/src/ui/approval/prompt.ts +206 -47
- package/src/ui/assistant/turn-status.ts +14 -5
- package/src/ui/footer.ts +4 -4
- package/src/ui/i18n/en.ts +47 -23
- package/src/ui/i18n/id.ts +76 -51
- package/src/ui/input/input.ts +4 -3
- package/src/ui/input/prompt-engine.ts +35 -5
- package/src/ui/render/activity-panel.ts +4 -2
- package/src/ui/render/hint.ts +7 -4
- package/src/ui/render/list.ts +32 -0
- package/src/ui/render/markdown.ts +6 -3
- package/src/ui/render/notice.ts +19 -0
- package/src/ui/render/table-grid.ts +7 -8
- package/src/ui/render/theme.ts +113 -39
- package/src/ui/runtime/screen.ts +74 -10
- package/src/ui/runtime/spinner.ts +19 -6
- package/src/ui/screens/dialog.ts +19 -1
- package/src/ui/screens/form.ts +80 -35
- package/src/ui/screens/model-manager.ts +82 -61
- package/src/ui/screens/output-window.ts +263 -0
- package/src/ui/screens/picker.ts +94 -81
- package/src/ui/screens/provider-manager.ts +100 -69
- package/src/ui/screens/wizard.ts +117 -28
- package/src/ui/tui/app.ts +196 -33
- package/src/ui/tui/transcript.ts +154 -25
- package/vendor/minicore/src/core/executor.ts +2 -0
- package/vendor/minicore/src/core/loop.ts +17 -6
- package/vendor/minicore/src/core/session.ts +3 -0
- package/vendor/minicore/src/core/tool.ts +1 -0
- package/vendor/minicore/src/providers/openai-compat.ts +28 -19
package/src/tools/todo.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { rmSync } from "node:fs"
|
|
1
2
|
import { mkdir, readFile } from "node:fs/promises"
|
|
2
3
|
import { resolve } from "node:path"
|
|
3
4
|
import type { Tool } from "#minicore"
|
|
@@ -7,11 +8,11 @@ import { sanitizeSessionPart } from "../lib/session-id.ts"
|
|
|
7
8
|
import { isJournalHealthy, loadJournal, mutationsSinceTurn } from "../session/journal.ts"
|
|
8
9
|
import {
|
|
9
10
|
checkWorkspaceIntegrity,
|
|
10
|
-
|
|
11
|
+
collectSessionModifiedFiles,
|
|
11
12
|
detectEvaluationTampering,
|
|
12
13
|
} from "../session/verification.ts"
|
|
13
14
|
import { type CanonicalAssignmentTable, encodeCanonicalAssignments } from "../task/assignment.ts"
|
|
14
|
-
import { isTaskId, TaskError } from "../task/model.ts"
|
|
15
|
+
import { isTaskId, type Task, TaskError, type TaskStatus } from "../task/model.ts"
|
|
15
16
|
import { TaskStore } from "../task/store.ts"
|
|
16
17
|
import { hasCanonicalIdentity, hasCanonicalTasks, synchronizeCanonicalTasks } from "../task/sync.ts"
|
|
17
18
|
import { requireToolCwd } from "./context.ts"
|
|
@@ -137,26 +138,28 @@ export async function resolveFreshEvidence(
|
|
|
137
138
|
// telah di-commit ke jurnal sesi ini. Best-effort pada jurnal absent/empty/
|
|
138
139
|
// corrupt agar kompatibilitas legacy turn-less & sesi tanpa jurnal tetap utuh.
|
|
139
140
|
const loaded = await loadJournal(sessionId, cwd).catch(() => null)
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
141
|
+
const modified = await collectSessionModifiedFiles(
|
|
142
|
+
sessionId,
|
|
143
|
+
cwd,
|
|
144
|
+
loaded?.status === "valid" ? loaded.records : undefined,
|
|
145
|
+
)
|
|
146
|
+
if (modified.length > 0) {
|
|
147
|
+
const integrity = await checkWorkspaceIntegrity(modified, cwd)
|
|
148
|
+
if (!integrity.ok) {
|
|
149
|
+
return {
|
|
150
|
+
verdict: "failed",
|
|
151
|
+
detail: integrity.summary,
|
|
152
|
+
...(base.requireVerified ? { requireVerified: true } : {}),
|
|
150
153
|
}
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
}
|
|
154
|
+
}
|
|
155
|
+
// [Fase 6A / ACE-02] Tamper guard fail-closed: evaluator/gate yang
|
|
156
|
+
// disentuh membuat SEMUA klaim completion tak bisa dipercaya.
|
|
157
|
+
const tamper = await detectEvaluationTampering(modified, cwd)
|
|
158
|
+
if (tamper.tampered) {
|
|
159
|
+
return {
|
|
160
|
+
verdict: "failed",
|
|
161
|
+
detail: `EVALUATOR_TAMPER_ATTEMPT: ${tamper.reason}`,
|
|
162
|
+
...(base.requireVerified ? { requireVerified: true } : {}),
|
|
160
163
|
}
|
|
161
164
|
}
|
|
162
165
|
}
|
|
@@ -195,26 +198,28 @@ export async function resolveFreshEvidence(
|
|
|
195
198
|
// [Fase 3 / LOOP-INV-12, LOOP-G21] Tier 1 integrity check sebelum mengizinkan
|
|
196
199
|
// bukti `passed` mengunci `COMPLETED`.
|
|
197
200
|
const loaded = await loadJournal(sessionId, cwd).catch(() => null)
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
201
|
+
const modified = await collectSessionModifiedFiles(
|
|
202
|
+
sessionId,
|
|
203
|
+
cwd,
|
|
204
|
+
loaded?.status === "valid" ? loaded.records : undefined,
|
|
205
|
+
)
|
|
206
|
+
if (modified.length > 0) {
|
|
207
|
+
const integrity = await checkWorkspaceIntegrity(modified, cwd)
|
|
208
|
+
if (!integrity.ok) {
|
|
209
|
+
return {
|
|
210
|
+
verdict: "failed",
|
|
211
|
+
detail: integrity.summary,
|
|
212
|
+
...(base.requireVerified ? { requireVerified: true } : {}),
|
|
208
213
|
}
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
}
|
|
214
|
+
}
|
|
215
|
+
// [Fase 6A / ACE-02] Tamper guard: bukti `passed` batal bila evaluator
|
|
216
|
+
// atau test diubah untuk meloloskan verifikasi.
|
|
217
|
+
const tamper = await detectEvaluationTampering(modified, cwd)
|
|
218
|
+
if (tamper.tampered) {
|
|
219
|
+
return {
|
|
220
|
+
verdict: "failed",
|
|
221
|
+
detail: `EVALUATOR_TAMPER_ATTEMPT: ${tamper.reason}`,
|
|
222
|
+
...(base.requireVerified ? { requireVerified: true } : {}),
|
|
218
223
|
}
|
|
219
224
|
}
|
|
220
225
|
}
|
|
@@ -258,20 +263,86 @@ function legacyPlanPath(sessionId: string, cwd: string): string {
|
|
|
258
263
|
// Audit #13 chain 28: todo + plan snapshot adalah state milik sesi —
|
|
259
264
|
// deleteSession wajib menghapusnya agar konten rencana tak bertahan sebagai
|
|
260
265
|
// residual reachable pasca-hapus. Best-effort (kegagalan tak menggagalkan hapus).
|
|
261
|
-
export
|
|
262
|
-
const { rm } = await import("node:fs/promises")
|
|
263
|
-
// Both are removed: canonical (N2) and legacy, because old files can still
|
|
264
|
-
// exist in a workspace that was never rewritten after the upgrade.
|
|
266
|
+
export function deleteTodoFilesSync(sessionId: string, cwd: string): void {
|
|
265
267
|
for (const p of [
|
|
266
268
|
todoPath(sessionId, cwd),
|
|
267
269
|
legacyTodoPath(sessionId, cwd),
|
|
268
270
|
planPath(sessionId, cwd),
|
|
269
271
|
legacyPlanPath(sessionId, cwd),
|
|
270
272
|
]) {
|
|
271
|
-
|
|
273
|
+
try {
|
|
274
|
+
rmSync(p, { force: true })
|
|
275
|
+
} catch {}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
export async function deleteTodoFiles(sessionId: string, cwd: string): Promise<void> {
|
|
280
|
+
deleteTodoFilesSync(sessionId, cwd)
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
export function taskStatusToTodoStatus(status: TaskStatus): TodoStatus {
|
|
284
|
+
switch (status) {
|
|
285
|
+
case "COMPLETED":
|
|
286
|
+
return "completed"
|
|
287
|
+
case "CANCELLED":
|
|
288
|
+
return "cancelled"
|
|
289
|
+
case "BLOCKED":
|
|
290
|
+
return "blocked"
|
|
291
|
+
case "IN_PROGRESS":
|
|
292
|
+
case "VERIFYING":
|
|
293
|
+
return "in_progress"
|
|
294
|
+
default:
|
|
295
|
+
return "pending"
|
|
272
296
|
}
|
|
273
297
|
}
|
|
274
298
|
|
|
299
|
+
export async function syncTodoViewsFromTaskStore(
|
|
300
|
+
sessionId: string,
|
|
301
|
+
cwd: string,
|
|
302
|
+
): Promise<TodoItem[] | null> {
|
|
303
|
+
const tasks = new TaskStore(cwd).listTasks(sessionId)
|
|
304
|
+
if (!tasks.length) return null
|
|
305
|
+
const mapped: TodoItem[] = [...tasks]
|
|
306
|
+
.sort((a, b) => a.order - b.order || a.id.localeCompare(b.id))
|
|
307
|
+
.map((t: Task) => {
|
|
308
|
+
const status = taskStatusToTodoStatus(t.status)
|
|
309
|
+
return {
|
|
310
|
+
content: t.title,
|
|
311
|
+
status,
|
|
312
|
+
...(status === "blocked" ? { blockedReason: t.blockedReason ?? "blocked" } : {}),
|
|
313
|
+
taskId: t.id,
|
|
314
|
+
}
|
|
315
|
+
})
|
|
316
|
+
await saveTodos(sessionId, mapped, cwd)
|
|
317
|
+
await savePlanSnapshot(sessionId, mapped, cwd).catch(() => {})
|
|
318
|
+
return mapped
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
const GLYPH_TO_STATUS: Record<string, TodoStatus> = {
|
|
322
|
+
" ": "pending",
|
|
323
|
+
"~": "in_progress",
|
|
324
|
+
x: "completed",
|
|
325
|
+
"-": "cancelled",
|
|
326
|
+
"!": "blocked",
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
export function extractCommittedTodoStatuses(
|
|
330
|
+
resultContent: unknown,
|
|
331
|
+
expectedCount: number,
|
|
332
|
+
): TodoStatus[] | undefined {
|
|
333
|
+
if (typeof resultContent !== "string" || expectedCount <= 0) return undefined
|
|
334
|
+
const lines = resultContent.split("\n")
|
|
335
|
+
const headerIdx = lines.findIndex((l) => /^todos \d+\/\d+/.test(l))
|
|
336
|
+
if (headerIdx === -1) return undefined
|
|
337
|
+
const out: TodoStatus[] = []
|
|
338
|
+
for (let i = headerIdx + 1; i < lines.length && out.length < expectedCount; i++) {
|
|
339
|
+
const st = GLYPH_TO_STATUS[lines[i]!.match(/^ {2}\[([ ~x!-])\] /)?.[1] ?? ""]
|
|
340
|
+
if (!st) break
|
|
341
|
+
out.push(st)
|
|
342
|
+
}
|
|
343
|
+
return out.length === expectedCount ? out : undefined
|
|
344
|
+
}
|
|
345
|
+
|
|
275
346
|
/** Sanitasi + batasi daftar + terapkan kebijakan completion. Diekspor untuk test.
|
|
276
347
|
*
|
|
277
348
|
* `evidence` default = `currentCompletionEvidence()` (sumber yang disuntik
|
|
@@ -297,29 +368,17 @@ export function applyCompletionPolicy(
|
|
|
297
368
|
opts?: { requireVerified?: boolean },
|
|
298
369
|
): TodoItem[] | null {
|
|
299
370
|
const requireVerified = opts?.requireVerified === true || evidence.requireVerified === true
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
)
|
|
312
|
-
}
|
|
313
|
-
if (requireVerified && evidence.verdict === "unverified") {
|
|
314
|
-
if (!list.some((t) => t.status === "completed")) return null
|
|
315
|
-
const reason =
|
|
316
|
-
evidence.detail?.trim().slice(0, 300) ||
|
|
317
|
-
"verification required: run verifier before marking completed"
|
|
318
|
-
return list.map((t) =>
|
|
319
|
-
t.status === "completed" ? { ...t, status: "blocked" as const, blockedReason: reason } : t,
|
|
320
|
-
)
|
|
321
|
-
}
|
|
322
|
-
return null
|
|
371
|
+
const fallbackReason =
|
|
372
|
+
evidence.verdict === "failed" || evidence.verdict === "stale"
|
|
373
|
+
? `verification ${evidence.verdict}`
|
|
374
|
+
: requireVerified && evidence.verdict === "unverified"
|
|
375
|
+
? "verification required: run verifier before marking completed"
|
|
376
|
+
: null
|
|
377
|
+
if (!fallbackReason || !list.some((t) => t.status === "completed")) return null
|
|
378
|
+
const reason = evidence.detail?.trim().slice(0, 300) || fallbackReason
|
|
379
|
+
return list.map((t) =>
|
|
380
|
+
t.status === "completed" ? { ...t, status: "blocked" as const, blockedReason: reason } : t,
|
|
381
|
+
)
|
|
323
382
|
}
|
|
324
383
|
|
|
325
384
|
export function normalizeTodos(
|
|
@@ -458,6 +517,7 @@ export async function reconcileCompletionEvidence(
|
|
|
458
517
|
sessionId: string,
|
|
459
518
|
cwd: string,
|
|
460
519
|
evidence: CompletionEvidence,
|
|
520
|
+
opts: { syncTaskStore?: boolean } = {},
|
|
461
521
|
): Promise<TodoItem[] | null> {
|
|
462
522
|
// `stale` diperlakukan seperti `failed` untuk otorisasi (tolak klaim),
|
|
463
523
|
// dengan label + alasan basi dipertahankan apa adanya.
|
|
@@ -465,6 +525,55 @@ export async function reconcileCompletionEvidence(
|
|
|
465
525
|
try {
|
|
466
526
|
const current = await loadTodos(sessionId, cwd)
|
|
467
527
|
const next = applyCompletionPolicy(current, evidence)
|
|
528
|
+
const canonical = opts.syncTaskStore === true && hasCanonicalTasks(cwd, sessionId)
|
|
529
|
+
let canonicalChanged = false
|
|
530
|
+
if (canonical) {
|
|
531
|
+
const store = new TaskStore(cwd)
|
|
532
|
+
const outcome = {
|
|
533
|
+
ok: false as const,
|
|
534
|
+
verdict: evidence.verdict,
|
|
535
|
+
...(evidence.detail ? { detail: evidence.detail } : {}),
|
|
536
|
+
summary: evidence.detail?.trim().slice(0, 300) || `verification ${evidence.verdict}`,
|
|
537
|
+
}
|
|
538
|
+
const blockedReason =
|
|
539
|
+
evidence.detail?.trim().slice(0, 300) ||
|
|
540
|
+
(evidence.verdict === "stale" ? "verification stale" : "verification failed")
|
|
541
|
+
store.withTransaction((tx) => {
|
|
542
|
+
const tasks = tx.listTasks(sessionId)
|
|
543
|
+
for (const t of tasks) {
|
|
544
|
+
if (t.status === "VERIFYING") {
|
|
545
|
+
tx.completeTaskVerification(sessionId, t.id, outcome)
|
|
546
|
+
canonicalChanged = true
|
|
547
|
+
continue
|
|
548
|
+
}
|
|
549
|
+
const jsonItem = (next ?? current).find((it) => it.taskId === t.id)
|
|
550
|
+
if (
|
|
551
|
+
jsonItem?.status === "blocked" &&
|
|
552
|
+
t.status !== "BLOCKED" &&
|
|
553
|
+
t.status !== "CANCELLED"
|
|
554
|
+
) {
|
|
555
|
+
tx.patchTask(
|
|
556
|
+
sessionId,
|
|
557
|
+
t.id,
|
|
558
|
+
{
|
|
559
|
+
status: "BLOCKED",
|
|
560
|
+
blockedReason: jsonItem.blockedReason ?? blockedReason,
|
|
561
|
+
verification: {
|
|
562
|
+
verdict: "failed",
|
|
563
|
+
...(evidence.detail ? { detail: evidence.detail.slice(0, 300) } : {}),
|
|
564
|
+
checkedAt: new Date().toISOString(),
|
|
565
|
+
},
|
|
566
|
+
},
|
|
567
|
+
{ allowReopen: t.status === "COMPLETED" },
|
|
568
|
+
)
|
|
569
|
+
canonicalChanged = true
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
})
|
|
573
|
+
}
|
|
574
|
+
if (canonicalChanged) {
|
|
575
|
+
return await syncTodoViewsFromTaskStore(sessionId, cwd)
|
|
576
|
+
}
|
|
468
577
|
if (!next) return null
|
|
469
578
|
await saveTodos(sessionId, next, cwd)
|
|
470
579
|
await savePlanSnapshot(sessionId, next, cwd).catch(() => {})
|
|
@@ -583,7 +692,7 @@ export const todoWriteTool: Tool = {
|
|
|
583
692
|
properties: {
|
|
584
693
|
todos: {
|
|
585
694
|
type: "array",
|
|
586
|
-
description: "full todo list (replace, not delta)",
|
|
695
|
+
description: "non-empty full todo list (replace, not delta)",
|
|
587
696
|
items: {
|
|
588
697
|
type: "object",
|
|
589
698
|
properties: {
|
|
@@ -660,11 +769,9 @@ export const todoWriteTool: Tool = {
|
|
|
660
769
|
// treats as "do not publish"). Rejecting after the JSON write would leave the
|
|
661
770
|
// legacy file describing a state TaskStore never accepted.
|
|
662
771
|
//
|
|
663
|
-
// EMPTY PAYLOAD
|
|
664
|
-
//
|
|
665
|
-
//
|
|
666
|
-
// through it: canonical rows survive, so the NEXT all-id-less write is still
|
|
667
|
-
// rejected.
|
|
772
|
+
// EMPTY PAYLOAD already threw in `normalizeTodos` above (Test I in
|
|
773
|
+
// phase4a5-idless-rejection proves `todos: []` rejects before 4A.5 and
|
|
774
|
+
// leaves canonical TaskStore rows untouched).
|
|
668
775
|
if (list.length > 0 && !hasCanonicalIdentity(list) && hasCanonicalTasks(cwd, sessionId)) {
|
|
669
776
|
const count = new TaskStore(cwd).listTasks(sessionId).length
|
|
670
777
|
throw new TaskError(
|
package/src/tools/web_fetch.ts
CHANGED
|
@@ -8,6 +8,43 @@ const MAX_REDIRECTS = LIMITS.WEB_FETCH_MAX_REDIRECTS
|
|
|
8
8
|
// Hard-cap pembacaan body SEBELUM slicing — cegah OOM dari response raksasa.
|
|
9
9
|
const BODY_HARD_CAP_BYTES = LIMITS.WEB_RESPONSE_BODY_HARD_CAP_BYTES
|
|
10
10
|
|
|
11
|
+
/**
|
|
12
|
+
* Ekstrak teks terbaca dari HTML agar halaman web penuh <script>/<style>/<svg>
|
|
13
|
+
* tidak memboroskan budget 8000 karakter sebelum isi artikel sempat terbaca.
|
|
14
|
+
*/
|
|
15
|
+
export function extractReadableHtml(html: string): string {
|
|
16
|
+
const withoutBlocks = html
|
|
17
|
+
.replace(/<!--[\s\S]*?-->/g, " ")
|
|
18
|
+
.replace(/<(script|style|noscript|svg)\b[^>]*>[\s\S]*?<\/\1>/gi, "\n")
|
|
19
|
+
.replace(
|
|
20
|
+
/<\/?(?:p|div|section|article|main|aside|header|footer|nav|h[1-6]|li|tr|td|th|blockquote|pre|br|hr)\b[^>]*>/gi,
|
|
21
|
+
"\n",
|
|
22
|
+
)
|
|
23
|
+
.replace(/<[^>]+>/g, " ")
|
|
24
|
+
const decoded = withoutBlocks
|
|
25
|
+
.replace(/ /gi, " ")
|
|
26
|
+
.replace(/&/gi, "&")
|
|
27
|
+
.replace(/</gi, "<")
|
|
28
|
+
.replace(/>/gi, ">")
|
|
29
|
+
.replace(/"/gi, '"')
|
|
30
|
+
.replace(/'|'/gi, "'")
|
|
31
|
+
.replace(/&#(\d+);/g, (_m, n) => {
|
|
32
|
+
const cp = Number(n)
|
|
33
|
+
return Number.isSafeInteger(cp) && cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : ""
|
|
34
|
+
})
|
|
35
|
+
.replace(/&#x([0-9a-f]+);/gi, (_m, hex) => {
|
|
36
|
+
const cp = Number.parseInt(hex, 16)
|
|
37
|
+
return Number.isSafeInteger(cp) && cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : ""
|
|
38
|
+
})
|
|
39
|
+
const cleaned = decoded
|
|
40
|
+
.split("\n")
|
|
41
|
+
.map((line) => line.replace(/[ \t\r]+/g, " ").trim())
|
|
42
|
+
.filter((line) => line.length > 0)
|
|
43
|
+
.join("\n")
|
|
44
|
+
.trim()
|
|
45
|
+
return cleaned
|
|
46
|
+
}
|
|
47
|
+
|
|
11
48
|
// Diekspor untuk web_search (jalur DDG): satu kebijakan cap untuk semua fetch.
|
|
12
49
|
export async function readBodyCapped(
|
|
13
50
|
res: Response,
|
|
@@ -119,8 +156,9 @@ export const webFetchTool: Tool = {
|
|
|
119
156
|
throw new Error(`blocked private host: ${current.hostname}`)
|
|
120
157
|
}
|
|
121
158
|
const headers = {
|
|
122
|
-
"user-agent": "minicode
|
|
159
|
+
"user-agent": "Mozilla/5.0 (compatible; minicode/1.0)",
|
|
123
160
|
accept: "text/html,application/json,text/*;q=0.9,*/*;q=0.8",
|
|
161
|
+
"accept-language": "en-US,en;q=0.9",
|
|
124
162
|
}
|
|
125
163
|
let res: Response | undefined
|
|
126
164
|
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
|
|
@@ -159,7 +197,9 @@ export const webFetchTool: Tool = {
|
|
|
159
197
|
|
|
160
198
|
const contentType = res.headers.get("content-type") ?? ""
|
|
161
199
|
const body = await readBodyCapped(res, controller)
|
|
162
|
-
const
|
|
200
|
+
const isHtml = /\b(?:text\/html|application\/xhtml\+xml)\b/i.test(contentType)
|
|
201
|
+
const readable = isHtml ? extractReadableHtml(body.text) || body.text : body.text
|
|
202
|
+
const scrubbed = scrubSecrets(readable)
|
|
163
203
|
const sliced = scrubbed.slice(0, limit)
|
|
164
204
|
const outputTruncation =
|
|
165
205
|
scrubbed.length > limit ? `\n\n… truncated ${scrubbed.length - limit} chars` : ""
|
package/src/tools/web_search.ts
CHANGED
|
@@ -14,6 +14,19 @@ export function capTotal(out: string, cap: number): string {
|
|
|
14
14
|
return out.length > cap ? `${out.slice(0, cap)}\n… [truncated: showing first ${cap} chars]` : out
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
+
export function decodeDdgUrl(raw: string): string {
|
|
18
|
+
const unescaped = raw.replace(/&/g, "&").trim()
|
|
19
|
+
const full = unescaped.startsWith("//") ? `https:${unescaped}` : unescaped
|
|
20
|
+
try {
|
|
21
|
+
const u = new URL(full)
|
|
22
|
+
if (u.hostname.endsWith("duckduckgo.com") && u.pathname.startsWith("/l/")) {
|
|
23
|
+
const uddg = u.searchParams.get("uddg")
|
|
24
|
+
if (uddg) return uddg
|
|
25
|
+
}
|
|
26
|
+
} catch {}
|
|
27
|
+
return full
|
|
28
|
+
}
|
|
29
|
+
|
|
17
30
|
export const webSearchTool: Tool = {
|
|
18
31
|
name: "web_search",
|
|
19
32
|
description:
|
|
@@ -33,6 +46,7 @@ export const webSearchTool: Tool = {
|
|
|
33
46
|
const q = String(query ?? "").trim()
|
|
34
47
|
if (!q) throw new Error("query required")
|
|
35
48
|
const n = Math.min(Math.max(Number(count) || 5, 1), 10)
|
|
49
|
+
const providerErrors: string[] = []
|
|
36
50
|
// Prefer Tavily if key available (more reliable than scraping)
|
|
37
51
|
const tavilyKey = process.env.TAVILY_API_KEY
|
|
38
52
|
if (tavilyKey) {
|
|
@@ -69,12 +83,16 @@ export const webSearchTool: Tool = {
|
|
|
69
83
|
? content
|
|
70
84
|
: fenceUntrustedToolOutput("web_search", content)
|
|
71
85
|
}
|
|
86
|
+
providerErrors.push(`tavily HTTP ${res.status}`)
|
|
72
87
|
await res.body?.cancel().catch(() => {})
|
|
73
88
|
} finally {
|
|
74
89
|
clearTimeout(t)
|
|
75
90
|
ctx.signal.removeEventListener("abort", onAbort)
|
|
76
91
|
}
|
|
77
|
-
} catch {
|
|
92
|
+
} catch (e) {
|
|
93
|
+
ctx.signal.throwIfAborted()
|
|
94
|
+
providerErrors.push(`tavily: ${scrubSecrets((e as Error).message)}`)
|
|
95
|
+
}
|
|
78
96
|
}
|
|
79
97
|
// Fallback 2: Brave Search API (gratis, JSON bersih) bila BRAVE_API_KEY ada.
|
|
80
98
|
const braveKey = process.env.BRAVE_API_KEY
|
|
@@ -116,13 +134,19 @@ export const webSearchTool: Tool = {
|
|
|
116
134
|
? content
|
|
117
135
|
: fenceUntrustedToolOutput("web_search", content)
|
|
118
136
|
}
|
|
137
|
+
providerErrors.push("brave: 0 results")
|
|
138
|
+
} else {
|
|
139
|
+
providerErrors.push(`brave HTTP ${res.status}`)
|
|
119
140
|
}
|
|
120
141
|
await res.body?.cancel().catch(() => {})
|
|
121
142
|
} finally {
|
|
122
143
|
clearTimeout(t)
|
|
123
144
|
ctx.signal.removeEventListener("abort", onAbort)
|
|
124
145
|
}
|
|
125
|
-
} catch {
|
|
146
|
+
} catch (e) {
|
|
147
|
+
ctx.signal.throwIfAborted()
|
|
148
|
+
providerErrors.push(`brave: ${scrubSecrets((e as Error).message)}`)
|
|
149
|
+
}
|
|
126
150
|
}
|
|
127
151
|
// Fallback 3: DuckDuckGo html lite (gratis, tanpa key).
|
|
128
152
|
const ddgUrl = `https://html.duckduckgo.com/html/?q=${encodeURIComponent(q)}`
|
|
@@ -137,8 +161,18 @@ export const webSearchTool: Tool = {
|
|
|
137
161
|
try {
|
|
138
162
|
const res = await fetch(ddgUrl, {
|
|
139
163
|
signal: controller.signal,
|
|
140
|
-
headers: {
|
|
164
|
+
headers: {
|
|
165
|
+
"user-agent": "Mozilla/5.0 (compatible; minicode/1.0)",
|
|
166
|
+
"accept-language": "en-US,en;q=0.9",
|
|
167
|
+
},
|
|
141
168
|
})
|
|
169
|
+
if (!res.ok) {
|
|
170
|
+
await res.body?.cancel().catch(() => {})
|
|
171
|
+
const errDetail = providerErrors.length ? ` (${providerErrors.join("; ")})` : ""
|
|
172
|
+
throw new Error(
|
|
173
|
+
`DuckDuckGo HTTP ${res.status} ${res.statusText || "blocked/rate-limited"}${errDetail}`,
|
|
174
|
+
)
|
|
175
|
+
}
|
|
142
176
|
// Cap streaming seperti web_fetch (bug-hunt 2026-09-19: res.text()
|
|
143
177
|
// tanpa batas = transient ~2x body di heap untuk halaman raksasa).
|
|
144
178
|
const body = await readBodyCapped(res, controller)
|
|
@@ -150,12 +184,12 @@ export const webSearchTool: Tool = {
|
|
|
150
184
|
const results: { url: string; title: string }[] = []
|
|
151
185
|
for (const m of scrubbed.matchAll(resRe)) {
|
|
152
186
|
if (results.length >= n) break
|
|
153
|
-
results.push({ url: m[1] ?? "", title: (m[2] ?? "").trim() })
|
|
187
|
+
results.push({ url: decodeDdgUrl(m[1] ?? ""), title: (m[2] ?? "").trim() })
|
|
154
188
|
}
|
|
155
189
|
if (results.length === 0) {
|
|
156
190
|
for (const m of scrubbed.matchAll(altRe)) {
|
|
157
191
|
if (results.length >= n) break
|
|
158
|
-
results.push({ url: m[1] ?? "", title: (m[2] ?? "").trim() })
|
|
192
|
+
results.push({ url: decodeDdgUrl(m[1] ?? ""), title: (m[2] ?? "").trim() })
|
|
159
193
|
}
|
|
160
194
|
}
|
|
161
195
|
if (results.length) {
|
|
@@ -168,9 +202,10 @@ export const webSearchTool: Tool = {
|
|
|
168
202
|
? content
|
|
169
203
|
: fenceUntrustedToolOutput("web_search", content)
|
|
170
204
|
}
|
|
205
|
+
const errHint = providerErrors.length ? ` (prior errors: ${providerErrors.join("; ")})` : ""
|
|
171
206
|
const fallback = body.truncated
|
|
172
|
-
? `[web_search] DuckDuckGo response exceeded the byte cap before structured results could be parsed for "${q}" —
|
|
173
|
-
: `[web_search] no structured results for "${q}" —
|
|
207
|
+
? `[web_search] DuckDuckGo response exceeded the byte cap before structured results could be parsed for "${q}"${errHint} — try setting TAVILY_API_KEY or BRAVE_API_KEY.`
|
|
208
|
+
: `[web_search] no structured results for "${q}"${errHint} — try setting TAVILY_API_KEY or BRAVE_API_KEY for more reliable results.`
|
|
174
209
|
return isAlreadyFenced(fallback)
|
|
175
210
|
? fallback
|
|
176
211
|
: fenceUntrustedToolOutput("web_search", fallback)
|
|
@@ -179,7 +214,11 @@ export const webSearchTool: Tool = {
|
|
|
179
214
|
ctx.signal.removeEventListener("abort", onAbort)
|
|
180
215
|
}
|
|
181
216
|
} catch (e) {
|
|
182
|
-
|
|
217
|
+
const errDetail =
|
|
218
|
+
providerErrors.length && !(e as Error).message.includes(providerErrors[0]!)
|
|
219
|
+
? ` (${providerErrors.join("; ")})`
|
|
220
|
+
: ""
|
|
221
|
+
throw new Error(`web_search failed: ${(e as Error).message}${errDetail}`)
|
|
183
222
|
}
|
|
184
223
|
},
|
|
185
224
|
}
|