@leitwerk-dev/protocol 0.1.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.
Files changed (118) hide show
  1. package/dist/LICENSE +13 -0
  2. package/dist/chunk-6L4W7WPV.js +1 -0
  3. package/dist/chunk-6L4W7WPV.js.map +1 -0
  4. package/dist/chunk-7PCFBAV4.js +740 -0
  5. package/dist/chunk-7PCFBAV4.js.map +1 -0
  6. package/dist/chunk-AAV3AAOF.js +1 -0
  7. package/dist/chunk-AAV3AAOF.js.map +1 -0
  8. package/dist/chunk-IEMT3JG4.js +1 -0
  9. package/dist/chunk-IEMT3JG4.js.map +1 -0
  10. package/dist/chunk-IWVU76M5.js +26 -0
  11. package/dist/chunk-IWVU76M5.js.map +1 -0
  12. package/dist/config-snapshot.d.ts +211 -0
  13. package/dist/config-snapshot.d.ts.map +1 -0
  14. package/dist/config-snapshot.js +2 -0
  15. package/dist/config-snapshot.js.map +1 -0
  16. package/dist/external-review.d.ts +8 -0
  17. package/dist/external-review.d.ts.map +1 -0
  18. package/dist/external-review.js +2 -0
  19. package/dist/external-review.js.map +1 -0
  20. package/dist/form-contract.d.ts +41 -0
  21. package/dist/form-contract.d.ts.map +1 -0
  22. package/dist/form-contract.js +2 -0
  23. package/dist/form-contract.js.map +1 -0
  24. package/dist/http-contracts-C8IXe8MU.d.ts +1483 -0
  25. package/dist/http-contracts.d.ts +959 -0
  26. package/dist/http-contracts.d.ts.map +1 -0
  27. package/dist/http-contracts.js +434 -0
  28. package/dist/http-contracts.js.map +1 -0
  29. package/dist/index.d.ts +21 -0
  30. package/dist/index.d.ts.map +1 -0
  31. package/dist/index.js +21 -0
  32. package/dist/index.js.map +1 -0
  33. package/dist/initial-prompt.d.ts +8 -0
  34. package/dist/initial-prompt.d.ts.map +1 -0
  35. package/dist/initial-prompt.js +103 -0
  36. package/dist/initial-prompt.js.map +1 -0
  37. package/dist/launcher-contract.d.ts +34 -0
  38. package/dist/launcher-contract.d.ts.map +1 -0
  39. package/dist/launcher-contract.js +2 -0
  40. package/dist/launcher-contract.js.map +1 -0
  41. package/dist/live-turn-projection.d.ts +39 -0
  42. package/dist/live-turn-projection.d.ts.map +1 -0
  43. package/dist/live-turn-projection.js +395 -0
  44. package/dist/live-turn-projection.js.map +1 -0
  45. package/dist/pi-session-message.d.ts +25 -0
  46. package/dist/pi-session-message.d.ts.map +1 -0
  47. package/dist/pi-session-message.js +27 -0
  48. package/dist/pi-session-message.js.map +1 -0
  49. package/dist/primary-path-snapshot.d.ts +77 -0
  50. package/dist/primary-path-snapshot.d.ts.map +1 -0
  51. package/dist/primary-path-snapshot.js +2 -0
  52. package/dist/primary-path-snapshot.js.map +1 -0
  53. package/dist/protocol.d.ts +428 -0
  54. package/dist/protocol.d.ts.map +1 -0
  55. package/dist/protocol.js +261 -0
  56. package/dist/protocol.js.map +1 -0
  57. package/dist/session-entry-tree.d.ts +15 -0
  58. package/dist/session-entry-tree.d.ts.map +1 -0
  59. package/dist/session-entry-tree.js +42 -0
  60. package/dist/session-entry-tree.js.map +1 -0
  61. package/dist/streamable-events.d.ts +4 -0
  62. package/dist/streamable-events.d.ts.map +1 -0
  63. package/dist/streamable-events.js +17 -0
  64. package/dist/streamable-events.js.map +1 -0
  65. package/dist/text-preview.d.ts +7 -0
  66. package/dist/text-preview.d.ts.map +1 -0
  67. package/dist/text-preview.js +23 -0
  68. package/dist/text-preview.js.map +1 -0
  69. package/dist/timeline-projection.d.ts +9 -0
  70. package/dist/timeline-projection.d.ts.map +1 -0
  71. package/dist/timeline-projection.js +30 -0
  72. package/dist/timeline-projection.js.map +1 -0
  73. package/dist/timestamp-ordering.d.ts +3 -0
  74. package/dist/timestamp-ordering.d.ts.map +1 -0
  75. package/dist/timestamp-ordering.js +15 -0
  76. package/dist/timestamp-ordering.js.map +1 -0
  77. package/dist/tool-renderer-contract.d.ts +18 -0
  78. package/dist/tool-renderer-contract.d.ts.map +1 -0
  79. package/dist/tool-renderer-contract.js +22 -0
  80. package/dist/tool-renderer-contract.js.map +1 -0
  81. package/dist/turn-continuation.d.ts +36 -0
  82. package/dist/turn-continuation.d.ts.map +1 -0
  83. package/dist/turn-continuation.js +179 -0
  84. package/dist/turn-continuation.js.map +1 -0
  85. package/dist/usage-by-turn-record.d.ts +5 -0
  86. package/dist/usage-by-turn-record.d.ts.map +1 -0
  87. package/dist/usage-by-turn-record.js +25 -0
  88. package/dist/usage-by-turn-record.js.map +1 -0
  89. package/dist/usage-snapshot.d.ts +25 -0
  90. package/dist/usage-snapshot.d.ts.map +1 -0
  91. package/dist/usage-snapshot.js +120 -0
  92. package/dist/usage-snapshot.js.map +1 -0
  93. package/dist/ws-event-payloads.d.ts +18 -0
  94. package/dist/ws-event-payloads.d.ts.map +1 -0
  95. package/dist/ws-event-payloads.js +47 -0
  96. package/dist/ws-event-payloads.js.map +1 -0
  97. package/package.json +65 -0
  98. package/src/config-snapshot.ts +244 -0
  99. package/src/external-review.ts +7 -0
  100. package/src/form-contract.ts +50 -0
  101. package/src/http-contracts.ts +1497 -0
  102. package/src/index.ts +20 -0
  103. package/src/initial-prompt.ts +127 -0
  104. package/src/launcher-contract.ts +43 -0
  105. package/src/live-turn-projection.ts +501 -0
  106. package/src/pi-session-message.ts +48 -0
  107. package/src/primary-path-snapshot.ts +98 -0
  108. package/src/protocol.ts +503 -0
  109. package/src/session-entry-tree.ts +63 -0
  110. package/src/streamable-events.ts +20 -0
  111. package/src/text-preview.ts +32 -0
  112. package/src/timeline-projection.ts +43 -0
  113. package/src/timestamp-ordering.ts +15 -0
  114. package/src/tool-renderer-contract.ts +41 -0
  115. package/src/turn-continuation.ts +298 -0
  116. package/src/usage-by-turn-record.ts +34 -0
  117. package/src/usage-snapshot.ts +174 -0
  118. package/src/ws-event-payloads.ts +73 -0
