@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.
@@ -0,0 +1,655 @@
1
+ /**
2
+ * PURPOSE: Reactive client-side store and synchronization for session workflow states.
3
+ * ALLOWED: Reactive state, useSyncExternalStore, Cordis uiConversation event registration.
4
+ * FORBIDDEN: Direct DOM manipulation, UI rendering.
5
+ */
6
+
7
+ import type { Context as ClientContext } from "@deepseek-ai/cordis";
8
+ import type { SessionEventLike } from "@deepseek-ai/dsh-api-session-controller/client";
9
+ import type { ChatNode } from "@deepseek-ai/dsh-client-ui-chat/client";
10
+ import type { ConversationNodeDefinition } from "@deepseek-ai/dsh-client-ui-conversation/client";
11
+ import { SessionId } from "@deepseek-ai/dsh-session/types";
12
+ import { useSyncExternalStore } from "react";
13
+ import { foldWorkflowState, WORKFLOW_EVENT_NAME } from "../fold.ts";
14
+ import type { WorkflowPayload, WorkflowRun } from "../types.ts";
15
+ import type { WorkflowPrintChatData } from "./WorkflowPrintStep.tsx";
16
+ import type { WorkflowStepChatData } from "./WorkflowStepRow.tsx";
17
+
18
+ const workflowRuns = new Map<string, WorkflowRun>();
19
+ const activeSessionRuns = new Map<SessionId, string>();
20
+ const activeSessionSeq = new Map<SessionId, number>();
21
+ const listeners = new Set<() => void>();
22
+
23
+ /**
24
+ * Purpose: Retrieves the cached workflow run for a given run ID.
25
+ * Contract:
26
+ * - Inputs: runId string.
27
+ * - Outputs: WorkflowRun if present in store, or undefined.
28
+ * - Throws: None.
29
+ */
30
+ export function getWorkflowRunState(runId: string): WorkflowRun | undefined {
31
+ return workflowRuns.get(runId);
32
+ }
33
+
34
+ /**
35
+ * Purpose: Retrieves the cached active workflow run for a given session.
36
+ * Contract:
37
+ * - Inputs: non-null sessionId of type SessionId.
38
+ * - Outputs: WorkflowRun if present in store, or undefined.
39
+ * - Throws: None.
40
+ */
41
+ export function getWorkflowState(
42
+ sessionId: SessionId,
43
+ ): WorkflowRun | undefined {
44
+ const activeRunId = activeSessionRuns.get(sessionId);
45
+ if (activeRunId) {
46
+ return workflowRuns.get(activeRunId);
47
+ }
48
+ return undefined;
49
+ }
50
+
51
+ /**
52
+ * Purpose: Updates or sets workflow run for a session and runId, notifying subscribers.
53
+ * Contract:
54
+ * - Inputs: non-null sessionId of type SessionId, WorkflowRun object, runId string, optional seq.
55
+ * - Outputs: void.
56
+ * - Throws: None.
57
+ */
58
+ export function setWorkflowState(
59
+ sessionId: SessionId,
60
+ run: WorkflowRun,
61
+ runId: string,
62
+ seq?: number,
63
+ ): void {
64
+ workflowRuns.set(runId, run);
65
+
66
+ const lastSeq = activeSessionSeq.get(sessionId);
67
+ if (seq === undefined || lastSeq === undefined || seq >= lastSeq) {
68
+ activeSessionRuns.set(sessionId, runId);
69
+ if (seq !== undefined) {
70
+ activeSessionSeq.set(sessionId, seq);
71
+ }
72
+ }
73
+
74
+ for (const listener of listeners) {
75
+ listener();
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Purpose: Updates or sets cached workflow run without modifying active session run, notifying subscribers.
81
+ * Contract:
82
+ * - Inputs: runId string, WorkflowRun object.
83
+ * - Outputs: void.
84
+ * - Throws: None.
85
+ */
86
+ export function setWorkflowRunState(runId: string, run: WorkflowRun): void {
87
+ workflowRuns.set(runId, run);
88
+ for (const listener of listeners) {
89
+ listener();
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Purpose: Clears workflow run for a session and notifies subscribers.
95
+ * Contract:
96
+ * - Inputs: non-null sessionId of type SessionId.
97
+ * - Outputs: void.
98
+ * - Throws: None.
99
+ */
100
+ export function clearWorkflowState(sessionId: SessionId): void {
101
+ const activeRunId = activeSessionRuns.get(sessionId);
102
+ if (activeRunId) {
103
+ workflowRuns.delete(activeRunId);
104
+ activeSessionRuns.delete(sessionId);
105
+ }
106
+ activeSessionSeq.delete(sessionId);
107
+ for (const listener of listeners) {
108
+ listener();
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Purpose: Subscribes a listener callback to workflow store modifications.
114
+ * Contract:
115
+ * - Inputs: listener callback function.
116
+ * - Outputs: Cleanup unregister function.
117
+ * - Throws: None.
118
+ */
119
+ export function subscribeWorkflowState(listener: () => void): () => void {
120
+ listeners.add(listener);
121
+ return () => {
122
+ listeners.delete(listener);
123
+ };
124
+ }
125
+
126
+ /**
127
+ * Purpose: React hook subscribing to reactive workflow run for a specific run ID.
128
+ * Contract:
129
+ * - Inputs: runId string.
130
+ * - Outputs: WorkflowRun or undefined.
131
+ * - Throws: None.
132
+ */
133
+ export function useWorkflowRunState(runId: string): WorkflowRun | undefined {
134
+ return useSyncExternalStore(
135
+ subscribeWorkflowState,
136
+ () => getWorkflowRunState(runId),
137
+ () => getWorkflowRunState(runId),
138
+ );
139
+ }
140
+
141
+ /**
142
+ * Purpose: React hook subscribing to reactive workflow run for a given session.
143
+ * Contract:
144
+ * - Inputs: non-null sessionId of type SessionId.
145
+ * - Outputs: WorkflowRun or undefined.
146
+ * - Throws: None.
147
+ */
148
+ export function useWorkflowState(
149
+ sessionId: SessionId,
150
+ ): WorkflowRun | undefined {
151
+ return useSyncExternalStore(
152
+ subscribeWorkflowState,
153
+ () => getWorkflowState(sessionId),
154
+ () => getWorkflowState(sessionId),
155
+ );
156
+ }
157
+
158
+ export const workflowStateDefinition: ConversationNodeDefinition<WorkflowRun> =
159
+ {
160
+ kind: "wf-state",
161
+ target: "chat",
162
+ match(event) {
163
+ if (event.type === "command/run") {
164
+ const data = event.data as
165
+ | { readonly name?: string; readonly args?: string }
166
+ | undefined;
167
+ if (
168
+ data?.name === WORKFLOW_EVENT_NAME &&
169
+ typeof data.args === "string"
170
+ ) {
171
+ try {
172
+ const payload = JSON.parse(data.args) as WorkflowPayload;
173
+ if (
174
+ payload.action === "init" &&
175
+ typeof payload.runId === "string"
176
+ ) {
177
+ return { id: payload.runId, role: "start" };
178
+ }
179
+ if (
180
+ (payload.action === "state" || payload.action === "output") &&
181
+ typeof payload.runId === "string"
182
+ ) {
183
+ return { id: payload.runId, role: "update" };
184
+ }
185
+ } catch {
186
+ return null;
187
+ }
188
+ }
189
+ }
190
+ return null;
191
+ },
192
+ start(context, match) {
193
+ const run = foldWorkflowState([match.event], context.id);
194
+ if (!run) {
195
+ // type-safe: match guarantees event is a valid init event folding into WorkflowRun
196
+ throw new Error(
197
+ `Failed to fold workflow state for event ${match.event.seq}`,
198
+ );
199
+ }
200
+ const data = match.event.data as { readonly args: string };
201
+ const payload = JSON.parse(data.args) as WorkflowPayload;
202
+ setWorkflowState(payload.sessionId, run, context.id, match.event.seq);
203
+ return run;
204
+ },
205
+ update(context, match) {
206
+ const events = context.matches.map((m) => m.event);
207
+ const run = foldWorkflowState(events, context.id);
208
+ if (run) {
209
+ const data = match.event.data as { readonly args: string };
210
+ const payload = JSON.parse(data.args) as WorkflowPayload;
211
+ setWorkflowState(payload.sessionId, run, context.id, match.event.seq);
212
+ return run;
213
+ }
214
+ return context.state;
215
+ },
216
+ buildViewNode(context) {
217
+ if (!context.state) return null;
218
+ const startMatch = context.start;
219
+ return {
220
+ key: context.key,
221
+ kind: "wf-state",
222
+ id: context.id,
223
+ target: "chat",
224
+ anchorSeq: startMatch ? startMatch.event.seq : 0,
225
+ location: startMatch ? startMatch.location : { kind: "unresolved" },
226
+ visibility: "visible",
227
+ groupTree: "process",
228
+ data: context.state,
229
+ };
230
+ },
231
+ };
232
+
233
+ export const workflowStepDefinition: ConversationNodeDefinition<WorkflowStepChatData> =
234
+ {
235
+ kind: "wf-step",
236
+ target: "chat",
237
+ match(event) {
238
+ if (event.type === "command/run") {
239
+ const data = event.data as
240
+ | { readonly name?: string; readonly args?: string }
241
+ | undefined;
242
+ if (
243
+ data?.name === WORKFLOW_EVENT_NAME &&
244
+ typeof data.args === "string"
245
+ ) {
246
+ try {
247
+ const payload = JSON.parse(data.args) as WorkflowPayload;
248
+ if (
249
+ payload.action === "step" &&
250
+ typeof payload.runId === "string"
251
+ ) {
252
+ return { id: payload.id, role: "start" };
253
+ }
254
+ } catch {
255
+ return null;
256
+ }
257
+ }
258
+ }
259
+ return null;
260
+ },
261
+ start(_context, match) {
262
+ const data = match.event.data as {
263
+ readonly args: string;
264
+ };
265
+ const payload = JSON.parse(data.args) as Extract<
266
+ WorkflowPayload,
267
+ { action: "step" }
268
+ >;
269
+ return {
270
+ stepIndex: payload.stepIndex,
271
+ label: payload.label,
272
+ kind: payload.kind,
273
+ sessionId: payload.sessionId,
274
+ runId: payload.runId,
275
+ };
276
+ },
277
+ update(context, match) {
278
+ const data = match.event.data as {
279
+ readonly args?: string;
280
+ };
281
+ if (data?.args && typeof data.args === "string") {
282
+ try {
283
+ const payload = JSON.parse(data.args) as Extract<
284
+ WorkflowPayload,
285
+ { action: "step" }
286
+ >;
287
+ return {
288
+ stepIndex: payload.stepIndex,
289
+ label: payload.label,
290
+ kind: payload.kind,
291
+ sessionId: payload.sessionId,
292
+ runId: payload.runId,
293
+ };
294
+ } catch {
295
+ // retain state on parse failure
296
+ }
297
+ }
298
+ return context.state;
299
+ },
300
+ buildViewNode(context) {
301
+ if (context.state === undefined) return null;
302
+ const startMatch = context.start;
303
+ return {
304
+ key: context.key,
305
+ kind: "wf-step",
306
+ id: context.id,
307
+ target: "chat",
308
+ anchorSeq: startMatch ? startMatch.event.seq : 0,
309
+ location: startMatch ? startMatch.location : { kind: "unresolved" },
310
+ visibility: "visible",
311
+ groupTree: "process",
312
+ data: context.state,
313
+ };
314
+ },
315
+ };
316
+
317
+ export const workflowPrintDefinition: ConversationNodeDefinition<WorkflowPrintChatData> =
318
+ {
319
+ kind: "wf-print",
320
+ target: "chat",
321
+ match(event) {
322
+ if (event.type === "command/run") {
323
+ const data = event.data as
324
+ | { readonly name?: string; readonly args?: string }
325
+ | undefined;
326
+ if (
327
+ data?.name === WORKFLOW_EVENT_NAME &&
328
+ typeof data.args === "string"
329
+ ) {
330
+ try {
331
+ const payload = JSON.parse(data.args) as WorkflowPayload;
332
+ if (
333
+ payload.action === "print" &&
334
+ typeof payload.runId === "string"
335
+ ) {
336
+ return { id: payload.id, role: "start" };
337
+ }
338
+ } catch {
339
+ return null;
340
+ }
341
+ }
342
+ }
343
+ return null;
344
+ },
345
+ start(_context, match) {
346
+ const data = match.event.data as { readonly args: string };
347
+ const payload = JSON.parse(data.args) as Extract<
348
+ WorkflowPayload,
349
+ { action: "print" }
350
+ >;
351
+ return {
352
+ id: payload.id,
353
+ text: payload.text,
354
+ runId: payload.runId,
355
+ sessionId: payload.sessionId,
356
+ };
357
+ },
358
+ update(context) {
359
+ return context.state;
360
+ },
361
+ buildViewNode(context) {
362
+ if (context.state === undefined) return null;
363
+ const startMatch = context.start;
364
+ return {
365
+ key: context.key,
366
+ kind: "wf-print",
367
+ id: context.id,
368
+ target: "chat",
369
+ anchorSeq: startMatch ? startMatch.event.seq : 0,
370
+ location: startMatch ? startMatch.location : { kind: "unresolved" },
371
+ visibility: "visible",
372
+ groupTree: "process",
373
+ data: context.state,
374
+ };
375
+ },
376
+ };
377
+
378
+ export interface WorkflowErrorState {
379
+ readonly commandId: string;
380
+ readonly name: string;
381
+ readonly args?: string | null;
382
+ readonly outcome?: { readonly kind: string; readonly text?: string } | null;
383
+ }
384
+
385
+ const trackedWfCommandIds = new Set<string>();
386
+
387
+ export const workflowErrorDefinition: ConversationNodeDefinition<WorkflowErrorState> =
388
+ {
389
+ kind: "wf-error",
390
+ target: "chat",
391
+ match(event) {
392
+ if (event.type === "command/run") {
393
+ const data = event.data as
394
+ | {
395
+ readonly name?: string;
396
+ readonly commandId?: string;
397
+ readonly args?: string;
398
+ }
399
+ | undefined;
400
+ if (
401
+ (data?.name === "wf" ||
402
+ data?.name === "wf-resume" ||
403
+ data?.name === "wf-abort") &&
404
+ data.commandId
405
+ ) {
406
+ const id = String(data.commandId);
407
+ trackedWfCommandIds.add(id);
408
+ return { id, role: "start" };
409
+ }
410
+ }
411
+ if (event.type === "command/done") {
412
+ const data = event.data as { readonly commandId?: string } | undefined;
413
+ if (
414
+ data?.commandId &&
415
+ trackedWfCommandIds.has(String(data.commandId))
416
+ ) {
417
+ const id = String(data.commandId);
418
+ trackedWfCommandIds.delete(id);
419
+ return { id, role: "update" };
420
+ }
421
+ }
422
+ return null;
423
+ },
424
+ start(_context, match) {
425
+ const data = match.event.data as {
426
+ readonly commandId: string;
427
+ readonly name: string;
428
+ readonly args?: string;
429
+ };
430
+ return {
431
+ commandId: String(data.commandId),
432
+ name: data.name,
433
+ args: data.args,
434
+ outcome: null,
435
+ };
436
+ },
437
+ update(context, match) {
438
+ const data = match.event.data as {
439
+ readonly kind: string;
440
+ readonly text?: string;
441
+ };
442
+ return {
443
+ ...context.state,
444
+ outcome: {
445
+ kind: data.kind,
446
+ text: data.text,
447
+ },
448
+ };
449
+ },
450
+ buildViewNode(context) {
451
+ if (context.state?.outcome?.kind !== "error") return null;
452
+ const startMatch = context.start;
453
+ return {
454
+ key: context.key,
455
+ kind: "wf-error",
456
+ id: context.id,
457
+ target: "chat",
458
+ anchorSeq: startMatch ? startMatch.event.seq : 0,
459
+ location: startMatch ? startMatch.location : { kind: "unresolved" },
460
+ visibility: "visible",
461
+ groupTree: "process",
462
+ data: {
463
+ name: context.state.name,
464
+ args: context.state.args,
465
+ text: context.state.outcome.text ?? "Command failed",
466
+ },
467
+ };
468
+ },
469
+ };
470
+
471
+ function workflowRequestEvent(event: SessionEventLike):
472
+ | {
473
+ readonly kind: "request";
474
+ readonly runId: string;
475
+ readonly rawInput: string;
476
+ readonly sessionId: SessionId;
477
+ }
478
+ | { readonly kind: "settled"; readonly runId: string }
479
+ | undefined {
480
+ if (event.type === "command/done" && event.data.kind === "error") {
481
+ return { kind: "settled", runId: event.data.commandId };
482
+ }
483
+ if (
484
+ event.type !== "command/run" ||
485
+ event.data.name !== WORKFLOW_EVENT_NAME ||
486
+ event.data.args === undefined
487
+ )
488
+ return undefined;
489
+ let payload: unknown;
490
+ try {
491
+ payload = JSON.parse(event.data.args);
492
+ } catch {
493
+ return undefined;
494
+ }
495
+ if (
496
+ typeof payload !== "object" ||
497
+ payload === null ||
498
+ !("action" in payload) ||
499
+ !("runId" in payload) ||
500
+ typeof payload.runId !== "string"
501
+ )
502
+ return undefined;
503
+ if (payload.action === "init" || payload.action === "request-failed") {
504
+ return { kind: "settled", runId: payload.runId };
505
+ }
506
+ if (
507
+ payload.action !== "request" ||
508
+ !("rawInput" in payload) ||
509
+ typeof payload.rawInput !== "string" ||
510
+ !("sessionId" in payload) ||
511
+ typeof payload.sessionId !== "string"
512
+ )
513
+ return undefined;
514
+ return {
515
+ kind: "request",
516
+ runId: payload.runId,
517
+ rawInput: payload.rawInput,
518
+ sessionId: SessionId(payload.sessionId),
519
+ };
520
+ }
521
+
522
+ const workflowRequestDefinition: ConversationNodeDefinition<{
523
+ readonly output: WorkflowPrintChatData;
524
+ readonly status: "queued" | "settled";
525
+ }> = {
526
+ kind: "wf-request",
527
+ target: "chat",
528
+ match(event) {
529
+ const request = workflowRequestEvent(event);
530
+ if (request === undefined) return null;
531
+ return {
532
+ id: request.runId,
533
+ role: request.kind === "request" ? "start" : "update",
534
+ };
535
+ },
536
+ start(_context, { event }) {
537
+ const request = workflowRequestEvent(event);
538
+ if (request === undefined || request.kind !== "request")
539
+ throw new Error("wf-request requires a request event to start");
540
+ return {
541
+ status: "queued",
542
+ output: {
543
+ text: `Workflow queued:\n\n /wf ${request.rawInput.trim().replaceAll("\n", "\n ")}`,
544
+ runId: request.runId,
545
+ sessionId: request.sessionId,
546
+ },
547
+ };
548
+ },
549
+ update(context, match) {
550
+ return match.role === "start"
551
+ ? context.state
552
+ : { ...context.state, status: "settled" };
553
+ },
554
+ buildViewNode(context) {
555
+ if (context.state === undefined) return null;
556
+ const first = context.matches[0];
557
+ return {
558
+ key: context.key,
559
+ kind: "wf-print",
560
+ id: context.id,
561
+ target: "chat",
562
+ anchorSeq: first.event.seq,
563
+ location: first.location,
564
+ visibility: context.state.status === "queued" ? "visible" : "hidden",
565
+ groupTree: "process",
566
+ data: context.state.output,
567
+ } satisfies ChatNode<"wf-print">;
568
+ },
569
+ };
570
+
571
+ const workflowListDefinition: ConversationNodeDefinition<
572
+ ChatNode<"wf-list">["data"]
573
+ > = {
574
+ kind: "wf-list",
575
+ target: "chat",
576
+ match(event) {
577
+ if (event.type === "command/run" && event.data.name === "wf-list") {
578
+ return { id: event.data.commandId, role: "start" };
579
+ }
580
+ // edge case: command/done has no name; the assembler pairs it with a matching start by commandId.
581
+ if (event.type === "command/done") {
582
+ return { id: event.data.commandId, role: "update" };
583
+ }
584
+ return null;
585
+ },
586
+ start(_context, { event }) {
587
+ if (event.type !== "command/run") {
588
+ throw new Error("wf-list requires command/run to start");
589
+ }
590
+ return {
591
+ name: event.data.name,
592
+ args: event.data.args === undefined ? null : event.data.args,
593
+ outcome: null,
594
+ };
595
+ },
596
+ update(context, { event }) {
597
+ if (event.type !== "command/done") return context.state;
598
+ return {
599
+ ...context.state,
600
+ outcome: { kind: event.data.kind, text: event.data.text },
601
+ };
602
+ },
603
+ buildViewNode(context) {
604
+ // edge case: Paged history can load settlement before command/run; no result exists until its start loads.
605
+ if (context.state === undefined) return null;
606
+ const first = context.matches[0];
607
+ return {
608
+ key: context.key,
609
+ kind: "wf-list",
610
+ id: context.id,
611
+ target: "chat",
612
+ anchorSeq: first.event.seq,
613
+ location: first.location,
614
+ visibility: "visible",
615
+ groupTree: "process",
616
+ data: context.state,
617
+ } satisfies ChatNode<"wf-list">;
618
+ },
619
+ };
620
+
621
+ /**
622
+ * Purpose: Registers workflow request, state, step, print, error, and list conversation nodes on Cordis uiConversation service.
623
+ * Contract:
624
+ * - Inputs: ClientContext with uiConversation service.
625
+ * - Outputs: Cleanup unregister function.
626
+ * - Throws: None.
627
+ */
628
+ export function registerWorkflowChatNodes(ctx: ClientContext): () => void {
629
+ const unregisterRequest = ctx.uiConversation.events.register(
630
+ workflowRequestDefinition,
631
+ );
632
+ const unregisterState = ctx.uiConversation.events.register(
633
+ workflowStateDefinition,
634
+ );
635
+ const unregisterStep = ctx.uiConversation.events.register(
636
+ workflowStepDefinition,
637
+ );
638
+ const unregisterPrint = ctx.uiConversation.events.register(
639
+ workflowPrintDefinition,
640
+ );
641
+ const unregisterError = ctx.uiConversation.events.register(
642
+ workflowErrorDefinition,
643
+ );
644
+ const unregisterList = ctx.uiConversation.events.register(
645
+ workflowListDefinition,
646
+ );
647
+ return () => {
648
+ unregisterRequest();
649
+ unregisterState();
650
+ unregisterStep();
651
+ unregisterPrint();
652
+ unregisterError();
653
+ unregisterList();
654
+ };
655
+ }