diff --git a/packages/AgentCore/Sources/AgentOrchestrator/AgentOrchestrator.swift b/packages/AgentCore/Sources/AgentOrchestrator/AgentOrchestrator.swift index 0e2e53b..97e8b19 100644 --- a/packages/AgentCore/Sources/AgentOrchestrator/AgentOrchestrator.swift +++ b/packages/AgentCore/Sources/AgentOrchestrator/AgentOrchestrator.swift @@ -37,6 +37,14 @@ public actor AgentOrchestrator { private let sessionId: SessionID private let systemPrompt: String private let availableToolsList: [ToolSchema] + /// Plan 10-02b / B-01: optional lazy resolver for the tool catalog. + /// When non-nil, takes precedence over `availableToolsList` and is + /// invoked once per outer turn iteration so registration timing on + /// the in-process side (e.g. self-knowledge tools register AFTER + /// installAgent runs) doesn't strand the orchestrator with a stale + /// snapshot. Tests continue to pass an immutable array via + /// `availableTools:`; production wires the resolver. + private let availableToolsResolver: (@Sendable () async -> [ToolSchema])? /// Plan 09-02 / D-01 — image-bearing turns are dispatched through the /// VisionRouter BEFORE the streaming loop. Defaulted-nil so existing test /// sites (and the Plan 1 installAgent wiring before Plan 2 lands) compile @@ -97,6 +105,7 @@ public actor AgentOrchestrator { sessionId: SessionID, systemPrompt: String, availableTools: [ToolSchema] = [], + availableToolsResolver: (@Sendable () async -> [ToolSchema])? = nil, visionRouter: VisionRouter? = nil, presenceSnapshot: PresenceStateSnapshot? = nil ) { @@ -107,6 +116,7 @@ public actor AgentOrchestrator { self.sessionId = sessionId self.systemPrompt = systemPrompt self.availableToolsList = availableTools + self.availableToolsResolver = availableToolsResolver self.visionRouter = visionRouter self.presenceSnapshot = presenceSnapshot self.logger = Logger(label: JarvisLogChannel.agent.rawValue) @@ -348,7 +358,18 @@ public actor AgentOrchestrator { // Compute tool_choice based on remaining budget. // AGENT-07: budget exhausted → toolChoice .none → cap-recovery. let toolChoice: ToolChoice = toolCallBudget > 0 ? .auto : .none - let toolsForCall: [ToolSchema] = toolCallBudget > 0 ? availableToolsList : [] + // Plan 10-02b / B-01: prefer the lazy resolver so production + // can refresh the catalog as in-process tools register after + // installAgent runs. Tests pass an immutable array via + // `availableTools:` and leave `availableToolsResolver: nil`, + // so behavior there is unchanged. + let resolvedCatalog: [ToolSchema] + if let resolver = availableToolsResolver { + resolvedCatalog = await resolver() + } else { + resolvedCatalog = availableToolsList + } + let toolsForCall: [ToolSchema] = toolCallBudget > 0 ? resolvedCatalog : [] // D-01: image-bearing turns use the multimodal stream overload so // the provider can encode the image bytes per its API diff --git a/packages/AgentCore/Tests/AgentOrchestratorTests/AvailableToolsWiringTests.swift b/packages/AgentCore/Tests/AgentOrchestratorTests/AvailableToolsWiringTests.swift index 6d99d25..ec1eb66 100644 --- a/packages/AgentCore/Tests/AgentOrchestratorTests/AvailableToolsWiringTests.swift +++ b/packages/AgentCore/Tests/AgentOrchestratorTests/AvailableToolsWiringTests.swift @@ -99,6 +99,85 @@ final class AvailableToolsWiringTests: XCTestCase { "B-01: tool names reaching the provider differ from the input catalog") } + /// B-01-RESOLVER: production wires `availableToolsResolver:` so the + /// in-process registry's late-bound self-knowledge tools (registered + /// AFTER installAgent runs) reach the orchestrator's per-turn + /// catalog. Asserts the resolver fires per turn and supersedes the + /// static `availableTools:` array when set. + func test_availableToolsResolver_supersedesStaticArrayPerTurn() async throws { + // Snapshot 1: empty (mirrors what installAgent saw at construction + // time before installSelfKnowledgeTools ran). + // Snapshot 2: 4 tools (mirrors what installSelfKnowledgeTools + // populated by the time the user's first turn fires). + let snapshot2: [ToolSchema] = [ + ToolSchema(name: "list_audio_devices", + description: "list", + inputSchema: Data(#"{"type":"object"}"#.utf8)), + ToolSchema(name: "get_active_audio_route", + description: "route", + inputSchema: Data(#"{"type":"object"}"#.utf8)), + ToolSchema(name: "get_self_state", + description: "self", + inputSchema: Data(#"{"type":"object"}"#.utf8)), + ToolSchema(name: "list_camera_devices", + description: "cameras", + inputSchema: Data(#"{"type":"object"}"#.utf8)), + ] + // The actor below holds the mutable snapshot so the @Sendable + // resolver closure stays Swift-6 strict-concurrency clean. + actor CatalogHolder { + var snapshot: [ToolSchema] = [] + func set(_ s: [ToolSchema]) { snapshot = s } + func get() -> [ToolSchema] { snapshot } + } + let holder = CatalogHolder() + let resolver: @Sendable () async -> [ToolSchema] = { await holder.get() } + + let mock = MockLLMProvider(script: .init(events: [ + .messageStart(LLMMessageStart(messageId: "m", model: "claude-opus-4-7", usagePrefix: nil)), + .stopReason(.endTurn), + .messageStop, + ])) + let replay = try ReplayLog(databaseURL: tempHome.dbURL) + let session = try await replay.beginSession(appVersion: "test", buildSHA: "deadbeef") + + let orch = AgentOrchestrator( + configStore: makeConfigStore(), + providerFactory: { _ in mock }, + toolDispatcher: StubToolDispatcher(), + replayLog: replay, + sessionId: session, + systemPrompt: "you are jarvis", + availableTools: [], // Static is empty (the bug condition). + availableToolsResolver: resolver // Resolver supersedes per turn. + ) + + // Turn 1: resolver returns empty (snapshot 1). + _ = await orch.submit(.text("turn one")) + for await event in orch.events { + if case .stateChange(.idle) = event { break } + } + + // Promote the holder before turn 2 so the resolver returns the + // populated catalog the second time around. + await holder.set(snapshot2) + + _ = await orch.submit(.text("turn two")) + for await event in orch.events { + if case .stateChange(.idle) = event { break } + } + + let recorded = await mock.getRecordedCalls() + XCTAssertGreaterThanOrEqual(recorded.count, 2, "expected at least 2 provider calls") + XCTAssertTrue(recorded[0].tools.isEmpty, + "turn 1: resolver returned empty snapshot — provider tools[] should be empty") + XCTAssertEqual(recorded[1].tools.count, 4, + "turn 2: resolver returned 4-tool snapshot — provider should see all 4 (orchestrator must NOT cache the resolver result)") + XCTAssertEqual(Set(recorded[1].tools.map(\.name)), + Set(snapshot2.map(\.name)), + "turn 2: tool names should match the resolver's late snapshot") + } + /// B-01-NEGATIVE: explicitly verifies that a default-init (omitting /// `availableTools:`) yields an empty `tools:` array at the provider. /// This pins down the precondition that the BUG was about hardcoding