UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

1,140 lines • 51.3 kB
// allow: SIZE_OK - pre-existing extension API wiring, aliases, cache, and discovery glue; the native Bun filesystem importer lives in its own module.
/**
 * Extension loader - native Bun imports on any Bun runtime, lazy jiti on Node.
 *
 */
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
    if (typeof path === "string" && /^\.\.?\//.test(path)) {
        return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
            return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
        });
    }
    return path;
};
import * as fs from "node:fs";
import { createRequire } from "node:module";
import * as path from "node:path";
import { fileURLToPath } from "node:url";
import * as _bundledPiAgentCore from "@earendil-works/pi-agent-core";
import * as _bundledPiAiCompat from "@earendil-works/pi-ai/compat";
import * as _bundledPiAiOauth from "@earendil-works/pi-ai/oauth";
import * as _bundledPiAiProviders from "@earendil-works/pi-ai/providers/all";
import * as _bundledPiTui from "@earendil-works/pi-tui";
// Static imports of packages that extensions may use.
// These MUST be static so Bun bundles them into the compiled binary.
// The virtualModules option then makes them available to extensions.
import * as _bundledTypebox from "typebox";
import * as _bundledTypeboxCompile from "typebox/compile";
import * as _bundledTypeboxValue from "typebox/value";
import { CONFIG_DIR_NAME, getAgentDir, isBunBinary, isBundledNode, isBunRuntime, VERSION } from "../../config.js";
// NOTE: This import works because loader.ts exports are NOT re-exported from index.ts,
// avoiding a circular dependency. Extensions can import from @code-yeongyu/senpi.
import * as _bundledPiCodingAgent from "../../index.js";
import * as _bundledSessionWorkerData from "../../modes/rpc/session-worker-data.js";
import { resolvePath } from "../../utils/paths.js";
import { createEventBus, EXTENSION_RPC_EVENT_CHANNEL } from "../event-bus.js";
import { execCommand } from "../exec.js";
import { RESERVED_MEMORY_REPORT_KEYS } from "../memory-report/memory-report-registry.js";
import { readPiManifest } from "../pi-manifest.js";
import { unboundSessionControlActions } from "../session-control-actions.js";
import { redactForUpload } from "../share/upload-redaction.js";
import { createSyntheticSourceInfo, getSyntheticPathSource, isSyntheticPath } from "../source-info.js";
import { subscriptionLimits } from "../subscription-limits/limit-store.js";
import { time } from "../timings.js";
import { validateChildModuleRegistration } from "../tool-dispatch/offload.js";
import { registerReadClassifier } from "../tools/read-classifiers.js";
import { validateMcpServerDeclaration } from "./builtin/mcp/config-schema.js";
import { registerRpcRemoteSource } from "./builtin/terminal/rpc-remote-source.js";
import { McpServerRegistry } from "./mcp-server-registry.js";
import { readPermissionPreset } from "./builtin/permission-system/preset-registry.js";
import { ownedBy, runOwnedBy } from "./extension-handle-ledger.js";
import { recordExtensionLoadKey } from "./extension-load-key.js";
import { cachedExtensionFactory, extensionModuleImporter, rememberExtensionFactory, } from "./extension-module-cache.js";
import { kernelToolInvokerStorage } from "./kernel-tools-context.js";
import { createLifecycleApi } from "./lifecycle-api.js";
import { withProviderLoginStart } from "./provider-login-start.js";
import { createSessionDialogApi } from "./session-dialog-api.js";
import { StaleExtensionContextError } from "./stale-context-error.js";
import { DEFAULT_EXTENSION_SESSION_PROFILE, DeviceMachineConflictError, EMPTY_SESSION_CONTEXT } from "./types.js";
function sessionProfile(options) {
    return {
        sessionKind: options?.sessionKind ?? "interactive",
        sessionContext: options?.sessionContext ?? EMPTY_SESSION_CONTEXT,
        ...(options?.side === undefined ? {} : { side: options.side }),
    };
}
function assertExtensionSide(extension, runs, registration) {
    if (runs === "brain" || runs === "hand")
        return;
    throw new Error(`Extension "${extension.path}" declared runs: ${JSON.stringify(runs)} for ${registration}; runs must be "brain" or "hand".`);
}
/** The events whose handlers may declare `{ providers }` (CK21). */
const PROVIDER_HOOK_EVENTS = [
    "before_provider_request",
    "provider_stream_event",
    "after_provider_response",
];
function declaredProviders(extension, providers, registration) {
    if (Array.isArray(providers) &&
        providers.length > 0 &&
        providers.every((provider) => typeof provider === "string" && provider !== ""))
        return Object.freeze([...providers]);
    throw new Error(`Extension "${extension.path}" declared providers: ${JSON.stringify(providers)} for ${registration}; providers must be a non-empty array of provider ids.`);
}
/** Modules available to extensions via virtualModules (for compiled binaries) */
const VIRTUAL_MODULES = {
    typebox: _bundledTypebox,
    "typebox/compile": _bundledTypeboxCompile,
    "typebox/value": _bundledTypeboxValue,
    "@sinclair/typebox": _bundledTypebox,
    "@sinclair/typebox/compile": _bundledTypeboxCompile,
    "@sinclair/typebox/value": _bundledTypeboxValue,
    "@earendil-works/pi-agent-core": _bundledPiAgentCore,
    "@earendil-works/pi-tui": _bundledPiTui,
    // Extensions resolve the pi-ai root to the compat entrypoint (a strict
    // superset of the core entrypoint): existing extensions using the old
    // global API keep working at runtime until compat is removed.
    "@earendil-works/pi-ai": _bundledPiAiCompat,
    "@earendil-works/pi-ai/compat": _bundledPiAiCompat,
    "@earendil-works/pi-ai/oauth": _bundledPiAiOauth,
    "@earendil-works/pi-ai/providers/all": _bundledPiAiProviders,
    "@earendil-works/pi-coding-agent": _bundledPiCodingAgent,
    "@mariozechner/pi-agent-core": _bundledPiAgentCore,
    "@mariozechner/pi-tui": _bundledPiTui,
    "@mariozechner/pi-ai": _bundledPiAiCompat,
    "@mariozechner/pi-ai/compat": _bundledPiAiCompat,
    "@mariozechner/pi-ai/oauth": _bundledPiAiOauth,
    "@mariozechner/pi-ai/providers/all": _bundledPiAiProviders,
    "@mariozechner/pi-coding-agent": _bundledPiCodingAgent,
    "@code-yeongyu/senpi": _bundledPiCodingAgent,
    "@code-yeongyu/senpi/session-worker-data": _bundledSessionWorkerData,
};
const require = createRequire(import.meta.url);
const isNodeSeaBinary = ("sea" in process.features && process.features.sea === true) ||
    process.getBuiltinModule("node:sea")?.isSea() === true;
