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.
Files changed (162) hide show
  1. package/CHANGELOG.md +935 -0
  2. package/LICENSE +21 -0
  3. package/README.md +200 -0
  4. package/cli/args.ts +195 -0
  5. package/cli/auto-update.ts +108 -0
  6. package/cli/commands/auth.ts +166 -0
  7. package/cli/commands/config.ts +382 -0
  8. package/cli/commands/doctor.ts +128 -0
  9. package/cli/commands/exec.ts +179 -0
  10. package/cli/commands/mcp.ts +35 -0
  11. package/cli/commands/memory.ts +107 -0
  12. package/cli/commands/pricing.ts +100 -0
  13. package/cli/commands/providers.ts +162 -0
  14. package/cli/commands/sessions.ts +128 -0
  15. package/cli/commands/skills.ts +61 -0
  16. package/cli/commands/stats.ts +82 -0
  17. package/cli/commands.ts +317 -0
  18. package/cli/index.ts +539 -0
  19. package/cli/model-manager.ts +112 -0
  20. package/cli/provider-manager.ts +111 -0
  21. package/cli/repl.ts +734 -0
  22. package/cli/router.ts +124 -0
  23. package/cli/setup.ts +780 -0
  24. package/cli/wizard.ts +21 -0
  25. package/docs/ARCHITECTURE.html +1222 -0
  26. package/docs/README.md +109 -0
  27. package/docs/architecture.md +44 -0
  28. package/docs/changelog.md +3 -0
  29. package/package.json +91 -0
  30. package/src/agents/pool.ts +43 -0
  31. package/src/app/mentions.ts +50 -0
  32. package/src/app/provider-layer.ts +118 -0
  33. package/src/app/rag-layer.ts +105 -0
  34. package/src/app/session.ts +154 -0
  35. package/src/app/tool-layer.ts +56 -0
  36. package/src/config.ts +372 -0
  37. package/src/constants.ts +119 -0
  38. package/src/hooks/run.ts +89 -0
  39. package/src/lib/atomic-write.ts +88 -0
  40. package/src/lib/db-path.ts +36 -0
  41. package/src/lib/git-hardening.ts +91 -0
  42. package/src/lib/ignore.ts +58 -0
  43. package/src/lib/keystore.ts +202 -0
  44. package/src/lib/net.ts +70 -0
  45. package/src/lib/safe-open.ts +138 -0
  46. package/src/lib/session-id.ts +23 -0
  47. package/src/lib/trash.ts +38 -0
  48. package/src/lib/trusted-exec.ts +81 -0
  49. package/src/lsp/client.ts +395 -0
  50. package/src/mcp/client.ts +400 -0
  51. package/src/mcp/http-transport.ts +344 -0
  52. package/src/mcp/server.ts +538 -0
  53. package/src/mcp/transport.ts +150 -0
  54. package/src/memory/files.ts +159 -0
  55. package/src/memory/vector.ts +775 -0
  56. package/src/policy/allowlist.ts +67 -0
  57. package/src/policy/bash-guard.ts +465 -0
  58. package/src/policy/compaction.ts +271 -0
  59. package/src/policy/context.ts +161 -0
  60. package/src/policy/executor.ts +199 -0
  61. package/src/policy/jail.ts +127 -0
  62. package/src/policy/permission.ts +517 -0
  63. package/src/policy/pricing.ts +336 -0
  64. package/src/policy/ratelimit.ts +54 -0
  65. package/src/policy/sandbox-policy.ts +157 -0
  66. package/src/policy/scrub.ts +138 -0
  67. package/src/policy/update-check.ts +200 -0
  68. package/src/policy/usage.ts +292 -0
  69. package/src/policy/verifier.ts +181 -0
  70. package/src/providers/anthropic.ts +401 -0
  71. package/src/providers/auth-store.ts +139 -0
  72. package/src/providers/build.ts +136 -0
  73. package/src/providers/detect.ts +126 -0
  74. package/src/providers/effort.ts +165 -0
  75. package/src/providers/guards.ts +107 -0
  76. package/src/providers/oauth.ts +326 -0
  77. package/src/providers/presets.ts +122 -0
  78. package/src/providers/provision.ts +298 -0
  79. package/src/providers/responses.ts +371 -0
  80. package/src/providers/router.ts +247 -0
  81. package/src/repo/repomap.ts +470 -0
  82. package/src/sandbox/docker.ts +129 -0
  83. package/src/sandbox/os.ts +193 -0
  84. package/src/session/checkpoint.ts +543 -0
  85. package/src/session/journal.ts +1347 -0
  86. package/src/session/persistence.ts +446 -0
  87. package/src/session/shadow-git.ts +351 -0
  88. package/src/session/turn-marker.ts +118 -0
  89. package/src/skills/loader.ts +117 -0
  90. package/src/telemetry/trace.ts +283 -0
  91. package/src/tools/ask_user.ts +54 -0
  92. package/src/tools/bash.ts +400 -0
  93. package/src/tools/code_run.ts +96 -0
  94. package/src/tools/delete_file.ts +31 -0
  95. package/src/tools/edit.ts +204 -0
  96. package/src/tools/git.ts +301 -0
  97. package/src/tools/glob.ts +90 -0
  98. package/src/tools/grep.ts +281 -0
  99. package/src/tools/hashline.ts +66 -0
  100. package/src/tools/index.ts +103 -0
  101. package/src/tools/lsp.ts +346 -0
  102. package/src/tools/mcp_call.ts +163 -0
  103. package/src/tools/memory.ts +144 -0
  104. package/src/tools/move_file.ts +47 -0
  105. package/src/tools/patch.ts +86 -0
  106. package/src/tools/read_file.ts +130 -0
  107. package/src/tools/read_image.ts +80 -0
  108. package/src/tools/submit_result.ts +49 -0
  109. package/src/tools/task.ts +346 -0
  110. package/src/tools/todo.ts +201 -0
  111. package/src/tools/web_fetch.ts +161 -0
  112. package/src/tools/web_search.ts +156 -0
  113. package/src/tools/write_file.ts +42 -0
  114. package/src/ui/approval/prompt.ts +76 -0
  115. package/src/ui/assistant/simple.ts +568 -0
  116. package/src/ui/assistant/turn-status.ts +303 -0
  117. package/src/ui/contract.ts +55 -0
  118. package/src/ui/footer.ts +105 -0
  119. package/src/ui/input/input.ts +805 -0
  120. package/src/ui/input/prompt-engine.ts +606 -0
  121. package/src/ui/render/collapse.ts +84 -0
  122. package/src/ui/render/detail.ts +24 -0
  123. package/src/ui/render/diff.ts +181 -0
  124. package/src/ui/render/errors.ts +239 -0
  125. package/src/ui/render/format.ts +54 -0
  126. package/src/ui/render/highlight.ts +294 -0
  127. package/src/ui/render/markdown.ts +120 -0
  128. package/src/ui/render/money.ts +12 -0
  129. package/src/ui/render/reasoning.ts +20 -0
  130. package/src/ui/render/sanitize.ts +80 -0
  131. package/src/ui/render/table.ts +88 -0
  132. package/src/ui/render/theme.ts +339 -0
  133. package/src/ui/render/width.ts +256 -0
  134. package/src/ui/render/wrap.ts +120 -0
  135. package/src/ui/runtime/bus-debug.ts +83 -0
  136. package/src/ui/runtime/chrome.ts +301 -0
  137. package/src/ui/runtime/spinner.ts +77 -0
  138. package/src/ui/runtime/statusline.ts +227 -0
  139. package/src/ui/screens/model-manager.ts +434 -0
  140. package/src/ui/screens/overlay.ts +61 -0
  141. package/src/ui/screens/picker.ts +307 -0
  142. package/src/ui/screens/provider-manager.ts +450 -0
  143. package/src/ui/screens/wizard.ts +132 -0
  144. package/vendor/minicore/VENDOR.md +29 -0
  145. package/vendor/minicore/package.json +21 -0
  146. package/vendor/minicore/src/core/budget.ts +26 -0
  147. package/vendor/minicore/src/core/compact.ts +76 -0
  148. package/vendor/minicore/src/core/errors.ts +60 -0
  149. package/vendor/minicore/src/core/events.ts +74 -0
  150. package/vendor/minicore/src/core/executor.ts +139 -0
  151. package/vendor/minicore/src/core/history.ts +32 -0
  152. package/vendor/minicore/src/core/index.ts +42 -0
  153. package/vendor/minicore/src/core/loop.ts +344 -0
  154. package/vendor/minicore/src/core/permission.ts +24 -0
  155. package/vendor/minicore/src/core/provider.ts +39 -0
  156. package/vendor/minicore/src/core/recovery.ts +34 -0
  157. package/vendor/minicore/src/core/session.ts +327 -0
  158. package/vendor/minicore/src/core/snapshot.ts +142 -0
  159. package/vendor/minicore/src/core/tokens.ts +111 -0
  160. package/vendor/minicore/src/core/tool.ts +118 -0
  161. package/vendor/minicore/src/core/types.ts +50 -0
  162. package/vendor/minicore/src/providers/openai-compat.ts +366 -0
