From f49c1a97cadb00290e31062a802691e9efe187ef Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Mon, 20 Jul 2026 20:22:15 -0700 Subject: [PATCH] feat(contracts): thread agent snapshot schemas for subagent observability ThreadAgentSnapshot + agent.snapshot activity payload, typed task usage, task.updated runtime event, and agent-linkage fields on task payloads. Includes the reviewed HTML plans. Co-Authored-By: Claude Fable 5 --- .../plans/subagent-observability-spec.html | 1235 ++++++++++++++ .../plans/subagent-observability-ui.html | 1424 +++++++++++++++++ packages/contracts/src/index.ts | 1 + packages/contracts/src/providerRuntime.ts | 78 +- packages/contracts/src/threadAgents.ts | 138 ++ 5 files changed, 2874 insertions(+), 2 deletions(-) create mode 100644 docs/project/plans/subagent-observability-spec.html create mode 100644 docs/project/plans/subagent-observability-ui.html create mode 100644 packages/contracts/src/threadAgents.ts diff --git a/docs/project/plans/subagent-observability-spec.html b/docs/project/plans/subagent-observability-spec.html new file mode 100644 index 0000000000..650c54223f --- /dev/null +++ b/docs/project/plans/subagent-observability-spec.html @@ -0,0 +1,1235 @@ + + + + + + Subagent Observability — Audit & Tech Spec + + + +
+

+ T3 Code · Plan 1 of 2 · 2026-07-20 · rev 3 (minimal transport) · companion: + UI mockups +

+

Subagent Observability: Audit & Tech Spec

+

+ Expose Codex v2 subagents and Claude Code subagents + workflows in a live T3 panel: who + is running, what they're doing, token burn, elapsed time, and a drill-in. One generic + interface; both providers plug into it. +

+ +
+ Rev 2 — adversarially reviewed by a Fable subagent and gpt-5.6-sol (codex), + both verifying claims against source. Material corrections: (1) Codex + v2 does not emit the rich collabAgentToolCall spawn items — + that's v1; the v2 tracker is now keyed on subAgentActivity + child + thread/started metadata, and T3's child-thread suppression turns out not to + engage for v2 at all. (2) Codex agents are reusable identities, so the + snapshot now separates identity from activations and adds an idle state. + (3) Persistence is now material-transitions-only (1s ticks stay in + memory) because orchestration events are append-only and replay reads are global. Full + review notes: /tmp/subagent-audit/review/.

+ Rev 3 — minimal transport. The bespoke stream event, subscriber gating, + projection table, migration, and capability flag are all deleted: the roster now ships as + one agent.snapshot activity kind through the existing + append/persist/replay channel, latest-wins on the client — the exact pattern the + context-window meter already uses. Server delta shrinks to: contract types, two adapters, + one reducer in ingestion. Rev 2's bespoke design remains in this doc's git history as the + graduation path if fleets outgrow the activity channel. +
+ + + +

1 · Audit: Codex v2

+

+ Sources: codex-rs @ bb947e8e (2026-07-13); T3's generated schema pin 678157ac. Initial audit + corrected by adversarial review — v1/v2 item emission re-verified handler by handler. +

+ +

+ The core fact: every v2 subagent is a full app-server thread. There are no + dedicated subagent RPCs — spawn/send/wait are model tools, not client methods. The + client observes subagents as ordinary threads plus parent-side thread items. +

+ +
    +
  • + v1 vs v2. features.multi_agent (v1, stable) vs + features.multi_agent_v2 (under development, default off) — but the + model catalog forces v2 for gpt-5.6-sol and gpt-5.6-terra (models.json: multi_agent_version: "v2"), so on the models we care about it's on with zero config. v2 has no depth limit; + concurrency defaults to 4 (max_concurrent_threads_per_session). +
  • +
  • + Identity & lineage arrive on the standard + thread/started notification. The Thread object carries + parentThreadId, shared sessionId, + agentNickname (random, e.g. "Marlow"), agentRole (agent_type: + explorer/awaiter/custom), and + source.subAgent.threadSpawn.{depth, agentPath} with hierarchical paths like + /root/researcher. + Clients are auto-subscribed to child-thread events — no subscribe call needed. +
  • +
  • + Parent-side items — v1 and v2 emit differently (this is where the first + draft was wrong): +
      +
    • + v1 emits rich collabAgentToolCall items for + spawn/send/resume/close/wait, carrying receiverThreadIds, + prompt, model, reasoningEffort, and + agentsStates (child thread id → {status, message}). +
    • +
    • + v2 emits + subAgentActivity {kind: started|interacted|interrupted, agentThreadId, + agentPath} + on spawn/message/interrupt (multi_agents_v2/spawn.rs:142 emits + only this — verified, no CollabAgentToolCall anywhere in the v2 + spawn path). The only v2 collabAgentToolCall emitter is + wait, and it ships with empty + receiverThreadIds / + agentsStates (multi_agents_v2/wait.rs:85,90). + Model/prompt/agentsStates are not on v2 parent items. +
    • +
    + Consequence: under v2, per-agent status and model must come from the + child thread's own stream (thread/status/changed, + turn/started|completed, thread/settings/updated), not from + parent items. +
  • +
  • + Per-agent token burn is free: + thread/tokenUsage/updated {threadId, turnId, tokenUsage: {total, last, + modelContextWindow}} + fires per child thread with input/cached/output/reasoning breakdowns. No server-side tree + rollup — client sums. +
  • +
  • + Agents are reusable identities, not one-shot tasks. + send_message/followup_task re-target an existing child thread + and trigger new turns on it (interaction events at event_mapping.rs:133-178). + A child turn/completed means "this run finished", not "this agent is done" — + the agent sits idle and resumable. +
  • +
  • + Reference consumer: the Codex TUI builds its /agent UI from + notifications alone — it caches child threads from + subAgentActivity/thread/started, buffers the last ~6 item + summaries per child, labels agents "{nickname} [{role}]". +
  • +
  • + Not exposed: the live AgentRegistry (model-facing + list_agents only), tree token rollups, per-agent "current activity" endpoint. + thread/list?parentThreadId/ancestorThreadId subtree filters are + experimental-gated and newer than T3's schema pin. +
  • +
+ +
+ T3 schema verdict: the vendored effect-codex-app-server pin + already has everything needed — subAgentActivity, + collabAgentToolCall, + Thread.parentThreadId/agentNickname/agentRole + + source.subAgent.threadSpawn, thread/tokenUsage/updated. No + regeneration required to ship. +
+ +
+ T3's child-thread suppression does not engage for v2 — child chatter behavior today is + unverified. + CodexSessionRuntime.rememberCollabReceiverTurns learns child threads only from + collabAgentToolCall.receiverThreadIds; under v2 those are empty, so the + collabReceiverTurns map never populates and the suppression list is inert. What + v2 child-thread notifications actually do to the parent timeline today (leak in? get dropped + elsewhere?) must be established with a live v2 wire probe — this is the + entry gate for the Codex slice (§8). The suppression narrative in the first draft applied + only to v1 models (e.g. gpt-5.6-luna). +
+ +

2 · Audit: Claude Agent SDK

+

+ Sources: @anthropic-ai/claude-agent-sdk 0.3.170 type declarations, CLI 2.1.214 binary, and a + live stream-json wire probe (real subagent spawn captured). All SDK-type claims + below re-verified by both reviewers. +

+ +

+ The core fact: a complete task lifecycle already streams over stdio, keyed + by task_id + tool_use_id, covering subagents, background shells, + monitors, and workflows uniformly: +

