@leitwerk-dev/showcase-processes 0.1.0 → 0.1.2

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.
Files changed (41) hide show
  1. package/dist/index.d.ts +106 -11
  2. package/dist/index.js +1240 -53
  3. package/dist/index.js.map +1 -1
  4. package/package.json +4 -4
  5. package/dist/file-action-triggers.d.ts +0 -9
  6. package/dist/file-action-triggers.d.ts.map +0 -1
  7. package/dist/file-action-triggers.js +0 -87
  8. package/dist/file-action-triggers.js.map +0 -1
  9. package/dist/file-external.d.ts +0 -16
  10. package/dist/file-external.d.ts.map +0 -1
  11. package/dist/file-external.js +0 -198
  12. package/dist/file-external.js.map +0 -1
  13. package/dist/index.d.ts.map +0 -1
  14. package/dist/poem-leaf-outcome.d.ts +0 -41
  15. package/dist/poem-leaf-outcome.d.ts.map +0 -1
  16. package/dist/poem-leaf-outcome.js +0 -110
  17. package/dist/poem-leaf-outcome.js.map +0 -1
  18. package/dist/process-definition.d.ts +0 -18
  19. package/dist/process-definition.d.ts.map +0 -1
  20. package/dist/process-definition.js +0 -832
  21. package/dist/process-definition.js.map +0 -1
  22. package/dist/turns/external-complete.d.ts +0 -6
  23. package/dist/turns/external-complete.d.ts.map +0 -1
  24. package/dist/turns/external-complete.js +0 -6
  25. package/dist/turns/external-complete.js.map +0 -1
  26. package/dist/turns/poem-creator.d.ts +0 -15
  27. package/dist/turns/poem-creator.d.ts.map +0 -1
  28. package/dist/turns/poem-creator.js +0 -72
  29. package/dist/turns/poem-creator.js.map +0 -1
  30. package/dist/turns/run-single-prompt.d.ts +0 -8
  31. package/dist/turns/run-single-prompt.d.ts.map +0 -1
  32. package/dist/turns/run-single-prompt.js +0 -57
  33. package/dist/turns/run-single-prompt.js.map +0 -1
  34. package/dist/ui/leaf-outcome-element.d.ts +0 -2
  35. package/dist/ui/leaf-outcome-element.d.ts.map +0 -1
  36. package/dist/ui/leaf-outcome-element.js +0 -79
  37. package/dist/ui/leaf-outcome-element.js.map +0 -1
  38. package/dist/ui/poem-leaf-outcome-element.d.ts +0 -2
  39. package/dist/ui/poem-leaf-outcome-element.d.ts.map +0 -1
  40. package/dist/ui/poem-leaf-outcome-element.js +0 -171
  41. package/dist/ui/poem-leaf-outcome-element.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,55 +1,1242 @@
1
+ // src/index.ts
1
2
  import { coreHostCapabilities } from "@leitwerk-dev/process-sdk";
