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
@@ -0,0 +1,455 @@
1
+ export type PipeTableAlignment = "left" | "right" | "center"
2
+
3
+ export interface MarkdownTable {
4
+ headers: string[]
5
+ rows: string[][]
6
+ aligns: PipeTableAlignment[]
7
+ alignments: PipeTableAlignment[]
8
+ source: string
9
+ raw: string
10
+ startLine: number
11
+ endLine: number
12
+ }
13
+
14
+ export type MarkdownBlock =
15
+ | {
16
+ type: "text"
17
+ kind: "text"
18
+ text: string
19
+ startLine: number
20
+ endLine: number
21
+ }
22
+ | {
23
+ type: "table"
24
+ kind: "table"
25
+ table: MarkdownTable
26
+ startLine: number
27
+ endLine: number
28
+ }
29
+
30
+ export type MarkdownTableStreamEvent =
31
+ | { type: "text"; text: string }
32
+ | { type: "table"; table: MarkdownTable; raw: string }
33
+
34
+ interface FenceInfo {
35
+ char: string
36
+ len: number
37
+ }
38
+
39
+ interface SplitRow {
40
+ cells: string[]
41
+ }
42
+
43
+ const ESC = String.fromCharCode(27)
44
+ const SGR_PATTERN = new RegExp(`${ESC}\\[[0-9;:]*m`, "g")
45
+
46
+ function withoutSgr(value: string): string {
47
+ return value.replace(SGR_PATTERN, "")
48
+ }
49
+
50
+ function fenceInfo(line: string): FenceInfo | null {
51
+ const match = /^ {0,3}(`{3,}|~{3,})([^`]*)$/.exec(withoutSgr(line))
52
+ if (!match) return null
53
+ const marker = match[1]!
54
+ return { char: marker[0]!, len: marker.length }
55
+ }
56
+
57
+ function isFenceClose(line: string, fence: FenceInfo): boolean {
58
+ const match = /^ {0,3}(`{3,}|~{3,})\s*$/.exec(withoutSgr(line))
59
+ if (!match) return false
60
+ const marker = match[1]!
61
+ return marker[0] === fence.char && marker.length >= fence.len
62
+ }
63
+
64
+ function isEscapedAt(text: string, index: number): boolean {
65
+ let count = 0
66
+ for (let i = index - 1; i >= 0 && text[i] === "\\"; i--) count++
67
+ return count % 2 === 1
68
+ }
69
+
70
+ function hasClosingRun(text: string, start: number, length: number): boolean {
71
+ let i = start
72
+ while (i < text.length) {
73
+ if (text[i] !== "`" || isEscapedAt(text, i)) {
74
+ i++
75
+ continue
76
+ }
77
+ let end = i + 1
78
+ while (text[end] === "`") end++
79
+ if (end - i === length) return true
80
+ i = end
81
+ }
82
+ return false
83
+ }
84
+
85
+ function splitPipeRowInternal(line: string, unmatchedCodeIsLiteral: boolean): SplitRow | null {
86
+ const raw = withoutSgr(line.replace(/\r$/, ""))
87
+ if (/^(?: {4,}|\t)/.test(raw)) return null
88
+ const body = raw.replace(/^ {0,3}/, "").trim()
89
+ const cells: string[] = [""]
90
+ let i = 0
91
+ let codeLength = 0
92
+ let hasPipe = false
93
+ while (i < body.length) {
94
+ const ch = body[i]!
95
+ if (ch === "\\" && body[i + 1] === "|" && isEscapedAt(body, i + 1)) {
96
+ cells[cells.length - 1] += body.slice(i, i + 2)
97
+ i += 2
98
+ continue
99
+ }
100
+ if (ch === "`" && !isEscapedAt(body, i)) {
101
+ let end = i + 1
102
+ while (body[end] === "`") end++
103
+ const run = body.slice(i, end)
104
+ if (codeLength === 0) {
105
+ if (!unmatchedCodeIsLiteral && hasClosingRun(body, end, run.length)) codeLength = run.length
106
+ } else if (run.length === codeLength) {
107
+ codeLength = 0
108
+ }
109
+ cells[cells.length - 1] += run
110
+ i = end
111
+ continue
112
+ }
113
+ if (ch === "|" && codeLength === 0) {
114
+ hasPipe = true
115
+ cells.push("")
116
+ i++
117
+ continue
118
+ }
119
+ cells[cells.length - 1] += ch
120
+ i++
121
+ }
122
+ if (!hasPipe) return null
123
+ if (body[0] === "|" && cells[0] === "") cells.shift()
124
+ if (
125
+ cells.length > 1 &&
126
+ body.endsWith("|") &&
127
+ cells[cells.length - 1] === "" &&
128
+ !isEscapedAt(body, body.length - 1)
129
+ ) {
130
+ cells.pop()
131
+ }
132
+ return { cells }
133
+ }
134
+
135
+ export function splitPipeRow(line: string): string[] | null {
136
+ return splitPipeRowInternal(line, false)?.cells ?? null
137
+ }
138
+
139
+ export const parseTableRow = splitPipeRow
140
+ export const isTableDelimiter = (line: string): boolean => parseDelimiterRow(line) !== null
141
+
142
+ function unescapeCell(cell: string): string {
143
+ let out = ""
144
+ let codeLength = 0
145
+ let i = 0
146
+ while (i < cell.length) {
147
+ const ch = cell[i]!
148
+ if (ch === "\\" && cell[i + 1] === "|" && isEscapedAt(cell, i + 1) && codeLength === 0) {
149
+ out += "|"
150
+ i += 2
151
+ continue
152
+ }
153
+ if (ch === "`" && !isEscapedAt(cell, i)) {
154
+ let end = i + 1
155
+ while (cell[end] === "`") end++
156
+ const run = cell.slice(i, end)
157
+ if (codeLength === 0) {
158
+ if (hasClosingRun(cell, end, run.length)) codeLength = run.length
159
+ } else if (run.length === codeLength) {
160
+ codeLength = 0
161
+ }
162
+ out += run
163
+ i = end
164
+ continue
165
+ }
166
+ out += ch
167
+ i++
168
+ }
169
+ return out.trim()
170
+ }
171
+
172
+ export function parseDelimiterRow(line: string): PipeTableAlignment[] | null {
173
+ const split = splitPipeRow(line)
174
+ if (!split || split.length === 0) return null
175
+ const aligns: PipeTableAlignment[] = []
176
+ for (const cell of split) {
177
+ const value = cell.trim()
178
+ const match = /^(:)?-{3,}(:)?$/.exec(value)
179
+ if (!match) return null
180
+ aligns.push(match[1] && match[2] ? "center" : match[2] ? "right" : match[1] ? "left" : "left")
181
+ }
182
+ return aligns
183
+ }
184
+
185
+ function makeTable(lines: readonly string[], start: number): MarkdownTable | null {
186
+ const headerSplit = splitPipeRow(lines[start] ?? "")
187
+ if (!headerSplit || headerSplit.length === 0) return null
188
+ const aligns = parseDelimiterRow(lines[start + 1] ?? "")
189
+ if (!aligns || aligns.length !== headerSplit.length) return null
190
+ const headers = headerSplit.map(unescapeCell)
191
+ const rows: string[][] = []
192
+ let end = start + 1
193
+ for (let i = start + 2; i < lines.length; i++) {
194
+ const line = lines[i]!
195
+ if (line.trim() === "") break
196
+ const split = splitPipeRow(line)
197
+ if (!split || split.length !== headers.length) break
198
+ rows.push(split.map(unescapeCell))
199
+ end = i
200
+ }
201
+ const source = lines.slice(start, end + 1).join("\n")
202
+ return {
203
+ headers,
204
+ rows,
205
+ aligns,
206
+ alignments: aligns,
207
+ source,
208
+ raw: source,
209
+ startLine: start,
210
+ endLine: end,
211
+ }
212
+ }
213
+
214
+ function normalizeLines(text: string): string {
215
+ return text.replace(/\r\n?/g, "\n")
216
+ }
217
+
218
+ function lineStarts(lines: readonly string[]): number[] {
219
+ const starts: number[] = []
220
+ let offset = 0
221
+ for (const line of lines) {
222
+ starts.push(offset)
223
+ offset += line.length + 1
224
+ }
225
+ return starts
226
+ }
227
+
228
+ function textBlock(text: string, startLine: number, endLine: number): MarkdownBlock {
229
+ return { type: "text", kind: "text", text, startLine, endLine }
230
+ }
231
+
232
+ function tableBlock(table: MarkdownTable): MarkdownBlock {
233
+ return {
234
+ type: "table",
235
+ kind: "table",
236
+ table,
237
+ startLine: table.startLine,
238
+ endLine: table.endLine,
239
+ }
240
+ }
241
+
242
+ export function parseMarkdownBlocks(input: string): MarkdownBlock[] {
243
+ const text = normalizeLines(input)
244
+ if (text.length === 0) return []
245
+ const lines = text.split("\n")
246
+ const starts = lineStarts(lines)
247
+ const blocks: MarkdownBlock[] = []
248
+ let cursor = 0
249
+ let i = 0
250
+ let fence: FenceInfo | null = null
251
+ const addText = (end: number, endLine: number): void => {
252
+ if (end <= cursor) return
253
+ const startLine = starts.indexOf(cursor)
254
+ blocks.push(textBlock(text.slice(cursor, end), startLine < 0 ? 0 : startLine, endLine))
255
+ cursor = end
256
+ }
257
+ while (i < lines.length) {
258
+ const line = lines[i]!
259
+ const fenceLine = fenceInfo(line)
260
+ if (fence) {
261
+ if (isFenceClose(line, fence)) fence = null
262
+ i++
263
+ continue
264
+ }
265
+ if (fenceLine) {
266
+ fence = fenceLine
267
+ i++
268
+ continue
269
+ }
270
+ const table = makeTable(lines, i)
271
+ if (table) {
272
+ addText(starts[i]!, Math.max(0, table.startLine - 1))
273
+ blocks.push(tableBlock(table))
274
+ const nextLine = table.endLine + 1
275
+ cursor = nextLine < starts.length ? starts[nextLine]! : text.length
276
+ i = nextLine
277
+ continue
278
+ }
279
+ i++
280
+ }
281
+ if (cursor < text.length) {
282
+ const startLine = starts.indexOf(cursor)
283
+ blocks.push(textBlock(text.slice(cursor), startLine < 0 ? 0 : startLine, lines.length - 1))
284
+ }
285
+ return blocks
286
+ }
287
+
288
+ export function parseMarkdownTable(
289
+ input: string | readonly string[],
290
+ ...extra: (string | number)[]
291
+ ): MarkdownTable | null {
292
+ const extraLines = extra.filter((value): value is string => typeof value === "string")
293
+ const source = [typeof input === "string" ? input : input.join("\n"), ...extraLines].join("\n")
294
+ return parseMarkdownBlocks(source).find((block) => block.type === "table")?.table ?? null
295
+ }
296
+
297
+ export const parsePipeTable = parseMarkdownTable
298
+ export const parseMarkdownPipeTable = parseMarkdownTable
299
+
300
+ export function parseMarkdownTables(input: string): MarkdownTable[] {
301
+ return parseMarkdownBlocks(input)
302
+ .filter((block): block is Extract<MarkdownBlock, { type: "table" }> => block.type === "table")
303
+ .map((block) => block.table)
304
+ }
305
+
306
+ export class MarkdownTableStream {
307
+ private lineBuffer = ""
308
+ private lineNumber = 0
309
+ private fence: FenceInfo | null = null
310
+ private candidate: {
311
+ line: string
312
+ lineNumber: number
313
+ headers: string[]
314
+ terminated: boolean
315
+ } | null = null
316
+ private active: {
317
+ headers: string[]
318
+ rows: string[][]
319
+ aligns: PipeTableAlignment[]
320
+ sourceLines: string[]
321
+ startLine: number
322
+ } | null = null
323
+
324
+ reset(): void {
325
+ this.lineBuffer = ""
326
+ this.lineNumber = 0
327
+ this.fence = null
328
+ this.candidate = null
329
+ this.active = null
330
+ }
331
+
332
+ feed(chunk: string): MarkdownTableStreamEvent[] {
333
+ return this.push(chunk)
334
+ }
335
+
336
+ push(chunk: string): MarkdownTableStreamEvent[] {
337
+ if (!chunk) return []
338
+ this.lineBuffer += chunk
339
+ const events: MarkdownTableStreamEvent[] = []
340
+ for (;;) {
341
+ const newline = this.lineBuffer.indexOf("\n")
342
+ if (newline < 0) break
343
+ const line = this.lineBuffer.slice(0, newline).replace(/\r$/, "")
344
+ this.lineBuffer = this.lineBuffer.slice(newline + 1)
345
+ this.processLine(line, true, events)
346
+ }
347
+ return events
348
+ }
349
+
350
+ finish(): MarkdownTableStreamEvent[] {
351
+ return this.flush()
352
+ }
353
+
354
+ flush(): MarkdownTableStreamEvent[] {
355
+ const events: MarkdownTableStreamEvent[] = []
356
+ if (this.lineBuffer) {
357
+ const line = this.lineBuffer.replace(/\r$/, "")
358
+ this.lineBuffer = ""
359
+ this.processLine(line, false, events)
360
+ }
361
+ this.finishTable(events)
362
+ this.finishCandidate(events)
363
+ return events
364
+ }
365
+
366
+ private text(line: string, terminated: boolean, events: MarkdownTableStreamEvent[]): void {
367
+ events.push({ type: "text", text: `${line}${terminated ? "\n" : ""}` })
368
+ }
369
+
370
+ private finishTable(events: MarkdownTableStreamEvent[]): void {
371
+ if (!this.active) return
372
+ const active = this.active
373
+ this.active = null
374
+ const source = active.sourceLines.join("\n")
375
+ const table: MarkdownTable = {
376
+ headers: active.headers,
377
+ rows: active.rows,
378
+ aligns: active.aligns,
379
+ alignments: active.aligns,
380
+ source,
381
+ raw: source,
382
+ startLine: active.startLine,
383
+ endLine: active.startLine + active.sourceLines.length - 1,
384
+ }
385
+ events.push({ type: "table", table, raw: source })
386
+ }
387
+
388
+ private finishCandidate(events: MarkdownTableStreamEvent[]): void {
389
+ if (!this.candidate) return
390
+ const candidate = this.candidate
391
+ this.candidate = null
392
+ this.text(candidate.line, candidate.terminated, events)
393
+ }
394
+
395
+ private processLine(line: string, terminated: boolean, events: MarkdownTableStreamEvent[]): void {
396
+ const currentLine = this.lineNumber++
397
+ if (this.fence) {
398
+ if (isFenceClose(line, this.fence)) this.fence = null
399
+ this.text(line, terminated, events)
400
+ return
401
+ }
402
+ const opening = fenceInfo(line)
403
+ if (opening) {
404
+ this.finishTable(events)
405
+ this.finishCandidate(events)
406
+ this.fence = opening
407
+ this.text(line, terminated, events)
408
+ return
409
+ }
410
+ if (this.active) {
411
+ const split = splitPipeRow(line)
412
+ if (line.trim() !== "" && split && split.length === this.active.headers.length) {
413
+ this.active.rows.push(split.map(unescapeCell))
414
+ this.active.sourceLines.push(line)
415
+ return
416
+ }
417
+ this.finishTable(events)
418
+ this.processLine(line, terminated, events)
419
+ return
420
+ }
421
+ if (this.candidate) {
422
+ const delimiter = parseDelimiterRow(line)
423
+ if (delimiter && delimiter.length === this.candidate.headers.length) {
424
+ this.active = {
425
+ headers: this.candidate.headers,
426
+ rows: [],
427
+ aligns: delimiter,
428
+ sourceLines: [this.candidate.line, line],
429
+ startLine: this.candidate.lineNumber,
430
+ }
431
+ this.candidate = null
432
+ return
433
+ }
434
+ this.text(this.candidate.line, this.candidate.terminated, events)
435
+ this.candidate = null
436
+ this.processLine(line, terminated, events)
437
+ return
438
+ }
439
+ if (line.trim() === "") {
440
+ this.text(line, terminated, events)
441
+ return
442
+ }
443
+ const split = splitPipeRow(line)
444
+ if (split) {
445
+ this.candidate = {
446
+ line,
447
+ lineNumber: currentLine,
448
+ headers: split.map(unescapeCell),
449
+ terminated,
450
+ }
451
+ return
452
+ }
453
+ this.text(line, terminated, events)
454
+ }
455
+ }
@@ -3,9 +3,13 @@
3
3
  // Inline: **bold**, *italic*, `code`, ~~strike~~, [text](url) -> teks accent (no underline).
