Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: the app registers each chat's model

ogsamrat5ebb60e0b6b8
diff --git a/apps/server/src/model-modes/PARITY.sha256 b/apps/server/src/model-modes/PARITY.sha256
index 47ae2f65..2366b79f 100644
--- a/apps/server/src/model-modes/PARITY.sha256
+++ b/apps/server/src/model-modes/PARITY.sha256
@@ -2,3 +2,5 @@
# A change to one must be ported to the other and this list updated in both.
609bbc9cb508b4f79295e0b2f1f4707bd1facbee83835d5db7eac02fa088f43b model-modes.mjs
ef8a96d1e71ea3f5f3ab7a96796d042c009d90cc2896e7132b8dfc4486540699 model-modes.d.mts
+f2259a4313af33359362e5bc603a1b197d2736fc0844aee73dbc696058304d07 strict-sessions.mjs
+9795dfe99dd6d8e89053232ef54b50877f4724ace6b9d946aa4c8e48b11c6495 strict-sessions.d.mts
diff --git a/apps/server/src/model-modes/model-modes.test.ts b/apps/server/src/model-modes/model-modes.test.ts
index 849a4e54..3d9df721 100644
--- a/apps/server/src/model-modes/model-modes.test.ts
+++ b/apps/server/src/model-modes/model-modes.test.ts
@@ -46,7 +46,7 @@ const request = (body: Record<string, unknown>, headers: Record<string, string>
describe("model modes", () => {
test("CLI/desktop parity: model-modes/PARITY.sha256 matches its files", () => {
const rows = readFileSync(path.join(import.meta.dir, "PARITY.sha256"), "utf8").split("\n").filter((line) => line && !line.startsWith("#"));
- expect(rows.map((row) => row.split(/\s+/)[1])).toEqual(["model-modes.mjs", "model-modes.d.mts"]);
+ expect(rows.map((row) => row.split(/\s+/)[1])).toEqual(["model-modes.mjs", "model-modes.d.mts", "strict-sessions.mjs", "strict-sessions.d.mts"]);
for (const row of rows) {
const [hash, name] = row.split(/\s+/);
const actual = createHash("sha256").update(readFileSync(path.join(import.meta.dir, name ?? ""))).digest("hex");
@@ -122,4 +122,95 @@ describe("model modes", () => {
expect(response.status).toBe(200);
expect(calls.map((c) => c.model)).toEqual(["kimi-k3.1-pro", "gpt-6-astra"]);
});
+
+ test("broker: strict sessions bind once before a chat's first agent request; conflicts and verification stop here; failures never block", async () => {
+ type Bind = Record<string, unknown>;
+ const binds: Bind[] = [];
+ const sent: { session: string | null; strict: string | null }[] = [];
+ const bound = new Map<string, { model: string; mode: string }>([["ses_other", { model: "kimi-k3.1-pro", mode: "native" }]]);
+ let strictOn = false;
+ const tools = [{ type: "function", name: "bash" }];
+ const b = new OmniRushGatewayBroker({
+ credentials: { gatewayUrl: "https://gateway.example/omnirush/v1", accessToken: "access-token", refreshToken: "refresh-token" },
+ engineToken: "local-engine-token",
+ chatPin: (id) => (id === "ses_lost" ? { box: true, revision: "lb1:0123456789ab" } : null),
+ fetch: async (input, init) => {
+ const url = new URL(String(input));
+ const headers = new Headers(init?.headers);
+ if (url.pathname === "/omnirush/collect/capabilities") return Response.json({ schema_versions: [1, 2, 3], ...(strictOn ? { strict_sessions: { mode: "enforce", bind: true, path: "/omnirush/device/session-binding", header: "X-OmniRush-Strict-Session", implicit: true } } : {}) });
+ if (url.pathname === "/omnirush/device/session-binding") {
+ const body = JSON.parse(String(init?.body)) as Bind & { session_id: string; parent_session_id?: string; model: string; mode: string };
+ binds.push(body);
+ if (body.session_id === "ses_down") throw new TypeError("fetch failed");
+ if (body.session_id === "ses_verify") return Response.json({ detail: "verification_required" }, { status: 403 });
+ if (body.session_id === "ses_claude") return Response.json({ detail: "use_claude_token" }, { status: 400 });
+ if (body.session_id === "ses_used400") return Response.json({ detail: "session_model_used", models_used: ["kimi-k3.1-pro"] }, { status: 400 });
+ if (body.session_id === "ses_used") return Response.json({ detail: "session_model_used", models_used: ["kimi-k3.1-pro"] }, { status: 409 });
+ const root = body.parent_session_id ? bound.get(body.parent_session_id) : null;
+ if (body.parent_session_id && !root) return Response.json({ detail: "session_unknown_parent" }, { status: 409 });
+ const binding = bound.get(body.session_id) ?? root ?? { model: body.model, mode: body.mode };
+ if (binding.model !== body.model || binding.mode !== body.mode) return Response.json({ detail: "session_binding_conflict", binding }, { status: 409 });
+ bound.set(body.session_id, binding);
+ return Response.json({ binding: { ...binding, session_id: body.session_id }, enforcement: "enforce", kept: [], ...(body.session_id === "ses_late" ? { bound_late: true } : {}) });
+ }
+ sent.push({ session: headers.get("x-omnirush-session-id"), strict: headers.get("x-omnirush-strict-session") });
+ if (headers.get("x-omnirush-session-id") === "ses_gwused") return Response.json({ models_used: ["gpt-6.1-sol"], detail: "session_model_used", error: { type: "invalid_request_error", code: "session_model_used", message: "This chat already ran on another model. Start a new chat to use this one.", omnirush: { code: "session_model_used", retry: false } } }, { status: 400, headers: { "x-should-retry": "false" } });
+ if (headers.get("x-omnirush-session-id") === "ses_gw") return Response.json({ detail: "mode_not_bound", error: { type: "invalid_request_error", code: "mode_not_bound", message: "This chat runs in a normal project. Start a new chat to change the project mode.", omnirush: { code: "mode_not_bound", retry: false } } }, { status: 400, headers: { "x-should-retry": "false" } });
+ return Response.json({ output: [] });
+ },
+ });
+ const post = (session: string, extra: Record<string, string> = {}, body: Record<string, unknown> = { model: "omnirush/gpt-6-astra", tools }) => b.handle(request(body, { "x-omnirush-session-id": session, ...extra }), "responses");
+ // An older server (no strict_sessions): no bind, no header.
+ await b.sessionUploadCapabilities();
+ expect((await post("ses_off")).status).toBe(200);
+ expect(binds).toEqual([]);
+ expect(sent).toEqual([{ session: "ses_off", strict: null }]);
+ strictOn = true;
+ b.resetCapabilities();
+ await b.sessionUploadCapabilities();
+ // A root binds once; every request of the chat says it is strict, titles and compactions too.
+ expect((await post("ses_root")).status).toBe(200);
+ expect((await post("ses_root")).status).toBe(200);
+ expect((await post("ses_root", {}, { model: "gpt-6-astra" })).status).toBe(200);
+ expect((await b.handle(request({ model: "gpt-6-astra" }, { "x-omnirush-session-id": "ses_root" }, "responses/compact"), "responses/compact")).status).toBe(200);
+ expect(binds).toEqual([{ session_id: "ses_root", model: "gpt-6-astra", mode: "native", capture_policy: "legacy" }]);
+ expect(sent.slice(1).map((s) => s.strict)).toEqual(["1", "1", "1", "1"]);
+ // A sub-agent names its root.
+ expect((await post("ses_child", { "x-parent-session-id": "ses_root" })).status).toBe(200);
+ expect(binds.at(-1)).toMatchObject({ session_id: "ses_child", parent_session_id: "ses_root" });
+ // A root the server does not know: bound first, then the child once more.
+ binds.length = 0;
+ expect((await post("ses_kid2", { "x-parent-session-id": "ses_lost", "x-omnirush-box": "1" })).status).toBe(200);
+ expect(binds.map((x) => [x.session_id, x.parent_session_id ?? null, x.mode, x.revision ?? null])).toEqual([["ses_kid2", "ses_lost", "box", "lb1:0123456789ab"], ["ses_lost", null, "box", "lb1:0123456789ab"], ["ses_kid2", "ses_lost", "box", "lb1:0123456789ab"]]);
+ // Conflicts and verification: refused here, never sent.
+ const before = sent.length;
+ const conflict = await post("ses_other");
+ expect(conflict.status).toBe(400);
+ expect(conflict.headers.get("x-should-retry")).toBe("false");
+ expect(((await conflict.json()) as { error: { code: string; message: string } }).error).toMatchObject({ code: "session_binding_conflict", message: "This chat runs on kimi-k3.1-pro. Start a new chat to use gpt-6-astra." });
+ const used = await post("ses_used");
+ expect(((await used.json()) as { error: { code: string; message: string } }).error).toMatchObject({ code: "session_model_used", message: "This chat already ran on kimi-k3.1-pro. Start a new chat to use gpt-6-astra." });
+ expect(((await (await post("ses_used400")).json()) as { error: { code: string } }).error.code).toBe("session_model_used");
+ const verify = await post("ses_verify");
+ expect(verify.status).toBe(403);
+ expect(((await verify.json()) as { error: { code: string } }).error.code).toBe("verification_required");
+ expect(sent.length).toBe(before);
+ // A late bind and a Claude chat are settled; a network failure never blocks and is tried again.
+ binds.length = 0;
+ for (const id of ["ses_late", "ses_late", "ses_claude", "ses_claude"]) expect((await post(id)).status).toBe(200);
+ expect(binds.map((x) => x.session_id)).toEqual(["ses_late", "ses_claude"]);
+ binds.length = 0;
+ expect((await post("ses_down")).status).toBe(200);
+ expect((await post("ses_down")).status).toBe(200);
+ expect(binds.length).toBe(2);
+ // The gateway's mode_not_bound: final, its words kept.
+ const held = await post("ses_gw");
+ expect(held.status).toBe(400);
+ expect(held.headers.get("x-should-retry")).toBe("false");
+ expect(((await held.json()) as { error: { message: string } }).error.message).toBe("This chat runs in a normal project. Start a new chat to change the project mode.");
+ const gwUsed = await post("ses_gwused");
+ expect(gwUsed.status).toBe(400);
+ expect(gwUsed.headers.get("x-should-retry")).toBe("false");
+ expect(((await gwUsed.json()) as { error: { message: string } }).error.message).toBe("This chat already ran on another model. Start a new chat to use this one.");
+ });
});
diff --git a/apps/server/src/model-modes/strict-sessions.d.mts b/apps/server/src/model-modes/strict-sessions.d.mts
new file mode 100644
index 00000000..0a2c1903
--- /dev/null
+++ b/apps/server/src/model-modes/strict-sessions.d.mts
@@ -0,0 +1,25 @@
+// Types of strict-sessions.mjs (the same pair of files in omnirush-cli
+// src/model-modes/ and omnirush-gui apps/server/src/model-modes/; PARITY.sha256).
+
+import type { ModelMode } from "./model-modes.mjs";
+
+export const STRICT_BIND_PATH: "/omnirush/device/session-binding";
+export const SESSION_BINDING_CONFLICT: "session_binding_conflict";
+export const SESSION_UNKNOWN_PARENT: "session_unknown_parent";
+export const SESSION_MODEL_USED: "session_model_used";
+export const STRICT_SESSION_HEADER: "x-omnirush-strict-session";
+export const VERIFICATION_REQUIRED: "verification_required";
+export const MODEL_NOT_BOUND: "model_not_bound";
+export const MODE_NOT_BOUND: "mode_not_bound";
+export const BIND_TIMEOUT_MS: number;
+export const VERIFICATION_MESSAGE: string;
+
+export type ChatPin = { model: string; mode: ModelMode; revision?: string | null };
+export type BindChat = ChatPin & { path: string | null; sessionId: string; rootId?: string | null; capturePolicy?: string | null; root?: ChatPin | null };
+export type BindOutcome = { ok: true } | { refused: { code: string; message: string } };
+export type BindPost = (path: string, body: Record<string, unknown>, signal: AbortSignal) => Promise<{ status: number; body: unknown }>;
+
+export function strictSessions(capabilities: unknown): { path: string; header: string } | null;
+export function bindingConflictMessage(binding: unknown, model: string): string;
+export function modelUsedMessage(modelsUsed: unknown, model: string): string;
+export function sessionBinder(post: BindPost, options?: { timeoutMs?: number }): (chat: BindChat) => Promise<BindOutcome>;
diff --git a/apps/server/src/model-modes/strict-sessions.mjs b/apps/server/src/model-modes/strict-sessions.mjs
new file mode 100644
index 00000000..05da8bcc
--- /dev/null
+++ b/apps/server/src/model-modes/strict-sessions.mjs
@@ -0,0 +1,123 @@
+// Strict sessions: each chat binds its model and project mode with the server.
+//
+// GET /collect/capabilities `strict_sessions: {mode, bind, path, header}`: while
+// `bind` is true, a chat's first agent request (where the client pins its
+// model) is preceded by POST <path> {session_id, parent_session_id?, model,
+// mode, revision?, capture_policy?}. A sub-agent names its root chat; a
+// root the server does not know yet is bound first and the child sent once
+// more. A conflict (the chat is bound to another model or mode, or already
+// ran on another model unbound) or a verification refusal stops the request
+// here; anything else (a Claude
+// chat, a refused model, a network failure, a 5xx, a timeout) never holds
+// the chat up: the request goes on unbound and a failed bind is tried again
+// on the next request. While binding is on, every model request of a chat
+// (compactions, titles and sub-agents too) carries the server's `header`
+// (X-OmniRush-Strict-Session): 1, so the gateway can bind it on the spot when the explicit bind failed.
+// No `strict_sessions` (an older server): no bind, no header.
+//
+// The same file ships in omnirush-cli (src/model-modes/) and omnirush-gui
+// (apps/server/src/model-modes/); PARITY.sha256 lists it in both. No imports.
+
+export const STRICT_BIND_PATH = "/omnirush/device/session-binding";
+export const SESSION_BINDING_CONFLICT = "session_binding_conflict";
+export const SESSION_UNKNOWN_PARENT = "session_unknown_parent";
+export const SESSION_MODEL_USED = "session_model_used";
+export const STRICT_SESSION_HEADER = "x-omnirush-strict-session";
+export const VERIFICATION_REQUIRED = "verification_required";
+export const MODEL_NOT_BOUND = "model_not_bound";
+export const MODE_NOT_BOUND = "mode_not_bound";
+export const BIND_TIMEOUT_MS = 5_000;
+export const VERIFICATION_MESSAGE = "Your account needs to be verified before it can use models. See https://omnirush.ai/console";
+
+const PATH = /^\/[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*$/;
+const HEADER = /^x-[a-z0-9-]{1,62}$/;
+
+/**
+ * A capabilities answer's strict sessions while the server asks clients to
+ * bind: { path, header } (header lower case), else null.
+ */
+export function strictSessions(capabilities) {
+ const block = capabilities && typeof capabilities === "object" ? capabilities.strict_sessions : null;
+ if (!block || typeof block !== "object" || block.bind !== true) return null;
+ const header = typeof block.header === "string" ? block.header.trim().toLowerCase() : "";
+ return {
+ path: typeof block.path === "string" && PATH.test(block.path) ? block.path : STRICT_BIND_PATH,
+ header: HEADER.test(header) ? header : STRICT_SESSION_HEADER,
+ };
+}
+
+/** The plain refusal of a request on another model or mode than the chat's binding. */
+export function bindingConflictMessage(binding, model) {
+ const bound = binding && typeof binding === "object" ? binding : {};
+ if (typeof bound.model === "string" && bound.model && bound.model !== model) return `This chat runs on ${bound.model}. Start a new chat to use ${model}.`;
+ if (bound.mode === "box") return "This chat runs in the sandbox. Start a new chat to run outside it.";
+ if (bound.mode === "native") return "This chat runs outside the sandbox. Start a new chat to run in it.";
+ return "This chat runs on another model. Start a new chat to use this one.";
+}
+
+/** The plain refusal of a bind for a chat that already ran on other models (`models_used`). */
+export function modelUsedMessage(modelsUsed, model) {
+ const used = Array.isArray(modelsUsed) ? modelsUsed.filter((id) => typeof id === "string" && id && id !== model) : [];
+ return used.length ? `This chat already ran on ${used.join(", ")}. Start a new chat to use ${model}.` : `This chat already ran on another model. Start a new chat to use ${model}.`;
+}
+
+function detailOf(answer) {
+ const body = answer && answer.body;
+ return body && typeof body === "object" && typeof body.detail === "string" ? body.detail : null;
+}
+
+/**
+ * The binder of one client process. `post(path, body, signal)` sends the
+ * bind (the client's bearer and origin) and resolves { status, body } (body
+ * parsed JSON or null); it may throw. bind(chat) resolves { ok: true } or
+ * { refused: { code, message } }, where chat is { path, sessionId, rootId?,
+ * model, mode, revision?, capturePolicy?, root?: { model, mode, revision? } }
+ * (root: the root chat's own pin, for binding it first). A session bound (or
+ * one the server will not bind: a Claude chat, a refused model) is not asked
+ * again in this process.
+ */
+export function sessionBinder(post, { timeoutMs = BIND_TIMEOUT_MS } = {}) {
+ const settled = new Set();
+ const settle = (id) => {
+ settled.add(id);
+ while (settled.size > 4000) settled.delete(settled.values().next().value);
+ };
+ const send = async (path, body) => {
+ try { return await post(path, body, AbortSignal.timeout(timeoutMs)); } catch { return null; }
+ };
+ const bodyOf = (id, parent, pin, capturePolicy) => ({
+ session_id: id,
+ ...(parent ? { parent_session_id: parent } : {}),
+ model: pin.model,
+ mode: pin.mode,
+ ...(pin.revision ? { revision: pin.revision } : {}),
+ ...(capturePolicy ? { capture_policy: capturePolicy } : {}),
+ });
+ return async function bind(chat) {
+ if (!chat || !chat.path || !chat.sessionId || !chat.model || settled.has(chat.sessionId)) return { ok: true };
+ const parent = chat.rootId && chat.rootId !== chat.sessionId ? chat.rootId : null;
+ const body = bodyOf(chat.sessionId, parent, chat, chat.capturePolicy);
+ let answer = await send(chat.path, body);
+ if (parent && answer && answer.status === 409 && detailOf(answer) === SESSION_UNKNOWN_PARENT) {
+ const root = await send(chat.path, bodyOf(parent, null, chat.root && chat.root.model ? chat.root : chat, chat.capturePolicy));
+ if (root && root.status === 200) {
+ settle(parent);
+ answer = await send(chat.path, body);
+ }
+ }
+ const status = answer ? answer.status : 0;
+ const detail = detailOf(answer);
+ if (detail === SESSION_BINDING_CONFLICT) {
+ return { refused: { code: SESSION_BINDING_CONFLICT, message: bindingConflictMessage(answer.body.binding, chat.model) } };
+ }
+ if (detail === SESSION_MODEL_USED) {
+ return { refused: { code: SESSION_MODEL_USED, message: modelUsedMessage(answer.body.models_used, chat.model) } };
+ }
+ if (detail === VERIFICATION_REQUIRED) {
+ return { refused: { code: VERIFICATION_REQUIRED, message: VERIFICATION_MESSAGE } };
+ }
+ // Bound (bound_late too), or a chat the server will not bind (a Claude chat, a refused model): settled.
+ if (status === 200 || status === 400 || status === 422) settle(chat.sessionId);
+ return { ok: true };
+ };
+}
diff --git a/apps/server/src/omnirush-gateway-broker.ts b/apps/server/src/omnirush-gateway-broker.ts
index e45dabe6..cf9bffcf 100644
--- a/apps/server/src/omnirush-gateway-broker.ts
+++ b/apps/server/src/omnirush-gateway-broker.ts
@@ -15,6 +15,8 @@ import { builtinOmniRushModelCatalog, omnirushModelWantsReasoningSummary } from
import { RejectedAttachments, isRejectedAttachmentError, type Attachment } from "./rejected-attachments.js";
import { gatewayUrlAllowed, RELEASE_GATEWAY_ERROR } from "./release-guard.js";
import { BOX_HEADER, MODEL_NOT_IN_MODE, notInModeMessage, projectMode } from "./model-modes/model-modes.mjs";
+import { MODE_NOT_BOUND, MODEL_NOT_BOUND, SESSION_BINDING_CONFLICT, SESSION_MODEL_USED, VERIFICATION_REQUIRED, sessionBinder, strictSessions } from "./model-modes/strict-sessions.mjs";
+import { redactionPolicy } from "./context/redact-policy.js";
/** A main chat's request on another model than the one it started on (one model per chat). */
const SESSION_MODEL_FIXED = "session_model_fixed";
@@ -85,6 +87,8 @@ type BrokerOptions = {
reasoningSummaryFor?: (model: string) => boolean | Promise<boolean>;
/** Hears the gateway's mandatory-update signals (see GatewayUpdateSignal). */
onUpdateSignal?: (signal: GatewayUpdateSignal) => void;
+ /** A chat's box pin ({ box, revision }, box/service.ts chatPin): the revision a strict-session bind names. */
+ chatPin?: (sessionId: string) => { box: boolean; revision: string | null } | null;
/**
* The desktop app's version: every request to omnirush.ai then names it in
* `X-OmniRush-Client: gui/<version>`, so the backend knows an updated app
@@ -213,7 +217,13 @@ const GATEWAY_ERROR_COPY: Record<string, string> = {
// A model outside the project's mode (model-modes/): the gateway's refusal, or the broker's own before sending.
[MODEL_NOT_IN_MODE]: notInModeMessage().replace(/^T/, "t"),
[SESSION_MODEL_FIXED]: "this chat keeps the model it started on. Start a new chat to use another model.",
+ // Strict sessions (model-modes/strict-sessions.mjs): the gateway holds a bound chat to its model and mode.
+ [MODEL_NOT_BOUND]: "this chat keeps the model it started on. Start a new chat to use another model.",
+ [MODE_NOT_BOUND]: "this chat keeps the project mode it started in. Start a new chat to change it.",
+ [SESSION_MODEL_USED]: "this chat already ran on another model. Start a new chat to use this one.",
};
+/** Refusals whose own message is shown as it is (the server's or the broker's words). */
+const OWN_WORDS = new Set([UPDATE_REQUIRED_CODE, MODEL_NOT_IN_MODE, SESSION_MODEL_FIXED, MODEL_NOT_BOUND, MODE_NOT_BOUND, SESSION_BINDING_CONFLICT, SESSION_MODEL_USED, VERIFICATION_REQUIRED]);
/** Readable copy for a gateway error code, or null for a code it does not know. */
export function gatewayErrorMessage(code: string, detail?: string | null): string | null {
@@ -352,7 +362,7 @@ function carriedFields(payload: Record<string, unknown>, nested: Record<string,
* check. Inside a stream (after any output) the engine takes an error frame
* for a passing fault and sends the request again, up to five times.
*/
-const FINAL_STREAM_CODES = new Set(["request_policy_refused", "session_quality_cap", "daily_grant_exhausted", "cyber_policy", MODEL_NOT_IN_MODE]);
+const FINAL_STREAM_CODES = new Set(["request_policy_refused", "session_quality_cap", "daily_grant_exhausted", "cyber_policy", MODEL_NOT_IN_MODE, MODEL_NOT_BOUND, MODE_NOT_BOUND, SESSION_MODEL_USED]);
/**
* A final refusal inside a stream as the frame the engine shows once and
@@ -680,7 +690,7 @@ function readableErrorBody(text: string, grant: string | null): { error: Record<
if (!code) return null;
const message = (grant && code === "daily_grant_exhausted" ? `omnirush.ai: ${grant.charAt(0).toLowerCase()}${grant.slice(1)}` : null)
// The server names the version to install, or the kind of project the model runs in; keep its words.
- ?? (code === UPDATE_REQUIRED_CODE || code === MODEL_NOT_IN_MODE || code === SESSION_MODEL_FIXED ? stringField(nested?.message) ?? stringField(payload.message) : null)
+ ?? (OWN_WORDS.has(code) ? stringField(nested?.message) ?? stringField(payload.message) : null)
?? gatewayErrorMessage(code, stringField(nested?.message))
?? (bareCode ? `omnirush.ai could not complete the model request (${code}).` : null);
if (!message) return null;
@@ -1258,6 +1268,16 @@ export class OmniRushGatewayBroker {
/** Each chat's model, from its first agent request (one model per chat; oldest first, bounded). */
private readonly sessionModels = new Map<string, string>();
private readonly onUpdateSignal?: (signal: GatewayUpdateSignal) => void;
+ private readonly chatPin?: BrokerOptions["chatPin"];
+ /** The strict sessions ({ path, header }) of the last capabilities answer (null: off, or an older server). */
+ private strictBind: { path: string; header: string } | null = null;
+ /** Strict sessions: each chat binds its model and mode once per process (model-modes/strict-sessions.mjs). */
+ private readonly bindSession = sessionBinder((path, payload, signal) => this.withDeviceBearer((state) => this.fetcher(new URL(path, state.gatewayUrl).toString(), {
+ method: "POST",
+ headers: { Authorization: `Bearer ${state.accessToken}`, "Content-Type": "application/json", Accept: "application/json" },
+ body: JSON.stringify(payload),
+ signal,
+ })).then(async (response) => ({ status: response.status, body: await response.json().catch(() => null) })));
private readonly reasoningSummaryFor: (model: string) => boolean | Promise<boolean>;
private readonly clientHeader: string | null;
private refreshInFlight: Promise<boolean> | null = null;
@@ -1299,6 +1319,7 @@ export class OmniRushGatewayBroker {
this.subagentModelRefused = options.subagentModelRefused;
this.modelInMode = options.modelInMode;
this.onUpdateSignal = options.onUpdateSignal;
+ this.chatPin = options.chatPin;
this.reasoningSummaryFor = options.reasoningSummaryFor ?? defaultReasoningSummaryFor;
}
@@ -1602,6 +1623,7 @@ export class OmniRushGatewayBroker {
if (settledKey && this.state?.gatewayUrl === gatewayUrl) {
this.capabilityFailure = null;
this.capabilityCache = { gatewayUrl, accountKey: settledKey, capabilities, expiresAt: Date.now() + TRACE_CAPABILITY_TTL_MS };
+ this.strictBind = strictSessions(capabilities);
}
return capabilities;
}
@@ -1731,6 +1753,8 @@ export class OmniRushGatewayBroker {
...(isRecord(payload.computer_use) ? { computer_use: payload.computer_use } : {}),
// The model provider lock (provider-lock.ts reads it; absent is locked).
...(isRecord(payload.providers) ? { providers: payload.providers } : {}),
+ // Strict sessions (model-modes/strict-sessions.mjs reads it; absent is no bind).
+ ...(isRecord(payload.strict_sessions) ? { strict_sessions: payload.strict_sessions } : {}),
};
} catch {
return null;
@@ -1942,6 +1966,10 @@ export class OmniRushGatewayBroker {
// One model per chat: a main chat's agent request on another model than its first is refused here.
const fixed = this.fixedModelRefusal(request, path, body);
if (fixed) return fixed;
+ // The last capabilities answer's switch: a model request never waits for one.
+ const strict = this.state ? this.strictBind : null;
+ const unbound = strict ? await this.strictBindRefusal(strict.path, request, path, body) : null;
+ if (unbound) return unbound;
const forwardedBody = path === "responses" && body !== undefined
? await withReasoningSummary(body, this.reasoningSummaryFor)
: body;
@@ -1953,7 +1981,7 @@ export class OmniRushGatewayBroker {
}
if (!this.state) break;
try {
- return await this.forward(request, path, forwardedBody, attempt === 0 ? accessToken : this.state.accessToken, requestId);
+ return await this.forward(request, path, forwardedBody, attempt === 0 ? accessToken : this.state.accessToken, requestId, strict?.header ?? null);
} catch (error) {
if (request.signal.aborted) throw error;
failure = fetchFailure(error);
@@ -1975,7 +2003,7 @@ export class OmniRushGatewayBroker {
);
}
- private forward(request: Request, path: string, body: ArrayBuffer | string | undefined, accessToken: string | undefined, requestId: string): Promise<Response> {
+ private forward(request: Request, path: string, body: ArrayBuffer | string | undefined, accessToken: string | undefined, requestId: string, strictHeader: string | null = null): Promise<Response> {
if (!this.state) throw new Error("OmniRush gateway credentials are unavailable");
const headers = new Headers();
headers.set("Authorization", `Bearer ${accessToken ?? this.state.accessToken}`);
@@ -1990,6 +2018,8 @@ export class OmniRushGatewayBroker {
}
// A box (sandbox) chat's request: the gateway judges its model in the box mode.
if (this.boxRequest(request)) headers.set(BOX_HEADER, "1");
+ // Strict sessions: every request of a chat says so (the gateway binds it itself if ours failed).
+ if (strictHeader && headers.has("x-omnirush-session-id")) headers.set(strictHeader, "1");
return this.fetcher(upstreamUrl(this.state.gatewayUrl, path), {
method: request.method,
headers,
@@ -2027,6 +2057,42 @@ export class OmniRushGatewayBroker {
return Response.json({ detail: SESSION_MODEL_FIXED, error: { type: "invalid_request_error", code: SESSION_MODEL_FIXED, message: `This chat runs on ${first}. Start a new chat to use ${model}.` } }, { status: 400, headers: { "x-should-retry": "false" } });
}
+ /**
+ * A chat's first agent request binds the chat (its pinned model, its mode,
+ * the box revision and the uploader's redaction policy); a sub-agent names
+ * its main chat. A conflict or a verification refusal is answered here and
+ * never sent; anything else goes on (model-modes/strict-sessions.mjs).
+ */
+ private async strictBindRefusal(bindPath: string, request: Request, path: string, body: ArrayBuffer | string | undefined): Promise<Response | null> {
+ const session = request.headers.get("x-omnirush-session-id");
+ if (body === undefined || path !== "responses" || !session) return null;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(typeof body === "string" ? body : new TextDecoder().decode(body));
+ } catch {
+ return null;
+ }
+ if (!isRecord(parsed) || typeof parsed.model !== "string" || !Array.isArray(parsed.tools) || parsed.tools.length === 0) return null;
+ const model = parsed.model.replace(/^omnirush\//, "");
+ const rootId = request.headers.get(PARENT_SESSION_HEADER);
+ const rootModel = rootId ? this.sessionModels.get(rootId) : null;
+ const rootPin = rootId ? this.chatPin?.(rootId) ?? null : null;
+ const outcome = await this.bindSession({
+ path: bindPath,
+ sessionId: session,
+ rootId,
+ model: this.sessionModels.get(session) ?? model,
+ mode: projectMode(this.boxRequest(request)),
+ revision: this.chatPin?.(session)?.revision ?? rootPin?.revision ?? null,
+ capturePolicy: redactionPolicy(),
+ root: rootId && rootModel ? { model: rootModel, mode: projectMode(rootPin?.box ?? this.boxSessions.has(rootId)), revision: rootPin?.revision ?? null } : null,
+ });
+ if (!("refused" in outcome)) return null;
+ this.log?.("info", "omnirush.ai refused this chat's binding; not sent", { code: outcome.refused.code });
+ const { code, message } = outcome.refused;
+ return Response.json({ detail: code, error: { type: "invalid_request_error", code, message } }, { status: code === VERIFICATION_REQUIRED ? 403 : 400, headers: { "x-should-retry": "false" } });
+ }
+
/** Whether a request comes from a box chat: marked so, or from a chat (or its main chat) marked earlier. */
private boxRequest(request: Request): boolean {
const sessions = [request.headers.get("x-omnirush-session-id"), request.headers.get(PARENT_SESSION_HEADER)].filter((id): id is string => Boolean(id));
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 2581a765..5417a5c2 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -1283,6 +1283,8 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
const entry = (await readOmniRushModelCatalog(config)).find((candidate) => candidate.id === model);
return !entry || modelAllowedIn(entry, projectMode(box));
},
+ // Strict sessions: a chat's bind names the box revision it started under.
+ chatPin: (sessionId) => boxServiceFor(config).chatPin(sessionId),
// The desktop's update gate (banner, blocked view); session uploads and
// project archives go on whatever it says.
...(config.omnirushGatewayCredentials?.onUpdateSignal ? { onUpdateSignal: config.omnirushGatewayCredentials.onUpdateSignal } : {}),
diff --git a/apps/server/src/session-uploader.ts b/apps/server/src/session-uploader.ts
index 0baa1455..56ac580f 100644
--- a/apps/server/src/session-uploader.ts
+++ b/apps/server/src/session-uploader.ts
@@ -888,6 +888,8 @@ export type TraceCapabilities = {
mcp?: Record<string, unknown>;
/** The model provider lock (provider-lock.ts): the block as the server sent it; absent is locked. */
providers?: Record<string, unknown>;
+ /** Strict sessions (model-modes/strict-sessions.mjs): the block as the server sent it; absent is no bind. */
+ strict_sessions?: Record<string, unknown>;
};