repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/ultra/drivers.ts
RawFile outline
- BUILTIN_TOOL_NAMES line 27
- HeadlessSession line 34
- setActiveToolsByName line 35
- bindExtensions line 36
- SessionFactoryDeps line 39
- createAgentSession line 40
- DefaultResourceLoader line 43
- getAgentDir line 49
- cwd line 50
- loadExtensions line 52
- extensionPaths line 54
- loadSkills line 56
- makeSessionFactory line 59
- LoadedExtension line 116
- path line 117
- resolvedPath line 118
- tools line 119
- commands line 120
- flags line 121
- shortcuts line 122
- messageRenderers line 123
- entryRenderers line 124
- LoadedExtensionsResult line 127
- extensions line 128
- runtime line 129
- normalizedPath line 141
- applyDeclaredOverrides line 146
- applyProviderOverrides line 209
- SessionManagerLike line 265
- getSessionId line 266
- getSessionFile line 267
- appendSessionInfo line 268
- SubagentSessionManagerDeps line 271
- SessionManager line 272
- cwd line 285
- parentSession line 286
- retention line 287
- sessionDir line 289
- SubagentSessionManagerArgs line 292
- name line 293
- retained line 294
- ManagedSubagentSession line 297
- ref line 298
- makeSubagentSessionManager line 302
- parseModelRef line 352
- ResolveModelDeps line 362
- modelRegistry line 363
- defaultModel line 365
- makeResolveModel line 368
// ultra — real SDK drivers (Task 9).
//
// The runner's SDK capabilities, wrapped behind injected factories so option
// construction remains unit-testable offline. `implementation.ts` supplies the
// real `createAgentSession`, `SessionManager`, and `DefaultResourceLoader`.
//
// SDK shapes verified against the installed declarations:
// - createAgentSession resolves to `{ session }`.
// - DefaultResourceLoader supports isolated resource discovery.
// - modelRegistry.find(provider, id) resolves explicit model refs.
import { existsSync } from "node:fs";
import { resolve } from "node:path";
import {
BUILTIN_TOOL_NAMES,
ULTRA_RESERVED_TOOL_NAMES,
} from "./dynamic-contract.ts";
import type { ResolvedDynamicExtension } from "./dynamic-types.ts";
import type { SubagentSessionRef } from "./journal.ts";
import type {
ResolveModel,
SessionFactory,
SessionLike,
SubagentSessionHandle,
} from "./runner.ts";
export { BUILTIN_TOOL_NAMES } from "./dynamic-contract.ts";
// ---------------------------------------------------------------------------
// sessionFactory — wraps createAgentSession with an isolated resource loader
// ---------------------------------------------------------------------------
/** The subset of the SDK the session factory needs (injected for testing). */
export interface HeadlessSession extends SessionLike {
setActiveToolsByName(toolNames: string[]): void;
bindExtensions(bindings: { mode: "print" }): Promise<void>;
}
export interface SessionFactoryDeps {
createAgentSession: (
opts: Record<string, unknown>,
) => Promise<{ session: HeadlessSession }> | { session: HeadlessSession };
DefaultResourceLoader: new (
opts: Record<string, unknown>,
) => {
reload(): Promise<void>;
getExtensions?(): unknown;
};
getAgentDir: () => string;
cwd: string;
/** When true, sub-agents load every host extension. */
loadExtensions?: boolean;
/** Explicit extensions loaded when broad discovery is disabled. */
extensionPaths?: string[];
/** When true, sub-agents discover host skills. */
loadSkills?: boolean;
}
export function makeSessionFactory(deps: SessionFactoryDeps): SessionFactory {
return async ({
model,
thinkingLevel,
tools,
customTools,
extensionPaths,
dynamicExtensions,
appendSystemPrompt,
sessionManager,
}) => {
// resourceLoader is REQUIRED for controlled discovery (P1). reload() MUST
// complete before the session is constructed.
const additionalExtensionPaths = [
...(deps.extensionPaths ?? []),
...(extensionPaths ?? []),
];
const resourceLoader = new deps.DefaultResourceLoader({
cwd: deps.cwd,
agentDir: deps.getAgentDir(),
noExtensions: !deps.loadExtensions,
additionalExtensionPaths:
additionalExtensionPaths.length > 0
? additionalExtensionPaths
: undefined,
noSkills: !deps.loadSkills,
noPromptTemplates: true,
noThemes: true,
noContextFiles: true,
...(appendSystemPrompt?.length ? { appendSystemPrompt } : {}),
});
await resourceLoader.reload();
if (dynamicExtensions?.length && resourceLoader.getExtensions)
applyDeclaredOverrides(
resourceLoader.getExtensions(),
dynamicExtensions,
new Set(customTools.map((tool) => tool.name)),
);
const activeTools =
deps.loadSkills && !tools.includes("read") ? [...tools, "read"] : tools;
const { session } = await deps.createAgentSession({
cwd: deps.cwd,
model,
resourceLoader,
thinkingLevel,
sessionManager, // clean child, or a matching interrupted child's manager
customTools, // [structuredOutputTool] — built by the runner from the step schema
});
// Passing `tools` to createAgentSession creates a hard registry allowlist,
// which prevents loaded extensions from activating their own tools.
session.setActiveToolsByName(activeTools);
await session.bindExtensions({ mode: "print" });
return session;
};
}
interface LoadedExtension {
path: string;
resolvedPath?: string;
tools?: Map<string, unknown>;
commands?: Map<string, unknown>;
flags?: Map<string, unknown>;
shortcuts?: Map<string, unknown>;
messageRenderers?: Map<string, unknown>;
entryRenderers?: Map<string, unknown>;
}
interface LoadedExtensionsResult {
extensions: LoadedExtension[];
runtime?: {
pendingProviderRegistrations?: Array<{
name: string;
extensionPath: string;
}>;
pendingNativeProviderRegistrations?: Array<{
provider: { name?: string; id?: string };
extensionPath: string;
}>;
};
}
function normalizedPath(path: string): string {
const absolute = resolve(path).replaceAll("\\", "/");
return process.platform === "win32" ? absolute.toLowerCase() : absolute;
}
function applyDeclaredOverrides(
loaded: unknown,
dynamicExtensions: ResolvedDynamicExtension[],
sdkToolNames: Set<string>,
): void {
const result = loaded as LoadedExtensionsResult;
if (!Array.isArray(result?.extensions)) return;
const dynamicByPath = new Map(
dynamicExtensions.map((extension) => [
normalizedPath(extension.loadPath),
extension,
]),
);
const registrations: Array<[keyof LoadedExtension, string]> = [
["tools", "tool"],
["commands", "command"],
["flags", "flag"],
["shortcuts", "shortcut"],
["messageRenderers", "renderer"],
["entryRenderers", "entry-renderer"],
];
const seen = new Map<string, Map<string, unknown>>();
for (const loadedExtension of result.extensions) {
const extension = dynamicByPath.get(
normalizedPath(loadedExtension.resolvedPath ?? loadedExtension.path),
);
for (const [field, qualifier] of registrations) {
const values = loadedExtension[field];
if (!(values instanceof Map)) continue;
for (const name of [...values.keys()]) {
const qualified = `${qualifier}:${name}`;
if (
extension &&
qualifier === "tool" &&
(ULTRA_RESERVED_TOOL_NAMES.has(name) || sdkToolNames.has(name))
)
throw new Error(
`ultra: dynamic extension "${extension.name}" cannot register reserved ${qualified}.`,
);
if (
extension &&
qualifier === "tool" &&
BUILTIN_TOOL_NAMES.has(name) &&
!extension.overrides.includes(qualified)
)
throw new Error(
`ultra: dynamic extension "${extension.name}" collides with ${qualified}; declare that exact override in manifest.json or rename it.`,
);
const prior = seen.get(qualified);
if (prior && extension) {
if (!extension.overrides.includes(qualified))
throw new Error(
`ultra: dynamic extension "${extension.name}" collides with ${qualified}; declare that exact override in manifest.json or rename it.`,
);
prior.delete(name);
}
if (!prior) seen.set(qualified, values);
}
}
}
applyProviderOverrides(result, dynamicExtensions);
}
function applyProviderOverrides(
result: LoadedExtensionsResult,
dynamicExtensions: ResolvedDynamicExtension[],
): void {
const dynamicByPath = new Map(
dynamicExtensions.map((extension) => [
normalizedPath(extension.loadPath),
extension,
]),
);
for (const registrations of [
result.runtime?.pendingProviderRegistrations,
result.runtime?.pendingNativeProviderRegistrations,
]) {
if (!registrations) continue;
const seen = new Map<string, number>();
for (let index = 0; index < registrations.length; index++) {
const registration = registrations[index];
const name =
"name" in registration
? registration.name
: (registration.provider.id ?? registration.provider.name);
if (!name) continue;
const prior = seen.get(name);
const extension = dynamicByPath.get(
normalizedPath(registration.extensionPath),
);
if (prior !== undefined && extension) {
const qualified = `provider:${name}`;
if (!extension.overrides.includes(qualified))
throw new Error(
`ultra: dynamic extension "${extension.name}" collides with ${qualified}; declare that exact override in manifest.json or rename it.`,
);
registrations.splice(prior, 1);
index--;
seen.clear();
for (let i = 0; i <= index; i++) {
const priorRegistration = registrations[i];
const priorName =
"name" in priorRegistration
? priorRegistration.name
: (priorRegistration.provider.id ??
priorRegistration.provider.name);
if (priorName) seen.set(priorName, i);
}
continue;
}
seen.set(name, index);
}
}
}
// ---------------------------------------------------------------------------
// subagentSessionManager — clean persistent child or matching continuation
// ---------------------------------------------------------------------------
interface SessionManagerLike {
getSessionId(): string;
getSessionFile(): string | undefined;
appendSessionInfo(name: string): string;
}
export interface SubagentSessionManagerDeps {
SessionManager: {
create(
cwd: string,
sessionDir?: string,
options?: { parentSession?: string },
): SessionManagerLike;
open(
path: string,
sessionDir?: string,
cwdOverride?: string,
): SessionManagerLike;
inMemory(cwd: string): SessionManagerLike;
};
cwd: string;
parentSession?: string;
retention: "all" | "none";
/** Test/custom storage override; production uses Pi's default session directory. */
sessionDir?: string;
}
export interface SubagentSessionManagerArgs {
name: string;
retained?: SubagentSessionRef;
}
export interface ManagedSubagentSession extends SubagentSessionHandle {
ref?: SubagentSessionRef;
}
/** Persist only beneath a persisted parent. A missing retained file starts clean. */
export function makeSubagentSessionManager(
deps: SubagentSessionManagerDeps,
): (args: SubagentSessionManagerArgs) => ManagedSubagentSession {
return ({ name, retained }) => {
if (deps.retention === "none" || !deps.parentSession) {
const manager = deps.SessionManager.inMemory(deps.cwd);
return {
manager,
id: manager.getSessionId(),
resumed: false,
};
}
if (retained && existsSync(retained.path)) {
try {
const manager = deps.SessionManager.open(
retained.path,
deps.sessionDir,
deps.cwd,
);
if (manager.getSessionId() === retained.id)
return {
manager,
id: manager.getSessionId(),
resumed: true,
ref: retained,
};
} catch {}
}
const manager = deps.SessionManager.create(deps.cwd, deps.sessionDir, {
parentSession: deps.parentSession,
});
manager.appendSessionInfo(name);
const path = manager.getSessionFile();
if (!path) return { manager, id: manager.getSessionId(), resumed: false };
return {
manager,
id: manager.getSessionId(),
resumed: false,
ref: { id: manager.getSessionId(), path },
};
};
}
// ---------------------------------------------------------------------------
// resolveModel — "provider/model" ref → Model object, else the host default
// ---------------------------------------------------------------------------
/** Split a `provider/model` ref on the first slash. */
function parseModelRef(ref: string): { provider: string; model: string } {
const i = ref.indexOf("/");
if (i <= 0 || i === ref.length - 1) {
throw new Error(
`ultra: invalid model ref "${ref}" — use "provider/model".`,
);
}
return { provider: ref.slice(0, i), model: ref.slice(i + 1) };
}
export interface ResolveModelDeps {
modelRegistry: { find(provider: string, modelId: string): unknown };
/** The host's current model (`ctx.model`) — the default when a step omits `model`. */
defaultModel: unknown;
}
export function makeResolveModel(deps: ResolveModelDeps): ResolveModel {
return (modelRef) => {
if (!modelRef) return deps.defaultModel;
const { provider, model } = parseModelRef(modelRef);
const found = deps.modelRegistry.find(provider, model);
if (!found) throw new Error(`ultra: model not found: ${modelRef}`);
return found;
};
}