Skip to content

Commit ae49990

Browse files
Nonoswordobviyus
andauthored
fix(lobster): preserve cancelled approvals and output bounds (#130259)
Keep managed Lobster state aligned with rejected approvals and enforce the configured byte limit on the JSON returned to the model. Co-authored-by: Nonosword <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 0a068cf commit ae49990

6 files changed

Lines changed: 189 additions & 56 deletions

File tree

‎docs/tools/lobster.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -297,7 +297,7 @@ Run a workflow file with args:
297297
| `pipeline` | required | Inline pipeline string, or a path ending in `.lobster`/`.yaml`/`.yml`/`.json` for a workflow file. |
298298
| `cwd` | gateway cwd | Relative working directory; must resolve inside the gateway working directory (absolute paths are rejected). |
299299
| `timeoutMs` | `20000` | Aborts the run if exceeded. |
300-
| `maxStdoutBytes` | `512000` | Aborts the run if captured stdout or stderr exceeds this size. |
300+
| `maxStdoutBytes` | `512000` | Aborts if captured stdout, stderr, or the embedded JSON result exceeds this size. |
301301
| `argsJson` | - | JSON string of args for a workflow file (ignored for inline pipelines). |
302302

303303
### `resume`
@@ -320,7 +320,7 @@ Passing `flowControllerId` and `flowGoal` on `run` (or `flowId` and
320320
`flowExpectedRevision` on `resume`) drives the call through the plugin
321321
runtime's managed [Task Flow](/automation/taskflow) API instead of returning
322322
a bare envelope: OpenClaw creates or resumes a durable flow record, applies the
323-
Lobster envelope to it (`waiting` on approval, `succeeded`/`failed` on
323+
Lobster envelope to it (`waiting` on approval, `succeeded`/`failed`/`cancelled` on
324324
completion), and returns `{ ok, envelope, flow, mutation }`. This mode requires
325325
a bound Task Flow runtime and is intended for plugin/controller code that needs
326326
durable flow state across gateway restarts, not typical ad hoc agent use.
@@ -365,6 +365,7 @@ pointer to that state, not the full pipeline state.
365365
| ------------------------------------------------------------- | -------------------------------------------------------------------------------- |
366366
| `lobster runtime timed out` | Pipeline exceeded `timeoutMs`. Increase it or split the pipeline. |
367367
| `lobster stdout exceeded maxStdoutBytes` (or `stderr`) | Captured output exceeded the cap. Raise `maxStdoutBytes` or reduce output. |
368+
| `lobster runtime result exceeded maxStdoutBytes` | The JSON result exceeded the cap. Raise `maxStdoutBytes` or reduce output. |
368369
| `run --args-json must be valid JSON` | `argsJson` (workflow-file runs) failed to parse. Fix the JSON string. |
369370
| `lobster runtime failed` (or another `runtime_error` message) | The embedded runtime returned an error envelope. Check gateway logs for details. |
370371

‎extensions/lobster/src/lobster-runner.test.ts‎

Lines changed: 53 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,17 @@ import os from "node:os";
33
import path from "node:path";
44
// Lobster tests cover lobster runner plugin behavior.
55
import { toErrorObject as toLintErrorObject } from "openclaw/plugin-sdk/error-runtime";
6+
import { useAutoCleanupTempDirTracker } from "openclaw/plugin-sdk/test-env";
67
import { createRequireRecord } from "openclaw/plugin-sdk/test-fixtures";
78
import { afterEach, describe, expect, it, vi } from "vitest";
8-
import { createEmbeddedLobsterRunner, resolveLobsterCwd } from "./lobster-runner.js";
9+
import {
10+
createEmbeddedLobsterRunner,
11+
resolveLobsterCwd,
12+
type LobsterRunnerParams,
13+
} from "./lobster-runner.js";
914

1015
const requireRecord = createRequireRecord("record", "expected-label-record");
16+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
1117

1218
function requireFirstCallParam(calls: ReadonlyArray<readonly unknown[]>, label: string) {
1319
const call = calls[0];
@@ -82,6 +88,51 @@ describe("createEmbeddedLobsterRunner", () => {
8288
});
8389
});
8490

91+
it.each(["inline", "workflow", "resume"])(
92+
"bounds the model-visible result for an embedded %s request",
93+
async (requestKind) => {
94+
const runtimeResult = {
95+
ok: true,
96+
protocolVersion: 1,
97+
status: "ok" as const,
98+
output: Array.from({ length: 115 }, () => ({ a: 1 })),
99+
requiresApproval: null,
100+
requiresInput: null,
101+
};
102+
const runtime = {
103+
runToolRequest: vi.fn().mockResolvedValue(runtimeResult),
104+
resumeToolRequest: vi.fn().mockResolvedValue(runtimeResult),
105+
};
106+
const runner = createEmbeddedLobsterRunner({
107+
loadRuntime: vi.fn().mockResolvedValue(runtime),
108+
});
109+
const tempDir = tempDirs.make("openclaw-lobster-limit-");
110+
const workflowPath = path.join(tempDir, "workflow.lobster");
111+
await fs.writeFile(workflowPath, "steps: []\n", "utf8");
112+
const params: LobsterRunnerParams =
113+
requestKind === "resume"
114+
? {
115+
action: "resume",
116+
token: "resume-token",
117+
approve: false,
118+
cwd: tempDir,
119+
timeoutMs: 2000,
120+
maxStdoutBytes: 1024,
121+
}
122+
: {
123+
action: "run",
124+
pipeline: requestKind === "workflow" ? workflowPath : "exec --json=true echo bounded",
125+
cwd: tempDir,
126+
timeoutMs: 2000,
127+
maxStdoutBytes: 1024,
128+
};
129+
130+
await expect(runner.run(params)).rejects.toThrow(
131+
"lobster runtime result exceeded maxStdoutBytes",
132+
);
133+
},
134+
);
135+
85136
it.each([
86137
"exec --json=true cat data.json",
87138
"exec --json=true cat config.yaml",
@@ -495,7 +546,7 @@ describe("createEmbeddedLobsterRunner", () => {
495546
pipeline: "commands.list",
496547
cwd: process.cwd(),
497548
timeoutMs: 2000,
498-
maxStdoutBytes: 4096,
549+
maxStdoutBytes: 512_000,
499550
}),
500551
).resolves.toMatchObject({ ok: true, status: "ok" });
501552
});

