Open History to see the last commit
1import Foundation
2
3/// Provider- and project-scoped data used by the composer command menu.
4/// The feature layer supplies these values because the composer should not
5/// know how a particular environment fetches provider or workspace data.
6struct FeatureComposerPowerFeatures {
7 typealias PathSearch = (_ query: String) async throws -> [FeatureComposerPathEntry]
8
9 var slashCommands: [FeatureProviderSlashCommand]
10 var skills: [FeatureProviderSkill]
11 var canCompactContext: Bool
12 var pathSearchScopeID: String
13 var searchPaths: PathSearch?
14
15 init(
16 slashCommands: [FeatureProviderSlashCommand] = [],
17 skills: [FeatureProviderSkill] = [],
18 canCompactContext: Bool = false,
19 pathSearchScopeID: String = "",
20 searchPaths: PathSearch? = nil
21 ) {
22 self.slashCommands = slashCommands
23 self.skills = skills
24 self.canCompactContext = canCompactContext
25 self.pathSearchScopeID = pathSearchScopeID
26 self.searchPaths = searchPaths
27 }
28
29 static var disabled: FeatureComposerPowerFeatures { FeatureComposerPowerFeatures() }
30
31 var enabledSkills: [FeatureProviderSkill] {
32 skills.filter(\.isEnabled)
33 }
34}
35
36enum FeatureContextCompaction {
37 static func isCommand(_ text: String, hasAttachments: Bool) -> Bool {
38 !hasAttachments
39 && text.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() == "/compact"
40 }
41
42 static func canStart(in detail: FeatureThreadDetail?, isBusy: Bool) -> Bool {
43 guard let detail, !isBusy, detail.isCompacting != true,
44 detail.approvals.isEmpty, detail.userInputs.isEmpty else { return false }
45 switch detail.thread.state {
46 case .queued, .working, .monitoring, .waitingForApproval, .waitingForInput:
47 return false
48 case .idle, .completed, .failed:
49 break
50 }
51
52 return detail.messages.contains { message in
53 guard message.role == .user, message.state != .queued else { return false }
54 return !message.attachments.isEmpty
55 || (!message.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
56 && !isCommand(message.text, hasAttachments: false))
57 } || (detail.page?.hasMore == true && detail.thread.settlementFacts?.latestUserMessageAt != nil)
58 }
59}
60
61public struct FeatureProviderSlashCommand: Identifiable, Sendable, Equatable, Hashable, Codable {
62 public var id: String { name }
63 public let name: String
64 public let description: String?
65 public let inputHint: String?
66
67 public init(
68 name: String,
69 description: String? = nil,
70 inputHint: String? = nil
71 ) {
72 self.name = name
73 self.description = description
74 self.inputHint = inputHint
75 }
76}
77
78public struct FeatureProviderSkill: Identifiable, Sendable, Equatable, Hashable, Codable {
79 public var id: String { name }
80 public let name: String
81 public let displayName: String?
82 public let description: String?
83 public let shortDescription: String?
84 public let path: String
85 public let scope: String?
86 public let isEnabled: Bool
87 public var userInvocationOnly: Bool? = nil
88 public var userInvocable: Bool? = nil
89
90 var invocation: String { "\(userInvocationOnly == true ? "/" : "$")\(name) " }
91
92 public init(
93 name: String,
94 displayName: String? = nil,
95 description: String? = nil,
96 shortDescription: String? = nil,
97 path: String = "",
98 scope: String? = nil,
99 isEnabled: Bool = true
100 ) {
101 self.name = name
102 self.displayName = displayName
103 self.description = description
104 self.shortDescription = shortDescription
105 self.path = path
106 self.scope = scope
107 self.isEnabled = isEnabled
108 }
109
110 var source: FeatureProviderSkillSource {
111 let normalizedPath = path.replacingOccurrences(of: "\\", with: "/")
112 if normalizedPath.contains("/.codex/plugins/")
113 || normalizedPath.contains("/.agents/plugins/") {
114 return .app
115 }
116 switch scope?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() {
117 case "repo", "repository": return .repository
118 case "project", "workspace", "local": return .project
119 case "user", "personal": return .personal
120 case "system": return .system
121 default: return .other
122 }
123 }
124}
125
126enum FeatureProviderSkillSource: String, Sendable, Equatable {
127 case app
128 case repository
129 case project
130 case personal
131 case system
132 case other
133
134 var systemImage: String {
135 switch self {
136 case .app: "square.grid.2x2"
137 case .repository, .project: "folder"
138 case .personal: "person.crop.circle"
139 case .system: "gearshape"
140 case .other: "shippingbox"
141 }
142 }
143}
144
145struct FeatureComposerPathEntry: Identifiable, Sendable, Equatable, Hashable {
146 enum Kind: String, Sendable, Equatable, Hashable {
147 case file
148 case directory
149 }
150
151 var id: String { path }
152 let path: String
153 let kind: Kind
154
155 init(path: String, kind: Kind) {
156 self.path = path
157 self.kind = kind
158 }
159
160 var name: String {
161 let normalized = path.replacingOccurrences(of: "\\", with: "/")
162 return normalized.split(separator: "/", omittingEmptySubsequences: true)
163 .last
164 .map(String.init) ?? path
165 }
166
167 var parentPath: String {
168 let normalized = path.replacingOccurrences(of: "\\", with: "/")
169 let parts = normalized.split(separator: "/", omittingEmptySubsequences: true)
170 return parts.dropLast().joined(separator: "/")
171 }
172}
173
174enum FeatureComposerTriggerKind: Sendable, Equatable {
175 case slashCommand
176 case model
177 case skill
178 case path
179}
180
181struct FeatureComposerTrigger: Sendable, Equatable {
182 let kind: FeatureComposerTriggerKind
183 let query: String
184 let range: Range<Int>
185}
186
187struct FeatureCodexFeedbackCommand: Sendable, Equatable {
188 private static let expression = try? NSRegularExpression(
189 pattern: #"^/feedback(?:\s+([\s\S]*))?$"#,
190 options: [.caseInsensitive]
191 )
192
193 let reason: String?
194
195 static func parse(_ text: String) -> Self? {
196 let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
197 guard trimmed.lowercased().hasPrefix("/feedback"),
198 let expression,
199 let match = expression.firstMatch(
200 in: trimmed,
201 range: NSRange(trimmed.startIndex..., in: trimmed)
202 ) else {
203 return nil
204 }
205 guard match.range(at: 1).location != NSNotFound,
206 let reasonRange = Range(match.range(at: 1), in: trimmed) else {
207 return Self(reason: nil)
208 }
209 let reason = trimmed[reasonRange].trimmingCharacters(in: .whitespacesAndNewlines)
210 return Self(reason: reason.isEmpty ? nil : reason)
211 }
212}
213
214/// Mirrors the shared web/mobile trigger grammar while keeping this target
215/// independent of the TypeScript runtime.
216enum FeatureComposerTriggerParser {
217 static func detect(in text: String, cursorOffset: Int? = nil) -> FeatureComposerTrigger? {
218 let cursor = min(max(cursorOffset ?? text.count, 0), text.count)
219 let cursorIndex = text.index(text.startIndex, offsetBy: cursor)
220 let prefix = text[..<cursorIndex]
221 let lineStartIndex = prefix.lastIndex(of: "\n").map { text.index(after: $0) }
222 ?? text.startIndex
223 let lineStart = text.distance(from: text.startIndex, to: lineStartIndex)
224 let linePrefix = String(text[lineStartIndex..<cursorIndex])
225 let lowercasedLine = linePrefix.lowercased()
226
227 if lowercasedLine == "/model" {
228 return FeatureComposerTrigger(kind: .model, query: "", range: lineStart..<cursor)
229 }
230 if lowercasedLine.hasPrefix("/model ") {
231 let query = String(linePrefix.dropFirst("/model ".count))
232 .trimmingCharacters(in: .whitespaces)
233 return FeatureComposerTrigger(kind: .model, query: query, range: lineStart..<cursor)
234 }
235 if linePrefix.first == "/", !linePrefix.dropFirst().contains(where: { $0.isWhitespace }) {
236 return FeatureComposerTrigger(
237 kind: .slashCommand,
238 query: String(linePrefix.dropFirst()),
239 range: lineStart..<cursor
240 )
241 }
242
243 var tokenStartIndex = cursorIndex
244 while tokenStartIndex > text.startIndex {
245 let previous = text.index(before: tokenStartIndex)
246 if text[previous].isWhitespace { break }
247 tokenStartIndex = previous
248 }
249 let token = String(text[tokenStartIndex..<cursorIndex])
250 let tokenStart = text.distance(from: text.startIndex, to: tokenStartIndex)
251
252 if token.first == "$" {
253 return FeatureComposerTrigger(
254 kind: .skill,
255 query: String(token.dropFirst()),
256 range: tokenStart..<cursor
257 )
258 }
259 if token.first == "@" {
260 return FeatureComposerTrigger(
261 kind: .path,
262 query: String(token.dropFirst()),
263 range: tokenStart..<cursor
264 )
265 }
266 return nil
267 }
268
269 static func replacing(
270 _ range: Range<Int>,
271 in text: String,
272 with replacement: String
273 ) -> String {
274 let lower = min(max(range.lowerBound, 0), text.count)
275 let upper = min(max(range.upperBound, lower), text.count)
276 let start = text.index(text.startIndex, offsetBy: lower)
277 let end = text.index(text.startIndex, offsetBy: upper)
278 return String(text[..<start]) + replacement + String(text[end...])
279 }
280}
281
282enum FeatureComposerFileLinkSerializer {
283 static func url(for path: String) -> URL? {
284 // Keep a Windows drive followed by a slash so the workspace router
285 // recognizes it as a file path instead of an external URL scheme.
286 URL(string: encodeDestination(path.replacingOccurrences(of: "\\", with: "/")))
287 }
288
289 static func markdownLink(for path: String) -> String {
290 let normalized = path.replacingOccurrences(of: "\\", with: "/")
291 let basename = normalized.split(separator: "/", omittingEmptySubsequences: true)
292 .last
293 .map(String.init) ?? path
294 let label = basename
295 .replacingOccurrences(of: "\\", with: "\\\\")
296 .replacingOccurrences(of: "[", with: "\\[")
297 .replacingOccurrences(of: "]", with: "\\]")
298 return "[\(label)](\(encodeDestination(path)))"
299 }
300
301 private static func encodeDestination(_ path: String) -> String {
302 let unescaped = Set(
303 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;,/:@&=+$-_.!~*'"
304 )
305 return path.utf8.map { byte -> String in
306 guard byte < 128,
307 let scalar = UnicodeScalar(Int(byte)),
308 unescaped.contains(Character(String(scalar))) else {
309 return String(format: "%%%02X", byte)
310 }
311 return String(scalar)
312 }.joined()
313 }
314}
315
316enum FeatureComposerMenuItem: Identifiable, Sendable, Equatable {
317 case modelCommand
318 case model(selection: FeatureSelection, label: String, description: String)
319 case providerCommand(FeatureProviderSlashCommand)
320 case skill(FeatureProviderSkill)
321 case path(FeatureComposerPathEntry)
322
323 var id: String {
324 switch self {
325 case .modelCommand: "command:model"
326 case let .model(selection, _, _): "model:\(selection.providerID):\(selection.modelID)"
327 case let .providerCommand(command): "command:\(command.id)"
328 case let .skill(skill): "skill:\(skill.id)"
329 case let .path(entry): "path:\(entry.path)"
330 }
331 }
332
333 var label: String {
334 switch self {
335 case .modelCommand: "/model"
336 case let .model(_, label, _): label
337 case let .providerCommand(command): "/\(command.name)"
338 case let .skill(skill): skill.displayName ?? skill.name
339 case let .path(entry): entry.name
340 }
341 }
342
343 var description: String {
344 switch self {
345 case .modelCommand: "Switch model"
346 case let .model(_, _, description): description
347 case let .providerCommand(command):
348 command.description ?? command.inputHint ?? ""
349 case let .skill(skill):
350 skill.shortDescription ?? skill.description ?? skill.scope ?? ""
351 case let .path(entry): entry.parentPath
352 }
353 }
354}
355
356enum FeatureComposerMenuBuilder {
357 private static func normalizedName(_ name: String) -> String {
358 name.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
359 }
360
361 private static func enabledSkills(
362 in skills: [FeatureProviderSkill]
363 ) -> [FeatureProviderSkill] {
364 var seenNames = Set<String>()
365 return skills.filter { skill in
366 guard skill.isEnabled else { return false }
367 return seenNames.insert(normalizedName(skill.name)).inserted
368 }
369 }
370
371 static func items(
372 trigger: FeatureComposerTrigger,
373 providers: [FeatureProvider],
374 currentSelection: FeatureSelection?,
375 threadSelection: FeatureSelection?,
376 powerFeatures: FeatureComposerPowerFeatures,
377 pathEntries: [FeatureComposerPathEntry]
378 ) -> [FeatureComposerMenuItem] {
379 switch trigger.kind {
380 case .slashCommand:
381 let query = trigger.query.lowercased()
382 let normalizedSkillQuery = query.hasPrefix("skill:")
383 ? String(query.dropFirst("skill:".count))
384 : query
385 var items: [FeatureComposerMenuItem] = []
386 if query.isEmpty || "model".contains(query) {
387 items.append(.modelCommand)
388 }
389 let enabledSkills = enabledSkills(in: powerFeatures.skills)
390 let skills = enabledSkills
391 .filter { $0.userInvocable != false }
392 .filter { skill in
393 guard !normalizedSkillQuery.isEmpty else { return true }
394 return [skill.name, skill.displayName, skill.shortDescription, skill.description]
395 .compactMap { $0 }
396 .contains { $0.localizedCaseInsensitiveContains(normalizedSkillQuery) }
397 }
398 .sorted {
399 ($0.displayName ?? $0.name).localizedStandardCompare($1.displayName ?? $1.name)
400 == .orderedAscending
401 }
402 let enabledSkillNames = Set(enabledSkills.map { normalizedName($0.name) })
403 let excludedCommandNames = Set(["model", "plan", "default"].map(normalizedName))
404 let commands = powerFeatures.slashCommands
405 .filter { !excludedCommandNames.contains(normalizedName($0.name)) }
406 .filter { normalizedName($0.name) != "compact" || powerFeatures.canCompactContext }
407 .filter { !enabledSkillNames.contains(normalizedName($0.name)) }
408 .filter { query.isEmpty || $0.name.localizedCaseInsensitiveContains(query) }
409 .sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
410 items.append(contentsOf: commands.map(FeatureComposerMenuItem.providerCommand))
411 items.append(contentsOf: skills.map(FeatureComposerMenuItem.skill))
412 return Array(items.prefix(20))
413
414 case .model:
415 let query = trigger.query.trimmingCharacters(in: .whitespacesAndNewlines)
416 return providers
417 .filter(\.isAvailable)
418 .filter { provider in
419 threadSelection == nil || provider.id == threadSelection?.providerID
420 }
421 .flatMap { provider in
422 provider.models
423 .filter { model in
424 guard provider.requiresNewThreadForModelChange,
425 let threadSelection else { return true }
426 return model.id == threadSelection.modelID
427 }
428 .map { model in
429 (
430 item: FeatureComposerMenuItem.model(
431 selection: FeatureSelection(
432 providerID: provider.id,
433 modelID: model.id,
434 options: currentSelection?.providerID == provider.id
435 && currentSelection?.modelID == model.id
436 ? currentSelection?.options ?? []
437 : DailyUXModelOptions.defaults(for: model)
438 ),
439 label: model.name,
440 description: provider.name
441 ),
442 searchText: "\(provider.name) \(model.name) \(model.id)"
443 )
444 }
445 }
446 .filter { query.isEmpty || $0.searchText.localizedCaseInsensitiveContains(query) }
447 .prefix(20)
448 .map(\.item)
449
450 case .skill:
451 let query = trigger.query.trimmingCharacters(in: .whitespacesAndNewlines)
452 return enabledSkills(in: powerFeatures.skills)
453 .filter { skill in
454 guard !query.isEmpty else { return true }
455 return [skill.name, skill.displayName, skill.shortDescription, skill.description]
456 .compactMap { $0 }
457 .contains { $0.localizedCaseInsensitiveContains(query) }
458 }
459 .sorted {
460 ($0.displayName ?? $0.name).localizedStandardCompare($1.displayName ?? $1.name)
461 == .orderedAscending
462 }
463 .prefix(20)
464 .map(FeatureComposerMenuItem.skill)
465
466 case .path:
467 return pathEntries
468 .uniquedByPath()
469 .prefix(20)
470 .map(FeatureComposerMenuItem.path)
471 }
472 }
473}
474
475private extension Array where Element == FeatureComposerPathEntry {
476 func uniquedByPath() -> [Element] {
477 var seen = Set<String>()
478 return filter { seen.insert($0.path).inserted }
479 }
480}