mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-30 21:49:18 +01:00
## Thinking Path > - Paperclip lets users choose an agent harness and account. > - The server resolves the runner for new agents. > - Claude still needs the same ordinary native-default journey as Codex. > - Existing agents must retain their runner, model and account. > - This PR defaults new Apple Silicon Claude agents to Paperclip Runner with Opus 5.5. > - Users can connect and work without a runner override. ## Linked Issues or Issue Description Refs #15683. This PR depends on #15994 and precedes #15997. Related scope: #15422, #13978 and #15224. ## What Changed - Resolve new Apple Silicon Claude agents to `paperclip_runner`, `provider: acpx`, `acpxAgent: claude`. Keep explicit Legacy, models, provider routing and saved execution. - Use `claude-opus-5-5` for ordinary Claude defaults and retain explicit overrides. - Reuse existing API-key/subscription connections, credential storage and checks. Generalize the shared Advanced runner control with Claude branding. - Carry configured effort into the shared v9 contract. Preserve compatible permissions, instructions, skills, timeouts and session behavior. Require Legacy for unsupported settings. - Qualify a new immutable managed Claude target at explicit Connect through the existing permission-gated probe. Use fresh scoped discovery for test and hire. Discard stale results and require an explicit Connect after settings change. - Retain merged Codex onboarding recovery, auth preparation, import/effort corrections and Grok Bot gates. - Check the Claude first-task wizard's saved default directly. Update configuration/runtime documentation and exact Opus 5.5 accounting. - Align hire fixtures with the merged host-environment restriction. Native agent-authenticated hires cannot inject host env settings; both creation endpoints verify that no extra agent is saved. ## Verification - Updated onto master `9179d8dcc3e908c217fde4f63c9d08ccf8132eeb` through #15994. Native input v9 carries effort while preserving v7 home modes and v8 Muse. Codex defaults remain unchanged. - Focused local verification passed 285 server tests, 323 UI tests, 124 setup/registry tests, and two v9 permission-pin transport cases. Direct server/UI TypeScript checks passed. An initial 30-second hook timeout was resolved by serial verification with a longer hook budget: all 122 credential/permission cases and 232 snapshot/environment cases pass. Direct server TypeScript checking also passes. - Ordinary web creation with the experiment disabled saved native Claude, Opus 5.5 and High effort without runner/model overrides. The actual product task and follow-up both succeeded on integrated source `b2c9fe43f9cd3bc5dd9d22552da0148845ba71a4` with the cloud-built daemon from `04e0202ca81387b17cbe7fd094a8338648356fe9`. The final master reconciliation also changes shared runtime source. Historical proof retains its source identity; a final-source cloud qualification is running before refreshing the preview daemon. - Both actual browser downloads were checked: v1 has three sections/six checkboxes (451 bytes); v2 preserves the original body and adds two Rollback checks (612 bytes). The original attachment stayed byte-identical. The follow-up records session resume and the same provider session. Total estimated API usage: $0.518432800, with no pending/unpriced usage in the successful fixture. - Fixed the live-discovered setup incompatibility: native API-key validation no longer depends on the global Legacy Claude CLI. The existing provider endpoint verifies the key without a paid prompt; subscription/custom routing probes remain intact. - Fixed security review's native-hire credential redirection: agent-supplied URLs, proxy/launch settings and other host environment controls are rejected before inheritance. Native credential references remain supported and partial edits use the saved harness. Added create/hire/update regression coverage. - Current-head cloud CI is green. All three stack PRs have fresh Greptile 5/5 reviews and zero unresolved review threads. Required typecheck, test and build gates ran in cloud CI; Docker work stayed remote. Earlier failed checks remain in their original runs. - Docker and native release builds ran in cloud infrastructure. An inadvertent local Rust prerequisite was stopped; no local Docker build was run. - The final master merge preserves task-loading, permission, skill-retention and OpenRouter changes. Pi uses a fresh combined profile 27, preserving both historical profile-24 declarations; Copilot remains profile 22. Focused protocol checks passed 155 cases (one skipped), the updated Pi attestation check passed 18 (one skipped), and 91 evaluation/catalog checks passed. - Latest-application manual continuation passed in 37.942 seconds on `695e5c005a85bddc8711d3fcddcaf6b7e1fb64d0`, with High effort, native Opus 5.5, Anthropic API attribution, the same resumed Claude session, an independently checked 635-byte file and persisted Done status. It uses the earlier verified Mac daemon; the preceding-source package qualification passed at `dca62c7aeb4b45f0dd91a8e18d386a16a2658ef8`. That package run predates the small TypeScript startup fix and is not relabeled as qualification for it. - Upgrade limitation: changed compiled sidecar identity rejected old durable launch state and recovery hit session-open bounds before eventually resuming. That attempt was operator-cancelled and retained; the successful manual continuation does not qualify seamless upgrades. - Local latency profile, Opus 5.5/High unchanged: three alternating real-ACP loopback samples per variant reduce median provider-ready time from 5.081s to 4.034s. The matched real API task startup improves from 5.533s to 4.348s, but total reply time changes from 17.933s to 20.221s because agent work varies. This establishes a startup saving of about one second, not a consistent total-reply speedup. A real candidate follow-up passed in 20.146s and resumed the same saved session. The loopback fixture makes no external model requests; failed initial probes remain retained. - The startup change passes 107 focused runtime/effort/lease tests, 53 profile checks (one skipped), TypeScript checking and the TypeScript-only runtime build. Native hire fixture checks pass 70 tests; their first local run retained a socket-hangup failure and stale OpenCode expectation, both accounted for before the passing rerun. Broader required checks run in cloud CI. ## Risks - Missing packages, authentication rejection, unsupported settings and unavailable models must fail explicitly. Existing agents retain saved execution; explicit runner changes use existing revision/session invalidation. - Subscription follow-up remains unverified; remaining live acceptance uses API keys per human steering. Historical accounting holds and the separate $50 ceiling remain intact. - The subscription acceptance limit remains explicit for review. No Claude database migration is introduced. ## Model Used OpenAI Codex, GPT-6 family, with reasoning, repository tools, code execution and browser testing. The exact serving model ID and context-window size are not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [ ] Focused local tests and final cloud verification pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
283 lines
24 KiB
TypeScript
283 lines
24 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import { and, eq, ne, sql } from "drizzle-orm";
|
|
import { aiConnectionPools, aiConnectionRouterCursors, aiConnectionTaskPins, companySecrets, connectionGrants, instanceSettings, plugins, toolApplications, toolConnections, toolConnectionInstalls, type Db } from "@paperclipai/db";
|
|
import { aiConnectionRouterAppDefinition, aiConnectionRouterSlug, aiConnectionPoolConfigSchema, isAiConnectionCompatible, type AiConnectionPool, type AiConnectionPoolMember, type AiConnectionRouterRequest, type AiConnectionRouterSelection, type AiConnectionPoolSaveInput, type AiConnectionUsage } from "@paperclipai/shared";
|
|
import { isCodexLocalKnownModel, codexLocalReasoningEffortsForModel } from "@paperclipai/adapter-codex-local";
|
|
import { models as claudeModels, claudeLocalReasoningEffortsForModel } from "@paperclipai/adapter-claude-local";
|
|
import { models as grokModels, grokLocalReasoningEffortsForModel } from "@paperclipai/adapter-grok-local";
|
|
import { aiConnectionService } from "./ai-connections.js";
|
|
import { instanceSettingsService } from "./instance-settings.js";
|
|
import { logActivity } from "./activity-log.js";
|
|
import { forbidden, notFound, conflict, unprocessable } from "../errors.js";
|
|
import type { PluginWorkerManager } from "./plugin-worker-manager.js";
|
|
import { resolvePaperclipRunnerProviderProfile, resolvePaperclipRunnerNativeProviderInput } from "./native-runtime/provider-profile.js";
|
|
|
|
const usageCache = new Map<string, { expires: number; value: AiConnectionUsage }>();
|
|
const usageInFlight = new Map<string, Promise<AiConnectionUsage | undefined>>();
|
|
const routedRuntimeKeys = new Set(["provider", "acpxAgent", "model", "modelReasoningEffort", "reasoningEffort", "effort", "variant"]);
|
|
export function applyAiConnectionRouterTaskSettings(config: Record<string, unknown>, selection: AiConnectionRouterSelection) {
|
|
return { ...Object.fromEntries(Object.entries(config).filter(([key]) => !routedRuntimeKeys.has(key))), ...selection.runtimeConfig };
|
|
}
|
|
export class AiConnectionPoolExhausted extends Error {
|
|
readonly code = "ai_connection_pool_exhausted";
|
|
constructor(readonly retryAt: string, readonly poolId: string) { super("All eligible pool accounts are over their usage limit. Waiting for usage to reset."); }
|
|
}
|
|
|
|
/** Routing can override provider/model only, never environment, permissions, or instructions. */
|
|
export function poolMemberRuntimeConfig(member: AiConnectionPoolMember, adapterType: string, overrides: Record<string, unknown> = {}) {
|
|
const notes: string[] = [];
|
|
const provider = member.binding.provider;
|
|
const profile = member.profile;
|
|
const expected = provider === "openai" ? profile.provider === "codex"
|
|
: provider === "anthropic" ? profile.provider === "acpx" && profile.acpxAgent === "claude"
|
|
: provider === "xai" ? profile.provider === "acpx" && profile.acpxAgent === "grok"
|
|
: profile.provider === "opencode";
|
|
if (!expected) throw unprocessable("Pool member harness does not match its account");
|
|
const supportsModel = (value: string) => provider === "openai" ? isCodexLocalKnownModel(value)
|
|
: provider === "anthropic" ? claudeModels.some((m) => m.id === value)
|
|
: provider === "xai" ? grokModels.some((m) => m.id === value) : value.startsWith("openrouter/");
|
|
const config: Record<string, unknown> = { provider: profile.provider, ...(profile.acpxAgent ? { acpxAgent: profile.acpxAgent } : {}), model: profile.model };
|
|
const validate = () => {
|
|
if (!isAiConnectionCompatible(member.binding, adapterType, config.model, config.provider, config.acpxAgent)) throw unprocessable("Pool member is incompatible with this harness");
|
|
if (adapterType === "paperclip_runner") {
|
|
const resolved = resolvePaperclipRunnerProviderProfile(config);
|
|
resolvePaperclipRunnerNativeProviderInput({ backend: resolved.backend, adapterConfig: config });
|
|
}
|
|
};
|
|
validate();
|
|
if (typeof overrides.model === "string" && overrides.model !== profile.model) {
|
|
if (supportsModel(overrides.model)) {
|
|
config.model = overrides.model;
|
|
try { validate(); } catch { config.model = profile.model; notes.push("Model override is unavailable for this member; using its default."); }
|
|
} else notes.push("Model override is unavailable for this member; using its default.");
|
|
}
|
|
const model = String(config.model);
|
|
const efforts = provider === "openai" ? codexLocalReasoningEffortsForModel(model)
|
|
: provider === "anthropic" ? claudeLocalReasoningEffortsForModel(model)
|
|
: provider === "xai" ? grokLocalReasoningEffortsForModel(model) : [];
|
|
const effortKey = adapterType === "paperclip_runner" ? profile.provider === "codex" || (profile.provider === "acpx" && profile.acpxAgent === "claude") ? "modelReasoningEffort" : null
|
|
: provider === "anthropic" ? "effort" : provider === "xai" ? "reasoningEffort" : provider === "openai" ? "modelReasoningEffort" : "variant";
|
|
const requested = overrides.modelReasoningEffort ?? overrides.reasoningEffort ?? overrides.effort ?? overrides.variant;
|
|
const effort = typeof requested === "string" && efforts.includes(requested) && effortKey ? requested
|
|
: profile.effort && efforts.includes(profile.effort) && effortKey ? profile.effort : null;
|
|
if (requested && requested !== effort) notes.push("Effort override is unavailable for this member; using its default.");
|
|
if (effort && effortKey) config[effortKey] = effort;
|
|
validate();
|
|
return { config, notes };
|
|
}
|
|
|
|
export function aiConnectionRouterService(db: Db, workerManager?: PluginWorkerManager) {
|
|
async function owner(pluginKey: string) {
|
|
const [plugin] = await db.select().from(plugins).where(eq(plugins.pluginKey, pluginKey));
|
|
if (!plugin || plugin.status !== "ready" || !plugin.manifestJson.capabilities.includes("ai.connections.route")) throw unprocessable("Enable a compatible AI connection router plugin");
|
|
return plugin;
|
|
}
|
|
async function enabled() {
|
|
if (!(await instanceSettingsService(db).getExperimental()).enableAiConnectionRouters) throw unprocessable("Ask your instance operator to enable AI connection routing.", { code: "ai_connection_router_disabled" });
|
|
}
|
|
async function catalog() {
|
|
const experimental = (await instanceSettingsService(db).getExperimental()).enableAiConnectionRouters;
|
|
const installed = await db.select().from(plugins);
|
|
return installed.filter(plugin => plugin.status !== "uninstalled" && plugin.manifestJson.aiConnectionRouter && plugin.manifestJson.capabilities.includes("ai.connections.route"))
|
|
.map(plugin => aiConnectionRouterAppDefinition(plugin.pluginKey, plugin.manifestJson.aiConnectionRouter!, {
|
|
available: experimental && plugin.status === "ready",
|
|
...(!experimental ? { reason: "Ask your instance operator to enable AI connection routing." }
|
|
: plugin.status !== "ready" ? { reason: "Enable the connection pool plugin in Plugins." } : {}),
|
|
}));
|
|
}
|
|
async function list(companyId: string) {
|
|
const rows = await db.select({ pool: aiConnectionPools }).from(aiConnectionPools)
|
|
.innerJoin(toolConnections, and(eq(toolConnections.id, aiConnectionPools.id), eq(toolConnections.companyId, aiConnectionPools.companyId)))
|
|
.where(and(eq(aiConnectionPools.companyId, companyId), ne(toolConnections.status, "archived")));
|
|
return rows.map(({ pool: row }): AiConnectionPool => ({ ...row.config, id: row.id, companyId, pluginKey: row.pluginKey, revision: row.revision }));
|
|
}
|
|
async function selectable(companyId: string, userId: string) {
|
|
if (!(await instanceSettingsService(db).getExperimental()).enableAiConnectionRouters) return [];
|
|
const accounts = await aiConnectionService(db).list(companyId, userId);
|
|
const result: AiConnectionPool[] = [];
|
|
for (const pool of await list(companyId)) {
|
|
if (!pool.enabled) continue;
|
|
try { await owner(pool.pluginKey); } catch { continue; }
|
|
const members = pool.members.filter(member => accounts.some(account => account.id === member.binding.connectionId && account.grantId === member.binding.grantId));
|
|
if (members.length) result.push({ ...pool, members });
|
|
}
|
|
return result;
|
|
}
|
|
async function inspect(companyId: string, poolId: string, userId: string) {
|
|
const pool = (await list(companyId)).find(pool => pool.id === poolId);
|
|
if (!pool) throw notFound("Connection pool not found");
|
|
const visible = await aiConnectionService(db).list(companyId, userId);
|
|
const result: Record<string, { reason: string; checkedAt: string | null; usage?: AiConnectionUsage }> = {};
|
|
for (const member of pool.members) {
|
|
const account = visible.find(account => account.id === member.binding.connectionId && account.grantId === member.binding.grantId);
|
|
const key = account ? await usageCacheKey(member, companyId) : null;
|
|
const cached = key ? usageCache.get(key) : undefined;
|
|
const observation = cached && cached.expires > Date.now() ? cached.value : undefined;
|
|
result[member.id] = { reason: account?.status === "connected" ? "Eligible if agent access permits" : account?.status ?? "Not permitted", checkedAt: account && observation ? observation.checkedAt : null, ...(account && observation ? { usage: observation } : {}) };
|
|
}
|
|
return result;
|
|
}
|
|
async function save(pluginKey: string, input: AiConnectionPoolSaveInput, userId: string) {
|
|
await enabled();
|
|
const plugin = await owner(pluginKey);
|
|
const config = aiConnectionPoolConfigSchema.parse(input.config);
|
|
const visible = await aiConnectionService(db).list(input.companyId, userId);
|
|
for (const member of config.members) {
|
|
if (!visible.some((v) => v.id === member.binding.connectionId && v.grantId === member.binding.grantId)) throw forbidden("Choose an account you may use in this company");
|
|
poolMemberRuntimeConfig(member, "paperclip_runner");
|
|
}
|
|
const id = input.id ?? randomUUID();
|
|
await db.transaction(async (tx) => {
|
|
if (input.id) {
|
|
const [row] = await tx.select().from(aiConnectionPools).where(and(eq(aiConnectionPools.id, id), eq(aiConnectionPools.companyId, input.companyId), eq(aiConnectionPools.pluginKey, pluginKey))).for("update");
|
|
if (!row) throw notFound("Connection pool not found");
|
|
const [connection] = await tx.select().from(toolConnections).where(and(eq(toolConnections.id, id), eq(toolConnections.companyId, input.companyId)));
|
|
if (!connection || connection.status === "archived") throw notFound("Connection pool not found");
|
|
if (input.expectedRevision !== row.revision) throw conflict("Pool changed; reload before saving");
|
|
await tx.update(aiConnectionPools).set({ config, revision: row.revision + 1, updatedAt: new Date() }).where(eq(aiConnectionPools.id, id));
|
|
await tx.update(toolConnections).set({ name: config.name, enabled: config.enabled, updatedAt: new Date() }).where(and(eq(toolConnections.id, id), eq(toolConnections.companyId, input.companyId)));
|
|
} else {
|
|
const key = `plugin:${pluginKey}:ai-router`;
|
|
await tx.insert(toolApplications).values({ companyId: input.companyId, applicationKey: key, name: plugin.manifestJson.aiConnectionRouter?.name ?? plugin.manifestJson.displayName, metadata: { sourceTemplateKey: aiConnectionRouterSlug(pluginKey) }, type: "paperclip_plugin", pluginId: plugin.id }).onConflictDoNothing();
|
|
const [application] = await tx.select().from(toolApplications).where(and(eq(toolApplications.companyId, input.companyId), eq(toolApplications.applicationKey, key)));
|
|
if (!application) throw new Error("Router application could not be created");
|
|
await tx.insert(toolConnections).values({ id, companyId: input.companyId, applicationId: application.id, name: config.name, uid: id, connectionPurpose: "ai", transport: "runtime_auth", enabled: config.enabled, status: "active", healthStatus: "ok", config: { aiRouter: { pluginKey }, sourceTemplateKey: aiConnectionRouterSlug(pluginKey) }, createdByUserId: userId });
|
|
await tx.insert(aiConnectionPools).values({ id, companyId: input.companyId, pluginKey, config });
|
|
await tx.insert(aiConnectionRouterCursors).values({ poolId: id, companyId: input.companyId });
|
|
await tx.insert(toolConnectionInstalls).values({ companyId: input.companyId, connectionId: id, targetType: "company", targetId: input.companyId, createdByUserId: userId });
|
|
}
|
|
await logActivity(tx as unknown as Db, { companyId: input.companyId, actorType: "user", actorId: userId, action: "ai_connection.pool_saved", entityType: "tool_connection", entityId: id, details: { enabled: config.enabled, memberCount: config.members.length, mode: config.mode } });
|
|
});
|
|
return (await list(input.companyId)).find((p) => p.id === id)!;
|
|
}
|
|
async function remove(companyId: string, poolId: string, expectedRevision: number, userId: string) {
|
|
// Archive the virtual connection; cascading deletion would erase task pins.
|
|
// Cleanup remains available when the experimental flag or plugin is off.
|
|
await db.transaction(async tx => {
|
|
const [row] = await tx.select().from(aiConnectionPools).where(and(eq(aiConnectionPools.id, poolId), eq(aiConnectionPools.companyId, companyId))).for("update");
|
|
if (!row) throw notFound("Connection pool not found");
|
|
const [connection] = await tx.select().from(toolConnections).where(and(eq(toolConnections.id, poolId), eq(toolConnections.companyId, companyId)));
|
|
if (!connection || connection.status === "archived") throw notFound("Connection pool not found");
|
|
if (row.revision !== expectedRevision) throw conflict("Pool changed; reload before deleting");
|
|
await tx.update(aiConnectionPools).set({ config: { ...row.config, enabled: false }, revision: row.revision + 1, updatedAt: new Date() }).where(eq(aiConnectionPools.id, poolId));
|
|
await tx.update(toolConnections).set({ status: "archived", enabled: false, updatedAt: new Date() }).where(and(eq(toolConnections.id, poolId), eq(toolConnections.companyId, companyId)));
|
|
await logActivity(tx as unknown as Db, { companyId, actorType: "user", actorId: userId, action: "ai_connection.pool_deleted", entityType: "tool_connection", entityId: poolId, details: { retainedTaskPins: true } });
|
|
});
|
|
return { ok: true };
|
|
}
|
|
async function usageCacheKey(member: AiConnectionPoolMember, companyId: string) {
|
|
const [grant] = await db.select().from(connectionGrants).where(and(eq(connectionGrants.companyId, companyId), eq(connectionGrants.id, member.binding.grantId)));
|
|
if (!grant) return null;
|
|
const ref = grant.credentialSecretRefs.find((r) => r.configPath === "ai.credential");
|
|
const [secret] = ref ? await db.select({ version: companySecrets.latestVersion }).from(companySecrets).where(and(eq(companySecrets.companyId, companyId), eq(companySecrets.id, ref.secretId))) : [];
|
|
return `${companyId}:${grant.id}:${ref?.secretId}:${secret?.version}:${grant.updatedAt.toISOString()}`;
|
|
}
|
|
async function probe(member: AiConnectionPoolMember, companyId: string, userId: string, deadline: number) {
|
|
const key = await usageCacheKey(member, companyId);
|
|
if (!key) return undefined;
|
|
const cached = usageCache.get(key);
|
|
if (cached && cached.expires > Date.now()) return cached.value;
|
|
let pending = usageInFlight.get(key);
|
|
if (!pending) {
|
|
let probeTimer: ReturnType<typeof setTimeout> | undefined;
|
|
pending = Promise.race([
|
|
aiConnectionService(db).probeUsage(companyId, userId, member.binding.connectionId, member.binding.grantId).catch(() => undefined),
|
|
new Promise<undefined>(resolve => { probeTimer = setTimeout(() => resolve(undefined), 15_000); }),
|
|
]).then(value => {
|
|
if (value) {
|
|
const resets = value.limits.map(v => Date.parse(v.resetsAt ?? "")).filter(v => Number.isFinite(v) && v > Date.now());
|
|
if (usageCache.size > 1000) usageCache.clear();
|
|
usageCache.set(key, { value, expires: Math.min(Date.now() + 60_000, ...resets) });
|
|
}
|
|
return value;
|
|
}).finally(() => { if (probeTimer) clearTimeout(probeTimer); usageInFlight.delete(key); });
|
|
usageInFlight.set(key, pending);
|
|
}
|
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
try {
|
|
return await Promise.race([
|
|
pending,
|
|
new Promise<undefined>(resolve => { timer = setTimeout(() => resolve(undefined), Math.max(0, deadline - Date.now())); }),
|
|
]);
|
|
} finally { if (timer) clearTimeout(timer); }
|
|
}
|
|
|
|
async function resolve(input: { companyId: string; poolId: string; agentId: string; userId: string | null; adapterType: string; taskKey: string; overrides?: Record<string, unknown>; existingGrantId?: string; requireExisting?: boolean; persisted?: AiConnectionRouterSelection }) {
|
|
const pinWhere = and(eq(aiConnectionTaskPins.companyId, input.companyId), eq(aiConnectionTaskPins.poolId, input.poolId), eq(aiConnectionTaskPins.agentId, input.agentId), eq(aiConnectionTaskPins.taskKey, input.taskKey));
|
|
const validateSelection = async (selection: AiConnectionRouterSelection, client = db) => aiConnectionService(client).select({ companyId: input.companyId, agentId: input.agentId, userId: input.userId, adapterType: input.adapterType, binding: selection.binding, model: selection.runtimeConfig.model, runnerProvider: selection.runtimeConfig.provider, acpxAgent: selection.runtimeConfig.acpxAgent });
|
|
if (input.persisted) {
|
|
if (input.persisted.poolId !== input.poolId) throw unprocessable("Persisted pool selection does not match this run");
|
|
const [pin] = await db.select().from(aiConnectionTaskPins).where(pinWhere);
|
|
// Uninstall can remove the virtual connection. Server-owned native recovery
|
|
// evidence still authorizes the original concrete selection, never a new one.
|
|
if (pin && (pin.selection.memberId !== input.persisted.memberId || JSON.stringify(pin.selection.binding) !== JSON.stringify(input.persisted.binding))) throw unprocessable("Persisted pool allocation is inconsistent");
|
|
await validateSelection(input.persisted);
|
|
return input.persisted;
|
|
}
|
|
await enabled();
|
|
for (let attempt = 0; attempt < 20; attempt++) {
|
|
const [record] = await db.select({ pool: aiConnectionPools, connectionStatus: toolConnections.status }).from(aiConnectionPools)
|
|
.innerJoin(toolConnections, and(eq(toolConnections.id, aiConnectionPools.id), eq(toolConnections.companyId, aiConnectionPools.companyId)))
|
|
.where(and(eq(aiConnectionPools.id, input.poolId), eq(aiConnectionPools.companyId, input.companyId)));
|
|
if (!record || record.connectionStatus === "archived") throw unprocessable("This connection pool is unavailable; choose another AI connection");
|
|
const row = record.pool;
|
|
if (!row.config.enabled) throw unprocessable("Enable the selected connection pool");
|
|
const plugin = await owner(row.pluginKey);
|
|
if (!workerManager?.isRunning(plugin.id)) throw unprocessable("The connection router worker is unavailable; retry when it is ready");
|
|
const [pin] = await db.select().from(aiConnectionTaskPins).where(pinWhere);
|
|
const [cursor] = await db.select().from(aiConnectionRouterCursors).where(and(eq(aiConnectionRouterCursors.poolId, row.id), eq(aiConnectionRouterCursors.companyId, input.companyId)));
|
|
if (!cursor) throw unprocessable("The connection pool cursor is unavailable");
|
|
const pool: AiConnectionPool = { ...row.config, id: row.id, companyId: row.companyId, pluginKey: row.pluginKey, revision: row.revision };
|
|
const deadline = Date.now() + 15_000;
|
|
const candidates: AiConnectionRouterRequest["candidates"] = [];
|
|
for (const member of pin ? [pin.member] : pool.members) {
|
|
try {
|
|
const effective = poolMemberRuntimeConfig(member, input.adapterType, input.overrides);
|
|
const selection: AiConnectionRouterSelection = { poolId: row.id, memberId: member.id, binding: member.binding, runtimeConfig: effective.config, notes: effective.notes };
|
|
await validateSelection(selection);
|
|
candidates.push({ member, runtimeConfig: effective.config, notes: effective.notes });
|
|
} catch (error) { if (pin) throw error; }
|
|
}
|
|
if (!pin && input.requireExisting) {
|
|
const existing = candidates.find((candidate) => candidate.member.binding.grantId === input.existingGrantId);
|
|
if (!existing) throw unprocessable("Reset this task session before adopting the connection pool");
|
|
candidates.splice(0, candidates.length, existing);
|
|
}
|
|
if (pool.mode === "usage_aware" && input.userId) {
|
|
// At most four provider calls at once; the shared deadline bounds the whole pool.
|
|
for (let i = 0; i < candidates.length && Date.now() < deadline; i += 4) await Promise.all(candidates.slice(i, i + 4).map(async (candidate) => { candidate.usage = await probe(candidate.member, input.companyId, input.userId!, deadline); }));
|
|
}
|
|
const authorizedPool = { ...pool, members: candidates.map((candidate) => candidate.member) };
|
|
const result = await workerManager.call(plugin.id, "routeAiConnection", { companyId: input.companyId, pool: authorizedPool, memberOrder: pool.members.map((member) => member.id), agentId: input.agentId, taskKey: input.taskKey, lastMemberId: cursor.lastMemberId, cursorVersion: cursor.version, ...(pin ? { pinnedMemberId: pin.member.id } : {}), candidates, now: new Date().toISOString() }, 5000);
|
|
if (result.kind === "exhausted") {
|
|
const retry = Date.parse(result.retryAt);
|
|
throw new AiConnectionPoolExhausted(new Date(Number.isFinite(retry) ? Math.max(Date.now() + 1000, retry) : Date.now() + 60_000).toISOString(), pool.id);
|
|
}
|
|
if (result.kind !== "selected") throw unprocessable("No pool account is permitted and compatible for this task");
|
|
const candidate = candidates.find((v) => v.member.id === result.memberId);
|
|
if (!candidate || (pin && candidate.member.id !== pin.member.id)) throw unprocessable("The router returned an unauthorized member");
|
|
const selected: AiConnectionRouterSelection = { poolId: row.id, memberId: candidate.member.id, binding: candidate.member.binding, runtimeConfig: candidate.runtimeConfig, notes: candidate.notes };
|
|
if (pin) return selected;
|
|
const committed = await db.transaction(async (tx) => {
|
|
const [locked] = await tx.select().from(aiConnectionRouterCursors).where(and(eq(aiConnectionRouterCursors.poolId, row.id), eq(aiConnectionRouterCursors.companyId, input.companyId))).for("update");
|
|
const [existing] = await tx.select().from(aiConnectionTaskPins).where(pinWhere);
|
|
if (existing) return { retry: true };
|
|
const [current] = await tx.select().from(aiConnectionPools).where(and(eq(aiConnectionPools.id, row.id), eq(aiConnectionPools.companyId, input.companyId))).for("share");
|
|
if (!locked || locked.version !== cursor.version || !current || current.revision !== row.revision) return { retry: true };
|
|
const [currentPlugin] = await tx.select().from(plugins).where(eq(plugins.id, plugin.id)).for("share");
|
|
if (currentPlugin?.status !== "ready") throw unprocessable("The router plugin was disabled during allocation");
|
|
await tx.select({ id: instanceSettings.id }).from(instanceSettings).where(eq(instanceSettings.singletonKey, "default")).for("share");
|
|
if (!(await instanceSettingsService(tx as unknown as Db).getExperimental()).enableAiConnectionRouters) throw unprocessable("AI connection routers were disabled during allocation");
|
|
await validateSelection(selected, tx as unknown as Db);
|
|
await tx.insert(aiConnectionTaskPins).values({ companyId: input.companyId, poolId: row.id, agentId: input.agentId, taskKey: input.taskKey, selection: selected, member: candidate.member });
|
|
await tx.update(aiConnectionRouterCursors).set({ lastMemberId: candidate.member.id, version: sql`${aiConnectionRouterCursors.version} + 1` }).where(eq(aiConnectionRouterCursors.poolId, row.id));
|
|
await logActivity(tx as unknown as Db, { companyId: input.companyId, actorType: "system", actorId: "system", agentId: input.agentId, action: "ai_connection.pool_selected", entityType: "tool_connection", entityId: row.id, details: { memberId: candidate.member.id, connectionId: candidate.member.binding.connectionId, taskKey: input.taskKey } });
|
|
return { retry: false };
|
|
});
|
|
if (!committed.retry) return selected;
|
|
}
|
|
throw conflict("Concurrent pool selections changed the cursor; retry this task");
|
|
}
|
|
return { catalog, list, selectable, inspect, save, remove, resolve };
|
|
}
|