Skip to content

Commit b985d5a

Browse files
authored
feat: stream live subagent progress in task events (#121549)
* feat(tasks): stream live subagent activity * fix(tasks): correlate edit activity from start events * fix(gateway): sanitize live task activity * test(reply): align custody harnesses with lifecycle * fix(outbound): preserve post-send recovery evidence * fix(types): align reply harnesses with current contracts * fix(tasks): preserve activity liveness and SDK parity * test(sdk): avoid unsafe task summary assertion * chore(contracts): refresh Plugin SDK API baseline
1 parent b6b937d commit b985d5a

23 files changed

Lines changed: 842 additions & 51 deletions

‎apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9651,6 +9651,8 @@ public struct TaskSummary: Codable, Sendable {
96519651
public let endedat: AnyCodable?
96529652
public let toolusecount: Int?
96539653
public let lasttoolname: String?
9654+
public let lastactivity: String?
9655+
public let diffstat: [String: AnyCodable]?
96549656
public let progresssummary: String?
96559657
public let terminalsummary: String?
96569658
public let error: String?
@@ -9680,6 +9682,8 @@ public struct TaskSummary: Codable, Sendable {
96809682
endedat: AnyCodable? = nil,
96819683
toolusecount: Int? = nil,
96829684
lasttoolname: String? = nil,
9685+
lastactivity: String? = nil,
9686+
diffstat: [String: AnyCodable]? = nil,
96839687
progresssummary: String? = nil,
96849688
terminalsummary: String? = nil,
96859689
error: String? = nil,
@@ -9708,6 +9712,8 @@ public struct TaskSummary: Codable, Sendable {
97089712
self.endedat = endedat
97099713
self.toolusecount = toolusecount
97109714
self.lasttoolname = lasttoolname
9715+
self.lastactivity = lastactivity
9716+
self.diffstat = diffstat
97119717
self.progresssummary = progresssummary
97129718
self.terminalsummary = terminalsummary
97139719
self.error = error
@@ -9738,6 +9744,8 @@ public struct TaskSummary: Codable, Sendable {
97389744
case endedat = "endedAt"
97399745
case toolusecount = "toolUseCount"
97409746
case lasttoolname = "lastToolName"
9747+
case lastactivity = "lastActivity"
9748+
case diffstat = "diffStat"
97419749
case progresssummary = "progressSummary"
97429750
case terminalsummary = "terminalSummary"
97439751
case error

‎docs/.generated/plugin-sdk-api-baseline.jsonl‎

Lines changed: 18 additions & 18 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { Value } from "typebox/value";
2+
import { describe, expect, it } from "vitest";
3+
import { TaskSummarySchema } from "./tasks.js";
4+
5+
describe("TaskSummarySchema", () => {
6+
it("accepts bounded live subagent progress and keeps diff stats closed", () => {
7+
const summary = {
8+
id: "task-1",
9+
status: "running",
10+
lastActivity: "Updating the gateway task ledger",
11+
diffStat: { files: 3, added: 12, removed: 4 },
12+
};
13+
14+
expect(Value.Check(TaskSummarySchema, summary)).toBe(true);
15+
expect(Value.Check(TaskSummarySchema, { ...summary, lastActivity: "x".repeat(201) })).toBe(
16+
false,
17+
);
18+
expect(
19+
Value.Check(TaskSummarySchema, {
20+
...summary,
21+
diffStat: { ...summary.diffStat, removed: -1 },
22+
}),
23+
).toBe(false);
24+
expect(
25+
Value.Check(TaskSummarySchema, {
26+
...summary,
27+
diffStat: { ...summary.diffStat, unchanged: 8 },
28+
}),
29+
).toBe(false);
30+
});
31+
});

‎packages/gateway-protocol/src/schema/tasks.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import type { Static } from "typebox";
33
import { Type } from "typebox";
44
import { closedObject } from "./closed-object.js";
55
import { NonEmptyString } from "./primitives.js";
6+
import { withSince } from "./since.js";
67

78
/**
89
* Task ledger protocol schemas.
@@ -31,6 +32,14 @@ const TaskDeliveryStatusSchema = Type.Union([
3132
Type.Literal("not_applicable"),
3233
]);
3334
const TaskTerminalOutcomeSchema = Type.Union([Type.Literal("succeeded"), Type.Literal("blocked")]);
35+
const TaskDiffStatSchema = withSince(
36+
"2026.8",
37+
closedObject({
38+
files: Type.Integer({ minimum: 0 }),
39+
added: Type.Integer({ minimum: 0 }),
40+
removed: Type.Integer({ minimum: 0 }),
41+
}),
42+
);
3443

3544
/** Public task summary returned by task list/get/cancel responses. */
3645
export const TaskSummarySchema = closedObject({
@@ -54,6 +63,8 @@ export const TaskSummarySchema = closedObject({
5463
endedAt: Type.Optional(TimestampSchema),
5564
toolUseCount: Type.Optional(Type.Integer({ minimum: 0 })),
5665
lastToolName: Type.Optional(Type.String()),
66+
lastActivity: Type.Optional(withSince("2026.8", Type.String({ maxLength: 200 }))),
67+
diffStat: Type.Optional(TaskDiffStatSchema),
5768
progressSummary: Type.Optional(Type.String()),
5869
terminalSummary: Type.Optional(Type.String()),
5970
error: Type.Optional(Type.String()),

‎packages/sdk/src/index.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import type {
66
GatewayRequestOptions,
77
OpenClawEvent,
88
OpenClawTransport,
9+
TaskSummary,
910
} from "./types.js";
1011

1112
type RequestCall = {
@@ -561,6 +562,8 @@ describe("OpenClaw SDK", () => {
561562
title: "Investigate issue",
562563
runId: "run_123",
563564
sessionKey: "agent:main:main",
565+
lastActivity: "Editing the registry",
566+
diffStat: { files: 2, added: 12, removed: 3 },
564567
},
565568
],
566569
},
@@ -569,6 +572,8 @@ describe("OpenClaw SDK", () => {
569572
id: "task_123",
570573
status: "running",
571574
title: "Investigate issue",
575+
lastActivity: "Running focused tests",
576+
diffStat: { files: 2, added: 12, removed: 3 },
572577
},
573578
},
574579
"tasks.cancel": {
@@ -592,13 +597,21 @@ describe("OpenClaw SDK", () => {
592597
title: "Investigate issue",
593598
runId: "run_123",
594599
sessionKey: "agent:main:main",
600+
lastActivity: "Editing the registry",
601+
diffStat: { files: 2, added: 12, removed: 3 },
595602
},
596603
]);
604+
const listedTask: TaskSummary | undefined = taskList.tasks[0];
605+
expect(listedTask).toBeDefined();
606+
expect(listedTask?.lastActivity).toBe("Editing the registry");
607+
expect(listedTask?.diffStat).toEqual({ files: 2, added: 12, removed: 3 });
597608
const taskGet = await oc.tasks.get("task_123");
598609
expect(taskGet.task).toEqual({
599610
id: "task_123",
600611
status: "running",
601612
title: "Investigate issue",
613+
lastActivity: "Running focused tests",
614+
diffStat: { files: 2, added: 12, removed: 3 },
602615
});
603616
const taskCancel = await oc.tasks.cancel("task_123", { reason: "user stopped task" });
604617
expect(taskCancel.found).toBe(true);

‎packages/sdk/src/types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,8 @@ export type TaskSummary = {
195195
startedAt?: RunTimestamp;
196196
endedAt?: RunTimestamp;
197197
progressSummary?: string;
198+
lastActivity?: string;
199+
diffStat?: { files: number; added: number; removed: number };
198200
terminalSummary?: string;
199201
error?: string;
200202
};

‎src/agents/cli-runner/execute-events.tool-result-args.test.ts‎

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
// CLI backends report a tool result without repeating the request, so the
2-
// terminal progress event has to carry the args the tool started with.
1+
// Correlated CLI tool results already carry their started args; display-only
2+
// results must not duplicate that potentially large payload.
33
import { describe, expect, it, vi } from "vitest";
44
import { type AgentEventRuntimePayload, onAgentEvent } from "../../infra/agent-events.js";
55
import { createCliEventHandlers } from "./execute-events.js";
@@ -66,7 +66,7 @@ function collectToolEvents(runId: string): {
6666
}
6767

6868
describe("cli tool result events", () => {
69-
it("carries the started args into the terminal event", () => {
69+
it("keeps correlated result args without adding them to display results", () => {
7070
const runId = "run-tool-result-args";
7171
const handlers = createCliEventHandlers({
7272
context: buildContext(runId),
@@ -88,10 +88,32 @@ describe("cli tool result events", () => {
8888
isError: true,
8989
result: "bash: nope-not-a-command: command not found",
9090
});
91+
handlers.emitCliDisplayToolUseStart({
92+
toolCallId: "call-2",
93+
name: "write",
94+
kind: "tool_use",
95+
args: { path: "note.txt", content: "hello" },
96+
});
97+
handlers.emitCliDisplayToolResult({
98+
toolCallId: "call-2",
99+
name: "write",
100+
isError: false,
101+
result: "wrote note.txt",
102+
});
103+
// The display result also releases correlation state for this call id.
104+
handlers.emitCliToolResult({
105+
toolCallId: "call-2",
106+
name: "write",
107+
isError: false,
108+
result: "duplicate terminal",
109+
});
91110

92-
const result = events.find((event) => event.data.phase === "result");
93-
expect(result?.data.args).toEqual({ command: "nope-not-a-command" });
94-
expect(result?.data.isError).toBe(true);
111+
const results = events.filter((event) => event.data.phase === "result");
112+
expect(results[0]?.data.args).toEqual({ command: "nope-not-a-command" });
113+
expect(results[0]?.data.isError).toBe(true);
114+
expect(results[1]?.data.args).toBeUndefined();
115+
expect(results[1]?.data.isError).toBe(false);
116+
expect(results[2]?.data.args).toBeUndefined();
95117
} finally {
96118
dispose();
97119
}

‎src/agents/cli-runner/execute-events.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ export function createCliEventHandlers(params: {
128128
toolCallId: event.toolCallId,
129129
isError: event.isError,
130130
result: sanitizeToolResult(event.result),
131-
...(startedArgs ? { args: startedArgs } : {}),
131+
...(startedArgs ? { args: sanitizeToolArgs(startedArgs) } : {}),
132132
...(resultContentSource ? { resultContentSource } : {}),
133133
},
134134
});
@@ -165,6 +165,7 @@ export function createCliEventHandlers(params: {
165165
observedCliActivity = true;
166166
recordToolResult(event);
167167
if (emitLiveEvents) {
168+
toolArgsByCallId.delete(event.toolCallId);
168169
emitAgentEvent({
169170
runId: runParams.runId,
170171
stream: "tool",

‎src/agents/embedded-agent-live-edit-diff.ts‎

Lines changed: 3 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
import { parseStreamingJson } from "@openclaw/ai/internal/runtime";
22
import { normalizeLowercaseStringOrEmpty } from "@openclaw/normalization-core/string-coerce";
3+
import { resolveFileMutationToolName, type FileMutationToolName } from "./tool-mutation-names.js";
34

45
const LIVE_EDIT_DIFF_MIN_INTERVAL_MS = 250;
56
const LIVE_EDIT_DIFF_MAX_PARTIAL_JSON_CHARS = 1024 * 1024;
67
const LIVE_EDIT_DIFF_MAX_TRACKED_CALLS = 64;
78

8-
type LiveEditToolKind = "write" | "edit" | "patch";
9-
109
type LiveEditDiffProgressState = {
1110
added: number;
1211
removed: number;
@@ -21,20 +20,6 @@ type LiveEditDiffProgress = {
2120
diff: { added: number; removed: number };
2221
};
2322

24-
/** Classify the canonical file tools shared by live progress and patch summaries. */
25-
export function resolveLiveEditToolKind(toolName: string): LiveEditToolKind | undefined {
26-
switch (normalizeLowercaseStringOrEmpty(toolName)) {
27-
case "write":
28-
return "write";
29-
case "edit":
30-
return "edit";
31-
case "apply_patch":
32-
return "patch";
33-
default:
34-
return undefined;
35-
}
36-
}
37-
3823
function countNewlines(value: unknown): number {
3924
if (typeof value !== "string") {
4025
return 0;
@@ -80,7 +65,7 @@ function countPatchLines(patch: unknown): { added: number; removed: number } {
8065
}
8166

8267
function countLiveEditDiff(
83-
kind: LiveEditToolKind,
68+
kind: FileMutationToolName,
8469
args: Record<string, unknown>,
8570
): { added: number; removed: number } {
8671
if (kind === "write") {
@@ -146,7 +131,7 @@ export function updateLiveEditDiffProgress(
146131
const block = readToolCallBlock(event);
147132
const toolCallId = typeof block?.id === "string" ? block.id : "";
148133
const name = typeof block?.name === "string" ? block.name : "";
149-
const kind = resolveLiveEditToolKind(name);
134+
const kind = resolveFileMutationToolName(name);
150135
const partialJson = typeof block?.partialJson === "string" ? block.partialJson : "";
151136
if (!toolCallId || !kind || !partialJson) {
152137
return undefined;

‎src/agents/embedded-agent-subscribe.handlers.tools.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1610,7 +1610,7 @@ describe("handleToolExecutionEnd mutating failure recovery", () => {
16101610
});
16111611

16121612
it("snapshots hook-adjusted args before result middleware can mutate them", async () => {
1613-
const { ctx } = createTestContext();
1613+
const { ctx, onAgentEvent } = createTestContext();
16141614
const toolCallId = "tool-cron-mutable-adjusted-args";
16151615
const executedArgs = {
16161616
action: "add",
@@ -1636,6 +1636,10 @@ describe("handleToolExecutionEnd mutating failure recovery", () => {
16361636
hadPotentialSideEffects: true,
16371637
});
16381638
expect(ctx.state.successfulCronAdds).toBe(1);
1639+
const resultEvent = onAgentEvent.mock.calls.find(
1640+
([event]) => event.stream === "tool" && event.data.phase === "result",
1641+
)?.[0];
1642+
expect(resultEvent?.data).not.toHaveProperty("args");
16391643
});
16401644

16411645
it("uses hook-adjusted message arguments for delivery telemetry", async () => {

0 commit comments

Comments
 (0)