Open History to see the last commit
1import { WorkflowHook, WorkflowRunStatus } from "@t3tools/contracts";
2import * as HostProcess from "@t3tools/shared/HostProcess";
3import * as Console from "effect/Console";
4import * as Effect from "effect/Effect";
5import * as Option from "effect/Option";
6import * as Schema from "effect/Schema";
7import { Argument, Command, Flag } from "effect/cli";
8
9import * as Workflows from "../workflows/Workflows.ts";
10import { WorkflowRun, WorkflowStep } from "../workflows/WorkflowStore.ts";
11import { projectLocationFlags } from "./config.ts";
12import {
13 jsonFlag,
14 printJson,
15 reportThreadErrors,
16 type ThreadTools,
17 ThreadUsageError,
18 withThreadTools,
19} from "./thread.ts";
20
21const RunResult = Schema.Struct({ run: WorkflowRun, steps: Schema.Array(WorkflowStep) });
22const RunsResult = Schema.Struct({ runs: Schema.Array(WorkflowRun) });
23const QuestionsResult = Schema.Struct({ questions: Schema.Array(Workflows.WorkflowQuestion) });
24const HooksResult = Schema.Struct({ hooks: Schema.Array(WorkflowHook) });
25const ThreadTitleResult = Schema.Struct({ thread: Schema.Struct({ title: Schema.String }) });
26const SignalResult = Schema.Struct({ delivery: Schema.Literals(["delivered", "buffered"]) });
27
28const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Json));
29const jsonArgument = (text: string, what: string) =>
30 decodeJson(text).pipe(
31 Effect.mapError(() => new ThreadUsageError({ detail: `${what} is not valid JSON.` })),
32 );
33
34const runLine = (run: WorkflowRun) =>
35 [run.runId, run.status.padEnd(9), run.workflow, run.title, run.detail ?? ""].join(" ").trimEnd();
36
37const printRun = Effect.fn("cli.workflow.printRun")(function* (
38 result: typeof RunResult.Type,
39 json: boolean,
40) {
41 if (json) return yield* printJson(result);
42 yield* Console.log(runLine(result.run));
43 for (const step of result.steps) {
44 yield* Console.log(
45 ` ${step.status.padEnd(9)} ${step.kind.padEnd(5)} ${step.name}${
46 step.attempts > 1 ? ` (${step.attempts} tries)` : ""
47 }${step.environmentId === null ? "" : ` in ${step.environmentId}`}${
48 step.detail === null ? "" : ` ${step.detail}`
49 }`,
50 );
51 }
52 if (result.run.result !== null) yield* printJson(result.run.result);
53});
54
55const runArgument = Argument.String("run").pipe(Argument.withDescription("Run id."));
56const readRun = (tools: ThreadTools, runId: string) =>
57 tools.call("t3_workflow", { action: "read", runId }, RunResult);
58
59const startCommand = Command.make("start", {
60 ...projectLocationFlags,
61 workflow: Argument.String("workflow").pipe(Argument.withDescription("Workflow name.")),
62 input: Flag.String("input").pipe(
63 Flag.withDescription("The run's payload, as JSON. Defaults to {}."),
64 Flag.withDefault("{}"),
65 ),
66 key: Flag.String("key").pipe(
67 Flag.withDescription(
68 "Required. Names this run: starting again with the same key is the same run, not a second one.",
69 ),
70 ),
71 json: jsonFlag,
72}).pipe(
73 Command.withDescription("Start a workflow run and print it."),
74 Command.withHandler((flags) =>
75 Effect.gen(function* () {
76 const input = yield* jsonArgument(flags.input, "--input");
77 if (flags.key.trim() === "") {
78 return yield* new ThreadUsageError({ detail: "--key cannot be blank." });
79 }
80 yield* withThreadTools(
81 flags,
82 Effect.fn("cli.workflow.start")(function* (tools) {
83 const started = yield* tools.call(
84 "t3_workflow",
85 { action: "start", workflow: flags.workflow, input, idempotencyKey: flags.key },
86 RunResult,
87 );
88 yield* printRun(started, flags.json);
89 }),
90 );
91 }).pipe(reportThreadErrors),
92 ),
93);
94
95const listCommand = Command.make("list", {
96 ...projectLocationFlags,
97 status: Flag.Literals("status", WorkflowRunStatus.literals).pipe(
98 Flag.withDescription(
99 "Only runs in this state. A skipped run is listed only with `skipped`, unless another run invoked it.",
100 ),
101 Flag.optional,
102 ),
103 tag: Flag.String("tag").pipe(
104 Flag.withDescription("Only runs their workflow tagged with this."),
105 Flag.optional,
106 ),
107 json: jsonFlag,
108}).pipe(
109 Command.withDescription("List workflow runs, newest first."),
110 Command.withHandler((flags) =>
111 withThreadTools(
112 flags,
113 Effect.fn("cli.workflow.list")(function* (tools) {
114 const { runs } = yield* tools.call(
115 "t3_workflow",
116 {
117 action: "list",
118 ...(Option.isSome(flags.status) ? { status: flags.status.value } : {}),
119 ...(Option.isSome(flags.tag) ? { tag: flags.tag.value } : {}),
120 },
121 RunsResult,
122 );
123 // A workflow skips what was never its to do, and that is most of what a trigger brings.
124 const listed = Option.isSome(flags.status)
125 ? runs
126 : runs.filter((run) => run.status !== "skipped" || run.parentRunId !== null);
127 if (flags.json) return yield* printJson(listed);
128 for (const run of listed) yield* Console.log(runLine(run));
129 }),
130 ).pipe(reportThreadErrors),
131 ),
132);
133
134const showCommand = Command.make("show", {
135 ...projectLocationFlags,
136 run: runArgument,
137 json: jsonFlag,
138}).pipe(
139 Command.withDescription("Show a run and its steps."),
140 Command.withHandler((flags) =>
141 withThreadTools(
142 flags,
143 Effect.fn("cli.workflow.show")(function* (tools) {
144 yield* printRun(yield* readRun(tools, flags.run), flags.json);
145 }),
146 ).pipe(reportThreadErrors),
147 ),
148);
149
150/** Why `action` would leave the run as it is, or undefined when it would act. */
151const noOpReason = (action: "resume" | "cancel", run: WorkflowRun) => {
152 if (action === "cancel") {
153 return run.endedAt === null
154 ? undefined
155 : `Run ${run.runId} is ${run.status}; nothing to cancel.`;
156 }
157 return run.status === "paused"
158 ? undefined
159 : `Run ${run.runId} is ${run.status}; nothing to resume.`;
160};
161
162const steer = Effect.fn("cli.workflow.steer")(function* (
163 tools: ThreadTools,
164 action: "resume" | "cancel",
165 flags: { readonly run: string; readonly json: boolean; readonly reason: Option.Option<string> },
166) {
167 const before = yield* readRun(tools, flags.run);
168 const skipped = noOpReason(action, before.run);
169 if (skipped !== undefined) {
170 // Stderr, so --json output stays the run alone.
171 yield* Console.error(skipped);
172 return yield* printRun(before, flags.json);
173 }
174 const after = yield* tools.call(
175 "t3_workflow",
176 {
177 action,
178 runId: flags.run,
179 ...(Option.isSome(flags.reason) ? { reason: flags.reason.value } : {}),
180 },
181 RunResult,
182 );
183 yield* printRun(after, flags.json);
184});
185
186const resumeCommand = Command.make("resume", {
187 ...projectLocationFlags,
188 run: runArgument,
189 json: jsonFlag,
190}).pipe(
191 Command.withDescription("Run a paused run's failed step again."),
192 Command.withHandler((flags) =>
193 withThreadTools(flags, (tools) =>
194 steer(tools, "resume", { ...flags, reason: Option.none() }),
195 ).pipe(reportThreadErrors),
196 ),
197);
198
199const cancelCommand = Command.make("cancel", {
200 ...projectLocationFlags,
201 run: runArgument,
202 reason: Flag.String("reason").pipe(
203 Flag.withDescription("Why, kept as the run's detail."),
204 Flag.optional,
205 ),
206 json: jsonFlag,
207}).pipe(
208 Command.withDescription("Cancel a run."),
209 Command.withHandler((flags) =>
210 withThreadTools(flags, (tools) => steer(tools, "cancel", flags)).pipe(reportThreadErrors),
211 ),
212);
213
214const signalCommand = Command.make("signal", {
215 ...projectLocationFlags,
216 value: Argument.String("value").pipe(
217 Argument.withDescription('What the wait receives, as JSON. A question takes {"choice": ...}.'),
218 ),
219 run: Flag.String("run").pipe(
220 Flag.withDescription("Run id. Pass with --wait, not with --workflow and --channel."),
221 Flag.optional,
222 ),
223 wait: Flag.String("wait").pipe(
224 Flag.withDescription("The wait's or question's name in that run."),
225 Flag.optional,
226 ),
227 workflow: Flag.String("workflow").pipe(
228 Flag.withDescription("Workflow name. Pass with --channel when the run is not known."),
229 Flag.optional,
230 ),
231 channel: Flag.String("channel").pipe(
232 Flag.withDescription("The channel the wait opened with."),
233 Flag.optional,
234 ),
235 id: Flag.String("id").pipe(
236 Flag.withDescription(
237 "Names this signal: sending it again with the same id is the same signal.",
238 ),
239 Flag.optional,
240 ),
241}).pipe(
242 Command.withDescription("Wake a waiting run, or answer its question."),
243 Command.withHandler((flags) =>
244 Effect.gen(function* () {
245 const value = yield* jsonArgument(flags.value, "The value");
246 const byRun = Option.isSome(flags.run) || Option.isSome(flags.wait);
247 const byChannel = Option.isSome(flags.workflow) || Option.isSome(flags.channel);
248 if (byRun && byChannel) {
249 return yield* new ThreadUsageError({
250 detail:
251 "Address a signal with --run and --wait, or with --workflow and --channel, not both.",
252 });
253 }
254 const completeRun = Option.isSome(flags.run) && Option.isSome(flags.wait);
255 const completeChannel = Option.isSome(flags.workflow) && Option.isSome(flags.channel);
256 if (!completeRun && !completeChannel) {
257 return yield* new ThreadUsageError({
258 detail: "Address a signal with --run and --wait, or with --workflow and --channel.",
259 });
260 }
261 // An agent answers through this command, so its answer is named after its thread.
262 const callingThread = (yield* HostProcess.Environment).T3CODE_THREAD_ID?.trim();
263 const threadTitle =
264 callingThread === undefined || callingThread === ""
265 ? undefined
266 : yield* withThreadTools({ ...flags, json: false }, (tools) =>
267 tools.call(
268 "t3_thread_read",
269 { threadId: callingThread, limit: 1, runLimit: 1 },
270 ThreadTitleResult,
271 ),
272 ).pipe(
273 Effect.map(({ thread }) => thread.title.trim()),
274 Effect.orElseSucceed(() => undefined),
275 );
276 yield* withThreadTools(
277 // Named on the answer to a question it sends.
278 { ...flags, json: false, clientLabel: threadTitle || "t3 workflow signal" },
279 Effect.fn("cli.workflow.signal")(function* (tools) {
280 const { delivery } = yield* tools.call(
281 "t3_workflow",
282 {
283 action: "signal",
284 value,
285 ...(Option.isSome(flags.run) ? { runId: flags.run.value } : {}),
286 ...(Option.isSome(flags.wait) ? { wait: flags.wait.value } : {}),
287 ...(Option.isSome(flags.workflow) ? { workflow: flags.workflow.value } : {}),
288 ...(Option.isSome(flags.channel) ? { channel: flags.channel.value } : {}),
289 ...(Option.isSome(flags.id) ? { signalId: flags.id.value } : {}),
290 },
291 SignalResult,
292 );
293 yield* Console.log(
294 delivery === "delivered" ? "Delivered." : "Kept until a run waits for it.",
295 );
296 }),
297 );
298 }).pipe(reportThreadErrors),
299 ),
300);
301
302const questionsCommand = Command.make("questions", {
303 ...projectLocationFlags,
304 kind: Flag.String("kind").pipe(
305 Flag.withDescription("Only questions of this kind, as their workflow's `asks` names it."),
306 Flag.optional,
307 ),
308 json: jsonFlag,
309}).pipe(
310 Command.withDescription("List the questions runs are waiting on a person to answer."),
311 Command.withHandler((flags) =>
312 withThreadTools(
313 flags,
314 Effect.fn("cli.workflow.questions")(function* (tools) {
315 const { questions } = yield* tools.call(
316 "t3_workflow",
317 { action: "questions", ...(Option.isSome(flags.kind) ? { kind: flags.kind.value } : {}) },
318 QuestionsResult,
319 );
320 if (flags.json) return yield* printJson(questions);
321 for (const question of questions) {
322 yield* Console.log(
323 [question.runId, question.name, question.kind ?? ""].join(" ").trimEnd(),
324 );
325 yield* printJson(question.request);
326 }
327 }),
328 ).pipe(reportThreadErrors),
329 ),
330);
331
332const hooksCommand = Command.make("hooks", {
333 ...projectLocationFlags,
334 json: jsonFlag,
335}).pipe(
336 Command.withDescription(
337 "List the URL paths that start runs. Each holds its hook's secret; add the server's origin.",
338 ),
339 Command.withHandler((flags) =>
340 withThreadTools(
341 flags,
342 Effect.fn("cli.workflow.hooks")(function* (tools) {
343 const { hooks } = yield* tools.call("t3_workflow", { action: "hooks" }, HooksResult);
344 if (flags.json) return yield* printJson(hooks);
345 for (const hook of hooks) {
346 yield* Console.log(`${hook.workflow} ${hook.name} ${hook.path}`);
347 }
348 }),
349 ).pipe(reportThreadErrors),
350 ),
351);
352
353const StoreResult = Schema.Struct({
354 entries: Schema.Array(Schema.Struct({ key: Schema.String, value: Schema.Json })),
355});
356const keyArgument = Argument.String("key").pipe(Argument.withDescription("The key in the store."));
357
358const storeListCommand = Command.make("list", {
359 ...projectLocationFlags,
360 prefix: Argument.String("prefix").pipe(
361 Argument.withDescription("Only keys that start with this."),
362 Argument.withDefault(""),
363 ),
364 json: jsonFlag,
365}).pipe(
366 Command.withDescription("List what workflows keep in the store."),
367 Command.withHandler((flags) =>
368 withThreadTools(
369 flags,
370 Effect.fn("cli.workflow.store.list")(function* (tools) {
371 const { entries } = yield* tools.call(
372 "t3_workflow",
373 { action: "store", ...(flags.prefix === "" ? {} : { key: flags.prefix }) },
374 StoreResult,
375 );
376 if (flags.json) return yield* printJson(entries);
377 for (const entry of entries) {
378 yield* Console.log(entry.key);
379 yield* printJson(entry.value);
380 }
381 }),
382 ).pipe(reportThreadErrors),
383 ),
384);
385
386const storeSetCommand = Command.make("set", {
387 ...projectLocationFlags,
388 key: keyArgument,
389 value: Argument.String("value").pipe(Argument.withDescription("The value, as JSON.")),
390}).pipe(
391 Command.withDescription("Set a key of the store, as a person flipping a switch does."),
392 Command.withHandler((flags) =>
393 Effect.gen(function* () {
394 const value = yield* jsonArgument(flags.value, "The value");
395 yield* withThreadTools(
396 { ...flags, json: false },
397 Effect.fn("cli.workflow.store.set")(function* (tools) {
398 yield* tools.call(
399 "t3_workflow",
400 { action: "store_set", key: flags.key, value },
401 StoreResult,
402 );
403 yield* Console.log(`Set ${flags.key}.`);
404 }),
405 );
406 }).pipe(reportThreadErrors),
407 ),
408);
409
410const storeDeleteCommand = Command.make("delete", {
411 ...projectLocationFlags,
412 key: keyArgument,
413}).pipe(
414 Command.withDescription("Delete a key of the store."),
415 Command.withHandler((flags) =>
416 withThreadTools(
417 { ...flags, json: false },
418 Effect.fn("cli.workflow.store.delete")(function* (tools) {
419 yield* tools.call("t3_workflow", { action: "store_delete", key: flags.key }, StoreResult);
420 yield* Console.log(`Deleted ${flags.key}.`);
421 }),
422 ).pipe(reportThreadErrors),
423 ),
424);
425
426const storeCommand = Command.make("store").pipe(
427 Command.withDescription("See and change what workflows keep between runs."),
428 Command.withSubcommands([storeListCommand, storeSetCommand, storeDeleteCommand]),
429);
430
431export const workflowCommand = Command.make("workflow").pipe(
432 Command.withDescription("Start, inspect and steer durable workflow runs on the running server."),
433 Command.withSubcommands([
434 startCommand,
435 listCommand,
436 showCommand,
437 resumeCommand,
438 cancelCommand,
439 signalCommand,
440 questionsCommand,
441 hooksCommand,
442 storeCommand,
443 ]),
444);