minicode-ai 0.11.0 → 0.13.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.
Files changed (221) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/LICENSE +21 -21
  3. package/README.md +4 -4
  4. package/cli/args.ts +46 -0
  5. package/cli/commands/acp.ts +163 -10
  6. package/cli/commands/config.ts +33 -18
  7. package/cli/commands/daemon.ts +515 -0
  8. package/cli/commands/exec.ts +145 -53
  9. package/cli/commands/openwork.ts +986 -0
  10. package/cli/commands/sessions.ts +4 -1
  11. package/cli/commands/stats.ts +34 -4
  12. package/cli/commands.ts +217 -2
  13. package/cli/index.ts +146 -14
  14. package/cli/recovery-warning.ts +115 -0
  15. package/cli/router.ts +32 -1
  16. package/cli/setup.ts +2332 -171
  17. package/cli/tui.ts +113 -7
  18. package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +489 -0
  19. package/docs/OUTPUT_EVENT_MODEL.md +289 -0
  20. package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +391 -0
  21. package/docs/OUTPUT_PROTOCOL_SPEC.md +285 -0
  22. package/docs/OUTPUT_RENDERING_SPEC.md +248 -0
  23. package/docs/OUTPUT_UX_RULES.md +449 -0
  24. package/docs/PLAN_UIUX_V6.md +2 -2
  25. package/docs/README.md +4 -3
  26. package/docs/TERMINAL_CONTRACT.md +278 -66
  27. package/docs/architecture.md +89 -7
  28. package/docs/changelog.md +1 -1
  29. package/docs/choosing-mode.md +2 -2
  30. package/docs/cli.md +9 -5
  31. package/docs/concepts.md +1 -1
  32. package/docs/contributing.md +9 -2
  33. package/docs/environment.md +6 -2
  34. package/docs/exec.md +46 -5
  35. package/docs/memory-sessions.md +2 -0
  36. package/docs/policy-sandbox.md +1 -1
  37. package/docs/pricing-budget.md +1 -1
  38. package/docs/quickstart.md +2 -2
  39. package/docs/repl.md +6 -2
  40. package/docs/security-model.md +1 -1
  41. package/docs/security.md +1 -1
  42. package/docs/skills.md +2 -2
  43. package/docs/terminal.md +9 -5
  44. package/docs/tools.md +1 -1
  45. package/package.json +35 -5
  46. package/src/app/session.ts +261 -15
  47. package/src/app/tool-layer.ts +94 -7
  48. package/src/daemon/approvals.ts +361 -0
  49. package/src/daemon/capability.ts +145 -0
  50. package/src/daemon/children.ts +142 -0
  51. package/src/daemon/client.ts +267 -0
  52. package/src/daemon/control.ts +350 -0
  53. package/src/daemon/discovery.ts +234 -0
  54. package/src/daemon/feed.ts +155 -0
  55. package/src/daemon/framing.ts +94 -0
  56. package/src/daemon/host.ts +316 -0
  57. package/src/daemon/protocol.ts +217 -0
  58. package/src/daemon/resource.ts +170 -0
  59. package/src/daemon/sanitize.ts +57 -0
  60. package/src/daemon/server.ts +627 -0
  61. package/src/daemon/store.ts +317 -0
  62. package/src/daemon/subscription.ts +270 -0
  63. package/src/daemon/telemetry.ts +81 -0
  64. package/src/hooks/run.ts +12 -1
  65. package/src/lib/atomic-write.ts +29 -3
  66. package/src/lib/db-path.ts +26 -0
  67. package/src/lib/keystore.ts +544 -42
  68. package/src/lib/net.ts +43 -1
  69. package/src/lib/safe-open.ts +116 -1
  70. package/src/lib/session-id.ts +15 -0
  71. package/src/lsp/client.ts +123 -5
  72. package/src/mcp/client.ts +139 -17
  73. package/src/mcp/server.ts +177 -50
  74. package/src/mcp/transport.ts +16 -19
  75. package/src/memory/vector.ts +770 -55
  76. package/src/policy/allowlist.ts +14 -2
  77. package/src/policy/bash-guard.ts +105 -10
  78. package/src/policy/compaction.ts +82 -5
  79. package/src/policy/consequence-engine.ts +220 -0
  80. package/src/policy/context.ts +132 -0
  81. package/src/policy/executor.ts +187 -121
  82. package/src/policy/no-progress.ts +559 -0
  83. package/src/policy/permission.ts +4 -8
  84. package/src/policy/pricing.ts +17 -3
  85. package/src/policy/scrub.ts +69 -2
  86. package/src/policy/tool-contract.ts +515 -0
  87. package/src/policy/usage.ts +310 -24
  88. package/src/policy/verifier.ts +6 -3
  89. package/src/policy/work-mode.ts +182 -0
  90. package/src/presentation/adapter.ts +533 -26
  91. package/src/presentation/events.ts +151 -0
  92. package/src/presentation/model.ts +180 -27
  93. package/src/presentation/projection.ts +858 -0
  94. package/src/presentation/reducer.ts +645 -310
  95. package/src/presentation/store.ts +12 -7
  96. package/src/providers/anthropic.ts +18 -10
  97. package/src/providers/responses.ts +17 -7
  98. package/src/runtime/capability.ts +409 -0
  99. package/src/runtime/child-execution.ts +274 -0
  100. package/src/runtime/composition.ts +958 -0
  101. package/src/runtime/dispatch.ts +591 -0
  102. package/src/runtime/execution-backend.ts +632 -0
  103. package/src/runtime/execution-events.ts +272 -0
  104. package/src/runtime/execution-id.ts +230 -0
  105. package/src/runtime/execution-journal.ts +926 -0
  106. package/src/runtime/execution-kernel.ts +456 -0
  107. package/src/runtime/execution-registry.ts +379 -0
  108. package/src/runtime/process-supervision.ts +276 -0
  109. package/src/runtime/production-execution.ts +551 -0
  110. package/src/runtime/production-runtime.ts +217 -0
  111. package/src/runtime/recovery-safety.ts +70 -0
  112. package/src/runtime/recovery.ts +477 -0
  113. package/src/runtime/runtime-capabilities.ts +179 -0
  114. package/src/runtime/runtime-diagnostics.ts +141 -0
  115. package/src/runtime/runtime-host.ts +365 -0
  116. package/src/runtime/runtime-status-facts.ts +222 -0
  117. package/src/runtime/runtime-status-provider.ts +74 -0
  118. package/src/runtime/runtime-status.ts +459 -0
  119. package/src/runtime/runtime-task-admission.ts +101 -0
  120. package/src/runtime/supervisor.ts +444 -0
  121. package/src/session/authority.ts +168 -0
  122. package/src/session/checkpoint.ts +88 -1
  123. package/src/session/context-adapter.ts +251 -0
  124. package/src/session/context-assembly.ts +242 -0
  125. package/src/session/context-identity.ts +389 -0
  126. package/src/session/context-projection.ts +248 -0
  127. package/src/session/context-selector.ts +500 -0
  128. package/src/session/cross-session-adoption.ts +249 -0
  129. package/src/session/full-history-fold.ts +171 -0
  130. package/src/session/identity.ts +192 -0
  131. package/src/session/journal.ts +805 -102
  132. package/src/session/open-work-intent.ts +732 -0
  133. package/src/session/open-work.ts +767 -0
  134. package/src/session/pending-tools.ts +94 -0
  135. package/src/session/persistence.ts +3569 -127
  136. package/src/session/runtime-header.ts +208 -0
  137. package/src/session/shadow-git.ts +13 -5
  138. package/src/session/verification.ts +1623 -0
  139. package/src/task/assignment.ts +136 -0
  140. package/src/task/autonomous-adapter.ts +168 -0
  141. package/src/task/autonomous-context.ts +630 -0
  142. package/src/task/autonomous-policy.ts +490 -0
  143. package/src/task/continuity.ts +179 -0
  144. package/src/task/execution-cancellation.ts +165 -0
  145. package/src/task/graph-validate.ts +379 -0
  146. package/src/task/graph.ts +305 -0
  147. package/src/task/identity.ts +230 -0
  148. package/src/task/model.ts +417 -0
  149. package/src/task/production-scheduler.ts +293 -0
  150. package/src/task/readiness.ts +229 -0
  151. package/src/task/scheduler-observability.ts +387 -0
  152. package/src/task/scheduler.ts +1197 -0
  153. package/src/task/scheduling-policy.ts +165 -0
  154. package/src/task/session-authority.ts +148 -0
  155. package/src/task/session-ownership.ts +211 -0
  156. package/src/task/store.ts +2887 -0
  157. package/src/task/sync.ts +343 -0
  158. package/src/task/trigger.ts +260 -0
  159. package/src/tools/bash.ts +377 -211
  160. package/src/tools/code_run.ts +1 -1
  161. package/src/tools/delete_file.ts +1 -1
  162. package/src/tools/edit.ts +33 -6
  163. package/src/tools/evidence.ts +30 -0
  164. package/src/tools/git.ts +4 -4
  165. package/src/tools/glob.ts +12 -3
  166. package/src/tools/grep.ts +1 -1
  167. package/src/tools/lsp.ts +4 -4
  168. package/src/tools/mcp_call.ts +11 -4
  169. package/src/tools/memory.ts +153 -18
  170. package/src/tools/move_file.ts +1 -1
  171. package/src/tools/patch.ts +1 -1
  172. package/src/tools/read_file.ts +1 -1
  173. package/src/tools/read_image.ts +1 -1
  174. package/src/tools/submit_result.ts +1 -1
  175. package/src/tools/task.ts +437 -41
  176. package/src/tools/todo.ts +662 -35
  177. package/src/tools/web_fetch.ts +4 -2
  178. package/src/tools/web_search.ts +9 -3
  179. package/src/tools/write_file.ts +1 -1
  180. package/src/ui/assistant/simple.ts +123 -50
  181. package/src/ui/assistant/turn-status.ts +17 -3
  182. package/src/ui/contract.ts +184 -0
  183. package/src/ui/footer.ts +54 -18
  184. package/src/ui/i18n/en.ts +62 -6
  185. package/src/ui/i18n/id.ts +62 -6
  186. package/src/ui/input/prompt-engine.ts +120 -25
  187. package/src/ui/render/errors.ts +39 -1
  188. package/src/ui/render/markdown-table.ts +455 -0
  189. package/src/ui/render/markdown.ts +22 -1
  190. package/src/ui/render/table-grid.ts +184 -0
  191. package/src/ui/render/table.ts +15 -76
  192. package/src/ui/runtime/screen.ts +7 -2
  193. package/src/ui/runtime/statusline.ts +25 -6
  194. package/src/ui/tui/app.ts +598 -133
  195. package/src/ui/tui/transcript.ts +531 -89
  196. package/vendor/minicore/VENDOR.md +1 -1
  197. package/vendor/minicore/src/core/budget.ts +25 -25
  198. package/vendor/minicore/src/core/compact.ts +75 -75
  199. package/vendor/minicore/src/core/errors.ts +59 -59
  200. package/vendor/minicore/src/core/events.ts +73 -73
  201. package/vendor/minicore/src/core/executor.ts +139 -139
  202. package/vendor/minicore/src/core/history.ts +31 -31
  203. package/vendor/minicore/src/core/index.ts +41 -41
  204. package/vendor/minicore/src/core/loop.ts +355 -355
  205. package/vendor/minicore/src/core/permission.ts +22 -22
  206. package/vendor/minicore/src/core/provider.ts +39 -39
  207. package/vendor/minicore/src/core/recovery.ts +35 -35
  208. package/vendor/minicore/src/core/session.ts +327 -327
  209. package/vendor/minicore/src/core/snapshot.ts +146 -146
  210. package/vendor/minicore/src/core/tokens.ts +107 -107
  211. package/vendor/minicore/src/core/tool.ts +115 -115
  212. package/vendor/minicore/src/core/types.ts +50 -50
  213. package/vendor/minicore/src/providers/openai-compat.ts +417 -417
  214. package/AGENTS.md +0 -45
  215. package/PLAN.md +0 -491
  216. package/docs/ARCHITECTURE.html +0 -1248
  217. package/docs/CONTROL-PLANE-MAP.md +0 -139
  218. package/docs/HARNESS.md +0 -150
  219. package/docs/SUMMARY.md +0 -52
  220. package/docs/UI_RENDER_PIPELINE.md +0 -165
  221. package/docs/USAGE.md +0 -11