+ +
task_started      {task_id, tool_use_id, description, subagent_type?, task_type?, workflow_name?, prompt?}
+task_progress     {task_id, description, usage:{total_tokens, tool_uses, duration_ms}, last_tool_name?, summary?}
+task_updated      {task_id, patch:{status: pending|running|completed|failed|killed|paused, end_time?, is_backgrounded?, error?}}
+task_notification {task_id, status: completed|failed|stopped, summary, usage?, output_file}
+ +
    +
  • + Subagent messages arrive on the main stream tagged + parent_tool_use_id + subagent_type + + task_description. By default only tool_use/tool_result blocks are forwarded; + forwardSubagentText: true forwards the full nested transcript. +
  • +
  • + "What it's doing right now": last_tool_name on every + progress tick and tool_progress heartbeats (tool_name, elapsed_time_seconds, parent_tool_use_id, task_id) are free. agentProgressSummaries: true additionally forks each running + subagent every ~30s for an AI-written present-tense summary in + task_progress.summary — real recurring model calls (SDK default is + off), so this is a per-instance setting, not a default (§8). +
  • +
  • + Workflows: task_started carries + task_type:'local_workflow' + workflow_name; + task_progress carries an undeclared-but-real + workflow_progress array (wire-probe confirmed) with + workflow_phase {index, title} and + workflow_agent {label, phaseIndex, phaseTitle, agentId, model, state, startedAt, + attempt, lastToolName, promptPreview, resultPreview, tokens, toolCalls, error} + entries. Not in sdk.d.ts; consume defensively behind a schema guard. + Per-agent full results are files-only (journal.jsonl, + agent-<id>.jsonl). +
  • +
  • + Usage granularity: per task (total_tokens only, no USD), per + message (if forwarded), per model + costUSD on the turn result.modelUsage, + session-wide via an explicitly-unstable control request. +
  • +
  • + Rosters: the typed background_tasks control request returns + the live task list (BackgroundTaskSummary[]) — this is the stable + roster/reconciliation source. A background_tasks_changed stream event was + also observed on the wire but is undeclared and its literal doesn't appear in the CLI + binary strings — treat as bonus signal only, never a dependency. +
  • +
  • + Gaps needing upstream: no model field on task events, no start_time on + task_started (use receive time), no per-subagent USD, + workflow_progress untyped. +
  • +
+ +
+ Today T3's ClaudeAdapter maps the lifecycle but strips the linkage. + task.started/progress/completed runtime events exist and are persisted, but + subagent_type, tool_use_id, workflow_name, + prompt, output_file are dropped; task_updated falls + into the unknown-subtype warning path (status transitions lost); + parent_tool_use_id traffic is filtered out of usage accounting. Raw payloads + survive in raw.payload on the ephemeral runtime events (NDJSON logs) — + recoverable at the adapter, but not from the durable store, so pre-feature + history cannot be backfilled (§5.5). +
+ +

3 · Audit: T3's existing pipeline

+ +
+ + + + + + + + + Codex app-server + Claude SDK + (stdio) + + + Adapters + normalize + + + ProviderRuntimeEventV2 + + task.* · item.* · turn.* + + + PubSub (in-memory) + + + + Ingestion + + lossy → activities + + + SQLite + projections + + + + WS subscribe + + snapshot + deltas + + + → atoms → React + + + + + + + + + + the gap: rich runtime events are compressed into + + + append-only activity rows; linkage fields dropped + + + + +
+ Two-tier pipeline: ephemeral runtime events → durable orchestration events → websocket. +
+
+ +
    +
  • + The right abstractions already exist. + ProviderRuntimeEventV2 already has + task.started/progress/completed (Claude emits them today, persisted and + streamed to clients as thread.activity-appended), a + collab_agent_tool_call canonical item type, and typed + ThreadTokenUsageSnapshot. +
  • +
  • + Snapshot+delta is a solved pattern: subscribeShell/subscribeThread + do live-buffer-first attach, snapshot-or-replay with afterSequence, + sequence-deduped deltas. projection_thread_sessions is the precedent for an + upserted per-thread mutable row. +
  • +
  • + Two cost facts that constrain the design (surfaced in review): +
      +
    • + Every accepted orchestration command appends an immutable event before + updating any projection — "upsert" describes the projection, not the event store. + High-frequency dispatches are permanent rows. +
    • +
    • + subscribeThread's afterSequence catch-up reads the + global event range after the cursor and filters per-thread afterward + (ws.ts:1385-1395), and shell resume falls back to full snapshots beyond + SHELL_RESUME_MAX_GAP = 1000. Fleet-wide event volume taxes every + reconnect. +
    • +
    + → persistence must be material transitions only (§5.3). +
  • +
  • + Compat asymmetry that shaped the transport: + OrchestrationEvent is a closed Schema.Union decoded by the RPC + client — a new event type breaks old clients (fails decode) and would need + per-subscriber gating. But OrchestrationThreadActivity.kind is an open string + with payload: Schema.Unknown — a new activity kind flows through + every layer untouched. That's why §5.3 ships the roster as an activity kind, not an event + type. +
  • +
  • + Gaps: only Claude emits task.* (Codex/OpenCode emit only + item lifecycles; ACP nothing). Task payloads lack name/model/parent-linkage and + usage is untyped. Tool activities carry no owning-agent id. Turn cost never + reaches the client. +
  • +
  • + Client: the right panel (rightPanelStore surfaces: + plan/diff/files/file/preview/terminal) is the natural mount; PlanSidebar is + the structural template; WorkingTimer (DOM-write ticking, no React commits), + Badge variants, animate-status-pulse, and + SimpleWorkEntryRow are the primitives to reuse. Mobile shares state via + client-runtime but duplicates presentation — put new derivation helpers in + client-runtime. +
  • +
+ +

4 · Unified data-availability matrix

+

+ "Wire" = the provider protocol T3 already speaks. "T3 today" = what actually reaches the + browser now. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
DatumCodex v2 wireClaude wireT3 todayPlan
Agent idyes child thread id (UUIDv7)yes task_id + tool_use_idtaskId only (Claude)normalize to agentId + keep provider
Name / label + yes nickname + role + path (child + thread/started) + yes description, subagent_type, name, workflow labeldescription onlyname + agentType
Model + partial child thread settings — not on v2 + parent items + + partial workflow agents yes; plain subagents only if + text forwarded + —optional model
Status / lifecycle + yes child thread/status + turn events (idle ≠ terminal) + yes task_updated + task_notificationstarted/completed only; task_updated dropped7-state enum incl. idle
Current activityyes child item streamyes last_tool_name; AI summaries opt-inlastToolName forwarded but not surfaced per-agentcurrentActivity + recent feed
Token burnyes per-thread breakdownsyes total_tokens per taskuntyped blobtyped usage
Start / end timeyes thread/turn timestampspartial end_time yes; start = receive timeactivity createdAtfirstStartedAt/lastActivityAt/endedAt
Parent linkageyes parentThreadId + depth + pathpartial tool_use_id, 1 level on stream—parentAgentId
Workflow phases / retriesn/a (paths encode tree) + partial undeclared + workflow_progress (incl. attempt) + —workflow agents = child agents with phaseTitle, attempt
Cost USDnopartial per-model per-turn only—out of scope v1
+ +

5 · Design: the generic interface

+ +