const isTypeScriptSourceRuntime = !isBunBinary && path.extname(fileURLToPath(import.meta.url)) === ".ts";
// Bun.Transpiler, Bun.resolveSync and Bun.plugin exist on every Bun runtime, not
// just inside compiled binaries: a bun-global install must not pay jiti + Babel
// for the bundled codemode extension and user TypeScript extensions on each boot.
const usesNativeBunImports = isBunBinary || isBunRuntime;
/**
 * Get aliases for jiti (used in built Node.js mode).
 * In compiled binary mode, virtualModules is used instead.
 */
let _aliases = null;
function getAliases() {
    if (_aliases)
        return _aliases;
    const __dirname = path.dirname(fileURLToPath(import.meta.url));
    const typeboxEntry = require.resolve("typebox");
    const typeboxCompileEntry = require.resolve("typebox/compile");
    const typeboxValueEntry = require.resolve("typebox/value");
    const codingAgentPackageRoot = path.resolve(__dirname, "../../..");
    const packagesRoot = path.dirname(codingAgentPackageRoot);
    const resolveWorkspaceOrBundled = (packageName, packageEntryRelativePath, workspaceRelativePath, sourceRelativePath, specifier) => {
        const bundledPath = path.join(codingAgentPackageRoot, "node_modules", packageName, packageEntryRelativePath);
        if (fs.existsSync(bundledPath)) {
            return bundledPath;
        }
        const workspacePath = path.join(packagesRoot, workspaceRelativePath);
        if (fs.existsSync(workspacePath)) {
            return workspacePath;
        }
        const sourcePath = path.join(packagesRoot, sourceRelativePath);
        if (fs.existsSync(sourcePath)) {
            return sourcePath;
        }
        return typeof import.meta.resolve === "function"
            ? fileURLToPath(import.meta.resolve(specifier))
            : require.resolve(specifier);
    };
    const piCodingAgentDistEntry = path.join(codingAgentPackageRoot, "dist/index.js");
    const piCodingAgentSourceEntry = path.join(codingAgentPackageRoot, "src/index.ts");
    const piCodingAgentEntry = fs.existsSync(piCodingAgentDistEntry) ? piCodingAgentDistEntry : piCodingAgentSourceEntry;
    const sessionWorkerDataDistEntry = path.join(codingAgentPackageRoot, "dist/modes/rpc/session-worker-data.js");
    const sessionWorkerDataEntry = fs.existsSync(sessionWorkerDataDistEntry)
        ? sessionWorkerDataDistEntry
        : path.join(codingAgentPackageRoot, "src/modes/rpc/session-worker-data.ts");
    const piAgentCoreEntry = resolveWorkspaceOrBundled("@earendil-works/pi-agent-core", "dist/index.js", "agent/dist/index.js", "agent/src/index.ts", "@earendil-works/pi-agent-core");
    const piTuiEntry = resolveWorkspaceOrBundled("@earendil-works/pi-tui", "dist/index.js", "tui/dist/index.js", "tui/src/index.ts", "@earendil-works/pi-tui");
    const piAiCompatEntry = resolveWorkspaceOrBundled("@earendil-works/pi-ai", "dist/compat.js", "ai/dist/compat.js", "ai/src/compat.ts", "@earendil-works/pi-ai/compat");
    const piAiOauthEntry = resolveWorkspaceOrBundled("@earendil-works/pi-ai", "dist/oauth.js", "ai/dist/oauth.js", "ai/src/oauth.ts", "@earendil-works/pi-ai/oauth");
    const piAiProvidersEntry = resolveWorkspaceOrBundled("@earendil-works/pi-ai", "dist/providers/all.js", "ai/dist/providers/all.js", "ai/src/providers/all.ts", "@earendil-works/pi-ai/providers/all");
    _aliases = {
        "@earendil-works/pi-coding-agent": piCodingAgentEntry,
        "@earendil-works/pi-agent-core": piAgentCoreEntry,
        "@earendil-works/pi-tui": piTuiEntry,
        "@earendil-works/pi-ai/providers/all": piAiProvidersEntry,
        "@earendil-works/pi-ai/compat": piAiCompatEntry,
        "@earendil-works/pi-ai/oauth": piAiOauthEntry,
        "@earendil-works/pi-ai": piAiCompatEntry,
        "@code-yeongyu/senpi": piCodingAgentEntry,
        "@code-yeongyu/senpi/session-worker-data": sessionWorkerDataEntry,
        "@mariozechner/pi-coding-agent": piCodingAgentEntry,
        "@mariozechner/pi-agent-core": piAgentCoreEntry,
        "@mariozechner/pi-tui": piTuiEntry,
        "@mariozechner/pi-ai/providers/all": piAiProvidersEntry,
        "@mariozechner/pi-ai/compat": piAiCompatEntry,
        "@mariozechner/pi-ai/oauth": piAiOauthEntry,
        "@mariozechner/pi-ai": piAiCompatEntry,
        typebox: typeboxEntry,
        "typebox/compile": typeboxCompileEntry,
        "typebox/value": typeboxValueEntry,
        "@sinclair/typebox": typeboxEntry,
        "@sinclair/typebox/compile": typeboxCompileEntry,
        "@sinclair/typebox/value": typeboxValueEntry,
    };
    return _aliases;
}
// Bun's module registry must not own generation graphs. Live runtimes and the
// existing factory cache retain wrappers; invalidation releases runtime ownership.
const runtimeFactories = new WeakMap();
export { clearExtensionCache, extensionModuleGenerationCount } from "./extension-module-cache.js";
/**
 * Create a runtime with throwing stubs for action methods.
 * Runner.bindCore() replaces these with real implementations.
 */
