Skip to content

An open-source, faster Devin alternative

TypeScript

feat(managed-agents): speak model protocol 5 to a host that says 5 (#1046)

opencomputer-app[bot]7da77ad773dd
diff --git a/services/managed-agents/src/computer/durable-object.ts b/services/managed-agents/src/computer/durable-object.ts
index dbc3223d..2200e48f 100644
--- a/services/managed-agents/src/computer/durable-object.ts
+++ b/services/managed-agents/src/computer/durable-object.ts
@@ -89,14 +89,14 @@ import {
sizeFor,
sizeShape,
} from "./config.js";
-import { computerHarnesses, takeHarnessPrefix } from "./harnesses.js";
+import { DEFAULT_HARNESS, computerHarnesses, harnessOnProfile, helloProfiles, profileHarnesses, takeHarnessPrefix } from "./harnesses.js";
import { type SealPurpose, seal, sha256Hex, unseal } from "./crypto.js";
import { type DiskReport, diskDecision } from "./disk-growth.js";
import { type Linked, LINK_TIMEOUT_MS, ThreadAccess, findThreadLinks, forwardedLinked, threadRefFor } from "./threads.js";
import { type ComputerInstallation, type ComputerRepository, selectTokenTarget, workspaceDefinition } from "./github.js";
import { hostToken } from "./host-token.js";
import { type AdoptedComputer, ComputerLifecycle, type ComputerState, type LifecycleReply } from "./lifecycle.js";
-import { MANAGED_MODEL_PROVIDER, modelCredentials, requestManagedModelKey } from "./model-key.js";
+import { MANAGED_MODEL_PROVIDER, type ModelCredentials, managedModelRoute, modelCredentials, requestManagedModelKey } from "./model-key.js";
import { mintOpenComputerKey } from "./opencomputer-key.js";
import { type AutomationRepositoryEnv, automationRepositoryCredential } from "../edge/automation-repository.js";
import { daysUnpaid, idleParkMs, parkingDecision, unpaidStage, unpaidWarning, unpaidWarningGiven } from "./parking.js";
@@ -109,6 +109,7 @@ import { type ApiCaller, type ApiOp, type ApiReply, ComputerSessionsApi } from "
import type { PreviewComputerState } from "../previews/worker.js";
import {
CALVIN_API_PROTOCOL,
+ CALVIN_MODEL_PROTOCOL,
CALVIN_PROTOCOL_VERSION,
type CalvinGatewayToHost,
type CalvinTraceContext,
@@ -126,6 +127,8 @@ import {
type CalvinReadThreadRequest,
type CalvinSpawnRequest,
type CalvinSpawnResult,
+ type ModelProfile,
+ type ModelRoute,
type SecretRequest,
type SessionSecret,
type WorkspaceDefinition,
@@ -543,8 +546,9 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
accountId: () => this.accountId(),
teamId: () => this.setting("slackTeamId") ?? "",
slack: (method, body) => this.slack(method, body),
- harnesses: () => computerHarnesses(this.hostFeatures()),
+ harnesses: () => this.harnesses(),
host: () => this.liveHost(),
+ managedRoute: async () => (await this.managedModel((await this.organizationModelKey()).key)).route,
send: (frame) => this.send(frame),
schedule: (purpose) => this.purposeScheduler(purpose),
liveSessions: () => this.liveSessions(),
@@ -724,30 +728,77 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
return this.keptHostFeatures() ?? this.liveHost()?.features;
}
+ /**
+ * The profiles a host at protocol 5 listed in its hello (work 097), kept as
+ * its features are and read once per object. A hello without any (its model
+ * proxy is down) leaves them; a hello below 5 forgets them.
+ */
+ private keptProfiles?: { value: ModelProfile[] | undefined };
+ private keptHostProfiles(): ModelProfile[] | undefined {
+ if (this.keptProfiles) return this.keptProfiles.value;
+ let value: ModelProfile[] | undefined;
+ try {
+ value = helloProfiles(JSON.parse(this.setting("hostProfiles") ?? "null"));
+ } catch {
+ // Unreadable: as if never recorded.
+ }
+ this.keptProfiles = { value };
+ return value;
+ }
+
+ private recordHostProfiles(profiles: ModelProfile[] | undefined): void {
+ if (JSON.stringify(profiles) === JSON.stringify(this.keptHostProfiles())) return;
+ if (profiles) this.put("hostProfiles", JSON.stringify(profiles));
+ else this.remove("hostProfiles");
+ this.keptProfiles = { value: profiles };
+ console.log(JSON.stringify({ level: "info", event: "computer.host_profiles_changed", profiles: profiles?.map((p) => p.name) ?? null }));
+ }
+
+ /** The harnesses this computer can run (harnesses.ts): by its host's profiles once it has listed them, by its features until then. */
+ private harnesses(): CalvinHarness[] {
+ const profiles = this.keptHostProfiles();
+ return profiles ? profileHarnesses(profiles) : computerHarnesses(this.hostFeatures());
+ }
+
/** Work 084 rollout gate: whether this organization's host is spoken to at v4 (api-gate.ts). */
private apiEnabled(): boolean {
return computerApiEnabled(this.env.COMPUTER_API_ORGS, this.setting("accountId"));
}
- /** The protocol every `welcome` says: ours, or v3 for an organization the gate holds back. */
+ /**
+ * Whether a host that said `protocol` (the connected one's, by default) is
+ * spoken to at protocol 5 (work 097): the one test in this object that
+ * tells the two protocols apart, made on the host's hello and nothing else.
+ * It and what it guards go when no host says 4.
+ */
+ private speaksProfiles(protocol = this.liveHost()?.protocol ?? 0): boolean {
+ return protocol >= CALVIN_MODEL_PROTOCOL;
+ }
+
+ /** The protocol every `welcome` says: ours (5 to a host that said 5), or v3 for an organization the gate holds back. */
private welcomeProtocol(): number {
- return this.apiEnabled() ? CALVIN_PROTOCOL_VERSION : GATED_PROTOCOL;
+ if (!this.apiEnabled()) return GATED_PROTOCOL;
+ return this.speaksProfiles() ? CALVIN_MODEL_PROTOCOL : CALVIN_PROTOCOL_VERSION;
}
- /** The connected host's hello `protocol` (at most v3 when gated off, recorded at its hello) and `features`; undefined when none is connected. */
- private liveHost(): { protocol: number; features: string[] } | undefined {
+ /**
+ * The connected host's hello `protocol` (at most v3 when gated off, recorded at its hello) and `features`, and
+ * the `profiles` kept from a hello at protocol 5; undefined when none is connected.
+ */
+ private liveHost(): { protocol: number; features: string[]; profiles?: ModelProfile[] } | undefined {
const socket = this.socket();
if (!socket) return undefined;
+ const profiles = this.keptHostProfiles();
try {
const a = socket.deserializeAttachment() as HostAttachment | null;
- return { protocol: a?.protocol ?? 1, features: a?.features ?? [] };
+ return { protocol: a?.protocol ?? 1, features: a?.features ?? [], ...(profiles ? { profiles } : {}) };
} catch {
return { protocol: 1, features: [] };
}
}
/** The host the sessions API sees: below protocol 4 until its welcome is sent (review r3 P2). */
- private apiHost(): { protocol: number; features: string[] } | undefined {
+ private apiHost(): { protocol: number; features: string[]; profiles?: ModelProfile[] } | undefined {
const socket = this.socket();
if (!socket) return undefined;
let welcomed = true;
@@ -1748,7 +1799,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
"slackBotToken",
await seal(link.botToken, this.env.BLUE_CHANNEL_ENCRYPTION_KEY, "slack-bot-token", `${accountId}\0${link.teamId}`),
);
- this.send({ t: "credentials", credentials: await this.credentials() });
+ this.send({ t: "credentials", ...(await this.hostCredentials()) });
// Work 081: the installer's token from the dashboard moves to their Slack id (never throws).
if (link.installerUserId && link.dashboardUserId) await this.access.agents.rekey(link.dashboardUserId, link.installerUserId);
return { previousTeamId: previous && previous !== link.teamId ? previous : null };
@@ -1766,7 +1817,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
this.ctx.storage.sql.exec("DELETE FROM join_requests");
// Other threads' text read for that workspace goes with it.
this.ctx.storage.sql.exec("UPDATE dispatches SET payload = json_remove(payload, '$.linked') WHERE json_extract(payload, '$.linked') IS NOT NULL");
- this.send({ t: "credentials", credentials: await this.credentials() });
+ this.send({ t: "credentials", ...(await this.hostCredentials()) });
return { teamId };
}
@@ -2708,7 +2759,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
this.send({
t: "welcome",
protocol: this.welcomeProtocol(),
- credentials: await this.credentials(),
+ ...(await this.hostCredentials()),
people: this.people(),
definition,
...preview,
@@ -2868,6 +2919,10 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
...(stored?.forkPath ? { forkPath: stored.forkPath } : {}),
// Work 082: a ChatGPT route runs Codex (only ever sent to a host at protocol 3 with the feature).
...(model.mode === "subscription" && model.provider === "chatgpt" ? { harness: "codex" as const } : {}),
+ // Protocol 5: a session runs Codex when it asked to and its route's profile serves Codex.
+ ...(model.mode === "profile" && harnessOnProfile(this.liveHost()?.profiles, model.profile, this.access.models.harness(row.key)) === "codex"
+ ? { harness: "codex" as const }
+ : {}),
},
msg: {
userId: dispatch.userId,
@@ -2879,7 +2934,8 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
},
credentials,
secrets,
- ...(model.mode === "subscription" ? { model } : {}),
+ // `managed` is the absence of a route: the host uses `credentials` (protocol 4) or `models` (5). Every other route is sent.
+ ...(model.mode === "managed" ? {} : { model }),
...(api ? { epoch: api.epoch, lastSeq: api.lastSeq } : {}),
...this.telemetry.sentTrace(dispatch),
};
@@ -2915,8 +2971,8 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
} catch {
return;
}
- // A pool computer runs no sessions: only its hello, and answers to its own token checks (work 081).
- if (event.t !== "hello" && event.t !== "probed" && isPoolId(this.setting("accountId") ?? "")) return;
+ // A pool computer runs no sessions: only its hello, and answers to its own token checks (work 081; `model-response` at protocol 5).
+ if (event.t !== "hello" && event.t !== "probed" && event.t !== "model-response" && isPoolId(this.setting("accountId") ?? "")) return;
switch (event.t) {
case "hello":
return this.hello(ws, event);
@@ -2983,7 +3039,12 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
case "probed":
return this.access.models.probed(event.id, event.result, event.error);
case "model-bound":
- return this.access.models.bound(event.sessionKey, event.mode, event.fingerprint);
+ return this.access.models.bound(event.sessionKey, event.mode, event.key ?? event.fingerprint, event.profile);
+ // Work 097, protocol 5: what an upstream answered on a session's credential, and the answer to a `model-request`.
+ case "model-observed":
+ return this.access.models.observed?.(event);
+ case "model-response":
+ return this.access.models.responded?.(event);
case "model-health":
return this.access.models.health(event);
case "model-denied":
@@ -3059,6 +3120,10 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
} satisfies HostAttachment);
// A pool slot's hello isn't the organization's computer's: its own hello as the organization comes after the claim.
if (!isPoolId(this.setting("accountId") ?? "")) this.recordHostFeatures(features ?? []);
+ // Work 097: a host at protocol 5 lists its model proxy's profiles; without them (the proxy is down) the last list stands.
+ const profiles = helloProfiles(event.profiles);
+ if (!this.speaksProfiles(protocol)) this.recordHostProfiles(undefined);
+ else if (profiles) this.recordHostProfiles(profiles);
this.telemetry.connected(event.version, previous);
if ((event.protocol ?? 1) < CALVIN_PROTOCOL_VERSION) {
// Expected of every host until calvin #129 ships protocol 3: a note, not a warning.
@@ -3082,7 +3147,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
JSON.stringify({
t: "welcome",
protocol: this.welcomeProtocol(),
- credentials: await this.credentials(),
+ ...(await this.hostCredentials()),
people: this.people(),
...(definition ? { definition } : {}),
...(await this.telemetry.credential(event.hostId)),
@@ -3331,23 +3396,33 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
return true;
}
- /** The host's credentials; `credentials.resolved` on `t` (or its own emitter), with where the model key came from. */
+ /** The host's credentials, as a `deliver` carries them. */
private async credentials(telemetry?: GatewayTelemetry): Promise<CalvinHostCredentials> {
+ return (await this.hostCredentials(telemetry)).credentials;
+ }
+
+ /**
+ * What a `welcome` or a `credentials` frame carries: the host's credentials
+ * and, at protocol 5, `models`, the route of a session whose delivery names
+ * none. `credentials.resolved` on `t` (or its own emitter), with where the
+ * model key came from.
+ */
+ private async hostCredentials(telemetry?: GatewayTelemetry): Promise<Pick<Extract<CalvinGatewayToHost, { t: "credentials" }>, "credentials" | "models">> {
return this.telemetry.within(telemetry, async (t) => {
const span = t.start("credentials.resolved");
try {
const teamId = this.setting("slackTeamId");
const { key, source } = await this.organizationModelKey();
- const { credentials: model, fallback } = modelCredentials(key, this.env);
- if (fallback) console.warn(JSON.stringify({ level: "warn", event: "computer.model_key_fallback", accountId: this.setting("accountId") }));
+ const model = await this.managedModel(key);
+ if (model.fallback) console.warn(JSON.stringify({ level: "warn", event: "computer.model_key_fallback", accountId: this.setting("accountId") }));
const credentials = {
slackBotToken: await this.slackBotToken(),
slackBotUserId: this.setting("slackBotUserId") ?? "",
...(teamId ? { teamId } : {}),
- ...model,
+ ...model.credentials,
};
span.end({ outcome: "completed", data: { source } });
- return credentials;
+ return { credentials, ...(model.route.mode === "managed" ? {} : { models: { [DEFAULT_HARNESS]: model.route } }) };
} catch (error) {
span.end({ outcome: "failed", error_type: "unknown" });
throw error;
@@ -3355,6 +3430,17 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
});
}
+ /**
+ * The organization's managed models as the connected host takes them
+ * (model-key.ts). Below protocol 5: the key in the host's credentials, and
+ * the route `managed`. At 5 (work 097): no key in the credentials, and the
+ * profile route that carries it, or a refusal.
+ */
+ private async managedModel(key: string | null): Promise<{ credentials: ModelCredentials; route: ModelRoute; fallback: boolean }> {
+ if (this.speaksProfiles()) return { credentials: {}, ...(await managedModelRoute(key, this.env, this.liveHost()?.profiles)) };
+ return { ...modelCredentials(key, this.env), route: { mode: "managed" } };
+ }
+
/**
* `unseal`, remembered in this object's memory (work 068 §3d): the bot
* token and the model key were decrypted on every flush and every Slack
@@ -3442,7 +3528,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
if (!accountId || isPoolId(accountId)) return;
this.unsealed.clear();
await this.refreshModelKey(accountId);
- this.send({ t: "credentials", credentials: await this.credentials() });
+ this.send({ t: "credentials", ...(await this.hostCredentials()) });
}
private provisionModelKey(accountId: string): void {
@@ -3456,7 +3542,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
return;
}
console.log(JSON.stringify({ level: "info", event: "computer.model_key_provisioned", accountId }));
- this.send({ t: "credentials", credentials: await this.credentials() });
+ this.send({ t: "credentials", ...(await this.hostCredentials()) });
})()
.catch((error: unknown) => console.error(JSON.stringify({ level: "error", event: "computer.model_key_provision_failed", accountId, message: errorText(error) })))
.finally(() => {
diff --git a/services/managed-agents/src/computer/harnesses.ts b/services/managed-agents/src/computer/harnesses.ts
index 515d4fdd..795ab2e8 100644
--- a/services/managed-agents/src/computer/harnesses.ts
+++ b/services/managed-agents/src/computer/harnesses.ts
@@ -13,7 +13,7 @@
// before #272 reads rows by owner alone, so a rollback must find none for a
// harness it does not know.
-import type { CalvinHarness, ModelProvider } from "./protocol.js";
+import type { CalvinHarness, ModelProfile, ModelProvider } from "./protocol.js";
/** The feature a host's hello lists when ChatGPT routes may go to it (with protocol 3). */
export const MODEL_PROXY_CHATGPT_FEATURE = "model-proxy/chatgpt";
@@ -72,6 +72,36 @@ export function computerHarnesses(features: readonly string[] | undefined): Calv
});
}
+// Protocol 5 (work 097): a host's hello lists its model proxy's profiles, and
+// a profile says which harnesses it serves. They replace the features above,
+// which go with protocol 4.
+
+/** The `profiles` of a hello, as far as they are well formed (at most 32); undefined when the hello lists none. */
+export function helloProfiles(value: unknown): ModelProfile[] | undefined {
+ if (!Array.isArray(value)) return undefined;
+ const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
+ return value
+ .filter((p): p is ModelProfile => isRecord(p) && typeof p.name === "string" && Array.isArray(p.vars) && p.vars.every((v) => typeof v === "string") && isRecord(p.harness))
+ .slice(0, 32)
+ .map(({ name, vars, harness }) => ({ name, vars, harness }));
+}
+
+/** The harnesses this computer can run: the default one, and those a profile of the host's latest hello serves. */
+export function profileHarnesses(profiles: readonly ModelProfile[]): CalvinHarness[] {
+ return HARNESSES.filter((h) => h === DEFAULT_HARNESS || profiles.some((p) => h in p.harness));
+}
+
+/**
+ * The harness a session on `profile` runs: the one it wants when the profile
+ * serves it, else one the profile serves (a Codex session on a profile for
+ * Claude Code runs Claude Code). A profile the host did not list: the wanted.
+ */
+export function harnessOnProfile(profiles: readonly ModelProfile[] | undefined, profile: string, wanted: CalvinHarness): CalvinHarness {
+ const serves = profiles?.find((p) => p.name === profile)?.harness;
+ if (!serves || wanted in serves) return wanted;
+ return HARNESSES.find((h) => h in serves) ?? wanted;
+}
+
export const HARNESS_UNAVAILABLE_CODE = "computer_harness_unavailable";
/** The refusal of a connection for a harness this computer cannot run: nothing was written. */
diff --git a/services/managed-agents/src/computer/model-access.ts b/services/managed-agents/src/computer/model-access.ts
index db4f1605..9cdd4e99 100644
--- a/services/managed-agents/src/computer/model-access.ts
+++ b/services/managed-agents/src/computer/model-access.ts
@@ -21,7 +21,7 @@ import { sha256Hex } from "./crypto.js";
import { DEFAULT_HARNESS } from "./harnesses.js";
import { MANAGED_MODEL_NAME } from "./model-key.js";
import type { PoolProbeResult } from "./pool.js";
-import type { CalvinGatewayToHost, CalvinHarness, ModelProvider, ModelRoute, ModelUsage } from "./protocol.js";
+import type { CalvinGatewayToHost, CalvinHarness, ModelObserved, ModelProfile, ModelProvider, ModelResponse, ModelRoute, ModelUsage } from "./protocol.js";
import type { SlackResult } from "./slack.js";
import type { SubscriptionEventName } from "./telemetry/catalog.js";
import type { EventFields } from "./telemetry/emitter.js";
@@ -297,8 +297,13 @@ export interface ModelAccessModels {
emit<N extends SubscriptionEventName>(name: N, fields: EventFields<N>): void;
/** `model-denied` from the host: the seat lacks a model; new threads start on `fallbackTo`. */
denied(owner: string | undefined, fallbackTo: string, provider?: ModelProvider): Promise<void>;
- /** `model-bound` from the host: what the proxy says a session runs on now. */
- bound(sessionKey: string, mode: string, fingerprint: string | undefined): void;
+ /** `model-bound` from the host: what the proxy says a session runs on now. At protocol 5 `fingerprint` is the frame's `key`, and `profile` its profile. */
+ bound(sessionKey: string, mode: string, fingerprint: string | undefined, profile?: string): void;
+ // Protocol 5 (work 097). Optional only while a build may still compose an implementation written for 4.
+ /** `model-observed` from the host: what an upstream answered on a session's credential. */
+ observed?(observed: ModelObserved): Promise<void>;
+ /** `model-response` from the host: the answer to a `model-request` of this implementation's. */
+ responded?(response: ModelResponse): void;
}
/** The person's agent from the dashboard (work 081) and the link between a dashboard user and their Slack identity. */
@@ -366,8 +371,17 @@ export interface ModelAccessDeps {
slack(method: string, body: Record<string, unknown>): Promise<SlackResult>;
/** The harnesses this computer can run (harnesses.ts `computerHarnesses`, from the host's latest recorded hello). */
harnesses: () => readonly CalvinHarness[];
- /** The connected host's hello `protocol` and `features`; undefined when no host is connected. */
- host(): { protocol: number; features: string[] } | undefined;
+ /**
+ * The connected host's hello `protocol` and `features`, and for a host at protocol 5 the `profiles` its
+ * hello listed (undefined there: it never listed any); undefined when no host is connected.
+ */
+ host(): { protocol: number; features: string[]; profiles?: ModelProfile[] } | undefined;
+ /**
+ * The organization's managed models as a route the connected host takes: `managed` below protocol 5; at 5
+ * the profile route with the organization's key (model-key.ts `managedModelRoute`), which the host also has
+ * as `models`. For a session that must be told so, having been sent another route.
+ */
+ managedRoute(): Promise<ModelRoute>;
/** A frame to the host; false when none is connected. */
send(frame: CalvinGatewayToHost): boolean;
/** The object's alarm for one purpose: `at` arms it, null disarms it. */
@@ -440,6 +454,8 @@ export function noModelAccess(deps?: Pick<ModelAccessDeps, "harnesses">): ModelA
emit: () => undefined,
denied: async () => undefined,
bound: () => undefined,
+ observed: async () => undefined,
+ responded: () => undefined,
},
agents: {
view,
diff --git a/services/managed-agents/src/computer/model-key.ts b/services/managed-agents/src/computer/model-key.ts
index f1cada8e..a81657a2 100644
--- a/services/managed-agents/src/computer/model-key.ts
+++ b/services/managed-agents/src/computer/model-key.ts
@@ -23,9 +23,16 @@
// shared COMPUTER_ANTHROPIC_API_KEY and logs `computer.model_key_fallback`.
// Key values are never logged. A subscription seat is never shared this way:
// the shared Claude OAuth token fallback went in work 097.
+//
+// Protocol 5 (work 097, design C2 and C8): the key no longer travels in the
+// host's credentials. It is a variable of a model route, `managedModelRoute`:
+// profile `openrouter` for the organization's key, `anthropic-key` for the
+// shared one; the host's model proxy holds the value and the runner never
+// sees it. `modelCredentials` is protocol 4's and goes with it.
import { hmacSha256Hex } from "../edge/runtime-usage.js";
-import type { CalvinHostCredentials } from "./protocol.js";
+import { sha256Hex } from "./crypto.js";
+import type { CalvinHostCredentials, ModelProfile, ModelRoute } from "./protocol.js";
export const MANAGED_MODEL_PROVIDER = "openrouter";
/**
@@ -55,6 +62,46 @@ export function modelCredentials(organizationKey: string | null, env: SharedMode
return { credentials: {}, fallback: true };
}
+/** The profile that spends the organization's key, and the one that spends the shared key (the proxy's default profiles). */
+export const MANAGED_MODEL_PROFILE = "openrouter";
+export const SHARED_KEY_PROFILE = "anthropic-key";
+
+/** What a thread hears when its computer has no managed credential at all; the host says the same of a session with no route. */
+export const NO_MODEL_CREDENTIAL = "No model credential is configured for this computer.";
+
+/**
+ * A credential's `key` when its author has no better name (design C2): the
+ * first 16 hex digits of sha256 over the profile, then every variable as
+ * `name=value` in name order, joined by NUL. It names the credential without
+ * revealing it, for high-entropy values only.
+ */
+export async function modelKey(profile: string, vars: Record<string, string>): Promise<string> {
+ const names = Object.keys(vars).sort();
+ return (await sha256Hex([profile, ...names.map((name) => `${name}=${vars[name]}`)].join("\0"))).slice(0, 16);
+}
+
+/** Whether a host lists `profile`. `profiles` undefined: its hello never listed any, so the host answers for itself. */
+export function listsProfile(profiles: readonly ModelProfile[] | undefined, profile: string): boolean {
+ return !profiles || profiles.some((p) => p.name === profile);
+}
+
+/** The route for `profile` with `vars`; a refusal when the host does not list the profile. */
+async function profileRoute(profiles: readonly ModelProfile[] | undefined, profile: string, vars: Record<string, string>): Promise<ModelRoute> {
+ if (!listsProfile(profiles, profile)) return { mode: "refuse", reason: `This computer has no model profile \`${profile}\`.` };
+ return { mode: "profile", profile, vars, key: await modelKey(profile, vars) };
+}
+
+/** Protocol 5's `modelCredentials`: the managed route of a host that lists `profiles`, and whether it is the shared key's. */
+export async function managedModelRoute(
+ organizationKey: string | null,
+ env: SharedModelEnv,
+ profiles: readonly ModelProfile[] | undefined,
+): Promise<{ route: ModelRoute; fallback: boolean }> {
+ if (organizationKey) return { route: await profileRoute(profiles, MANAGED_MODEL_PROFILE, { token: organizationKey }), fallback: false };
+ if (env.COMPUTER_ANTHROPIC_API_KEY) return { route: await profileRoute(profiles, SHARED_KEY_PROFILE, { token: env.COMPUTER_ANTHROPIC_API_KEY }), fallback: true };
+ return { route: { mode: "refuse", reason: NO_MODEL_CREDENTIAL }, fallback: true };
+}
+
export interface ProvisionEnv {
OPENCOMPUTER_APP_URL?: string;
OC_MANAGED_CRED_HMAC_SECRET?: string;
diff --git a/services/managed-agents/src/computer/protocol.ts b/services/managed-agents/src/computer/protocol.ts
index 127ede6b..be3bb8d7 100644
--- a/services/managed-agents/src/computer/protocol.ts
+++ b/services/managed-agents/src/computer/protocol.ts
@@ -16,9 +16,19 @@ import type { Linked } from "./threads.js";
// thread (`kind: "api"`, the `cs_` id as its key) and carries its `sessionId`; a person may have
// no Slack id. Every field is optional: a v3 frame reads unchanged, and v4 frames go only to a
// host that says 4 (`hostSpeaksV4`).
+// 5 (work 097, design C2): every session's model traffic goes through the host's model proxy, by
+// profile. The hello lists the proxy's `profiles`; `welcome` and `credentials` carry `models`;
+// routes are `profile` or `refuse`; `model-observed`, `model-request` and `model-response` exist.
+// `managed` and `subscription` routes, the `model-proxy` features, `probe`/`probed`,
+// `model-health` and the model key in `credentials` do not exist at 5. A host that says 5 gets
+// only protocol 5's shapes, a host below it exactly what it got before: this gateway speaks both
+// until no host says 4, then everything marked protocol 4 here goes and
+// CALVIN_PROTOCOL_VERSION becomes 5.
export const CALVIN_PROTOCOL_VERSION = 4;
/** The first host protocol that has the session API (work 084). */
export const CALVIN_API_PROTOCOL = 4;
+/** The first host protocol whose model routes are profiles (work 097); a `welcome` says it only to such a host. */
+export const CALVIN_MODEL_PROTOCOL = 5;
export type SecretScope = "session" | "user" | "workspace";
@@ -152,6 +162,7 @@ export interface CalvinHostCredentials {
slackBotUserId: string;
teamId?: string;
claudeOAuthToken?: string;
+ /** Protocol 4 only, with `anthropicBaseUrl`: at 5 the key travels in a route's `vars` (`models`). */
anthropicApiKey?: string;
/**
* Where `anthropicApiKey` is spent, when not Anthropic: the organization's
@@ -235,11 +246,14 @@ export type CalvinGatewayToHost =
preview?: CalvinPreviewConfig;
/** Work 084: the relay's edge key. Absent: the wire is off on this computer. */
wire?: CalvinWireConfig;
+ /** Protocol 5: the route of a session whose own delivery carries none, by harness. */
+ models?: Partial<Record<CalvinHarness, ModelRoute>>;
}
/** Work 074: the previews config changed (tunnel provisioned, a port registered or released). Sent before the `previewed` it causes. */
| { t: "previews"; preview: CalvinPreviewConfig }
| { t: "people"; people: CalvinPerson[] }
- | { t: "credentials"; credentials: CalvinHostCredentials }
+ /** Protocol 5: `models` replaces the whole map of the `welcome`. */
+ | { t: "credentials"; credentials: CalvinHostCredentials; models?: Partial<Record<CalvinHarness, ModelRoute>> }
| {
t: "deliver";
id: string;
@@ -248,7 +262,10 @@ export type CalvinGatewayToHost =
credentials?: CalvinHostCredentials;
secrets?: SessionSecret[];
trace?: CalvinTraceContext;
- /** Work 077: the session's model route. Absent = managed (older gateways); never `refuse` (a refused delivery is not sent). */
+ /**
+ * Work 077: the session's model route. Absent = managed (older gateways); never `refuse` (a refused delivery is not sent).
+ * Protocol 5: absent = `models[harness]`.
+ */
model?: ModelRoute;
/** Work 084: the log's epoch and the last seq the SessionLog holds; the writer continues at lastSeq + 1. */
epoch?: number;
@@ -281,12 +298,23 @@ export type CalvinGatewayToHost =
* arrives at the organization's object.
*/
| { t: "assign"; organizationId: string; hostToken: string; gatewayUrl: string }
- | CalvinGatewayToHostV4;
+ | CalvinGatewayToHostV4
+ | CalvinGatewayToHostV5;
export type CalvinHostToGateway =
/** `features`: what this host can do; `model-proxy` (work 077) means subscription routes may go to it. */
/** `journals` (work 084): every session journal on the host's disk, so the gateway sends `epoch` for the ones it is ahead on. */
- | { t: "hello"; protocol: number; hostId: string; version: string; sessions: CalvinSessionReport[]; features?: string[]; journals?: CalvinJournalReport[] }
+ /** `profiles` (protocol 5): the model proxy's, while the host is connected to it; a change re-sends the hello. */
+ | {
+ t: "hello";
+ protocol: number;
+ hostId: string;
+ version: string;
+ sessions: CalvinSessionReport[];
+ features?: string[];
+ journals?: CalvinJournalReport[];
+ profiles?: ModelProfile[];
+ }
| { t: "session"; report: CalvinSessionReport }
| { t: "workspace"; status: unknown }
/** `/data`'s size and free space, every 5 minutes (work 071): the disk grows near capacity (disk-growth.ts). */
@@ -317,7 +345,8 @@ export type CalvinHostToGateway =
| { t: "reply"; id: string; ok: boolean; error?: string }
/** Work 077: the model proxy's answers and reports, relayed by the host. */
| { t: "probed"; id: string; result?: { status: number; usage?: ModelUsage }; error?: string }
- | { t: "model-bound"; sessionKey: string; mode: "subscription" | "managed" | "refuse"; fingerprint?: string }
+ /** Protocol 4: `subscription` or `managed`, with `fingerprint`. Protocol 5: `profile`, with `profile` and `key`. `refuse` in both. */
+ | { t: "model-bound"; sessionKey: string; mode: "subscription" | "managed" | "profile" | "refuse"; fingerprint?: string; profile?: string; key?: string }
| {
t: "model-health";
sessionKey: string;
@@ -331,7 +360,8 @@ export type CalvinHostToGateway =
usage?: ModelUsage;
}
| { t: "model-denied"; sessionKey: string; model: string; fallbackTo: string }
- | CalvinHostToGatewayV4;
+ | CalvinHostToGatewayV4
+ | CalvinHostToGatewayV5;
/** Work 082: whose subscription a route spends. */
export type ModelProvider = "anthropic" | "chatgpt";
@@ -345,6 +375,12 @@ export type ModelProvider = "anthropic" | "chatgpt";
* token replaces the old one in place); `managed` means the deliver's
* `credentials`, as before; `refuse` is only ever pushed (`model`), with a
* sentence for the thread.
+ *
+ * Protocol 5 (work 097): `profile` or `refuse`, nothing else. `profile` names
+ * one of the profiles the host's hello lists and carries the values of its
+ * variables. `subscription` is protocol 4's and goes with it. `managed` is
+ * never sent at 5: here it still means a session with no route of its own,
+ * which the host runs on `models[harness]`.
*/
export type ModelRoute =
| {
@@ -359,6 +395,16 @@ export type ModelRoute =
maxModel?: string;
}
| { mode: "managed" }
+ | {
+ mode: "profile";
+ profile: string;
+ /** The profile's variables by name. Credential values: a frame that carries them is never logged. */
+ vars: Record<string, string>;
+ /** Names the credential without revealing it (model-key.ts `modelKey`, or its author's own name): `[A-Za-z0-9._:-]{1,64}`. */
+ key: string;
+ owner?: string;
+ maxModel?: string;
+ }
| { mode: "refuse"; reason: string };
/** A subscription's usage windows, as the proxy last saw them: percentages, resets in epoch ms. */
@@ -545,6 +591,64 @@ export type CalvinHostToGatewayV4 =
*/
| { t: "wake"; sessionId: string };
+// ---------------------------------------------------------------- v5 (work 097)
+// Mirrors calvin src/protocol.ts at 5 (design C2). The gateway knows a profile by its name and
+// the harnesses it serves; everything else about it is the proxy's configuration.
+
+/** A profile as the proxy's hello lists it; the host forwards it unread. */
+export interface ModelProfile {
+ name: string;
+ /** Names of the variables a route must carry. */
+ vars: string[];
+ /** harness → what that harness's adapter needs. Opaque here: only the harness names are read. */
+ harness: Partial<Record<CalvinHarness, unknown>>;
+}
+
+/**
+ * The proxy's report of what an upstream answered on a credential, relayed by the host unread: a
+ * status with the headers the profile reports and the start of an error body, or a transport
+ * error's class. The proxy limits how often it arrives. `body` is upstream text: parsed, never
+ * logged, never shown.
+ */
+export interface ModelObserved {
+ sessionKey: string;
+ key: string;
+ profile: string;
+ status?: number;
+ /** Lower-case name → value. */
+ headers?: Record<string, string>;
+ body?: string;
+ error?: string;
+}
+
+/** A request of the gateway's own through a profile, with the credential in `vars`; answered by `model-response`. */
+export interface ModelRequest {
+ id: string;
+ profile: string;
+ vars: Record<string, string>;
+ method: string;
+ /** One of the profile's routes. */
+ path: string;
+ /** The raw query string, without the `?`. */
+ query?: string;
+ headers?: Record<string, string>;
+ body?: string;
+}
+
+/** `error`: the proxy's own code, `proxy_unavailable`, or `timeout` when the host gave up waiting. */
+export interface ModelResponse {
+ id: string;
+ status?: number;
+ /** Lower-case name → value. */
+ headers?: Record<string, string>;
+ body?: string;
+ error?: string;
+}
+
+export type CalvinGatewayToHostV5 = { t: "model-request" } & ModelRequest;
+
+export type CalvinHostToGatewayV5 = ({ t: "model-observed" } & ModelObserved) | ({ t: "model-response" } & ModelResponse);
+
/** The app's name in git, the author until a person's name is known. */
export const COMPUTER_GIT_NAME = "Computer";
diff --git a/services/managed-agents/test/computer-model-profiles-do.test.ts b/services/managed-agents/test/computer-model-profiles-do.test.ts
new file mode 100644
index 00000000..f07acfa3
--- /dev/null
+++ b/services/managed-agents/test/computer-model-profiles-do.test.ts
@@ -0,0 +1,178 @@
+import { env, runDurableObjectAlarm, runInDurableObject, SELF } from "cloudflare:test";
+import { describe, expect, it } from "vitest";
+
+import type { ComputerDurableObject } from "../src/computer/durable-object.js";
+import { hostToken } from "../src/computer/host-token.js";
+import { modelKey } from "../src/computer/model-key.js";
+import { CALVIN_MODEL_PROTOCOL, CALVIN_PROTOCOL_VERSION } from "../src/computer/protocol.js";
+
+/**
+ * Work 097, protocol 5 (design C2 and C8), in the real ComputerDurableObject:
+ * a host whose hello says 5 gets its managed model as a route on a profile of
+ * its model proxy, and no key in its credentials; a host that says 4 gets
+ * what it always got. The host's hello decides, and nothing else.
+ */
+
+const ORIGIN = "https://managedagents.test";
+const SHARED_KEY = "sk-ant-test";
+
+type Stub = DurableObjectStub<ComputerDurableObject>;
+type Account = {
+ bindManagedModelCredential(input: Record<string, string>): Promise<string>;
+ deleteManagedModelCredential(provider: string): Promise<boolean>;
+};
+const computers = () => (env as unknown as { COMPUTERS: DurableObjectNamespace<ComputerDurableObject> }).COMPUTERS;
+const account = (org: string) => (env as unknown as { ACCOUNTS: { getByName(name: string): Account } }).ACCOUNTS.getByName(org);
+const inside = <T,>(stub: Stub, fn: (instance: any, state: DurableObjectState) => T) => runInDurableObject(stub, fn as never) as Promise<T>;
+
+const profile = (name: string, harness: string) => ({ name, vars: ["token"], harness: { [harness]: {} } });
+const PROFILES = [profile("anthropic-key", "claude"), profile("openrouter", "claude")];
+
+function nextMessage(socket: WebSocket, type: string): Promise<any> {
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error(`no ${type} frame`)), 5000);
+ const listener = (event: MessageEvent) => {
+ const frame = JSON.parse(String(event.data));
+ if (frame.t !== type) return;
+ clearTimeout(timer);
+ socket.removeEventListener("message", listener);
+ resolve(frame);
+ };
+ socket.addEventListener("message", listener);
+ });
+}
+
+/** A linked organization whose billing gate admits it. */
+async function organization(org: string, team: string): Promise<Stub> {
+ await computers().getByName(`computer-slack-team:${team}`).claimTeam(team, org);
+ const stub = computers().getByName(org);
+ await stub.linkSlack(org, { teamId: team, teamName: "Profiles", botUserId: "UBOTPROF", botToken: "xoxb-profiles-token", installerUserId: "U0OWNER" });
+ await inside(stub, (instance) => {
+ instance.env = {
+ ...instance.env,
+ COMPUTER_API_ORGS: "*",
+ // An earlier test may leave a halted billing gate on the shared env.
+ OPENCOMPUTER_BILLING: { checkAdmission: async () => ({ allowed: true, isHalted: false, haltedAt: null, reason: null, paid: true, modelAccess: null }) },
+ };
+ });
+ return stub;
+}
+
+/** The organization's host connects and says `hello`; its socket and the welcome it got. */
+async function connect(org: string, hello: Record<string, unknown>): Promise<{ socket: WebSocket; welcome: any }> {
+ const upgraded = await SELF.fetch(`${ORIGIN}/v1/computer/host?organizationId=${org}`, {
+ headers: { upgrade: "websocket", authorization: `Bearer ${await hostToken("test-computer-host-token-key", org)}` },
+ });
+ const socket = upgraded.webSocket!;
+ socket.accept();
+ const welcomed = nextMessage(socket, "welcome");
+ socket.send(JSON.stringify({ t: "hello", hostId: org, version: "test", sessions: [], journals: [], ...hello }));
+ return { socket, welcome: await welcomed };
+}
+
+/** One Slack message into a new thread, as the host receives it. */
+async function deliver(stub: Stub, org: string, team: string, socket: WebSocket, ts: string): Promise<any> {
+ const delivered = nextMessage(socket, "deliver");
+ await stub.acceptSlackEvent(org, { eventId: `EvProf${ts}`, teamId: team, channelId: "C1", threadTs: ts, messageTs: ts, userId: "U0OWNER", text: "hi", mentioned: true, receivedAt: Date.now() });
+ await inside(stub, (_instance, state) => state.storage.sql.exec("UPDATE alarms SET at = 0 WHERE purpose = 'slack'"));
+ await runDurableObjectAlarm(stub);
+ const frame = await delivered;
+ socket.send(JSON.stringify({ t: "reply", id: frame.id, ok: true }));
+ return frame;
+}
+
+const route = async (name: string, token: string) => ({ mode: "profile", profile: name, vars: { token }, key: await modelKey(name, { token }) });
+
+describe("a host at protocol 5", () => {
+ it("gets the managed model as a profile route, never as a key in its credentials", async () => {
+ const ORG = "org_profiles";
+ const TEAM = "T0PROFILES";
+ await account(ORG).bindManagedModelCredential({ provider: "openrouter", key: "sk-or-profiles", orKeyHash: "or-hash-p1", operationId: "op-p1" });
+ const stub = await organization(ORG, TEAM);
+
+ const { socket, welcome } = await connect(ORG, { protocol: CALVIN_MODEL_PROTOCOL, profiles: PROFILES });
+ expect(welcome.protocol).toBe(CALVIN_MODEL_PROTOCOL);
+ expect(welcome.credentials).not.toHaveProperty("anthropicApiKey");
+ expect(welcome.credentials).not.toHaveProperty("anthropicBaseUrl");
+ expect(welcome.models).toEqual({ claude: await route("openrouter", "sk-or-profiles") });
+
+ // A session's route is its delivery's `model`, else `models[harness]` (C2). The public build sends none of
+ // its own; an implementation that routes sessions may. The organization's key either way.
+ const frame = await deliver(stub, ORG, TEAM, socket, "500.1");
+ expect(frame.model ?? welcome.models.claude).toEqual(await route("openrouter", "sk-or-profiles"));
+ expect(frame.session.harness ?? "claude").toBe("claude");
+ expect(JSON.stringify(frame.credentials)).not.toContain("sk-or-profiles");
+
+ // What the proxy observed and bound is the hosted implementation's business: nothing answers, nothing breaks.
+ const key = welcome.models.claude.key;
+ socket.send(JSON.stringify({ t: "model-bound", sessionKey: frame.session.key, mode: "profile", profile: "openrouter", key }));
+ socket.send(JSON.stringify({ t: "model-observed", sessionKey: frame.session.key, key, profile: "openrouter", status: 401, headers: {} }));
+ socket.send(JSON.stringify({ t: "model-response", id: "nobody-asked", status: 200 }));
+
+ // A deleted key: the shared one, on its own profile, pushed like any credential change.
+ await account(ORG).deleteManagedModelCredential("openrouter");
+ const pushed = nextMessage(socket, "credentials");
+ await stub.modelKeyChanged();
+ const credentials = await pushed;
+ expect(credentials.models).toEqual({ claude: await route("anthropic-key", SHARED_KEY) });
+ expect(JSON.stringify(credentials.credentials)).not.toContain(SHARED_KEY);
+ socket.close();
+ }, 20_000);
+
+ it("is refused, in the backend's words, a profile its hello does not list", async () => {
+ const ORG = "org_profiles_unlisted";
+ await account(ORG).bindManagedModelCredential({ provider: "openrouter", key: "sk-or-unlisted", orKeyHash: "or-hash-p2", operationId: "op-p2" });
+ await organization(ORG, "T0PROFUNL");
+
+ const listed = await connect(ORG, { protocol: CALVIN_MODEL_PROTOCOL, profiles: [profile("anthropic-key", "claude")] });
+ expect(listed.welcome.models).toEqual({ claude: { mode: "refuse", reason: "This computer has no model profile `openrouter`." } });
+
+ // The same host with its model proxy down says no profiles: the last list stands.
+ const again = nextMessage(listed.socket, "welcome");
+ listed.socket.send(JSON.stringify({ t: "hello", protocol: CALVIN_MODEL_PROTOCOL, hostId: ORG, version: "test", sessions: [], journals: [] }));
+ expect((await again).models.claude.mode).toBe("refuse");
+
+ // The proxy back, with the profile: the route.
+ const back = nextMessage(listed.socket, "welcome");
+ listed.socket.send(JSON.stringify({ t: "hello", protocol: CALVIN_MODEL_PROTOCOL, hostId: ORG, version: "test", sessions: [], journals: [], profiles: PROFILES }));
+ expect((await back).models).toEqual({ claude: await route("openrouter", "sk-or-unlisted") });
+ listed.socket.close();
+ }, 20_000);
+
+ it("lists the harnesses its profiles serve", async () => {
+ const ORG = "org_profiles_harness";
+ const stub = await organization(ORG, "T0PROFHAR");
+ const harnesses = () => inside(stub, (instance) => instance.harnesses() as string[]);
+
+ const first = await connect(ORG, { protocol: CALVIN_MODEL_PROTOCOL, profiles: PROFILES });
+ expect(await harnesses()).toEqual(["claude"]);
+ const again = nextMessage(first.socket, "welcome");
+ first.socket.send(JSON.stringify({ t: "hello", protocol: CALVIN_MODEL_PROTOCOL, hostId: ORG, version: "test", sessions: [], journals: [], profiles: [...PROFILES, profile("openai-key", "codex")] }));
+ await again;
+ expect(await harnesses()).toEqual(["claude", "codex"]);
+ first.socket.close();
+ });
+});
+
+describe("a host at protocol 4, after one at 5", () => {
+ it("gets protocol 4's welcome and delivery: the key in its credentials, no route", async () => {
+ const ORG = "org_profiles_back";
+ const TEAM = "T0PROFBACK";
+ const stub = await organization(ORG, TEAM);
+
+ const five = await connect(ORG, { protocol: CALVIN_MODEL_PROTOCOL, profiles: PROFILES });
+ expect(five.welcome.models).toEqual({ claude: await route("anthropic-key", SHARED_KEY) });
+ five.socket.close();
+
+ const four = await connect(ORG, { protocol: CALVIN_PROTOCOL_VERSION, features: ["model-proxy"] });
+ expect(four.welcome.protocol).toBe(CALVIN_PROTOCOL_VERSION);
+ expect(four.welcome.credentials.anthropicApiKey).toBe(SHARED_KEY);
+ expect(four.welcome).not.toHaveProperty("models");
+ const frame = await deliver(stub, ORG, TEAM, four.socket, "501.1");
+ expect(frame.credentials.anthropicApiKey).toBe(SHARED_KEY);
+ expect(frame).not.toHaveProperty("model");
+ // The profiles went with the host that listed them.
+ expect(await inside(stub, (instance) => instance.setting("hostProfiles"))).toBeUndefined();
+ four.socket.close();
+ }, 20_000);
+});
diff --git a/services/managed-agents/test/computer-model-profiles.test.ts b/services/managed-agents/test/computer-model-profiles.test.ts
new file mode 100644
index 00000000..3d3e5d5c
--- /dev/null
+++ b/services/managed-agents/test/computer-model-profiles.test.ts
@@ -0,0 +1,112 @@
+import { describe, expect, it } from "vitest";
+
+import { harnessOnProfile, helloProfiles, profileHarnesses } from "../src/computer/harnesses.js";
+import { noModelAccess } from "../src/computer/model-access.js";
+import { NO_MODEL_CREDENTIAL, listsProfile, managedModelRoute, modelKey } from "../src/computer/model-key.js";
+import type { ModelProfile } from "../src/computer/protocol.js";
+
+/**
+ * Work 097, protocol 5 (design C2 and C8): a model route names a profile of
+ * the host's model proxy and carries its variables. The pure parts: the
+ * `key` hash, the managed route, and what a hello's profiles say.
+ */
+
+const profile = (name: string, ...harnesses: string[]): ModelProfile => ({ name, vars: ["token"], harness: Object.fromEntries(harnesses.map((h) => [h, {}])) });
+const LISTED = [profile("anthropic-key", "claude"), profile("openrouter", "claude"), profile("openai-key", "codex")];
+
+describe("modelKey", () => {
+ it("is the first 16 hex digits of sha256 over the profile and its variables in name order, joined by NUL", async () => {
+ // printf 'openrouter\0token=sk-or-test' | sha256sum
+ expect(await modelKey("openrouter", { token: "sk-or-test" })).toBe("427939d396f90454");
+ // printf 'p\0a=1\0b=2' | sha256sum
+ expect(await modelKey("p", { b: "2", a: "1" })).toBe("c79bd378f5b5e1f1");
+ });
+
+ it("differs by profile and by value", async () => {
+ const key = await modelKey("openrouter", { token: "sk-or-test" });
+ expect(await modelKey("anthropic-key", { token: "sk-or-test" })).not.toBe(key);
+ expect(await modelKey("openrouter", { token: "sk-or-other" })).not.toBe(key);
+ });
+});
+
+describe("managedModelRoute", () => {
+ const env = { COMPUTER_ANTHROPIC_API_KEY: "sk-ant-shared" };
+
+ it("routes the organization's key on `openrouter`", async () => {
+ expect(await managedModelRoute("sk-or-org", env, LISTED)).toEqual({
+ route: { mode: "profile", profile: "openrouter", vars: { token: "sk-or-org" }, key: await modelKey("openrouter", { token: "sk-or-org" }) },
+ fallback: false,
+ });
+ });
+
+ it("falls back to the shared key on `anthropic-key`", async () => {
+ expect(await managedModelRoute(null, env, LISTED)).toEqual({
+ route: { mode: "profile", profile: "anthropic-key", vars: { token: "sk-ant-shared" }, key: await modelKey("anthropic-key", { token: "sk-ant-shared" }) },
+ fallback: true,
+ });
+ });
+
+ it("refuses, in the backend's words, a profile the host's hello does not list", async () => {
+ expect(await managedModelRoute("sk-or-org", env, [profile("anthropic-key", "claude")])).toEqual({
+ route: { mode: "refuse", reason: "This computer has no model profile `openrouter`." },
+ fallback: false,
+ });
+ expect((await managedModelRoute(null, env, [])).route).toEqual({ mode: "refuse", reason: "This computer has no model profile `anthropic-key`." });
+ });
+
+ it("leaves the answer to a host whose hello never listed any profile", async () => {
+ expect((await managedModelRoute("sk-or-org", env, undefined)).route).toMatchObject({ mode: "profile", profile: "openrouter" });
+ expect(listsProfile(undefined, "openrouter")).toBe(true);
+ expect(listsProfile([], "openrouter")).toBe(false);
+ });
+
+ it("refuses when there is no managed credential at all", async () => {
+ expect(await managedModelRoute(null, {}, LISTED)).toEqual({ route: { mode: "refuse", reason: NO_MODEL_CREDENTIAL }, fallback: true });
+ });
+});
+
+describe("a hello's profiles", () => {
+ it("keeps the well-formed ones, and only their protocol fields", () => {
+ expect(helloProfiles(undefined)).toBeUndefined();
+ expect(helloProfiles("openrouter")).toBeUndefined();
+ expect(helloProfiles([])).toEqual([]);
+ expect(
+ helloProfiles([
+ { name: "openrouter", vars: ["token"], harness: { claude: { baseUrl: "http://proxy" } }, extra: 1 },
+ { name: "no-vars", harness: {} },
+ { name: 7, vars: [], harness: {} },
+ { name: "vars-not-strings", vars: [1], harness: {} },
+ { name: "harness-not-an-object", vars: [], harness: [] },
+ null,
+ ]),
+ ).toEqual([{ name: "openrouter", vars: ["token"], harness: { claude: { baseUrl: "http://proxy" } } }]);
+ expect(helloProfiles(Array.from({ length: 40 }, (_, i) => profile(`p${i}`, "claude")))).toHaveLength(32);
+ });
+
+ it("say which harnesses the computer can run: the default one, and those a profile serves", () => {
+ expect(profileHarnesses([])).toEqual(["claude"]);
+ expect(profileHarnesses([profile("openrouter", "claude")])).toEqual(["claude"]);
+ expect(profileHarnesses(LISTED)).toEqual(["claude", "codex"]);
+ });
+
+ it("say which harness a session on a profile runs", () => {
+ expect(harnessOnProfile(LISTED, "openrouter", "claude")).toBe("claude");
+ expect(harnessOnProfile(LISTED, "openai-key", "codex")).toBe("codex");
+ // A profile that does not serve the wanted harness: the one it serves.
+ expect(harnessOnProfile(LISTED, "openrouter", "codex")).toBe("claude");
+ expect(harnessOnProfile(LISTED, "openai-key", "claude")).toBe("codex");
+ // A profile the host did not list, or a host that listed none: the wanted one.
+ expect(harnessOnProfile(LISTED, "unknown", "codex")).toBe("codex");
+ expect(harnessOnProfile(undefined, "openrouter", "codex")).toBe("codex");
+ });
+});
+
+describe("noModelAccess at protocol 5", () => {
+ it("gives no session a route of its own (each runs on the host's `models`), and ignores what the host observed", async () => {
+ const access = noModelAccess();
+ expect(await access.models.forDelivery({ key: "T:C:1", ownerId: "U1" }, "U1")).toEqual({ route: { mode: "managed" }, reason: "no_subscription" });
+ expect(await access.models.observed?.({ sessionKey: "T:C:1", key: "k", profile: "openrouter", status: 401 })).toBeUndefined();
+ expect(access.models.responded?.({ id: "r1", status: 200 })).toBeUndefined();
+ access.models.bound("T:C:1", "profile", "k", "openrouter");
+ });
+});
diff --git a/services/managed-agents/vitest.config.ts b/services/managed-agents/vitest.config.ts
index e0c8c132..46c0f70f 100644
--- a/services/managed-agents/vitest.config.ts
+++ b/services/managed-agents/vitest.config.ts
@@ -269,7 +269,7 @@ export default defineConfig({
],
test: {
name: "computer",
- include: ["test/computer-routes.test.ts", "test/computer-operator.test.ts", "test/computer-pool-probe-do.test.ts", "test/computer-agent-routes.test.ts", "test/computer-size.test.ts", "test/computer-spawn.test.ts", "test/computer-threads.test.ts", "test/computer-queue.test.ts", "test/computer-disk.test.ts", "test/computer-model-access-do.test.ts", "test/computer-hosted-do.test.ts"],
+ include: ["test/computer-routes.test.ts", "test/computer-operator.test.ts", "test/computer-pool-probe-do.test.ts", "test/computer-agent-routes.test.ts", "test/computer-size.test.ts", "test/computer-spawn.test.ts", "test/computer-threads.test.ts", "test/computer-queue.test.ts", "test/computer-disk.test.ts", "test/computer-model-access-do.test.ts", "test/computer-model-profiles-do.test.ts", "test/computer-hosted-do.test.ts"],
},
},
{
@@ -424,6 +424,7 @@ export default defineConfig({
"test/auth.test.ts",
"test/computer-grants.test.ts",
"test/computer-model-access.test.ts",
+ "test/computer-model-profiles.test.ts",
"test/computer-disk-growth.test.ts",
"test/deployment-region.test.ts",
"test/session-runtime-selection.test.ts",
@@ -495,6 +496,7 @@ export default defineConfig({
"test/computer-connections.test.ts",
"test/computer-model-subscriptions.test.ts",
"test/computer-codex-subscriptions.test.ts",
+ "test/computer-subscription-profiles.test.ts",
"test/computer-agent-connect.test.ts",
"test/computer-connect-codes.test.ts",
"test/computer-units.test.ts",