@leitwerk-dev/process-sdk 0.3.1 → 0.4.1
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.
- package/dist/{chunk-GVBLXKSR.js → chunk-HT2AXXLH.js} +2 -1
- package/dist/chunk-HT2AXXLH.js.map +1 -0
- package/dist/core-capabilities.d.ts +63 -2
- package/dist/core-capabilities.d.ts.map +1 -1
- package/dist/define-process.d.ts +40 -26
- package/dist/define-process.d.ts.map +1 -1
- package/dist/{extension-api-DM-AvWOW.d.ts → extension-api-Ljc4UTZ0.d.ts} +258 -64
- package/dist/extension-api.d.ts +52 -0
- package/dist/extension-api.d.ts.map +1 -1
- package/dist/external-source-poll.d.ts +1 -1
- package/dist/external-source-poll.d.ts.map +1 -1
- package/dist/file-external-source.d.ts +32 -0
- package/dist/file-external-source.d.ts.map +1 -0
- package/dist/flow-mapped.typecheck.d.ts +2 -0
- package/dist/flow-mapped.typecheck.d.ts.map +1 -0
- package/dist/flow.d.ts +188 -177
- package/dist/flow.d.ts.map +1 -1
- package/dist/index.d.ts +11 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4387 -4313
- package/dist/index.js.map +1 -1
- package/dist/mapped-turn.d.ts +6 -22
- package/dist/mapped-turn.d.ts.map +1 -1
- package/dist/outcome-contract.d.ts +19 -0
- package/dist/outcome-contract.d.ts.map +1 -0
- package/dist/outcome-schema.d.ts +25 -0
- package/dist/outcome-schema.d.ts.map +1 -0
- package/dist/pi-config-public.js +1 -1
- package/dist/pi-config.js +1 -1
- package/dist/process-flow-view.d.ts +3 -14
- package/dist/process-flow-view.d.ts.map +1 -1
- package/dist/process-graph.d.ts +10 -4
- package/dist/process-graph.d.ts.map +1 -1
- package/dist/scoped-settings.d.ts +87 -0
- package/dist/scoped-settings.d.ts.map +1 -0
- package/dist/ticket-creation.d.ts +24 -0
- package/dist/ticket-creation.d.ts.map +1 -0
- package/dist/turn-semantics.d.ts +3 -3
- package/dist/turn-semantics.d.ts.map +1 -1
- package/dist/turn-wait.d.ts +53 -0
- package/dist/turn-wait.d.ts.map +1 -0
- package/dist/types.d.ts +31 -18
- package/dist/types.d.ts.map +1 -1
- package/package.json +6 -6
- package/src/core-capabilities.ts +87 -1
- package/src/define-process.ts +420 -596
- package/src/extension-api.ts +60 -0
- package/src/external-source-poll.ts +6 -24
- package/src/file-external-source.ts +135 -0
- package/src/flow-mapped.typecheck.ts +136 -0
- package/src/flow.ts +746 -815
- package/src/index.ts +48 -1
- package/src/mapped-turn.ts +74 -23
- package/src/outcome-contract.ts +119 -0
- package/src/outcome-schema.ts +315 -0
- package/src/process-flow-view.ts +84 -346
- package/src/process-graph.ts +95 -45
- package/src/scoped-settings.ts +113 -0
- package/src/ticket-creation.ts +113 -0
- package/src/turn-semantics.ts +85 -193
- package/src/turn-wait.ts +76 -0
- package/src/types.ts +30 -16
- 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,
|
package/src/mapped-turn.ts
CHANGED
|
@@ -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
|
|
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,119 @@
|
|
|
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
|
+
function validateContractOutcome(
|
|
32
|
+
spec: OutcomeToolSpec,
|
|
33
|
+
markdown?: TurnResultMarkdownBehavior | null,
|
|
34
|
+
) {
|
|
35
|
+
compileOutcomeParameters(
|
|
36
|
+
outcomeCallParameters(
|
|
37
|
+
spec,
|
|
38
|
+
markdown?.mode === "outcome_tool_argument" ? markdown.parameterName : undefined,
|
|
39
|
+
),
|
|
40
|
+
spec.strictSchema,
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Resolve once on the server, before worker I/O; callbacks receive immutable copies. @internal */
|
|
45
|
+
export function resolveOutcomeContract<TParams, TState>(
|
|
46
|
+
turn: LlmTurnDefinition<string, TParams, TState>,
|
|
47
|
+
ctx: OutcomeParameterContext<TParams, TState>,
|
|
48
|
+
iteration?: MappedTurnIteration,
|
|
49
|
+
): ResolvedOutcomeContract {
|
|
50
|
+
const context = freeze(
|
|
51
|
+
structuredClone({
|
|
52
|
+
...ctx,
|
|
53
|
+
...(iteration
|
|
54
|
+
? {
|
|
55
|
+
...iteration,
|
|
56
|
+
item: turn.forEach?.itemCodec.parse(iteration.item) ?? iteration.item,
|
|
57
|
+
}
|
|
58
|
+
: {}),
|
|
59
|
+
}),
|
|
60
|
+
);
|
|
61
|
+
const outcomes: Record<string, OutcomeToolSpec> = {};
|
|
62
|
+
for (const [name, value] of Object.entries(turn.outcomes ?? {})) {
|
|
63
|
+
const spec = value as ProcessToolOutcomeSpec<TParams, TState>;
|
|
64
|
+
if (spec.resolveParameters && turn.forEach && !iteration)
|
|
65
|
+
throw new Error(`Outcome '${name}' needs its frozen mapped item`);
|
|
66
|
+
const resolved = spec.resolveParameters ? spec.resolveParameters(context) : {};
|
|
67
|
+
if (!isUnknownRecord(resolved) || typeof resolved.then === "function")
|
|
68
|
+
throw new Error(`Outcome '${name}' parameter resolver must return a synchronous object`);
|
|
69
|
+
const contract: OutcomeToolSpec = {
|
|
70
|
+
description: spec.description,
|
|
71
|
+
parameters: { ...spec.parameters, ...resolved },
|
|
72
|
+
strictSchema: spec.strictSchema || undefined,
|
|
73
|
+
publishedProduct: spec.publishedProduct || undefined,
|
|
74
|
+
turnResultMarkdownParameter: spec.turnResultMarkdownParameter || undefined,
|
|
75
|
+
resultSummaryParameter: spec.resultSummaryParameter || undefined,
|
|
76
|
+
};
|
|
77
|
+
validateContractOutcome(contract, turn.turnResultMarkdown);
|
|
78
|
+
outcomes[name] = contract;
|
|
79
|
+
}
|
|
80
|
+
return JSON.parse(
|
|
81
|
+
JSON.stringify({
|
|
82
|
+
version: 1,
|
|
83
|
+
outcomes,
|
|
84
|
+
turnResultMarkdown: turn.turnResultMarkdown ?? null,
|
|
85
|
+
publishedProduct: turn.publishedProduct ?? null,
|
|
86
|
+
}),
|
|
87
|
+
) as ResolvedOutcomeContract;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Overlay the frozen declaration while retaining current executable handlers. @internal */
|
|
91
|
+
export function applyOutcomeContract<TOutcome extends string, TParams, TState>(
|
|
92
|
+
turn: LlmTurnDefinition<TOutcome, TParams, TState>,
|
|
93
|
+
snapshot: unknown,
|
|
94
|
+
): LlmTurnDefinition<TOutcome, TParams, TState> {
|
|
95
|
+
if (!isUnknownRecord(snapshot) || snapshot.version !== 1 || !isUnknownRecord(snapshot.outcomes))
|
|
96
|
+
throw new Error("Invalid frozen outcome contract");
|
|
97
|
+
const contract = snapshot as unknown as ResolvedOutcomeContract;
|
|
98
|
+
const outcomes: Record<string, ProcessToolOutcomeSpec<TParams, TState>> = {};
|
|
99
|
+
for (const [name, spec] of Object.entries(contract.outcomes)) {
|
|
100
|
+
const current = turn.outcomes?.[name as TOutcome];
|
|
101
|
+
if (!current) throw new Error(`Frozen outcome '${name}' no longer has an executable handler`);
|
|
102
|
+
validateContractOutcome(spec, contract.turnResultMarkdown);
|
|
103
|
+
const {
|
|
104
|
+
resolveParameters,
|
|
105
|
+
strictSchema,
|
|
106
|
+
publishedProduct,
|
|
107
|
+
turnResultMarkdownParameter,
|
|
108
|
+
resultSummaryParameter,
|
|
109
|
+
...handler
|
|
110
|
+
} = current;
|
|
111
|
+
outcomes[name] = { ...handler, ...spec };
|
|
112
|
+
}
|
|
113
|
+
return {
|
|
114
|
+
...turn,
|
|
115
|
+
outcomes,
|
|
116
|
+
turnResultMarkdown: contract.turnResultMarkdown ?? undefined,
|
|
117
|
+
publishedProduct: contract.publishedProduct ?? undefined,
|
|
118
|
+
} as LlmTurnDefinition<TOutcome, TParams, TState>;
|
|
119
|
+
}
|
|
@@ -0,0 +1,315 @@
|
|
|
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
|
+
/** @internal */
|
|
229
|
+
export function snakeCase(value: string): string {
|
|
230
|
+
return value
|
|
231
|
+
.replace(/([a-z0-9])([A-Z])/g, "$1_$2")
|
|
232
|
+
.replace(/[^a-zA-Z0-9]+/g, "_")
|
|
233
|
+
.replace(/^_+|_+$/g, "")
|
|
234
|
+
.toLowerCase();
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Validate the parameter DSL with its established server error codes. @public */
|
|
238
|
+
export function validateOutcomeParameters(
|
|
239
|
+
parameters: Record<string, OutcomeToolParameterSpec>,
|
|
240
|
+
value: unknown,
|
|
241
|
+
): OutcomeSchemaIssue[] {
|
|
242
|
+
if (!isUnknownRecord(value))
|
|
243
|
+
return [{ path: "arguments", code: "invalid_params", message: "params must be an object" }];
|
|
244
|
+
const issues: OutcomeSchemaIssue[] = Object.keys(value)
|
|
245
|
+
.filter((key) => !Object.hasOwn(parameters, key))
|
|
246
|
+
.map((key) => ({ path: key, code: "unknown_parameter", message: `${key}: unknown parameter` }));
|
|
247
|
+
for (const [key, spec] of Object.entries(parameters)) {
|
|
248
|
+
const item = value[key];
|
|
249
|
+
const requiredCode = spec.requiredErrorCode ?? `${snakeCase(key)}_required`;
|
|
250
|
+
if (
|
|
251
|
+
item === undefined ||
|
|
252
|
+
(spec.type === "string" && typeof item === "string" && !item.trim() && spec.required)
|
|
253
|
+
) {
|
|
254
|
+
if (spec.required)
|
|
255
|
+
issues.push({
|
|
256
|
+
path: key,
|
|
257
|
+
code: requiredCode,
|
|
258
|
+
message: `${key}: required and must be non-empty`,
|
|
259
|
+
});
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
const errors = validateOutcomeValue(outcomeParameterSchema(spec), item, key);
|
|
263
|
+
if (
|
|
264
|
+
spec.type === "array" &&
|
|
265
|
+
Array.isArray(item) &&
|
|
266
|
+
(spec.items === undefined || spec.items.type === "string") &&
|
|
267
|
+
spec.minItems !== undefined &&
|
|
268
|
+
normalizeStringArray(item).length < spec.minItems &&
|
|
269
|
+
!errors.some((issue) => issue.code === "minItems")
|
|
270
|
+
)
|
|
271
|
+
errors.push({
|
|
272
|
+
path: key,
|
|
273
|
+
code: "minItems",
|
|
274
|
+
message: `${key}: requires at least ${spec.minItems} nonempty item(s)`,
|
|
275
|
+
});
|
|
276
|
+
issues.push(
|
|
277
|
+
...errors.map((issue) => ({
|
|
278
|
+
...issue,
|
|
279
|
+
code:
|
|
280
|
+
issue.path === key && issue.code === "minItems"
|
|
281
|
+
? (spec.minItemsErrorCode ?? requiredCode)
|
|
282
|
+
: issue.path === key && issue.code === "minimum"
|
|
283
|
+
? (spec.minimumErrorCode ?? spec.invalidErrorCode ?? `invalid_${snakeCase(key)}`)
|
|
284
|
+
: (spec.invalidErrorCode ?? `invalid_${snakeCase(key)}`),
|
|
285
|
+
})),
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
return issues;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Include injected Markdown only for the model call, not terminal params. @internal */
|
|
292
|
+
export function outcomeCallParameters(
|
|
293
|
+
spec: OutcomeToolSpec,
|
|
294
|
+
markdownParameter?: string,
|
|
295
|
+
): Record<string, OutcomeToolParameterSpec> {
|
|
296
|
+
if (!markdownParameter || spec.turnResultMarkdownParameter) return spec.parameters;
|
|
297
|
+
return {
|
|
298
|
+
...spec.parameters,
|
|
299
|
+
...(!spec.strictSchema
|
|
300
|
+
? {
|
|
301
|
+
resultSummary: {
|
|
302
|
+
type: "string" as const,
|
|
303
|
+
description: "Concise result summary for this attempt.",
|
|
304
|
+
},
|
|
305
|
+
}
|
|
306
|
+
: {}),
|
|
307
|
+
[markdownParameter]: {
|
|
308
|
+
type: "string",
|
|
309
|
+
description:
|
|
310
|
+
"Operator-facing Markdown result. Pass raw Markdown without wrapping it in a code fence.",
|
|
311
|
+
required: true,
|
|
312
|
+
requiredErrorCode: `${markdownParameter}_required`,
|
|
313
|
+
},
|
|
314
|
+
};
|
|
315
|
+
}
|