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,161 @@
|
|
|
1
|
+
import type { Tool } from "#minicore"
|
|
2
|
+
import { LIMITS } from "../constants.ts"
|
|
3
|
+
import { isPrivateHostWithDns } from "../lib/net.ts"
|
|
4
|
+
import { scrubSecrets } from "../policy/scrub.ts"
|
|
5
|
+
|
|
6
|
+
const MAX_REDIRECTS = LIMITS.WEB_FETCH_MAX_REDIRECTS
|
|
7
|
+
// Hard-cap pembacaan body SEBELUM slicing — cegah OOM dari response raksasa.
|
|
8
|
+
const BODY_HARD_CAP_CHARS = LIMITS.WEB_FETCH_BODY_HARD_CAP_CHARS
|
|
9
|
+
|
|
10
|
+
async function readBodyCapped(res: Response, controller: AbortController): Promise<string> {
|
|
11
|
+
if (!res.body) return ""
|
|
12
|
+
const reader = res.body.getReader()
|
|
13
|
+
const decoder = new TextDecoder()
|
|
14
|
+
let out = ""
|
|
15
|
+
try {
|
|
16
|
+
while (true) {
|
|
17
|
+
const { done, value } = await reader.read()
|
|
18
|
+
if (done) break
|
|
19
|
+
out += decoder.decode(value, { stream: true })
|
|
20
|
+
if (out.length > BODY_HARD_CAP_CHARS) {
|
|
21
|
+
controller.abort(new Error("response exceeds body hard cap"))
|
|
22
|
+
break
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
} finally {
|
|
26
|
+
reader.releaseLock()
|
|
27
|
+
}
|
|
28
|
+
return out
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Snippet body error dengan cap streaming (F-15): cukup untuk diagnosis,
|
|
32
|
+
// tak pernah buffer body utuh. Cancel stream setelah cap agar server
|
|
33
|
+
// berhenti mengirim (hemat bandwidth + memori).
|
|
34
|
+
async function readErrorSnippet(res: Response, maxChars = 4096): Promise<string> {
|
|
35
|
+
if (!res.body) return ""
|
|
36
|
+
const reader = res.body.getReader()
|
|
37
|
+
const decoder = new TextDecoder()
|
|
38
|
+
let out = ""
|
|
39
|
+
try {
|
|
40
|
+
for (;;) {
|
|
41
|
+
const { done, value } = await reader.read()
|
|
42
|
+
if (value) out += decoder.decode(value, { stream: true })
|
|
43
|
+
if (done || out.length >= maxChars) break
|
|
44
|
+
}
|
|
45
|
+
} catch {
|
|
46
|
+
return out.slice(0, maxChars)
|
|
47
|
+
} finally {
|
|
48
|
+
try {
|
|
49
|
+
await reader.cancel()
|
|
50
|
+
} catch {}
|
|
51
|
+
try {
|
|
52
|
+
reader.releaseLock()
|
|
53
|
+
} catch {}
|
|
54
|
+
}
|
|
55
|
+
return out.slice(0, maxChars)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export const webFetchTool: Tool = {
|
|
59
|
+
name: "web_fetch",
|
|
60
|
+
description:
|
|
61
|
+
"Fetch a public HTTP/HTTPS URL (GET, 10s timeout, max 50k chars). Use for browsing public web pages. Blocks private IPs and private redirect targets.",
|
|
62
|
+
parameters: {
|
|
63
|
+
type: "object",
|
|
64
|
+
properties: {
|
|
65
|
+
url: { type: "string", description: "https:// URL to fetch" },
|
|
66
|
+
maxChars: { type: "number", description: "max chars to return (default 20000, max 50000)" },
|
|
67
|
+
},
|
|
68
|
+
required: ["url"],
|
|
69
|
+
additionalProperties: false,
|
|
70
|
+
},
|
|
71
|
+
async execute({ url, maxChars }, ctx) {
|
|
72
|
+
const u = String(url ?? "").trim()
|
|
73
|
+
if (!u) throw new Error("url required")
|
|
74
|
+
let parsed: URL
|
|
75
|
+
try {
|
|
76
|
+
parsed = new URL(u)
|
|
77
|
+
} catch {
|
|
78
|
+
throw new Error(`invalid url: ${u}`)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const limit = Math.min(Math.max(Number(maxChars) || 20000, 1000), 50000)
|
|
82
|
+
const controller = new AbortController()
|
|
83
|
+
const timeout = setTimeout(() => controller.abort(new Error("fetch timeout 10s")), 10_000)
|
|
84
|
+
// Link parent signal — selalu pasang listener dulu, cek aborted setelahnya
|
|
85
|
+
// (tutup race abort antara check dan addEventListener).
|
|
86
|
+
const onParentAbort = () => controller.abort(ctx.signal.reason)
|
|
87
|
+
ctx.signal.addEventListener("abort", onParentAbort, { once: true })
|
|
88
|
+
if (ctx.signal.aborted) controller.abort(ctx.signal.reason)
|
|
89
|
+
|
|
90
|
+
try {
|
|
91
|
+
// Redirect ditangani MANUAL: tiap hop divalidasi ulang isPrivateHost +
|
|
92
|
+
// DNS tanpa cache klien — menutup SSRF via open-redirect & rebinding
|
|
93
|
+
// yang mengandalkan cache basi. SISA RESIDUAL jujur (audit 2026-09-16
|
|
94
|
+
// B6): validasi-lalu-fetch = check-then-connect; resolver OS bisa
|
|
95
|
+
// mengembalikan IP berbeda saat connect dibanding saat cek. Menutupnya
|
|
96
|
+
// butuh pin-IP di level socket (di luar API fetch) — ditunda sadar,
|
|
97
|
+
// bukan diklaim tertutup.
|
|
98
|
+
let current = parsed
|
|
99
|
+
// F-21: noCache di SEMUA hop (sesuai komentar desain di atas): cache DNS
|
|
100
|
+
// 30 dtk memperlebar jendela rebinding + meracuni hasil negatif — tiap
|
|
101
|
+
// redirect harus resolve ulang, bukan memakai cache basi.
|
|
102
|
+
if (await isPrivateHostWithDns(current.hostname, { noCache: true })) {
|
|
103
|
+
throw new Error(`blocked private host: ${current.hostname}`)
|
|
104
|
+
}
|
|
105
|
+
const headers = {
|
|
106
|
+
"user-agent": "minicode-webfetch/1.0",
|
|
107
|
+
accept: "text/html,application/json,text/*;q=0.9,*/*;q=0.8",
|
|
108
|
+
}
|
|
109
|
+
let res: Response | undefined
|
|
110
|
+
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
|
|
111
|
+
res = await fetch(current.toString(), {
|
|
112
|
+
signal: controller.signal,
|
|
113
|
+
headers,
|
|
114
|
+
redirect: "manual",
|
|
115
|
+
})
|
|
116
|
+
if (res.status < 300 || res.status >= 400) break
|
|
117
|
+
const loc = res.headers.get("location")
|
|
118
|
+
if (!loc) break
|
|
119
|
+
let next: URL
|
|
120
|
+
try {
|
|
121
|
+
next = new URL(loc, current)
|
|
122
|
+
} catch {
|
|
123
|
+
throw new Error(`invalid redirect location: ${loc}`)
|
|
124
|
+
}
|
|
125
|
+
if (next.protocol !== "http:" && next.protocol !== "https:") {
|
|
126
|
+
throw new Error(`redirect to disallowed protocol: ${next.protocol}`)
|
|
127
|
+
}
|
|
128
|
+
if (await isPrivateHostWithDns(next.hostname, { noCache: true })) {
|
|
129
|
+
throw new Error(`blocked private host (redirect target): ${next.hostname}`)
|
|
130
|
+
}
|
|
131
|
+
current = next
|
|
132
|
+
void res.body?.cancel().catch(() => {})
|
|
133
|
+
}
|
|
134
|
+
if (!res) throw new Error("unreachable")
|
|
135
|
+
if (res.status >= 300 && res.status < 400) {
|
|
136
|
+
throw new Error(`too many redirects (>${MAX_REDIRECTS})`)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
if (!res.ok) {
|
|
140
|
+
// F-15: JANGAN res.text() mentah — error body raksasa (500MB dari
|
|
141
|
+
// server jahat) ter-buffer penuh sebelum slice(0,1000). Baca streaming
|
|
142
|
+
// dengan cap kecil (snippet diagnosis cukup 4k), lalu cancel.
|
|
143
|
+
const body = await readErrorSnippet(res)
|
|
144
|
+
const snippet = scrubSecrets(body).slice(0, 1000)
|
|
145
|
+
throw new Error(`fetch ${res.status} ${res.statusText}${snippet ? `: ${snippet}` : ""}`)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const contentType = res.headers.get("content-type") ?? ""
|
|
149
|
+
const raw = await readBodyCapped(res, controller)
|
|
150
|
+
const scrubbed = scrubSecrets(raw)
|
|
151
|
+
const sliced = scrubbed.slice(0, limit)
|
|
152
|
+
const truncated =
|
|
153
|
+
scrubbed.length > limit ? `\n\n… truncated ${scrubbed.length - limit} chars` : ""
|
|
154
|
+
const header = `[${current} ${res.status} ${contentType}]\n`
|
|
155
|
+
return (header + sliced + truncated).slice(0, limit + 500)
|
|
156
|
+
} finally {
|
|
157
|
+
clearTimeout(timeout)
|
|
158
|
+
ctx.signal.removeEventListener("abort", onParentAbort)
|
|
159
|
+
}
|
|
160
|
+
},
|
|
161
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import type { Tool } from "#minicore"
|
|
2
|
+
import { isPrivateHost } from "../lib/net.ts"
|
|
3
|
+
import { scrubSecrets } from "../policy/scrub.ts"
|
|
4
|
+
|
|
5
|
+
// Penanda truncation (temuan audit #02): snippet/total yang dipotong
|
|
6
|
+
// diam-diam tampak lengkap. Snippet 400 char, total per-provider di-cap.
|
|
7
|
+
export function cutSnippet(s: string): string {
|
|
8
|
+
const clean = scrubSecrets(s)
|
|
9
|
+
return clean.length > 400 ? `${clean.slice(0, 400)}…` : clean
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function capTotal(out: string, cap: number): string {
|
|
13
|
+
return out.length > cap ? `${out.slice(0, cap)}\n… [truncated: showing first ${cap} chars]` : out
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export const webSearchTool: Tool = {
|
|
17
|
+
name: "web_search",
|
|
18
|
+
description:
|
|
19
|
+
"Search the web (Google grounding-like via DuckDuckGo/Tavily). Returns top results with snippets. Uses web_fetch under the hood with SSRF guard.",
|
|
20
|
+
parameters: {
|
|
21
|
+
type: "object",
|
|
22
|
+
properties: {
|
|
23
|
+
query: { type: "string", description: "search query" },
|
|
24
|
+
count: { type: "number", description: "max results (default 5, max 10)" },
|
|
25
|
+
},
|
|
26
|
+
required: ["query"],
|
|
27
|
+
additionalProperties: false,
|
|
28
|
+
},
|
|
29
|
+
async execute({ query, count }, ctx) {
|
|
30
|
+
// Fail-fast saat sesi sudah dibatalkan — sebelum network apa pun.
|
|
31
|
+
ctx.signal.throwIfAborted()
|
|
32
|
+
const q = String(query ?? "").trim()
|
|
33
|
+
if (!q) throw new Error("query required")
|
|
34
|
+
const n = Math.min(Math.max(Number(count) || 5, 1), 10)
|
|
35
|
+
// Prefer Tavily if key available (more reliable than scraping)
|
|
36
|
+
const tavilyKey = process.env.TAVILY_API_KEY
|
|
37
|
+
if (tavilyKey) {
|
|
38
|
+
try {
|
|
39
|
+
const controller = new AbortController()
|
|
40
|
+
const t = setTimeout(() => controller.abort(), 8000)
|
|
41
|
+
const onAbort = () => controller.abort(ctx.signal.reason)
|
|
42
|
+
ctx.signal.addEventListener("abort", onAbort, { once: true })
|
|
43
|
+
try {
|
|
44
|
+
const res = await fetch("https://api.tavily.com/search", {
|
|
45
|
+
method: "POST",
|
|
46
|
+
headers: { "content-type": "application/json" },
|
|
47
|
+
body: JSON.stringify({
|
|
48
|
+
api_key: tavilyKey,
|
|
49
|
+
query: q,
|
|
50
|
+
max_results: n,
|
|
51
|
+
search_depth: "basic",
|
|
52
|
+
}),
|
|
53
|
+
signal: controller.signal,
|
|
54
|
+
})
|
|
55
|
+
if (res.ok) {
|
|
56
|
+
const data = (await res.json()) as {
|
|
57
|
+
results?: { title: string; url: string; content: string }[]
|
|
58
|
+
}
|
|
59
|
+
const results = (data.results ?? []).slice(0, n)
|
|
60
|
+
const out = results
|
|
61
|
+
.map((r, i) => `${i + 1}. ${r.title}\n ${r.url}\n ${cutSnippet(r.content)}`)
|
|
62
|
+
.join("\n\n")
|
|
63
|
+
return capTotal(`[tavily ${results.length} results for "${q}"]\n${out}`, 20000)
|
|
64
|
+
}
|
|
65
|
+
} finally {
|
|
66
|
+
clearTimeout(t)
|
|
67
|
+
ctx.signal.removeEventListener("abort", onAbort)
|
|
68
|
+
}
|
|
69
|
+
} catch {}
|
|
70
|
+
}
|
|
71
|
+
// Fallback 2: Brave Search API (gratis, JSON bersih) bila BRAVE_API_KEY ada.
|
|
72
|
+
const braveKey = process.env.BRAVE_API_KEY
|
|
73
|
+
if (braveKey) {
|
|
74
|
+
try {
|
|
75
|
+
const controller = new AbortController()
|
|
76
|
+
const t = setTimeout(() => controller.abort(), 8000)
|
|
77
|
+
// Tautkan pembatalan parent (sebelumnya hanya Tavily yang menautkan).
|
|
78
|
+
const onAbort = () => controller.abort(ctx.signal.reason)
|
|
79
|
+
if (ctx.signal.aborted) controller.abort(ctx.signal.reason)
|
|
80
|
+
else ctx.signal.addEventListener("abort", onAbort, { once: true })
|
|
81
|
+
try {
|
|
82
|
+
const res = await fetch(
|
|
83
|
+
`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(q)}&count=${n}`,
|
|
84
|
+
{
|
|
85
|
+
headers: { "X-Subscription-Token": braveKey, accept: "application/json" },
|
|
86
|
+
signal: controller.signal,
|
|
87
|
+
},
|
|
88
|
+
)
|
|
89
|
+
if (res.ok) {
|
|
90
|
+
const data = (await res.json()) as {
|
|
91
|
+
web?: { results?: { title: string; url: string; description: string }[] }
|
|
92
|
+
}
|
|
93
|
+
const results = (data.web?.results ?? []).slice(0, n)
|
|
94
|
+
if (results.length) {
|
|
95
|
+
const out = results
|
|
96
|
+
.map(
|
|
97
|
+
(r, i) =>
|
|
98
|
+
`${i + 1}. ${r.title}\n ${r.url}\n ${cutSnippet(r.description ?? "")}`,
|
|
99
|
+
)
|
|
100
|
+
.join("\n\n")
|
|
101
|
+
return capTotal(`[brave ${results.length} results for "${q}"]\n${out}`, 20000)
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
} finally {
|
|
105
|
+
clearTimeout(t)
|
|
106
|
+
ctx.signal.removeEventListener("abort", onAbort)
|
|
107
|
+
}
|
|
108
|
+
} catch {}
|
|
109
|
+
}
|
|
110
|
+
// Fallback 3: DuckDuckGo html lite (gratis, tanpa key).
|
|
111
|
+
const ddgUrl = `https://html.duckduckgo.com/html/?q=${encodeURIComponent(q)}`
|
|
112
|
+
try {
|
|
113
|
+
const parsed = new URL(ddgUrl)
|
|
114
|
+
if (isPrivateHost(parsed.hostname)) throw new Error("blocked")
|
|
115
|
+
const controller = new AbortController()
|
|
116
|
+
const t = setTimeout(() => controller.abort(), 8000)
|
|
117
|
+
const onAbort = () => controller.abort(ctx.signal.reason)
|
|
118
|
+
if (ctx.signal.aborted) controller.abort(ctx.signal.reason)
|
|
119
|
+
else ctx.signal.addEventListener("abort", onAbort, { once: true })
|
|
120
|
+
try {
|
|
121
|
+
const res = await fetch(ddgUrl, {
|
|
122
|
+
signal: controller.signal,
|
|
123
|
+
headers: { "user-agent": "minicode-websearch/1.0" },
|
|
124
|
+
})
|
|
125
|
+
const html = await res.text()
|
|
126
|
+
const scrubbed = scrubSecrets(html)
|
|
127
|
+
// DDG markup berubah-ubah; coba dua pola kelas umum.
|
|
128
|
+
const resRe = /<a[^>]+class="result__url"[^>]*href="([^"]+)"[^>]*>([^<]+)<\/a>/g
|
|
129
|
+
const altRe = /<a[^>]+class="[^"]*result__a[^"]*"[^>]*href="([^"]+)"[^>]*>([^<]+)<\/a>/g
|
|
130
|
+
const results: { url: string; title: string }[] = []
|
|
131
|
+
for (const m of scrubbed.matchAll(resRe)) {
|
|
132
|
+
if (results.length >= n) break
|
|
133
|
+
results.push({ url: m[1] ?? "", title: (m[2] ?? "").trim() })
|
|
134
|
+
}
|
|
135
|
+
if (results.length === 0) {
|
|
136
|
+
for (const m of scrubbed.matchAll(altRe)) {
|
|
137
|
+
if (results.length >= n) break
|
|
138
|
+
results.push({ url: m[1] ?? "", title: (m[2] ?? "").trim() })
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (results.length) {
|
|
142
|
+
return capTotal(
|
|
143
|
+
`[duckduckgo ${results.length} results for "${q}"]\n${results.map((r, i) => `${i + 1}. ${r.title}\n ${r.url}`).join("\n")}`,
|
|
144
|
+
8000,
|
|
145
|
+
)
|
|
146
|
+
}
|
|
147
|
+
return `[web_search] no structured results for "${q}" — coba set TAVILY_API_KEY atau BRAVE_API_KEY untuk hasil lebih baik.`
|
|
148
|
+
} finally {
|
|
149
|
+
clearTimeout(t)
|
|
150
|
+
ctx.signal.removeEventListener("abort", onAbort)
|
|
151
|
+
}
|
|
152
|
+
} catch (e) {
|
|
153
|
+
throw new Error(`web_search failed: ${(e as Error).message}`)
|
|
154
|
+
}
|
|
155
|
+
},
|
|
156
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { stat } from "node:fs/promises"
|
|
2
|
+
import { resolve } from "node:path"
|
|
3
|
+
import type { Tool } from "#minicore"
|
|
4
|
+
import { LIMITS } from "../constants.ts"
|
|
5
|
+
import { atomicWriteText } from "../lib/atomic-write.ts"
|
|
6
|
+
import { assertSafeWriteTarget, resolveSafePath } from "../lib/safe-open.ts"
|
|
7
|
+
import { appendLspDiagnostics } from "../policy/verifier.ts"
|
|
8
|
+
|
|
9
|
+
export const writeFileTool: Tool = {
|
|
10
|
+
name: "write_file",
|
|
11
|
+
description:
|
|
12
|
+
"Create or overwrite a file with text content (atomic write, creates parent directories). Max 5M chars (~20MB). Cannot write outside the workspace, to secret paths (.env, .ssh, node_modules) or to .minicode/ state — write your own notes in the workspace instead. Prefer edit for small changes to an existing file.",
|
|
13
|
+
parameters: {
|
|
14
|
+
type: "object",
|
|
15
|
+
properties: {
|
|
16
|
+
path: { type: "string", description: "path relative to the workspace (e.g. src/a.ts)" },
|
|
17
|
+
content: { type: "string", description: "full file content to write" },
|
|
18
|
+
},
|
|
19
|
+
required: ["path", "content"],
|
|
20
|
+
additionalProperties: false,
|
|
21
|
+
},
|
|
22
|
+
async execute({ path, content }, ctx) {
|
|
23
|
+
ctx.signal.throwIfAborted()
|
|
24
|
+
const p = path as string
|
|
25
|
+
const root = (ctx as { cwd?: string }).cwd ?? process.cwd()
|
|
26
|
+
// Verifikasi path terpusat (logis + target nyata) — detail di safe-open.ts.
|
|
27
|
+
const { real: realAbs } = await resolveSafePath(p, root)
|
|
28
|
+
// Tolak menimpa symlink final (swap antara cek dan tulis gagal tutup).
|
|
29
|
+
await assertSafeWriteTarget(resolve(root, p), root)
|
|
30
|
+
// guard large write — chars vs bytes (emoji/CJK 4x)
|
|
31
|
+
const c = content as string
|
|
32
|
+
if (c.length > LIMITS.WRITE_FILE_MAX_CHARS)
|
|
33
|
+
throw new Error(`content too large: ${c.length} chars (max 5M)`)
|
|
34
|
+
if (Buffer.byteLength(c, "utf8") > LIMITS.WRITE_FILE_MAX_CHARS * 4)
|
|
35
|
+
throw new Error(`content too large: ${Buffer.byteLength(c, "utf8")} bytes > ~20M`)
|
|
36
|
+
// atomic: write tmp (O_EXCL + randomUUID) then rename — anti-hijack & atomic
|
|
37
|
+
await atomicWriteText(realAbs, c)
|
|
38
|
+
const st = await stat(realAbs).catch(() => null)
|
|
39
|
+
const base = `wrote ${realAbs} (${st?.size ?? c.length} bytes)`
|
|
40
|
+
return await appendLspDiagnostics(realAbs, c, base, undefined, root)
|
|
41
|
+
},
|
|
42
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// View persetujuan tool — readline + warna, murni presentasi.
|
|
2
|
+
// Lapisan policy tidak mengimpor file ini; ia di-inject sebagai callback dari
|
|
3
|
+
// composition root (cli/setup.ts -> createMinicodeSession -> permission).
|
|
4
|
+
import { askLine } from "../input/input.ts"
|
|
5
|
+
import { sanitizeAnsiLine } from "../render/sanitize.ts"
|
|
6
|
+
import { c } from "../render/theme.ts"
|
|
7
|
+
|
|
8
|
+
/** Subset struktural tool call yang dibutuhkan view — tanpa tipe kernel. */
|
|
9
|
+
export interface ApprovalRequest {
|
|
10
|
+
name: string
|
|
11
|
+
args?: unknown
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export async function promptAsk(call: ApprovalRequest): Promise<"allow" | "deny" | "always"> {
|
|
15
|
+
if (!process.stdin.isTTY) return "deny"
|
|
16
|
+
// Non-visual feedback bisa dimatikan untuk aksesibilitas/recording.
|
|
17
|
+
// Bell hanya bila stdout TTY: byte `\x07` di stdout pipe mengotori output
|
|
18
|
+
// program (kontrak: stdout = output PROGRAM, bukan diagnostik).
|
|
19
|
+
if (process.env.MINICODE_BELL !== "0" && process.stdout.isTTY) process.stdout.write("\x07")
|
|
20
|
+
// Live-region untuk screen reader: baris polos tanpa ANSI agar terbaca
|
|
21
|
+
// sebagai teks, bukan escape mentah. Bell saja mengganggu tanpa informasi.
|
|
22
|
+
if (process.env.MINICODE_A11Y === "1")
|
|
23
|
+
process.stderr.write(`[approval required: ${sanitizeAnsiLine(call.name)}]\n`)
|
|
24
|
+
|
|
25
|
+
// toolName/actionSummary berasal dari model/MCP (tidak terpercaya). Tanpa
|
|
26
|
+
// sanitasi, `\x1b[2J\x1b[H` di dalam args.command akan membersihkan layar
|
|
27
|
+
// terminal user saat prompt persetujuan tampil (sama seperti provider:text).
|
|
28
|
+
const toolName = sanitizeAnsiLine(call.name)
|
|
29
|
+
const args = (call.args ?? {}) as Record<string, unknown>
|
|
30
|
+
|
|
31
|
+
let actionSummary = ""
|
|
32
|
+
if (args.command) actionSummary = `Command: ${String(args.command).slice(0, 100)}`
|
|
33
|
+
else if (args.path) actionSummary = `File: ${String(args.path)}`
|
|
34
|
+
else if (args.query) actionSummary = `Query: ${String(args.query)}`
|
|
35
|
+
else {
|
|
36
|
+
let json = ""
|
|
37
|
+
try {
|
|
38
|
+
json = JSON.stringify(args)
|
|
39
|
+
} catch {
|
|
40
|
+
json = String(args)
|
|
41
|
+
}
|
|
42
|
+
actionSummary = `Args: ${json.slice(0, 100)}`
|
|
43
|
+
}
|
|
44
|
+
actionSummary = sanitizeAnsiLine(actionSummary)
|
|
45
|
+
|
|
46
|
+
process.stdout.write(`\n${c.warning(c.bold("Approval required"))}\n`)
|
|
47
|
+
process.stdout.write(` ${c.bold("Tool:")} ${c.info(toolName)}\n`)
|
|
48
|
+
process.stdout.write(` ${actionSummary}\n`)
|
|
49
|
+
|
|
50
|
+
const promptText = `${c.bold("[y]")} Allow once ${c.bold("[a]")} Always ${c.bold("[n]")} Deny: `
|
|
51
|
+
const ans = (await askLine({ prompt: promptText })) ?? ""
|
|
52
|
+
|
|
53
|
+
const a = ans.trim().toLowerCase()
|
|
54
|
+
if (a === "a" || a === "always") return "always"
|
|
55
|
+
if (a === "y" || a === "yes") return "allow"
|
|
56
|
+
return "deny"
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** View pertanyaan ask_user — di-inject ke src/tools/ask_user.ts dari cli/setup.ts.
|
|
60
|
+
* Teks pertanyaan berasal dari model (tidak terpercaya): disanitasi sebelum
|
|
61
|
+
* tampil agar tak bisa membersihkan layar via escape sequence. Return null
|
|
62
|
+
* bila user membatalkan (Esc/Ctrl+C → askLine null) atau jawaban kosong. */
|
|
63
|
+
export async function promptAskText(question: string, options?: string[]): Promise<string | null> {
|
|
64
|
+
if (!process.stdin.isTTY) return null
|
|
65
|
+
const q = sanitizeAnsiLine(question).slice(0, 2000)
|
|
66
|
+
process.stdout.write(`\n${c.warning(c.bold("Agent asks"))}\n`)
|
|
67
|
+
process.stdout.write(` ${q}\n`)
|
|
68
|
+
if (options?.length) {
|
|
69
|
+
options.forEach((o, i) => {
|
|
70
|
+
process.stdout.write(` ${c.dim(`${i + 1}.`)} ${sanitizeAnsiLine(o)}\n`)
|
|
71
|
+
})
|
|
72
|
+
}
|
|
73
|
+
const ans = await askLine({ prompt: `${c.bold("Your answer")} (empty = cancel): ` })
|
|
74
|
+
if (ans == null || !ans.trim()) return null
|
|
75
|
+
return ans.trim()
|
|
76
|
+
}
|