@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,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
+ }