@leitwerk-dev/process-sdk 0.3.1 → 0.4.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 (63) hide show
  1. package/dist/{chunk-GVBLXKSR.js → chunk-HT2AXXLH.js} +2 -1
  2. package/dist/chunk-HT2AXXLH.js.map +1 -0
  3. package/dist/core-capabilities.d.ts +57 -1
  4. package/dist/core-capabilities.d.ts.map +1 -1
  5. package/dist/define-process.d.ts +40 -26
  6. package/dist/define-process.d.ts.map +1 -1
  7. package/dist/{extension-api-DM-AvWOW.d.ts → extension-api-Ljc4UTZ0.d.ts} +258 -64
  8. package/dist/extension-api.d.ts +52 -0
  9. package/dist/extension-api.d.ts.map +1 -1
  10. package/dist/external-source-poll.d.ts +1 -1
  11. package/dist/external-source-poll.d.ts.map +1 -1
  12. package/dist/file-external-source.d.ts +32 -0
  13. package/dist/file-external-source.d.ts.map +1 -0
  14. package/dist/flow-mapped.typecheck.d.ts +2 -0
  15. package/dist/flow-mapped.typecheck.d.ts.map +1 -0
  16. package/dist/flow.d.ts +188 -177
  17. package/dist/flow.d.ts.map +1 -1
  18. package/dist/index.d.ts +11 -4
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +4424 -4327
  21. package/dist/index.js.map +1 -1
  22. package/dist/mapped-turn.d.ts +6 -22
  23. package/dist/mapped-turn.d.ts.map +1 -1
  24. package/dist/outcome-contract.d.ts +19 -0
  25. package/dist/outcome-contract.d.ts.map +1 -0
  26. package/dist/outcome-schema.d.ts +23 -0
  27. package/dist/outcome-schema.d.ts.map +1 -0
  28. package/dist/pi-config-public.js +1 -1
  29. package/dist/pi-config.js +1 -1
  30. package/dist/process-flow-view.d.ts +3 -14
  31. package/dist/process-flow-view.d.ts.map +1 -1
  32. package/dist/process-graph.d.ts +10 -4
  33. package/dist/process-graph.d.ts.map +1 -1
  34. package/dist/scoped-settings.d.ts +87 -0
  35. package/dist/scoped-settings.d.ts.map +1 -0
  36. package/dist/ticket-creation.d.ts +24 -0
  37. package/dist/ticket-creation.d.ts.map +1 -0
  38. package/dist/turn-semantics.d.ts +3 -3
  39. package/dist/turn-semantics.d.ts.map +1 -1
  40. package/dist/turn-wait.d.ts +53 -0
  41. package/dist/turn-wait.d.ts.map +1 -0
  42. package/dist/types.d.ts +31 -18
  43. package/dist/types.d.ts.map +1 -1
  44. package/package.json +6 -6
  45. package/src/core-capabilities.ts +76 -1
  46. package/src/define-process.ts +420 -596
  47. package/src/extension-api.ts +60 -0
  48. package/src/external-source-poll.ts +6 -24
  49. package/src/file-external-source.ts +135 -0
  50. package/src/flow-mapped.typecheck.ts +136 -0
  51. package/src/flow.ts +744 -805
  52. package/src/index.ts +48 -1
  53. package/src/mapped-turn.ts +74 -23
  54. package/src/outcome-contract.ts +126 -0
  55. package/src/outcome-schema.ts +314 -0
  56. package/src/process-flow-view.ts +84 -346
  57. package/src/process-graph.ts +95 -45
  58. package/src/scoped-settings.ts +113 -0
  59. package/src/ticket-creation.ts +113 -0
  60. package/src/turn-semantics.ts +99 -188
  61. package/src/turn-wait.ts +76 -0
  62. package/src/types.ts +30 -16
  63. package/dist/chunk-GVBLXKSR.js.map +0 -1