‎extensions/lobster/src/lobster-runner.ts‎

Lines changed: 26 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -112,14 +112,17 @@ function createLimitedSink(maxBytes: number, label: "stdout" | "stderr") {
112112
});
113113
}
114114

115-
function normalizeEnvelope(envelope: EmbeddedToolEnvelope): Extract<LobsterEnvelope, { ok: true }> {
115+
function normalizeEnvelope(
116+
envelope: EmbeddedToolEnvelope,
117+
maxStdoutBytes: number,
118+
): Extract<LobsterEnvelope, { ok: true }> {
116119
if (!envelope.ok) {
117120
throw new Error(envelope.error?.message ?? "lobster runtime failed");
118121
}
119122
if (envelope.status === "needs_input") {
120123
throw new Error("Lobster input requests are not supported by the OpenClaw Lobster tool yet");
121124
}
122-
return {
125+
const normalized: Extract<LobsterEnvelope, { ok: true }> = {
123126
ok: true,
124127
status: envelope.status ?? "ok",
125128
output: Array.isArray(envelope.output) ? envelope.output : [],
@@ -137,6 +140,10 @@ function normalizeEnvelope(envelope: EmbeddedToolEnvelope): Extract<LobsterEnvel
137140
}
138141
: null,
139142
};
143+
if (Buffer.byteLength(JSON.stringify(normalized, null, 2), "utf8") > maxStdoutBytes) {
144+
throw new Error("lobster runtime result exceeded maxStdoutBytes");
145+
}
146+
return normalized;
140147
}
141148

142149
function isMissingPathError(error: unknown) {
@@ -229,6 +236,7 @@ export function createEmbeddedLobsterRunner(options?: {
229236
const runtime = await runtimePromise;
230237
return await withTimeout(params.timeoutMs, async (signal) => {
231238
const ctx = createEmbeddedToolContext(params, signal);
239+
let envelope: EmbeddedToolEnvelope;
232240

233241
if (params.action === "run") {
234242
const pipeline = params.pipeline?.trim() ?? "";
@@ -247,29 +255,27 @@ export function createEmbeddedLobsterRunner(options?: {
247255
throw new Error("run --args-json must be valid JSON");
248256
}
249257
}
250-
return normalizeEnvelope(await runtime.runToolRequest({ filePath, args, ctx }));
258+
envelope = await runtime.runToolRequest({ filePath, args, ctx });
259+
} else {
260+
envelope = await runtime.runToolRequest({ pipeline, ctx });
251261
}
252-
253-
return normalizeEnvelope(await runtime.runToolRequest({ pipeline, ctx }));
254-
}
255-
256-
const token = params.token?.trim() ?? "";
257-
const approvalId = params.approvalId?.trim() ?? "";
258-
if (!token && !approvalId) {
259-
throw new Error("token or approvalId required");
260-
}
261-
if (typeof params.approve !== "boolean") {
262-
throw new Error("approve required");
263-
}
264-
265-
return normalizeEnvelope(
266-
await runtime.resumeToolRequest({
262+
} else {
263+
const token = params.token?.trim() ?? "";
264+
const approvalId = params.approvalId?.trim() ?? "";
265+
if (!token && !approvalId) {
266+
throw new Error("token or approvalId required");
267+
}
268+
if (typeof params.approve !== "boolean") {
269+
throw new Error("approve required");
270+
}
271+
envelope = await runtime.resumeToolRequest({
267272
...(token ? { token } : {}),
268273
...(approvalId ? { approvalId } : {}),
269274
approved: params.approve,
270275
ctx,
271-
}),
272-
);
276+
});
277+
}
278+
return normalizeEnvelope(envelope, Math.max(1024, params.maxStdoutBytes));
273279
});
274280
},
275281
};