export function createExtensionRuntime() {
    const notInitialized = () => {
        throw new Error("Extension runtime not initialized. Action methods cannot be called during extension loading.");
    };
    const state = {};
    // Shared sequence across the legacy and native pre-bind queues so flushers
    // can replay registrations in original call order (last-registration-wins).
    let nextProviderRegistrationOrder = 0;
    const eventBusUnsubscribers = new Set();
    const assertActive = () => {
        if (state.staleMessage) {
            throw new StaleExtensionContextError(state.staleMessage);
        }
    };
    const runtime = {
        deviceMachine: undefined,
        isLoopRemote: () => false,
        sendMessage: notInitialized,
        sendUserMessage: notInitialized,
        appendEntry: notInitialized,
        setSessionName: notInitialized,
        getSessionName: notInitialized,
        setLabel: notInitialized,
        executeTool: () => Promise.reject(new Error("Extension runtime not initialized")),
        getActiveTools: notInitialized,
        getAllTools: notInitialized,
        getSettings: notInitialized,
        setActiveTools: notInitialized,
        // registerTool() is valid during extension load; refresh is only needed post-bind.
        refreshTools: () => { },
        registerRemovedToolHint: () => { },
        registerLazyToolActivator: () => { },
        getCommands: notInitialized,
        setModel: () => Promise.reject(new Error("Extension runtime not initialized")),
        getThinkingLevel: notInitialized,
        setThinkingLevel: notInitialized,
        setSessionModel: () => Promise.reject(new Error("Extension runtime not initialized")),
        setSessionThinkingLevel: notInitialized,
        setSessionFastMode: notInitialized,
        sessionControl: unboundSessionControlActions(),
        flagValues: new Map(),
        pendingProviderRegistrations: [],
        pendingNativeProviderRegistrations: [],
        pendingVirtualModelRegistrations: [],
        mcpServers: new McpServerRegistry(),
        createContext: notInitialized,
        assertActive,
        invalidate: (message) => {
            if (state.staleMessage)
                return;
            state.staleMessage =
                message ??
                    "This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().";
            for (const unsubscribe of eventBusUnsubscribers)
                unsubscribe();
            eventBusUnsubscribers.clear();
            runtime.evalHandleHost = undefined;
            runtimeFactories.delete(runtime);
        },
        trackEventBusSubscription: (unsubscribe) => {
            let active = true;
            const trackedUnsubscribe = () => {
                if (!active)
                    return;
                active = false;
                eventBusUnsubscribers.delete(trackedUnsubscribe);
                unsubscribe();
            };
            eventBusUnsubscribers.add(trackedUnsubscribe);
            return trackedUnsubscribe;
        },
        // Pre-bind: queue registrations so bindCore() can flush them once the
        // model registry is available. bindCore() replaces both with direct calls.
        registerProvider: (name, config, extensionPath = "<unknown>") => {
            runtime.pendingProviderRegistrations.push({
                name,
                config,
                extensionPath,
                order: nextProviderRegistrationOrder++,
            });
        },
        registerNativeProvider: (provider, extensionPath = "<unknown>") => {
            runtime.pendingNativeProviderRegistrations.push({
                provider,
                extensionPath,
                order: nextProviderRegistrationOrder++,
            });
        },
        unregisterProvider: (name) => {
            runtime.pendingProviderRegistrations = runtime.pendingProviderRegistrations.filter((r) => r.name !== name);
            runtime.pendingNativeProviderRegistrations = runtime.pendingNativeProviderRegistrations.filter((r) => r.provider.id !== name);
        },
        registerVirtualModel: (definition, extensionPath = "<unknown>") => {
            runtime.pendingVirtualModelRegistrations.push({ definition, extensionPath });
        },
        unregisterVirtualModel: (provider, id) => {
            runtime.pendingVirtualModelRegistrations = runtime.pendingVirtualModelRegistrations.filter(({ definition }) => definition.provider !== provider || definition.id !== id);
        },
        emitProviderLoginStart: async () => { },
    };
    return runtime;
}
const unboundSessionControl = unboundSessionControlActions();
function sessionControlOf(runtime) {
    return runtime.sessionControl ?? unboundSessionControl;
}
/**
 * Drain queued pre-bind provider registrations in original call order.
 *
 * Legacy (name/config) and native registrations queue in separate arrays during
 * extension loading, each stamped with a shared sequence number. Flushers replay
 * entries ordered by that sequence so mixed registerProvider(name, config) /
 * registerProvider(provider) calls keep last-registration-wins. Clears both queues.
 */
