ide на основе vs code
Это ide на основе vs code(code oss), в ней будет встроенный умный апи роутинг, свой маркет с плагинами(агент харнесс, поддержка java/kotlin/мобильной разработки, командная разработка проектов, orca, оркестратор агентов
Это ide на основе vs code(code oss), в ней будет встроенный умный апи роутинг, свой маркет с плагинами(агент харнесс, поддержка java/kotlin/мобильной разработки, командная разработка проектов, orca, оркестратор агентов
> Generated by super-planner. Source: roadmap.md (Phase 12). > Last updated: 2026-05-14 after live-SDK probing + 4-model council review (GPT-5.5, Claude Opus 4.6, GPT-5.3-Codex, plus original 3-model on 2026-05-13).
Status: ✅ DONE (production landed + E2E validated 2026-05-15)
Make Claude subagents (sessions spawned by the SDK's Task/Agent tool) first-class for clients. The host detects subagent starts in the live SDK stream, routes inner messages to a child session URI, completes that child session, and serves transcripts on demand for both live and restored sessions — closing the Phase 13 deferral noted at `claudeAgent.ts:610`.
In scope
isSubagentSession(uri); consumers (ClaudeAgent.getSessionMessages) become one-liners. Hides every URI-shape branch from the rest of the codebase. See CONTEXT.md M7 §"Subagent correlation".getTranscript. Owns all subagentURI → Turn[] complexity. Two opportunistic feeders (noteLiveAgentId, notePrimingFromParent) populate an in-memory cache; chain falls through to four named strategies on miss.parent_tool_use_id on an inner message, sourcing agentName / agentDisplayName / agentDescription from the originating Task/Agent tool_use block.parent_tool_use_id is non-null carries parentToolCallId so `AgentSideEffects` routes it to the subagent session.CanUseTool.agentIDOut of scope
claude.subagents overlay row, no DB extension. The relationship is fully inferable from live SDK signals + on-demand scan; persistence would buy nothing on a cold path. See Q4.subagents/ subdirectory and SessionKey.subpath distinguishes them; listSessions already returns only top-level entries. See Q9.<root>/subagents/agent-<id>.jsonl — nested subagents recursively flatten under the same root. Phase 12 ships single-level navigation; nested replay is a follow-up if/when it surfaces.subagent_started from the live mapper; replay-only navigation works without it._loadParentTranscript into its own resolver without touching consumers.Options.ClaudeMapperState.Map<tool_use_id, turnId> invariant CONTEXT M7 references)._meta.toolKind = 'subagent').listSubagents, getSubagentMessages, SDKAssistantMessage.parent_tool_use_id, SDKTaskNotificationMessage are all confirmed present in the bundled node_modules/@anthropic-ai/claude-agent-sdk/sdk.d.ts.The host already has all of the *server-side* subagent plumbing — `AgentSideEffects` creates child sessions silently on subagent_started, buffers signals that arrive before their subagent_started (`agentSideEffects.ts:95-105, 308-317`), and tears down on subagent_completed. Phase 12 is the Claude-side emitter for those signals plus the Claude-side transcript fetch for subagent URIs.
Documented in full at CONTEXT.md M7 §"Subagent correlation: SDK gaps and resolution strategy". Headline facts that drive this plan:
1. `SessionMessage.parent_tool_use_id` is always `null`. Empirically verified: zero non-null occurrences across 2,525 files / 110k+ envelopes / live getSubagentMessages calls. The field is typed as the literal null (not string | null). Reading it on the replay path produces silently-wrong correlations. The corresponding live-stream field on SDKAssistantMessage IS populated — that's the live mapper's join, not a replay primitive. 2. `agentId` and `toolUseResult.agentId` are stripped by SDK normalization. The on-disk JSONL has both, but getSubagentMessages and getSessionMessages return only [type, uuid, session_id, message, parent_tool_use_id, timestamp] — agentId is gone. 3. The SDK does inject a synthetic `agentId: <id>` text block as the LAST entry of every Agent `tool_result.content[]`. Reliable when present; format may vary by SDK version. This is the cleanest cold-path primitive. 4. `Agent.tool_use.input.prompt` ≡ subagent's first user message body — byte-for-byte identical in every sampled case. Slower but bulletproof fallback. 5. `listSubagents` returns alphabetically (`readdir`) order, NOT invocation order. Tested across 27 sessions: 1/27 happened to match invocation order; 23 had count mismatches because the directory accumulates orphans (nested subagents, sidechain branches, compacted history). Cannot be used as a positional join. 6. `CanUseTool` callback exposes `agentID` for inner subagent tools. Free live correlation source. 7. Compacted/forked sessions have a synthetic first SDK entry; the SDK's chain-walking excludes pre-compaction Agent calls. Not a Phase 12 concern (those subagents are unreachable by design), but documented so future readers don't try to "fix" it.
There is no first-class SDK API today that maps (parentSessionId, toolCallId) → agentId. The resolver layer carries multiple imperfect strategies behind one stable interface; when the SDK ships native correlation, one strategy slots in and the others delete.
ClaudeAgent.getSessionMessages(uri)
│
▼
IClaudeTranscriptService.getTranscript(uri)
│
├── isSubagentSession(uri)? ──► IClaudeSubagentResolver.getTranscript(uri)
│ │
│ ├── 0. In-memory cache hit
│ │ (populated by noteLiveAgentId
│ │ and notePrimingFromParent)
│ │
│ │ ┌─ on miss: chain ─┐
│ ├──────│ 1. TextSuffixStrategy (parse agentId text block in tool_result)
│ │ │ 2. PromptMatchStrategy (compare parent prompt body to subagent first user message)
│ │ │ 3. NativeStrategy (when SDK ships it — placeholder)
│ │ └──────────────────┘
│
└── else ──► _loadParentTranscript(uri)
│
├── _sdkService.getSessionMessages(...)
├── mapSessionMessagesToTurns(...) ← Phase 13
└── _subagentResolver.notePrimingFromParent(uri, transcript)
← cache primingSubagent path: complex inside, simple outside. Parent path: simple inside, simple outside. Both: same ingress.
| # | Strategy | When it hits | Cost | Reliability | |---|---|---|---|---| | — | In-memory cache | After first lookup OR after parent transcript load OR after canUseTool sees agentID | O(1) | 100% when populated | | 1 | TextSuffixStrategy | Cold path; parse the synthetic agentId: <id> block from the parent's Agent.tool_result.content[] last entry | One regex per tool_result; reuses already-loaded parent transcript when called via notePrimingFromParent | High when present; missing in some sessions / SDK versions | | 2 | PromptMatchStrategy | Cold path fallback when TextSuffix misses | listSubagents + N × getSubagentMessages(limit:1), compare first user message text vs parent's Agent.tool_use.input.prompt | Bulletproof when prompts are non-empty; slow | | 3 | NativeStrategy | TODO: when SDK ships first-class lookup | O(1) | TBD |
LiveCaptureStrategy is *not* in the chain — it's a write path (noteLiveAgentId) that feeds the in-memory cache. Conceptually it's "strategy 0" but architecturally it's a feeder, not a chain participant.
The workbench can only navigate to a subagent URI after loading the parent transcript (the marker is constructed from parent data). The transcript service exploits this dependency: after _loadParentTranscript succeeds, it calls resolver.notePrimingFromParent(parentURI, transcript). The resolver runs TextSuffixStrategy over the entire transcript and bulk-populates the cache. By the time the user clicks a subagent marker, the lookup is O(1).
This means PromptMatchStrategy's slow N-fetch path only fires when:
Both are uncommon. The common case is a hot cache.
1. ✅ Enable `forwardSubagentText: true`. Add to the Options bag assembled in `claudeMaterializer.ts` (alongside the existing includePartialMessages: true). Without this the live stream omits subagent text/thinking blocks (`sdk.d.ts:1376-1379`) and the child session ends up tool-only, while replay via getSubagentMessages returns the full transcript — a live-vs-replay asymmetry that would surface as a UX bug.
Options carries the field; manual smoke confirms inner text appears.2. ✅ Add SDK bindings. Extend `IClaudeAgentSdkService` and IClaudeSdkBindings with listSubagents(sessionId, options?): Promise<readonly string[]> and getSubagentMessages(sessionId, agentId, options?): Promise<readonly SessionMessage[]> (both mirror the existing getSessionMessages shape).
_loadSdk forwards both calls; new test stubs exercise faulted + happy paths via the existing _loadSdk override.3. ✅ Extend `ClaudeMapperState` with subagent bookkeeping. Add four private maps + two sets, public accessors, and explicit drain semantics:
_subagentSpawningTools: Map<tool_use_id, { agentName: string; displayName: string; description?: string }> — populated in startToolBlock when toolName ∈ {'Task','Agent'}. agentName / description come from the tool_use.input (subagent_type field for Task, declaration name for Agent — fall back to toolName if missing); displayName from `getClaudeToolDisplayName`._announcedSubagents: Set<parent_tool_use_id> — guards subagent_started so it fires exactly once per subagent regardless of how many inner messages arrive._innerToolToParent: Map<inner_tool_use_id, parent_tool_use_id> — populated when the live mapper sees an inner tool_use (the message itself has envelope parent_tool_use_id !== null). Step 5's canUseTool agentID-bridge consumes this via a public accessor getParentToolCallId(innerToolUseId: string): string | undefined (necessary because claudeCanUseTool.ts lives outside the mapper and cannot read private fields). The accessor mirrors the existing public lookupToolCall on ClaudeMapperState.SDKTaskStartedMessage4. ✅ Define `IClaudeSubagentResolver` + strategy classes. New file `claudeSubagentResolver.ts`:
IClaudeSubagentResolver interface with three methods: getTranscript(subagentURI, token): Promise<readonly Turn[]>, noteLiveAgentId(parentURI, toolCallId, agentId): void, notePrimingFromParent(parentURI, transcript): void.ISubagentLookupStrategy interface with name: string (for telemetry) and lookup(parent, toolCallId, ctx): Promise<string | undefined>.TextSuffixStrategy — given a parent transcript (or fetches one if not supplied via ctx), scans every Agent tool_result.content[] for the synthetic last-text-block matching a tolerant regex /^\s*agentId:\s+([a-z0-9]+)\b/im (case-insensitive, lenient whitespace, anchored only by line start — robust to minor format drift between SDK versions). Returns the matching agentId. The same scan, when called from notePrimingFromParent, populates *every* (toolCallId, agentId) pair it finds in one pass.PromptMatchStrategy — calls listSubagents for the parent, then for each agentId calls getSubagentMessages(limit:1) and compares the first user message text against the parent's Agent.tool_use.input.prompt. Match → that agentId is the answer. Validate inputs with locally-defined vObj5. ✅ Bridge `CanUseTool.agentID` → `pending_confirmation.parentToolCallId` + feed resolver cache. Three plumbing changes are required because the existing seam is too narrow:
getMapperState: () => ClaudeMapperState | undefined and subagentResolver: IClaudeSubagentResolver. Wire both at the call site in `claudeAgent.ts:469`.agentID?: string. Accept it in handleCanUseTool and forward into the request.parentToolCallId?: string. The signal type `IAgentToolPendingConfirmationSignal` already supports the field; the session just needs to thread it through.With those in place, the bridge logic:
options.agentID is set: parentToolCallId = mapperState?.getParentToolCallId(options.toolUseID) (the new public accessor from step 3).pending_confirmation signal with parentToolCallId set so `AgentSideEffects` routes it to the subagent session.subagentResolver.noteLiveAgentId(parentURI, parentToolCallId, options.agentID) to feed the cache for free.requestUserInput (interactive tools inside a subagent — AskUserQuestion)._innerToolToParent that the new accessor reads).pending_confirmation for an inner subagent tool carries parentToolCallId; integration test confirms the resolver cache is populated; a downstream getTranscript(subagentURI) returns the right transcript without falling through the strategy chain.6. ✅ Emit `subagent_started` and tag inner mapper signals. Update `mapSDKMessageToAgentSignals`:
SDKMessage, read the live parent_tool_use_id from the envelope (declared on SDKAssistantMessage / SDKUserMessage / SDKPartialAssistantMessage per `sdk.d.ts:2345, 3050`). NOTE: this is the live envelope, NOT SessionMessage — the latter's parent_tool_use_id is always null per the empirical findings above._announcedSubagents does not contain it: look up the spawning tool in _subagentSpawningTools. On hit, prepend an IAgentSubagentStartedSignal to this message's signal batch and mark announced. On miss (transcript truncation, mid-resume), fall back to agentName: 'subagent', displayName: 'Subagent', description: undefined. The host's `AgentSideEffects._handleSubagentStarted` tolerates these.parent_tool_use_id: set parentToolCallId = parent_tool_use_id. Also call state._innerToolToParent.set(toolUseId, parent_tool_use_id) for any inner tool_use block so step 5's canUseTool bridge can find the parent.AgentSideEffects already buffers 7. ✅ Emit `subagent_completed`. The protocol explicitly distinguishes foreground from background subagents because parent-tool completion is unreliable for the latter (`agentSideEffects.ts:576-581`). Critical ordering reality (council 2026-05-14): for background subagents, tool_result always arrives FIRST (the parent doesn't wait); SDKTaskNotificationMessage arrives later when the background work actually finishes. The discriminator is _backgroundTasks (populated from SDKTaskStartedMessage, step 3), NOT arrival order.
Three trigger sites:
message.type === 'system' && message.subtype === 'task_started'. If message.tool_use_id is in _subagentSpawningTools, add it to _backgroundTasks. This must arrive BEFORE the parent tool_result for the foreground/background discriminator to work (the SDK emits task_started before yielding the parent's tool_result for background mode).mapUserMessage, when a tool_result lands for a tool_use_id in _subagentSpawningTools:tool_use_id is in _backgroundTasks: skip (background completion will arrive later via task_notification).tool_use_id is not in _completedSubagents: append IAgentSubagentCompletedSignal after the existing SessionToolCallComplete action, add to _completedSubagents, and remove from `_subagentSpawningTools` (happy-path cleanup so the orphan drain doesn't warn on it).This ordering is the only correct interpretation:
_backgroundTasks → tool_result fires completion. ✅_backgroundTasks → tool_result is skipped, later task_notification fires completion. ✅task_notification.tool_use_id is absent (per `sdk.d.ts:3399`): no completion fires. Orphan drain in clearPendingToolCalls does NOT touch entries in _backgroundTasks, so the entry survives across turns. Acceptable: the child session stays alive until the agent host shuts down. Rare edge case; document as known limitation.task_started then tool_result does NOT fire completion, (c) background task_started then tool_result then task_notification fires completion exactly once, (d) task_notification without prior task_started (defensive) treats as foreground, (e) orphan drain leaves _backgroundTasks entries alone.8. ✅ Implement `IClaudeTranscriptService` + wire `ClaudeAgent.getSessionMessages` to it. New file `claudeTranscriptService.ts`:
getTranscript(uri, token): Promise<readonly Turn[]>.isSubagentSession(uri) → delegate to IClaudeSubagentResolver. Else → _loadParentTranscript(uri, token)._loadParentTranscript: 1. Walk parseSubagentSessionUri iteratively if a subagent URI was somehow passed (defensive). 2. parentSessionId = AgentSession.id(uri); provisional check returns []. 3. cwd = (await _sdkService.getSessionInfo(parentSessionId))?.cwd. 4. transcript = await _sdkService.getSessionMessages(parentSessionId, { dir: cwd, includeSystemMessages: true }). 5. turns = mapSessionMessagesToTurns(transcript, uri, _logService). 6. Priming side effect, wrapped in its own try/catch so a TextSuffixStrategy bug or validator error during priming cannot break otherwise-successful parent transcript reads: ``typescript try { this._subagentResolver.notePrimingFromParent(uri, transcript); } catch (err) { this._logService.warn('[Claude] notePrimingFromParent failed', err); } ` 7. Return turns`.
[] (mirror `claudeAgent.ts:619-622`). Priming has its own try/catch (above) and never propagates errors.getSessionMessages body with a one-liner: return this._transcriptService.getTranscript(session, CancellationToken.None);.claudeAgent.ts into _loadParentTranscript. Old code path goes away entirely.claudeTranscriptService.ts, claudeAgent.ts.getTranscript(parentURI) (existing parent path), getTranscript(subagentURI) (new resolver path), nested URI walks, all SDK errors → [], verifies notePrimingFromParent is invoked with the loaded transcript, AND verifies a deliberately-faulted priming does NOT propagate.9. ✅ Subagent session cleanup on parent dispose. `AgentSideEffects.removeSubagentSessions` already exists; verify disposeSession calls it for Claude parents the same way Copilot does. Also drop the parent's entry from the resolver's cache (_subagentResolver.disposeParent(parentURI) — small new method, just deletes the cache entry). Pure plumbing check; minimal new code.
disposeSession(parent) clears both the resolver's cache entry and any _subagentSessions entries.| Path | Change | Notes | |------|--------|-------| | claudeMaterializer.ts | modify | Add forwardSubagentText: true to the SDK Options bag. | | claudeAgentSdkService.ts | modify | Add listSubagents + getSubagentMessages to IClaudeAgentSdkService and IClaudeSdkBindings. | | claudeMapSessionEvents.ts | modify | ClaudeMapperState gains 3 maps + 1 set; mapper emits subagent_started, tags inner signals with parentToolCallId, populates _innerToolToParent, emits subagent_completed with mutual exclusion; orphan drain extended in clearPendingToolCalls. | | claudeSubagentResolver.ts | create | IClaudeSubagentResolver + ISubagentLookupStrategy + TextSuffixStrategy + PromptMatchStrategy + NativeStrategy placeholder + ChainedSubagentResolver + in-memory cache + telemetry counter. | | claudeTranscriptService.ts | create | IClaudeTranscriptService.getTranscript(uri) single ingress; branches on isSubagentSession; calls resolver for subagents,
Note: no changes to `claudeSessionMetadataStore.ts`. Persistence dropped per Q4.
'Task' and 'Agent'. Confirmed by `sdk.d.ts:36, 95` and matched by Phase 13's `SUBAGENT_TOOL_NAMES`. Reuse the same constant in the live mapper and in TextSuffixStrategy.parent_tool_use_id on SDKAssistantMessage / SDKUserMessage / SDKPartialAssistantMessage. NOT from SessionMessage (the replay envelope's field is always null per Q11), NOT from a separate SDK event. Production reference at `claudeMessageDispatch.ts:232` uses the same trigger._backgroundTasks (populated from SDKTaskStartedMessage), NOT by arrival order. For background subagents, tool_result always arrives FIRST (immediately, parent doesn't wait) and task_notification arrives LATER when the background work finishes. The plan's original "whichever fires first" mutual-exclusion was empirically wrong — see council 2026-05-14 finding #1. Foreground branch checks _backgroundTasks and skips if present; background branch fires on task_notification terminal status. _completedSubagents still guards against double-fire defensively. The roadmap is explicit that "background subagents continue running after the parent tool call returns" ( 1. In-memory cache hit — populated by noteLiveAgentId (canUseTool feeder) and notePrimingFromParent (TextSuffix bulk-scan after every parent load). 2. `TextSuffixStrategy` — parses the synthetic agentId: <id> block the SDK injects into every Agent tool_result.content[]. Reliable when present; format may shift between SDK versions. 3. `PromptMatchStrategy` — listSubagents + N × getSubagentMessages(limit:1), match first-user-message text against parent's Agent.tool_use.input.prompt. Bulletproof (the prompt body is verbatim shared) but slow. 4. `NativeStrategy` — placeholder. Slot in at chain position 1 once the SDK ships first-class correlation.
No DB row, no ClaudeSessionMetadataStore extension. The cache is process-lifetime; restart re-pays the cold path once per parent session on first navigation, but priming makes that cost amortise across subsequent clicks. See CONTEXT.md M7's "Subagent correlation" subsection for the full empirical justification.
getSubagentMessages only accepts the root sessionId; nested transcripts flatten on disk under the same root (`sdk.d.ts:906`). Phase 12 ships URL-level navigation only; deeper inlining is out of scope.claude.subagents overlay row on ClaudeSessionMetadataStore. Reverted: the relationship is fully inferable from SDK signals, persistence adds DB schema + JSON codec + race handling for marginal benefit on a cold path. The user explicitly steered this direction. If a future caller proves a sub-second cold-restart navigation requirement, revisit then.[] on every failure path. One bad subagent transcript must not break sibling navigation. Same rule applies inside every strategy — a strategy that throws is treated as "miss" and the chain continues.subagent_started fires for a parent_tool_use_id whose Task/Agent tool_use was never observed (transcript truncation, mid-resume), fall back to agentName: 'subagent', displayName: 'Subagent', description: undefined. Reachable only in edge cases (truncation/compaction); the normal resume path replays the Task tool_use first.tool_use.input.prompt (e.g. retried delegation, parallel identical sub-tasks), PromptMatch cannot tell which toolCallId maps to which agentId. Mitigation: TextSuffixStrategy runs first and resolves the common case unambiguously — PromptMatch fires only as a fallback when TextSuffix missed for that specific toolCallId. The cache + live capture also typically cover this case. Inherent strategy limitation, not a bug; the NativeStrategy (when SDK ships) closes the gap entirely. Documented in Q18.listSubagents + up to N × getSubagentMessages(limit:1) for PromptMatchStrategy. Mitigated by (a) TextSuffixStrategy running first and usually hitting on every Agent tool_result without any extra SDK calls, (b) notePrimingFromParent populating the cache opportunistically when the parent transcript loads, (c) process-lifetime cache persistence. The slow chain-fallthrough fires only when both TextSuffix and the cache miss — uncommon._backgroundTasks orphan-skip in clearPendingToolCalls (step 3): the entry doesn't generate a warning, but the child session stays alive until process shutdown. Rare edge case; documented as a known limitation.agentId: <hex> (use SendMessage with to: '<hex>') .... The tolerant regex (/^\s*agentId:\s+([a-z0-9]+)\b/imclaudeSubagentResolver.test.ts (new): each strategy in isolation against canned SDK fixtures; chain ordering (text-suffix hit short-circuits prompt-match); priming (notePrimingFromParent populates cache for every Agent tool_result in the supplied transcript); cache hit short-circuit (chain not called); telemetry counter increments per resolution; noteLiveAgentId populates cache.claudeTranscriptService.test.ts (new): branches correctly on isSubagentSession; parent path always calls notePrimingFromParent; every SDK error → warn + []; nested-URI walks reach the correct root.claudeMapSessionEvents.test.ts (modify): subagent ordering, parentToolCallId propagation, foreground completion, background completion, mutual-exclusion (background wins → foreground no-ops, and vice versa), spawning-tool-miss fallback, orphan drain on turn end, _innerToolToParent populated for inner tool_uses.claudeCanUseTool.test.ts (modify): agentID propagates through pending_confirmation signal carrying parentToolCallId; resolver noteLiveAgentId is called on the right pair.claudeAgent.test.ts (modify): getSessionMessages(parentURI) and getSessionMessages(subagentURI) both go through IClaudeTranscriptServiceIClaudeAgentSdkService returns a canned parent transcript with an Agent tool_use + tool_result containing the synthetic agentId: <id> text suffix + a separately-canned subagent transcript. Drive ClaudeAgent.getSessionMessages(parentURI) → assert subagent marker present; verify resolver cache populated (priming fired). Then getSessionMessages(subagentURI) → assert mapped subagent Turn[] returned via cache hit.typecheck-client clean, valid-layers-check clean.The workspace has the launch skill (Playwright-driven Code OSS automation) and code-oss-logs skill (find and read dev-build logs). Smoke scenario:
1. Use the launch skill to start Code OSS with the agent host enabled and a Claude session open. 2. Send a prompt that the model is likely to delegate via Agent (e.g. "use the Agent tool to list files in /tmp"). 3. Watch for the subagent marker rendering in the parent transcript and confirm the workbench can drill into the subagent session and see its turns. 4. Use the code-oss-logs skill to inspect agent-host logs for [AgentSideEffects] Creating subagent session and the absence of buffered-signal warnings; also confirm a claude.subagent.resolved_via.<strategy> telemetry counter incremented. 5. Restart Code OSS; reopen the same parent session; click into the same subagent marker; confirm the transcript still loads (this exercises the cold path through the resolver chain + priming).
If the live model rarely invokes the Agent tool in a deterministic way, fall back to a MockAgent-driven scenario (scripts/code-agent-host.js --enable-mock-agent) that synthesises an Agent turn and a paired subagent transcript on disk.
node ./scripts/code-agent-host.js --enable-mock-agent plus the ahp-websocket client to drive getSessionMessages(subagentURI) directly against the proxy. (Optional; covered by integration test.)Recorded as steps land. Captures any drift between the plan and the final code.
forwardSubagentText: true (landed)Options bag in claudeMaterializer.ts immediately after includePartialMessages: true.Options carries forwardSubagentText: true ... in claudeAgent.test.ts (Phase 8 suite, mirrors the existing enableFileCheckpointing assertion).IClaudeAgentSdkService and IClaudeSdkBindings in claudeAgentSdkService.ts with listSubagents(sessionId, options?) and getSubagentMessages(sessionId, agentId, options?). Production methods are thin forwards through _getSdk(), matching the existing getSessionMessages shape.importBehavior literal, FakeClaudeAgentSdkService (programmable subagentsBySessionId + subagentMessagesByKey maps + per-call recordings + rejection hooks), and ProxyRoundTripSdkService in the integration test (no-op stubs — the proxy-round-trip integration doesn't touch subagents).ClaudeAgentSdkService forwards listSubagents + getSubagentMessages to the underlying bindings ... covers the happy path. Faulted paths are covered by the existing cache-and-log-once test (the loader is shared with listSessions).ClaudeMapperState subagent bookkeeping (landed)_subagentSpawningTools, _backgroundTasks, _innerToolToParent, _announcedSubagents, _completedSubagents.lookupToolCall / cacheFileEdit / takeFileEdit):markSubagentSpawningTool(toolUseId, agentId | undefined) / getSubagentSpawningTool(toolUseId)markBackgroundTask(toolUseId) / isBackgroundTask(toolUseId)setInnerToolParent(innerId, parentId) / getParentToolCallId(innerId) ← public accessor used by step 5markSubagentAnnounced(agentId): boolean / markSubagentCompleted(agentId): boolean (return true only on first call — idempotency guard)_subagentSpawningTools is { agentId: string | undefined }, not the plan's { agentName, displayName, description? }. Reason: the metadata fields are only needed at signal-emit time (step 6), where the mapper has direct access to the _toolCallTurnIds drain warns. Added a logService.warn(...) per dropped entry citing the unresolved agentId so the orphan condition is diagnosable. No test churn — the existing step-3 test still passes; the warning is observational.IClaudeSubagentResolver + strategy chain (landed)IClaudeSubagentResolver decorator + interface, ISubagentLookupStrategy interface, the three strategies (TextSuffixStrategy, PromptMatchStrategy, NativeStrategy), ChainedSubagentResolver production impl, plus SUBAGENT_ID_SUFFIX_REGEX and scanTranscriptForAgentIds as exported helpers (the latter is reused by notePrimingFromParent and TextSuffixStrategy.lookup)./^\s*agentId:\s+([a-z0-9]+)\b/im matches empirical SDK suffix; character class is hex (no -) to match real agent ids. Tested across 7 input variants including leading whitespace, multi-space, mixed case, and rejected forms (agentid:abc missing space, description: decoy).vString / vObj keep the strategy layering-clean (no extensions/ imports). The strategy parses toolCall.toolInput JSON, narrows to { prompt: string }, then compares against the first 'user' SessionMessage's text content. No subagent_started + tag inner signals (landed)SUBAGENT_SPAWNING_TOOL_NAMES = new Set(['Task', 'Agent']) at file scope.mapSDKMessageToAgentSignals now reads envelope parent_tool_use_id from stream_event / user types and threads it into mapStreamEvent / tagWithParent.mapStreamEvent's content_block_start for tool_use: when the envelope's parent_tool_use_id === null AND the tool name is in SUBAGENT_SPAWNING_TOOL_NAMES, registers a spawning entry; otherwise (inner emission) records the inner-tool→parent edge via setInnerToolParent.tagWithParent post-processes signal batches: tags every action / pending_confirmation with parentToolCallId; prepends an IAgentSubagentStartedSignal the first time a given parent is seen (idempotency via state.markSubagentAnnounced). On unknown parent (no spawning entry — transcript truncation, mid-resume), falls back to agentName: 'subagent', agentDisplayName: 'Subagent' and agentDescription: undefinedsubagent_completed (landed)mapUserMessage checks _subagentSpawningTools + _backgroundTasks after the existing SessionToolCallComplete emission. If the entry exists and is NOT background AND markSubagentCompleted returns true, appends an IAgentSubagentCompletedSignal and clears the spawning entry.type: 'system' / subtype: 'task_started'): if tool_use_id matches an existing spawning entry, flips it to background via markBackgroundTask. Order-dependent: task_started must arrive before the parent tool_result per SDK semantics (and the test verifies this).type: 'system' / subtype: 'task_notification'): when status ∈ {'completed','failed','stopped'} AND tool_use_id is set AND the spawning entry still exists AND markSubagentCompleted returns true, emits IAgentSubagentCompletedSignal and clears the spawning entry. Idempotent — a duplicate notification is a no-op. When tool_use_id is absent on a terminal notification (per sdk.d.ts:3399), no completion fires and the background entry stays put across clearPendingToolCallsCanUseTool.agentID bridge (landed, depends on 3+4+6)IClaudeCanUseToolDeps extended with subagentResolver: IClaudeSubagentResolver.IClaudeCanUseToolOptions extended with optional agentID?: string (matches the SDK's sdk.d.ts:187 field).ClaudeAgentSession.requestPermission accepts new optional parentToolCallId?: string and emits it on the pending_confirmation signal — the signal type at agentService.ts:340 already supported the field; just plumbed through.mapperState accessor chain: `ClaudeSdkMessageRouter.mapperState` → `ClaudeSdkPipeline.mapperState` → `ClaudeAgentSession.mapperState`, so the bridge can call state.getParentToolCallId(options.toolUseID) without breaking encapsulation.dispatchCanUseTool: when options.agentID is set, looks up parentToolCallId, calls subagentResolver.noteLiveAgentId(session.sessionUri, parentToolCallId, agentID) (feeds the cache), and forwards parentToolCallId through requestPermission.IClaudeSubagentResolver injected into ClaudeAgent via @IClaudeSubagentResolver and threaded into IClaudeTranscriptService single ingress (landed)getTranscript(uri, token): subagent URIs delegate to IClaudeSubagentResolver.getTranscript; parent URIs hit IClaudeAgentSdkService.getSessionMessages → mapSessionMessagesToTurns → notePrimingFromParent (priming wrapped in its own try/catch so a resolver/validator bug cannot break a successful parent read).ClaudeAgent.getSessionMessages is now a 3-line one-liner around the transcript service. Removed: the inline TODO throw on subagent URI, the in-place SDK fetch / map / catch chain. The plan's "Phase 13 throw on subagent URI" test was rewritten to assert the new delegation semantics (subagent URI → resolver, SDK NOT touched).createDecorator<IClaudeTranscriptService> in both agentHostMain.ts and agentHostServerMain.ts after the resolver.primingCalls log).IClaudeSubagentResolver extended with disposeParent(parentUri): void. Implementation just deletes the per-parent inner cache map; no other state to clean (the resolver doesn't track per-parent live data outside the cache).ClaudeAgent.disposeSession now calls this._subagentResolver?.disposeParent(session) in both the provisional-abort and materialized-deleteAndDispose branches. Optional-chained because a small number of test scaffolds construct ClaudeAgent without registering the resolver — they don't exercise the canUseTool path, so the guard keeps the cleanup best-effort rather than forcing every test to wire the dependency.resolver.disposedParents contains the disposed URI.After the 2026-05-14 full-phase council review, two of three reviewers (GPT-5.5 + Codex) independently flagged a routing regression: AskUserQuestion and ExitPlanMode invoked from inside a subagent context were NOT being tagged with parentToolCallId. The early INTERACTIVE_CLAUDE_TOOLS branch in dispatchCanUseTool returned before the Phase 12 step 5 bridge ran, so their emitted SessionInputRequested / pending_confirmation signals landed on the parent session instead of the subagent. The plan's step 5 explicitly called this out ("Same change for requestUserInput — interactive tools inside a subagent — AskUserQuestion") but the fix had only been applied to the non-interactive path.
Fix landed:
resolveSubagentParent(deps, session, options) helper that runs the agentID → parentToolCallId resolution and feeds subagentResolver.noteLiveAgentId. Both the non-interactive path and the two interactive paths (handleExitPlanMode, handleAskUserQuestion) now call it.handleInteractiveTool now forwards the full IClaudeCanUseToolOptions (was just toolUseID).ClaudeAgentSession.requestUserInput extended with an optional parentToolCallId arg; emits it on the SessionInputRequested action signal so AgentSideEffects re-routes it to the subagent session (the routing seam at agentSideEffects.ts:289 already handles tagged actions uniformly)._innerToolToParent for both interactive tools, drives an AskUserQuestion and an ExitPlanMode call with agentID set, and asserts both emitted signals carry parentToolCallId AND both feed the resolver via noteLiveAgentId.After the council review, an architecture pass identified that the mapperState accessor chain (Router → Pipeline → Session) existed only so the canUseTool bridge could read one piece of subagent correlation state (getParentToolCallId). Three pass-through getters for one external read — a shallow leak.
The fix moves all five Phase-12 collections (spawning, background, innerToParent, announced, completed) off ClaudeMapperState and onto IClaudeSubagentResolver, keyed by parent session URI via a per-parent IParentSubagentTracker. The resolver becomes the single domain authority for subagent correlation: cache (read+write), live tracker (read+write), strategy chain, transcript fetch, parent disposal.
Concretely:
IClaudeSubagentResolver gains 9 verbs: noteSpawningTool, getSpawningTool, clearSpawningTool, noteBackgroundTask, isBackgroundTask, noteInnerToolEdge, getParentToolCallId, markAnnounced, markCompleted, plus a turn-end drain drainOrphanedSpawningTools.ClaudeMapperState shrinks back to its pre-Phase-12 size (10 verbs); the file's SUBAGENT_SPAWNING_TOOL_NAMES constant stays as the mapper still classifies tool names at content_block_start.mapSDKMessageToAgentSignals takes a new subagentResolver: IClaudeSubagentResolver arg; every state.X subagent call becomes resolver.X(session, ...). tagWithParent keeps state as a second arg for the spawning-tool name lookup (which legitimately lives in _toolCallNames).ClaudeSdkMessageRouter injects IClaudeSubagentResolver and threads it through. The mapperStateTests:
r() helper in claudeMapSessionEvents.test.ts returns a fresh real ChainedSubagentResolver (no-op SDK + empty strategy chain) so the existing tests pass it through transparently and the Phase-12 step-3/6/7 tests assert on its state.state.markX verbs).FakeClaudeSubagentResolver in claudeAgent.test.ts gained in-memory implementations of all 9 new tracker methods (still records liveNotes/primingCalls/disposedParents for assertion).entry.session.mapperState.setInnerToolParent via two as unknown casts; it now calls resolver.noteInnerToolEdge(sessionUri, ...) directly. The interactive-tool regression test does the same.Deletion test outcome: deleting the mapperState accessor chain dissolved 3 modules' getters and removed 2 as unknown test casts. Subagent correlation now has one named seam (IClaudeSubagentResolver).
Validation: 129 unit tests green, full type-check (typecheck-client) clean, valid-layers-check clean.
Two private methods on the new modules carried complex logic that was tested only indirectly. Per the personal-CLAUDE.md guideline ("if a private method is complex enough to warrant its own tests, extract it as a public standalone function"), both were lifted to free functions with explicit deps so the integration test no longer carries the burden of exercising every branch.
`loadParentTranscript` (extracted from ClaudeTranscriptService._loadParentTranscript):
[], mapper throws → [], priming throws → still returns turns. The third was untestable through the existing entry point because the only caller chain went through the real mapSessionMessagesToTurns (no way to make it throw).IParentTranscriptDeps with sdk, resolver, logService, and an optional mapper test seam. The class becomes a 4-line wrapper.`resolveAgentIdViaChain` (extracted from ChainedSubagentResolver._resolveAgentId):
this. The integrated chain test had to construct two resolvers — one for the hit path, one for the 'none' path — because resolution counts are per-instance.IResolveChainDeps with strategies, cacheGet, cacheSet, bump callbacks. Pure orchestration, no class needed.Validation: 137 unit tests green (was 129; +4 transcript service + +4 chain orchestration), full type-check clean, valid-layers-check clean.
Manual launch on 2026-05-14 surfaced a regression: subagent Task tool calls render in the parent transcript as "Running agents" with no inner content and never complete. Agent host log proved it:
assistant + 4 inner user messages with non-null parent_tool_use_idstream_event partials with non-null parent_tool_use_idtool_result for unknown tool_use_id warnings from mapUserMessageRoot cause: the Phase 12 plan assumed forwardSubagentText: true would deliver inner content via SDKPartialAssistantMessage (stream_event). Empirically the SDK delivers inner content only as canonical SDKAssistantMessage / SDKUserMessage envelopes. mapAssistantCanonical() returned [] for every inner message, so:
SessionResponsePart)tool_use blocks: never registered (no state.startToolBlock to populate _toolCallTurnIds)tool_result: hit the unknown-tool-use-id warn path because the lookup missesA second corollary was found in the same investigation: the SDK does NOT invoke the parent's `canUseTool` callback for inner subagent tools (it runs them in bypassPermissions internally). So the Phase 12 step 5 bridge — wired correctly — never fires for inner tools. The only signal source for inner tool calls is the canonical assistant message.
Fix: rewrote mapAssistantCanonical to handle inner messages (parent_tool_use_id !== null) by walking message.content and emitting one signal per block:
text / thinking → SessionResponsePart (Markdown / Reasoning) with the full contenttool_use → SessionToolCallStart + SessionToolCallReady (with confirmed: NotNeeded to auto-transition through PendingConfirmation since inner tools skip the host gate) + register the tool_use_id via state.startToolBlock so the matching tool_result can pair back, AND subagentResolver.noteInnerToolEdge(...) so any future canUseTool with agentID (rare top-level case) still has the parent edge availabletagWithParent then tags every emitted action with parent_tool_use_id and AgentSideEffects routes them to the subagent session.
Top-level (parent_tool_use_id === null) behaviour is unchanged: partials still cover everything, the canonical message still returns [].
CONTEXT.md M7 updated with the empirical correction and the canUseTool-skip finding. New regression test in claudeMapSessionEvents.test.ts drives an inner canonical assistant + inner tool_result, asserts text + tool-call signals fire and complete with parentToolCallId set on every action.
Validation: 138 unit tests green (was 137; +1 regression). Full type-check + layer-check clean. Awaiting user manual re-test.
Known follow-ups deferred from this fix (file separately when scoped):
subagent_started falls back to agentName: 'subagent' and agentDisplayName: 'Subagent' when the spawning entry is found. The Agent tool's input carries subagent_type (e.g. "Explore", "general-purpose") and description which would render much better. Plumbing those requires extending noteSpawningTool to carry metadata and writing it from the canonical assistant (where tool_use.input is complete) rather than content_block_start (where input is empty).agentId: suffix). PromptMatch should pick up the slack at replay time. Worth re-instrumenting after a few real sessions to see the actual resolved_via.<name> distribution.claudeAgent.test.ts, claudeMapSessionEvents.test.ts, claudeSubagentResolver.test.ts, claudeFileEditObserver.test.ts).valid-layers-check clean.as any introduced. Locally-defined validators (vObj / vString) keep the resolver layer below extensions/. The two as unknown as casts that exist are in tests for reaching into private state (read-only).resolved_via.<name>) is enough for the migration signal. Per-resolution event with duration would be more useful for debugging slow cold paths but adds noise. Default: counter only; promote to per-resolution event if a slow case ever surfaces.*Previously open, now resolved: SDKTaskStartedMessage usage (Q17), DI scope (Q19), canUseTool plumbing (Q20). PromptMatch duplicate handling clarified in Q18.*
parent_tool_use_id dispatch on SDKAssistantMessage), `sdkSessionAdapter.ts` (subagent transcript adapter), `claudeCodeSessionService.ts` (_loadSubagents — pure inference path, no DB)._handleSubagentStarted (line 461), _drainPendingSubagentSignals (line 441), completeSubagentSession (line 580), removeSubagentSessions (line 601), _pendingSubagentSignals buffer (lines 95-105, 307-317), _subagentSessions map (line 92).CanUseTool.agentID `sdk.d.ts:187`, BaseHookInput.agent_id `sdk.d.ts:131`, SessionMessage.parent_tool_use_id: null `sdk.d.ts:3566`Consensus + accepted findings: 1. Drop persistence; infer instead (consensus, all 3) — CanUseTool.agentID provides live capture; on-demand scan handles cold paths. 2. `SessionMessage.parent_tool_use_id` typed `null` literal (Opus, Codex) — claimed real value on inner .message. Later disproved empirically — see 2026-05-14 update. 3. `pending_confirmation` for inner subagent tools missing (GPT-5.5) — claudeCanUseTool.ts doesn't accept agentID; signals don't carry parentToolCallId. Step 5 added. 4. `forwardSubagentText: true` not enabled (Opus) — live subagent stream is tool-only without it. Step 1 added. 5. `getSubagentMessages(limit:1)` is wrong (Opus, Codex) — production scans full transcript. Step 7 originally corrected; later superseded by the strategy chain. 6. Foreground/background `subagent_completed` not mutually exclusive (GPT-5.5) — original "whichever first" would tear down a still-running background subagent. Step 7 now uses _completedSubagents set for mutual exclusion. 7. `listSessions` filter unnecessary (Opus, Codex) — SessionKey.subpath discriminator handles it.
Investigations after the initial review changed several conclusions:
getSubagentMessages calls — zero non-null occurrences in either envelope or inner message. The literal null type is accurate. Q11 corrected; the previous "read from .message" guidance was wrong.agentId (subagent envelope), toolUseResult.agentId (parent envelope), parent_tool_use_id (everywhere) — all gone from getSessionMessages / getSubagentMessages output.Agent.tool_use.input.prompt and subagent's first user message. Bulletproof fallback when text-suffix misses.IClaudeTranscriptService (single ingress) + IClaudeSubagentResolver (strategy chain) + notePrimingFromParent (cache pre-population from parent loads). Step 7's "scan via parent_tool_use_id" replaced entirely. New steps 4 (resolver) and 8 (transcript service). Q11 corrected, Q14 (listSubagents ordering) and Q15 (compaction) and Q16 (transcript service rationale) added.After the rewrite, council reviewed and surfaced more issues. All addressed:
1. BLOCKING (3/3 reviewers) — Background-subagent completion fires too early. The original mutual-exclusion logic assumed "whichever fires first wins," but tool_result for background subagents ALWAYS arrives first (the parent doesn't wait). The foreground branch would always win and prematurely tear down the still-running subagent. Fix: ingest SDKTaskStartedMessage into a new _backgroundTasks: Set<tool_use_id>; the foreground branch checks this set and skips when present, so only the later task_notification fires completion. Resolves the previously-open question about SDKTaskStartedMessage (Q17). Step 3, step 7, Q3, and Risks all updated. 2. BLOCKING (3/3 reviewers) — `canUseTool` bridge has no path to mapper state. Step 5 originally said state._innerToolToParent[toolUseID], but ClaudeMapperState is private to a different module and claudeCanUseTool.ts has narrow deps. Fix: expanded IClaudeCanUseToolDeps with getMapperState and subagentResolver; added a public getParentToolCallId(innerToolUseId) accessor on ClaudeMapperState (mirrors the existing lookupToolCall accessor); extended requestPermission / requestUserInput args with parentToolCallId?. Step 5 and Q20 rewritten. 3. BLOCKING (2/3 reviewers) — PromptMatch "deterministic first match is correct" is wrong.
Non-blocking observations (all accepted):
IClaudeTranscriptService earns its keep (priming hook has no other natural home).disposeParent lifecycle is clean.---
claudeSubagentSignals modulePhase 12 emission code had been accreting in claudeMapSessionEvents.ts (~832 LOC, 11 functions). Architecture review flagged poor locality: the Phase 7/8 live mapper file was carrying ~200 LOC of subagent-only emission helpers plus a constant set, and Phase 12 tests had drifted into the mapper's test file.
Extracted to `claudeSubagentSignals.ts`:
SUBAGENT_SPAWNING_TOOL_NAMES — set of tool names that spawn subagentstagWithParent(events, parent) — stamps _meta.parentSessionId onto eventsmapSubagentSystemMessage(message, resolver) — Phase 12 system-message pathbuildTopLevelSubagentReadyAction(block, session, turnId) — emits SessionToolCallReady with _meta.subagentDescription / subagentAgentName for the parent's Task tool call (top-level path)
emitInnerAssistantSignals(message, resolver, session, parent) —forwards inner subagent canonical assistant content (text / thinking / tool_use) tagged with parent
safeStringify for tool-result serializationmapAssistantCanonical in the live mapper shrank from ~190 LOC to a ~20-line dispatcher that calls one of the two extracted entry points.
Test split mirrors production split:
claudeMapSessionEvents.test.ts into a new claudeSubagentSignals.test.ts (state surface, top-level spawning, _meta.toolKind on Start, top-level canonical Ready, inner subagent message, unknown parent fallback, inner canonical text/thinking/tool_use, foreground completion, background completion).
buildTopLevelSubagentReadyAction drops malformed _meta fields; mapSubagentSystemMessage ignores invalid task_notification.
Validation: 141 tests pass across all 6 agentHost test files; typecheck-client and valid-layers-check clean.
---
SubagentRegistry refactor + E2E validationAfter the live wiring landed, an architecture sweep collapsed the junk-drawer IClaudeSubagentResolver singleton (13-method DI service keyed by parentUri everywhere) into a per-session domain model:
tool_use, owns its own lifecycle state: agentId (set-once via setAgentId), background (mutable bool flipped on task_started), subagentType / description (metadata from the tool_use.input written at canonical-assistant time), and idempotency latches markAnnounced / markCompleted.
ClaudeAgentSession collection of SubagentSpawn + reverse index from inner tool_use_id → parent Task. Owned by the session (via _register), dies with it automatically — no disposeParent needed, no parentUri parameter on any method.
claudeSubagentResolver.ts: the strategy chain (TextSuffixStrategy → PromptMatchStrategy → NativeStrategy), resolveAgentIdViaChain (pure orchestrator), getSubagentTranscript (the only public entrypoint for subagent transcript fetch). The parent-transcript-fetch + registry-priming logic was inlined directly into ClaudeAgent.getSessionMessages (~25 lines, no separate file).
session.subagents.getParentSpawn(...) directly; the agent dropped its IClaudeSubagentResolver injection and the deps passed to handleCanUseTool.
IClaudeSubagentResolver and the short-lived IClaudeTranscriptService decorator are gone from agentHostMain.ts / agentHostServerMain.ts.
The two scenarios from the roadmap's "Manual end-to-end validation" section were executed end-to-end against the live SDK via the launch skill and code-oss-logs skill:
1. Live spawn. Launched the Agents window, switched the agent picker to Claude, sent *"Spin up 2 subagents that do something, I want to make sure they render correctly"*. Observed two Explore: Run subagent task parent rows enter Running immediately, each nested with their inner Glob / Read tool calls (with completion chips), collapsing to Ran subagent on tool_result. Final parent assistant text rendered below. No console errors, no [Claude] warn-logs. 2. Replay. Opened a historical Claude session in the sidebar that had Task spawns. Parent rows rendered with the same labels as the live path; clicking a subagent marker opened the subagent transcript inline (resolved via the strategy chain on first open, primed cache thereafter). Inner content rendered without errors.
(claudeAgent.test.ts, claudeSubagentRegistry.test.ts, claudeSubagentResolver.test.ts, claudeSubagentSignals.test.ts, claudeMapSessionEvents.test.ts, claudeSdkPipeline.test.ts / claudeSdkMessageRouter.test.ts).
typecheck-client and valid-layers-check clean./improve-codebase-architecture and /avoid-private-methods lenses across the full diff after each step; only intentional test-seam exports remain.
(buildDefaultStrategies, IResolveChainDeps) — both demoted to module-private; one stale JSDoc reference to the deleted IClaudeTranscriptService was updated to point at getSubagentTranscript.
Phase 12 is now closed.
pending_confirmationparentToolCallIdtool_use's tool_result arrives for foreground subagents only, or (b) SDKTaskNotificationMessage with terminal status arrives for background subagents. Mutually exclusive — see Q3.Options.forwardSubagentText: true (`sdk.d.ts:1376-1379`) so live subagent messages include text/thinking, not just tool_use/tool_result.listSubagents and getSubagentMessages on `IClaudeAgentSdkService` / IClaudeSdkBindings.claude.subagent.resolved_via.<strategyName> per resolution so we can observe migration when SDK ships native correlation.message.type === 'system' && message.subtype === 'task_started'tool_use_id_subagentSpawningToolsSDKTaskStartedMessagetool_result_completedSubagents: Set<tool_use_id> — tracks which subagents have already fired subagent_completed (foreground OR background). Lives for the full session lifetime, NOT drained at turn end (a long-running background subagent's task_notification may arrive turns after its parent tool_result).clearPendingToolCalls (called from mapResult) to drop entries from _subagentSpawningTools only when both (a) no task_result has been seen AND (b) the tool_use_id is not in _backgroundTasks (background subagents intentionally outlive turn boundaries). Warn once per genuine orphan. Happy-path removal from _subagentSpawningTools happens in step 7's completion sites. _announcedSubagents, _backgroundTasks, and _completedSubagents are NOT drained on turn end.task_started ingestion path.vStringextensions/copilot/.../claudeSessionSchema.tsplatform/agentHostas anyNativeStrategy — placeholder. Returns undefined for now. Documented TODO with the SDK feature it'll consume when shipped.ChainedSubagentResolver — composes strategies in order, first non-undefined hit wins. Cache hits short-circuit before the chain runs. Emits telemetry counter claude.subagent.resolved_via.<strategy.name> (or cache / none) per resolution.Map<parentSessionId, Map<toolCallId, agentId>> field on the resolver; cleared on parent session disposal (see step 9).createDecorator<IClaudeSubagentResolver> in agentHostMain.ts / agentHostServerMain.ts (matches the existing Claude-service singleton pattern at agentHostMain.ts:116-121). Resolved in Decisions — not an open question.claudeSubagentResolver.ts.parentToolCallIdsubagent_started_handleSubagentStartedparentToolCallId propagation, idempotent subagent_started, spawning-tool-miss fallback, and _innerToolToParent population.message.type === 'system' && message.subtype === 'task_notification'status ∈ {'completed','failed','stopped'}tool_use_id_subagentSpawningTools_completedSubagentsIAgentSubagentCompletedSignal_completedSubagents_subagentSpawningTools_backgroundTasks_loadParentTranscriptnotePrimingFromParentagentIDIClaudeCanUseToolOptions_subagentResolver.noteLiveAgentIdagentIDrequestPermissionrequestUserInputpending_confirmationparentToolCallId_transcriptService.getTranscript(...)claudeTranscriptService.tsdisposeSession_subagentResolver.disposeParentclaudeSubagentResolver.test.tsnotePrimingFromParentclaudeTranscriptService.test.tsisSubagentSession[]parentToolCallId_innerToolToParentgetSessionMessages(subagentURI)[]agentIDpending_confirmationnoteLiveAgentIdIClaudeSubagentResolver:<sessionId>/subagents/agent-<id>.jsonlSessionKey.subpathlistSessionsSessionMessage[] → Turn[] shape, same M7 grouping rules. Subagent transcripts will themselves contain Task/Agent markers in nested cases, which the mapper already flattens to subagent-marker ToolCalls — those navigate to deeper-nested URIs that step 8's iterative walk handles..message and was readable via cast. Wrong. Empirical scan of 2,525 files / 110k+ envelopes / live SDK calls: zero non-null occurrences in either location. The literal null type at `sdk.d.ts:3566` is accurate. The replay path has NO parent_tool_use_id join key — that's why Q4's strategy chain exists. The corresponding LIVE field on SDKAssistantMessage IS populated and is what step 6 reads.tool_use/tool_result (`sdk.d.ts:1376-1379`). Without it, live subagent sessions are content-empty while replay returns full transcripts — a silent UX regression.parentToolCallId does NOT cover pending_confirmation signals because those originate from the canUseTool callback path, not from the message-stream mapper. Step 5 explicitly bridges CanUseTool.agentID (`sdk.d.ts:187`) into the signal. Without this, inner subagent permission prompts land on the parent session and the resulting SessionToolCallReady action has no matching SessionToolCallStart.subagents/ directory accumulates orphans (nested subagents, sidechain branches, compacted history). A coworker proposed positional matching (Nth Agent tool_use → Nth listSubagents result); rejected after empirical falsification. listSubagents is a discovery primitive (find all subagent files), NOT a correlation primitive. The strategy chain always pairs it with content-based matching.message.model === '<synthetic>'); the SDK's chain-walking excludes pre-compaction Agent tool_use blocks even though they appear in the raw JSONL. This means subagents from before the compaction boundary are unreachable via getSessionMessages. Not a Phase 12 concern (those subagents are unreachable by design — there's no marker to click), but documented so we don't try to "fix" it.isSubagentSession(uri) and then call either the resolver or the parent-load path. Hiding this branch behind one method makes the resolver's strategy chain a pure implementation detail; it also gives the parent path the natural priming hook (every successful parent load triggers notePrimingFromParent). The parent path stays simple inside (no strategies of its own — see "Out of scope" rationale).subagent_completed (step 7, Q3). Without ingesting it, background subagents are completed prematurely when their immediate parent tool_result arrives. The mapper populates _backgroundTasks from task_started.tool_use_id.disposeParent(parentURI) from ClaudeAgent.disposeSession (step 9) clears the relevant slice. Per-ClaudeAgent-instance was considered and rejected as inconsistent.IClaudeCanUseToolDeps only takes getSession + configurationService (`claudeCanUseTool.ts:20`). Step 5 expands it with getMapperState and subagentResolver. ClaudeMapperState also gains a public getParentToolCallId(innerToolUseId): string | undefined accessor (private field reads from outside the module are not allowed); mirrors the existing public lookupToolCall accessor.resolved_via.prompt_matchtask_started to arrive before the parent tool_result so _backgroundTasks is populated when tool_result is evaluated. Empirically the SDK emits task_started first; documented but not contractually guaranteed. Defensive interpretation: if tool_result arrives for a tool_use_id not in _backgroundTasks, treat as foreground (current behavior). A later task_notification for the same id would no-op via _completedSubagents. Worst case: a background subagent is incorrectly treated as foreground and its child session is torn down early. Mitigation: integration test asserts the actual ordering against a stubbed SDK that emits task_started first.Read/Bash with auto-approval) may never trigger canUseTool, so the live mapping isn't built — first navigation falls back to the chain. Acceptable; the chain handles it.subagent_started is the primary mechanism; the buffer at `agentSideEffects.ts:307-317` catches any future case where the mapper splits emissions. Documented invariant: every batch with a parent_tool_use_id-bearing signal includes its subagent_started (when not yet announced) at index 0._meta.toolKind = 'subagent' + ToolResultContentType.Subagent). Phase 12 only adds the *fetch* path; live child sessions are in-memory only.ClaudeMapperState lives at the `ClaudeSdkMessageRouter` level and survives the `ClaudeSdkPipeline` rebind path (line 345, 386). The new subagent collections (_subagentSpawningTools, _announcedSubagents, _innerToolToParent, _backgroundTasks, _completedSubagents) follow the same convention as _toolCallTurnIds: cross-message state survives queue rebinds intentionally, since the SDK replays from resume: sessionId and the same subagent state should still apply. Re-emission of subagent_started is guarded by _announcedSubagents.ChainedSubagentResolver + the strategies into one file — the interface separation is the load-bearing part.[]runTests with the relevant files; aim for the same fixture style as Phase 13's claudeReplayMapper.test.ts.tool_use.inputgetClaudeToolDisplayNameclaudeToolDisplay.tstool_use.inputSDKTaskStartedMessage ingestion (mapper-side recognition) is deferred to step 6 where the per-SDKMessage envelope-reading loop already needs to be added. Step 3 exposes markBackgroundTask as the seam; step 6 calls it from the new switch arm.clearPendingToolCalls drain semantics: now also iterates _subagentSpawningTools and drops entries that are NOT in _backgroundTasks. Background entries survive across turn boundaries by design — their synthetic completion tool_result can arrive many turns later.subagent state surface: spawning tools, inner-tool parent lookup, announce/complete idempotency, drain preserves background tasks ... in claudeMapSessionEvents.test.ts.valid-layers-check clean, full mapper test suite (21 tests) + full ClaudeAgent suite (93 tests) green.as anyMap<parentURI.toString(), Map<toolCallId, agentId>>. Resolution counter is in-memory (getResolutionCounts() returns a snapshot) since platform/agentHost has no ITelemetryService; higher layers can forward to telemetry if desired. createForTest(sdk, log, strategies) test seam swaps the chain without unsafe casts — _strategies is now mutable (still private) so the static factory can replace it.IClaudeAgentSdkService (matches the existing Claude-service pattern).extractAgentIdPair accepts ToolCallStatus.Completed AND ToolCallStatus.PendingResultConfirmation (both expose content). Plan only mentioned Completed; PendingResultConfirmation is the gated-result path and shares the same shape.scanTranscriptForAgentIds filtering, and the chained resolver's cache-short-circuit + chain-ordering + priming + telemetry-count behaviour in a single snapshot assertion.valid-layers-check clean; 27 resolver + mapper tests green; full ClaudeAgent suite (93 tests) regression-clean (120 tests total across the three files).AgentSideEffects._handleSubagentStartedClaudeMapperState.clearSubagentSpawningTool(toolUseId) helper used by both happy-path completion sites; clears both the spawning entry and any _backgroundTasks flag.mapSystemMessage switch in the mapper handles both subtypes; everything else returns [] (preserves prior fall-through for compact_boundary, hooks, etc.).IClaudeCanUseToolDepsFakeClaudeSubagentResolver in claudeAgent.test.ts recording noteLiveAgentId / notePrimingFromParent / disposeParent calls._innerToolToParent directly, invokes the captured canUseTool with agentID set, asserts pending_confirmation.parentToolCallId is the parent and resolver.liveNotes recorded the (parent, agentId) triple.claudeCanUseTool.ts's resolveSubagentParent calls deps.subagentResolver.getParentToolCallId(session.sessionUri, options.toolUseID) directly — no more Session→Pipeline→Router walk.disposeParent evicts both the cache and the live tracker.forwardSubagentTextSessionKey.subpathPromptMatchStrategy: `claudeSessionSchema.ts` — vObj, vString, vNullable, vUuid. No as any casts.extensions/copilot/.../claudeSessionSchema.tssrc/vs/platform/agentHost/extensions/claudeSubagentResolver.ts_subagentSpawningToolsTextSuffixStrategyagentHostMain.ts_innerToolToParent^agentId: ([a-z0-9]+) /m/^\s*agentId:\s+([a-z0-9]+)\b/imLiveCaptureStrategynoteLiveAgentId