import { groupBy } from "effect/Array"; import * as DateTime from "effect/DateTime"; import type { ModelSelection, OrchestrationV2AppThread, OrchestrationV2Subagent, OrchestrationV2SubagentWorkflow, OrchestrationV2TurnItem, } from "@t3tools/contracts"; import { isOrchestrationV2WorkActive, isProviderNativeSubagentThread } from "@t3tools/contracts"; import { mFallback, msg } from "gt-i18n"; import type { MFunctionType } from "gt-i18n/types"; export type RuntimeSubagentStatus = | "pending" | "running" | "waiting" | "idle" | "completed" | "failed" | "cancelled" | "interrupted"; export interface SubagentUsage { readonly totalTokens: number; readonly inputTokens?: number; readonly cachedInputTokens?: number; readonly outputTokens?: number; readonly reasoningOutputTokens?: number; readonly toolUses?: number; readonly durationMs?: number; } export interface SubagentActivityEntry { readonly at: string; readonly summary: string; } export interface SubagentWorkflowPhase { readonly index: number; readonly title: string; } export interface SubagentRunHandles { readonly runId?: string | undefined; readonly scriptPath?: string | undefined; readonly transcriptDir?: string | undefined; readonly sessionUrl?: string | undefined; } export interface RuntimeSubagent { readonly id: string; readonly kind: "subagent" | "subagent_batch" | "workflow" | "workflow_agent"; readonly title: string; readonly role: string | null; readonly model: string | null; readonly effort: string | null; readonly speed?: string | undefined; readonly status: RuntimeSubagentStatus; readonly activationCount: number; readonly usage: SubagentUsage | null; readonly progress: string | null; readonly lastToolName: string | null; readonly result: string | null; readonly error: string | null; readonly outputFile: string | null; readonly parentAgentId: string | null; readonly agentIndex: number | null; readonly phaseIndex: number | null; readonly phaseTitle: string | null; readonly attempt: number | null; readonly workflowName: string | null; readonly phases: ReadonlyArray; readonly runHandles: SubagentRunHandles | null; readonly childThreadId: string | null; readonly recentActivity: ReadonlyArray; readonly firstSeenAt: string; readonly startedAt: string | null; readonly completedAt: string | null; readonly updatedAt: string; } const TERMINAL_STATUSES: ReadonlySet = new Set([ "completed", "failed", "cancelled", "interrupted", ]); export function isTerminalSubagentStatus(status: RuntimeSubagentStatus): boolean { return TERMINAL_STATUSES.has(status); } export function isActiveSubagentStatus(status: RuntimeSubagentStatus): boolean { return isOrchestrationV2WorkActive(status); } export function isLiveSubagentTurnItem(item: OrchestrationV2TurnItem): boolean { return item.type === "subagent" && isOrchestrationV2WorkActive(item.status); } export function waitingOnSubagentsLabel(count: number, resolve: MFunctionType = mFallback): string { return resolve( msg("{count, plural, =1 {Waiting on a subagent} other {Waiting on {count} subagents}}", { count, }), ); } export interface SubagentWorkflowGroup { readonly workflow: RuntimeSubagent; readonly phases: ReadonlyArray<{ readonly index: number; readonly title: string; readonly members: ReadonlyArray; readonly state: "pending" | "running" | "done"; readonly settledCount: number; }>; readonly unphasedMembers: ReadonlyArray; } function workflowUsage(source: { readonly totalTokens?: number | undefined; readonly toolCalls?: number | undefined; readonly durationMs?: number | undefined; }): SubagentUsage | null { if (source.totalTokens === undefined) return null; return { totalTokens: source.totalTokens, ...(source.toolCalls === undefined ? {} : { toolUses: source.toolCalls }), ...(source.durationMs === undefined ? {} : { durationMs: source.durationMs }), }; } function isoFromEpochMillis(value: number | undefined): string | null { return value === undefined ? null : DateTime.formatIso(DateTime.makeUnsafe(value)); } function workflowMembersToRuntime( coordinator: RuntimeSubagent, workflow: OrchestrationV2SubagentWorkflow, ): ReadonlyArray { return workflow.agents.map((agent) => { // A workflow that stopped (or went idle with nothing left to watch) stops its open members. const status = (agent.state === "queued" || agent.state === "running") && (isTerminalSubagentStatus(coordinator.status) || coordinator.status === "idle") ? coordinator.status : agent.state === "queued" ? "pending" : agent.state; const failed = status === "failed"; const startedAt = isoFromEpochMillis(agent.startedAt); const completedAt = isTerminalSubagentStatus(status) ? (isoFromEpochMillis(agent.completedAt) ?? (agent.startedAt !== undefined && agent.durationMs !== undefined ? isoFromEpochMillis(agent.startedAt + agent.durationMs) : coordinator.completedAt)) : null; return { ...coordinator, id: `${coordinator.id}:agent:${agent.index}`, kind: "workflow_agent" as const, title: agent.label, model: agent.model ?? null, effort: agent.effort ?? null, ...(agent.speed === undefined ? {} : { speed: agent.speed }), status, activationCount: agent.attempt ?? 1, usage: workflowUsage(agent), progress: agent.prompt ?? null, result: failed ? null : (agent.result ?? null), error: failed ? (agent.result ?? null) : null, parentAgentId: coordinator.id, agentIndex: agent.index, phaseIndex: agent.phaseIndex ?? null, phaseTitle: agent.phaseTitle ?? null, attempt: agent.attempt ?? null, phases: [], childThreadId: agent.childThreadId ?? null, recentActivity: [], firstSeenAt: isoFromEpochMillis(agent.queuedAt) ?? startedAt ?? coordinator.firstSeenAt, startedAt, completedAt, updatedAt: completedAt ?? startedAt ?? coordinator.firstSeenAt, } satisfies RuntimeSubagent; }); } export function promptTitle(prompt: string): string { if (prompt.length <= 80) return prompt; let end = 77; const previous = prompt.charCodeAt(end - 1); const next = prompt.charCodeAt(end); if (previous >= 0xd800 && previous <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) { end -= 1; } return `${prompt.slice(0, end)}...`; } export function workflowMemberModelSelection( member: Pick, instanceId: ModelSelection["instanceId"], ): ModelSelection | undefined { if (!member.model) return undefined; return { instanceId, model: member.model, options: [ ...(member.effort ? [{ id: "effort", value: member.effort }] : []), ...(member.speed ? [{ id: "fastMode", value: member.speed === "fast" }] : []), ], }; } export function projectedSubagentsToRuntime( subagents: ReadonlyArray<{ readonly id: string; readonly title: string | null; readonly prompt: string; readonly model: string | null; readonly status: OrchestrationV2Subagent["status"]; readonly progress?: string | undefined; readonly childThreadId?: string | null | undefined; readonly workflow?: OrchestrationV2SubagentWorkflow | undefined; readonly result: string | null; readonly startedAt: DateTime.Utc | null; readonly completedAt: DateTime.Utc | null; readonly updatedAt: DateTime.Utc; }>, ): ReadonlyArray { return subagents.flatMap((subagent) => { const updatedAt = DateTime.formatIso(subagent.updatedAt); const startedAt = subagent.startedAt === null ? null : DateTime.formatIso(subagent.startedAt); const firstSeenAt = startedAt ?? updatedAt; const { workflow } = subagent; const runHandles = workflow?.runHandles ?? null; const coordinator = { id: subagent.id, kind: workflow === undefined ? "subagent" : "workflow", title: subagent.title ?? promptTitle(subagent.prompt), role: null, model: subagent.model, effort: null, status: subagent.status, activationCount: 1, usage: workflow === undefined ? null : workflowUsage(workflow), progress: subagent.progress ?? null, lastToolName: null, result: subagent.result, error: subagent.status === "failed" ? (subagent.result ?? null) : null, outputFile: null, parentAgentId: null, agentIndex: null, phaseIndex: null, phaseTitle: null, attempt: null, workflowName: workflow?.name ?? null, phases: workflow?.phases ?? [], runHandles, childThreadId: subagent.childThreadId ?? null, recentActivity: [], firstSeenAt, startedAt, completedAt: subagent.completedAt === null ? null : DateTime.formatIso(subagent.completedAt), updatedAt, } satisfies RuntimeSubagent; return workflow === undefined ? [coordinator] : [coordinator, ...workflowMembersToRuntime(coordinator, workflow)]; }); } export function deriveWorkflowGroups( agents: ReadonlyArray, resolve: MFunctionType = mFallback, ): ReadonlyArray { const workflows = agents .filter((agent) => agent.kind === "workflow") .sort((a, b) => a.firstSeenAt.localeCompare(b.firstSeenAt) || a.id.localeCompare(b.id)); const members = groupBy( agents.filter((agent) => agent.kind !== "workflow" && agent.parentAgentId !== null), (agent) => agent.parentAgentId!, ); return workflows.map((workflow) => { const workflowMembers = Object.hasOwn(members, workflow.id) ? members[workflow.id]! : []; // Union, not either/or: the declared plan lags the members, because the // provider only admits a phase once something in it starts. Members seed // the map; the declared titles then overwrite whatever they guessed. const phaseTitles = new Map(); for (const member of workflowMembers) { if (member.phaseIndex === null) continue; phaseTitles.set( member.phaseIndex, member.phaseTitle ?? phaseTitles.get(member.phaseIndex) ?? resolve(msg("Phase {number}", { number: member.phaseIndex + 1 })), ); } for (const phase of workflow.phases) phaseTitles.set(phase.index, phase.title); const knownPhases = Array.from(phaseTitles.entries()) .map(([index, title]) => ({ index, title })) .sort((a, b) => a.index - b.index); const phases = knownPhases.map((phase) => { const phaseMembers = workflowMembers .filter((member) => member.phaseIndex === phase.index) .sort((a, b) => (a.agentIndex ?? 0) - (b.agentIndex ?? 0)); const hasActiveMember = phaseMembers.some( // Idle members count as active for phase-liveness: a resumable Codex // member has not finished the phase. (member) => isActiveSubagentStatus(member.status) || member.status === "idle", ); const settledCount = phaseMembers.filter((member) => isTerminalSubagentStatus(member.status), ).length; const state: "pending" | "running" | "done" = phaseMembers.length === 0 ? "pending" : hasActiveMember ? "running" : "done"; return { index: phase.index, title: phase.title, members: phaseMembers, state, settledCount, }; }); const unphasedMembers = workflowMembers .filter((member) => member.phaseIndex === null) .sort((a, b) => (a.agentIndex ?? 0) - (b.agentIndex ?? 0)); return { workflow, phases, unphasedMembers }; }); } // Workflow scripts open with their `meta` export, after any leading comments. // Each comment has one way to match, so a prompt of `////` divider lines cannot backtrack. const WORKFLOW_SCRIPT_START = /^\s*(?:(?:\/\/[^\r\n\u2028\u2029]*(?:[\r\n\u2028\u2029]|$)|\/\*(?:[^*]|\*(?!\/))*\*\/)\s*)*export\s+const\s+meta\b/; /** * Whether a user message is the script a provider-native workflow runs. Servers mark every * subagent prompt either way; only threads recorded before the mark fall back to the text. */ export function isWorkflowScriptMessage(message: { readonly role: string; readonly text: string; readonly workflowScript?: boolean | undefined; }): boolean { return ( message.role === "user" && (message.workflowScript ?? WORKFLOW_SCRIPT_START.test(message.text)) ); } type ProjectedSubagent = Parameters[0][number] & Pick; export interface WorkflowOpening { readonly messageId: string; readonly script: string; readonly name: string | null; readonly description: string | null; readonly driver: OrchestrationV2Subagent["driver"] | null; readonly providerInstanceId: OrchestrationV2Subagent["providerInstanceId"] | null; /** Null until the parent thread's coordinator row is loaded. */ readonly group: SubagentWorkflowGroup | null; } /** * The opening of a workflow coordinator's thread: its first user message is the workflow script, * shown as the workflow's plan. The coordinator row lives on the parent thread, so * `parentSubagents` is the parent projection's subagents, or null when it is not loaded. */ export function resolveWorkflowOpening( input: { readonly thread: Pick; readonly messages: ReadonlyArray<{ readonly id: string; readonly role: string; readonly text: string; readonly workflowScript?: boolean | undefined; }>; readonly parentSubagents: ReadonlyArray | null; }, resolve: MFunctionType = mFallback, ): WorkflowOpening | null { if (!isProviderNativeSubagentThread(input.thread)) return null; const first = input.messages.find((message) => message.role === "user"); if (first === undefined) return null; const coordinator = input.parentSubagents?.find( (subagent) => subagent.childThreadId === input.thread.id, ); if (first.workflowScript === false) return null; if (coordinator?.workflow === undefined && !isWorkflowScriptMessage(first)) return null; return { messageId: first.id, script: first.text, name: coordinator?.workflow?.name ?? null, description: coordinator?.title ?? null, driver: coordinator?.driver ?? null, providerInstanceId: coordinator?.providerInstanceId ?? null, group: coordinator?.workflow === undefined ? null : (deriveWorkflowGroups(projectedSubagentsToRuntime([coordinator]), resolve)[0] ?? null), }; } /** * The parent thread whose subagent rows describe this thread's workflow, or null when the thread * does not open with a workflow script. Gates loading the parent so ordinary subagent threads * never subscribe to their parent's detail. */ export function workflowOpeningParentThreadId(input: { readonly thread: Pick; readonly messages: ReadonlyArray[0]>; }): OrchestrationV2AppThread["id"] | null { if (!isProviderNativeSubagentThread(input.thread)) return null; const first = input.messages.find((message) => message.role === "user"); return first !== undefined && isWorkflowScriptMessage(first) ? input.thread.lineage.parentThreadId : null; } const WORKFLOW_AGENT_COUNTS = { working: msg("{count} working"), done: msg("{count} done"), failed: msg("{count} failed"), stopped: msg("{count} stopped"), }; /** The opening block's heading: the workflow, what it does, and how its agents stand. */ export function workflowOpeningHeadline( opening: WorkflowOpening, resolve: MFunctionType = mFallback, ): { readonly title: string; readonly description: string | null; readonly agents: string | null; } { const title = opening.name ?? opening.description ?? resolve(msg("Workflow")); const members = opening.group === null ? [] : [ ...opening.group.phases.flatMap((phase) => phase.members), ...opening.group.unphasedMembers, ]; const counts = new Map(); for (const member of members) { const key = isTerminalSubagentStatus(member.status) ? member.status === "completed" ? "done" : member.status === "failed" ? "failed" : "stopped" : "working"; counts.set(key, (counts.get(key) ?? 0) + 1); } const agents = members.length === 0 ? null : [ resolve( msg("{count, plural, one {{count} agent} other {{count} agents}}", { count: members.length, }), ), ...(["working", "done", "failed", "stopped"] as const) .filter((key) => counts.has(key)) .map((key) => resolve(WORKFLOW_AGENT_COUNTS[key], { count: counts.get(key)! })), ].join(" ยท "); return { title, description: opening.description !== null && opening.description !== title ? opening.description : null, agents, }; }