Skip to content

Commit f1e88d4

Browse files
committed
feat(durable): expose gateway and CLI lifecycle
1 parent ca3efe4 commit f1e88d4

15 files changed

Lines changed: 1833 additions & 0 deletions

‎docs/gateway/protocol.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -547,6 +547,18 @@ terminal summary, and sanitized error text. `agentId` identifies the agent
547547
executing the task; `sessionKey` and `ownerKey` preserve requester and control
548548
context.
549549

550+
### Durable coordination RPCs
551+
552+
Operator clients may inspect native Durable Core coordination state through a
553+
bounded projection instead of reading the durable SQLite store directly.
554+
555+
- `durable.coordination.get` requires `operator.read`.
556+
- Params: `{ "workflowRunId": string }`.
557+
- Result: `{ "projection": DurableCoordinationProjection }`.
558+
- The projection includes workflow identity, status, recovery state, current
559+
step, waiting reason, external task/session/run bindings, child counts, ref
560+
summaries, and supported controls.
561+
550562
### Operator helper methods
551563

552564
- Operators may call `commands.list` (`operator.read`) to fetch the runtime

‎src/cli/gateway-cli/run-loop.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
import { randomUUID } from "node:crypto";
33
import net from "node:net";
44
import { clearRuntimeConfigSnapshot } from "../../config/runtime-snapshot.js";
5+
import { startDurableRecoveryWorker } from "../../durable/recovery.js";
6+
import { maybeRecordDurableGatewayStartup } from "../../durable/startup.js";
57
import {
68
captureGatewayRestartTraceHandoff,
79
createGatewayRestartTraceHandoffEnv,
@@ -124,6 +126,7 @@ export async function runGatewayLoop(params: {
124126
const eagerLifecycleRuntime = await loadGatewayLifecycleRuntimeModule();
125127
let lock = await acquireGatewayLock({ port: params.lockPort });
126128
let server: Awaited<ReturnType<typeof startGatewayServer>> | null = null;
129+
let stopDurableRecoveryWorker: (() => void) | null = null;
127130
let shuttingDown = false;
128131
let restartResolver: (() => void) | null = null;
129132
// The HTTP server can report ready before params.start returns its close handle.
@@ -618,6 +621,8 @@ export async function runGatewayLoop(params: {
618621

619622
armCloseForceExitTimerForIndefiniteRestart();
620623
const closeDrainTimeoutMs = resolveRestartCloseDrainTimeoutMs();
624+
stopDurableRecoveryWorker?.();
625+
stopDurableRecoveryWorker = null;
621626
await server?.close({
622627
reason: isRestart ? "gateway restarting" : "gateway stopping",
623628
restartExpectedMs: isRestart ? 1500 : null,
@@ -840,6 +845,15 @@ export async function runGatewayLoop(params: {
840845
let startupFailedBeforeServerHandle = false;
841846
try {
842847
server = await params.start({ startupStartedAt });
848+
await maybeRecordDurableGatewayStartup({
849+
processInstanceId,
850+
startupStartedAt,
851+
port: params.lockPort,
852+
});
853+
stopDurableRecoveryWorker?.();
854+
stopDurableRecoveryWorker = startDurableRecoveryWorker({
855+
processInstanceId,
856+
});
843857
startupFailedWithoutServerHandle = false;
844858
isFirstStart = false;
845859
} catch (err) {
@@ -877,6 +891,8 @@ export async function runGatewayLoop(params: {
877891
});
878892
}
879893
} finally {
894+
stopDurableRecoveryWorker?.();
895+
stopDurableRecoveryWorker = null;
880896
await releaseLockIfHeld();
881897
cleanupSignals();
882898
}

‎src/cli/program/command-registry-core.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,13 @@ const coreEntrySpecs: readonly CommandGroupDescriptorSpec<
131131
mod.registerAgentsCommands(program);
132132
},
133133
),
134+
defineImportedCommandGroupSpec(
135+
["durable"],
136+
() => import("./register.durable.js"),
137+
(mod, { program }) => {
138+
mod.registerDurableCommand(program);
139+
},
140+
),
134141
...withProgramOnlySpecs(
135142
defineImportedProgramCommandGroupSpecs([
136143
{

‎src/cli/program/core-command-descriptors.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,12 @@ const coreCliCommandCatalog = defineCommandDescriptorCatalog([
113113
description: "Inspect durable background tasks and flows",
114114
hasSubcommands: true,
115115
},
116+
{
117+
name: "durable",
118+
description: "Inspect native durable workflow runs, timelines, and coordination state",
119+
hasSubcommands: true,
120+
parentDefaultHelp: true,
121+
},
116122
] as const satisfies ReadonlyArray<CoreCliCommandDescriptor>);
117123

118124
/** Static root-command descriptors for the core CLI surface. */
Lines changed: 207 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,207 @@
1+
import type { Command } from "commander";
2+
import {
3+
durableCommand,
4+
type DurableCliAction,
5+
type DurableCliOptions,
6+
} from "../../commands/durable.js";
7+
import { defaultRuntime } from "../../runtime.js";
8+
9+
type DurableCliCommanderOptions = {
10+
json?: boolean;
11+
store?: string;
12+
limit?: string;
13+
reason?: string;
14+
delayMs?: string;
15+
type?: string;
16+
correlationId?: string;
17+
idempotencyKey?: string;
18+
payloadJson?: string;
19+
};
20+
21+
function parseLimit(value: string | undefined): number | undefined {
22+
if (value === undefined) {
23+
return undefined;
24+
}
25+
const parsed = Number(value);
26+
if (!Number.isInteger(parsed) || parsed < 1) {
27+
defaultRuntime.error("--limit must be a positive integer.");
28+
defaultRuntime.exit(1);
29+
return undefined;
30+
}
31+
return parsed;
32+
}
33+
34+
function parseNonNegativeInteger(value: string | undefined, flagName: string): number | undefined {
35+
if (value === undefined) {
36+
return undefined;
37+
}
38+
const parsed = Number(value);
39+
if (!Number.isInteger(parsed) || parsed < 0) {
40+
defaultRuntime.error(`${flagName} must be a non-negative integer.`);
41+
defaultRuntime.exit(1);
42+
return undefined;
43+
}
44+
return parsed;
45+
}
46+
47+
function parsePayloadJson(value: string | undefined): Record<string, unknown> | undefined {
48+
if (value === undefined) {
49+
return undefined;
50+
}
51+
try {
52+
const parsed = JSON.parse(value) as unknown;
53+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
54+
return parsed as Record<string, unknown>;
55+
}
56+
} catch {
57+
// The explicit error below is clearer than leaking JSON parser internals.
58+
}
59+
defaultRuntime.error("--payload-json must be a JSON object.");
60+
defaultRuntime.exit(1);
61+
return undefined;
62+
}
63+
64+
function parseSignalType(value: string | undefined): DurableCliOptions["signalType"] {
65+
if (
66+
value === undefined ||
67+
value === "human_input" ||
68+
value === "approval" ||
69+
value === "rejection" ||
70+
value === "external_callback" ||
71+
value === "cancel" ||
72+
value === "resume"
73+
) {
74+
return value;
75+
}
76+
defaultRuntime.error(
77+
"--type must be one of: human_input, approval, rejection, external_callback, cancel, resume.",
78+
);
79+
defaultRuntime.exit(1);
80+
return undefined;
81+
}
82+
83+
function addCommonOptions(command: Command): Command {
84+
return command
85+
.option("--json", "Output JSON instead of text", false)
86+
.option("--store <path>", "Path to durable workflow SQLite store");
87+
}
88+
89+
async function runDurableAction(
90+
action: DurableCliAction,
91+
workflowRunId: string | undefined,
92+
opts: DurableCliCommanderOptions,
93+
): Promise<void> {
94+
await durableCommand(
95+
{
96+
action,
97+
workflowRunId,
98+
json: Boolean(opts.json),
99+
store: opts.store,
100+
limit: parseLimit(opts.limit),
101+
reason: opts.reason,
102+
delayMs: parseNonNegativeInteger(opts.delayMs, "--delay-ms"),
103+
signalType: parseSignalType(opts.type),
104+
correlationId: opts.correlationId,
105+
idempotencyKey: opts.idempotencyKey,
106+
payload: parsePayloadJson(opts.payloadJson),
107+
},
108+
defaultRuntime,
109+
);
110+
}
111+
112+
export function registerDurableCommand(program: Command) {
113+
const durable = program
114+
.command("durable")
115+
.description("Inspect native durable workflow runs, timelines, and coordination state");
116+
117+
addCommonOptions(
118+
durable.command("stats").description("Show durable workflow store stats"),
119+
).action(async (opts) => {
120+
await runDurableAction("stats", undefined, opts);
121+
});
122+
123+
addCommonOptions(
124+
durable
125+
.command("runs")
126+
.description("List recent durable workflow runs")
127+
.option("--limit <count>", "Maximum runs to show", "50"),
128+
).action(async (opts) => {
129+
await runDurableAction("runs", undefined, opts);
130+
});
131+
132+
for (const [name, action, description] of [
133+
["show", "show", "Show a durable workflow run with steps, links, signals, and timeline"],
134+
["timeline", "timeline", "Show durable workflow events for one run"],
135+
["steps", "steps", "Show durable workflow steps for one run"],
136+
["children", "children", "Show child workflow links for one run"],
137+
["parents", "parents", "Show parent workflow links for one run"],
138+
[
139+
"coordination",
140+
"coordination",
141+
"Show durable coordination projection for task, TaskFlow, and Workboard",
142+
],
143+
["signals", "signals", "Show durable workflow signals for one run"],
144+
["refs", "refs", "Show durable workflow state refs for one run"],
145+
["timers", "timers", "Show durable workflow timers for one run"],
146+
] as const) {
147+
addCommonOptions(durable.command(`${name} <workflowRunId>`).description(description)).action(
148+
async (workflowRunId: string, opts) => {
149+
await runDurableAction(action, workflowRunId, opts);
150+
},
151+
);
152+
}
153+
154+
addCommonOptions(
155+
durable
156+
.command("cancel <workflowRunId>")
157+
.description("Cancel a durable workflow run in the control plane")
158+
.option("--reason <text>", "Reason recorded in the durable event log"),
159+
).action(async (workflowRunId: string, opts) => {
160+
await runDurableAction("cancel", workflowRunId, opts);
161+
});
162+
163+
addCommonOptions(
164+
durable
165+
.command("retry <workflowRunId>")
166+
.description("Queue or schedule retry for a durable workflow run")
167+
.option("--delay-ms <ms>", "Delay before retry is due", "0")
168+
.option("--reason <text>", "Reason recorded in the durable event log"),
169+
).action(async (workflowRunId: string, opts) => {
170+
await runDurableAction("retry", workflowRunId, opts);
171+
});
172+
173+
addCommonOptions(
174+
durable
175+
.command("resume <workflowRunId>")
176+
.description("Move a waiting durable workflow run back to runnable state")
177+
.option("--reason <text>", "Reason recorded in the durable event log"),
178+
).action(async (workflowRunId: string, opts) => {
179+
await runDurableAction("resume", workflowRunId, opts);
180+
});
181+
182+
addCommonOptions(
183+
durable
184+
.command("signal <workflowRunId>")
185+
.description("Record a human or external signal for a durable workflow run")
186+
.option(
187+
"--type <type>",
188+
"Signal type: human_input, approval, rejection, external_callback, cancel, resume",
189+
"human_input",
190+
)
191+
.option("--payload-json <json>", "JSON object stored as signal payload metadata")
192+
.option("--correlation-id <id>", "External correlation id")
193+
.option("--idempotency-key <key>", "Idempotency key for duplicate signal suppression")
194+
.option("--reason <text>", "Reason recorded in the durable event log"),
195+
).action(async (workflowRunId: string, opts) => {
196+
await runDurableAction("signal", workflowRunId, opts);
197+
});
198+
199+
addCommonOptions(
200+
durable
201+
.command("mark-unknown <workflowRunId>")
202+
.description("Mark a run as unknown after a possible side effect")
203+
.option("--reason <text>", "Reason recorded in the durable event log"),
204+
).action(async (workflowRunId: string, opts) => {
205+
await runDurableAction("mark-unknown", workflowRunId, opts);
206+
});
207+
}

0 commit comments

Comments
 (0)