export function drainPendingProviderRegistrations(runtime) {
    const drained = [
        ...runtime.pendingProviderRegistrations.map((entry) => ({ kind: "config", ...entry })),
        ...runtime.pendingNativeProviderRegistrations.map((entry) => ({ kind: "native", ...entry })),
    ];
    drained.sort((a, b) => a.order - b.order);
    runtime.pendingProviderRegistrations = [];
    runtime.pendingNativeProviderRegistrations = [];
    return drained;
}
/**
 * Create the ExtensionAPI for an extension.
 * Registration methods write to the extension object.
 * Action methods delegate to the shared runtime.
 */
/**
 * The session a handler's host context belongs to. A stale context (session replacement still reports
 * `session_extensions_removed` on the invalidated runner) has none: its handler runs with no ambient
 * invoker, and its own guarded getters, kernelTools included, still refuse it.
 */
function handlerSessionId(context) {
    if (!context || !("sessionManager" in context))
        return undefined;
    try {
        return context.sessionManager?.getSessionId();
    }
    catch (error) {
        if (error instanceof StaleExtensionContextError)
            return undefined;
        throw error;
    }
}
function createExtensionAPI(extension, runtime, cwd, eventBus, session) {
    const pendingFlagValues = new Map();
    const pendingRuntimeChanges = [];
    const loadingUnsubscribers = [];
    let state = "loading";
    const assertActive = () => {
        if (state === "failed") {
            throw new Error(`Extension "${extension.path}" failed to load and its API is no longer active.`);
        }
        runtime.assertActive();
    };
    let deviceMachineStaged = false;
    const applyRuntimeChange = (change) => {
        if (state === "loading")
            pendingRuntimeChanges.push(change);
        else
            change();
    };
    const clearPending = () => {
        deviceMachineStaged = false;
        pendingFlagValues.clear();
        pendingRuntimeChanges.length = 0;
        loadingUnsubscribers.length = 0;
    };
    const api = {
        cwd,
        sessionKind: session.sessionKind,
        sessionContext: session.sessionContext,
        get engine() {
            return _bundledPiCodingAgent;
        },
        // Registration methods - write to extension
        on(event, handler, options) {
            assertActive();
            const runs = options?.runs;
            if (runs !== undefined)
                assertExtensionSide(extension, runs, `"${event}"`);
            // Checked on every side, also for a handler this side does not register: a malformed declaration always throws.
            const providers = PROVIDER_HOOK_EVENTS.includes(event) && options?.providers !== undefined
                ? declaredProviders(extension, options.providers, `"${event}"`)
                : undefined;
            if (runs !== undefined && session.side !== undefined && runs !== session.side)
                return () => { };
            const registeredHandler = ownedBy(extension, (...args) => {
                // A child event can run inside its parent's task-tool async scope.
                // Bind the host context here, preserving registered-handler metadata.
                const sessionId = handlerSessionId(args[1]);
                const invoke = () => handler(...args);
                return sessionId
                    ? kernelToolInvokerStorage.run({ sessionId }, invoke)
                    : kernelToolInvokerStorage.exit(invoke);
            });
            const list = extension.handlers.get(event) ?? [];
            list.push(registeredHandler);
            extension.handlers.set(event, list);
            if (runs !== undefined) {
                extension.handlerSides ??= new WeakMap();
                extension.handlerSides.set(registeredHandler, runs);
            }
            if (providers !== undefined) {
                extension.handlerProviders ??= new WeakMap();
                extension.handlerProviders.set(registeredHandler, providers);
            }
            if (event === "before_agent_start" && options?.previewSafe === true) {
                extension.previewSafeHandlers ??= new WeakSet();
                extension.previewSafeHandlers.add(registeredHandler);
            }
            if (event === "before_agent_start" && options?.runLast === true) {
                extension.runLastHandlers ??= new WeakSet();
                extension.runLastHandlers.add(registeredHandler);
            }
            if ((event === "context" || event === "context_with_system") && options?.mutatesMessages === false) {
                extension.nonMutatingContextHandlers ??= new WeakSet();
                extension.nonMutatingContextHandlers.add(registeredHandler);
            }
            return () => {
                const handlers = extension.handlers.get(event);
                if (!handlers)
                    return;
                const handlerIndex = handlers.indexOf(registeredHandler);
                if (handlerIndex === -1)
                    return;
                handlers.splice(handlerIndex, 1);
                if (handlers.length === 0)
                    extension.handlers.delete(event);
            };
        },
        registerDeviceMachine(machine) {
            assertActive();
            if (runtime.deviceMachine !== undefined) {
                throw new DeviceMachineConflictError(runtime.deviceMachine.extensionPath, extension.path);
            }
            if (deviceMachineStaged)
                throw new DeviceMachineConflictError(extension.path, extension.path);
            deviceMachineStaged = true;
            // Staged like provider registrations: a factory that throws after registering leaves no device behind.
            applyRuntimeChange(() => {
                runtime.deviceMachine = { machine, extensionPath: extension.path };
            });
        },
        registerTool(tool) {
            runtime.assertActive();
            if (tool.name === "tool_search" && extension.sourceInfo.source !== "builtin") {
                throw new Error('Tool name "tool_search" is reserved for the builtin tool-search extension.');
            }
            if (typeof tool.parameters !== "object" || tool.parameters === null || Array.isArray(tool.parameters)) {
                throw new Error(`Tool "${tool.name}" registered by extension "${extension.path}" must define an object parameter schema.`);
            }
            if (tool.runs !== undefined)
                assertExtensionSide(extension, tool.runs, `tool "${tool.name}"`);
            extension.tools.set(tool.name, {
                definition: Object.assign(Object.create(Object.getPrototypeOf(tool)), tool, {
                    execute: ownedBy(extension, tool.execute),
                }),
                sourceInfo: extension.sourceInfo,
            });
            runtime.refreshTools();
        },
        registerLazyToolActivator(activator) {
            runtime.assertActive();
            const activators = extension.lazyToolActivators ?? [];
            activators.push(activator);
            extension.lazyToolActivators = activators;
            runtime.registerLazyToolActivator(activator);
        },
        provideEvalHandleHost(host) {
            runtime.assertActive();
            runtime.evalHandleHost = host;
        },
        registerRemovedToolHint(name, hint) {
            runtime.assertActive();
            let hints = extension.removedToolHints;
            if (!hints) {
                hints = new Map();
                extension.removedToolHints = hints;
            }
            hints.set(name, hint);
            runtime.registerRemovedToolHint(name, hint);
        },
        registerChildModule(registration) {
            runtime.assertActive();
            validateChildModuleRegistration(registration);
            const modules = extension.childModules ?? new Map();
            modules.set(registration.id, { registration: { ...registration }, sourceInfo: extension.sourceInfo });
            extension.childModules = modules;
        },
        registerFilesystemPolicy(policy) {
            runtime.assertActive();
            const policies = extension.filesystemPolicies ?? [];
            policies.push(policy);
            extension.filesystemPolicies = policies;
        },
        registerCommand(name, options) {
            assertActive();
            if (typeof name !== "string" || name.length === 0) {
                throw new Error(`Command registered by extension "${extension.path}" must have a non-empty string name. Use pi.registerCommand("name", { description, handler }).`);
            }
            if (typeof options?.handler !== "function") {
                throw new Error(`Command "/${name}" registered by extension "${extension.path}" must define handler().`);
            }
            extension.commands.set(name, {
                name,
                sourceInfo: extension.sourceInfo,
                ...options,
                handler: ownedBy(extension, options.handler),
            });
        },
        registerShortcut(shortcut, options) {
            assertActive();
            extension.shortcuts.set(shortcut, {
                shortcut,
                extensionPath: extension.path,
                ...options,
                handler: ownedBy(extension, options.handler),
            });
        },
        registerFlag(name, options) {
            assertActive();
            if (options.default !== undefined && typeof options.default !== options.type) {
                throw new Error(`Invalid default for flag "${name}": expected ${options.type}, got ${typeof options.default}`);
            }
            extension.flags.set(name, { name, extensionPath: extension.path, ...options });
            if (options.default !== undefined && !runtime.flagValues.has(name)) {
                if (state === "loading") {
                    if (!pendingFlagValues.has(name))
                        pendingFlagValues.set(name, options.default);
                }
                else {
                    runtime.flagValues.set(name, options.default);
                }
            }
        },
        registerMessageRenderer(customType, renderer) {
            assertActive();
            extension.messageRenderers.set(customType, renderer);
        },
        registerMemoryReporter(name, reporter) {
            assertActive();
            if (RESERVED_MEMORY_REPORT_KEYS.has(name)) {
                throw new Error(`Memory reporter name "${name}" is reserved by the memory report`);
            }
            extension.memoryReporters ??= new Map();
            extension.memoryReporters.set(name, reporter);
        },
        registerMarkdownTransformer(transformer) {
            assertActive();
            extension.markdownTransformer = transformer;
        },
        registerEntryRenderer(customType, renderer, options) {
            assertActive();
            extension.entryRenderers ??= new Map();
            extension.entryRenderers.set(customType, renderer);
            extension.entryRendererOptions ??= new Map();
            if (options === undefined)
                extension.entryRendererOptions.delete(customType);
            else
                extension.entryRendererOptions.set(customType, options);
        },
        registerReadClassifier(classifier) {
            assertActive();
            const unregister = runtime.trackEventBusSubscription(registerReadClassifier(classifier));
            if (state === "loading")
                loadingUnsubscribers.push(unregister);
            return unregister;
        },
        registerRpcRemoteSource(source) {
            assertActive();
            const unregister = runtime.trackEventBusSubscription(registerRpcRemoteSource(source));
            if (state === "loading")
                loadingUnsubscribers.push(unregister);
            return unregister;
        },
        registerMcpServer(name, config) {
            assertActive();
            const error = validateMcpServerDeclaration(name, config);
            if (error) {
                throw new Error(error);
            }
            extension.mcpServers.set(name, {
                name,
                config: structuredClone(config),
                extensionPath: extension.path,
                registrationCwd: extension.registrationCwd,
            });
            runtime.mcpServers.changed();
        },
        unregisterMcpServer(name) {
            assertActive();
            if (extension.mcpServers.delete(name))
                runtime.mcpServers.changed();
        },
        getMcpServers() {
            assertActive();
            return runtime.mcpServers.list();
        },
        // Flag access - checks extension registered it, reads from runtime
        getFlag(name) {
            assertActive();
            if (!extension.flags.has(name))
                return undefined;
            return runtime.flagValues.has(name) ? runtime.flagValues.get(name) : pendingFlagValues.get(name);
        },
        getPermissionPreset() {
            assertActive();
            let sessionManager;
            try {
                sessionManager = runtime.createContext().sessionManager;
            }
            catch {
                // Before the host binds the runtime there is no session to read a preset for.
                return undefined;
            }
            return readPermissionPreset(sessionManager);
        },
        sessionDialog: createSessionDialogApi(() => {
            assertActive();
            return runtime.createContext().ui;
        }),
        getSubscriptionLimits() {
            assertActive();
            return subscriptionLimits.snapshot();
        },
        onSubscriptionLimits(listener) {
            assertActive();
            return subscriptionLimits.subscribe(listener);
        },
        // Action methods - delegate to shared runtime
        lifecycle: createLifecycleApi(() => {
            assertActive();
            if (!runtime.lifecycle)
                throw new Error("Extension lifecycle is not bound to a session");
            return runtime.lifecycle;
        }),
        // Itemized sends answer receipts (senpi#3811); a plain send stays fire-and-forget.
        sendMessage: ((message, options) => {
            assertActive();
            const items = options?.items;
            if (items === undefined) {
                runtime.sendMessage(message, options);
                return undefined;
            }
            const itemized = runtime.sendItemizedMessage;
            // A host without item custody delivers the batch plainly and answers no receipts, like an engine without items.
            if (itemized === undefined) {
                runtime.sendMessage(message, options);
                return Promise.resolve(undefined);
            }
            return itemized(message, { ...options, items });
        }),
        sendUserMessage(content, options) {
            assertActive();
            runtime.sendUserMessage(content, options);
        },
        isLoopRemote: () => runtime.isLoopRemote(),
        appendEntry(customType, data, options) {
            assertActive();
            runtime.appendEntry(customType, data, options);
        },
        setSessionName(name) {
            assertActive();
            runtime.setSessionName(name);
        },
        getSessionName() {
            assertActive();
            return runtime.getSessionName();
        },
        setLabel(entryId, label) {
            assertActive();
            runtime.setLabel(entryId, label);
        },
        exec(command, args, options) {
            assertActive();
            return execCommand(command, args, options?.cwd ?? cwd, options);
        },
        redactForUpload(text, options) {
            assertActive();
            return redactForUpload(text, options);
        },
        hostVersion: VERSION,
        executeTool(toolName, params, options) {
            runtime.assertActive();
            return runtime.executeTool(toolName, params, options);
        },
        getActiveTools() {
            assertActive();
            return runtime.getActiveTools();
        },
        armToolBarrier(spec) {
            assertActive();
            if (!runtime.armToolBarrier)
                throw new Error("This runtime has no tool barrier (senpi#3717).");
            runtime.armToolBarrier(spec);
        },
        releaseToolBarrier(id) {
            assertActive();
            return runtime.releaseToolBarrier?.(id) ?? false;
        },
        getAllTools() {
            assertActive();
            return runtime.getAllTools();
        },
        getSettings() {
            assertActive();
            return runtime.getSettings();
        },
        setActiveTools(toolNames) {
            assertActive();
            runtime.setActiveTools(toolNames);
        },
        getCommands() {
            assertActive();
            return runtime.getCommands();
        },
        setModel(model) {
            assertActive();
            return runtime.setModel(model, { source: "extension", actor: extension.path });
        },
        getThinkingLevel() {
            assertActive();
            return runtime.getThinkingLevel();
        },
        setThinkingLevel(level) {
            assertActive();
            runtime.setThinkingLevel(level);
        },
        setSessionModel(model) {
            runtime.assertActive();
            return runtime.setSessionModel(model, { source: "extension", actor: extension.path });
        },
        setSessionThinkingLevel(level) {
            runtime.assertActive();
            runtime.setSessionThinkingLevel(level);
        },
        setSessionFastMode(enabled) {
            runtime.assertActive();
            runtime.setSessionFastMode(enabled);
        },
        registerProvider(providerOrName, config) {
            assertActive();
            if (typeof providerOrName === "string") {
                if (!config)
                    throw new Error("Provider config is required when registering by name");
                const wrapped = withProviderLoginStart(providerOrName, config, (event) => runtime.emitProviderLoginStart(event));
                applyRuntimeChange(() => runtime.registerProvider(providerOrName, wrapped, extension.path));
                return;
            }
            applyRuntimeChange(() => runtime.registerNativeProvider(providerOrName, extension.path));
        },
        unregisterProvider(name) {
            assertActive();
            applyRuntimeChange(() => runtime.unregisterProvider(name, extension.path));
        },
        session: {
            registerControlEndpoint(options) {
                runtime.assertActive();
                return sessionControlOf(runtime).registerControlEndpoint(options);
            },
            admissionGate() {
                runtime.assertActive();
                return sessionControlOf(runtime).admissionGate();
            },
            admitExternalMessage(input) {
                runtime.assertActive();
                return sessionControlOf(runtime).admitExternalMessage(input);
            },
            listAdmittedDeliveries() {
                runtime.assertActive();
                return sessionControlOf(runtime).listAdmittedDeliveries();
            },
            persistHeaderNow() {
                runtime.assertActive();
                return sessionControlOf(runtime).persistHeaderNow();
            },
            relocationOffered() {
                runtime.assertActive();
                return sessionControlOf(runtime).relocationOffered();
            },
            relocationTargets(signal) {
                runtime.assertActive();
                return sessionControlOf(runtime).relocationTargets(signal);
            },
            requestRelocation(request, signal) {
                runtime.assertActive();
                return sessionControlOf(runtime).requestRelocation(request, signal);
            },
        },
        rpc: {
            emit(name, data) {
                runtime.assertActive();
                const normalizedName = name.trim();
                if (normalizedName.length === 0)
                    throw new Error("RPC extension event name must not be empty");
                eventBus.emit(EXTENSION_RPC_EVENT_CHANNEL, {
                    name: normalizedName,
                    data,
                });
            },
            handle(name, handler) {
                runtime.assertActive();
                const normalizedName = name.trim();
                if (normalizedName.length === 0)
                    throw new Error("RPC extension request name must not be empty");
                const handlers = extension.rpcHandlers ?? new Map();
                if (handlers.has(normalizedName)) {
                    throw new Error(`RPC extension request handler already registered: ${normalizedName}`);
                }
                handlers.set(normalizedName, ownedBy(extension, handler));
                extension.rpcHandlers = handlers;
            },
        },
        registerVirtualModel(model) {
            assertActive();
            // Routing runs after the runner binds, so the context is created per request. The state
            // comes from the session branch that this router wrote.
            const definition = {
                ...model,
                route: (request) => model.route(request, runtime.createContext()),
            };
            applyRuntimeChange(() => runtime.registerVirtualModel(definition, extension.path));
        },
        unregisterVirtualModel(provider, id) {
            assertActive();
            applyRuntimeChange(() => runtime.unregisterVirtualModel(provider, id));
        },
        events: {
            emit(channel, data) {
                assertActive();
                eventBus.emit(channel, data);
            },
            on(channel, handler) {
                assertActive();
                const unsubscribe = runtime.trackEventBusSubscription(eventBus.on(channel, handler));
                if (state === "loading")
                    loadingUnsubscribers.push(unsubscribe);
                return unsubscribe;
            },
        },
    };
    recordExtensionLoadKey(api, runtime);
    return {
        api,
        commit: () => {
            if (state !== "loading")
                return;
            runtime.assertActive();
            // Checked before anything is applied: another extension may have registered a device machine while this load's
            // registration was staged (from an event fired during this factory). The load then fails whole, nothing half-applied.
            if (deviceMachineStaged && runtime.deviceMachine !== undefined) {
                throw new DeviceMachineConflictError(runtime.deviceMachine.extensionPath, extension.path);
            }
            for (const [name, value] of pendingFlagValues) {
                if (!runtime.flagValues.has(name))
                    runtime.flagValues.set(name, value);
            }
            for (const apply of pendingRuntimeChanges)
                apply();
            state = "active";
            clearPending();
        },
        discard: () => {
            if (state !== "loading")
                return;
            state = "failed";
            for (const unsubscribe of loadingUnsubscribers)
                unsubscribe();
            clearPending();
        },
    };
}
// Keep the Node-only transformer out of Bun's compiled dependency graph.
const importNodeOnlyApi = (specifier) => import(__rewriteRelativeImportExtension(specifier));
async function createExtensionModuleImporter() {
    if (usesNativeBunImports) {
        const { createBunExtensionImporter } = await import("./bun-extension-importer.js");
        return createBunExtensionImporter(VIRTUAL_MODULES, {}, {
            preparedCache: { dir: path.join(getAgentDir(), "cache", "extension-modules"), release: VERSION },
        });
    }
    const { createJiti } = await importNodeOnlyApi("jiti/static");
    return createJiti(import.meta.url, {
        moduleCache: false,
        // Compiled binaries and the bundled Node distribution use embedded modules.
        // Source TypeScript reuses host modules and root tsconfig paths. Unbundled
        // Node builds use dist aliases.
        ...(isNodeSeaBinary || isBundledNode
            ? { virtualModules: VIRTUAL_MODULES, tryNative: false }
            : isTypeScriptSourceRuntime
                ? { alias: getAliases(), virtualModules: VIRTUAL_MODULES, tsconfigPaths: true }
                : { alias: getAliases() }),
    });
}
async function loadExtensionModule(extensionPath, getImporter) {
    const cachedFactory = cachedExtensionFactory(extensionPath);
    if (cachedFactory) {
        return cachedFactory;
    }
    const importer = await getImporter();
    const module = await importer.import(extensionPath, { default: true });
    const factory = module;
    if (typeof factory !== "function") {
        return undefined;
    }
    rememberExtensionFactory(extensionPath, factory, importer);
    return factory;
}
/**
 * Create an Extension object with empty collections.
 */