+ Principle: don't invent a new pipeline — enrich the one that exists. The + task.* runtime-event family is already the provider-agnostic "unit of delegated + work". We (a) extend its payloads with the missing typed fields, (b) make the Codex adapter + synthesize the same events from v2 notifications, and (c) have ingestion fold them into one + upserted snapshot per agent that rides the existing subscribeThread stream — + with persistence limited to material transitions. +

+ +

5.1 Contract: identity + activations new

+

+ Review-driven shape change: a Codex agent is a durable, re-activatable identity while a + Claude task is a one-shot execution. The snapshot models the identity with rollups + of its activations, so a follow-up doesn't destroy history and elapsed time stays + meaningful. +

+
// packages/contracts/src/orchestration.ts (additive)
+ThreadAgentStatus = "pending" | "running" | "waiting" | "idle" | "completed" | "failed" | "stopped"
+  // waiting  = blocked on approval/user-input, or queued (workflow)
+  // idle     = finished a run but resumable (Codex send_message/followup; Claude paused)
+  // completed/failed/stopped = terminal
+
+ThreadAgentUsage = {
+  totalTokens: NonNegativeInt,
+  inputTokens?, cachedInputTokens?, outputTokens?, reasoningOutputTokens?,
+  toolUses?: NonNegativeInt,
+}
+
+ThreadAgentSnapshot = {
+  agentId: TrimmedNonEmptyString,        // stable identity: Claude task_id · Codex child thread id
+  provider: ProviderDriverKind,          // id-space discriminator; prevents cross-provider collisions
+  kind: "subagent" | "workflow" | "workflow_agent" | "shell" | "monitor" | "other",
+  name: TrimmedNonEmptyString,           // description · nickname · workflow label
+  agentType?: TrimmedNonEmptyString,     // subagent_type · agent_role
+  model?: TrimmedNonEmptyString,
+  status: ThreadAgentStatus,
+  currentActivity?: TrimmedNonEmptyString,
+  lastToolName?: TrimmedNonEmptyString,
+  usage?: ThreadAgentUsage,              // cumulative across activations
+  firstStartedAt: IsoDateTime,
+  lastActivityAt: IsoDateTime,
+  endedAt?: IsoDateTime,                 // cleared on re-activation
+  activationCount: NonNegativeInt,       // Codex follow-ups · workflow retry attempts
+  spawnTurnId?: TurnId,                  // turn that created it
+  lastTurnId?: TurnId,                   // latest turn that touched it (UI groups by this)
+  parentAgentId?: TrimmedNonEmptyString,
+  phaseIndex?: NonNegativeInt,           // workflow phase membership (index is authoritative;
+  phaseTitle?: TrimmedNonEmptyString,    //   title is display — titles can repeat across phases)
+  // kind === "workflow" only:
+  phases?: Array<{ index: NonNegativeInt, title: TrimmedNonEmptyString }>, // ordered phase list
+  scriptPath?: TrimmedNonEmptyString,    // persisted workflow script (WorkflowOutput.scriptPath)
+  runId?: TrimmedNonEmptyString,         // workflow run id (resume handle)
+  approvalRequestId?: ApprovalRequestId, // set while waiting on an approval → UI deep-link
+  outputFile?: TrimmedNonEmptyString,    // Claude transcript path — phase-2 drill-in needs it
+  resultSummary?: TrimmedNonEmptyString,
+  errorMessage?: TrimmedNonEmptyString,
+  recentActivity: Array<{ at: IsoDateTime, summary: string }>, // ring buffer, max 6
+  updatedAt: IsoDateTime,                // staleness + "while you were away" watermark
+}
+ +

5.2 Provider mapping

+
+
+

Claude → snapshot

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SDK messageEffect
task_started + upsert: id, name=description, kind from task_type, agentType=subagent_type, + firstStartedAt=now, status=running, outputFile later +
task_progress + usage, lastToolName, currentActivity=summary; + workflow_progress[] (schema-guarded): + workflow_phase entries → the workflow snapshot's ordered + phases list; workflow_agent entries → upsert child + workflow_agent snapshots (label, phaseIndex+phaseTitle, model, state, + tokens, attempt) +
Workflow tool_result (WorkflowOutput) + scriptPath + runId onto the workflow snapshot (typed on + the tool output: "Path to the persisted workflow script for this invocation") +
task_updatedstatus patch (killed→stopped, paused→idle), endedAt=end_time, errorMessage
task_notificationterminal status, resultSummary, final usage, outputFile
tool_progress (has task_id)lastToolName + recentActivity entry
can_use_tool / approval (has agent_id)status=waiting + approvalRequestId; cleared on resolution
+

+ Adapter fixes: stop dropping + subagent_type/tool_use_id/workflow_name/output_file; handle + task_updated (today: warning path). Roster reconciliation via the typed + background_tasks control request (not the undeclared stream event). + agentProgressSummaries is a per-instance setting, default off — fallback + currentActivity is last_tool_name. Not enabling + forwardSubagentText in v1. +

+
+
+

