@leitwerk-dev/process-sdk 0.3.0 → 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-I7U6HCLN.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 +43 -26
  6. package/dist/define-process.d.ts.map +1 -1
  7. package/dist/{extension-api-3Vr3RE8S.d.ts → extension-api-Ljc4UTZ0.d.ts} +440 -49
  8. package/dist/extension-api.d.ts +66 -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 +234 -118
  17. package/dist/flow.d.ts.map +1 -1
  18. package/dist/index.d.ts +15 -7
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +4189 -3534
  21. package/dist/index.js.map +1 -1
  22. package/dist/mapped-turn.d.ts +169 -0
  23. package/dist/mapped-turn.d.ts.map +1 -0
  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 +45 -24
  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 +447 -540
  47. package/src/extension-api.ts +78 -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 +888 -532
  52. package/src/index.ts +77 -2
  53. package/src/mapped-turn.ts +437 -0
  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 +102 -116
  61. package/src/turn-wait.ts +76 -0
  62. package/src/types.ts +44 -22
  63. package/dist/chunk-I7U6HCLN.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,10 +131,6 @@ function validateOutcomeTurnResultContract<TParams = unknown, TState = unknown>(
130
131
  return errors;
131
132
  }
132
133
 
133
- function isValidOutcomeToolArrayItemType(type: unknown): boolean {
134
- return type === "string" || type === "number" || type === "boolean" || type === "object";
135
- }
136
-
137
134
  function validateOutcomeToolParameters<TParams = unknown, TState = unknown>(
138
135
  turnKindLabel: string,
139
136
  turnId: string,
@@ -143,48 +140,50 @@ function validateOutcomeToolParameters<TParams = unknown, TState = unknown>(
143
140
  for (const [outcome, outcomeSpec] of Object.entries(outcomes ?? {}) as Array<
144
141
  [string, ProcessToolOutcomeSpec<TParams, TState>]
145
142
  >) {
143
+ const outcomeContext = `${turnKindLabel} turn '${turnId}' outcome '${outcome}'`;
146
144
  if (outcomeSpec.publishedProduct) {
147
145
  errors.push(...validateProcessProductName(outcomeSpec.publishedProduct));
148
146
  const parameterName = outcomeSpec.turnResultMarkdownParameter?.trim() ?? "";
149
147
  if (!parameterName) {
150
148
  errors.push(
151
- `${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`,
152
150
  );
153
151
  } else if (!Object.hasOwn(outcomeSpec.parameters, parameterName)) {
154
152
  errors.push(
155
- `${turnKindLabel} turn '${turnId}' outcome '${outcome}' publishes product '${outcomeSpec.publishedProduct}' from missing parameter '${parameterName}'`,
153
+ `${outcomeContext} publishes product '${outcomeSpec.publishedProduct}' from missing parameter '${parameterName}'`,
156
154
  );
157
155
  }
158
156
  }
159
- for (const [paramName, paramSpec] of Object.entries(outcomeSpec.parameters) as Array<
160
- [string, OutcomeToolParameterSpec]
161
- >) {
162
- if (paramSpec.minItems !== undefined && paramSpec.type !== "array") {
163
- errors.push(
164
- `${turnKindLabel} turn '${turnId}' outcome '${outcome}' parameter '${paramName}' uses minItems but is not an array`,
165
- );
166
- }
167
- if (paramSpec.minimum !== undefined && paramSpec.type !== "number") {
168
- errors.push(
169
- `${turnKindLabel} turn '${turnId}' outcome '${outcome}' parameter '${paramName}' uses minimum but is not a number`,
170
- );
171
- }
172
- if (paramSpec.items !== undefined && paramSpec.type !== "array") {
173
- errors.push(
174
- `${turnKindLabel} turn '${turnId}' outcome '${outcome}' parameter '${paramName}' declares array items but is not an array`,
175
- );
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}`);
176
167
  }
177
168
  if (paramSpec.type === "array") {
178
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
+ ) {
179
175
  errors.push(
180
- `${turnKindLabel} turn '${turnId}' outcome '${outcome}' parameter '${paramName}' is an array and must declare items`,
181
- );
182
- } else if (!isValidOutcomeToolArrayItemType(paramSpec.items.type)) {
183
- errors.push(
184
- `${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)}'`,
185
177
  );
186
178
  }
187
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
+ }
188
187
  }
