Open History to see the last commit
1import Foundation
2
3enum CodexArtifactTemplateKind: String, Equatable, Sendable {
4 case document, presentation, spreadsheet, site
5 case googleDocs = "google-docs"
6 case googleSlides = "google-slides"
7 case googleSheets = "google-sheets"
8 case image, email, slack
9
10 var label: String {
11 switch self {
12 case .document: "Document template"
13 case .presentation: "Presentation template"
14 case .spreadsheet: "Spreadsheet template"
15 case .site: "Site template"
16 case .googleDocs: "Google Doc template"
17 case .googleSlides: "Google Slides template"
18 case .googleSheets: "Google Sheet template"
19 case .image: "Image template"
20 case .email: "Email template"
21 case .slack: "Slack template"
22 }
23 }
24
25 func usePrompt(skillName: String) -> String {
26 let skill = "$\(skillName)"
27 return switch self {
28 case .document: "Create a document using this \(skill) about…"
29 case .presentation: "Create a presentation using the \(skill) template about…"
30 case .spreadsheet: "Create a spreadsheet using this \(skill) about…"
31 case .site: "Create a Site using this \(skill) about…"
32 case .googleDocs: "Create a Google Doc using this \(skill) about…"
33 case .googleSlides: "Create a Google Slides presentation using this \(skill) about…"
34 case .googleSheets: "Create a Google Sheet using this \(skill) about…"
35 case .image: "Create an image using this \(skill) of…"
36 case .email: "Draft an email using this \(skill) about…"
37 case .slack: "Draft a Slack message using this \(skill) about…"
38 }
39 }
40}
41
42struct CodexArtifactTemplate: Equatable, Sendable {
43 let kind: CodexArtifactTemplateKind
44 let displayName: String
45 let skillDirectory: String
46 let skillName: String
47 let galleryKind: String?
48
49 var usePrompt: String { kind.usePrompt(skillName: skillName) }
50
51 var useURL: URL? {
52 var components = URLComponents()
53 components.scheme = "t3code"
54 components.host = "codex-artifact-template"
55 components.path = "/use"
56 components.queryItems = [URLQueryItem(name: "prompt", value: usePrompt)]
57 return components.url
58 }
59}
60
61enum CodexMarkdownDirectives {
62 private static let artifactPrefix = "::artifact-template{"
63 private static let fileCitationPrefix = ":codex-file-citation{"
64 private static let fileCitationCharacters = Array(fileCitationPrefix)
65
66 static func artifactTemplate(from line: String) -> CodexArtifactTemplate? {
67 guard line.prefix(while: { $0 == " " }).count < 4, line.first != "\t" else {
68 return nil
69 }
70 let source = line.trimmingCharacters(in: .whitespaces)
71 guard source.hasPrefix(artifactPrefix), source.hasSuffix("}"),
72 let attributes = attributes(
73 in: String(source.dropFirst(artifactPrefix.count).dropLast())
74 ),
75 let kindValue = attributes["artifact_kind"],
76 let kind = CodexArtifactTemplateKind(rawValue: kindValue),
77 let displayName = attributes["display_name"]?.trimmingCharacters(
78 in: .whitespacesAndNewlines
79 ), !displayName.isEmpty,
80 let directory = attributes["skill_directory"], isAbsolutePath(directory),
81 let skillName = attributes["skill_name"],
82 skillName.hasPrefix("artifact-template-") else { return nil }
83
84 let gallery = attributes["gallery_kind"]
85 guard gallery == nil || gallery == "imagegen" || gallery == "product-design" else {
86 return nil
87 }
88 return CodexArtifactTemplate(
89 kind: kind,
90 displayName: displayName,
91 skillDirectory: directory,
92 skillName: skillName,
93 galleryKind: gallery
94 )
95 }
96
97 static func replacingFileCitations(in source: String) -> String {
98 // Most messages have no citations. Keep them out of the character-by-character
99 // link and code scanner, including incomplete Markdown arriving in a stream.
100 guard source.contains(fileCitationPrefix) else { return source }
101 let lines = source.components(separatedBy: "\n")
102 var fence: Character?
103 var fenceCount = 0
104 return lines.map { line in
105 let trimmed = line.drop(while: { $0 == " " || $0 == "\t" })
106 if let marker = trimmed.first, marker == "`" || marker == "~" {
107 let count = trimmed.prefix(while: { $0 == marker }).count
108 if count >= 3 {
109 if fence == nil { fence = marker; fenceCount = count }
110 else if fence == marker, count >= fenceCount { fence = nil }
111 return line
112 }
113 }
114 let leadingSpaces = line.prefix(while: { $0 == " " }).count
115 guard fence == nil, leadingSpaces < 4, line.first != "\t",
116 line.contains(fileCitationPrefix) else {
117 return line
118 }
119 return replacingCitationsInInlineMarkdown(line)
120 }.joined(separator: "\n")
121 }
122
123 private static func replacingCitationsInInlineMarkdown(_ line: String) -> String {
124 let characters = Array(line)
125 var result = ""
126 var cursor = 0
127
128 while cursor < characters.count {
129 if characters[cursor] == "[", !isEscaped(at: cursor, in: characters),
130 let end = markdownLinkEnd(in: characters, from: cursor) {
131 result += String(characters[cursor..<end])
132 cursor = end
133 continue
134 }
135 if characters[cursor] == "`", !isEscaped(at: cursor, in: characters) {
136 let end = characters[cursor...].prefix(while: { $0 == "`" }).count + cursor
137 let count = end - cursor
138 if let closing = closingBacktickRun(
139 ofLength: count,
140 after: end,
141 in: characters
142 ) {
143 result += String(characters[cursor..<closing])
144 cursor = closing
145 continue
146 }
147 }
148 if characters[cursor] == ":", !isEscaped(at: cursor, in: characters),
149 characters[cursor...].starts(with: fileCitationCharacters),
150 let closing = directiveEnd(in: characters, from: cursor) {
151 let directive = String(characters[cursor...closing])
152 if let replacement = fileCitation(from: directive) {
153 result += replacement
154 cursor = closing + 1
155 continue
156 }
157 }
158 result.append(characters[cursor]); cursor += 1
159 }
160 return result
161 }
162
163 static func fileCitation(from directive: String) -> String? {
164 let prefix = fileCitationPrefix
165 guard directive.hasPrefix(prefix), directive.hasSuffix("}"),
166 let values = attributes(in: String(directive.dropFirst(prefix.count).dropLast())),
167 let rawPath = values["path"] else { return nil }
168 let path = rawPath.trimmingCharacters(in: .whitespacesAndNewlines)
169 guard !path.isEmpty else { return nil }
170 let normalizedPath = path.replacingOccurrences(of: "\\", with: "/")
171 .replacingOccurrences(of: #"/+$"#, with: "", options: .regularExpression)
172 let label = normalizedPath.split(separator: "/").last.map(String.init)
173 ?? (normalizedPath.isEmpty ? "File" : normalizedPath)
174 var destination = path
175 .replacingOccurrences(of: "%", with: "%25")
176 .replacingOccurrences(of: "#", with: "%23")
177 .replacingOccurrences(of: "?", with: "%3F")
178 .replacingOccurrences(of: "<", with: "%3C")
179 .replacingOccurrences(of: ">", with: "%3E")
180 .replacingOccurrences(of: "\r", with: "%0D")
181 .replacingOccurrences(of: "\n", with: "%0A")
182 if let line = values["line_range_start"],
183 let value = Int(line.trimmingCharacters(in: .whitespacesAndNewlines)), value > 0 {
184 destination += "#L\(value)"
185 }
186 return "[\(escapedMarkdownLabel(label))](<\(destination)>)"
187 }
188
189 private static func attributes(in source: String) -> [String: String]? {
190 let chars = Array(source)
191 var values: [String: String] = [:]
192 var cursor = 0
193 while cursor < chars.count {
194 while cursor < chars.count, chars[cursor].isWhitespace { cursor += 1 }
195 guard cursor < chars.count else { break }
196 let keyStart = cursor
197 while cursor < chars.count, chars[cursor].isLetter || chars[cursor].isNumber
198 || chars[cursor] == "_" { cursor += 1 }
199 guard cursor > keyStart else { return nil }
200 let key = String(chars[keyStart..<cursor])
201 while cursor < chars.count, chars[cursor].isWhitespace { cursor += 1 }
202 guard cursor < chars.count, chars[cursor] == "=" else { return nil }
203 cursor += 1
204 while cursor < chars.count, chars[cursor].isWhitespace { cursor += 1 }
205 guard cursor < chars.count else { return nil }
206 let quote: Character? = chars[cursor] == "\"" || chars[cursor] == "'"
207 ? chars[cursor]
208 : nil
209 if quote != nil { cursor += 1 }
210 var value = ""
211 while cursor < chars.count,
212 quote == nil ? !chars[cursor].isWhitespace : chars[cursor] != quote {
213 if chars[cursor] == "\\", cursor + 1 < chars.count,
214 chars[cursor + 1] == quote || chars[cursor + 1] == "\\" {
215 cursor += 1
216 }
217 value.append(chars[cursor]); cursor += 1
218 }
219 guard !value.isEmpty else { return nil }
220 if quote != nil {
221 guard cursor < chars.count else { return nil }
222 cursor += 1
223 }
224 guard values.updateValue(value, forKey: key) == nil else { return nil }
225 }
226 return values
227 }
228
229 private static func markdownLinkEnd(in chars: [Character], from start: Int) -> Int? {
230 guard let labelEnd = closingBracket(in: chars, from: start) else { return nil }
231 let suffix = labelEnd + 1
232 guard suffix < chars.count else { return nil }
233 if chars[suffix] == "(" {
234 return closingDelimiter(")", in: chars, after: suffix)
235 }
236 if chars[suffix] == "[" {
237 return closingBracket(in: chars, from: suffix).map { $0 + 1 }
238 }
239 return nil
240 }
241
242 private static func closingBracket(in chars: [Character], from start: Int) -> Int? {
243 var depth = 1
244 var cursor = start + 1
245 while cursor < chars.count {
246 if !isEscaped(at: cursor, in: chars) {
247 if chars[cursor] == "[" { depth += 1 }
248 if chars[cursor] == "]" {
249 depth -= 1
250 if depth == 0 { return cursor }
251 }
252 }
253 cursor += 1
254 }
255 return nil
256 }
257
258 private static func closingDelimiter(
259 _ delimiter: Character,
260 in chars: [Character],
261 after start: Int
262 ) -> Int? {
263 var cursor = start + 1
264 while cursor < chars.count {
265 if chars[cursor] == delimiter, !isEscaped(at: cursor, in: chars) { return cursor + 1 }
266 cursor += 1
267 }
268 return nil
269 }
270
271 private static func closingBacktickRun(
272 ofLength length: Int,
273 after start: Int,
274 in chars: [Character]
275 ) -> Int? {
276 var cursor = start
277 while cursor < chars.count {
278 guard chars[cursor] == "`", !isEscaped(at: cursor, in: chars) else {
279 cursor += 1
280 continue
281 }
282 let end = chars[cursor...].prefix(while: { $0 == "`" }).count + cursor
283 if end - cursor == length { return end }
284 cursor = end
285 }
286 return nil
287 }
288
289 private static func directiveEnd(in chars: [Character], from start: Int) -> Int? {
290 var cursor = start + fileCitationCharacters.count
291 var quote: Character?
292 while cursor < chars.count {
293 let character = chars[cursor]
294 if let activeQuote = quote {
295 if character == activeQuote, !isEscaped(at: cursor, in: chars) { quote = nil }
296 } else if character == "\"" || character == "'" {
297 quote = character
298 } else if character == "}" {
299 return cursor
300 }
301 cursor += 1
302 }
303 return nil
304 }
305
306 private static func isEscaped(at index: Int, in chars: [Character]) -> Bool {
307 guard index > 0 else { return false }
308 var backslashes = 0
309 var cursor = index - 1
310 while chars[cursor] == "\\" {
311 backslashes += 1
312 guard cursor > 0 else { break }
313 cursor -= 1
314 }
315 return backslashes.isMultiple(of: 2) == false
316 }
317
318 private static func escapedMarkdownLabel(_ value: String) -> String {
319 let escaped = CharacterSet(charactersIn: "\\[]*_`<&")
320 return value.unicodeScalars.reduce(into: "") { result, scalar in
321 if escaped.contains(scalar) { result.append("\\") }
322 result.unicodeScalars.append(scalar)
323 }
324 }
325
326 private static func isAbsolutePath(_ path: String) -> Bool {
327 if path.hasPrefix("/"), !path.hasPrefix("//") { return true }
328 if path.range(of: #"^[A-Za-z]:[\\/]"#, options: .regularExpression) != nil { return true }
329 return path.range(of: #"^(?:\\\\[^\\]+\\[^\\]+|//[^/]+/[^/]+)"#,
330 options: .regularExpression) != nil
331 }
332}