@@ -0,0 +1,113 @@
1
+ import type { ResolvedSetting, SettingsContext, SettingsSubject } from "@leitwerk-dev/domain";
2
+ import type {
3
+ SettingChoice,
4
+ SettingMetadata,
5
+ SettingsScopeOverview,
6
+ } from "@leitwerk-dev/protocol/http-contracts";
7
+ import { createCapabilityToken } from "./capabilities.js";
8
+
9
+ export type { NamedSelection, SettingChoice } from "@leitwerk-dev/protocol/http-contracts";
10
+
11
+ /** Non-secret, JSON-compatible setting owned and validated by an extension. @public */
12
+ export interface SettingDefinition<T = unknown> extends SettingMetadata {
13
+ /** Must reject invalid values without coercing missing overrides into empty values. @public */
14
+ schema: {
15
+ /** @public */
16
+ parse(value: unknown): T;
17
+ };
18
+ /** @public */
19
+ defaultValue: T;
20
+ /** Label retained selections synchronously, without remote discovery. @public */
21
+ choiceLabel?(value: string): string;
22
+ /** Dynamic non-secret choices for generic forms. @public */
23
+ choices?(
24
+ context: SettingsContext,
25
+ request?: {
26
+ /** Search text supplied by the operator. @public */
27
+ search?: string;
28
+ /** Saved selections that must remain discoverable while searching. @public */
29
+ values?: readonly string[];
30
+ },
31
+ ): readonly SettingChoice[] | Promise<readonly SettingChoice[]>;
32
+ }
33
+
34
+ /** @public */
35
+ export interface SettingsScopeDefinition {
36
+ /** Namespaced; instance and repository are provided by core. @public */
37
+ id: string;
38
+ /** @public */
39
+ label: string;
40
+ /** Optional display names and label grouping for the generic scope overview. @public */
41
+ overview?: SettingsScopeOverview;
42
+ }
43
+
44
+ /** Trusted server-side discovery input. @public */
45
+ export interface SettingsSubjectInput {
46
+ /** @public */
47
+ scopeType: string;
48
+ /** Stable identity, independent of the display name. @public */
49
+ identity: string;
50
+ /** @public */
51
+ label: string;
52
+ /** @public */
53
+ context?: SettingsContext;
54
+ /** Normalized locators known by the provider to identify this repository. @public */
55
+ aliases?: readonly string[];
56
+ }
57
+
58
+ /** Extension-owned purpose; separate from the internal title-generation model purpose. @public */
59
+ export interface ExecutionPurposeDefinition {
60
+ /** @public */
61
+ id: string;
62
+ /** @public */
63
+ label: string;
64
+ /** A nullable model-profile setting. Null delegates to YAML/catalog defaults. @public */
65
+ modelSettingKey?: string;
66
+ /** Only these non-secret values are captured and sent to the worker. @public */
67
+ settingKeys?: readonly string[];
68
+ }
69
+
70
+ /** @public */
71
+ export interface ScopedSettingsDeclaration {
72
+ /** @public */
73
+ scopes?: readonly SettingsScopeDefinition[];
74
+ /** @public */
75
+ settings: readonly SettingDefinition[];
76
+ /** @public */
77
+ purposes?: readonly ExecutionPurposeDefinition[];
78
+ }
79
+
80
+ /** Server-only capability. Workers receive immutable start snapshots. @public */
81
+ export interface ScopedSettingsResolver {
82
+ /** @public */
83
+ resolve<T>(definition: SettingDefinition<T>, context: SettingsContext): ResolvedSetting<T>;
84
+ /** Read a retained subject by stable identity without discovery or remote requests. @public */
85
+ findSubject(scopeType: string, identity: string): SettingsSubject | null;
86
+ /** Read a retained subject by ID, including retained redirects. @public */
87
+ getSubject(id: string): SettingsSubject | null;
88
+ /** Initialize a field once. Existing overrides and explicit resets are preserved. @public */
89
+ seedOverride<T>(subjectId: string, definition: SettingDefinition<T>, value: T): boolean;
90
+ /** Retains stable subject identities and known aliases across rediscovery. @public */
91
+ discover(input: SettingsSubjectInput): SettingsSubject;
92
+ /** Called only by explicit discovery, never during step preparation. @public */
93
+ registerDiscovery(
94
+ scopeType: string,
95
+ discover: () => Promise<readonly SettingsSubjectInput[]>,
96
+ options?: {
97
+ /** Limit navigation without deleting retained subjects or overrides. @public */
98
+ includesSubject?: (
99
+ subject: SettingsSubject,
100
+ context: Readonly<Record<string, SettingsSubject>>,
101
+ ) => boolean;
102
+ },
103
+ ): void;
104
+ }
105
+
106
+ /** @public */
107
+ export const scopedSettingsCapability =
108
+ createCapabilityToken<ScopedSettingsResolver>("core:scopedSettings");
109
+
110
+ /** Provider origins and stable IDs define identity; clone URLs are aliases. @public */
111
+ export function repositorySettingsIdentity(origin: string, repositoryId: string | number): string {
112
+ return `provider:${JSON.stringify([new URL(origin).origin, String(repositoryId)])}`;
113
+ }
@@ -0,0 +1,113 @@
1
+ import { asUnknownRecord } from "@leitwerk-dev/domain";
2
+ import type {
3
+ IntegrationToolDefinition,
4
+ TicketCreationDestinationList,
5
+ TicketCreationDestinationProvider,
6
+ TicketCreationDestinationSummary,
7
+ } from "./extension-api.js";
8
+
9
+ /** @internal */
10
+ export function markdownTicketCreationDefinition(
11
+ displayName: string,
12
+ destinations: TicketCreationDestinationProvider,
13
+ descriptionKey = "body",
14
+ labelDescription = "Optional existing label names",
15
+ ): Pick<IntegrationToolDefinition, "parameters" | "capability"> {
16
+ return {
17
+ parameters: {
18
+ type: "object",
19
+ properties: {
20
+ title: { type: "string", description: "Concise issue title" },
21
+ [descriptionKey]: { type: "string", description: "Complete Markdown issue description" },
22
+ labels: { type: "array", items: { type: "string" }, description: labelDescription },
23
+ },
24
+ required: ["title", descriptionKey],
25
+ },
26
+ capability: {
27
+ kind: "ticket_creation",
28
+ displayName,
29
+ processId: "ticket_creation_process",
30
+ startTurnId: "create_ticket",
31
+ titlePath: "/title",
32
+ descriptionPath: `/${descriptionKey}`,
33
+ descriptionFormat: "markdown",
34
+ destinations,
35
+ },
36
+ };
37
+ }
38
+
39
+ /** @internal */
40
+ export async function listTicketDestinations(
41
+ provider: string,
42
+ profiles: readonly string[],
43
+ list: (profile: string) => Promise<readonly TicketCreationDestinationSummary[]>,
44
+ ): Promise<TicketCreationDestinationList> {
45
+ const results = await Promise.all(
46
+ profiles.map(async (profile) => {
47
+ try {
48
+ return { destinations: await list(profile), warnings: [] };
49
+ } catch {
50
+ return {
51
+ destinations: [],
52
+ warnings: [`${provider} profile '${profile}' is currently unavailable.`],
53
+ };
54
+ }
55
+ }),
56
+ );
57
+ return {
58
+ destinations: results.flatMap((result) => result.destinations),
59
+ warnings: results.flatMap((result) => result.warnings),
60
+ };
61
+ }
62
+
63
+ /** @internal */
64
+ export interface TicketCreationConfig {
65
+ /** @internal */
66
+ enabled: boolean;
67
+ /** @internal */
68
+ defaultLabels: string[];
69
+ }
70
+
71
+ /** @internal */
72
+ export function ticketLabelNames(value: unknown, label = "labels"): string[] {
73
+ if (value === undefined) return [];
74
+ if (!Array.isArray(value) || value.some((name) => typeof name !== "string" || !name.trim()))
75
+ throw new Error(`${label} must be an array of nonempty label names`);
76
+ return [...new Set(value.map((name: string) => name.trim()))];
77
+ }
78
+
79
+ /** @internal */
80
+ export function parseTicketCreationConfig(value: unknown, provider: string): TicketCreationConfig {
81
+ const raw = asUnknownRecord(value)?.ticket_creation;
82
+ const config = raw === undefined ? {} : asUnknownRecord(raw);
83
+ if (!config || (config.enabled !== undefined && typeof config.enabled !== "boolean"))
84
+ throw new Error(`${provider} ticket_creation.enabled must be a boolean`);
85
+ return {
86
+ enabled: config.enabled === true,
87
+ defaultLabels: ticketLabelNames(
88
+ config.default_labels === undefined ? ["created-by-leitwerk"] : config.default_labels,
89
+ `${provider} ticket_creation.default_labels`,
90
+ ),
91
+ };
92
+ }
93
+
94
+ /** @internal */
95
+ export function ticketDestinationId(profile: string, resourceId: string | number): string {
96
+ return `${encodeURIComponent(profile)}.${resourceId}`;
97
+ }
98
+
99
+ /** @internal */
100
+ export function parseTicketDestinationId(value: string): {
101
+ /** @internal */ profile: string;
102
+ /** @internal */ resourceId: string;
103
+ } {
104
+ const separator = value.lastIndexOf(".");
105
+ try {
106
+ const profile = decodeURIComponent(value.slice(0, separator));
107
+ const resourceId = value.slice(separator + 1);
108
+ if (separator <= 0 || !profile.trim() || !/^[1-9]\d*$/.test(resourceId)) throw new Error();
109
+ return { profile, resourceId };
110
+ } catch {
111
+ throw new Error("Unknown ticket destination");
112
+ }
113
+ }
@@ -11,11 +11,12 @@ import type {
11
11
  ProcessToolOutcomeSpec,
12
12
  TurnDefinition,
13
13
  } from "./define-process.js";
