From 3eeb3c178ea8e2e3543bf437ffbc9f7331a7133c Mon Sep 17 00:00:00 2001 From: James Maes Date: Thu, 7 May 2026 07:37:01 -0500 Subject: [PATCH] feat(10-02b): add availableToolsResolver for late-bound tool catalogs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plan 10-02b / B-01: AgentOrchestrator gains an optional `availableToolsResolver: (@Sendable () async -> [ToolSchema])?` init parameter that, when set, supersedes the static `availableTools:` array on every outer-loop iteration of runTurnLoop. The static array continues to work for tests (and is the default), but production wires the resolver so the in-process registry's late-bound self-knowledge tools (registered AFTER installAgent runs the orchestrator constructor) reach the request body's tools[] payload. Without this, the install-order dependency chain installMemory → installVision → installAgent → installVoice → installSelfKnowledgeTools would force the orchestrator to capture an empty snapshot of the in-process registry at construction time. By the time the user submits their first turn, the four self-knowledge tools have registered — but the orchestrator's frozen array would not see them. The resolver is invoked once per outer turn iteration (not per stream event), so the cost is one actor hop per LLM round-trip — negligible. Test coverage: - test_availableToolsResolver_supersedesStaticArrayPerTurn: seeds the resolver with empty on turn 1, populates 4 tools before turn 2, and asserts the provider sees the correct snapshot for each turn. - All 222 AgentCore tests pass unchanged. Co-Authored-By: Claude Opus 4.7 --- .../AgentOrchestrator/AgentOrchestrator.swift | 23 +++++- .../AvailableToolsWiringTests.swift | 79 +++++++++++++++++++ 2 files changed, 101 insertions(+), 1 deletion(-) 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