feat(FN-5203): merge fusion/fn-5203
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
createResolvedAgentSession,
|
||||
resolveExecutorSessionModel,
|
||||
resolvePlanningSessionModel,
|
||||
} from "../agent-session-helpers.js";
|
||||
import { MOCK_PROVIDER_ID } from "../providers/mock-provider.js";
|
||||
|
||||
const { resolveRuntimeMock } = vi.hoisted(() => ({
|
||||
resolveRuntimeMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../runtime-resolution.js", async () => {
|
||||
const actual = await vi.importActual<typeof import("../runtime-resolution.js")>("../runtime-resolution.js");
|
||||
return {
|
||||
...actual,
|
||||
resolveRuntime: resolveRuntimeMock,
|
||||
};
|
||||
});
|
||||
|
||||
describe("createResolvedAgentSession with mock provider", () => {
|
||||
beforeEach(() => {
|
||||
resolveRuntimeMock.mockReset().mockResolvedValue({
|
||||
runtime: {
|
||||
id: "pi",
|
||||
name: "pi",
|
||||
createSession: vi.fn(),
|
||||
promptWithFallback: vi.fn(),
|
||||
describeModel: vi.fn(),
|
||||
},
|
||||
runtimeId: "pi",
|
||||
wasConfigured: false,
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["executor", "triage", "reviewer", "merger", "heartbeat", "validation"] as const)(
|
||||
"selects mock runtime for %s sessions and bypasses runtime resolution",
|
||||
async (sessionPurpose) => {
|
||||
const beforeSpawnSession = vi.fn();
|
||||
const result = await createResolvedAgentSession({
|
||||
sessionPurpose,
|
||||
cwd: "/tmp/project/.worktrees/fn-5203",
|
||||
systemPrompt: "system",
|
||||
defaultProvider: ` ${MOCK_PROVIDER_ID.toUpperCase()} `,
|
||||
defaultModelId: "scripted",
|
||||
beforeSpawnSession,
|
||||
});
|
||||
|
||||
expect(result.runtimeId).toBe(MOCK_PROVIDER_ID);
|
||||
expect(result.wasConfigured).toBe(true);
|
||||
expect(resolveRuntimeMock).not.toHaveBeenCalled();
|
||||
expect(beforeSpawnSession).toHaveBeenCalledTimes(1);
|
||||
expect((result.session as any).__mock.sessionPurpose).toBe(sessionPurpose);
|
||||
|
||||
const shim = (result.session as any).promptWithFallback;
|
||||
expect(typeof shim).toBe("function");
|
||||
await expect(shim("hello from mock helper")).resolves.toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
it("leaves executor and planning model resolution unchanged for task-level mock provider", () => {
|
||||
expect(resolveExecutorSessionModel(MOCK_PROVIDER_ID, "scripted", undefined)).toEqual({
|
||||
provider: MOCK_PROVIDER_ID,
|
||||
modelId: "scripted",
|
||||
});
|
||||
expect(resolvePlanningSessionModel(MOCK_PROVIDER_ID, "scripted", undefined)).toEqual({
|
||||
provider: MOCK_PROVIDER_ID,
|
||||
modelId: "scripted",
|
||||
});
|
||||
});
|
||||
});
|
||||
241
packages/engine/src/__tests__/mock-provider.test.ts
Normal file
241
packages/engine/src/__tests__/mock-provider.test.ts
Normal file
@@ -0,0 +1,241 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { mkdtemp, mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
const { httpRequestMock, httpsRequestMock } = vi.hoisted(() => ({
|
||||
httpRequestMock: vi.fn(),
|
||||
httpsRequestMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("node:http", () => ({
|
||||
request: httpRequestMock,
|
||||
}));
|
||||
|
||||
vi.mock("node:https", () => ({
|
||||
request: httpsRequestMock,
|
||||
}));
|
||||
|
||||
import * as http from "node:http";
|
||||
import * as https from "node:https";
|
||||
import type { ToolDefinition } from "@mariozechner/pi-coding-agent";
|
||||
import { accumulateSessionTokenUsage } from "../session-token-usage.js";
|
||||
import {
|
||||
MOCK_PROVIDER_ID,
|
||||
MOCK_SYNTHETIC_TOKEN_USAGE,
|
||||
MockAgentRuntime,
|
||||
clearMockScript,
|
||||
resetMockScripts,
|
||||
setMockScript,
|
||||
} from "../providers/mock-provider.js";
|
||||
|
||||
function createTool(name: string, execute = vi.fn().mockResolvedValue({ content: [], details: {} })): ToolDefinition {
|
||||
return {
|
||||
name,
|
||||
label: name,
|
||||
description: name,
|
||||
parameters: { type: "object" } as never,
|
||||
execute,
|
||||
} as unknown as ToolDefinition;
|
||||
}
|
||||
|
||||
async function createWorkspace(taskId = "FN-5203") {
|
||||
const root = await mkdtemp(join(tmpdir(), "fn-mock-provider-"));
|
||||
const cwd = join(root, ".worktrees", "test-mode");
|
||||
await mkdir(cwd, { recursive: true });
|
||||
const taskDir = join(root, ".fusion", "tasks", taskId);
|
||||
await mkdir(taskDir, { recursive: true });
|
||||
await writeFile(join(taskDir, "task.json"), JSON.stringify({ id: taskId, steps: [{ status: "todo" }, { status: "done" }, { status: "todo" }] }), "utf8");
|
||||
return { root, cwd, taskDir, taskId };
|
||||
}
|
||||
|
||||
describe("MockAgentRuntime", () => {
|
||||
beforeEach(() => {
|
||||
resetMockScripts();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
resetMockScripts();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["executor", ["fn_task_show", "fn_task_update", "fn_task_update"]],
|
||||
["triage", ["write", "fn_review_spec"]],
|
||||
["reviewer", []],
|
||||
["merger", []],
|
||||
["heartbeat", []],
|
||||
["validation", []],
|
||||
] as const)("runs the default %s script deterministically", async (sessionPurpose, expectedCalls) => {
|
||||
const runtime = new MockAgentRuntime();
|
||||
const { cwd, taskDir, taskId } = await createWorkspace();
|
||||
const toolCalls: string[] = [];
|
||||
const writeExecute = vi.fn(async (_id, args) => {
|
||||
await writeFile(String((args as { path: string }).path), String((args as { content: string }).content), "utf8");
|
||||
toolCalls.push("write");
|
||||
return { content: [], details: {} };
|
||||
});
|
||||
const updateExecute = vi.fn(async (_id, args) => {
|
||||
toolCalls.push("fn_task_update");
|
||||
return { content: [{ type: "text", text: JSON.stringify(args) }], details: {} };
|
||||
});
|
||||
const reviewSpecExecute = vi.fn(async () => {
|
||||
toolCalls.push("fn_review_spec");
|
||||
return { content: [{ type: "text", text: "APPROVE" }], details: {} };
|
||||
});
|
||||
const taskShowExecute = vi.fn(async () => {
|
||||
toolCalls.push("fn_task_show");
|
||||
return { steps: [{ status: "todo" }, { status: "done" }, { status: "todo" }] };
|
||||
});
|
||||
const onText = vi.fn();
|
||||
const onToolStart = vi.fn();
|
||||
const onToolEnd = vi.fn();
|
||||
|
||||
const { session } = await runtime.createSession({
|
||||
cwd,
|
||||
systemPrompt: "system",
|
||||
runtimeContext: { sessionPurpose },
|
||||
customTools: [
|
||||
createTool("write", writeExecute),
|
||||
createTool("fn_task_show", taskShowExecute),
|
||||
createTool("fn_task_update", updateExecute),
|
||||
createTool("fn_review_spec", reviewSpecExecute),
|
||||
],
|
||||
onText,
|
||||
onToolStart,
|
||||
onToolEnd,
|
||||
taskId,
|
||||
taskTitle: "Mock task",
|
||||
});
|
||||
|
||||
await runtime.promptWithFallback(session, "run it");
|
||||
|
||||
expect(runtime.describeModel(session)).toBe("mock/scripted");
|
||||
expect((session as any).state).toEqual({});
|
||||
expect((session as any).getSessionStats()).toEqual({ tokens: MOCK_SYNTHETIC_TOKEN_USAGE });
|
||||
expect(toolCalls).toEqual(expectedCalls);
|
||||
expect(onToolStart.mock.calls.map(([name]) => name)).toEqual(expectedCalls);
|
||||
expect(onToolEnd.mock.calls.map(([name]) => name)).toEqual(expectedCalls);
|
||||
|
||||
if (sessionPurpose === "executor") {
|
||||
expect(taskShowExecute).toHaveBeenCalledTimes(1);
|
||||
}
|
||||
if (sessionPurpose === "triage") {
|
||||
const promptText = await readFile(join(taskDir, "PROMPT.md"), "utf8");
|
||||
expect(promptText).toContain("## Mission");
|
||||
}
|
||||
if (sessionPurpose === "reviewer" || sessionPurpose === "validation") {
|
||||
expect(onText).toHaveBeenCalledWith(expect.stringContaining("Verdict: APPROVE"));
|
||||
}
|
||||
});
|
||||
|
||||
it("prefers a task-scoped override over the default script", async () => {
|
||||
const runtime = new MockAgentRuntime();
|
||||
const { cwd, taskId } = await createWorkspace("FN-9999");
|
||||
const updateExecute = vi.fn();
|
||||
const override = vi.fn(async (ctx) => {
|
||||
await ctx.invokeTool("fn_task_update", { step: 7, status: "done" });
|
||||
});
|
||||
setMockScript({ sessionPurpose: "executor", taskId }, { run: override });
|
||||
|
||||
const { session } = await runtime.createSession({
|
||||
cwd,
|
||||
systemPrompt: "system",
|
||||
runtimeContext: { sessionPurpose: "executor" },
|
||||
customTools: [createTool("fn_task_update", updateExecute)],
|
||||
taskId,
|
||||
});
|
||||
|
||||
await runtime.promptWithFallback(session, "override");
|
||||
expect(override).toHaveBeenCalled();
|
||||
expect(updateExecute).toHaveBeenCalledWith(expect.any(String), { step: 7, status: "done" }, undefined, undefined, expect.anything());
|
||||
|
||||
clearMockScript({ sessionPurpose: "executor", taskId });
|
||||
updateExecute.mockClear();
|
||||
await runtime.promptWithFallback(session, "default");
|
||||
expect(updateExecute).toHaveBeenCalledWith(expect.any(String), { step: 1, status: "done" }, undefined, undefined, expect.anything());
|
||||
});
|
||||
|
||||
it("accumulates synthetic token usage once per session baseline", async () => {
|
||||
const runtime = new MockAgentRuntime();
|
||||
const { cwd, taskId } = await createWorkspace();
|
||||
const store = {
|
||||
getTask: vi.fn().mockResolvedValue({ tokenUsage: undefined }),
|
||||
updateTask: vi.fn(),
|
||||
};
|
||||
|
||||
const { session } = await runtime.createSession({
|
||||
cwd,
|
||||
systemPrompt: "system",
|
||||
runtimeContext: { sessionPurpose: "heartbeat" },
|
||||
taskId,
|
||||
});
|
||||
|
||||
await accumulateSessionTokenUsage(store as never, taskId, session);
|
||||
await accumulateSessionTokenUsage(store as never, taskId, session);
|
||||
|
||||
expect(store.updateTask).toHaveBeenCalledTimes(1);
|
||||
expect(store.updateTask).toHaveBeenCalledWith(taskId, {
|
||||
tokenUsage: expect.objectContaining({
|
||||
inputTokens: MOCK_SYNTHETIC_TOKEN_USAGE.input,
|
||||
outputTokens: MOCK_SYNTHETIC_TOKEN_USAGE.output,
|
||||
cachedTokens: MOCK_SYNTHETIC_TOKEN_USAGE.cacheRead,
|
||||
cacheWriteTokens: MOCK_SYNTHETIC_TOKEN_USAGE.cacheWrite,
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
it("never makes network calls and does not import network SDKs", async () => {
|
||||
const runtime = new MockAgentRuntime();
|
||||
const originalFetch = globalThis.fetch;
|
||||
const fetchSpy = vi.fn(async () => {
|
||||
throw new Error("fetch should not be called");
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchSpy);
|
||||
httpRequestMock.mockImplementation(() => {
|
||||
throw new Error("http.request should not be called");
|
||||
});
|
||||
httpsRequestMock.mockImplementation(() => {
|
||||
throw new Error("https.request should not be called");
|
||||
});
|
||||
|
||||
for (const sessionPurpose of ["executor", "triage", "reviewer", "merger", "heartbeat", "validation"] as const) {
|
||||
const { cwd, taskId } = await createWorkspace(`FN-${sessionPurpose}`);
|
||||
const { session } = await runtime.createSession({
|
||||
cwd,
|
||||
systemPrompt: "system",
|
||||
runtimeContext: { sessionPurpose },
|
||||
customTools: [
|
||||
createTool("write", vi.fn(async (_id, args) => {
|
||||
await writeFile(String((args as { path: string }).path), String((args as { content: string }).content), "utf8");
|
||||
return { content: [], details: {} };
|
||||
})),
|
||||
createTool("fn_task_update"),
|
||||
createTool("fn_review_spec"),
|
||||
createTool("fn_task_show"),
|
||||
],
|
||||
taskId,
|
||||
});
|
||||
await runtime.promptWithFallback(session, "network guard");
|
||||
}
|
||||
|
||||
expect(fetchSpy).not.toHaveBeenCalled();
|
||||
expect(http.request).toBe(httpRequestMock);
|
||||
expect(https.request).toBe(httpsRequestMock);
|
||||
expect(httpRequestMock).not.toHaveBeenCalled();
|
||||
expect(httpsRequestMock).not.toHaveBeenCalled();
|
||||
|
||||
if (originalFetch) {
|
||||
vi.stubGlobal("fetch", originalFetch);
|
||||
} else {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
|
||||
const source = await readFile(new URL("../providers/mock-provider.ts", import.meta.url), "utf8");
|
||||
for (const forbidden of ["node:http", "node:https", "undici", "node-fetch", "@mariozechner/pi-ai"]) {
|
||||
expect(source).not.toContain(forbidden);
|
||||
}
|
||||
expect(MOCK_PROVIDER_ID).toBe("mock");
|
||||
});
|
||||
});
|
||||
@@ -36,14 +36,18 @@ vi.mock("../pi.js", () => ({
|
||||
|
||||
// Mock the runtime resolution module
|
||||
const mockResolveRuntime = vi.fn();
|
||||
vi.mock("../runtime-resolution.js", () => ({
|
||||
resolveRuntime: (...args: unknown[]) => mockResolveRuntime(...args),
|
||||
buildRuntimeResolutionContext: vi.fn().mockReturnValue({
|
||||
sessionPurpose: "test",
|
||||
runtimeHint: undefined,
|
||||
pluginRunner: {},
|
||||
}),
|
||||
}));
|
||||
vi.mock("../runtime-resolution.js", async () => {
|
||||
const actual = await vi.importActual<typeof import("../runtime-resolution.js")>("../runtime-resolution.js");
|
||||
return {
|
||||
...actual,
|
||||
resolveRuntime: (...args: unknown[]) => mockResolveRuntime(...args),
|
||||
buildRuntimeResolutionContext: vi.fn().mockReturnValue({
|
||||
sessionPurpose: "test",
|
||||
runtimeHint: undefined,
|
||||
pluginRunner: {},
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
// Mock session skill context
|
||||
vi.mock("../session-skill-context.js", () => ({
|
||||
|
||||
@@ -17,12 +17,14 @@ import {
|
||||
resolveTaskPlanningModel,
|
||||
type Settings,
|
||||
} from "@fusion/core";
|
||||
import { resolveRuntime, buildRuntimeResolutionContext, type SessionPurpose } from "./runtime-resolution.js";
|
||||
import { resolveRuntime, buildRuntimeResolutionContext, isMockProviderId, type SessionPurpose } from "./runtime-resolution.js";
|
||||
import { createLogger } from "./logger.js";
|
||||
import { promptWithFallback, describeModel } from "./pi.js";
|
||||
import { MockAgentRuntime } from "./providers/mock-provider.js";
|
||||
|
||||
/** Logger for agent session helpers */
|
||||
const sessionLog = createLogger("agent-session");
|
||||
const mockRuntimeSingleton = new MockAgentRuntime();
|
||||
|
||||
function extractSkillNamesFromSelection(skillSelection: SkillSelectionContext | undefined): string[] {
|
||||
if (!skillSelection || !Array.isArray(skillSelection.requestedSkillNames)) {
|
||||
@@ -239,11 +241,24 @@ export async function createResolvedAgentSession(
|
||||
...(mergedSkillNames.length > 0 ? { skills: mergedSkillNames } : {}),
|
||||
};
|
||||
|
||||
// Build the resolution context
|
||||
const context = buildRuntimeResolutionContext(sessionPurpose, pluginRunner, runtimeHint);
|
||||
const useMockRuntime = isMockProviderId(runtimeOptions.defaultProvider);
|
||||
const effectiveRuntimeOptions = useMockRuntime
|
||||
? {
|
||||
...runtimeOptions,
|
||||
runtimeContext: {
|
||||
...runtimeOptions.runtimeContext,
|
||||
sessionPurpose,
|
||||
},
|
||||
}
|
||||
: runtimeOptions;
|
||||
|
||||
// Resolve the runtime
|
||||
const resolved = await resolveRuntime(context);
|
||||
const resolved = useMockRuntime
|
||||
? {
|
||||
runtime: mockRuntimeSingleton,
|
||||
runtimeId: mockRuntimeSingleton.id,
|
||||
wasConfigured: true,
|
||||
}
|
||||
: await resolveRuntime(buildRuntimeResolutionContext(sessionPurpose, pluginRunner, runtimeHint));
|
||||
|
||||
sessionLog.log(
|
||||
`[${sessionPurpose}] Using runtime "${resolved.runtimeId}" (configured=${resolved.wasConfigured})`,
|
||||
@@ -253,7 +268,7 @@ export async function createResolvedAgentSession(
|
||||
// latest sync point (just before LLM session instantiation) rather than
|
||||
// here, before the runtime's own awaited setup work runs. See
|
||||
// AgentRuntimeOptions.beforeSpawnSession for the contract.
|
||||
const result = await resolved.runtime.createSession(runtimeOptions);
|
||||
const result = await resolved.runtime.createSession(effectiveRuntimeOptions);
|
||||
|
||||
// Attach the resolved runtime's promptWithFallback as a bound method on the
|
||||
// session object when it is not already present. This is the dispatch hook
|
||||
|
||||
@@ -92,6 +92,19 @@ export {
|
||||
ensureDefaultHeartbeatProcedureFile,
|
||||
} from "./agent-instructions.js";
|
||||
export { HEARTBEAT_PROCEDURE, HEARTBEAT_SYSTEM_PROMPT, HEARTBEAT_NO_TASK_SYSTEM_PROMPT } from "./agent-heartbeat.js";
|
||||
export {
|
||||
MOCK_PROVIDER_ID,
|
||||
MOCK_SYNTHETIC_TOKEN_USAGE,
|
||||
MockAgentRuntime,
|
||||
MockAgentSession,
|
||||
mockScriptRegistry,
|
||||
setMockScript,
|
||||
clearMockScript,
|
||||
resetMockScripts,
|
||||
resolveMockScript,
|
||||
type MockScript,
|
||||
type MockScriptContext,
|
||||
} from "./providers/index.js";
|
||||
export { WorktreePool, scanIdleWorktrees, cleanupOrphanedWorktrees, reapOrphanWorktrees } from "./worktree-pool.js";
|
||||
export {
|
||||
pruneWorktreeAdminEntries,
|
||||
|
||||
13
packages/engine/src/providers/index.ts
Normal file
13
packages/engine/src/providers/index.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
export {
|
||||
MOCK_PROVIDER_ID,
|
||||
MOCK_SYNTHETIC_TOKEN_USAGE,
|
||||
MockAgentRuntime,
|
||||
MockAgentSession,
|
||||
mockScriptRegistry,
|
||||
setMockScript,
|
||||
clearMockScript,
|
||||
resetMockScripts,
|
||||
resolveMockScript,
|
||||
type MockScript,
|
||||
type MockScriptContext,
|
||||
} from "./mock-provider.js";
|
||||
275
packages/engine/src/providers/mock-provider.ts
Normal file
275
packages/engine/src/providers/mock-provider.ts
Normal file
@@ -0,0 +1,275 @@
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import * as fusionCore from "@fusion/core";
|
||||
import type { MockSessionPurpose } from "@fusion/core";
|
||||
import type { AgentRuntime, AgentRuntimeOptions, AgentSessionResult } from "../agent-runtime.js";
|
||||
import type { SessionPurpose } from "../runtime-resolution.js";
|
||||
import type { AgentSession, ToolDefinition } from "@mariozechner/pi-coding-agent";
|
||||
|
||||
function resolveProjectRootFromWorktree(cwd: string): string | undefined {
|
||||
try {
|
||||
const accessor = Reflect.get(fusionCore as object, "getProjectRootFromWorktree");
|
||||
if (typeof accessor === "function") {
|
||||
return (accessor as (worktreePath: string) => string | undefined)(cwd);
|
||||
}
|
||||
} catch {
|
||||
// Fall through to cwd below.
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export const MOCK_PROVIDER_ID = (() => {
|
||||
try {
|
||||
const value = Reflect.get(fusionCore as object, "MOCK_PROVIDER_ID");
|
||||
return typeof value === "string" && value.trim().length > 0 ? value : "mock";
|
||||
} catch {
|
||||
return "mock";
|
||||
}
|
||||
})();
|
||||
|
||||
/**
|
||||
* Intentionally non-zero token stats so budget-accounting paths still exercise
|
||||
* in test mode without relying on any provider pricing tables or network calls.
|
||||
*/
|
||||
export const MOCK_SYNTHETIC_TOKEN_USAGE = {
|
||||
input: 100,
|
||||
output: 50,
|
||||
cacheRead: 0,
|
||||
cacheWrite: 0,
|
||||
} as const;
|
||||
|
||||
export interface MockScriptContext {
|
||||
sessionPurpose: MockSessionPurpose;
|
||||
prompt: string;
|
||||
options: AgentRuntimeOptions;
|
||||
tools: ToolDefinition[];
|
||||
taskId?: string;
|
||||
taskTitle?: string;
|
||||
invokeTool(name: string, args: Record<string, unknown>): Promise<unknown>;
|
||||
}
|
||||
|
||||
export interface MockScript {
|
||||
run(ctx: MockScriptContext): Promise<void>;
|
||||
}
|
||||
|
||||
interface MockScriptKey {
|
||||
sessionPurpose: MockSessionPurpose;
|
||||
taskId?: string;
|
||||
}
|
||||
|
||||
function registryKey({ sessionPurpose, taskId }: MockScriptKey): string {
|
||||
return `${sessionPurpose}:${taskId ?? "*"}`;
|
||||
}
|
||||
|
||||
const overrides = new Map<string, MockScript>();
|
||||
|
||||
export const mockScriptRegistry = {
|
||||
setMockScript(key: MockScriptKey, script: MockScript): void {
|
||||
overrides.set(registryKey(key), script);
|
||||
},
|
||||
clearMockScript(key: MockScriptKey): void {
|
||||
overrides.delete(registryKey(key));
|
||||
},
|
||||
resetMockScripts(): void {
|
||||
overrides.clear();
|
||||
},
|
||||
resolveMockScript(key: MockScriptKey): MockScript {
|
||||
return overrides.get(registryKey(key))
|
||||
?? overrides.get(registryKey({ sessionPurpose: key.sessionPurpose }))
|
||||
?? DEFAULT_SCRIPTS[key.sessionPurpose];
|
||||
},
|
||||
};
|
||||
|
||||
export const setMockScript = mockScriptRegistry.setMockScript.bind(mockScriptRegistry);
|
||||
export const clearMockScript = mockScriptRegistry.clearMockScript.bind(mockScriptRegistry);
|
||||
export const resetMockScripts = mockScriptRegistry.resetMockScripts.bind(mockScriptRegistry);
|
||||
export const resolveMockScript = mockScriptRegistry.resolveMockScript.bind(mockScriptRegistry);
|
||||
|
||||
let toolCallCounter = 0;
|
||||
|
||||
interface MockAgentSessionState {
|
||||
sessionPurpose: MockSessionPurpose;
|
||||
options: AgentRuntimeOptions;
|
||||
}
|
||||
|
||||
interface MockToolCallResult {
|
||||
steps?: Array<{ status?: string }>;
|
||||
}
|
||||
|
||||
export class MockAgentSession {
|
||||
readonly __mock: MockAgentSessionState;
|
||||
readonly state: { errorMessage?: string; error?: string } = {};
|
||||
|
||||
constructor(options: AgentRuntimeOptions, sessionPurpose: MockSessionPurpose) {
|
||||
this.__mock = { options, sessionPurpose };
|
||||
}
|
||||
|
||||
dispose(): void {}
|
||||
|
||||
getSessionStats(): { tokens: typeof MOCK_SYNTHETIC_TOKEN_USAGE } {
|
||||
return { tokens: MOCK_SYNTHETIC_TOKEN_USAGE };
|
||||
}
|
||||
}
|
||||
|
||||
async function executeTool(
|
||||
tools: ToolDefinition[],
|
||||
options: AgentRuntimeOptions,
|
||||
name: string,
|
||||
args: Record<string, unknown>,
|
||||
): Promise<unknown> {
|
||||
const tool = tools.find((candidate) => candidate.name === name);
|
||||
if (!tool) {
|
||||
throw new Error(`Mock tool not available: ${name}`);
|
||||
}
|
||||
|
||||
options.onToolStart?.(tool.name, args);
|
||||
try {
|
||||
const result = await tool.execute(
|
||||
`mock-tool-${++toolCallCounter}`,
|
||||
args,
|
||||
undefined,
|
||||
undefined,
|
||||
{} as never,
|
||||
);
|
||||
options.onToolEnd?.(tool.name, false, result);
|
||||
return result;
|
||||
} catch (error) {
|
||||
options.onToolEnd?.(tool.name, true, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function buildPromptSkeleton(taskId: string): string {
|
||||
return `# Task: ${taskId}\n\n## Mission\n- Deterministic mock provider triage output.\n\n## Steps\n### Step 0: Preflight\n- Confirm scope and context.\n\n### Step 1: Implement\n- Make the requested changes.\n\n### Step 2: Testing\n- Run focused tests and broader verification.\n\n### Step 3: Docs\n- Update required documentation.\n\n## Completion Criteria\n- Tests relevant to the change pass.\n- Documentation is updated when required.\n\n## Git Commit Convention\n- Use FN-prefixed conventional commits.\n`;
|
||||
}
|
||||
|
||||
function extractStepsFromTaskShowResult(result: unknown): Array<{ status?: string }> {
|
||||
const candidates: unknown[] = [result];
|
||||
if (result && typeof result === "object") {
|
||||
const record = result as Record<string, unknown>;
|
||||
candidates.push(record.details);
|
||||
candidates.push(record.task);
|
||||
}
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (!candidate || typeof candidate !== "object") continue;
|
||||
const maybeSteps = (candidate as MockToolCallResult).steps;
|
||||
if (Array.isArray(maybeSteps)) {
|
||||
return maybeSteps;
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
async function loadTaskSteps(options: AgentRuntimeOptions): Promise<Array<{ status?: string }>> {
|
||||
const taskId = options.taskId;
|
||||
if (!taskId) return [];
|
||||
const projectRoot = resolveProjectRootFromWorktree(options.cwd) ?? options.cwd;
|
||||
const taskJsonPath = join(projectRoot, ".fusion", "tasks", taskId, "task.json");
|
||||
try {
|
||||
const raw = await readFile(taskJsonPath, "utf8");
|
||||
const parsed = JSON.parse(raw) as { steps?: Array<{ status?: string }> };
|
||||
return Array.isArray(parsed.steps) ? parsed.steps : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
const DEFAULT_SCRIPTS: Record<MockSessionPurpose, MockScript> = {
|
||||
executor: {
|
||||
async run(ctx) {
|
||||
let steps: Array<{ status?: string }> = [];
|
||||
if (ctx.taskId && ctx.tools.some((tool) => tool.name === "fn_task_show")) {
|
||||
const taskDetails = await ctx.invokeTool("fn_task_show", { id: ctx.taskId });
|
||||
steps = extractStepsFromTaskShowResult(taskDetails);
|
||||
}
|
||||
if (steps.length === 0) {
|
||||
steps = await loadTaskSteps(ctx.options);
|
||||
}
|
||||
for (const [index, step] of steps.entries()) {
|
||||
if (step.status !== "done" && step.status !== "skipped") {
|
||||
await ctx.invokeTool("fn_task_update", { step: index + 1, status: "done" });
|
||||
}
|
||||
}
|
||||
ctx.options.onText?.("Mock executor completed scripted step updates.");
|
||||
},
|
||||
},
|
||||
triage: {
|
||||
async run(ctx) {
|
||||
const taskId = ctx.taskId ?? "FN-TEST";
|
||||
const projectRoot = resolveProjectRootFromWorktree(ctx.options.cwd) ?? ctx.options.cwd;
|
||||
const promptPath = join(projectRoot, ".fusion", "tasks", taskId, "PROMPT.md");
|
||||
const content = buildPromptSkeleton(taskId);
|
||||
const writeTool = ctx.tools.find((tool) => tool.name === "write");
|
||||
if (writeTool) {
|
||||
await ctx.invokeTool("write", { path: promptPath, content });
|
||||
} else {
|
||||
await mkdir(join(projectRoot, ".fusion", "tasks", taskId), { recursive: true });
|
||||
await writeFile(promptPath, content, "utf8");
|
||||
}
|
||||
if (ctx.tools.some((tool) => tool.name === "fn_review_spec")) {
|
||||
await ctx.invokeTool("fn_review_spec", {});
|
||||
} else {
|
||||
ctx.options.onText?.("APPROVE");
|
||||
}
|
||||
},
|
||||
},
|
||||
reviewer: {
|
||||
async run(ctx) {
|
||||
ctx.options.onText?.("Verdict: APPROVE\n\nSummary: Mock reviewer approved scripted output.\n");
|
||||
},
|
||||
},
|
||||
merger: {
|
||||
async run(ctx) {
|
||||
ctx.options.onText?.("Mock merger no-op.");
|
||||
},
|
||||
},
|
||||
heartbeat: {
|
||||
async run(ctx) {
|
||||
ctx.options.onText?.("Mock heartbeat no-op.");
|
||||
},
|
||||
},
|
||||
validation: {
|
||||
async run(ctx) {
|
||||
ctx.options.onText?.("Verdict: APPROVE\n\nSummary: Mock validation passed.\n");
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export class MockAgentRuntime implements AgentRuntime {
|
||||
readonly id = MOCK_PROVIDER_ID;
|
||||
readonly name = "Mock Provider (test mode)";
|
||||
|
||||
async createSession(options: AgentRuntimeOptions): Promise<AgentSessionResult> {
|
||||
await options.beforeSpawnSession?.();
|
||||
const sessionPurpose = (options.runtimeContext?.sessionPurpose as SessionPurpose | undefined) ?? "executor";
|
||||
return {
|
||||
session: new MockAgentSession(options, sessionPurpose) as unknown as AgentSession,
|
||||
sessionFile: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
async promptWithFallback(session: AgentSession, prompt: string, _promptOptions?: unknown): Promise<void> {
|
||||
const mockSession = session as unknown as MockAgentSession;
|
||||
const { options, sessionPurpose } = mockSession.__mock;
|
||||
const tools = options.customTools ?? [];
|
||||
const script = mockScriptRegistry.resolveMockScript({
|
||||
sessionPurpose,
|
||||
taskId: options.taskId,
|
||||
});
|
||||
await script.run({
|
||||
sessionPurpose,
|
||||
prompt,
|
||||
options,
|
||||
tools,
|
||||
taskId: options.taskId,
|
||||
taskTitle: options.taskTitle,
|
||||
invokeTool: (name, args) => executeTool(tools, options, name, args),
|
||||
});
|
||||
}
|
||||
|
||||
describeModel(_session: AgentSession): string {
|
||||
return "mock/scripted";
|
||||
}
|
||||
}
|
||||
@@ -9,10 +9,24 @@
|
||||
|
||||
import type { AgentRuntime, AgentRuntimeOptions, AgentSessionResult } from "./agent-runtime.js";
|
||||
import type { PluginRunner } from "./plugin-runner.js";
|
||||
import * as fusionCore from "@fusion/core";
|
||||
import type { AgentSession } from "@mariozechner/pi-coding-agent";
|
||||
import { createLogger } from "./logger.js";
|
||||
import { createFnAgent, promptWithFallback, describeModel } from "./pi.js";
|
||||
|
||||
const MOCK_PROVIDER_ID = (() => {
|
||||
try {
|
||||
const value = Reflect.get(fusionCore as object, "MOCK_PROVIDER_ID");
|
||||
return typeof value === "string" && value.trim().length > 0 ? value : "mock";
|
||||
} catch {
|
||||
return "mock";
|
||||
}
|
||||
})();
|
||||
|
||||
export function isMockProviderId(provider: string | undefined): boolean {
|
||||
return provider?.trim().toLowerCase() === MOCK_PROVIDER_ID;
|
||||
}
|
||||
|
||||
/** Logger for the runtime resolution subsystem */
|
||||
const runtimeLog = createLogger("runtime-resolver");
|
||||
|
||||
|
||||
Reference in New Issue
Block a user