189
188
  }
190
189
  return errors;
@@ -321,6 +320,10 @@ export function validateLlmTurnDefinition<
321
320
  }
322
321
 
323
322
  errors.push(...validateOutcomeToolParameters("LLM", turnId, declaredOutcomes));
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(...)`);
324
327
 
325
328
  return errors;
326
329
  }
@@ -334,28 +337,73 @@ export function validateAutomaticTurnDefinition<
334
337
  return [
335
338
  ...validateOutcomeTurnResultContract("Automatic", turnId, turnDef.outcomes, turnDef.turnEnd),
336
339
  ...validateOutcomeToolParameters("Automatic", turnId, turnDef.outcomes),
340
+ ...validateExternalActions("Automatic", turnId, turnDef.externalActions),
337
341
  ];
338
342
  }
339
343
 
340
- /** @internal */
344
+ /** Intrinsic checks shared by standalone turn validation and route compilation. @internal */
345
+ export function validateExternalActions<TParams, TState>(
346
+ kind: string,
347
+ turnId: string,
348
+ actions: HumanTurnDefinition<TParams, TState>["externalActions"],
349
+ ): string[] {
350
+ const errors: string[] = [];
351
+ for (const [externalActionId, externalAction] of Object.entries(actions ?? {})) {
352
+ if (externalActionId.trim() === "") {
353
+ errors.push(
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`,
357
+ );
358
+ }
359
+ if (externalAction.id !== externalActionId) {
360
+ errors.push(
361
+ `${kind} turn '${turnId}' external action '${externalActionId}' has mismatched ${kind === "Human" ? "spec " : ""}id '${externalAction.id}'`,
362
+ );
363
+ }
364
+ if (externalAction.source.kind.trim() === "") {
365
+ errors.push(
366
+ `${kind} turn '${turnId}' external action '${externalActionId}' must declare a non-empty source kind`,
367
+ );
368
+ }
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
+ );
377
+ }
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
+ }
390
+ }
391
+ }
392
+
393
+ return errors;
394
+ }
395
+
396
+ /** Intrinsic metadata checked before action derivation, which also validates routing. @internal */
341
397
  export function validateHumanTurnDefinition<TParams = unknown, TState = unknown>(
342
398
  turnId: string,
343
399
  turnDef: HumanTurnDefinition<TParams, TState>,
344
400
  ): string[] {
345
401
  const errors: string[] = [];
346
-
347
- try {
348
- resolveHumanTurnView({ turnId, turn: turnDef });
349
- } catch (error: unknown) {
350
- errors.push(error instanceof Error ? error.message : String(error));
351
- }
352
402
  if (turnDef.reviewProduct) {
353
403
  errors.push(...validateProcessProductName(turnDef.reviewProduct));
354
404
  }
355
405
 
356
- const actionEntries = Object.entries(turnDef.actions) as Array<
357
- [string, HumanTurnDefinition<TParams, TState>["actions"][string]]
358
- >;
406
+ const actionEntries = Object.entries(turnDef.actions);
359
407
  if (actionEntries.length === 0) {
360
408
  errors.push(`Human turn '${turnId}' must declare at least one action`);
361
409
  }
@@ -384,58 +432,13 @@ export function validateHumanTurnDefinition<TParams = unknown, TState = unknown>
384
432
  if (trigger.id.trim() === "") {
385
433
  errors.push(`Human turn '${turnId}' contains an external trigger with an empty id`);
386
434
  }
387
- if (actionId.trim() === "") {
388
- errors.push(
389
- `Human turn '${turnId}' external trigger '${trigger.id}' must declare a non-empty actionId`,
390
- );
391
- }
392
- if (trigger.label.trim() === "") {
393
- errors.push(
394
- `Human turn '${turnId}' external trigger '${trigger.id}' must declare a non-empty label`,
395
- );
396
- }
397
- if (trigger.description.trim() === "") {
398
- errors.push(
399
- `Human turn '${turnId}' external trigger '${trigger.id}' must declare a non-empty description`,
400
- );
401
- }
402
- }
403
-
404
- for (const [externalActionId, externalAction] of Object.entries(turnDef.externalActions ?? {})) {
405
- if (externalActionId.trim() === "") {
406
- errors.push(`Human turn '${turnId}' contains an external action with an empty id`);
407
- }
408
- if (externalAction.id !== externalActionId) {
409
- errors.push(
410
- `Human turn '${turnId}' external action '${externalActionId}' has mismatched id '${externalAction.id}'`,
411
- );
412
- }
413
- if (externalAction.source.kind.trim() === "") {
414
- errors.push(
415
- `Human turn '${turnId}' external action '${externalActionId}' must declare a non-empty source kind`,
416
- );
417
- }
418
- const targetCount =
419
- (externalAction.to !== undefined ? 1 : 0) +
420
- (externalAction.complete === true ? 1 : 0) +
421
- (externalAction.lifecycleStatus !== undefined ? 1 : 0);
422
- if (targetCount !== 1) {
423
- errors.push(
424
- `Human turn '${turnId}' external action '${externalActionId}' must declare exactly one target`,
425
- );
426
- }
427
- if (externalAction.publishInput) {
428
- errors.push(...validateProcessProductName(externalAction.publishInput.productName));
429
- if (externalAction.publishInput.inputField.trim() === "") {
430
- errors.push(
431
- `Human turn '${turnId}' external action '${externalActionId}' publishInput must declare a non-empty inputField`,
432
- );
433
- }
434
- if (externalAction.complete === true || externalAction.lifecycleStatus !== undefined) {
435
- errors.push(
436
- `Human turn '${turnId}' external action '${externalActionId}' cannot publish input on a terminal route`,
437
- );
438
- }
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}`);
439
442
  }
440
443
  }
441
444
 
@@ -479,31 +482,14 @@ export function validateExternalTurnDefinition<TParams = unknown, TState = unkno
479
482
  export function validateTurnDefinition<TParams = unknown, TState = unknown>(
480
483
  turnId: string,
481
484
  turnDef: TurnDefinition<TParams, TState>,
482
- ): string[];
483
- /** @internal */
484
- export function validateTurnDefinition<TParams = unknown, TState = unknown>(
485
- turnDef: TurnDefinition<TParams, TState>,
486
- ): string[];
487
- /** @internal */
488
- export function validateTurnDefinition<TParams = unknown, TState = unknown>(
489
- turnIdOrDef: string | TurnDefinition<TParams, TState>,
490
- turnDef?: TurnDefinition<TParams, TState>,
491
485
  ): string[] {
492
- const effectiveTurnDef = typeof turnIdOrDef === "string" ? turnDef : turnIdOrDef;
493
- const effectiveTurnId =
494
- typeof turnIdOrDef === "string"
495
- ? turnIdOrDef
496
- : ((turnIdOrDef as { id?: string }).id ?? "unknown_turn");
497
- if (!effectiveTurnDef) {
498
- return ["Turn definition is required"];
499
- }
500
- return isLlmTurnDefinition(effectiveTurnDef)
501
- ? validateLlmTurnDefinition(effectiveTurnId, effectiveTurnDef)
502
- : isAutomaticTurnDefinition(effectiveTurnDef)
503
- ? validateAutomaticTurnDefinition(effectiveTurnId, effectiveTurnDef)
504
- : isHumanTurnDefinition(effectiveTurnDef)
505
- ? validateHumanTurnDefinition(effectiveTurnId, effectiveTurnDef)
506
- : 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);
507
493
  }
508
494
 
509
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
+ }