‎extensions/lobster/src/lobster-taskflow.test.ts‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Lobster tests cover lobster taskflow plugin behavior.
2+
import { createRuntimeTaskFlow } from "openclaw/plugin-sdk/plugin-test-runtime";
23
import { describe, expect, it, vi } from "vitest";
34
import type { LobsterRunner } from "./lobster-runner.js";
45
import { resumeManagedLobsterFlow, runManagedLobsterFlow } from "./lobster-taskflow.js";
@@ -25,6 +26,7 @@ function createRunFlowParams(
2526
): Parameters<typeof runManagedLobsterFlow>[0] {
2627
return {
2728
taskFlow,
29+
config: {},
2830
runner,
2931
runnerParams: {
3032
action: "run",
@@ -44,6 +46,7 @@ function createResumeFlowParams(
4446
): Parameters<typeof resumeManagedLobsterFlow>[0] {
4547
return {
4648
taskFlow,
49+
config: {},
4750
runner,
4851
flowId: "flow-1",
4952
expectedRevision: 4,
@@ -226,3 +229,70 @@ describe("resumeManagedLobsterFlow", () => {
226229
});
227230
});
228231
});
232+
233+
describe("cancelled managed Lobster flows", () => {
234+
it.each(["run", "resume"])(
235+
"persists a cancelled TaskFlow for a rejected Lobster %s",
236+
async (action) => {
237+
const taskFlow = createRuntimeTaskFlow().bindSession({
238+
sessionKey: `agent:main:lobster-cancel-${action}`,
239+
});
240+
const runner = createRunner({
241+
ok: true,
242+
status: "cancelled",
243+
output: [],
244+
requiresApproval: null,
245+
});
246+
let result;
247+
if (action === "run") {
248+
result = await runManagedLobsterFlow(createRunFlowParams(taskFlow, runner));
249+
} else {
250+
const waitingFlow = taskFlow.createManaged({
251+
controllerId: "tests/lobster",
252+
goal: "Resume Lobster workflow",
253+
status: "waiting",
254+
});
255+
result = await resumeManagedLobsterFlow({
256+
...createResumeFlowParams(taskFlow, runner),
257+
flowId: waitingFlow.flowId,
258+
expectedRevision: waitingFlow.revision,
259+
});
260+
}
261+
262+
if (!result.ok) {
263+
throw result.error;
264+
}
265+
expect(taskFlow.get(result.flow.flowId)?.status).toBe("cancelled");
266+
},
267+
);
268+
269+
it.each(["unsettled", "rejected"])(
270+
"does not finish or fail when TaskFlow cancellation is %s",
271+
async (outcome) => {
272+
const cancel =
273+
outcome === "unsettled"
274+
? vi.fn().mockResolvedValue({
275+
found: true,
276+
cancelled: false,
277+
reason: "One or more child tasks are still active.",
278+
tasks: [],
279+
})
280+
: vi.fn().mockRejectedValue(new Error("cancel transport error"));
281+
const taskFlow = createFakeTaskFlow({ cancel });
282+
const runner = createRunner({
283+
ok: true,
284+
status: "cancelled",
285+
output: [],
286+
requiresApproval: null,
287+
});
288+
289+
const result = expectManagedFlowFailure(
290+
await resumeManagedLobsterFlow(createResumeFlowParams(taskFlow, runner)),
291+
);
292+
293+
expect(result.error.message).toMatch(/cancellation failed|cancel transport error/u);
294+
expect(taskFlow.finish).not.toHaveBeenCalled();
295+
expect(taskFlow.fail).not.toHaveBeenCalled();
296+
},
297+
);
298+
});

‎extensions/lobster/src/lobster-taskflow.ts‎

Lines changed: 35 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@ export type BoundTaskFlow = ReturnType<
1717
>;
1818

1919
type FlowRecord = NonNullable<ReturnType<BoundTaskFlow["tryCreateManaged"]>>;
20-
type MutationResult = ReturnType<BoundTaskFlow["setWaiting"]>;
20+
type MutationResult =
21+
| ReturnType<BoundTaskFlow["setWaiting"]>
22+
| Awaited<ReturnType<BoundTaskFlow["cancel"]>>;
2123

2224
type LobsterApprovalWaitState = {
2325
kind: "lobster_approval";
@@ -29,6 +31,7 @@ type LobsterApprovalWaitState = {
2931

3032
type RunManagedLobsterFlowParams = {
3133
taskFlow: BoundTaskFlow;
34+
config: OpenClawPluginApi["config"];
3235
runner: LobsterRunner;
3336
runnerParams: LobsterRunnerParams;
3437
controllerId: string;
@@ -40,6 +43,7 @@ type RunManagedLobsterFlowParams = {
4043

4144
type ResumeManagedLobsterFlowParams = {
4245
taskFlow: BoundTaskFlow;
46+
config: OpenClawPluginApi["config"];
4347
runner: LobsterRunner;
4448
runnerParams: LobsterRunnerParams & {
4549
action: "resume";
@@ -117,46 +121,45 @@ function buildApprovalWaitState(envelope: Extract<LobsterEnvelope, { ok: true }>
117121
} satisfies LobsterApprovalWaitState;
118122
}
119123

120-
function applyEnvelopeToFlow(params: {
121-
taskFlow: BoundTaskFlow;
122-
flow: FlowRecord;
123-
envelope: LobsterEnvelope;
124-
waitingStep: string;
125-
}): MutationResult {
126-
const { taskFlow, flow, envelope, waitingStep } = params;
127-
const flowMutation = { flowId: flow.flowId, expectedRevision: flow.revision };
128-
129-
if (!envelope.ok) {
130-
return taskFlow.fail(flowMutation);
131-
}
132-
133-
if (envelope.status === "needs_approval") {
134-
return taskFlow.setWaiting({
135-
...flowMutation,
136-
currentStep: waitingStep,
137-
waitJson: buildApprovalWaitState(envelope),
138-
});
139-
}
140-
141-
return taskFlow.finish(flowMutation);
142-
}
143-
144124
async function executeManagedLobsterFlow(
145-
params: Pick<RunManagedLobsterFlowParams, "taskFlow" | "runner" | "runnerParams" | "waitingStep">,
125+
params: Pick<
126+
RunManagedLobsterFlowParams,
127+
"taskFlow" | "config" | "runner" | "runnerParams" | "waitingStep"
128+
>,
146129
flow: FlowRecord,
147130
failureFlowId = flow.flowId,
148131
): Promise<ManagedLobsterFlowResult> {
149132
try {
150133
const envelope = await params.runner.run(params.runnerParams);
151-
const mutation = applyEnvelopeToFlow({
152-
taskFlow: params.taskFlow,
153-
flow,
154-
envelope,
155-
waitingStep: params.waitingStep ?? "await_lobster_approval",
156-
});
134+
if (envelope.ok && envelope.status === "cancelled") {
135+
try {
136+
const mutation = await params.taskFlow.cancel({ flowId: flow.flowId, cfg: params.config });
137+
return mutation.cancelled
138+
? { ok: true, envelope, flow, mutation }
139+
: {
140+
ok: false,
141+
flow,
142+
mutation,
143+
error: new Error(`TaskFlow cancellation failed: ${mutation.reason ?? "unknown"}`),
144+
};
145+
} catch (error) {
146+
const err = error instanceof Error ? error : new Error(String(error));
147+
return { ok: false, flow, error: err };
148+
}
149+
}
150+
const flowMutation = { flowId: flow.flowId, expectedRevision: flow.revision };
157151
if (!envelope.ok) {
152+
const mutation = params.taskFlow.fail(flowMutation);
158153
return { ok: false, flow, mutation, error: new Error(envelope.error.message) };
159154
}
155+
const mutation =
156+
envelope.status === "needs_approval"
157+
? params.taskFlow.setWaiting({
158+
...flowMutation,
159+
currentStep: params.waitingStep ?? "await_lobster_approval",
160+
waitJson: buildApprovalWaitState(envelope),
161+
})
162+
: params.taskFlow.finish(flowMutation);
160163
return { ok: true, envelope, flow, mutation };
161164
} catch (error) {
162165
const err = error instanceof Error ? error : new Error(String(error));

0 commit comments

Comments
 (0)