Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
"@anthropic-ai/claude-agent-sdk": "0.3.200",
"@anthropic-ai/sandbox-runtime": "0.0.71",
"@clack/prompts": "^1.5.1",
"@earendil-works/pi-coding-agent": "^0.80.3",
"@earendil-works/pi-coding-agent": "0.80.10",
"@modelcontextprotocol/ext-apps": "^1.7.2",
"@modelcontextprotocol/node": "^2.0.0",
"@modelcontextprotocol/sdk": "^1.29.0",
Expand Down
36 changes: 18 additions & 18 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

32 changes: 30 additions & 2 deletions src/local-agent-pi.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { AgentSessionEvent, AgentSessionEventListener } from "@earendil-works/pi-coding-agent";
import {
PiLocalAgentDriver,
Expand All @@ -11,7 +14,10 @@ import type { LocalAgentRuntimeContext } from "./local-agent-runtime.js";
class FakePiSession implements PiSessionLike {
readonly sessionId = "pi_session_1";
readonly messages: any[] = [];
readonly modelRegistry = { find: () => ({ id: "model" }) } as unknown as PiSessionLike["modelRegistry"];
readonly modelRuntime = {
getModel: () => ({ id: "model" }),
getModels: () => [],
} as unknown as PiSessionLike["modelRuntime"];
private readonly listeners = new Set<AgentSessionEventListener>();
disposeCount = 0;
model?: unknown;
Expand Down Expand Up @@ -135,7 +141,9 @@ assert.deepEqual(sessions[1]?.activeTools, ["read", "grep", "find", "ls", "edit"
await pool.close();

const missingModelSession = new FakePiSession();
Object.defineProperty(missingModelSession, "modelRegistry", { value: { find: () => undefined } });
Object.defineProperty(missingModelSession, "modelRuntime", {
value: { getModel: () => undefined, getModels: () => [] },
});
const missingModelDriver = new PiLocalAgentDriver(async () => missingModelSession);
const missingModelRuntime = await missingModelDriver.createRuntime(context);
assert.equal(missingModelRuntime.isOk(), true);
Expand All @@ -152,3 +160,23 @@ if (missingModel.isErr()) {
assert.match(missingModel.error.message, /provider\/missing-model/);
}
await missingModelRuntime.value.close();

const originalPiAgentDir = process.env.PI_CODING_AGENT_DIR;
const piAgentDir = mkdtempSync(join(tmpdir(), "devspace-pi-sdk-smoke-"));
process.env.PI_CODING_AGENT_DIR = piAgentDir;
try {
const realDriver = new PiLocalAgentDriver();
const realRuntime = await realDriver.createRuntime({
agentId: "agt_pi_sdk_smoke",
provider: "pi",
workspaceRoot: piAgentDir,
writeMode: "full_access",
});
assert.equal(realRuntime.isOk(), true, "default Pi factory initializes the installed SDK");
if (realRuntime.isErr()) throw realRuntime.error;
await realRuntime.value.close();
} finally {
if (originalPiAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
else process.env.PI_CODING_AGENT_DIR = originalPiAgentDir;
rmSync(piAgentDir, { recursive: true, force: true });
}
59 changes: 31 additions & 28 deletions src/local-agent-pi.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { join } from "node:path";
import type { AgentSession, ModelRegistry } from "@earendil-works/pi-coding-agent";
import type { AgentSession, ModelRuntime, ModelRuntimeAuthOverrides } from "@earendil-works/pi-coding-agent";
import {
AgentProviderExecutionError,
AgentProviderProtocolError,
Expand Down Expand Up @@ -31,7 +31,7 @@ export type PiSessionLike = Pick<
AgentSession,
| "sessionId"
| "messages"
| "modelRegistry"
| "modelRuntime"
| "prompt"
| "subscribe"
| "setActiveToolsByName"
Expand Down Expand Up @@ -144,7 +144,7 @@ export class PiSessionRuntime implements LocalAgentRuntime {
await updatePiSandboxSession(this.session, input.workspaceRoot, input.writeMode ?? "allowed");
this.session.setActiveToolsByName([...piToolsForWriteMode(input.writeMode)]);
if (input.model) {
const model = resolvePiModel(this.session.modelRegistry, input.model);
const model = resolvePiModel(this.session.modelRuntime, input.model);
if (!model) {
throw new AgentProviderProtocolError({
code: "PROVIDER_PROTOCOL_ERROR",
Expand Down Expand Up @@ -202,8 +202,7 @@ async function defaultPiSessionFactory(
env: NodeJS.ProcessEnv = {},
): Promise<PiSessionLike> {
const {
AuthStorage,
ModelRegistry,
ModelRuntime,
SessionManager,
DefaultResourceLoader,
createAgentSession,
Expand All @@ -212,11 +211,13 @@ async function defaultPiSessionFactory(
// DevSpace's agentDir is the compatibility directory used for instructions;
// Pi keeps its own native auth, model, and session state under getAgentDir().
const agentDir = getAgentDir();
const authStorage = AuthStorage.create(join(agentDir, "auth.json"));
const modelRegistry = ModelRegistry.create(authStorage, join(agentDir, "models.json"));
applyPiProviderEnvironment(modelRegistry, env);
const modelRuntime = await ModelRuntime.create({
authPath: join(agentDir, "auth.json"),
modelsPath: join(agentDir, "models.json"),
});
applyPiProviderEnvironment(modelRuntime, env);
const sessionManager = await resolveSessionManager(SessionManager, input.workspaceRoot, input.providerSessionId);
const model = input.model ? resolvePiModel(modelRegistry, input.model) : undefined;
const model = input.model ? resolvePiModel(modelRuntime, input.model) : undefined;
if (input.model && !model) {
throw new AgentProviderProtocolError({
code: "PROVIDER_PROTOCOL_ERROR",
Expand All @@ -238,8 +239,7 @@ async function defaultPiSessionFactory(
const result = await createAgentSession({
cwd: input.workspaceRoot,
agentDir,
authStorage,
modelRegistry,
modelRuntime,
sessionManager: sessionManager as never,
resourceLoader,
...(model ? { model: model as never } : {}),
Expand All @@ -265,24 +265,25 @@ async function defaultPiSessionFactory(
}

function applyPiProviderEnvironment(
modelRegistry: ModelRegistry,
modelRuntime: ModelRuntime,
env: NodeJS.ProcessEnv,
): void {
const getApiKeyAndHeaders = modelRegistry.getApiKeyAndHeaders.bind(modelRegistry);
const providerEnv = Object.fromEntries(
Object.entries(env).filter((entry): entry is [string, string] => entry[1] !== undefined),
);
modelRegistry.getApiKeyAndHeaders = async (model) => {
const auth = await getApiKeyAndHeaders(model);
if (!auth.ok) return auth;
return {
...auth,
env: {
...auth.env,
...providerEnv,
},
};
};
if (Object.keys(providerEnv).length === 0) return;

const getAuth = modelRuntime.getAuth.bind(modelRuntime);
modelRuntime.getAuth = ((
target: string | Parameters<ModelRuntime["getAuth"]>[0],
overrides?: ModelRuntimeAuthOverrides,
) => getAuth(target as never, {
...overrides,
env: {
...overrides?.env,
...providerEnv,
},
})) as ModelRuntime["getAuth"];
}

export function piToolsForWriteMode(writeMode: LocalAgentRunInput["writeMode"]): readonly string[] {
Expand Down Expand Up @@ -321,13 +322,15 @@ async function resolveSessionManager(
return SessionManager.open(match.path);
}

function resolvePiModel(registry: { find(provider: string, modelId: string): unknown; getAll?: () => unknown[] }, reference: string): unknown {
function resolvePiModel(runtime: {
getModel(providerId: string, modelId: string): unknown;
getModels(): readonly unknown[];
}, reference: string): unknown {
const separator = reference.indexOf("/");
if (separator !== -1) {
return registry.find(reference.slice(0, separator), reference.slice(separator + 1));
return runtime.getModel(reference.slice(0, separator), reference.slice(separator + 1));
}
const all = registry.getAll?.() ?? [];
return all.find((model) => asRecord(model)?.id === reference);
return runtime.getModels().find((model) => asRecord(model)?.id === reference);
}

export function extractPiFinalResponse(value: unknown): string {
Expand Down