Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Markdown/MarkdownBlocks.swift3// Description: Block-level parser for the Markdown the research agent writes (headings, lists, tables, code, figures, quotes); inline styling is left to AttributedString.4import Foundation56public enum MarkdownBlock: Sendable, Equatable {7 case heading(level: Int, text: String)8 case paragraph(String)9 case list(items: [ListItem])10 case table(header: [String], rows: [[String]], alignments: [Alignment])11 case code(language: String?, text: String)12 /// display math between `$$` or `\[ \]`: shown as source (there is no native TeX engine in the app)13 case math(String)14 case image(alt: String, url: String)15 case quote(String)16 case rule1718 public struct ListItem: Sendable, Equatable {19 public var depth: Int20 /// "•" for bullets, "3." for ordered items21 public var marker: String22 public var text: String23 }24 public enum Alignment: Sendable, Equatable { case leading, center, trailing }25}2627public enum MarkdownParser {28 /// Parses a complete or still-streaming document. An unterminated code fence is treated as code to the end, so a29 /// report renders sensibly while it is being written.30 public static func parse(_ source: String) -> [MarkdownBlock] {31 var blocks: [MarkdownBlock] = []32 let lines = source.replacingOccurrences(of: "\r\n", with: "\n").components(separatedBy: "\n")33 var i = 034 var para: [String] = []35 func flush() { if !para.isEmpty { blocks.append(.paragraph(para.joined(separator: "\n"))); para = [] } }3637 while i < lines.count {38 let raw = lines[i]39 let line = raw.trimmingCharacters(in: .whitespaces)4041 if line.hasPrefix("```") || line.hasPrefix("~~~") {42 flush()43 let fence = String(line.prefix(3))44 let lang = line.dropFirst(3).trimmingCharacters(in: .whitespaces)45 var body: [String] = []46 i += 147 while i < lines.count, !lines[i].trimmingCharacters(in: .whitespaces).hasPrefix(fence) { body.append(lines[i]); i += 1 }48 i += 149 blocks.append(.code(language: lang.isEmpty ? nil : lang, text: body.joined(separator: "\n")))50 continue51 }52 if line == "$$" || line == "\\[" {53 flush()54 let close = line == "$$" ? "$$" : "\\]"55 var body: [String] = []56 i += 157 while i < lines.count, lines[i].trimmingCharacters(in: .whitespaces) != close { body.append(lines[i]); i += 1 }58 i += 159 blocks.append(.math(body.joined(separator: "\n")))60 continue61 }62 if line.hasPrefix("$$"), line.hasSuffix("$$"), line.count > 4 {63 flush(); blocks.append(.math(String(line.dropFirst(2).dropLast(2)).trimmingCharacters(in: .whitespaces))); i += 1; continue64 }65 if line.isEmpty { flush(); i += 1; continue }6667 if let h = heading(line) { flush(); blocks.append(h); i += 1; continue }68 if isRule(line) { flush(); blocks.append(.rule); i += 1; continue }69 if let img = image(line) { flush(); blocks.append(img); i += 1; continue }7071 if line.hasPrefix("|") || (line.contains("|") && i + 1 < lines.count && isTableDivider(lines[i + 1])) {72 if i + 1 < lines.count, isTableDivider(lines[i + 1]) {73 flush()74 let header = cells(line)75 let aligns = cells(lines[i + 1]).map(alignment)76 var rows: [[String]] = []77 i += 278 while i < lines.count {79 let l = lines[i].trimmingCharacters(in: .whitespaces)80 guard !l.isEmpty, l.contains("|") else { break }81 var r = cells(l)82 if r.count < header.count { r += Array(repeating: "", count: header.count - r.count) }83 rows.append(Array(r.prefix(header.count)))84 i += 185 }86 blocks.append(.table(header: header, rows: rows, alignments: aligns + Array(repeating: .leading, count: max(0, header.count - aligns.count))))87 continue88 }89 }90 if line.hasPrefix(">") {91 flush()92 var body: [String] = []93 while i < lines.count, lines[i].trimmingCharacters(in: .whitespaces).hasPrefix(">") {94 var l = lines[i].trimmingCharacters(in: .whitespaces).dropFirst()95 if l.first == " " { l = l.dropFirst() }96 body.append(String(l)); i += 197 }98 blocks.append(.quote(body.joined(separator: "\n")))99 continue100 }101 if listItem(raw) != nil {102 flush()103 var items: [MarkdownBlock.ListItem] = []104 while i < lines.count {105 if let it = listItem(lines[i]) { items.append(it); i += 1 }106 else if !lines[i].trimmingCharacters(in: .whitespaces).isEmpty, lines[i].hasPrefix(" "), !items.isEmpty {107 // continuation line of the previous item108 items[items.count - 1].text += " " + lines[i].trimmingCharacters(in: .whitespaces); i += 1109 } else { break }110 }111 blocks.append(.list(items: items))112 continue113 }114 para.append(line); i += 1115 }116 flush()117 return blocks118 }119120 static func heading(_ line: String) -> MarkdownBlock? {121 guard line.hasPrefix("#") else { return nil }122 let level = line.prefix(while: { $0 == "#" }).count123 guard level <= 6, line.count > level, line[line.index(line.startIndex, offsetBy: level)] == " " else { return nil }124 var text = line.dropFirst(level).trimmingCharacters(in: .whitespaces)125 while text.hasSuffix("#") { text = String(text.dropLast()).trimmingCharacters(in: .whitespaces) }126 return .heading(level: level, text: text)127 }128129 static func isRule(_ line: String) -> Bool {130 let s = line.replacingOccurrences(of: " ", with: "")131 return s.count >= 3 && (s.allSatisfy { $0 == "-" } || s.allSatisfy { $0 == "*" } || s.allSatisfy { $0 == "_" })132 }133134 /// A line that is only an image: `` (optionally with a title after the URL).135 static func image(_ line: String) -> MarkdownBlock? {136 guard line.hasPrefix(" else { return nil }137 let alt = String(line[line.index(line.startIndex, offsetBy: 2)..<close.lowerBound])138 var url = String(line[close.upperBound..<line.index(before: line.endIndex)])139 guard !alt.contains("]("), !url.contains("](") else { return nil }140 if let sp = url.firstIndex(of: " ") { url = String(url[..<sp]) }141 return url.isEmpty ? nil : .image(alt: alt, url: url)142 }143144 static func isTableDivider(_ raw: String) -> Bool {145 let l = raw.trimmingCharacters(in: .whitespaces)146 guard l.contains("-"), l.contains("|") || l.hasPrefix(":") || l.hasPrefix("-") else { return false }147 let c = cells(l)148 return !c.isEmpty && c.allSatisfy { cell in149 let t = cell.trimmingCharacters(in: .whitespaces)150 return t.count >= 1 && t.contains("-") && t.allSatisfy { $0 == "-" || $0 == ":" }151 }152 }153154 /// Splits a table row on unescaped pipes outside code spans.155 static func cells(_ raw: String) -> [String] {156 var l = raw.trimmingCharacters(in: .whitespaces)157 if l.hasPrefix("|") { l.removeFirst() }158 if l.hasSuffix("|"), !l.hasSuffix("\\|") { l.removeLast() }159 var out: [String] = []; var cur = ""; var inCode = false; var escaped = false160 for ch in l {161 if escaped { cur.append(ch); escaped = false; continue }162 if ch == "\\" { escaped = true; continue }163 if ch == "`" { inCode.toggle(); cur.append(ch); continue }164 if ch == "|", !inCode { out.append(cur.trimmingCharacters(in: .whitespaces)); cur = ""; continue }165 cur.append(ch)166 }167 out.append(cur.trimmingCharacters(in: .whitespaces))168 return out169 }170171 static func alignment(_ cell: String) -> MarkdownBlock.Alignment {172 let t = cell.trimmingCharacters(in: .whitespaces)173 if t.hasPrefix(":"), t.hasSuffix(":") { return .center }174 if t.hasSuffix(":") { return .trailing }175 return .leading176 }177178 static func listItem(_ raw: String) -> MarkdownBlock.ListItem? {179 let indent = raw.prefix(while: { $0 == " " || $0 == "\t" }).reduce(0) { $0 + ($1 == "\t" ? 4 : 1) }180 let line = raw.trimmingCharacters(in: .whitespaces)181 if line.count > 2, let f = line.first, "-*+".contains(f), line[line.index(after: line.startIndex)] == " " {182 guard !isRule(line) else { return nil }183 return .init(depth: indent / 2, marker: "•", text: String(line.dropFirst(2)).trimmingCharacters(in: .whitespaces))184 }185 let digits = line.prefix(while: \.isNumber)186 if !digits.isEmpty, digits.count <= 4 {187 let rest = line.dropFirst(digits.count)188 if let f = rest.first, f == "." || f == ")", rest.dropFirst().first == " " {189 return .init(depth: indent / 2, marker: "\(digits).", text: String(rest.dropFirst(2)).trimmingCharacters(in: .whitespaces))190 }191 }192 return nil193 }194}195196/// The agent's report markers (`:gold:`, `:up:`, `:warn:` …, see shared/vqMarkers.ts on the server) and the emoji it197/// may still write, as SF Symbol names for native rendering.198public enum ReportMarkers {199 public static let symbols: [String: (symbol: String, label: String)] = [200 "gold": ("1.circle.fill", "1st"), "silver": ("2.circle.fill", "2nd"), "bronze": ("3.circle.fill", "3rd"),201 "up": ("arrow.up.square.fill", "up"), "down": ("arrow.down.square.fill", "down"), "flat": ("arrow.right.square.fill", "flat"),202 "bull": ("chart.line.uptrend.xyaxis.circle.fill", "bullish"), "bear": ("chart.line.downtrend.xyaxis.circle.fill", "bearish"),203 "check": ("checkmark.circle.fill", "yes"), "cross": ("xmark.circle.fill", "no"), "warn": ("exclamationmark.triangle.fill", "caution"),204 "star": ("star.fill", "key point"), "risk": ("exclamationmark.shield.fill", "risk"), "target": ("target", "target"),205 "idea": ("lightbulb.fill", "idea"), "clock": ("clock.fill", "watch"),206 ]207 static let emoji: [(String, String)] = [208 ("🥇", "gold"), ("🥈", "silver"), ("🥉", "bronze"), ("✅", "check"), ("☑️", "check"), ("✔️", "check"), ("❌", "cross"), ("✖️", "cross"),209 ("⚠️", "warn"), ("⚠", "warn"), ("📈", "up"), ("📉", "down"), ("🎯", "target"), ("💡", "idea"), ("⭐️", "star"), ("⭐", "star"), ("🌟", "star"),210 ("🟢", "check"), ("🔴", "cross"), ("🟡", "warn"), ("🟠", "warn"), ("⏰", "clock"), ("🕒", "clock"), ("📅", "clock"), ("🗓️", "clock"), ("🚨", "risk"),211 ]212213 public enum Piece: Sendable, Equatable { case text(String); case marker(String) }214215 /// Splits inline text into plain runs and known markers. `:name:` inside a word or a URL is left alone.216 public static func split(_ input: String) -> [Piece] {217 var text = input218 for (e, name) in emoji where text.contains(e) { text = text.replacingOccurrences(of: e, with: ":\(name):") }219 guard text.contains(":") else { return [.text(text)] }220 var out: [Piece] = []; var cur = ""221 let chars = Array(text); var i = 0222 func wordish(_ c: Character) -> Bool { c.isLetter || c.isNumber || c == "_" }223 while i < chars.count {224 if chars[i] == ":", let end = chars[(i + 1)...].firstIndex(of: ":"), end - i <= 8 {225 let name = String(chars[(i + 1)..<end])226 let before = i > 0 ? chars[i - 1] : " ", after = end + 1 < chars.count ? chars[end + 1] : " "227 if symbols[name] != nil, !wordish(before), before != ":", before != "/", !wordish(after), after != "/" {228 if !cur.isEmpty { out.append(.text(cur)); cur = "" }229 out.append(.marker(name)); i = end + 1; continue230 }231 }232 cur.append(chars[i]); i += 1233 }234 if !cur.isEmpty { out.append(.text(cur)) }235 return out236 }237}238