4
4
 
5
5
  import { highlightCode } from "./highlight.ts"
6
+ import { type MarkdownTable, parseMarkdownBlocks } from "./markdown-table.ts"
6
7
  import { sanitizeAnsi } from "./sanitize.ts"
8
+ import { renderMarkdownTable } from "./table-grid.ts"
7
9
  import { c } from "./theme.ts"
8
10
 
11
+ export { renderMarkdownTable, renderMarkdownTableLines } from "./table-grid.ts"
12
+
9
13
  export interface FenceMatch {
10
14
  char: string
11
15
  len: number
@@ -64,13 +68,30 @@ export function decorateMarkdown(text: string): string {
64
68
  // renderInline, dan highlight tak pernah melihat escape mentah. Urutan ini
65
69
  // juga melindungi placeholder `\u0000` (sanitize membuang null model).
66
70
  const lines = sanitizeAnsi(text).split("\n")
71
+ const tableStarts = new Map<number, MarkdownTable>()
72
+ for (const block of parseMarkdownBlocks(lines.join("\n"))) {
73
+ if (block.type === "table") tableStarts.set(block.startLine, block.table)
74
+ }
67
75
  const out: string[] = []
68
76
  let inFence = false
69
77
  let fenceLang = ""
70
78
  let fenceChar = ""
71
79
  let fenceLen = 0
72
80
 
73
- for (const line of lines) {
81
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
82
+ const table = tableStarts.get(lineIndex)
83
+ if (table) {
84
+ if (process.stdout.isTTY)
85
+ out.push(
86
+ ...renderMarkdownTable(table, process.stdout.columns || 80, renderInline).split("\n"),
87
+ )
88
+ else
89
+ for (let tableLine = lineIndex; tableLine <= table.endLine; tableLine++)
90
+ out.push(lines[tableLine]!)
91
+ lineIndex = table.endLine
92
+ continue
93
+ }
94
+ const line = lines[lineIndex]!
74
95
  // Code fence handling — catat char & panjang pembuka, hanya tutup bila cocok.
75
96
  const fence = parseFence(line)
76
97
  if (fence) {
@@ -0,0 +1,184 @@
1
+ import type { MarkdownTable, PipeTableAlignment } from "./markdown-table.ts"
2
+ import { cleanUntrusted, sanitizeAnsiLine } from "./sanitize.ts"
3
+ import { c, getTerminalWidth } from "./theme.ts"
4
+ import { displayWidth, padToWidth, truncateToWidth } from "./width.ts"
5
+
6
+ export interface GridColumn {
7
+ header: string
8
+ align?: PipeTableAlignment
9
+ width?: number
10
+ }
11
+
12
+ export interface GridTable {
13
+ headers: readonly string[]
14
+ rows: readonly (readonly string[])[]
15
+ aligns?: readonly PipeTableAlignment[]
16
+ widths?: readonly (number | undefined)[]
17
+ }
18
+
19
+ export interface GridRenderOptions {
20
+ width?: number
21
+ ellipsis?: string
22
+ maxCellWidth?: number
23
+ minCellWidth?: number
24
+ styleHeader?: boolean
25
+ formatCell?: (value: string) => string
26
+ }
27
+
28
+ const DEFAULT_ELLIPSIS = "…"
29
+ const DEFAULT_MAX_CELL_WIDTH = 50
30
+ const MIN_CONTENT_WIDTH = 3
31
+
32
+ function cleanCell(value: unknown): string {
33
+ return cleanUntrusted(
34
+ sanitizeAnsiLine(value == null ? "" : String(value)),
35
+ !!process.stdout.isTTY,
36
+ )
37
+ .replace(/[\t\v\f\u0085\u2028\u2029]/g, " ")
38
+ .replace(/\r/g, " ")
39
+ }
40
+
41
+ function alignCell(value: string, width: number, align: PipeTableAlignment): string {
42
+ if (align === "right") return padToWidth(value, width, "right")
43
+ if (align === "center") {
44
+ const diff = width - displayWidth(value)
45
+ if (diff <= 0) return value
46
+ const left = Math.floor(diff / 2)
47
+ return `${" ".repeat(left)}${value}${" ".repeat(diff - left)}`
48
+ }
49
+ return padToWidth(value, width)
50
+ }
51
+
52
+ function verticalField(header: string, value: string, width: number, ellipsis: string): string {
53
+ const safeHeader = cleanCell(header)
54
+ const safeValue = cleanCell(value)
55
+ const safeWidth = Math.max(1, width)
56
+ const labelBudget = Math.max(1, safeWidth - 2)
57
+ const label = truncateToWidth(safeHeader, labelBudget, ellipsis)
58
+ const prefix = `${label}:`
59
+ const valueBudget = safeWidth - displayWidth(prefix) - 1
60
+ if (valueBudget <= 0) return truncateToWidth(prefix, safeWidth, ellipsis)
61
+ const shown = truncateToWidth(safeValue, valueBudget, ellipsis)
62
+ return truncateToWidth(`${prefix} ${shown}`, safeWidth, ellipsis)
63
+ }
64
+
65
+ function renderVertical(table: GridTable, width: number, ellipsis: string): string[] {
66
+ const out: string[] = []
67
+ for (const row of table.rows) {
68
+ const fields: string[] = []
69
+ for (let i = 0; i < table.headers.length; i++) {
70
+ fields.push(verticalField(table.headers[i] ?? "", row[i] ?? "", width, ellipsis))
71
+ }
72
+ if (fields.length) out.push(fields.join("\n"))
73
+ }
74
+ if (out.length === 0) {
75
+ for (const header of table.headers)
76
+ out.push(truncateToWidth(cleanCell(header), Math.max(1, width), ellipsis))
77
+ }
78
+ return out
79
+ }
80
+
81
+ function requestedWidth(value: number | undefined): number | undefined {
82
+ if (value == null || !Number.isFinite(value)) return undefined
83
+ return Math.max(0, Math.trunc(value))
84
+ }
85
+
86
+ function naturalWidths(table: GridTable, maxCellWidth: number): number[] {
87
+ return table.headers.map((header, i) => {
88
+ const requested = requestedWidth(table.widths?.[i])
89
+ if (requested != null) return requested
90
+ let max = displayWidth(cleanCell(header))
91
+ for (const row of table.rows) max = Math.max(max, displayWidth(cleanCell(row[i])))
92
+ return Math.min(max, maxCellWidth)
93
+ })
94
+ }
95
+
96
+ function fitWidths(natural: readonly number[], budget: number, minimum: number): number[] | null {
97
+ const widths = natural.map((value) => Math.max(minimum, value))
98
+ const naturalTotal = widths.reduce((sum, value) => sum + value, 0)
99
+ if (naturalTotal <= budget) return widths
100
+ const room = budget - widths.length * minimum
101
+ if (room < 0) return null
102
+ const extras = widths.map((value) => value - minimum)
103
+ const extraTotal = extras.reduce((sum, value) => sum + value, 0)
104
+ if (extraTotal <= 0) return null
105
+ let assigned = 0
106
+ for (let i = 0; i < widths.length; i++) {
107
+ const share =
108
+ i === widths.length - 1 ? room - assigned : Math.floor((extras[i]! * room) / extraTotal)
109
+ const amount = Math.min(extras[i]!, Math.max(0, share))
110
+ widths[i] = minimum + amount
111
+ assigned += amount
112
+ }
113
+ return widths
114
+ }
115
+
116
+ export function renderGridTable(table: GridTable, options: GridRenderOptions = {}): string {
117
+ if (table.headers.length === 0) return ""
118
+ if (table.rows.length === 0 && options.styleHeader === false) return ""
119
+ const requestedTotalWidth = options.width ?? getTerminalWidth()
120
+ const width = Number.isFinite(requestedTotalWidth)
121
+ ? Math.max(1, Math.trunc(requestedTotalWidth))
122
+ : getTerminalWidth()
123
+ const ellipsis = options.ellipsis ?? DEFAULT_ELLIPSIS
124
+ const requestedMaxCellWidth = options.maxCellWidth ?? DEFAULT_MAX_CELL_WIDTH
125
+ const maxCellWidth = Number.isFinite(requestedMaxCellWidth)
126
+ ? Math.max(1, Math.trunc(requestedMaxCellWidth))
127
+ : DEFAULT_MAX_CELL_WIDTH
128
+ const requestedMinCellWidth = options.minCellWidth ?? MIN_CONTENT_WIDTH
129
+ const minCellWidth = Number.isFinite(requestedMinCellWidth)
130
+ ? Math.max(1, Math.trunc(requestedMinCellWidth))
131
+ : MIN_CONTENT_WIDTH
132
+ const overhead = table.headers.length * 3 - 1
133
+ const budget = width - overhead
134
+ const natural = naturalWidths(table, maxCellWidth)
135
+ const minimum = Math.max(1, Math.min(minCellWidth, ...natural.map((value) => Math.max(1, value))))
136
+ const widths =
137
+ (width < 40 && table.headers.length > 3) || budget < table.headers.length * minimum
138
+ ? null
139
+ : fitWidths(natural, budget, minimum)
140
+ if (!widths) return renderVertical(table, width, ellipsis).join("\n")
141
+
142
+ const aligns = table.aligns ?? table.headers.map(() => "left" as const)
143
+ const cell = (value: unknown, column: number): string => {
144
+ const colWidth = widths[column]!
145
+ const align = aligns[column] ?? "left"
146
+ const raw = cleanCell(value)
147
+ const rendered = options.formatCell?.(raw) ?? raw
148
+ return alignCell(truncateToWidth(rendered, colWidth, ellipsis), colWidth, align)
149
+ }
150
+ const header = table.headers.map((value, i) => {
151
+ const rendered = cell(value, i)
152
+ return options.styleHeader === false ? ` ${rendered} ` : ` ${c.bold(c.accent(rendered))} `
153
+ })
154
+ const rows = table.rows.map((row) => table.headers.map((_, i) => ` ${cell(row[i] ?? "", i)} `))
155
+ const separator = c.dim(widths.map((value) => "─".repeat(value + 2)).join(" "))
156
+ return [separator, header.join(" "), ...rows.map((row) => row.join(" "))].join("\n")
157
+ }
158
+
159
+ export const renderTableGrid = renderGridTable
160
+ export const renderGrid = renderGridTable
161
+
162
+ export function renderMarkdownTable(
163
+ table: MarkdownTable,
164
+ width = getTerminalWidth(),
165
+ formatCell?: (value: string) => string,
166
+ ): string {
167
+ return renderGridTable(
168
+ {
169
+ headers: table.headers,
170
+ rows: table.rows,
171
+ aligns: table.aligns,
172
+ },
173
+ { width, styleHeader: true, formatCell },
174
+ )
175
+ }
176
+
177
+ export function renderMarkdownTableLines(
178
+ table: MarkdownTable,
179
+ width = getTerminalWidth(),
180
+ formatCell?: (value: string) => string,
181
+ ): string[] {
182
+ const rendered = renderMarkdownTable(table, width, formatCell)
183
+ return rendered ? rendered.split("\n") : []
184
+ }