@@ -1,7 +1,7 @@
1
1
  import type { Tool } from "#minicore"
2
2
  import { LIMITS } from "../constants.ts"
3
3
  import { isPrivateHostWithDns } from "../lib/net.ts"
4
- import { scrubSecrets } from "../policy/scrub.ts"
4
+ import { fenceUntrustedToolOutput, isAlreadyFenced, scrubSecrets } from "../policy/scrub.ts"
5
5
 
6
6
  const MAX_REDIRECTS = LIMITS.WEB_FETCH_MAX_REDIRECTS
7
7
  // Hard-cap pembacaan body SEBELUM slicing — cegah OOM dari response raksasa.
@@ -161,7 +161,9 @@ export const webFetchTool: Tool = {
161
161
  shown.username = ""
162
162
  shown.password = ""
163
163
  const header = `[${scrubSecrets(shown.toString())} ${res.status} ${contentType}]\n`
164
- return (header + sliced + truncated).slice(0, limit + 500)
164
+ const content = (header + sliced + truncated).slice(0, limit + 500)
165
+ // [Fase 4 / TOOL-05] Pagar data tak-terpercaya pada output web_fetch
166
+ return isAlreadyFenced(content) ? content : fenceUntrustedToolOutput("web_fetch", content)
165
167
  } finally {
166
168
  clearTimeout(timeout)
167
169
  ctx.signal.removeEventListener("abort", onParentAbort)
@@ -1,6 +1,6 @@
1
1
  import type { Tool } from "#minicore"
2
2
  import { isPrivateHost } from "../lib/net.ts"
3
- import { scrubSecrets } from "../policy/scrub.ts"
3
+ import { fenceUntrustedToolOutput, isAlreadyFenced, scrubSecrets } from "../policy/scrub.ts"
4
4
  import { readBodyCapped } from "./web_fetch.ts"
5
5
 
6
6
  // Penanda truncation (temuan audit #02): snippet/total yang dipotong
@@ -142,12 +142,18 @@ export const webSearchTool: Tool = {
142
142
  }
143
143
  }