function createExtension(extensionPath, resolvedPath, registrationCwd) {
    const source = getSyntheticPathSource(extensionPath) ?? "local";
    const baseDir = isSyntheticPath(extensionPath) ? undefined : path.dirname(resolvedPath);
    return {
        path: extensionPath,
        resolvedPath,
        sourceInfo: createSyntheticSourceInfo(extensionPath, {
            source,
            baseDir,
            scope: source === "builtin" ? "system" : "temporary",
        }),
        handlers: new Map(),
        tools: new Map(),
        removedToolHints: new Map(),
        lazyToolActivators: [],
        filesystemPolicies: [],
        messageRenderers: new Map(),
        memoryReporters: new Map(),
        entryRenderers: undefined,
        commands: new Map(),
        rpcHandlers: new Map(),
        flags: new Map(),
        shortcuts: new Map(),
        mcpServers: new Map(),
        registrationCwd,
    };
}
async function initializeExtension(factory, extensionPath, resolvedPath, cwd, eventBus, runtime, session) {
    const extension = createExtension(extensionPath, resolvedPath, cwd);
    const load = createExtensionAPI(extension, runtime, cwd, eventBus, session);
    runtime.mcpServers.track(extension);
    try {
        await runOwnedBy(extension, () => factory(load.api));
        load.commit();
        if (usesNativeBunImports) {
            const factories = runtimeFactories.get(runtime) ?? new Set();
            factories.add(factory);
            runtimeFactories.set(runtime, factories);
        }
    }
    catch (error) {
        runtime.mcpServers.untrack(extension);
        load.discard();
        throw error;
    }
    time(`${extensionPath} factory`, "extensions");
    return extension;
}
async function loadExtension(extensionPath, cwd, eventBus, runtime, getImporter, factoryResolver, session = DEFAULT_EXTENSION_SESSION_PROFILE) {
    const resolvedPath = resolvePath(extensionPath, cwd, { normalizeUnicodeSpaces: true });
    try {
        const factory = factoryResolver?.(extensionPath, resolvedPath) ?? (await loadExtensionModule(resolvedPath, getImporter));
        time(`${extensionPath} module import`, "extensions");
        if (!factory) {
            return { extension: null, error: `Extension does not export a valid factory function: ${extensionPath}` };
        }
        const extension = await initializeExtension(factory, extensionPath, resolvedPath, cwd, eventBus, runtime, session);
        return { extension, error: null };
    }
    catch (err) {
        const message = err instanceof Error ? err.message : String(err);
        return { extension: null, error: `Failed to load extension: ${message}` };
    }
}
/**
 * Create an Extension from an inline factory function.
 */
