@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
package/src/index.ts CHANGED
@@ -50,6 +50,7 @@ export {
50
50
  type ProcessLaunchPlanServiceLike,
51
51
  type ProcessModelSelectionPreviewResultLike,
52
52
  type ProcessModelSelectionServiceLike,
53
+ type ProcessObservationUpdate,
53
54
  type ProcessProjectRepoLike,
54
55
  type ProcessQuestionServiceLike,
55
56
  type ProcessWatcherServiceLike,
@@ -57,8 +58,10 @@ export {
57
58
  type ProgrammaticLaunchResultLike,
58
59
  type QueuedProcessInputLike,
59
60
  type RegisteredProcessWatcherLike,
61
+ type WaitingProcessRestart,
60
62
  type WatcherLaunchResultLike,
61
63
  } from "./core-capabilities.js";
64
+ export type { OutcomeParameterContext } from "./define-process.js";
62
65
  export {
63
66
  type AutomaticTurnDefinition,
64
67
  automaticTurn,
@@ -69,7 +72,9 @@ export {
69
72
  getExternalSourceTransitionId,
70
73
  type HumanTurnDefinition,
71
74
  humanTurn,
75
+ type LlmOutcomeSubmission,
72
76
  type LlmTurnDefinition,
77
+ type LlmTurnPreparationContext,
73
78
  llmTurn,
74
79
  type ProcessEffectPlan,
75
80
  type ProcessHumanTurnExternalActionSpec,
@@ -78,6 +83,7 @@ export {
78
83
  resolveHumanTurnView,
79
84
  routeTurnOutcomes,
80
85
  type TurnDefinition,
86
+ validateProcessDefinition,
81
87
  } from "./define-process.js";
82
88
  export { createEventBus } from "./event-bus.js";
83
89
  export type {
@@ -124,6 +130,7 @@ export type {
124
130
  TicketCreationDestinationSnapshot,
125
131
  TicketCreationDestinationSummary,
126
132
  TicketCreationReceipt,
133
+ TurnDiagnosticReport,
127
134
  UiLauncherDefinition,
128
135
  UiLauncherSummary,
129
136
  WorkerCompleteInput,
@@ -142,6 +149,13 @@ export {
142
149
  createExternalSourcePollReporter,
143
150
  type ExternalSourcePollReporter,
144
151
  } from "./external-source-poll.js";
152
+ export {
153
+ consumeTriggerFile,
154
+ createFileExternalSourceProvider,
155
+ defineFileExternalSource,
156
+ type FileExternalInput,
157
+ readTriggerFile,
158
+ } from "./file-external-source.js";
145
159
  export {
146
160
  AutomaticOutcomeBuilder,
147
161
  createFlowPromptContext,
@@ -225,6 +239,20 @@ export {
225
239
  piWorker,
226
240
  resolveProviderOptions,
227
241
  } from "./model-provider.js";
242
+ export {
243
+ applyOutcomeContract,
244
+ type ResolvedOutcomeContract,
245
+ resolveOutcomeContract,
246
+ } from "./outcome-contract.js";
247
+ export {
248
+ assertOutcomeSchema,
249
+ compileOutcomeParameters,
250
+ type OutcomeSchemaIssue,
251
+ outcomeCallParameters,
252
+ outcomeParameterSchema,
253
+ validateOutcomeParameters,
254
+ validateOutcomeValue,
255
+ } from "./outcome-schema.js";
228
256
  export { buildProcessFlowView } from "./process-flow-view.js";
229
257
  export {
230
258
  getProcessGraph,
@@ -237,7 +265,6 @@ export {
237
265
  type ProcessGraphView,
238
266
  serializeProcessGraph,
239
267
  toProcessGraphView,
240
- validateProcessGraphEntryTurns,
241
268
  validateProcessGraphProducts,
242
269
  validateProcessGraphTurnTransitions,
243
270
  } from "./process-graph.js";
@@ -290,6 +317,7 @@ export {
290
317
  parseRepositoryPullRequestConfig,
291
318
  } from "./repository-source-config.js";
292
319
  export type { RepositoryIssue, RepositoryPullRequest } from "./repository-types.js";
320
+ export * from "./scoped-settings.js";
293
321
  export type {
294
322
  ServerExtensionEventMap,
295
323
  ServerExtensionEventName,
@@ -306,6 +334,15 @@ export {
306
334
  structuralStateCodec,
307
335
  } from "./state-helpers.js";
308
336
  export { sanitizeWorkerSubprocessEnv } from "./subprocess-env.js";
337
+ export {
338
+ listTicketDestinations,
339
+ markdownTicketCreationDefinition,
340
+ parseTicketCreationConfig,
341
+ parseTicketDestinationId,
342
+ type TicketCreationConfig,
343
+ ticketDestinationId,
344
+ ticketLabelNames,
345
+ } from "./ticket-creation.js";
309
346
  export { numberArg, objectArg, projectParameters, stringArg } from "./tool-arguments.js";
310
347
  export type { ToolCallRendererDefinition } from "./tool-renderers.js";
311
348
  export {
@@ -324,6 +361,16 @@ export {
324
361
  resolveLlmTurnRestorePrimaryLeafAfterTurn,
325
362
  validateTurnDefinition,
326
363
  } from "./turn-semantics.js";
364
+ export {
365
+ type InitialProcessBinding,
366
+ RetryableWaitError,
367
+ type TurnWaitBinding,
368
+ type TurnWaitCompletion,
369
+ type TurnWaitContext,
370
+ type TurnWaitDecision,
371
+ type TurnWaitNotice,
372
+ type TurnWaitPredicate,
373
+ } from "./turn-wait.js";
327
374
  export type {
328
375
  EventBus,
329
376
  OutcomeToolArrayItemSpec,
@@ -1,9 +1,11 @@
1
1
  import type {
2
+ MappedItem,
2
3
  ProcessInstance,
3
4
  ProcessProject,
4
5
  ProcessTurnTerminalLifecycleStatus,
5
6
  TurnId,
6
7
  } from "@leitwerk-dev/domain";
8
+ import type { LlmTurnDefinition, ProcessToolOutcomeSpec } from "./define-process.js";
7
9
  import type { Codec, ProcessTurnOutcomeEvent } from "./extension-api.js";
8
10
  import { SafeOutcomePlanningError } from "./extension-api.js";
9
11
 
@@ -51,19 +53,9 @@ export interface MappedTurnItemContext<TItem = unknown> {
51
53
  }
52
54
 
53
55
  /** Serialized active item carried by worker payloads and turn records. @internal */
54
- export interface MappedTurnIteration {
56
+ export interface MappedTurnIteration extends MappedTurnItemContext<unknown> {
55
57
  /** @internal */
56
58
  readonly runId: string;
57
- /** @internal */
58
- readonly itemKey: string;
59
- /** @internal */
60
- readonly itemLabel: string;
61
- /** @internal */
62
- readonly itemIndex: number;
63
- /** @internal */
64
- readonly itemCount: number;
65
- /** JSON value produced by the item codec. @internal */
66
- readonly item: unknown;
67
59
  }
68
60
 
69
61
  /** @public */
@@ -163,16 +155,7 @@ export interface MappedLlmTurnSpec<
163
155
  }
164
156
 
165
157
  /** @internal */
166
- export interface FrozenMappedItem {
167
- /** @internal */
168
- index: number;
169
- /** @internal */
170
- key: string;
171
- /** @internal */
172
- label: string;
173
- /** @internal */
174
- itemJson: string;
175
- }
158
+ export type FrozenMappedItem = Pick<MappedItem, "itemIndex" | "itemKey" | "label" | "itemJson">;
176
159
 
177
160
  /** @internal */
178
161
  export interface MappedFreezeResult<TState = unknown> {
@@ -197,6 +180,74 @@ export interface MappedCollectResult<TState = unknown> {
197
180
  };
198
181
  }
199
182
 
183
+ /** @internal */
184
+ export function validateMappedTurn<TOutcome extends string, TParams, TState>(
185
+ turnId: string,
186
+ turnDef: LlmTurnDefinition<TOutcome, TParams, TState>,
187
+ ): string[] {
188
+ const mapped = turnDef.forEach;
189
+ if (mapped === undefined) return [];
190
+ const errors: string[] = [];
191
+ for (const name of ["items", "key", "collect"] as const) {
192
+ if (typeof mapped[name] !== "function") {
193
+ errors.push(`Mapped turn '${turnId}' must declare ${name}`);
194
+ }
195
+ }
196
+ for (const name of ["itemCodec", "resultCodec"] as const) {
197
+ const codec = mapped[name];
198
+ if (typeof codec?.parse !== "function" || typeof codec?.serialize !== "function") {
199
+ errors.push(`Mapped turn '${turnId}' must declare ${name}`);
200
+ }
201
+ }
202
+ if (turnDef.turnEnd) {
203
+ errors.push(`Mapped turn '${turnId}' must finish items through outcome tools`);
204
+ }
205
+ if (turnDef.publishedProduct) {
206
+ errors.push(`Mapped turn '${turnId}' cannot publish a product from item turns`);
207
+ }
208
+ const outcomes = Object.entries(turnDef.outcomes ?? {}) as Array<
209
+ [string, ProcessToolOutcomeSpec<TParams, TState>]
210
+ >;
211
+ if (outcomes.length === 0) {
212
+ errors.push(`Mapped turn '${turnId}' must declare at least one outcome tool`);
213
+ }
214
+ for (const [outcomeId, spec] of outcomes) {
215
+ if (
216
+ "branches" in spec ||
217
+ spec.to !== undefined ||
218
+ spec.complete !== undefined ||
219
+ spec.lifecycleStatus !== undefined ||
220
+ spec.effect !== undefined ||
221
+ spec.publishedProduct !== undefined
222
+ ) {
223
+ errors.push(
224
+ `Mapped turn '${turnId}' outcome '${outcomeId}' cannot route, change state, or publish`,
225
+ );
226
+ }
227
+ if (typeof mapped.yields?.[outcomeId] !== "function") {
228
+ errors.push(`Mapped turn '${turnId}' outcome '${outcomeId}' must declare a yield`);
229
+ }
230
+ }
231
+ for (const outcomeId of Object.keys(mapped.yields ?? {})) {
232
+ if (!Object.hasOwn(turnDef.outcomes ?? {}, outcomeId)) {
233
+ errors.push(`Mapped turn '${turnId}' yields undeclared outcome '${outcomeId}'`);
234
+ }
235
+ }
236
+ const routing = mapped.routing;
237
+ if (routing?.kind === "static") {
238
+ if ((routing.to === undefined) === (routing.lifecycleStatus === undefined)) {
239
+ errors.push(`Mapped turn '${turnId}' collection must declare exactly one target`);
240
+ }
241
+ } else if (routing?.kind === "branches") {
242
+ if (Object.keys(routing.branches).length === 0 || typeof routing.choose !== "function") {
243
+ errors.push(`Mapped turn '${turnId}' collection routing needs branches and a chooser`);
244
+ }
245
+ } else {
246
+ errors.push(`Mapped turn '${turnId}' must declare a collection route`);
247
+ }
248
+ return errors;
249
+ }
250
+
200
251
  function toJsonValue(value: unknown, context: string): string {
201
252
  let json: string | undefined;
202
253
  try {
@@ -268,8 +319,8 @@ export function freezeMappedItems<TParams, TState>(
268
319
  const label = plainText(typeof rawLabel === "string" ? rawLabel : "") || key;
269
320
  parsed.push(item);
270
321
  items.push({
271
- index,
272
- key,
322
+ itemIndex: index,
323
+ itemKey: key,
273
324
  label: label.slice(0, MAPPED_ITEM_LABEL_MAX_LENGTH),
274
325
  itemJson: toJsonValue(
275
326
  spec.itemCodec.serialize(item),
@@ -0,0 +1,126 @@
1
+ import { isUnknownRecord } from "@leitwerk-dev/domain";
2
+ import type {
3
+ LlmTurnDefinition,
4
+ OutcomeParameterContext,
5
+ ProcessToolOutcomeSpec,
6
+ } from "./define-process.js";
7
+ import type { MappedTurnIteration } from "./mapped-turn.js";
8
+ import { compileOutcomeParameters, outcomeCallParameters } from "./outcome-schema.js";
9
+ import type { OutcomeToolSpec, TurnResultMarkdownBehavior } from "./types.js";
10
+
11
+ /** Serializable contract owned by a prepared turn start. @internal */
12
+ export interface ResolvedOutcomeContract {
13
+ /** @internal */
14
+ version: 1;
15
+ /** @internal */
16
+ outcomes: Record<string, OutcomeToolSpec>;
17
+ /** @internal */
18
+ turnResultMarkdown: TurnResultMarkdownBehavior | null;
19
+ /** @internal */
20
+ publishedProduct: string | null;
21
+ }
22
+
23
+ function freeze<T>(value: T): T {
24
+ if (value && typeof value === "object") {
25
+ Object.freeze(value);
26
+ for (const child of Object.values(value)) freeze(child);
27
+ }
28
+ return value;
29
+ }
30
+
31
+ /** Resolve once on the server, before worker I/O; callbacks receive immutable copies. @internal */
32
+ export function resolveOutcomeContract<TParams, TState>(
33
+ turn: LlmTurnDefinition<string, TParams, TState>,
34
+ ctx: OutcomeParameterContext<TParams, TState>,
35
+ iteration?: MappedTurnIteration,
36
+ ): ResolvedOutcomeContract {
37
+ const context = freeze(
38
+ structuredClone({
39
+ ...ctx,
40
+ ...(iteration
41
+ ? {
42
+ ...iteration,
43
+ item: turn.forEach?.itemCodec.parse(iteration.item) ?? iteration.item,
44
+ }
45
+ : {}),
46
+ }),
47
+ );
48
+ const outcomes: Record<string, OutcomeToolSpec> = {};
49
+ for (const [name, value] of Object.entries(turn.outcomes ?? {})) {
50
+ const spec = value as ProcessToolOutcomeSpec<TParams, TState>;
51
+ if (spec.resolveParameters && turn.forEach && !iteration)
52
+ throw new Error(`Outcome '${name}' needs its frozen mapped item`);
53
+ const resolved = spec.resolveParameters ? spec.resolveParameters(context) : {};
54
+ if (!isUnknownRecord(resolved) || typeof resolved.then === "function")
55
+ throw new Error(`Outcome '${name}' parameter resolver must return a synchronous object`);
56
+ const contract: OutcomeToolSpec = {
57
+ description: spec.description,
58
+ parameters: { ...spec.parameters, ...resolved },
59
+ ...(spec.strictSchema ? { strictSchema: true } : {}),
60
+ ...(spec.publishedProduct ? { publishedProduct: spec.publishedProduct } : {}),
61
+ ...(spec.turnResultMarkdownParameter
62
+ ? { turnResultMarkdownParameter: spec.turnResultMarkdownParameter }
63
+ : {}),
64
+ ...(spec.resultSummaryParameter
65
+ ? { resultSummaryParameter: spec.resultSummaryParameter }
66
+ : {}),
67
+ };
68
+ compileOutcomeParameters(
69
+ outcomeCallParameters(
70
+ contract,
71
+ turn.turnResultMarkdown?.mode === "outcome_tool_argument"
72
+ ? turn.turnResultMarkdown.parameterName
73
+ : undefined,
74
+ ),
75
+ contract.strictSchema,
76
+ );
77
+ outcomes[name] = contract;
78
+ }
79
+ return JSON.parse(
80
+ JSON.stringify({
81
+ version: 1,
82
+ outcomes,
83
+ turnResultMarkdown: turn.turnResultMarkdown ?? null,
84
+ publishedProduct: turn.publishedProduct ?? null,
85
+ }),
86
+ ) as ResolvedOutcomeContract;
87
+ }
88
+
89
+ /** Overlay the frozen declaration while retaining current executable handlers. @internal */
90
+ export function applyOutcomeContract<TOutcome extends string, TParams, TState>(
91
+ turn: LlmTurnDefinition<TOutcome, TParams, TState>,
92
+ snapshot: unknown,
93
+ ): LlmTurnDefinition<TOutcome, TParams, TState> {
94
+ if (!isUnknownRecord(snapshot) || snapshot.version !== 1 || !isUnknownRecord(snapshot.outcomes))
95
+ throw new Error("Invalid frozen outcome contract");
96
+ const contract = snapshot as unknown as ResolvedOutcomeContract;
97
+ const outcomes: Record<string, ProcessToolOutcomeSpec<TParams, TState>> = {};
98
+ for (const [name, spec] of Object.entries(contract.outcomes)) {
99
+ const current = turn.outcomes?.[name as TOutcome];
100
+ if (!current) throw new Error(`Frozen outcome '${name}' no longer has an executable handler`);
101
+ compileOutcomeParameters(
102
+ outcomeCallParameters(
103
+ spec,
104
+ contract.turnResultMarkdown?.mode === "outcome_tool_argument"
105
+ ? contract.turnResultMarkdown.parameterName
106
+ : undefined,
107
+ ),
108
+ spec.strictSchema,
109
+ );
110
+ const {
111
+ resolveParameters,
112
+ strictSchema,
113
+ publishedProduct,
114
+ turnResultMarkdownParameter,
115
+ resultSummaryParameter,
116
+ ...handler
117
+ } = current;
118
+ outcomes[name] = { ...handler, ...spec };
119
+ }
120
+ return {
121
+ ...turn,
122
+ outcomes,
123
+ turnResultMarkdown: contract.turnResultMarkdown ?? undefined,
124
+ publishedProduct: contract.publishedProduct ?? undefined,
125
+ } as LlmTurnDefinition<TOutcome, TParams, TState>;
126
+ }
@@ -0,0 +1,314 @@
1
+ import { isUnknownRecord, normalizeStringArray } from "@leitwerk-dev/domain";
2
+ import type {
3
+ OutcomeToolArrayItemSpec,
4
+ OutcomeToolParameterSpec,
5
+ OutcomeToolSpec,
6
+ } from "./types.js";
7
+
8
+ /** A structural error relative to the submitted tool arguments. @public */
9
+ export interface OutcomeSchemaIssue {
10
+ /** @public */
11
+ path: string;
12
+ /** @public */
13
+ code: string;
14
+ /** @public */
15
+ message: string;
16
+ }
17
+
18
+ /** Convert the parameter DSL to a native JSON Schema value declaration. @internal */
19
+ export function outcomeParameterSchema(spec: OutcomeToolParameterSpec): OutcomeToolArrayItemSpec {
20
+ const {
21
+ required,
22
+ requiredProperties,
23
+ requiredErrorCode,
24
+ invalidErrorCode,
25
+ minItemsErrorCode,
26
+ minimumErrorCode,
27
+ ...value
28
+ } = spec;
29
+ return {
30
+ ...value,
31
+ ...(spec.type === "array" ? { items: spec.items ?? { type: "string" } } : {}),
32
+ ...(requiredProperties ? { required: requiredProperties } : {}),
33
+ ...(spec.type === "string" && required ? { minLength: Math.max(1, spec.minLength ?? 0) } : {}),
34
+ };
35
+ }
36
+
37
+ /** Compile and check a model-facing object schema. @public */
38
+ export function compileOutcomeParameters(
39
+ parameters: Record<string, OutcomeToolParameterSpec>,
40
+ strict = false,
41
+ ): OutcomeToolArrayItemSpec {
42
+ const schema: OutcomeToolArrayItemSpec = {
43
+ type: "object",
44
+ properties: Object.fromEntries(
45
+ Object.entries(parameters).map(([name, spec]) => [name, outcomeParameterSchema(spec)]),
46
+ ),
47
+ required: Object.keys(parameters).filter((name) => parameters[name].required),
48
+ additionalProperties: false,
49
+ };
50
+ assertOutcomeSchema(schema, strict);
51
+ return schema;
52
+ }
53
+
54
+ /** Reject malformed declarations before a tool is exposed to the model. @public */
55
+ export function assertOutcomeSchema(
56
+ schema: OutcomeToolArrayItemSpec,
57
+ strict = false,
58
+ path = "arguments",
59
+ ): void {
60
+ const fail = (message: string): never => {
61
+ throw new Error(`${path}: ${message}`);
62
+ };
63
+ if (!isUnknownRecord(schema)) fail("expected a schema object");
64
+ if (schema.anyOf !== undefined) {
65
+ if (schema.type !== undefined || !Array.isArray(schema.anyOf) || !schema.anyOf.length)
66
+ fail("anyOf needs at least one variant and cannot also declare type");
67
+ if (
68
+ schema.properties ||
69
+ schema.items ||
70
+ schema.required ||
71
+ schema.enum ||
72
+ schema.minimum !== undefined ||
73
+ schema.minLength !== undefined ||
74
+ schema.minItems !== undefined ||
75
+ schema.additionalProperties !== undefined
76
+ )
77
+ fail("put value constraints inside the anyOf variants");
78
+ schema.anyOf.forEach((variant, index) => {
79
+ assertOutcomeSchema(variant, strict, `${path}.anyOf[${index}]`);
80
+ });
81
+ return;
82
+ }
83
+ if (!["string", "number", "boolean", "object", "array"].includes(schema.type ?? ""))
84
+ fail("unsupported or missing type");
85
+ for (const [key, type] of [
86
+ ["minLength", "string"],
87
+ ["minimum", "number"],
88
+ ["minItems", "array"],
89
+ ] as const) {
90
+ const value = schema[key];
91
+ if (
92
+ value !== undefined &&
93
+ (schema.type !== type ||
94
+ !Number.isFinite(value) ||
95
+ (key !== "minimum" && (!Number.isInteger(value) || value < 0)))
96
+ )
97
+ fail(`invalid ${key} for ${schema.type}`);
98
+ }
99
+ if (
100
+ schema.enum !== undefined &&
101
+ (schema.type !== "string" ||
102
+ !Array.isArray(schema.enum) ||
103
+ !schema.enum.length ||
104
+ schema.enum.some((value) => typeof value !== "string"))
105
+ )
106
+ fail("enum must contain strings on a string schema");
107
+ if (schema.type === "array") {
108
+ if (!schema.items) fail("array must declare items");
109
+ assertOutcomeSchema(schema.items!, strict, `${path}[]`);
110
+ } else if (schema.items !== undefined) fail("items requires an array");
111
+ if (schema.type === "object") {
112
+ const properties = schema.properties ?? {};
113
+ if (!isUnknownRecord(properties)) fail("properties must be an object");
114
+ if (
115
+ schema.required !== undefined &&
116
+ (!Array.isArray(schema.required) ||
117
+ schema.required.some((key) => typeof key !== "string" || !Object.hasOwn(properties, key)))
118
+ )
119
+ fail("required must name declared properties");
120
+ if (
121
+ schema.additionalProperties !== undefined &&
122
+ typeof schema.additionalProperties !== "boolean"
123
+ )
124
+ fail("additionalProperties must be boolean");
125
+ if (
126
+ strict &&
127
+ (schema.additionalProperties !== false ||
128
+ Object.keys(properties).some((key) => !schema.required?.includes(key)))
129
+ )
130
+ fail("strict schemas require every property and additionalProperties: false");
131
+ for (const [key, value] of Object.entries(properties))
132
+ assertOutcomeSchema(value, strict, `${path}.${key}`);
133
+ } else if (
134
+ schema.properties !== undefined ||
135
+ schema.required !== undefined ||
136
+ schema.additionalProperties !== undefined
137
+ )
138
+ fail("object keywords require an object");
139
+ }
140
+
141
+ /** Validate native schema values, retaining errors from an identifiable union branch. @public */
142
+ export function validateOutcomeValue(
143
+ schema: OutcomeToolArrayItemSpec,
144
+ value: unknown,
145
+ path = "arguments",
146
+ ): OutcomeSchemaIssue[] {
147
+ const error = (code: string, message: string): OutcomeSchemaIssue[] => [
148
+ { path, code, message: `${path}: ${message}` },
149
+ ];
150
+ if (schema.anyOf) {
151
+ const branches = schema.anyOf.map((variant) => validateOutcomeValue(variant, value, path));
152
+ if (branches.some((errors) => !errors.length)) return [];
153
+ // Single-value string enums form an unambiguous discriminator. Generic anyOf
154
+ // still accepts any matching branch, including overlapping alternatives.
155
+ if (isUnknownRecord(value) && schema.anyOf.every((variant) => variant.type === "object")) {
156
+ for (const key of Object.keys(schema.anyOf[0]?.properties ?? {})) {
157
+ const tags = schema.anyOf.map((variant) =>
158
+ variant.required?.includes(key) &&
159
+ variant.properties?.[key]?.type === "string" &&
160
+ variant.properties[key].enum?.length === 1
161
+ ? variant.properties[key].enum![0]
162
+ : undefined,
163
+ );
164
+ if (tags.some((tag) => tag === undefined) || new Set(tags).size !== tags.length) continue;
165
+ const selected = tags.indexOf(value[key] as string);
166
+ if (selected >= 0) return branches[selected];
167
+ return [
168
+ {
169
+ path: `${path}.${key}`,
170
+ code: "enum",
171
+ message: `${path}.${key}: choose ${tags.join(", ")}`,
172
+ },
173
+ ];
174
+ }
175
+ }
176
+ return error(
177
+ "anyOf",
178
+ `must match an alternative (${branches.map((errors) => errors.map((issue) => issue.message).join("; ")).join(" | ")})`,
179
+ );
180
+ }
181
+ if (schema.type === "object") {
182
+ if (!isUnknownRecord(value)) return error("type", "expected an object");
183
+ const properties = schema.properties ?? {};
184
+ return [
185
+ ...Object.keys(value)
186
+ .filter((key) => schema.additionalProperties === false && !Object.hasOwn(properties, key))
187
+ .map((key) => ({
188
+ path: `${path}.${key}`,
189
+ code: "unknown_parameter",
190
+ message: `${path}.${key}: unsupported field; allowed fields: ${Object.keys(properties).join(", ")}`,
191
+ })),
192
+ ...(schema.required ?? [])
193
+ .filter((key) => !Object.hasOwn(value, key) || value[key] === undefined)
194
+ .map((key) => ({
195
+ path: `${path}.${key}`,
196
+ code: "required",
197
+ message: `${path}.${key}: required`,
198
+ })),
199
+ ...Object.entries(properties).flatMap(([key, spec]) =>
200
+ value[key] === undefined ? [] : validateOutcomeValue(spec, value[key], `${path}.${key}`),
201
+ ),
202
+ ];
203
+ }
204
+ if (schema.type === "array") {
205
+ if (!Array.isArray(value)) return error("type", "expected an array");
206
+ return [
207
+ ...(value.length < (schema.minItems ?? 0)
208
+ ? error("minItems", `requires at least ${schema.minItems} item(s)`)
209
+ : []),
210
+ ...value.flatMap((item, index) =>
211
+ schema.items ? validateOutcomeValue(schema.items, item, `${path}[${index}]`) : [],
212
+ ),
213
+ ];
214
+ }
215
+ if (typeof value !== schema.type || (typeof value === "number" && !Number.isFinite(value)))
216
+ return error("type", `expected ${schema.type === "number" ? "a finite number" : schema.type}`);
217
+ if (typeof value === "string") {
218
+ if (schema.enum && !schema.enum.includes(value))
219
+ return error("enum", `choose ${schema.enum.join(", ")}`);
220
+ if (value.length < (schema.minLength ?? 0))
221
+ return error("minLength", `requires at least ${schema.minLength} characters`);
222
+ }
223
+ if (typeof value === "number" && schema.minimum !== undefined && value < schema.minimum)
224
+ return error("minimum", `must be >= ${schema.minimum}`);
225
+ return [];
226
+ }
227
+
228
+ function snakeCase(value: string): string {
229
+ return value
230
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
231
+ .replace(/[^a-zA-Z0-9]+/g, "_")
232
+ .replace(/^_+|_+$/g, "")
233
+ .toLowerCase();
234
+ }
235
+
236
+ /** Validate the parameter DSL with its established server error codes. @public */
237
+ export function validateOutcomeParameters(
238
+ parameters: Record<string, OutcomeToolParameterSpec>,
239
+ value: unknown,
240
+ ): OutcomeSchemaIssue[] {
241
+ if (!isUnknownRecord(value))
242
+ return [{ path: "arguments", code: "invalid_params", message: "params must be an object" }];
243
+ const issues: OutcomeSchemaIssue[] = Object.keys(value)
244
+ .filter((key) => !Object.hasOwn(parameters, key))
245
+ .map((key) => ({ path: key, code: "unknown_parameter", message: `${key}: unknown parameter` }));
246
+ for (const [key, spec] of Object.entries(parameters)) {
247
+ const item = value[key];
248
+ const requiredCode = spec.requiredErrorCode ?? `${snakeCase(key)}_required`;
249
+ if (
250
+ item === undefined ||
251
+ (spec.type === "string" && typeof item === "string" && !item.trim() && spec.required)
252
+ ) {
253
+ if (spec.required)
254
+ issues.push({
255
+ path: key,
256
+ code: requiredCode,
257
+ message: `${key}: required and must be non-empty`,
258
+ });
259
+ continue;
260
+ }
261
+ const errors = validateOutcomeValue(outcomeParameterSchema(spec), item, key);
262
+ if (
263
+ spec.type === "array" &&
264
+ Array.isArray(item) &&
265
+ (spec.items === undefined || spec.items.type === "string") &&
266
+ spec.minItems !== undefined &&
267
+ normalizeStringArray(item).length < spec.minItems &&
268
+ !errors.some((issue) => issue.code === "minItems")
269
+ )
270
+ errors.push({
271
+ path: key,
272
+ code: "minItems",
273
+ message: `${key}: requires at least ${spec.minItems} nonempty item(s)`,
274
+ });
275
+ issues.push(
276
+ ...errors.map((issue) => ({
277
+ ...issue,
278
+ code:
279
+ issue.path === key && issue.code === "minItems"
280
+ ? (spec.minItemsErrorCode ?? requiredCode)
281
+ : issue.path === key && issue.code === "minimum"
282
+ ? (spec.minimumErrorCode ?? spec.invalidErrorCode ?? `invalid_${snakeCase(key)}`)
283
+ : (spec.invalidErrorCode ?? `invalid_${snakeCase(key)}`),
284
+ })),
285
+ );
286
+ }
287
+ return issues;
288
+ }
289
+
290
+ /** Include injected Markdown only for the model call, not terminal params. @internal */
291
+ export function outcomeCallParameters(
292
+ spec: OutcomeToolSpec,
293
+ markdownParameter?: string,
294
+ ): Record<string, OutcomeToolParameterSpec> {
295
+ if (!markdownParameter || spec.turnResultMarkdownParameter) return spec.parameters;
296
+ return {
297
+ ...spec.parameters,
298
+ ...(!spec.strictSchema
299
+ ? {
300
+ resultSummary: {
301
+ type: "string" as const,
302
+ description: "Concise result summary for this attempt.",
303
+ },
304
+ }
305
+ : {}),
306
+ [markdownParameter]: {
307
+ type: "string",
308
+ description:
309
+ "Operator-facing Markdown result. Pass raw Markdown without wrapping it in a code fence.",
310
+ required: true,
311
+ requiredErrorCode: `${markdownParameter}_required`,
312
+ },
313
+ };
314
+ }