@juicesharp/rpiv-workflow 1.19.1 → 2.0.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.
- package/README.md +81 -8
- package/api.ts +18 -703
- package/audit-ctx.ts +103 -0
- package/audit-rows.ts +154 -0
- package/audit.ts +158 -190
- package/built-ins.ts +40 -45
- package/chain-state.ts +220 -0
- package/command-run.ts +64 -31
- package/command.ts +123 -21
- package/docs/workflow-authoring.md +356 -63
- package/{lifecycle.ts → events.ts} +161 -37
- package/execution-host.ts +75 -0
- package/host.ts +149 -64
- package/index.ts +25 -81
- package/internal-utils.ts +171 -71
- package/internal.ts +22 -1
- package/judge.ts +241 -0
- package/layers.ts +10 -15
- package/load/alias.ts +6 -12
- package/load/cache.ts +9 -6
- package/load/index.ts +27 -106
- package/load/issues.ts +31 -0
- package/load/legacy.ts +102 -0
- package/load/merge.ts +2 -2
- package/load/resolve-default.ts +3 -4
- package/load/shape-guards.ts +3 -6
- package/load/skill-contract-phase.ts +94 -0
- package/loop-constructors.ts +24 -0
- package/loop-def.ts +285 -0
- package/loop-kinds.ts +750 -0
- package/loop-parallel.ts +250 -0
- package/loop-waves.ts +99 -0
- package/loop.ts +330 -0
- package/loops/constructors.ts +334 -0
- package/loops/derivations.ts +65 -0
- package/loops/introspection.ts +184 -0
- package/loops/panel.ts +196 -0
- package/loops/verify.ts +99 -0
- package/messages.ts +249 -156
- package/outcomes/collectors/directory-path.ts +7 -3
- package/outcomes/collectors/index.ts +1 -0
- package/outcomes/collectors/require-opt.ts +11 -0
- package/outcomes/collectors/text-scan.ts +47 -0
- package/outcomes/collectors/tool-call.ts +8 -3
- package/outcomes/collectors/transcript-path.ts +4 -18
- package/outcomes/collectors/union.ts +30 -10
- package/outcomes/collectors/url.ts +9 -14
- package/outcomes/collectors/workspace-diff.ts +21 -14
- package/outcomes/exec.ts +17 -0
- package/outcomes/git-commit.ts +190 -100
- package/outcomes/index.ts +1 -0
- package/outcomes/parsers/json-body.ts +2 -2
- package/outcomes/side-effect.ts +3 -3
- package/output-spec.ts +36 -10
- package/output.ts +98 -20
- package/package.json +27 -11
- package/predicates.ts +11 -8
- package/preview.ts +81 -21
- package/registration.ts +117 -36
- package/routing-dsl.ts +322 -0
- package/routing.ts +48 -2
- package/runner/by-name.ts +2 -1
- package/runner/by-run-id.ts +2 -1
- package/runner/chain-advance.ts +84 -56
- package/runner/errors.ts +10 -0
- package/runner/failure.ts +163 -0
- package/runner/index.ts +7 -13
- package/runner/input-validation.ts +16 -23
- package/runner/preflight.ts +169 -0
- package/runner/resolve-stage.ts +68 -0
- package/runner/resume-entry.ts +121 -0
- package/runner/resume-loop.ts +131 -0
- package/runner/resume.ts +368 -262
- package/runner/run-context.ts +165 -0
- package/runner/run-stage.ts +490 -0
- package/runner/runner.ts +202 -449
- package/runner/script-stage.ts +104 -112
- package/schema-compat.ts +12 -1
- package/semaphore.ts +55 -0
- package/sessions/extraction.ts +146 -81
- package/sessions/halt-routing.ts +195 -0
- package/sessions/index.ts +3 -1
- package/sessions/locate.ts +141 -0
- package/sessions/reattach.ts +71 -0
- package/sessions/sessions.ts +114 -199
- package/sessions/spawn.ts +132 -119
- package/sessions/success-persist.ts +89 -0
- package/skill-contract.ts +22 -25
- package/skill-contracts/composition.ts +86 -37
- package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
- package/skill-contracts/harvest.ts +4 -4
- package/skill-contracts/index.ts +15 -8
- package/skill-contracts/registry.ts +33 -50
- package/stage-def.ts +595 -0
- package/stage-errors.ts +84 -0
- package/stage-identity.ts +56 -0
- package/startup.ts +4 -1
- package/state/index.ts +8 -1
- package/state/names.ts +91 -65
- package/state/paths.ts +20 -0
- package/state/raw.ts +77 -0
- package/state/reads.ts +103 -85
- package/state/resolve.ts +73 -0
- package/state/state.ts +135 -15
- package/state/writes.ts +29 -12
- package/transcript.ts +24 -0
- package/triggers.ts +11 -3
- package/types.ts +290 -78
- package/validate/contract-compat.ts +198 -0
- package/validate/graph.ts +134 -0
- package/validate/issue.ts +328 -0
- package/validate/stage-rules.ts +499 -0
- package/validate-output.ts +82 -7
- package/validate-workflow.ts +57 -759
- package/validation-bounds.ts +35 -0
- package/control-flow.ts +0 -135
- package/fanout.ts +0 -102
- package/iterate.ts +0 -155
- package/load/cache.test.ts +0 -82
- package/load/shape-guards.test.ts +0 -74
- package/outcomes/collectors/directory-path.test.ts +0 -64
- package/outcomes/collectors/tool-call.test.ts +0 -110
- package/outcomes/collectors/transcript-path.test.ts +0 -70
- package/outcomes/collectors/union.test.ts +0 -59
- package/outcomes/collectors/url.test.ts +0 -67
- package/outcomes/collectors/workspace-diff.test.ts +0 -107
- package/outcomes/git-commit.test.ts +0 -194
- package/outcomes/parsers/json-body.test.ts +0 -80
- package/runner/by-name.test.ts +0 -95
- package/runner/by-run-id.test.ts +0 -115
- package/runner/resume-fanout.test.ts +0 -331
- package/runner/resume-fanout.ts +0 -136
- package/runner/resume-iterate.test.ts +0 -444
- package/runner/resume-iterate.ts +0 -111
- package/runner/resume.test.ts +0 -1130
- package/runner/stage-lifecycle.ts +0 -500
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* disposer; multiple registrations fan out per event.
|
|
12
12
|
*
|
|
13
13
|
* Every event fires AFTER the corresponding JSONL row lands on disk
|
|
14
|
-
* (onStageEnd / onStageError / onRoute /
|
|
14
|
+
* (onStageEnd / onStageError / onRoute / onUnitEnd). Listeners
|
|
15
15
|
* thus see consistent state when they read past rows via
|
|
16
16
|
* `readLastStage` / `readAllStages`.
|
|
17
17
|
*
|
|
@@ -26,17 +26,17 @@
|
|
|
26
26
|
* caller through the existing path.
|
|
27
27
|
*/
|
|
28
28
|
|
|
29
|
-
import type {
|
|
29
|
+
import type { CapPolicy, Unit, UnitRole } from "./api.js";
|
|
30
|
+
import { formatError, globalSlot } from "./internal-utils.js";
|
|
30
31
|
import { MSG_LIFECYCLE_THREW } from "./messages.js";
|
|
31
|
-
import type { Output } from "./output.js";
|
|
32
|
-
import type { RunWorkflowResult } from "./runner/runner.js";
|
|
32
|
+
import type { Output, RunView } from "./output.js";
|
|
33
33
|
import type { RunTrigger } from "./triggers.js";
|
|
34
|
-
import type {
|
|
34
|
+
import type { RunWorkflowResult } from "./types.js";
|
|
35
35
|
|
|
36
36
|
/**
|
|
37
37
|
* Run-scoped context shared by every lifecycle callback. Mirrors the
|
|
38
38
|
* shape `EdgeContext` and `FanoutContext` already use (frozen identity
|
|
39
|
-
* + `
|
|
39
|
+
* + the deep-readonly `RunView`) so listeners reconstruct "where am I" without
|
|
40
40
|
* widening the per-event payload.
|
|
41
41
|
*/
|
|
42
42
|
export interface LifecycleContext {
|
|
@@ -46,7 +46,22 @@ export interface LifecycleContext {
|
|
|
46
46
|
totalStages: number;
|
|
47
47
|
/** What triggered this run; defaulted at `runWorkflow` entry if `options.trigger` was omitted. */
|
|
48
48
|
trigger: RunTrigger;
|
|
49
|
-
state:
|
|
49
|
+
state: RunView;
|
|
50
|
+
/**
|
|
51
|
+
* Distinct stage names already executed in this run — the engine's
|
|
52
|
+
* authoritative `RunContext.visited`, RECONSTRUCTED from the JSONL trail on a
|
|
53
|
+
* resume. Populated only on the run-level projection (`lifecycleCtxFor`, which
|
|
54
|
+
* backs `onWorkflowStart`/`onWorkflowEnd`, script-stage `onStageStart`, and the
|
|
55
|
+
* loop/route fires); UNDEFINED on session-fired events (`lifecycleCtxFromSession`
|
|
56
|
+
* carries `runIdentity` only, never the live visited set).
|
|
57
|
+
*
|
|
58
|
+
* Exists so a status-line bridge can SEED its own distinct-visited accumulator
|
|
59
|
+
* at `onWorkflowStart`: a resumed run kicks the chain at its reconstructed walk
|
|
60
|
+
* position (a deep `stageNumber`), but only re-fires per-stage events from that
|
|
61
|
+
* point forward — without this, the bridge would recount `visited` from zero and
|
|
62
|
+
* a near-done resume would render a misleadingly tiny `visited/totalStages`.
|
|
63
|
+
*/
|
|
64
|
+
visited?: readonly string[];
|
|
50
65
|
}
|
|
51
66
|
|
|
52
67
|
/**
|
|
@@ -63,13 +78,55 @@ export type StageRef =
|
|
|
63
78
|
| { kind: "skill"; name: string; stageNumber: number; skill: string }
|
|
64
79
|
| { kind: "script"; name: string; stageNumber: number };
|
|
65
80
|
|
|
81
|
+
/**
|
|
82
|
+
* Payload for `onLoopStart`. `units` is present only when the loop
|
|
83
|
+
* precomputes its unit list (fanout) — pull loops (iterate/assess) discover
|
|
84
|
+
* units one at a time, so listeners observe them via `onUnitStart`.
|
|
85
|
+
* `kind: "verify"` is a verify-bearing stage (a desugared attempt→verify
|
|
86
|
+
* loop) — verified stages follow loop semantics: observe units, not
|
|
87
|
+
* `onStageEnd`.
|
|
88
|
+
*/
|
|
89
|
+
export interface LoopStartInfo {
|
|
90
|
+
kind: "fanout" | "iterate" | "assess" | "verify";
|
|
91
|
+
units?: readonly Unit[];
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Per-unit event payload. `skill` is the unit's DISPATCHED skill body — the
|
|
96
|
+
* parent stage's skill for produce units, the judge's own skill (or the
|
|
97
|
+
* synthetic `<parent>-judge` label for prompt judges) for judge units — so a
|
|
98
|
+
* model-override listener can resolve a per-unit model through the existing
|
|
99
|
+
* `models.json` cascade (`skills.<name>`) without new configuration axes.
|
|
100
|
+
*/
|
|
101
|
+
export interface UnitEvent {
|
|
102
|
+
role: UnitRole;
|
|
103
|
+
/** 0-based generation cursor (== the round index for assess loops). */
|
|
104
|
+
index: number;
|
|
105
|
+
/** Stable audit identity (`unit.id ?? unit.label`); undefined for assess units. */
|
|
106
|
+
unitId?: string;
|
|
107
|
+
/** Display tag (`"phase 2/5"`, `"r0·judge"`). */
|
|
108
|
+
label: string;
|
|
109
|
+
/** Dispatched skill body. */
|
|
110
|
+
skill: string;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Payload for `onLoopCap` — fired when a loop's effective cap trips. */
|
|
114
|
+
export interface LoopCapInfo {
|
|
115
|
+
kind: LoopStartInfo["kind"];
|
|
116
|
+
/** Units run (fanout/iterate) or rounds run (assess) when the cap tripped. */
|
|
117
|
+
count: number;
|
|
118
|
+
/** The effective cap: `min(loop.max, run.maxIterations)`. */
|
|
119
|
+
max: number;
|
|
120
|
+
policy: CapPolicy;
|
|
121
|
+
}
|
|
122
|
+
|
|
66
123
|
/**
|
|
67
124
|
* Opt-in lifecycle listeners. Single subscriber per slot per bundle —
|
|
68
125
|
* fan-out is a userland wrapper. Every callback may return a Promise;
|
|
69
126
|
* the runner awaits it before advancing (back-pressure for free).
|
|
70
127
|
*
|
|
71
128
|
* Every event fires AFTER its corresponding JSONL row lands on disk
|
|
72
|
-
* (onStageEnd / onStageError / onRoute /
|
|
129
|
+
* (onStageEnd / onStageError / onRoute / onUnitEnd), so a
|
|
73
130
|
* listener that calls `readLastStage(cwd, ctx.runId)` from inside the
|
|
74
131
|
* callback is guaranteed to observe the just-recorded row.
|
|
75
132
|
*
|
|
@@ -88,8 +145,11 @@ export type StageRef =
|
|
|
88
145
|
* onStageRetry: (stage, attempt) => console.warn(` ⟲ ${stage.name} retry #${attempt}`),
|
|
89
146
|
* onStageError: (stage, error) => console.error(` ✗ ${stage.name}: ${error}`),
|
|
90
147
|
* onRoute: (from, to) => console.log(` ↪ ${from.name} → ${to}`),
|
|
91
|
-
*
|
|
92
|
-
*
|
|
148
|
+
* onLoopStart: (stage, info) => console.log(` ⇉ ${stage.name} [${info.kind}]`),
|
|
149
|
+
* onUnitStart: (stage, u) => console.log(` → ${u.label} (${u.role})`),
|
|
150
|
+
* onUnitEnd: (stage, u) => console.log(` · ${stage.name} #${u.index}`),
|
|
151
|
+
* onUnitHalt: (stage, u, reason) => console.warn(` ✗ ${stage.name} #${u.index}: ${reason}`),
|
|
152
|
+
* onLoopCap: (stage, c) => console.warn(` ⚠ ${stage.name} capped at ${c.max}`),
|
|
93
153
|
* onWorkflowEnd: (result) =>
|
|
94
154
|
* console.log(result.success ? "✓ done" : `✗ ${result.error ?? "halted"}`),
|
|
95
155
|
* };
|
|
@@ -123,22 +183,44 @@ export interface LifecycleListeners {
|
|
|
123
183
|
/** After the stage's "failed"/"aborted" row lands in JSONL. Terminal for the run. */
|
|
124
184
|
onStageError?(stage: StageRef, error: string, ctx: LifecycleContext): void | Promise<void>;
|
|
125
185
|
|
|
126
|
-
/**
|
|
127
|
-
|
|
186
|
+
/**
|
|
187
|
+
* After an `EdgeFn` picks and its routing-decision row lands. `to` may be the
|
|
188
|
+
* `STOP` sentinel literal `"stop"`. `bypassed` lists the decision edge's
|
|
189
|
+
* not-taken RECOVERY arms — failure loops the chosen arm skipped for good (see
|
|
190
|
+
* `bypassedRecoveryArms` in routing.ts). A progress listener credits them so
|
|
191
|
+
* the bar reaches full while the terminal stage runs; empty for deterministic
|
|
192
|
+
* (string) edges and gates with no loop-back alternative.
|
|
193
|
+
*/
|
|
194
|
+
onRoute?(from: StageRef, to: string, ctx: LifecycleContext, bypassed?: readonly string[]): void | Promise<void>;
|
|
195
|
+
|
|
196
|
+
/** After `onStageStart`, before unit 1's session (after the unit list is computed for fanout). */
|
|
197
|
+
onLoopStart?(stage: StageRef, info: LoopStartInfo, ctx: LifecycleContext): void | Promise<void>;
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Per unit, BEFORE the unit's session opens — fired uniformly for produce
|
|
201
|
+
* AND judge units (closing the judge pre-session gap). This is the seam a
|
|
202
|
+
* model-override listener flips `pi.setModel` on; units run strictly
|
|
203
|
+
* sequentially, so the global flip is race-free.
|
|
204
|
+
*/
|
|
205
|
+
onUnitStart?(stage: StageRef, unit: UnitEvent, ctx: LifecycleContext): void | Promise<void>;
|
|
128
206
|
|
|
129
|
-
/**
|
|
130
|
-
|
|
207
|
+
/** Per unit, after the unit's JSONL row lands. Loop units never fire `onStageEnd`. */
|
|
208
|
+
onUnitEnd?(stage: StageRef, unit: UnitEvent, output: Output, ctx: LifecycleContext): void | Promise<void>;
|
|
131
209
|
|
|
132
|
-
/**
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
210
|
+
/**
|
|
211
|
+
* Per unit, after a collect-all fanout unit's NON-TERMINAL `collected:true`
|
|
212
|
+
* failed row lands — the unit halted but the run survives (the synthesis fold
|
|
213
|
+
* skips its sentinel slot). Fired ONLY on the soft-halt path; a fail-fast unit
|
|
214
|
+
* fires `onStageError` (terminal) instead, and a successful unit fires
|
|
215
|
+
* `onUnitEnd`. Distinct from both so a lane surface can flip the unit's sub-row
|
|
216
|
+
* ✗ rather than leaving it to spin (then be swept ✓ at `onWorkflowEnd`).
|
|
217
|
+
* `reason` is the halt cause — the same text the `collected:true` row's
|
|
218
|
+
* `errMsg` carries.
|
|
219
|
+
*/
|
|
220
|
+
onUnitHalt?(stage: StageRef, unit: UnitEvent, reason: string, ctx: LifecycleContext): void | Promise<void>;
|
|
139
221
|
|
|
140
|
-
/**
|
|
141
|
-
|
|
222
|
+
/** After an `onCap: "advance"` trip — fired after the `{type:"loop-cap"}` telemetry row append attempt. */
|
|
223
|
+
onLoopCap?(stage: StageRef, info: LoopCapInfo, ctx: LifecycleContext): void | Promise<void>;
|
|
142
224
|
|
|
143
225
|
/** Last call — `result` is the same envelope `runWorkflow` returns. */
|
|
144
226
|
onWorkflowEnd?(result: RunWorkflowResult, ctx: LifecycleContext): void | Promise<void>;
|
|
@@ -180,8 +262,7 @@ export class LifecycleDispatcher {
|
|
|
180
262
|
try {
|
|
181
263
|
await (fn as (...a: unknown[]) => unknown)(...(args as unknown[]));
|
|
182
264
|
} catch (e) {
|
|
183
|
-
|
|
184
|
-
host.ui.notify(MSG_LIFECYCLE_THREW(event, reason), "warning");
|
|
265
|
+
host.ui.notify(MSG_LIFECYCLE_THREW(event, formatError(e)), "warning");
|
|
185
266
|
}
|
|
186
267
|
}
|
|
187
268
|
}
|
|
@@ -198,17 +279,7 @@ export class LifecycleDispatcher {
|
|
|
198
279
|
*/
|
|
199
280
|
const REGISTRY_KEY = Symbol.for("@juicesharp/rpiv-workflow:lifecycle");
|
|
200
281
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
function getRegistry(): LifecycleListeners[] {
|
|
204
|
-
const g = globalThis as unknown as Global;
|
|
205
|
-
let registry = g[REGISTRY_KEY] as LifecycleListeners[] | undefined;
|
|
206
|
-
if (!registry) {
|
|
207
|
-
registry = [];
|
|
208
|
-
g[REGISTRY_KEY] = registry;
|
|
209
|
-
}
|
|
210
|
-
return registry;
|
|
211
|
-
}
|
|
282
|
+
const getRegistry = globalSlot(REGISTRY_KEY, () => [] as LifecycleListeners[]);
|
|
212
283
|
|
|
213
284
|
/**
|
|
214
285
|
* Register a cross-package lifecycle-listener bundle. Returns a disposer
|
|
@@ -258,11 +329,64 @@ export function buildLifecycleContext(args: {
|
|
|
258
329
|
workflow: string;
|
|
259
330
|
totalStages: number;
|
|
260
331
|
trigger: RunTrigger;
|
|
261
|
-
state:
|
|
332
|
+
state: RunView;
|
|
333
|
+
visited?: readonly string[];
|
|
262
334
|
}): LifecycleContext {
|
|
263
335
|
return args;
|
|
264
336
|
}
|
|
265
337
|
|
|
338
|
+
/**
|
|
339
|
+
* Build a `LifecycleContext` from the current `RunContext` (typed
|
|
340
|
+
* structurally so this base-layer module never imports the runtime types).
|
|
341
|
+
* Captured per fire so listeners always see the latest `state` snapshot.
|
|
342
|
+
* THE one RunContext → LifecycleContext projection — the runner, the loop
|
|
343
|
+
* driver, and the resume entries all share it; no per-module clones to keep
|
|
344
|
+
* aligned by convention.
|
|
345
|
+
*/
|
|
346
|
+
export function lifecycleCtxFor(run: {
|
|
347
|
+
cwd: string;
|
|
348
|
+
runId: string;
|
|
349
|
+
workflow: { name: string };
|
|
350
|
+
totalStages: number;
|
|
351
|
+
trigger: RunTrigger;
|
|
352
|
+
state: RunView;
|
|
353
|
+
visited: ReadonlySet<string>;
|
|
354
|
+
}): LifecycleContext {
|
|
355
|
+
return buildLifecycleContext({
|
|
356
|
+
cwd: run.cwd,
|
|
357
|
+
runId: run.runId,
|
|
358
|
+
workflow: run.workflow.name,
|
|
359
|
+
totalStages: run.totalStages,
|
|
360
|
+
trigger: run.trigger,
|
|
361
|
+
state: run.state,
|
|
362
|
+
// Snapshot the live set — listeners must not mutate the engine's accumulator,
|
|
363
|
+
// and a fired ctx is captured per fire so a later `visited.add` is irrelevant.
|
|
364
|
+
visited: [...run.visited],
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* Build a `LifecycleContext` from any SessionContext/AuditCtx-shaped object
|
|
370
|
+
* (cwd + runId + the frozen `runIdentity` + live state). The session, audit,
|
|
371
|
+
* and extraction layers all fire through this projection instead of
|
|
372
|
+
* re-spelling the six-field literal.
|
|
373
|
+
*/
|
|
374
|
+
export function lifecycleCtxFromSession(s: {
|
|
375
|
+
cwd: string;
|
|
376
|
+
runId: string;
|
|
377
|
+
runIdentity: { workflow: string; totalStages: number; trigger: RunTrigger };
|
|
378
|
+
state: RunView;
|
|
379
|
+
}): LifecycleContext {
|
|
380
|
+
return buildLifecycleContext({
|
|
381
|
+
cwd: s.cwd,
|
|
382
|
+
runId: s.runId,
|
|
383
|
+
workflow: s.runIdentity.workflow,
|
|
384
|
+
totalStages: s.runIdentity.totalStages,
|
|
385
|
+
trigger: s.runIdentity.trigger,
|
|
386
|
+
state: s.state,
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
|
|
266
390
|
/** Build the `"skill"` arm of `StageRef`. */
|
|
267
391
|
export function skillStageRef(name: string, stageNumber: number, skill: string): StageRef {
|
|
268
392
|
return { kind: "skill", name, stageNumber, skill };
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Execution-host injection seam. The /wf launcher + runner are Pi-agnostic; the
|
|
3
|
+
* SDK-backed executor (`SdkWorkflowHost`) lives in rpiv-pi. rpiv-pi registers a
|
|
4
|
+
* provider at startup; `runWorkflow` looks it up, builds the executor from the
|
|
5
|
+
* live observer ctx, and threads it for stage execution (the executor relays UI
|
|
6
|
+
* back to the live session). Absent provider ⇒ the live ctx executes directly
|
|
7
|
+
* (graceful degrade for non-Pi embedders / tests).
|
|
8
|
+
*/
|
|
9
|
+
import type { ModelSelection, WorkflowHostContext } from "./host.js";
|
|
10
|
+
import { globalSlot } from "./internal-utils.js";
|
|
11
|
+
|
|
12
|
+
/** What the provider hands back per run: the detached executor, an optional
|
|
13
|
+
* cancellation `signal` (rpiv-pi wires it from `ctx.ui.onTerminalInput`),
|
|
14
|
+
* and a `dispose` the runner calls in `finally` to unsubscribe the keystroke
|
|
15
|
+
* tap. `signal`/`dispose` are absent in headless mode (no UI ⇒ no abort). */
|
|
16
|
+
export interface WorkflowExecution {
|
|
17
|
+
host: WorkflowHostContext;
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
dispose?: () => void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface WorkflowExecutionProvider {
|
|
23
|
+
/** Build the detached executor host (+ abort signal/teardown) from the live
|
|
24
|
+
* observer ctx + run identity. `childSessionsDir` is the RESOLVED run-scoped
|
|
25
|
+
* session dir — the runner computes it from its internal layout helper so
|
|
26
|
+
* rpiv-pi never imports a layout function across the package boundary. */
|
|
27
|
+
createHost(
|
|
28
|
+
observer: WorkflowHostContext,
|
|
29
|
+
opts: {
|
|
30
|
+
runId: string;
|
|
31
|
+
childSessionsDir: string;
|
|
32
|
+
name?: string;
|
|
33
|
+
/** Workflow name — lets the lane dock render a `workflow:` tag. Threaded
|
|
34
|
+
* from workflow.name (run path) / header.workflow (resume path). */
|
|
35
|
+
workflow?: string;
|
|
36
|
+
/** The run's original `/wf` input (the user prompt) — the dock renders it as the
|
|
37
|
+
* descriptor label when no `--name` alias is set. Threaded from options.input /
|
|
38
|
+
* header.input. */
|
|
39
|
+
input?: string;
|
|
40
|
+
},
|
|
41
|
+
): WorkflowExecution | Promise<WorkflowExecution>;
|
|
42
|
+
/** Per-stage model resolution (rpiv-pi's resolveStageModel) — threaded onto
|
|
43
|
+
* RunContext.resolveModel so the dispatcher fills each child's ModelSelection. */
|
|
44
|
+
resolveModel?(id: { stage: string; skill: string }): ModelSelection | undefined;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Use the SAME globalThis[Symbol.for(...)] slot mechanism as
|
|
48
|
+
// `registerLifecycle`/the built-in registry (internal-utils.globalSlot), NOT a
|
|
49
|
+
// plain module-level `let`. rpiv-pi reaches this seam via a dynamic
|
|
50
|
+
// `import("@juicesharp/rpiv-workflow/startup")` while the runner reaches it via a
|
|
51
|
+
// static `../execution-host.js`; if those ever resolve to two module instances
|
|
52
|
+
// of rpiv-workflow (peer-dependency duplication), a module-local `let` would put
|
|
53
|
+
// `register` and `get` on DIFFERENT slots and the lookup would silently return
|
|
54
|
+
// `undefined` (degrade-to-live — a quiet correctness bug, not a crash). A
|
|
55
|
+
// process-global Symbol slot is instance-independent and matches the precedent
|
|
56
|
+
// this seam claims to mirror.
|
|
57
|
+
//
|
|
58
|
+
// globalSlot signature: `globalSlot<T>(key: symbol, init: () => T): () => T` — a
|
|
59
|
+
// lazily-initialised getter. Because the provider must be resettable to
|
|
60
|
+
// `undefined` (and globalSlot never re-runs init once seeded), anchor a MUTABLE
|
|
61
|
+
// BOX, exactly like the lifecycle flush-box pattern (internal-utils.ts).
|
|
62
|
+
const getProviderBox = globalSlot(Symbol.for("@juicesharp/rpiv-workflow:executionHostProvider"), () => ({
|
|
63
|
+
provider: undefined as WorkflowExecutionProvider | undefined,
|
|
64
|
+
}));
|
|
65
|
+
|
|
66
|
+
export function registerWorkflowExecutionHost(p: WorkflowExecutionProvider): void {
|
|
67
|
+
getProviderBox().provider = p;
|
|
68
|
+
}
|
|
69
|
+
export function getWorkflowExecutionProvider(): WorkflowExecutionProvider | undefined {
|
|
70
|
+
return getProviderBox().provider;
|
|
71
|
+
}
|
|
72
|
+
/** Test reset — re-exported from `internal.ts` and called in `test/setup.ts` beforeEach. */
|
|
73
|
+
export function __resetWorkflowExecutionHost(): void {
|
|
74
|
+
getProviderBox().provider = undefined;
|
|
75
|
+
}
|
package/host.ts
CHANGED
|
@@ -3,108 +3,193 @@
|
|
|
3
3
|
* environment, expressed in workflow-domain vocabulary.
|
|
4
4
|
*
|
|
5
5
|
* The package never re-exports `@earendil-works/pi-coding-agent` types
|
|
6
|
-
* from its public surface.
|
|
7
|
-
* / `ReplacedSessionContext` structurally satisfy these ports, so
|
|
8
|
-
* embedders pass their Pi handles directly without casting; consumers
|
|
9
|
-
* wanting to drive the runtime from a non-Pi adapter implement these two
|
|
10
|
-
* interfaces.
|
|
6
|
+
* from its public surface. Two host shapes implement these ports:
|
|
11
7
|
*
|
|
12
|
-
* -
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
* `withSession`.
|
|
8
|
+
* - The interactive Pi launcher (`ExtensionCommandContext`) — satisfies the
|
|
9
|
+
* OBSERVER surface (`ui`/`sessionManager`/`hasUI`/`waitForIdle`) and is
|
|
10
|
+
* retained as a progress observer only; it no longer executes stages.
|
|
11
|
+
* - The detached executor host (`SdkWorkflowHost`, in rpiv-pi) — satisfies the
|
|
12
|
+
* FULL surface including `spawnChild`/`maxConcurrency`; it owns the child
|
|
13
|
+
* `AgentSession` pool every stage runs in.
|
|
19
14
|
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
15
|
+
* - `WorkflowHost` — registry-level host (default-export ctor +
|
|
16
|
+
* skill-registration preflight).
|
|
17
|
+
* - `WorkflowHostContext` — per-command ctx passed into `runWorkflow`; spawns
|
|
18
|
+
* child sessions and never swaps itself out.
|
|
19
|
+
*
|
|
20
|
+
* Compile-time tripwire: `host.test.ts` asserts Pi's concrete observer types
|
|
21
|
+
* extend the observer surface; `rpiv-pi`'s `sdk-workflow-host.test.ts` asserts
|
|
22
|
+
* `SdkWorkflowHost` satisfies the full executor port (the satisfaction
|
|
23
|
+
* assertion lives there because rpiv-workflow must not import rpiv-pi).
|
|
23
24
|
*/
|
|
24
25
|
|
|
25
26
|
/**
|
|
26
|
-
* Registry-level host. Default-exported function receives this; the
|
|
27
|
-
*
|
|
28
|
-
* already-streaming agent) and for skill-registration preflight.
|
|
27
|
+
* Registry-level host. Default-exported function receives this; the runner
|
|
28
|
+
* uses it for skill-registration preflight (enumerating registered commands).
|
|
29
29
|
*
|
|
30
|
-
* The
|
|
31
|
-
*
|
|
30
|
+
* The two methods we touch on Pi's `ExtensionAPI`. Anything beyond these is
|
|
31
|
+
* invisible to the runtime. (`sendUserMessage` was removed with the
|
|
32
|
+
* continue-policy host-fallback ladder — every stage now holds a live child
|
|
33
|
+
* ctx, so the registry-level sender has no caller.)
|
|
32
34
|
*/
|
|
33
35
|
export interface WorkflowHost {
|
|
34
|
-
/** Register a slash command. Used by the `/wf` entry point.
|
|
36
|
+
/** Register a slash command. Used by the `/wf` entry point. The handler
|
|
37
|
+
* receives the LAUNCHER ctx (observer surface) — the interactive Pi
|
|
38
|
+
* `ExtensionCommandContext` Pi delivers; it constructs the executor host
|
|
39
|
+
* that actually runs stages. Typing the ctx as the executor
|
|
40
|
+
* `WorkflowHostContext` here would demand `spawnChild`/`maxConcurrency` of
|
|
41
|
+
* Pi's ctx and break the `host.test.ts` tripwire (Pi's ctx is an OBSERVER). */
|
|
35
42
|
registerCommand(
|
|
36
43
|
name: string,
|
|
37
44
|
options: {
|
|
38
45
|
description?: string;
|
|
39
|
-
handler: (args: string, ctx:
|
|
46
|
+
handler: (args: string, ctx: WorkflowLauncherContext) => Promise<void>;
|
|
40
47
|
},
|
|
41
48
|
): void;
|
|
42
|
-
/**
|
|
43
|
-
* Send a user message into the active agent stream. Used by the
|
|
44
|
-
* continue-policy session handler.
|
|
45
|
-
*
|
|
46
|
-
* Pi declares this `void` at the type level but returns a Promise at
|
|
47
|
-
* runtime; we declare `void | Promise<void>` so `await` is safe in
|
|
48
|
-
* either world.
|
|
49
|
-
*/
|
|
50
|
-
sendUserMessage(content: string): void | Promise<void>;
|
|
51
49
|
/** Enumerate currently registered slash commands. Used by skill-registration preflight. */
|
|
52
50
|
getCommands(): ReadonlyArray<{ name: string; source: string }>;
|
|
53
51
|
}
|
|
54
52
|
|
|
55
53
|
/**
|
|
56
|
-
*
|
|
57
|
-
*
|
|
54
|
+
* The observer-only ctx the registry-level host hands the `/wf` handler. The
|
|
55
|
+
* launcher relays progress through it and constructs the executor host that
|
|
56
|
+
* runs stages; it excludes the executor additions (`spawnChild`/
|
|
57
|
+
* `maxConcurrency`) so Pi's `ExtensionCommandContext` structurally satisfies it
|
|
58
|
+
* (and `ExtensionAPI` therefore satisfies `WorkflowHost` — the tripwire).
|
|
59
|
+
*/
|
|
60
|
+
export type WorkflowLauncherContext = Omit<WorkflowHostContext, "spawnChild" | "maxConcurrency">;
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Resolved per-unit model override, applied by the host at child-session
|
|
64
|
+
* creation — NOT via global mutation. `model` is a host-opaque model key the
|
|
65
|
+
* host's adapter resolves through its own registry; `thinking` mirrors Pi's
|
|
66
|
+
* thinking levels. Both optional — absent means "host default".
|
|
67
|
+
*/
|
|
68
|
+
export interface ModelSelection {
|
|
69
|
+
model?: string;
|
|
70
|
+
thinking?: "off" | "minimal" | "low" | "medium" | "high" | "xhigh";
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Per-command host ctx. Embedders hand this to `runWorkflow`; the runner
|
|
75
|
+
* threads it (and the child ctx delivered to each `spawnChild`'s `withSession`)
|
|
58
76
|
* through stages.
|
|
59
77
|
*
|
|
60
|
-
* Exhaustive list of members the runtime touches — adding any reach
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
* `sendUserMessage` is declared optional HERE because the outer command
|
|
64
|
-
* ctx Pi delivers to a `/wf` handler does not carry one. The replacement
|
|
65
|
-
* ctx delivered inside `newSession`'s `withSession` callback always does
|
|
66
|
-
* — that stronger guarantee is modelled by the `WorkflowSessionContext`
|
|
67
|
-
* subtype below, which `withSession` delivers. Code holding a bare
|
|
68
|
-
* `WorkflowHostContext` (the workflow-start path before any session
|
|
69
|
-
* opens) must still null-check before calling.
|
|
78
|
+
* Exhaustive list of members the runtime touches — adding any reach outside
|
|
79
|
+
* this list is a port-widening decision, not an oversight.
|
|
70
80
|
*/
|
|
71
81
|
export interface WorkflowHostContext {
|
|
72
82
|
cwd: string;
|
|
73
83
|
hasUI: boolean;
|
|
74
84
|
ui: {
|
|
75
85
|
notify(message: string, level?: "info" | "warning" | "error"): void;
|
|
76
|
-
setStatus(key: string, text: string | undefined): void;
|
|
77
86
|
};
|
|
78
87
|
sessionManager: {
|
|
88
|
+
/**
|
|
89
|
+
* The session transcript (Pi: a message-union array with private
|
|
90
|
+
* discriminators). DELIBERATELY `unknown` — naming a workflow-domain
|
|
91
|
+
* type here would break the no-cast structural pass-through of Pi's
|
|
92
|
+
* ctx. The runtime never calls this directly: `readBranch(ctx)`
|
|
93
|
+
* (transcript.ts) is the single boundary that narrows the value to
|
|
94
|
+
* `BranchEntry[]`.
|
|
95
|
+
*/
|
|
79
96
|
getBranch(): unknown;
|
|
97
|
+
/**
|
|
98
|
+
* Session identity + on-disk location of the active session — read by
|
|
99
|
+
* `readSessionRef` (transcript.ts) so every stage row records which
|
|
100
|
+
* session backed it. `getSessionFile` is `undefined` for non-persisting
|
|
101
|
+
* (in-memory) sessions.
|
|
102
|
+
*/
|
|
103
|
+
getSessionId(): string;
|
|
104
|
+
getSessionFile(): string | undefined;
|
|
80
105
|
};
|
|
81
106
|
waitForIdle(): Promise<void>;
|
|
107
|
+
|
|
108
|
+
/** Cooperative cancellation handle the launcher forwards into `runWorkflow`.
|
|
109
|
+
* On Pi this is `ExtensionCommandContext.signal`; optional so non-Pi
|
|
110
|
+
* embedders / the observer-only surface need not provide it. */
|
|
111
|
+
signal?: AbortSignal;
|
|
112
|
+
|
|
113
|
+
/** Max child sessions runnable at once. 1 ⇒ sequential. The loop reads this;
|
|
114
|
+
* it never invents a number. */
|
|
115
|
+
readonly maxConcurrency: number;
|
|
116
|
+
|
|
82
117
|
/**
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
*
|
|
94
|
-
*
|
|
118
|
+
* Spawn an isolated child session, send `prompt`, run `body` on its ctx,
|
|
119
|
+
* return body's result. The PARENT ctx STAYS VALID (no swap). The runner may
|
|
120
|
+
* have up to `maxConcurrency` spawnChild calls in flight at once.
|
|
121
|
+
*
|
|
122
|
+
* `model` is the resolved per-unit override, applied by the host at session
|
|
123
|
+
* creation — NOT via global mutation. `signal`, when provided, lets the host abort THIS
|
|
124
|
+
* child mid-flight (`session.abort()`/`dispose()`) the moment it fires —
|
|
125
|
+
* the dispatcher threads `run.signal` here so an aborted run interrupts
|
|
126
|
+
* in-flight children, not just between stages.
|
|
127
|
+
*
|
|
128
|
+
* `reattach`, when provided, makes the host OPEN the persisted session at
|
|
129
|
+
* `sessionFile` IN PLACE (appending to it) instead of creating a fresh one,
|
|
130
|
+
* and DELIVER it to `withSession` WITHOUT sending `prompt` — the prior turn
|
|
131
|
+
* already ran, so the body promotes from the existing branch or re-prompts via
|
|
132
|
+
* `sendUserMessage`. This is the detached replacement for the deleted
|
|
133
|
+
* adopt-a-file session-swap path: session-backed resume of a failed
|
|
134
|
+
* single stage (`resumeWithSessionLadder`) and per-unit reattach
|
|
135
|
+
* both spawn a reattaching child rather than swapping the live session.
|
|
136
|
+
* On a non-persisting (in-memory) host or a missing
|
|
137
|
+
* file the host falls back to a fresh child; the runner already gates
|
|
138
|
+
* `reattach` on a `locateSessionFile` hit, so the file is known to exist.
|
|
139
|
+
*
|
|
140
|
+
* `fork`, when provided, makes the host FORK the persisted session at
|
|
141
|
+
* `sessionFile` into a NEW child session (new id, new file) carrying the full
|
|
142
|
+
* prior transcript as context, WITHOUT mutating the source file and WITHOUT
|
|
143
|
+
* sending `prompt` (the body sends the continuation turn via `sendUserMessage`,
|
|
144
|
+
* then measures the inherited prefix). This is how `sessionPolicy: "continue"`
|
|
145
|
+
* continues its predecessor's conversation under detachment — the predecessor's
|
|
146
|
+
* file stays intact (DAG-fork-safe; the continue child has its own resumable
|
|
147
|
+
* identity). The runner gates `fork` on a `locateSessionFile` hit, so the file
|
|
148
|
+
* is known to exist. At most one of `reattach` / `fork` is set; both suppress
|
|
149
|
+
* the host's initial `prompt` send.
|
|
95
150
|
*/
|
|
96
|
-
|
|
151
|
+
spawnChild<T>(options: {
|
|
152
|
+
prompt: string;
|
|
153
|
+
model?: ModelSelection;
|
|
154
|
+
signal?: AbortSignal;
|
|
155
|
+
reattach?: { sessionFile: string };
|
|
156
|
+
fork?: { sessionFile: string };
|
|
157
|
+
/**
|
|
158
|
+
* The fan-out unit index for this spawn, surfaced so a lane-aware host can
|
|
159
|
+
* publish the child under a per-unit registry slot (rpiv-pi's lane dock/viewer).
|
|
160
|
+
* Set by `openChild` from `StageSession.unit?.index`; undefined for a non-fan-out
|
|
161
|
+
* single stage (and for reattach/fork), which the host maps to its reserved
|
|
162
|
+
* single-unit slot. Purely an observability hint — a non-lane host ignores it and
|
|
163
|
+
* it NEVER affects execution.
|
|
164
|
+
*/
|
|
165
|
+
unitIndex?: number;
|
|
166
|
+
withSession: (child: WorkflowSessionContext) => Promise<T>;
|
|
167
|
+
}): Promise<T>;
|
|
97
168
|
}
|
|
98
169
|
|
|
99
170
|
/**
|
|
100
|
-
* The
|
|
101
|
-
*
|
|
102
|
-
*
|
|
103
|
-
*
|
|
104
|
-
*
|
|
105
|
-
* fact for every caller operating inside a session. `host.test.ts`
|
|
106
|
-
* asserts Pi's internal replacement ctx still satisfies this.
|
|
171
|
+
* The child ctx delivered to `spawnChild`'s `withSession` callback. The parent
|
|
172
|
+
* `WorkflowHostContext` declares NO sender; this session subtype ADDS
|
|
173
|
+
* `sendUserMessage` as the guaranteed in-session sender — the host always wires
|
|
174
|
+
* one into a freshly-spawned child session. So any caller operating inside a
|
|
175
|
+
* session can send without a presence check, a compile-time fact of the subtype.
|
|
107
176
|
*/
|
|
108
177
|
export interface WorkflowSessionContext extends WorkflowHostContext {
|
|
109
178
|
sendUserMessage(content: string): Promise<void>;
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Set by a watchdog-equipped host (rpiv-pi) when it aborted THIS child because a
|
|
182
|
+
* single tool call (bash) overran the per-command wall-clock ceiling; returns the
|
|
183
|
+
* failure reason for the recorded row, or `undefined` when no watchdog fired.
|
|
184
|
+
*
|
|
185
|
+
* The watchdog aborts via `session.abort()`, so the timeout reaches `postStage` as
|
|
186
|
+
* a `stopReason:"aborted"` branch — indistinguishable from a run/user abort by the
|
|
187
|
+
* transcript alone. This getter is the out-of-band channel that tells the two apart:
|
|
188
|
+
* a watchdog timeout routes through the soft-halt gate (a collect-all unit records a
|
|
189
|
+
* non-terminal failed row so the fan-out gate still finalizes; a non-fan-out stage
|
|
190
|
+
* fails terminally) INSTEAD of throwing `WorkflowAbortError` — which would re-dispatch
|
|
191
|
+
* the SAME runaway command on resume and wedge again. Optional: a host without a
|
|
192
|
+
* watchdog omits it and every abort stays a plain abort.
|
|
193
|
+
*/
|
|
194
|
+
toolTimeout?(): { reason: string } | undefined;
|
|
110
195
|
}
|