export async function loadExtensionFromFactory(factory, cwd, eventBus, runtime, extensionPath = "<inline>", session = DEFAULT_EXTENSION_SESSION_PROFILE) {
    const resolvedCwd = resolvePath(cwd);
    return initializeExtension(factory, extensionPath, extensionPath, resolvedCwd, eventBus, runtime, session);
}
/**
 * Load extensions from paths.
 */
async function loadExtensionsInternal(paths, cwd, eventBus, runtime, options) {
    const session = sessionProfile(options);
    const extensions = [];
    const errors = [];
    const warnings = [];
    const resolvedCwd = resolvePath(cwd);
    const resolvedEventBus = eventBus ?? createEventBus();
    const resolvedRuntime = runtime ?? createExtensionRuntime();
    const getImporter = () => extensionModuleImporter(createExtensionModuleImporter);
    for (const extPath of paths) {
        const { extension, error } = await loadExtension(extPath, resolvedCwd, resolvedEventBus, resolvedRuntime, getImporter, options?.factoryResolver, session);
        if (error) {
            errors.push({ path: extPath, error });
            continue;
        }
        if (extension) {
            extensions.push(extension);
        }
    }
    return {
        extensions,
        errors,
        warnings,
        runtime: resolvedRuntime,
        eventBus: resolvedEventBus,
    };
}
export async function loadExtensions(paths, cwd, eventBus, runtime, options) {
    return loadExtensionsInternal(paths, cwd, eventBus, runtime, options);
}
export async function loadExtensionsCached(paths, cwd, eventBus, runtime) {
    return loadExtensionsInternal(paths, cwd, eventBus, runtime);
}
function isExtensionFile(name) {
    return name.endsWith(".ts") || name.endsWith(".js");
}
/**
 * Resolve extension entry points from a directory.
 *
 * Checks for:
 * 1. package.json with "pi.extensions" field -> returns declared paths
 * 2. index.ts or index.js -> returns the index file
 *
 * Returns resolved paths or null if no entry points found.
 */
