Skip to content
Merged
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
41 changes: 41 additions & 0 deletions main/services/subagents/agent-compatibility.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
} from "@earendil-works/pi-ai/providers/faux";
import type { AgentTool } from "@earendil-works/pi-agent-core";
import type { ResolvedModelRuntime } from "../model-runtime-core.js";
import { appendPiMessages } from "../pi-compaction-session-store.js";
import { SubagentApprovalLedgerV2 } from "./approval-v2.js";
import { createSubagentAuthorityV2 } from "./authority-v2.js";
import {
Expand Down Expand Up @@ -600,6 +601,46 @@ test("child context compaction bounds oversized tool output before the next prov
assert.equal(registry.activeCount, 0);
});

test("child completion survives a Pi journal append failure", async () => {
const core = createFauxCore({
provider: "aiden-compat-journal-resilience",
models: [{ id: "compat-journal-resilience", contextWindow: 8_192 }],
});
core.setResponses([fauxAssistantMessage("completed despite journal failure")]);
const journalErrors: unknown[] = [];
let failedAssistantBatch = false;
const registry = new SubagentRuntimeRegistry(undefined, undefined, {
appendPiMessages: async (session, messages, visibleChatMessageId) => {
if (
!failedAssistantBatch &&
messages.some((message) => message.role === "assistant")
) {
failedAssistantBatch = true;
throw new Error("injected child journal failure");
}
await appendPiMessages(session, messages, visibleChatMessageId);
},
onPiJournalError: (error) => journalErrors.push(error),
});
const runningChild = child(
registry,
runtimeFrom(core.getModel() as Model<Api>, core.streamSimple),
);

await assert.doesNotReject(
runningChild.prompt("Complete even if the in-memory journal cannot append."),
);

assert.equal(core.state.callCount, 1);
assert.equal(failedAssistantBatch, true);
assert.equal(journalErrors.length, 1);
assert.match(
JSON.stringify(runningChild.agent.state.messages),
/completed despite journal failure/u,
);
assert.equal(registry.activeCount, 0);
});

test("forked initial context is compacted before the first provider request", async () => {
const core = createFauxCore({
provider: "aiden-compat-initial-fork",
Expand Down
40 changes: 36 additions & 4 deletions main/services/subagents/child-agent-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import type {
ThinkingLevel,
} from "@earendil-works/pi-agent-core";
import type { AssistantMessage } from "@earendil-works/pi-ai";
import { writeDevLog } from "../dev-log.js";
import { buildAgentRuntimeOptions } from "../generation-runtime.js";
import {
assertGenerationContextCapacity,
Expand Down Expand Up @@ -79,6 +80,11 @@ interface RegisteredSubagentChild {
yieldingInference: boolean;
}

export interface SubagentRuntimeRegistryOptions {
appendPiMessages?: typeof appendPiMessages;
onPiJournalError?: (error: unknown) => void;
}

function childIdentity(
groupId: string,
requestedChildId?: string,
Expand Down Expand Up @@ -115,11 +121,14 @@ function boundedSettlement(
export class SubagentRuntimeRegistry {
private readonly children = new Map<string, RegisteredSubagentChild>();
private readonly concurrency: SubagentConcurrencyGate;
private readonly appendSessionMessages: typeof appendPiMessages;
private readonly onPiJournalError: (error: unknown) => void;
private shuttingDown = false;

constructor(
private healthMetrics?: SubagentHealthMetricsSink,
private readonly maxChildren = MAX_REGISTERED_SUBAGENT_CHILDREN,
options: SubagentRuntimeRegistryOptions = {},
) {
if (
!Number.isInteger(maxChildren) ||
Expand All @@ -129,6 +138,15 @@ export class SubagentRuntimeRegistry {
throw new Error("Invalid subagent runtime child limit.");
}
this.concurrency = new SubagentConcurrencyGate();
this.appendSessionMessages = options.appendPiMessages ?? appendPiMessages;
this.onPiJournalError =
options.onPiJournalError ??
((error) => {
writeDevLog("error", "subagents", [
"Could not append child Pi session messages.",
error,
]);
});
}

setHealthMetrics(healthMetrics: SubagentHealthMetricsSink): void {
Expand Down Expand Up @@ -184,7 +202,7 @@ export class SubagentRuntimeRegistry {
});
const sessionPromise = (async () => {
const session = await new InMemorySessionRepo().create({ id: sessionId });
await appendPiMessages(session, spec.initialMessages ?? []);
await this.appendSessionMessages(session, spec.initialMessages ?? []);
return session;
})();
const cancellation = new AbortController();
Expand All @@ -207,6 +225,21 @@ export class SubagentRuntimeRegistry {
lastAssistantMessage = event.message;
}
});
const flushPiMessages = async (
session: Awaited<typeof sessionPromise>,
): Promise<boolean> => {
if (pendingPiMessages.length === 0) return true;
const batch = pendingPiMessages;
pendingPiMessages = [];
try {
await this.appendSessionMessages(session, batch);
return true;
} catch (error) {
pendingPiMessages = [...batch, ...pendingPiMessages];
this.onPiJournalError(error);
return false;
}
};
const deployment: SubagentDeployment = isLocalProviderDeployment(
spec.runtime.provider,
)
Expand Down Expand Up @@ -287,9 +320,8 @@ export class SubagentRuntimeRegistry {
} else {
await agent.continue();
}
const batch = pendingPiMessages;
pendingPiMessages = [];
await appendPiMessages(session, batch);
const journalFlushed = await flushPiMessages(session);
if (!journalFlushed) break;
if (!lastAssistantMessage) break;
const result = await coordinator.check(lastAssistantMessage);
if (!result.messages) break;
Expand Down
Loading