Codex v2 → snapshot (corrected)

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NotificationEffect
child thread/started (source = subAgent.threadSpawn) + upsert identity: id=thread id, name=nickname, agentType=agentRole, parentAgentId, + depth/path, firstStartedAt +
subAgentActivity item (parent stream) + started → running; interacted → running + activationCount++; interrupted → stopped +
child turn/startedstatus=running (clear endedAt/resultSummary on re-activation)
child turn/completed + status=idle (resumable — not terminal), resultSummary=last + message +
child thread/status/changedactive flags waitingOnApproval/UserInput → waiting; closed → stopped
child thread/tokenUsage/updatedusage (full breakdown)
child item/started|completedcurrentActivity + recentActivity (reuse item titles)
child thread/settings/updatedmodel (v2 parent items don't carry it)
+

+ collabAgentToolCall is not used for tracking (v2 emits it only for + wait, with empty receivers) — render it as a parent activity only. Runtime + change: CodexSessionRuntime learns children from + thread/started.source + subAgentActivity, routes their + notifications to the agent tracker, and filters them out of the parent timeline. + Entry gate: a live v2 wire probe to establish what child chatter + reaches T3 today (§8). +

+
+
+ +

+ 5.3 Transport: one activity kind, zero new machinery rev 3 +

+

+ The dumb store already exists — use it. + OrchestrationThreadActivity has a free-form kind and an open + payload: Schema.Unknown, is persisted/capped/replayed, and streams over + subscribeThread today. And T3 already ships latest-wins state through it: + context-window.updated activities carry a full usage snapshot and the client + just takes the newest one (deriveLatestContextWindowSnapshot). Agents work + identically: +

+
// Ingestion keeps the per-thread agent map in memory (it must merge events anyway).
+// On a MATERIAL change — status transition · name/model/phase discovery ·
+// currentActivity change · usage crossing a 25k step · terminal fields —
+// it appends ONE activity via the EXISTING thread.activity.append command:
+{ kind: "agent.snapshot",
+  tone: "info",
+  summary: "2 agents running",               // human-readable on purpose (see compat)
+  payload: { agents: ThreadAgentSnapshot[] } } // full roster, latest-wins
+
+// Client: scan thread.activities for the newest agent.snapshot → that IS the panel state.
+// Same derivation pattern as the context-window meter. Typed decode of the payload
+// happens client-side against the contracts schema; a failed decode = ignore the row.
+

What this deletes relative to the rev-2 design — with no loss of insight:

+ + + + + + + + + + + + + + + + + + + + + + + + + +
Rev 2 (bespoke transport)Rev 3 (activity channel)
+ New thread.agent.upsert command + thread.agent-upserted event + in the closed union + Reuses thread.activity.append — no new command or event types
+ Subscriber opt-in gating + acceptAgentEvents + old/new contract tests + (closed-union decode risk) + + Not needed: kind is an open string, payload is + Unknown — old clients decode fine and render a rare benign "2 agents + running" info row (arguably a feature) +
+ projection_thread_agents table + migration + snapshot-assembly changes + + shell-refetch exclusion + + Not needed: rows land in the existing activities projection; the 500-row cap is the + retention policy +
ServerConfig.threadAgents capability flag + Not needed: presence of an agent.snapshot activity is self-describing +
Reducer hydration from the new projection + Same trick ingestion already uses for task titles: on first event for a thread, read the + latest agent.snapshot from the loaded thread detail (findTaskTitleInActivities + precedent) +
+
    +
  • + Volume: full-roster payload (≤ ~10 agents, a few KB) × material + transitions only ≈ tens of rows per agent run — same order as the + task.progress rows Claude already writes today. 1s ticks and elapsed time + stay client-derived, never persisted. +
  • +
  • + Codex-synthesized task.* events still bypass + runtimeEventToActivities + (the marker survives from rev 2) — they feed the reducer only, so slice 2 adds no timeline + spam. New clients add one skip line for agent.snapshot in + deriveWorkLogEntries (precedent: context-window.updated is + skipped the same way). +
  • +
  • + Known trade-offs, accepted: (a) the payload is untyped on the wire — the + schema lives in contracts and the client decodes tolerantly; (b) latest-wins inside a + 500-cap window means a thread with 500+ later activities loses its old roster — at that + distance the agents are ancient history, and the timeline's task.* rows + remain; (c) full-roster-per-write is O(agents) redundant — at ≤10 agents this is noise, + and it's what makes latest-wins (and therefore everything else) simple. +
  • +
  • + Escape hatch: if per-agent typed wire events or bigger fleets ever + matter, the rev-2 design (dedicated event + projection + subscriber gating, preserved in + git history of this doc) is the graduation path. Don't build it until the counter metric + (§8) says so. +
  • +
+ +

5.3b What happens to child-thread events — dropped today, distilled tomorrow

+

+ Today, T3 durably stores none of it. Precisely: Codex v1 child-thread + notifications are suppressed at the session runtime (their item events are re-attributed to + the parent turn; thread/turn/usage events dropped); Codex v2 child chatter is unaudited (the + suppression doesn't fire — probe gate in §8); Claude subagent traffic is reduced to the + task.* activity rows and its parent_tool_use_id stream deltas are + filtered out. The only place raw child events land is the rotating NDJSON observability logs + — not queryable, not replayed. +

+

This plan changes that to "distilled, not mirrored":

+
    +
  • + Durably stored (new): the per-agent snapshot — identity, lifecycle, usage + rollups, recentActivity (last 6 summaries), result summary, script/output + pointers — as agent.snapshot activity rows in the existing activities + projection + event store. This is what survives restarts and reconnects. +
  • +
  • + Still not stored: full child transcripts (every tool call, message delta, + reasoning block). Deliberately — mirroring child streams into the orchestration store + would multiply event volume by fleet size (§3's replay-cost facts). The providers already + persist them (Codex rollout files readable via thread/read; Claude + agent-<id>.jsonl / output_file), so the phase-2 drill-in + RPC reads them on demand from provider storage instead of duplicating them. +
  • +
  • + Caveat that falls out: transcript drill-in is only as durable as provider + storage — e.g. an ephemeral Codex thread or a cleaned /tmp output file means + the snapshot survives but the deep transcript doesn't. Acceptable: the snapshot is the + record; the transcript is an inspection tool. +
  • +
+ +

5.4 Recovery & staleness new (review-driven)

+
    +
  • + Reducer bootstrap: on the first event for a thread, hydrate the in-memory + agent map from the latest persisted agent.snapshot activity (same pattern + ingestion already uses to recover task titles from activities), so a mid-run server + restart doesn't orphan records when the next task_progress arrives without + its task_started. +
  • +
  • + Orphan sweep: provider sessions are child processes of the T3 server — on + session.exited (or a new session.started for the thread), all + non-terminal agents for that thread transition to stopped with + endedAt=now and an "orphaned on session exit" errorMessage. Reconciliation on + resume: Claude via the background_tasks control request; Codex via tracked + child threads. +
  • +
  • + Client staleness: updatedAt + the client's sync watermark + distinguish "running" from "stale while disconnected"; the UI's transport states + (loading/synchronizing/live/reconnecting) come from the existing subscription status + machinery, not the snapshot. +
  • +
  • + History: pre-feature threads cannot be backfilled — dropped fields only + exist in ephemeral NDJSON logs. Documented as a non-goal. +
  • +
+ +

5.5 Drill-in

+
    +
  • + Phase 1 (ships with the panel): recentActivity ring buffer + + resultSummary + prompt preview. Workflow cards get a "View script" + affordance: scriptPath opens in the right panel's existing + file: surface (read-only file preview — zero new viewer code; the path is + outside the workspace root, so the file surface needs to accept absolute session paths or + the server proxies the read). +
  • +
  • + Phase 2 (full transcript): one read RPC + orchestration.getAgentTranscript {threadId, agentId}. Codex: + thread/read on the child thread. Claude: tail outputFile / + agent-<id>.jsonl server-side (the snapshot's + outputFile field exists for exactly this), rendered with the existing + work-log row components. Avoids turning on forwardSubagentText globally. +
  • +
+ +

6 · Server changes (all additive)

+

+ Rev 3: no new command, event type, projection table, migration, subscription input, or + capability flag. The entire delta is contracts (types only), two adapters, and one reducer + inside ingestion. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
#WhereChangeSize
1packages/contracts + ThreadAgentSnapshot + status/usage schemas and the + agent.snapshot payload schema (used for client-side decode — no + wire-protocol change); extend TaskStarted/Progress/Completed payloads + (optional + name/agentType/model/toolUseId/parentTaskId/workflowName/phaseIndex/phaseTitle/phases/attempt/scriptPath/runId/outputFile + + typed usage + timeline-bypass marker) + S
2ClaudeAdapter + Carry the dropped fields; handle task_updated; approval → agent attribution + via agent_id; workflow_progress schema-guarded parse into + child task.* events; background_tasks reconciliation; + agentProgressSummaries per-instance option (default off) + M
3CodexSessionRuntime / CodexAdapter + Gated on live v2 probe. Track children from + thread/started.source.subAgent + subAgentActivity; route child + notifications to synthesized timeline-bypassing task.* events per §5.2; + keep child chatter out of the parent timeline (new filtering — the existing suppression + doesn't fire for v2) + M–L
4ProviderRuntimeIngestion + Agent reducer (in-memory, hydrated from the latest persisted + agent.snapshot) → material-transition agent.snapshot activity + appends through the existing command; orphan sweep on session exit; dispatch-rate + counter metric + M
+

+ Non-goals v1: cost USD attribution, ACP (Cursor/Grok) support (no wire signal exists), + cross-thread agent trees, controlling agents (stop/steer — Codex exposes interruption only + as a model tool today), history backfill. OpenCode: falls out automatically if its adapter + ever emits task.*. +

+ +

7 · Client changes

+
    +
  • + Derivation in client-runtime (shared with mobile): + deriveLatestAgentSnapshot(activities) — newest + agent.snapshot row, tolerant payload decode (mirrors + deriveLatestContextWindowSnapshot) — plus + deriveAgentPanelState(agents, syncStatus) — group by workflow, split + running/settled (by lastTurnId), compute totals, staleness from + updatedAt + subscription state. +
  • +
  • + Web: add "agents" to + RIGHT_PANEL_KINDS (singleton surface, storage v7→8); tab + "+" add-menu entry + in RightPanelTabs (surface always addable from the menu; the tab auto-appears + once the thread has agents); an AgentsPanel branch in ChatView's + surface switch; a compact live strip near the "Working…" row; one skip line for + agent.snapshot in deriveWorkLogEntries. Reuse: + Badge, animate-status-pulse, WorkingTimer, + SimpleWorkEntryRow. +
  • +
  • + Mobile: inspector-pane tenant on tablet, sheet on phone — later slice, + shares the derivation helpers. +
  • +
  • + Visual design + feature-to-field milestones: see the + companion UI plan. +
  • +
+ +

8 · Phasing, risks, open questions

+

Phasing

+
    +
  1. + Slice 1 — contracts + Claude: #1, #2, #4, #5 → panel shows Claude + subagents + workflows end-to-end. +
  2. +
  3. + Slice 2 — Codex: entry gate: live v2 wire probe (spawn agents on + gpt-5.6-sol through T3's app-server wrapper, capture exactly which child notifications + arrive and what leaks into the timeline today). Then #3 → same panel lights up for Codex + with zero client work. +
  4. +
  5. Slice 3 — drill-in transcripts + mobile.
  6. +
+

Risks

+
    +
  • + workflow_progress is undeclared in the SDK types — schema-guarded parsing; + file upstream for typing. The background_tasks_changed stream event is + probe-only evidence — never a dependency (typed control request is the roster source). +
  • +
  • + Codex child-thread routing touches turn-attribution logic — needs tests that parent + transcript behavior is unchanged for both v1 and v2 models. +
  • +
  • + Event volume: material-transition persistence bounds it, but slice 1 ships with a counter + metric on agent-upsert dispatch rate so we see reality before slice 2 multiplies it. +
  • +
  • + Compat: one test that an old client's activity handling renders (or benignly ignores) an + agent.snapshot row — the open-string channel makes this low-risk, but verify + rather than assume. +
  • +
+

Open questions

+
    +
  • Settled-agent grouping: collapse by turn (current lean) or by workflow run?
  • +
  • + Auto-open the panel on first agent spawn? (Lean: badge on the tab + the inline strip, no + auto-open.) +
  • +
  • + agentProgressSummaries: per-instance setting shipped off — do we want a UI + toggle in thread settings, or instance config only? +
  • +
+
+ + diff --git a/docs/project/plans/subagent-observability-ui.html b/docs/project/plans/subagent-observability-ui.html new file mode 100644 index 0000000000..ce43a24bb4 --- /dev/null +++ b/docs/project/plans/subagent-observability-ui.html @@ -0,0 +1,1424 @@ + + + + + + Subagent Observability — UI Mockups + + + +
+

+ T3 Code · Plan 2 of 2 · 2026-07-20 · rev 2 (post-review) · companion: + audit & tech spec +

+

Subagent Observability: UI Mockups

+

+ Three directions for surfacing live subagents and workflows. All three consume the same + ThreadAgentSnapshot[] from the spec, use T3's existing tokens (DM Sans, the + sky/emerald/amber status language, animate-status-pulse dots, + Badge chips), and mount without new layout regions. They differ in + where attention lives. +

+

+ Rev 2 after adversarial review (Fable + gpt-5.6-sol): every promised feature is now pinned + to a contract field and milestone (table below), + transport/staleness states are specified instead of assumed free, the Stop control is + explicitly out of v1 scope, and the Agents surface stays reachable from the panel "+" menu + even before any agent has run. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
DirectionOne-linerBest when
AAgents panel (right-panel surface)A first-class "Agents" tab beside Diff/Files/Browser with one card per agentYou want to watch a fleet while reading the chat
BInline live stripA collapsed roster docked above the composer that expands in placeGlanceable awareness with zero layout cost
CMission controlTree + drill-in split view with workflow phase barHeavy workflow runs; debugging what an agent did
+ + +

+ Option A Agents panel — a right-panel surface + recommended core +

+

+ Adds kind: "agents" to the existing right-panel workspace. A tab with a live + count badge sits beside Diff/Files/Browser; the panel shows one compact card per agent, + grouped by origin (workflow vs. direct spawns), with a summary footer aggregating burn. + Cards expand in place to the recent-activity feed. +

+ +
+
+
+
+ t3code · fix-auth-flow +
+ ▤▥ +
+
+
+
+ Audit the auth flow and fix the session-refresh race — use a workflow. +
+
+
+
+
+ ⚙ Workflow: audit-auth-flow + · +
+
+ Working for + · 4 agents running +
+
+
+ Reply… +
↑
+
+
+
+
+ ⛬ Agents 4 + DiffFiles+ +
+
+
+ Workflow · audit-auth-flow + {} script +
+
+ ✓ Audit +
+
+
+ audit:auth-entrypoints4m 02s +
+
Found 3 candidate races · report → /tmp/audit/entry.md
+
+ 118.4k tok·41 tools +
+
+
+ Verify2 running · 1 done +
+
+
+ verify:session-refreshsonnet +
+
▸ Reproducing the race in sessionRefresh.test.ts
+
+ 41.2k tok ↑·12 tools +
+
+
+
+ verify:token-rotationsonnet +
+
▸ Read apps/server/src/auth/rotate.ts
+
+ 26.0k tok ↑·8 tools +
+
+
+ Fixpending +
+
+ Direct spawns +
+
+
+ Marlowexplorercodex +
+
+ Waiting on approval · /root/marlow +
+
+ 61.8k tok·blocked 41s +
+
+
+
+ 3 running + 1 waiting + Σ 247k tok +
+
+
+
+
+ Option A — "Agents" as a peer of Diff/Files. Workflow agents group under real phase + headers (✓ done / running counts / pending) from the snapshot's phases list; + "{} script" opens the workflow's JS file in the file surface. Token burn is a plain + counter with a live-tick ▲ — burn is unbounded, so it must not look like progress toward + completion. Amber = blocked on approval (clicking jumps to the prompt). +
+
+ +
+
+ Pros +
    +
  • Zero new layout machinery — tab strip, docking, sheet mode, resize all exist
  • +
  • Persistent: watch agents while scrolling chat; count badge when hidden
  • +
  • Cards scale from 1 subagent to a 10-agent workflow (groups + scroll)
  • +
  • Natural home for phase-2 drill-in (card → expanded feed)
  • +
+
+
+ Cons +
    +
  • Competes for the right panel with Diff/Browser (tab switching)
  • +
  • Hidden by default on <980px until the user opens the sheet
  • +
  • Discovery depends on noticing the tab badge
  • +
+
+
+ + +

+ Option B Inline live strip — agents live in the conversation +

+

+ No panel at all: a roster strip docks between the timeline and the composer whenever ≥1 + agent is live, replacing the bare "Working…" row. Collapsed, it's one line with a face-pile + and aggregate burn; expanded, one row per agent. Terminal states fold into the timeline as + ordinary work-log entries. Inspired by the existing turn-fold ("Worked for 4m 12s") + language. +

+ +
+
+
+
+ t3code · fix-auth-flow +
+ ▤▥ +
+
+
+
+ Audit the auth flow and fix the session-refresh race — use a workflow. +
+
+
+
+
+ ✓ audit:auth-entrypoints — 3 candidate races + ✓ +
+
+ +
+
+ + 4 agents +
+ V + V + M + A +
+ · Verify 2/3 · · + Σ 247k + ▾ +
+
+ verify:session-refreshReproducing the race in sessionRefresh.test.ts41.2k · +
+
+ verify:token-rotationRead apps/server/src/auth/rotate.ts26.0k · +
+
+ Marlow explorerWaiting on approval — Review approval request61.8k · +
+
+ audit:auth-entrypointsDone · 3 candidate races found118.4k · 4m 02s +
+
+ +
+ Reply… +
↑
+
+
+
+
+
+ Option B — the roster is part of the conversation flow. Collapsed by default to a single + line; the ▾ expands rows in place. Rows click through to a drill-in sheet. +
+
+ +
+
+ Pros +
    +
  • Impossible to miss — agents appear exactly where you're already looking
  • +
  • Works identically on mobile/narrow (no panel dependency)
  • +
  • Cheapest build: one component + the existing work-log fold pattern
  • +
  • Keeps the right panel free for Diff/Browser
  • +
+
+
+ Cons +
    +
  • Competes with the composer for vertical space when expanded
  • +
  • No room for rich per-agent detail — drill-in must open elsewhere
  • +
  • Long fleets (10+) need truncation ("+6 more")
  • +
+
+
+ + +

Option C Mission control — tree + drill-in split

+

+ The maximal version, for when a workflow is the main event: the right panel (or maximized + panel) becomes a two-pane console. Left: the agent tree — workflow → phases → agents, Codex + agent paths shown as real hierarchy. Right: the selected agent's live dossier — status, + model, burn breakdown, and a streaming activity feed built from + recentActivity (phase 2: full transcript). A phase progress bar sits on top. +

+ +
+
+
+
+ t3code · fix-auth-flow · Agents +
+ ⤢ +
+
+
+
+
+
+ audit-auth-flow + workflow + {} script + · + Σ 247k tok · 41 tools +
+
+
+
+
+
+
+ Audit ✓Verify 2/3Fix +
+
+
+
+
+ ▾Phase: Verify +
+
+ verify:session-refresh41.2k +
+
+ verify:token-rotation26.0k +
+
+ verify:cookie-scopequeued +
+
+ ▾Phase: Audit +
+
+ audit:auth-entrypoints118.4k +
+
+ ▾Direct · codex +
+
+ Marlow explorer61.8k +
+
+ /marlow/grep_worker8.1k +
+
+
+
+ verify:session-refresh + sonnet + ⏹ Stop +
+
+
Elapsed
+
Tokens41.2k
+
Tools12
+
Runs1
+
+
+ Prompt: “Adversarially verify: session refresh race in refreshSession() — try + to reproduce…” +
+
+
+ 18:42:11▸ Bash · vp test run sessionRefresh.test.ts +
+
+ 18:41:56▸ Edit · sessionRefresh.test.ts (+34) +
+
+ 18:41:20▸ Read · apps/server/src/auth/refresh.ts +
+
+ 18:40:58▸ Grep · "refreshSession" — 14 matches +
+
+ 18:40:41Spawned · fork: last 2 turns +
+
+
+
+
+
+
+
+
+ Option C — tree honors real structure: workflow phases (Claude) and nested agent paths + (Codex, /marlow/grep_worker). The dossier pane streams the recent-activity + feed. Stop is v2+ only: no per-subagent interrupt exists in T3's command + set today, and Codex exposes interruption only as a model tool — it needs its own protocol + work. +
+
+ +
+
+ Pros +
    +
  • Only option that shows structure: phases, nesting, queue state
  • +
  • Drill-in is first-class, not an afterthought — best debugging surface
  • +
  • Maximized mode turns T3 into a genuine fleet console
  • +
+
+
+ Cons +
    +
  • Most surface area to build and maintain (~2–3× Option A)
  • +
  • Overkill for the common case of 1–2 subagents
  • +
  • Split panes need ≥ the maximized panel width to breathe
  • +
+
+
+ + +

Recommendation

+
+

+ Ship A, seed it with B's collapsed line, grow into C. These aren't + mutually exclusive — they're one system at three zoom levels. But (review pushback, + accepted) they are not all "the same data at more room": each step up needs + specific contract fields to exist first. The milestones below make that explicit so the UI + never promises what the wire can't deliver. +

+
    +
  1. + v1: Option A panel + Option B's + collapsed one-liner only (replacing today's bare "Working…" row; clicking it + opens the panel). Strictly limited to v1-milestone fields. +
  2. +
  3. + v1.5: in-card expansion in the panel → the recent-activity feed (C's + dossier content, without the split layout) + approval deep-links. +
  4. +
  5. + v2: when maximized, the Agents surface upgrades to C's tree + dossier + layout. Stop/steer controls land here — they need new provider-command plumbing, not + just layout. +
  6. +
+
+ +

Feature → contract field → milestone

+

+ Every visible affordance in the mocks, pinned to its data source. Nothing ships ahead of its + row. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UI affordanceContract field(s)Milestone
Name, type chip, status dot, elapsed, token barname, agentType, status, firstStartedAt/lastActivityAt, usagev1
"What it's doing" line + currentActivity (AI summary when enabled) with + lastToolName fallback + v1
Workflow grouping + phase headers (✓ Audit / Verify / Fix pending) + kind, parentAgentId, phaseIndex per agent + ordered phases on + the workflow snapshot (phase status derived: done = all members settled, running = any + running, pending = no members yet) + v1
"{} script" → workflow JS in file surface + scriptPath from WorkflowOutput (Claude-only; Codex has no + workflow concept) + v1
Amber row → jump to pending approvalapprovalRequestId (spec §5.1) + existing approval panel focusv1.5
"attempt 2 — retrying" + activationCount + errorMessage (Claude workflows only — + workflow_progress.attempt; no Codex source) + v1.5
Recent-activity feed in card/dossierrecentActivity ring bufferv1.5
Result link ("report → /tmp/…")resultSummary (path rendering is client-side sniffing)v1.5
"While you were away" divider, stale badgesupdatedAt + client sync watermark from subscription statev1.5
Full transcript dossier, per-agent tool feedoutputFile + getAgentTranscript RPC (spec §5.5)v2
Stop / steer buttonsnew provider commands — not in the observability contract at allv2+
+

+ Cut from the mocks after review: the "Isolation: worktree" stat (no wire source for either + provider) and the reasoning-effort chip (Codex v2 parent items don't carry effort; revisit + if a child-settings source is plumbed). The per-card provider chip is derived from the + thread's session, not a snapshot field. +

+ +

Shared component inventory (all options)

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PieceReuses
Status dot + pulse + animate-status-pulse, resolveThreadStatusPill color language + (sky=running, emerald=done, amber=waiting, red=failed, zinc=queued) +
Elapsed timers + WorkingTimer self-ticking DOM-write pattern (no React commits per tick) +
Model/role chipsBadge variants
Token burn counter + Plain tabular-nums count + live-tick indicator. Not a bar/ring: + burn has no denominator, and a fill implies progress. (ContextWindowMeter's + ring stays where a real denominator exists — context windows.) +
Activity feed rowsSimpleWorkEntryRow / work-log derivation, filtered by agentId
Panel shell / tabs / sheetRightPanelTabs + PreviewPanelShell resize + maximize
+ +

States to design past the happy path

+
    +
  • + Empty / discovery: the tab auto-appears once the thread has any agent + (and persists with settled history), but the surface is always reachable from the + right panel's "+" add-menu with an explanatory empty state — so users can discover it + before ever triggering an agent. +
  • +
  • + Idle vs done (Codex): a Codex agent that finished a run is + idle and resumable, not completed — dimmed sky dot, "idle · resumable" label. If + the model sends it a follow-up, the card re-activates (run count increments, elapsed + resumes). Distinct from Claude's terminal green check. +
  • +
  • + Waiting on approval: amber row links straight to the pending approval via + approvalRequestId (highest-value click in the whole feature; v1.5). +
  • +
  • + Failure: red dot + errorMessage snippet on the card; Claude + workflow agents show attempt count ("attempt 2 — retrying"). Codex has no retry signal — + failed is failed. +
  • +
  • + Transport states (separate axis from agent lifecycle): loading (skeleton + cards), synchronizing, live, reconnecting (dim panel + "reconnecting…" banner, timers + freeze at lastActivityAt), and subscription-error. While disconnected, + running agents get a stale badge after 30s past updatedAt — a snapshot can't + distinguish "still running" from "died while we were away", so the UI must not pretend it + can. +
  • +
  • + Orphaned: if the provider session exits, the server sweeps non-terminal + agents to stopped ("orphaned on session exit") — the panel shows them as + stopped with that reason, no zombie spinners. +
  • +
  • + Reconnect catch-up: settled-while-away agents (settled + updatedAt newer than the client's last-sync watermark) group under a "while + you were away" divider (v1.5). +
  • +
  • + Overflow: >8 agents → group headers become sticky, settled groups + auto-collapse; the reducer caps settled agents carried in the roster at 50/thread (oldest + settled pruned first). +
  • +
+ + +
+ + diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 43270efdec..ebf6ffbf00 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -18,6 +18,7 @@ export * from "./git.ts"; export * from "./vcs.ts"; export * from "./sourceControl.ts"; export * from "./orchestration.ts"; +export * from "./threadAgents.ts"; export * from "./editor.ts"; export * from "./project.ts"; export * from "./filesystem.ts"; diff --git a/packages/contracts/src/providerRuntime.ts b/packages/contracts/src/providerRuntime.ts index eb2563eff0..e76850b981 100644 --- a/packages/contracts/src/providerRuntime.ts +++ b/packages/contracts/src/providerRuntime.ts @@ -176,6 +176,7 @@ const ProviderRuntimeEventType = Schema.Literals([ "user-input.resolved", "task.started", "task.progress", + "task.updated", "task.completed", "hook.started", "hook.progress", @@ -226,6 +227,7 @@ const UserInputRequestedType = Schema.Literal("user-input.requested"); const UserInputResolvedType = Schema.Literal("user-input.resolved"); const TaskStartedType = Schema.Literal("task.started"); const TaskProgressType = Schema.Literal("task.progress"); +const TaskUpdatedType = Schema.Literal("task.updated"); const TaskCompletedType = Schema.Literal("task.completed"); const HookStartedType = Schema.Literal("hook.started"); const HookProgressType = Schema.Literal("hook.progress"); @@ -459,10 +461,56 @@ const UserInputResolvedPayload = Schema.Struct({ }); export type UserInputResolvedPayload = typeof UserInputResolvedPayload.Type; +/** + * Typed task usage rollup. `usage` on task events was historically + * `Schema.Unknown` (raw Claude SDK shape); emitters now normalize to this. + */ +export const RuntimeTaskUsage = Schema.Struct({ + totalTokens: NonNegativeInt, + inputTokens: Schema.optional(NonNegativeInt), + cachedInputTokens: Schema.optional(NonNegativeInt), + outputTokens: Schema.optional(NonNegativeInt), + reasoningOutputTokens: Schema.optional(NonNegativeInt), + toolUses: Schema.optional(NonNegativeInt), + durationMs: Schema.optional(NonNegativeInt), +}); +export type RuntimeTaskUsage = typeof RuntimeTaskUsage.Type; + +/** + * Agent-linkage fields shared by the task lifecycle payloads. Optional and + * additive: pre-existing emitters that only set taskId/description remain + * valid. + * + * `timelineBypass: true` marks events synthesized purely to feed the agent + * reducer (e.g. Codex child-thread activity): ingestion must skip the + * activity-timeline projection for them, otherwise child fleets would spray + * a row per tool call into the transcript. + */ +const TaskAgentLinkage = { + name: Schema.optional(TrimmedNonEmptyStringSchema), + agentType: Schema.optional(TrimmedNonEmptyStringSchema), + model: Schema.optional(TrimmedNonEmptyStringSchema), + toolUseId: Schema.optional(TrimmedNonEmptyStringSchema), + parentTaskId: Schema.optional(RuntimeTaskId), + workflowName: Schema.optional(TrimmedNonEmptyStringSchema), + phaseIndex: Schema.optional(NonNegativeInt), + phaseTitle: Schema.optional(TrimmedNonEmptyStringSchema), + phases: Schema.optional( + Schema.Array(Schema.Struct({ index: NonNegativeInt, title: TrimmedNonEmptyStringSchema })), + ), + attempt: Schema.optional(NonNegativeInt), + scriptPath: Schema.optional(TrimmedNonEmptyStringSchema), + runId: Schema.optional(TrimmedNonEmptyStringSchema), + outputFile: Schema.optional(TrimmedNonEmptyStringSchema), + timelineBypass: Schema.optional(Schema.Boolean), +} as const; + const TaskStartedPayload = Schema.Struct({ taskId: RuntimeTaskId, description: Schema.optional(TrimmedNonEmptyStringSchema), taskType: Schema.optional(TrimmedNonEmptyStringSchema), + prompt: Schema.optional(TrimmedNonEmptyStringSchema), + ...TaskAgentLinkage, }); export type TaskStartedPayload = typeof TaskStartedPayload.Type; @@ -470,16 +518,34 @@ const TaskProgressPayload = Schema.Struct({ taskId: RuntimeTaskId, description: TrimmedNonEmptyStringSchema, summary: Schema.optional(TrimmedNonEmptyStringSchema), - usage: Schema.optional(Schema.Unknown), + usage: Schema.optional(Schema.Union([RuntimeTaskUsage, Schema.Unknown])), lastToolName: Schema.optional(TrimmedNonEmptyStringSchema), + ...TaskAgentLinkage, }); export type TaskProgressPayload = typeof TaskProgressPayload.Type; +/** + * Non-terminal state patch (Claude `task_updated`): running/paused flips, + * backgrounding, error text, end time. + */ +const TaskUpdatedPayload = Schema.Struct({ + taskId: RuntimeTaskId, + status: Schema.optional( + Schema.Literals(["pending", "running", "completed", "failed", "killed", "paused"]), + ), + endTime: Schema.optional(IsoDateTime), + isBackgrounded: Schema.optional(Schema.Boolean), + errorMessage: Schema.optional(TrimmedNonEmptyStringSchema), + ...TaskAgentLinkage, +}); +export type TaskUpdatedPayload = typeof TaskUpdatedPayload.Type; + const TaskCompletedPayload = Schema.Struct({ taskId: RuntimeTaskId, status: Schema.Literals(["completed", "failed", "stopped"]), summary: Schema.optional(TrimmedNonEmptyStringSchema), - usage: Schema.optional(Schema.Unknown), + usage: Schema.optional(Schema.Union([RuntimeTaskUsage, Schema.Unknown])), + ...TaskAgentLinkage, }); export type TaskCompletedPayload = typeof TaskCompletedPayload.Type; @@ -835,6 +901,13 @@ const ProviderRuntimeTaskProgressEvent = Schema.Struct({ }); export type ProviderRuntimeTaskProgressEvent = typeof ProviderRuntimeTaskProgressEvent.Type; +const ProviderRuntimeTaskUpdatedEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: TaskUpdatedType, + payload: TaskUpdatedPayload, +}); +export type ProviderRuntimeTaskUpdatedEvent = typeof ProviderRuntimeTaskUpdatedEvent.Type; + const ProviderRuntimeTaskCompletedEvent = Schema.Struct({ ...ProviderRuntimeEventBase.fields, type: TaskCompletedType, @@ -995,6 +1068,7 @@ export const ProviderRuntimeEventV2 = Schema.Union([ ProviderRuntimeUserInputResolvedEvent, ProviderRuntimeTaskStartedEvent, ProviderRuntimeTaskProgressEvent, + ProviderRuntimeTaskUpdatedEvent, ProviderRuntimeTaskCompletedEvent, ProviderRuntimeHookStartedEvent, ProviderRuntimeHookProgressEvent, diff --git a/packages/contracts/src/threadAgents.ts b/packages/contracts/src/threadAgents.ts new file mode 100644 index 0000000000..ad43e918d2 --- /dev/null +++ b/packages/contracts/src/threadAgents.ts @@ -0,0 +1,138 @@ +import * as Schema from "effect/Schema"; +import { + ApprovalRequestId, + IsoDateTime, + NonNegativeInt, + TrimmedNonEmptyString, + TurnId, +} from "./baseSchemas.ts"; +import { ProviderDriverKind } from "./providerInstance.ts"; + +/** + * `ThreadAgentSnapshot` — one delegated worker (subagent, workflow, workflow + * agent, background shell, monitor) observed on a thread. + * + * The snapshot models a stable *identity* with rollups across its activations: + * a Codex collab agent is a durable, re-activatable child thread (follow-ups + * re-run it), while a Claude task is a one-shot execution. `status: "idle"` + * captures the Codex "finished a run but resumable" state, which is distinct + * from the terminal `completed`. + * + * Transport: the full per-thread roster is carried latest-wins in the payload + * of an `agent.snapshot` thread activity (see `ThreadAgentsActivityPayload`). + * There is no dedicated wire event — the activity channel's open `kind` string + * and unknown payload are the compatibility surface, mirroring how + * `context-window.updated` ships token snapshots today. + */ +export const ThreadAgentStatus = Schema.Literals([ + // Not yet running (workflow agent queued behind a phase, Codex pendingInit). + "pending", + "running", + // Blocked on an approval or user-input request. + "waiting", + // Finished a run but resumable (Codex agents between activations; Claude paused). + "idle", + "completed", + "failed", + "stopped", +]); +export type ThreadAgentStatus = typeof ThreadAgentStatus.Type; + +export const THREAD_AGENT_TERMINAL_STATUSES: ReadonlySet = new Set([ + "completed", + "failed", + "stopped", +]); + +export const ThreadAgentKind = Schema.Literals([ + "subagent", + "workflow", + "workflow_agent", + "shell", + "monitor", + "other", +]); +export type ThreadAgentKind = typeof ThreadAgentKind.Type; + +/** Cumulative usage across all of an agent's activations. */ +export const ThreadAgentUsage = Schema.Struct({ + totalTokens: NonNegativeInt, + inputTokens: Schema.optional(NonNegativeInt), + cachedInputTokens: Schema.optional(NonNegativeInt), + outputTokens: Schema.optional(NonNegativeInt), + reasoningOutputTokens: Schema.optional(NonNegativeInt), + toolUses: Schema.optional(NonNegativeInt), +}); +export type ThreadAgentUsage = typeof ThreadAgentUsage.Type; + +export const ThreadAgentActivityEntry = Schema.Struct({ + at: IsoDateTime, + summary: TrimmedNonEmptyString, +}); +export type ThreadAgentActivityEntry = typeof ThreadAgentActivityEntry.Type; + +/** Ordered workflow phase, present only on `kind: "workflow"` snapshots. */ +export const ThreadAgentWorkflowPhase = Schema.Struct({ + index: NonNegativeInt, + title: TrimmedNonEmptyString, +}); +export type ThreadAgentWorkflowPhase = typeof ThreadAgentWorkflowPhase.Type; + +export const THREAD_AGENT_RECENT_ACTIVITY_LIMIT = 6; + +export const ThreadAgentSnapshot = Schema.Struct({ + // Stable identity: Claude task_id, Codex child thread id. Provider + // discriminates the id space so cross-provider collisions are impossible. + agentId: TrimmedNonEmptyString, + provider: ProviderDriverKind, + kind: ThreadAgentKind, + name: TrimmedNonEmptyString, + // Provider agent type: Claude subagent_type ("Explore"), Codex agent_role + // ("explorer"). + agentType: Schema.optional(TrimmedNonEmptyString), + model: Schema.optional(TrimmedNonEmptyString), + status: ThreadAgentStatus, + currentActivity: Schema.optional(TrimmedNonEmptyString), + lastToolName: Schema.optional(TrimmedNonEmptyString), + usage: Schema.optional(ThreadAgentUsage), + firstStartedAt: IsoDateTime, + lastActivityAt: IsoDateTime, + // Cleared when a re-activation (Codex follow-up) starts a new run. + endedAt: Schema.optional(IsoDateTime), + // Codex follow-ups and Claude workflow retry attempts. + activationCount: NonNegativeInt, + spawnTurnId: Schema.optional(TurnId), + lastTurnId: Schema.optional(TurnId), + parentAgentId: Schema.optional(TrimmedNonEmptyString), + // Workflow phase membership. Index is authoritative; title is display-only + // (titles can repeat across phases). + phaseIndex: Schema.optional(NonNegativeInt), + phaseTitle: Schema.optional(TrimmedNonEmptyString), + // kind === "workflow" only. + phases: Schema.optional(Schema.Array(ThreadAgentWorkflowPhase)), + scriptPath: Schema.optional(TrimmedNonEmptyString), + runId: Schema.optional(TrimmedNonEmptyString), + // Set while waiting on an approval so the UI can deep-link to the request. + approvalRequestId: Schema.optional(ApprovalRequestId), + // Claude transcript/output path; the drill-in RPC reads it on demand. + outputFile: Schema.optional(TrimmedNonEmptyString), + resultSummary: Schema.optional(TrimmedNonEmptyString), + errorMessage: Schema.optional(TrimmedNonEmptyString), + recentActivity: Schema.Array(ThreadAgentActivityEntry), + // Staleness watermark: how fresh this record is, independent of transport + // state. Clients compare against their sync watermark. + updatedAt: IsoDateTime, +}); +export type ThreadAgentSnapshot = typeof ThreadAgentSnapshot.Type; + +export const THREAD_AGENTS_ACTIVITY_KIND = "agent.snapshot"; + +/** + * Payload of an `agent.snapshot` thread activity: the complete latest-wins + * roster for the thread. Decoded tolerantly on the client — a row that fails + * to decode is ignored, never fatal. + */ +export const ThreadAgentsActivityPayload = Schema.Struct({ + agents: Schema.Array(ThreadAgentSnapshot), +}); +export type ThreadAgentsActivityPayload = typeof ThreadAgentsActivityPayload.Type;