14
- import { llmTurn, resolveHumanTurnView } from "./define-process.js";
14
+ import { llmTurn } from "./define-process.js";
15
+ import { validateMappedTurn } from "./mapped-turn.js";
16
+ import { compileOutcomeParameters } from "./outcome-schema.js";
15
17
  import { validatePiBuiltInToolArray } from "./pi-config.js";
16
18
  import { REQUIRED_MARKDOWN_RESULT_TURN_RESULT } from "./tool-renderers.js";
17
19
  import {
18
- type OutcomeToolParameterSpec,
19
20
  type ProcessActionPreviewDefinition,
20
21
  type ProcessActionSchedulingDefinition,
21
22
  RESERVED_INTEGRATION_TOOL_NAMES,
@@ -130,16 +131,6 @@ function validateOutcomeTurnResultContract<TParams = unknown, TState = unknown>(
130
131
  return errors;
131
132
  }
132
133
 
133
- function isValidOutcomeToolArrayItemType(type: unknown): boolean {
134
- return (
135
- type === "string" ||
136
- type === "number" ||
137
- type === "boolean" ||
138
- type === "object" ||
139
- type === "array"
140
- );
141
- }
142
-
143
134
  function validateOutcomeToolParameters<TParams = unknown, TState = unknown>(
144
135
  turnKindLabel: string,
145
136
  turnId: string,
@@ -149,48 +140,50 @@ function validateOutcomeToolParameters<TParams = unknown, TState = unknown>(
149
140
  for (const [outcome, outcomeSpec] of Object.entries(outcomes ?? {}) as Array<
150
141
  [string, ProcessToolOutcomeSpec<TParams, TState>]
151
142
  >) {
143
+ const outcomeContext = `${turnKindLabel} turn '${turnId}' outcome '${outcome}'`;
152
144
  if (outcomeSpec.publishedProduct) {
153
145
  errors.push(...validateProcessProductName(outcomeSpec.publishedProduct));
154
146
  const parameterName = outcomeSpec.turnResultMarkdownParameter?.trim() ?? "";
155
147
  if (!parameterName) {
156
148
  errors.push(
157
- `${turnKindLabel} turn '${turnId}' outcome '${outcome}' publishes product '${outcomeSpec.publishedProduct}' but does not declare a turn-result markdown parameter`,
149
+ `${outcomeContext} publishes product '${outcomeSpec.publishedProduct}' but does not declare a turn-result markdown parameter`,
158
150
  );
159
151
  } else if (!Object.hasOwn(outcomeSpec.parameters, parameterName)) {
160
152
  errors.push(
161
- `${turnKindLabel} turn '${turnId}' outcome '${outcome}' publishes product '${outcomeSpec.publishedProduct}' from missing parameter '${parameterName}'`,
153
+ `${outcomeContext} publishes product '${outcomeSpec.publishedProduct}' from missing parameter '${parameterName}'`,
162
154
  );
163
155
  }
164
156
  }
165
- for (const [paramName, paramSpec] of Object.entries(outcomeSpec.parameters) as Array<
166
- [string, OutcomeToolParameterSpec]
167
- >) {
168
- if (paramSpec.minItems !== undefined && paramSpec.type !== "array") {
169
- errors.push(
170
- `${turnKindLabel} turn '${turnId}' outcome '${outcome}' parameter '${paramName}' uses minItems but is not an array`,
171
- );
172
- }
173
- if (paramSpec.minimum !== undefined && paramSpec.type !== "number") {
174
- errors.push(
175
- `${turnKindLabel} turn '${turnId}' outcome '${outcome}' parameter '${paramName}' uses minimum but is not a number`,
176
- );
177
- }
178
- if (paramSpec.items !== undefined && paramSpec.type !== "array") {
179
- errors.push(
180
- `${turnKindLabel} turn '${turnId}' outcome '${outcome}' parameter '${paramName}' declares array items but is not an array`,
181
- );
157
+ for (const [paramName, paramSpec] of Object.entries(outcomeSpec.parameters)) {
158
+ const context = `${outcomeContext} parameter '${paramName}'`;
159
+ const before = errors.length;
160
+ for (const [property, type, message] of [
161
+ ["minItems", "array", "uses minItems but is not an array"],
162
+ ["minimum", "number", "uses minimum but is not a number"],
163
+ ["items", "array", "declares array items but is not an array"],
164
+ ] as const) {
165
+ if (paramSpec[property] !== undefined && paramSpec.type !== type)
166
+ errors.push(`${context} ${message}`);
182
167
  }
183
168
  if (paramSpec.type === "array") {
184
169
  if (!paramSpec.items) {
170
+ errors.push(`${context} is an array and must declare items`);
171
+ } else if (
172
+ !paramSpec.items.anyOf &&
173
+ !["string", "number", "boolean", "object", "array"].includes(paramSpec.items.type ?? "")
174
+ ) {
185
175
  errors.push(
186
- `${turnKindLabel} turn '${turnId}' outcome '${outcome}' parameter '${paramName}' is an array and must declare items`,
187
- );
188
- } else if (!isValidOutcomeToolArrayItemType(paramSpec.items.type)) {
189
- errors.push(
190
- `${turnKindLabel} turn '${turnId}' outcome '${outcome}' parameter '${paramName}' declares unsupported array item type '${String(paramSpec.items.type)}'`,
176
+ `${context} declares unsupported array item type '${String(paramSpec.items.type)}'`,
191
177
  );
192
178
  }
193
179
  }
180
+ if (errors.length === before) {
181
+ try {
182
+ compileOutcomeParameters({ [paramName]: paramSpec }, outcomeSpec.strictSchema);
183
+ } catch (error) {
184
+ errors.push(`${context}: ${error instanceof Error ? error.message : String(error)}`);
185
+ }
186
+ }
194
187
  }
195
188
  }
196
189
  return errors;
@@ -328,109 +321,89 @@ export function validateLlmTurnDefinition<
328
321
 
329
322
  errors.push(...validateOutcomeToolParameters("LLM", turnId, declaredOutcomes));
330
323
  errors.push(...validateMappedTurn(turnId, turnDef));
324
+ errors.push(...validateExternalActions("LLM", turnId, turnDef.externalActions));
325
+ if (Object.keys(turnDef.externalActions ?? {}).length && !turnDef.waitFor)
326
+ errors.push(`LLM turn '${turnId}' external actions require .waitFor(...)`);
331
327
 
332
328
  return errors;
333
329
  }
334
330
 
335
- function validateMappedTurn<TOutcome extends string, TParams, TState>(
331
+ /** @internal */
332
+ export function validateAutomaticTurnDefinition<
333
+ TOutcome extends string = string,
334
+ TParams = unknown,
335
+ TState = unknown,
336
+ >(turnId: string, turnDef: AutomaticTurnDefinition<TOutcome, TParams, TState>): string[] {
337
+ return [
338
+ ...validateOutcomeTurnResultContract("Automatic", turnId, turnDef.outcomes, turnDef.turnEnd),
339
+ ...validateOutcomeToolParameters("Automatic", turnId, turnDef.outcomes),
340
+ ...validateExternalActions("Automatic", turnId, turnDef.externalActions),
341
+ ];
342
+ }
343
+
344
+ /** Intrinsic checks shared by standalone turn validation and route compilation. @internal */
345
+ export function validateExternalActions<TParams, TState>(
346
+ kind: string,
336
347
  turnId: string,
337
- turnDef: LlmTurnDefinition<TOutcome, TParams, TState>,
348
+ actions: HumanTurnDefinition<TParams, TState>["externalActions"],
338
349
  ): string[] {
339
- const mapped = turnDef.forEach;
340
- if (mapped === undefined) return [];
341
350
  const errors: string[] = [];
342
- for (const name of ["items", "key", "collect"] as const) {
343
- if (typeof mapped[name] !== "function") {
344
- errors.push(`Mapped turn '${turnId}' must declare ${name}`);
345
- }
346
- }
347
- for (const name of ["itemCodec", "resultCodec"] as const) {
348
- const codec = mapped[name];
349
- if (typeof codec?.parse !== "function" || typeof codec?.serialize !== "function") {
350
- errors.push(`Mapped turn '${turnId}' must declare ${name}`);
351
- }
352
- }
353
- if (turnDef.turnEnd) {
354
- errors.push(`Mapped turn '${turnId}' must finish items through outcome tools`);
355
- }
356
- if (turnDef.publishedProduct) {
357
- errors.push(`Mapped turn '${turnId}' cannot publish a product from item turns`);
358
- }
359
- const outcomes = Object.entries(turnDef.outcomes ?? {}) as Array<
360
- [string, ProcessToolOutcomeSpec<TParams, TState>]
361
- >;
362
- if (outcomes.length === 0) {
363
- errors.push(`Mapped turn '${turnId}' must declare at least one outcome tool`);
364
- }
365
- for (const [outcomeId, spec] of outcomes) {
366
- if (
367
- "branches" in spec ||
368
- spec.to !== undefined ||
369
- spec.complete !== undefined ||
370
- spec.lifecycleStatus !== undefined ||
371
- spec.effect !== undefined ||
372
- spec.lifecycleIntent !== undefined ||
373
- spec.publishedProduct !== undefined
374
- ) {
351
+ for (const [externalActionId, externalAction] of Object.entries(actions ?? {})) {
352
+ if (externalActionId.trim() === "") {
375
353
  errors.push(
376
- `Mapped turn '${turnId}' outcome '${outcomeId}' cannot route, change state, or publish`,
354
+ kind === "Human"
355
+ ? `Human turn '${turnId}' declares an empty external action id`
356
+ : `${kind} turn '${turnId}' contains an external action with an empty id`,
377
357
  );
378
358
  }
379
- if (typeof mapped.yields?.[outcomeId] !== "function") {
380
- errors.push(`Mapped turn '${turnId}' outcome '${outcomeId}' must declare a yield`);
359
+ if (externalAction.id !== externalActionId) {
360
+ errors.push(
361
+ `${kind} turn '${turnId}' external action '${externalActionId}' has mismatched ${kind === "Human" ? "spec " : ""}id '${externalAction.id}'`,
362
+ );
381
363
  }
382
- }
383
- for (const outcomeId of Object.keys(mapped.yields ?? {})) {
384
- if (!Object.hasOwn(turnDef.outcomes ?? {}, outcomeId)) {
385
- errors.push(`Mapped turn '${turnId}' yields undeclared outcome '${outcomeId}'`);
364
+ if (externalAction.source.kind.trim() === "") {
365
+ errors.push(
366
+ `${kind} turn '${turnId}' external action '${externalActionId}' must declare a non-empty source kind`,
367
+ );
386
368
  }
387
- }
388
- const routing = mapped.routing;
389
- if (routing?.kind === "static") {
390
- if ((routing.to === undefined) === (routing.lifecycleStatus === undefined)) {
391
- errors.push(`Mapped turn '${turnId}' collection must declare exactly one target`);
369
+ const targetCount =
370
+ (externalAction.to !== undefined ? 1 : 0) +
371
+ (externalAction.complete === true ? 1 : 0) +
372
+ (externalAction.lifecycleStatus !== undefined ? 1 : 0);
373
+ if (targetCount !== 1) {
374
+ errors.push(
375
+ `${kind} turn '${turnId}' external action '${externalActionId}' must declare exactly one target${kind === "Human" ? " via 'to', 'complete', or 'lifecycleStatus'" : ""}`,
376
+ );
392
377
  }
393
- } else if (routing?.kind === "branches") {
394
- if (Object.keys(routing.branches).length === 0 || typeof routing.choose !== "function") {
395
- errors.push(`Mapped turn '${turnId}' collection routing needs branches and a chooser`);
378
+ if (externalAction.publishInput) {
379
+ errors.push(...validateProcessProductName(externalAction.publishInput.productName));
380
+ if (externalAction.publishInput.inputField.trim() === "") {
381
+ errors.push(
382
+ `${kind} turn '${turnId}' external action '${externalActionId}' publishInput must declare a non-empty inputField`,
383
+ );
384
+ }
385
+ if (externalAction.complete === true || externalAction.lifecycleStatus !== undefined) {
386
+ errors.push(
387
+ `${kind} turn '${turnId}' external action '${externalActionId}' cannot publish input on a terminal route`,
388
+ );
389
+ }
396
390
  }
397
- } else {
398
- errors.push(`Mapped turn '${turnId}' must declare a collection route`);
399
391
  }
400
- return errors;
401
- }
402
392
 
403
- /** @internal */
404
- export function validateAutomaticTurnDefinition<
405
- TOutcome extends string = string,
406
- TParams = unknown,
407
- TState = unknown,
408
- >(turnId: string, turnDef: AutomaticTurnDefinition<TOutcome, TParams, TState>): string[] {
409
- return [
410
- ...validateOutcomeTurnResultContract("Automatic", turnId, turnDef.outcomes, turnDef.turnEnd),
411
- ...validateOutcomeToolParameters("Automatic", turnId, turnDef.outcomes),
412
- ];
393
+ return errors;
413
394
  }
414
395
 
415
- /** @internal */
396
+ /** Intrinsic metadata checked before action derivation, which also validates routing. @internal */
416
397
  export function validateHumanTurnDefinition<TParams = unknown, TState = unknown>(
417
398
  turnId: string,
418
399
  turnDef: HumanTurnDefinition<TParams, TState>,
419
400
  ): string[] {
420
401
  const errors: string[] = [];
421
-
422
- try {
423
- resolveHumanTurnView({ turnId, turn: turnDef });
424
- } catch (error: unknown) {
425
- errors.push(error instanceof Error ? error.message : String(error));
426
- }
427
402
  if (turnDef.reviewProduct) {
428
403
  errors.push(...validateProcessProductName(turnDef.reviewProduct));
429
404
  }
430
405
 
431
- const actionEntries = Object.entries(turnDef.actions) as Array<
432
- [string, HumanTurnDefinition<TParams, TState>["actions"][string]]
433
- >;
406
+ const actionEntries = Object.entries(turnDef.actions);
434
407
  if (actionEntries.length === 0) {
435
408
  errors.push(`Human turn '${turnId}' must declare at least one action`);
436
409
  }
@@ -459,58 +432,13 @@ export function validateHumanTurnDefinition<TParams = unknown, TState = unknown>
459
432
  if (trigger.id.trim() === "") {
460
433
  errors.push(`Human turn '${turnId}' contains an external trigger with an empty id`);
461
434
  }
462
- if (actionId.trim() === "") {
463
- errors.push(
464
- `Human turn '${turnId}' external trigger '${trigger.id}' must declare a non-empty actionId`,
465
- );
466
- }
467
- if (trigger.label.trim() === "") {
468
- errors.push(
469
- `Human turn '${turnId}' external trigger '${trigger.id}' must declare a non-empty label`,
470
- );
471
- }
472
- if (trigger.description.trim() === "") {
473
- errors.push(
474
- `Human turn '${turnId}' external trigger '${trigger.id}' must declare a non-empty description`,
475
- );
476
- }
477
- }
478
-
479
- for (const [externalActionId, externalAction] of Object.entries(turnDef.externalActions ?? {})) {
480
- if (externalActionId.trim() === "") {
481
- errors.push(`Human turn '${turnId}' contains an external action with an empty id`);
482
- }
483
- if (externalAction.id !== externalActionId) {
484
- errors.push(
485
- `Human turn '${turnId}' external action '${externalActionId}' has mismatched id '${externalAction.id}'`,
486
- );
487
- }
488
- if (externalAction.source.kind.trim() === "") {
489
- errors.push(
490
- `Human turn '${turnId}' external action '${externalActionId}' must declare a non-empty source kind`,
491
- );
492
- }
493
- const targetCount =
494
- (externalAction.to !== undefined ? 1 : 0) +
495
- (externalAction.complete === true ? 1 : 0) +
496
- (externalAction.lifecycleStatus !== undefined ? 1 : 0);
497
- if (targetCount !== 1) {
498
- errors.push(
499
- `Human turn '${turnId}' external action '${externalActionId}' must declare exactly one target`,
500
- );
501
- }
502
- if (externalAction.publishInput) {
503
- errors.push(...validateProcessProductName(externalAction.publishInput.productName));
504
- if (externalAction.publishInput.inputField.trim() === "") {
505
- errors.push(
506
- `Human turn '${turnId}' external action '${externalActionId}' publishInput must declare a non-empty inputField`,
507
- );
508
- }
509
- if (externalAction.complete === true || externalAction.lifecycleStatus !== undefined) {
510
- errors.push(
511
- `Human turn '${turnId}' external action '${externalActionId}' cannot publish input on a terminal route`,
512
- );
513
- }
435
+ const context = `Human turn '${turnId}' external trigger '${trigger.id}'`;
436
+ for (const [field, value] of Object.entries({
437
+ actionId,
438
+ label: trigger.label,
439
+ description: trigger.description,
440
+ })) {
441
+ if (value.trim() === "") errors.push(`${context} must declare a non-empty ${field}`);
514
442
  }
515
443
  }
516
444
 
@@ -554,31 +482,14 @@ export function validateExternalTurnDefinition<TParams = unknown, TState = unkno
554
482
  export function validateTurnDefinition<TParams = unknown, TState = unknown>(
555
483
  turnId: string,
556
484
  turnDef: TurnDefinition<TParams, TState>,
557
- ): string[];
558
- /** @internal */
559
- export function validateTurnDefinition<TParams = unknown, TState = unknown>(
560
- turnDef: TurnDefinition<TParams, TState>,
561
- ): string[];
562
- /** @internal */
563
- export function validateTurnDefinition<TParams = unknown, TState = unknown>(
564
- turnIdOrDef: string | TurnDefinition<TParams, TState>,
565
- turnDef?: TurnDefinition<TParams, TState>,
566
485
  ): string[] {
567
- const effectiveTurnDef = typeof turnIdOrDef === "string" ? turnDef : turnIdOrDef;
568
- const effectiveTurnId =
569
- typeof turnIdOrDef === "string"
570
- ? turnIdOrDef
571
- : ((turnIdOrDef as { id?: string }).id ?? "unknown_turn");
572
- if (!effectiveTurnDef) {
573
- return ["Turn definition is required"];
574
- }
575
- return isLlmTurnDefinition(effectiveTurnDef)
576
- ? validateLlmTurnDefinition(effectiveTurnId, effectiveTurnDef)
577
- : isAutomaticTurnDefinition(effectiveTurnDef)
578
- ? validateAutomaticTurnDefinition(effectiveTurnId, effectiveTurnDef)
579
- : isHumanTurnDefinition(effectiveTurnDef)
580
- ? validateHumanTurnDefinition(effectiveTurnId, effectiveTurnDef)
581
- : validateExternalTurnDefinition(effectiveTurnId, effectiveTurnDef);
486
+ return isLlmTurnDefinition(turnDef)
487
+ ? validateLlmTurnDefinition(turnId, turnDef)
488
+ : isAutomaticTurnDefinition(turnDef)
489
+ ? validateAutomaticTurnDefinition(turnId, turnDef)
490
+ : isHumanTurnDefinition(turnDef)
491
+ ? validateHumanTurnDefinition(turnId, turnDef)
492
+ : validateExternalTurnDefinition(turnId, turnDef);
582
493
  }
583
494
 
584
495
  /** @internal */
@@ -0,0 +1,76 @@
1
+ import type { CapabilityToken } from "./capabilities.js";
2
+ import type {
3
+ ProcessLaunchConfig,
4
+ ProcessLaunchProjectConfig,
5
+ ProcessSnapshotContext,
6
+ } from "./extension-api.js";
7
+
8
+ /** Initial repository bindings resolved before the first execution. @public */
9
+ export type InitialProcessBinding<TParams = unknown> = Pick<
10
+ ProcessLaunchConfig<TParams>,
11
+ "params" | "metadata" | "settingsContext"
12
+ > & {
13
+ /** Complete, nonempty repository set. @public */
14
+ projects: readonly ProcessLaunchProjectConfig[];
15
+ };
16
+
17
+ /** A server-owned readiness decision, with no worker attempt. @public */
18
+ export type TurnWaitDecision<TParams = unknown> =
19
+ | TurnWaitCompletion
20
+ | TurnWaitNotice
21
+ | TurnWaitBinding<TParams>;
22
+
23
+ /** A readiness condition or source cancellation with operator guidance. @public */
24
+ export interface TurnWaitNotice {
25
+ /** @internal */
26
+ readonly kind: "waiting" | "abort";
27
+ /** Safe operator guidance. @public */
28
+ readonly message: string;
29
+ }
30
+
31
+ /** Initial bindings staged by a successful readiness check. @public */
32
+ export interface TurnWaitBinding<TParams = unknown> {
33
+ /** @internal */
34
+ readonly kind: "bind";
35
+ /** @internal */
36
+ readonly binding: InitialProcessBinding<TParams>;
37
+ }
38
+
39
+ /** A terminal decision returned from a turn's server-side waiting condition. @public */
40
+ export interface TurnWaitCompletion {
41
+ /** @internal */
42
+ readonly kind: "complete";
43
+ }
44
+
45
+ /** Server context for a repeatable condition. External operations must be read-only. @public */
46
+ export interface TurnWaitContext<TParams = unknown, TState = unknown>
47
+ extends ProcessSnapshotContext<TParams, TState> {
48
+ /** Cancelled on timeout or server shutdown. @public */
49
+ readonly signal: AbortSignal;
50
+ /** Resolve an extension-owned server adapter. Never perform external writes here. @public */
51
+ require<T>(token: CapabilityToken<T>): T | T[];
52
+ /** Stage process state with this check; stale and failed checks discard it. @public */
53
+ setState(state: TState): void;
54
+ /** Wait at the normal polling interval with safe operator guidance. Return this decision. @public */
55
+ waiting(message: string): TurnWaitDecision<TParams>;
56
+ /** Abort without a worker when the source is cancelled. Return this decision. @public */
57
+ abort(message: string): TurnWaitDecision<TParams>;
58
+ /** Bind initial params and projects atomically, then check again before starting a worker. Only available before any project or execution exists. @public */
59
+ bindInitialProjects(binding: InitialProcessBinding<TParams>): TurnWaitDecision<TParams>;
60
+ /** Finish the process without allocating a worker. Return this decision. @public */
61
+ complete(): TurnWaitCompletion;
62
+ }
63
+
64
+ /** False keeps this turn waiting; true permits execution; complete ends the process. @public */
65
+ export type TurnWaitPredicate<TParams = unknown, TState = unknown> = (
66
+ process: TurnWaitContext<TParams, TState>,
67
+ ) => boolean | TurnWaitDecision<TParams> | Promise<boolean | TurnWaitDecision<TParams>>;
68
+
69
+ /** A temporary observation failure. Other predicate errors require an explicit retry. @public */
70
+ export class RetryableWaitError extends Error {
71
+ /** The message must be safe to show to an operator. @public */
72
+ constructor(message: string, options?: ErrorOptions) {
73
+ super(message, options);
74
+ this.name = "RetryableWaitError";
75
+ }
76
+ }