Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GrokAcpSubagents.ts

593 lines19.4 KB

1import type { RuntimeTaskStatus } from "@t3tools/contracts";
2import * as Schema from "effect/Schema";
3​
4/**
5 * Pure mapping of Grok Build x.ai session notifications onto T3's shared
6 * task.* surface. Claude stamps workflow members with parentAgentId +
7 * timelineBypass and a stable slot id; Codex does the same for collab
8 * children. Grok must not invent a third shape.
9 *
10 * Standalone `agent()` spawns are direct subagents: they must not set
11 * parentAgentId to the parent ACP session, or the Agents fold treats them
12 * as workflow members of a coordinator that does not exist.
13 */
14​
15export const GROK_SESSION_NOTIFICATION_METHODS = [
16 "x.ai/session_notification",
17 "_x.ai/session_notification",
18 "x.ai/session/update",
19 "_x.ai/session/update",
20] as const;
21​
22export type GrokSessionNotificationMethod = (typeof GROK_SESSION_NOTIFICATION_METHODS)[number];
23​
24export const XAiSessionNotification = Schema.Unknown;
25export type XAiSessionNotification = typeof XAiSessionNotification.Type;
26​
27export interface GrokWorkflowPhase {
28 readonly title: string;
29 readonly state: string;
31​
32export interface GrokWorkflowAgent {
33 readonly agentId: string;
34 readonly label: string;
35 readonly phase: string | undefined;
36 readonly model: string | undefined;
37 readonly state: string;
38 readonly tokensUsed: number;
39 readonly durationMs: number;
41​
42export interface GrokWorkflowUpdated {
43 readonly runId: string;
44 readonly revision: number;
45 readonly name: string;
46 readonly objective: string;
47 readonly status: string;
48 readonly phases: ReadonlyArray<GrokWorkflowPhase>;
49 readonly currentPhase: string | undefined;
50 readonly agentBudget: number | undefined;
51 readonly agentsUsed: number | undefined;
52 readonly elapsedMs: number | undefined;
53 readonly activeAgents: number | undefined;
54 readonly currentAgentLabel: string | undefined;
55 readonly agents: ReadonlyArray<GrokWorkflowAgent>;
56 readonly pauseMessage: string | undefined;
57 readonly resultSummary: string | undefined;
59​
60export interface GrokSubagentUpdate {
61 readonly kind: "spawned" | "progress" | "finished";
62 readonly subagentId: string;
63 readonly childSessionId: string | undefined;
64 readonly role: string | undefined;
65 readonly description: string | undefined;
66 readonly model: string | undefined;
67 readonly status: string | undefined;
68 readonly error: string | undefined;
69 readonly tokensUsed: number | undefined;
70 readonly durationMs: number | undefined;
71 readonly turnCount: number | undefined;
72 readonly toolCallCount: number | undefined;
73 readonly lastToolName: string | undefined;
74 readonly output: string | undefined;
76​
77export interface GrokTypedUsageSnapshot {
78 readonly totalTokens: number;
79 readonly durationMs?: number;
80 readonly toolUses?: number;
82​
83export interface GrokSubagentTrackState {
84 readonly seenRunIds: ReadonlySet<string>;
85 readonly completedRunIds: ReadonlySet<string>;
86 readonly seenMemberIds: ReadonlySet<string>;
87 readonly completedMemberIds: ReadonlySet<string>;
88 readonly memberFingerprints: ReadonlyMap<string, string>;
89 readonly seenSubagentIds: ReadonlySet<string>;
90 readonly completedSubagentIds: ReadonlySet<string>;
91 /** Last published usage per task id so a tool-only tick cannot zero tokens. */
92 readonly usageByTaskId: ReadonlyMap<string, GrokTypedUsageSnapshot>;
94​
95export function emptyGrokSubagentTrackState(): GrokSubagentTrackState {
96 return {
97 seenRunIds: new Set(),
98 completedRunIds: new Set(),
99 seenMemberIds: new Set(),
100 completedMemberIds: new Set(),
101 memberFingerprints: new Map(),
102 seenSubagentIds: new Set(),
103 completedSubagentIds: new Set(),
104 usageByTaskId: new Map(),
105 };
107​
108export interface GrokTaskEventSpec {
109 readonly type: "task.started" | "task.progress" | "task.completed";
110 readonly payload: Record<string, unknown>;
112​
113function asRecord(value: unknown): Record<string, unknown> | undefined {
114 return typeof value === "object" && value !== null && !Array.isArray(value)
115 ? (value as Record<string, unknown>)
116 : undefined;
118​
119function readString(value: unknown): string | undefined {
120 return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
122​
123function nonNegativeInt(value: unknown): number | undefined {
124 if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
125 return undefined;
126 }
127 return Math.trunc(value);
129​
130function sessionUpdateTag(update: Record<string, unknown>): string | undefined {
131 return readString(update.sessionUpdate) ?? readString(update.session_update);
133​
134function unwrapSessionUpdate(payload: unknown): Record<string, unknown> | undefined {
135 const envelope = asRecord(payload);
136 if (!envelope) {
137 return undefined;
138 }
139 const nestedParams = asRecord(envelope.params);
140 return asRecord(envelope.update) ?? asRecord(nestedParams?.update) ?? envelope;
142​
143export function parseXAiWorkflowUpdated(payload: unknown): GrokWorkflowUpdated | undefined {
144 const update = unwrapSessionUpdate(payload);
145 if (!update) {
146 return undefined;
147 }
148 const tag = sessionUpdateTag(update);
149 if (tag !== undefined && tag !== "workflow_updated" && tag !== "WorkflowUpdated") {
150 return undefined;
151 }
152 const runId = readString(update.run_id) ?? readString(update.runId);
153 const name = readString(update.name);
154 if (runId === undefined || name === undefined) {
155 return undefined;
156 }
157 if (
158 tag === undefined &&
159 (readString(update.status) === undefined || !Array.isArray(update.phases))
160 ) {
161 return undefined;
162 }
163 const phases = Array.isArray(update.phases)
164 ? update.phases.flatMap((entry): ReadonlyArray<GrokWorkflowPhase> => {
165 const record = asRecord(entry);
166 const title = readString(record?.title);
167 const state = readString(record?.state);
168 return title && state ? [{ title, state }] : [];
169 })
170 : [];
171 const agents = Array.isArray(update.agents)
172 ? update.agents.flatMap((entry): ReadonlyArray<GrokWorkflowAgent> => {
173 const record = asRecord(entry);
174 const agentId = readString(record?.agent_id) ?? readString(record?.agentId);
175 const state = readString(record?.state);
176 if (agentId === undefined || state === undefined) {
177 return [];
178 }
179 return [
180 {
181 agentId,
182 label: readString(record?.label) ?? agentId,
183 phase: readString(record?.phase),
184 model: readString(record?.model),
185 state,
186 tokensUsed: nonNegativeInt(record?.tokens_used ?? record?.tokensUsed) ?? 0,
187 durationMs: nonNegativeInt(record?.duration_ms ?? record?.durationMs) ?? 0,
188 },
189 ];
190 })
191 : [];
192 return {
193 runId,
194 revision: nonNegativeInt(update.revision) ?? 0,
195 name,
196 objective: readString(update.objective) ?? "",
197 status: readString(update.status) ?? "active",
198 phases,
199 currentPhase: readString(update.current_phase) ?? readString(update.currentPhase),
200 agentBudget: nonNegativeInt(update.agent_budget ?? update.agentBudget),
201 agentsUsed: nonNegativeInt(update.agents_used ?? update.agentsUsed),
202 elapsedMs: nonNegativeInt(update.elapsed_ms ?? update.elapsedMs),
203 activeAgents: nonNegativeInt(update.active_agents ?? update.activeAgents),
204 currentAgentLabel:
205 readString(update.current_agent_label) ?? readString(update.currentAgentLabel),
206 agents,
207 pauseMessage: readString(update.pause_message) ?? readString(update.pauseMessage),
208 resultSummary: readString(update.result_summary) ?? readString(update.resultSummary),
209 };
211​
212export function parseXAiSubagentUpdate(payload: unknown): GrokSubagentUpdate | undefined {
213 const update = unwrapSessionUpdate(payload);
214 if (!update) {
215 return undefined;
216 }
217 const tag = sessionUpdateTag(update);
218 const kind =
219 tag === "subagent_spawned" || tag === "SubagentSpawned"
220 ? "spawned"
221 : tag === "subagent_progress" || tag === "SubagentProgress"
222 ? "progress"
223 : tag === "subagent_finished" || tag === "SubagentFinished"
224 ? "finished"
225 : undefined;
226 if (kind === undefined) {
227 return undefined;
228 }
229 const subagentId = readString(update.subagent_id) ?? readString(update.subagentId);
230 if (subagentId === undefined) {
231 return undefined;
232 }
233 return {
234 kind,
235 subagentId,
236 childSessionId: readString(update.child_session_id) ?? readString(update.childSessionId),
237 role:
238 readString(update.subagent_type) ??
239 readString(update.subagentType) ??
240 readString(update.agent_type) ??
241 readString(update.agentType) ??
242 readString(update.role),
243 description:
244 readString(update.description) ?? readString(update.label) ?? readString(update.title),
245 model: readString(update.model),
246 status: readString(update.status),
247 error: readString(update.error),
248 tokensUsed: nonNegativeInt(update.tokens_used ?? update.tokensUsed),
249 durationMs: nonNegativeInt(update.duration_ms ?? update.durationMs),
250 turnCount: nonNegativeInt(update.turn_count ?? update.turnCount ?? update.turns),
251 toolCallCount: nonNegativeInt(
252 update.tool_call_count ?? update.toolCallCount ?? update.tool_calls ?? update.toolCalls,
253 ),
254 lastToolName:
255 readString(update.last_tool_name) ??
256 readString(update.lastToolName) ??
257 readString(update.tool_name) ??
258 readString(update.toolName),
259 output: readString(update.output) ?? readString(update.summary),
260 };
262​
263export function grokWorkflowRunStatus(status: string): RuntimeTaskStatus {
264 switch (status) {
265 case "active":
266 return "running";
267 case "complete":
268 return "completed";
269 case "failed":
270 return "failed";
271 case "cancelled":
272 case "interrupted":
273 case "cleared":
274 return "cancelled";
275 default:
276 return "idle";
277 }
279​
280export function grokWorkflowAgentStatus(state: string): RuntimeTaskStatus {
281 switch (state) {
282 case "queued":
283 case "pending":
284 return "pending";
285 case "running":
286 case "start":
287 return "running";
288 case "done":
289 case "completed":
290 return "completed";
291 case "failed":
292 case "error":
293 return "failed";
294 case "cancelled":
295 return "cancelled";
296 default:
297 return "running";
298 }
300​
301export function grokWorkflowRunIsTerminal(status: string): boolean {
302 return (
303 status === "complete" ||
304 status === "failed" ||
305 status === "cancelled" ||
306 status === "interrupted" ||
307 status === "cleared"
308 );
310​
311export function grokWorkflowAgentIsTerminal(state: string): boolean {
312 return (
313 state === "done" ||
314 state === "completed" ||
315 state === "failed" ||
316 state === "error" ||
317 state === "cancelled"
318 );
320​
321export function grokWorkflowMemberTaskId(runId: string, agentId: string): string {
322 return `${runId}:wf:${agentId}`;
324​
325function memberFingerprint(agent: GrokWorkflowAgent, status: RuntimeTaskStatus): string {
326 return [
327 status,
328 agent.state,
329 agent.label,
330 agent.model ?? "",
331 agent.phase ?? "",
332 agent.tokensUsed,
333 agent.durationMs,
334 ].join("\u001f");
336​
337function runCompletedStatus(status: string): "completed" | "failed" | "stopped" {
338 if (status === "failed") return "failed";
339 if (status === "complete") return "completed";
340 return "stopped";
342​
343function agentCompletedStatus(state: string): "completed" | "failed" | "stopped" {
344 if (state === "failed" || state === "error") return "failed";
345 if (state === "cancelled") return "stopped";
346 return "completed";
348​
349function mergeTypedUsageFromCounts(
350 input: {
351 readonly tokensUsed?: number | undefined;
352 readonly durationMs?: number | undefined;
353 readonly toolCallCount?: number | undefined;
354 },
355 previous: GrokTypedUsageSnapshot | undefined,
356): GrokTypedUsageSnapshot | undefined {
357 if (
358 input.tokensUsed === undefined &&
359 input.durationMs === undefined &&
360 input.toolCallCount === undefined
361 ) {
362 return previous;
363 }
364 // RuntimeTaskUsage requires totalTokens. A later tool/duration-only tick
365 // must reuse the last known count; `?? 0` would replace the task-usage row.
366 const durationMs = input.durationMs ?? previous?.durationMs;
367 const toolUses = input.toolCallCount ?? previous?.toolUses;
368 return {
369 totalTokens: input.tokensUsed ?? previous?.totalTokens ?? 0,
370 ...(durationMs !== undefined ? { durationMs } : {}),
371 ...(toolUses !== undefined ? { toolUses } : {}),
372 };
374​
375function subagentTitle(update: GrokSubagentUpdate): string {
376 return update.description ?? update.role ?? update.subagentId;
378​
379export function applyGrokWorkflowUpdate(
380 state: GrokSubagentTrackState,
381 update: GrokWorkflowUpdated,
382): { readonly state: GrokSubagentTrackState; readonly events: ReadonlyArray<GrokTaskEventSpec> } {
383 const seenRunIds = new Set(state.seenRunIds);
384 const completedRunIds = new Set(state.completedRunIds);
385 const seenMemberIds = new Set(state.seenMemberIds);
386 const completedMemberIds = new Set(state.completedMemberIds);
387 const memberFingerprints = new Map(state.memberFingerprints);
388 const usageByTaskId = new Map(state.usageByTaskId);
389 const events: Array<GrokTaskEventSpec> = [];
390​
391 const phases = update.phases.map((phase, index) => ({ index, title: phase.title }));
392 const currentPhaseIndex = update.currentPhase
393 ? update.phases.findIndex((phase) => phase.title === update.currentPhase)
394 : -1;
395 const runStatus = grokWorkflowRunStatus(update.status);
396 const runSeen = seenRunIds.has(update.runId);
397 if (!runSeen) {
398 seenRunIds.add(update.runId);
399 events.push({
400 type: "task.started",
401 payload: {
402 taskId: update.runId,
403 description: update.objective || update.name,
404 taskType: "local_workflow",
405 workflowName: update.name,
406 title: update.name,
407 ...(phases.length > 0 ? { phases } : {}),
408 ...(currentPhaseIndex >= 0 ? { phaseIndex: currentPhaseIndex } : {}),
409 ...(update.currentPhase ? { phaseTitle: update.currentPhase } : {}),
410 runHandles: { runId: update.runId },
411 },
412 });
413 } else if (!completedRunIds.has(update.runId)) {
414 events.push({
415 type: "task.progress",
416 payload: {
417 taskId: update.runId,
418 description: update.objective || update.name,
419 summary: update.currentAgentLabel ?? update.currentPhase ?? update.status,
420 status: runStatus,
421 taskType: "local_workflow",
422 workflowName: update.name,
423 title: update.name,
424 ...(phases.length > 0 ? { phases } : {}),
425 ...(currentPhaseIndex >= 0 ? { phaseIndex: currentPhaseIndex } : {}),
426 ...(update.currentPhase ? { phaseTitle: update.currentPhase } : {}),
427 runHandles: { runId: update.runId },
428 },
429 });
430 }
431​
432 if (grokWorkflowRunIsTerminal(update.status) && !completedRunIds.has(update.runId)) {
433 completedRunIds.add(update.runId);
434 events.push({
435 type: "task.completed",
436 payload: {
437 taskId: update.runId,
438 status: runCompletedStatus(update.status),
439 summary: update.resultSummary ?? update.pauseMessage ?? update.status,
440 taskType: "local_workflow",
441 workflowName: update.name,
442 title: update.name,
443 ...(phases.length > 0 ? { phases } : {}),
444 runHandles: { runId: update.runId },
445 },
446 });
447 }
448​
449 for (const [agentIndex, agent] of update.agents.entries()) {
450 const memberId = grokWorkflowMemberTaskId(update.runId, agent.agentId);
451 const status = grokWorkflowAgentStatus(agent.state);
452 const fingerprint = memberFingerprint(agent, status);
453 if (memberFingerprints.get(memberId) === fingerprint) {
454 continue;
455 }
456 memberFingerprints.set(memberId, fingerprint);
457 const memberSeen = seenMemberIds.has(memberId);
458 const linkage = {
459 taskId: memberId,
460 description: agent.label,
461 taskType: "subagent",
462 parentAgentId: update.runId,
463 title: agent.label,
464 workflowName: update.name,
465 ...(agent.model ? { model: agent.model } : {}),
466 ...(agent.phase ? { phaseTitle: agent.phase } : {}),
467 agentIndex,
468 timelineBypass: true,
469 };
470 if (!memberSeen) {
471 seenMemberIds.add(memberId);
472 events.push({ type: "task.started", payload: linkage });
473 }
474 const typedUsage = mergeTypedUsageFromCounts(
475 {
476 tokensUsed: agent.tokensUsed > 0 ? agent.tokensUsed : undefined,
477 durationMs: agent.durationMs > 0 ? agent.durationMs : undefined,
478 },
479 usageByTaskId.get(memberId),
480 );
481 if (typedUsage) {
482 usageByTaskId.set(memberId, typedUsage);
483 }
484 events.push({
485 type: "task.progress",
486 payload: {
487 ...linkage,
488 summary: agent.state,
489 status,
490 ...(typedUsage ? { typedUsage } : {}),
491 },
492 });
493 if (grokWorkflowAgentIsTerminal(agent.state) && !completedMemberIds.has(memberId)) {
494 completedMemberIds.add(memberId);
495 events.push({
496 type: "task.completed",
497 payload: {
498 ...linkage,
499 status: agentCompletedStatus(agent.state),
500 summary: agent.label,
501 ...(typedUsage ? { typedUsage } : {}),
502 },
503 });
504 }
505 }
506​
507 return {
508 state: {
509 ...state,
510 seenRunIds,
511 completedRunIds,
512 seenMemberIds,
513 completedMemberIds,
514 memberFingerprints,
515 usageByTaskId,
516 },
517 events,
518 };
520​
521export function applyGrokSubagentUpdate(
522 state: GrokSubagentTrackState,
523 update: GrokSubagentUpdate,
524): { readonly state: GrokSubagentTrackState; readonly events: ReadonlyArray<GrokTaskEventSpec> } {
525 const seenSubagentIds = new Set(state.seenSubagentIds);
526 const completedSubagentIds = new Set(state.completedSubagentIds);
527 const usageByTaskId = new Map(state.usageByTaskId);
528 const events: Array<GrokTaskEventSpec> = [];
529 const title = subagentTitle(update);
530 const typedUsage = mergeTypedUsageFromCounts(update, usageByTaskId.get(update.subagentId));
531 if (typedUsage) {
532 usageByTaskId.set(update.subagentId, typedUsage);
533 }
534 const linkage = {
535 taskId: update.subagentId,
536 description: title,
537 title,
538 taskType: "subagent",
539 role: update.role ?? "general-purpose",
540 ...(update.model ? { model: update.model } : {}),
541 ...(update.childSessionId ? { agentPath: update.childSessionId } : {}),
542 timelineBypass: true,
543 };
544​
545 if (update.kind === "spawned" && !seenSubagentIds.has(update.subagentId)) {
546 seenSubagentIds.add(update.subagentId);
547 events.push({ type: "task.started", payload: linkage });
548 } else if (update.kind === "progress") {
549 if (!seenSubagentIds.has(update.subagentId)) {
550 seenSubagentIds.add(update.subagentId);
551 events.push({ type: "task.started", payload: linkage });
552 }
553 if (!completedSubagentIds.has(update.subagentId)) {
554 events.push({
555 type: "task.progress",
556 payload: {
557 ...linkage,
558 status: "running",
559 summary: update.lastToolName ?? update.status ?? update.role ?? "running",
560 ...(update.lastToolName ? { lastToolName: update.lastToolName } : {}),
561 ...(typedUsage ? { typedUsage } : {}),
562 },
563 });
564 }
565 } else if (update.kind === "finished" && !completedSubagentIds.has(update.subagentId)) {
566 if (!seenSubagentIds.has(update.subagentId)) {
567 seenSubagentIds.add(update.subagentId);
568 events.push({ type: "task.started", payload: linkage });
569 }
570 completedSubagentIds.add(update.subagentId);
571 const finished = update.status ?? "completed";
572 events.push({
573 type: "task.completed",
574 payload: {
575 ...linkage,
576 status:
577 finished === "failed" ? "failed" : finished === "cancelled" ? "stopped" : "completed",
578 summary: update.error ?? update.output ?? finished,
579 ...(typedUsage ? { typedUsage } : {}),
580 },
581 });
582 }
583​
584 return {
585 state: {
586 ...state,
587 seenSubagentIds,
588 completedSubagentIds,
589 usageByTaskId,
590 },
591 events,
592 };