@@ -0,0 +1,1497 @@
1
+ import {
2
+ type Actor,
3
+ type DurableModelSelection,
4
+ type FutureExecutionBlockReason,
5
+ type InstanceTurnConfigMap,
6
+ type LaunchModelConfigInput,
7
+ normalizeActor,
8
+ normalizeLaunchModelConfigInput,
9
+ type ProcessEvent,
10
+ type ProcessFlowView,
11
+ type ProcessInput,
12
+ type ProcessInstance,
13
+ type ProcessLeafOutcomeSnapshot,
14
+ type ProcessProject,
15
+ type ProcessQuestionRequest,
16
+ type ProcessRowSlot,
17
+ type ProcessSelectedTurnModelSource,
18
+ type ProcessTurnAnnotation,
19
+ type ProcessTurnRecord,
20
+ type ProcessTurnType,
21
+ type QuestionAnswerDraft,
22
+ type SerializedProcessGraph,
23
+ trimToNull,
24
+ type WorkerLease,
25
+ } from "@leitwerk-dev/domain";
26
+ import * as v from "valibot";
27
+ import type { ProcessWatcherType } from "./config-snapshot.js";
28
+ import type {
29
+ ActionFormDefinition,
30
+ ActionFormFieldDefinition,
31
+ FormFieldOptionDefinition,
32
+ } from "./form-contract.js";
33
+ import type { LauncherValidationError, UiLauncherSummaryBase } from "./launcher-contract.js";
34
+ import type {
35
+ PrimaryPathSnapshot,
36
+ PrimaryPathStreamingAssistantSnapshot,
37
+ PrimaryPathToolCallSnapshot,
38
+ PrimaryPathTraceItemSnapshot,
39
+ TurnUsageSnapshot,
40
+ } from "./primary-path-snapshot.js";
41
+ import {
42
+ err,
43
+ nullableStringSchema,
44
+ ok,
45
+ optionalNullableStringSchema,
46
+ type ParseResult,
47
+ parseLiteral,
48
+ parseSchema,
49
+ unknownRecordSchema,
50
+ } from "./protocol.js";
51
+ import type { ToolCallRendererDefinition } from "./tool-renderer-contract.js";
52
+
53
+ export interface AuthMeResponseBody {
54
+ authEnabled: boolean;
55
+ actor: Actor | null;
56
+ }
57
+
58
+ export interface ProcessListItem {
59
+ process: ProcessInstance;
60
+ projects: ProcessProject[];
61
+ workerLease: WorkerLease | null;
62
+ processDisplayName: string | null;
63
+ }
64
+
65
+ export type ScheduleMode = "now" | "once" | "cron";
66
+
67
+ export type ScheduleConfigInput = {
68
+ mode: ScheduleMode;
69
+ runAt?: string | null;
70
+ cronExpression?: string | null;
71
+ };
72
+
73
+ export interface FutureExecutionBaseSummary {
74
+ id: string;
75
+ kind: "launch" | "action";
76
+ scheduleKind: "once" | "cron";
77
+ processId: string;
78
+ nextRunAt: string;
79
+ cronExpression: string | null;
80
+ title: string;
81
+ subtitle: string;
82
+ status?: "scheduled" | "blocked";
83
+ modelSelection?: DurableModelSelection | null;
84
+ blockedReason?: FutureExecutionBlockReason | null;
85
+ }
86
+
87
+ export type LauncherModelConfigDefaults = LaunchModelConfigInput;
88
+
89
+ export interface FutureLaunchSummary extends FutureExecutionBaseSummary {
90
+ kind: "launch";
91
+ launcherId: string;
92
+ launcherLabel: string;
93
+ launchTitle: string | null;
94
+ launcherInput: Record<string, unknown>;
95
+ skillIds: string[];
96
+ modelConfig: LauncherModelConfigDefaults;
97
+ }
98
+
99
+ export interface FutureActionSummary extends FutureExecutionBaseSummary {
100
+ kind: "action";
101
+ instanceId: string;
102
+ actionId: string;
103
+ actionLabel: string;
104
+ nextTurnModelProfileId: string | null;
105
+ }
106
+
107
+ export type FutureExecutionSummary = FutureLaunchSummary | FutureActionSummary;
108
+
109
+ export type ProcessActionFieldDefinition = ActionFormFieldDefinition;
110
+ export type ProcessActionFormDefinition = ActionFormDefinition;
111
+
112
+ export type ProcessActionPreviewSummary = {
113
+ kind: "turn" | "terminal";
114
+ turnId: string | null;
115
+ turnKind: ProcessTurnType | null;
116
+ description: string;
117
+ };
118
+
119
+ export interface ProcessActionSummary {
120
+ id: string;
121
+ label: string;
122
+ description: string | null;
123
+ preview: ProcessActionPreviewSummary | null;
124
+ supportsScheduling: boolean;
125
+ supportsNextTurnModelOverride: boolean;
126
+ form?: ProcessActionFormDefinition;
127
+ }
128
+
129
+ export interface ScheduledActionDetail {
130
+ id: string;
131
+ nextRunAt: string;
132
+ actionId: string;
133
+ actionLabel: string;
134
+ input: Record<string, unknown>;
135
+ nextTurnModelProfileId: string | null;
136
+ status?: "scheduled" | "blocked";
137
+ modelSelection?: DurableModelSelection | null;
138
+ blockedReason?: FutureExecutionBlockReason | null;
139
+ action: ProcessActionSummary;
140
+ }
141
+
142
+ export type ProcessActionModelResolutionSource =
143
+ | ProcessSelectedTurnModelSource
144
+ | "persisted_selection"
145
+ | "none";
146
+
147
+ export interface ProcessActionModelResolutionPreview {
148
+ status: "resolved" | "none" | "error";
149
+ modelProfileId: string | null;
150
+ source: ProcessActionModelResolutionSource | null;
151
+ error: string | null;
152
+ }
153
+
154
+ export interface ProcessActionWarmPromptCacheContext {
155
+ previousModelProfileId: string;
156
+ compatibleModelProfileIds: readonly string[];
157
+ expiresAt: string;
158
+ }
159
+
160
+ export interface PromptCacheSwitchResolution {
161
+ switchingModelMayBypassPromptCache: boolean;
162
+ recommendedModelProfileId: string | null;
163
+ }
164
+
165
+ export function resolvePromptCacheSwitch(input: {
166
+ context: ProcessActionWarmPromptCacheContext | null | undefined;
167
+ effectiveModelProfileId: string;
168
+ selectableModelProfileIds?: readonly string[];
169
+ now?: number;
170
+ }): PromptCacheSwitchResolution {
171
+ const expiresAtMs = input.context ? Date.parse(input.context.expiresAt) : Number.NaN;
172
+ if (
173
+ !input.context ||
174
+ !Number.isFinite(expiresAtMs) ||
175
+ (input.now ?? Date.now()) > expiresAtMs ||
176
+ input.context.compatibleModelProfileIds.includes(input.effectiveModelProfileId)
177
+ ) {
178
+ return { switchingModelMayBypassPromptCache: false, recommendedModelProfileId: null };
179
+ }
180
+ const selectableIds = input.selectableModelProfileIds
181
+ ? new Set(input.selectableModelProfileIds)
182
+ : null;
183
+ const recommendations = input.context.compatibleModelProfileIds.filter(
184
+ (profileId) => !selectableIds || selectableIds.has(profileId),
185
+ );
186
+ return {
187
+ switchingModelMayBypassPromptCache: true,
188
+ recommendedModelProfileId: recommendations.includes(input.context.previousModelProfileId)
189
+ ? input.context.previousModelProfileId
190
+ : (recommendations[0] ?? null),
191
+ };
192
+ }
193
+
194
+ export interface ProcessActionModelPreview {
195
+ kind: "llm_turn" | "not_applicable" | "unavailable";
196
+ turnId: string | null;
197
+ description: string | null;
198
+ resolvedModel?: ProcessActionModelResolutionPreview;
199
+ warmPromptCache?: ProcessActionWarmPromptCacheContext;
200
+ unavailableReason?:
201
+ | "action_not_found"
202
+ | "action_not_visible"
203
+ | "invalid_action_input"
204
+ | "action_failed";
205
+ unavailableMessage?: string | null;
206
+ }
207
+
208
+ export type ProcessExternalSourceSummary = {
209
+ id: string;
210
+ kind: string;
211
+ externalActionId?: string;
212
+ sourceKind?: string;
213
+ label: string | null;
214
+ description: string | null;
215
+ };
216
+
217
+ export type ProcessExternalTriggerSummary = ProcessExternalSourceSummary;
218
+
219
+ export interface ProcessSelectedTurnSummary {
220
+ turnId: string;
221
+ kind: ProcessTurnType;
222
+ description: string;
223
+ commentary: string | null;
224
+ externalTriggers: ProcessExternalSourceSummary[];
225
+ }
226
+
227
+ export type ModelProfileAvailability = "available" | "unavailable" | "stale";
228
+
229
+ export type ModelProfileOptionSummary = {
230
+ id: string;
231
+ label: string;
232
+ description: string;
233
+ availability: ModelProfileAvailability;
234
+ safeReason?: string | null;
235
+ checkedAt?: string | null;
236
+ };
237
+
238
+ export interface ProviderOptionChoiceSummary {
239
+ value: string;
240
+ label: string;
241
+ }
242
+
243
+ export interface ProviderOptionFieldSummary {
244
+ id: string;
245
+ label: string;
246
+ required: boolean;
247
+ minLength: number | null;
248
+ maxLength: number | null;
249
+ defaultValue: string | null;
250
+ /** Advisory values. Values outside this list can still be valid. */
251
+ choices: readonly ProviderOptionChoiceSummary[];
252
+ }
253
+
254
+ export interface ModelProviderOptionsResponseBody {
255
+ modelProfileId: string;
256
+ providerId: string;
257
+ fields: readonly ProviderOptionFieldSummary[];
258
+ choicesStatus: "available" | "unavailable";
259
+ choicesUnavailableReason: string | null;
260
+ }
261
+
262
+ export interface ProcessTurnModelConfigurationView {
263
+ turnId: string;
264
+ description: string;
265
+ pathType: string;
266
+ processConfigModelProfileId: string | null;
267
+ instanceModelProfileId: string | null;
268
+ effectiveConfiguredModelProfileId: string | null;
269
+ source: "instance" | "process_config" | "default";
270
+ }
271
+
272
+ export type ProcessModelConfigurationIssueView = {
273
+ code: "invalid_turn_configs_json";
274
+ reason: "invalid_json" | "not_object" | "turn_config_not_object";
275
+ turnId?: string;
276
+ };
277
+
278
+ export interface ProcessModelConfigurationView {
279
+ state:
280
+ | { kind: "ready" }
281
+ | { kind: "blocked"; issues: readonly ProcessModelConfigurationIssueView[] };
282
+ availableProfiles: readonly ModelProfileOptionSummary[];
283
+ effectiveSelectedTurn: {
284
+ turnId: string;
285
+ description: string;
286
+ modelProfileId: string;
287
+ source: ProcessActionModelResolutionSource;
288
+ } | null;
289
+ defaultModel: {
290
+ processConfigModelProfileId: string | null;
291
+ instanceModelProfileId: string | null;
292
+ effectiveModelProfileId: string | null;
293
+ source: "instance" | "process_config" | "catalog_default" | "none";
294
+ };
295
+ turns: readonly ProcessTurnModelConfigurationView[];
296
+ }
297
+
298
+ export type ProcessRunToolParameterView = {
299
+ name: string;
300
+ type: string;
301
+ description: string;
302
+ required: boolean;
303
+ };
304
+
305
+ export type ProcessRunToolView = {
306
+ name: string;
307
+ description: string;
308
+ parameters: readonly ProcessRunToolParameterView[];
309
+ };
310
+
311
+ export type ProcessRunTurnView = {
312
+ turnId: string;
313
+ description: string;
314
+ pathType: string;
315
+ consumedProducts: readonly string[];
316
+ publishedProducts: readonly string[];
317
+ activePiToolNames: readonly string[];
318
+ outcomeActions: readonly ProcessRunToolView[];
319
+ };
320
+
321
+ export type ProcessRunDetailsView = {
322
+ systemPrompt: string | null;
323
+ appendSystemPrompt: string | null;
324
+ availablePiToolNames: readonly string[];
325
+ turns: readonly ProcessRunTurnView[];
326
+ };
327
+
328
+ export interface ProcessLaunchConfigurationParameterView {
329
+ fieldId: string;
330
+ label: string;
331
+ value: string | null;
332
+ }
333
+
334
+ export interface ProcessLaunchConfigurationProjectView {
335
+ key: string;
336
+ repoLocator: string;
337
+ repoLocatorKind: ProcessProject["repoLocatorKind"];
338
+ baseBranch: string;
339
+ workBranch: string | null;
340
+ externalId: string | null;
341
+ externalUrl: string | null;
342
+ pipelineStatus: string | null;
343
+ }
344
+
345
+ export interface ProcessLaunchConfigurationView {
346
+ launcherId: string | null;
347
+ launcherLabel: string | null;
348
+ launcherSchemaTitle: string | null;
349
+ paramsParseError: string | null;
350
+ parameters: readonly ProcessLaunchConfigurationParameterView[];
351
+ projects: readonly ProcessLaunchConfigurationProjectView[];
352
+ }
353
+
354
+ export interface PiSessionUsageSnapshot {
355
+ input: number;
356
+ output: number;
357
+ /** Provider-reported reasoning/thinking tokens. This is a subset of output tokens. */
358
+ reasoning?: number;
359
+ cacheRead: number;
360
+ cacheWrite: number;
361
+ totalTokens: number;
362
+ cost?: {
363
+ input: number;
364
+ output: number;
365
+ cacheRead: number;
366
+ cacheWrite: number;
367
+ total: number;
368
+ };
369
+ }
370
+
371
+ export type PiSessionTextContentBlock = { type: "text"; text: string };
372
+
373
+ export type PiSessionThinkingContentBlock = {
374
+ type: "thinking";
375
+ thinking: string;
376
+ redacted?: boolean;
377
+ };
378
+
379
+ export type PiSessionToolCallContentBlock = {
380
+ type: "toolCall";
381
+ id: string;
382
+ name: string;
383
+ arguments: Record<string, unknown>;
384
+ };
385
+
386
+ export type PiSessionImageContentBlock = {
387
+ type: "image";
388
+ data: string;
389
+ mimeType: string;
390
+ };
391
+
392
+ export type PiSessionContentBlock =
393
+ | PiSessionTextContentBlock
394
+ | PiSessionThinkingContentBlock
395
+ | PiSessionToolCallContentBlock
396
+ | PiSessionImageContentBlock;
397
+
398
+ export interface PiSessionMessageRecord {
399
+ role?: string;
400
+ content?: string | PiSessionContentBlock[];
401
+ toolCallId?: string;
402
+ toolName?: string;
403
+ details?: unknown;
404
+ isError?: boolean;
405
+ usage?: PiSessionUsageSnapshot;
406
+ stopReason?: string;
407
+ errorMessage?: string;
408
+ provider?: string;
409
+ model?: string;
410
+ timestamp?: number;
411
+ }
412
+
413
+ export interface PiSessionEntry {
414
+ type: string;
415
+ id: string;
416
+ parentId: string | null;
417
+ timestamp: string;
418
+ message?: PiSessionMessageRecord;
419
+ targetId?: string;
420
+ label?: string;
421
+ }
422
+
423
+ export interface ProcessDiagnosticsData {
424
+ process: ProcessInstance;
425
+ projects: ProcessProject[];
426
+ inputs: ProcessInput[];
427
+ events: ProcessEvent[];
428
+ leafOutcomeSnapshots: ProcessLeafOutcomeSnapshot[];
429
+ turnRecords: ProcessTurnRecord[];
430
+ turnAnnotations: ProcessTurnAnnotation[];
431
+ workerLease: WorkerLease | null;
432
+ processDisplayName: string | null;
433
+ processGraph: SerializedProcessGraph;
434
+ processFlow: ProcessFlowView;
435
+ piSessionEntries: PiSessionEntry[];
436
+ definesLeafOutcome: boolean;
437
+ selectedTurn?: ProcessSelectedTurnSummary | null;
438
+ scheduledAction?: ScheduledActionDetail | null;
439
+ modelConfiguration: ProcessModelConfigurationView;
440
+ runDetails: ProcessRunDetailsView;
441
+ launchConfiguration: ProcessLaunchConfigurationView;
442
+ actions: ProcessActionSummary[];
443
+ toolRenderers: ToolCallRendererDefinition[];
444
+ }
445
+
446
+ export interface ProcessDetailData extends ProcessDiagnosticsData {
447
+ primaryPath: PrimaryPathSnapshot;
448
+ }
449
+
450
+ export interface LauncherModelConfigSchema {
451
+ availableProfiles: readonly ModelProfileOptionSummary[];
452
+ llmTurns: ReadonlyArray<{
453
+ turnId: string;
454
+ description: string;
455
+ }>;
456
+ }
457
+
458
+ export type LauncherDefaultModelPreview = {
459
+ source: "instance_default" | "process_config_default" | "catalog_default" | "none";
460
+ profile: ModelProfileOptionSummary | null;
461
+ };
462
+
463
+ export interface LauncherTurnModelConfigPreview {
464
+ turnId: string;
465
+ description: string;
466
+ effective: {
467
+ source: ProcessActionModelResolutionSource;
468
+ profile: ModelProfileOptionSummary | null;
469
+ };
470
+ }
471
+
472
+ export type LauncherModelConfigPreview = {
473
+ defaultModel: LauncherDefaultModelPreview;
474
+ turns: readonly LauncherTurnModelConfigPreview[];
475
+ };
476
+
477
+ export type UiLauncherSummary = UiLauncherSummaryBase & {
478
+ modelConfigSchema?: LauncherModelConfigSchema;
479
+ processFlow?: ProcessFlowView;
480
+ };
481
+
482
+ export type ProcessRetryConfig = {
483
+ launcherId: string;
484
+ title: string | null;
485
+ launcherInput: Record<string, unknown>;
486
+ skillIds: string[];
487
+ modelConfig: LauncherModelConfigDefaults;
488
+ };
489
+
490
+ export type WatcherLaunchModelSummary = {
491
+ defaultModelProfileId: string | null;
492
+ turnConfigs: Array<{ turnId: string; modelProfileId: string | null }>;
493
+ };
494
+
495
+ export interface WatcherSummaryBase {
496
+ processId: string;
497
+ processDisplayName: string;
498
+ watcherId: string;
499
+ label: string;
500
+ description: string;
501
+ type: ProcessWatcherType;
502
+ enabled: boolean;
503
+ pollInterval: string;
504
+ configPath: string;
505
+ targetSummary: string;
506
+ launchModel: WatcherLaunchModelSummary;
507
+ }
508
+
509
+ export interface JiraWatcherSummary extends WatcherSummaryBase {
510
+ type: "jira";
511
+ project: string;
512
+ labels: {
513
+ trigger: string;
514
+ done: string;
515
+ required?: string[];
516
+ forbidden?: string[];
517
+ };
518
+ targetBranchLabelPrefix: string;
519
+ }
520
+
521
+ export interface GitLabMrWatcherSummary extends WatcherSummaryBase {
522
+ type: "gitlab_mr";
523
+ group: string;
524
+ labels: {
525
+ trigger: string;
526
+ done: string;
527
+ };
528
+ }
529
+
530
+ export type FilesystemWatcherSummary = WatcherSummaryBase & {
531
+ type: "filesystem";
532
+ filePath: string;
533
+ };
534
+
535
+ export type WatcherSummary = JiraWatcherSummary | GitLabMrWatcherSummary | FilesystemWatcherSummary;
536
+
537
+ export interface SkillUsageSummary {
538
+ attachedAllTime: number;
539
+ attachedLast30Days: number;
540
+ invokedAllTime: number;
541
+ invokedLast30Days: number;
542
+ }
543
+
544
+ export interface SkillRepositorySummary {
545
+ id: string;
546
+ label: string;
547
+ url: string;
548
+ ref: string;
549
+ path: string;
550
+ lastRefreshedAt: string | null;
551
+ error: string | null;
552
+ }
553
+
554
+ export interface SkillCatalogItem {
555
+ repositoryId: string;
556
+ id: string;
557
+ label: string;
558
+ description: string | null;
559
+ sourcePath: string;
560
+ sourceRevision: string;
561
+ registered: boolean;
562
+ updateAvailable: boolean;
563
+ conflict: boolean;
564
+ stale: boolean;
565
+ usage: SkillUsageSummary;
566
+ }
567
+
568
+ export type SkillRegistrationKind = "configuration" | "catalog";
569
+
570
+ export interface InstalledSkillCatalogItem {
571
+ id: string;
572
+ label: string;
573
+ description: string | null;
574
+ activeRevisionId: string;
575
+ activeSourceRevision: string | null;
576
+ registrationKind: SkillRegistrationKind;
577
+ sourceRepositoryId: string | null;
578
+ updateAvailable: boolean;
579
+ usage: SkillUsageSummary;
580
+ }
581
+
582
+ export interface SkillRevisionSummary {
583
+ id: string;
584
+ sourceRevision: string | null;
585
+ importedAt: string;
586
+ active: boolean;
587
+ }
588
+
589
+ export interface SkillUsageProcessSummary {
590
+ instanceId: string;
591
+ title: string;
592
+ attachedAt: string;
593
+ invocationCount: number;
594
+ lastInvokedAt: string | null;
595
+ }
596
+
597
+ export interface SkillCatalogDetail extends SkillCatalogItem {
598
+ skillMarkdown: string;
599
+ processes: SkillUsageProcessSummary[];
600
+ }
601
+
602
+ export interface InstalledSkillCatalogDetail extends InstalledSkillCatalogItem {
603
+ skillMarkdown: string;
604
+ processes: SkillUsageProcessSummary[];
605
+ revisions: SkillRevisionSummary[];
606
+ }
607
+
608
+ export type ErrorResponseBody = { error?: string | null; code?: string | null };
609
+
610
+ export type ProcessesListResponseBody = {
611
+ processes: ProcessListItem[];
612
+ futureExecutions: FutureExecutionSummary[];
613
+ };
614
+
615
+ export interface ProcessOverviewItem extends ProcessRowSlot {
616
+ processDisplayName: string | null;
617
+ /** Nullable durable title before external-id/instance-id display fallback. */
618
+ processTitle: string | null;
619
+ initialPromptPreview: string | null;
620
+ createdAt: string;
621
+ updatedAt: string;
622
+ closedAt: string | null;
623
+ }
624
+
625
+ interface FutureExecutionOverviewItemBase {
626
+ id: string;
627
+ scheduleKind: "once" | "cron";
628
+ processId: string;
629
+ nextRunAt: string;
630
+ cronExpression: string | null;
631
+ title: string;
632
+ initialPromptPreview: string | null;
633
+ status?: "scheduled" | "blocked";
634
+ blockedReason?: FutureExecutionBlockReason | null;
635
+ }
636
+
637
+ export interface FutureLaunchOverviewItem extends FutureExecutionOverviewItemBase {
638
+ kind: "launch";
639
+ instanceId: null;
640
+ launcherId: string;
641
+ launcherLabel: string;
642
+ }
643
+
644
+ export interface FutureActionOverviewItem extends FutureExecutionOverviewItemBase {
645
+ kind: "action";
646
+ instanceId: string;
647
+ actionId: string;
648
+ actionLabel: string;
649
+ }
650
+
651
+ export type FutureExecutionOverviewItem = FutureLaunchOverviewItem | FutureActionOverviewItem;
652
+
653
+ export interface ProcessesOverviewResponseBody {
654
+ processes: ProcessOverviewItem[];
655
+ futureExecutions: FutureExecutionOverviewItem[];
656
+ /** True when the bounded sidebar response omitted less-recent rows. */
657
+ truncated: boolean;
658
+ }
659
+
660
+ export interface ProcessBrowsePagination {
661
+ limit: number;
662
+ offset: number;
663
+ total: number;
664
+ processTotal: number;
665
+ futureExecutionTotal: number;
666
+ hasMore: boolean;
667
+ }
668
+
669
+ export interface ProcessBrowseFacets {
670
+ statusCounts: Record<
671
+ "all" | "running" | "scheduled" | "needs_attention" | "completed" | "aborted",
672
+ number
673
+ >;
674
+ processTypes: Array<{ value: string; label: string; count: number }>;
675
+ }
676
+
677
+ export type ProcessBrowseItem =
678
+ | { kind: "process"; item: ProcessOverviewItem }
679
+ | { kind: "future"; item: FutureExecutionOverviewItem };
680
+
681
+ export interface ProcessBrowseResponseBody {
682
+ /** Globally sorted page. The browser must preserve this server-owned order. */
683
+ items: ProcessBrowseItem[];
684
+ pagination: ProcessBrowsePagination;
685
+ facets: ProcessBrowseFacets;
686
+ }
687
+
688
+ export type TurnTraceToolCallSnapshot = Omit<PrimaryPathToolCallSnapshot, "result"> & {
689
+ resultText: string | null;
690
+ truncated: boolean;
691
+ };
692
+
693
+ export type TurnPiInputPartRole = "user" | "system" | "unknown";
694
+
695
+ export interface TurnPiInputPart {
696
+ role: TurnPiInputPartRole;
697
+ text: string;
698
+ createdAt: string;
699
+ }
700
+
701
+ export interface TurnPiInputSnapshot {
702
+ parts: TurnPiInputPart[];
703
+ fullPrompt: string;
704
+ createdAt: string;
705
+ userInput?: string | null;
706
+ }
707
+
708
+ export interface TurnTraceSnapshot {
709
+ assistant: PrimaryPathStreamingAssistantSnapshot;
710
+ toolCalls: TurnTraceToolCallSnapshot[];
711
+ traceItems: PrimaryPathTraceItemSnapshot[];
712
+ usage: TurnUsageSnapshot | null;
713
+ piInput: TurnPiInputSnapshot | null;
714
+ }
715
+
716
+ export interface TurnTracePreview {
717
+ turnRecordId: string;
718
+ assistantTextPreview: string;
719
+ assistantTextTruncated: boolean;
720
+ thinkingPreview: string;
721
+ thinkingPreviewTruncated: boolean;
722
+ toolCallCount: number;
723
+ traceItemCount: number;
724
+ hasReasoningDetails: boolean;
725
+ usage: TurnUsageSnapshot | null;
726
+ piInput: { createdAt: string | null; partCount: number; userInputPreview: string | null } | null;
727
+ }
728
+
729
+ export type ProcessTimelineTurnPresentation =
730
+ | "llm_turn"
731
+ | "automatic_turn"
732
+ | "operator_decision"
733
+ | "external_trigger";
734
+
735
+ export interface ProcessTimelineTurnSummary {
736
+ id: string;
737
+ turnId: string;
738
+ turnType: ProcessTurnType;
739
+ displayTurn: string;
740
+ outcome: string;
741
+ summary: string;
742
+ output: string;
743
+ turnResultMarkdown: string;
744
+ pathType: ProcessTurnRecord["pathType"];
745
+ createdAt: string;
746
+ presentation: ProcessTimelineTurnPresentation;
747
+ status: "completed" | "in_progress";
748
+ modelProfileId: string | null;
749
+ /** Durable lineage needed by the chronicle rail and input correlation. */
750
+ attemptNumber: number;
751
+ parentTurnRecordId: string | null;
752
+ startedAt: string;
753
+ endedAt: string | null;
754
+ actionSource: "ui" | "external" | "scheduled" | null;
755
+ }
756
+
757
+ export type ProcessTimelineInputSummary = Pick<
758
+ ProcessInput,
759
+ "id" | "sequence" | "source" | "kind" | "bodyMarkdown" | "receivedAt" | "consumedAt"
760
+ >;
761
+
762
+ export interface ProcessExternalTriggerSignal {
763
+ triggerId: string;
764
+ state: "error" | "armed" | "triggered" | "waiting";
765
+ occurredAt: string | null;
766
+ secondaryDetail: string | null;
767
+ }
768
+
769
+ export interface ProcessTimelineSnapshot {
770
+ prompt: { text: string | null; createdAt: string | null };
771
+ turns: ProcessTimelineTurnSummary[];
772
+ tracePreviewsByTurnRecordId: Record<string, TurnTracePreview>;
773
+ inputs: ProcessTimelineInputSummary[];
774
+ externalTriggerSignals: ProcessExternalTriggerSignal[];
775
+ }
776
+
777
+ export interface CurrentErrorSummary {
778
+ title: string;
779
+ summary: string;
780
+ guidance?: string;
781
+ technicalDetail?: string | null;
782
+ }
783
+
784
+ export interface CurrentTurnRecoverySummary extends CurrentErrorSummary {
785
+ turnRecordId: string;
786
+ defaultContinuePrompt: string;
787
+ canContinue: boolean;
788
+ defaultModelProfileId: string | null;
789
+ providerOptions: Record<string, string>;
790
+ }
791
+
792
+ export interface StartupRecoverySummary extends CurrentErrorSummary {
793
+ startRecordId: string;
794
+ kind: "preparation_failed" | "bootstrap_failed";
795
+ action: "choose_model" | "retry_startup";
796
+ defaultModelProfileId: string | null;
797
+ providerOptions: Record<string, string>;
798
+ }
799
+
800
+ export type CurrentProcessErrorSummary = CurrentErrorSummary;
801
+
802
+ export interface ProcessUsageEstimateSnapshot {
803
+ usage: TurnUsageSnapshot;
804
+ includesLiveTurn: boolean;
805
+ totalLlmTurnCount: number;
806
+ coveredTurnCount: number;
807
+ missingUsageTurnCount: number;
808
+ missingCostTurnCount: number;
809
+ isPartial: boolean;
810
+ }
811
+
812
+ export interface PrimaryPathUiSnapshot extends PrimaryPathSnapshot {
813
+ entryCount: number;
814
+ entriesOmitted: true;
815
+ }
816
+
817
+ export type ProcessUiSnapshotProcess = Pick<
818
+ ProcessInstance,
819
+ | "id"
820
+ | "processId"
821
+ | "selectedTurnId"
822
+ | "lifecycleStatus"
823
+ | "currentExecution"
824
+ | "planRevision"
825
+ | "title"
826
+ | "externalId"
827
+ | "externalUrl"
828
+ | "initialDefaultModelProfileId"
829
+ | "createdAt"
830
+ | "updatedAt"
831
+ | "closedAt"
832
+ >;
833
+
834
+ /**
835
+ * Initial render contract for process detail. Raw process events, inputs,
836
+ * session entries, projects, and full durable records belong to diagnostics;
837
+ * this DTO carries only browser-facing projections.
838
+ */
839
+ export interface ProcessDetailUiSnapshotResponseBody {
840
+ process: ProcessUiSnapshotProcess;
841
+ /** Durable requests in Chronicle order; at most one is open for the current turn. */
842
+ questionRequests: ProcessQuestionRequest[];
843
+ leafOutcomeSnapshots: ProcessLeafOutcomeSnapshot[];
844
+ processDisplayName: string | null;
845
+ processFlow: ProcessFlowView;
846
+ definesLeafOutcome: boolean;
847
+ selectedTurn: ProcessSelectedTurnSummary | null;
848
+ scheduledAction: ScheduledActionDetail | null;
849
+ modelConfiguration: ProcessModelConfigurationView;
850
+ runDetails: ProcessRunDetailsView;
851
+ launchConfiguration: ProcessLaunchConfigurationView;
852
+ actions: ProcessActionSummary[];
853
+ toolRenderers: ToolCallRendererDefinition[];
854
+ primaryPath: PrimaryPathUiSnapshot;
855
+ timeline: ProcessTimelineSnapshot;
856
+ instanceTree: ProcessInstanceTreeResponseBody;
857
+ recovery: CurrentTurnRecoverySummary | null;
858
+ startupRecovery: StartupRecoverySummary | null;
859
+ processError: CurrentProcessErrorSummary | null;
860
+ usageEstimate: ProcessUsageEstimateSnapshot | null;
861
+ persistedModelSelectionWarning: string | null;
862
+ session: { signature: string | null };
863
+ }
864
+
865
+ export type InstanceTreeTurnResultState = "succeeded" | "failed" | "aborted" | "pending";
866
+
867
+ /** Redacted, semantic process history. Pi message/activity categories are never exposed. */
868
+ export interface InstanceTreeNodeSummary {
869
+ id: string;
870
+ parentId: string | null;
871
+ label: string;
872
+ pathType: "primary" | "root_branch" | "leaf_branch";
873
+ resultState: InstanceTreeTurnResultState;
874
+ timestamp: string;
875
+ }
876
+
877
+ export interface InstanceTreeEdgeSummary {
878
+ id: string;
879
+ sourceNodeId: string;
880
+ targetNodeId: string | null;
881
+ hasContext: boolean;
882
+ productLabels: readonly string[];
883
+ actionLabel: string | null;
884
+ endState: "not_applied" | "completed" | null;
885
+ }
886
+
887
+ export interface ProcessInstanceTreeResponseBody {
888
+ currentLeafId: string | null;
889
+ nodes: InstanceTreeNodeSummary[];
890
+ edges: InstanceTreeEdgeSummary[];
891
+ }
892
+
893
+ export interface TurnReasoningDetailResponseBody {
894
+ instanceId: string;
895
+ turnRecordId: string;
896
+ sessionSignature: string | null;
897
+ reasoning: TurnTraceSnapshot;
898
+ }
899
+
900
+ export interface SubmitQuestionAnswersRequestBody {
901
+ draft: QuestionAnswerDraft[];
902
+ }
903
+
904
+ export type QuestionRequestMutationResponseBody = {
905
+ request: ProcessQuestionRequest;
906
+ };
907
+
908
+ export type FutureExecutionDetailResponseBody = FutureExecutionSummary;
909
+
910
+ export type LaunchersResponseBody = { launchers: UiLauncherSummary[] };
911
+
912
+ export type WatchersResponseBody = { watchers: WatcherSummary[] };
913
+ export type SkillCatalogDetailResponseBody = { skill: SkillCatalogDetail };
914
+ export type InstalledSkillCatalogDetailResponseBody = { skill: InstalledSkillCatalogDetail };
915
+ export type SkillsCatalogResponseBody = {
916
+ repositories: SkillRepositorySummary[];
917
+ availableSkills: SkillCatalogItem[];
918
+ installedSkills: InstalledSkillCatalogItem[];
919
+ };
920
+
921
+ export interface LauncherDefaultsResponseBody {
922
+ defaults: Record<string, unknown>;
923
+ title: string | null;
924
+ modelConfig: LauncherModelConfigDefaults;
925
+ warnings?: LauncherValidationError[];
926
+ }
927
+
928
+ export type LauncherOptionsResponseBody = {
929
+ options: Record<string, readonly FormFieldOptionDefinition[]>;
930
+ };
931
+
932
+ export type LauncherRecentValuesResponseBody = {
933
+ values: Record<string, readonly string[]>;
934
+ };
935
+
936
+ export type LauncherModelConfigPreviewResponseBody = { preview: LauncherModelConfigPreview };
937
+
938
+ export interface LauncherMutationResponseBody {
939
+ kind?: "scheduled";
940
+ process?: ProcessInstance | null;
941
+ futureExecution?: FutureLaunchSummary | null;
942
+ projects?: ProcessProject[];
943
+ errors?: LauncherValidationError[];
944
+ error?: string | null;
945
+ }
946
+
947
+ export type ScheduledActionMutationResponseBody = {
948
+ kind?: "scheduled";
949
+ scheduledAction?: ScheduledActionDetail | null;
950
+ error?: string | null;
951
+ };
952
+
953
+ export type ProcessRetryConfigResponseBody = ProcessRetryConfig;
954
+
955
+ export type ProcessActionModelPreviewResponseBody = { preview: ProcessActionModelPreview };
956
+
957
+ export type ProcessDiagnosticsResponseBody = ProcessDiagnosticsData;
958
+
959
+ export type PrimaryPathSnapshotResponseBody = PrimaryPathSnapshot;
960
+
961
+ export type CronPreviewResponseBody = { nextRunAt: string };
962
+
963
+ type ParsedLauncherRequestBody = {
964
+ title: string | null;
965
+ titleProvided: boolean;
966
+ launcherInput: Record<string, unknown>;
967
+ launcherInputProvided: boolean;
968
+ skillIds?: string[];
969
+ modelConfig: LauncherModelConfigDefaults;
970
+ modelConfigProvided: boolean;
971
+ schedule: ParsedScheduleRequest;
972
+ scheduleProvided: boolean;
973
+ };
974
+
975
+ type ParsedActionRequestBody = {
976
+ input: Record<string, unknown>;
977
+ inputProvided: boolean;
978
+ nextTurnModelProfileId?: string | null;
979
+ nextTurnModelProfileIdProvided: boolean;
980
+ schedule: ParsedScheduleRequest;
981
+ scheduleProvided: boolean;
982
+ };
983
+
984
+ const SCHEDULE_MODES = ["now", "once", "cron"] as const;
985
+ const PROCESS_LIFECYCLE_STATUSES = [
986
+ "discovered",
987
+ "active",
988
+ "waiting",
989
+ "error",
990
+ "completed",
991
+ "aborted",
992
+ ] as const;
993
+ const launcherStructuredBodySchema = v.strictObject({
994
+ title: v.optional(nullableStringSchema),
995
+ launcherInput: v.optional(unknownRecordSchema),
996
+ skillIds: v.optional(v.array(v.string())),
997
+ modelConfig: v.optional(v.unknown()),
998
+ schedule: v.optional(v.unknown()),
999
+ });
1000
+ const actionStructuredBodySchema = v.strictObject({
1001
+ input: v.optional(unknownRecordSchema),
1002
+ nextTurnModelProfileId: optionalNullableStringSchema,
1003
+ schedule: v.optional(v.unknown()),
1004
+ });
1005
+ const futureLaunchPayloadInputSchema = v.object({
1006
+ launcherInput: v.optional(v.nullable(unknownRecordSchema)),
1007
+ modelConfig: v.optional(v.unknown()),
1008
+ actor: v.optional(v.nullable(unknownRecordSchema)),
1009
+ launchPlan: v.object({
1010
+ launcherId: v.string(),
1011
+ processId: v.string(),
1012
+ handoffDedupKey: optionalNullableStringSchema,
1013
+ processInput: v.object({
1014
+ processId: v.string(),
1015
+ selectedTurnId: optionalNullableStringSchema,
1016
+ lifecycleStatus: v.picklist(PROCESS_LIFECYCLE_STATUSES),
1017
+ title: optionalNullableStringSchema,
1018
+ externalId: optionalNullableStringSchema,
1019
+ externalUrl: optionalNullableStringSchema,
1020
+ metadata: v.optional(v.nullable(unknownRecordSchema)),
1021
+ defaultModelProfileId: optionalNullableStringSchema,
1022
+ turnConfigsJson: optionalNullableStringSchema,
1023
+ selectedTurnModelProfileId: optionalNullableStringSchema,
1024
+ selectedTurnModelKind: v.optional(v.nullable(v.picklist(["explicit", "inherited"]))),
1025
+ selectedTurnModelSource: v.optional(
1026
+ v.nullable(
1027
+ v.picklist([
1028
+ "action_override",
1029
+ "launch_override",
1030
+ "instance_turn_config",
1031
+ "process_config_turn",
1032
+ "instance_default",
1033
+ "process_config_default",
1034
+ "catalog_default",
1035
+ "legacy_persisted",
1036
+ ]),
1037
+ ),
1038
+ ),
1039
+ paramsJson: optionalNullableStringSchema,
1040
+ stateJson: optionalNullableStringSchema,
1041
+ }),
1042
+ titleSourceFields: v.optional(
1043
+ v.nullable(v.array(v.object({ label: v.string(), value: v.string() }))),
1044
+ ),
1045
+ projectInputs: v.optional(
1046
+ v.nullable(
1047
+ v.array(
1048
+ v.object({
1049
+ key: v.string(),
1050
+ repoLocator: v.string(),
1051
+ baseBranch: v.string(),
1052
+ workBranch: optionalNullableStringSchema,
1053
+ externalId: optionalNullableStringSchema,
1054
+ externalUrl: optionalNullableStringSchema,
1055
+ metadata: v.optional(v.nullable(unknownRecordSchema)),
1056
+ }),
1057
+ ),
1058
+ ),
1059
+ ),
1060
+ startTurnId: optionalNullableStringSchema,
1061
+ }),
1062
+ selectedSkillIds: v.optional(v.array(v.string())),
1063
+ resourceSelections: v.optional(
1064
+ v.array(v.object({ skillId: v.string(), revisionId: v.string() })),
1065
+ ),
1066
+ });
1067
+ const futureActionPayloadInputSchema = v.object({
1068
+ input: v.optional(v.nullable(unknownRecordSchema)),
1069
+ nextTurnModelProfileId: optionalNullableStringSchema,
1070
+ actionLabel: optionalNullableStringSchema,
1071
+ actor: v.optional(v.nullable(unknownRecordSchema)),
1072
+ });
1073
+
1074
+ export type ParsedScheduleRequest =
1075
+ | { mode: "now" }
1076
+ | { mode: "once"; runAt: string }
1077
+ | { mode: "cron"; cronExpression: string };
1078
+ type ValidatedScheduleRequest =
1079
+ | { mode: "now"; nextRunAt: null; cronExpression: null }
1080
+ | { mode: "once"; nextRunAt: string; cronExpression: null }
1081
+ | { mode: "cron"; nextRunAt: string; cronExpression: string };
1082
+
1083
+ type FutureLaunchPayloadBase = v.InferOutput<typeof futureLaunchPayloadInputSchema>;
1084
+ type FutureActionPayloadBase = v.InferOutput<typeof futureActionPayloadInputSchema>;
1085
+ const cloneUnknownRecord = (value?: Record<string, unknown> | null) =>
1086
+ value ? { ...value } : null;
1087
+ const cloneTurnConfigMap = (turnConfigs: InstanceTurnConfigMap = {}) =>
1088
+ Object.fromEntries(
1089
+ Object.entries(turnConfigs as Record<string, InstanceTurnConfigMap[string]>).map(
1090
+ ([turnId, turnConfig]) => [turnId, { ...turnConfig }],
1091
+ ),
1092
+ ) as InstanceTurnConfigMap;
1093
+ const normalizeFutureLaunchPayload = (payload: FutureLaunchPayloadBase) => {
1094
+ const modelConfig = normalizeLaunchModelConfigInput(
1095
+ (payload.modelConfig ?? {}) as LaunchModelConfigInput,
1096
+ );
1097
+ return {
1098
+ launcherInput: cloneUnknownRecord(payload.launcherInput) ?? {},
1099
+ modelConfig: {
1100
+ defaultModelProfileId: modelConfig.defaultModelProfileId ?? null,
1101
+ turnConfigs: cloneTurnConfigMap(modelConfig.turnConfigs),
1102
+ },
1103
+ actor: normalizeActor(payload.actor),
1104
+ selectedSkillIds: [
1105
+ ...(payload.selectedSkillIds ??
1106
+ payload.resourceSelections?.map(({ skillId }) => skillId) ??
1107
+ []),
1108
+ ],
1109
+ resourceSelections: (payload.resourceSelections ?? []).map((selection) => ({ ...selection })),
1110
+ launchPlan: {
1111
+ launcherId: payload.launchPlan.launcherId,
1112
+ processId: payload.launchPlan.processId,
1113
+ handoffDedupKey: trimToNull(payload.launchPlan.handoffDedupKey) ?? null,
1114
+ processInput: {
1115
+ processId: payload.launchPlan.processInput.processId,
1116
+ selectedTurnId: payload.launchPlan.processInput.selectedTurnId ?? null,
1117
+ lifecycleStatus: payload.launchPlan.processInput.lifecycleStatus,
1118
+ title: payload.launchPlan.processInput.title ?? null,
1119
+ externalId: payload.launchPlan.processInput.externalId ?? null,
1120
+ externalUrl: payload.launchPlan.processInput.externalUrl ?? null,
1121
+ metadata: cloneUnknownRecord(payload.launchPlan.processInput.metadata),
1122
+ defaultModelProfileId: payload.launchPlan.processInput.defaultModelProfileId ?? null,
1123
+ turnConfigsJson: payload.launchPlan.processInput.turnConfigsJson ?? null,
1124
+ selectedTurnModelProfileId:
1125
+ payload.launchPlan.processInput.selectedTurnModelProfileId ?? null,
1126
+ selectedTurnModelKind: payload.launchPlan.processInput.selectedTurnModelKind ?? null,
1127
+ selectedTurnModelSource: payload.launchPlan.processInput.selectedTurnModelSource ?? null,
1128
+ paramsJson: payload.launchPlan.processInput.paramsJson ?? null,
1129
+ stateJson: payload.launchPlan.processInput.stateJson ?? null,
1130
+ },
1131
+ titleSourceFields: (payload.launchPlan.titleSourceFields ?? []).map((field) => ({
1132
+ ...field,
1133
+ })),
1134
+ projectInputs: (payload.launchPlan.projectInputs ?? []).map((project) => ({
1135
+ key: project.key,
1136
+ repoLocator: project.repoLocator,
1137
+ baseBranch: project.baseBranch,
1138
+ workBranch: project.workBranch ?? null,
1139
+ externalId: project.externalId ?? null,
1140
+ externalUrl: project.externalUrl ?? null,
1141
+ metadata: cloneUnknownRecord(project.metadata),
1142
+ })),
1143
+ startTurnId: payload.launchPlan.startTurnId ?? null,
1144
+ },
1145
+ };
1146
+ };
1147
+ const normalizeFutureActionPayload = (payload: FutureActionPayloadBase) => ({
1148
+ input: cloneUnknownRecord(payload.input) ?? {},
1149
+ nextTurnModelProfileId: trimToNull(payload.nextTurnModelProfileId) ?? null,
1150
+ actionLabel: trimToNull(payload.actionLabel) ?? null,
1151
+ actor: normalizeActor(payload.actor),
1152
+ });
1153
+
1154
+ export type FutureLaunchPayload = ReturnType<typeof normalizeFutureLaunchPayload>;
1155
+ export type FutureActionPayload = ReturnType<typeof normalizeFutureActionPayload>;
1156
+
1157
+ function hasOwn(object: Record<string, unknown>, key: string): boolean {
1158
+ return Object.hasOwn(object, key);
1159
+ }
1160
+
1161
+ function parseJsonPayload(payloadJson: string, context: string): ParseResult<unknown> {
1162
+ try {
1163
+ return ok(JSON.parse(payloadJson));
1164
+ } catch {
1165
+ return err(`${context} must be valid JSON`);
1166
+ }
1167
+ }
1168
+
1169
+ function parseRecord(value: unknown, context: string): ParseResult<Record<string, unknown>> {
1170
+ return parseSchema(unknownRecordSchema, value, context);
1171
+ }
1172
+
1173
+ function parseLauncherTurnConfigMap(
1174
+ value: unknown,
1175
+ context: string,
1176
+ ): ParseResult<InstanceTurnConfigMap> {
1177
+ const record = parseRecord(value, context);
1178
+ if (!record.ok) {
1179
+ return record;
1180
+ }
1181
+ const turnConfigs: InstanceTurnConfigMap = {};
1182
+ for (const [turnId, turnConfigValue] of Object.entries(record.value)) {
1183
+ const turnConfig = parseRecord(turnConfigValue, `${context}.${turnId}`);
1184
+ if (!turnConfig.ok) {
1185
+ return turnConfig;
1186
+ }
1187
+ const modelProfileId =
1188
+ trimToNull(turnConfig.value.modelProfileId) ?? trimToNull(turnConfig.value.model_profile);
1189
+ turnConfigs[turnId] = modelProfileId ? { modelProfileId } : {};
1190
+ }
1191
+ return ok(turnConfigs);
1192
+ }
1193
+
1194
+ export function parseScheduleRequestInput(value: unknown): ParseResult<ParsedScheduleRequest> {
1195
+ if (value === undefined || value === null) {
1196
+ return ok({ mode: "now" });
1197
+ }
1198
+ const record = parseRecord(value, "schedule");
1199
+ if (!record.ok) {
1200
+ return record;
1201
+ }
1202
+ const mode = parseLiteral(record.value.mode ?? "now", SCHEDULE_MODES, "schedule.mode");
1203
+ if (!mode.ok || mode.value === "now") {
1204
+ return mode.ok ? ok({ mode: "now" }) : mode;
1205
+ }
1206
+ if (mode.value === "once") {
1207
+ const runAt = typeof record.value.runAt === "string" ? record.value.runAt : null;
1208
+ return runAt && !Number.isNaN(Date.parse(runAt))
1209
+ ? ok({ mode: "once", runAt: new Date(runAt).toISOString() })
1210
+ : err("runAt must be a valid ISO datetime");
1211
+ }
1212
+ const cronExpression = trimToNull(record.value.cronExpression);
1213
+ return cronExpression
1214
+ ? ok({ mode: "cron", cronExpression })
1215
+ : err("cronExpression is required for cron schedules");
1216
+ }
1217
+
1218
+ export function validateScheduleRequestInput(
1219
+ schedule: ParsedScheduleRequest,
1220
+ allowedModes: readonly ScheduleMode[],
1221
+ options: {
1222
+ now?: () => Date;
1223
+ resolveCronNextRunAt?: (expression: string, now: Date) => string;
1224
+ } = {},
1225
+ ): ParseResult<ValidatedScheduleRequest> {
1226
+ if (!allowedModes.includes(schedule.mode)) {
1227
+ return err(`Unsupported schedule mode '${schedule.mode}'`);
1228
+ }
1229
+ if (schedule.mode === "now") {
1230
+ return ok({ mode: "now", nextRunAt: null, cronExpression: null });
1231
+ }
1232
+ const now = options.now ?? (() => new Date());
1233
+ if (schedule.mode === "once") {
1234
+ const runAt = new Date(schedule.runAt);
1235
+ return Number.isNaN(runAt.getTime())
1236
+ ? err("runAt must be a valid ISO datetime")
1237
+ : runAt.getTime() <= now().getTime()
1238
+ ? err("Scheduled time must be in the future")
1239
+ : ok({ mode: "once", nextRunAt: runAt.toISOString(), cronExpression: null });
1240
+ }
1241
+ if (!options.resolveCronNextRunAt) {
1242
+ return err("resolveCronNextRunAt is required for cron schedules");
1243
+ }
1244
+ try {
1245
+ return ok({
1246
+ mode: "cron",
1247
+ nextRunAt: options.resolveCronNextRunAt(schedule.cronExpression, now()),
1248
+ cronExpression: schedule.cronExpression,
1249
+ });
1250
+ } catch (error) {
1251
+ return err(error instanceof Error ? error.message : "Invalid cron expression");
1252
+ }
1253
+ }
1254
+
1255
+ export function parseLauncherTurnConfigsJson(
1256
+ turnConfigsJson: string | null | undefined,
1257
+ ): ParseResult<InstanceTurnConfigMap> {
1258
+ if (!turnConfigsJson) {
1259
+ return ok({});
1260
+ }
1261
+ const parsed = parseJsonPayload(turnConfigsJson, "turnConfigsJson");
1262
+ return parsed.ok ? parseLauncherTurnConfigMap(parsed.value, "turnConfigsJson") : parsed;
1263
+ }
1264
+
1265
+ export function parseLauncherInputJson(
1266
+ launcherInputJson: string | null | undefined,
1267
+ context = "launcherInputJson",
1268
+ ): ParseResult<Record<string, unknown>> {
1269
+ if (launcherInputJson === undefined || launcherInputJson === null) {
1270
+ return ok({});
1271
+ }
1272
+ const parsed = parseJsonPayload(launcherInputJson, context);
1273
+ return parsed.ok ? parseRecord(parsed.value, context) : parsed;
1274
+ }
1275
+
1276
+ export function parseLauncherModelConfigInput(
1277
+ value: unknown,
1278
+ context = "modelConfig",
1279
+ ): ParseResult<LaunchModelConfigInput> {
1280
+ if (value === undefined || value === null) {
1281
+ return ok({});
1282
+ }
1283
+ const record = parseRecord(value, context);
1284
+ if (!record.ok) {
1285
+ return record;
1286
+ }
1287
+ const defaultModelProfileId = trimToNull(record.value.defaultModelProfileId);
1288
+ if (
1289
+ hasOwn(record.value, "defaultModelProfileId") &&
1290
+ record.value.defaultModelProfileId !== null &&
1291
+ typeof record.value.defaultModelProfileId !== "string"
1292
+ ) {
1293
+ return err(`${context}.defaultModelProfileId must be a string or null`);
1294
+ }
1295
+ const turnConfigs =
1296
+ record.value.turnConfigs === undefined
1297
+ ? ok(undefined)
1298
+ : parseLauncherTurnConfigMap(record.value.turnConfigs, `${context}.turnConfigs`);
1299
+ return turnConfigs.ok
1300
+ ? ok(
1301
+ normalizeLaunchModelConfigInput({
1302
+ ...(defaultModelProfileId ? { defaultModelProfileId } : {}),
1303
+ ...(turnConfigs.value ? { turnConfigs: turnConfigs.value } : {}),
1304
+ }),
1305
+ )
1306
+ : turnConfigs;
1307
+ }
1308
+
1309
+ function hasInlineScheduleFields(object: Record<string, unknown>): boolean {
1310
+ return hasOwn(object, "mode") || hasOwn(object, "runAt") || hasOwn(object, "cronExpression");
1311
+ }
1312
+
1313
+ export function parseLauncherRequestBody(value: unknown): ParseResult<ParsedLauncherRequestBody> {
1314
+ if (value === undefined || value === null) {
1315
+ return ok({
1316
+ title: null,
1317
+ titleProvided: false,
1318
+ launcherInput: {},
1319
+ launcherInputProvided: false,
1320
+ modelConfig: {},
1321
+ modelConfigProvided: false,
1322
+ schedule: { mode: "now" },
1323
+ scheduleProvided: false,
1324
+ });
1325
+ }
1326
+ const record = parseRecord(value, "launcher request body");
1327
+ if (!record.ok) {
1328
+ return record;
1329
+ }
1330
+ if (
1331
+ hasOwn(record.value, "title") ||
1332
+ record.value.launcherInput !== undefined ||
1333
+ record.value.skillIds !== undefined ||
1334
+ record.value.modelConfig !== undefined ||
1335
+ record.value.schedule !== undefined
1336
+ ) {
1337
+ if (
1338
+ Object.keys(record.value).some(
1339
+ (key) =>
1340
+ key !== "title" &&
1341
+ key !== "launcherInput" &&
1342
+ key !== "skillIds" &&
1343
+ key !== "modelConfig" &&
1344
+ key !== "schedule",
1345
+ )
1346
+ ) {
1347
+ return err(
1348
+ "launcher request body must use { title, launcherInput, skillIds, modelConfig, schedule }",
1349
+ );
1350
+ }
1351
+ const parsed = parseSchema(launcherStructuredBodySchema, value, "launcher request body");
1352
+ if (!parsed.ok) {
1353
+ return parsed;
1354
+ }
1355
+ const modelConfig = parseLauncherModelConfigInput(parsed.value.modelConfig);
1356
+ if (!modelConfig.ok) {
1357
+ return modelConfig;
1358
+ }
1359
+ const schedule = parseScheduleRequestInput(parsed.value.schedule);
1360
+ if (!schedule.ok) {
1361
+ return schedule;
1362
+ }
1363
+ const skillIds = parsed.value.skillIds ?? [];
1364
+ if (new Set(skillIds).size !== skillIds.length) {
1365
+ return err("skillIds must not contain duplicates");
1366
+ }
1367
+ return ok({
1368
+ title: parsed.value.title ?? null,
1369
+ titleProvided: hasOwn(record.value, "title"),
1370
+ launcherInput: parsed.value.launcherInput ?? {},
1371
+ launcherInputProvided: hasOwn(record.value, "launcherInput"),
1372
+ ...(hasOwn(record.value, "skillIds") ? { skillIds: [...skillIds] } : {}),
1373
+ modelConfig: modelConfig.value,
1374
+ modelConfigProvided: hasOwn(record.value, "modelConfig"),
1375
+ schedule: schedule.value,
1376
+ scheduleProvided: hasOwn(record.value, "schedule"),
1377
+ });
1378
+ }
1379
+ const modelConfig = parseLauncherModelConfigInput(record.value, "modelConfig");
1380
+ if (!modelConfig.ok) {
1381
+ return modelConfig;
1382
+ }
1383
+ const schedule = parseScheduleRequestInput(record.value);
1384
+ if (!schedule.ok) {
1385
+ return schedule;
1386
+ }
1387
+ return ok({
1388
+ title: null,
1389
+ titleProvided: false,
1390
+ launcherInput: record.value,
1391
+ launcherInputProvided: true,
1392
+ modelConfig: modelConfig.value,
1393
+ modelConfigProvided: true,
1394
+ schedule: schedule.value,
1395
+ scheduleProvided: hasInlineScheduleFields(record.value),
1396
+ });
1397
+ }
1398
+
1399
+ export function parseActionRequestBody(value: unknown): ParseResult<ParsedActionRequestBody> {
1400
+ if (value === undefined || value === null) {
1401
+ return ok({
1402
+ input: {},
1403
+ inputProvided: false,
1404
+ nextTurnModelProfileIdProvided: false,
1405
+ schedule: { mode: "now" },
1406
+ scheduleProvided: false,
1407
+ });
1408
+ }
1409
+ const record = parseRecord(value, "action request body");
1410
+ if (!record.ok) {
1411
+ return record;
1412
+ }
1413
+ const nextTurnModelProfileIdProvided = hasOwn(record.value, "nextTurnModelProfileId");
1414
+ if (
1415
+ record.value.input !== undefined ||
1416
+ nextTurnModelProfileIdProvided ||
1417
+ record.value.schedule !== undefined
1418
+ ) {
1419
+ if (
1420
+ Object.keys(record.value).some(
1421
+ (key) => key !== "input" && key !== "nextTurnModelProfileId" && key !== "schedule",
1422
+ )
1423
+ ) {
1424
+ return err("action request body must use { input, nextTurnModelProfileId }");
1425
+ }
1426
+ const parsed = parseSchema(actionStructuredBodySchema, value, "action request body");
1427
+ if (!parsed.ok) {
1428
+ return parsed;
1429
+ }
1430
+ const schedule = parseScheduleRequestInput(parsed.value.schedule);
1431
+ if (!schedule.ok) {
1432
+ return schedule;
1433
+ }
1434
+ return ok({
1435
+ input: parsed.value.input ?? {},
1436
+ inputProvided: hasOwn(record.value, "input"),
1437
+ nextTurnModelProfileIdProvided,
1438
+ schedule: schedule.value,
1439
+ scheduleProvided: hasOwn(record.value, "schedule"),
1440
+ ...(nextTurnModelProfileIdProvided
1441
+ ? { nextTurnModelProfileId: parsed.value.nextTurnModelProfileId ?? null }
1442
+ : {}),
1443
+ });
1444
+ }
1445
+ const schedule = parseScheduleRequestInput(record.value);
1446
+ if (!schedule.ok) {
1447
+ return schedule;
1448
+ }
1449
+ return ok({
1450
+ input: record.value,
1451
+ inputProvided: true,
1452
+ nextTurnModelProfileIdProvided,
1453
+ schedule: schedule.value,
1454
+ scheduleProvided: hasInlineScheduleFields(record.value),
1455
+ ...(nextTurnModelProfileIdProvided
1456
+ ? { nextTurnModelProfileId: trimToNull(record.value.nextTurnModelProfileId) }
1457
+ : {}),
1458
+ });
1459
+ }
1460
+
1461
+ export function serializeFutureLaunchPayload(payload: unknown): string {
1462
+ return JSON.stringify(normalizeFutureLaunchPayload(payload as FutureLaunchPayloadBase));
1463
+ }
1464
+
1465
+ export function parseFutureLaunchPayloadObject(
1466
+ value: unknown,
1467
+ context = "Scheduled launch payload",
1468
+ ): ParseResult<FutureLaunchPayload> {
1469
+ const parsed = parseSchema(futureLaunchPayloadInputSchema, value, context);
1470
+ return parsed.ok ? ok(normalizeFutureLaunchPayload(parsed.value)) : parsed;
1471
+ }
1472
+
1473
+ export function parseFutureLaunchPayloadJson(
1474
+ payloadJson: string,
1475
+ ): ParseResult<FutureLaunchPayload> {
1476
+ const parsed = parseJsonPayload(payloadJson, "Scheduled launch payload");
1477
+ return parsed.ok ? parseFutureLaunchPayloadObject(parsed.value) : parsed;
1478
+ }
1479
+
1480
+ export function serializeFutureActionPayload(payload: unknown): string {
1481
+ return JSON.stringify(normalizeFutureActionPayload(payload as FutureActionPayloadBase));
1482
+ }
1483
+
1484
+ export function parseFutureActionPayloadObject(
1485
+ value: unknown,
1486
+ context = "Scheduled action payload",
1487
+ ): ParseResult<FutureActionPayload> {
1488
+ const parsed = parseSchema(futureActionPayloadInputSchema, value, context);
1489
+ return parsed.ok ? ok(normalizeFutureActionPayload(parsed.value)) : parsed;
1490
+ }
1491
+
1492
+ export function parseFutureActionPayloadJson(
1493
+ payloadJson: string,
1494
+ ): ParseResult<FutureActionPayload> {
1495
+ const parsed = parseJsonPayload(payloadJson, "Scheduled action payload");
1496
+ return parsed.ok ? parseFutureActionPayloadObject(parsed.value) : parsed;
1497
+ }