mirror of
https://github.com/alkimake/paperclip.git
synced 2026-06-14 01:50:39 +09:00
Add cheap model profiles for local adapters (#4881)
## Thinking Path > - Paperclip is a control plane for autonomous AI companies, where adapters are the boundary between the board, agents, and execution runtimes. > - Local adapters currently expose a primary runtime configuration, but operators often need a cheaper model lane for routine or low-risk work. > - That cheap lane has to stay adapter-owned: runtime profile settings should not mutate the primary adapter config or bypass existing auth/secret mediation. > - Issue creation also needs an ergonomic way to request primary, cheap, or custom model behavior for a selected assignee. > - This pull request adds a first-class `cheap` model profile contract across adapter capabilities, heartbeat config resolution, agent configuration, and issue creation. > - The benefit is cheaper task execution can be configured and requested explicitly while preserving adapter boundaries, secret handling, and audit visibility. ## What Changed - Added adapter model-profile capability metadata and a `cheap` profile contract for supported local adapters. - Applied `runtimeConfig.modelProfiles.cheap.adapterConfig` during heartbeat config resolution, including requested/applied/fallback run metadata. - Added agent configuration UI for cheap model profile settings without writing those settings into primary `adapterConfig`. - Added New Issue assignee model lane controls for Primary / Cheap / Custom and request payload handling. - Added run ledger profile badges and Storybook stories for the new cheap-lane UI states. - Added tests for validators, heartbeat model profile application, permission/secret mediation, UI payload helpers, and run ledger rendering. - Added committed UI verification screenshots under `docs/pr-screenshots/pap-2837/`. - Addressed Greptile review feedback around cheap-profile defaults, shared profile types, and fallback test data. ## Verification Local: - `pnpm exec vitest run packages/shared/src/validators/issue.test.ts server/src/__tests__/adapter-registry.test.ts server/src/__tests__/agent-permissions-routes.test.ts server/src/__tests__/heartbeat-model-profile.test.ts ui/src/components/IssueRunLedger.test.tsx ui/src/lib/agent-config-patch.test.ts ui/src/lib/issue-assignee-overrides.test.ts ui/src/lib/new-agent-runtime-config.test.ts` — passed, 8 files / 103 tests. - `pnpm exec vitest run ui/src/lib/new-agent-runtime-config.test.ts ui/src/components/IssueRunLedger.test.tsx` — passed after Greptile/rebase follow-up, 2 files / 17 tests. - `pnpm --filter @paperclipai/ui typecheck` — passed after Greptile/rebase follow-up. - `pnpm -r typecheck` — passed. - `pnpm build` — passed. - `pnpm test:run` — did not complete successfully in this local worktree: it stopped in pre-existing `@paperclipai/adapter-utils` sandbox/SSH fixture suites outside this PR diff. Failures were 5s local timeouts plus `git init -b` unsupported by this machine's Git 2.21.0. The branch-specific targeted suites above passed. - Branch was fetched/rebased onto `public-gh/master`; `git rev-list --left-right --count public-gh/master...HEAD` reports `0 9`. Remote PR checks on latest head `e30bf399146451c86cee98ed528d51d33fa5af5a`: - `policy` — passed. - `verify` — passed. - `e2e` — passed. - `Greptile Review` — passed, confidence score 5/5; Greptile review threads resolved. - `security/snyk (cryppadotta)` — passed. Screenshots: - [New issue cheap lane desktop](https://github.com/paperclipai/paperclip/blob/PAP-2837-plan-cheap-model-for-adapters-that-can-support-it/docs/pr-screenshots/pap-2837/newissue-cheap-desktop.png) - [New issue custom lane desktop](https://github.com/paperclipai/paperclip/blob/PAP-2837-plan-cheap-model-for-adapters-that-can-support-it/docs/pr-screenshots/pap-2837/newissue-custom-desktop.png) - [New issue unsupported adapter desktop](https://github.com/paperclipai/paperclip/blob/PAP-2837-plan-cheap-model-for-adapters-that-can-support-it/docs/pr-screenshots/pap-2837/newissue-unsupported-desktop.png) - [Run ledger model profile badges desktop](https://github.com/paperclipai/paperclip/blob/PAP-2837-plan-cheap-model-for-adapters-that-can-support-it/docs/pr-screenshots/pap-2837/runledger-profile-badges-desktop.png) - Mobile variants are also in `docs/pr-screenshots/pap-2837/`. ## Risks - Medium: heartbeat config mediation now merges runtime model profiles into adapter configs, so adapter secret normalization and host-command restrictions must keep covering nested config paths. - Medium: the UI adds another issue creation choice; unsupported adapters must keep hiding the cheap lane and preserve primary behavior. - Low migration risk: no database migration is included. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used OpenAI Codex coding agent using GPT-5-class reasoning with repo tool use and command execution. Exact served model/context window was not exposed by the runtime. ## 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 - [ ] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] If this change affects the UI, I have included before/after screenshots - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
parent
1fe1067361
commit
a3de1d764d
60 changed files with 2216 additions and 151 deletions
|
|
@ -28,6 +28,7 @@ import {
|
|||
findActiveServerAdapter,
|
||||
findServerAdapter,
|
||||
listAdapterModels,
|
||||
listAdapterModelProfiles,
|
||||
registerServerAdapter,
|
||||
requireServerAdapter,
|
||||
unregisterServerAdapter,
|
||||
|
|
@ -79,6 +80,31 @@ describe("server adapter registry", () => {
|
|||
]);
|
||||
});
|
||||
|
||||
it("exposes adapter model profiles when adapters declare them", async () => {
|
||||
const adapterWithProfiles: ServerAdapterModule = {
|
||||
...externalAdapter,
|
||||
modelProfiles: [
|
||||
{
|
||||
key: "cheap",
|
||||
label: "Cheap",
|
||||
adapterConfig: { model: "external-mini" },
|
||||
source: "adapter_default",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
registerServerAdapter(adapterWithProfiles);
|
||||
|
||||
expect(await listAdapterModelProfiles("external_test")).toEqual([
|
||||
{
|
||||
key: "cheap",
|
||||
label: "Cheap",
|
||||
adapterConfig: { model: "external-mini" },
|
||||
source: "adapter_default",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("removes external adapters when unregistered", () => {
|
||||
registerServerAdapter(externalAdapter);
|
||||
|
||||
|
|
@ -167,6 +193,45 @@ describe("server adapter registry", () => {
|
|||
expect(adapter!.supportsLocalAgentJwt).toBe(true);
|
||||
});
|
||||
|
||||
it("built-in local adapters declare cheap model profile defaults where supported", async () => {
|
||||
await expect(listAdapterModelProfiles("claude_local")).resolves.toEqual([
|
||||
expect.objectContaining({
|
||||
key: "cheap",
|
||||
adapterConfig: expect.objectContaining({ model: "claude-sonnet-4-6" }),
|
||||
source: "adapter_default",
|
||||
}),
|
||||
]);
|
||||
await expect(listAdapterModelProfiles("codex_local")).resolves.toEqual([
|
||||
expect.objectContaining({
|
||||
key: "cheap",
|
||||
adapterConfig: expect.objectContaining({ model: "gpt-5.3-codex-spark" }),
|
||||
source: "adapter_default",
|
||||
}),
|
||||
]);
|
||||
await expect(listAdapterModelProfiles("gemini_local")).resolves.toEqual([
|
||||
expect.objectContaining({
|
||||
key: "cheap",
|
||||
adapterConfig: expect.objectContaining({ model: "gemini-2.5-flash-lite" }),
|
||||
source: "adapter_default",
|
||||
}),
|
||||
]);
|
||||
await expect(listAdapterModelProfiles("opencode_local")).resolves.toEqual([
|
||||
expect.objectContaining({
|
||||
key: "cheap",
|
||||
adapterConfig: expect.objectContaining({ model: "openai/gpt-5.1-codex-mini" }),
|
||||
source: "adapter_default",
|
||||
}),
|
||||
]);
|
||||
await expect(listAdapterModelProfiles("cursor")).resolves.toEqual([
|
||||
expect.objectContaining({
|
||||
key: "cheap",
|
||||
adapterConfig: expect.objectContaining({ model: "gpt-5.1-codex-mini" }),
|
||||
source: "adapter_default",
|
||||
}),
|
||||
]);
|
||||
await expect(listAdapterModelProfiles("pi_local")).resolves.toEqual([]);
|
||||
});
|
||||
|
||||
it("switches active adapter behavior back to the builtin when an override is paused", async () => {
|
||||
const builtIn = findServerAdapter("claude_local");
|
||||
expect(builtIn).not.toBeNull();
|
||||
|
|
|
|||
|
|
@ -496,6 +496,165 @@ describe.sequential("agent permission routes", () => {
|
|||
expect(mockLogActivity).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("blocks agent-authenticated self-updates that set cheap-profile host-executed workspace commands", async () => {
|
||||
mockAgentService.getById.mockResolvedValue({
|
||||
...baseAgent,
|
||||
adapterType: "codex_local",
|
||||
});
|
||||
|
||||
const app = await createApp({
|
||||
type: "agent",
|
||||
agentId,
|
||||
companyId,
|
||||
source: "agent_key",
|
||||
runId: "run-1",
|
||||
});
|
||||
|
||||
const res = await requestApp(app, (baseUrl) => request(baseUrl)
|
||||
.patch(`/api/agents/${agentId}`)
|
||||
.send({
|
||||
runtimeConfig: {
|
||||
modelProfiles: {
|
||||
cheap: {
|
||||
adapterConfig: {
|
||||
workspaceStrategy: {
|
||||
type: "git_worktree",
|
||||
provisionCommand: "touch /tmp/paperclip-rce",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body.error).toContain("host-executed workspace commands");
|
||||
expect(res.body.error).toContain(
|
||||
"runtimeConfig.modelProfiles.cheap.adapterConfig.workspaceStrategy.provisionCommand",
|
||||
);
|
||||
expect(mockLogActivity).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("allows board updates that set cheap-profile workspace commands", async () => {
|
||||
mockAgentService.getById.mockResolvedValue({
|
||||
...baseAgent,
|
||||
adapterType: "codex_local",
|
||||
});
|
||||
|
||||
const app = await createApp({
|
||||
type: "board",
|
||||
userId: "board-user",
|
||||
source: "local_implicit",
|
||||
isInstanceAdmin: true,
|
||||
companyIds: [companyId],
|
||||
});
|
||||
|
||||
const runtimeConfig = {
|
||||
modelProfiles: {
|
||||
cheap: {
|
||||
adapterConfig: {
|
||||
workspaceStrategy: {
|
||||
type: "git_worktree",
|
||||
provisionCommand: "bash ./scripts/provision-worktree.sh",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const res = await requestApp(app, (baseUrl) => request(baseUrl)
|
||||
.patch(`/api/agents/${agentId}`)
|
||||
.send({ runtimeConfig }));
|
||||
|
||||
expect(res.status, JSON.stringify(res.body)).toBe(200);
|
||||
expect(mockAgentService.update).toHaveBeenCalledWith(
|
||||
agentId,
|
||||
expect.objectContaining({ runtimeConfig }),
|
||||
expect.anything(),
|
||||
);
|
||||
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
|
||||
action: "agent.updated",
|
||||
}));
|
||||
});
|
||||
|
||||
it("normalizes cheap-profile env bindings through the adapter config secret pipeline", async () => {
|
||||
mockAgentService.getById.mockResolvedValue({
|
||||
...baseAgent,
|
||||
adapterType: "codex_local",
|
||||
});
|
||||
mockSecretService.normalizeAdapterConfigForPersistence.mockImplementation(async (_companyId, config) => ({
|
||||
...config,
|
||||
env: {
|
||||
API_TOKEN: {
|
||||
type: "secret_ref",
|
||||
secretId: "33333333-3333-4333-8333-333333333333",
|
||||
version: "latest",
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
const app = await createApp({
|
||||
type: "board",
|
||||
userId: "board-user",
|
||||
source: "local_implicit",
|
||||
isInstanceAdmin: true,
|
||||
companyIds: [companyId],
|
||||
});
|
||||
|
||||
const res = await requestApp(app, (baseUrl) => request(baseUrl)
|
||||
.patch(`/api/agents/${agentId}`)
|
||||
.send({
|
||||
runtimeConfig: {
|
||||
modelProfiles: {
|
||||
cheap: {
|
||||
adapterConfig: {
|
||||
model: "gpt-5.3-codex-spark",
|
||||
env: {
|
||||
API_TOKEN: {
|
||||
type: "secret_ref",
|
||||
secretId: "33333333-3333-4333-8333-333333333333",
|
||||
version: "latest",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
expect(res.status, JSON.stringify(res.body)).toBe(200);
|
||||
expect(mockSecretService.normalizeAdapterConfigForPersistence).toHaveBeenCalledWith(
|
||||
companyId,
|
||||
expect.objectContaining({
|
||||
model: "gpt-5.3-codex-spark",
|
||||
env: expect.any(Object),
|
||||
}),
|
||||
{ strictMode: false },
|
||||
);
|
||||
expect(mockAgentService.update).toHaveBeenCalledWith(
|
||||
agentId,
|
||||
expect.objectContaining({
|
||||
runtimeConfig: {
|
||||
modelProfiles: {
|
||||
cheap: {
|
||||
adapterConfig: {
|
||||
model: "gpt-5.3-codex-spark",
|
||||
env: {
|
||||
API_TOKEN: {
|
||||
type: "secret_ref",
|
||||
secretId: "33333333-3333-4333-8333-333333333333",
|
||||
version: "latest",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
it("blocks agent-authenticated self-updates that set instructions bundle roots", async () => {
|
||||
const app = await createApp({
|
||||
type: "agent",
|
||||
|
|
|
|||
123
server/src/__tests__/heartbeat-model-profile.test.ts
Normal file
123
server/src/__tests__/heartbeat-model-profile.test.ts
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import type { AdapterModelProfileDefinition } from "../adapters/index.js";
|
||||
import {
|
||||
mergeModelProfileAdapterConfig,
|
||||
normalizeModelProfileWakeContext,
|
||||
resolveModelProfileApplication,
|
||||
} from "../services/heartbeat.ts";
|
||||
|
||||
const cheapProfile: AdapterModelProfileDefinition = {
|
||||
key: "cheap",
|
||||
label: "Cheap",
|
||||
adapterConfig: {
|
||||
model: "adapter-cheap",
|
||||
modelReasoningEffort: "low",
|
||||
},
|
||||
source: "adapter_default",
|
||||
};
|
||||
|
||||
describe("heartbeat model profile application", () => {
|
||||
it("applies cheap profile patches before explicit issue adapter config overrides", () => {
|
||||
const modelProfile = resolveModelProfileApplication({
|
||||
adapterModelProfiles: [cheapProfile],
|
||||
agentRuntimeConfig: {},
|
||||
issueModelProfile: "cheap",
|
||||
contextSnapshot: {},
|
||||
});
|
||||
|
||||
const merged = mergeModelProfileAdapterConfig({
|
||||
baseConfig: {
|
||||
model: "primary",
|
||||
modelReasoningEffort: "high",
|
||||
approvalPolicy: "strict",
|
||||
},
|
||||
modelProfile,
|
||||
issueAdapterConfig: {
|
||||
model: "issue-explicit",
|
||||
},
|
||||
});
|
||||
|
||||
expect(modelProfile).toMatchObject({
|
||||
requested: "cheap",
|
||||
requestedBy: "issue_override",
|
||||
applied: "cheap",
|
||||
configSource: "adapter_default",
|
||||
fallbackReason: null,
|
||||
});
|
||||
expect(merged).toEqual({
|
||||
model: "issue-explicit",
|
||||
modelReasoningEffort: "low",
|
||||
approvalPolicy: "strict",
|
||||
});
|
||||
});
|
||||
|
||||
it("lets agent runtime profile config customize adapter defaults", () => {
|
||||
const modelProfile = resolveModelProfileApplication({
|
||||
adapterModelProfiles: [cheapProfile],
|
||||
agentRuntimeConfig: {
|
||||
modelProfiles: {
|
||||
cheap: {
|
||||
adapterConfig: {
|
||||
model: "agent-cheap",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
issueModelProfile: null,
|
||||
contextSnapshot: { modelProfile: "cheap" },
|
||||
});
|
||||
|
||||
expect(modelProfile).toMatchObject({
|
||||
requested: "cheap",
|
||||
requestedBy: "wake_context",
|
||||
applied: "cheap",
|
||||
configSource: "agent_runtime",
|
||||
adapterConfig: {
|
||||
model: "agent-cheap",
|
||||
modelReasoningEffort: "low",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to the primary config when the adapter does not support the requested profile", () => {
|
||||
const modelProfile = resolveModelProfileApplication({
|
||||
adapterModelProfiles: [],
|
||||
agentRuntimeConfig: {
|
||||
modelProfiles: {
|
||||
cheap: {
|
||||
adapterConfig: {
|
||||
model: "agent-cheap",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
issueModelProfile: null,
|
||||
contextSnapshot: { modelProfile: "cheap" },
|
||||
});
|
||||
|
||||
const merged = mergeModelProfileAdapterConfig({
|
||||
baseConfig: {
|
||||
model: "primary",
|
||||
},
|
||||
modelProfile,
|
||||
issueAdapterConfig: null,
|
||||
});
|
||||
|
||||
expect(modelProfile).toMatchObject({
|
||||
requested: "cheap",
|
||||
applied: null,
|
||||
fallbackReason: "adapter_profile_not_supported",
|
||||
adapterConfig: null,
|
||||
});
|
||||
expect(merged).toEqual({ model: "primary" });
|
||||
});
|
||||
|
||||
it("normalizes a wake payload model profile into run context", () => {
|
||||
const contextSnapshot = normalizeModelProfileWakeContext({
|
||||
contextSnapshot: {},
|
||||
payload: { modelProfile: "cheap" },
|
||||
});
|
||||
|
||||
expect(contextSnapshot).toMatchObject({ modelProfile: "cheap" });
|
||||
});
|
||||
});
|
||||
|
|
@ -6,6 +6,7 @@ export {
|
|||
findServerAdapter,
|
||||
findActiveServerAdapter,
|
||||
detectAdapterModel,
|
||||
listAdapterModelProfiles,
|
||||
registerServerAdapter,
|
||||
unregisterServerAdapter,
|
||||
requireServerAdapter,
|
||||
|
|
@ -15,6 +16,7 @@ export type {
|
|||
AdapterExecutionContext,
|
||||
AdapterExecutionResult,
|
||||
AdapterInvocationMeta,
|
||||
AdapterModelProfileDefinition,
|
||||
AdapterEnvironmentCheckLevel,
|
||||
AdapterEnvironmentCheck,
|
||||
AdapterEnvironmentTestStatus,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import type { ServerAdapterModule } from "./types.js";
|
||||
import type { AdapterModelProfileDefinition, ServerAdapterModule } from "./types.js";
|
||||
import { getAdapterSessionManagement } from "@paperclipai/adapter-utils";
|
||||
import {
|
||||
execute as claudeExecute,
|
||||
|
|
@ -9,7 +9,11 @@ import {
|
|||
sessionCodec as claudeSessionCodec,
|
||||
getQuotaWindows as claudeGetQuotaWindows,
|
||||
} from "@paperclipai/adapter-claude-local/server";
|
||||
import { agentConfigurationDoc as claudeAgentConfigurationDoc, models as claudeModels } from "@paperclipai/adapter-claude-local";
|
||||
import {
|
||||
agentConfigurationDoc as claudeAgentConfigurationDoc,
|
||||
models as claudeModels,
|
||||
modelProfiles as claudeModelProfiles,
|
||||
} from "@paperclipai/adapter-claude-local";
|
||||
import {
|
||||
execute as codexExecute,
|
||||
listCodexSkills,
|
||||
|
|
@ -18,7 +22,11 @@ import {
|
|||
sessionCodec as codexSessionCodec,
|
||||
getQuotaWindows as codexGetQuotaWindows,
|
||||
} from "@paperclipai/adapter-codex-local/server";
|
||||
import { agentConfigurationDoc as codexAgentConfigurationDoc, models as codexModels } from "@paperclipai/adapter-codex-local";
|
||||
import {
|
||||
agentConfigurationDoc as codexAgentConfigurationDoc,
|
||||
models as codexModels,
|
||||
modelProfiles as codexModelProfiles,
|
||||
} from "@paperclipai/adapter-codex-local";
|
||||
import {
|
||||
execute as cursorExecute,
|
||||
listCursorSkills,
|
||||
|
|
@ -26,7 +34,11 @@ import {
|
|||
testEnvironment as cursorTestEnvironment,
|
||||
sessionCodec as cursorSessionCodec,
|
||||
} from "@paperclipai/adapter-cursor-local/server";
|
||||
import { agentConfigurationDoc as cursorAgentConfigurationDoc, models as cursorModels } from "@paperclipai/adapter-cursor-local";
|
||||
import {
|
||||
agentConfigurationDoc as cursorAgentConfigurationDoc,
|
||||
models as cursorModels,
|
||||
modelProfiles as cursorModelProfiles,
|
||||
} from "@paperclipai/adapter-cursor-local";
|
||||
import {
|
||||
execute as geminiExecute,
|
||||
listGeminiSkills,
|
||||
|
|
@ -34,7 +46,11 @@ import {
|
|||
testEnvironment as geminiTestEnvironment,
|
||||
sessionCodec as geminiSessionCodec,
|
||||
} from "@paperclipai/adapter-gemini-local/server";
|
||||
import { agentConfigurationDoc as geminiAgentConfigurationDoc, models as geminiModels } from "@paperclipai/adapter-gemini-local";
|
||||
import {
|
||||
agentConfigurationDoc as geminiAgentConfigurationDoc,
|
||||
models as geminiModels,
|
||||
modelProfiles as geminiModelProfiles,
|
||||
} from "@paperclipai/adapter-gemini-local";
|
||||
import {
|
||||
execute as openCodeExecute,
|
||||
listOpenCodeSkills,
|
||||
|
|
@ -46,6 +62,7 @@ import {
|
|||
import {
|
||||
agentConfigurationDoc as openCodeAgentConfigurationDoc,
|
||||
models as openCodeModels,
|
||||
modelProfiles as openCodeModelProfiles,
|
||||
} from "@paperclipai/adapter-opencode-local";
|
||||
import {
|
||||
execute as openclawGatewayExecute,
|
||||
|
|
@ -67,6 +84,7 @@ import {
|
|||
} from "@paperclipai/adapter-pi-local/server";
|
||||
import {
|
||||
agentConfigurationDoc as piAgentConfigurationDoc,
|
||||
modelProfiles as piModelProfiles,
|
||||
} from "@paperclipai/adapter-pi-local";
|
||||
import {
|
||||
execute as hermesExecute,
|
||||
|
|
@ -126,6 +144,7 @@ const claudeLocalAdapter: ServerAdapterModule = {
|
|||
sessionCodec: claudeSessionCodec,
|
||||
sessionManagement: getAdapterSessionManagement("claude_local") ?? undefined,
|
||||
models: claudeModels,
|
||||
modelProfiles: claudeModelProfiles,
|
||||
listModels: listClaudeModels,
|
||||
supportsLocalAgentJwt: true,
|
||||
supportsInstructionsBundle: true,
|
||||
|
|
@ -144,6 +163,7 @@ const codexLocalAdapter: ServerAdapterModule = {
|
|||
sessionCodec: codexSessionCodec,
|
||||
sessionManagement: getAdapterSessionManagement("codex_local") ?? undefined,
|
||||
models: codexModels,
|
||||
modelProfiles: codexModelProfiles,
|
||||
listModels: listCodexModels,
|
||||
refreshModels: refreshCodexModels,
|
||||
supportsLocalAgentJwt: true,
|
||||
|
|
@ -163,6 +183,7 @@ const cursorLocalAdapter: ServerAdapterModule = {
|
|||
sessionCodec: cursorSessionCodec,
|
||||
sessionManagement: getAdapterSessionManagement("cursor") ?? undefined,
|
||||
models: cursorModels,
|
||||
modelProfiles: cursorModelProfiles,
|
||||
listModels: listCursorModels,
|
||||
supportsLocalAgentJwt: true,
|
||||
supportsInstructionsBundle: true,
|
||||
|
|
@ -180,6 +201,7 @@ const geminiLocalAdapter: ServerAdapterModule = {
|
|||
sessionCodec: geminiSessionCodec,
|
||||
sessionManagement: getAdapterSessionManagement("gemini_local") ?? undefined,
|
||||
models: geminiModels,
|
||||
modelProfiles: geminiModelProfiles,
|
||||
supportsLocalAgentJwt: true,
|
||||
supportsInstructionsBundle: true,
|
||||
instructionsPathKey: "instructionsFilePath",
|
||||
|
|
@ -206,6 +228,7 @@ const openCodeLocalAdapter: ServerAdapterModule = {
|
|||
syncSkills: syncOpenCodeSkills,
|
||||
sessionCodec: openCodeSessionCodec,
|
||||
models: openCodeModels,
|
||||
modelProfiles: openCodeModelProfiles,
|
||||
sessionManagement: getAdapterSessionManagement("opencode_local") ?? undefined,
|
||||
listModels: listOpenCodeModels,
|
||||
supportsLocalAgentJwt: true,
|
||||
|
|
@ -224,6 +247,7 @@ const piLocalAdapter: ServerAdapterModule = {
|
|||
sessionCodec: piSessionCodec,
|
||||
sessionManagement: getAdapterSessionManagement("pi_local") ?? undefined,
|
||||
models: [],
|
||||
modelProfiles: piModelProfiles,
|
||||
listModels: listPiModels,
|
||||
supportsLocalAgentJwt: true,
|
||||
supportsInstructionsBundle: true,
|
||||
|
|
@ -474,6 +498,16 @@ export async function refreshAdapterModels(type: string): Promise<{ id: string;
|
|||
return adapter.models ?? [];
|
||||
}
|
||||
|
||||
export async function listAdapterModelProfiles(type: string): Promise<AdapterModelProfileDefinition[]> {
|
||||
const adapter = findActiveServerAdapter(type);
|
||||
if (!adapter) return [];
|
||||
if (adapter.listModelProfiles) {
|
||||
const discovered = await adapter.listModelProfiles();
|
||||
if (discovered.length > 0) return discovered;
|
||||
}
|
||||
return adapter.modelProfiles ?? [];
|
||||
}
|
||||
|
||||
export function listServerAdapters(): ServerAdapterModule[] {
|
||||
return Array.from(adaptersByType.values());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,6 +22,8 @@ export type {
|
|||
AdapterSkillContext,
|
||||
AdapterSessionCodec,
|
||||
AdapterModel,
|
||||
AdapterModelProfileKey,
|
||||
AdapterModelProfileDefinition,
|
||||
NativeContextManagement,
|
||||
ResolvedSessionCompactionPolicy,
|
||||
SessionCompactionPolicy,
|
||||
|
|
|
|||
|
|
@ -66,6 +66,7 @@ interface AdapterCapabilities {
|
|||
supportsSkills: boolean;
|
||||
supportsLocalAgentJwt: boolean;
|
||||
requiresMaterializedRuntimeSkills: boolean;
|
||||
supportsModelProfiles: boolean;
|
||||
}
|
||||
|
||||
interface AdapterInfo {
|
||||
|
|
@ -119,6 +120,7 @@ function buildAdapterCapabilities(adapter: ServerAdapterModule): AdapterCapabili
|
|||
supportsSkills: Boolean(adapter.listSkills || adapter.syncSkills),
|
||||
supportsLocalAgentJwt: adapter.supportsLocalAgentJwt ?? false,
|
||||
requiresMaterializedRuntimeSkills: adapter.requiresMaterializedRuntimeSkills ?? false,
|
||||
supportsModelProfiles: Boolean(adapter.modelProfiles?.length || adapter.listModelProfiles),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -63,6 +63,7 @@ import {
|
|||
findActiveServerAdapter,
|
||||
findServerAdapter,
|
||||
listAdapterModels,
|
||||
listAdapterModelProfiles,
|
||||
refreshAdapterModels,
|
||||
requireServerAdapter,
|
||||
} from "../adapters/index.js";
|
||||
|
|
@ -710,6 +711,99 @@ export function agentRoutes(
|
|||
return normalizedRuntimeConfig;
|
||||
}
|
||||
|
||||
function listRuntimeModelProfileAdapterConfigs(runtimeConfig: unknown): Array<{
|
||||
profileKey: string;
|
||||
profile: Record<string, unknown>;
|
||||
adapterConfig: Record<string, unknown>;
|
||||
path: string;
|
||||
}> {
|
||||
const runtimeRecord = asRecord(runtimeConfig);
|
||||
const modelProfiles = asRecord(runtimeRecord?.modelProfiles);
|
||||
if (!modelProfiles) return [];
|
||||
|
||||
const entries: Array<{
|
||||
profileKey: string;
|
||||
profile: Record<string, unknown>;
|
||||
adapterConfig: Record<string, unknown>;
|
||||
path: string;
|
||||
}> = [];
|
||||
for (const [profileKey, rawProfile] of Object.entries(modelProfiles)) {
|
||||
const profile = asRecord(rawProfile);
|
||||
const adapterConfig = asRecord(profile?.adapterConfig);
|
||||
if (!profile || !adapterConfig) continue;
|
||||
entries.push({
|
||||
profileKey,
|
||||
profile,
|
||||
adapterConfig,
|
||||
path: `runtimeConfig.modelProfiles.${profileKey}.adapterConfig`,
|
||||
});
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
function assertNoAgentRuntimeConfigAdapterConfigMutation(req: Request, runtimeConfig: unknown) {
|
||||
for (const entry of listRuntimeModelProfileAdapterConfigs(runtimeConfig)) {
|
||||
assertNoAgentAdapterConfigMutation(req, entry.adapterConfig, entry.path);
|
||||
}
|
||||
}
|
||||
|
||||
async function normalizeMediatedAdapterConfigForPersistence(input: {
|
||||
companyId: string;
|
||||
adapterType: string | null | undefined;
|
||||
adapterConfig: Record<string, unknown>;
|
||||
constraintAdapterConfig?: Record<string, unknown>;
|
||||
}): Promise<Record<string, unknown>> {
|
||||
const normalizedAdapterConfig = await secretsSvc.normalizeAdapterConfigForPersistence(
|
||||
input.companyId,
|
||||
input.adapterConfig,
|
||||
{ strictMode: strictSecretsMode },
|
||||
);
|
||||
await assertAdapterConfigConstraints(
|
||||
input.companyId,
|
||||
input.adapterType,
|
||||
input.constraintAdapterConfig
|
||||
? { ...input.constraintAdapterConfig, ...normalizedAdapterConfig }
|
||||
: normalizedAdapterConfig,
|
||||
);
|
||||
return normalizedAdapterConfig;
|
||||
}
|
||||
|
||||
async function normalizeRuntimeConfigAdapterConfigsForPersistence(
|
||||
companyId: string,
|
||||
adapterType: string,
|
||||
runtimeConfig: Record<string, unknown>,
|
||||
baseAdapterConfig: Record<string, unknown>,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const entries = listRuntimeModelProfileAdapterConfigs(runtimeConfig);
|
||||
if (entries.length === 0) return runtimeConfig;
|
||||
const adapterModelProfiles = await listAdapterModelProfiles(adapterType);
|
||||
|
||||
const normalizedRuntimeConfig = { ...runtimeConfig };
|
||||
const modelProfiles = asRecord(runtimeConfig.modelProfiles) ?? {};
|
||||
const normalizedModelProfiles = { ...modelProfiles };
|
||||
normalizedRuntimeConfig.modelProfiles = normalizedModelProfiles;
|
||||
|
||||
for (const entry of entries) {
|
||||
const adapterProfile = adapterModelProfiles.find((profile) => profile.key === entry.profileKey);
|
||||
const adapterDefaultConfig = asRecord(adapterProfile?.adapterConfig) ?? {};
|
||||
const normalizedAdapterConfig = await normalizeMediatedAdapterConfigForPersistence({
|
||||
companyId,
|
||||
adapterType,
|
||||
adapterConfig: entry.adapterConfig,
|
||||
constraintAdapterConfig: {
|
||||
...baseAdapterConfig,
|
||||
...adapterDefaultConfig,
|
||||
},
|
||||
});
|
||||
normalizedModelProfiles[entry.profileKey] = {
|
||||
...entry.profile,
|
||||
adapterConfig: normalizedAdapterConfig,
|
||||
};
|
||||
}
|
||||
|
||||
return normalizedRuntimeConfig;
|
||||
}
|
||||
|
||||
function generateEd25519PrivateKeyPem(): string {
|
||||
const { privateKey } = generateKeyPairSync("ed25519");
|
||||
return privateKey.export({ type: "pkcs8", format: "pem" }).toString();
|
||||
|
|
@ -866,15 +960,34 @@ export function agentRoutes(
|
|||
function assertNoAgentInstructionsConfigMutation(
|
||||
req: Request,
|
||||
adapterConfig: Record<string, unknown> | null | undefined,
|
||||
path = "adapterConfig",
|
||||
) {
|
||||
if (req.actor.type !== "agent" || !adapterConfig) return;
|
||||
const changedSensitiveKeys = KNOWN_INSTRUCTIONS_BUNDLE_KEYS.filter((key) => adapterConfig[key] !== undefined);
|
||||
const changedSensitiveKeys = KNOWN_INSTRUCTIONS_BUNDLE_KEYS
|
||||
.filter((key) => adapterConfig[key] !== undefined)
|
||||
.map((key) => `${path}.${key}`);
|
||||
if (changedSensitiveKeys.length === 0) return;
|
||||
throw forbidden(
|
||||
`Agent-authenticated callers cannot modify instructions path or bundle configuration (${changedSensitiveKeys.join(", ")})`,
|
||||
);
|
||||
}
|
||||
|
||||
function adapterConfigTouchesInstructionsConfig(adapterConfig: Record<string, unknown>) {
|
||||
return KNOWN_INSTRUCTIONS_BUNDLE_KEYS.some((key) => adapterConfig[key] !== undefined);
|
||||
}
|
||||
|
||||
function assertNoAgentAdapterConfigMutation(
|
||||
req: Request,
|
||||
adapterConfig: Record<string, unknown>,
|
||||
path = "adapterConfig",
|
||||
) {
|
||||
assertNoAgentInstructionsConfigMutation(req, adapterConfig, path);
|
||||
assertNoAgentHostWorkspaceCommandMutation(
|
||||
req,
|
||||
collectAgentAdapterWorkspaceCommandPaths(adapterConfig, path),
|
||||
);
|
||||
}
|
||||
|
||||
function summarizeAgentUpdateDetails(patch: Record<string, unknown>) {
|
||||
const changedTopLevelKeys = Object.keys(patch).sort();
|
||||
const details: Record<string, unknown> = { changedTopLevelKeys };
|
||||
|
|
@ -1064,6 +1177,14 @@ export function agentRoutes(
|
|||
res.json(models);
|
||||
});
|
||||
|
||||
router.get("/companies/:companyId/adapters/:type/model-profiles", async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
assertCompanyAccess(req, companyId);
|
||||
const type = assertKnownAdapterType(req.params.type as string);
|
||||
const profiles = await listAdapterModelProfiles(type);
|
||||
res.json(profiles);
|
||||
});
|
||||
|
||||
router.get("/companies/:companyId/adapters/:type/detect-model", async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
assertCompanyAccess(req, companyId);
|
||||
|
|
@ -1624,21 +1745,16 @@ export function agentRoutes(
|
|||
...hireInput
|
||||
} = req.body;
|
||||
hireInput.adapterType = assertKnownAdapterType(hireInput.adapterType);
|
||||
const rawHireAdapterConfig = (hireInput.adapterConfig ?? {}) as Record<string, unknown>;
|
||||
assertNoNewAgentLegacyPromptTemplate(
|
||||
hireInput.adapterType,
|
||||
(hireInput.adapterConfig ?? {}) as Record<string, unknown>,
|
||||
);
|
||||
assertNoAgentHostWorkspaceCommandMutation(
|
||||
req,
|
||||
collectAgentAdapterWorkspaceCommandPaths(hireInput.adapterConfig),
|
||||
);
|
||||
assertNoAgentInstructionsConfigMutation(
|
||||
req,
|
||||
(hireInput.adapterConfig ?? {}) as Record<string, unknown>,
|
||||
rawHireAdapterConfig,
|
||||
);
|
||||
assertNoAgentAdapterConfigMutation(req, rawHireAdapterConfig);
|
||||
assertNoAgentRuntimeConfigAdapterConfigMutation(req, hireInput.runtimeConfig);
|
||||
const requestedAdapterConfig = applyCreateDefaultsByAdapterType(
|
||||
hireInput.adapterType,
|
||||
((hireInput.adapterConfig ?? {}) as Record<string, unknown>),
|
||||
rawHireAdapterConfig,
|
||||
);
|
||||
const desiredSkillAssignment = await resolveDesiredSkillAssignment(
|
||||
companyId,
|
||||
|
|
@ -1646,20 +1762,21 @@ export function agentRoutes(
|
|||
requestedAdapterConfig,
|
||||
Array.isArray(requestedDesiredSkills) ? requestedDesiredSkills : undefined,
|
||||
);
|
||||
const normalizedAdapterConfig = await secretsSvc.normalizeAdapterConfigForPersistence(
|
||||
const normalizedAdapterConfig = await normalizeMediatedAdapterConfigForPersistence({
|
||||
companyId,
|
||||
desiredSkillAssignment.adapterConfig,
|
||||
{ strictMode: strictSecretsMode },
|
||||
);
|
||||
await assertAdapterConfigConstraints(
|
||||
adapterType: hireInput.adapterType,
|
||||
adapterConfig: desiredSkillAssignment.adapterConfig,
|
||||
});
|
||||
const normalizedRuntimeConfig = await normalizeRuntimeConfigAdapterConfigsForPersistence(
|
||||
companyId,
|
||||
hireInput.adapterType,
|
||||
normalizeNewAgentRuntimeConfig(hireInput.runtimeConfig),
|
||||
normalizedAdapterConfig,
|
||||
);
|
||||
const normalizedHireInput = {
|
||||
...hireInput,
|
||||
adapterConfig: normalizedAdapterConfig,
|
||||
runtimeConfig: normalizeNewAgentRuntimeConfig(hireInput.runtimeConfig),
|
||||
runtimeConfig: normalizedRuntimeConfig,
|
||||
};
|
||||
|
||||
const company = await db
|
||||
|
|
@ -1814,21 +1931,16 @@ export function agentRoutes(
|
|||
...createInput
|
||||
} = req.body;
|
||||
createInput.adapterType = assertKnownAdapterType(createInput.adapterType);
|
||||
const rawCreateAdapterConfig = (createInput.adapterConfig ?? {}) as Record<string, unknown>;
|
||||
assertNoNewAgentLegacyPromptTemplate(
|
||||
createInput.adapterType,
|
||||
(createInput.adapterConfig ?? {}) as Record<string, unknown>,
|
||||
);
|
||||
assertNoAgentHostWorkspaceCommandMutation(
|
||||
req,
|
||||
collectAgentAdapterWorkspaceCommandPaths(createInput.adapterConfig),
|
||||
);
|
||||
assertNoAgentInstructionsConfigMutation(
|
||||
req,
|
||||
(createInput.adapterConfig ?? {}) as Record<string, unknown>,
|
||||
rawCreateAdapterConfig,
|
||||
);
|
||||
assertNoAgentAdapterConfigMutation(req, rawCreateAdapterConfig);
|
||||
assertNoAgentRuntimeConfigAdapterConfigMutation(req, createInput.runtimeConfig);
|
||||
const requestedAdapterConfig = applyCreateDefaultsByAdapterType(
|
||||
createInput.adapterType,
|
||||
((createInput.adapterConfig ?? {}) as Record<string, unknown>),
|
||||
rawCreateAdapterConfig,
|
||||
);
|
||||
const desiredSkillAssignment = await resolveDesiredSkillAssignment(
|
||||
companyId,
|
||||
|
|
@ -1836,14 +1948,15 @@ export function agentRoutes(
|
|||
requestedAdapterConfig,
|
||||
Array.isArray(requestedDesiredSkills) ? requestedDesiredSkills : undefined,
|
||||
);
|
||||
const normalizedAdapterConfig = await secretsSvc.normalizeAdapterConfigForPersistence(
|
||||
const normalizedAdapterConfig = await normalizeMediatedAdapterConfigForPersistence({
|
||||
companyId,
|
||||
desiredSkillAssignment.adapterConfig,
|
||||
{ strictMode: strictSecretsMode },
|
||||
);
|
||||
await assertAdapterConfigConstraints(
|
||||
adapterType: createInput.adapterType,
|
||||
adapterConfig: desiredSkillAssignment.adapterConfig,
|
||||
});
|
||||
const normalizedRuntimeConfig = await normalizeRuntimeConfigAdapterConfigsForPersistence(
|
||||
companyId,
|
||||
createInput.adapterType,
|
||||
normalizeNewAgentRuntimeConfig(createInput.runtimeConfig),
|
||||
normalizedAdapterConfig,
|
||||
);
|
||||
await assertAgentEnvironmentSelection(companyId, createInput.adapterType, createInput.defaultEnvironmentId);
|
||||
|
|
@ -1855,7 +1968,7 @@ export function agentRoutes(
|
|||
const createdAgent = await svc.create(companyId, {
|
||||
...createInput,
|
||||
adapterConfig: normalizedAdapterConfig,
|
||||
runtimeConfig: normalizeNewAgentRuntimeConfig(createInput.runtimeConfig),
|
||||
runtimeConfig: normalizedRuntimeConfig,
|
||||
status: "idle",
|
||||
spentMonthlyCents: 0,
|
||||
lastHeartbeatAt: null,
|
||||
|
|
@ -2230,14 +2343,8 @@ export function agentRoutes(
|
|||
res.status(422).json({ error: "adapterConfig must be an object" });
|
||||
return;
|
||||
}
|
||||
assertNoAgentInstructionsConfigMutation(req, adapterConfig);
|
||||
assertNoAgentHostWorkspaceCommandMutation(
|
||||
req,
|
||||
collectAgentAdapterWorkspaceCommandPaths(adapterConfig),
|
||||
);
|
||||
const changingInstructionsConfig = Object.keys(adapterConfig).some((key) =>
|
||||
KNOWN_INSTRUCTIONS_BUNDLE_KEYS.includes(key as (typeof KNOWN_INSTRUCTIONS_BUNDLE_KEYS)[number]),
|
||||
);
|
||||
assertNoAgentAdapterConfigMutation(req, adapterConfig);
|
||||
const changingInstructionsConfig = adapterConfigTouchesInstructionsConfig(adapterConfig);
|
||||
if (changingInstructionsConfig) {
|
||||
await assertCanManageInstructionsPath(req, existing);
|
||||
}
|
||||
|
|
@ -2247,6 +2354,16 @@ export function agentRoutes(
|
|||
const requestedAdapterType = hasOwn(patchData, "adapterType")
|
||||
? assertKnownAdapterType(patchData.adapterType as string | null | undefined)
|
||||
: existing.adapterType;
|
||||
let requestedRuntimeConfig: Record<string, unknown> | null = null;
|
||||
if (hasOwn(patchData, "runtimeConfig")) {
|
||||
const runtimeConfig = asRecord(patchData.runtimeConfig);
|
||||
if (!runtimeConfig) {
|
||||
res.status(422).json({ error: "runtimeConfig must be an object" });
|
||||
return;
|
||||
}
|
||||
assertNoAgentRuntimeConfigAdapterConfigMutation(req, runtimeConfig);
|
||||
requestedRuntimeConfig = runtimeConfig;
|
||||
}
|
||||
const touchesAdapterConfiguration =
|
||||
hasOwn(patchData, "adapterType") ||
|
||||
hasOwn(patchData, "adapterConfig");
|
||||
|
|
@ -2292,19 +2409,20 @@ export function agentRoutes(
|
|||
requestedAdapterType,
|
||||
rawEffectiveAdapterConfig,
|
||||
);
|
||||
const normalizedEffectiveAdapterConfig = await secretsSvc.normalizeAdapterConfigForPersistence(
|
||||
existing.companyId,
|
||||
effectiveAdapterConfig,
|
||||
{ strictMode: strictSecretsMode },
|
||||
);
|
||||
const normalizedEffectiveAdapterConfig = await normalizeMediatedAdapterConfigForPersistence({
|
||||
companyId: existing.companyId,
|
||||
adapterType: requestedAdapterType,
|
||||
adapterConfig: effectiveAdapterConfig,
|
||||
});
|
||||
patchData.adapterConfig = syncInstructionsBundleConfigFromFilePath(existing, normalizedEffectiveAdapterConfig);
|
||||
}
|
||||
if (touchesAdapterConfiguration && requestedAdapterType === "opencode_local") {
|
||||
const effectiveAdapterConfig = asRecord(patchData.adapterConfig) ?? {};
|
||||
await assertAdapterConfigConstraints(
|
||||
if (requestedRuntimeConfig) {
|
||||
const baseAdapterConfig = asRecord(patchData.adapterConfig) ?? asRecord(existing.adapterConfig) ?? {};
|
||||
patchData.runtimeConfig = await normalizeRuntimeConfigAdapterConfigsForPersistence(
|
||||
existing.companyId,
|
||||
requestedAdapterType,
|
||||
effectiveAdapterConfig,
|
||||
requestedRuntimeConfig,
|
||||
baseAdapterConfig,
|
||||
);
|
||||
}
|
||||
if (touchesAdapterConfiguration || Object.prototype.hasOwnProperty.call(patchData, "defaultEnvironmentId")) {
|
||||
|
|
|
|||
|
|
@ -47,11 +47,14 @@ export function assertNoAgentHostWorkspaceCommandMutation(req: Request, paths: s
|
|||
);
|
||||
}
|
||||
|
||||
export function collectAgentAdapterWorkspaceCommandPaths(adapterConfig: unknown): string[] {
|
||||
export function collectAgentAdapterWorkspaceCommandPaths(
|
||||
adapterConfig: unknown,
|
||||
prefix = "adapterConfig",
|
||||
): string[] {
|
||||
if (!isRecord(adapterConfig)) return [];
|
||||
return collectWorkspaceStrategyCommandPaths(
|
||||
adapterConfig.workspaceStrategy,
|
||||
"adapterConfig.workspaceStrategy",
|
||||
`${prefix}.workspaceStrategy`,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -8,11 +8,13 @@ import type { Db } from "@paperclipai/db";
|
|||
import {
|
||||
AGENT_DEFAULT_MAX_CONCURRENT_RUNS,
|
||||
ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY,
|
||||
MODEL_PROFILE_KEYS,
|
||||
isEnvironmentDriverSupportedForAdapter,
|
||||
type BillingType,
|
||||
type EnvironmentLeaseStatus,
|
||||
type ExecutionWorkspace,
|
||||
type ExecutionWorkspaceConfig,
|
||||
type ModelProfileKey,
|
||||
type RunLivenessState,
|
||||
} from "@paperclipai/shared";
|
||||
import {
|
||||
|
|
@ -38,8 +40,14 @@ import { conflict, HttpError, notFound } from "../errors.js";
|
|||
import { logger } from "../middleware/logger.js";
|
||||
import { publishLiveEvent } from "./live-events.js";
|
||||
import { getRunLogStore, type RunLogHandle } from "./run-log-store.js";
|
||||
import { getServerAdapter, runningProcesses } from "../adapters/index.js";
|
||||
import type { AdapterExecutionResult, AdapterInvocationMeta, AdapterSessionCodec, UsageSummary } from "../adapters/index.js";
|
||||
import { getServerAdapter, listAdapterModelProfiles, runningProcesses } from "../adapters/index.js";
|
||||
import type {
|
||||
AdapterExecutionResult,
|
||||
AdapterInvocationMeta,
|
||||
AdapterModelProfileDefinition,
|
||||
AdapterSessionCodec,
|
||||
UsageSummary,
|
||||
} from "../adapters/index.js";
|
||||
import { createLocalAgentJwt } from "../agent-auth-jwt.js";
|
||||
import { parseObject, asBoolean, asNumber, appendWithByteCap, MAX_EXCERPT_BYTES } from "../adapters/utils.js";
|
||||
import { costService } from "./costs.js";
|
||||
|
|
@ -879,10 +887,23 @@ type SessionCompactionDecision = {
|
|||
};
|
||||
|
||||
interface ParsedIssueAssigneeAdapterOverrides {
|
||||
modelProfile: ModelProfileKey | null;
|
||||
adapterConfig: Record<string, unknown> | null;
|
||||
useProjectWorkspace: boolean | null;
|
||||
}
|
||||
|
||||
type ModelProfileRequestSource = "issue_override" | "wake_context";
|
||||
type AppliedModelProfileConfigSource = "agent_runtime" | "adapter_default";
|
||||
|
||||
export interface ModelProfileApplication {
|
||||
requested: ModelProfileKey | null;
|
||||
requestedBy: ModelProfileRequestSource | null;
|
||||
applied: ModelProfileKey | null;
|
||||
configSource: AppliedModelProfileConfigSource | null;
|
||||
fallbackReason: string | null;
|
||||
adapterConfig: Record<string, unknown> | null;
|
||||
}
|
||||
|
||||
export type ResolvedWorkspaceForRun = {
|
||||
cwd: string;
|
||||
source: "project_primary" | "task_session" | "agent_home";
|
||||
|
|
@ -917,6 +938,147 @@ function readNonEmptyString(value: unknown): string | null {
|
|||
return typeof value === "string" && value.trim().length > 0 ? value : null;
|
||||
}
|
||||
|
||||
function readModelProfileKey(value: unknown): ModelProfileKey | null {
|
||||
return MODEL_PROFILE_KEYS.includes(value as ModelProfileKey)
|
||||
? (value as ModelProfileKey)
|
||||
: null;
|
||||
}
|
||||
|
||||
function readContextModelProfile(
|
||||
contextSnapshot: Record<string, unknown> | null | undefined,
|
||||
): ModelProfileKey | null {
|
||||
return readModelProfileKey(contextSnapshot?.modelProfile);
|
||||
}
|
||||
|
||||
export function normalizeModelProfileWakeContext(input: {
|
||||
contextSnapshot: Record<string, unknown>;
|
||||
payload: Record<string, unknown> | null | undefined;
|
||||
}): Record<string, unknown> {
|
||||
const modelProfileFromPayload = readModelProfileKey(input.payload?.modelProfile);
|
||||
if (!readContextModelProfile(input.contextSnapshot) && modelProfileFromPayload) {
|
||||
input.contextSnapshot.modelProfile = modelProfileFromPayload;
|
||||
}
|
||||
return input.contextSnapshot;
|
||||
}
|
||||
|
||||
function readAgentRuntimeModelProfile(
|
||||
runtimeConfig: unknown,
|
||||
key: ModelProfileKey,
|
||||
): { enabled: boolean; adapterConfig: Record<string, unknown>; configured: boolean } {
|
||||
const modelProfiles = parseObject(parseObject(runtimeConfig).modelProfiles);
|
||||
const profile = parseObject(modelProfiles[key]);
|
||||
if (Object.keys(profile).length === 0) {
|
||||
return { enabled: true, adapterConfig: {}, configured: false };
|
||||
}
|
||||
|
||||
return {
|
||||
enabled: profile.enabled !== false,
|
||||
adapterConfig: parseObject(profile.adapterConfig),
|
||||
configured: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveModelProfileApplication(input: {
|
||||
adapterModelProfiles: AdapterModelProfileDefinition[];
|
||||
agentRuntimeConfig: unknown;
|
||||
issueModelProfile: ModelProfileKey | null | undefined;
|
||||
contextSnapshot: Record<string, unknown> | null | undefined;
|
||||
profileResolutionFallbackReason?: string | null;
|
||||
}): ModelProfileApplication {
|
||||
const issueModelProfile = input.issueModelProfile ?? null;
|
||||
const contextModelProfile = readContextModelProfile(input.contextSnapshot);
|
||||
const requested = issueModelProfile ?? contextModelProfile;
|
||||
const requestedBy: ModelProfileRequestSource | null = issueModelProfile
|
||||
? "issue_override"
|
||||
: contextModelProfile
|
||||
? "wake_context"
|
||||
: null;
|
||||
|
||||
if (!requested) {
|
||||
return {
|
||||
requested: null,
|
||||
requestedBy: null,
|
||||
applied: null,
|
||||
configSource: null,
|
||||
fallbackReason: null,
|
||||
adapterConfig: null,
|
||||
};
|
||||
}
|
||||
|
||||
const adapterProfile = input.adapterModelProfiles.find((profile) => profile.key === requested) ?? null;
|
||||
if (!adapterProfile) {
|
||||
return {
|
||||
requested,
|
||||
requestedBy,
|
||||
applied: null,
|
||||
configSource: null,
|
||||
fallbackReason: input.profileResolutionFallbackReason ?? "adapter_profile_not_supported",
|
||||
adapterConfig: null,
|
||||
};
|
||||
}
|
||||
|
||||
const runtimeProfile = readAgentRuntimeModelProfile(input.agentRuntimeConfig, requested);
|
||||
if (!runtimeProfile.enabled) {
|
||||
return {
|
||||
requested,
|
||||
requestedBy,
|
||||
applied: null,
|
||||
configSource: null,
|
||||
fallbackReason: "agent_runtime_profile_disabled",
|
||||
adapterConfig: null,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
requested,
|
||||
requestedBy,
|
||||
applied: requested,
|
||||
configSource: runtimeProfile.configured ? "agent_runtime" : "adapter_default",
|
||||
fallbackReason: null,
|
||||
adapterConfig: {
|
||||
...parseObject(adapterProfile.adapterConfig),
|
||||
...runtimeProfile.adapterConfig,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function mergeModelProfileAdapterConfig(input: {
|
||||
baseConfig: Record<string, unknown>;
|
||||
modelProfile: ModelProfileApplication;
|
||||
issueAdapterConfig: Record<string, unknown> | null | undefined;
|
||||
}): Record<string, unknown> {
|
||||
return {
|
||||
...input.baseConfig,
|
||||
...(input.modelProfile.adapterConfig ?? {}),
|
||||
...(input.issueAdapterConfig ?? {}),
|
||||
};
|
||||
}
|
||||
|
||||
function modelProfileRunMetadata(
|
||||
modelProfile: ModelProfileApplication,
|
||||
): Record<string, unknown> | null {
|
||||
if (!modelProfile.requested) return null;
|
||||
return {
|
||||
requested: modelProfile.requested,
|
||||
requestedBy: modelProfile.requestedBy,
|
||||
applied: modelProfile.applied,
|
||||
configSource: modelProfile.configSource,
|
||||
fallbackReason: modelProfile.fallbackReason,
|
||||
};
|
||||
}
|
||||
|
||||
function mergeModelProfileRunMetadata(
|
||||
resultJson: Record<string, unknown> | null,
|
||||
modelProfile: ModelProfileApplication,
|
||||
): Record<string, unknown> | null {
|
||||
const metadata = modelProfileRunMetadata(modelProfile);
|
||||
if (!metadata) return resultJson;
|
||||
return {
|
||||
...(resultJson ?? {}),
|
||||
modelProfile: metadata,
|
||||
};
|
||||
}
|
||||
|
||||
export function summarizeHeartbeatRunContextSnapshot(
|
||||
contextSnapshot: Record<string, unknown> | null | undefined,
|
||||
): Record<string, unknown> | null {
|
||||
|
|
@ -930,6 +1092,7 @@ export function summarizeHeartbeatRunContextSnapshot(
|
|||
"wakeReason",
|
||||
"wakeSource",
|
||||
"wakeTriggerDetail",
|
||||
"modelProfile",
|
||||
] as const;
|
||||
|
||||
for (const key of allowedKeys) {
|
||||
|
|
@ -1259,6 +1422,9 @@ function parseIssueAssigneeAdapterOverrides(
|
|||
raw: unknown,
|
||||
): ParsedIssueAssigneeAdapterOverrides | null {
|
||||
const parsed = parseObject(raw);
|
||||
const modelProfile = MODEL_PROFILE_KEYS.includes(parsed.modelProfile as ModelProfileKey)
|
||||
? parsed.modelProfile as ModelProfileKey
|
||||
: null;
|
||||
const parsedAdapterConfig = parseObject(parsed.adapterConfig);
|
||||
const adapterConfig =
|
||||
Object.keys(parsedAdapterConfig).length > 0 ? parsedAdapterConfig : null;
|
||||
|
|
@ -1266,8 +1432,9 @@ function parseIssueAssigneeAdapterOverrides(
|
|||
typeof parsed.useProjectWorkspace === "boolean"
|
||||
? parsed.useProjectWorkspace
|
||||
: null;
|
||||
if (!adapterConfig && useProjectWorkspace === null) return null;
|
||||
if (!modelProfile && !adapterConfig && useProjectWorkspace === null) return null;
|
||||
return {
|
||||
modelProfile,
|
||||
adapterConfig,
|
||||
useProjectWorkspace,
|
||||
};
|
||||
|
|
@ -1551,6 +1718,7 @@ function enrichWakeContextSnapshot(input: {
|
|||
if (!readNonEmptyString(contextSnapshot["wakeTriggerDetail"]) && triggerDetail) {
|
||||
contextSnapshot.wakeTriggerDetail = triggerDetail;
|
||||
}
|
||||
normalizeModelProfileWakeContext({ contextSnapshot, payload });
|
||||
|
||||
return {
|
||||
contextSnapshot,
|
||||
|
|
@ -4964,9 +5132,42 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
|
|||
workspaceConfig: existingExecutionWorkspace?.config ?? null,
|
||||
mode: effectiveExecutionWorkspaceMode,
|
||||
});
|
||||
const mergedConfig = issueAssigneeOverrides?.adapterConfig
|
||||
? { ...persistedWorkspaceManagedConfig, ...issueAssigneeOverrides.adapterConfig }
|
||||
: persistedWorkspaceManagedConfig;
|
||||
let adapterModelProfiles: AdapterModelProfileDefinition[] = [];
|
||||
let profileResolutionFallbackReason: string | null = null;
|
||||
try {
|
||||
adapterModelProfiles = await listAdapterModelProfiles(agent.adapterType);
|
||||
} catch (error) {
|
||||
profileResolutionFallbackReason = "adapter_profile_resolution_failed";
|
||||
logger.warn(
|
||||
{
|
||||
err: error,
|
||||
companyId: agent.companyId,
|
||||
agentId: agent.id,
|
||||
adapterType: agent.adapterType,
|
||||
runId: run.id,
|
||||
},
|
||||
"Failed to resolve adapter model profiles; falling back to primary adapter config",
|
||||
);
|
||||
}
|
||||
const modelProfileApplication = resolveModelProfileApplication({
|
||||
adapterModelProfiles,
|
||||
agentRuntimeConfig: agent.runtimeConfig,
|
||||
issueModelProfile: issueAssigneeOverrides?.modelProfile ?? null,
|
||||
contextSnapshot: context,
|
||||
profileResolutionFallbackReason,
|
||||
});
|
||||
const modelProfileMetadata = modelProfileRunMetadata(modelProfileApplication);
|
||||
if (modelProfileMetadata) {
|
||||
context.paperclipModelProfile = modelProfileMetadata;
|
||||
if (modelProfileApplication.requested) context.modelProfile = modelProfileApplication.requested;
|
||||
} else {
|
||||
delete context.paperclipModelProfile;
|
||||
}
|
||||
const mergedConfig = mergeModelProfileAdapterConfig({
|
||||
baseConfig: persistedWorkspaceManagedConfig,
|
||||
modelProfile: modelProfileApplication,
|
||||
issueAdapterConfig: issueAssigneeOverrides?.adapterConfig ?? null,
|
||||
});
|
||||
const configSnapshot = buildExecutionWorkspaceConfigSnapshot(mergedConfig, selectedEnvironmentId);
|
||||
const executionRunConfig = stripWorkspaceRuntimeFromExecutionRunConfig(mergedConfig);
|
||||
const { resolvedConfig, secretKeys } = await resolveExecutionRunAdapterConfig({
|
||||
|
|
@ -5527,12 +5728,16 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
|
|||
if (key in meta.env) meta.env[key] = "***REDACTED***";
|
||||
}
|
||||
}
|
||||
const modelProfileMetadata = modelProfileRunMetadata(modelProfileApplication);
|
||||
await appendRunEvent(currentRun, seq++, {
|
||||
eventType: "adapter.invoke",
|
||||
stream: "system",
|
||||
level: "info",
|
||||
message: "adapter invocation",
|
||||
payload: meta as unknown as Record<string, unknown>,
|
||||
payload: {
|
||||
...(meta as unknown as Record<string, unknown>),
|
||||
...(modelProfileMetadata ? { modelProfile: modelProfileMetadata } : {}),
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
|
|
@ -5715,11 +5920,14 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
|
|||
|
||||
const persistedResultJson = mergeHeartbeatRunResultJson(
|
||||
mergeRunStopMetadataForAgent(agent, outcome, {
|
||||
resultJson: mergeAdapterRecoveryMetadata({
|
||||
resultJson: adapterResult.resultJson ?? null,
|
||||
errorFamily: adapterResult.errorFamily ?? null,
|
||||
retryNotBefore: adapterResult.retryNotBefore ?? null,
|
||||
}),
|
||||
resultJson: mergeModelProfileRunMetadata(
|
||||
mergeAdapterRecoveryMetadata({
|
||||
resultJson: adapterResult.resultJson ?? null,
|
||||
errorFamily: adapterResult.errorFamily ?? null,
|
||||
retryNotBefore: adapterResult.retryNotBefore ?? null,
|
||||
}),
|
||||
modelProfileApplication,
|
||||
),
|
||||
errorCode: runErrorCode,
|
||||
errorMessage: runErrorMessage,
|
||||
}),
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue