@leitwerk-dev/process-sdk 0.1.9 → 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.
Files changed (169) hide show
  1. package/dist/{chunk-TRQJ5PRM.js → chunk-TA4KO53Q.js} +1 -5
  2. package/dist/chunk-TA4KO53Q.js.map +1 -0
  3. package/dist/{chunk-5RJZ2E7D.js → chunk-WFY2WWZE.js} +2 -6
  4. package/dist/{chunk-5RJZ2E7D.js.map → chunk-WFY2WWZE.js.map} +1 -1
  5. package/dist/core-capabilities.d.ts +70 -34
  6. package/dist/core-capabilities.d.ts.map +1 -1
  7. package/dist/define-process.d.ts +17 -49
  8. package/dist/define-process.d.ts.map +1 -1
  9. package/dist/{extension-api-BBcwktmc.d.ts → extension-api-CcqZCYJx.d.ts} +136 -70
  10. package/dist/extension-api.d.ts +115 -7
  11. package/dist/extension-api.d.ts.map +1 -1
  12. package/dist/external-action-source.d.ts +7 -0
  13. package/dist/external-action-source.d.ts.map +1 -0
  14. package/dist/external-source-poll.d.ts +15 -0
  15. package/dist/external-source-poll.d.ts.map +1 -0
  16. package/dist/flow.d.ts +80 -104
  17. package/dist/flow.d.ts.map +1 -1
  18. package/dist/fs-utils.d.ts +2 -0
  19. package/dist/fs-utils.d.ts.map +1 -1
  20. package/dist/git-binary.js +25 -33
  21. package/dist/git-binary.js.map +1 -1
  22. package/dist/index.d.ts +21 -9
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +4694 -29
  25. package/dist/index.js.map +1 -1
  26. package/dist/integration-http.d.ts +21 -0
  27. package/dist/integration-http.d.ts.map +1 -0
  28. package/dist/json-data.d.ts +3 -0
  29. package/dist/json-data.d.ts.map +1 -0
  30. package/dist/leaf-outcome-renderer.js +74 -64
  31. package/dist/leaf-outcome-renderer.js.map +1 -1
  32. package/dist/leaf-outcomes.d.ts.map +1 -1
  33. package/dist/model-provider.d.ts.map +1 -1
  34. package/dist/pi-config.d.ts +1 -5
  35. package/dist/pi-config.d.ts.map +1 -1
  36. package/dist/pi-config.js +20 -180
  37. package/dist/pi-config.js.map +1 -1
  38. package/dist/process-flow-view.d.ts.map +1 -1
  39. package/dist/process-graph.d.ts.map +1 -1
  40. package/dist/process-watcher-source.d.ts.map +1 -1
  41. package/dist/project-binding.d.ts +9 -0
  42. package/dist/project-binding.d.ts.map +1 -0
  43. package/dist/registry-utils.d.ts.map +1 -1
  44. package/dist/repository-feedback.d.ts +29 -0
  45. package/dist/repository-feedback.d.ts.map +1 -0
  46. package/dist/repository-git-env.d.ts +2 -0
  47. package/dist/repository-git-env.d.ts.map +1 -1
  48. package/dist/repository-http.d.ts +19 -0
  49. package/dist/repository-http.d.ts.map +1 -0
  50. package/dist/repository-https.d.ts +3 -0
  51. package/dist/repository-https.d.ts.map +1 -0
  52. package/dist/repository-issue-watcher.d.ts +31 -0
  53. package/dist/repository-issue-watcher.d.ts.map +1 -0
  54. package/dist/repository-source-config.d.ts +32 -0
  55. package/dist/repository-source-config.d.ts.map +1 -0
  56. package/dist/repository-types.d.ts +36 -0
  57. package/dist/repository-types.d.ts.map +1 -0
  58. package/dist/review-flow.js +12 -43
  59. package/dist/review-flow.js.map +1 -1
  60. package/dist/runtime-internals.js +18 -2
  61. package/dist/runtime-internals.js.map +1 -1
  62. package/dist/state-helpers.d.ts +2 -0
  63. package/dist/state-helpers.d.ts.map +1 -1
  64. package/dist/subprocess-env.d.ts +1 -0
  65. package/dist/subprocess-env.d.ts.map +1 -1
  66. package/dist/tool-arguments.d.ts +7 -0
  67. package/dist/tool-arguments.d.ts.map +1 -0
  68. package/dist/turn-semantics.d.ts +5 -6
  69. package/dist/turn-semantics.d.ts.map +1 -1
  70. package/dist/types.d.ts +5 -15
  71. package/dist/types.d.ts.map +1 -1
  72. package/package.json +6 -5
  73. package/src/core-capabilities.ts +81 -37
  74. package/src/define-process.ts +190 -313
  75. package/src/extension-api.ts +142 -6
  76. package/src/external-action-source.ts +12 -0
  77. package/src/external-source-poll.ts +49 -0
  78. package/src/flow.ts +332 -664
  79. package/src/fs-utils.ts +17 -2
  80. package/src/index.ts +54 -13
  81. package/src/integration-http.ts +58 -0
  82. package/src/json-data.ts +25 -0
  83. package/src/leaf-outcomes.ts +1 -9
  84. package/src/model-provider.ts +10 -23
  85. package/src/pi-config.ts +1 -6
  86. package/src/process-flow-view.ts +32 -88
  87. package/src/process-graph.ts +25 -51
  88. package/src/process-watcher-source.ts +3 -6
  89. package/src/project-binding.ts +36 -0
  90. package/src/registry-utils.ts +1 -5
  91. package/src/repository-feedback.ts +59 -0
  92. package/src/repository-git-env.ts +34 -0
  93. package/src/repository-http.ts +71 -0
  94. package/src/repository-https.ts +22 -0
  95. package/src/repository-issue-watcher.ts +92 -0
  96. package/src/repository-source-config.ts +60 -0
  97. package/src/repository-types.ts +25 -0
  98. package/src/state-helpers.ts +8 -4
  99. package/src/subprocess-env.ts +6 -0
  100. package/src/tool-arguments.ts +37 -0
  101. package/src/turn-semantics.ts +31 -75
  102. package/src/types.ts +5 -15
  103. package/dist/browser-ui-extension.js +0 -2
  104. package/dist/browser-ui-extension.js.map +0 -1
  105. package/dist/capabilities.js +0 -7
  106. package/dist/capabilities.js.map +0 -1
  107. package/dist/chunk-TRQJ5PRM.js.map +0 -1
  108. package/dist/codecs.js +0 -9
  109. package/dist/codecs.js.map +0 -1
  110. package/dist/commit-message.js +0 -3
  111. package/dist/commit-message.js.map +0 -1
  112. package/dist/core-capabilities.js +0 -6
  113. package/dist/core-capabilities.js.map +0 -1
  114. package/dist/define-process.js +0 -1078
  115. package/dist/define-process.js.map +0 -1
  116. package/dist/event-bus.js +0 -31
  117. package/dist/event-bus.js.map +0 -1
  118. package/dist/extension-api.js +0 -5
  119. package/dist/extension-api.js.map +0 -1
  120. package/dist/flow.js +0 -1645
  121. package/dist/flow.js.map +0 -1
  122. package/dist/form-contract.js +0 -2
  123. package/dist/form-contract.js.map +0 -1
  124. package/dist/fs-utils.js +0 -23
  125. package/dist/fs-utils.js.map +0 -1
  126. package/dist/graph-fragments.js +0 -57
  127. package/dist/graph-fragments.js.map +0 -1
  128. package/dist/host-capabilities.js +0 -42
  129. package/dist/host-capabilities.js.map +0 -1
  130. package/dist/launcher-contract.js +0 -2
  131. package/dist/launcher-contract.js.map +0 -1
  132. package/dist/leaf-outcomes.js +0 -52
  133. package/dist/leaf-outcomes.js.map +0 -1
  134. package/dist/model-provider.js +0 -171
  135. package/dist/model-provider.js.map +0 -1
  136. package/dist/process-definition-internals.js +0 -25
  137. package/dist/process-definition-internals.js.map +0 -1
  138. package/dist/process-flow-view.js +0 -418
  139. package/dist/process-flow-view.js.map +0 -1
  140. package/dist/process-graph.js +0 -212
  141. package/dist/process-graph.js.map +0 -1
  142. package/dist/process-launcher-builder.js +0 -43
  143. package/dist/process-launcher-builder.js.map +0 -1
  144. package/dist/process-watcher-builder.js +0 -40
  145. package/dist/process-watcher-builder.js.map +0 -1
  146. package/dist/process-watcher-source.js +0 -52
  147. package/dist/process-watcher-source.js.map +0 -1
  148. package/dist/registry-utils.js +0 -18
  149. package/dist/registry-utils.js.map +0 -1
  150. package/dist/repository-git-env.js +0 -26
  151. package/dist/repository-git-env.js.map +0 -1
  152. package/dist/server-events.js +0 -2
  153. package/dist/server-events.js.map +0 -1
  154. package/dist/server-process-builder.js +0 -52
  155. package/dist/server-process-builder.js.map +0 -1
  156. package/dist/state-helpers.js +0 -18
  157. package/dist/state-helpers.js.map +0 -1
  158. package/dist/subprocess-env.js +0 -34
  159. package/dist/subprocess-env.js.map +0 -1
  160. package/dist/tool-renderers.js +0 -63
  161. package/dist/tool-renderers.js.map +0 -1
  162. package/dist/turn-semantics.js +0 -365
  163. package/dist/turn-semantics.js.map +0 -1
  164. package/dist/types.js +0 -23
  165. package/dist/types.js.map +0 -1
  166. package/dist/ui-process-builder.js +0 -30
  167. package/dist/ui-process-builder.js.map +0 -1
  168. package/dist/worker-process-builder.js +0 -22
  169. package/dist/worker-process-builder.js.map +0 -1
package/src/fs-utils.ts CHANGED
@@ -18,11 +18,26 @@ export async function atomicWriteUtf8(filePath: string, content: string): Promis
18
18
  }
19
19
  }
20
20
 
21
- export function isEnoent(error: unknown): boolean {
21
+ // The parent itself is not inside: callers require a strict descendant.
22
+ export function isPathInside(parent: string, child: string): boolean {
23
+ const relative = path.relative(parent, child);
24
+ return (
25
+ relative !== "" &&
26
+ relative !== ".." &&
27
+ !relative.startsWith(`..${path.sep}`) &&
28
+ !path.isAbsolute(relative)
29
+ );
30
+ }
31
+
32
+ export function hasErrorCode(error: unknown, code: string): boolean {
22
33
  return (
23
34
  typeof error === "object" &&
24
35
  error !== null &&
25
36
  "code" in error &&
26
- (error as { code?: unknown }).code === "ENOENT"
37
+ (error as { code?: unknown }).code === code
27
38
  );
28
39
  }
40
+
41
+ export function isEnoent(error: unknown): boolean {
42
+ return hasErrorCode(error, "ENOENT");
43
+ }
package/src/index.ts CHANGED
@@ -31,6 +31,7 @@ export {
31
31
  type DeferredProcessActivationSnapshot,
32
32
  type DeferredProcessActivationSnapshotQuery,
33
33
  type DeferredProcessActivationSnapshotResult,
34
+ type ExternalObservationInput,
34
35
  type ExternalSourceArmingLike,
35
36
  type ExternalSourceFireInput,
36
37
  type ExternalSourceServiceLike,
@@ -44,7 +45,11 @@ export {
44
45
  type LaunchPlanPreparationIssue,
45
46
  type LaunchPlanPreparationIssueCode,
46
47
  type LaunchPlanPreparationResultLike,
48
+ type LaunchRunServiceLike,
47
49
  type ModelProfileOptionSummaryLike,
50
+ type PollingHandleLike,
51
+ type PollingServiceLike,
52
+ type PollResultLike,
48
53
  type PreparedDeferredProcessActivation,
49
54
  type ProcessActionExecutionOrigin,
50
55
  type ProcessActionExecutionSource,
@@ -55,10 +60,6 @@ export {
55
60
  type ProcessEngineLike,
56
61
  type ProcessEngineResultLike,
57
62
  type ProcessEventRepoLike,
58
- type ProcessLaunchConfigExecutionInput,
59
- type ProcessLaunchExecutionResultLike,
60
- type ProcessLaunchExecutorLike,
61
- type ProcessLaunchFailureStageLike,
62
63
  type ProcessLaunchPlanServiceLike,
63
64
  type ProcessModelSelectionPreviewFailureCode,
64
65
  type ProcessModelSelectionPreviewResultLike,
@@ -67,8 +68,11 @@ export {
67
68
  type ProcessQuestionServiceLike,
68
69
  type ProcessRepoLike,
69
70
  type ProcessWatcherServiceLike,
71
+ type ProgrammaticLaunchRequestLike,
72
+ type ProgrammaticLaunchResultLike,
70
73
  type QueuedProcessInputLike,
71
74
  type RegisteredProcessWatcherLike,
75
+ type WatcherLaunchResultLike,
72
76
  type WorkerSupervisorLike,
73
77
  } from "./core-capabilities.js";
74
78
  export {
@@ -87,6 +91,7 @@ export {
87
91
  humanTurn,
88
92
  type LlmModelPurpose,
89
93
  type LlmTurnDefinition,
94
+ type LlmTurnPreparationContext,
90
95
  llmTurn,
91
96
  type OutcomeRouteOptions,
92
97
  type OutcomeRouteSpec,
@@ -112,10 +117,6 @@ export {
112
117
  type ProcessTurnEndSpec,
113
118
  resolveHumanTurnView,
114
119
  routeTurnOutcomes,
115
- type ServerAutomaticTurnDefinition,
116
- type ServerAutomaticTurnRestartBehavior,
117
- type ServerAutomaticTurnRunResult,
118
- serverAutomaticTurn,
119
120
  type TurnDefinition,
120
121
  type TurnDefinitionRecord,
121
122
  } from "./define-process.js";
@@ -126,18 +127,22 @@ export type {
126
127
  ExtensionLifecycleHook,
127
128
  ExtensionProcessDefinition,
128
129
  ExternalActionSource,
130
+ ExternalEventDescription,
129
131
  ExternalSourceEffect,
130
132
  ExternalSourceEffectContext,
131
133
  ExternalSourceInputMode,
132
134
  ExternalSourceResolveContext,
133
135
  FormDefinition,
134
136
  FormFieldDefinition,
137
+ GitHttpsCredentialMaterial,
135
138
  GitSshCredentialMaterial,
136
139
  IntegrationToolDefinition,
137
140
  IntegrationToolExecutionContext,
138
141
  LauncherContext,
139
142
  LauncherModelProfileSummary,
140
143
  LauncherVisibility,
144
+ LaunchPreparationCheck,
145
+ LaunchPreparationContext,
141
146
  LeafOutcomeCaptureContext,
142
147
  LeafOutcomeCaptureResult,
143
148
  LeitwerkExtensionManifest,
@@ -174,6 +179,13 @@ export type {
174
179
  ServerTransitionEffect,
175
180
  ServerTransitionRequest,
176
181
  ServerTransitionRuntime,
182
+ TicketCreationCapability,
183
+ TicketCreationDestinationContext,
184
+ TicketCreationDestinationList,
185
+ TicketCreationDestinationProvider,
186
+ TicketCreationDestinationSnapshot,
187
+ TicketCreationDestinationSummary,
188
+ TicketCreationReceipt,
177
189
  UiLauncherConfigResolution,
178
190
  UiLauncherDefinition,
179
191
  UiLauncherResolutionResult,
@@ -186,7 +198,9 @@ export type {
186
198
  WorkerRunHandle,
187
199
  WorkerTurnHandler,
188
200
  } from "./extension-api.js";
189
- export { findUiLauncherById } from "./extension-api.js";
201
+ export { findUiLauncherById, SafeLaunchPreparationError } from "./extension-api.js";
202
+ export { defineExternalActionSource } from "./external-action-source.js";
203
+ export { createExternalSourcePollReporter } from "./external-source-poll.js";
190
204
  export {
191
205
  AutomaticFlowBuilder,
192
206
  AutomaticOutcomeBuilder,
@@ -204,12 +218,12 @@ export {
204
218
  FlowFragmentBuilder,
205
219
  type FlowHumanTurn,
206
220
  type FlowLlmOutcomeEffectContext,
221
+ type FlowLlmPreparationContext,
207
222
  type FlowLlmTurn,
208
223
  FlowProcessBuilder,
209
224
  type FlowPromptContext,
210
225
  type FlowRepoContext,
211
226
  type FlowRepoLookup,
212
- type FlowServerAutomaticTurn,
213
227
  type FlowTurn,
214
228
  flow,
215
229
  HumanActionBuilder,
@@ -221,9 +235,8 @@ export {
221
235
  type PlanFieldOptions,
222
236
  PlanResultBuilder,
223
237
  PublishedResultBuilder,
224
- ServerAutomaticFlowBuilder,
225
238
  } from "./flow.js";
226
- export { atomicWriteUtf8, isEnoent } from "./fs-utils.js";
239
+ export { atomicWriteUtf8, hasErrorCode, isEnoent, isPathInside } from "./fs-utils.js";
227
240
  export {
228
241
  type AcceptedReviewHandoffActionSpec,
229
242
  acceptedReviewHandoffAction,
@@ -237,6 +250,8 @@ export {
237
250
  createCapabilityAccessor,
238
251
  type ProvidedCapability,
239
252
  } from "./host-capabilities.js";
253
+ export { IntegrationHttpClient, IntegrationHttpError } from "./integration-http.js";
254
+ export { parseJsonData } from "./json-data.js";
240
255
  export type {
241
256
  LauncherCardMetadata,
242
257
  LauncherFieldDefinition,
@@ -343,11 +358,36 @@ export {
343
358
  parseProcessWatcherLaunchModelConfig,
344
359
  } from "./process-watcher-source.js";
345
360
  export {
361
+ type RepositoryProjectBinding,
362
+ resolveRepositoryProjectBinding,
363
+ } from "./project-binding.js";
364
+ export {
365
+ normalizeRepositoryFeedback,
366
+ type RepositoryFeedbackItem,
367
+ repositoryFeedbackBatch,
368
+ } from "./repository-feedback.js";
369
+ export {
370
+ clearRepositoryGitHttpsHelpers,
346
371
  clearRepositoryGitSshWrappers,
347
372
  repositoryGitArgs,
348
373
  repositoryGitSubprocessEnv,
374
+ setRepositoryGitHttpsHelper,
349
375
  setRepositoryGitSshWrapper,
350
376
  } from "./repository-git-env.js";
377
+ export { RepositoryHttpClient } from "./repository-http.js";
378
+ export { repositoryHttpsUrl } from "./repository-https.js";
379
+ export {
380
+ matchesRepository,
381
+ parseRepositoryIssueWatcherConfig,
382
+ presentRepositoryIssueWatcherConfig,
383
+ type RepositoryIssueWatcherConfig,
384
+ } from "./repository-issue-watcher.js";
385
+ export {
386
+ parseRepositoryFeedbackConfig,
387
+ parseRepositoryIssueCancelledConfig,
388
+ parseRepositoryPullRequestConfig,
389
+ } from "./repository-source-config.js";
390
+ export type { RepositoryIssue, RepositoryPullRequest } from "./repository-types.js";
351
391
  export {
352
392
  buildPlanSavedEventPayload,
353
393
  buildReviewCompletedEventPayload,
@@ -379,12 +419,14 @@ export {
379
419
  createEmptyStructuralProcessState,
380
420
  parseStructuralProcessState,
381
421
  type StructuralProcessState,
422
+ structuralStateCodec,
382
423
  } from "./state-helpers.js";
383
424
  export {
384
425
  type SubprocessEnvInput,
385
426
  sanitizeWorkerSubprocessEnv,
386
427
  WORKER_SUBPROCESS_SENSITIVE_ENV_KEYS,
387
428
  } from "./subprocess-env.js";
429
+ export { numberArg, objectArg, projectParameters, stringArg } from "./tool-arguments.js";
388
430
  export type {
389
431
  ToolCallRendererDefinition,
390
432
  ToolCallRendererFieldDefinition,
@@ -409,7 +451,6 @@ export {
409
451
  isExternalTurnDefinition,
410
452
  isHumanTurnDefinition,
411
453
  isLlmTurnDefinition,
412
- isServerAutomaticTurnDefinition,
413
454
  resolveLlmTurnRestorePrimaryLeafAfterTurn,
414
455
  resolveLlmTurnStartSelection,
415
456
  validateAutomaticTurnDefinition,
@@ -0,0 +1,58 @@
1
+ /** An HTTP failure without provider response bodies or credentials. */
2
+ export class IntegrationHttpError extends Error {
3
+ constructor(
4
+ readonly status: number,
5
+ message: string,
6
+ ) {
7
+ super(message);
8
+ }
9
+ }
10
+
11
+ /** Shared transport; extensions own endpoint paths, credentials, and response types. */
12
+ export class IntegrationHttpClient {
13
+ constructor(
14
+ private readonly provider: string,
15
+ private readonly baseUrl: string,
16
+ private readonly headers: Record<string, string>,
17
+ private readonly pagination = { key: "per_page", size: 100 },
18
+ ) {}
19
+
20
+ protected async response(path: string, init: RequestInit = {}): Promise<Response> {
21
+ const response = await fetch(`${this.baseUrl}${path}`, {
22
+ ...init,
23
+ headers: {
24
+ ...this.headers,
25
+ ...(init.body ? { "Content-Type": "application/json" } : {}),
26
+ ...init.headers,
27
+ },
28
+ });
29
+ if (!response.ok)
30
+ throw new IntegrationHttpError(
31
+ response.status,
32
+ `${this.provider} ${init.method ?? "GET"} ${path} failed with ${response.status}`,
33
+ );
34
+ return response;
35
+ }
36
+
37
+ protected async request<T>(path: string, init: RequestInit = {}): Promise<T> {
38
+ const response = await this.response(path, init);
39
+ return response.status === 204 ? (undefined as T) : response.json();
40
+ }
41
+
42
+ protected writeJson<T>(path: string, method: string, body: unknown, signal?: AbortSignal) {
43
+ return this.request<T>(path, { method, body: JSON.stringify(body), signal });
44
+ }
45
+
46
+ protected async pages<T>(path: string, signal?: AbortSignal): Promise<T[]> {
47
+ const items: T[] = [];
48
+ const { key, size } = this.pagination;
49
+ for (let page = 1; ; page++) {
50
+ const separator = path.includes("?") ? "&" : "?";
51
+ const batch = await this.request<T[]>(`${path}${separator}${key}=${size}&page=${page}`, {
52
+ signal,
53
+ });
54
+ items.push(...batch);
55
+ if (batch.length < size) return items;
56
+ }
57
+ }
58
+ }
@@ -0,0 +1,25 @@
1
+ /** Validate and detach JSON data without silently dropping unsupported values. */
2
+ export function parseJsonData(
3
+ value: unknown,
4
+ message = "Value must be JSON-serializable",
5
+ ): unknown {
6
+ const ancestors = new Set<object>();
7
+ function parse(value: unknown): unknown {
8
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
9
+ if (typeof value === "number" && Number.isFinite(value)) return value;
10
+ if (!value || typeof value !== "object" || ancestors.has(value)) throw new Error(message);
11
+ ancestors.add(value);
12
+ try {
13
+ if (Array.isArray(value)) return Array.from(value, parse);
14
+ if (
15
+ ![Object.prototype, null].includes(Object.getPrototypeOf(value)) ||
16
+ Object.getOwnPropertySymbols(value).length
17
+ )
18
+ throw new Error(message);
19
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, parse(item)]));
20
+ } finally {
21
+ ancestors.delete(value);
22
+ }
23
+ }
24
+ return parse(value);
25
+ }
@@ -1,15 +1,7 @@
1
+ import { copiedUnknownRecordSchema as unknownRecordSchema } from "@leitwerk-dev/domain";
1
2
  import * as v from "valibot";
2
3
  import type { LeafOutcomeCaptureResult, ProcessLeafOutcomeDefinition } from "./extension-api.js";
3
4
 
4
- const unknownRecordSchema = v.pipe(
5
- v.unknown(),
6
- v.check(
7
- (value) => typeof value === "object" && value !== null && !Array.isArray(value),
8
- "Expected object",
9
- ),
10
- v.record(v.string(), v.unknown()),
11
- );
12
-
13
5
  function isNonEmptyString(value: unknown): value is string {
14
6
  return typeof value === "string" && value.trim() !== "";
15
7
  }
@@ -76,17 +76,11 @@ export function defineProviderOptions<TConfig = unknown>(
76
76
  if (fieldId.trim() === "") {
77
77
  throw new Error("Provider option field ids must not be empty");
78
78
  }
79
- if (
80
- field.minLength !== undefined &&
81
- (!Number.isInteger(field.minLength) || field.minLength < 0)
82
- ) {
83
- throw new Error(`Provider option '${fieldId}' minLength must be a non-negative integer`);
84
- }
85
- if (
86
- field.maxLength !== undefined &&
87
- (!Number.isInteger(field.maxLength) || field.maxLength < 0)
88
- ) {
89
- throw new Error(`Provider option '${fieldId}' maxLength must be a non-negative integer`);
79
+ for (const bound of ["minLength", "maxLength"] as const) {
80
+ const value = field[bound];
81
+ if (value !== undefined && (!Number.isInteger(value) || value < 0)) {
82
+ throw new Error(`Provider option '${fieldId}' ${bound} must be a non-negative integer`);
83
+ }
90
84
  }
91
85
  if (
92
86
  field.minLength !== undefined &&
@@ -446,16 +440,9 @@ export function credentialBasedModelStatuses(
446
440
  credentialStatus: ProviderCredentialStatus,
447
441
  unavailableReason: string,
448
442
  ): readonly ProviderModelStatus[] {
449
- const seen = new Set<string>();
450
- const statuses: ProviderModelStatus[] = [];
451
- for (const configured of configuredModels) {
452
- if (seen.has(configured.modelId)) continue;
453
- seen.add(configured.modelId);
454
- statuses.push({
455
- modelId: configured.modelId,
456
- availability: credentialStatus.available ? "available" : "unavailable",
457
- ...(credentialStatus.available ? {} : { safeReason: unavailableReason }),
458
- });
459
- }
460
- return statuses;
443
+ return [...new Set(configuredModels.map((configured) => configured.modelId))].map((modelId) => ({
444
+ modelId,
445
+ availability: credentialStatus.available ? "available" : "unavailable",
446
+ ...(credentialStatus.available ? {} : { safeReason: unavailableReason }),
447
+ }));
461
448
  }
package/src/pi-config.ts CHANGED
@@ -233,12 +233,7 @@ export function resolveProcessPiConfig(input: {
233
233
  };
234
234
  }
235
235
 
236
- export function resolveTurnActiveToolNames(input: {
237
- turnId: string;
238
- turnDef: LlmTurnDefinition<string, unknown, unknown>;
239
- }): string[] {
240
- return resolveTurnAvailableToolNames(input);
241
- }
236
+ export { resolveTurnAvailableToolNames as resolveTurnActiveToolNames };
242
237
 
243
238
  // Mirror Pi's PI_CODING_AGENT_DIR expansion semantics from
244
239
  // pi-mono/packages/coding-agent/src/config.ts.
@@ -7,17 +7,10 @@ import {
7
7
  type ProcessTurnTerminalLifecycleStatus,
8
8
  type ProcessTurnTransition,
9
9
  type TurnId,
10
+ trimToNull,
10
11
  } from "@leitwerk-dev/domain";
11
12
  import type { ProcessGraphTurnView, ProcessGraphView } from "./process-graph.js";
12
13
 
13
- function trimToNull(value: string | undefined | null): string | null {
14
- if (typeof value !== "string") {
15
- return null;
16
- }
17
- const trimmed = value.trim();
18
- return trimmed === "" ? null : trimmed;
19
- }
20
-
21
14
  /**
22
15
  * Human/operator turns are routing decisions: they pick which path the process
23
16
  * takes but perform no work themselves. They are collapsed out of the flow graph
@@ -52,17 +45,13 @@ function computeRoutingAnchors(
52
45
  graph: ProcessGraphView,
53
46
  routingIds: ReadonlySet<TurnId>,
54
47
  ): Map<TurnId, TurnId> {
55
- const declarationIndex = new Map<TurnId, number>();
56
- [...graph.turns.keys()].forEach((turnId, index) => {
57
- declarationIndex.set(turnId, index);
58
- });
59
-
60
- const happyIndex = new Map<TurnId, number>();
61
- (graph.happyPath ?? []).forEach((turnId, index) => {
62
- if (!happyIndex.has(turnId)) {
63
- happyIndex.set(turnId, index);
64
- }
65
- });
48
+ // Happy-path turns come first, then the remaining turns in declaration order.
49
+ const preferenceIndex = new Map(
50
+ [...new Set([...(graph.happyPath ?? []), ...graph.turns.keys()])].map((turnId, index) => [
51
+ turnId,
52
+ index,
53
+ ]),
54
+ );
66
55
 
67
56
  const workPredecessors = new Map<TurnId, TurnId[]>();
68
57
  const routingPredecessors = new Map<TurnId, TurnId[]>();
@@ -84,22 +73,14 @@ function computeRoutingAnchors(
84
73
  }
85
74
  }
86
75
 
87
- const preferenceKey = (turnId: TurnId): [number, number] => [
88
- happyIndex.get(turnId) ?? Number.POSITIVE_INFINITY,
89
- declarationIndex.get(turnId) ?? Number.POSITIVE_INFINITY,
90
- ];
91
76
  const pickPreferred = (candidates: readonly TurnId[]): TurnId | undefined => {
92
77
  let best: TurnId | undefined;
93
- let bestKey: [number, number] | undefined;
78
+ let bestIndex = Number.POSITIVE_INFINITY;
94
79
  for (const candidate of candidates) {
95
- const key = preferenceKey(candidate);
96
- if (
97
- bestKey === undefined ||
98
- key[0] < bestKey[0] ||
99
- (key[0] === bestKey[0] && key[1] < bestKey[1])
100
- ) {
80
+ const index = preferenceIndex.get(candidate) ?? Number.POSITIVE_INFINITY;
81
+ if (best === undefined || index < bestIndex) {
101
82
  best = candidate;
102
- bestKey = key;
83
+ bestIndex = index;
103
84
  }
104
85
  }
105
86
  return best;
@@ -168,18 +149,16 @@ function redirectTransition(
168
149
  }
169
150
 
170
151
  function dedupeTransitions(transitions: readonly ProcessTurnTransition[]): ProcessTurnTransition[] {
171
- const seen = new Set<string>();
172
- const result: ProcessTurnTransition[] = [];
152
+ const result = new Map<string, ProcessTurnTransition>();
173
153
  for (const transition of transitions) {
174
154
  const label = trimToNull(transition.outcome) ?? trimToNull(transition.trigger);
175
155
  const key = `${transition.nextTurnId ?? ""}|${transition.lifecycleStatus ?? ""}|${label ?? ""}`;
176
- if (seen.has(key)) {
156
+ if (result.has(key)) {
177
157
  continue;
178
158
  }
179
- seen.add(key);
180
- result.push(transition);
159
+ result.set(key, transition);
181
160
  }
182
- return result;
161
+ return [...result.values()];
183
162
  }
184
163
 
185
164
  /**
@@ -197,10 +176,7 @@ export function collapseRoutingTurns(graph: ProcessGraphView): ProcessGraphView
197
176
  routingIds.add(turnId);
198
177
  }
199
178
  }
200
- if (routingIds.size === 0) {
201
- return graph;
202
- }
203
- if (routingIds.size === graph.turns.size) {
179
+ if (routingIds.size === 0 || routingIds.size === graph.turns.size) {
204
180
  return graph;
205
181
  }
206
182
 
@@ -264,29 +240,18 @@ export function collapseRoutingTurns(graph: ProcessGraphView): ProcessGraphView
264
240
  * completing path exists.
265
241
  */
266
242
  function deriveSpine(graph: ProcessGraphView, entry: TurnId): TurnId[] {
267
- const turnsWithCompletedTerminal = new Set<TurnId>();
268
- for (const [turnId, turn] of graph.turns) {
269
- if (turn.transitions.some((transition) => transition.lifecycleStatus === "completed")) {
270
- turnsWithCompletedTerminal.add(turnId);
271
- }
272
- }
273
- if (turnsWithCompletedTerminal.size === 0) {
274
- return [entry];
275
- }
276
-
277
243
  const predecessor = new Map<TurnId, TurnId | null>([[entry, null]]);
278
244
  const queue: TurnId[] = [entry];
279
245
  let goal: TurnId | null = null;
280
- while (queue.length > 0) {
281
- const current = queue.shift() as TurnId;
282
- if (turnsWithCompletedTerminal.has(current)) {
283
- goal = current;
284
- break;
285
- }
246
+ for (const current of queue) {
286
247
  const turn = graph.turns.get(current);
287
248
  if (!turn) {
288
249
  continue;
289
250
  }
251
+ if (turn.transitions.some((transition) => transition.lifecycleStatus === "completed")) {
252
+ goal = current;
253
+ break;
254
+ }
290
255
  for (const transition of turn.transitions) {
291
256
  const next = transition.nextTurnId;
292
257
  if (next === undefined || predecessor.has(next) || !graph.turns.has(next)) {
@@ -360,24 +325,6 @@ function transitionLabel(transition: { outcome?: string; trigger?: string }): st
360
325
  return raw === null ? null : humanizeProcessLabel(raw);
361
326
  }
362
327
 
363
- function buildNode(input: {
364
- turnId: TurnId;
365
- turn: ProcessGraphTurnView;
366
- spineIndex: number | null;
367
- anchorTurnId: TurnId | null;
368
- isEntry: boolean;
369
- }): ProcessFlowNode {
370
- return {
371
- turnId: input.turnId,
372
- description: trimToNull(input.turn.description) ?? input.turnId,
373
- turnType: input.turn.turnType,
374
- role: input.spineIndex === null ? "branch" : "spine",
375
- spineIndex: input.spineIndex,
376
- anchorTurnId: input.spineIndex === null ? input.anchorTurnId : null,
377
- isEntry: input.isEntry,
378
- };
379
- }
380
-
381
328
  /**
382
329
  * Projects a process graph into a spine-first flow view for operator-facing
383
330
  * diagrams. The spine is the declared happy path (or a derived best-effort path
@@ -411,15 +358,15 @@ export function buildProcessFlowView(rawGraph: ProcessGraphView): ProcessFlowVie
411
358
  const nodes: ProcessFlowNode[] = [];
412
359
  for (const [turnId, turn] of graph.turns) {
413
360
  const spineIndex = spineIndexByTurn.get(turnId) ?? null;
414
- nodes.push(
415
- buildNode({
416
- turnId,
417
- turn,
418
- spineIndex,
419
- anchorTurnId: anchorByTurn.get(turnId) ?? null,
420
- isEntry: entrySet.has(turnId),
421
- }),
422
- );
361
+ nodes.push({
362
+ turnId,
363
+ description: trimToNull(turn.description) ?? turnId,
364
+ turnType: turn.turnType,
365
+ role: spineIndex === null ? "branch" : "spine",
366
+ spineIndex,
367
+ anchorTurnId: spineIndex === null ? (anchorByTurn.get(turnId) ?? null) : null,
368
+ isEntry: entrySet.has(turnId),
369
+ });
423
370
  }
424
371
 
425
372
  const edges: ProcessFlowEdge[] = [];
@@ -439,12 +386,9 @@ export function buildProcessFlowView(rawGraph: ProcessGraphView): ProcessFlowVie
439
386
  continue;
440
387
  }
441
388
  const next = transition.nextTurnId;
442
- if (next === undefined) {
443
- continue;
444
- }
445
389
  // Skip self-loops: an edge that leaves and re-enters the same box adds
446
390
  // clutter without conveying additional flow.
447
- if (next === turnId) {
391
+ if (next === undefined || next === turnId) {
448
392
  continue;
449
393
  }
450
394
  const fromIndex = spineIndexByTurn.get(turnId);
@@ -36,68 +36,42 @@ export interface ProcessGraphView {
36
36
  turns: ReadonlyMap<TurnId, ProcessGraphTurnView>;
37
37
  }
38
38
 
39
- function toTurnType(definition: TurnDefinition<unknown, unknown>): ProcessTurnType {
40
- switch (definition.kind) {
41
- case "llm":
42
- case "human":
43
- case "external":
44
- case "automatic":
45
- case "server_automatic":
46
- return definition.kind;
47
- }
48
- }
49
-
50
- function humanPublishedProducts(definition: TurnDefinition<unknown, unknown>): string[] {
51
- if (definition.kind !== "human") {
52
- return [];
53
- }
54
- const products: string[] = [];
55
- for (const action of Object.values(definition.actions)) {
56
- for (const field of action.form?.fields ?? []) {
57
- if (!field.publish) {
58
- continue;
39
+ function turnPublishedProducts(definition: TurnDefinition<unknown, unknown>): string[] {
40
+ const products = new Set<string>();
41
+ if (definition.kind === "human") {
42
+ for (const action of Object.values(definition.actions)) {
43
+ for (const field of action.form?.fields ?? []) {
44
+ if (field.publish) {
45
+ products.add(
46
+ typeof field.publish === "object" && field.publish.product
47
+ ? field.publish.product
48
+ : field.id,
49
+ );
50
+ }
59
51
  }
60
- products.push(
61
- typeof field.publish === "object" && field.publish.product
62
- ? field.publish.product
63
- : field.id,
64
- );
65
52
  }
66
- }
67
- for (const externalAction of Object.values(definition.externalActions ?? {})) {
68
- if (externalAction.publishInput) {
69
- products.push(externalAction.publishInput.productName);
53
+ for (const action of Object.values(definition.externalActions ?? {})) {
54
+ if (action.publishInput) {
55
+ products.add(action.publishInput.productName);
56
+ }
57
+ }
58
+ } else if (definition.kind === "llm" || definition.kind === "automatic") {
59
+ for (const outcome of Object.values(definition.outcomes ?? {})) {
60
+ if (typeof outcome?.publishedProduct === "string") {
61
+ products.add(outcome.publishedProduct);
62
+ }
70
63
  }
71
64
  }
72
- return [...new Set(products)];
73
- }
74
-
75
- function outcomePublishedProducts(definition: TurnDefinition<unknown, unknown>): string[] {
76
- if (
77
- definition.kind !== "llm" &&
78
- definition.kind !== "automatic" &&
79
- definition.kind !== "server_automatic"
80
- ) {
81
- return [];
82
- }
83
- return [
84
- ...new Set(
85
- Object.values(definition.outcomes ?? {})
86
- .map((outcome) => outcome?.publishedProduct)
87
- .filter((productName): productName is string => typeof productName === "string"),
88
- ),
89
- ];
65
+ return [...products];
90
66
  }
91
67
 
92
68
  function toTurnView(
93
69
  binding: ProcessTurnBinding<TurnDefinition<unknown, unknown>>,
94
70
  ): ProcessGraphTurnView {
95
71
  const definition = binding.definition;
96
- const publishedProducts = [
97
- ...new Set([...humanPublishedProducts(definition), ...outcomePublishedProducts(definition)]),
98
- ];
72
+ const publishedProducts = turnPublishedProducts(definition);
99
73
  return {
100
- turnType: toTurnType(definition),
74
+ turnType: definition.kind,
101
75
  description: definition.description,
102
76
  transitions: getProcessTurnTransitions(binding),
103
77
  ...(definition.kind === "human" && definition.reviewProduct