@@ -0,0 +1,86 @@
1
+ import { stat } from "node:fs/promises"
2
+ import type { Tool } from "#minicore"
3
+ import { LIMITS } from "../constants.ts"
4
+ import { atomicWriteText } from "../lib/atomic-write.ts"
5
+ import { assertSafeWriteTarget, resolveSafePath, safeReadFile } from "../lib/safe-open.ts"
6
+ import { flexibleMatch } from "./edit.ts"
7
+
8
+ // Apply SEARCH/REPLACE block (a la Aider) ke file. Search block harus match
9
+ // tepat sekali (dengan toleransi fuzzy). Bisa multiple patches.
10
+ export const applyPatchTool: Tool = {
11
+ name: "apply_patch",
12
+ description:
13
+ "Apply SEARCH/REPLACE block(s) to a file. Each search must match exactly once. Blocks apply sequentially to the same content (max 50 blocks per call). Prefer for multiple changes in one file; use edit for a single small change.",
14
+ parameters: {
15
+ type: "object",
16
+ properties: {
17
+ path: { type: "string", description: "path relative to the workspace" },
18
+ patches: {
19
+ type: "array",
20
+ description: "Array of {search, replace} blocks. Applied sequentially to the same content.",
21
+ items: {
22
+ type: "object",
23
+ properties: {
24
+ search: {
25
+ type: "string",
26
+ description: "code block to be replaced (exact or fuzzy match)",
27
+ },
28
+ replace: { type: "string", description: "replacement code block" },
29
+ },
30
+ required: ["search", "replace"],
31
+ additionalProperties: false,
32
+ },
33
+ },
34
+ },
35
+ required: ["path", "patches"],
36
+ additionalProperties: false,
37
+ },
38
+ async execute({ path, patches }, ctx) {
39
+ ctx.signal.throwIfAborted()
40
+ const p = path as string
41
+ const root = (ctx as { cwd?: string }).cwd ?? process.cwd()
42
+ // Verifikasi path terpusat (logis + target nyata) — detail di safe-open.ts.
43
+ const { abs, real: realAbs } = await resolveSafePath(p, root)
44
+ // Tolak menimpa symlink final (swap antara cek dan tulis gagal tutup).
45
+ await assertSafeWriteTarget(abs, root)
46
+ const st = await stat(realAbs).catch(() => null)
47
+ if (!st) throw new Error(`file not found: ${p}`)
48
+ if (st.size > LIMITS.READ_FILE_MAX_BYTES) throw new Error(`file too large: ${p} (${st.size})`)
49
+
50
+ // Pakai safeReadFile (O_NOFOLLOW) agar swap symlink di antara cek dan baca gagal ELOOP.
51
+ let content = await safeReadFile(abs, root)
52
+ const patchList = patches as { search: string; replace: string }[]
53
+ if (patchList.length > 50) throw new Error(`too many patches: ${patchList.length} (max 50)`)
54
+ const applied: string[] = []
55
+
56
+ for (let i = 0; i < patchList.length; i++) {
57
+ ctx.signal.throwIfAborted()
58
+ const { search: oldS, replace: newS } = patchList[i]!
59
+ if (oldS === newS) {
60
+ applied.push(`[${i}] skipped: oldString == newString`)
61
+ continue
62
+ }
63
+ const match = flexibleMatch(content, oldS)
64
+ if (!match) throw new Error(`patch[${i}]: search block not found in ${p}`)
65
+ // ensure uniqueness untuk semua mode
66
+ const second = flexibleMatch(content.slice(match.end), oldS)
67
+ if (second) {
68
+ throw new Error(
69
+ `patch[${i}]: search block found multiple times in ${p} — provide more context`,
70
+ )
71
+ }
72
+ content = content.slice(0, match.start) + newS + content.slice(match.end)
73
+ if (content.length > LIMITS.WRITE_FILE_MAX_CHARS)
74
+ throw new Error(`result too large after patch[${i}]: ${content.length} chars (max 5M)`)
75
+ const note = match.mode !== "exact" ? ` (${match.mode} match)` : ""
76
+ applied.push(`[${i}] replaced ${oldS.length} → ${newS.length} chars${note}`)
77
+ }
78
+
79
+ if (content.length > LIMITS.WRITE_FILE_MAX_CHARS)
80
+ throw new Error(`result too large: ${content.length} chars (max 5M)`)
81
+
82
+ await atomicWriteText(realAbs, content)
83
+
84
+ return `applied ${applied.length} patch(es) to ${realAbs}:\n${applied.join("\n")}`
85
+ },
86
+ }
@@ -0,0 +1,130 @@
1
+ import { isAbsolute, resolve } from "node:path"
2
+ import type { Tool } from "#minicore"
3
+ import { LIMITS } from "../constants.ts"
4
+ import { safeOpenRead } from "../lib/safe-open.ts"
5
+ import { scrubSecrets } from "../policy/scrub.ts"
6
+
7
+ // defense-in-depth: also jail inside tool (permission layer is primary)
8
+
9
+ /**
10
+ * Format isi file sebagai `N: <line>` dengan paging.
11
+ *
12
+ * Sebelum ini tool hanya bisa membaca file utuh, jadi file di atas
13
+ * READ_FILE_MAX_BYTES sama sekali tak terjangkau. Nomor baris juga penting:
14
+ * tanpa itu model harus menghitung sendiri saat menyusun `edit`/`apply_patch`
15
+ * dan sering salah rujuk.
16
+ *
17
+ * Diekspor untuk test.
18
+ */
19
+ export function formatLines(
20
+ raw: string,
21
+ opts: { offset?: number; limit?: number } = {},
22
+ ): { text: string; totalLines: number; from: number; to: number } {
23
+ // File yang diakhiri newline tidak menghasilkan baris kosong tambahan.
24
+ const all = raw.split("\n")
25
+ if (all.length > 1 && all[all.length - 1] === "") all.pop()
26
+ const totalLines = all.length
27
+
28
+ const rawOffset = Number(opts.offset ?? 1)
29
+ // 1-indexed; offset 0 diperlakukan sebagai 1 supaya model tak perlu menebak.
30
+ const from = Number.isFinite(rawOffset) ? Math.max(1, Math.floor(rawOffset)) : 1
31
+ const rawLimit = Number(opts.limit ?? LIMITS.READ_FILE_DEFAULT_LINE_LIMIT)
32
+ const limit = Number.isFinite(rawLimit)
33
+ ? Math.min(Math.max(1, Math.floor(rawLimit)), LIMITS.READ_FILE_MAX_LINE_LIMIT)
34
+ : LIMITS.READ_FILE_DEFAULT_LINE_LIMIT
35
+
36
+ if (from > totalLines) {
37
+ return {
38
+ text: `(offset ${from} is past the end of the file — ${totalLines} lines total)`,
39
+ totalLines,
40
+ from,
41
+ to: from,
42
+ }
43
+ }
44
+
45
+ const to = Math.min(totalLines, from + limit - 1)
46
+ const width = String(to).length
47
+ const body = all
48
+ .slice(from - 1, to)
49
+ .map((line, i) => {
50
+ const n = String(from + i).padStart(width, " ")
51
+ const capped =
52
+ line.length > LIMITS.READ_FILE_MAX_LINE_CHARS
53
+ ? `${line.slice(0, LIMITS.READ_FILE_MAX_LINE_CHARS)}… [line truncated]`
54
+ : line
55
+ return `${n}: ${capped}`
56
+ })
57
+ .join("\n")
58
+
59
+ const remaining = totalLines - to
60
+ const footer =
61
+ remaining > 0
62
+ ? `\n… ${remaining} more lines (continue: offset=${to + 1})`
63
+ : from > 1
64
+ ? "\n(end of file)"
65
+ : ""
66
+ return { text: body + footer, totalLines, from, to }
67
+ }
68
+
69
+ export const readFileTool: Tool = {
70
+ name: "read_file",
71
+ description:
72
+ "Read a text file in the workspace with line numbers. Output is N: <line> and a footer telling the next offset. Large files MUST be read in chunks via offset/limit (max 2MB per file, 5000 lines per call, 2000 chars per line). Prefer this over `cat` in bash. Cannot read outside the workspace, secrets, or node_modules.",
73
+ parameters: {
74
+ type: "object",
75
+ properties: {
76
+ path: { type: "string", description: "path relative to the workspace (e.g. src/a.ts)" },
77
+ offset: { type: "number", description: "starting line (1-indexed, default 1)" },
78
+ limit: { type: "number", description: "number of lines (default 2000, max 5000)" },
79
+ },
80
+ required: ["path"],
81
+ additionalProperties: false,
82
+ },
83
+ async execute({ path, offset, limit }, ctx) {
84
+ ctx.signal.throwIfAborted()
85
+ const p = path as string
86
+ const root = (ctx as { cwd?: string }).cwd ?? process.cwd()
87
+ const abs = isAbsolute(p) ? resolve(p) : resolve(root, p)
88
+ // Semua verifikasi path (jail + sensitif + O_NOFOLLOW) terjadi di SATU
89
+ // titik saat open — detail di safe-open.ts. Tidak ada resolve/stat
90
+ // terpisah: handle dipakai untuk stat (cap ukuran) lalu baca.
91
+ let handle: Awaited<ReturnType<typeof safeOpenRead>>["handle"]
92
+ try {
93
+ ;({ handle } = await safeOpenRead(abs, root))
94
+ } catch (e) {
95
+ // ENOENT → pesan seragam; sisanya (jail/sensitif/ELOOP/raw IO) apa adanya
96
+ const msg = (e as Error).message ?? ""
97
+ if ((e as NodeJS.ErrnoException).code === "ENOENT" || msg.includes("ENOENT"))
98
+ throw new Error(`file not found: ${p}`)
99
+ throw e
100
+ }
101
+ let raw: string
102
+ try {
103
+ const st = await handle.stat().catch(() => null)
104
+ if (!st) throw new Error(`file not found: ${p}`)
105
+ if (st.isDirectory()) throw new Error(`path is a directory, not a file: ${p}`)
106
+
107
+ const paged = offset != null || limit != null
108
+ // Hard cap absolut 50M bahkan untuk paged — cegah OOM 1GB via offset/limit
109
+ const HARD_CAP = 50 * 1024 * 1024
110
+ if (st.size > HARD_CAP)
111
+ throw new Error(`file too large: ${p} (${st.size} bytes > ${HARD_CAP}) — hard cap`)
112
+ // File raksasa tetap bisa dibaca SELAMA pemanggil menyebut rentang baris.
113
+ // Tanpa offset/limit kita menolak seperti sebelumnya agar tidak diam-diam
114
+ // memotong konteks yang model kira utuh.
115
+ if (st.size > LIMITS.READ_FILE_MAX_BYTES && !paged) {
116
+ throw new Error(
117
+ `file too large: ${p} (${st.size} bytes > ${LIMITS.READ_FILE_MAX_BYTES}) — read it in chunks with offset/limit`,
118
+ )
119
+ }
120
+ raw = await handle.readFile("utf8")
121
+ } finally {
122
+ await handle.close().catch(() => {})
123
+ }
124
+ const { text } = formatLines(raw, {
125
+ offset: offset as number | undefined,
126
+ limit: limit as number | undefined,
127
+ })
128
+ return scrubSecrets(text)
129
+ },
130
+ }
@@ -0,0 +1,80 @@
1
+ import { isAbsolute, resolve } from "node:path"
2
+ import type { Tool } from "#minicore"
3
+ import { LIMITS } from "../constants.ts"
4
+ import { safeOpenRead } from "../lib/safe-open.ts"
5
+ import { estimateImageTokens } from "../policy/context.ts"
6
+
7
+ // Batas b64 = batas truncate kernel yang sebenarnya: toolResultMaxTokens
8
+ // (default 4096) × DEFAULT_CHARS_PER_TOKEN (4) = 16.384 chars, dengan margin
9
+ // kecil untuk header data-URL + baris metadata. Sinkron dengan komentar di
10
+ // vendor tokens.ts — angka lain (BASH_OUTPUT×5) melanggar intent anti-korup.
11
+ const IMAGE_B64_MAX_CHARS = 4096 * 4 - 200
12
+
13
+ export const readImageTool: Tool = {
14
+ name: "read_image",
15
+ description:
16
+ "Read an image file as base64 for vision review (PNG/JPG/WebP/GIF). Returns data URL + token estimate.",
17
+ parameters: {
18
+ type: "object",
19
+ properties: {
20
+ path: { type: "string", description: "path image relatif" },
21
+ },
22
+ required: ["path"],
23
+ additionalProperties: false,
24
+ },
25
+ async execute({ path }, ctx) {
26
+ ctx.signal.throwIfAborted()
27
+ const p = path as string
28
+ const root = (ctx as { cwd?: string }).cwd ?? process.cwd()
29
+ const abs = isAbsolute(p) ? resolve(p) : resolve(root, p)
30
+ // TOCTOU-safe: safeOpenRead = realpath(abs) → cek jail+sensitif di dalam
31
+ // root → open(preReal, O_NOFOLLOW). Bukan open(abs) yang bisa di-swap jadi
32
+ // symlink luar di antara cek dan open — semua verifikasi ada di titik ini.
33
+ let handle: Awaited<ReturnType<typeof safeOpenRead>>["handle"]
34
+ try {
35
+ ;({ handle } = await safeOpenRead(abs, root))
36
+ } catch (e) {
37
+ // ENOENT → pesan seragam; sisanya (jail/sensitif/ELOOP/raw IO) apa adanya
38
+ const msg = (e as Error).message ?? ""
39
+ if ((e as NodeJS.ErrnoException).code === "ENOENT" || msg.includes("ENOENT"))
40
+ throw new Error(`file not found: ${p}`)
41
+ throw e
42
+ }
43
+ let buf: Buffer
44
+ let st: { size: number } | null = null
45
+ try {
46
+ st = await handle.stat().catch(() => null)
47
+ if (!st) throw new Error(`file not found: ${p}`)
48
+ if (st.size > LIMITS.READ_FILE_MAX_BYTES)
49
+ throw new Error(`image too large: ${st.size} bytes (max 2M)`)
50
+ buf = await handle.readFile()
51
+ // Cek b64 agar tidak terpotong diam-diam oleh serializeContent.
52
+ // Investigasi Phase 5 (probe E-1): batas kernel truncate yang SEBENARNYA
53
+ // = maxTokens(4096) × 4 = 16.384 chars (toolResultMaxTokens TIDAK pernah
54
+ // dioverride). Guard lama memakai BASH_OUTPUT_MAX_CHARS×5 = 100k — 6,1×
55
+ // di atas kernel → gambar >~12KB lolos guard lalu DIPOTONG TENGAH oleh
56
+ // kernel = base64 korup terkirim. Guard kini memakai angka kernel.
57
+ const estB64 = Math.ceil((buf.byteLength * 4) / 3) + 30
58
+ if (estB64 > IMAGE_B64_MAX_CHARS)
59
+ throw new Error(
60
+ `image too large: base64 ~${estB64} chars exceeds the ${IMAGE_B64_MAX_CHARS}-char context limit — compress first (e.g. via code_run sharp)`,
61
+ )
62
+ } finally {
63
+ await handle.close().catch(() => {})
64
+ }
65
+ const b64 = buf.toString("base64")
66
+ const ext = p.split(".").pop()?.toLowerCase() ?? "png"
67
+ const mime =
68
+ ext === "jpg" || ext === "jpeg"
69
+ ? "image/jpeg"
70
+ : ext === "webp"
71
+ ? "image/webp"
72
+ : ext === "gif"
73
+ ? "image/gif"
74
+ : "image/png"
75
+ const tokens = estimateImageTokens(buf.byteLength)
76
+ // S4 — kirim utuh + laporkan bytes (dulu slice 200k diam-diam → gambar korup).
77
+ // File sudah di-cap BASH_OUTPUT_MAX_CHARS di atas, jadi b64 selalu muat konteks.
78
+ return `data:${mime};base64,${b64}\n(${buf.byteLength} bytes ${mime}, tokens ~${tokens})`
79
+ },
80
+ }
@@ -0,0 +1,49 @@
1
+ import type { Tool } from "#minicore"
2
+
3
+ // Hasil terstruktur akhir task — pengganti response_format:json_schema yang
4
+ // tidak didukung semua provider. Tanpa tool ini model "menyimpulkan" dalam
5
+ // teks bebas dan CLI (exec --json) harus menebak batas JSON dari prosa.
6
+ // State per proses cukup: satu run CLI = satu sesi (seperti todoSession).
7
+
8
+ export interface SubmittedResult {
9
+ result: unknown
10
+ summary?: string
11
+ at: number
12
+ }
13
+
14
+ let last: SubmittedResult | null = null
15
+
16
+ export function getSubmittedResult(): SubmittedResult | null {
17
+ return last
18
+ }
19
+
20
+ export function clearSubmittedResult(): void {
21
+ last = null
22
+ }
23
+
24
+ export const submitResultTool: Tool = {
25
+ name: "submit_result",
26
+ description:
27
+ "Submit the final structured result of this task as a JSON object (instead of burying it in prose). Call once when done; exec --json surfaces it verbatim.",
28
+ parameters: {
29
+ type: "object",
30
+ properties: {
31
+ result: {
32
+ type: "object",
33
+ description: "hasil akhir terstruktur (object JSON, bukan string)",
34
+ },
35
+ summary: { type: "string", description: "ringkasan satu baris untuk log" },
36
+ },
37
+ required: ["result"],
38
+ additionalProperties: false,
39
+ },
40
+ async execute({ result, summary }, ctx) {
41
+ ctx.signal.throwIfAborted()
42
+ if (!result || typeof result !== "object" || Array.isArray(result))
43
+ throw new Error("result must be a JSON object")
44
+ const s = typeof summary === "string" ? summary.slice(0, 300) : undefined
45
+ last = { result, ...(s ? { summary: s } : {}), at: Date.now() }
46
+ const bytes = JSON.stringify(result).length
47
+ return `submitted (${bytes} bytes)${s ? `: ${s}` : ""}`
48
+ },
49
+ }