@juicesharp/rpiv-workflow 1.20.0 → 2.1.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 +98 -545
- package/api.ts +1 -1
- package/audit-ctx.ts +103 -0
- package/audit-rows.ts +18 -0
- package/audit.ts +119 -164
- package/built-ins.ts +26 -6
- package/chain-state.ts +119 -68
- package/command-run.ts +35 -30
- package/command.ts +10 -4
- package/docs/embedding.md +341 -0
- package/docs/workflow-authoring.md +70 -16
- package/docs/workflow-basics.md +125 -10
- package/events.ts +44 -4
- package/execution-host.ts +75 -0
- package/host.ts +137 -82
- package/internal-utils.ts +89 -3
- package/internal.ts +1 -0
- package/judge.ts +23 -11
- package/load/alias.ts +3 -3
- package/load/index.ts +15 -1
- package/load/issues.ts +2 -2
- package/load/legacy.ts +2 -2
- package/load/resolve-default.ts +3 -4
- package/load/skill-contract-phase.ts +1 -1
- package/loop-constructors.ts +19 -618
- package/loop-def.ts +60 -15
- package/loop-kinds.ts +319 -62
- package/loop-parallel.ts +250 -0
- package/loop-waves.ts +99 -0
- package/loop.ts +106 -80
- 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 +58 -33
- package/outcomes/collectors/index.ts +1 -0
- package/outcomes/collectors/text-scan.ts +47 -0
- package/outcomes/collectors/transcript-path.ts +2 -15
- package/outcomes/collectors/union.ts +2 -1
- package/outcomes/collectors/url.ts +2 -14
- package/outcomes/collectors/workspace-diff.ts +1 -1
- package/outcomes/git-commit.ts +57 -6
- package/output-spec.ts +1 -1
- package/output.ts +59 -1
- package/package.json +19 -6
- package/preview.ts +18 -18
- package/registration.ts +11 -4
- package/routing-dsl.ts +53 -41
- package/routing.ts +46 -0
- package/runner/chain-advance.ts +30 -17
- package/runner/errors.ts +7 -30
- package/runner/failure.ts +67 -13
- package/runner/input-validation.ts +8 -5
- package/runner/preflight.ts +17 -21
- package/runner/resume-entry.ts +23 -3
- package/runner/resume-loop.ts +50 -29
- package/runner/resume.ts +96 -10
- package/runner/run-context.ts +20 -16
- package/runner/run-stage.ts +125 -91
- package/runner/runner.ts +163 -69
- package/runner/script-stage.ts +23 -29
- package/schema-compat.ts +1 -2
- package/semaphore.ts +55 -0
- package/sessions/extraction.ts +103 -60
- package/sessions/halt-routing.ts +195 -0
- package/sessions/index.ts +2 -2
- package/sessions/locate.ts +60 -9
- package/sessions/reattach.ts +28 -20
- package/sessions/sessions.ts +103 -191
- package/sessions/spawn.ts +132 -119
- package/sessions/success-persist.ts +89 -0
- package/skill-contracts/composition.ts +8 -10
- package/skill-contracts/harvest.ts +3 -2
- package/skill-contracts/registry.ts +1 -1
- package/stage-def.ts +115 -47
- package/stage-errors.ts +84 -0
- package/stage-identity.ts +56 -0
- package/startup.ts +1 -0
- package/state/paths.ts +11 -3
- package/state/raw.ts +2 -3
- package/state/resolve.ts +3 -3
- package/state/state.ts +26 -3
- package/state/writes.ts +1 -1
- package/types.ts +97 -43
- package/validate/contract-compat.ts +16 -11
- package/validate/graph.ts +10 -1
- package/validate/issue.ts +20 -6
- package/validate/stage-rules.ts +139 -60
- package/validate-output.ts +27 -20
- package/validate-workflow.ts +5 -3
- package/validation-bounds.ts +35 -0
- package/docs/cover.png +0 -0
- package/docs/cover.svg +0 -120
- package/load/cache.test.ts +0 -82
- package/load/shape-guards.test.ts +0 -77
- package/outcomes/collectors/directory-path.test.ts +0 -64
- package/outcomes/collectors/tool-call.test.ts +0 -112
- package/outcomes/collectors/transcript-path.test.ts +0 -70
- package/outcomes/collectors/union.test.ts +0 -113
- package/outcomes/collectors/url.test.ts +0 -67
- package/outcomes/collectors/workspace-diff.test.ts +0 -120
- package/outcomes/git-commit.test.ts +0 -240
- 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/header-write-failure.test.ts +0 -64
- package/runner/resume-loop.test.ts +0 -1410
- package/runner/resume-session.test.ts +0 -400
- package/runner/resume.test.ts +0 -1805
- package/sessions/locate.test.ts +0 -77
package/sessions/sessions.ts
CHANGED
|
@@ -3,205 +3,140 @@
|
|
|
3
3
|
* `runStageSession` is the only public entry (loop units run through it too,
|
|
4
4
|
* threading their identity via `StageSession.unit`).
|
|
5
5
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* — is policy-agnostic.
|
|
6
|
+
* Every stage runs in its own detached child session (`spawnChildAndRun`,
|
|
7
|
+
* spawn.ts); the only surviving policy divergence is the branch offset
|
|
8
|
+
* (`branchOffsetFor`). Everything in this file — post-processing, halt routing,
|
|
9
|
+
* success persistence, outcome reading — is policy-agnostic.
|
|
11
10
|
*
|
|
12
11
|
* Companion modules:
|
|
13
|
-
* - extraction.ts
|
|
14
|
-
*
|
|
15
|
-
* - spawn.ts
|
|
16
|
-
*
|
|
17
|
-
* -
|
|
18
|
-
*
|
|
19
|
-
*
|
|
12
|
+
* - extraction.ts — produceAndValidateOutput + retry loop +
|
|
13
|
+
* outcome helpers (collector → parser pipeline).
|
|
14
|
+
* - spawn.ts — the child-spawn primitives (`spawnChildAndRun`,
|
|
15
|
+
* `reattachChildSession`, `resendIntoChild`) + `branchOffsetFor`.
|
|
16
|
+
* - halt-routing.ts — the halt pipeline (`haltStageOrSoftHalt` gate +
|
|
17
|
+
* the per-arm halt helpers + `auditFor`); consumed by
|
|
18
|
+
* `postStage` below and `reattach.ts`.
|
|
19
|
+
* - success-persist.ts — `recordStageSuccess` + `unitEventOf`; consumed by
|
|
20
|
+
* `postStage` below and `reattach.ts`.
|
|
21
|
+
* - reattach.ts — session-backed resume (promotion + reattach); reuses
|
|
22
|
+
* postStage / recordStageSuccess / the halt helpers
|
|
23
|
+
* exported below instead of duplicating them.
|
|
20
24
|
*/
|
|
21
25
|
|
|
22
|
-
import {
|
|
23
|
-
type AuditCtx,
|
|
24
|
-
currentStageRef,
|
|
25
|
-
failedArgs,
|
|
26
|
-
recordCancellation,
|
|
27
|
-
recordStopFailure,
|
|
28
|
-
recordTerminalFailure,
|
|
29
|
-
terminate,
|
|
30
|
-
} from "../audit.js";
|
|
31
|
-
import { persistStageSuccess } from "../audit-rows.js";
|
|
32
|
-
import { lifecycleCtxFromSession, skillStageRef, type UnitEvent } from "../events.js";
|
|
33
|
-
import {
|
|
34
|
-
FAIL_AUDIT_WRITE,
|
|
35
|
-
FAIL_VALIDATION_EXHAUSTED,
|
|
36
|
-
MSG_STAGE_COMPLETE,
|
|
37
|
-
MSG_STAGE_FAILED,
|
|
38
|
-
MSG_UNIT_COMPLETE,
|
|
39
|
-
} from "../messages.js";
|
|
40
|
-
import type { Output } from "../output.js";
|
|
41
|
-
import type { SessionRef } from "../state/index.js";
|
|
26
|
+
import { WorkflowAbortError } from "../internal-utils.js";
|
|
42
27
|
import { type BranchEntry, classifyStop, readBranch, readSessionRef, type StopSignal } from "../transcript.js";
|
|
43
|
-
import type { StageSession, WorkflowHostContext } from "../types.js";
|
|
28
|
+
import type { StageSession, WorkflowHostContext, WorkflowSessionContext } from "../types.js";
|
|
44
29
|
import { produceAndValidateOutput } from "./extraction.js";
|
|
45
|
-
import {
|
|
30
|
+
import { haltStageOrSoftHalt } from "./halt-routing.js";
|
|
31
|
+
import { branchOffsetFor, resendIntoChild, spawnChildAndRun } from "./spawn.js";
|
|
32
|
+
import { recordStageSuccess } from "./success-persist.js";
|
|
46
33
|
|
|
47
34
|
// ===========================================================================
|
|
48
35
|
// PUBLIC ENTRIES — what the orchestrator calls
|
|
49
36
|
// ===========================================================================
|
|
50
37
|
|
|
51
|
-
/** Execute one DAG stage (or loop unit) in its own session. */
|
|
38
|
+
/** Execute one DAG stage (or loop unit) in its own detached child session. */
|
|
52
39
|
export async function runStageSession(ctx: WorkflowHostContext, s: StageSession): Promise<void> {
|
|
53
|
-
|
|
54
|
-
const { cancelled } = await handler.spawn(ctx, s.prompt, (sessionCtx) => postStage(sessionCtx, s), s.continueHost);
|
|
55
|
-
// Pre-open cancellation — no session ever backed this activation.
|
|
56
|
-
if (cancelled) recordCancellation(ctx, auditFor(s, null));
|
|
40
|
+
await spawnChildAndRun(ctx, s, (child) => postStage(ctx, child, s));
|
|
57
41
|
}
|
|
58
42
|
|
|
59
|
-
// ===========================================================================
|
|
60
|
-
// POST-PROCESSING — runs after the agent loop settles
|
|
61
|
-
// ===========================================================================
|
|
62
|
-
|
|
63
43
|
/**
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
*
|
|
44
|
+
* Continue body — runs inside a FORKED child (`forkChildSession`, spawn.ts)
|
|
45
|
+
* carrying the predecessor's full transcript. Re-derive the inherited-prefix
|
|
46
|
+
* offset from the actual forked branch BEFORE the continuation turn is sent
|
|
47
|
+
* (the boundary past which only this stage's own output lives), send the turn
|
|
48
|
+
* via `resendIntoChild` (`/skill:` and templates expand through the rpiv-args
|
|
49
|
+
* input hook exactly as a fresh prompt would), then run the standard `postStage`
|
|
50
|
+
* scoped by that offset. From there the flow is byte-identical to a fresh stage —
|
|
51
|
+
* stop classification, extraction, persistence — only sliced past the prefix.
|
|
67
52
|
*
|
|
68
|
-
* The
|
|
69
|
-
*
|
|
70
|
-
*
|
|
53
|
+
* The re-derived offset (not a launcher-branch read) flows into `postStage` →
|
|
54
|
+
* `readSessionRef`, so the continue stage's own row records the offset its forked
|
|
55
|
+
* branch ran under; resume re-applies that persisted value verbatim.
|
|
71
56
|
*/
|
|
72
|
-
export async function
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
const session = readSessionRef(ctx, offset);
|
|
76
|
-
const outcome = readSessionOutcome(ctx, offset);
|
|
77
|
-
if (outcome.stop !== "stop") return haltStage(ctx, s, outcome.stop, session);
|
|
78
|
-
|
|
79
|
-
const result = await produceAndValidateOutput(ctx, s, outcome.branch, offset);
|
|
80
|
-
if (result.kind === "fatal") return haltStageWithExtractionError(ctx, s, result.message, session);
|
|
81
|
-
if (result.kind === "validation-exhausted")
|
|
82
|
-
return haltStageWithValidationFailure(ctx, s, result.failureSummary, session);
|
|
83
|
-
|
|
84
|
-
if (!(await recordStageSuccess(ctx, s, result.output, session))) return;
|
|
85
|
-
// The validated Output goes to the continuation directly — loop drivers
|
|
86
|
-
// thread it into accumulated / feedForward without state back-reads.
|
|
87
|
-
await s.onSuccess(ctx, result.output);
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
// ===========================================================================
|
|
91
|
-
// HALT HELPERS — turn a halt reason into the right audit-layer call
|
|
92
|
-
// ===========================================================================
|
|
93
|
-
|
|
94
|
-
async function haltStage(
|
|
95
|
-
ctx: WorkflowHostContext,
|
|
96
|
-
s: StageSession,
|
|
97
|
-
stop: Exclude<StopSignal, "stop">,
|
|
98
|
-
session: SessionRef | null,
|
|
99
|
-
): Promise<void> {
|
|
100
|
-
await recordStopFailure(ctx, auditFor(s, session), stop, `${s.skill} failed`, s.onFailure);
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
async function haltStageWithExtractionError(
|
|
104
|
-
ctx: WorkflowHostContext,
|
|
105
|
-
s: StageSession,
|
|
106
|
-
message: string,
|
|
107
|
-
session: SessionRef | null,
|
|
108
|
-
): Promise<void> {
|
|
109
|
-
await recordTerminalFailure(
|
|
110
|
-
ctx,
|
|
111
|
-
auditFor(s, session),
|
|
112
|
-
{ status: "failed", notifyMsg: MSG_STAGE_FAILED(s.skill), notifyLevel: "error", errMsg: message },
|
|
113
|
-
s.onFailure,
|
|
114
|
-
);
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
/** Exported to the `reattach.ts` companion — a promotion's validation-exhausted halt is identical to live. */
|
|
118
|
-
export async function haltStageWithValidationFailure(
|
|
119
|
-
ctx: WorkflowHostContext,
|
|
57
|
+
export async function continueStageSession(
|
|
58
|
+
obsCtx: WorkflowHostContext,
|
|
59
|
+
child: WorkflowSessionContext,
|
|
120
60
|
s: StageSession,
|
|
121
|
-
failureSummary: string,
|
|
122
|
-
session: SessionRef | null,
|
|
123
61
|
): Promise<void> {
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
failedArgs(FAIL_VALIDATION_EXHAUSTED(s.skill, failureSummary)),
|
|
128
|
-
s.onFailure,
|
|
129
|
-
);
|
|
62
|
+
const offset = readBranch(child).length;
|
|
63
|
+
await resendIntoChild(child, s.prompt);
|
|
64
|
+
await postStage(obsCtx, child, s, offset);
|
|
130
65
|
}
|
|
131
66
|
|
|
132
67
|
// ===========================================================================
|
|
133
|
-
//
|
|
68
|
+
// POST-PROCESSING — runs after the agent loop settles
|
|
134
69
|
// ===========================================================================
|
|
135
70
|
|
|
136
71
|
/**
|
|
137
|
-
*
|
|
138
|
-
* chain
|
|
139
|
-
*
|
|
140
|
-
* set iff the row that carried it landed") and sets `state.termination.error`
|
|
141
|
-
* to halt the run. Persistence + state apply run through
|
|
142
|
-
* `persistStageSuccess` (audit-rows.ts) — the ONE success pipeline shared
|
|
143
|
-
* with the script path: the row reuses the activation's pre-allocated number
|
|
144
|
-
* so `output.meta.stageNumber` and the row agree, and unit rows carry the
|
|
145
|
-
* structured identity fields alongside the decorated display `stage`.
|
|
72
|
+
* Stage post-processing: classify outcome → produce & validate output →
|
|
73
|
+
* persist → chain. Exported to the `reattach.ts` companion — a reattached
|
|
74
|
+
* session's continuation runs this exact pipeline, byte-identical to live.
|
|
146
75
|
*
|
|
147
|
-
*
|
|
148
|
-
*
|
|
149
|
-
*
|
|
150
|
-
*
|
|
151
|
-
*
|
|
76
|
+
* TWO ctxs (detachment): `obsCtx` is the long-lived LAUNCHER/observer ctx the
|
|
77
|
+
* walk threads — it stays valid across every stage, so the user-facing recording
|
|
78
|
+
* (success/halt rows + notifications + lifecycle) AND the chain continuation
|
|
79
|
+
* (`onSuccess` → advance/step, which spawns the NEXT stage's child) all run on
|
|
80
|
+
* it, NOT on the per-stage child (whose UI is the lane binding — noOp in the
|
|
81
|
+
* background lane — and which is disposed when the stage ends). `child` is the
|
|
82
|
+
* in-session ctx: the agent transcript (`readBranch`/`readSessionRef`) and the
|
|
83
|
+
* validation-retry re-prompt (`produceAndValidateOutput` → `resendIntoChild`)
|
|
84
|
+
* read/write through it. Spawning the next stage off `obsCtx` is what keeps the
|
|
85
|
+
* launcher the single spawner (no nested-child chain).
|
|
152
86
|
*
|
|
153
|
-
*
|
|
154
|
-
*
|
|
87
|
+
* The backing `SessionRef` is captured ONCE at entry — every row this
|
|
88
|
+
* pipeline can write (success, stop-failure, extraction/validation failure)
|
|
89
|
+
* carries the same provenance value.
|
|
155
90
|
*/
|
|
156
|
-
export async function
|
|
157
|
-
|
|
91
|
+
export async function postStage(
|
|
92
|
+
obsCtx: WorkflowHostContext,
|
|
93
|
+
child: WorkflowSessionContext,
|
|
158
94
|
s: StageSession,
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
)
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
unitEventOf(s),
|
|
186
|
-
output,
|
|
187
|
-
lifecycleCtxFromSession(s),
|
|
188
|
-
);
|
|
189
|
-
} else {
|
|
190
|
-
ctx.ui.notify(MSG_STAGE_COMPLETE(s.skill), "info");
|
|
191
|
-
await s.lifecycle.fire(ctx, "onStageEnd", currentStageRef(s), output, lifecycleCtxFromSession(s));
|
|
192
|
-
}
|
|
193
|
-
return true;
|
|
95
|
+
// Defaults to the policy-derived offset (fresh ⇒ undefined; resume continue ⇒
|
|
96
|
+
// the persisted row's value). The live continue body passes the value it
|
|
97
|
+
// re-derived from the forked branch, which is authoritative there.
|
|
98
|
+
offset: number | undefined = branchOffsetFor(s.stage.sessionPolicy, s.branchOffset),
|
|
99
|
+
): Promise<void> {
|
|
100
|
+
const session = readSessionRef(child, offset);
|
|
101
|
+
const outcome = readSessionOutcome(child, offset);
|
|
102
|
+
// Abort surfaces as a STOP CLASSIFICATION, not a promise rejection:
|
|
103
|
+
// `session.abort()` makes the SDK RESOLVE `prompt()` with a
|
|
104
|
+
// `stopReason:"aborted"` transcript message, so an aborted in-flight child runs
|
|
105
|
+
// straight into here. Throw BEFORE haltStage/softHaltUnit/any row write so:
|
|
106
|
+
// (a) no `collected:true` row is written (else the resume fold marks the unit
|
|
107
|
+
// "don't re-dispatch" → permanent work loss), (b) the parallel fold's
|
|
108
|
+
// `isAbortError` branch leaves the slot unfilled, and (c) resume re-dispatches
|
|
109
|
+
// the unit cleanly.
|
|
110
|
+
//
|
|
111
|
+
// A genuine run/user abort (`s.signal` fired) ALWAYS re-dispatches on resume, so it
|
|
112
|
+
// takes the throw unconditionally. An `aborted` stop with the signal cold is examined
|
|
113
|
+
// for a watchdog tool-timeout (`child.toolTimeout`): the host aborted a runaway bash,
|
|
114
|
+
// which must route to the soft-halt gate (collect-all unit survives; else terminal
|
|
115
|
+
// fail) — NOT WorkflowAbortError, which would re-run the same runaway command on resume.
|
|
116
|
+
if (s.signal?.aborted) throw new WorkflowAbortError();
|
|
117
|
+
if (outcome.stop === "aborted") {
|
|
118
|
+
const timeout = child.toolTimeout?.();
|
|
119
|
+
if (timeout) return haltStageOrSoftHalt(obsCtx, s, { kind: "timeout", reason: timeout.reason }, session);
|
|
120
|
+
throw new WorkflowAbortError();
|
|
194
121
|
}
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
122
|
+
// Every halt below routes through the single `haltStageOrSoftHalt` gate: a
|
|
123
|
+
// fanout unit marked `collectAll` records a NON-terminal failed row + a sentinel
|
|
124
|
+
// slot instead of halting the run; everything else takes the arm's fail-fast
|
|
125
|
+
// halt. Recording + the continuation run on obsCtx (the launcher) — the per-stage
|
|
126
|
+
// child is disposed when the stage ends.
|
|
127
|
+
if (outcome.stop !== "stop") return haltStageOrSoftHalt(obsCtx, s, { kind: "stop", stop: outcome.stop }, session);
|
|
128
|
+
|
|
129
|
+
const result = await produceAndValidateOutput(child, s, outcome.branch, offset);
|
|
130
|
+
if (result.kind === "fatal")
|
|
131
|
+
return haltStageOrSoftHalt(obsCtx, s, { kind: "extraction", message: result.message }, session);
|
|
132
|
+
if (result.kind === "validation-exhausted")
|
|
133
|
+
return haltStageOrSoftHalt(obsCtx, s, { kind: "validation", failureSummary: result.failureSummary }, session);
|
|
200
134
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
135
|
+
if (!(await recordStageSuccess(obsCtx, s, result.output, session))) return;
|
|
136
|
+
// The validated Output goes to the continuation directly — loop drivers
|
|
137
|
+
// thread it into accumulated / feedForward without state back-reads. Runs on
|
|
138
|
+
// obsCtx so the next stage's child is spawned off the launcher.
|
|
139
|
+
await s.onSuccess(obsCtx, result.output);
|
|
205
140
|
}
|
|
206
141
|
|
|
207
142
|
// ===========================================================================
|
|
@@ -229,26 +164,3 @@ function readSessionOutcome(ctx: WorkflowHostContext, branchOffset: number | und
|
|
|
229
164
|
stop: classifyStop(branch, branchOffset),
|
|
230
165
|
};
|
|
231
166
|
}
|
|
232
|
-
|
|
233
|
-
// ===========================================================================
|
|
234
|
-
// Helpers
|
|
235
|
-
// ===========================================================================
|
|
236
|
-
|
|
237
|
-
const auditFor = (s: StageSession, session: SessionRef | null): AuditCtx => ({
|
|
238
|
-
cwd: s.cwd,
|
|
239
|
-
runId: s.runId,
|
|
240
|
-
state: s.state,
|
|
241
|
-
stageName: s.stageName,
|
|
242
|
-
skill: s.skill,
|
|
243
|
-
// The Pi session backing this activation — `null` only for pre-open
|
|
244
|
-
// cancellation (the one writer here that never entered a session).
|
|
245
|
-
session,
|
|
246
|
-
lifecycle: s.lifecycle,
|
|
247
|
-
runIdentity: s.runIdentity,
|
|
248
|
-
// The activation's pre-allocated stage number (set once output production
|
|
249
|
-
// began) — a failure row reuses it instead of burning a second number.
|
|
250
|
-
allocatedStageNumber: s.allocatedStageNumber,
|
|
251
|
-
// Loop units thread their identity onto failure/cancellation rows so failed
|
|
252
|
-
// trailers carry the structured fields the resume drift guard consumes.
|
|
253
|
-
...(s.unit ? { unit: s.unit } : {}),
|
|
254
|
-
});
|
package/sessions/spawn.ts
CHANGED
|
@@ -1,139 +1,152 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Session
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
2
|
+
* Session opening — the child-spawn primitives every stage and loop unit runs
|
|
3
|
+
* through. With every stage isolated in its own child session, "send into an
|
|
4
|
+
* existing session" doesn't exist, so there's no stale-ctx fallback ladder,
|
|
5
|
+
* no registry-host fallback param, and no defensive `sendUserMessage` guards.
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* `
|
|
7
|
+
* Three open modes, all routed through `ctx.spawnChild`:
|
|
8
|
+
* - FRESH (`spawnChildAndRun`) — a brand-new child; the host sends the prompt.
|
|
9
|
+
* - REATTACH (`reattachChildSession`) — open a persisted file IN PLACE
|
|
10
|
+
* (session-backed resume); the host skips the prompt, the body promotes/nudges.
|
|
11
|
+
* - FORK (`forkChildSession`) — copy a PREDECESSOR's persisted session into a
|
|
12
|
+
* NEW file carrying its full transcript (`sessionPolicy: "continue"`); the host
|
|
13
|
+
* skips the prompt, the body re-derives the inherited-prefix offset and sends
|
|
14
|
+
* the continuation turn. This is the detached continuation mechanism — prior-
|
|
15
|
+
* session lineage survives detachment via `SessionManager.forkFrom`, resolving
|
|
16
|
+
* the original OQ1 (which assumed it could not). The source file is never
|
|
17
|
+
* mutated, so DAG forks are safe and the continue child has its own resumable
|
|
18
|
+
* identity.
|
|
10
19
|
*/
|
|
11
20
|
|
|
12
21
|
import type { SessionPolicy } from "../api.js";
|
|
13
|
-
import type {
|
|
14
|
-
import type { WorkflowHostContext } from "../types.js";
|
|
22
|
+
import type { StageSession, WorkflowHostContext, WorkflowSessionContext } from "../types.js";
|
|
15
23
|
|
|
16
24
|
/**
|
|
17
|
-
*
|
|
18
|
-
*
|
|
25
|
+
* The per-policy branch offset — fresh ignores the stage-captured value;
|
|
26
|
+
* continue flows it through so a continue stage's outcome still skips the prior
|
|
27
|
+
* transcript its forked child inherited (trail / replay symmetry). The sole
|
|
28
|
+
* surviving policy divergence.
|
|
19
29
|
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
* on whichever ctx is valid for that policy (fresh → freshCtx
|
|
27
|
-
* inside `withSession`; continue → the supplied ctx, after a
|
|
28
|
-
* send+waitForIdle settles the existing session). `cancelled: true`
|
|
29
|
-
* means a fresh session was cancelled before `withSession` ran.
|
|
30
|
-
* - `send(ctx, msg, host?)` — send into an already-established session
|
|
31
|
-
* and wait for it to settle (used by the validation-retry path).
|
|
32
|
-
*
|
|
33
|
-
* `host` is the registry-level fallback for continue stages — used only
|
|
34
|
-
* when `ctx.sendUserMessage` is absent (the outer command ctx at the
|
|
35
|
-
* very start of a workflow whose first stage is continue-policy).
|
|
36
|
-
* Everywhere else (continue stages following any other stage),
|
|
37
|
-
* `ctx.sendUserMessage` is present and preferred because Pi marks the
|
|
38
|
-
* captured host stale after `ctx.newSession()`. `enforceSessionInvariants`
|
|
39
|
-
* still requires a host whenever any stage is continue-policy so the
|
|
40
|
-
* start-stage path has a working fallback. Fresh ignores `host` entirely.
|
|
30
|
+
* The `captured` value is sourced from the continuation's ACTUAL branch:
|
|
31
|
+
* - live (`continueStageSession`) re-derives it from the forked child's branch
|
|
32
|
+
* length before the continuation turn is sent, and threads it through `postStage`;
|
|
33
|
+
* - resume takes it from the persisted row (`SessionRef.branchOffset`) of the
|
|
34
|
+
* continue stage's own forked session.
|
|
35
|
+
* Never the launcher's branch (the bug the fork redesign removed).
|
|
41
36
|
*/
|
|
42
|
-
export
|
|
43
|
-
|
|
44
|
-
spawn(
|
|
45
|
-
ctx: WorkflowHostContext,
|
|
46
|
-
prompt: string,
|
|
47
|
-
body: (sessionCtx: WorkflowHostContext) => Promise<void>,
|
|
48
|
-
host?: WorkflowHost,
|
|
49
|
-
): Promise<{ cancelled: boolean }>;
|
|
50
|
-
send(ctx: WorkflowHostContext, msg: string, host?: WorkflowHost): Promise<void>;
|
|
37
|
+
export function branchOffsetFor(policy: SessionPolicy | undefined, captured: number | undefined): number | undefined {
|
|
38
|
+
return policy === "continue" ? captured : undefined;
|
|
51
39
|
}
|
|
52
40
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
// `freshCtx` is a `WorkflowSessionContext` — the port guarantees
|
|
58
|
-
// `sendUserMessage` on the replacement ctx, so no runtime guard.
|
|
59
|
-
withSession: async (freshCtx) => {
|
|
60
|
-
await freshCtx.sendUserMessage(prompt);
|
|
61
|
-
await body(freshCtx);
|
|
62
|
-
},
|
|
63
|
-
});
|
|
64
|
-
return { cancelled };
|
|
65
|
-
},
|
|
66
|
-
async send(ctx, msg) {
|
|
67
|
-
// At runtime ctx is the in-session replacement (a
|
|
68
|
-
// `WorkflowSessionContext`), but the shared `SessionPolicyHandler`
|
|
69
|
-
// types it as the base `WorkflowHostContext` (continue's send may run
|
|
70
|
-
// on the senderless start ctx), so this seam keeps a defensive guard.
|
|
71
|
-
if (!ctx.sendUserMessage) {
|
|
72
|
-
throw new Error("FRESH_HANDLER.send: replacement ctx missing sendUserMessage");
|
|
73
|
-
}
|
|
74
|
-
await ctx.sendUserMessage(msg);
|
|
75
|
-
},
|
|
76
|
-
};
|
|
41
|
+
/** Optional open mode — absent ⇒ FRESH; `reattach` opens a persisted file in
|
|
42
|
+
* place; `fork` copies a predecessor's session into a new file. The two carry
|
|
43
|
+
* the same `{ sessionFile }` shape; only the host's open semantics differ. */
|
|
44
|
+
type OpenMode = { reattach: { sessionFile: string } } | { fork: { sessionFile: string } };
|
|
77
45
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
//
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
};
|
|
46
|
+
/**
|
|
47
|
+
* THE child-spawn primitive every mode below reduces to. Open an isolated child
|
|
48
|
+
* (parent stays valid) in the requested `mode`, let the host apply the
|
|
49
|
+
* prompt/model/signal (+ reattach/fork), wait for the agent to settle, then run
|
|
50
|
+
* `body` on the guaranteed-in-session child ctx. The await-idle-then-body
|
|
51
|
+
* sequence — load-bearing for the IDLE-BEFORE-REPROMPT invariant — lives here
|
|
52
|
+
* once, so the three named entries can't drift on it. Up to `ctx.maxConcurrency`
|
|
53
|
+
* may be in flight (the loop's semaphore bounds fanout; single stages run one).
|
|
54
|
+
*/
|
|
55
|
+
function openChild(
|
|
56
|
+
ctx: WorkflowHostContext,
|
|
57
|
+
s: Pick<StageSession, "prompt" | "model" | "signal" | "laneUnitIndex">,
|
|
58
|
+
body: (child: WorkflowSessionContext) => Promise<void>,
|
|
59
|
+
mode?: OpenMode,
|
|
60
|
+
): Promise<void> {
|
|
61
|
+
return ctx.spawnChild({
|
|
62
|
+
prompt: s.prompt, // FRESH: host sends it. REATTACH/FORK: carried for parity; host skips auto-replay.
|
|
63
|
+
model: s.model,
|
|
64
|
+
signal: s.signal,
|
|
65
|
+
// The lane key for a lane-aware host's per-unit slot — set only for fan-out units.
|
|
66
|
+
// Undefined for sequential loop units / single stages / reattach / fork, all
|
|
67
|
+
// of which map to the host's reserved single-unit slot so the lane row keeps
|
|
68
|
+
// showing the one live session. Inert on a non-lane host.
|
|
69
|
+
unitIndex: s.laneUnitIndex,
|
|
70
|
+
...mode,
|
|
71
|
+
withSession: async (child) => {
|
|
72
|
+
await child.waitForIdle();
|
|
73
|
+
await body(child);
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
}
|
|
110
77
|
|
|
111
78
|
/**
|
|
112
|
-
*
|
|
113
|
-
*
|
|
114
|
-
* `host.sendUserMessage` only when ctx doesn't expose one (workflow start
|
|
115
|
-
* with a continue-first-stage). Throws if neither path is available —
|
|
116
|
-
* `enforceSessionInvariants` should have rejected the workflow before
|
|
117
|
-
* we land here.
|
|
79
|
+
* FRESH open. Open a brand-new isolated child session; the host sends the prompt
|
|
80
|
+
* and applies the model. The default stage/loop-unit entry.
|
|
118
81
|
*/
|
|
119
|
-
|
|
82
|
+
export function spawnChildAndRun(
|
|
120
83
|
ctx: WorkflowHostContext,
|
|
121
|
-
|
|
122
|
-
|
|
84
|
+
s: Pick<StageSession, "prompt" | "model" | "signal" | "laneUnitIndex">,
|
|
85
|
+
body: (child: WorkflowSessionContext) => Promise<void>,
|
|
123
86
|
): Promise<void> {
|
|
124
|
-
|
|
125
|
-
await ctx.sendUserMessage(msg);
|
|
126
|
-
return;
|
|
127
|
-
}
|
|
128
|
-
if (host) {
|
|
129
|
-
await host.sendUserMessage(msg);
|
|
130
|
-
return;
|
|
131
|
-
}
|
|
132
|
-
throw new Error(
|
|
133
|
-
"CONTINUE_HANDLER: neither ctx.sendUserMessage nor a workflow host available — continue policy requires one of them",
|
|
134
|
-
);
|
|
87
|
+
return openChild(ctx, s, body);
|
|
135
88
|
}
|
|
136
89
|
|
|
137
|
-
|
|
138
|
-
|
|
90
|
+
/**
|
|
91
|
+
* THE reattach primitive — the detached replacement for the deleted
|
|
92
|
+
* live-session swap (`ctx.switchSession`). Spawn a child bound to the PERSISTED
|
|
93
|
+
* session at `sessionFile` (the host opens it, no fresh creation, no initial `prompt`),
|
|
94
|
+
* then run `body` on the in-session child ctx whose `getBranch` reflects the
|
|
95
|
+
* prior transcript. `body` is `reattachStageSession` (sessions/reattach.ts),
|
|
96
|
+
* which promotes from the loaded branch or nudges via `resendIntoChild`.
|
|
97
|
+
*
|
|
98
|
+
* `sessionFile` is supplied by the resume entry (a `locateSessionFile` hit), so
|
|
99
|
+
* the host always has a real file; a missing/in-memory case is gated upstream.
|
|
100
|
+
* There is NO `{ cancelled }` arm — a detached reattach has no live-session swap
|
|
101
|
+
* for the user to dismiss.
|
|
102
|
+
*/
|
|
103
|
+
export function reattachChildSession(
|
|
104
|
+
ctx: WorkflowHostContext,
|
|
105
|
+
s: Pick<StageSession, "prompt" | "model" | "signal" | "laneUnitIndex">,
|
|
106
|
+
sessionFile: string,
|
|
107
|
+
body: (child: WorkflowSessionContext) => Promise<void>,
|
|
108
|
+
): Promise<void> {
|
|
109
|
+
return openChild(ctx, s, body, { reattach: { sessionFile } });
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* THE fork primitive — the detached continuation mechanism for
|
|
114
|
+
* `sessionPolicy: "continue"`. Spawn a child by FORKING the PREDECESSOR's
|
|
115
|
+
* persisted session at `sessionFile` (`SessionManager.forkFrom`: a new file +
|
|
116
|
+
* new id carrying the predecessor's full transcript, source left intact), then
|
|
117
|
+
* run `body` on the in-session child ctx whose `getBranch` reflects that prior
|
|
118
|
+
* transcript. The host opens the fork and does NOT send the carried `prompt` —
|
|
119
|
+
* `body` (`continueStageSession`, sessions.ts) measures the inherited prefix and
|
|
120
|
+
* sends the continuation turn via `resendIntoChild`.
|
|
121
|
+
*
|
|
122
|
+
* `sessionFile` is the predecessor stage's persisted session (a
|
|
123
|
+
* `locateSessionFile` hit gated by the caller, from `run.state.lastSession`), so
|
|
124
|
+
* the host always has a real file. Distinct from `reattachChildSession` (which
|
|
125
|
+
* opens the SAME file IN PLACE for resume): a fork must not mutate the
|
|
126
|
+
* predecessor's file and gives the continue stage its own resumable identity.
|
|
127
|
+
*/
|
|
128
|
+
export function forkChildSession(
|
|
129
|
+
ctx: WorkflowHostContext,
|
|
130
|
+
s: Pick<StageSession, "prompt" | "model" | "signal" | "laneUnitIndex">,
|
|
131
|
+
sessionFile: string,
|
|
132
|
+
body: (child: WorkflowSessionContext) => Promise<void>,
|
|
133
|
+
): Promise<void> {
|
|
134
|
+
return openChild(ctx, s, body, { fork: { sessionFile } });
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Re-prompt an already-open child and wait for it to settle — the
|
|
139
|
+
* validation-retry path (`askAgentToFix`) and the resume reattach nudge.
|
|
140
|
+
* The child ctx always exposes `sendUserMessage`, so no guard.
|
|
141
|
+
*
|
|
142
|
+
* IDLE-BEFORE-REPROMPT INVARIANT: uses `sendUserMessage` (which QUEUES, safe
|
|
143
|
+
* mid-stream), NOT `prompt()` — the SDK THROWS "Agent is already processing" if
|
|
144
|
+
* `prompt()` is called while streaming. Every entry point honors this:
|
|
145
|
+
* `spawnChildAndRun` calls `waitForIdle()` before `body`, and the host's
|
|
146
|
+
* `prompt()` is only the single initial send. Callers must never call a child's
|
|
147
|
+
* `prompt()` again after the first; re-prompts go through `sendUserMessage` here.
|
|
148
|
+
*/
|
|
149
|
+
export async function resendIntoChild(child: WorkflowSessionContext, msg: string): Promise<void> {
|
|
150
|
+
await child.sendUserMessage(msg);
|
|
151
|
+
await child.waitForIdle();
|
|
139
152
|
}
|