144
144
  if (results.length) {
145
- return capTotal(
145
+ const content = capTotal(
146
146
  `[duckduckgo ${results.length} results for "${q}"]\n${results.map((r, i) => `${i + 1}. ${r.title}\n ${r.url}`).join("\n")}`,
147
147
  8000,
148
148
  )
149
+ return isAlreadyFenced(content)
150
+ ? content
151
+ : fenceUntrustedToolOutput("web_search", content, `query=${q}`)
149
152
  }
150
- return `[web_search] no structured results for "${q}" — coba set TAVILY_API_KEY atau BRAVE_API_KEY untuk hasil lebih baik.`
153
+ const fallback = `[web_search] no structured results for "${q}" — coba set TAVILY_API_KEY atau BRAVE_API_KEY untuk hasil lebih baik.`
154
+ return isAlreadyFenced(fallback)
155
+ ? fallback
156
+ : fenceUntrustedToolOutput("web_search", fallback, `query=${q}`)
151
157
  } finally {
152
158
  clearTimeout(t)
153
159
  ctx.signal.removeEventListener("abort", onAbort)
@@ -22,7 +22,7 @@ export const writeFileTool: Tool = {
22
22
  async execute({ path, content }, ctx) {
23
23
  ctx.signal.throwIfAborted()
24
24
  const p = path as string
25
- const root = (ctx as { cwd?: string }).cwd ?? process.cwd()
25
+ const root = ctx.cwd ?? process.cwd()
26
26
  // Verifikasi path terpusat (logis + target nyata) — detail di safe-open.ts.
27
27
  const { real: realAbs } = await resolveSafePath(p, root)
28
28
  // Tolak menimpa symlink final (swap antara cek dan tulis gagal tutup).
@@ -4,6 +4,7 @@
4
4
  // MINICODE_COMPACT=1 atau setCompactMode (/compact).
5
5
  import { Buffer } from "node:buffer"
6
6
  import type {
7
+ PresentationPolicy,
7
8
  UiBus,
8
9
  UiPresentationActivity,
9
10
  UiPresentationEvent,
@@ -19,10 +20,10 @@ import {
19
20
  } from "../render/collapse.ts"
20
21
  import { detail } from "../render/detail.ts"
21
22
  import { renderDiffCard } from "../render/diff.ts"
22
- import { formatFriendly, friendlyError, friendlyFromCategory } from "../render/errors.ts"
23
23
  import { formatArgsPreview, formatProviderError, formatUsage } from "../render/format.ts"
24
24
  import { highlightCode } from "../render/highlight.ts"
25
- import { decorateMarkdown, type FenceMatch, parseFence } from "../render/markdown.ts"
25
+ import { decorateMarkdown, type FenceMatch, parseFence, renderInline } from "../render/markdown.ts"
26
+ import { MarkdownTableStream } from "../render/markdown-table.ts"
26
27
  import { reasoning } from "../render/reasoning.ts"
27
28
  import {
28
29
  cleanUntrusted,
@@ -31,6 +32,7 @@ import {
31
32
  sanitizeAnsiLine,
32
33
  stripSgr,
33
34
  } from "../render/sanitize.ts"
35
+ import { renderMarkdownTable } from "../render/table-grid.ts"
34
36
  import { c, glyphs, stripAnsi } from "../render/theme.ts"
35
37
  import { displayWidth, truncateToWidth } from "../render/width.ts"
36
38
  import { formatWrapped } from "../render/wrap.ts"
@@ -47,6 +49,8 @@ export interface SimpleOptions {
47
49
  quiet?: boolean
48
50
  getSnapshot?: () => UiPresentationSnapshot | null
49
51
  onPresentationEvent?: (handler: (event: UiPresentationEvent) => void) => () => void
52
+ /** Kebijakan kanonik dari composition root; absen = logika inline legacy. */
53
+ policy?: PresentationPolicy
50
54
  }
51
55
 
52
56
  // Buffer output turn terakhir untuk /copy: teks model (sudah sanitize, sama
@@ -54,11 +58,28 @@ export interface SimpleOptions {
54
58
  // scrollback milik terminal; ini konten yang berguna ditempel ulang. Cap agar
55
59
  // sesi panjang tak membengkakkan memori.
56
60
  const LAST_TURN_MAX_CHARS = 200_000
61
+ export const MAX_COPY_TURNS = 10
57
62
  let lastTurnText = ""
63
+ let previousTurnTexts: string[] = []
64
+
58
65
  /** Isi output turn terakhir (teks model + hasil tool). */
59
66
  export function getLastTurnText(): string {
60
67
  return lastTurnText
61
68
  }
69
+
70
+ export function getLastTurnTexts(count = 1): string[] {
71
+ const all = lastTurnText ? [...previousTurnTexts, lastTurnText] : [...previousTurnTexts]
72
+ const n = Number.isFinite(count) ? Math.max(1, Math.floor(count)) : 1
73
+ return all.slice(-n)
74
+ }
75
+
76
+ const archiveTurn = (): void => {
77
+ if (!lastTurnText) return
78
+ previousTurnTexts.push(lastTurnText)
79
+ if (previousTurnTexts.length > MAX_COPY_TURNS) previousTurnTexts.shift()
80
+ lastTurnText = ""
81
+ }
82
+
62
83
  const rememberTurn = (s: string) => {
63
84
  if (!s) return
64
85
  // Samakan dengan yang terlihat: kebijakan pipa (F2) berlaku juga untuk /copy.
@@ -132,7 +153,10 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
132
153
  // Shadowing disengaja agar ~20 call-site tak perlu diubah satu per satu.
133
154
  const wOut = opts.quiet ? (_: string) => {} : wOutDirect
134
155
  const wErr = opts.quiet ? (_: string) => {} : wErrDirect
135
- let streamBuffer = ""
156
+ previousTurnTexts = []
157
+ lastTurnText = ""
158
+ const tableStream = new MarkdownTableStream()
159
+ let plainLineBuffer = ""
136
160
  // Sanitizer sadar-stream per aliran teks (temuan F1): ekor escape yang
137
161
  // terpotong di batas chunk ditahan dan disambung ke chunk berikut SEBELUM
138
162
  // sanitasi — tanpa ini "ESC[" + "32m" tampil literal. Satu instans per
@@ -289,15 +313,36 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
289
313
  emitAnswer(formatWrapped(decorateMarkdown(line), w, true))
290
314
  emitAnswer("\n")
291
315
  }
292
- const flushBuf = () => {
293
- if (!streamBuffer) return
294
- const parts = streamBuffer.split("\n")
316
+ const consumePlainText = (text: string): void => {
317
+ const combined = plainLineBuffer + text
318
+ const parts = combined.split("\n")
295
319
  for (let i = 0; i < parts.length - 1; i++) flushLine(parts[i]!)
296
- streamBuffer = parts[parts.length - 1] ?? ""
320
+ plainLineBuffer = parts[parts.length - 1] ?? ""
321
+ }
322
+ const consumeTableEvents = (events: ReturnType<MarkdownTableStream["push"]>): void => {
323
+ for (const event of events) {
324
+ if (event.type === "text") {
325
+ consumePlainText(event.text)
326
+ continue
327
+ }
328
+ const width = process.stdout.columns || 80
329
+ const rendered = process.stdout.isTTY
330
+ ? renderMarkdownTable(event.table, width, renderInline)
331
+ : event.raw
332
+ emitAnswer(`${rendered}\n`)
333
+ }
334
+ }
335
+ const flushTableStream = (): void => {
336
+ consumeTableEvents(tableStream.flush())
337
+ if (plainLineBuffer) {
338
+ flushLine(plainLineBuffer)
339
+ plainLineBuffer = ""
340
+ }
297
341
  }
298
342
 
299
343
  const presentationEnabled = !!opts.getSnapshot
300
344
  const presentedTerminals = new Set<string>()
345
+ const presentedVerifications = new Set<string>()
301
346
  const presentationSnapshot = (): UiPresentationSnapshot | null => {
302
347
  if (!presentationEnabled || !opts.getSnapshot) return null
303
348
  try {
@@ -320,19 +365,33 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
320
365
  }
321
366
  const linearSuffix = (activity: UiPresentationActivity | undefined): string => {
322
367
  if (!activity) return ""
323
- const parts: string[] = [statusWord(activity.status)]
324
- if (activity.durationMs !== undefined)
325
- parts.push(t("one.duration", { v: Math.max(0, Math.round(activity.durationMs)) }))
326
- if (activity.denyReason)
327
- parts.push(t("one.denyReason", { reason: sanitizeAnsiLine(activity.denyReason) }))
328
- const paths = activity.receipt?.paths ?? []
368
+ // Bagian suffix dipilih policy kanonik bila di-inject; format tetap di sini.
369
+ const desc = opts.policy ? opts.policy.describeActivity(activity) : undefined
370
+ const status = desc?.status ?? activity.status
371
+ const parts: string[] = [statusWord(status)]
372
+ const durationMs = desc?.durationMs ?? activity.durationMs
373
+ if (durationMs !== undefined)
374
+ parts.push(t("one.duration", { v: Math.max(0, Math.round(durationMs)) }))
375
+ const denyReason = desc?.denyReason ?? activity.denyReason
376
+ if (denyReason) parts.push(t("one.denyReason", { reason: sanitizeAnsiLine(denyReason) }))
377
+ const paths = desc ? desc.receiptPaths : (activity.receipt?.paths ?? [])
329
378
  if (paths.length > 0) {
330
379
  const cleanPaths = paths
331
380
  .map((path) => truncateToWidth(sanitizeAnsiLine(path), 80, ""))
332
381
  .join(", ")
333
382
  parts.push(t("one.receipt", { paths: cleanPaths }))
334
383
  }
335
- if (activity.supersedes) parts.push(t("ts.retry"))
384
+ if (desc ? desc.retryOf !== undefined : activity.supersedes) parts.push(t("ts.retry"))
385
+ // P2.11: penanda verifikasi/provenans dari deskripsi policy (ASCII aman).
386
+ // Absen = unknown/live — tidak dirender sebagai keberhasilan.
387
+ const verification = desc?.verification ?? activity.verification
388
+ if (verification) {
389
+ parts.push(
390
+ verification.verdict === "present" ? "verified" : `unverified:${verification.verdict}`,
391
+ )
392
+ }
393
+ const provenance = desc?.provenance ?? activity.provenance
394
+ if (provenance === "replay" || provenance === "reconstructed") parts.push(provenance)
336
395
  return parts.length > 0 ? ` ${c.muted(`[${parts.join(" · ")}]`)}` : ""
337
396
  }
338
397
  const paintTerminal = (status: UiPresentationActivity["status"], line: string): string => {
@@ -343,6 +402,27 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
343
402
  }
344
403
  const writePresentationTerminal = (event: UiPresentationEvent): void => {
345
404
  if (!presentationEnabled) return
405
+ flushTableStream()
406
+ // Observasi verifikasi punya baris sendiri (dedup per invocation):
407
+ // terminal tool sudah tampil duluan dan baris linear append-only.
408
+ // Baris ini tak pernah mengklaim status tool.
409
+ if (event.type === "verification.observed") {
410
+ const verification = event.verification
411
+ if (!verification || !event.toolCallId) return
412
+ if (presentedVerifications.has(verification.invocationId)) return
413
+ presentedVerifications.add(verification.invocationId)
414
+ const activity = presentationActivity(event.toolCallId)
415
+ if (activity?.parentToolCallId) return
416
+ const name = sanitizeAnsiLine(activity?.name ?? event.name ?? "tool")
417
+ const target = activity?.target ?? event.target
418
+ const targetText = target ? ` ${truncateToWidth(sanitizeAnsiLine(target), 120, "")}` : ""
419
+ const line =
420
+ verification.verdict === "present"
421
+ ? ` ${glyphs.arrow} ${name}${targetText} verified`
422
+ : ` ? ${name}${targetText} unverified (${verification.verdict})`
423
+ wErr(`${verification.verdict === "present" ? c.success(line) : c.muted(line)}\n`)
424
+ return
425
+ }
346
426
  if (
347
427
  event.type !== "tool.failed" &&
348
428
  event.type !== "tool.denied" &&
@@ -354,11 +434,12 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
354
434
  if (presentedTerminals.has(event.toolCallId)) return
355
435
  presentedTerminals.add(event.toolCallId)
356
436
  const activity = presentationActivity(event.toolCallId)
357
- const name = sanitizeAnsiLine(activity?.name ?? event.name ?? "tool")
358
- const target = activity?.target ?? event.target
437
+ const desc = opts.policy && activity ? opts.policy.describeActivity(activity) : undefined
438
+ const name = sanitizeAnsiLine(desc?.name ?? activity?.name ?? event.name ?? "tool")
439
+ const target = desc?.target ?? activity?.target ?? event.target
359
440
  const targetText = target ? ` ${truncateToWidth(sanitizeAnsiLine(target), 120, "")}` : ""
360
- const status = activity?.status ?? event.status ?? "failed"
361
- const message = event.message ?? activity?.error?.message
441
+ const status = desc?.status ?? activity?.status ?? event.status ?? "failed"
442
+ const message = event.message ?? desc?.message ?? activity?.error?.message
362
443
  const detail = message
363
444
  ? `: ${truncateToWidth(sanitizeAnsi(String(message)), 200, "…").split("\n")[0] ?? ""}`
364
445
  : ""
@@ -372,6 +453,9 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
372
453
  }
373
454
  offs.push(
374
455
  bus.on("turn:started", (e) => {
456
+ flushTableStream()
457
+ tableStream.reset()
458
+ fence = null
375
459
  // Turn baru: buffer turn sebelumnya dibuang (lihat /copy yang juga
376
460
  // reset di sini) — /expand hanya untuk turn yang baru selesai.
377
461
  thinkState = "off"
@@ -381,20 +465,17 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
381
465
  answerTruncated = false
382
466
  clearCollapsedSections()
383
467
  collapse.setActiveSection(null)
384
- lastTurnText = ""
468
+ archiveTurn()
385
469
  pendingError = null
386
470
  presentedTerminals.clear()
471
+ presentedVerifications.clear()
387
472
 
388
473
  if (opts.verbose) wErr(c.muted(t("one.turnHead", { n: e.turn })))
389
474
  }),
390
475
  )
391
476
  offs.push(
392
477
  bus.on("turn:completed", () => {
393
- flushBuf()
394
- if (streamBuffer) {
395
- flushLine(streamBuffer)
396
- streamBuffer = ""
397
- }
478
+ flushTableStream()
398
479
  // Ekor escape yang tertahan (F1) dibuang di sini — deterministik, tak
399
480
  // pernah bocor mentah; begitu pula saat detach/abort di bawah.
400
481
  textSan.flush()
@@ -421,9 +502,8 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
421
502
  answerTruncated = false
422
503
  }
423
504
  const clean = cleanUntrusted(textSan.push(e.text), !!process.stdout.isTTY)
424
- streamBuffer += clean
425
505
  rememberTurn(clean)
426
- flushBuf()
506
+ consumeTableEvents(tableStream.push(clean))
427
507
  }),
428
508
  )
429
509
  offs.push(
@@ -508,6 +588,7 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
508
588
  )
509
589
  offs.push(
510
590
  bus.on("step:started", (e: { step: UiStep }) => {
591
+ flushTableStream()
511
592
  if (!opts.verbose) return
512
593
  const calls = e.step.toolCalls
513
594
  // Nama + argumen dari model (tak terpercaya): sanitasi sebelum tampil.
@@ -521,6 +602,7 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
521
602
  )
522
603
  offs.push(
523
604
  bus.on("execution:started", (e) => {
605
+ flushTableStream()
524
606
  // Section aktif = tool yang sedang jalan — target tombol + / - saat busy.
525
607
  collapse.setActiveSection("tool")
526
608
  // Ganti fase: sisa baris thinking yang belum ber-newline dicetak dulu
@@ -545,6 +627,7 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
545
627
  )
546
628
  offs.push(
547
629
  bus.on("execution:completed", (e) => {
630
+ flushTableStream()
548
631
  const callId = e.execution.call.id
549
632
  const activity = presentationActivity(callId)
550
633
  if (activity && activity.status !== "completed" && callId && presentedTerminals.has(callId)) {
@@ -554,7 +637,10 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
554
637
  const name = e.execution.call.name
555
638
  const args = (e.execution.call.args ?? {}) as Record<string, unknown>
556
639
  const suffix = linearSuffix(activity)
557
- const isError = activity ? activity.status !== "completed" : r.isError === true
640
+ // Keputusan error dari status kanonik bila policy/snapshot ada.
641
+ const status =
642
+ opts.policy && activity ? opts.policy.describeActivity(activity).status : activity?.status
643
+ const isError = status ? status !== "completed" : r.isError === true
558
644
  // Hasil string ikut ke buffer /copy (versi sanitize, cap per-add agar
559
645
  // satu read_file raksasa tak langsung memenuhi buffer sendirian).
560
646
  if (!isError && typeof r.content === "string")
@@ -710,21 +796,19 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
710
796
  }),
711
797
  )
712
798
  offs.push(
713
- bus.on("context:compacted", (e) =>
799
+ bus.on("context:compacted", (e) => {
800
+ flushTableStream()
714
801
  wErr(
715
802
  c.warning(`${t("ts.compacted", { reason: sanitizeAnsiLine(String(e.reason ?? "")) })}\n`),
716
- ),
717
- ),
803
+ )
804
+ }),
718
805
  )
719
806
 
720
807
  return () => {
721
808
  // Sisa parsal di-flush dulu (jangan hilang diam-diam), baru lepas.
722
809
  // Tanpa ini detach di tengah baris membuang ekornya — dan di jalur abort
723
- // (tanpa turn:completed) sisa streamBuffer bocor ke turn berikutnya.
724
- if (streamBuffer) {
725
- flushLine(streamBuffer)
726
- streamBuffer = ""
727
- }
810
+ // (tanpa turn:completed) sisa stream tabel bocor ke turn berikutnya.
811
+ flushTableStream()
728
812
  // Ekor escape tertahan (F1) dibuang di sini juga: abort/error/budget
729
813
  // tanpa turn:completed tak boleh meninggalkan ANSI tail.
730
814
  textSan.flush()
@@ -740,19 +824,8 @@ export function attachSimpleLogger(bus: UiBus, opts: SimpleOptions = {}): () =>
740
824
  /**
741
825
  * Error apa pun → satu pesan siap tampil.
742
826
  *
743
- * Sebelumnya mengembalikan `${kind}: ${message}` mentah, sehingga baris terakhir
744
- * yang dilihat user setelah run gagal adalah dump JSON provider — pada uji live
745
- * OpenRouter: `provider: rate limited (429): {"error":{...400 karakter...}}`.
746
- * Kini kategori dipetakan lewat src/ui/render/errors.ts, sama seperti event error.
827
+ * CATATAN: implementasi pindah ke `src/ui/render/errors.ts` (lapisan render)
828
+ * supaya TUI fullscreen, wizard, dan one-shot memakai SATU formatter kanonik
829
+ * yang sama — TUI tak lagi menarik renderer linier hanya demi format error.
747
830
  */
748
- export function formatError(e: unknown): string {
749
- const obj = e as { kind?: string; category?: string; message?: string } | undefined
750
- // ProviderError punya `category`; AgentError punya `kind`.
751
- if (obj?.category) return formatFriendly(friendlyFromCategory(obj.category, obj.message ?? ""))
752
- if (obj?.kind) {
753
- const friendly = friendlyError(`${obj.kind}: ${obj.message ?? ""}`)
754
- return formatFriendly(friendly)
755
- }
756
- if (e instanceof Error) return formatFriendly(friendlyError(e.message))
757
- return String(e)
758
- }
831
+ export { formatError } from "../render/errors.ts"
@@ -63,6 +63,12 @@ export function attachTurnStatus(
63
63
  * (default hemat: shell tetap bersih).
64
64
  */
65
65
  getStats?: () => string | undefined
66
+ /**
67
+ * Label activity kanonik (di-inject composition root dari snapshot
68
+ * presentasi). Dipakai untuk nama+target garis status bila ada; absen =
69
+ * parse raw legacy dari args model.
70
+ */
71
+ activityFor?: (toolCallId: string) => { name: string; target?: string } | undefined
66
72
  } = {},
67
73
  ): TurnStatusHandle {
68
74
  if (!process.stderr.isTTY) return { detach: () => {}, endTurn: () => {} }
@@ -224,10 +230,18 @@ export function attachTurnStatus(
224
230
  registerStatusLine(handle)
225
231
 
226
232
  const statusToolLabel = (e: {
227
- execution: { call: { name: string; args?: unknown } }
233
+ execution: { call: { id?: string; name: string; args?: unknown } }
228
234
  }): string => {
229
- const name = e.execution.call.name
230
- const args = (e.execution.call.args ?? {}) as Record<string, unknown>
235
+ // Sumber kanonik dulu (snapshot presentasi via DI); fallback raw legacy.
236
+ // Bentuk args dinormalisasi agar logika cap/sanitasi di bawah identik.
237
+ const canonical = e.execution.call.id ? opts.activityFor?.(e.execution.call.id) : undefined
238
+ const name = canonical?.name ?? e.execution.call.name
239
+ const args = canonical
240
+ ? ((canonical.target !== undefined ? { path: canonical.target } : {}) as Record<
241
+ string,
242
+ unknown
243
+ >)
244
+ : ((e.execution.call.args ?? {}) as Record<string, unknown>)
231
245
  let target = ""
232
246
  if (typeof args.path === "string") target = args.path
233
247
  else if (typeof args.file === "string") target = args.file
@@ -86,6 +86,8 @@ export interface UiTurnSummary {
86
86
  toolsInterrupted: number
87
87
  filesChanged: number
88
88
  checkpointId?: string
89
+ testSummary?: { passed: number; failed: number; summary: string }
90
+ evidenceComplete?: boolean
89
91
  durationMs: number
90
92
  }
91
93
 
@@ -95,7 +97,27 @@ export interface UiPresentationError {
95
97
  hint?: string
96
98
  }
97
99
 
100
+ /**
101
+ * Provenans tampilan P2.11 — struktural, tanpa impor presentation.
102
+ * Absen = live-atau-tak-ditentukan; ketiadaan tidak boleh dibaca sebagai
103
+ * keberhasilan. Hanya nilai non-live yang ditulis eksplisit.
104
+ */
105
+ export type UiProvenance = "live" | "replay" | "reconstructed" | "unknown"
106
+
107
+ /**
108
+ * Observasi verifikasi untuk display — tanpa evidenceReference (tetap di
109
+ * jurnal), tanpa otoritas efek. Absen = UNKNOWN (diturunkan di proyeksi).
110
+ */
111
+ export interface UiVerificationDisplay {
112
+ invocationId: string
113
+ verdict: "present" | "absent" | "inconclusive"
114
+ method: string
115
+ observedAt: number
116
+ }
117
+
98
118
  export interface UiPresentationReceipt {
119
+ sessionId?: string
120
+ turnId?: number
99
121
  paths?: string[]
100
122
  checkpointId?: string
101
123
  stats?: { added?: number; removed?: number }
@@ -122,17 +144,134 @@ export interface UiPresentationActivity {
122
144
  parentToolCallId?: string
123
145
  supersedes?: string
124
146
  expandRef?: { toolCallId: string; idx: number }
147
+ verification?: UiVerificationDisplay
148
+ provenance?: UiProvenance
125
149
  }
126
150
 
127
151
  export interface UiPresentationTurn {
128
152
  turnId: number
129
153
  status: "running" | "completed" | "failed" | "cancelled" | "interrupted"
130
154
  summary?: UiTurnSummary
155
+ provenance?: UiProvenance
156
+ }
157
+
158
+ export interface UiPresentationMessage {
159
+ id: string
160
+ sessionId: string
161
+ turnId: number
162
+ role: "user" | "assistant"
163
+ text: string
164
+ truncated: boolean
165
+ promptRef?: string
166
+ }
167
+
168
+ export interface UiPresentationReasoning {
169
+ id: string
170
+ sessionId: string
171
+ turnId: number
172
+ truncated: boolean
173
+ expandRef: { toolCallId: string; idx: number }
174
+ }
175
+
176
+ export interface UiPresentationSystem {
177
+ id: string
178
+ sessionId: string
179
+ turnId: number
180
+ kind: "context_compacted" | "recovery" | "checkpoint" | "notice"
181
+ text: string
182
+ reason?: string
183
+ severity: "info" | "warning" | "error" | "critical"
184
+ }
185
+
186
+ export interface UiPresentationPlan {
187
+ planId: string
188
+ sessionId: string
189
+ turnId: number
190
+ status: "open" | "completed" | "cancelled"
191
+ steps: Array<{
192
+ stepId: string
193
+ title?: string
194
+ status: "pending" | "active" | "completed" | "cancelled" | "blocked"
195
+ }>
196
+ }
197
+
198
+ export interface UiPresentationFinding {
199
+ findingId: string
200
+ sessionId: string
201
+ turnId: number
202
+ category: string
203
+ severity: "info" | "warning" | "error" | "critical"
204
+ summary: string
205
+ evidence: string[]
206
+ }
207
+
208
+ export interface UiPresentationResult {
209
+ resultId: string
210
+ sessionId: string
211
+ turnId: number
212
+ status: "completed" | "failed" | "cancelled"
213
+ summary: string
214
+ action?: string
215
+ }
216
+
217
+ export interface UiPresentationDiagnostic {
218
+ id: string
219
+ sessionId: string
220
+ turnId: number
221
+ category: string
222
+ severity: "info" | "warning" | "error" | "critical"
223
+ message: string
224
+ cause?: string
225
+ action?: string
226
+ }
227
+
228
+ /** Deskripsi activity dari policy kanonik (tanpa paint/sanitasi/truncate). */
229
+ export interface ActivityPolicyDescription {
230
+ toolCallId: string
231
+ name: string
232
+ target?: string
233
+ status: UiToolStatus
234
+ summary?: string
235
+ message?: string
236
+ durationMs?: number
237
+ denyReason?: string
238
+ receiptPaths: string[]
239
+ testSummary?: { passed: number; failed: number; summary: string }
240
+ retryOf?: string
241
+ childCount: number
242
+ isChild: boolean
243
+ expandRef?: { toolCallId: string; idx: number }
244
+ error?: { cause?: string; message: string; hint?: string }
245
+ tsStart: number
246
+ tsEnd?: number
247
+ verification?: UiVerificationDisplay
248
+ provenance?: UiProvenance
249
+ }
250
+
251
+ /**
252
+ * Kumpulan keputusan proyeksi kanonik untuk renderer. Di-inject composition
253
+ * root dari `src/presentation/`; absen = logika inline legacy di renderer.
254
+ * Renderer tidak boleh mengimpor `src/presentation` langsung — batas lapisan.
255
+ */
256
+ export interface PresentationPolicy {
257
+ describeActivity: (
258
+ activity: UiPresentationActivity,
259
+ opts?: { childCount?: number },
260
+ ) => ActivityPolicyDescription
261
+ matchTurn: (turns: UiPresentationTurn[], summary: UiTurnSummary) => UiPresentationTurn | undefined
262
+ elapsedVisible: (tsStart: number, now: number) => boolean
131
263
  }
132
264
 
133
265
  export interface UiPresentationSnapshot {
134
266
  activities: UiPresentationActivity[]
135
267
  turns: UiPresentationTurn[]
268
+ conversation?: UiPresentationMessage[]
269
+ reasoning?: UiPresentationReasoning[]
270
+ system?: UiPresentationSystem[]
271
+ plans?: UiPresentationPlan[]
272
+ findings?: UiPresentationFinding[]
273
+ results?: UiPresentationResult[]
274
+ diagnostics?: UiPresentationDiagnostic[]
136
275
  }
137
276
 
138
277
  export interface UiApprovalOutcome {
@@ -143,19 +282,35 @@ export interface UiApprovalOutcome {
143
282
 
144
283
  export interface UiPresentationEvent {
145
284
  type:
285
+ | "user.message"
146
286
  | "turn.started"
147
287
  | "turn.completed"
148
288
  | "turn.failed"
149
289
  | "turn.cancelled"
290
+ | "model.delta"
291
+ | "model.completed"
292
+ | "reasoning.delta"
293
+ | "reasoning.completed"
150
294
  | "tool.started"
295
+ | "tool.progress"
151
296
  | "tool.completed"
152
297
  | "tool.failed"
153
298
  | "tool.denied"
154
299
  | "tool.cancelled"
155
300
  | "approval.requested"
156
301
  | "approval.settled"
302
+ | "file.changed"
303
+ | "test.completed"
304
+ | "context.compacted"
305
+ | "plan.updated"
306
+ | "finding.detected"
307
+ | "result.produced"
308
+ | "diagnostic.raised"
309
+ | "checkpoint.created"
310
+ | "verification.observed"
157
311
  seq?: number
158
312
  turnId?: number
313
+ stepId?: number
159
314
  toolCallId?: string
160
315
  approvalId?: string
161
316
  name?: string
@@ -171,4 +326,33 @@ export interface UiPresentationEvent {
171
326
  outcome?: UiApprovalOutcome
172
327
  via?: "prompt" | "system"
173
328
  summary?: UiTurnSummary
329
+ promptRef?: string
330
+ delta?: string
331
+ text?: string
332
+ truncated?: boolean
333
+ toolSummary?: string
334
+ hint?: string
335
+ expandRef?: { toolCallId: string; idx: number }
336
+ receipt?: UiPresentationReceipt
337
+ parentToolCallId?: string
338
+ paths?: string[]
339
+ journalSeq?: number
340
+ checkpointId?: string
341
+ test?: { passed: number; failed: number; summary: string }
342
+ invocationId?: string
343
+ verification?: UiVerificationDisplay
344
+ provenance?: UiProvenance
345
+ compactionReason?: string
346
+ planId?: string
347
+ findingId?: string
348
+ resultId?: string
349
+ category?: string
350
+ severity?: "info" | "warning" | "error" | "critical"
351
+ action?: string
352
+ steps?: Array<{
353
+ stepId: string
354
+ title?: string
355
+ status: "pending" | "active" | "completed" | "cancelled" | "blocked"
356
+ }>
357
+ evidence?: string[]
174
358
  }