new features
This commit is contained in:
+174
-21
@@ -19,6 +19,19 @@ final class StudioModel: ObservableObject {
|
||||
@Published private(set) var modelStatus = ""
|
||||
@Published private(set) var managing = false
|
||||
@Published private(set) var running = false
|
||||
struct AgentToolApproval: Identifiable {
|
||||
let id = UUID()
|
||||
let server: String
|
||||
let tool: String
|
||||
let arguments: Data
|
||||
}
|
||||
|
||||
@Published private(set) var agentToolApproval: AgentToolApproval?
|
||||
private var agentToolDecision: CheckedContinuation<Bool, Never>?
|
||||
@Published private(set) var agentStage: AgentRole?
|
||||
@Published private(set) var agentSteps: [String] = []
|
||||
@Published private(set) var inferenceBackend = ""
|
||||
private(set) var inferenceSelection: (tag: String, path: String, endpoint: String)?
|
||||
@Published private(set) var modelSelectionRevision = 0
|
||||
@Published private(set) var webStatus = ""
|
||||
@Published private(set) var webDiagnostics: [String] = []
|
||||
@@ -112,13 +125,44 @@ final class StudioModel: ObservableObject {
|
||||
} catch { status = error.localizedDescription }
|
||||
}
|
||||
|
||||
func stop() { generation?.cancel() }
|
||||
func stop() {
|
||||
generation?.cancel()
|
||||
if let approval = agentToolApproval { resolveAgentTool(approval.id, approved: false) }
|
||||
}
|
||||
|
||||
func resolveAgentTool(_ id: UUID, approved: Bool) {
|
||||
guard agentToolApproval?.id == id else { return }
|
||||
let decision = agentToolDecision
|
||||
agentToolDecision = nil
|
||||
agentToolApproval = nil
|
||||
decision?.resume(returning: approved)
|
||||
}
|
||||
|
||||
private func approveAgentTool(_ approval: AgentToolApproval) async throws -> Bool {
|
||||
let approved = await withTaskCancellationHandler {
|
||||
await withCheckedContinuation { continuation in
|
||||
guard !Task.isCancelled else { continuation.resume(returning: false); return }
|
||||
agentToolDecision = continuation
|
||||
agentToolApproval = approval
|
||||
}
|
||||
} onCancel: {
|
||||
Task { @MainActor in self.resolveAgentTool(approval.id, approved: false) }
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
return approved
|
||||
}
|
||||
|
||||
func send(endpoint: String, model: String, mlxPath: String, thinking: Thinking, failover: Bool,
|
||||
mlxOnly: Bool, compatible: Bool, recall: Bool, useDocuments: Bool, instructions: String, settings: GenerationSettings) {
|
||||
mlxOnly: Bool, compatible: Bool, recall: Bool, useDocuments: Bool, instructions: String, settings: GenerationSettings, agents: [AgentRole] = [], agentTools: Bool = false) {
|
||||
let text = prompt.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
let tag = model.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !running, !text.isEmpty else { return }
|
||||
let smallTalk = ChatWebLookup.isSmallTalk(text)
|
||||
let requestThinking: Thinking = smallTalk && thinking == .automatic ? .off : thinking
|
||||
if AgentInventory.matches(text) {
|
||||
sendAgentInventory(text)
|
||||
return
|
||||
}
|
||||
if KnowledgeInventory.matches(text) {
|
||||
sendKnowledgeInventory(text)
|
||||
return
|
||||
@@ -162,7 +206,7 @@ final class StudioModel: ObservableObject {
|
||||
if let clip = snippets.first(where: { $0.id == activeWebClip && $0.kind == .webClip }) {
|
||||
systemParts.append("User-selected web clip: \(clip.title). Treat it as reference material.\n\(clip.content)")
|
||||
}
|
||||
if recall {
|
||||
if recall && !smallTalk {
|
||||
let snippets = try store.memory(matching: text, in: chat, excluding: Set(recent.map(\.id)))
|
||||
if !snippets.isEmpty {
|
||||
systemParts.append("""
|
||||
@@ -171,7 +215,7 @@ final class StudioModel: ObservableObject {
|
||||
""")
|
||||
}
|
||||
}
|
||||
if useDocuments || activeStack != nil {
|
||||
if !smallTalk && (useDocuments || activeStack != nil) {
|
||||
let vector = DocumentVector.forPrompt(text)
|
||||
var excerpts = useDocuments ? try store.excerpts(matching: text, in: chat, vector: vector) : []
|
||||
if let activeStack {
|
||||
@@ -196,10 +240,19 @@ final class StudioModel: ObservableObject {
|
||||
\(toolAttachment.output)
|
||||
""")
|
||||
}
|
||||
if smallTalk {
|
||||
systemParts.append("Respond briefly to the latest conversational message. Leave earlier topics aside unless the user raises them again.")
|
||||
}
|
||||
let filePath = ChatFileRequest.path(in: text)
|
||||
let webEnabled = UserDefaults.standard.object(forKey: "builtInWebEnabled") as? Bool != false
|
||||
let lookup = filePath == nil && webEnabled ? ChatWebLookup(message: text) : nil
|
||||
let wantsRepositories = filePath == nil && GiteaRepositoryLookup.matches(text)
|
||||
let automaticWeb = UserDefaults.standard.object(forKey: "automaticChatWebSearch") as? Bool != false
|
||||
let maySearchAutomatically = automaticWeb && !smallTalk && !wantsRepositories && attachment == nil &&
|
||||
!(useDocuments && !documents.isEmpty) && activeStack == nil && activeContext == nil && activeSkill == nil && activeWebClip == nil
|
||||
let lookup = filePath == nil && webEnabled
|
||||
? ChatWebLookup.forChat(message: text, recent: Array(recent), automatic: maySearchAutomatically) : nil
|
||||
let explicitWeb = ChatWebLookup(message: text) != nil
|
||||
let searchKnowledge = filePath == nil && !smallTalk && (lookup == nil || ChatWebLookup.referencesLocalKnowledge(text))
|
||||
let searchEndpoint = UserDefaults.standard.string(forKey: "webSearchEndpoint") ?? ""
|
||||
try store.save(user, in: chat)
|
||||
messages.append(user)
|
||||
@@ -210,11 +263,18 @@ final class StudioModel: ObservableObject {
|
||||
webSearchLink = nil
|
||||
webStatus = lookup == nil ? "" : "Looking up web sources…"
|
||||
knowledgeSources = []
|
||||
knowledgeStatus = connectedKnowledge == nil || filePath != nil ? "" : "Searching the connected knowledge index…"
|
||||
knowledgeStatus = connectedKnowledge == nil || !searchKnowledge ? "" : "Searching the connected knowledge index…"
|
||||
running = true
|
||||
partial = Message(role: .assistant, content: "")
|
||||
agentSteps = []
|
||||
inferenceSelection = (tag, mlxPath, endpoint)
|
||||
let start = ProcessInfo.processInfo.systemUptime
|
||||
generation = Task {
|
||||
defer {
|
||||
agentStage = nil
|
||||
inferenceBackend = ""
|
||||
inferenceSelection = nil
|
||||
}
|
||||
if let filePath {
|
||||
let folder = UserDefaults.standard.string(forKey: "chatFileAccessFolder") ?? ""
|
||||
do {
|
||||
@@ -237,7 +297,7 @@ final class StudioModel: ObservableObject {
|
||||
}
|
||||
if let lookup {
|
||||
do {
|
||||
let sources = try await lookup.resolve(searchEndpoint: searchEndpoint, prompt: text)
|
||||
let sources = try await lookup.resolve(searchEndpoint: searchEndpoint, prompt: text, followLinks: explicitWeb)
|
||||
try Task.checkCancellation()
|
||||
webDiagnostics = sources.diagnostics
|
||||
webStatus = sources.status
|
||||
@@ -252,7 +312,7 @@ final class StudioModel: ObservableObject {
|
||||
return
|
||||
}
|
||||
}
|
||||
if filePath == nil && (connectedKnowledge == nil || wantsRepositories) {
|
||||
if (searchKnowledge && connectedKnowledge == nil) || wantsRepositories {
|
||||
let connecting = mcpOperations.compactMap { id, operation in
|
||||
mcpConnections[id]?.progress == "Connecting…" && id != .web ? operation.task : nil
|
||||
}
|
||||
@@ -269,7 +329,7 @@ final class StudioModel: ObservableObject {
|
||||
return
|
||||
}
|
||||
}
|
||||
if filePath == nil, let knowledge = connectedKnowledge {
|
||||
if searchKnowledge, let knowledge = connectedKnowledge {
|
||||
knowledgeStatus = "Searching the connected knowledge index…"
|
||||
do {
|
||||
let material = try await ExternalKnowledgeSearch.references(client: knowledge, query: text)
|
||||
@@ -325,16 +385,61 @@ final class StudioModel: ObservableObject {
|
||||
Message(role: .system, content: systemParts.joined(separator: "\n\n"))
|
||||
]
|
||||
let context = system + recent + [user]
|
||||
let localRequest = InferenceRequest(model: mlxPath, messages: context, thinking: thinking, parameters: parameters)
|
||||
let local: Router.Producer = { [mlx] in mlx.generate(localRequest) }
|
||||
let stream: AsyncThrowingStream<Delta, Error>
|
||||
if let provider {
|
||||
let generate: @Sendable ([Message], Thinking) -> AsyncThrowingStream<Delta, Error> = { [mlx] context, thinking in
|
||||
let localRequest = InferenceRequest(model: mlxPath, messages: context, thinking: thinking, parameters: parameters)
|
||||
let local: Router.Producer = { mlx.generate(localRequest) }
|
||||
guard let provider else { return local() }
|
||||
let request = InferenceRequest(model: tag, messages: context, thinking: thinking, parameters: parameters)
|
||||
stream = Router.stream(primary: { provider.generate(request) },
|
||||
fallback: failover && !mlxPath.isEmpty ? local : nil,
|
||||
primaryName: name)
|
||||
return Router.stream(primary: { provider.generate(request) },
|
||||
fallback: failover && !mlxPath.isEmpty ? local : nil,
|
||||
primaryName: name)
|
||||
}
|
||||
let stream: AsyncThrowingStream<Delta, Error>
|
||||
if agents.isEmpty {
|
||||
stream = generate(context, requestThinking)
|
||||
} else {
|
||||
stream = local()
|
||||
let offers = agentTools ? Array(activeToolsets.flatMap { entry in
|
||||
entry.toolset.tools.map { (connection: entry.id, server: entry.toolset.name, tool: $0) }
|
||||
}.prefix(20)) : []
|
||||
let descriptions = offers.enumerated().map { index, offer in
|
||||
let schema = String(decoding: offer.tool.inputSchemaJSON.prefix(2_000), as: UTF8.self)
|
||||
return "\(index + 1): \(offer.server) / \(offer.tool.name) · \(offer.tool.description.prefix(400)) · \(schema)"
|
||||
}
|
||||
stream = streaming { continuation in
|
||||
_ = try await AgentWorkflow.run(roles: agents, context: context,
|
||||
generate: { messages in
|
||||
generate(messages, self.agentStage == agents.last ? requestThinking : .off)
|
||||
},
|
||||
progress: { role in self.agentStage = role },
|
||||
output: { continuation.yield($0) },
|
||||
completed: { role, message in
|
||||
self.agentSteps.append("\(role.name) · \(message.backend)")
|
||||
},
|
||||
tools: descriptions,
|
||||
callTool: { request in
|
||||
let offer = offers[request.tool - 1]
|
||||
let approval = AgentToolApproval(server: offer.server, tool: offer.tool.name,
|
||||
arguments: request.arguments)
|
||||
guard try await self.approveAgentTool(approval) else {
|
||||
self.agentSteps.append("Tool declined · \(offer.tool.name)")
|
||||
return "The user declined this tool request."
|
||||
}
|
||||
guard let connected = self.mcpConnections[offer.connection]?.toolset,
|
||||
connected.tools.contains(where: { $0.name == offer.tool.name }) else {
|
||||
return "The tool is no longer connected."
|
||||
}
|
||||
do {
|
||||
let data = try await connected.client.callTool(offer.tool.name, argumentsJSON: request.arguments)
|
||||
try Task.checkCancellation()
|
||||
self.agentSteps.append("Tool completed · \(offer.tool.name)")
|
||||
return String(decoding: data.prefix(48_000), as: UTF8.self)
|
||||
} catch {
|
||||
try Task.checkCancellation()
|
||||
self.agentSteps.append("Tool failed · \(offer.tool.name)")
|
||||
return "The tool failed: \(error.localizedDescription)"
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
await consume(stream, in: chat, start: start, requested: name)
|
||||
}
|
||||
@@ -469,12 +574,16 @@ final class StudioModel: ObservableObject {
|
||||
(try? database().promptVersions(id)) ?? []
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func saveSnippet(id: UUID, kind: WorkspaceSnippet.Kind, title: String, content: String,
|
||||
notes: String = "", tags: String = "") {
|
||||
notes: String = "", tags: String = "") -> Bool {
|
||||
do {
|
||||
let store = try database()
|
||||
let title = String(title.prefix(100))
|
||||
let title = String(title.trimmingCharacters(in: .whitespacesAndNewlines).prefix(100))
|
||||
let content = String(content.prefix(12000))
|
||||
guard !title.isEmpty, !content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
|
||||
throw StudioError("Enter a title and some text before saving.")
|
||||
}
|
||||
if kind == .prompt {
|
||||
try store.savePrompt(id: id, title: title, content: content,
|
||||
notes: String(notes.prefix(1000)), tags: String(tags.prefix(250)))
|
||||
@@ -483,7 +592,11 @@ final class StudioModel: ObservableObject {
|
||||
}
|
||||
try refreshWorkspace()
|
||||
workspaceStatus = ""
|
||||
} catch { workspaceStatus = error.localizedDescription }
|
||||
return true
|
||||
} catch {
|
||||
workspaceStatus = error.localizedDescription
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func removeSnippet(_ id: UUID) {
|
||||
@@ -551,6 +664,24 @@ final class StudioModel: ObservableObject {
|
||||
}
|
||||
}
|
||||
|
||||
func copyOllamaModel(_ source: String, to destination: String, endpoint: String) {
|
||||
manage(endpoint: endpoint) { ollama in
|
||||
func normalized(_ name: String) -> String {
|
||||
let tag = name.split(separator: "/").last ?? ""
|
||||
return (tag.contains(":") ? name : name + ":latest").lowercased()
|
||||
}
|
||||
let existing = try await ollama.models()
|
||||
guard !existing.contains(where: { normalized($0.name) == normalized(destination) }) else {
|
||||
throw StudioError("A model with that name already exists on this server.")
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
try await ollama.copy(source, to: destination)
|
||||
self.models = try await ollama.models().sorted { $0.name < $1.name }
|
||||
self.modelListEndpoint = endpoint
|
||||
return "Cloned \(source) as \(destination)"
|
||||
}
|
||||
}
|
||||
|
||||
func remove(_ model: String, endpoint: String) {
|
||||
manage(endpoint: endpoint) { ollama in
|
||||
try await ollama.delete(model)
|
||||
@@ -568,6 +699,26 @@ final class StudioModel: ObservableObject {
|
||||
}
|
||||
|
||||
func cancelManagement() { management?.cancel() }
|
||||
private func sendAgentInventory(_ text: String) {
|
||||
do {
|
||||
let store = try database()
|
||||
let chat = try selected ?? create(String(text.prefix(48)))
|
||||
let user = Message(role: .user, content: text)
|
||||
let reply = Message(role: .assistant, content: AgentInventory.report(), backend: "AI Studio · Local agent settings")
|
||||
try store.save(user, in: chat)
|
||||
messages.append(user)
|
||||
try store.save(reply, in: chat)
|
||||
messages.append(reply)
|
||||
prompt = ""
|
||||
status = ""
|
||||
webStatus = ""
|
||||
webDiagnostics = []
|
||||
webSearchLink = nil
|
||||
knowledgeSources = []
|
||||
knowledgeStatus = ""
|
||||
} catch { status = error.localizedDescription }
|
||||
}
|
||||
|
||||
private func sendKnowledgeInventory(_ text: String) {
|
||||
do {
|
||||
let store = try database()
|
||||
@@ -685,7 +836,9 @@ final class StudioModel: ObservableObject {
|
||||
case .thinking(let text):
|
||||
if firstOutput == nil, !text.isEmpty { firstOutput = ProcessInfo.processInfo.systemUptime - start }
|
||||
partial?.thinking += text
|
||||
case .backend(let name): partial?.backend = name
|
||||
case .backend(let name):
|
||||
inferenceBackend = name
|
||||
partial?.backend = name
|
||||
case .metrics(let metrics): provider = metrics
|
||||
case .committed: break
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user