Skip to content

Open source CapCut alternative.

TypeScript

Handle hosted planner failures without running local tasks

David Le0945502b631c
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
index 8becb6ed..742b3981 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
@@ -241,6 +241,48 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
]
)
+ if Self.shouldFailSafelyWithoutLocalTask(resolution) {
+ let response = Self.modelUnavailableResponse(for: resolution)
+ let decision = AppHarnessDecision(
+ kind: .respond,
+ message: response,
+ traceID: traceID,
+ metadata: [
+ "structuredDecision": "true",
+ "router": "modelUnavailable",
+ "resolution.status": resolution.status.rawValue
+ ]
+ )
+ let handlingResult = UserQueryCommandHandlingResult(
+ status: .failedSafe,
+ threadStatus: .failed,
+ decision: decision,
+ summary: response,
+ taskLabel: nil,
+ traceID: traceID,
+ metadata: modelMetadata.merging([
+ "appHarness.decision": AppHarnessDecisionKind.respond.rawValue,
+ "router": "modelUnavailable",
+ "resolution.status": resolution.status.rawValue,
+ "resolution.reason": resolution.metadata["reason"] ?? ""
+ ]) { _, new in new },
+ documentReviewRequest: nil,
+ agentVisualizationPlan: nil,
+ cursorOverlayRequest: nil
+ )
+ _ = await genericHarnessLifecycle.coordinator.failSafe(
+ taskID: taskID,
+ reason: "Hosted command parser did not produce a safe action plan"
+ )
+ await coordinatorRegistry.finish(taskID: taskID)
+ logHandlingResult(
+ handlingResult,
+ stage: "modelUnavailable",
+ hint: "The hosted planner failed before producing executable intent; no local task was run."
+ )
+ return handlingResult
+ }
+
if Self.shouldAskClarificationBeforeLocalTask(resolution) {
let question = Self.clarificationQuestion(for: resolution)
let decision = AppHarnessDecision(
@@ -849,12 +891,6 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
private static func shouldRespondWithoutLocalTask(_ resolution: LocalAppTaskCatalogResolution) -> Bool {
guard resolution.status == .needsConfirmation else { return false }
- if resolution.intent == nil {
- let reason = resolution.metadata["reason"]
- if reason == "hostedModelIntentUnavailable" {
- return true
- }
- }
if resolution.metadata["responseMode"] == "conversation",
resolution.metadata["assistantResponse"]?.isEmpty == false {
return true
@@ -863,6 +899,16 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
&& resolution.metadata["assistantResponse"]?.isEmpty == false
}
+ private static func shouldFailSafelyWithoutLocalTask(_ resolution: LocalAppTaskCatalogResolution) -> Bool {
+ guard resolution.status == .needsConfirmation,
+ resolution.intent == nil,
+ resolution.metadata["reason"] == "hostedModelIntentUnavailable"
+ else {
+ return false
+ }
+ return resolution.metadata["responseMode"] != "conversation"
+ }
+
private static func shouldAskClarificationBeforeLocalTask(_ resolution: LocalAppTaskCatalogResolution) -> Bool {
guard resolution.status == .needsConfirmation,
shouldRespondWithoutLocalTask(resolution) == false
@@ -907,6 +953,19 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
return "I can help, but I need a clearer request before opening an app."
}
+ private static func modelUnavailableResponse(for resolution: LocalAppTaskCatalogResolution) -> String {
+ let modelStatus = resolution.metadata["modelCallStatus"] ?? ""
+ if modelStatus == AIModelCallStatus.missingCredentials.rawValue {
+ return "The hosted command parser is not configured yet, so I couldn't safely run that action."
+ }
+ if modelStatus == AIModelCallStatus.providerOutage.rawValue
+ || modelStatus == AIModelCallStatus.timeout.rawValue
+ || modelStatus == AIModelCallStatus.rateLimited.rawValue {
+ return "The hosted command parser is not available right now, so I couldn't safely run that action."
+ }
+ return "The hosted command parser failed before it produced a safe action plan, so I didn't run anything."
+ }
+
private func retrieveSemanticMemory(
command: String,
resolution: LocalAppTaskCatalogResolution
diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift
index 8a820999..99989579 100644
--- a/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift
+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyBackendInferenceClient.swift
@@ -204,7 +204,22 @@ public struct DonkeyBackendInferenceClient: @unchecked Sendable {
decoder: decoder
)
case "error":
+ if let result = try? Self.decodeLocalUIUnderstandingResult(
+ from: event.data,
+ decoder: decoder
+ ) {
+ finalResult = result
+ return
+ }
let error = (try? decoder.decode(RemoteScreenshotParseStreamError.self, from: Data(event.data.utf8)))
+ if let recovered = error?.message,
+ let result = try? Self.decodeLocalUIUnderstandingResult(
+ from: recovered,
+ decoder: decoder
+ ) {
+ finalResult = result
+ return
+ }
throw DonkeyBackendInferenceClientError.httpStatus(
response.statusCode,
error?.message ?? event.data
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swift b/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swift
index 4e04efee..84112957 100644
--- a/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swift
+++ b/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swift
@@ -76,29 +76,34 @@ public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {
)
}
- if let intent = try TaskIntentWireCodec.decodeHostedPlanningIntent(
- outputText,
- definitions: request.taskDefinitions,
- originalCommand: request.command,
- appFinderCatalog: request.appFinderCatalog,
- sourceModelCallID: "model-call-\(request.sourceTraceID)",
- parserName: "hosted-responses-v1",
- parserSource: .onlineModel
- ) {
- return TaskIntentAdapterResult(
- intent: intent,
- trace: trace(
- entry: entry,
- request: request,
- status: .completed,
- validationStatus: "schemaDecoded",
- latencyMS: latencyMS,
- metadata: Self.outputDiagnostics(for: outputText).merging([
- "provider": "donkeyBackend",
- "privacy.store": "false"
- ]) { current, _ in current }
+ var decodeFailureMetadata: [String: String] = [:]
+ do {
+ if let intent = try TaskIntentWireCodec.decodeHostedPlanningIntent(
+ outputText,
+ definitions: request.taskDefinitions,
+ originalCommand: request.command,
+ appFinderCatalog: request.appFinderCatalog,
+ sourceModelCallID: "model-call-\(request.sourceTraceID)",
+ parserName: "hosted-responses-v1",
+ parserSource: .onlineModel
+ ) {
+ return TaskIntentAdapterResult(
+ intent: intent,
+ trace: trace(
+ entry: entry,
+ request: request,
+ status: .completed,
+ validationStatus: "schemaDecoded",
+ latencyMS: latencyMS,
+ metadata: Self.outputDiagnostics(for: outputText).merging([
+ "provider": "donkeyBackend",
+ "privacy.store": "false"
+ ]) { current, _ in current }
+ )
)
- )
+ }
+ } catch {
+ decodeFailureMetadata = Self.planningDecodeFailureMetadata(error)
}
let baseMetadata = Self.outputDiagnostics(for: outputText)
@@ -106,6 +111,7 @@ public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {
"provider": "donkeyBackend",
"privacy.store": "false"
]) { current, _ in current }
+ .merging(decodeFailureMetadata) { current, _ in current }
if let noTaskMetadata = try? TaskIntentWireCodec.hostedPlanningNoTaskMetadata(
outputText,
parserName: "hosted-responses-v1"
@@ -130,6 +136,23 @@ public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {
request: request,
previousOutputText: outputText,
previousMetadata: baseMetadata.merging(repairSeed) { current, _ in current },
+ previousFailure: "The previous localAppTask JSON decoded but failed runtime validation, so it cannot be executed.",
+ startedAt: startedAt
+ )
+ }
+
+ if !outputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ return await repairHostedPlanningIntent(
+ entry: entry,
+ backend: backend,
+ request: request,
+ previousOutputText: outputText,
+ previousMetadata: baseMetadata.merging([
+ "reason": "hostedPlanningSchemaDecodeFailed",
+ "validation.failure": "hostedPlanningSchemaDecodeFailed",
+ "planner.repairable": "true"
+ ]) { current, _ in current },
+ previousFailure: "The previous planner output did not decode as the required generic_harness_planning schema, so it cannot be executed.",
startedAt: startedAt
)
}
@@ -158,6 +181,13 @@ public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {
}
}
+ private static func planningDecodeFailureMetadata(_ error: Error) -> [String: String] {
+ [
+ "reason": "hostedPlanningSchemaDecodeFailed",
+ "detail": String(describing: error)
+ ]
+ }
+
private func responseRequest(
entry: AIModelRegistryEntry,
adapterRequest: TaskIntentAdapterRequest,
@@ -240,6 +270,7 @@ public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {
request: TaskIntentAdapterRequest,
previousOutputText: String,
previousMetadata: [String: String],
+ previousFailure: String,
startedAt: TimeInterval
) async -> TaskIntentAdapterResult {
do {
@@ -247,7 +278,10 @@ public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {
responseRequest(
entry: entry,
adapterRequest: request,
- repairContext: HostedPlanningRepairContext(previousOutputText: previousOutputText)
+ repairContext: HostedPlanningRepairContext(
+ previousOutputText: previousOutputText,
+ previousFailure: previousFailure
+ )
)
)
let latencyMS = (ProcessInfo.processInfo.systemUptime - startedAt) * 1_000
@@ -266,30 +300,35 @@ public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {
)
}
- if let intent = try TaskIntentWireCodec.decodeHostedPlanningIntent(
- repairOutputText,
- definitions: request.taskDefinitions,
- originalCommand: request.command,
- appFinderCatalog: request.appFinderCatalog,
- sourceModelCallID: "model-call-\(request.sourceTraceID)-repair",
- parserName: "hosted-responses-v1",
- parserSource: .onlineModel
- ) {
- return TaskIntentAdapterResult(
- intent: intent,
- trace: trace(
- entry: entry,
- request: request,
- status: .completed,
- validationStatus: "schemaDecoded",
- latencyMS: latencyMS,
- metadata: Self.repairMetadata(
- previousMetadata: previousMetadata,
- repairOutputText: repairOutputText,
- status: "schemaDecoded"
+ var repairDecodeFailureMetadata: [String: String] = [:]
+ do {
+ if let intent = try TaskIntentWireCodec.decodeHostedPlanningIntent(
+ repairOutputText,
+ definitions: request.taskDefinitions,
+ originalCommand: request.command,
+ appFinderCatalog: request.appFinderCatalog,
+ sourceModelCallID: "model-call-\(request.sourceTraceID)-repair",
+ parserName: "hosted-responses-v1",
+ parserSource: .onlineModel
+ ) {
+ return TaskIntentAdapterResult(
+ intent: intent,
+ trace: trace(
+ entry: entry,
+ request: request,
+ status: .completed,
+ validationStatus: "schemaDecoded",
+ latencyMS: latencyMS,
+ metadata: Self.repairMetadata(
+ previousMetadata: previousMetadata,
+ repairOutputText: repairOutputText,
+ status: "schemaDecoded"
+ )
)
)
- )
+ }
+ } catch {
+ repairDecodeFailureMetadata = Self.planningDecodeFailureMetadata(error)
}
if let noTaskMetadata = try? TaskIntentWireCodec.hostedPlanningNoTaskMetadata(
@@ -320,7 +359,7 @@ public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {
previousMetadata: previousMetadata,
repairOutputText: repairOutputText,
status: "invalid"
- )
+ ).merging(repairDecodeFailureMetadata) { current, _ in current }
)
} catch is CancellationError {
return result(entry: entry, request: request, status: .cancelled, validationStatus: "notValidated", latencyMS: nil)
@@ -522,9 +561,11 @@ public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {
private struct HostedPlanningRepairContext {
var previousOutputText: String
+ var previousFailure: String
+
var feedback: String {
[
- "The previous localAppTask JSON decoded but failed runtime validation, so it cannot be executed.",
+ previousFailure,
"Return one corrected strict JSON object using the same schema.",
"If no supported executable action is possible, return a conversation or clarification route.",
"Use the relevant app skill and catalog metadata to repair app-specific workflow fields instead of inventing unsupported behavior."
diff --git a/apps/Donkey/Sources/DonkeyAI/TaskIntentWireCodec.swift b/apps/Donkey/Sources/DonkeyAI/TaskIntentWireCodec.swift
index 0528429f..517a88b9 100644
--- a/apps/Donkey/Sources/DonkeyAI/TaskIntentWireCodec.swift
+++ b/apps/Donkey/Sources/DonkeyAI/TaskIntentWireCodec.swift
@@ -172,30 +172,15 @@ enum TaskIntentWireCodec {
"type": "object",
"additionalProperties": false,
"required": [
- "schemaVersion",
- "structuredIntent",
- "ambiguityRisk",
- "contextNeeds",
- "planSteps",
- "verificationCriteria",
- "fallbacks",
- "clarificationPolicy",
- "metadata"
+ "structuredIntent"
],
"properties": [
- "schemaVersion": ["type": "string", "enum": ["generic_harness_planning"]],
"structuredIntent": [
"type": "object",
"additionalProperties": false,
"required": [
"route",
- "goal",
- "taskType",
- "targetAppName",
- "entities",
- "normalizedEntities",
- "confidence",
- "needsConfirmation"
+ "taskType"
],
"properties": [
"route": [
@@ -862,6 +847,37 @@ private struct GenericHarnessPlanningWire: Decodable {
var fallbacks: [String]
var clarificationPolicy: GenericHarnessClarificationPolicyWire
var metadata: [String: String]
+
+ private enum CodingKeys: String, CodingKey {
+ case structuredIntent
+ case ambiguityRisk
+ case contextNeeds
+ case planSteps
+ case verificationCriteria
+ case fallbacks
+ case clarificationPolicy
+ case metadata
+ }
+
+ init(from decoder: Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ self.schemaVersion = "generic_harness_planning"
+ self.structuredIntent = try container.decode(GenericHarnessStructuredIntentWire.self, forKey: .structuredIntent)
+ self.ambiguityRisk = try container.decodeIfPresent(GenericHarnessAmbiguityRiskWire.self, forKey: .ambiguityRisk)
+ ?? GenericHarnessAmbiguityRiskWire(
+ ambiguityClass: "safe",
+ riskLevel: "low",
+ missingInformation: [],
+ shouldAskBeforeActing: false
+ )
+ self.contextNeeds = try container.decodeIfPresent(GenericHarnessStringListWire.self, forKey: .contextNeeds)?.values ?? []
+ self.planSteps = try container.decodeIfPresent([GenericHarnessPlanStepWire].self, forKey: .planSteps) ?? []
+ self.verificationCriteria = try container.decodeIfPresent(GenericHarnessStringListWire.self, forKey: .verificationCriteria)?.values ?? []
+ self.fallbacks = try container.decodeIfPresent(GenericHarnessStringListWire.self, forKey: .fallbacks)?.values ?? []
+ self.clarificationPolicy = try container.decodeIfPresent(GenericHarnessClarificationPolicyWire.self, forKey: .clarificationPolicy)
+ ?? GenericHarnessClarificationPolicyWire(shouldAsk: false, questions: [], policy: "")
+ self.metadata = try container.decodeIfPresent(GenericHarnessStringMapWire.self, forKey: .metadata)?.values ?? [:]
+ }
}
private struct GenericHarnessStructuredIntentWire: Decodable {
@@ -873,6 +889,35 @@ private struct GenericHarnessStructuredIntentWire: Decodable {
var normalizedEntities: [String: String]
var confidence: Double
var needsConfirmation: Bool
+
+ private enum CodingKeys: String, CodingKey {
+ case route
+ case goal
+ case taskType
+ case targetAppName
+ case entities
+ case normalizedEntities
+ case confidence
+ case needsConfirmation
+ }
+
+ init(from decoder: Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ self.route = try container.decode(String.self, forKey: .route)
+ self.taskType = try container.decode(String.self, forKey: .taskType)
+ self.entities = try container.decodeIfPresent(GenericHarnessStringMapWire.self, forKey: .entities)?.values ?? [:]
+ self.normalizedEntities = try container.decodeIfPresent(GenericHarnessStringMapWire.self, forKey: .normalizedEntities)?.values ?? entities
+ self.goal = try container.decodeIfPresent(String.self, forKey: .goal)
+ ?? normalizedEntities["goal"]
+ ?? entities["goal"]
+ ?? ""
+ self.targetAppName = try container.decodeIfPresent(String.self, forKey: .targetAppName)
+ ?? normalizedEntities["appName"]
+ ?? entities["appName"]
+ ?? "none"
+ self.confidence = try container.decodeIfPresent(Double.self, forKey: .confidence) ?? 0.7
+ self.needsConfirmation = try container.decodeIfPresent(Bool.self, forKey: .needsConfirmation) ?? false
+ }
}
private struct GenericHarnessAmbiguityRiskWire: Decodable {
@@ -880,6 +925,33 @@ private struct GenericHarnessAmbiguityRiskWire: Decodable {
var riskLevel: String
var missingInformation: [String]
var shouldAskBeforeActing: Bool
+
+ init(
+ ambiguityClass: String,
+ riskLevel: String,
+ missingInformation: [String],
+ shouldAskBeforeActing: Bool
+ ) {
+ self.ambiguityClass = ambiguityClass
+ self.riskLevel = riskLevel
+ self.missingInformation = missingInformation
+ self.shouldAskBeforeActing = shouldAskBeforeActing
+ }
+
+ private enum CodingKeys: String, CodingKey {
+ case ambiguityClass
+ case riskLevel
+ case missingInformation
+ case shouldAskBeforeActing
+ }
+
+ init(from decoder: Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ self.ambiguityClass = try container.decodeIfPresent(String.self, forKey: .ambiguityClass) ?? "safe"
+ self.riskLevel = try container.decodeIfPresent(String.self, forKey: .riskLevel) ?? "low"
+ self.missingInformation = try container.decodeIfPresent(GenericHarnessStringListWire.self, forKey: .missingInformation)?.values ?? []
+ self.shouldAskBeforeActing = try container.decodeIfPresent(Bool.self, forKey: .shouldAskBeforeActing) ?? false
+ }
}
private struct GenericHarnessPlanStepWire: Decodable {
@@ -905,14 +977,14 @@ private struct GenericHarnessPlanStepWire: Decodable {
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
- self.id = try container.decode(String.self, forKey: .id)
- self.summary = try container.decode(String.self, forKey: .summary)
self.toolName = try container.decode(String.self, forKey: .toolName)
- self.inputEntity = try container.decode(String.self, forKey: .inputEntity)
- self.controlID = try container.decode(String.self, forKey: .controlID)
- self.focusKey = try container.decode(String.self, forKey: .focusKey)
- self.toolInputs = try container.decodeIfPresent([String: String].self, forKey: .toolInputs) ?? [:]
- self.expectedObservation = try container.decode(String.self, forKey: .expectedObservation)
+ self.id = try container.decodeIfPresent(String.self, forKey: .id) ?? toolName
+ self.summary = try container.decodeIfPresent(String.self, forKey: .summary) ?? ""
+ self.inputEntity = try container.decodeIfPresent(String.self, forKey: .inputEntity) ?? ""
+ self.controlID = try container.decodeIfPresent(String.self, forKey: .controlID) ?? ""
+ self.focusKey = try container.decodeIfPresent(String.self, forKey: .focusKey) ?? ""
+ self.toolInputs = try container.decodeIfPresent(GenericHarnessStringMapWire.self, forKey: .toolInputs)?.values ?? [:]
+ self.expectedObservation = try container.decodeIfPresent(String.self, forKey: .expectedObservation) ?? ""
}
}
@@ -920,6 +992,107 @@ private struct GenericHarnessClarificationPolicyWire: Decodable {
var shouldAsk: Bool
var questions: [String]
var policy: String
+
+ init(shouldAsk: Bool, questions: [String], policy: String) {
+ self.shouldAsk = shouldAsk
+ self.questions = questions
+ self.policy = policy
+ }
+
+ private enum CodingKeys: String, CodingKey {
+ case shouldAsk
+ case questions
+ case policy
+ }
+
+ init(from decoder: Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ self.shouldAsk = try container.decodeIfPresent(Bool.self, forKey: .shouldAsk) ?? false
+ self.questions = try container.decodeIfPresent(GenericHarnessStringListWire.self, forKey: .questions)?.values ?? []
+ self.policy = try container.decodeIfPresent(String.self, forKey: .policy) ?? ""
+ }
+}
+
+private struct GenericHarnessStringListWire: Decodable {
+ var values: [String]
+
+ init(from decoder: Decoder) throws {
+ let container = try decoder.singleValueContainer()
+ if let strings = try? container.decode([String].self) {
+ self.values = strings
+ return
+ }
+ if let string = try? container.decode(String.self) {
+ self.values = string.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? [] : [string]
+ return
+ }
+ if let object = try? container.decode(GenericHarnessStringMapWire.self) {
+ self.values = object.values
+ .map { key, value in value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? key : value }
+ .filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
+ .sorted()
+ return
+ }
+ self.values = []
+ }
+}
+
+private struct GenericHarnessStringMapWire: Decodable {
+ var values: [String: String]
+
+ init(from decoder: Decoder) throws {
+ let container = try decoder.container(keyedBy: GenericHarnessDynamicCodingKey.self)
+ var values: [String: String] = [:]
+ for key in container.allKeys {
+ guard let value = try? container.decode(GenericHarnessStringValueWire.self, forKey: key),
+ !value.value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ else {
+ continue
+ }
+ values[key.stringValue] = value.value
+ }
+ self.values = values
+ }
+}
+
+private struct GenericHarnessStringValueWire: Decodable {
+ var value: String
+
+ init(from decoder: Decoder) throws {
+ let container = try decoder.singleValueContainer()
+ if let string = try? container.decode(String.self) {
+ self.value = string
+ } else if let bool = try? container.decode(Bool.self) {
+ self.value = String(bool)
+ } else if let int = try? container.decode(Int.self) {
+ self.value = String(int)
+ } else if let double = try? container.decode(Double.self) {
+ self.value = String(double)
+ } else if let strings = try? container.decode([String].self) {
+ self.value = strings.joined(separator: ", ")
+ } else if let object = try? container.decode([String: String].self) {
+ self.value = object
+ .map { "\($0.key): \($0.value)" }
+ .sorted()
+ .joined(separator: ", ")
+ } else {
+ self.value = ""
+ }
+ }
+}
+
+private struct GenericHarnessDynamicCodingKey: CodingKey {
+ var stringValue: String
+ var intValue: Int?
+
+ init?(stringValue: String) {
+ self.stringValue = stringValue
+ }
+
+ init?(intValue: Int) {
+ self.stringValue = String(intValue)
+ self.intValue = intValue
+ }
}
private struct TaskIntentWire: Decodable {
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
index 9008e5f1..2c649fb8 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
@@ -385,8 +385,16 @@ struct AIHarnessAdapterTests {
let format = try #require(text["format"] as? [String: Any])
#expect(format["name"] as? String == "generic_harness_planning")
let schema = try #require(format["schema"] as? [String: Any])
+ let required = try #require(schema["required"] as? [String])
+ #expect(required.contains("schemaVersion") == false)
let properties = try #require(schema["properties"] as? [String: Any])
+ #expect(properties["schemaVersion"] == nil)
#expect(properties["structuredIntent"] != nil)
+ let structuredIntent = try #require(properties["structuredIntent"] as? [String: Any])
+ let structuredRequired = try #require(structuredIntent["required"] as? [String])
+ #expect(structuredRequired.contains("goal") == false)
+ #expect(structuredRequired.contains("targetAppName") == false)
+ #expect(structuredRequired.contains("confidence") == false)
#expect(properties["ambiguityRisk"] != nil)
#expect(properties["contextNeeds"] != nil)
#expect(properties["planSteps"] != nil)
@@ -465,6 +473,82 @@ struct AIHarnessAdapterTests {
#expect(toolEnums.contains("skill.script.execute"))
}
+ @Test
+ func hostedTaskIntentAdapterDefaultsMissingPlanningSchemaVersion() async {
+ let output = hostedPlanningOutput(
+ goal: "play a selected song in Music",
+ taskType: "local_app_interaction",
+ targetAppName: "Music",
+ entitiesJSON: #"{"appName":"Music","goal":"play media","query":"Yellow Coldplay"}"#,
+ normalizedEntitiesJSON: #"{"appName":"Music","goal":"play media","query":"Yellow Coldplay"}"#,
+ confidence: 0.91,
+ planStepsJSON: #"[{"id":"launch","summary":"Open Music.","toolName":"app.openOrFocus","inputEntity":"","controlID":"","focusKey":"","expectedObservation":"Music is focused."},{"id":"focus-search","summary":"Focus search.","toolName":"ui.focusSearch","inputEntity":"","controlID":"search","focusKey":"Command+F","expectedObservation":"Search is focused."},{"id":"set-text","summary":"Enter query.","toolName":"ui.setText","inputEntity":"query","controlID":"search","focusKey":"","expectedObservation":"Query is entered."},{"id":"submit","summary":"Submit search.","toolName":"ui.pressReturn","inputEntity":"","controlID":"","focusKey":"","expectedObservation":"Search is submitted."}]"#,
+ verificationCriteriaJSON: #"{"success":"Playback command is attempted."}"#,
+ fallbacksJSON: #"["Ask if the song is ambiguous."]"#
+ )
+ .replacingOccurrences(
+ of: #""goal":"play a selected song in Music","#,
+ with: ""
+ )
+ let httpClient = FakeAIHTTPClient(data: responseData(outputText: output), statusCode: 200)
+ let adapter = HostedTaskIntentParsingAdapter(
+ configuration: DonkeyBackendInferenceConfiguration(
+ baseURL: URL(string: "https://donkey.example")!,
+ clientID: "client-1"
+ ),
+ httpClient: httpClient
+ )
+
+ let result = await adapter.parseTaskIntent(
+ TaskIntentAdapterRequest(
+ command: "play some coldplay",
+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,
+ sourceTraceID: "trace-repair-intent"
+ )
+ )
+
+ #expect(result.intent?.taskType == "local_app_interaction")
+ #expect(result.trace.status == .completed)
+ #expect(result.trace.validationStatus == "schemaDecoded")
+ #expect(result.intent?.metadata["genericHarness.schemaVersion"] == "generic_harness_planning")
+ #expect(result.intent?.metadata["genericHarness.intent.goal"] == "play media")
+ #expect(result.intent?.metadata["genericHarness.verificationCriteriaJSON"] == #"["Playback command is attempted."]"#)
+ #expect(result.trace.metadata["reason"] == nil)
+ #expect(result.trace.metadata["planner.repairAttempted"] == nil)
+ #expect(httpClient.requests.count == 1)
+ }
+
+ @Test
+ func hostedTaskIntentAdapterTreatsIrreparablePlanningEnvelopeAsInvalidOutput() async {
+ let httpClient = SequencedFakeAIHTTPClient(responses: [
+ HTTPStub(data: responseData(outputText: "{}"), statusCode: 200),
+ HTTPStub(data: responseData(outputText: "{}"), statusCode: 200)
+ ])
+ let adapter = HostedTaskIntentParsingAdapter(
+ configuration: DonkeyBackendInferenceConfiguration(
+ baseURL: URL(string: "https://donkey.example")!,
+ clientID: "client-1"
+ ),
+ httpClient: httpClient
+ )
+
+ let result = await adapter.parseTaskIntent(
+ TaskIntentAdapterRequest(
+ command: "play some coldplay",
+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,
+ sourceTraceID: "trace-invalid-intent"
+ )
+ )
+
+ #expect(result.intent == nil)
+ #expect(result.trace.status == .invalidOutput)
+ #expect(result.trace.validationStatus == "invalid")
+ #expect(result.trace.metadata["reason"] == "hostedPlanningSchemaDecodeFailed")
+ #expect(result.trace.metadata["planner.repairAttempted"] == "true")
+ #expect(result.trace.metadata["planner.repairStatus"] == "invalid")
+ #expect(httpClient.requests.count == 2)
+ }
+
@Test
func hostedTaskIntentAdapterPreservesNoTaskConversationResponse() async throws {
let httpClient = FakeAIHTTPClient(
@@ -1152,7 +1236,7 @@ struct AIHarnessAdapterTests {
metadataJSON: String = "{}"
) -> String {
"""
- {"schemaVersion":"generic_harness_planning","structuredIntent":{"route":"\(route)","goal":"\(goal)","taskType":"\(taskType)","targetAppName":"\(targetAppName)","entities":\(entitiesJSON),"normalizedEntities":\(normalizedEntitiesJSON),"confidence":\(confidence),"needsConfirmation":\(needsConfirmation)},"ambiguityRisk":{"ambiguityClass":"\(ambiguityClass)","riskLevel":"\(riskLevel)","missingInformation":\(missingInformationJSON),"shouldAskBeforeActing":\(shouldAskBeforeActing)},"contextNeeds":\(contextNeedsJSON),"planSteps":\(planStepsJSON),"verificationCriteria":\(verificationCriteriaJSON),"fallbacks":\(fallbacksJSON),"clarificationPolicy":{"shouldAsk":\(clarificationShouldAsk),"questions":\(clarificationQuestionsJSON),"policy":"\(clarificationPolicy)"},"metadata":\(metadataJSON)}
+ {"structuredIntent":{"route":"\(route)","goal":"\(goal)","taskType":"\(taskType)","targetAppName":"\(targetAppName)","entities":\(entitiesJSON),"normalizedEntities":\(normalizedEntitiesJSON),"confidence":\(confidence),"needsConfirmation":\(needsConfirmation)},"ambiguityRisk":{"ambiguityClass":"\(ambiguityClass)","riskLevel":"\(riskLevel)","missingInformation":\(missingInformationJSON),"shouldAskBeforeActing":\(shouldAskBeforeActing)},"contextNeeds":\(contextNeedsJSON),"planSteps":\(planStepsJSON),"verificationCriteria":\(verificationCriteriaJSON),"fallbacks":\(fallbacksJSON),"clarificationPolicy":{"shouldAsk":\(clarificationShouldAsk),"questions":\(clarificationQuestionsJSON),"policy":"\(clarificationPolicy)"},"metadata":\(metadataJSON)}
"""
}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift
index 55fcd359..315f36c2 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/DonkeyBackendInferenceClientTests.swift
@@ -308,6 +308,72 @@ struct DonkeyBackendInferenceClientTests {
#expect(result.controls.map(\.id) == ["final-result"])
}
+ @Test
+ @MainActor
+ func parseScreenshotStreamRecoversResultFromErrorEventPayload() async throws {
+ let stalePartial = LocalUIUnderstandingResult(
+ controls: [
+ LocalUIUnderstandingControl(
+ id: "stale-close",
+ label: "Close",
+ kind: .button,
+ confidence: 0.5
+ )
+ ],
+ confidence: 0.5,
+ metadata: ["screenshotParser.stream": "partial"]
+ )
+ let final = LocalUIUnderstandingResult(
+ controls: [
+ LocalUIUnderstandingControl(
+ id: "final-close",
+ label: "Close",
+ kind: .button,
+ confidence: 0.9
+ )
+ ],
+ confidence: 0.9,
+ metadata: ["screenshotParser.stream": "final"]
+ )
+ let encoder = JSONEncoder()
+ let concatenatedResults = [
+ String(data: try encoder.encode(stalePartial), encoding: .utf8)!,
+ String(data: try encoder.encode(final), encoding: .utf8)!
+ ].joined(separator: "\n")
+ let errorPayloadData = try JSONSerialization.data(
+ withJSONObject: [
+ "error": "invalid_provider_output",
+ "message": concatenatedResults
+ ]
+ )
+ let errorPayload = try #require(String(data: errorPayloadData, encoding: .utf8))
+ let responseText = [
+ "event: error",
+ "data: \(errorPayload)",
+ "",
+ ].joined(separator: "\n")
+ let httpClient = FixtureHTTPClient(
+ data: Data(responseText.utf8),
+ statusCode: 200,
+ headerFields: ["Content-Type": "text/event-stream"]
+ )
+ let client = DonkeyBackendInferenceClient(
+ configuration: configuration(),
+ httpClient: httpClient
+ )
+
+ let result = try await client.parseScreenshotStream(
+ LocalUIUnderstandingRequest(
+ traceID: "trace-error-recovery",
+ targetID: "target-error-recovery",
+ pixelSize: HotLoopSize(width: 200, height: 100, space: .window)
+ ),
+ imageData: Data("png".utf8)
+ ) { _ in }
+
+ #expect(result.controls.map(\.id) == ["final-close"])
+ }
+
@Test
func screenshotParseOverlayMapperConvertsWindowPixelsToScreenOverlayCoordinates() throws {
let result = LocalUIUnderstandingResult(
diff --git a/docs/guides/backend-apis.md b/docs/guides/backend-apis.md
index f2079476..1a191c75 100644
--- a/docs/guides/backend-apis.md
+++ b/docs/guides/backend-apis.md
@@ -73,8 +73,11 @@ provider names are configuration/data inside private adapters only.
fast structured task-intent and follow-up decisions to `gemini-3.1-flash-lite`,
keep `gemini-3.5-flash` available for general chat and non-decision Responses
calls, and use `gemini-3-flash-preview` for browser Computer Use tool calls.
- Keep model selection in code rather than environment overrides. For Google
- Cloud credits, set
+ Keep model selection in code rather than environment overrides. Structured
+ decision requests normalize JSON schemas for Gemini and retry without
+ provider-enforced schema when Vertex rejects schema parameters; Mac-side
+ runtime validation still owns whether the returned JSON is executable. For
+ Google Cloud credits, set
`GOOGLE_APPLICATION_CREDENTIALS_JSON` as a hosted-deploy sensitive env var
rather than storing Google provider credentials in the Mac app.
- The OpenAI hosted Responses adapter uses `OPENAI_API_KEY` only for macOS
diff --git a/scripts/run-donkey-dev.sh b/scripts/run-donkey-dev.sh
index d3ee5698..0dab04da 100755
--- a/scripts/run-donkey-dev.sh
+++ b/scripts/run-donkey-dev.sh
@@ -139,7 +139,6 @@ PY
if [ -n "$summary" ]; then
echo "Dev overlay config: $summary"
- echo "Dev overlay logs: look for 'debug inspection rendering ... elements=N' below."
else
echo "Dev overlay config: invalid JSON at $overlay_config"
fi
diff --git a/site/src/lib/inference/adapters/gemini-computer-use.ts b/site/src/lib/inference/adapters/gemini-computer-use.ts
index 3136db5c..830f04fe 100644
--- a/site/src/lib/inference/adapters/gemini-computer-use.ts
+++ b/site/src/lib/inference/adapters/gemini-computer-use.ts
@@ -47,6 +47,7 @@ export const geminiBrowserInteractionToolType = "donkey_gemini_browser_interacti
export const debugUIInspectionToolType = "donkey_debug_ui_inspection";
const fastDecisionSchemaNames = new Set([
+ "generic_harness_planning",
"task_intent_v1",
"task_followup_resolution_v1",
]);
@@ -111,10 +112,22 @@ export function createGeminiComputerUseProvider(
const client = clientFactory(clientConfig.options);
let rawResponse: unknown;
+ let retriedWithoutSchema = false;
try {
rawResponse = await client.models.generateContent(requestParameters);
} catch (error) {
- throw geminiProviderError(error);
+ if (shouldRetryWithoutStructuredSchema(error, requestParameters)) {
+ retriedWithoutSchema = true;
+ try {
+ rawResponse = await client.models.generateContent(
+ withoutStructuredResponseSchema(requestParameters),
+ );
+ } catch (retryError) {
+ throw geminiProviderError(retryError);
+ }
+ } else {
+ throw geminiProviderError(error);
+ }
}
const rawBody = toJsonValue(rawResponse);
@@ -129,6 +142,7 @@ export function createGeminiComputerUseProvider(
api: "google-genai-sdk",
service: clientConfig.service,
registeredTools,
+ structuredSchemaRetry: String(retriedWithoutSchema),
},
};
}
@@ -405,13 +419,108 @@ function generationConfigFromBody(body: JsonObject): Partial<GenerateContentConf
if (responseFormat?.json) {
config.responseMimeType = "application/json";
if (responseFormat.schema) {
- config.responseJsonSchema = responseFormat.schema;
+ config.responseJsonSchema = geminiJsonSchema(responseFormat.schema);
}
}
return config;
}
+const supportedGeminiJsonSchemaKeys = new Set([
+ "$anchor",
+ "$defs",
+ "$id",
+ "$ref",
+ "additionalProperties",
+ "anyOf",
+ "description",
+ "enum",
+ "format",
+ "items",
+ "maxItems",
+ "maximum",
+ "minItems",
+ "minimum",
+ "oneOf",
+ "prefixItems",
+ "properties",
+ "propertyOrdering",
+ "required",
+ "title",
+ "type",
+]);
+
+function geminiJsonSchema(schema: JsonObject): JsonObject {
+ const sanitized = sanitizeGeminiJsonSchema(schema);
+ return sanitized !== undefined && isJsonObject(sanitized) ? sanitized : schema;
+}
+
+function sanitizeGeminiJsonSchema(value: JsonValue): JsonValue | undefined {
+ if (Array.isArray(value)) {
+ return value
+ .map(sanitizeGeminiJsonSchema)
+ .filter((item): item is JsonValue => item !== undefined);
+ }
+
+ if (!isJsonObject(value)) {
+ return value;
+ }
+
+ const sanitized: JsonObject = {};
+ for (const [key, child] of Object.entries(value)) {
+ if (!supportedGeminiJsonSchemaKeys.has(key)) {
+ continue;
+ }
+
+ const childValue = sanitizeGeminiJsonSchema(child);
+ if (childValue !== undefined) {
+ sanitized[key] = childValue;
+ }
+ }
+
+ if (
+ sanitized.type === "object" &&
+ isJsonObject(sanitized.properties) &&
+ !Array.isArray(sanitized.propertyOrdering)
+ ) {
+ sanitized.propertyOrdering = Object.keys(sanitized.properties);
+ }
+
+ return sanitized;
+}
+
+function shouldRetryWithoutStructuredSchema(
+ error: unknown,
+ request: GenerateContentParameters,
+) {
+ return (
+ hasStructuredResponseSchema(request) &&
+ error instanceof ApiError &&
+ error.status === 400
+ );
+}
+
+function hasStructuredResponseSchema(request: GenerateContentParameters) {
+ const config = request.config;
+ return Boolean(
+ config &&
+ ("responseJsonSchema" in config || "responseSchema" in config),
+ );
+}
+
+function withoutStructuredResponseSchema(
+ request: GenerateContentParameters,
+): GenerateContentParameters {
+ const restConfig = { ...(request.config ?? {}) };
+ delete restConfig.responseJsonSchema;
+ delete restConfig.responseSchema;
+
+ return {
+ ...request,
+ config: restConfig,
+ };
+}
+
function responseFormatFromBody(body: JsonObject): { json: boolean; schema?: JsonObject } | null {
const format =
isJsonObject(body.text) && isJsonObject(body.text.format)
diff --git a/site/src/lib/inference/screenshot-parsing/gemini-flash.ts b/site/src/lib/inference/screenshot-parsing/gemini-flash.ts
index 537cf433..b2f7c011 100644
--- a/site/src/lib/inference/screenshot-parsing/gemini-flash.ts
+++ b/site/src/lib/inference/screenshot-parsing/gemini-flash.ts
@@ -345,10 +345,18 @@ function parseGeminiOutput(rawBody: JsonValue) {
}
function parseGeminiOutputText(text: string) {
+ const candidates = jsonObjectCandidates(text).reverse();
let parsed: unknown;
- try {
- parsed = JSON.parse(text);
- } catch {
+ for (const candidate of candidates) {
+ try {
+ parsed = JSON.parse(candidate);
+ break;
+ } catch {
+ continue;
+ }
+ }
+
+ if (parsed === undefined) {
throw new InferenceProviderError("Gemini returned invalid screenshot parser JSON.", {
statusCode: 502,
code: "invalid_provider_output",
@@ -372,6 +380,47 @@ function parseGeminiOutputText(text: string) {
return output.data;
}
+function jsonObjectCandidates(text: string) {
+ const trimmed = text.trim();
+ const candidates = trimmed ? [trimmed] : [];
+ let objectStart = -1;
+ let depth = 0;
+ let inString = false;
+ let escaped = false;
+
+ for (let index = 0; index < text.length; index += 1) {
+ const character = text[index];
+
+ if (inString) {
+ if (escaped) {
+ escaped = false;
+ } else if (character === "\\") {
+ escaped = true;
+ } else if (character === "\"") {
+ inString = false;
+ }
+ continue;
+ }
+
+ if (character === "\"") {
+ inString = true;
+ } else if (character === "{") {
+ if (depth === 0) {
+ objectStart = index;
+ }
+ depth += 1;
+ } else if (character === "}" && depth > 0) {
+ depth -= 1;
+ if (depth === 0 && objectStart >= 0) {
+ candidates.push(text.slice(objectStart, index + 1));
+ objectStart = -1;
+ }
+ }
+ }
+
+ return Array.from(new Set(candidates));
+}
+
async function streamGeminiContent(
client: GeminiClient,
request: ScreenshotParseRequest,