feat(FN-3155): add createAiSession plugin context API with DI wiring
This merge brings FN-3155's plugin `createAiSession` API (types, DI hooks, engine adapter, context wiring, docs, and tests), FN-3056's task title sanitization, and FN-3129's tokenized footer and mobile initialization for MissionManager. It also adds CentralCore Docker node management, a new AddNodeM Fusion-Task-Id: FN-3155
This commit is contained in:
66
packages/core/src/__tests__/ai-engine-loader.test.ts
Normal file
66
packages/core/src/__tests__/ai-engine-loader.test.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
getCreateAiSessionFactory,
|
||||
getFnAgent,
|
||||
setCreateAiSessionFactory,
|
||||
setCreateFnAgent,
|
||||
} from "../ai-engine-loader.js";
|
||||
import type { CreateAiSessionFactory } from "../plugin-types.js";
|
||||
|
||||
describe("ai-engine-loader", () => {
|
||||
beforeEach(() => {
|
||||
setCreateFnAgent(undefined);
|
||||
setCreateAiSessionFactory(undefined);
|
||||
});
|
||||
|
||||
it("returns undefined createAiSession factory before registration", async () => {
|
||||
await expect(getCreateAiSessionFactory()).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("stores and returns createAiSession factory", async () => {
|
||||
const factory: CreateAiSessionFactory = vi.fn(async () => ({
|
||||
session: {
|
||||
prompt: async () => {},
|
||||
state: { messages: [] },
|
||||
},
|
||||
}));
|
||||
|
||||
setCreateAiSessionFactory(factory);
|
||||
|
||||
await expect(getCreateAiSessionFactory()).resolves.toBe(factory);
|
||||
});
|
||||
|
||||
it("clears createAiSession factory when set to undefined", async () => {
|
||||
setCreateAiSessionFactory(async () => ({
|
||||
session: {
|
||||
prompt: async () => {},
|
||||
state: { messages: [] },
|
||||
},
|
||||
}));
|
||||
|
||||
setCreateAiSessionFactory(undefined);
|
||||
|
||||
await expect(getCreateAiSessionFactory()).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("does not interfere with createFnAgent registration", async () => {
|
||||
const fnAgent = vi.fn();
|
||||
const factory: CreateAiSessionFactory = vi.fn(async () => ({
|
||||
session: {
|
||||
prompt: async () => {},
|
||||
state: { messages: [] },
|
||||
},
|
||||
}));
|
||||
|
||||
setCreateFnAgent(fnAgent);
|
||||
setCreateAiSessionFactory(factory);
|
||||
|
||||
await expect(getFnAgent()).resolves.toBe(fnAgent);
|
||||
await expect(getCreateAiSessionFactory()).resolves.toBe(factory);
|
||||
|
||||
setCreateAiSessionFactory(undefined);
|
||||
|
||||
await expect(getFnAgent()).resolves.toBe(fnAgent);
|
||||
await expect(getCreateAiSessionFactory()).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,8 @@ import { mkdtempSync, existsSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { PluginLoader } from "../plugin-loader.js";
|
||||
import { PluginStore } from "../plugin-store.js";
|
||||
import type { FusionPlugin, PluginManifest } from "../plugin-types.js";
|
||||
import { setCreateAiSessionFactory } from "../ai-engine-loader.js";
|
||||
import type { CreateAiSessionOptions, FusionPlugin, PluginManifest } from "../plugin-types.js";
|
||||
|
||||
// Test plugin manifest
|
||||
function makeManifest(overrides: Partial<PluginManifest> = {}): PluginManifest {
|
||||
@@ -147,11 +148,13 @@ describe("PluginLoader", () => {
|
||||
beforeEach(() => {
|
||||
rootDir = makeTmpDir();
|
||||
pluginStore = new PluginStore(rootDir, { inMemoryDb: true });
|
||||
setCreateAiSessionFactory(undefined);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
const { rm } = await import("node:fs/promises");
|
||||
await rm(rootDir, { recursive: true, force: true });
|
||||
setCreateAiSessionFactory(undefined);
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
@@ -990,6 +993,85 @@ describe("PluginLoader", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("createAiSession plugin context injection", () => {
|
||||
it("createContext includes createAiSession when factory is registered", async () => {
|
||||
const loader = new PluginLoader({ pluginStore, taskStore: mockTaskStore });
|
||||
const factory = vi.fn(async () => ({
|
||||
session: { prompt: async () => {}, state: { messages: [] } },
|
||||
}));
|
||||
setCreateAiSessionFactory(factory);
|
||||
|
||||
const context = await (loader as any).createContext(makePlugin(makeManifest({ id: "ctx-ai" })));
|
||||
|
||||
expect(context.createAiSession).toBe(factory);
|
||||
});
|
||||
|
||||
it("createContext sets createAiSession to undefined when no factory is registered", async () => {
|
||||
const loader = new PluginLoader({ pluginStore, taskStore: mockTaskStore });
|
||||
|
||||
const context = await (loader as any).createContext(makePlugin(makeManifest({ id: "ctx-no-ai" })));
|
||||
|
||||
expect(context).toHaveProperty("createAiSession");
|
||||
expect(context.createAiSession).toBeUndefined();
|
||||
});
|
||||
|
||||
it("createAiSession calls through to underlying factory with provided options", async () => {
|
||||
const loader = new PluginLoader({ pluginStore, taskStore: mockTaskStore });
|
||||
const factory = vi.fn(async () => ({
|
||||
session: { prompt: async () => {}, state: { messages: [] } },
|
||||
}));
|
||||
setCreateAiSessionFactory(factory);
|
||||
|
||||
const context = await (loader as any).createContext(makePlugin(makeManifest({ id: "ctx-call-through" })));
|
||||
const options: CreateAiSessionOptions = {
|
||||
cwd: rootDir,
|
||||
systemPrompt: "You are a plugin test agent",
|
||||
tools: "readonly",
|
||||
defaultProvider: "anthropic",
|
||||
defaultModelId: "claude-sonnet",
|
||||
};
|
||||
|
||||
await context.createAiSession?.(options);
|
||||
|
||||
expect(factory).toHaveBeenCalledWith(options);
|
||||
expect(factory).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("allows plugin onLoad to call ctx.createAiSession and receive a result", async () => {
|
||||
await pluginStore.init();
|
||||
|
||||
const pluginId = "onload-create-ai-session";
|
||||
const pluginDir = join(rootDir, "plugins");
|
||||
const pluginPath = await writePluginWithHooks(
|
||||
pluginDir,
|
||||
"onload-create-ai-session.js",
|
||||
{
|
||||
onLoad:
|
||||
"(async (ctx) => { const result = await ctx.createAiSession({ cwd: process.cwd(), systemPrompt: 'test prompt' }); if (!result?.session?.state?.messages) throw new Error('missing session result'); })",
|
||||
},
|
||||
makeManifest({ id: pluginId }),
|
||||
);
|
||||
|
||||
await pluginStore.registerPlugin({
|
||||
manifest: makeManifest({ id: pluginId }),
|
||||
path: pluginPath,
|
||||
});
|
||||
|
||||
setCreateAiSessionFactory(async () => ({
|
||||
session: {
|
||||
prompt: async () => {},
|
||||
state: { messages: [{ role: "assistant", content: "ok" }] },
|
||||
},
|
||||
sessionFile: join(rootDir, "session.json"),
|
||||
}));
|
||||
|
||||
const loader = new PluginLoader({ pluginStore, taskStore: mockTaskStore });
|
||||
const plugin = await loader.loadPlugin(pluginId);
|
||||
|
||||
expect(plugin.state).toBe("started");
|
||||
});
|
||||
});
|
||||
|
||||
// ── getPluginTools ─────────────────────────────────────────────────
|
||||
|
||||
describe("getPluginTools", () => {
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { mkdtempSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { PluginLoader } from "../plugin-loader.js";
|
||||
import { PluginStore } from "../plugin-store.js";
|
||||
import type {
|
||||
CreateAiSessionFactory,
|
||||
CreateAiSessionOptions,
|
||||
FusionPlugin,
|
||||
PluginPromptContribution,
|
||||
PluginPromptContributions,
|
||||
@@ -1241,3 +1248,50 @@ describe("validatePluginManifest contribution metadata", () => {
|
||||
expect(result.errors).toContain("setup.description is required and must be a non-empty string");
|
||||
});
|
||||
});
|
||||
|
||||
describe("CreateAiSession types", () => {
|
||||
it("supports CreateAiSessionOptions with required cwd and systemPrompt", () => {
|
||||
const options: CreateAiSessionOptions = {
|
||||
cwd: "/tmp/project",
|
||||
systemPrompt: "You are a plugin helper",
|
||||
};
|
||||
|
||||
expect(options.cwd).toBe("/tmp/project");
|
||||
expect(options.systemPrompt).toContain("plugin");
|
||||
});
|
||||
|
||||
it("supports CreateAiSessionFactory and AiSessionResult structural shape", async () => {
|
||||
const factory: CreateAiSessionFactory = async (options) => ({
|
||||
session: {
|
||||
prompt: async () => {
|
||||
void options.systemPrompt;
|
||||
},
|
||||
state: { messages: [{ role: "assistant", content: "hello" }] },
|
||||
},
|
||||
sessionFile: join(options.cwd, "session.json"),
|
||||
});
|
||||
|
||||
const result = await factory({ cwd: "/tmp/project", systemPrompt: "prompt" });
|
||||
expect(result.session.state.messages[0]?.role).toBe("assistant");
|
||||
expect(result.sessionFile).toContain("session.json");
|
||||
});
|
||||
|
||||
it("createContext runtime includes createAiSession field", async () => {
|
||||
const rootDir = mkdtempSync(join(tmpdir(), "kb-plugin-types-test-"));
|
||||
const pluginStore = new PluginStore(rootDir, { inMemoryDb: true });
|
||||
const loader = new PluginLoader({
|
||||
pluginStore,
|
||||
taskStore: { getRootDir: () => rootDir } as any,
|
||||
});
|
||||
|
||||
const context = await (loader as any).createContext({
|
||||
manifest: { id: "runtime-field-test", name: "Runtime", version: "1.0.0" },
|
||||
state: "installed",
|
||||
hooks: {},
|
||||
tools: [],
|
||||
routes: [],
|
||||
} as FusionPlugin);
|
||||
|
||||
expect(context).toHaveProperty("createAiSession");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,12 +10,15 @@
|
||||
* returns `undefined` and callers degrade gracefully.
|
||||
*/
|
||||
|
||||
import type { CreateAiSessionFactory } from "./plugin-types.js";
|
||||
|
||||
// Engine exports a function type we intentionally don't pull in here — importing
|
||||
// the type would reintroduce the cycle this module is designed to avoid.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
type CreateFnAgent = any;
|
||||
|
||||
let createFnAgent: CreateFnAgent | undefined;
|
||||
let createAiSessionFactory: CreateAiSessionFactory | undefined;
|
||||
|
||||
/** Shape of a message in an agent session's state. */
|
||||
export interface AgentMessage {
|
||||
@@ -38,3 +41,19 @@ export function setCreateFnAgent(fn: CreateFnAgent | undefined): void {
|
||||
export async function getFnAgent(): Promise<CreateFnAgent> {
|
||||
return createFnAgent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wire engine's plugin-facing AI session factory into core.
|
||||
* Called by `@fusion/engine` at module load; tests may register stubs.
|
||||
*/
|
||||
export function setCreateAiSessionFactory(fn: CreateAiSessionFactory | undefined): void {
|
||||
createAiSessionFactory = fn;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns engine-registered plugin AI session factory, or `undefined` when
|
||||
* engine hasn't registered it (common in isolated core tests).
|
||||
*/
|
||||
export async function getCreateAiSessionFactory(): Promise<CreateAiSessionFactory | undefined> {
|
||||
return createAiSessionFactory;
|
||||
}
|
||||
|
||||
@@ -147,6 +147,9 @@ export type {
|
||||
PluginRuntimeFactory,
|
||||
PluginRuntimeRegistration,
|
||||
PluginContext,
|
||||
CreateAiSessionOptions,
|
||||
AiSessionResult,
|
||||
CreateAiSessionFactory,
|
||||
PluginLogger,
|
||||
PluginSkillContribution,
|
||||
PluginWorkflowStepContribution,
|
||||
|
||||
@@ -35,6 +35,7 @@ import type {
|
||||
} from "./plugin-types.js";
|
||||
import { validatePluginManifest } from "./plugin-types.js";
|
||||
import { createLogger } from "./logger.js";
|
||||
import { getCreateAiSessionFactory } from "./ai-engine-loader.js";
|
||||
|
||||
// Minimum Fusion version for plugin compatibility checks (can be expanded later)
|
||||
const MINIMUM_FUSION_VERSION = "0.1.0";
|
||||
@@ -108,11 +109,21 @@ export class PluginLoader extends EventEmitter<{
|
||||
// ── Context Creation ───────────────────────────────────────────────
|
||||
|
||||
private async createContext(plugin: FusionPlugin): Promise<PluginContext> {
|
||||
const createAiSession = await getCreateAiSessionFactory();
|
||||
if (process.env.DEBUG?.includes("plugins")) {
|
||||
log.log(
|
||||
createAiSession
|
||||
? `[plugin:${plugin.manifest.id}] createAiSession available`
|
||||
: `[plugin:${plugin.manifest.id}] createAiSession unavailable`,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
pluginId: plugin.manifest.id,
|
||||
taskStore: this.options.taskStore,
|
||||
settings: await this.getPluginSettings(plugin.manifest.id),
|
||||
logger: this.createLogger(plugin.manifest.id),
|
||||
createAiSession,
|
||||
emitEvent: (event: string, data: unknown) => {
|
||||
this.emit("plugin:error", { pluginId: plugin.manifest.id, error: new Error(`Custom event: ${event}`) });
|
||||
// Custom events are logged but not surfaced as errors
|
||||
|
||||
@@ -79,6 +79,46 @@ export interface PluginSettingSchema {
|
||||
|
||||
// ── Plugin Hooks ─────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Options for creating an AI session from plugin runtime context.
|
||||
* This is a focused subset of engine agent options exposed to plugin authors.
|
||||
*/
|
||||
export interface CreateAiSessionOptions {
|
||||
/** Working directory for the agent session */
|
||||
cwd: string;
|
||||
/** System prompt for the agent */
|
||||
systemPrompt: string;
|
||||
/** Tool mode: "coding" for full tools, "readonly" for read-only */
|
||||
tools?: "coding" | "readonly";
|
||||
/** Default model provider (e.g., "anthropic") */
|
||||
defaultProvider?: string;
|
||||
/** Default model ID within the provider */
|
||||
defaultModelId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result returned from creating an AI session through PluginContext.
|
||||
*/
|
||||
export interface AiSessionResult {
|
||||
/** The underlying agent session — plugins call .prompt() on it */
|
||||
session: {
|
||||
prompt(text: string): Promise<void>;
|
||||
state: {
|
||||
messages: Array<{
|
||||
role: string;
|
||||
content?: unknown;
|
||||
}>;
|
||||
};
|
||||
};
|
||||
/** Path to persisted session file, if any */
|
||||
sessionFile?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Engine-injected factory for plugin AI sessions.
|
||||
*/
|
||||
export type CreateAiSessionFactory = (options: CreateAiSessionOptions) => Promise<AiSessionResult>;
|
||||
|
||||
/**
|
||||
* Context object passed to plugins at runtime.
|
||||
* Contains task store access, settings, logging, and event emission.
|
||||
@@ -93,6 +133,8 @@ export interface PluginContext {
|
||||
logger: PluginLogger;
|
||||
/** Emit custom events */
|
||||
emitEvent: (event: string, data: unknown) => void;
|
||||
/** Engine-injected AI session factory (undefined when engine is not loaded) */
|
||||
createAiSession?: CreateAiSessionFactory;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user