function resolveExtensionEntries(dir) {
    // Check for package.json with "pi" field first
    const packageJsonPath = path.join(dir, "package.json");
    if (fs.existsSync(packageJsonPath)) {
        const manifest = readPiManifest(packageJsonPath);
        if (manifest?.extensions?.length) {
            const entries = [];
            for (const extPath of manifest.extensions) {
                const resolvedExtPath = path.resolve(dir, extPath);
                if (fs.existsSync(resolvedExtPath)) {
                    entries.push(resolvedExtPath);
                }
            }
            if (entries.length > 0) {
                return entries;
            }
        }
    }
    // Check for index.ts or index.js
    const indexTs = path.join(dir, "index.ts");
    const indexJs = path.join(dir, "index.js");
    if (fs.existsSync(indexTs)) {
        return [indexTs];
    }
    if (fs.existsSync(indexJs)) {
        return [indexJs];
    }
    return null;
}
/**
 * Discover extensions in a directory.
 *
 * Discovery rules:
 * 1. Direct files: `extensions/*.ts` or `*.js` → load
 * 2. Subdirectory with index: `extensions/* /index.ts` or `index.js` → load
 * 3. Subdirectory with package.json: `extensions/* /package.json` with "pi" field → load what it declares
 *
 * No recursion beyond one level. Complex packages must use package.json manifest.
 */
