@lukstei/dsh-yaml-workflow 0.0.0-stage → 0.2.2-rc.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/fold.ts ADDED
@@ -0,0 +1,201 @@
1
+ /**
2
+ * PURPOSE: Pure session event folding to reconstruct workflow run state.
3
+ * ALLOWED: Pure state derivation from events.
4
+ * FORBIDDEN: No I/O, no filesystem, no external runtime dependencies.
5
+ */
6
+
7
+ import type { SessionEvent } from "@deepseek-ai/dsh-session";
8
+ import { WORKFLOW_SKILL_NAME } from "./skill.ts";
9
+ import type {
10
+ WorkflowInitPayloadData,
11
+ WorkflowPayload,
12
+ WorkflowRun,
13
+ WorkflowRunSummary,
14
+ WorkflowState,
15
+ } from "./types.ts";
16
+
17
+ export const WORKFLOW_EVENT_NAME = "wf-event" as const;
18
+
19
+ function isValidInitPayload(
20
+ payload: WorkflowPayload,
21
+ ): payload is { readonly action: "init" } & WorkflowInitPayloadData {
22
+ return (
23
+ payload.action === "init" &&
24
+ Boolean(
25
+ payload.workflow &&
26
+ payload.invocation &&
27
+ payload.invocation.runId === payload.runId,
28
+ )
29
+ );
30
+ }
31
+
32
+ /**
33
+ * Purpose: Pure fold over session command/run events to derive the latest workflow run.
34
+ * Contract:
35
+ * - Inputs: events array in chronological log order, optional targetRunId string.
36
+ * - Outputs: latest WorkflowRun if a workflow was initiated, or null.
37
+ * - Throws: None.
38
+ */
39
+ export function foldWorkflowState(
40
+ events: readonly { readonly type: string; readonly data?: unknown }[],
41
+ targetRunId?: string,
42
+ ): WorkflowRun | null {
43
+ let current: WorkflowRun | null = null;
44
+
45
+ for (const { type, data } of events) {
46
+ if (type !== "command/run") continue;
47
+ if (!data || typeof data !== "object") continue;
48
+
49
+ const cmd = data as {
50
+ readonly name?: string;
51
+ readonly args?: string;
52
+ };
53
+ if (cmd.name !== WORKFLOW_EVENT_NAME || typeof cmd.args !== "string")
54
+ continue;
55
+
56
+ try {
57
+ const payload = JSON.parse(cmd.args) as WorkflowPayload;
58
+ if (!payload.runId) {
59
+ continue;
60
+ }
61
+ if (targetRunId && payload.runId !== targetRunId) {
62
+ continue;
63
+ }
64
+ if (isValidInitPayload(payload)) {
65
+ current = {
66
+ workflow: payload.workflow,
67
+ invocation: payload.invocation,
68
+ state: { stepIndex: 0, status: "running" },
69
+ };
70
+ } else if (
71
+ payload.action === "state" &&
72
+ current &&
73
+ payload.runId === current.invocation.runId
74
+ ) {
75
+ const {
76
+ action: _,
77
+ sessionId: _sessionId,
78
+ runId: _runId,
79
+ ...delta
80
+ } = payload;
81
+ const nextState: WorkflowState = {
82
+ ...current.state,
83
+ ...delta,
84
+ };
85
+ if (delta.status !== undefined && delta.status !== "aborted") {
86
+ delete nextState.error;
87
+ }
88
+ current = {
89
+ workflow: current.workflow,
90
+ invocation: current.invocation,
91
+ state: nextState,
92
+ };
93
+ } else if (
94
+ payload.action === "output" &&
95
+ current &&
96
+ payload.runId === current.invocation.runId
97
+ ) {
98
+ // type-safe: outputType === "list" guarantees payload.value was recorded as JSON array of strings
99
+ const outputValue: string | readonly string[] =
100
+ payload.outputType === "list"
101
+ ? (JSON.parse(payload.value) as readonly string[])
102
+ : payload.value;
103
+ const nextOutputs: Record<string, string | readonly string[]> = {
104
+ ...(current.state.outputs ?? {}),
105
+ [payload.name]: outputValue,
106
+ };
107
+ const nextState: WorkflowState = {
108
+ ...current.state,
109
+ outputs: nextOutputs,
110
+ };
111
+ current = {
112
+ workflow: current.workflow,
113
+ invocation: current.invocation,
114
+ state: nextState,
115
+ };
116
+ }
117
+ } catch {
118
+ // ignore corrupted or non-payload args
119
+ }
120
+ }
121
+
122
+ return current;
123
+ }
124
+
125
+ export function initialWorkflowRunSummary(): WorkflowRunSummary {
126
+ return {
127
+ status: "idle",
128
+ skillInvoked: false,
129
+ };
130
+ }
131
+
132
+ export function foldWorkflowEvent(
133
+ state: WorkflowRunSummary,
134
+ event: SessionEvent,
135
+ ): WorkflowRunSummary {
136
+ if (event.type === "tool/call") {
137
+ if (state.skillInvoked) return state;
138
+ if (event.data.name === "skill") {
139
+ try {
140
+ const parsed = JSON.parse(event.data.arguments);
141
+ if (parsed.name === WORKFLOW_SKILL_NAME) {
142
+ return { ...state, skillInvoked: true };
143
+ }
144
+ } catch {
145
+ // ignore malformed arguments
146
+ }
147
+ }
148
+ return state;
149
+ }
150
+
151
+ if (event.type !== "command/run") return state;
152
+
153
+ if (event.data.name !== WORKFLOW_EVENT_NAME) {
154
+ if (
155
+ event.data.name === "wf" ||
156
+ event.data.name === "wf-validate" ||
157
+ event.data.name === "wf-resume" ||
158
+ event.data.name === "wf-abort" ||
159
+ event.data.name === "wf-list"
160
+ ) {
161
+ if (state.skillInvoked) return state;
162
+ return { ...state, skillInvoked: true };
163
+ }
164
+ return state;
165
+ }
166
+ if (typeof event.data.args !== "string") {
167
+ return state;
168
+ }
169
+
170
+ try {
171
+ const payload = JSON.parse(event.data.args) as WorkflowPayload;
172
+ if (!payload.runId) return state;
173
+
174
+ if (isValidInitPayload(payload)) {
175
+ return {
176
+ status: "running",
177
+ runId: payload.runId,
178
+ stepIndex: 0,
179
+ skillInvoked: state.skillInvoked,
180
+ };
181
+ }
182
+
183
+ if (payload.action === "state" && state.runId === payload.runId) {
184
+ return {
185
+ ...state,
186
+ status: payload.status ?? state.status,
187
+ stepIndex: payload.stepIndex ?? state.stepIndex,
188
+ };
189
+ }
190
+ } catch {
191
+ // ignore corrupted or non-payload args
192
+ }
193
+
194
+ return state;
195
+ }
196
+
197
+ export function toWorkflowRunSummaryRecord(
198
+ summary: WorkflowRunSummary,
199
+ ): WorkflowRunSummary | null {
200
+ return summary.status !== "idle" || summary.skillInvoked ? summary : null;
201
+ }
package/src/index.ts ADDED
@@ -0,0 +1,468 @@
1
+ /**
2
+ * PURPOSE: Cordis plugin entrypoint and public module re-exports.
3
+ * ALLOWED: Plugin metadata, context command registration, delegating to runner and re-exporting public API.
4
+ * FORBIDDEN: No inline execution loops, no direct filesystem operations.
5
+ */
6
+
7
+ import type { Context } from "@deepseek-ai/cordis";
8
+ import type { Agent } from "@deepseek-ai/dsh-agent";
9
+ import type {
10
+ CommandInvocation,
11
+ CommandResult,
12
+ } from "@deepseek-ai/dsh-commands";
13
+ import type { Session } from "@deepseek-ai/dsh-session";
14
+ import { defineTool } from "@deepseek-ai/dsh-tools";
15
+ import { DshWorkflowEffectContext } from "./effects.ts";
16
+ import { parseListOutput } from "./parser.ts";
17
+ import {
18
+ discardWorkflow,
19
+ listWorkflows,
20
+ requestWorkflow,
21
+ requestWorkflowResume,
22
+ startPendingWorkflows,
23
+ validateWorkflowTarget,
24
+ } from "./runner.ts";
25
+ import {
26
+ WORKFLOW_SKILL_CONTENT,
27
+ WORKFLOW_SKILL_DESCRIPTION,
28
+ WORKFLOW_SKILL_NAME,
29
+ } from "./skill.ts";
30
+ import {
31
+ foldWorkflowEvent,
32
+ foldWorkflowState,
33
+ initialWorkflowRunSummary,
34
+ toWorkflowRunSummaryRecord,
35
+ } from "./transitions.ts";
36
+ import { workflowRunSummarySchema } from "./types.ts";
37
+
38
+ export type { Agent } from "@deepseek-ai/dsh-agent";
39
+ export type {
40
+ CommandDefinition,
41
+ CommandInvocation,
42
+ CommandResult,
43
+ } from "@deepseek-ai/dsh-commands";
44
+ export type { Session } from "@deepseek-ai/dsh-session";
45
+ export * from "./skill.ts";
46
+
47
+ declare module "@deepseek-ai/cordis" {
48
+ interface Context {
49
+ skills: {
50
+ register: (spec: {
51
+ name: string;
52
+ description: string;
53
+ source: string;
54
+ content: string;
55
+ }) => () => void;
56
+ };
57
+ }
58
+ }
59
+
60
+ export const name = "dsh-workflow-runner";
61
+ export const inject = [
62
+ "commands",
63
+ "sessionProjections",
64
+ "subagents",
65
+ "tools",
66
+ "skills",
67
+ ] as const;
68
+
69
+ /**
70
+ * Registers /wf and /wf-resume slash commands with Cordis commands service.
71
+ * CONTRACT:
72
+ * - Input: Cordis Context instance with injected 'commands' service.
73
+ * - Output: Promise<void> (registers projection, commands, and tools in context).
74
+ */
75
+ export async function apply(ctx: Context): Promise<void> {
76
+ const log = ctx.logger("dsh-workflow-runner");
77
+ const sessionEffects = new WeakMap<Session, DshWorkflowEffectContext>();
78
+ ctx.on("session/event", (session, event) => {
79
+ if (event.type !== "command/done") return;
80
+ const effects = sessionEffects.get(session);
81
+ if (effects !== undefined) startPendingWorkflows(effects);
82
+ });
83
+
84
+ const projectionHandle = await ctx.sessionProjections.register({
85
+ key: "workflow",
86
+ stateSchema: workflowRunSummarySchema,
87
+ init: () => initialWorkflowRunSummary(),
88
+ apply: (state, event) => foldWorkflowEvent(state, event),
89
+ wire: {
90
+ viewSchema: workflowRunSummarySchema.nullable(),
91
+ view: toWorkflowRunSummaryRecord,
92
+ },
93
+ stateVersion: 1,
94
+ });
95
+
96
+ ctx.effect(() => () => projectionHandle.dispose());
97
+
98
+ ctx.effect(() =>
99
+ ctx.skills.register({
100
+ name: WORKFLOW_SKILL_NAME,
101
+ description: WORKFLOW_SKILL_DESCRIPTION,
102
+ source: "runtime",
103
+ content: WORKFLOW_SKILL_CONTENT,
104
+ }),
105
+ );
106
+
107
+ ctx.tools.register(
108
+ defineTool({
109
+ name: "save_output",
110
+ description:
111
+ "Save a named workflow output value for the current workflow step.",
112
+ parameters: {
113
+ name: {
114
+ type: "string",
115
+ required: true,
116
+ description: "The name of the output declared in the workflow step.",
117
+ },
118
+ value: {
119
+ type: "string",
120
+ required: true,
121
+ description: "The string value to save as the step output.",
122
+ },
123
+ },
124
+ output: {
125
+ schema: {
126
+ type: "object",
127
+ properties: {
128
+ success: { type: "boolean", required: true },
129
+ message: { type: "string", required: true },
130
+ },
131
+ additionalProperties: false,
132
+ },
133
+ render(_args, val) {
134
+ return [{ type: "text", text: val.message }];
135
+ },
136
+ },
137
+ async execute(args, exec) {
138
+ const agent = exec.agent;
139
+ if (!agent) {
140
+ return { success: false, message: "No active agent session" };
141
+ }
142
+ const events = agent.session.snapshotEvents();
143
+ const run = foldWorkflowState(events);
144
+ if (!run) {
145
+ return {
146
+ success: false,
147
+ message: "No active workflow run found",
148
+ };
149
+ }
150
+ if (run.state.status !== "running") {
151
+ return {
152
+ success: false,
153
+ message: "Workflow is not currently running",
154
+ };
155
+ }
156
+ const currentStepIndex = run.state.stepIndex;
157
+ const step = run.workflow.steps[currentStepIndex];
158
+ if (!step || step.kind === "print" || !step.outputs) {
159
+ return {
160
+ success: false,
161
+ message: `Current step ${currentStepIndex + 1} does not declare any outputs`,
162
+ };
163
+ }
164
+ const targetOutput = step.outputs[args.name];
165
+ if (
166
+ !targetOutput ||
167
+ (targetOutput.type !== "string" && targetOutput.type !== "list")
168
+ ) {
169
+ return {
170
+ success: false,
171
+ message: `Current step does not declare a string or list output named '${args.name}'`,
172
+ };
173
+ }
174
+
175
+ let serializedValue = args.value;
176
+ if (targetOutput.type === "list") {
177
+ const parsed = parseListOutput(args.name, args.value, targetOutput);
178
+ if (parsed.kind === "error") {
179
+ return {
180
+ success: false,
181
+ message: parsed.message,
182
+ };
183
+ }
184
+ serializedValue = JSON.stringify(parsed.value);
185
+ }
186
+
187
+ const effects = new DshWorkflowEffectContext({
188
+ ctx,
189
+ agent,
190
+ log,
191
+ });
192
+ effects.recordOutput(
193
+ currentStepIndex,
194
+ args.name,
195
+ serializedValue,
196
+ targetOutput.type,
197
+ undefined,
198
+ run.invocation.runId,
199
+ );
200
+
201
+ return {
202
+ success: true,
203
+ message: `Successfully saved output '${args.name}'`,
204
+ };
205
+ },
206
+ }),
207
+ {
208
+ when: ({ agent }: { agent: Agent }) =>
209
+ projectionHandle.stateOf(agent.session).status === "running",
210
+ },
211
+ );
212
+
213
+ ctx.tools.register(
214
+ defineTool({
215
+ name: "wf_validate",
216
+ description:
217
+ "Validate a workflow YAML file and optional arguments without executing it.",
218
+ parameters: {
219
+ target: {
220
+ type: "string",
221
+ required: true,
222
+ description:
223
+ "Path or identifier of the workflow YAML file (e.g. 'deploy.yaml' or '.agents/wf/build.yaml').",
224
+ },
225
+ args: {
226
+ type: "string",
227
+ description:
228
+ "Optional key=value arguments or trailing instructions (e.g. 'env=production version=1.0').",
229
+ },
230
+ },
231
+ output: {
232
+ schema: {
233
+ type: "object",
234
+ properties: {
235
+ success: { type: "boolean", required: true },
236
+ message: { type: "string", required: true },
237
+ },
238
+ additionalProperties: false,
239
+ },
240
+ render(_args, val) {
241
+ return [{ type: "text", text: val.message }];
242
+ },
243
+ },
244
+ async execute(args, exec) {
245
+ const agent = exec.agent;
246
+ if (!agent) {
247
+ return { success: false, message: "No active agent session" };
248
+ }
249
+ const target = args.target.trim();
250
+ if (target.length === 0) {
251
+ return {
252
+ success: false,
253
+ message: "Target workflow path is required",
254
+ };
255
+ }
256
+ const safeTarget =
257
+ target.includes(" ") &&
258
+ !target.startsWith('"') &&
259
+ !target.startsWith("'")
260
+ ? `"${target}"`
261
+ : target;
262
+ const effects = new DshWorkflowEffectContext({
263
+ ctx,
264
+ agent,
265
+ log,
266
+ });
267
+ const rawInput =
268
+ typeof args.args === "string" && args.args.trim().length > 0
269
+ ? `${safeTarget} ${args.args}`
270
+ : safeTarget;
271
+ const result = await validateWorkflowTarget(rawInput, effects);
272
+ if (result.kind === "error") {
273
+ return {
274
+ success: false,
275
+ message: result.text,
276
+ };
277
+ }
278
+ return {
279
+ success: true,
280
+ message: result.text ?? "",
281
+ };
282
+ },
283
+ }),
284
+ {
285
+ when: ({ agent }: { agent: Agent }) => {
286
+ const summary = projectionHandle.stateOf(agent.session);
287
+ return summary.status !== "idle" || summary.skillInvoked;
288
+ },
289
+ },
290
+ );
291
+
292
+ ctx.commands.register({
293
+ name: "wf",
294
+ description: "Execute prompt workflow from YAML",
295
+ input: { hint: "<workflow.yaml>" },
296
+ handler: async (invocation: CommandInvocation): Promise<CommandResult> => {
297
+ const effects = new DshWorkflowEffectContext({
298
+ ctx,
299
+ agent: invocation.agent,
300
+ log,
301
+ });
302
+ sessionEffects.set(invocation.agent.session, effects);
303
+ return requestWorkflow(
304
+ invocation.rawInput,
305
+ effects,
306
+ invocation.commandId,
307
+ );
308
+ },
309
+ });
310
+
311
+ ctx.commands.register({
312
+ name: "wf-resume",
313
+ description: "Resume an interrupted workflow",
314
+ input: { hint: "[instructions]" },
315
+ handler: (invocation: CommandInvocation): Promise<CommandResult> => {
316
+ const effects = new DshWorkflowEffectContext({
317
+ ctx,
318
+ agent: invocation.agent,
319
+ log,
320
+ });
321
+ return requestWorkflowResume(
322
+ effects,
323
+ invocation.rawInput,
324
+ invocation.signal,
325
+ );
326
+ },
327
+ });
328
+
329
+ ctx.commands.register({
330
+ name: "wf-abort",
331
+ description: "Discard the active workflow",
332
+ handler: (invocation: CommandInvocation): Promise<CommandResult> => {
333
+ const effects = new DshWorkflowEffectContext({
334
+ ctx,
335
+ agent: invocation.agent,
336
+ log,
337
+ });
338
+ return discardWorkflow({ effects });
339
+ },
340
+ });
341
+
342
+ ctx.commands.register({
343
+ name: "wf-list",
344
+ description: "List workflows in common and local directories",
345
+ handler: (invocation: CommandInvocation): Promise<CommandResult> => {
346
+ const effects = new DshWorkflowEffectContext({
347
+ ctx,
348
+ agent: invocation.agent,
349
+ log,
350
+ });
351
+ return listWorkflows(effects);
352
+ },
353
+ });
354
+
355
+ ctx.commands.register({
356
+ name: "wf-validate",
357
+ description: "Validate workflow YAML and arguments without execution",
358
+ input: { hint: "<workflow.yaml> [key=value ...]" },
359
+ handler: (invocation: CommandInvocation): Promise<CommandResult> => {
360
+ const effects = new DshWorkflowEffectContext({
361
+ ctx,
362
+ agent: invocation.agent,
363
+ log,
364
+ });
365
+ return validateWorkflowTarget(invocation.rawInput, effects);
366
+ },
367
+ });
368
+ }
369
+
370
+ // Re-export pure parsers and utilities
371
+ export {
372
+ formatOutputRetryPrompt,
373
+ formatStepPrompt,
374
+ formatValidationSummary,
375
+ formatWorkflowList,
376
+ formatWorkflowParamDescriptor,
377
+ interpolateTemplate,
378
+ isFlatChoiceMapping,
379
+ parseBoolean,
380
+ parseInvocationInput,
381
+ parseSubagentShorthand,
382
+ parseWorkflowDocument,
383
+ parseWorkflowFile,
384
+ parseWorkflowSummary,
385
+ preprocessWorkflow,
386
+ resolveGate,
387
+ resolveWorkflowArgs,
388
+ } from "./parser.ts";
389
+
390
+ // Re-export pure validation rules and types
391
+ export {
392
+ formatValidationErrors,
393
+ ruleDuplicateOutputNames,
394
+ ruleStepOutputReferences,
395
+ ruleSubagentDependencies,
396
+ ruleSubagentOutputRequired,
397
+ ruleTemplateArgs,
398
+ ruleUnusedOutputs,
399
+ ruleWorkflowNameOutputReferences,
400
+ type ValidationError,
401
+ validateWorkflow,
402
+ WORKFLOW_RULES,
403
+ type WorkflowRule,
404
+ type WorkflowValidationContext,
405
+ } from "./rules.ts";
406
+
407
+ // Re-export runtime execution functions
408
+ export {
409
+ discardWorkflow,
410
+ executeValidatedWorkflow,
411
+ executeWorkflow,
412
+ listWorkflows,
413
+ resumeWorkflow,
414
+ type ValidatedWorkflow,
415
+ validateWorkflowInvocation,
416
+ validateWorkflowTarget,
417
+ } from "./runner.ts";
418
+
419
+ // Re-export pure transitions and folding
420
+ export {
421
+ applyAbort,
422
+ applyGatePause,
423
+ applyStepPause,
424
+ computeStepTransition,
425
+ foldWorkflowState,
426
+ type TransitionParams,
427
+ } from "./transitions.ts";
428
+
429
+ // Re-export domain types and schemas
430
+ export {
431
+ type FileOutputBase,
432
+ FileOutputBaseSchema,
433
+ type FormatStepPromptOptions,
434
+ type ParsedInvocation,
435
+ type StepOutputDef,
436
+ StepOutputDefSchema,
437
+ type StepOutputsMap,
438
+ StepOutputsMapSchema,
439
+ type SubagentConfig,
440
+ SubagentConfigSchema,
441
+ type TransitionResult,
442
+ WORKFLOW_EVENT_NAME,
443
+ type WorkflowArg,
444
+ WorkflowArgSchema,
445
+ type WorkflowDocument,
446
+ type WorkflowEffect,
447
+ type WorkflowFile,
448
+ WorkflowFileSchema,
449
+ type WorkflowFileStep,
450
+ WorkflowFileStepSchema,
451
+ type WorkflowFoldResult,
452
+ type WorkflowGroup,
453
+ type WorkflowInitPayloadData,
454
+ type WorkflowInvocation,
455
+ type WorkflowOutputPayloadData,
456
+ type WorkflowParamSummary,
457
+ type WorkflowPayload,
458
+ type WorkflowPrintPayloadData,
459
+ type WorkflowRun,
460
+ type WorkflowState,
461
+ type WorkflowStatePayloadData,
462
+ WorkflowStateSchema,
463
+ type WorkflowStatus,
464
+ WorkflowStatusSchema,
465
+ type WorkflowStep,
466
+ type WorkflowStepPayloadData,
467
+ type WorkflowSummary,
468
+ } from "./types.ts";