@leitwerk-dev/process-sdk 0.3.0 → 0.3.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-I7U6HCLN.js → chunk-GVBLXKSR.js} +1 -1
- package/dist/chunk-GVBLXKSR.js.map +1 -0
- package/dist/define-process.d.ts +3 -0
- package/dist/define-process.d.ts.map +1 -1
- package/dist/{extension-api-3Vr3RE8S.d.ts → extension-api-DM-AvWOW.d.ts} +206 -9
- package/dist/extension-api.d.ts +14 -0
- package/dist/extension-api.d.ts.map +1 -1
- package/dist/flow.d.ts +118 -13
- package/dist/flow.d.ts.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +602 -44
- package/dist/index.js.map +1 -1
- package/dist/mapped-turn.d.ts +185 -0
- package/dist/mapped-turn.d.ts.map +1 -0
- package/dist/pi-config-public.js +1 -1
- package/dist/pi-config.js +1 -1
- package/dist/turn-semantics.d.ts.map +1 -1
- package/dist/types.d.ts +15 -7
- package/dist/types.d.ts.map +1 -1
- package/package.json +6 -6
- package/src/define-process.ts +83 -0
- package/src/extension-api.ts +18 -0
- package/src/flow.ts +448 -31
- package/src/index.ts +29 -1
- package/src/mapped-turn.ts +386 -0
- package/src/turn-semantics.ts +76 -1
- package/src/types.ts +15 -7
- package/dist/chunk-I7U6HCLN.js.map +0 -1
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ProcessInstance,
|
|
3
|
+
ProcessProject,
|
|
4
|
+
ProcessTurnTerminalLifecycleStatus,
|
|
5
|
+
TurnId,
|
|
6
|
+
} from "@leitwerk-dev/domain";
|
|
7
|
+
import type { Codec, ProcessTurnOutcomeEvent } from "./extension-api.js";
|
|
8
|
+
import { SafeOutcomePlanningError } from "./extension-api.js";
|
|
9
|
+
|
|
10
|
+
/** @public */
|
|
11
|
+
type MaybePromise<T> = T | Promise<T>;
|
|
12
|
+
|
|
13
|
+
/** Maximum length of a mapped item key. @internal */
|
|
14
|
+
export const MAPPED_ITEM_KEY_MAX_LENGTH = 200;
|
|
15
|
+
/** Maximum length of a mapped item label. @internal */
|
|
16
|
+
export const MAPPED_ITEM_LABEL_MAX_LENGTH = 200;
|
|
17
|
+
/** Maximum number of items frozen by one mapped run. @internal */
|
|
18
|
+
export const MAPPED_ITEM_MAX_COUNT = 500;
|
|
19
|
+
/** Graph trigger used by a mapped turn's collection route. @internal */
|
|
20
|
+
export const MAPPED_COLLECT_TRIGGER = "collect" as const;
|
|
21
|
+
|
|
22
|
+
/** @internal */
|
|
23
|
+
export function mappedCollectTrigger(branchId?: string): string {
|
|
24
|
+
return branchId === undefined ? MAPPED_COLLECT_TRIGGER : `${MAPPED_COLLECT_TRIGGER}:${branchId}`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Durable snapshot of process data available to mapped-turn server callbacks. @public */
|
|
28
|
+
export interface MappedTurnServerContext<TParams = unknown, TState = unknown> {
|
|
29
|
+
/** @public */
|
|
30
|
+
readonly process: ProcessInstance;
|
|
31
|
+
/** @internal */
|
|
32
|
+
readonly projects: readonly ProcessProject[];
|
|
33
|
+
/** @public */
|
|
34
|
+
readonly params: TParams;
|
|
35
|
+
/** @public */
|
|
36
|
+
readonly state: TState;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Active item of a mapped LLM turn, as delivered to one worker turn. @public */
|
|
40
|
+
export interface MappedTurnItemContext<TItem = unknown> {
|
|
41
|
+
/** Frozen, codec-validated item value. @public */
|
|
42
|
+
readonly item: TItem;
|
|
43
|
+
/** Stable key unique within the run. @public */
|
|
44
|
+
readonly itemKey: string;
|
|
45
|
+
/** Short plain-text label shown to operators. @public */
|
|
46
|
+
readonly itemLabel: string;
|
|
47
|
+
/** Zero-based position in the frozen order. @public */
|
|
48
|
+
readonly itemIndex: number;
|
|
49
|
+
/** Number of frozen items in the run. @public */
|
|
50
|
+
readonly itemCount: number;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Serialized active item carried by worker payloads and turn records. @internal */
|
|
54
|
+
export interface MappedTurnIteration {
|
|
55
|
+
/** @internal */
|
|
56
|
+
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
|
+
}
|
|
68
|
+
|
|
69
|
+
/** @public */
|
|
70
|
+
export interface MappedItemInput<TItem = unknown> {
|
|
71
|
+
/** @public */
|
|
72
|
+
readonly item: TItem;
|
|
73
|
+
/** @public */
|
|
74
|
+
readonly index: number;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** @public */
|
|
78
|
+
export interface MappedSnapshotInput<TParams = unknown, TState = unknown, TItem = unknown> {
|
|
79
|
+
/** @public */
|
|
80
|
+
readonly params: TParams;
|
|
81
|
+
/** @public */
|
|
82
|
+
readonly state: TState;
|
|
83
|
+
/** @public */
|
|
84
|
+
readonly items: readonly TItem[];
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Context passed to a mapped outcome's `yield` callback. @public */
|
|
88
|
+
export interface MappedOutcomeContext<TParams = unknown, TState = unknown, TItem = unknown>
|
|
89
|
+
extends MappedTurnServerContext<TParams, TState>,
|
|
90
|
+
MappedTurnItemContext<TItem> {}
|
|
91
|
+
|
|
92
|
+
/** @public */
|
|
93
|
+
export interface MappedYieldInput<TParams = unknown, TState = unknown, TItem = unknown> {
|
|
94
|
+
/** @public */
|
|
95
|
+
readonly ctx: MappedOutcomeContext<TParams, TState, TItem>;
|
|
96
|
+
/** @public */
|
|
97
|
+
readonly event: ProcessTurnOutcomeEvent;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** @public */
|
|
101
|
+
export type MappedItemYield<
|
|
102
|
+
TParams = unknown,
|
|
103
|
+
TState = unknown,
|
|
104
|
+
TItem = unknown,
|
|
105
|
+
TResult = unknown,
|
|
106
|
+
> = (input: MappedYieldInput<TParams, TState, TItem>) => MaybePromise<TResult>;
|
|
107
|
+
|
|
108
|
+
/** @public */
|
|
109
|
+
export type MappedCollect<TParams = unknown, TState = unknown, TResult = unknown> = (
|
|
110
|
+
ctx: MappedTurnServerContext<TParams, TState>,
|
|
111
|
+
orderedResults: readonly TResult[],
|
|
112
|
+
) => MaybePromise<TState>;
|
|
113
|
+
|
|
114
|
+
/** Route applied once, after collection. @internal */
|
|
115
|
+
export type MappedCollectRouting<TParams = unknown, TState = unknown> =
|
|
116
|
+
| {
|
|
117
|
+
/** @internal */
|
|
118
|
+
kind: "static";
|
|
119
|
+
/** @internal */
|
|
120
|
+
to?: TurnId;
|
|
121
|
+
/** @internal */
|
|
122
|
+
lifecycleStatus?: ProcessTurnTerminalLifecycleStatus;
|
|
123
|
+
}
|
|
124
|
+
| {
|
|
125
|
+
/** @internal */
|
|
126
|
+
kind: "branches";
|
|
127
|
+
/** @internal */
|
|
128
|
+
branches: Readonly<Record<string, TurnId>>;
|
|
129
|
+
/** @internal */
|
|
130
|
+
choose(ctx: MappedTurnServerContext<TParams, TState>): MaybePromise<string>;
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Durable sequential iteration of one LLM turn over frozen items. Items run one
|
|
135
|
+
* at a time; each item yields a typed result, and business state and routing
|
|
136
|
+
* change once, when all results are collected.
|
|
137
|
+
* @public
|
|
138
|
+
*/
|
|
139
|
+
export interface MappedLlmTurnSpec<
|
|
140
|
+
TParams = unknown,
|
|
141
|
+
TState = unknown,
|
|
142
|
+
TItem = unknown,
|
|
143
|
+
TResult = unknown,
|
|
144
|
+
> {
|
|
145
|
+
/** Evaluated once when the turn is entered. @public */
|
|
146
|
+
items(ctx: MappedTurnServerContext<TParams, TState>): readonly unknown[] | null | undefined;
|
|
147
|
+
/** @public */
|
|
148
|
+
itemCodec: Codec<TItem>;
|
|
149
|
+
/** @public */
|
|
150
|
+
resultCodec: Codec<TResult>;
|
|
151
|
+
/** @public */
|
|
152
|
+
key(input: MappedItemInput<TItem>): string;
|
|
153
|
+
/** Defaults to the item key. @public */
|
|
154
|
+
label?(input: MappedItemInput<TItem>): string;
|
|
155
|
+
/** Applied in the freezing transaction, before any item starts. @public */
|
|
156
|
+
stateAfterSnapshot?(input: MappedSnapshotInput<TParams, TState, TItem>): TState;
|
|
157
|
+
/** @internal */
|
|
158
|
+
yields: Readonly<Record<string, MappedItemYield<TParams, TState, TItem, TResult>>>;
|
|
159
|
+
/** @internal */
|
|
160
|
+
collect: MappedCollect<TParams, TState, TResult>;
|
|
161
|
+
/** @internal */
|
|
162
|
+
routing: MappedCollectRouting<TParams, TState>;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** @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
|
+
}
|
|
176
|
+
|
|
177
|
+
/** @internal */
|
|
178
|
+
export interface MappedFreezeResult<TState = unknown> {
|
|
179
|
+
/** @internal */
|
|
180
|
+
items: FrozenMappedItem[];
|
|
181
|
+
/** State to persist in the freezing transaction, when `stateAfterSnapshot` is declared. @internal */
|
|
182
|
+
state?: TState;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** @internal */
|
|
186
|
+
export interface MappedCollectResult<TState = unknown> {
|
|
187
|
+
/** @internal */
|
|
188
|
+
state: TState;
|
|
189
|
+
/** @internal */
|
|
190
|
+
route: {
|
|
191
|
+
/** @internal */
|
|
192
|
+
trigger: string;
|
|
193
|
+
/** @internal */
|
|
194
|
+
nextTurnId?: TurnId;
|
|
195
|
+
/** @internal */
|
|
196
|
+
lifecycleStatus?: ProcessTurnTerminalLifecycleStatus;
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function toJsonValue(value: unknown, context: string): string {
|
|
201
|
+
let json: string | undefined;
|
|
202
|
+
try {
|
|
203
|
+
json = JSON.stringify(value);
|
|
204
|
+
} catch {
|
|
205
|
+
json = undefined;
|
|
206
|
+
}
|
|
207
|
+
if (json === undefined) {
|
|
208
|
+
throw new SafeOutcomePlanningError("invalid_mapped_value", `${context} is not JSON`);
|
|
209
|
+
}
|
|
210
|
+
return json;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function plainText(value: string): string {
|
|
214
|
+
return value.replace(/\s+/g, " ").trim();
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function errorMessage(error: unknown): string {
|
|
218
|
+
return error instanceof Error ? error.message : String(error);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Evaluates, validates, and serializes the items of a mapped turn. @internal */
|
|
222
|
+
export function freezeMappedItems<TParams, TState>(
|
|
223
|
+
turnId: TurnId,
|
|
224
|
+
spec: MappedLlmTurnSpec<TParams, TState>,
|
|
225
|
+
ctx: MappedTurnServerContext<TParams, TState>,
|
|
226
|
+
): MappedFreezeResult<TState> {
|
|
227
|
+
const raw = spec.items(ctx) ?? [];
|
|
228
|
+
if (!Array.isArray(raw)) {
|
|
229
|
+
throw new SafeOutcomePlanningError(
|
|
230
|
+
"invalid_mapped_items",
|
|
231
|
+
`Mapped turn '${turnId}' items must be an array`,
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
if (raw.length > MAPPED_ITEM_MAX_COUNT) {
|
|
235
|
+
throw new SafeOutcomePlanningError(
|
|
236
|
+
"invalid_mapped_items",
|
|
237
|
+
`Mapped turn '${turnId}' may freeze at most ${MAPPED_ITEM_MAX_COUNT} items`,
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
const parsed: unknown[] = [];
|
|
241
|
+
const items: FrozenMappedItem[] = [];
|
|
242
|
+
const keys = new Set<string>();
|
|
243
|
+
for (const [index, value] of raw.entries()) {
|
|
244
|
+
let item: unknown;
|
|
245
|
+
try {
|
|
246
|
+
item = spec.itemCodec.parse(value);
|
|
247
|
+
} catch (error) {
|
|
248
|
+
throw new SafeOutcomePlanningError(
|
|
249
|
+
"invalid_mapped_item",
|
|
250
|
+
`Mapped turn '${turnId}' item ${index} is invalid: ${errorMessage(error)}`,
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
const key = spec.key({ item, index });
|
|
254
|
+
if (typeof key !== "string" || key.trim() === "" || key.length > MAPPED_ITEM_KEY_MAX_LENGTH) {
|
|
255
|
+
throw new SafeOutcomePlanningError(
|
|
256
|
+
"invalid_mapped_item_key",
|
|
257
|
+
`Mapped turn '${turnId}' item ${index} needs a non-empty key of at most ${MAPPED_ITEM_KEY_MAX_LENGTH} characters`,
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
if (keys.has(key)) {
|
|
261
|
+
throw new SafeOutcomePlanningError(
|
|
262
|
+
"duplicate_mapped_item_key",
|
|
263
|
+
`Mapped turn '${turnId}' repeats item key '${key}'`,
|
|
264
|
+
);
|
|
265
|
+
}
|
|
266
|
+
keys.add(key);
|
|
267
|
+
const rawLabel = spec.label ? spec.label({ item, index }) : key;
|
|
268
|
+
const label = plainText(typeof rawLabel === "string" ? rawLabel : "") || key;
|
|
269
|
+
parsed.push(item);
|
|
270
|
+
items.push({
|
|
271
|
+
index,
|
|
272
|
+
key,
|
|
273
|
+
label: label.slice(0, MAPPED_ITEM_LABEL_MAX_LENGTH),
|
|
274
|
+
itemJson: toJsonValue(
|
|
275
|
+
spec.itemCodec.serialize(item),
|
|
276
|
+
`Mapped turn '${turnId}' item '${key}'`,
|
|
277
|
+
),
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
return {
|
|
281
|
+
items,
|
|
282
|
+
...(spec.stateAfterSnapshot
|
|
283
|
+
? {
|
|
284
|
+
state: spec.stateAfterSnapshot({
|
|
285
|
+
params: ctx.params,
|
|
286
|
+
state: ctx.state,
|
|
287
|
+
items: parsed,
|
|
288
|
+
}),
|
|
289
|
+
}
|
|
290
|
+
: {}),
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** Maps one item outcome to its serialized, codec-validated result. @internal */
|
|
295
|
+
export async function yieldMappedItemResult<TParams, TState>(input: {
|
|
296
|
+
/** @internal */
|
|
297
|
+
turnId: TurnId;
|
|
298
|
+
/** @internal */
|
|
299
|
+
spec: MappedLlmTurnSpec<TParams, TState>;
|
|
300
|
+
/** @internal */
|
|
301
|
+
ctx: MappedTurnServerContext<TParams, TState>;
|
|
302
|
+
/** @internal */
|
|
303
|
+
iteration: MappedTurnIteration;
|
|
304
|
+
/** @internal */
|
|
305
|
+
event: ProcessTurnOutcomeEvent;
|
|
306
|
+
}): Promise<string> {
|
|
307
|
+
const yieldResult = input.spec.yields[input.event.outcome];
|
|
308
|
+
if (!yieldResult) {
|
|
309
|
+
throw new SafeOutcomePlanningError(
|
|
310
|
+
"unknown_mapped_outcome",
|
|
311
|
+
`Mapped turn '${input.turnId}' has no result for outcome '${input.event.outcome}'`,
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
const item = input.spec.itemCodec.parse(input.iteration.item);
|
|
315
|
+
const value = await yieldResult({
|
|
316
|
+
ctx: {
|
|
317
|
+
...input.ctx,
|
|
318
|
+
item,
|
|
319
|
+
itemKey: input.iteration.itemKey,
|
|
320
|
+
itemLabel: input.iteration.itemLabel,
|
|
321
|
+
itemIndex: input.iteration.itemIndex,
|
|
322
|
+
itemCount: input.iteration.itemCount,
|
|
323
|
+
},
|
|
324
|
+
event: input.event,
|
|
325
|
+
});
|
|
326
|
+
let result: unknown;
|
|
327
|
+
try {
|
|
328
|
+
result = input.spec.resultCodec.parse(value);
|
|
329
|
+
} catch (error) {
|
|
330
|
+
throw new SafeOutcomePlanningError(
|
|
331
|
+
"invalid_mapped_result",
|
|
332
|
+
`Mapped turn '${input.turnId}' produced an invalid result for item '${input.iteration.itemKey}': ${errorMessage(error)}`,
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
return toJsonValue(
|
|
336
|
+
input.spec.resultCodec.serialize(result),
|
|
337
|
+
`Mapped turn '${input.turnId}' result for item '${input.iteration.itemKey}'`,
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** Collects ordered results once and resolves the turn's single business route. @internal */
|
|
342
|
+
export async function collectMappedResults<TParams, TState>(input: {
|
|
343
|
+
/** @internal */
|
|
344
|
+
turnId: TurnId;
|
|
345
|
+
/** @internal */
|
|
346
|
+
spec: MappedLlmTurnSpec<TParams, TState>;
|
|
347
|
+
/** @internal */
|
|
348
|
+
ctx: MappedTurnServerContext<TParams, TState>;
|
|
349
|
+
/** Serialized results in frozen item order. @internal */
|
|
350
|
+
resultJsons: readonly string[];
|
|
351
|
+
}): Promise<MappedCollectResult<TState>> {
|
|
352
|
+
const results = input.resultJsons.map((json, index) => {
|
|
353
|
+
try {
|
|
354
|
+
return input.spec.resultCodec.parse(JSON.parse(json));
|
|
355
|
+
} catch (error) {
|
|
356
|
+
throw new SafeOutcomePlanningError(
|
|
357
|
+
"invalid_mapped_result",
|
|
358
|
+
`Mapped turn '${input.turnId}' stored an invalid result at item ${index}: ${errorMessage(error)}`,
|
|
359
|
+
);
|
|
360
|
+
}
|
|
361
|
+
});
|
|
362
|
+
const state = await input.spec.collect(input.ctx, results);
|
|
363
|
+
const routing = input.spec.routing;
|
|
364
|
+
if (routing.kind === "static") {
|
|
365
|
+
return {
|
|
366
|
+
state,
|
|
367
|
+
route: {
|
|
368
|
+
trigger: mappedCollectTrigger(),
|
|
369
|
+
...(routing.to !== undefined ? { nextTurnId: routing.to } : {}),
|
|
370
|
+
...(routing.lifecycleStatus !== undefined
|
|
371
|
+
? { lifecycleStatus: routing.lifecycleStatus }
|
|
372
|
+
: {}),
|
|
373
|
+
},
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
const branchId = await routing.choose({ ...input.ctx, state });
|
|
377
|
+
if (!Object.hasOwn(routing.branches, branchId)) {
|
|
378
|
+
throw new Error(
|
|
379
|
+
`Mapped turn '${input.turnId}' collection selected unknown branch '${branchId}'`,
|
|
380
|
+
);
|
|
381
|
+
}
|
|
382
|
+
return {
|
|
383
|
+
state,
|
|
384
|
+
route: { trigger: mappedCollectTrigger(branchId), nextTurnId: routing.branches[branchId] },
|
|
385
|
+
};
|
|
386
|
+
}
|
package/src/turn-semantics.ts
CHANGED
|
@@ -131,7 +131,13 @@ function validateOutcomeTurnResultContract<TParams = unknown, TState = unknown>(
|
|
|
131
131
|
}
|
|
132
132
|
|
|
133
133
|
function isValidOutcomeToolArrayItemType(type: unknown): boolean {
|
|
134
|
-
return
|
|
134
|
+
return (
|
|
135
|
+
type === "string" ||
|
|
136
|
+
type === "number" ||
|
|
137
|
+
type === "boolean" ||
|
|
138
|
+
type === "object" ||
|
|
139
|
+
type === "array"
|
|
140
|
+
);
|
|
135
141
|
}
|
|
136
142
|
|
|
137
143
|
function validateOutcomeToolParameters<TParams = unknown, TState = unknown>(
|
|
@@ -321,7 +327,76 @@ export function validateLlmTurnDefinition<
|
|
|
321
327
|
}
|
|
322
328
|
|
|
323
329
|
errors.push(...validateOutcomeToolParameters("LLM", turnId, declaredOutcomes));
|
|
330
|
+
errors.push(...validateMappedTurn(turnId, turnDef));
|
|
331
|
+
|
|
332
|
+
return errors;
|
|
333
|
+
}
|
|
324
334
|
|
|
335
|
+
function validateMappedTurn<TOutcome extends string, TParams, TState>(
|
|
336
|
+
turnId: string,
|
|
337
|
+
turnDef: LlmTurnDefinition<TOutcome, TParams, TState>,
|
|
338
|
+
): string[] {
|
|
339
|
+
const mapped = turnDef.forEach;
|
|
340
|
+
if (mapped === undefined) return [];
|
|
341
|
+
const errors: string[] = [];
|
|
342
|
+
for (const name of ["items", "key", "collect"] as const) {
|
|
343
|
+
if (typeof mapped[name] !== "function") {
|
|
344
|
+
errors.push(`Mapped turn '${turnId}' must declare ${name}`);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
for (const name of ["itemCodec", "resultCodec"] as const) {
|
|
348
|
+
const codec = mapped[name];
|
|
349
|
+
if (typeof codec?.parse !== "function" || typeof codec?.serialize !== "function") {
|
|
350
|
+
errors.push(`Mapped turn '${turnId}' must declare ${name}`);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
if (turnDef.turnEnd) {
|
|
354
|
+
errors.push(`Mapped turn '${turnId}' must finish items through outcome tools`);
|
|
355
|
+
}
|
|
356
|
+
if (turnDef.publishedProduct) {
|
|
357
|
+
errors.push(`Mapped turn '${turnId}' cannot publish a product from item turns`);
|
|
358
|
+
}
|
|
359
|
+
const outcomes = Object.entries(turnDef.outcomes ?? {}) as Array<
|
|
360
|
+
[string, ProcessToolOutcomeSpec<TParams, TState>]
|
|
361
|
+
>;
|
|
362
|
+
if (outcomes.length === 0) {
|
|
363
|
+
errors.push(`Mapped turn '${turnId}' must declare at least one outcome tool`);
|
|
364
|
+
}
|
|
365
|
+
for (const [outcomeId, spec] of outcomes) {
|
|
366
|
+
if (
|
|
367
|
+
"branches" in spec ||
|
|
368
|
+
spec.to !== undefined ||
|
|
369
|
+
spec.complete !== undefined ||
|
|
370
|
+
spec.lifecycleStatus !== undefined ||
|
|
371
|
+
spec.effect !== undefined ||
|
|
372
|
+
spec.lifecycleIntent !== undefined ||
|
|
373
|
+
spec.publishedProduct !== undefined
|
|
374
|
+
) {
|
|
375
|
+
errors.push(
|
|
376
|
+
`Mapped turn '${turnId}' outcome '${outcomeId}' cannot route, change state, or publish`,
|
|
377
|
+
);
|
|
378
|
+
}
|
|
379
|
+
if (typeof mapped.yields?.[outcomeId] !== "function") {
|
|
380
|
+
errors.push(`Mapped turn '${turnId}' outcome '${outcomeId}' must declare a yield`);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
for (const outcomeId of Object.keys(mapped.yields ?? {})) {
|
|
384
|
+
if (!Object.hasOwn(turnDef.outcomes ?? {}, outcomeId)) {
|
|
385
|
+
errors.push(`Mapped turn '${turnId}' yields undeclared outcome '${outcomeId}'`);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
const routing = mapped.routing;
|
|
389
|
+
if (routing?.kind === "static") {
|
|
390
|
+
if ((routing.to === undefined) === (routing.lifecycleStatus === undefined)) {
|
|
391
|
+
errors.push(`Mapped turn '${turnId}' collection must declare exactly one target`);
|
|
392
|
+
}
|
|
393
|
+
} else if (routing?.kind === "branches") {
|
|
394
|
+
if (Object.keys(routing.branches).length === 0 || typeof routing.choose !== "function") {
|
|
395
|
+
errors.push(`Mapped turn '${turnId}' collection routing needs branches and a chooser`);
|
|
396
|
+
}
|
|
397
|
+
} else {
|
|
398
|
+
errors.push(`Mapped turn '${turnId}' must declare a collection route`);
|
|
399
|
+
}
|
|
325
400
|
return errors;
|
|
326
401
|
}
|
|
327
402
|
|
package/src/types.ts
CHANGED
|
@@ -81,17 +81,25 @@ export interface ResolvedProcessPiConfig {
|
|
|
81
81
|
availableToolNames: string[];
|
|
82
82
|
}
|
|
83
83
|
|
|
84
|
-
/** @
|
|
84
|
+
/** @public */
|
|
85
85
|
export type OutcomeToolParameterType = "string" | "number" | "array" | "boolean" | "object";
|
|
86
|
-
/** @internal */
|
|
87
|
-
export type OutcomeToolArrayItemType = Exclude<OutcomeToolParameterType, "array">;
|
|
88
86
|
|
|
89
|
-
/** @
|
|
87
|
+
/** JSON-schema-compatible value declaration nested below an outcome parameter. @public */
|
|
90
88
|
export interface OutcomeToolArrayItemSpec {
|
|
91
|
-
/** @
|
|
92
|
-
type:
|
|
93
|
-
/** @
|
|
89
|
+
/** @public */
|
|
90
|
+
type: OutcomeToolParameterType;
|
|
91
|
+
/** @public */
|
|
94
92
|
description?: string;
|
|
93
|
+
/** @public */
|
|
94
|
+
minItems?: number;
|
|
95
|
+
/** @public */
|
|
96
|
+
items?: OutcomeToolArrayItemSpec;
|
|
97
|
+
/** @public */
|
|
98
|
+
properties?: Record<string, OutcomeToolArrayItemSpec>;
|
|
99
|
+
/** @public */
|
|
100
|
+
required?: readonly string[];
|
|
101
|
+
/** @public */
|
|
102
|
+
additionalProperties?: boolean;
|
|
95
103
|
}
|
|
96
104
|
|
|
97
105
|
/** @public */
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/pi-config.ts","../src/types.ts"],"sourcesContent":["import { homedir } from \"node:os\";\nimport type { ConfigSnapshot } from \"@leitwerk-dev/protocol\";\nimport Mustache from \"mustache\";\nimport type { LlmTurnDefinition } from \"./define-process.js\";\nimport {\n\tPI_BUILT_IN_TOOL_NAMES,\n\ttype PiBuiltInToolName,\n\ttype ProcessPiConfig,\n\ttype ResolvedProcessPiConfig,\n} from \"./types.js\";\n\n/** @internal */\ntype TemplateScalar = string | number | boolean;\n/** @internal */\ntype TemplateValue = TemplateScalar | TemplateContext | readonly TemplateValue[] | undefined;\n\n/** @internal */\nexport interface TemplateContext {\n\t/** @internal */\n\t[key: string]: TemplateValue;\n}\n\nfunction isScalarValue(value: unknown): value is string | number | boolean {\n\treturn typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\";\n}\n\nfunction toTemplateContextRecord(value: unknown): TemplateContext {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\treturn {};\n\t}\n\tconst context: TemplateContext = {};\n\tfor (const [key, candidate] of Object.entries(value)) {\n\t\tif (isScalarValue(candidate)) {\n\t\t\tcontext[key] = candidate;\n\t\t}\n\t}\n\treturn context;\n}\n\n/** @internal */\nexport function createTemplateContext(input: {\n\t/** @internal */\n\tparams?: unknown;\n\t/** @internal */\n\tprocess?: {\n\t\t/** @internal */\n\t\tprocessId?: string | null;\n\t\t/** @internal */\n\t\texternalId?: string | null;\n\t\t/** @internal */\n\t\texternalUrl?: string | null;\n\t\t/** @internal */\n\t\tselectedTurnId?: string | null;\n\t};\n\t/** @internal */\n\tprojects?: ReadonlyArray<{\n\t\t/** @internal */\n\t\tkey: string;\n\t\t/** @internal */\n\t\trepoLocator: string;\n\t\t/** @internal */\n\t\tbaseBranch: string;\n\t\t/** @internal */\n\t\tworkBranch?: string | null;\n\t}>;\n}): TemplateContext {\n\tconst context: TemplateContext = {\n\t\t...toTemplateContextRecord(input.params),\n\t};\n\tif (input.process) {\n\t\tcontext.processId = input.process.processId ?? undefined;\n\t\tcontext.externalId = input.process.externalId ?? undefined;\n\t\tcontext.externalUrl = input.process.externalUrl ?? undefined;\n\t\tcontext.selectedTurnId = input.process.selectedTurnId ?? undefined;\n\t}\n\tconst firstProject = input.projects?.[0];\n\tif (firstProject) {\n\t\tcontext.projectKey = firstProject.key;\n\t\tcontext.repositoryUrl = firstProject.repoLocator;\n\t\tcontext.baseBranch = firstProject.baseBranch;\n\t\tcontext.workBranch = firstProject.workBranch ?? undefined;\n\t}\n\treturn context;\n}\n\n/** @internal */\nexport function interpolateTemplate(template: string, context: TemplateContext): string {\n\treturn Mustache.render(template, context);\n}\n\n/** @internal */\ntype TurnToolDefinitionLike =\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: \"llm\";\n\t\t\t/** @internal */\n\t\t\tavailableTools: readonly PiBuiltInToolName[];\n\t }\n\t| {\n\t\t\t/** @internal */\n\t\t\tkind: string;\n\t };\n\n/** @internal */\ntype ProcessTurnBindingLike = {\n\t/** @internal */\n\tdefinition: TurnToolDefinitionLike;\n};\n\n/** @internal */\ntype ProcessToolSource = TurnToolDefinitionLike | ProcessTurnBindingLike;\n\nfunction isTurnDefinitionSource(source: ProcessToolSource): source is TurnToolDefinitionLike {\n\treturn \"kind\" in source;\n}\n\nfunction resolveToolSourceDefinition(source: ProcessToolSource): TurnToolDefinitionLike {\n\treturn isTurnDefinitionSource(source) ? source : source.definition;\n}\n\n/** @internal */\nexport function validatePiBuiltInToolArray(\n\ttoolNames: readonly unknown[],\n\tcontext: string,\n): string[] {\n\tconst errors: string[] = [];\n\tconst seen = new Set<string>();\n\tfor (const rawName of toolNames) {\n\t\tif (typeof rawName !== \"string\") {\n\t\t\terrors.push(`${context} must contain only string tool names`);\n\t\t\tcontinue;\n\t\t}\n\t\tconst name = rawName.trim();\n\t\tif (name === \"\") {\n\t\t\terrors.push(`${context} must not contain empty tool names`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (name !== rawName) {\n\t\t\terrors.push(`${context} must use canonical Pi tool names without surrounding whitespace`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!PI_BUILT_IN_TOOL_NAMES.includes(name as PiBuiltInToolName)) {\n\t\t\terrors.push(\n\t\t\t\t`${context} references unknown Pi tool '${name}'. Expected one of ${PI_BUILT_IN_TOOL_NAMES.join(\", \")}`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (seen.has(name)) {\n\t\t\terrors.push(`${context} must not contain duplicate Pi tool '${name}'`);\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(name);\n\t}\n\treturn errors;\n}\n\n/** @internal */\nexport function resolveTurnAvailableToolNames(input: {\n\t/** @internal */\n\tturnId: string;\n\t/** @internal */\n\tturnDef: LlmTurnDefinition<string, unknown, unknown>;\n}): string[] {\n\tconst errors = validatePiBuiltInToolArray(\n\t\tinput.turnDef.availableTools,\n\t\t`turn '${input.turnId}' availableTools`,\n\t);\n\tif (errors.length > 0) {\n\t\tthrow new Error(errors.join(\"; \"));\n\t}\n\treturn [...input.turnDef.availableTools];\n}\n\n/** @internal */\nexport function collectProcessAvailableToolNames(\n\tturns: Iterable<ProcessToolSource> | undefined,\n): string[] {\n\tconst usedToolNames = new Set<PiBuiltInToolName>();\n\tfor (const source of turns ?? []) {\n\t\tconst definition = resolveToolSourceDefinition(source);\n\t\tif (definition.kind !== \"llm\" || !(\"availableTools\" in definition)) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst errors = validatePiBuiltInToolArray(definition.availableTools, \"LLM turn availableTools\");\n\t\tif (errors.length > 0) {\n\t\t\tthrow new Error(errors.join(\"; \"));\n\t\t}\n\t\tfor (const toolName of definition.availableTools) {\n\t\t\tusedToolNames.add(toolName);\n\t\t}\n\t}\n\treturn PI_BUILT_IN_TOOL_NAMES.filter((toolName) => usedToolNames.has(toolName));\n}\n\nconst DEFAULT_TOOL_DESCRIPTIONS: Record<PiBuiltInToolName, string> = {\n\tread: \"Read file contents\",\n\tbash: \"Execute bash commands (ls, grep, find, etc.)\",\n\tedit: \"Make surgical edits to files (find exact text and replace)\",\n\twrite: \"Create or overwrite files\",\n\tgrep: \"Search file contents\",\n\tfind: \"Find files by name/path\",\n\tls: \"List directory contents\",\n};\n\nfunction buildDefaultSystemPrompt(availableToolNames: readonly string[]): string {\n\tconst toolList =\n\t\tavailableToolNames.length > 0\n\t\t\t? availableToolNames\n\t\t\t\t\t.map((toolName) => {\n\t\t\t\t\t\tconst description =\n\t\t\t\t\t\t\tDEFAULT_TOOL_DESCRIPTIONS[toolName as PiBuiltInToolName] ?? \"Built-in Pi tool\";\n\t\t\t\t\t\treturn `- ${toolName}: ${description}`;\n\t\t\t\t\t})\n\t\t\t\t\t.join(\"\\n\")\n\t\t\t: \"- No built-in tools are available for this process unless a turn registers custom tools.\";\n\treturn `You are an expert coding assistant operating inside pi, a coding agent harness. You help users by using the tools made available for the active turn.\n\nAvailable built-in tools for this process:\n${toolList}\n\nIn addition to the tools above, you may have access to other custom tools depending on the active turn.\n\nGuidelines:\n- Use only tools that are available in the active turn.\n- Use read/search tools to examine files before editing.\n- Use edit for precise changes when it is available (old text must match exactly).\n- Use write only for new files or complete rewrites when it is available.\n- When summarizing your actions, output plain text directly - do NOT use cat or bash to display what you did.\n- Be concise in your responses.\n- Show file paths clearly when working with files.`;\n}\n\n/** @internal */\nexport function resolveProcessPiConfig(input: {\n\t/** @internal */\n\tprocessId: string;\n\t/** @internal */\n\tprocessPiConfig?: ProcessPiConfig;\n\t/** @internal */\n\tturns?: Iterable<ProcessToolSource>;\n\t/** @internal */\n\tconfigSnapshot?: ConfigSnapshot;\n\t/** @internal */\n\ttemplateContext: TemplateContext;\n}): ResolvedProcessPiConfig {\n\tconst processConfig = input.configSnapshot?.process_configs?.[input.processId];\n\tconst processPiOverride = processConfig?.pi;\n\tconst availableToolNames = collectProcessAvailableToolNames(input.turns);\n\n\tconst configSystemPromptTemplate = input.configSnapshot?.pi?.system_prompt_template;\n\tconst systemPromptTemplate =\n\t\tprocessPiOverride?.system_prompt_template ??\n\t\tinput.processPiConfig?.systemPromptTemplate ??\n\t\tconfigSystemPromptTemplate;\n\tconst appendSystemPromptTemplate =\n\t\tprocessPiOverride?.append_system_prompt_template ??\n\t\tinput.processPiConfig?.appendSystemPromptTemplate;\n\n\tconst resolvedSystemPrompt = systemPromptTemplate\n\t\t? interpolateTemplate(systemPromptTemplate, input.templateContext)\n\t\t: buildDefaultSystemPrompt(availableToolNames);\n\tconst sessionCwd = input.processPiConfig?.sessionCwdTemplate\n\t\t? interpolateTemplate(input.processPiConfig.sessionCwdTemplate, input.templateContext).trim()\n\t\t: undefined;\n\n\treturn {\n\t\tsystemPrompt: resolvedSystemPrompt,\n\t\tappendSystemPrompt: appendSystemPromptTemplate\n\t\t\t? interpolateTemplate(appendSystemPromptTemplate, input.templateContext)\n\t\t\t: undefined,\n\t\t...(sessionCwd ? { sessionCwd } : {}),\n\t\tavailableToolNames,\n\t};\n}\n\nexport { resolveTurnAvailableToolNames as resolveTurnActiveToolNames };\n\n// Mirror Pi's PI_CODING_AGENT_DIR expansion semantics from\n// pi-mono/packages/coding-agent/src/config.ts.\n/** @internal */\nexport function expandPiAgentDir(agentDir: string): string {\n\tif (agentDir === \"~\") {\n\t\treturn homedir();\n\t}\n\tif (agentDir.startsWith(\"~/\")) {\n\t\treturn homedir() + agentDir.slice(1);\n\t}\n\treturn agentDir;\n}\n\n/** @internal */\nexport function resolvePiAgentDir(options: {\n\t/** @internal */\n\tagentDir?: string | null;\n\t/** @internal */\n\tconfigSnapshot?: ConfigSnapshot;\n\t/** @internal */\n\tfallbackDir: string;\n}): string {\n\tconst configuredAgentDir =\n\t\ttypeof options.agentDir === \"string\" && options.agentDir.trim() !== \"\"\n\t\t\t? options.agentDir\n\t\t\t: typeof options.configSnapshot?.pi?.agent_dir === \"string\" &&\n\t\t\t\t\toptions.configSnapshot.pi.agent_dir.trim() !== \"\"\n\t\t\t\t? options.configSnapshot.pi.agent_dir\n\t\t\t\t: options.fallbackDir;\n\treturn expandPiAgentDir(configuredAgentDir);\n}\n","import type {\n\tTurnAcceptanceState as DomainTurnAcceptanceState,\n\tProcessTurnRecordPathType,\n\tProcessTurnTerminalLifecycleStatus,\n\tTurnId,\n} from \"@leitwerk-dev/domain\";\nimport type { UsageCostSnapshot, UsageTokenCounts } from \"@leitwerk-dev/protocol\";\n\n/** @internal */\nexport interface TurnOptions {\n\t/** @internal */\n\treset?: boolean;\n}\n\n/** @internal */\nexport interface TurnResult<T extends string = string> {\n\t/** @internal */\n\toutcome: T;\n\t/** @internal */\n\tparams: Record<string, unknown>;\n}\n\n/** @public */\nexport const PI_BUILT_IN_TOOL_NAMES = [\n\t\"read\",\n\t\"bash\",\n\t\"edit\",\n\t\"write\",\n\t\"grep\",\n\t\"find\",\n\t\"ls\",\n] as const;\n/** @public */\nexport type PiBuiltInToolName = (typeof PI_BUILT_IN_TOOL_NAMES)[number];\n\n/** Tool names owned by the worker runtime rather than an integration extension. @internal */\nexport const FRAMEWORK_LLM_TOOL_NAMES = [\n\t\"ask_questions\",\n\t\"markdown_result\",\n\t\"upload_result_images\",\n] as const;\n\n/** Names integration tools cannot use because Pi or the worker runtime owns them. @internal */\nexport const RESERVED_INTEGRATION_TOOL_NAMES = [\n\t...PI_BUILT_IN_TOOL_NAMES,\n\t...FRAMEWORK_LLM_TOOL_NAMES,\n] as const;\n\n/** @public */\nexport interface ProcessPiConfig {\n\t/**\n\t * System prompt template. Rendered with Mustache against runtime context.\n\t * Use {{variableName}} for escaped values and {{{variableName}}} for raw values.\n\t * When omitted, Pi's default system prompt is used.\n\t */\n\t/** @internal */\n\tsystemPromptTemplate?: string;\n\t/**\n\t * Additional text appended after the base system prompt/resources. Rendered\n\t * with Mustache against runtime context.\n\t */\n\t/** @public */\n\tappendSystemPromptTemplate?: string;\n\t/**\n\t * Code-defined Pi session working directory template. Rendered with Mustache\n\t * against runtime context. When omitted, the process workspace root is used.\n\t */\n\t/** @public */\n\tsessionCwdTemplate?: string;\n}\n\n/** @internal */\nexport interface ResolvedProcessPiConfig {\n\t/** @internal */\n\tsystemPrompt?: string;\n\t/** @internal */\n\tappendSystemPrompt?: string;\n\t/** @internal */\n\tsessionCwd?: string;\n\t/** @internal */\n\tavailableToolNames: string[];\n}\n\n/** @internal */\nexport type OutcomeToolParameterType = \"string\" | \"number\" | \"array\" | \"boolean\" | \"object\";\n/** @internal */\nexport type OutcomeToolArrayItemType = Exclude<OutcomeToolParameterType, \"array\">;\n\n/** @internal */\nexport interface OutcomeToolArrayItemSpec {\n\t/** @internal */\n\ttype: OutcomeToolArrayItemType;\n\t/** @internal */\n\tdescription?: string;\n}\n\n/** @public */\nexport interface OutcomeToolParameterSpec {\n\t/** @internal */\n\ttype: OutcomeToolParameterType;\n\t/** @internal */\n\tdescription: string;\n\t/** @internal */\n\trequired?: boolean;\n\t/** @internal */\n\trequiredErrorCode?: string;\n\t/** @internal */\n\tinvalidErrorCode?: string;\n\t/** @internal */\n\tminItems?: number;\n\t/** @internal */\n\tminItemsErrorCode?: string;\n\t/** @internal */\n\tminimum?: number;\n\t/** @internal */\n\tminimumErrorCode?: string;\n\t/** @internal */\n\titems?: OutcomeToolArrayItemSpec;\n\t/** @internal */\n\tenum?: readonly string[];\n}\n\n/** @internal */\nexport interface OutcomeToolSpec {\n\t/** @internal */\n\tdescription: string;\n\t/** @internal */\n\tparameters: Record<string, OutcomeToolParameterSpec>;\n\t/** Product published from this outcome's turn-result markdown, when selected. @internal */\n\tpublishedProduct?: string;\n\t/** Outcome parameter whose markdown value is captured as the turn result. @internal */\n\tturnResultMarkdownParameter?: string;\n\t/** Outcome parameter containing a concise operator-facing summary. @internal */\n\tresultSummaryParameter?: string;\n}\n\n/** @public */\nexport interface PiTreeEntry {\n\t/** @internal */\n\treadonly id: string;\n\t/** @internal */\n\treadonly parentId: string | null;\n\t/** @public */\n\treadonly type: string;\n\t/** @internal */\n\treadonly timestamp: string;\n\t/** @public */\n\treadonly message?: {\n\t\t/** @internal */\n\t\treadonly role?: string;\n\t\t/** @public */\n\t\treadonly content?: unknown;\n\t};\n\t/** Pi custom-message fields. Details are intentionally excluded from model context. @internal */\n\treadonly customType?: string;\n\t/** @public */\n\treadonly content?: unknown;\n\t/** @internal */\n\treadonly details?: unknown;\n\t/** @internal */\n\treadonly targetId?: string;\n\t/** @internal */\n\treadonly label?: string;\n}\n\n/** @internal */\nexport interface PiTreeNode {\n\t/** @internal */\n\treadonly entry: PiTreeEntry;\n\t/** @internal */\n\treadonly children: readonly PiTreeNode[];\n\t/** @internal */\n\treadonly label?: string;\n\t/** @internal */\n\treadonly labelTimestamp?: string;\n}\n\n/** @public */\nexport interface PiTurnExecutionResult {\n\t/** @internal */\n\tstartLeafId: string | null;\n\t/** @internal */\n\tendLeafId: string | null;\n\t/** @internal */\n\tcreatedEntryIds: string[];\n\t/** @internal */\n\tresultEntryId: string;\n\t/** Final assistant markdown captured from the Pi assistant message for this turn, when available. @internal */\n\tassistantMarkdown?: string | null;\n}\n\n/** @internal */\nexport type PiEventType =\n\t| \"turn.start\"\n\t| \"turn.end\"\n\t| \"stream.delta\"\n\t| \"tool.call\"\n\t| \"tool.update\"\n\t| \"tool.result\"\n\t| \"toolcall.start\"\n\t| \"toolcall.delta\"\n\t| \"toolcall.end\"\n\t| \"compaction.start\"\n\t| \"compaction.end\"\n\t| \"label.changed\"\n\t| \"error\"\n\t| \"retry.start\"\n\t| \"retry.end\"\n\t| \"usage\";\n\n/** @internal */\nexport interface PiEvent {\n\t/** @internal */\n\ttype: PiEventType;\n\t/** @internal */\n\tturnId: string;\n\t/** @internal */\n\tdata: Record<string, unknown>;\n\t/** @internal */\n\ttimestamp: string;\n}\n\n/** @internal */\nexport type PiEventHandler = (event: PiEvent) => void;\n\n/** @internal */\nexport type PiSessionDiagnosticLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\n/** @internal */\nexport interface PiSessionDiagnostic {\n\t/** @internal */\n\tlevel: PiSessionDiagnosticLevel;\n\t/** @internal */\n\tcode: string;\n\t/** @internal */\n\tmessage: string;\n\t/** @internal */\n\ttimestamp: string;\n\t/** @internal */\n\tturnId?: string;\n\t/** @internal */\n\tdetails?: Record<string, unknown>;\n}\n\n/** @internal */\nexport type PiSessionDiagnosticHandler = (diagnostic: PiSessionDiagnostic) => void;\n\n/** @public */\nexport interface PiCustomToolExecutionContext {\n\t/** Pi's identity for this exact invocation; stable across the paused call. @public */\n\ttoolCallId: string;\n\t/** Aborted when the active turn is stopped or torn down. @public */\n\tsignal: AbortSignal;\n\t/** Pause model-execution budgets while this custom tool awaits durable operator input. @internal */\n\tsuspendPromptGuards?: () => () => void;\n}\n\n/** @public */\nexport interface PiCustomTool {\n\t/** @public */\n\tname: string;\n\t/** @internal */\n\tdescription: string;\n\t/** @internal */\n\tparameters: Record<string, unknown>;\n\t/** @internal */\n\texecutionMode?: \"sequential\" | \"parallel\";\n\t/** @public */\n\texecute(args: Record<string, unknown>, context?: PiCustomToolExecutionContext): Promise<unknown>;\n}\n\n/** @internal */\nexport interface PiUsageData extends UsageTokenCounts {\n\t/** @internal */\n\tcost: UsageCostSnapshot;\n\t/** @internal */\n\tcacheHitRate: number;\n}\n\n/** @internal */\nexport interface PiRunDetails {\n\t/** @internal */\n\tloadedAgentsFiles: Array<{\n\t\t/** @internal */\n\t\tpath: string;\n\t\t/** @internal */\n\t\tsizeBytes: number;\n\t}>;\n\t/** @internal */\n\tloadedSkills: Array<{\n\t\t/** @internal */\n\t\tname: string;\n\t\t/** @internal */\n\t\tpath: string;\n\t}>;\n\t/** @internal */\n\tavailableToolNames: string[];\n}\n\n/** @internal */\nexport type ProcessCustomTool = PiCustomTool;\n\n/** @public */\nexport interface PiCustomMessageInput {\n\t/** @internal */\n\tcontent: string;\n\t/** @internal */\n\tdetails: unknown;\n\t/** @internal */\n\tdisplay?: boolean;\n}\n\n/** @internal */\nexport type PiTerminalAcknowledgementState =\n\t| \"open\"\n\t| \"outcome_accepted\"\n\t| \"acknowledgement_succeeded\"\n\t| \"acknowledgement_failed_ignored\";\n\n/** @internal */\nexport interface PiTerminalAcknowledgementControl {\n\t/** @internal */\n\treadonly timeoutMs: number;\n\t/** @internal */\n\tstate(): PiTerminalAcknowledgementState;\n\t/** @internal */\n\tisOperatorAbortRequested(): boolean;\n\t/** @internal */\n\tmarkSucceeded(): void;\n\t/** @internal */\n\tmarkFailed(reason: string): void;\n}\n\n/** @public */\nexport interface PiPromptOptions {\n\t/** @public */\n\ttools?: readonly PiCustomTool[];\n\t/** @internal */\n\tactiveTools?: readonly string[];\n\t/** @internal Runtime-only hook used by the worker Pi adapter before a tool executes. */\n\tshouldBlockToolCall?: (toolName: string) => string | null;\n\t/** @internal Guard suspension used by durable interactive tools. */\n\tsuspendPromptGuards?: () => () => void;\n\t/** @internal Runtime-only terminal outcome acknowledgement state. */\n\tterminalAcknowledgement?: PiTerminalAcknowledgementControl;\n}\n\n/** @public */\nexport interface PiTreeHandle {\n\t/** @internal */\n\treadonly sessionId: string;\n\t/** @internal */\n\treadonly treeFile: string;\n\t/** @internal */\n\treadonly isResumed: boolean;\n\n\t/** @internal */\n\tgetRunDetails(): PiRunDetails;\n\t/** @internal */\n\tgetLeafId(): string | null;\n\t/** @internal */\n\tgetEntry(id: string): PiTreeEntry | undefined;\n\t/** @internal */\n\tgetBranch(fromId?: string): PiTreeEntry[];\n\t/** @internal */\n\tgetChildren(parentId: string): PiTreeEntry[];\n\t/** @internal */\n\tgetTree(): PiTreeNode[];\n\t/** @internal */\n\tbranch(entryId: string): void | Promise<void>;\n\t/** @internal */\n\tbranchFromRoot(): void | Promise<void>;\n\t/** @internal */\n\tresetLeaf(): void | Promise<void>;\n\t/**\n\t * Compact the current Pi context. `details` is persisted with the resulting\n\t * compaction entry, but deliberately remains outside model context.\n\t */\n\t/** @internal */\n\tcompact?(customInstructions?: string, details?: unknown): Promise<unknown>;\n\t/** @public */\n\tprompt(text: string, options?: PiPromptOptions): Promise<PiTurnExecutionResult>;\n\t/** @public */\n\tpromptLiteral(text: string, options?: PiPromptOptions): Promise<PiTurnExecutionResult>;\n\t/** @public */\n\tpromptCustom(\n\t\tinput: PiCustomMessageInput,\n\t\toptions?: PiPromptOptions,\n\t): Promise<PiTurnExecutionResult>;\n\t/** @public */\n\tcontinueTurn(options?: PiPromptOptions): Promise<PiTurnExecutionResult>;\n\t/** @internal */\n\tappendCustomMessage?(input: PiCustomMessageInput): Promise<string>;\n\t/** @internal */\n\tsteer(text: string): Promise<void>;\n\t/** @internal */\n\tabortTurn(): Promise<void>;\n\t/** @internal */\n\tsubscribe(handler: PiEventHandler): () => void;\n\t/** @internal */\n\tsubscribeDiagnostics?(handler: PiSessionDiagnosticHandler): () => void;\n\t/** @internal */\n\tclose(): Promise<void>;\n}\n\n/** @public */\nexport const TURN_CONTEXT_MODES = [\"full\", \"compacted\", \"fresh\", \"fresh_seeded\"] as const;\n/** @public */\nexport type TurnContextMode = (typeof TURN_CONTEXT_MODES)[number];\n\n/** @public */\nexport const TURN_COMPLETION_MODES = [\"turn_end\"] as const;\n/** @public */\nexport type TurnCompletionMode = (typeof TURN_COMPLETION_MODES)[number];\n\n/** @public */\nexport type TurnBranchType = ProcessTurnRecordPathType;\n\n/** @public */\nexport interface TurnResultMarkdownNoneBehavior {\n\t/** @internal */\n\tmode: \"none\";\n}\n\n/** @public */\nexport interface TurnResultMarkdownAssistantOutputBehavior {\n\t/** @internal */\n\tmode: \"assistant_output\";\n\t/** @internal */\n\trequired?: boolean;\n}\n\n/** @public */\nexport interface TurnResultMarkdownToolCallBehavior {\n\t/** @internal */\n\tmode: \"tool_call\";\n\t/** @internal */\n\ttoolName: string;\n\t/** @internal */\n\tsource?: \"arguments\" | \"result\";\n\t/** @internal */\n\tpath: string;\n\t/** @internal */\n\trequired?: boolean;\n}\n\n/** @public */\nexport interface TurnResultMarkdownOutcomeToolArgumentBehavior {\n\t/** @internal */\n\tmode: \"outcome_tool_argument\";\n\t/** @internal */\n\tparameterName: string;\n\t/** @internal */\n\trequired?: boolean;\n}\n\n/** @public */\nexport type TurnResultMarkdownBehavior =\n\t| TurnResultMarkdownNoneBehavior\n\t| TurnResultMarkdownAssistantOutputBehavior\n\t| TurnResultMarkdownToolCallBehavior\n\t| TurnResultMarkdownOutcomeToolArgumentBehavior;\n\n/** @public */\nexport type TurnAcceptanceState = DomainTurnAcceptanceState;\n\n/** @public */\nexport interface ProcessActionSchedulingFixedTurnPreview {\n\t/** @public */\n\tkind: \"fixed_turn\";\n\t/** @public */\n\tturnId: TurnId | null;\n}\n\n/** @public */\nexport interface ProcessActionSchedulingTriggerPreview {\n\t/** @public */\n\tkind: \"trigger\";\n\t/** @internal */\n\ttrigger: string;\n}\n\n/** @public */\nexport interface ProcessActionSchedulingTerminalPreview {\n\t/** @public */\n\tkind: \"terminal\";\n\t/** @internal */\n\tlifecycleStatus: ProcessTurnTerminalLifecycleStatus;\n}\n\n/** @public */\nexport type ProcessActionSchedulingPreview =\n\t| ProcessActionSchedulingFixedTurnPreview\n\t| ProcessActionSchedulingTriggerPreview\n\t| ProcessActionSchedulingTerminalPreview;\n\n/** @public */\nexport type ProcessActionPreviewDefinition = ProcessActionSchedulingPreview;\n\n/** @internal */\nexport interface ProcessActionSchedulingDefinition {\n\t/** @internal */\n\tpreview: ProcessActionSchedulingPreview;\n}\n\n/** @internal */\nexport interface HumanTurnActionView {\n\t/** @internal */\n\tactionId: string;\n\t/** @internal */\n\tacceptanceState: TurnAcceptanceState;\n\t/** @internal */\n\tlabel?: string;\n\t/** @internal */\n\tdescription?: string;\n\t/** @internal */\n\tpreview?: ProcessActionPreviewDefinition;\n\t/** @internal */\n\tscheduling?: ProcessActionSchedulingDefinition;\n}\n\n/** @internal */\nexport interface HumanTurnNotesField {\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tlabel: string;\n\t/** @internal */\n\tdescription?: string;\n\t/** @internal */\n\tplaceholder?: string;\n\t/** @internal */\n\trequired?: boolean;\n}\n\n/** @internal */\nexport interface HumanTurnExternalTrigger {\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tactionId: string;\n\t/** @internal */\n\tlabel: string;\n\t/** @internal */\n\tdescription: string;\n}\n\n/** @internal */\nexport interface HumanTurnExternalActionView {\n\t/** Process-local arming id exposed to providers and UI. @internal */\n\tid: string;\n\t/** @internal */\n\texternalActionId: string;\n\t/** @internal */\n\tsourceKind: string;\n\t/** @internal */\n\tlabel: string | null;\n\t/** @internal */\n\tdescription: string | null;\n}\n\n/** @internal */\nexport interface EventBus<TEventMap extends object = Record<string, unknown>> {\n\t/** @internal */\n\temit<K extends keyof TEventMap & string>(event: K, data: TEventMap[K]): void;\n\t/** @internal */\n\ton<K extends keyof TEventMap & string>(\n\t\tevent: K,\n\t\thandler: (data: TEventMap[K]) => void | Promise<void>,\n\t): void;\n\t/** @internal */\n\toff<K extends keyof TEventMap & string>(\n\t\tevent: K,\n\t\thandler: (data: TEventMap[K]) => void | Promise<void>,\n\t): void;\n}\n"],"mappings":";AAAA,SAAS,eAAe;AAExB,OAAO,cAAc;;;ACqBd,IAAM,yBAAyB;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD;AAKO,IAAM,2BAA2B;AAAA,EACvC;AAAA,EACA;AAAA,EACA;AACD;AAGO,IAAM,kCAAkC;AAAA,EAC9C,GAAG;AAAA,EACH,GAAG;AACJ;;;ADxBA,SAAS,cAAc,OAAoD;AAC1E,SAAO,OAAO,UAAU,YAAY,OAAO,UAAU,YAAY,OAAO,UAAU;AACnF;AAEA,SAAS,wBAAwB,OAAi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