function discoverExtensionsInDir(dir) {
    if (!fs.existsSync(dir)) {
        return [];
    }
    const discovered = [];
    try {
        const entries = fs
            .readdirSync(dir, { withFileTypes: true })
            .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
        for (const entry of entries) {
            const entryPath = path.join(dir, entry.name);
            // 1. Direct files: *.ts or *.js
            if ((entry.isFile() || entry.isSymbolicLink()) && isExtensionFile(entry.name)) {
                discovered.push(entryPath);
                continue;
            }
            // 2 & 3. Subdirectories
            if (entry.isDirectory() || entry.isSymbolicLink()) {
                const entries = resolveExtensionEntries(entryPath);
                if (entries) {
                    discovered.push(...entries);
                }
            }
        }
    }
    catch {
        return [];
    }
    return discovered;
}
/**
 * Discover and load extensions from standard locations.
 */
export async function discoverAndLoadExtensions(configuredPaths, cwd, agentDir = getAgentDir(), eventBus) {
    const resolvedCwd = resolvePath(cwd);
    const resolvedAgentDir = resolvePath(agentDir);
    const allPaths = [];
    const seen = new Set();
    const addPaths = (paths) => {
        for (const p of paths) {
            const resolved = path.resolve(p);
            if (!seen.has(resolved)) {
                seen.add(resolved);
                allPaths.push(p);
            }
        }
    };
    // 1. Project-local extensions: cwd/${CONFIG_DIR_NAME}/extensions/
    const localExtDir = path.join(resolvedCwd, CONFIG_DIR_NAME, "extensions");
    addPaths(discoverExtensionsInDir(localExtDir));
    // 2. Global extensions: agentDir/extensions/
    const globalExtDir = path.join(resolvedAgentDir, "extensions");
    addPaths(discoverExtensionsInDir(globalExtDir));
    // 3. Explicitly configured paths
    for (const p of configuredPaths) {
        const resolved = resolvePath(p, resolvedCwd, { normalizeUnicodeSpaces: true });
        if (fs.existsSync(resolved) && fs.statSync(resolved).isDirectory()) {
            // Check for package.json with pi manifest or index.ts
            const entries = resolveExtensionEntries(resolved);
            if (entries) {
                addPaths(entries);
                continue;
            }
            // No explicit entries - discover individual files in directory
            addPaths(discoverExtensionsInDir(resolved));
            continue;
        }
        addPaths([resolved]);
    }
    return loadExtensions(allPaths, resolvedCwd, eventBus);
}
//# sourceMappingURL=loader.js.map