@leitwerk-dev/showcase-processes 0.1.8 → 0.2.0

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