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