Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ web_modules/
*.d.ts
*.d.cts
*.d.mts
# Authored JavaScript, not compile output: workflow examples, project workflows, e2e fixtures.
!examples/workflows/*.js
!tests/e2e/fixtures/*.js
!.pi/workflows/*.js
# Hand-written declarations for committed .mjs helpers
!/pi-packages.d.mts
!/scripts/*.d.mts
Expand Down Expand Up @@ -151,13 +155,13 @@ vite.config.js.timestamp-*
vite.config.ts.timestamp-*
.vite/

# package-lock.json committed for reproducible CI installs (excluded from publish)

# pi-schematic local config (credentials, API keys)
.chunkhound.json
.chunkhound/
.mcp.json
.pi/
# Local pi state is ignored, except authored project workflows (see exception above).
.pi/*
!.pi/workflows/

# macOS
.DS_Store
Expand Down
1,179 changes: 684 additions & 495 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"@earendil-works/pi-tui": ">=1.2.0",
"typebox": ">=1.3.27"
},
"dependencies": {},
"scripts": {
"prepare": "husky",
"test": "vitest run --project unit",
Expand Down
42 changes: 40 additions & 2 deletions spawn/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ function getInheritableParentToolNames(parentToolNames: string[], availableTools
* Local child custom tools are added separately. Parent-only custom tools are
* intentionally excluded so the child never advertises a tool it cannot execute.
*
* handoff and spawn never carry into children.
* handoff, spawn and the run-scoped workflow_output never carry into children.
*/
export function buildChildToolNames(
parentToolNames: string[],
Expand Down Expand Up @@ -484,7 +484,12 @@ export function executeSpawn(
provider: route.provider,
modelId: route.modelId,
}
: { status: "inherited" };
: { status: "inherited", provider: route.provider, modelId: route.modelId };

// WHY: capture the run-owned sink before any await. A late flush after this run ends
// must write to the run that spawned the child, never the next run's sink.
const childUsageSink = state.childUsageSink;
const childProvider = route.provider;

const childSessionEpoch = state.childSessionEpoch;
const isStale = () => state.childSessionEpoch !== childSessionEpoch;
Expand Down Expand Up @@ -541,6 +546,17 @@ export function executeSpawn(
// public session value so child details describe what actually runs. The
// fallback keeps intentionally partial session test doubles compatible.
const effectiveChildThinking = () => session.thinkingLevel ?? requestedChildThinking;
// Child spend belongs to the run ledger from the moment it is incurred. Flushing
// cumulative usage on every message_end keeps live cost attributed to the child's
// model, so an aborted run cannot leave a model-less residual; cumulative (not
// delta) makes the settle flush idempotent.
const flushChildSpend = () => {
if (!childUsageSink) {
return;
}
childUsageSink(toolCallId, childProvider, childModel.id, collectChildAccounting(session).usage);
};
let unsubscribeChildEvents: (() => void) | undefined;
const buildBaseDetails = (truncated: boolean, outcome: SpawnOutcome): SpawnResultDetails => ({
model: childModel.id,
thinking: effectiveChildThinking(),
Expand Down Expand Up @@ -570,8 +586,26 @@ export function executeSpawn(
throw new Error(describeAbort(abortedSignal.reason));
};

// The subscription is UI-independent; a failure loses live flushes only, and
// the settle flush below still runs, so it never fails the spawn.
if (typeof session.subscribe === "function") {
try {
unsubscribeChildEvents = session.subscribe((event) => {
if (event.type === "message_end") {
flushChildSpend();
}
});
} catch (error) {
const issue = `Spawn event subscription failed: ${failureMessage(error)}`;
if (ctx.hasUI) {
ctx.ui.notify(issue, "warning");
}
}
}

const runChild = async (): Promise<ChildRun> => {
let primary: { error: unknown } | undefined;

try {
if (isStale()) {
await abortAndInvalidate();
Expand Down Expand Up @@ -664,6 +698,10 @@ export function executeSpawn(
primary = { error };
throw error;
} finally {
unsubscribeChildEvents?.();
// Last flush before dispose: covers headless runs, missed message_end events
// and abort paths.
flushChildSpend();
clearChildSession();
try {
// AgentSession always provides dispose(); the guard keeps intentionally
Expand Down
8 changes: 7 additions & 1 deletion spawn/renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,14 @@ function normalizeRoute(value: unknown): SpawnRouteDetails | undefined {
if (!isRecord(value)) {
return undefined;
}
// Accept both the persisted `{status:"inherited"}` and the current shape with
// provider/modelId; the extra identity is preserved when present.
if (value.status === "inherited") {
return { status: "inherited" };
return {
status: "inherited",
...(typeof value.provider === "string" ? { provider: value.provider } : {}),
...(typeof value.modelId === "string" ? { modelId: value.modelId } : {}),
};
}
if (value.status === "routed" && typeof value.group === "string" && typeof value.provider === "string" && typeof value.modelId === "string") {
return { status: "routed", group: value.group, provider: value.provider, modelId: value.modelId };
Expand Down
6 changes: 5 additions & 1 deletion spawn/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,12 @@ import type { AgentSession } from "@earendil-works/pi-coding-agent";

export type SpawnOutcome = "running" | "success" | "aborted" | "error";

/** Advisory spawn notice type (event-subscription failure). Informational, never a run
* error, so it must not reuse the workflow error entry type. */
export type SpawnRouteDetails =
| { status: "inherited" }
// provider/modelId are optional only to read sessions persisted before they were added;
// every new write sets them so the spend ledger never splits one model across two rows.
| { status: "inherited"; provider?: string; modelId?: string }
| { status: "routed"; group: string; provider: string; modelId: string }
| { status: "unknown-fallback"; requestedGroup: string; provider: string; modelId: string };

Expand Down
17 changes: 17 additions & 0 deletions state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,19 @@
*/

import type { AgentSession } from "@earendil-works/pi-coding-agent";
import type { Usage } from "@earendil-works/pi-ai";
import type { ModelGroupsBootValidation, ResolvedModelGroup } from "./model-groups/types.js";
import type { FrontmatterEntry, FrontmatterIssue } from "./frontmatter-cache.js";
import type { NotebookTopicBoundaryHint } from "./notebook/topic.js";

/**
* Run-scoped sink for live child spend. The active workflow host installs it, and the
* spawn tool flushes each child's cumulative usage on every message_end and at settle.
* Null outside a workflow run; only host dispose uninstalls it, never resetState, because
* a run survives `workflow.new`.
*/
type ChildUsageSink = (toolCallId: string, provider: string | null, model: string, usage: Usage) => void;

/** A handoff accepted by the tool, kept until its turn_end boundary is confirmed or failed. */
export interface StagedHandoff {
/** Written to the cut's and the successor's details; identifies the cut on the branch. */
Expand Down Expand Up @@ -128,6 +137,12 @@ export interface SchematicState {
/** One abort promise per child session, shared by signal and reset cleanup. WeakMap entries are GC'd with the session; no manual clear needed. */
childAbortPromises: WeakMap<AgentSession, Promise<void>>;

/** Live child-spend sink installed by the active workflow host; see {@link ChildUsageSink}. */
childUsageSink: ChildUsageSink | null;

/** True while a workflow run owns the input channel (serial-run invariant, see docs/workflows.md). */
inputSuppressed: boolean;

/** Whether readonly mode is active — write/edit/powershell blocked; handoff needs explicit /handoff or a human topic boundary; bash writes limited to temp. */
readonlyEnabled: boolean;

Expand Down Expand Up @@ -205,6 +220,8 @@ export function createState(): SchematicState {
liveChildSessions,
childSessionEpoch: 0,
childAbortPromises: new WeakMap(),
childUsageSink: null,
inputSuppressed: false,
readonlyEnabled: false,
readonlyNudgePending: false,
readonlyNudgeRearmAtSettle: false,
Expand Down
16 changes: 11 additions & 5 deletions tests/unit/spawn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ test("spawn forwards requested thinking and reports the session effective thinki
expect(seenConfig?.thinkingLevel, "requested thinking is forwarded unchanged").toBe("max");
expect(runningDetails.thinking, "running details report Pi's effective thinking").toBe("off");
expect(result.details.thinking, "final details report Pi's effective thinking").toBe("off");
expect(result.details.route).toStrictEqual({ status: "inherited" });
expect(result.details.route).toStrictEqual({ status: "inherited", provider: "test", modelId: "non-reasoning-model" });
});

test("spawn execute composes Model Group routing with readonly child guards", async () => {
Expand Down Expand Up @@ -871,7 +871,13 @@ test("spawn execute derives result stats from the child entries", async () => {
expect(updates).toStrictEqual([
{
content: [],
details: { model: "mock-model", thinking: "high", truncated: false, outcome: "running", route: { status: "inherited" } },
details: {
model: "mock-model",
thinking: "high",
truncated: false,
outcome: "running",
route: { status: "inherited", provider: "test", modelId: "mock-model" },
},
},
]);
expect(result.content[0].text).toBe("child result");
Expand Down Expand Up @@ -1434,7 +1440,7 @@ function failedSpawnResult(text: string) {
thinking: "high",
truncated: false,
outcome: "error",
route: { status: "inherited" },
route: { status: "inherited", provider: "test", modelId: "mock-model" },
stats: { inputTokens: 80, outputTokens: 4, cacheReadTokens: 10, cacheWriteTokens: 1, totalTokens: 95, cost: 13, turns: 2 },
},
usage: FAILED_CHILD_USAGE,
Expand Down Expand Up @@ -1570,7 +1576,7 @@ test("a parent abort between child creation and the prompt returns an aborted re
thinking: "high",
truncated: false,
outcome: "aborted",
route: { status: "inherited" },
route: { status: "inherited", provider: "test", modelId: "mock-model" },
stats: { inputTokens: 80, outputTokens: 4, cacheReadTokens: 10, cacheWriteTokens: 1, totalTokens: 95, cost: 13, turns: 2 },
});
expect(result.content[0].text).toBe("Child agent aborted: aborted before start");
Expand Down Expand Up @@ -2195,7 +2201,7 @@ test("executeSpawn forwards inherited constraints to routing and succeeds when s
sessionFactory,
);
expect(result.details.outcome).toBe("success");
expect(result.details.route).toStrictEqual({ status: "inherited" });
expect(result.details.route).toStrictEqual({ status: "inherited", provider: "openai", modelId: "parent" });
expect(sessionFactory, "inherited route with satisfied requirements creates one child").toHaveBeenCalledOnce();
});

Expand Down
Loading
Loading