2
- import { createFileExternalSourceProvider } from "./file-external.js";
3
- import { k8sSmokeLongProcess, k8sSmokeProcess, k8sSmokeSpecializedProcess, poemCreatorProcess, singlePromptExternalCompleteProcess, singlePromptProcess, singlePromptWithToolProcess, } from "./process-definition.js";
4
- import { leaveFeedbackToolRenderer } from "./turns/poem-creator.js";
5
- export const manifest = {
6
- id: "showcase-processes",
7
- version: "0.1.0",
8
- };
9
- const fileTriggerDefaults = {
10
- poll_interval: "1s",
11
- poem_review_path: "/tmp/poem-review-{instanceId}",
12
- complete_prompt_path: "/tmp/complete-prompt",
13
- };
14
- const singlePromptExtension = {
15
- manifest,
16
- setupCatalog(api) {
17
- api.registerToolRenderer(leaveFeedbackToolRenderer);
18
- api.registerProcess(singlePromptProcess);
19
- api.registerProcess(singlePromptWithToolProcess);
20
- api.registerProcess(singlePromptExternalCompleteProcess);
21
- api.registerProcess(k8sSmokeProcess);
22
- api.registerProcess(k8sSmokeSpecializedProcess);
23
- api.registerProcess(k8sSmokeLongProcess);
24
- api.registerProcess(poemCreatorProcess);
25
- },
26
- setupServer(api, rawConfig) {
27
- const deps = api.get(coreHostCapabilities.serverSetup);
28
- if (!deps || Array.isArray(deps)) {
29
- return;
30
- }
31
- const config = (rawConfig ?? {});
32
- const resolvedFileTriggerConfig = {
33
- ...fileTriggerDefaults,
34
- ...config.file_triggers,
35
- };
36
- const fileSourceProvider = createFileExternalSourceProvider(deps, {
37
- "/tmp/complete-prompt": resolvedFileTriggerConfig.complete_prompt_path,
38
- "/tmp/poem-review-{instanceId}": resolvedFileTriggerConfig.poem_review_path,
39
- });
40
- api.onStart(() => {
41
- fileSourceProvider.start();
42
- });
43
- api.onStop(() => {
44
- fileSourceProvider.stop();
45
- });
46
- },
47
- };
48
- export default singlePromptExtension;
49
- export * from "./file-external.js";
50
- export * from "./poem-leaf-outcome.js";
51
- export * from "./process-definition.js";
52
- export * from "./turns/external-complete.js";
53
- export * from "./turns/poem-creator.js";
54
- export * from "./turns/run-single-prompt.js";
3
+
4
+ // src/file-external.ts
5
+ import {
6
+ consumeTriggerFile,
7
+ createPollLoop,
8
+ emptyPollResult,
9
+ parseDurationMs,
10
+ readTriggerFile
11
+ } from "@leitwerk-dev/watcher-utils";
12
+ var FILE_EXTERNAL_PRESENCE_KIND = "@leitwerk-dev/showcase-processes.file.presence";
13
+ var FILE_EXTERNAL_INSTRUCTION_KIND = "@leitwerk-dev/showcase-processes.file.instruction";
14
+ function normalizeConfig(input) {
15
+ return {
16
+ path: input.path,
17
+ pollInterval: input.pollInterval,
18
+ consume: input.consume
19
+ };
20
+ }
21
+ function interpolateTemplate(template, values) {
22
+ return template.replace(/\{([a-zA-Z0-9_]+)\}/g, (match, key) => values[key] ?? match);
23
+ }
24
+ function resolveFileConfig(input, ctx) {
25
+ return {
26
+ ...input,
27
+ path: interpolateTemplate(input.path, { instanceId: ctx.process.id })
28
+ };
29
+ }
30
+ function fileLabel(kind, path) {
31
+ return kind === "presence" ? `File present: ${path}` : `File instruction: ${path}`;
32
+ }
33
+ var fileExternal = {
34
+ presence(input) {
35
+ const config = normalizeConfig(input);
36
+ return {
37
+ kind: FILE_EXTERNAL_PRESENCE_KIND,
38
+ label: fileLabel("presence", config.path),
39
+ description: `Fires when ${config.path} exists`,
40
+ config,
41
+ inputMode: "none",
42
+ resolve(ctx) {
43
+ return resolveFileConfig(config, ctx);
44
+ }
45
+ };
46
+ },
47
+ instruction(input) {
48
+ const config = normalizeConfig(input);
49
+ return {
50
+ kind: FILE_EXTERNAL_INSTRUCTION_KIND,
51
+ label: fileLabel("instruction", config.path),
52
+ description: `Reads ${config.path} as instruction text`,
53
+ config,
54
+ inputMode: "instruction",
55
+ resolve(ctx) {
56
+ return resolveFileConfig(config, ctx);
57
+ }
58
+ };
59
+ }
60
+ };
61
+ function parseFileConfig(value) {
62
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
63
+ return null;
64
+ }
65
+ const record = value;
66
+ if (typeof record.path !== "string" || record.path.trim() === "") {
67
+ return null;
68
+ }
69
+ return {
70
+ path: record.path,
71
+ pollInterval: typeof record.pollInterval === "string" ? record.pollInterval : "1s",
72
+ consume: record.consume === "keep" ? "keep" : "delete"
73
+ };
74
+ }
75
+ async function maybeConsume(config) {
76
+ if (config.consume === "delete") {
77
+ await consumeTriggerFile(config.path);
78
+ }
79
+ }
80
+ function createDueTracker() {
81
+ const nextDueAtByKey = /* @__PURE__ */ new Map();
82
+ return {
83
+ isDue(key, pollInterval, nowMs = Date.now()) {
84
+ const nextDueAt = nextDueAtByKey.get(key) ?? 0;
85
+ if (nextDueAt > nowMs) {
86
+ return false;
87
+ }
88
+ const intervalMs = parseDurationMs(pollInterval, 1e3);
89
+ nextDueAtByKey.set(key, nowMs + intervalMs);
90
+ return true;
91
+ },
92
+ prune(activeKeys) {
93
+ for (const key of [...nextDueAtByKey.keys()]) {
94
+ if (!activeKeys.has(key)) {
95
+ nextDueAtByKey.delete(key);
96
+ }
97
+ }
98
+ }
99
+ };
100
+ }
101
+ function resolveArmedFileConfig(armed, resolveAlias) {
102
+ const parsed = parseFileConfig(armed.resolved) ?? parseFileConfig(armed.source.config);
103
+ return parsed ? resolveAlias(parsed) : null;
104
+ }
105
+ async function pollArmedFileSource(armed, resolveConfig, isDue, activeKeys, result) {
106
+ const config = resolveArmedFileConfig(armed, resolveConfig);
107
+ if (!config) {
108
+ result.errors.push(`${armed.id}:invalid_config`);
109
+ return null;
110
+ }
111
+ const key = `${armed.instanceId}:${armed.id}`;
112
+ activeKeys.add(key);
113
+ if (!isDue(key, config.pollInterval)) {
114
+ return null;
115
+ }
116
+ const file = await readTriggerFile(config.path);
117
+ if (!file.exists) {
118
+ return null;
119
+ }
120
+ return { config, file };
121
+ }
122
+ async function firePresenceSources(deps, result, resolveConfig, isDue, activeKeys) {
123
+ for (const armed of deps.externalSources.listArmed(FILE_EXTERNAL_PRESENCE_KIND)) {
124
+ const target = await pollArmedFileSource(armed, resolveConfig, isDue, activeKeys, result);
125
+ if (!target) {
126
+ continue;
127
+ }
128
+ const { config } = target;
129
+ const fired = await deps.externalSources.fire({
130
+ instanceId: armed.instanceId,
131
+ armingId: armed.id,
132
+ event: { path: config.path, pollInterval: config.pollInterval },
133
+ mergeKey: config.path
134
+ });
135
+ if (!fired.ok) {
136
+ result.errors.push(`${armed.id}:${fired.code ?? fired.error ?? "fire_failed"}`);
137
+ continue;
138
+ }
139
+ await maybeConsume(config);
140
+ result.created.push(armed.id);
141
+ }
142
+ }
143
+ async function fireInstructionSources(deps, result, resolveConfig, isDue, activeKeys) {
144
+ for (const armed of deps.externalSources.listArmed(FILE_EXTERNAL_INSTRUCTION_KIND)) {
145
+ const target = await pollArmedFileSource(armed, resolveConfig, isDue, activeKeys, result);
146
+ if (!target) {
147
+ continue;
148
+ }
149
+ const { config, file } = target;
150
+ const instruction = file.content.trim();
151
+ if (!instruction) {
152
+ continue;
153
+ }
154
+ const fired = await deps.externalSources.fire({
155
+ instanceId: armed.instanceId,
156
+ armingId: armed.id,
157
+ input: { instruction },
158
+ event: { path: config.path, pollInterval: config.pollInterval },
159
+ mergeKey: config.path
160
+ });
161
+ if (!fired.ok) {
162
+ result.errors.push(`${armed.id}:${fired.code ?? fired.error ?? "fire_failed"}`);
163
+ continue;
164
+ }
165
+ await maybeConsume(config);
166
+ result.created.push(armed.id);
167
+ }
168
+ }
169
+ function createFileExternalSourceProvider(deps, aliases = {}) {
170
+ function applyAlias(config) {
171
+ const exact = aliases[config.path];
172
+ if (exact) {
173
+ return { ...config, path: exact };
174
+ }
175
+ for (const [template, replacement] of Object.entries(aliases)) {
176
+ if (!replacement || !template.includes("{instanceId}")) {
177
+ continue;
178
+ }
179
+ const [prefix, suffix = ""] = template.split("{instanceId}");
180
+ if (!prefix || !config.path.startsWith(prefix) || !config.path.endsWith(suffix)) {
181
+ continue;
182
+ }
183
+ const instanceId = config.path.slice(prefix.length, config.path.length - suffix.length);
184
+ return {
185
+ ...config,
186
+ path: replacement.includes("{instanceId}") ? interpolateTemplate(replacement, { instanceId }) : replacement
187
+ };
188
+ }
189
+ return config;
190
+ }
191
+ const due = createDueTracker();
192
+ return createPollLoop({
193
+ pollInterval: () => "50ms",
194
+ isEnabled: () => true,
195
+ defaultIntervalMs: 50,
196
+ async pollOnce() {
197
+ const result = emptyPollResult();
198
+ const activeKeys = /* @__PURE__ */ new Set();
199
+ await firePresenceSources(deps, result, applyAlias, due.isDue, activeKeys);
200
+ await fireInstructionSources(deps, result, applyAlias, due.isDue, activeKeys);
201
+ due.prune(activeKeys);
202
+ return result;
203
+ }
204
+ });
205
+ }
206
+
207
+ // src/process-definition.ts
208
+ import { execFileSync } from "child_process";
209
+ import { setTimeout as delay } from "timers/promises";
210
+ import { createReviewSubject } from "@leitwerk-dev/domain";
211
+ import {
212
+ createEmptyStructuralProcessState,
213
+ flow,
214
+ parseStructuralProcessState
215
+ } from "@leitwerk-dev/process-sdk";
216
+
217
+ // src/poem-leaf-outcome.ts
218
+ import { normalizeMarkdownText } from "@leitwerk-dev/domain";
219
+ function normalizePoemBody(body) {
220
+ return body.replace(/<br\s*\/?>/gi, "\n");
221
+ }
222
+ function normalizeOptionalText(value) {
223
+ if (typeof value !== "string") {
224
+ return null;
225
+ }
226
+ const trimmed = value.trim();
227
+ return trimmed === "" ? null : trimmed;
228
+ }
229
+ function normalizeReview(review) {
230
+ if (!review) {
231
+ return null;
232
+ }
233
+ return {
234
+ outcome: review.outcome,
235
+ summary: normalizeOptionalText(review.summary),
236
+ feedback: normalizeOptionalText(review.feedback)
237
+ };
238
+ }
239
+ function uniqueNonEmptyStrings(values) {
240
+ const seen = /* @__PURE__ */ new Set();
241
+ const result = [];
242
+ for (const value of values) {
243
+ if (!value || seen.has(value)) {
244
+ continue;
245
+ }
246
+ seen.add(value);
247
+ result.push(value);
248
+ }
249
+ return result;
250
+ }
251
+ function extractLeafEntryMarkdown(entry) {
252
+ const content = entry?.message?.content;
253
+ return typeof content === "string" && content.trim() !== "" ? content.trim() : null;
254
+ }
255
+ function resolvePoemLeafMarkdown(input) {
256
+ const turnResultMarkdown = input.turnResultMarkdown?.trim() ?? "";
257
+ if (turnResultMarkdown !== "") {
258
+ return turnResultMarkdown;
259
+ }
260
+ return extractLeafEntryMarkdown(input.leafEntry) ?? "";
261
+ }
262
+ function parsePoemLeafMarkdown(markdown) {
263
+ const normalized = normalizeMarkdownText(markdown);
264
+ if (normalized === "") {
265
+ return { title: null, stanzas: [] };
266
+ }
267
+ const lines = normalized.split("\n");
268
+ let title = null;
269
+ let bodyStartIndex = 0;
270
+ for (let index = 0; index < lines.length; index += 1) {
271
+ const line = lines[index]?.trim() ?? "";
272
+ if (line === "") {
273
+ continue;
274
+ }
275
+ if (line.startsWith("#")) {
276
+ title = line.replace(/^#{1,6}\s*/, "").trim() || null;
277
+ bodyStartIndex = index + 1;
278
+ }
279
+ break;
280
+ }
281
+ const body = normalizePoemBody(lines.slice(bodyStartIndex).join("\n")).trim();
282
+ if (body === "") {
283
+ return { title, stanzas: [] };
284
+ }
285
+ const stanzas = body.split(/\n\s*\n+/).map(
286
+ (stanza) => stanza.split("\n").map((line) => line.trim()).filter((line) => line !== "")
287
+ ).filter((stanza) => stanza.length > 0);
288
+ return { title, stanzas };
289
+ }
290
+ function buildPoemLeafOutcomePayload(input) {
291
+ const normalizedMarkdown = normalizeMarkdownText(input.markdown);
292
+ const parsed = parsePoemLeafMarkdown(normalizedMarkdown);
293
+ const review = normalizeReview(input.review);
294
+ return {
295
+ prompt: input.prompt,
296
+ markdown: normalizedMarkdown,
297
+ title: parsed.title,
298
+ stanzas: parsed.stanzas,
299
+ ...review ? { review } : {}
300
+ };
301
+ }
302
+ function buildPoemLeafOutcomeFallbackMarkdown(input) {
303
+ const normalizedMarkdown = normalizeMarkdownText(input.markdown);
304
+ const review = normalizeReview(input.review);
305
+ if (!review) {
306
+ return normalizedMarkdown;
307
+ }
308
+ const reviewSectionHeading = review.outcome === "no_issues" ? "## LLM Opinion" : "## Review";
309
+ const reviewParagraphs = review.outcome === "no_issues" ? uniqueNonEmptyStrings([review.summary ?? "The automated review found no issues."]) : uniqueNonEmptyStrings([
310
+ review.summary,
311
+ review.feedback,
312
+ review.summary === null && review.feedback === null ? "The automated review reported issues but returned no details." : null
313
+ ]);
314
+ const reviewSection = [reviewSectionHeading, ...reviewParagraphs].join("\n\n");
315
+ return [normalizedMarkdown, reviewSection].filter((section) => section.trim() !== "").join("\n\n");
316
+ }
317
+
318
+ // src/turns/external-complete.ts
319
+ var externalCompleteActionId = "complete_external_prompt";
320
+ var externalPromptCompletionTurnId = "await_external_prompt_completion";
321
+ var externalPromptCompletionTurnDescription = "Wait for an external completion trigger after the single prompt finishes";
322
+ var externalPromptCompletionTriggerLabel = "Configured prompt-complete file";
323
+ var externalPromptCompletionTriggerDescription = "Write any content to the configured prompt-complete trigger file (default: /tmp/complete-prompt) to complete the process. The file is removed after a successful completion.";
324
+
325
+ // src/turns/poem-creator.ts
326
+ var poemCreatorActionIds = {
327
+ completePoem: "complete_poem",
328
+ requestRevision: "request_poem_revision",
329
+ runAutoReview: "run_poem_auto_review",
330
+ acceptReview: "accept_poem_review",
331
+ requestReviewChanges: "request_poem_review_changes",
332
+ dismissReview: "dismiss_poem_review"
333
+ };
334
+ function formatGermanyDay(now) {
335
+ return new Intl.DateTimeFormat("en-GB", {
336
+ timeZone: "Europe/Berlin",
337
+ weekday: "long",
338
+ day: "numeric",
339
+ month: "long",
340
+ year: "numeric"
341
+ }).format(now);
342
+ }
343
+ function buildDefaultPoemPrompt(now = /* @__PURE__ */ new Date()) {
344
+ const germanyDay = formatGermanyDay(now);
345
+ return `Write a short poem in Markdown that is either inspired by ${germanyDay} in Germany or by the craft of building cloud software. Keep it vivid, warm, and concise.`;
346
+ }
347
+ function buildDraftPoemInstruction(promptText) {
348
+ return `Write a short poem in Markdown that clearly responds to the operator's prompt.
349
+
350
+ Prompt:
351
+ ${promptText}
352
+
353
+ Requirements:
354
+ - include a title as a Markdown heading
355
+ - keep the poem concise
356
+ - make the imagery clearly connected to the prompt
357
+ - render each poetic line with an explicit HTML <br> so line breaks survive rendering
358
+ - do not rely on single Markdown newlines alone for poem line formatting
359
+ - only the primary branch should write or revise the poem directly`;
360
+ }
361
+ function buildRevisePoemInstruction(revisionGuidance) {
362
+ return `Continue from the current poem on this branch and revise it according to this request:
363
+
364
+ ${revisionGuidance}
365
+
366
+ Preserve the parts of the current poem that the request does not ask you to change. Return the complete revised poem in the same Markdown format.`;
367
+ }
368
+ function buildReviewPoemInstruction(promptText, poemDraftMarkdown) {
369
+ return `Review the latest poem draft against the operator's prompt.
370
+
371
+ Prompt:
372
+ ${promptText}
373
+
374
+ Poem draft to review:
375
+ ${poemDraftMarkdown}
376
+
377
+ You are reviewing the poem only. Do not draft, rewrite, or directly edit the poem. Only produce review feedback.
378
+
379
+ Explicit <br> line breaks in the poem body are expected for rendering and count as correct formatting.
380
+
381
+ If the poem is strong, relevant, and well-formed Markdown, call no_issues with a brief confirmation summary.
382
+ If the poem misses the prompt, needs revision, or is awkwardly structured, call leave_feedback with a brief summary and concise plain-text feedback.`;
383
+ }
384
+ var leaveFeedbackToolRenderer = {
385
+ toolName: "leave_feedback",
386
+ title: "Feedback",
387
+ fields: [
388
+ {
389
+ id: "message",
390
+ label: "Feedback",
391
+ kind: "plaintext",
392
+ source: "arguments",
393
+ path: "message"
394
+ }
395
+ ]
396
+ };
397
+
398
+ // src/turns/run-single-prompt.ts
399
+ import {
400
+ llmTurn,
401
+ REQUIRED_MARKDOWN_RESULT_TURN_RESULT
402
+ } from "@leitwerk-dev/process-sdk";
403
+ function buildSinglePromptInstruction(promptText) {
404
+ return `Run the following one-shot operator prompt exactly once.
405
+
406
+ ${promptText}`;
407
+ }
408
+ function buildSinglePromptWithToolInstruction(promptText) {
409
+ return `Run the following one-shot operator prompt exactly once.
410
+
411
+ ${promptText}
412
+
413
+ When you are done, call the done tool with a short summary of the result.`;
414
+ }
415
+ function createRunSinglePromptTurn(promptText) {
416
+ return llmTurn({
417
+ description: "Run a single operator-provided prompt and finish on turn end",
418
+ availableTools: ["read", "bash", "edit", "write"],
419
+ completionMode: "turn_end",
420
+ branchType: "primary",
421
+ context: "fresh",
422
+ prompt: () => buildSinglePromptInstruction(promptText),
423
+ outcomes: {},
424
+ turnEnd: {
425
+ outcome: "completed",
426
+ params: {},
427
+ complete: true
428
+ },
429
+ turnResultMarkdown: REQUIRED_MARKDOWN_RESULT_TURN_RESULT
430
+ });
431
+ }
432
+ function createRunSinglePromptWithToolTurn(promptText) {
433
+ return llmTurn({
434
+ description: "Run a single operator-provided prompt and require the done tool",
435
+ availableTools: ["read", "bash", "edit", "write"],
436
+ completionMode: "turn_end",
437
+ branchType: "primary",
438
+ context: "fresh",
439
+ prompt: () => buildSinglePromptWithToolInstruction(promptText),
440
+ outcomes: {
441
+ done: {
442
+ description: "Mark the prompt run as complete",
443
+ parameters: {
444
+ summary: {
445
+ type: "string",
446
+ description: "Short summary of the result",
447
+ required: true,
448
+ requiredErrorCode: "summary_required"
449
+ }
450
+ }
451
+ }
452
+ },
453
+ turnResultMarkdown: REQUIRED_MARKDOWN_RESULT_TURN_RESULT
454
+ });
455
+ }
456
+ var runSinglePrompt = createRunSinglePromptTurn(
457
+ "Run the operator-provided single prompt."
458
+ );
459
+ var runSinglePromptWithTool = createRunSinglePromptWithToolTurn(
460
+ "Run the operator-provided single prompt."
461
+ );
462
+
463
+ // src/process-definition.ts
464
+ var promptProcessParamsCodec = {
465
+ parse(value) {
466
+ const record = typeof value === "object" && value !== null ? value : {};
467
+ return {
468
+ prompt: typeof record.prompt === "string" ? record.prompt : ""
469
+ };
470
+ },
471
+ serialize(value) {
472
+ return value;
473
+ }
474
+ };
475
+ var structuralStateCodec = {
476
+ parse(value) {
477
+ return parseStructuralProcessState(value);
478
+ },
479
+ serialize(value) {
480
+ return value;
481
+ }
482
+ };
483
+ var poemCreatorStateCodec = {
484
+ parse(value) {
485
+ const structural = parseStructuralProcessState(value);
486
+ const record = typeof value === "object" && value !== null ? value : {};
487
+ const latestReviewOutcome = typeof record.latestReviewOutcome === "string" ? record.latestReviewOutcome === "issues_found" ? "leave_feedback" : record.latestReviewOutcome === "no_issues" || record.latestReviewOutcome === "leave_feedback" ? record.latestReviewOutcome : null : null;
488
+ return {
489
+ ...structural,
490
+ latestReviewMarkdown: typeof record.latestReviewMarkdown === "string" ? record.latestReviewMarkdown : null,
491
+ latestReviewSummary: typeof record.latestReviewSummary === "string" ? record.latestReviewSummary : null,
492
+ latestReviewOutcome
493
+ };
494
+ },
495
+ serialize(value) {
496
+ return value;
497
+ }
498
+ };
499
+ function validateLaunchInput(input, fallbackPrompt) {
500
+ const inputPrompt = typeof input.prompt === "string" ? input.prompt.trim() : "";
501
+ const prompt = inputPrompt || fallbackPrompt?.trim() || "";
502
+ if (!prompt) {
503
+ return {
504
+ ok: false,
505
+ errors: [{ code: "required", fieldId: "prompt", message: "prompt is required" }]
506
+ };
507
+ }
508
+ return {
509
+ ok: true,
510
+ prompt
511
+ };
512
+ }
513
+ function buildPromptTitleSourceFields(prompt, label = "Prompt") {
514
+ return [{ label, value: prompt }];
515
+ }
516
+ function clearReviewRefs(state) {
517
+ return {
518
+ ...state,
519
+ review: null
520
+ };
521
+ }
522
+ function patchPoemCreatorState(state, input) {
523
+ const nextState = {
524
+ ...state,
525
+ ..."reviewSubject" in input ? { reviewSubject: input.reviewSubject ?? null } : {},
526
+ ..."latestReviewMarkdown" in input ? { latestReviewMarkdown: input.latestReviewMarkdown ?? null } : {},
527
+ ..."latestReviewSummary" in input ? { latestReviewSummary: input.latestReviewSummary ?? null } : {},
528
+ ..."latestReviewOutcome" in input ? { latestReviewOutcome: input.latestReviewOutcome ?? null } : {},
529
+ ..."semanticEntryRefs" in input ? { semanticEntryRefs: input.semanticEntryRefs } : {}
530
+ };
531
+ if (!input.clearReviewRefs) {
532
+ return nextState;
533
+ }
534
+ return {
535
+ ...nextState,
536
+ semanticEntryRefs: clearReviewRefs(nextState.semanticEntryRefs)
537
+ };
538
+ }
539
+ function buildPoemLeafReview(state) {
540
+ if (!state.latestReviewOutcome) {
541
+ return null;
542
+ }
543
+ return {
544
+ outcome: state.latestReviewOutcome,
545
+ summary: state.latestReviewSummary,
546
+ feedback: state.latestReviewOutcome === "leave_feedback" ? state.latestReviewMarkdown : null
547
+ };
548
+ }
549
+ function createMarkdownLeafOutcome(rendererId) {
550
+ return {
551
+ rendererId,
552
+ capture(ctx) {
553
+ const markdown = ctx.turnRecord?.turnResultMarkdown?.trim() ?? "";
554
+ return {
555
+ rendererId,
556
+ schemaVersion: 1,
557
+ props: {
558
+ prompt: ctx.params.prompt,
559
+ markdown: markdown.length > 0 ? markdown : null,
560
+ leafEntryId: ctx.leaf.entryId,
561
+ turnRecordId: ctx.leaf.turnRecordId
562
+ },
563
+ fallbackMarkdown: markdown.length > 0 ? markdown : null
564
+ };
565
+ }
566
+ };
567
+ }
568
+ function createPoemLeafOutcome(rendererId) {
569
+ return {
570
+ rendererId,
571
+ capture(ctx) {
572
+ const reviewLeafEntryId = ctx.state.semanticEntryRefs.review?.entryId ?? null;
573
+ const review = buildPoemLeafReview(ctx.state);
574
+ const isReviewLeaf = reviewLeafEntryId !== null && ctx.leaf.entryId === reviewLeafEntryId;
575
+ const primaryPoemLeafRef = ctx.state.semanticEntryRefs.currentPrimaryPathLeaf;
576
+ const primaryPoemTurnRecord = primaryPoemLeafRef?.turnRecordId ? ctx.readTurnRecord(primaryPoemLeafRef.turnRecordId) : null;
577
+ const markdown = isReviewLeaf ? resolvePoemLeafMarkdown({
578
+ turnResultMarkdown: primaryPoemTurnRecord?.turnResultMarkdown,
579
+ leafEntry: primaryPoemLeafRef ? ctx.readTreeEntry(primaryPoemLeafRef.entryId) : null
580
+ }) : resolvePoemLeafMarkdown({
581
+ turnResultMarkdown: ctx.turnRecord?.turnResultMarkdown,
582
+ leafEntry: ctx.readLeafEntry()
583
+ });
584
+ if (isReviewLeaf && !review) {
585
+ throw new Error("Poem review leaf outcome requires latestReviewOutcome state");
586
+ }
587
+ if (isReviewLeaf && !markdown) {
588
+ throw new Error("Poem review leaf outcome requires a readable primary poem leaf");
589
+ }
590
+ const fallbackMarkdown = buildPoemLeafOutcomeFallbackMarkdown({
591
+ markdown,
592
+ review: isReviewLeaf ? review : null
593
+ });
594
+ return {
595
+ rendererId,
596
+ schemaVersion: 1,
597
+ props: buildPoemLeafOutcomePayload({
598
+ prompt: ctx.params.prompt,
599
+ markdown,
600
+ review: isReviewLeaf ? review : null
601
+ }),
602
+ fallbackMarkdown: fallbackMarkdown || null
603
+ };
604
+ }
605
+ };
606
+ }
607
+ var poemTurnIds = {
608
+ draftPoem: "draft_poem",
609
+ poemReview: "poem_review",
610
+ reviewPoemDraft: "review_poem_draft",
611
+ poemReviewFeedback: "poem_review_feedback"
612
+ };
613
+ var poemDraftReviewSubject = { kind: "plan" };
614
+ var poemFeedbackReviewSubject = { kind: "implementation" };
615
+ var poemRevisionForm = {
616
+ id: poemCreatorActionIds.requestRevision,
617
+ title: "Request poem revision",
618
+ fields: [
619
+ {
620
+ id: "message",
621
+ label: "Revision request",
622
+ kind: "textarea",
623
+ primaryPrompt: true,
624
+ required: true,
625
+ publish: true,
626
+ description: "Tell the next primary-branch poem draft what should change."
627
+ }
628
+ ],
629
+ submitLabel: "Request revision"
630
+ };
631
+ var poemReviewChangesForm = {
632
+ id: poemCreatorActionIds.requestReviewChanges,
633
+ title: "Request review changes",
634
+ fields: [
635
+ {
636
+ id: "message",
637
+ label: "Review revision request",
638
+ kind: "textarea",
639
+ primaryPrompt: true,
640
+ required: true,
641
+ publish: true,
642
+ description: "Tell the review branch how to revise its review output."
643
+ }
644
+ ],
645
+ submitLabel: "Request review changes"
646
+ };
647
+ var singlePromptProcess = flow.process("single_prompt_process").displayName("Single Prompt").entry("run_single_prompt").codecs({
648
+ params: promptProcessParamsCodec,
649
+ state: structuralStateCodec
650
+ }).initialState(() => createEmptyStructuralProcessState()).turn(
651
+ flow.llm("run_single_prompt").description("Run a single operator-provided prompt and finish on turn end").tools("read", "bash", "edit", "write").prompt(async (ctx) => buildSinglePromptInstruction(ctx.params.prompt)).end("completed").complete()
652
+ ).ui((api) => {
653
+ api.leafOutcome(
654
+ createMarkdownLeafOutcome(
655
+ "@leitwerk-dev/showcase-processes:single_prompt_process.leaf_outcome"
656
+ )
657
+ );
658
+ }).launcher({
659
+ id: "single_prompt_process.single_prompt_ui",
660
+ label: "Single Prompt",
661
+ description: "Run one prompt and finish on turn end",
662
+ visibility: "ui",
663
+ ui: {
664
+ card: {
665
+ title: "Single Prompt",
666
+ description: "Run a one-shot prompt. The shared launcher shell chooses the model configuration."
667
+ },
668
+ launchConfigSchema: {
669
+ id: "single_prompt_form",
670
+ title: "Single Prompt",
671
+ fields: [
672
+ {
673
+ id: "prompt",
674
+ label: "Prompt",
675
+ kind: "textarea",
676
+ required: true,
677
+ placeholder: "Say hello.",
678
+ description: "The exact prompt sent to Pi for this one-shot run. This version finishes when the assistant turn ends normally."
679
+ }
680
+ ],
681
+ submitLabel: "Run Prompt"
682
+ },
683
+ resolveDefaults() {
684
+ return {
685
+ prompt: ""
686
+ };
687
+ },
688
+ resolveLaunchConfig(input) {
689
+ const validated = validateLaunchInput(input);
690
+ if (!validated.ok) {
691
+ return validated;
692
+ }
693
+ return {
694
+ ok: true,
695
+ launchConfig: {
696
+ processId: "single_prompt_process",
697
+ params: { prompt: validated.prompt },
698
+ titleSourceFields: buildPromptTitleSourceFields(validated.prompt),
699
+ startTurnId: "run_single_prompt"
700
+ }
701
+ };
702
+ }
703
+ }
704
+ }).define();
705
+ var singlePromptWithToolProcess = flow.process("single_prompt_with_tool_process").displayName("Single Prompt + Done Tool").entry("run_single_prompt_with_tool").codecs({
706
+ params: promptProcessParamsCodec,
707
+ state: structuralStateCodec
708
+ }).initialState(() => createEmptyStructuralProcessState()).turn(
709
+ flow.llm("run_single_prompt_with_tool").description("Run a single operator-provided prompt and require the done tool").tools("read", "bash", "edit", "write").prompt(async (ctx) => buildSinglePromptWithToolInstruction(ctx.params.prompt)).outcomeTool(
710
+ "done",
711
+ (tool) => tool.description("Mark the prompt run as complete").requiredString("summary", "Short summary of the result").complete()
712
+ )
713
+ ).ui((api) => {
714
+ api.leafOutcome(
715
+ createMarkdownLeafOutcome(
716
+ "@leitwerk-dev/showcase-processes:single_prompt_with_tool_process.leaf_outcome"
717
+ )
718
+ );
719
+ }).launcher({
720
+ id: "single_prompt_with_tool_process.single_prompt_with_tool_ui",
721
+ label: "Single Prompt + Done Tool",
722
+ description: "Run one prompt and require an explicit done tool",
723
+ visibility: "ui",
724
+ ui: {
725
+ card: {
726
+ title: "Single Prompt + Done Tool",
727
+ description: "Run a one-shot prompt and force an explicit done tool call. The shared launcher shell chooses the model configuration."
728
+ },
729
+ launchConfigSchema: {
730
+ id: "single_prompt_with_tool_form",
731
+ title: "Single Prompt + Done Tool",
732
+ fields: [
733
+ {
734
+ id: "prompt",
735
+ label: "Prompt",
736
+ kind: "textarea",
737
+ required: true,
738
+ placeholder: "Say hello, then call the done tool with a short summary.",
739
+ description: "The exact prompt sent to Pi for this one-shot run. This version requires the explicit done outcome tool."
740
+ }
741
+ ],
742
+ submitLabel: "Run Prompt + Tool"
743
+ },
744
+ resolveDefaults() {
745
+ return {
746
+ prompt: ""
747
+ };
748
+ },
749
+ resolveLaunchConfig(input) {
750
+ const validated = validateLaunchInput(input);
751
+ if (!validated.ok) {
752
+ return validated;
753
+ }
754
+ return {
755
+ ok: true,
756
+ launchConfig: {
757
+ processId: "single_prompt_with_tool_process",
758
+ params: { prompt: validated.prompt },
759
+ titleSourceFields: buildPromptTitleSourceFields(validated.prompt),
760
+ startTurnId: "run_single_prompt_with_tool"
761
+ }
762
+ };
763
+ }
764
+ }
765
+ }).define();
766
+ function defineK8sSmokeProcess(args) {
767
+ const promptField = args.promptField;
768
+ const resolveLaunchConfig = promptField ? (input) => {
769
+ const validated = validateLaunchInput(input, args.defaultPrompt);
770
+ if (!validated.ok) return validated;
771
+ return {
772
+ ok: true,
773
+ launchConfig: {
774
+ processId: args.processId,
775
+ params: { prompt: validated.prompt },
776
+ titleSourceFields: buildPromptTitleSourceFields(validated.prompt, args.titleLabel),
777
+ startTurnId: args.runTurnId
778
+ }
779
+ };
780
+ } : () => ({
781
+ ok: true,
782
+ launchConfig: {
783
+ processId: args.processId,
784
+ params: { prompt: args.defaultPrompt },
785
+ titleSourceFields: buildPromptTitleSourceFields(args.defaultPrompt, args.titleLabel),
786
+ startTurnId: args.runTurnId
787
+ }
788
+ });
789
+ const runTurn = flow.automatic(args.runTurnId).description(args.runTurnDescription).run(async (ctx) => {
790
+ const result = await args.run(ctx);
791
+ return { outcome: "ready", ...result };
792
+ }).outcome("ready", (outcome) => {
793
+ outcome.description(args.outcomeDescription);
794
+ args.describeOutcome?.(outcome);
795
+ return outcome.to(args.waitTurnId);
796
+ });
797
+ const waitTurn = flow.human(args.waitTurnId).description(args.waitDescription);
798
+ if (args.waitCommentary) {
799
+ waitTurn.commentary(args.waitCommentary);
800
+ }
801
+ if (args.runAgain) {
802
+ const runAgain = args.runAgain;
803
+ waitTurn.action(
804
+ "run_again",
805
+ (action) => action.label(runAgain.label).description(runAgain.description).acceptanceState("neutral").to(args.runTurnId)
806
+ );
807
+ }
808
+ waitTurn.action(
809
+ "complete",
810
+ (action) => action.label(args.completeLabel).acceptanceState("accepted").complete()
811
+ );
812
+ return flow.process(args.processId).displayName(args.displayName).entry(args.runTurnId).codecs({ params: promptProcessParamsCodec, state: structuralStateCodec }).initialState(() => createEmptyStructuralProcessState()).turn(runTurn).turn(waitTurn).launcher({
813
+ id: args.launcherId,
814
+ label: args.displayName,
815
+ description: args.launcherDescription,
816
+ visibility: "ui",
817
+ ui: {
818
+ card: { title: args.displayName, description: args.cardDescription },
819
+ launchConfigSchema: {
820
+ id: args.formId,
821
+ title: args.displayName,
822
+ fields: promptField ? [{ id: "prompt", label: promptField.label, kind: "text", required: true }] : [],
823
+ submitLabel: args.submitLabel
824
+ },
825
+ ...promptField ? { resolveDefaults: () => ({ prompt: args.defaultPrompt }) } : {},
826
+ resolveLaunchConfig
827
+ }
828
+ }).define();
829
+ }
830
+ var k8sSmokeProcess = defineK8sSmokeProcess({
831
+ processId: "k8s_smoke_process",
832
+ displayName: "Kubernetes Smoke",
833
+ runTurnId: "k8s_smoke_run",
834
+ waitTurnId: "k8s_smoke_wait",
835
+ runTurnDescription: "Run a deterministic worker-side Kubernetes smoke step",
836
+ outcomeDescription: "The worker-side smoke step completed",
837
+ describeOutcome: (outcome) => outcome.string("prompt", "The smoke prompt"),
838
+ waitDescription: "Wait after the Kubernetes smoke worker step",
839
+ waitCommentary: "The smoke worker is idle; actions can respawn it on the retained PVC.",
840
+ runAgain: { label: "Run smoke again", description: "Select the worker-side smoke turn again." },
841
+ completeLabel: "Complete smoke",
842
+ launcherId: "k8s_smoke_process.k8s_smoke_ui",
843
+ launcherDescription: "Run a deterministic worker-backed Kubernetes smoke process",
844
+ cardDescription: "Creates a worker pod/PVC and then waits for a follow-up action.",
845
+ formId: "k8s_smoke_form",
846
+ submitLabel: "Run smoke",
847
+ promptField: { label: "Smoke prompt" },
848
+ defaultPrompt: "kind smoke",
849
+ titleLabel: "Smoke",
850
+ run: (ctx) => ({
851
+ params: { prompt: ctx.params.prompt },
852
+ markdown: `Kubernetes smoke worker ran: ${ctx.params.prompt}`
853
+ })
854
+ });
855
+ var k8sSmokeSpecializedProcess = defineK8sSmokeProcess({
856
+ processId: "k8s_smoke_specialized_process",
857
+ displayName: "Kubernetes Specialized Smoke",
858
+ runTurnId: "k8s_smoke_specialized_run",
859
+ waitTurnId: "k8s_smoke_specialized_wait",
860
+ runTurnDescription: "Verify the specialized Kubernetes worker image tool path",
861
+ outcomeDescription: "The specialized image tool ran",
862
+ describeOutcome: (outcome) => outcome.requiredString("output", "Tool output"),
863
+ waitDescription: "Wait after specialized image verification",
864
+ waitCommentary: "The specialized Kubernetes image was selected and executed its smoke tool.",
865
+ completeLabel: "Complete specialized smoke",
866
+ launcherId: "k8s_smoke_specialized_process.k8s_smoke_specialized_ui",
867
+ launcherDescription: "Run a deterministic worker-backed process on the specialized smoke image",
868
+ cardDescription: "Validates runtime-profile image selection with a deterministic tool.",
869
+ formId: "k8s_smoke_specialized_form",
870
+ submitLabel: "Run specialized smoke",
871
+ defaultPrompt: "specialized",
872
+ titleLabel: "Smoke",
873
+ run: () => {
874
+ const output = execFileSync("leitwerk-specialized-tool", { encoding: "utf8" }).trim();
875
+ return { params: { output }, markdown: output };
876
+ }
877
+ });
878
+ var k8sSmokeLongProcess = defineK8sSmokeProcess({
879
+ processId: "k8s_smoke_long_process",
880
+ displayName: "Kubernetes Long Smoke",
881
+ runTurnId: "k8s_smoke_long_run",
882
+ waitTurnId: "k8s_smoke_long_wait",
883
+ runTurnDescription: "Stay busy long enough for server restart adoption tests",
884
+ outcomeDescription: "The long smoke step completed",
885
+ waitDescription: "Wait after long smoke",
886
+ completeLabel: "Complete long smoke",
887
+ launcherId: "k8s_smoke_long_process.k8s_smoke_long_ui",
888
+ launcherDescription: "Run a long worker-backed process for server restart adoption tests",
889
+ cardDescription: "Keeps a worker pod busy while the server restarts.",
890
+ formId: "k8s_smoke_long_form",
891
+ submitLabel: "Run long smoke",
892
+ defaultPrompt: "long",
893
+ titleLabel: "Smoke",
894
+ run: async () => {
895
+ await delay(9e4);
896
+ return { params: {}, markdown: "long smoke completed" };
897
+ }
898
+ });
899
+ var singlePromptExternalCompleteProcess = flow.process("single_prompt_external_complete_process").displayName("Single Prompt + External Complete").entry("run_single_prompt").codecs({
900
+ params: promptProcessParamsCodec,
901
+ state: structuralStateCodec
902
+ }).initialState(() => createEmptyStructuralProcessState()).turn(
903
+ flow.llm("run_single_prompt").description("Run a single operator-provided prompt and finish on turn end").tools("read", "bash", "edit", "write").prompt(async (ctx) => buildSinglePromptInstruction(ctx.params.prompt)).end("completed").to(externalPromptCompletionTurnId)
904
+ ).turn(
905
+ flow.external(externalPromptCompletionTurnId).description(externalPromptCompletionTurnDescription).from(
906
+ fileExternal.presence({
907
+ path: "/tmp/complete-prompt",
908
+ pollInterval: "1s",
909
+ consume: "delete"
910
+ })
911
+ ).complete()
912
+ ).ui((api) => {
913
+ api.leafOutcome(
914
+ createMarkdownLeafOutcome(
915
+ "@leitwerk-dev/showcase-processes:single_prompt_external_complete_process.leaf_outcome"
916
+ )
917
+ );
918
+ }).launcher({
919
+ id: "single_prompt_external_complete_process.single_prompt_external_complete_ui",
920
+ label: "Single Prompt + External Complete",
921
+ description: "Run one prompt, then wait for the external complete trigger file",
922
+ visibility: "ui",
923
+ ui: {
924
+ card: {
925
+ title: "Single Prompt + External Complete",
926
+ description: "Run a one-shot prompt, preserve its result in the chronicle, and finish only when the external completion trigger fires."
927
+ },
928
+ launchConfigSchema: {
929
+ id: "single_prompt_external_complete_form",
930
+ title: "Single Prompt + External Complete",
931
+ fields: [
932
+ {
933
+ id: "prompt",
934
+ label: "Prompt",
935
+ kind: "textarea",
936
+ required: true,
937
+ placeholder: "Say hello, then wait for the external completion file.",
938
+ description: "The prompt runs once. After it finishes, the process waits for the configured prompt-complete trigger file (default: /tmp/complete-prompt)."
939
+ }
940
+ ],
941
+ submitLabel: "Run Prompt"
942
+ },
943
+ resolveDefaults() {
944
+ return {
945
+ prompt: ""
946
+ };
947
+ },
948
+ resolveLaunchConfig(input) {
949
+ const validated = validateLaunchInput(input);
950
+ if (!validated.ok) {
951
+ return validated;
952
+ }
953
+ return {
954
+ ok: true,
955
+ launchConfig: {
956
+ processId: "single_prompt_external_complete_process",
957
+ params: { prompt: validated.prompt },
958
+ titleSourceFields: buildPromptTitleSourceFields(validated.prompt),
959
+ startTurnId: "run_single_prompt"
960
+ }
961
+ };
962
+ }
963
+ }
964
+ }).define();
965
+ var poemDraftReviewSpec = flow.human(poemTurnIds.poemReview).description("Human review of the drafted poem on the primary branch").reviewProduct("poem-draft", { subject: "plan" }).notesFields([
966
+ {
967
+ id: "message",
968
+ label: "Revision notes",
969
+ placeholder: "Ask for a different tone, tighter rhythm, or stronger imagery"
970
+ }
971
+ ]).commentary(
972
+ "Review the poem on the primary branch, complete it, request another draft, or send it to automated review."
973
+ ).action(
974
+ poemCreatorActionIds.completePoem,
975
+ (action) => action.label("Complete poem").description("Accept the current poem and finish the process.").acceptanceState("accepted").complete().effect(({ ctx }) => ({
976
+ state: patchPoemCreatorState(ctx.state, {
977
+ reviewSubject: null
978
+ })
979
+ }))
980
+ ).action(
981
+ poemCreatorActionIds.requestRevision,
982
+ (action) => action.label("Request revision").description("Send the poem back for another primary-branch draft.").acceptanceState("requires_changes").form(poemRevisionForm).trigger("revision_requested").schedulable().to(poemTurnIds.draftPoem)
983
+ ).action(
984
+ poemCreatorActionIds.runAutoReview,
985
+ (action) => action.label("Run automated review").description("Send the current poem draft to the LLM reviewer.").acceptanceState("neutral").trigger("operator_re_review").schedulable().to(poemTurnIds.reviewPoemDraft).effect(({ ctx }) => ({
986
+ state: patchPoemCreatorState(ctx.state, {
987
+ reviewSubject: createReviewSubject(poemFeedbackReviewSubject.kind),
988
+ latestReviewMarkdown: null,
989
+ latestReviewSummary: null,
990
+ latestReviewOutcome: null,
991
+ clearReviewRefs: true
992
+ })
993
+ }))
994
+ ).externalAction(
995
+ "poem_review_file",
996
+ fileExternal.instruction({
997
+ path: "/tmp/poem-review-{instanceId}",
998
+ pollInterval: "1s",
999
+ consume: "delete"
1000
+ }),
1001
+ (external) => external.label("Configured poem review file").description("Write revision feedback to the configured poem-review file").publishInput("message", { inputField: "instruction" }).to(poemTurnIds.draftPoem)
1002
+ ).definition;
1003
+ var poemReviewFeedbackSpec = flow.human(poemTurnIds.poemReviewFeedback).description("Human review of the LLM review output").reviewProduct("message", { subject: "implementation" }).notesFields([
1004
+ {
1005
+ id: "message",
1006
+ label: "Review feedback notes",
1007
+ placeholder: "Explain what the LLM reviewer should change in its review"
1008
+ }
1009
+ ]).commentary(
1010
+ "Review the review output itself. Accept it to pass the feedback to the primary branch, request changes to continue on the same review branch, or dismiss it and return to the poem decision."
1011
+ ).action(
1012
+ poemCreatorActionIds.acceptReview,
1013
+ (action) => action.label("Accept review").description(
1014
+ "Accept the current review outcome and continue with the primary-branch poem flow."
1015
+ ).acceptanceState("accepted").to(poemTurnIds.draftPoem)
1016
+ ).action(
1017
+ poemCreatorActionIds.requestReviewChanges,
1018
+ (action) => action.label("Request review changes").description("Ask the LLM reviewer to revise its review on the review branch.").acceptanceState("requires_changes").form(poemReviewChangesForm).trigger("operator_re_review").schedulable().to(poemTurnIds.reviewPoemDraft)
1019
+ ).action(
1020
+ poemCreatorActionIds.dismissReview,
1021
+ (action) => action.label("Dismiss review").description("Return to the poem decision without applying the review feedback.").acceptanceState("neutral").to(poemTurnIds.poemReview).effect(({ ctx }) => ({
1022
+ state: patchPoemCreatorState(ctx.state, {
1023
+ reviewSubject: createReviewSubject(poemDraftReviewSubject.kind),
1024
+ latestReviewMarkdown: null,
1025
+ latestReviewSummary: null,
1026
+ latestReviewOutcome: null,
1027
+ clearReviewRefs: true
1028
+ })
1029
+ }))
1030
+ ).definition;
1031
+ var poemCreatorProcess = flow.process("poem_creator_process").displayName("Poem Creator").entry(poemTurnIds.draftPoem).codecs({
1032
+ params: promptProcessParamsCodec,
1033
+ state: poemCreatorStateCodec
1034
+ }).initialState(() => ({
1035
+ ...createEmptyStructuralProcessState(),
1036
+ latestReviewMarkdown: null,
1037
+ latestReviewSummary: null,
1038
+ latestReviewOutcome: null
1039
+ })).turn(
1040
+ flow.llm(poemTurnIds.draftPoem).description("Draft poem").fullPrimary().continueFromPrimaryLeaf().optionalConsume("message").buildPrompt(async (ctx) => {
1041
+ const message = ctx.input.message?.trim();
1042
+ return message ? buildRevisePoemInstruction(message) : buildDraftPoemInstruction(ctx.params.prompt);
1043
+ }).publish("poem-draft").to(poemTurnIds.poemReview).state(
1044
+ ({ ctx }) => patchPoemCreatorState(ctx.state, {
1045
+ reviewSubject: createReviewSubject(poemDraftReviewSubject.kind),
1046
+ latestReviewMarkdown: null,
1047
+ latestReviewSummary: null,
1048
+ latestReviewOutcome: null,
1049
+ clearReviewRefs: true
1050
+ })
1051
+ )
1052
+ ).turn({ id: poemTurnIds.poemReview, definition: poemDraftReviewSpec }).turn(
1053
+ flow.llm(poemTurnIds.reviewPoemDraft).description("Review poem").rootBranchReview().continueFromReviewBranch().reviews(createReviewSubject("plan")).consume("poem-draft").optionalConsume("message").buildPrompt(async (ctx) => {
1054
+ const message = ctx.input.message?.trim();
1055
+ const poemDraft = ctx.input["poem-draft"];
1056
+ if (!poemDraft) {
1057
+ throw new Error("Review poem turn requires poem-draft input");
1058
+ }
1059
+ const reviewInstruction = buildReviewPoemInstruction(ctx.params.prompt, poemDraft);
1060
+ return message ? `${reviewInstruction}
1061
+
1062
+ Reviewer revision guidance:
1063
+ ${message}` : reviewInstruction;
1064
+ }).outcomeTool(
1065
+ "no_issues",
1066
+ (tool) => tool.description("The poem is ready to publish").requiredString("summary", "Short confirmation summary").markdown("review", {
1067
+ description: "Concise review opinion confirming the poem is ready",
1068
+ publish: true
1069
+ }).to(poemTurnIds.poemReview).state(
1070
+ ({ ctx, event }) => patchPoemCreatorState(ctx.state, {
1071
+ reviewSubject: createReviewSubject(poemDraftReviewSubject.kind),
1072
+ latestReviewMarkdown: null,
1073
+ latestReviewSummary: typeof event.params.summary === "string" ? event.params.summary : null,
1074
+ latestReviewOutcome: "no_issues"
1075
+ })
1076
+ )
1077
+ ).outcomeTool(
1078
+ "leave_feedback",
1079
+ (tool) => tool.description("Leave concise feedback for the human reviewer").requiredString("summary", "Short summary of the feedback").markdown("message", {
1080
+ description: "Concise plain-text feedback describing what to improve",
1081
+ publish: true
1082
+ }).to(poemTurnIds.poemReviewFeedback).state(
1083
+ ({ ctx, event }) => patchPoemCreatorState(ctx.state, {
1084
+ reviewSubject: createReviewSubject(poemFeedbackReviewSubject.kind),
1085
+ latestReviewMarkdown: typeof event.params.message === "string" ? event.params.message : ctx.output?.content ?? null,
1086
+ latestReviewSummary: typeof event.params.summary === "string" ? event.params.summary : null,
1087
+ latestReviewOutcome: "leave_feedback"
1088
+ })
1089
+ )
1090
+ )
1091
+ ).turn({ id: poemTurnIds.poemReviewFeedback, definition: poemReviewFeedbackSpec }).ui((api) => {
1092
+ api.leafOutcome(
1093
+ createPoemLeafOutcome("@leitwerk-dev/showcase-processes:poem_creator_process.leaf_outcome")
1094
+ );
1095
+ }).launcher({
1096
+ id: "poem_creator_process.poem_creator_ui",
1097
+ label: "Poem Creator",
1098
+ description: "Create a poem, review it on the primary branch, and optionally send it through a human-gated llm review loop",
1099
+ visibility: "ui",
1100
+ ui: {
1101
+ card: {
1102
+ title: "Poem Creator",
1103
+ description: "A fast multi-step demo: poem drafting on the primary branch plus a human-gated llm review branch."
1104
+ },
1105
+ launchConfigSchema: {
1106
+ id: "poem_creator_form",
1107
+ title: "Poem Creator",
1108
+ fields: [
1109
+ {
1110
+ id: "prompt",
1111
+ label: "Poem Prompt",
1112
+ kind: "textarea",
1113
+ required: true,
1114
+ placeholder: "Write a short poem about the weather in Berlin or the joy of shipping cloud software.",
1115
+ description: "Leave the prefilled prompt as-is to try the feature immediately, or replace it with your own poem idea."
1116
+ }
1117
+ ],
1118
+ submitLabel: "Create Poem"
1119
+ },
1120
+ resolveDefaults() {
1121
+ return {
1122
+ prompt: buildDefaultPoemPrompt()
1123
+ };
1124
+ },
1125
+ resolveLaunchConfig(input) {
1126
+ const validated = validateLaunchInput(input, buildDefaultPoemPrompt());
1127
+ if (!validated.ok) {
1128
+ return validated;
1129
+ }
1130
+ return {
1131
+ ok: true,
1132
+ launchConfig: {
1133
+ processId: "poem_creator_process",
1134
+ params: { prompt: validated.prompt },
1135
+ titleSourceFields: buildPromptTitleSourceFields(validated.prompt, "Poem Prompt"),
1136
+ startTurnId: poemTurnIds.draftPoem
1137
+ }
1138
+ };
1139
+ }
1140
+ }
1141
+ }).watcher({
1142
+ id: "create_poem",
1143
+ label: "Create Poem from File",
1144
+ description: "Launch Poem Creator whenever the configured filesystem watcher finds a prompt file",
1145
+ type: "filesystem",
1146
+ matches(event) {
1147
+ return typeof event.content === "string";
1148
+ },
1149
+ resolveLaunchConfig(event) {
1150
+ const prompt = typeof event.content === "string" ? event.content.trim() : "";
1151
+ return {
1152
+ processId: "poem_creator_process",
1153
+ params: { prompt },
1154
+ titleSourceFields: buildPromptTitleSourceFields(prompt, "Poem Prompt"),
1155
+ startTurnId: poemTurnIds.draftPoem
1156
+ };
1157
+ }
1158
+ }).define();
1159
+
1160
+ // src/index.ts
1161
+ var manifest = {
1162
+ id: "showcase-processes",
1163
+ version: "0.1.0"
1164
+ };
1165
+ var fileTriggerDefaults = {
1166
+ poll_interval: "1s",
1167
+ poem_review_path: "/tmp/poem-review-{instanceId}",
1168
+ complete_prompt_path: "/tmp/complete-prompt"
1169
+ };
1170
+ var singlePromptExtension = {
1171
+ manifest,
1172
+ setupCatalog(api) {
1173
+ api.registerToolRenderer(leaveFeedbackToolRenderer);
1174
+ api.registerProcess(singlePromptProcess);
1175
+ api.registerProcess(singlePromptWithToolProcess);
1176
+ api.registerProcess(singlePromptExternalCompleteProcess);
1177
+ api.registerProcess(k8sSmokeProcess);
1178
+ api.registerProcess(k8sSmokeSpecializedProcess);
1179
+ api.registerProcess(k8sSmokeLongProcess);
1180
+ api.registerProcess(poemCreatorProcess);
1181
+ },
1182
+ setupServer(api, rawConfig) {
1183
+ const deps = api.get(coreHostCapabilities.serverSetup);
1184
+ if (!deps || Array.isArray(deps)) {
1185
+ return;
1186
+ }
1187
+ const config = rawConfig ?? {};
1188
+ const resolvedFileTriggerConfig = {
1189
+ ...fileTriggerDefaults,
1190
+ ...config.file_triggers
1191
+ };
1192
+ const fileSourceProvider = createFileExternalSourceProvider(deps, {
1193
+ "/tmp/complete-prompt": resolvedFileTriggerConfig.complete_prompt_path,
1194
+ "/tmp/poem-review-{instanceId}": resolvedFileTriggerConfig.poem_review_path
1195
+ });
1196
+ api.onStart(() => {
1197
+ fileSourceProvider.start();
1198
+ });
1199
+ api.onStop(() => {
1200
+ fileSourceProvider.stop();
1201
+ });
1202
+ }
1203
+ };
1204
+ var index_default = singlePromptExtension;
1205
+ export {
1206
+ FILE_EXTERNAL_INSTRUCTION_KIND,
1207
+ FILE_EXTERNAL_PRESENCE_KIND,
1208
+ buildDefaultPoemPrompt,
1209
+ buildDraftPoemInstruction,
1210
+ buildPoemLeafOutcomeFallbackMarkdown,
1211
+ buildPoemLeafOutcomePayload,
1212
+ buildReviewPoemInstruction,
1213
+ buildRevisePoemInstruction,
1214
+ buildSinglePromptInstruction,
1215
+ buildSinglePromptWithToolInstruction,
1216
+ createFileExternalSourceProvider,
1217
+ createRunSinglePromptTurn,
1218
+ createRunSinglePromptWithToolTurn,
1219
+ index_default as default,
1220
+ externalCompleteActionId,
1221
+ externalPromptCompletionTriggerDescription,
1222
+ externalPromptCompletionTriggerLabel,
1223
+ externalPromptCompletionTurnDescription,
1224
+ externalPromptCompletionTurnId,
1225
+ extractLeafEntryMarkdown,
1226
+ fileExternal,
1227
+ k8sSmokeLongProcess,
1228
+ k8sSmokeProcess,
1229
+ k8sSmokeSpecializedProcess,
1230
+ leaveFeedbackToolRenderer,
1231
+ manifest,
1232
+ parsePoemLeafMarkdown,
1233
+ poemCreatorActionIds,
1234
+ poemCreatorProcess,
1235
+ resolvePoemLeafMarkdown,
1236
+ runSinglePrompt,
1237
+ runSinglePromptWithTool,
1238
+ singlePromptExternalCompleteProcess,
1239
+ singlePromptProcess,
1240
+ singlePromptWithToolProcess
1241
+ };
55
1242
  //# sourceMappingURL=index.js.map