Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions Sources/verbemo/Config.swift
Original file line number Diff line number Diff line change
Expand Up @@ -480,7 +480,7 @@ enum Config {
/// Post-transcript summarization. `backend: auto` walks the chain in
/// LLMBackend: the local `claude` CLI, the Anthropic API, the `codex` CLI,
/// the OpenAI API, then ollama — subscriptions before metered keys.
struct SummarySettings {
struct SummarySettings: Sendable {
var enabled = Config.defaultFlag(.summaryEnabled)
var backend = Config.defaultString(.summaryBackend)
/// Summarizing is where a cheap model quietly costs you something:
Expand Down Expand Up @@ -547,12 +547,12 @@ enum Config {
/// named by `transcription.openai.api_key_path` (or, in a config written
/// before that setting, `summary.openai_api_key_path` — see
/// `openAIKeyFile`), verbemo's own key file, then the shared one.
static func openAIKey() -> String? {
static func openAIKey(in config: [String: Any]? = Config.raw()) -> String? {
if let env = Home.current.variable("OPENAI_API_KEY"),
!env.trimmed.isEmpty {
return env.trimmed
}
if let configured = openAIKeyFile(in: load()) { return secret(at: configured) }
if let configured = openAIKeyFile(in: config) { return secret(at: configured) }
return secret(at: openAIKeyPath) ?? secret(atAnyOf: openAISharedKeyPaths)
}

Expand All @@ -579,12 +579,12 @@ enum Config {

/// Anthropic key, in order: ANTHROPIC_API_KEY, a token file named by
/// `summary.api_key_path`, verbemo's own key file, then the shared one.
static func anthropicKey() -> String? {
static func anthropicKey(in config: [String: Any]? = Config.raw()) -> String? {
if let env = Home.current.variable("ANTHROPIC_API_KEY"),
!env.trimmed.isEmpty {
return env.trimmed
}
if let configured = summary().apiKeyPath { return secret(at: configured) }
if let configured = summary(in: config).apiKeyPath { return secret(at: configured) }
return secret(at: anthropicKeyPath) ?? secret(atAnyOf: anthropicSharedKeyPaths)
}

Expand Down
1 change: 1 addition & 0 deletions Sources/verbemo/SessionState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ enum SessionState {
/// network, spent allowance): retry later. `failed: <reason>` — it
/// won't work on a retry. Absent — nothing to do, either because the
/// summary exists or because summarizing is off.
static let summaryManual = "summary_manual"
static let summaryStatus = "summary_status"
/// The same three states for putting names to the speaker labels.
/// `deferred` — no model could be reached: retry later. `failed` — it
Expand Down
26 changes: 22 additions & 4 deletions Sources/verbemo/Sessions/PostProcessor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ enum PostProcessor {
&& (retryFailed || !gaveUp(SessionState.Key.speakersStatus, SessionState.Key.speakersFailedFor,
.speakerNames))
work.summary = policy.summary
&& meta[SessionState.Key.summaryManual] as? Bool != true
&& !hasCurrentSummary(dir, meta: meta)
&& (retryFailed || !gaveUp(SessionState.Key.summaryStatus, SessionState.Key.summaryFailedFor,
.summary))
Expand All @@ -98,13 +99,13 @@ enum PostProcessor {
}

/// Regenerate just this version's summary; keep the previous bytes on failure.
static func regenerateSummary(_ dir: URL, policy: Policy = .configured) async throws {
static func regenerateSummary(_ dir: URL, policy: Policy = .configured, request: SummaryRequest? = nil) async throws {
let root = try validatedSessionRoot(for: dir)
func validate() throws -> Transcript {
if let reason = Config.unreadableReason {
if request == nil, let reason = Config.unreadableReason {
throw Refusal.configUnreadable(reason)
}
guard policy.summary else {
guard request != nil || policy.summary else {
throw SummaryRegenerationError.unavailable(localised("Summary generation is off.", "Создание сводки выключено."))
}
guard !FileManager.default.fileExists(atPath: root.appendingPathComponent(".recording.json").path),
Expand All @@ -118,6 +119,13 @@ enum PostProcessor {
try SessionClaim.acquire(root, stage: .finish)
defer { SessionClaim.release(root) }
let transcript = try validate()
try Task.checkCancellation()
if request != nil {
// A one-run destination must never become a configured background retry.
try SessionState.amend(dir, with: [SessionState.Key.summaryManual: true])
}
try await request?.checkAccess()
try Task.checkCancellation()
let meta = SessionState.read(root) ?? [:]
let calendar = meta["calendar"] as? [String: Any]
let title = (meta["title"] as? String) ?? (calendar?["title"] as? String) ?? root.lastPathComponent
Expand All @@ -127,7 +135,7 @@ enum PostProcessor {
context.append("Participants: " + attendees.joined(separator: ", "))
}
let names = SpeakerNames.read(from: dir)
guard await Summarizer.summarize(transcript: transcript.named(with: names), context: context, into: dir) != nil else {
guard await Summarizer.summarize(transcript: transcript.named(with: names), context: context, into: dir, request: request) != nil else {
throw SummaryRegenerationError.unavailable(localised(
"The summary could not be regenerated. The previous summary is preserved; see the session log.",
"Не удалось перегенерировать сводку. Предыдущая сводка сохранена; подробности в журнале встречи."))
Expand Down Expand Up @@ -187,10 +195,20 @@ enum PostProcessor {
}
}

static func manualSummaryRefusal(_ dir: URL) -> Completion? {
let meta = SessionState.read(dir) ?? [:]
guard meta[SessionState.Key.summaryManual] as? Bool == true,
!hasCurrentSummary(dir, meta: meta) else { return nil }
let english = "This summary needs an explicit provider choice. Use Create a new summary to retry."
return .refused(english, localised(english,
"Для этой сводки нужно выбрать способ создания. Нажмите «Создать новую сводку», чтобы повторить попытку."))
}

/// The button and command share the explicit retry and its outcome; the sweep uses finish.
static func finishManually(_ dir: URL, policy: Policy = .configured) async -> Completion {
do {
let work = try await finishWork(dir, policy: policy, retryFailed: true)
if let refusal = manualSummaryRefusal(dir) { return refusal }
guard !work.isEmpty else { return .nothingToDo }
let meta = SessionState.read(dir) ?? [:]
let missingNames = work.names && !FileManager.default.fileExists(atPath: dir.appendingPathComponent(SpeakerNames.file).path)
Expand Down
7 changes: 4 additions & 3 deletions Sources/verbemo/Sessions/SpeakerNamer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ enum SpeakerNamer {
var lastModel: String?
var lastReason = Analytics.Reason.unknown

for backend in backends {
for (index, backend) in backends.enumerated() {
do {
log("naming speakers with \(backend.name)")
let answer = try await backend.call(
Expand Down Expand Up @@ -144,8 +144,9 @@ enum SpeakerNamer {
lastBackend = backend.name
lastModel = backend.model
lastReason = Analytics.reason(for: error)
log(LLMError.signInAdvice(error, backend: backend.name) ?? (LLMError.isUsageLimit(error)
? "\(backend.name) is out of allowance — trying the next backend"
let hasNext = index + 1 < backends.count
log(LLMError.signInAdvice(error, backend: backend.name, hasNextBackend: hasNext) ?? (LLMError.isUsageLimit(error)
? "\(backend.name) is out of allowance" + (hasNext ? " — trying the next backend" : "")
: "naming via \(backend.name) failed: \(error)"))
}
}
Expand Down
1 change: 1 addition & 0 deletions Sources/verbemo/Sessions/TranscriptVersions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ enum TranscriptVersions {
let reset: [String: Any?] = [
SessionState.Key.summaryStale: archive != nil && fm.fileExists(atPath: dir.appendingPathComponent("summary.md").path) ? true : nil,
SessionState.Key.speakersStatus: nil, SessionState.Key.summaryStatus: nil,
SessionState.Key.summaryManual: nil,
SessionState.Key.speakersFailedFor: nil, SessionState.Key.summaryFailedFor: nil,
SessionState.Key.speakersDeferrals: nil, SessionState.Key.summaryDeferrals: nil,
SessionState.Key.transcriptionFailed: nil, SessionState.Key.transcriptionAttempts: nil,
Expand Down
6 changes: 3 additions & 3 deletions Sources/verbemo/Setup/Credentials.swift
Original file line number Diff line number Diff line change
Expand Up @@ -123,20 +123,20 @@ enum Credentials {
// transcription.
if Home.current.variable("OPENAI_API_KEY")?
.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false {
return Config.openAIKey()
return Config.openAIKey(in: config)
}
if let named = pathSetting(.summaryOpenAIKeyPath, in: config) {
return Config.secret(at: named)
}
return Config.openAIKey()
return Config.openAIKey(in: config)
}
if let named = pathSetting(.summaryOpenAICompatibleKeyPath, in: config) {
return Config.secret(at: named)
}
if let pasted = Config.secret(at: openAICompatibleKeyPath) { return pasted }
let host = URL(string: baseURL.trimmingCharacters(in: .whitespacesAndNewlines))?
.host?.lowercased() ?? ""
return OpenAICompatible.isLoopback(host) ? Config.openAIKey() : nil
return OpenAICompatible.isLoopback(host) ? Config.openAIKey(in: config) : nil
}

private static func pathSetting(_ key: Config.Key, in config: [String: Any]?) -> URL? {
Expand Down
76 changes: 60 additions & 16 deletions Sources/verbemo/Summary/LLMBackend.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ struct LLMBackend: Sendable {
/// option — and the whole transcript went back to every backend in the
/// chain at every launch and every change of network, for ever.
var isUnchosenFallback = false
var checkAccess: @Sendable () async throws -> Void = {}
/// (system prompt, user prompt) → completion text.
let call: @Sendable (String, String) async throws -> String

Expand Down Expand Up @@ -59,27 +60,29 @@ struct LLMBackend: Sendable {
static func available(
preference: String = "auto",
anthropicModel: String? = nil,
openAIModel overriddenOpenAIModel: String? = nil
openAIModel overriddenOpenAIModel: String? = nil,
config: [String: Any]? = Config.raw(),
freezeConfiguration: Bool = false
) -> [LLMBackend] {
// Whatever the home says instead — nothing at all, in a test that has
// not brought a fake of its own.
if let supplied = Home.current.languageModels { return supplied(preference) }
let settings = Config.summary()
let settings = Config.summary(in: config)
let openAIModelID = overriddenOpenAIModel ?? settings.openAIModel

var candidates: [LLMBackend] = []
if let claude = cliPath("claude") {
candidates.append(claudeCLI(path: claude, model: anthropicModel))
}
if let key = Config.anthropicKey() {
if let key = Config.anthropicKey(in: config) {
candidates.append(anthropic(key: key, model: anthropicModel ?? settings.model))
}
if let codex = cliPath("codex") {
candidates.append(codexCLI(path: codex))
candidates.append(codexCLI(path: codex, freezeConfiguration: freezeConfiguration))
}
// Not simply the OpenAI key: an OpenAI-compatible endpoint has a key
// of its own — see `Credentials.summaryOpenAIKey`.
if let key = Credentials.summaryOpenAIKey() {
if let key = Credentials.summaryOpenAIKey(in: config) {
candidates.append(openAI(key: key, model: openAIModelID, baseURL: settings.openAIBaseURL))
}
var local = ollama(model: settings.ollamaModel, baseURL: settings.ollamaBaseURL)
Expand Down Expand Up @@ -109,10 +112,21 @@ struct LLMBackend: Sendable {
}
}

private static func checkKey(_ check: Credentials.Check) async throws {
switch await check.ask() {
case .works: return
case .refused: throw LLMError.http(401, "Authentication refused")
case .unreachable: throw URLError(.cannotConnectToHost)
case .unexpected(let status): throw LLMError.http(status, "Access check failed")
}
}

// MARK: - Anthropic

private static func claudeCLI(path: String, model: String?) -> LLMBackend {
LLMBackend(name: "claude-cli", model: model) { system, prompt in
LLMBackend(name: "claude-cli", model: model, checkAccess: {
_ = try await run(executable: path, arguments: ["auth", "status"], input: "", timeout: 20)
}) { system, prompt in
try await run(
executable: path,
arguments: claudeArguments(system: system, model: model),
Expand Down Expand Up @@ -163,7 +177,9 @@ struct LLMBackend: Sendable {
}

private static func anthropic(key: String, model: String) -> LLMBackend {
LLMBackend(name: "anthropic-api", model: model) { system, prompt in
LLMBackend(name: "anthropic-api", model: model, checkAccess: {
try await checkKey(.init(service: .anthropic, key: key))
}) { system, prompt in
var request = URLRequest(url: URL(string: "https://api.anthropic.com/v1/messages")!)
request.httpMethod = "POST"
request.timeoutInterval = 600
Expand Down Expand Up @@ -197,17 +213,31 @@ struct LLMBackend: Sendable {
/// `codex exec` prints a running trace to stdout, so the answer is read
/// from the file it writes with `--output-last-message` rather than
/// scraped out of the log.
private static func codexCLI(path: String) -> LLMBackend {
static func codexCLI(path: String, freezeConfiguration: Bool = false) -> LLMBackend {
let configURL = codexConfigURL
let config = try? Data(contentsOf: configURL)
let servers = config.flatMap { String(data: $0, encoding: .utf8) }.map(mcpServerNames(inTOML:)) ?? []
let checkConfig: @Sendable () throws -> Void = {
guard !freezeConfiguration || (try? Data(contentsOf: configURL)) == config else {
throw PostProcessor.SummaryRegenerationError.unavailable(localised(
"Codex configuration changed. Choose the provider again before sending the transcript.",
"Настройки Codex изменились. Выберите способ заново перед отправкой текста."))
}
}
// The CLI resolves its model from its own config or default. We do
// not know that model here and must not report the API's model as it.
LLMBackend(name: "codex-cli", model: nil) { system, prompt in
return LLMBackend(name: "codex-cli", model: nil, checkAccess: {
try checkConfig()
_ = try await run(executable: path, arguments: ["login", "status"], input: "", timeout: 20)
}) { system, prompt in
try checkConfig()
let output = FileManager.default.temporaryDirectory
.appendingPathComponent("verbemo-codex-\(UUID().uuidString).txt")
defer { try? FileManager.default.removeItem(at: output) }

_ = try await run(
executable: path,
arguments: codexArguments(output: output),
arguments: codexArguments(output: output, mcpServers: freezeConfiguration ? servers : codexMCPServers()),
input: "\(system)\n\n\(prompt)",
timeout: 1800
)
Expand Down Expand Up @@ -265,11 +295,15 @@ struct LLMBackend: Sendable {

/// The MCP servers the person's codex config defines, read from
/// `$CODEX_HOME/config.toml` or `~/.codex/config.toml`.
static func codexMCPServers() -> [String]? {
private static var codexConfigURL: URL {
let home = Home.current.variable("CODEX_HOME").map { Home.current.expanding($0) }
?? Home.current.url.appendingPathComponent(".codex", isDirectory: true)
return home.appendingPathComponent("config.toml")
}

static func codexMCPServers() -> [String]? {
guard let text = try? String(
contentsOf: home.appendingPathComponent("config.toml"), encoding: .utf8)
contentsOf: codexConfigURL, encoding: .utf8)
else { return [] }
return mcpServerNames(inTOML: text)
}
Expand Down Expand Up @@ -328,7 +362,10 @@ struct LLMBackend: Sendable {
}

private static func openAI(key: String, model: String, baseURL: String) -> LLMBackend {
LLMBackend(name: "openai-api", model: model) { system, prompt in
LLMBackend(name: "openai-api", model: model, checkAccess: {
_ = try OpenAICompatible.url(baseURL: baseURL, path: "models")
try await checkKey(.init(service: .openAI(baseURL: baseURL), key: key))
}) { system, prompt in
let url = try OpenAICompatible.url(baseURL: baseURL, path: "chat/completions")
var request = URLRequest(url: url)
request.httpMethod = "POST"
Expand Down Expand Up @@ -363,7 +400,13 @@ struct LLMBackend: Sendable {
// MARK: - local

private static func ollama(model: String, baseURL: String) -> LLMBackend {
LLMBackend(name: "ollama", model: model, promptLimit: OllamaClient.promptLimit) {
LLMBackend(name: "ollama", model: model, promptLimit: OllamaClient.promptLimit, checkAccess: {
let models = try await OllamaClient.listModels(baseURL: baseURL)
guard SetupSelection.ollamaModel(named: model, in: models) != nil else {
throw PostProcessor.SummaryRegenerationError.unavailable(localised(
"The selected Ollama model is unavailable.", "Выбранная модель Ollama недоступна."))
}
}) {
system, prompt in
try await OllamaClient.chat(
baseURL: baseURL, model: model, system: system, prompt: prompt)
Expand Down Expand Up @@ -500,11 +543,12 @@ enum LLMError: Error, CustomStringConvertible {
"oauth token expired", "oauth token revoked", "access token could not be refreshed",
]

static func signInAdvice(_ error: Error, backend: String) -> String? {
static func signInAdvice(_ error: Error, backend: String, hasNextBackend: Bool = true) -> String? {
guard (error as? LLMError)?.isSignedOut == true,
["claude-cli", "codex-cli"].contains(backend) else { return nil }
let command = backend == "claude-cli" ? "claude /login" : "codex login"
return "\(backend) is signed out — sign in again with `\(command)`; trying the next backend"
return "\(backend) is signed out — sign in again with `\(command)`"
+ (hasNextBackend ? "; trying the next backend" : "")
}

/// Whether the same request would plausibly succeed later: no network, a
Expand Down
Loading
Loading