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