Skip to content

Commit b99b703

Browse files
committed
feat(worker): expose supervised terminal outcomes
1 parent de291a3 commit b99b703

7 files changed

Lines changed: 460 additions & 188 deletions

‎src/node-host/invoke-worker-supervisor.test.ts‎

Lines changed: 65 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -161,13 +161,17 @@ describe("node-host worker supervisor commands", () => {
161161
expect(payload).not.toHaveProperty("errorText");
162162
});
163163

164-
it("omits completed worker output from the durable wire receipt", async () => {
164+
it("returns completed worker output without internal process fields", async () => {
165165
const input = launchInput();
166-
const privatePath = "/private/workspaces/session-1/secret.txt";
166+
const resultJson = JSON.stringify({
167+
status: "completed",
168+
transcriptLeafId: "leaf-1",
169+
transcriptNextSeq: 2,
170+
});
167171
const receipt: NodeWorkerLaunchReceipt = {
168172
...fullReceipt(input),
169173
state: "completed",
170-
resultJson: JSON.stringify({ argv: ["worker", "--internal-worker-ipc"], privatePath }),
174+
resultJson,
171175
completedAtMs: 12,
172176
};
173177

@@ -177,10 +181,7 @@ describe("node-host worker supervisor commands", () => {
177181
supervisor: supervisorWith(receipt),
178182
});
179183

180-
const raw = result?.payloadJSON ?? "";
181-
expect(raw).not.toContain("argv");
182-
expect(raw).not.toContain(privatePath);
183-
expect(JSON.parse(raw)).toEqual({
184+
expect(JSON.parse(result?.payloadJSON ?? "{}")).toEqual({
184185
launchId: input.launchId,
185186
planHash: receipt.planHash,
186187
environmentId: input.descriptor.admission.environmentId,
@@ -189,6 +190,42 @@ describe("node-host worker supervisor commands", () => {
189190
placementGeneration: input.placementGeneration,
190191
runId: input.descriptor.assignment.runId,
191192
state: "completed",
193+
resultJson,
194+
});
195+
const payload = JSON.parse(result?.payloadJSON ?? "{}") as Record<string, unknown>;
196+
expect(payload).not.toHaveProperty("supervisor");
197+
expect(payload).not.toHaveProperty("worker");
198+
expect(payload).not.toHaveProperty("gatewayNamespace");
199+
expect(payload).not.toHaveProperty("descriptor");
200+
expect(payload).not.toHaveProperty("errorText");
201+
});
202+
203+
it("returns failed worker diagnostics without completed output", async () => {
204+
const input = launchInput();
205+
const receipt: NodeWorkerLaunchReceipt = {
206+
...fullReceipt(input),
207+
state: "failed",
208+
worker: null,
209+
errorText: "worker exited before completion",
210+
completedAtMs: 12,
211+
};
212+
213+
const { result } = await invokePrivate({
214+
command: NODE_WORKER_SUPERVISOR_STATUS_COMMAND,
215+
paramsJSON: JSON.stringify({ launchId: input.launchId }),
216+
supervisor: supervisorWith(receipt),
217+
});
218+
219+
expect(JSON.parse(result?.payloadJSON ?? "{}")).toEqual({
220+
launchId: input.launchId,
221+
planHash: receipt.planHash,
222+
environmentId: input.descriptor.admission.environmentId,
223+
sessionId: input.descriptor.admission.sessionId,
224+
ownerEpoch: input.descriptor.admission.ownerEpoch,
225+
placementGeneration: input.placementGeneration,
226+
runId: input.descriptor.assignment.runId,
227+
state: "failed",
228+
errorText: receipt.errorText,
192229
});
193230
});
194231

@@ -226,6 +263,27 @@ describe("node-host worker supervisor commands", () => {
226263
expect(mocks.cancel.mock.calls).toHaveLength(0);
227264
});
228265

266+
it("fails closed when a durable terminal receipt is inconsistent", async () => {
267+
const input = launchInput();
268+
const receipt: NodeWorkerLaunchReceipt = {
269+
...fullReceipt(input),
270+
state: "completed",
271+
resultJson: null,
272+
completedAtMs: 12,
273+
};
274+
275+
const { result } = await invokePrivate({
276+
command: NODE_WORKER_SUPERVISOR_STATUS_COMMAND,
277+
paramsJSON: JSON.stringify({ launchId: input.launchId }),
278+
supervisor: supervisorWith(receipt),
279+
});
280+
281+
expect(result).toMatchObject({
282+
ok: false,
283+
error: { code: "UNAVAILABLE", message: "node worker supervisor command failed" },
284+
});
285+
});
286+
229287
it("returns a bounded generic error without leaking supervisor details", async () => {
230288
const leaked = `/private/path/${"secret".repeat(2_000)}`;
231289
const supervisor = supervisorWith(fullReceipt());

‎src/node-host/node-worker-launch-store.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,11 @@ import {
1111
type OpenClawStateDatabaseOptions,
1212
} from "../state/openclaw-state-db.js";
1313
import { OPENCLAW_STATE_SCHEMA_SQL } from "../state/openclaw-state-schema.js";
14+
import type { NodeWorkerSupervisorIdentity } from "../worker/node-supervisor-protocol.js";
1415
import {
1516
inspectNodeWorkerProcessIdentity,
1617
type NodeWorkerProcessIdentity,
1718
} from "./node-worker-process-identity.js";
18-
import type { NodeWorkerSupervisorIdentity } from "./node-worker-supervisor-identity.js";
1919

2020
type NodeWorkerLaunchState =
2121
| "pending"
Lines changed: 30 additions & 168 deletions
Original file line numberDiff line numberDiff line change
@@ -1,190 +1,52 @@
1-
import { createHash } from "node:crypto";
2-
import { stableStringify } from "@openclaw/normalization-core";
3-
import { isRecord } from "@openclaw/normalization-core/record-coerce";
41
import {
5-
parseWorkerLaunchDescriptor,
6-
type WorkerLaunchDescriptor,
7-
} from "../worker/launch-descriptor.js";
2+
parseNodeWorkerSupervisorReceipt,
3+
type NodeWorkerLaunchInput,
4+
type NodeWorkerSupervisorIdentity,
5+
type NodeWorkerSupervisorReceipt,
6+
} from "../worker/node-supervisor-protocol.js";
87
import type { NodeWorkerLaunchReceipt } from "./node-worker-launch-store.js";
9-
import type { NodeWorkerSupervisorIdentity } from "./node-worker-supervisor-identity.js";
108

11-
export type { NodeWorkerSupervisorIdentity } from "./node-worker-supervisor-identity.js";
12-
13-
const IDENTIFIER_MAX_CHARS = 256;
14-
const GATEWAY_NAMESPACE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
15-
const NODE_WORKER_SUPERVISOR_CANCEL_REQUEST_MAX_BYTES = 4 * 1024;
16-
17-
export type NodeWorkerLaunchInput = {
18-
launchId: string;
19-
gatewayNamespace: string;
20-
bundleHash: string;
21-
placementGeneration: number;
22-
descriptor: WorkerLaunchDescriptor;
23-
};
24-
25-
export type NodeWorkerSupervisorReceipt = NodeWorkerSupervisorIdentity & {
26-
state: "pending" | "running" | "completed" | "failed" | "interrupted" | "cancelled";
27-
};
9+
export {
10+
nodeWorkerPlanHash,
11+
parseNodeWorkerCancelInput,
12+
parseNodeWorkerLaunchInput,
13+
parseNodeWorkerLookupInput,
14+
} from "../worker/node-supervisor-protocol.js";
15+
export type {
16+
NodeWorkerLaunchInput,
17+
NodeWorkerSupervisorIdentity,
18+
NodeWorkerSupervisorReceipt,
19+
} from "../worker/node-supervisor-protocol.js";
2820

2921
export type NodeWorkerSupervisorControl = {
3022
launch(input: NodeWorkerLaunchInput): Promise<NodeWorkerLaunchReceipt>;
3123
status(launchId: string): Promise<NodeWorkerLaunchReceipt | undefined>;
3224
cancel(expected: NodeWorkerSupervisorIdentity): Promise<NodeWorkerLaunchReceipt | undefined>;
3325
};
3426

35-
function hasExactKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {
36-
return (
37-
Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key))
38-
);
39-
}
40-
41-
function requireIdentifier(value: unknown, label: string): string {
42-
if (
43-
typeof value !== "string" ||
44-
value.length === 0 ||
45-
value.length > IDENTIFIER_MAX_CHARS ||
46-
value.trim() !== value ||
47-
value.includes("\0")
48-
) {
49-
throw new Error(`INVALID_REQUEST: ${label} must be a bounded non-empty identifier`);
50-
}
51-
return value;
52-
}
53-
54-
function requireNonNegativeInteger(value: unknown, label: string): number {
55-
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
56-
throw new Error(`INVALID_REQUEST: ${label} must be a non-negative safe integer`);
57-
}
58-
return value;
59-
}
60-
61-
function decodeRequest(raw?: string | null): unknown {
62-
if (!raw) {
63-
throw new Error("INVALID_REQUEST: paramsJSON required");
64-
}
65-
try {
66-
return JSON.parse(raw) as unknown;
67-
} catch {
68-
throw new Error("INVALID_REQUEST: paramsJSON malformed JSON");
69-
}
70-
}
71-
72-
export function parseNodeWorkerLaunchInput(raw?: string | null): NodeWorkerLaunchInput {
73-
const value = decodeRequest(raw);
74-
if (
75-
!isRecord(value) ||
76-
!hasExactKeys(value, [
77-
"launchId",
78-
"gatewayNamespace",
79-
"bundleHash",
80-
"placementGeneration",
81-
"descriptor",
82-
])
83-
) {
84-
throw new Error("INVALID_REQUEST: invalid node worker launch request");
85-
}
86-
const launchId = requireIdentifier(value.launchId, "launchId");
87-
const gatewayNamespace = requireIdentifier(value.gatewayNamespace, "gatewayNamespace");
88-
if (!GATEWAY_NAMESPACE_PATTERN.test(gatewayNamespace)) {
89-
throw new Error("INVALID_REQUEST: gatewayNamespace must be a safe bounded path component");
90-
}
91-
if (typeof value.bundleHash !== "string" || !/^[a-f0-9]{64}$/u.test(value.bundleHash)) {
92-
throw new Error("INVALID_REQUEST: bundleHash must be 64 lowercase hexadecimal characters");
93-
}
94-
let descriptor: WorkerLaunchDescriptor;
95-
try {
96-
descriptor = parseWorkerLaunchDescriptor(value.descriptor);
97-
} catch {
98-
throw new Error("INVALID_REQUEST: invalid worker launch descriptor");
99-
}
100-
if (descriptor.admission.handshake.bundleHash !== value.bundleHash) {
101-
throw new Error("INVALID_REQUEST: descriptor bundle hash does not match bundleHash");
102-
}
103-
return {
104-
launchId,
105-
gatewayNamespace,
106-
bundleHash: value.bundleHash,
107-
placementGeneration: requireNonNegativeInteger(
108-
value.placementGeneration,
109-
"placementGeneration",
110-
),
111-
descriptor,
112-
};
113-
}
114-
115-
export function parseNodeWorkerLookupInput(raw?: string | null): { launchId: string } {
116-
const value = decodeRequest(raw);
117-
if (!isRecord(value) || !hasExactKeys(value, ["launchId"])) {
118-
throw new Error("INVALID_REQUEST: invalid node worker lookup request");
119-
}
120-
return { launchId: requireIdentifier(value.launchId, "launchId") };
121-
}
122-
123-
export function parseNodeWorkerCancelInput(raw?: string | null): NodeWorkerSupervisorIdentity {
124-
if (!raw || Buffer.byteLength(raw, "utf8") > NODE_WORKER_SUPERVISOR_CANCEL_REQUEST_MAX_BYTES) {
125-
throw new Error("INVALID_REQUEST: invalid node worker cancel request");
126-
}
127-
const value = decodeRequest(raw);
128-
if (
129-
!isRecord(value) ||
130-
!hasExactKeys(value, [
131-
"launchId",
132-
"planHash",
133-
"environmentId",
134-
"sessionId",
135-
"ownerEpoch",
136-
"placementGeneration",
137-
"runId",
138-
])
139-
) {
140-
throw new Error("INVALID_REQUEST: invalid node worker cancel request");
141-
}
142-
if (typeof value.planHash !== "string" || !/^[a-f0-9]{64}$/u.test(value.planHash)) {
143-
throw new Error("INVALID_REQUEST: planHash must be 64 lowercase hexadecimal characters");
144-
}
145-
return {
146-
launchId: requireIdentifier(value.launchId, "launchId"),
147-
planHash: value.planHash,
148-
environmentId: requireIdentifier(value.environmentId, "environmentId"),
149-
sessionId: requireIdentifier(value.sessionId, "sessionId"),
150-
ownerEpoch: requireNonNegativeInteger(value.ownerEpoch, "ownerEpoch"),
151-
placementGeneration: requireNonNegativeInteger(
152-
value.placementGeneration,
153-
"placementGeneration",
154-
),
155-
runId: requireIdentifier(value.runId, "runId"),
156-
};
157-
}
158-
159-
export function nodeWorkerPlanHash(
160-
input: Pick<
161-
NodeWorkerLaunchInput,
162-
"bundleHash" | "descriptor" | "gatewayNamespace" | "placementGeneration"
163-
>,
164-
): string {
165-
return createHash("sha256")
166-
.update(
167-
stableStringify({
168-
bundleHash: input.bundleHash,
169-
descriptor: input.descriptor,
170-
gatewayNamespace: input.gatewayNamespace,
171-
placementGeneration: input.placementGeneration,
172-
}),
173-
)
174-
.digest("hex");
175-
}
176-
17727
export function projectNodeWorkerSupervisorReceipt(
17828
receipt: NodeWorkerLaunchReceipt,
17929
): NodeWorkerSupervisorReceipt {
180-
return {
30+
const identity = {
18131
launchId: receipt.launchId,
18232
planHash: receipt.planHash,
18333
environmentId: receipt.environmentId,
18434
sessionId: receipt.sessionId,
18535
ownerEpoch: receipt.ownerEpoch,
18636
placementGeneration: receipt.placementGeneration,
18737
runId: receipt.runId,
188-
state: receipt.state,
18938
};
39+
const projected =
40+
receipt.state === "completed"
41+
? { ...identity, state: receipt.state, resultJson: receipt.resultJson }
42+
: receipt.state === "failed" ||
43+
receipt.state === "interrupted" ||
44+
receipt.state === "cancelled"
45+
? { ...identity, state: receipt.state, errorText: receipt.errorText }
46+
: { ...identity, state: receipt.state };
47+
const parsed = parseNodeWorkerSupervisorReceipt(projected);
48+
if (!parsed) {
49+
throw new Error("node worker supervisor durable receipt is inconsistent");
50+
}
51+
return parsed;
19052
}

‎src/node-host/node-worker-supervisor-identity.ts‎

Lines changed: 0 additions & 9 deletions
This file was deleted.

‎src/state/openclaw-state-db.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ import {
8181
import { getOpenClawStateRuntimeSchema } from "./openclaw-state-schema-compatibility.js";
8282
import { OPENCLAW_STATE_SCHEMA_SQL } from "./openclaw-state-schema.js";
8383

84-
const OPENCLAW_STATE_MIGRATION_ASSERTIONS = {
84+
const STATE_MIGRATION_ASSERTIONS = {
8585
5: assertOpenClawStateDatabaseV5ForMigration,
8686
6: assertOpenClawStateDatabaseV6ForMigration,
8787
} as const;
@@ -178,7 +178,7 @@ function repairOpenClawStateDatabaseSchemaWithWriteAccess(
178178
allowedMissingTables: LAZY_ADDITIVE_STATE_TABLES,
179179
});
180180
} else if (previousVersion === 5 || previousVersion === 6) {
181-
OPENCLAW_STATE_MIGRATION_ASSERTIONS[previousVersion](db, { pathname });
181+
STATE_MIGRATION_ASSERTIONS[previousVersion](db, { pathname });
182182
}
183183
if (rebuiltIndexNames.size === 0) {
184184
assertSqliteIntegrity(db, pathname);
@@ -366,7 +366,7 @@ function ensureSchema(db: DatabaseSync, pathname: string, env: NodeJS.ProcessEnv
366366
ensureAdditiveStateColumns(db);
367367
assertCurrentStateRuntimeSchema(db, pathname);
368368
} else if (previousVersion === 5 || previousVersion === 6) {
369-
OPENCLAW_STATE_MIGRATION_ASSERTIONS[previousVersion](db, { pathname });
369+
STATE_MIGRATION_ASSERTIONS[previousVersion](db, { pathname });
370370
}
371371
dropLegacyStateTables(db);
372372
migrateRetiredCommitmentsSchema(db, previousVersion);

0 commit comments

Comments
 (0)