Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: sol model, ultra effort, collector v2, and account hardening

Samrat Talukdard6f9174d824f
diff --git a/.opencode/package-lock.json b/.opencode/package-lock.json
index ad431ccd..fe102832 100644
--- a/.opencode/package-lock.json
+++ b/.opencode/package-lock.json
@@ -5,7 +5,7 @@
"packages": {
"": {
"dependencies": {
- "@opencode-ai/plugin": "1.17.11"
+ "@opencode-ai/plugin": "1.18.18"
}
},
"node_modules/@ai-sdk/provider": {
@@ -99,20 +99,20 @@
]
},
"node_modules/@opencode-ai/plugin": {
- "version": "1.17.11",
- "resolved": "https://registry.npmjs.org/@opencode-ai/plugin/-/plugin-1.17.11.tgz",
- "integrity": "sha512-mE6SR1tVxL98zbZrlneqF/+dpIKLeZHKzWZy35Hq54uEnuCM1gKq3LK8F2PG2zMBDKQtz2fahEIksJ7svoPLLw==",
+ "version": "1.18.18",
+ "resolved": "https://registry.npmjs.org/@opencode-ai/plugin/-/plugin-1.18.18.tgz",
+ "integrity": "sha512-vqQeqJtn9c+J+tIQDzYk88xip/NVNN1hym1ATmckxo6zINHAoXoul4Sw/jgnvL00rLsfAvhja28qax4h3g/5Jg==",
"license": "MIT",
"dependencies": {
"@ai-sdk/provider": "3.0.8",
- "@opencode-ai/sdk": "1.17.11",
+ "@opencode-ai/sdk": "1.18.18",
"effect": "4.0.0-beta.83",
"zod": "4.1.8"
},
"peerDependencies": {
- "@opentui/core": ">=0.3.4",
- "@opentui/keymap": ">=0.3.4",
- "@opentui/solid": ">=0.3.4"
+ "@opentui/core": ">=0.4.5",
+ "@opentui/keymap": ">=0.4.5",
+ "@opentui/solid": ">=0.4.5"
},
"peerDependenciesMeta": {
"@opentui/core": {
@@ -127,9 +127,9 @@
}
},
"node_modules/@opencode-ai/sdk": {
- "version": "1.17.11",
- "resolved": "https://registry.npmjs.org/@opencode-ai/sdk/-/sdk-1.17.11.tgz",
- "integrity": "sha512-UdSwnNM4/cD5rHnI8O7VaHuiwYnsEOglpRPVeeYE2S5Nm1K34ijCyZGDvBecb0ShdBQgn49XvyQWJH6cREsIPw==",
+ "version": "1.18.18",
+ "resolved": "https://registry.npmjs.org/@opencode-ai/sdk/-/sdk-1.18.18.tgz",
+ "integrity": "sha512-zJlwXskIR47V1dkPJqeKBgq7nejG1uU8lJaGIGqbX3MWRCT8vKn0fEotbxuPCKnTdmWsDyNGNg9q1qIliDSMDA==",
"license": "MIT",
"dependencies": {
"cross-spawn": "7.0.6"
diff --git a/apps/app/src/app/constants.test.ts b/apps/app/src/app/constants.test.ts
index bceda495..9efa7c19 100644
--- a/apps/app/src/app/constants.test.ts
+++ b/apps/app/src/app/constants.test.ts
@@ -6,6 +6,8 @@ declare const expect: (value: unknown) => {
import {
DEFAULT_MODEL,
+ OMNIRUSH_MODEL_IDS,
+ isOmniRushModelID,
OMNIRUSH_EXTENSION_CATALOG,
filterOmniRushExtensionCatalogForPlatform,
resolveOmniRushExtensionCatalogPlatform,
@@ -21,6 +23,13 @@ describe("OmniRush.ai extension catalog platform filter", () => {
expect(DEFAULT_MODEL).toEqual({ providerID: "omnirush", modelID: "gpt-6-astra" });
});
+ test("recognises every omnirush.ai model, default first", () => {
+ expect([...OMNIRUSH_MODEL_IDS]).toEqual(["gpt-6-astra", "gpt-5.6-sol"]);
+ expect(isOmniRushModelID("gpt-5.6-sol")).toEqual(true);
+ expect(isOmniRushModelID("GPT-6-Astra")).toEqual(true);
+ expect(isOmniRushModelID("z-ai/glm-5.2")).toEqual(false);
+ });
+
test("resolves browser runtime to web and desktop runtime to OS", () => {
expect(resolveOmniRushExtensionCatalogPlatform("web", "macos")).toEqual("web");
expect(resolveOmniRushExtensionCatalogPlatform("desktop", "macos")).toEqual("darwin");
diff --git a/apps/app/src/app/constants.ts b/apps/app/src/app/constants.ts
index 2c6ab8db..dd296c59 100644
--- a/apps/app/src/app/constants.ts
+++ b/apps/app/src/app/constants.ts
@@ -18,11 +18,24 @@ export const VARIANT_PREF_KEY = "omnirush.modelVariant";
export { LANGUAGE_PREF_KEY } from "../i18n";
export const HIDE_TITLEBAR_PREF_KEY = "omnirush.hideTitlebar";
+/** Models served by the omnirush.ai account route; the first entry is the default. */
+export const OMNIRUSH_MODEL_IDS = ["gpt-6-astra", "gpt-5.6-sol"] as const;
+
export const DEFAULT_MODEL: ModelRef = {
providerID: "omnirush",
- modelID: "gpt-6-astra",
+ modelID: OMNIRUSH_MODEL_IDS[0],
};
+export function isOmniRushModelID(modelID: string): boolean {
+ return (OMNIRUSH_MODEL_IDS as readonly string[]).includes(modelID.trim().toLowerCase());
+}
+
+/**
+ * Effort levels offered for every omnirush.ai model, in picker order. Must
+ * match the variants the server's runtime config declares for the models.
+ */
+export const OMNIRUSH_REASONING_EFFORTS = ["low", "high", "xhigh", "ultra"] as const;
+
export const SUGGESTED_PLUGINS: SuggestedPlugin[] = [];
export type ExtensionKind = "mcp" | "plugin" | "skill" | "ui-control" | "extension";
diff --git a/apps/app/src/app/lib/model-behavior.ts b/apps/app/src/app/lib/model-behavior.ts
index 3d5e858c..f059aef2 100644
--- a/apps/app/src/app/lib/model-behavior.ts
+++ b/apps/app/src/app/lib/model-behavior.ts
@@ -1,5 +1,6 @@
import type { ProviderListItem } from "../types";
import type { ModelBehaviorOption } from "../types";
+import { OMNIRUSH_REASONING_EFFORTS } from "../constants";
import { t } from "../../i18n";
type ProviderModel = ProviderListItem["models"][string];
@@ -11,6 +12,7 @@ const WELL_KNOWN_VARIANT_ORDER = [
"medium",
"high",
"xhigh",
+ "ultra",
"max",
] as const;
@@ -22,6 +24,7 @@ const VARIANT_DEFAULT_SCORE: Record<string, number> = {
medium: VARIANT_DEFAULT_TARGET,
high: 4,
xhigh: 5,
+ ultra: 6,
max: 6,
};
@@ -106,16 +109,27 @@ const providerFamily = (providerID: string, providerName?: string | null) => {
return normalizedId;
};
+const isOmniRushProvider = (providerID: string) => providerID.trim().toLowerCase() === "omnirush";
+
const usesGlmDisplayAliases = (
- _providerID: string,
+ providerID: string,
model: ProviderModel,
_providerName?: string | null,
) => {
- return [model.id, model.name].some(
+ return !isOmniRushProvider(providerID) && [model.id, model.name].some(
(value) => value?.trim().toLowerCase().includes("gpt") === true,
);
};
+/**
+ * omnirush.ai models offer exactly the contract's effort levels. The engine
+ * merges its own OpenAI defaults (none, minimal, medium, max) into a reasoning
+ * model's variants, so the reported keys are filtered to the allow-list rather
+ * than trusted, which also keeps the picker default at "high".
+ */
+const omnirushVariantKeys = (keys: string[]) =>
+ keys.filter((key) => (OMNIRUSH_REASONING_EFFORTS as readonly string[]).includes(key));
+
const getBehaviorTitle = (
providerID: string,
model: ProviderModel,
@@ -186,7 +200,7 @@ const getVariantDescription = (
if (key === "high") return family === "anthropic"
? t("model_behavior.desc_high_anthropic")
: t("model_behavior.desc_high");
- if (key === "xhigh" || key === "max") return family === "anthropic"
+ if (key === "xhigh" || key === "ultra" || key === "max") return family === "anthropic"
? t("model_behavior.desc_max_anthropic")
: t("model_behavior.desc_max");
return t("model_behavior.desc_generic", { label: label.toLowerCase() });
@@ -198,9 +212,11 @@ export const getModelBehaviorOptions = (
providerName?: string | null,
): ModelBehaviorOption[] => {
const reportedVariantKeys = sortVariantKeys(getVariantKeys(model));
- const variantKeys = usesGlmDisplayAliases(providerID, model, providerName)
- ? reportedVariantKeys.filter((key) => key === "low" || key === "high" || key === "xhigh")
- : reportedVariantKeys;
+ const variantKeys = isOmniRushProvider(providerID)
+ ? omnirushVariantKeys(reportedVariantKeys)
+ : usesGlmDisplayAliases(providerID, model, providerName)
+ ? reportedVariantKeys.filter((key) => key === "low" || key === "high" || key === "xhigh")
+ : reportedVariantKeys;
if (!variantKeys.length) return [];
return variantKeys.map((key) => {
const label = getVariantLabel(key);
diff --git a/apps/app/src/react-app/domains/session/chat/session-empty-hero.tsx b/apps/app/src/react-app/domains/session/chat/session-empty-hero.tsx
index 84dfbdf1..f6ca7e6d 100644
--- a/apps/app/src/react-app/domains/session/chat/session-empty-hero.tsx
+++ b/apps/app/src/react-app/domains/session/chat/session-empty-hero.tsx
@@ -48,35 +48,35 @@ type TimeGreeting = {
export function greetingForLocalHour(hour: number): TimeGreeting {
if (hour < 5) {
return {
- title: "still up? let's make it count 🌙",
- subtitle: "tell me what we're building",
+ title: "what would you like to work on?",
+ subtitle: "describe the outcome you need",
};
}
if (hour < 12) {
return {
- title: "good morning, let's make something cool ☀️",
+ title: "good morning. how can I help?",
subtitle: "what are we getting done?",
};
}
if (hour < 17) {
return {
- title: "good afternoon, let's cook ✨",
+ title: "good afternoon. how can I help?",
subtitle: "what should we tackle?",
};
}
if (hour < 22) {
return {
- title: "good evening, ready to make some magic? 🌙",
+ title: "good evening. how can I help?",
subtitle: "what are we getting done?",
};
}
return {
- title: "late-night mode, let's ship something 🌙",
- subtitle: "what are we building?",
+ title: "what would you like to work on?",
+ subtitle: "describe the outcome you need",
};
}
diff --git a/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx b/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx
index bd51e1dd..475d6848 100644
--- a/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx
+++ b/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx
@@ -1003,10 +1003,10 @@ function NativeAccountFooter({ onOpenAccountSettings }: { onOpenAccountSettings:
const accountDetail = usage
? `${compactTokenCount(usage.remainingTokens)} tokens left today`
: connected
- ? "Astra ready"
+ ? "omnirush.ai models ready"
: status?.reauthorizationRequired
? "Sign in again to continue"
- : "Use Astra with your account";
+ : "Use omnirush.ai models with your account";
return (
<SidebarFooter className="border-t border-sidebar-border/60 p-1.5 pe-0">
diff --git a/apps/app/src/react-app/domains/settings/pages/general-view.tsx b/apps/app/src/react-app/domains/settings/pages/general-view.tsx
index 27a8da95..a011ba16 100644
--- a/apps/app/src/react-app/domains/settings/pages/general-view.tsx
+++ b/apps/app/src/react-app/domains/settings/pages/general-view.tsx
@@ -101,7 +101,7 @@ export function GeneralSettingsView(props: GeneralSettingsViewProps) {
try {
await omnirushAccountConnect();
setAccount(await omnirushAccountStatus());
- setAccountMessage("Account connected. Astra is ready.");
+ setAccountMessage("Account connected. omnirush.ai models are ready.");
} catch (error) {
setAccountMessage(error instanceof Error ? error.message : "The account could not be connected.");
} finally {
@@ -112,9 +112,11 @@ export function GeneralSettingsView(props: GeneralSettingsViewProps) {
async function signOutAccount() {
setAccountBusy(true);
try {
- await omnirushAccountSignOut();
+ const result = await omnirushAccountSignOut();
setAccount({ connected: false, gatewayConfigured: account?.gatewayConfigured ?? false });
- setAccountMessage("Signed out on this Mac.");
+ setAccountMessage(result.remoteRevoked
+ ? "Signed out on this Mac and revoked its device session."
+ : "Signed out on this Mac. The remote session could not be reached.");
} finally {
setAccountBusy(false);
}
@@ -142,7 +144,7 @@ export function GeneralSettingsView(props: GeneralSettingsViewProps) {
{accountMessage || (account.connected
? account.usage
? `${compactTokenCount(account.usage.remainingTokens)} of ${compactTokenCount(account.usage.tokenLimit)} tokens left today`
- : "Astra is ready on this Mac."
+ : "omnirush.ai models are ready on this Mac."
: account.gatewayConfigured
? account.reauthorizationRequired
? "Your session expired. Sign in again to continue."
diff --git a/apps/app/src/react-app/kernel/model-config.ts b/apps/app/src/react-app/kernel/model-config.ts
index a00a56d1..747e00ec 100644
--- a/apps/app/src/react-app/kernel/model-config.ts
+++ b/apps/app/src/react-app/kernel/model-config.ts
@@ -5,6 +5,7 @@ import {
MODEL_PREF_KEY,
SESSION_MODEL_PREF_KEY,
VARIANT_PREF_KEY,
+ isOmniRushModelID,
} from "../../app/constants";
import type { ModelRef } from "../../app/types";
import {
@@ -156,8 +157,9 @@ export function readStoredDefaultModel(): ModelRef {
const stored = window.localStorage.getItem(MODEL_PREF_KEY);
const parsed = parseModelRef(stored);
// Public OmniRush releases previously persisted a retired managed model.
- // Keep external provider choices, but migrate the built-in route to Astra.
- if (parsed?.providerID === "omnirush" && parsed.modelID !== DEFAULT_MODEL.modelID) {
+ // Keep external provider choices and every current omnirush.ai model, but
+ // migrate retired built-in routes to the default model.
+ if (parsed?.providerID === "omnirush" && !isOmniRushModelID(parsed.modelID)) {
writeStoredDefaultModel(DEFAULT_MODEL);
return DEFAULT_MODEL;
}
diff --git a/apps/app/tests/model-behavior.test.ts b/apps/app/tests/model-behavior.test.ts
index c2a364c9..089ef692 100644
--- a/apps/app/tests/model-behavior.test.ts
+++ b/apps/app/tests/model-behavior.test.ts
@@ -1,8 +1,10 @@
import { describe, expect, test } from "bun:test";
import type { ProviderListItem } from "../src/app/types";
+import { OMNIRUSH_REASONING_EFFORTS } from "../src/app/constants";
import {
getModelBehaviorOptions,
+ getModelBehaviorSummary,
nextModelBehaviorValue,
previousModelBehaviorValue,
} from "../src/app/lib/model-behavior";
@@ -77,7 +79,86 @@ const model: ProviderModel = {
},
};
+const omnirushModel = (id: string, name: string): ProviderModel => ({
+ ...model,
+ id,
+ name,
+ providerID: "omnirush",
+ api: { id, url: "http://127.0.0.1:8090/omnirush-gateway/v1", npm: "@ai-sdk/openai" },
+ variants: {
+ low: { reasoning_effort: "low" },
+ high: { reasoning_effort: "high" },
+ xhigh: { reasoning_effort: "xhigh" },
+ ultra: { reasoning_effort: "ultra" },
+ },
+});
+
+const OMNIRUSH_MODELS = [
+ omnirushModel("gpt-6-astra", "GPT 6 Astra"),
+ omnirushModel("gpt-5.6-sol", "GPT-5.6 Sol"),
+];
+
describe("model behavior options", () => {
+ test("offers low, high, xhigh and ultra for every omnirush.ai model", () => {
+ for (const internal of OMNIRUSH_MODELS) {
+ const options = getModelBehaviorOptions("omnirush", internal, "omnirush.ai");
+ expect(options.map(({ value, label }) => ({ value, label }))).toEqual([
+ { value: "low", label: "Low" },
+ { value: "high", label: "High" },
+ { value: "xhigh", label: "Xhigh" },
+ { value: "ultra", label: "Ultra" },
+ ]);
+ expect(nextModelBehaviorValue(options, "xhigh")).toBe("ultra");
+ expect(nextModelBehaviorValue(options, "ultra")).toBe("low");
+ expect(previousModelBehaviorValue(options, "low")).toBe("ultra");
+
+ const summary = getModelBehaviorSummary("omnirush", internal, "ultra", "omnirush.ai");
+ expect(summary.value).toBe("ultra");
+ expect(summary.label).toBe("Ultra");
+ expect(getModelBehaviorSummary("omnirush", internal, null, "omnirush.ai").value).toBe("high");
+ }
+ });
+
+ test("hides the effort levels the engine adds on its own to omnirush.ai models", () => {
+ expect([...OMNIRUSH_REASONING_EFFORTS]).toEqual(["low", "high", "xhigh", "ultra"]);
+ for (const internal of OMNIRUSH_MODELS) {
+ // What GET /config/providers reports once the engine has merged its
+ // OpenAI reasoning defaults into the configured variants.
+ const reported: ProviderModel = {
+ ...internal,
+ variants: {
+ ...internal.variants,
+ none: { reasoningEffort: "none", reasoningSummary: "auto" },
+ minimal: { reasoningEffort: "minimal" },
+ medium: { reasoningEffort: "medium", reasoningSummary: "auto" },
+ max: { reasoningEffort: "max" },
+ },
+ };
+ const options = getModelBehaviorOptions("omnirush", reported, "omnirush.ai");
+ expect(options.map((option) => option.value)).toEqual(["low", "high", "xhigh", "ultra"]);
+ expect(getModelBehaviorSummary("omnirush", reported, null, "omnirush.ai").value).toBe("high");
+ expect(getModelBehaviorSummary("omnirush", reported, "medium", "omnirush.ai").value).toBe("high");
+ expect(getModelBehaviorSummary("omnirush", reported, "ultra", "omnirush.ai").value).toBe("ultra");
+ }
+ });
+
+ test("shows both omnirush.ai models under the omnirush.ai provider with their display names", () => {
+ expect(OMNIRUSH_MODELS.map((internal) => resolveModelDisplayName(internal.id, internal.name)))
+ .toEqual(["GPT 6 Astra", "GPT-5.6 Sol"]);
+ for (const internal of OMNIRUSH_MODELS) {
+ expect(resolveModelProviderDisplayName("omnirush", internal.id, "omnirush.ai", internal.name)).toBe("omnirush.ai");
+ expect(resolveModelProviderIconId("omnirush", internal.id, internal.name)).toBe("omnirush");
+ }
+ expect(dedupeModelOptions([
+ { providerID: "omnirush", modelID: "gpt-6-astra" },
+ { providerID: "omnirush", modelID: "gpt-5.6-sol" },
+ { providerID: "omnirush", modelID: "gpt-6-astra" },
+ ])).toEqual([
+ { providerID: "omnirush", modelID: "gpt-6-astra" },
+ { providerID: "omnirush", modelID: "gpt-5.6-sol" },
+ ]);
+ });
+
test("uses only the raw effort values reported by the model", () => {
const options = getModelBehaviorOptions("openai", model);
@@ -91,6 +172,7 @@ describe("model behavior options", () => {
test("keeps model and provider identities truthful", () => {
expect(resolveModelDisplayName("gpt-6-astra", "GPT-6 Astra")).toBe("GPT 6 Astra");
expect(resolveModelProviderDisplayName("omnirush", "gpt-6-astra")).toBe("omnirush.ai");
+ expect(resolveModelProviderDisplayName("omnirush", "gpt-5.6-sol")).toBe("omnirush.ai");
expect(resolveModelDisplayName("gpt-5.6-sol", "GPT-5.6 Sol")).toBe("GPT-5.6 Sol");
expect(resolveModelDisplayName("gpt-5.6-terra", "GPT-5.6 Terra")).toBe("GPT-5.6 Terra");
expect(resolveModelDisplayName("claude-sonnet-4", "Claude Sonnet 4")).toBe("Claude Sonnet 4");
diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjs
index 1dfc2eef..258bf643 100644
--- a/apps/desktop/electron/main.mjs
+++ b/apps/desktop/electron/main.mjs
@@ -2057,9 +2057,9 @@ const desktopCommandHandlers = {
return result;
},
"omnirushAccountSignOut": async () => {
- await omnirushAccountStore.clear();
+ const result = await omnirushAccountStore.clear();
await runtimeManager.omnirushServerRestart({});
- return { connected: false };
+ return { connected: false, remoteRevoked: result.remoteRevoked };
},
"automationRunnerConfigure": async (event, ...args) => {
return desktopAutomationRunner.configure(args[0] ?? null);
diff --git a/apps/desktop/electron/omnirush-account.mjs b/apps/desktop/electron/omnirush-account.mjs
index d3451823..0b4f31fd 100644
--- a/apps/desktop/electron/omnirush-account.mjs
+++ b/apps/desktop/electron/omnirush-account.mjs
@@ -10,7 +10,7 @@ const KEYCHAIN_SERVICES = {
accessToken: "ai.omnirush.desktop.gateway-access",
refreshToken: "ai.omnirush.desktop.gateway-refresh",
};
-const DEFAULT_GATEWAY_URL = "https://api.omnirush.ai/omnirush/v1";
+const DEFAULT_GATEWAY_URL = "https://omnirush.ai/omnirush/v1";
const DEV_GATEWAY_URL = "http://localhost:8090/omnirush/v1";
function normalizeCredential(value) {
@@ -102,6 +102,7 @@ export function createDesktopOmniRushAccountStore({
sleep = (milliseconds) => new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds)),
}) {
let cached = null;
+ let refreshInFlight = null;
const signedOutPath = `${filePath}.signed-out`;
async function safeStorage() {
@@ -168,30 +169,57 @@ export function createDesktopOmniRushAccountStore({
}
async function configuredGatewayUrl() {
+ // Development builds keep using omnirush.ai. Only an explicit
+ // OMNIRUSH_GATEWAY_URL, or OMNIRUSH_DEV_MODE=1 together with
+ // OMNIRUSH_LOCAL_API=1, points the account service at a local API.
+ const localApiSelected = env.OMNIRUSH_DEV_MODE === "1" && env.OMNIRUSH_LOCAL_API === "1";
return normalizeGatewayUrl(env.OMNIRUSH_GATEWAY_URL)
?? normalizeGatewayUrl(await readMacKeychain(KEYCHAIN_SERVICES.gatewayUrl, platform))
- ?? (env.OMNIRUSH_DEV_MODE === "1" ? DEV_GATEWAY_URL : DEFAULT_GATEWAY_URL);
+ ?? (localApiSelected ? DEV_GATEWAY_URL : DEFAULT_GATEWAY_URL);
}
async function refresh(credentials) {
- const refreshUrl = controlPlaneBase(credentials.gatewayUrl);
- refreshUrl.pathname += "/device/refresh";
- const response = await fetchImpl(refreshUrl, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ refresh_token: credentials.refreshToken }),
- signal: AbortSignal.timeout(20_000),
- });
- if (!response.ok) return null;
- const payload = await response.json();
- const refreshed = validCredentials({
- gatewayUrl: payload.gateway_url ?? credentials.gatewayUrl,
- accessToken: payload.access_token,
- refreshToken: payload.refresh_token,
+ if (refreshInFlight) return refreshInFlight;
+ refreshInFlight = (async () => {
+ const refreshUrl = controlPlaneBase(credentials.gatewayUrl);
+ refreshUrl.pathname += "/device/refresh";
+ const response = await fetchImpl(refreshUrl, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ refresh_token: credentials.refreshToken }),
+ signal: AbortSignal.timeout(20_000),
+ });
+ if (response.status === 401 || response.status === 403) return null;
+ if (!response.ok) throw new Error(`Account refresh unavailable (${response.status})`);
+ const payload = await response.json();
+ const refreshed = validCredentials({
+ gatewayUrl: payload.gateway_url ?? credentials.gatewayUrl,
+ accessToken: payload.access_token,
+ refreshToken: payload.refresh_token,
+ });
+ if (!refreshed) throw new Error("Account service returned invalid credentials");
+ await save(refreshed);
+ return refreshed;
+ })().finally(() => {
+ refreshInFlight = null;
});
- if (!refreshed) return null;
- await save(refreshed);
- return refreshed;
+ return refreshInFlight;
+ }
+
+ async function remoteLogout(credentials) {
+ const logoutUrl = controlPlaneBase(credentials.gatewayUrl);
+ logoutUrl.pathname += "/device/logout";
+ try {
+ const response = await fetchImpl(logoutUrl, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ refresh_token: credentials.refreshToken }),
+ signal: AbortSignal.timeout(20_000),
+ });
+ return response.ok;
+ } catch {
+ return false;
+ }
}
async function fetchProfile(credentials, allowRefresh = true) {
@@ -274,6 +302,7 @@ export function createDesktopOmniRushAccountStore({
};
} catch (error) {
if (error instanceof InvalidAccountCredentialsError) {
+ await clear({ revokeRemote: false });
return {
connected: false,
gatewayConfigured,
@@ -297,10 +326,16 @@ export function createDesktopOmniRushAccountStore({
}
}
- async function clear() {
+ async function clear({ revokeRemote = true } = {}) {
+ const credentials = cached ?? await load();
+ const remoteRevoked = !credentials || !revokeRemote
+ ? !credentials || !revokeRemote
+ : await remoteLogout(credentials);
cached = null;
await rm(filePath, { force: true });
+ await mkdir(path.dirname(signedOutPath), { recursive: true });
await writeFile(signedOutPath, "signed-out\n", { mode: 0o600 });
+ return { remoteRevoked };
}
return { load, save, authorize, status, clear };
diff --git a/apps/desktop/electron/omnirush-account.test.mjs b/apps/desktop/electron/omnirush-account.test.mjs
index 00196bce..6d78dd65 100644
--- a/apps/desktop/electron/omnirush-account.test.mjs
+++ b/apps/desktop/electron/omnirush-account.test.mjs
@@ -83,6 +83,45 @@ test("device authorization polls, encrypts, and restores the account", async ()
]);
});
+async function authorizeOrigin(env) {
+ const requested = [];
+ const options = await storeOptions({
+ env,
+ fetchImpl: async (url) => {
+ requested.push(String(url));
+ return Response.json({ detail: "unavailable" }, { status: 503 });
+ },
+ });
+ const store = createDesktopOmniRushAccountStore(options);
+ await assert.rejects(store.authorize({ gatewayUrl: undefined, deviceName: "Test Mac", openVerification: async () => undefined }));
+ assert.equal(requested.length, 1);
+ return requested[0];
+}
+
+test("defaults the account service to omnirush.ai, even in development mode", async () => {
+ assert.equal(await authorizeOrigin({}), "https://omnirush.ai/omnirush/device/authorize");
+ assert.equal(await authorizeOrigin({ OMNIRUSH_DEV_MODE: "1" }), "https://omnirush.ai/omnirush/device/authorize");
+ assert.equal(await authorizeOrigin({ OMNIRUSH_LOCAL_API: "1" }), "https://omnirush.ai/omnirush/device/authorize");
+});
+
+test("selects the local API only with OMNIRUSH_DEV_MODE=1 and OMNIRUSH_LOCAL_API=1", async () => {
+ assert.equal(
+ await authorizeOrigin({ OMNIRUSH_DEV_MODE: "1", OMNIRUSH_LOCAL_API: "1" }),
+ "http://localhost:8090/omnirush/device/authorize",
+ );
+});
+
+test("an explicit OMNIRUSH_GATEWAY_URL always wins", async () => {
+ assert.equal(
+ await authorizeOrigin({ OMNIRUSH_GATEWAY_URL: "https://staging.example/omnirush/v1" }),
+ "https://staging.example/omnirush/device/authorize",
+ );
+ assert.equal(
+ await authorizeOrigin({ OMNIRUSH_DEV_MODE: "1", OMNIRUSH_LOCAL_API: "1", OMNIRUSH_GATEWAY_URL: "https://staging.example/omnirush/v1" }),
+ "https://staging.example/omnirush/device/authorize",
+ );
+});
+
test("profile lookup refreshes an expired device credential and persists the rotation", async () => {
const options = await storeOptions({
env: {
@@ -127,6 +166,7 @@ test("profile lookup refreshes an expired device credential and persists the rot
});
test("sign out prevents legacy credentials from being imported again", async () => {
+ let logoutBody = null;
const options = await storeOptions({
env: {
OMNIRUSH_DEV_MODE: "1",
@@ -134,24 +174,51 @@ test("sign out prevents legacy credentials from being imported again", async ()
OMNIRUSH_ACCESS_TOKEN: "legacy-access",
OMNIRUSH_REFRESH_TOKEN: "legacy-refresh",
},
- fetchImpl: async (url) => {
- if (new URL(url).pathname.endsWith("/device/me")) {
+ fetchImpl: async (url, init = {}) => {
+ const pathname = new URL(url).pathname;
+ if (pathname.endsWith("/device/me")) {
return Response.json({
status: "active",
usage: { token_limit: 100000, used_tokens: 0, remaining_tokens: 100000 },
});
}
+ if (pathname.endsWith("/device/logout")) {
+ logoutBody = JSON.parse(init.body);
+ return new Response(null, { status: 204 });
+ }
throw new Error(`Unexpected request ${url}`);
},
});
const store = createDesktopOmniRushAccountStore(options);
assert.equal((await store.status()).connected, true);
- await store.clear();
+ const result = await store.clear();
+ assert.equal(result.remoteRevoked, true);
+ assert.deepEqual(logoutBody, { refresh_token: "legacy-refresh" });
const restarted = createDesktopOmniRushAccountStore(options);
assert.equal((await restarted.status()).connected, false);
});
+test("sign out clears the local account when remote revocation is unavailable", async () => {
+ const options = await storeOptions({
+ env: {
+ OMNIRUSH_DEV_MODE: "1",
+ OMNIRUSH_GATEWAY_URL: "http://localhost:8090/omnirush/v1",
+ OMNIRUSH_ACCESS_TOKEN: "legacy-access",
+ OMNIRUSH_REFRESH_TOKEN: "legacy-refresh",
+ },
+ fetchImpl: async (url) => {
+ if (new URL(url).pathname.endsWith("/device/logout")) throw new Error("offline");
+ return Response.json({ email: "[email protected]", status: "active" });
+ },
+ });
+ const store = createDesktopOmniRushAccountStore(options);
+ assert.equal((await store.status()).connected, true);
+ const result = await store.clear();
+ assert.equal(result.remoteRevoked, false);
+ assert.equal((await createDesktopOmniRushAccountStore(options).status()).connected, false);
+});
+
test("marks an irrecoverably expired device session as signed out", async () => {
const options = await storeOptions({
env: {
diff --git a/apps/desktop/electron/runtime.mjs b/apps/desktop/electron/runtime.mjs
index e7993efc..63eabb41 100644
--- a/apps/desktop/electron/runtime.mjs
+++ b/apps/desktop/electron/runtime.mjs
@@ -1994,6 +1994,7 @@ export function createRuntimeManager({
? {
...gatewayCredentials,
persist: (credentials) => omnirushGatewayCredentials.save(credentials),
+ invalidate: () => omnirushGatewayCredentials.clear({ revokeRemote: false }),
}
: undefined,
});
diff --git a/apps/desktop/scripts/electron-dev.mjs b/apps/desktop/scripts/electron-dev.mjs
index 16c428c0..a80cea60 100644
--- a/apps/desktop/scripts/electron-dev.mjs
+++ b/apps/desktop/scripts/electron-dev.mjs
@@ -12,7 +12,8 @@ const electronHelperDir = resolve(desktopRoot, "resources", "helpers");
// Browser automation is approval-free in local development unless explicitly
// disabled. Set this here as well as in the workspace scripts so direct
// `@omnirush/desktop` launches behave the same as `pnpm dev` and
-// `pnpm dev:electron`.
+// `pnpm dev:electron`. Dev mode alone keeps the omnirush.ai account service;
+// export OMNIRUSH_LOCAL_API=1 (or OMNIRUSH_GATEWAY_URL) to target a local API.
process.env.OMNIRUSH_DEV_MODE ??= "1";
process.env.OMNIRUSH_BROWSER_AUTO_APPROVE ??= "1";
diff --git a/apps/server/package.json b/apps/server/package.json
index d99c870e..439e498a 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -12,7 +12,7 @@
"test:coverage": "bun --conditions=development test --coverage --coverage-reporter=text --coverage-reporter=lcov --coverage-dir=coverage",
"test:artifacts": "bun --conditions=development test src/artifact-files.e2e.test.ts src/workspace-init.test.ts src/server.normalizeWorkspaceRelativePath.test.ts",
"build:enterprise-mcp-client": "pnpm --filter @omnirush/enterprise-mcp-client build",
- "build": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && tsc -p tsconfig.json && bun build src/opencode-plugins/managed-policy-next.ts src/opencode-plugins/managed-policy.ts src/opencode-plugins/omnirush-chrome-devtools.ts src/opencode-plugins/omnirush-extensions-preview.ts src/opencode-plugins/omnirush-capabilities-knowledge.ts src/opencode-plugins/omnirush-office-attachments.ts src/opencode-plugins/omnirush-spreadsheets.ts src/opencode-plugins/omnirush-pdf-attachments.ts src/opencode-plugins/omnirush-anthropic-adaptive-thinking.ts src/opencode-plugins/omnirush-anthropic-tool-schema.ts src/opencode-plugins/omnirush-title-recovery.ts --root src/opencode-plugins --outdir dist/opencode-plugins --target node --format esm && node scripts/copy-pdfium-wasm.mjs dist/opencode-plugins",
+ "build": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && tsc -p tsconfig.json && bun build src/opencode-plugins/managed-policy-next.ts src/opencode-plugins/managed-policy.ts src/opencode-plugins/omnirush-chrome-devtools.ts src/opencode-plugins/omnirush-extensions-preview.ts src/opencode-plugins/omnirush-capabilities-knowledge.ts src/opencode-plugins/omnirush-office-attachments.ts src/opencode-plugins/omnirush-spreadsheets.ts src/opencode-plugins/omnirush-pdf-attachments.ts src/opencode-plugins/omnirush-anthropic-adaptive-thinking.ts src/opencode-plugins/omnirush-anthropic-tool-schema.ts src/opencode-plugins/omnirush-title-recovery.ts src/opencode-plugins/omnirush-reasoning-effort.ts --root src/opencode-plugins --outdir dist/opencode-plugins --target node --format esm && node scripts/copy-pdfium-wasm.mjs dist/opencode-plugins",
"build:bin": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && bun build --compile src/cli.ts --outfile dist/bin/omnirush-server",
"build:bin:all": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && bun ./script/build.ts --outdir dist/bin --target bun-darwin-arm64 --target bun-darwin-x64 --target bun-linux-x64 --target bun-linux-arm64 --target bun-windows-x64 --target bun-windows-arm64",
"prepare:npm": "pnpm build:bin && node scripts/publish-npm.mjs --prepare-only",
diff --git a/apps/server/src/omnirush-extensions-plugin-path.ts b/apps/server/src/omnirush-extensions-plugin-path.ts
index 42c54639..6eeb7f5c 100644
--- a/apps/server/src/omnirush-extensions-plugin-path.ts
+++ b/apps/server/src/omnirush-extensions-plugin-path.ts
@@ -40,3 +40,4 @@ export const omnirushOfficeAttachmentsPluginPath = () => omnirushPluginPath("omn
export const omnirushSpreadsheetsPluginPath = () => omnirushPluginPath("omnirush-spreadsheets");
export const omnirushPdfAttachmentsPluginPath = () => omnirushPluginPath("omnirush-pdf-attachments");
export const omnirushTitleRecoveryPluginPath = () => omnirushPluginPath("omnirush-title-recovery");
+export const omnirushReasoningEffortPluginPath = () => omnirushPluginPath("omnirush-reasoning-effort");
diff --git a/apps/server/src/omnirush-gateway-broker.test.ts b/apps/server/src/omnirush-gateway-broker.test.ts
index 1e981f6a..557d453a 100644
--- a/apps/server/src/omnirush-gateway-broker.test.ts
+++ b/apps/server/src/omnirush-gateway-broker.test.ts
@@ -1,8 +1,37 @@
import { describe, expect, test } from "bun:test";
import { OmniRushGatewayBroker } from "./omnirush-gateway-broker.js";
+import { OmniRushReasoningEffort } from "./opencode-plugins/omnirush-reasoning-effort.js";
import type { OmniRushGatewayCredentials } from "./types.js";
+type UpstreamCall = { body: Record<string, unknown>; headers: Headers };
+
+function capturingBroker(calls: UpstreamCall[]) {
+ return new OmniRushGatewayBroker({
+ credentials: {
+ gatewayUrl: "https://gateway.example/omnirush/v1",
+ accessToken: "access-token",
+ refreshToken: "refresh-token",
+ },
+ engineToken: "local-engine-token",
+ fetch: async (_input, init) => {
+ // Untouched bodies are forwarded as the original ArrayBuffer; injected ones as JSON text.
+ const raw = init?.body;
+ const text = typeof raw === "string" ? raw : new TextDecoder().decode(raw as ArrayBuffer);
+ calls.push({ body: JSON.parse(text), headers: new Headers(init?.headers) });
+ return Response.json({ output: [] });
+ },
+ });
+}
+
+function gatewayRequest(body: Record<string, unknown>, headers: Record<string, string> = {}, path = "responses") {
+ return new Request(`http://127.0.0.1/omnirush-gateway/v1/${path}`, {
+ method: "POST",
+ headers: { Authorization: "Bearer local-engine-token", "Content-Type": "application/json", ...headers },
+ body: JSON.stringify(body),
+ });
+}
+
describe("OmniRush gateway broker", () => {
test("refreshes one expired credential and retries concurrent requests with the rotated token", async () => {
let refreshCalls = 0;
@@ -63,5 +92,83 @@ describe("OmniRush gateway broker", () => {
}), "chat/completions");
expect(response.status).toBe(404);
});
-});
+ test("invalidates a revoked device session and returns a professional sign-in error", async () => {
+ let invalidated = 0;
+ const broker = new OmniRushGatewayBroker({
+ credentials: {
+ gatewayUrl: "https://gateway.example/omnirush/v1",
+ accessToken: "revoked-access",
+ refreshToken: "revoked-refresh",
+ invalidate: async () => { invalidated += 1; },
+ },
+ engineToken: "local-engine-token",
+ fetch: async (input) => {
+ const pathname = new URL(String(input)).pathname;
+ if (pathname.endsWith("/device/refresh")) {
+ return Response.json({ detail: "device_token_invalid" }, { status: 401 });
+ }
+ return Response.json({ detail: "device_token_invalid" }, { status: 401 });
+ },
+ });
+ const response = await broker.handle(new Request("http://127.0.0.1/omnirush-gateway/v1/responses", {
+ method: "POST",
+ headers: { Authorization: "Bearer local-engine-token", "Content-Type": "application/json" },
+ body: JSON.stringify({ model: "gpt-6-astra", input: "test" }),
+ }), "responses");
+
+ expect(response.status).toBe(401);
+ expect(await response.json()).toEqual({
+ error: {
+ message: "Your omnirush.ai session has expired. Sign in again from Settings.",
+ type: "authentication_error",
+ code: "omnirush_account_required",
+ },
+ });
+ await Bun.sleep(1);
+ expect(invalidated).toBe(1);
+ });
+
+ test("sends the ultra variant selected in the desktop as reasoning.effort", async () => {
+ const calls: UpstreamCall[] = [];
+ const broker = capturingBroker(calls);
+ // The engine merges the variant options and runs the plugin hooks before
+ // its OpenAI adapter builds the body; for gpt-6-astra that adapter emits
+ // no reasoning block at all, so only the private header carries the level.
+ const hooks = await OmniRushReasoningEffort();
+ const headers: { headers: Record<string, string> } = { headers: {} };
+ const hookInput = {
+ agent: "omnirush",
+ model: { id: "gpt-6-astra", providerID: "omnirush" },
+ message: { id: "msg_ultra", model: { variant: "ultra" } },
+ };
+ await hooks["chat.params"](hookInput, { options: { reasoning_effort: "ultra" } });
+ await hooks["chat.headers"](hookInput, headers);
+
+ const response = await broker.handle(gatewayRequest({ model: "gpt-6-astra", input: "test" }, headers.headers), "responses");
+
+ expect(response.status).toBe(200);
+ expect(calls).toHaveLength(1);
+ expect(calls[0]?.body).toEqual({ model: "gpt-6-astra", input: "test", reasoning: { effort: "ultra" } });
+ expect(calls[0]?.headers.has("x-omnirush-reasoning-effort")).toBe(false);
+ expect(calls[0]?.headers.get("authorization")).toBe("Bearer access-token");
+ });
+
+ test("keeps an effort the engine already emitted and the legacy top-level field", async () => {
+ const calls: UpstreamCall[] = [];
+ const broker = capturingBroker(calls);
+ const header = { "x-omnirush-reasoning-effort": "ultra" };
+
+ await broker.handle(gatewayRequest({ model: "gpt-5.6-sol", input: "a", reasoning: { effort: "ultra", summary: "auto" } }, header), "responses");
+ await broker.handle(gatewayRequest({ model: "gpt-5.6-sol", input: "b", reasoning_effort: "high" }, header), "responses/compact");
+ await broker.handle(gatewayRequest({ model: "gpt-6-astra", input: "c" }, { "x-omnirush-reasoning-effort": "turbo" }), "responses");
+ await broker.handle(gatewayRequest({ model: "gpt-6-astra", input: "d" }), "responses");
+
+ expect(calls.map((call) => call.body)).toEqual([
+ { model: "gpt-5.6-sol", input: "a", reasoning: { effort: "ultra", summary: "auto" } },
+ { model: "gpt-5.6-sol", input: "b", reasoning_effort: "high" },
+ { model: "gpt-6-astra", input: "c" },
+ { model: "gpt-6-astra", input: "d" },
+ ]);
+ });
+});
diff --git a/apps/server/src/omnirush-gateway-broker.ts b/apps/server/src/omnirush-gateway-broker.ts
index b9ff379e..f18b8aff 100644
--- a/apps/server/src/omnirush-gateway-broker.ts
+++ b/apps/server/src/omnirush-gateway-broker.ts
@@ -1,7 +1,7 @@
import { timingSafeEqual } from "node:crypto";
import { externalFetch } from "./server-fetch.js";
-import type { OmniRushGatewayCredentials } from "./types.js";
+import type { OmniRushGatewayCredentialBundle, OmniRushGatewayCredentials } from "./types.js";
type BrokerOptions = {
credentials?: OmniRushGatewayCredentials;
@@ -62,6 +62,41 @@ function collectorUrl(gatewayUrl: string): string {
return url.toString();
}
+/**
+ * Set by the omnirush-reasoning-effort engine plugin; keep the two
+ * definitions identical. The header is consumed here and never forwarded.
+ */
+const REASONING_EFFORT_HEADER = "x-omnirush-reasoning-effort";
+const REASONING_EFFORTS = new Set(["none", "minimal", "low", "medium", "high", "xhigh", "ultra", "max"]);
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function requestedReasoningEffort(request: Request): string | null {
+ const effort = request.headers.get(REASONING_EFFORT_HEADER)?.trim().toLowerCase() ?? "";
+ return REASONING_EFFORTS.has(effort) ? effort : null;
+}
+
+/**
+ * Guarantee the selected effort reaches omnirush.ai as Responses-API
+ * `reasoning.effort`. The engine's OpenAI adapter only emits it for model ids
+ * it recognises as reasoning models; an effort it already emitted (or a legacy
+ * top-level `reasoning_effort`) is left untouched.
+ */
+function withReasoningEffort(body: ArrayBuffer, effort: string): ArrayBuffer | string {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(new TextDecoder().decode(body));
+ } catch {
+ return body;
+ }
+ if (!isRecord(parsed) || typeof parsed.reasoning_effort === "string") return body;
+ const reasoning = isRecord(parsed.reasoning) ? parsed.reasoning : {};
+ if (typeof reasoning.effort === "string") return body;
+ return JSON.stringify({ ...parsed, reasoning: { ...reasoning, effort } });
+}
+
function responseHeaders(headers: Headers): Headers {
const result = new Headers();
for (const [name, value] of headers) {
@@ -78,6 +113,7 @@ export class OmniRushGatewayBroker {
private state: CredentialState | null;
private readonly engineToken: string;
private readonly persist?: OmniRushGatewayCredentials["persist"];
+ private readonly invalidate?: OmniRushGatewayCredentials["invalidate"];
private readonly fetcher: typeof externalFetch;
private refreshInFlight: Promise<boolean> | null = null;
@@ -92,6 +128,7 @@ export class OmniRushGatewayBroker {
: null;
this.engineToken = options.engineToken?.trim() ?? "";
this.persist = options.credentials?.persist;
+ this.invalidate = options.credentials?.invalidate;
this.fetcher = options.fetch ?? externalFetch;
}
@@ -111,14 +148,24 @@ export class OmniRushGatewayBroker {
const body = request.method === "GET"
? undefined
- : await request.arrayBuffer();
+ : await this.requestBody(request, normalizedPath);
const tokenUsed = this.state.accessToken;
let response = await this.forward(request, normalizedPath, body, tokenUsed);
- const credentialAlreadyRotated = this.state.accessToken !== tokenUsed;
- if (response.status === 401 && (credentialAlreadyRotated || await this.refresh(tokenUsed))) {
+ const credentialAlreadyRotated = this.state?.accessToken !== tokenUsed;
+ if (response.status === 401 && this.state && (credentialAlreadyRotated || await this.refresh(tokenUsed))) {
await response.body?.cancel().catch(() => undefined);
response = await this.forward(request, normalizedPath, body);
}
+ if (response.status === 401 && !this.state) {
+ await response.body?.cancel().catch(() => undefined);
+ return Response.json({
+ error: {
+ message: "Your omnirush.ai session has expired. Sign in again from Settings.",
+ type: "authentication_error",
+ code: "omnirush_account_required",
+ },
+ }, { status: 401 });
+ }
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
@@ -140,15 +187,22 @@ export class OmniRushGatewayBroker {
signal: AbortSignal.timeout(30_000),
});
let response = await send();
- const credentialAlreadyRotated = this.state.accessToken !== tokenUsed;
- if (response.status === 401 && (credentialAlreadyRotated || await this.refresh(tokenUsed))) {
+ const credentialAlreadyRotated = this.state?.accessToken !== tokenUsed;
+ if (response.status === 401 && this.state && (credentialAlreadyRotated || await this.refresh(tokenUsed))) {
await response.body?.cancel().catch(() => undefined);
response = await send();
}
return response;
}
- private forward(request: Request, path: string, body: ArrayBuffer | undefined, accessToken?: string): Promise<Response> {
+ private async requestBody(request: Request, path: string): Promise<ArrayBuffer | string> {
+ const body = await request.arrayBuffer();
+ const effort = requestedReasoningEffort(request);
+ if (!effort || (path !== "responses" && path !== "responses/compact")) return body;
+ return withReasoningEffort(body, effort);
+ }
+
+ private forward(request: Request, path: string, body: ArrayBuffer | string | undefined, accessToken?: string): 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}`);
@@ -185,6 +239,10 @@ export class OmniRushGatewayBroker {
});
if (!response.ok) {
await response.body?.cancel().catch(() => undefined);
+ if (response.status === 401 || response.status === 403) {
+ this.state = null;
+ void this.invalidate?.().catch(() => undefined);
+ }
return false;
}
const payload: unknown = await response.json();
@@ -198,7 +256,7 @@ export class OmniRushGatewayBroker {
return true;
}
- private async persistLatest(credentials: CredentialState, attempt = 0): Promise<void> {
+ private async persistLatest(credentials: OmniRushGatewayCredentialBundle, attempt = 0): Promise<void> {
if (!this.persist) return;
try {
await this.persist(credentials);
diff --git a/apps/server/src/omnirush-runtime-config.test.ts b/apps/server/src/omnirush-runtime-config.test.ts
index a35221bd..2d533d9b 100644
--- a/apps/server/src/omnirush-runtime-config.test.ts
+++ b/apps/server/src/omnirush-runtime-config.test.ts
@@ -123,17 +123,44 @@ describe("omnirush runtime config file", () => {
name: "omnirush.ai",
env: ["OMNIRUSH_ACCESS_TOKEN"],
options: { baseURL: "http://127.0.0.1:8090/omnirush/v1" },
- models: {
- "gpt-6-astra": {
- name: "Astra",
- reasoning: true,
- tool_call: true,
- },
- },
});
expect(JSON.stringify(parsed)).not.toContain("access-token");
});
+ test("exposes every omnirush.ai model with the shared effort levels, default first", () => {
+ const parsed = buildOmniRushRuntimeConfigObjectFromSnapshot({}, {
+ baseUrl: "http://127.0.0.1:8090/omnirush/v1",
+ });
+ const providers = parsed.provider as Record<string, { models: Record<string, Record<string, unknown>> }>;
+ const models = providers.omnirush!.models;
+ const variants = {
+ low: { reasoning_effort: "low" },
+ high: { reasoning_effort: "high" },
+ xhigh: { reasoning_effort: "xhigh" },
+ ultra: { reasoning_effort: "ultra" },
+ // The engine merges its own OpenAI reasoning defaults into a model's
+ // variants and only drops entries marked disabled; these keep the
+ // resolved picker at exactly the four levels above.
+ none: { disabled: true },
+ minimal: { disabled: true },
+ medium: { disabled: true },
+ max: { disabled: true },
+ };
+ const enabledVariants = (model: Record<string, unknown>) => Object.entries(model.variants as Record<string, { disabled?: boolean }>)
+ .filter(([, options]) => options.disabled !== true)
+ .map(([key]) => key);
+
+ expect(Object.keys(models)).toEqual(["gpt-6-astra", "gpt-5.6-sol"]);
+ expect(models["gpt-6-astra"]).toMatchObject({ name: "GPT 6 Astra", reasoning: true, tool_call: true, variants });
+ expect(models["gpt-5.6-sol"]).toMatchObject({ name: "GPT-5.6 Sol", reasoning: true, tool_call: true, variants });
+ for (const id of ["gpt-6-astra", "gpt-5.6-sol"]) {
+ expect(Object.keys(models[id]!.variants as object).sort()).toEqual(Object.keys(variants).sort());
+ expect(enabledVariants(models[id]!)).toEqual(["low", "high", "xhigh", "ultra"]);
+ }
+ expect(parsed.model).toBe("omnirush/gpt-6-astra");
+ expect((parsed.plugin as string[]).some((plugin) => /omnirush-reasoning-effort\.(?:ts|js)$/.test(plugin))).toBe(true);
+ });
+
test("derives the desktop loopback gateway from the server config without process-global credentials", async () => {
const { config } = await setup();
config.port = 48123;
diff --git a/apps/server/src/omnirush-runtime-config.ts b/apps/server/src/omnirush-runtime-config.ts
index ff353289..c30219bb 100644
--- a/apps/server/src/omnirush-runtime-config.ts
+++ b/apps/server/src/omnirush-runtime-config.ts
@@ -23,6 +23,7 @@ import {
omnirushAnthropicAdaptiveThinkingPluginPath,
omnirushAnthropicToolSchemaPluginPath,
omnirushTitleRecoveryPluginPath,
+ omnirushReasoningEffortPluginPath,
omnirushOfficeAttachmentsPluginPath,
omnirushSpreadsheetsPluginPath,
omnirushChromeDevtoolsPluginPath,
@@ -44,7 +45,24 @@ import { CONNECT_MCP_SERVER_NAME_PREFIX } from "./connect-mcp-server-catalog.js"
import { OMNIRUSH_AGENT_PROMPT } from "./omnirush-agent-prompt.js";
const INTERNAL_PROVIDER_ID = "omnirush";
-const INTERNAL_MODEL_ID = "gpt-6-astra";
+const INTERNAL_DEFAULT_MODEL_ID = "gpt-6-astra";
+/**
+ * Effort levels offered for every omnirush.ai model, in picker order. Clients
+ * send these literal values; the backend maps "ultra" to the upstream maximum.
+ */
+const INTERNAL_REASONING_EFFORTS = ["low", "high", "xhigh", "ultra"] as const;
+/**
+ * Effort levels the engine adds on its own to every reasoning model served by
+ * the OpenAI adapter (it merges its defaults into the configured variants and
+ * drops only entries marked disabled). Declaring them disabled keeps the
+ * picker at exactly INTERNAL_REASONING_EFFORTS and the default at "high".
+ */
+const INTERNAL_HIDDEN_EFFORTS = ["none", "minimal", "medium", "max"] as const;
+/** Models served by the omnirush.ai account route. The default comes first. */
+const INTERNAL_MODELS: ReadonlyArray<{ id: string; name: string }> = [
+ { id: INTERNAL_DEFAULT_MODEL_ID, name: "GPT 6 Astra" },
+ { id: "gpt-5.6-sol", name: "GPT-5.6 Sol" },
+];
type InternalGatewayRuntime = {
baseUrl: string;
@@ -84,27 +102,43 @@ function resolveConfiguredInternalGatewayRuntime(
return resolveInternalGatewayRuntime(env);
}
+function internalGatewayModel(name: string): Record<string, unknown> {
+ return {
+ name,
+ reasoning: true,
+ tool_call: true,
+ structured_output: true,
+ temperature: true,
+ // Keep the effort controls visible in the desktop model picker. The
+ // selected variant is merged into the request options by the engine; the
+ // omnirush-reasoning-effort plugin and the local gateway broker make sure
+ // it reaches the outgoing request as reasoning.effort for every model.
+ variants: {
+ ...Object.fromEntries(
+ INTERNAL_REASONING_EFFORTS.map((effort) => [effort, { reasoning_effort: effort }]),
+ ),
+ ...Object.fromEntries(
+ INTERNAL_HIDDEN_EFFORTS.map((effort) => [effort, { disabled: true }]),
+ ),
+ },
+ limit: { context: 400_000, output: 128_000 },
+ modalities: { input: ["text", "image", "pdf"], output: ["text"] },
+ };
+}
+
function internalGatewayProvider(runtime: InternalGatewayRuntime): Record<string, unknown> {
return {
// The native OpenAI provider uses the Responses API, which preserves
// reasoning summaries, tool calls, and delegated task events. The generic
// compatibility provider only emits /chat/completions and loses those
- // Astra capabilities.
+ // capabilities.
npm: "@ai-sdk/openai",
name: "omnirush.ai",
env: ["OMNIRUSH_ACCESS_TOKEN"],
options: { baseURL: runtime.baseUrl },
- models: {
- [INTERNAL_MODEL_ID]: {
- name: "Astra",
- reasoning: true,
- tool_call: true,
- structured_output: true,
- temperature: true,
- limit: { context: 400_000, output: 128_000 },
- modalities: { input: ["text", "image", "pdf"], output: ["text"] },
- },
- },
+ models: Object.fromEntries(
+ INTERNAL_MODELS.map((model) => [model.id, internalGatewayModel(model.name)]),
+ ),
};
}
@@ -139,7 +173,7 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(
return {
...engineConfig,
...(internalGateway
- ? { model: `${INTERNAL_PROVIDER_ID}/${INTERNAL_MODEL_ID}` }
+ ? { model: `${INTERNAL_PROVIDER_ID}/${INTERNAL_DEFAULT_MODEL_ID}` }
: {}),
...(runtimeConfig.managedPolicy?.allowCustomProviders === false ? { enabled_providers: [
...Object.keys(provider).filter((id) => /^(?:lpr_|omnirush$)/i.test(id)),
@@ -181,6 +215,7 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(
omnirushPdfAttachmentsPluginPath(),
omnirushAnthropicAdaptiveThinkingPluginPath(),
omnirushAnthropicToolSchemaPluginPath(),
+ omnirushReasoningEffortPluginPath(),
omnirushTitleRecoveryPluginPath(),
...runtimePluginList(runtimeConfig),
],
diff --git a/apps/server/src/opencode-plugins/omnirush-reasoning-effort.test.ts b/apps/server/src/opencode-plugins/omnirush-reasoning-effort.test.ts
new file mode 100644
index 00000000..c139afd2
--- /dev/null
+++ b/apps/server/src/opencode-plugins/omnirush-reasoning-effort.test.ts
@@ -0,0 +1,108 @@
+import { describe, expect, test } from "bun:test";
+import { OmniRushReasoningEffort } from "./omnirush-reasoning-effort.js";
+
+type Hooks = Awaited<ReturnType<typeof OmniRushReasoningEffort>>;
+
+const astra = { id: "gpt-6-astra", providerID: "omnirush" };
+const sol = { id: "gpt-5.6-sol", providerID: "omnirush" };
+
+async function run(
+ hooks: Hooks,
+ input: Parameters<Hooks["chat.params"]>[0],
+ options: Record<string, unknown>,
+) {
+ const params = { options };
+ await hooks["chat.params"](input, params);
+ const headers: { headers: Record<string, string> } = { headers: {} };
+ await hooks["chat.headers"](input, headers);
+ return { options: params.options, headers: headers.headers };
+}
+
+describe("OmniRushReasoningEffort", () => {
+ test("mirrors the ultra variant into reasoningEffort and the private header", async () => {
+ const hooks = await OmniRushReasoningEffort();
+ const result = await run(
+ hooks,
+ { agent: "omnirush", model: astra, message: { id: "msg_1", model: { variant: "ultra" } } },
+ { reasoning_effort: "ultra", temperature: 0.2 },
+ );
+ expect(result.options).toEqual({ reasoning_effort: "ultra", reasoningEffort: "ultra", temperature: 0.2 });
+ expect(result.headers).toEqual({ "x-omnirush-reasoning-effort": "ultra" });
+ });
+
+ test("applies to every omnirush.ai model", async () => {
+ const hooks = await OmniRushReasoningEffort();
+ for (const [index, model] of [astra, sol].entries()) {
+ const result = await run(
+ hooks,
+ { agent: "omnirush", model, message: { id: `msg_${index}`, model: { variant: "xhigh" } } },
+ { reasoning_effort: "xhigh" },
+ );
+ expect(result.options.reasoningEffort).toBe("xhigh");
+ expect(result.headers["x-omnirush-reasoning-effort"]).toBe("xhigh");
+ }
+ });
+
+ test("prefers the variant options over the variant name", async () => {
+ const hooks = await OmniRushReasoningEffort();
+ const result = await run(
+ hooks,
+ { agent: "omnirush", model: astra, message: { id: "msg_2", model: { variant: "max" } } },
+ { reasoning_effort: "ultra" },
+ );
+ expect(result.options.reasoningEffort).toBe("ultra");
+ expect(result.headers["x-omnirush-reasoning-effort"]).toBe("ultra");
+ });
+
+ test("falls back to the variant name when the options carry no effort", async () => {
+ const hooks = await OmniRushReasoningEffort();
+ const result = await run(
+ hooks,
+ { agent: "omnirush", model: astra, message: { id: "msg_3", model: { variant: "High" } } },
+ {},
+ );
+ expect(result.options).toEqual({ reasoningEffort: "high" });
+ expect(result.headers).toEqual({ "x-omnirush-reasoning-effort": "high" });
+ });
+
+ test("leaves requests without a selected effort untouched", async () => {
+ const hooks = await OmniRushReasoningEffort();
+ const result = await run(hooks, { agent: "omnirush", model: astra, message: { id: "msg_4", model: {} } }, { temperature: 0.2 });
+ expect(result.options).toEqual({ temperature: 0.2 });
+ expect(result.headers).toEqual({});
+ });
+
+ test("ignores unknown effort values", async () => {
+ const hooks = await OmniRushReasoningEffort();
+ const result = await run(
+ hooks,
+ { agent: "omnirush", model: astra, message: { id: "msg_5", model: { variant: "turbo" } } },
+ { reasoning_effort: "turbo" },
+ );
+ expect(result.options).toEqual({ reasoning_effort: "turbo" });
+ expect(result.headers).toEqual({});
+ });
+
+ test("skips other providers and title generation", async () => {
+ const hooks = await OmniRushReasoningEffort();
+ const external = await run(
+ hooks,
+ { agent: "omnirush", model: { id: "gpt-5.5", providerID: "openai" }, message: { id: "msg_6", model: { variant: "ultra" } } },
+ { reasoning_effort: "ultra" },
+ );
+ expect(external.options).toEqual({ reasoning_effort: "ultra" });
+ expect(external.headers).toEqual({});
+ const title = await run(
+ hooks,
+ { agent: "title", model: astra, message: { id: "msg_7", model: { variant: "ultra" } } },
+ {},
+ );
+ expect(title.options).toEqual({});
+ expect(title.headers).toEqual({});
+ });
+
+ test("module exposes only the plugin factory", async () => {
+ const mod = await import("./omnirush-reasoning-effort.js");
+ expect(Object.keys(mod)).toEqual(["OmniRushReasoningEffort"]);
+ });
+});
diff --git a/apps/server/src/opencode-plugins/omnirush-reasoning-effort.ts b/apps/server/src/opencode-plugins/omnirush-reasoning-effort.ts
new file mode 100644
index 00000000..31cb4ef0
--- /dev/null
+++ b/apps/server/src/opencode-plugins/omnirush-reasoning-effort.ts
@@ -0,0 +1,82 @@
+/**
+ * OmniRush.ai Reasoning Effort Plugin
+ *
+ * omnirush.ai models expose their effort levels as engine variants
+ * (low / high / xhigh / ultra) whose options carry the client-facing
+ * `reasoning_effort` value. The bundled OpenAI Responses adapter only reads
+ * the camel-case `reasoningEffort` option, and it only emits
+ * `reasoning.effort` for model ids it recognises as reasoning models, so the
+ * selected level could silently disappear before the request leaves the
+ * engine. This plugin keeps the selection on the wire by
+ *
+ * 1. mirroring the variant's effort into `reasoningEffort`, so the adapter
+ * emits `reasoning.effort` wherever it can, and
+ * 2. tagging the request with a private header that the local gateway
+ * broker turns into `reasoning.effort` when the body still lacks one.
+ *
+ * The header never leaves the machine: the broker only forwards an explicit
+ * allow-list of headers to omnirush.ai.
+ */
+const PROVIDER_ID = "omnirush";
+/** Read by OmniRushGatewayBroker; keep the two definitions identical. */
+const EFFORT_HEADER = "x-omnirush-reasoning-effort";
+const EFFORTS = new Set(["none", "minimal", "low", "medium", "high", "xhigh", "ultra", "max"]);
+/** Cheap side requests never carry the conversation's effort selection. */
+const SKIPPED_AGENTS = new Set(["title"]);
+const MAX_PENDING = 512;
+
+type HookInput = {
+ agent?: string;
+ model: { id: string; providerID: string };
+ message?: { id?: string; model?: { variant?: string } };
+};
+
+// chat.params sees the merged variant options; chat.headers runs right after
+// it for the same user message and only sees the message. Bridge the two by
+// message id so both hooks describe the same effort.
+const pending = new Map<string, string>();
+
+function normalizeEffort(value: unknown): string | null {
+ if (typeof value !== "string") return null;
+ const effort = value.trim().toLowerCase();
+ return EFFORTS.has(effort) ? effort : null;
+}
+
+function isInternalModel(input: HookInput): boolean {
+ return input.model.providerID.trim().toLowerCase() === PROVIDER_ID
+ && !SKIPPED_AGENTS.has(input.agent ?? "");
+}
+
+function optionEffort(options: Record<string, unknown>): string | null {
+ return normalizeEffort(options.reasoningEffort) ?? normalizeEffort(options.reasoning_effort);
+}
+
+function remember(messageId: string | undefined, effort: string): void {
+ if (!messageId) return;
+ if (pending.size >= MAX_PENDING) pending.clear();
+ pending.set(messageId, effort);
+}
+
+function recall(input: HookInput): string | null {
+ const messageId = input.message?.id;
+ const bridged = messageId ? pending.get(messageId) : undefined;
+ if (messageId) pending.delete(messageId);
+ return bridged ?? normalizeEffort(input.message?.model?.variant);
+}
+
+// Single export: the OpenCode plugin loader treats every export of a plugin
+// module as a plugin factory, so helpers must stay module-private.
+export const OmniRushReasoningEffort = async () => ({
+ "chat.params": async (input: HookInput, output: { options: Record<string, unknown> }) => {
+ if (!isInternalModel(input)) return;
+ const effort = optionEffort(output.options) ?? normalizeEffort(input.message?.model?.variant);
+ if (!effort) return;
+ if (normalizeEffort(output.options.reasoningEffort) !== effort) output.options.reasoningEffort = effort;
+ remember(input.message?.id, effort);
+ },
+ "chat.headers": async (input: HookInput, output: { headers: Record<string, string> }) => {
+ if (!isInternalModel(input)) return;
+ const effort = recall(input);
+ if (effort) output.headers[EFFORT_HEADER] = effort;
+ },
+});
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index ba6a92b8..6d537835 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -725,6 +725,12 @@ function isPromptAsyncProxyRequest(method: string, proxyPath: string) {
return method === "POST" && /^\/session\/[^/]+\/prompt_async$/.test(normalizeOpencodeProxyPath(proxyPath));
}
+// A prompt dispatch (v1 prompt_async, v2 prompt, or a slash command) is the
+// collector's "prompt" milestone: the workspace is captured as the turn begins.
+function isCollectorPromptDispatch(method: string, proxyPath: string): boolean {
+ return method === "POST" && /^\/session\/[^/]+\/(?:prompt_async|prompt|command)$/.test(normalizeOpencodeProxyPath(proxyPath));
+}
+
function collectorSessionId(proxyPath: string): string | null {
const match = normalizeOpencodeProxyPath(proxyPath).match(/^\/session\/([^/]+)\/(?:prompt_async|prompt|command|abort|interrupt)$/);
if (!match?.[1]) return null;
@@ -887,6 +893,7 @@ function observeCollectedSession(input: {
}
input.collector.recordTrace(input.sessionId, "session.idle", { status: statusType });
input.collector.flushTrace(input.sessionId, { messages: delta });
+ input.collector.captureSnapshot(input.sessionId, "turn_completed");
return;
}
input.collector.recordTrace(input.sessionId, "session.observer_timeout");
@@ -922,12 +929,24 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
: undefined
);
const gatewayBroker = new OmniRushGatewayBroker({
- credentials: gatewayCredentials,
+ credentials: gatewayCredentials
+ ? {
+ ...gatewayCredentials,
+ // Revoked or expired omnirush.ai credentials also discard spooled
+ // collector uploads: a signed-out account leaves nothing queued.
+ invalidate: async () => {
+ await workspaceCollector.clearSpool().catch(() => undefined);
+ await gatewayCredentials.invalidate?.();
+ },
+ }
+ : undefined,
engineToken: config.omnirushEngineToken,
});
const workspaceCollector = new WorkspaceCollector({
...(gatewayBroker.enabled ? { upload: (sessionId, compressed) => gatewayBroker.collect(sessionId, compressed) } : {}),
stateDir: runtimeStorageDir(config),
+ appVersion: SERVER_VERSION,
+ engineVersion: OPENCODE_VERSION,
log: (level, message, attributes) => logger.log(level, message, attributes),
});
workspaceCollectorsByServer.set(config, workspaceCollector);
@@ -1753,6 +1772,7 @@ export async function proxyOpencodeRequest(input: {
path: normalizeOpencodeProxyPath(proxyPath),
body: collectorRequestPayload(body),
});
+ if (isCollectorPromptDispatch(method, proxyPath)) collector.captureSnapshot(collectedSessionId, "prompt");
}
if (pool && method === "GET" && isEngineEventPath(proxyPath)) {
// An open engine event stream means this workspace is visible somewhere in
diff --git a/apps/server/src/types.ts b/apps/server/src/types.ts
index eab03d5b..9cfc86d3 100644
--- a/apps/server/src/types.ts
+++ b/apps/server/src/types.ts
@@ -83,11 +83,15 @@ export interface ApprovalConfig {
export type LocalManagedMcpVaultKeyProvider = () => Promise<Uint8Array>;
-export type OmniRushGatewayCredentials = {
+export type OmniRushGatewayCredentialBundle = {
gatewayUrl: string;
accessToken: string;
refreshToken: string;
- persist?: (credentials: Omit<OmniRushGatewayCredentials, "persist">) => Promise<void>;
+};
+
+export type OmniRushGatewayCredentials = OmniRushGatewayCredentialBundle & {
+ persist?: (credentials: OmniRushGatewayCredentialBundle) => Promise<void>;
+ invalidate?: () => Promise<void>;
};
export interface ServerConfig {
diff --git a/apps/server/src/workspace-collector.test.ts b/apps/server/src/workspace-collector.test.ts
index b37cf8e0..bfbf9f69 100644
--- a/apps/server/src/workspace-collector.test.ts
+++ b/apps/server/src/workspace-collector.test.ts
@@ -1,12 +1,24 @@
import { afterEach, describe, expect, test } from "bun:test";
import { execFile } from "node:child_process";
-import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { createHash } from "node:crypto";
+import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { basename, join } from "node:path";
import { promisify } from "node:util";
import { zstdDecompressSync } from "node:zlib";
-import { WorkspaceCollector, isCollectorPathDenied, redactCollectorText } from "./workspace-collector.js";
+import {
+ COLLECTOR_SCHEMA_VERSION,
+ MAX_COLLECTOR_DIFF_BYTES,
+ WorkspaceCollector,
+ clampCollectorText,
+ collectGitBlock,
+ diffHeaderPath,
+ filterCollectorDiff,
+ isCollectorPathDenied,
+ redactCollectorText,
+ stripRemoteUserinfo,
+} from "./workspace-collector.js";
const execFileAsync = promisify(execFile);
const roots: string[] = [];
@@ -184,7 +196,6 @@ describe("workspace collector privacy", () => {
});
test("captures changed files in a bounded journal before the next snapshot", async () => {
- if (process.platform !== "darwin" && process.platform !== "win32") return;
const root = await mkdtemp(join(tmpdir(), "omnirush-collector-changes-"));
roots.push(root);
const uploads: Array<Record<string, unknown>> = [];
@@ -198,9 +209,11 @@ describe("workspace collector privacy", () => {
});
const sessionId = "session-changes-1234";
collector.startSession(sessionId, "workspace-changes", root);
- await new Promise((resolve) => setTimeout(resolve, 40));
+ await collector.idle(sessionId);
await writeFile(join(root, "created.txt"), "contact [email protected]");
- await new Promise((resolve) => setTimeout(resolve, 80));
+ collector.recordTrace(sessionId, "file.read", { path: "created.txt" });
+ collector.flushTrace(sessionId);
+ await new Promise((resolve) => setTimeout(resolve, 40));
await collector.stop();
const change = uploads.find((item) => item.snapshot_type === "change");
@@ -210,4 +223,507 @@ describe("workspace collector privacy", () => {
expect(changeFile?.content).toContain('"path":"created.txt"');
expect(changeFile?.content).not.toContain("[email protected]");
});
+
+ test("records a privacy manifest and touched paths without uploading denied files", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-collector-manifest-"));
+ roots.push(root);
+ await writeFile(join(root, "touched.ts"), "export const ok = true;");
+ await writeFile(join(root, ".env.local"), "SECRET=do-not-upload");
+ const uploads: Array<Record<string, unknown>> = [];
+ const collector = new WorkspaceCollector({
+ upload: async (_sessionId, compressed) => {
+ uploads.push(JSON.parse(zstdDecompressSync(compressed).toString("utf8")) as Record<string, unknown>);
+ return Response.json({ ok: true }, { status: 201 });
+ },
+ fallbackScanMs: 60_000,
+ });
+ const sessionId = "session-manifest-1234";
+ collector.startSession(sessionId, "workspace-manifest", root);
+ collector.recordTrace(sessionId, "file.read", { path: "touched.ts" });
+ collector.flushTrace(sessionId);
+ await collector.stop();
+ const start = uploads.find((item) => item.snapshot_type === "start");
+ const workspaceFile = (start?.files as Array<{ path: string; content: string }>).find((file) => file.path === "__omnirush__/workspace.json");
+ expect(workspaceFile?.content).toContain('"capture_policy":"consented_workspace_session"');
+ expect(workspaceFile?.content).toContain('"touched_paths":["touched.ts"]');
+ expect(JSON.stringify(uploads)).not.toContain("do-not-upload");
+ });
+});
+
+// --- collector envelope v2 ---------------------------------------------------
+
+type Envelope = Record<string, unknown> & {
+ files: Array<{ path: string; content: string; sha256: string }>;
+ manifest: Array<{ path: string; sha256: string; size: number }>;
+ workspace: { root_name: string; git: Record<string, unknown> | null };
+ environment: Record<string, unknown>;
+ privacy: Record<string, unknown>;
+ touched_paths: string[];
+ trace?: Array<{ type: string; data?: Record<string, unknown> }>;
+};
+
+const sha256 = (text: string) => createHash("sha256").update(text).digest("hex");
+
+function makeUploads() {
+ const uploads: Envelope[] = [];
+ const upload = async (_sessionId: string, compressed: Uint8Array) => {
+ uploads.push(JSON.parse(zstdDecompressSync(compressed).toString("utf8")) as Envelope);
+ return Response.json({ ok: true }, { status: 201 });
+ };
+ return { uploads, upload };
+}
+
+async function git(root: string, ...args: string[]): Promise<string> {
+ const { stdout } = await execFileAsync("git", ["-C", root, "-c", "commit.gpgsign=false", "-c", "user.name=Dev", "-c", "[email protected]", ...args]);
+ return String(stdout).trim();
+}
+
+describe("workspace collector envelope v2", () => {
+ test("uploads a v2 envelope with trigger, environment, manifest, hashed files and privacy fields", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-collector-v2-"));
+ roots.push(root);
+ await writeFile(join(root, "app.ts"), "export const answer = 42;\n");
+ await mkdir(join(root, "nested"));
+ await writeFile(join(root, "nested", "note.md"), "call me at +1 (415) 555-0132\n");
+ await writeFile(join(root, ".env"), "TOKEN=nope\n");
+ const { uploads, upload } = makeUploads();
+ const collector = new WorkspaceCollector({ upload, fallbackScanMs: 60_000, appVersion: "1.2.3", engineVersion: "9.9.9" });
+ const sessionId = "session-v2-envelope-1";
+ collector.startSession(sessionId, "workspace-v2", root);
+ collector.recordTrace(sessionId, "file.read", { path: "app.ts" });
+ collector.flushTrace(sessionId);
+ await collector.stop();
+
+ expect(uploads.map((item) => [item.snapshot_type, item.trigger])).toEqual([
+ ["start", "session_start"],
+ ["trace", "trace_flush"],
+ ["end", "session_end"],
+ ]);
+ for (const envelope of uploads) {
+ expect(envelope.schema_version).toBe(COLLECTOR_SCHEMA_VERSION);
+ expect(typeof envelope.captured_at).toBe("string");
+ expect(Number.isNaN(Date.parse(envelope.captured_at as string))).toBe(false);
+ expect(envelope.workspace.root_name).toBe(basename(root));
+ expect(envelope.environment).toMatchObject({
+ os: process.platform,
+ arch: process.arch,
+ app_version: "1.2.3",
+ engine_version: "9.9.9",
+ });
+ for (const key of ["os_version", "node_version", "shell", "locale", "timezone", "git_version"]) {
+ expect(key in envelope.environment).toBe(true);
+ }
+ expect(envelope.privacy).toMatchObject({ capture_policy: "consented_workspace_session", git_internals_excluded: true, environment_variables_excluded: true });
+ expect(envelope.touched_paths).toEqual(["app.ts"]);
+ for (const file of envelope.files) expect(file.sha256).toBe(sha256(file.content));
+ }
+ const start = uploads[0]!;
+ expect(start.workspace.git).toBeNull();
+ expect(start.manifest.map((entry) => entry.path).sort()).toEqual(["app.ts", "nested/note.md"]);
+ for (const entry of start.manifest) {
+ const file = start.files.find((candidate) => candidate.path === entry.path);
+ expect(file).toBeDefined();
+ expect(file?.sha256).toBe(entry.sha256);
+ expect(entry.size).toBe(Buffer.byteLength(file!.content));
+ }
+ expect(JSON.stringify(uploads)).not.toContain("415");
+ expect(JSON.stringify(uploads)).not.toContain("TOKEN=nope");
+ const trace = uploads[1]!;
+ expect(Array.isArray(trace.trace)).toBe(true);
+ expect(trace.trace?.map((event) => event.type)).toContain("file.read");
+ expect(trace.manifest).toEqual([]);
+ });
+
+ test("summarises a git repository without shipping internals or remote credentials", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-collector-git-"));
+ roots.push(root);
+ await git(root, "init", "-q");
+ await git(root, "remote", "add", "origin", "https://oauth2:[email protected]/acme/widgets.git");
+ await git(root, "remote", "add", "mirror", "[email protected]:acme/widgets-mirror.git");
+ await writeFile(join(root, "app.txt"), "line one\n");
+ await writeFile(join(root, "credentials.json"), '{"password":"hunter2-committed"}\n');
+ await writeFile(join(root, "blob.bin"), Buffer.from([0, 1, 2, 3, 4]));
+ await git(root, "add", "-A");
+ await git(root, "commit", "-q", "-m", "initial commit by [email protected]");
+ await writeFile(join(root, "app.txt"), "line one\nline two added\n");
+ await writeFile(join(root, "credentials.json"), '{"password":"hunter2-modified"}\n');
+ await writeFile(join(root, "blob.bin"), Buffer.from([0, 9, 9, 9, 9, 9]));
+ await writeFile(join(root, ".env.local"), "TOKEN=abcdef123456\n");
+ await writeFile(join(root, "staged.txt"), "staged content\n");
+ await git(root, "add", "staged.txt");
+ const head = await git(root, "rev-parse", "HEAD");
+ const branch = await git(root, "branch", "--show-current");
+
+ const { uploads, upload } = makeUploads();
+ const collector = new WorkspaceCollector({ upload, fallbackScanMs: 60_000 });
+ const sessionId = "session-v2-git-1";
+ collector.startSession(sessionId, "workspace-git", root);
+ await collector.stop();
+
+ const start = uploads.find((item) => item.snapshot_type === "start")!;
+ const gitBlock = start.workspace.git as {
+ commit: string; branch: string; dirty: boolean; upstream: string | null; ahead: number | null; behind: number | null;
+ remotes: Array<{ name: string; url: string }>; recent_commits: Array<{ sha: string; at: string; subject: string }>;
+ status: Array<{ code: string; path: string }>; diff: string; diff_truncated: boolean;
+ };
+ expect(gitBlock.commit).toBe(head);
+ expect(gitBlock.branch).toBe(branch);
+ expect(gitBlock.dirty).toBe(true);
+ expect(gitBlock.upstream).toBeNull();
+ expect(gitBlock.ahead).toBeNull();
+ expect(gitBlock.behind).toBeNull();
+ expect([...gitBlock.remotes].sort((left, right) => left.name.localeCompare(right.name))).toEqual([
+ { name: "mirror", url: "github.com:acme/widgets-mirror.git" },
+ { name: "origin", url: "https://github.com/acme/widgets.git" },
+ ]);
+ expect(gitBlock.recent_commits).toHaveLength(1);
+ expect(gitBlock.recent_commits[0]).toMatchObject({ sha: head, subject: "initial commit by [REDACTED_PII]" });
+ expect(Number.isNaN(Date.parse(gitBlock.recent_commits[0]!.at))).toBe(false);
+ const statusPaths = gitBlock.status.map((entry) => entry.path);
+ expect(gitBlock.status).toContainEqual({ code: " M", path: "app.txt" });
+ expect(gitBlock.status).toContainEqual({ code: "A ", path: "staged.txt" });
+ expect(statusPaths).not.toContain("credentials.json");
+ expect(statusPaths).not.toContain(".env.local");
+ expect(gitBlock.diff).toContain("+line two added");
+ expect(gitBlock.diff).toContain("+staged content");
+ expect(gitBlock.diff).not.toContain("credentials.json");
+ expect(gitBlock.diff).not.toContain("blob.bin");
+ expect(gitBlock.diff).not.toContain("Binary files");
+ expect(gitBlock.diff_truncated).toBe(false);
+ expect(start.manifest.map((entry) => entry.path).sort()).toEqual(["app.txt", "staged.txt"]);
+ const serialized = JSON.stringify(uploads);
+ for (const forbidden of ["ghp_secrettoken123456", "oauth2:", "hunter2", "abcdef123456", "[email protected]", ".git/"]) {
+ expect(serialized).not.toContain(forbidden);
+ }
+ });
+
+ test("caps the git diff and flags truncation", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-collector-bigdiff-"));
+ roots.push(root);
+ await git(root, "init", "-q");
+ await writeFile(join(root, "big.txt"), "seed\n");
+ await git(root, "add", "-A");
+ await git(root, "commit", "-q", "-m", "seed");
+ const lines: string[] = [];
+ for (let index = 0; index < 12_000; index += 1) lines.push(`line ${index} ${"x".repeat(60)}`);
+ await writeFile(join(root, "big.txt"), `${lines.join("\n")}\n`);
+
+ const { uploads, upload } = makeUploads();
+ const collector = new WorkspaceCollector({ upload, fallbackScanMs: 60_000 });
+ collector.startSession("session-v2-bigdiff-1", "workspace-bigdiff", root);
+ await collector.stop();
+
+ const gitBlock = uploads[0]!.workspace.git as { diff: string; diff_truncated: boolean };
+ expect(gitBlock.diff_truncated).toBe(true);
+ expect(Buffer.byteLength(gitBlock.diff)).toBeLessThanOrEqual(MAX_COLLECTOR_DIFF_BYTES);
+ expect(gitBlock.diff).toContain("+line 0 ");
+ });
+
+ test("scopes the git block to a workspace nested inside a larger repository", async () => {
+ const repo = await mkdtemp(join(tmpdir(), "omnirush-collector-nested-"));
+ roots.push(repo);
+ await git(repo, "init", "-q");
+ await mkdir(join(repo, "pkg-a"));
+ await mkdir(join(repo, "pkg-b"));
+ await writeFile(join(repo, "pkg-a", "a.txt"), "a1\n");
+ await writeFile(join(repo, "pkg-b", "b.txt"), "b1\n");
+ await writeFile(join(repo, ".netrc"), "machine example.com login jane password hunter2-netrc\n");
+ await git(repo, "add", "-A");
+ await git(repo, "commit", "-q", "-m", "initial");
+ await writeFile(join(repo, "pkg-b", "b.txt"), "b1\nOUTSIDE-COMMIT\n");
+ await git(repo, "add", "-A");
+ await git(repo, "commit", "-q", "-m", "OUTSIDE-COMMIT touches pkg-b only");
+ await writeFile(join(repo, "pkg-a", "a.txt"), "a1\na2 INSIDE-CHANGE\n");
+ await writeFile(join(repo, "pkg-a", "new.txt"), "untracked\n");
+ await writeFile(join(repo, "pkg-b", "b.txt"), "b2 OUTSIDE-CHANGE\n");
+ await writeFile(join(repo, ".netrc"), "machine example.com login jane password hunter2-CHANGED\n");
+ const head = await git(repo, "rev-parse", "HEAD");
+
+ // A monorepo package: only its own subtree, with workspace-relative paths
+ // that line up with the manifest.
+ const block = (await collectGitBlock(join(repo, "pkg-a")))!;
+ expect(block).not.toBeNull();
+ expect(block.commit).toBe(head);
+ expect(block.dirty).toBe(true);
+ expect([...block.status].sort((left, right) => left.path.localeCompare(right.path))).toEqual([
+ { code: " M", path: "a.txt" },
+ { code: "??", path: "new.txt" },
+ ]);
+ expect(block.diff).toContain("diff --git a/a.txt b/a.txt");
+ expect(block.diff).toContain("+a2 INSIDE-CHANGE");
+ expect(block.recent_commits.map((commit) => commit.subject)).toEqual(["initial"]);
+ const serialized = JSON.stringify(block);
+ for (const forbidden of ["OUTSIDE", "pkg-a/", "pkg-b", ".netrc", "hunter2"]) {
+ expect(serialized).not.toContain(forbidden);
+ }
+
+ // A plain project folder under a repository root (a home directory kept
+ // in a dotfiles repo): nothing beyond the folder itself is described.
+ await mkdir(join(repo, "projects", "foo"), { recursive: true });
+ await writeFile(join(repo, "projects", "foo", "notes.txt"), "hello\n");
+ const nested = (await collectGitBlock(join(repo, "projects", "foo")))!;
+ expect(nested).not.toBeNull();
+ expect(nested.diff).toBeNull();
+ expect(nested.diff_truncated).toBe(false);
+ expect(nested.dirty).toBe(false);
+ expect(nested.recent_commits).toEqual([]);
+ for (const entry of nested.status) {
+ expect(entry.code).toBe("??");
+ expect(entry.path.startsWith("notes.txt") || entry.path === "./").toBe(true);
+ }
+ const nestedSerialized = JSON.stringify(nested);
+ for (const forbidden of ["OUTSIDE", "projects", "pkg-", ".netrc", "hunter2"]) {
+ expect(nestedSerialized).not.toContain(forbidden);
+ }
+ });
+
+ test("clamps git metadata to the collector's field limits after redaction", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-collector-limits-"));
+ roots.push(root);
+ await git(root, "init", "-q");
+ await git(root, "checkout", "-q", "-b", `feature/${Array.from({ length: 6 }, () => "x".repeat(100)).join("/")}`);
+ await git(root, "remote", "add", "origin", `https://example.com/${"r".repeat(2_100)}.git`);
+ await writeFile(join(root, "a.txt"), "a\n");
+ await git(root, "add", "-A");
+ // 980 characters before redaction; every short address becomes the longer
+ // [REDACTED_PII] marker, so only the post-redaction length breaks the cap.
+ await git(root, "commit", "-q", "-m", "[email protected] ".repeat(140).trim());
+
+ const block = (await collectGitBlock(root))!;
+ expect(block).not.toBeNull();
+ expect(block.recent_commits).toHaveLength(1);
+ const subject = block.recent_commits[0]!.subject;
+ expect(subject).not.toContain("[email protected]");
+ expect(subject.startsWith("[REDACTED_PII]")).toBe(true);
+ expect(Array.from(subject)).toHaveLength(1_024);
+ expect(Array.from(block.branch!)).toHaveLength(512);
+ expect(block.branch!.startsWith("feature/")).toBe(true);
+ expect(block.remotes).toHaveLength(1);
+ expect(Array.from(block.remotes[0]!.url)).toHaveLength(2_048);
+ expect(block.remotes[0]!.url.startsWith("https://example.com/")).toBe(true);
+ });
+
+ test("captures prompt and turn_completed snapshots only when the workspace changed", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-collector-triggers-"));
+ roots.push(root);
+ await writeFile(join(root, "a.txt"), "alpha\n");
+ await writeFile(join(root, "b.txt"), "beta\n");
+ const { uploads, upload } = makeUploads();
+ const collector = new WorkspaceCollector({ upload, changeDebounceMs: 60_000, fallbackScanMs: 60_000 });
+ const sessionId = "session-v2-triggers-1";
+ collector.startSession(sessionId, "workspace-triggers", root);
+ collector.captureSnapshot(sessionId, "prompt");
+ await collector.idle(sessionId);
+ expect(uploads.map((item) => item.snapshot_type)).toEqual(["start"]);
+
+ await writeFile(join(root, "a.txt"), "alpha changed\n");
+ collector.captureSnapshot(sessionId, "turn_completed");
+ await collector.idle(sessionId);
+ expect(uploads.map((item) => [item.snapshot_type, item.trigger])).toEqual([["start", "session_start"], ["change", "turn_completed"]]);
+ const change = uploads[1]!;
+ const changedPaths = change.files.map((file) => file.path).filter((path) => !path.startsWith("__omnirush__/"));
+ expect(changedPaths).toEqual(["a.txt"]);
+ expect(change.files.find((file) => file.path === "a.txt")?.sha256).toBe(sha256("alpha changed\n"));
+ expect(change.manifest.map((entry) => entry.path).sort()).toEqual(["a.txt", "b.txt"]);
+ expect(change.manifest.find((entry) => entry.path === "a.txt")?.sha256).toBe(sha256("alpha changed\n"));
+ expect(change.manifest.find((entry) => entry.path === "b.txt")?.sha256).toBe(sha256("beta\n"));
+
+ collector.captureSnapshot(sessionId, "prompt");
+ await collector.idle(sessionId);
+ collector.flushTrace(sessionId);
+ await collector.stop();
+ const triggers = uploads
+ .filter((item) => item.snapshot_type === "trace")
+ .flatMap((item) => item.trace ?? [])
+ .filter((event) => event.type === "collector.trigger")
+ .map((event) => event.data);
+ expect(triggers).toEqual([
+ { trigger: "prompt", captured: false },
+ { trigger: "turn_completed", captured: true },
+ { trigger: "prompt", captured: false },
+ ]);
+ const end = uploads.find((item) => item.snapshot_type === "end")!;
+ expect(end.files.map((file) => file.path).filter((path) => !path.startsWith("__omnirush__/"))).toEqual([]);
+ });
+});
+
+describe("workspace collector durable retry", () => {
+ test("spools failed uploads to disk with a failure ledger and delivers them once the gateway recovers", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-collector-spool-"));
+ const stateDir = await mkdtemp(join(tmpdir(), "omnirush-collector-spool-state-"));
+ roots.push(root, stateDir);
+ await writeFile(join(root, "app.txt"), "hello\n");
+ const uploads: Envelope[] = [];
+ let healthy = false;
+ const warnings: string[] = [];
+ const collector = new WorkspaceCollector({
+ stateDir,
+ upload: async (_sessionId, compressed) => {
+ if (!healthy) return Response.json({ error: "unavailable" }, { status: 503 });
+ uploads.push(JSON.parse(zstdDecompressSync(compressed).toString("utf8")) as Envelope);
+ return Response.json({ ok: true }, { status: 201 });
+ },
+ log: (level, message) => { if (level === "warn") warnings.push(message); },
+ fallbackScanMs: 60_000,
+ uploadRetryDelayMs: 1,
+ retryBaseMs: 60_000,
+ });
+ const sessionId = "session-spool-1234";
+ collector.startSession(sessionId, "workspace-spool", root);
+ await collector.idle(sessionId);
+
+ expect(uploads).toHaveLength(0);
+ expect(await collector.spoolStatus()).toMatchObject({ entries: 1 });
+ expect(warnings).toContain("OmniRush collection artifact spooled for retry");
+ const spoolDir = join(stateDir, "omnirush-collector-spool");
+ const names = (await readdir(spoolDir)).sort();
+ expect(names.some((name) => name.endsWith(".json"))).toBe(true);
+ expect(names.some((name) => name.endsWith(".zst"))).toBe(true);
+ if (process.platform !== "win32") {
+ for (const name of names) expect((await stat(join(spoolDir, name))).mode & 0o777).toBe(0o600);
+ expect((await stat(spoolDir)).mode & 0o777).toBe(0o700);
+ }
+ const ledger = JSON.parse(await readFile(join(stateDir, "omnirush-collector-sessions.json"), "utf8")) as { sessions: Record<string, Record<string, unknown>> };
+ expect(ledger.sessions[sessionId]).toMatchObject({ failureCount: 1, nextSequence: 1 });
+ expect(typeof ledger.sessions[sessionId]?.lastFailureAt).toBe("string");
+ expect(await collector.sessionDeliveryStatus(sessionId)).toMatchObject({ failureCount: 1, lastSuccessAt: null });
+
+ healthy = true;
+ expect(await collector.drainSpool()).toEqual({ delivered: 1, pending: 0 });
+ expect(uploads.map((item) => [item.snapshot_type, item.trigger, item.sequence])).toEqual([["start", "session_start", 1]]);
+ expect(await collector.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
+ await collector.stop();
+ expect(uploads.map((item) => [item.snapshot_type, item.sequence])).toEqual([["start", 1], ["end", 2]]);
+ expect(await collector.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
+ const settled = JSON.parse(await readFile(join(stateDir, "omnirush-collector-sessions.json"), "utf8")) as { sessions: Record<string, Record<string, unknown>> };
+ expect(typeof settled.sessions[sessionId]?.lastSuccessAt).toBe("string");
+ expect(settled.sessions[sessionId]).toMatchObject({ failureCount: 1 });
+ });
+
+ test("retries spooled uploads with backoff on the next collector start", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-collector-respool-"));
+ const stateDir = await mkdtemp(join(tmpdir(), "omnirush-collector-respool-state-"));
+ roots.push(root, stateDir);
+ await writeFile(join(root, "app.txt"), "hello\n");
+ const sessionId = "session-respool-1234";
+ const first = new WorkspaceCollector({
+ stateDir,
+ upload: async () => { throw new Error("network down"); },
+ fallbackScanMs: 60_000,
+ uploadRetryDelayMs: 1,
+ retryBaseMs: 60_000,
+ });
+ first.startSession(sessionId, "workspace-respool", root);
+ await first.stop();
+ expect(await first.spoolStatus()).toMatchObject({ entries: 2 });
+
+ const { uploads, upload } = makeUploads();
+ const second = new WorkspaceCollector({ stateDir, upload, fallbackScanMs: 60_000, retryBaseMs: 10, retryMaxMs: 20 });
+ for (let attempt = 0; attempt < 100 && uploads.length < 2; attempt += 1) {
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+ expect(uploads.map((item) => [item.snapshot_type, item.trigger, item.sequence])).toEqual([["start", "session_start", 1], ["end", "session_end", 2]]);
+ expect(await second.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
+ await second.stop();
+ });
+
+ test("bounds the spool, drops permanently rejected uploads and clears on request", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-collector-spoolcap-"));
+ const stateDir = await mkdtemp(join(tmpdir(), "omnirush-collector-spoolcap-state-"));
+ roots.push(root, stateDir);
+ await writeFile(join(root, "app.txt"), "v0\n");
+ let status = 503;
+ const collector = new WorkspaceCollector({
+ stateDir,
+ upload: async () => Response.json({ error: "nope" }, { status }),
+ fallbackScanMs: 60_000,
+ changeDebounceMs: 60_000,
+ uploadRetryDelayMs: 1,
+ retryBaseMs: 60_000,
+ spoolMaxEntries: 2,
+ });
+ const sessionId = "session-spoolcap-1234";
+ collector.startSession(sessionId, "workspace-spoolcap", root);
+ await collector.idle(sessionId);
+ for (let version = 1; version <= 3; version += 1) {
+ await writeFile(join(root, "app.txt"), `v${version}\n`);
+ collector.captureSnapshot(sessionId, "turn_completed");
+ await collector.idle(sessionId);
+ }
+ expect(await collector.spoolStatus()).toMatchObject({ entries: 2 });
+ const spoolDir = join(stateDir, "omnirush-collector-spool");
+ const sequences = (await Promise.all((await readdir(spoolDir)).filter((name) => name.endsWith(".json"))
+ .map(async (name) => (JSON.parse(await readFile(join(spoolDir, name), "utf8")) as { sequence: number }).sequence))).sort();
+ expect(sequences).toEqual([3, 4]);
+
+ status = 400;
+ await writeFile(join(root, "app.txt"), "v4\n");
+ collector.captureSnapshot(sessionId, "turn_completed");
+ await collector.idle(sessionId);
+ expect(await collector.spoolStatus()).toMatchObject({ entries: 2 });
+ expect(await collector.sessionDeliveryStatus(sessionId)).toMatchObject({ failureCount: 5 });
+
+ await collector.clearSpool();
+ expect(await collector.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
+ await collector.stop();
+ });
+});
+
+describe("workspace collector git helpers", () => {
+ test("clamps text by code points without splitting surrogate pairs", () => {
+ expect(clampCollectorText("abc", 5)).toBe("abc");
+ expect(clampCollectorText("abcdef", 3)).toBe("abc");
+ const faces = "\u{1F600}".repeat(4);
+ expect(clampCollectorText(faces, 4)).toBe(faces);
+ expect(clampCollectorText(faces, 3)).toBe("\u{1F600}".repeat(3));
+ expect(Array.from(clampCollectorText("y".repeat(2_000), 1_024))).toHaveLength(1_024);
+ });
+
+ test("strips userinfo from scheme and scp-like remotes", () => {
+ expect(stripRemoteUserinfo("https://user:[email protected]/org/repo.git")).toBe("https://example.com/org/repo.git");
+ expect(stripRemoteUserinfo("ssh://[email protected]:2222/org/repo.git")).toBe("ssh://example.com:2222/org/repo.git");
+ expect(stripRemoteUserinfo("[email protected]:org/repo.git")).toBe("example.com:org/repo.git");
+ expect(stripRemoteUserinfo("https://example.com/org/repo.git")).toBe("https://example.com/org/repo.git");
+ expect(stripRemoteUserinfo("/srv/git/repo.git")).toBe("/srv/git/repo.git");
+ });
+
+ test("parses plain and quoted diff headers", () => {
+ expect(diffHeaderPath("diff --git a/src/app.ts b/src/app.ts")).toBe("src/app.ts");
+ expect(diffHeaderPath("diff --git a/with space.txt b/with space.txt")).toBe("with space.txt");
+ expect(diffHeaderPath('diff --git "a/caf\\303\\251 \\"x\\".txt" "b/caf\\303\\251 \\"x\\".txt"')).toBe('café "x".txt');
+ expect(diffHeaderPath("diff --git a/one.txt b/two.txt")).toBeNull();
+ expect(diffHeaderPath("not a header")).toBeNull();
+ });
+
+ test("filters denied and binary diff sections and redacts the rest", () => {
+ const raw = [
+ "diff --git a/app.ts b/app.ts",
+ "--- a/app.ts",
+ "+++ b/app.ts",
+ "@@ -1 +1 @@",
+ "-const key = 'old';",
+ "+const key = 'sk-1234567890abcdefghijklmnop';",
+ "diff --git a/.env b/.env",
+ "--- a/.env",
+ "+++ b/.env",
+ "@@ -1 +1 @@",
+ "+PASSWORD=super-secret-value",
+ "diff --git a/blob.bin b/blob.bin",
+ "Binary files a/blob.bin and b/blob.bin differ",
+ "diff --git a/keys/service.json b/keys/service.json",
+ "+{\"private\":true}",
+ "",
+ ].join("\n");
+ const result = filterCollectorDiff(raw);
+ expect(result.truncated).toBe(false);
+ expect(result.diff).toContain("diff --git a/app.ts b/app.ts");
+ expect(result.diff).toContain("[REDACTED]");
+ expect(result.diff).not.toContain("sk-1234567890abcdefghijklmnop");
+ expect(result.diff).not.toContain(".env");
+ expect(result.diff).not.toContain("super-secret-value");
+ expect(result.diff).not.toContain("blob.bin");
+ expect(result.diff).not.toContain("keys/service.json");
+ expect(filterCollectorDiff("")).toEqual({ diff: null, truncated: false });
+ expect(filterCollectorDiff("diff --git a/x b/x\n+ok\n", true).truncated).toBe(true);
+ });
});
diff --git a/apps/server/src/workspace-collector.ts b/apps/server/src/workspace-collector.ts
index 00bfa58a..fb99f7ad 100644
--- a/apps/server/src/workspace-collector.ts
+++ b/apps/server/src/workspace-collector.ts
@@ -1,8 +1,9 @@
-import { createHash } from "node:crypto";
-import { execFile } from "node:child_process";
+import { createHash, randomBytes } from "node:crypto";
+import { execFile, spawn } from "node:child_process";
import { watch, type FSWatcher } from "node:fs";
-import { lstat, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
-import { dirname, join, relative, resolve, sep } from "node:path";
+import { lstat, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
+import { release as osRelease } from "node:os";
+import { basename, dirname, join, relative, resolve, sep } from "node:path";
import { promisify } from "node:util";
import { zstdCompress } from "node:zlib";
import { minimatch } from "minimatch";
@@ -11,24 +12,102 @@ import { externalFetch } from "./server-fetch.js";
const execFileAsync = promisify(execFile);
+export const COLLECTOR_SCHEMA_VERSION = 2;
export const MAX_COLLECTOR_FILE_BYTES = 1024 * 1024;
export const MAX_COLLECTOR_SESSION_BYTES = 64 * 1024 * 1024;
+export const MAX_COLLECTOR_DIFF_BYTES = 512 * 1024;
+export const MAX_COLLECTOR_FILES = 20_000;
+const MAX_FILES = MAX_COLLECTOR_FILES;
const MAX_SNAPSHOT_BYTES = 20 * 1024 * 1024;
const MAX_TRACE_BYTES = 4 * 1024 * 1024;
-const MAX_FILES = 20_000;
const MAX_COMPRESSED_BYTES = 16 * 1024 * 1024;
const CHANGE_DEBOUNCE_MS = 2_000;
const FALLBACK_SCAN_MS = 10_000;
const MAX_CHANGE_JOURNAL_ENTRIES = 512;
const MAX_CHANGE_JOURNAL_BYTES = 768 * 1024;
const MAX_SESSION_LEDGER_ENTRIES = 512;
+const MAX_TOUCHED_PATHS = 128;
+const MAX_GIT_STATUS_ENTRIES = 500;
+const MAX_GIT_RECENT_COMMITS = 50;
+const MAX_GIT_REMOTES = 10;
+const GIT_DIFF_READ_BYTES = 4 * 1024 * 1024;
+// Field limits enforced by the omnirush.ai collector endpoint (counted in code
+// points). A longer value is rejected with 400, which is never retried or
+// spooled, so every free-text field is clamped here *after* redaction: a
+// replacement marker can be longer than the text it replaces.
+const MAX_GIT_SUBJECT_CHARS = 1024;
+const MAX_GIT_REF_CHARS = 512;
+const MAX_GIT_REMOTE_NAME_CHARS = 128;
+const MAX_GIT_REMOTE_URL_CHARS = 2048;
+const MAX_GIT_PATH_CHARS = 4096;
+const MAX_ROOT_NAME_CHARS = 255;
+const MAX_ENVIRONMENT_FIELD_CHARS = 256;
const SESSION_LEDGER_FILE = "omnirush-collector-sessions.json";
+const SPOOL_DIRECTORY = "omnirush-collector-spool";
+const MAX_SPOOL_BYTES = 128 * 1024 * 1024;
+const MAX_SPOOL_ENTRIES = 200;
+const MAX_SPOOL_ATTEMPTS = 24;
+const UPLOAD_ATTEMPTS = 3;
+const UPLOAD_RETRY_DELAY_MS = 250;
+const RETRY_BASE_MS = 5_000;
+const RETRY_MAX_MS = 5 * 60_000;
+const RETRYABLE_STATUSES = new Set([408, 425, 429, 500, 502, 503, 504]);
type SnapshotType = "start" | "change" | "end" | "trace";
+export type CollectorTrigger =
+ | "session_start"
+ | "resume"
+ | "prompt"
+ | "turn_completed"
+ | "fs_change"
+ | "periodic"
+ | "session_end"
+ | "trace_flush";
+
+type ChangeTrigger = Extract<CollectorTrigger, "prompt" | "turn_completed" | "fs_change" | "periodic">;
+
type CollectorFile = {
path: string;
content: string;
+ sha256: string;
+};
+
+type ManifestEntry = {
+ path: string;
+ sha256: string;
+ size: number;
+};
+
+type GitRemote = { name: string; url: string };
+type GitCommit = { sha: string; at: string; subject: string };
+type GitStatusEntry = { code: string; path: string };
+
+export type CollectorGitBlock = {
+ commit: string | null;
+ branch: string | null;
+ dirty: boolean;
+ upstream: string | null;
+ ahead: number | null;
+ behind: number | null;
+ remotes: GitRemote[];
+ recent_commits: GitCommit[];
+ status: GitStatusEntry[];
+ diff: string | null;
+ diff_truncated: boolean;
+};
+
+export type CollectorEnvironment = {
+ os: string;
+ os_version: string;
+ arch: string;
+ app_version: string | null;
+ engine_version: string | null;
+ node_version: string;
+ shell: string | null;
+ locale: string | null;
+ timezone: string | null;
+ git_version: string | null;
};
type TraceEvent = {
@@ -42,6 +121,7 @@ type ChangeJournalEntry = {
at: string;
status: "present" | "deleted" | "skipped";
content?: string;
+ sha256?: string;
};
type SessionLedgerRecord = {
@@ -50,6 +130,9 @@ type SessionLedgerRecord = {
sentBytes?: number;
lastMessageId?: string;
lastSeenAt: string;
+ failureCount?: number;
+ lastFailureAt?: string;
+ lastSuccessAt?: string;
};
type SessionLedger = {
@@ -57,6 +140,26 @@ type SessionLedger = {
sessions: Record<string, SessionLedgerRecord>;
};
+type HashCacheEntry = {
+ size: number;
+ mtimeMs: number;
+ binary: boolean;
+ sha256: string;
+ bytes: number;
+};
+
+type SpoolMeta = {
+ id: string;
+ session_id: string;
+ snapshot_type: SnapshotType;
+ trigger: CollectorTrigger;
+ sequence: number;
+ bytes: number;
+ created_at: string;
+ attempts: number;
+ last_attempt_at?: string;
+};
+
type SessionState = {
id: string;
root: string;
@@ -70,12 +173,19 @@ type SessionState = {
started: boolean;
finished: boolean;
changeTimer: ReturnType<typeof setTimeout> | null;
+ changeTrigger: ChangeTrigger | null;
scanTimer: ReturnType<typeof setInterval> | null;
watcher: FSWatcher | null;
trace: TraceEvent[];
changeJournal: Map<string, ChangeJournalEntry>;
+ touchedPaths: Set<string>;
changeJournalBytes: number;
changeCaptureTail: Promise<void>;
+ hashCache: Map<string, HashCacheEntry>;
+ baseline: Map<string, string> | null;
+ failureCount: number;
+ lastFailureAt?: string;
+ lastSuccessAt?: string;
ready: Promise<void>;
tail: Promise<void>;
};
@@ -89,8 +199,19 @@ type CollectorOptions = {
log?: (level: "info" | "warn", message: string, attributes?: Record<string, unknown>) => void;
changeDebounceMs?: number;
fallbackScanMs?: number;
+ appVersion?: string;
+ engineVersion?: string;
+ uploadRetryDelayMs?: number;
+ retryBaseMs?: number;
+ retryMaxMs?: number;
+ spoolMaxEntries?: number;
+ spoolMaxBytes?: number;
};
+type TransmitOutcome =
+ | { ok: true }
+ | { ok: false; retryable: boolean; reason: string };
+
const DENIED_EXACT_NAMES = new Set([
".git",
".ssh",
@@ -120,6 +241,20 @@ const PII_PATTERNS: Array<[RegExp, string]> = [
[/(?<![\d.])(?:25[0-5]|2[0-4]\d|1?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}(?!\d)/g, "[REDACTED_PII]"],
];
+const PRIVACY_POLICY = {
+ capture_policy: "consented_workspace_session",
+ gitignored_paths_excluded: true,
+ git_internals_excluded: true,
+ environment_variables_excluded: true,
+ denied_path_classes: [".env*", "credentials", "keys", ".git", "node_modules", "binaries_over_1MiB"],
+ redaction: ["provider_secrets", "private_keys", "pii"],
+ manifest_hash_basis: "sha256_of_redacted_utf8",
+ max_file_bytes: MAX_COLLECTOR_FILE_BYTES,
+ max_session_bytes: MAX_COLLECTOR_SESSION_BYTES,
+ max_files: MAX_FILES,
+ max_diff_bytes: MAX_COLLECTOR_DIFF_BYTES,
+} as const;
+
function resolveCollectUrl(rawGatewayUrl: string | undefined): string | null {
const value = rawGatewayUrl?.trim();
if (!value) return null;
@@ -141,6 +276,29 @@ function portablePath(root: string, path: string): string {
return relative(root, path).split(sep).join("/");
}
+export function collectorPathForUpload(path: string): string {
+ return redactCollectorText(path).text;
+}
+
+/**
+ * Truncates text to `limit` code points without splitting a surrogate pair.
+ * The backend counts code points, so this never exceeds its limit.
+ */
+export function clampCollectorText(text: string, limit: number): string {
+ if (text.length <= limit) return text;
+ const points = Array.from(text);
+ return points.length <= limit ? text : points.slice(0, limit).join("");
+}
+
+/** The upload-safe workspace name: basename only, redacted, then clamped. */
+function workspaceRootName(root: string): string {
+ return clampCollectorText(collectorPathForUpload(root.split(sep).filter(Boolean).at(-1) ?? "workspace"), MAX_ROOT_NAME_CHARS);
+}
+
+function sha256Hex(input: string | Buffer): string {
+ return createHash("sha256").update(input).digest("hex");
+}
+
export function isCollectorPathDenied(path: string): boolean {
const parts = path.replaceAll("\\", "/").split("/").filter(Boolean);
return parts.some((part) => {
@@ -172,6 +330,21 @@ export function redactCollectorText(input: string): { text: string; count: numbe
return { text, count };
}
+/**
+ * Removes the userinfo (`user:password@`) from a git remote URL. Both
+ * scheme URLs (`https://token@host/...`) and scp-like remotes
+ * (`git@host:org/repo.git`) lose their userinfo so an embedded access token
+ * can never travel with a snapshot.
+ */
+export function stripRemoteUserinfo(url: string): string {
+ const trimmed = url.trim();
+ const scheme = trimmed.match(/^([a-z][a-z0-9+.-]*:\/\/)([^/?#]*@)?(.*)$/i);
+ if (scheme) return `${scheme[1]}${scheme[3] ?? ""}`;
+ const scp = trimmed.match(/^([^/@:\s]+@)([^/:\s]+:.*)$/);
+ if (scp) return scp[2] ?? trimmed;
+ return trimmed;
+}
+
function isBinary(buffer: Buffer): boolean {
const sample = buffer.subarray(0, Math.min(buffer.length, 8_192));
if (sample.includes(0)) return true;
@@ -182,6 +355,37 @@ function isBinary(buffer: Buffer): boolean {
return sample.length > 0 && suspicious / sample.length > 0.1;
}
+const PATH_FIELD_NAMES = new Set([
+ "path",
+ "file_path",
+ "filepath",
+ "filename",
+ "target_path",
+ "workspace_path",
+]);
+
+function pathCandidates(value: unknown, key = "", output: string[] = [], depth = 0): string[] {
+ if (output.length >= 128 || depth > 6) return output;
+ if (typeof value === "string") {
+ const candidate = value.trim();
+ if (PATH_FIELD_NAMES.has(key.toLowerCase()) && candidate && candidate.length <= 2_048
+ && !candidate.includes("\n") && !candidate.includes("\r") && !candidate.includes("://")) {
+ output.push(candidate);
+ }
+ return output;
+ }
+ if (!value || typeof value !== "object") return output;
+ if (Array.isArray(value)) {
+ for (const item of value) pathCandidates(item, key, output, depth + 1);
+ return output;
+ }
+ for (const [childKey, childValue] of Object.entries(value)) {
+ pathCandidates(childValue, childKey, output, depth + 1);
+ if (output.length >= 128) break;
+ }
+ return output;
+}
+
async function readGitignoreFile(directory: string): Promise<string[]> {
try {
return (await readFile(resolve(directory, ".gitignore"), "utf8"))
@@ -218,6 +422,14 @@ async function gitIgnoresPath(root: string, path: string): Promise<boolean> {
}
}
+function optionalString(value: unknown): string | undefined {
+ return typeof value === "string" ? value : undefined;
+}
+
+function optionalCount(value: unknown): number | undefined {
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
+}
+
async function readSessionLedger(path: string | null): Promise<SessionLedger> {
if (!path) return { version: 1, sessions: {} };
try {
@@ -233,7 +445,17 @@ async function readSessionLedger(path: string | null): Promise<SessionLedger> {
|| typeof record.nextSequence !== "number" || !Number.isSafeInteger(record.nextSequence) || record.nextSequence < 0
|| (record.sentBytes !== undefined && (!Number.isSafeInteger(record.sentBytes) || record.sentBytes < 0))
|| typeof record.lastSeenAt !== "string") return [];
- return [[sessionId, record as SessionLedgerRecord] as const];
+ const cleaned: SessionLedgerRecord = {
+ segment: record.segment,
+ nextSequence: record.nextSequence,
+ lastSeenAt: record.lastSeenAt,
+ ...(record.sentBytes !== undefined ? { sentBytes: record.sentBytes } : {}),
+ ...(optionalString(record.lastMessageId) ? { lastMessageId: record.lastMessageId } : {}),
+ ...(optionalCount(record.failureCount) !== undefined ? { failureCount: record.failureCount } : {}),
+ ...(optionalString(record.lastFailureAt) ? { lastFailureAt: record.lastFailureAt } : {}),
+ ...(optionalString(record.lastSuccessAt) ? { lastSuccessAt: record.lastSuccessAt } : {}),
+ };
+ return [[sessionId, cleaned] as const];
}),
);
return { version: 1, sessions };
@@ -324,21 +546,286 @@ async function listWorkspaceFiles(root: string): Promise<string[]> {
}
}
-async function gitMetadata(root: string): Promise<Record<string, string | null>> {
- const git = async (...args: string[]) => {
+type GitRunResult = { stdout: Buffer; ok: boolean; truncated: boolean };
+
+/**
+ * Runs a read-only git command with a hard output cap and timeout. Output past
+ * the cap is dropped (and the child killed) instead of buffering unbounded
+ * data; callers treat `truncated` as a signal, never as an error.
+ */
+function runGit(root: string, args: string[], options: { maxBytes: number; timeoutMs: number }): Promise<GitRunResult> {
+ return new Promise((resolvePromise) => {
+ const chunks: Buffer[] = [];
+ let total = 0;
+ let truncated = false;
+ let timedOut = false;
+ let settled = false;
+ let child: ReturnType<typeof spawn>;
+ const finish = (ok: boolean) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ resolvePromise({ stdout: Buffer.concat(chunks), ok, truncated });
+ };
+ const timer = setTimeout(() => {
+ timedOut = true;
+ child?.kill("SIGKILL");
+ }, options.timeoutMs);
+ timer.unref?.();
try {
- const { stdout } = await execFileAsync("git", ["-C", root, ...args], { timeout: 5_000, maxBuffer: 64 * 1024 });
- return String(stdout).trim() || null;
+ child = spawn("git", ["-C", root, "-c", "core.quotePath=false", ...args], {
+ stdio: ["ignore", "pipe", "ignore"],
+ windowsHide: true,
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0", GIT_PAGER: "cat", PAGER: "cat" },
+ });
} catch {
+ finish(false);
+ return;
+ }
+ child.stdout?.on("data", (chunk: Buffer) => {
+ if (truncated) return;
+ const remaining = options.maxBytes - total;
+ if (chunk.length > remaining) {
+ chunks.push(chunk.subarray(0, remaining));
+ total += remaining;
+ truncated = true;
+ child.kill("SIGKILL");
+ return;
+ }
+ chunks.push(chunk);
+ total += chunk.length;
+ });
+ child.on("error", () => finish(false));
+ child.on("close", (code) => finish(!timedOut && (truncated || code === 0)));
+ });
+}
+
+async function gitText(root: string, args: string[], maxBytes = 64 * 1024, timeoutMs = 5_000): Promise<string | null> {
+ const result = await runGit(root, args, { maxBytes, timeoutMs });
+ if (!result.ok || result.truncated) return null;
+ const text = result.stdout.toString("utf8").trim();
+ return text || null;
+}
+
+async function gitHead(root: string): Promise<string | null> {
+ return gitText(root, ["rev-parse", "--verify", "-q", "HEAD"]);
+}
+
+/**
+ * Parses `git status --porcelain=v1 -z`. Porcelain paths are always relative
+ * to the repository root, so when the workspace is a subdirectory (`prefix`,
+ * as printed by `git rev-parse --show-prefix`) the prefix is stripped and any
+ * entry outside it is dropped: nothing outside the workspace root may leave
+ * the machine, and paths must match the workspace-relative manifest.
+ */
+function parseGitStatus(raw: string, prefix = ""): { entries: GitStatusEntry[]; dirty: boolean } {
+ const entries: GitStatusEntry[] = [];
+ let dirty = false;
+ for (const record of raw.split("\0")) {
+ if (record.length < 4) continue;
+ const code = record.slice(0, 2);
+ const repoPath = record.slice(3);
+ if (!repoPath) continue;
+ if (prefix && !repoPath.startsWith(prefix)) continue;
+ const path = repoPath.slice(prefix.length);
+ if (!path) continue;
+ if (code !== "??" && code !== "!!") dirty = true;
+ if (isCollectorPathDenied(path)) continue;
+ if (entries.length >= MAX_GIT_STATUS_ENTRIES) continue;
+ const uploadPath = collectorPathForUpload(path);
+ if (uploadPath.length > MAX_GIT_PATH_CHARS) continue;
+ entries.push({ code, path: uploadPath });
+ }
+ return { entries, dirty };
+}
+
+function parseGitRemotes(raw: string): GitRemote[] {
+ const remotes = new Map<string, string>();
+ for (const line of raw.split(/\r?\n/)) {
+ const match = line.match(/^(\S+)\t(.+?)(?:\s+\((fetch|push)\))?$/);
+ if (!match?.[1] || !match[2]) continue;
+ if (remotes.has(match[1]) && match[3] === "push") continue;
+ remotes.set(match[1], match[2]);
+ }
+ return [...remotes.entries()]
+ .slice(0, MAX_GIT_REMOTES)
+ .map(([name, url]) => ({
+ name: clampCollectorText(collectorPathForUpload(name), MAX_GIT_REMOTE_NAME_CHARS),
+ url: clampCollectorText(collectorPathForUpload(stripRemoteUserinfo(url)), MAX_GIT_REMOTE_URL_CHARS),
+ }));
+}
+
+function parseGitLog(raw: string): GitCommit[] {
+ const commits: GitCommit[] = [];
+ for (const record of raw.split("\0")) {
+ const [sha, at, subject] = record.replace(/^\n/, "").split("\x1f");
+ if (!sha || !/^[0-9a-f]{7,64}$/.test(sha) || !at) continue;
+ commits.push({ sha, at, subject: clampCollectorText(collectorPathForUpload(subject ?? ""), MAX_GIT_SUBJECT_CHARS) });
+ if (commits.length >= MAX_GIT_RECENT_COMMITS) break;
+ }
+ return commits;
+}
+
+/**
+ * Decodes a C-style quoted git path (`"a/caf\303\251.txt"`), returning the
+ * unquoted string and the index just past the closing quote, or null when the
+ * quoting is malformed.
+ */
+function unquoteGitPath(text: string, start: number): { value: string; end: number } | null {
+ if (text[start] !== '"') return null;
+ const bytes: number[] = [];
+ let index = start + 1;
+ while (index < text.length) {
+ const char = text[index]!;
+ if (char === '"') return { value: Buffer.from(bytes).toString("utf8"), end: index + 1 };
+ if (char === "\\") {
+ const next = text[index + 1];
+ if (next === undefined) return null;
+ const simple: Record<string, number> = { n: 10, t: 9, r: 13, a: 7, b: 8, f: 12, v: 11, "\\": 92, '"': 34 };
+ if (simple[next] !== undefined) {
+ bytes.push(simple[next]!);
+ index += 2;
+ continue;
+ }
+ const octal = text.slice(index + 1, index + 4);
+ if (/^[0-7]{3}$/.test(octal)) {
+ bytes.push(Number.parseInt(octal, 8));
+ index += 4;
+ continue;
+ }
return null;
}
- };
- const [commit, branch, status] = await Promise.all([
- git("rev-parse", "HEAD"),
- git("branch", "--show-current"),
- git("status", "--porcelain", "--untracked-files=no"),
+ for (const byte of Buffer.from(char, "utf8")) bytes.push(byte);
+ index += 1;
+ }
+ return null;
+}
+
+/** Extracts the b-side path from a `diff --git a/<p> b/<p>` header. */
+export function diffHeaderPath(header: string): string | null {
+ const prefix = "diff --git ";
+ if (!header.startsWith(prefix)) return null;
+ const rest = header.slice(prefix.length).replace(/\r$/, "");
+ if (rest.startsWith('"')) {
+ const quoted = unquoteGitPath(rest, 0);
+ if (!quoted || !quoted.value.startsWith("a/")) return null;
+ return quoted.value.slice(2);
+ }
+ if (!rest.startsWith("a/")) return null;
+ const length = (rest.length - 5) / 2;
+ if (!Number.isInteger(length) || length < 0) return null;
+ const left = rest.slice(2, 2 + length);
+ if (rest.slice(2 + length, 5 + length) !== " b/" || rest.slice(5 + length) !== left) return null;
+ return left;
+}
+
+/**
+ * Keeps only the diff sections that belong to eligible text files, redacts
+ * them, and caps the result. Sections whose header cannot be parsed are
+ * dropped: an unreadable path must never leak a denied file's contents.
+ */
+export function filterCollectorDiff(raw: string, inputTruncated = false): { diff: string | null; truncated: boolean } {
+ let output = "";
+ let used = 0;
+ let truncated = inputTruncated;
+ for (const section of raw.split(/^(?=diff --git )/m)) {
+ if (!section.startsWith("diff --git ")) continue;
+ const headerEnd = section.indexOf("\n");
+ const path = diffHeaderPath(headerEnd === -1 ? section : section.slice(0, headerEnd));
+ if (!path || isCollectorPathDenied(path)) continue;
+ if (/^(?:Binary files .* differ|GIT binary patch)/m.test(section)) continue;
+ const redacted = redactCollectorText(section).text;
+ const size = Buffer.byteLength(redacted);
+ if (used + size > MAX_COLLECTOR_DIFF_BYTES) {
+ truncated = true;
+ if (used === 0) {
+ output = Buffer.from(redacted).subarray(0, MAX_COLLECTOR_DIFF_BYTES).toString("utf8").replace(/�+$/, "");
+ }
+ break;
+ }
+ output += redacted;
+ used += size;
+ }
+ return { diff: output || null, truncated };
+}
+
+/**
+ * Combined staged + unstaged text diff of the workspace. `--relative` with the
+ * `.` pathspec limits the diff to the workspace subtree and makes every header
+ * path workspace-relative, so a workspace that is a subdirectory of a larger
+ * repository (a monorepo package, a project under a home-directory dotfiles
+ * repo) never ships changes from outside its own root.
+ */
+async function gitDiff(root: string, hasHead: boolean): Promise<{ diff: string | null; truncated: boolean }> {
+ const common = ["--no-color", "--no-ext-diff", "--no-textconv", "--no-renames", "--relative", "--src-prefix=a/", "--dst-prefix=b/"];
+ const scope = ["--", "."];
+ const options = { maxBytes: GIT_DIFF_READ_BYTES, timeoutMs: 20_000 };
+ if (hasHead) {
+ const result = await runGit(root, ["diff", "HEAD", ...common, ...scope], options);
+ if (result.ok) return filterCollectorDiff(result.stdout.toString("utf8"), result.truncated);
+ }
+ // An unborn branch has no HEAD to diff against: combine the index (against
+ // the empty tree) with the working tree changes on top of it.
+ const [staged, unstaged] = await Promise.all([
+ runGit(root, ["diff", "--cached", ...common, ...scope], options),
+ runGit(root, ["diff", ...common, ...scope], options),
]);
- return { commit, branch, dirty: status ? "true" : "false" };
+ if (!staged.ok && !unstaged.ok) return { diff: null, truncated: false };
+ const text = `${staged.ok ? staged.stdout.toString("utf8") : ""}${unstaged.ok ? unstaged.stdout.toString("utf8") : ""}`;
+ return filterCollectorDiff(text, staged.truncated || unstaged.truncated);
+}
+
+/**
+ * Builds the safe git summary of a workspace with the git CLI only. Nothing is
+ * read from `.git` directly and no object, pack, hook, or config content is
+ * ever included: the block carries what the repository *is* (HEAD, branch,
+ * upstream, remotes without userinfo, recent subjects) and what is in flight
+ * (porcelain status and the combined text diff), all redacted.
+ */
+export async function collectGitBlock(root: string): Promise<CollectorGitBlock | null> {
+ const inside = await gitText(root, ["rev-parse", "--is-inside-work-tree"]);
+ if (inside !== "true") return null;
+ // Where the workspace sits inside the repository ("" at the top level,
+ // "packages/app/" for a nested workspace). Status, log and diff below are
+ // scoped to that subtree; without a reliable answer the block is skipped
+ // rather than risk describing files outside the workspace root.
+ const prefixResult = await runGit(root, ["rev-parse", "--show-prefix"], { maxBytes: 64 * 1024, timeoutMs: 5_000 });
+ if (!prefixResult.ok || prefixResult.truncated) return null;
+ const prefix = prefixResult.stdout.toString("utf8").trim().replaceAll("\\", "/");
+ const scope = prefix ? ["--", "."] : [];
+ const [commit, branch, upstream, status, remotes, log] = await Promise.all([
+ gitHead(root),
+ gitText(root, ["branch", "--show-current"]),
+ gitText(root, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"]),
+ runGit(root, ["status", "--porcelain=v1", "-z", "--no-renames", "--untracked-files=normal", "--", "."], { maxBytes: 2 * 1024 * 1024, timeoutMs: 15_000 }),
+ gitText(root, ["remote", "-v"]),
+ runGit(root, ["log", `--max-count=${MAX_GIT_RECENT_COMMITS}`, "--no-color", "-z", "--format=%H%x1f%cI%x1f%s", ...scope], { maxBytes: 256 * 1024, timeoutMs: 5_000 }),
+ ]);
+ let ahead: number | null = null;
+ let behind: number | null = null;
+ if (upstream) {
+ const counts = await gitText(root, ["rev-list", "--left-right", "--count", "HEAD...@{upstream}"]);
+ const match = counts?.match(/^(\d+)\s+(\d+)$/);
+ if (match) {
+ ahead = Number.parseInt(match[1]!, 10);
+ behind = Number.parseInt(match[2]!, 10);
+ }
+ }
+ const parsedStatus = status.ok ? parseGitStatus(status.stdout.toString("utf8"), prefix) : { entries: [], dirty: false };
+ const diff = await gitDiff(root, Boolean(commit));
+ return {
+ commit,
+ branch: branch ? clampCollectorText(collectorPathForUpload(branch), MAX_GIT_REF_CHARS) : null,
+ dirty: parsedStatus.dirty,
+ upstream: upstream ? clampCollectorText(collectorPathForUpload(upstream), MAX_GIT_REF_CHARS) : null,
+ ahead,
+ behind,
+ remotes: remotes ? parseGitRemotes(remotes) : [],
+ recent_commits: log.ok ? parseGitLog(log.stdout.toString("utf8")) : [],
+ status: parsedStatus.entries,
+ diff: diff.diff,
+ diff_truncated: diff.truncated,
+ };
}
async function workspaceSignature(root: string): Promise<string> {
@@ -352,49 +839,79 @@ async function workspaceSignature(root: string): Promise<string> {
// A file can disappear while the workspace is being scanned.
}
}
+ // A commit changes the repository without touching any eligible file; fold
+ // HEAD in so the next prompt or turn still captures the new history.
+ hash.update("HEAD\0").update((await gitHead(root)) ?? "").update("\0");
return hash.digest("hex");
}
-async function collectFiles(
+type WorkspaceScan = {
+ manifest: ManifestEntry[];
+ files: CollectorFile[];
+ manifestTruncated: boolean;
+ contentTruncated: boolean;
+};
+
+/**
+ * Walks every eligible workspace file, hashes its uploadable (redacted) form
+ * for the manifest, and gathers content for either the whole tree (start
+ * snapshots) or only the files whose hash differs from the previous manifest.
+ * Unchanged files are recognised by size + mtime through the per-session hash
+ * cache, so repeated snapshots cost a stat per file instead of a read.
+ */
+async function scanWorkspace(
root: string,
+ cache: Map<string, HashCacheEntry>,
+ baseline: Map<string, string> | null,
byteLimit: number,
- workspaceId: string,
- session?: Pick<SessionState, "id" | "segment" | "resumed">,
-): Promise<CollectorFile[]> {
+ includeAll: boolean,
+): Promise<WorkspaceScan> {
+ const manifest: ManifestEntry[] = [];
const files: CollectorFile[] = [];
+ const seen = new Set<string>();
let used = 0;
- const metadata = JSON.stringify({
- workspace_id: workspaceId,
- ...(session ? {
- session_id: session.id,
- session_segment: session.segment,
- session_resumed: session.resumed,
- } : {}),
- root_name: root.split(sep).filter(Boolean).at(-1) ?? "workspace",
- git: await gitMetadata(root),
- });
- files.push({ path: "__omnirush__/workspace.json", content: metadata });
- used += Buffer.byteLength(metadata);
-
- for (const path of await listWorkspaceFiles(root)) {
- if (files.length >= MAX_FILES || used >= byteLimit) break;
+ let contentTruncated = false;
+ const paths = await listWorkspaceFiles(root);
+ for (const path of paths) {
+ if (manifest.length >= MAX_FILES) break;
try {
const absolute = resolve(root, path);
if (portablePath(root, absolute).startsWith("../")) continue;
const file = await lstat(absolute);
if (!file.isFile() || file.isSymbolicLink() || file.size > MAX_COLLECTOR_FILE_BYTES) continue;
- const buffer = await readFile(absolute);
- if (buffer.length > MAX_COLLECTOR_FILE_BYTES || isBinary(buffer)) continue;
- const redacted = redactCollectorText(buffer.toString("utf8")).text;
- const size = Buffer.byteLength(redacted);
- if (used + size > byteLimit) continue;
- files.push({ path, content: redacted });
- used += size;
+ seen.add(path);
+ const cached = cache.get(path);
+ let entry: HashCacheEntry | undefined = cached && cached.size === file.size && cached.mtimeMs === file.mtimeMs ? cached : undefined;
+ let redacted: string | undefined;
+ if (!entry) {
+ const buffer = await readFile(absolute);
+ if (buffer.length > MAX_COLLECTOR_FILE_BYTES || isBinary(buffer)) {
+ cache.set(path, { size: file.size, mtimeMs: file.mtimeMs, binary: true, sha256: "", bytes: 0 });
+ continue;
+ }
+ redacted = redactCollectorText(buffer.toString("utf8")).text;
+ entry = { size: file.size, mtimeMs: file.mtimeMs, binary: false, sha256: sha256Hex(redacted), bytes: Buffer.byteLength(redacted) };
+ cache.set(path, entry);
+ }
+ if (entry.binary) continue;
+ manifest.push({ path, sha256: entry.sha256, size: entry.bytes });
+ const changed = includeAll || baseline?.get(path) !== entry.sha256;
+ if (!changed) continue;
+ if (used + entry.bytes > byteLimit) {
+ contentTruncated = true;
+ continue;
+ }
+ if (redacted === undefined) redacted = redactCollectorText((await readFile(absolute)).toString("utf8")).text;
+ files.push({ path: collectorPathForUpload(path), content: redacted, sha256: sha256Hex(redacted) });
+ used += Buffer.byteLength(redacted);
} catch {
// Workspaces are live; races are expected and retried by the next snapshot.
}
}
- return files;
+ for (const key of cache.keys()) {
+ if (!seen.has(key)) cache.delete(key);
+ }
+ return { manifest, files, manifestTruncated: paths.length >= MAX_FILES, contentTruncated };
}
function compressZstd(payload: Buffer): Promise<Buffer> {
@@ -406,6 +923,67 @@ function compressZstd(payload: Buffer): Promise<Buffer> {
});
}
+function collectorEnvironment(appVersion: string | undefined, engineVersion: string | undefined, gitVersion: string | null): CollectorEnvironment {
+ let locale: string | null = null;
+ let timezone: string | null = null;
+ try {
+ const resolved = Intl.DateTimeFormat().resolvedOptions();
+ locale = resolved.locale || null;
+ timezone = resolved.timeZone || null;
+ } catch {
+ // Intl data can be missing in trimmed runtimes.
+ }
+ const shellPath = process.platform === "win32" ? process.env.COMSPEC : process.env.SHELL;
+ const field = (value: string | null | undefined): string | null =>
+ value?.trim() ? clampCollectorText(value.trim(), MAX_ENVIRONMENT_FIELD_CHARS) : null;
+ return {
+ os: process.platform,
+ os_version: field(osRelease()) ?? "",
+ arch: process.arch,
+ app_version: field(appVersion),
+ engine_version: field(engineVersion),
+ node_version: field(process.versions.node ?? process.version.replace(/^v/, "")) ?? "",
+ shell: shellPath?.trim() ? field(basename(shellPath.trim())) : null,
+ locale: field(locale),
+ timezone: field(timezone),
+ git_version: field(gitVersion),
+ };
+}
+
+function spoolId(counter: number): string {
+ return `${Date.now().toString(16).padStart(12, "0")}-${counter.toString(16).padStart(6, "0")}-${randomBytes(4).toString("hex")}`;
+}
+
+async function writeFileAtomic(path: string, data: Buffer | string): Promise<void> {
+ const temporary = `${path}.${randomBytes(4).toString("hex")}.tmp`;
+ await writeFile(temporary, data, { mode: 0o600 });
+ try {
+ await rename(temporary, path);
+ } catch (error) {
+ await rm(temporary, { force: true }).catch(() => undefined);
+ throw error;
+ }
+}
+
+function parseSpoolMeta(value: unknown): SpoolMeta | null {
+ if (!value || typeof value !== "object") return null;
+ const record = value as Partial<SpoolMeta>;
+ if (typeof record.id !== "string" || typeof record.session_id !== "string" || typeof record.snapshot_type !== "string"
+ || typeof record.trigger !== "string" || typeof record.sequence !== "number" || typeof record.bytes !== "number"
+ || typeof record.created_at !== "string") return null;
+ return {
+ id: record.id,
+ session_id: record.session_id,
+ snapshot_type: record.snapshot_type as SnapshotType,
+ trigger: record.trigger as CollectorTrigger,
+ sequence: record.sequence,
+ bytes: record.bytes,
+ created_at: record.created_at,
+ attempts: optionalCount(record.attempts) ?? 0,
+ ...(optionalString(record.last_attempt_at) ? { last_attempt_at: record.last_attempt_at } : {}),
+ };
+}
+
export class WorkspaceCollector {
private readonly collectUrl: string | null;
private readonly token: string;
@@ -413,12 +991,26 @@ export class WorkspaceCollector {
private readonly uploader?: CollectorOptions["upload"];
private readonly log: NonNullable<CollectorOptions["log"]>;
private readonly ledgerPath: string | null;
+ private readonly spoolDir: string | null;
private readonly ledgerReady: Promise<void>;
private ledger: SessionLedger = { version: 1, sessions: {} };
private ledgerWriteTail: Promise<void> = Promise.resolve();
private readonly sessions = new Map<string, SessionState>();
private readonly changeDebounceMs: number;
private readonly fallbackScanMs: number;
+ private readonly appVersion?: string;
+ private readonly engineVersion?: string;
+ private readonly uploadRetryDelayMs: number;
+ private readonly retryBaseMs: number;
+ private readonly retryMaxMs: number;
+ private readonly spoolMaxEntries: number;
+ private readonly spoolMaxBytes: number;
+ private environmentCache: Promise<CollectorEnvironment> | null = null;
+ private spoolCounter = 0;
+ private spoolTail: Promise<void> = Promise.resolve();
+ private retryTimer: ReturnType<typeof setTimeout> | null = null;
+ private retryFailures = 0;
+ private stopped = false;
constructor(options: CollectorOptions = {}) {
this.collectUrl = resolveCollectUrl(options.gatewayUrl ?? process.env.OMNIRUSH_GATEWAY_URL);
@@ -426,10 +1018,29 @@ export class WorkspaceCollector {
this.fetcher = options.fetch ?? externalFetch;
this.uploader = options.upload;
this.log = options.log ?? (() => undefined);
- this.ledgerPath = options.stateDir ? join(resolve(options.stateDir), SESSION_LEDGER_FILE) : null;
+ const stateDir = options.stateDir ? resolve(options.stateDir) : null;
+ this.ledgerPath = stateDir ? join(stateDir, SESSION_LEDGER_FILE) : null;
+ this.spoolDir = stateDir ? join(stateDir, SPOOL_DIRECTORY) : null;
this.ledgerReady = this.loadLedger();
this.changeDebounceMs = options.changeDebounceMs ?? CHANGE_DEBOUNCE_MS;
this.fallbackScanMs = options.fallbackScanMs ?? FALLBACK_SCAN_MS;
+ this.appVersion = options.appVersion;
+ this.engineVersion = options.engineVersion;
+ this.uploadRetryDelayMs = options.uploadRetryDelayMs ?? UPLOAD_RETRY_DELAY_MS;
+ this.retryBaseMs = options.retryBaseMs ?? RETRY_BASE_MS;
+ this.retryMaxMs = options.retryMaxMs ?? RETRY_MAX_MS;
+ this.spoolMaxEntries = options.spoolMaxEntries ?? MAX_SPOOL_ENTRIES;
+ this.spoolMaxBytes = options.spoolMaxBytes ?? MAX_SPOOL_BYTES;
+ if (this.spoolDir) {
+ if (this.enabled) {
+ // Uploads spooled by a previous process are retried once this one is up.
+ this.scheduleRetry(this.retryBaseMs);
+ } else {
+ // Without an account there is nobody to deliver queued snapshots to;
+ // a sign-out must not leave workspace content waiting on disk.
+ void this.clearSpool().catch(() => undefined);
+ }
+ }
}
private async loadLedger(): Promise<void> {
@@ -448,11 +1059,24 @@ export class WorkspaceCollector {
.catch(() => undefined)
.then(async () => {
await mkdir(dirname(this.ledgerPath!), { recursive: true, mode: 0o700 });
- await writeFile(this.ledgerPath!, snapshot, { encoding: "utf8", mode: 0o600 });
+ await writeFileAtomic(this.ledgerPath!, snapshot);
});
await this.ledgerWriteTail;
}
+ private ledgerRecord(state: SessionState): SessionLedgerRecord {
+ return {
+ segment: state.segment,
+ nextSequence: state.sequence,
+ sentBytes: state.sentBytes,
+ ...(state.lastMessageId ? { lastMessageId: state.lastMessageId } : {}),
+ lastSeenAt: new Date().toISOString(),
+ failureCount: state.failureCount,
+ ...(state.lastFailureAt ? { lastFailureAt: state.lastFailureAt } : {}),
+ ...(state.lastSuccessAt ? { lastSuccessAt: state.lastSuccessAt } : {}),
+ };
+ }
+
private async prepareSession(state: SessionState): Promise<void> {
await this.ledgerReady;
const previous = this.ledger.sessions[state.id];
@@ -460,6 +1084,9 @@ export class WorkspaceCollector {
state.sequence = previous?.nextSequence ?? 0;
state.sentBytes = previous?.sentBytes ?? 0;
state.lastMessageId = previous?.lastMessageId;
+ state.failureCount = previous?.failureCount ?? 0;
+ state.lastFailureAt = previous?.lastFailureAt;
+ state.lastSuccessAt = previous?.lastSuccessAt;
state.resumed = Boolean(previous);
if (state.resumed) {
state.trace.push({
@@ -468,25 +1095,37 @@ export class WorkspaceCollector {
data: { session_segment: state.segment, previous_segment: previous?.segment ?? null },
});
}
- this.ledger.sessions[state.id] = {
- segment: state.segment,
- nextSequence: state.sequence,
- sentBytes: state.sentBytes,
- ...(state.lastMessageId ? { lastMessageId: state.lastMessageId } : {}),
- lastSeenAt: new Date().toISOString(),
- };
+ this.ledger.sessions[state.id] = this.ledgerRecord(state);
await this.saveLedger();
}
private async persistSession(state: SessionState): Promise<void> {
await this.ledgerReady;
- this.ledger.sessions[state.id] = {
- segment: state.segment,
- nextSequence: state.sequence,
- sentBytes: state.sentBytes,
- ...(state.lastMessageId ? { lastMessageId: state.lastMessageId } : {}),
- lastSeenAt: new Date().toISOString(),
- };
+ this.ledger.sessions[state.id] = this.ledgerRecord(state);
+ await this.saveLedger();
+ }
+
+ private async recordLedgerOutcome(sessionId: string, outcome: "success" | "failure"): Promise<void> {
+ const now = new Date().toISOString();
+ const state = this.sessions.get(sessionId);
+ if (state) {
+ if (outcome === "success") state.lastSuccessAt = now;
+ else {
+ state.failureCount += 1;
+ state.lastFailureAt = now;
+ }
+ await this.persistSession(state);
+ return;
+ }
+ await this.ledgerReady;
+ const record = this.ledger.sessions[sessionId];
+ if (!record) return;
+ if (outcome === "success") record.lastSuccessAt = now;
+ else {
+ record.failureCount = (record.failureCount ?? 0) + 1;
+ record.lastFailureAt = now;
+ }
+ record.lastSeenAt = now;
await this.saveLedger();
}
@@ -505,10 +1144,36 @@ export class WorkspaceCollector {
await this.persistSession(state);
}
+ async sessionDeliveryStatus(sessionId: string): Promise<{ failureCount: number; lastFailureAt: string | null; lastSuccessAt: string | null } | null> {
+ await this.ledgerReady;
+ const state = this.sessions.get(sessionId);
+ if (state) {
+ await state.ready;
+ return { failureCount: state.failureCount, lastFailureAt: state.lastFailureAt ?? null, lastSuccessAt: state.lastSuccessAt ?? null };
+ }
+ const record = this.ledger.sessions[sessionId];
+ if (!record) return null;
+ return { failureCount: record.failureCount ?? 0, lastFailureAt: record.lastFailureAt ?? null, lastSuccessAt: record.lastSuccessAt ?? null };
+ }
+
get enabled(): boolean {
return Boolean(this.uploader || (this.collectUrl && this.token));
}
+ private environment(): Promise<CollectorEnvironment> {
+ this.environmentCache ??= (async () => {
+ let gitVersion: string | null = null;
+ try {
+ const { stdout } = await execFileAsync("git", ["--version"], { timeout: 5_000, maxBuffer: 16 * 1024 });
+ gitVersion = String(stdout).trim().replace(/^git version\s+/i, "") || null;
+ } catch {
+ gitVersion = null;
+ }
+ return collectorEnvironment(this.appVersion, this.engineVersion, gitVersion);
+ })();
+ return this.environmentCache;
+ }
+
startSession(sessionId: string, workspaceId: string, root: string): void {
if (!this.enabled || this.sessions.has(sessionId) || !/^[A-Za-z0-9._:-]{8,128}$/.test(sessionId)) return;
const state: SessionState = {
@@ -523,12 +1188,17 @@ export class WorkspaceCollector {
started: false,
finished: false,
changeTimer: null,
+ changeTrigger: null,
scanTimer: null,
watcher: null,
trace: [],
changeJournal: new Map(),
+ touchedPaths: new Set(),
changeJournalBytes: 0,
changeCaptureTail: Promise.resolve(),
+ hashCache: new Map(),
+ baseline: null,
+ failureCount: 0,
ready: Promise.resolve(),
tail: Promise.resolve(),
};
@@ -537,14 +1207,14 @@ export class WorkspaceCollector {
this.enqueue(state, async () => {
await state.ready;
state.lastSignature = await workspaceSignature(root);
- await this.uploadWorkspace(state, "start");
+ await this.uploadWorkspace(state, "start", state.resumed ? "resume" : "session_start");
state.started = true;
});
try {
state.watcher = watch(root, { recursive: true }, (_event, filename) => {
if (filename && isCollectorPathDenied(String(filename))) return;
if (filename) this.queueChangedPath(state, String(filename));
- this.scheduleChange(state);
+ this.scheduleChange(state, "fs_change");
});
state.watcher.on("error", () => {
state.watcher?.close();
@@ -555,7 +1225,7 @@ export class WorkspaceCollector {
}
state.scanTimer = setInterval(() => {
void workspaceSignature(root).then((signature) => {
- if (signature && state.lastSignature && signature !== state.lastSignature) this.scheduleChange(state);
+ if (signature && state.lastSignature && signature !== state.lastSignature) this.scheduleChange(state, "periodic");
state.lastSignature = signature;
}).catch(() => undefined);
}, this.fallbackScanMs);
@@ -565,14 +1235,48 @@ export class WorkspaceCollector {
recordTrace(sessionId: string, type: string, data?: unknown): void {
const state = this.sessions.get(sessionId);
if (!state || state.finished) return;
+ for (const candidate of pathCandidates(data)) this.recordTouchedPath(state, candidate);
state.trace.push({ at: new Date().toISOString(), type, ...(data === undefined ? {} : { data }) });
if (state.trace.length > 5_000) state.trace.splice(0, state.trace.length - 5_000);
}
+ private recordTouchedPath(state: SessionState, candidate: string): void {
+ let path = candidate.replaceAll("\\", "/");
+ if (path.startsWith("/")) {
+ path = portablePath(state.root, resolve(path));
+ } else {
+ path = portablePath(state.root, resolve(state.root, path));
+ }
+ if (!path || path.startsWith("../") || isCollectorPathDenied(path) || state.touchedPaths.has(path)) return;
+ state.touchedPaths.add(path);
+ this.queueChangedPath(state, path);
+ this.scheduleChange(state, "fs_change");
+ }
+
+ /**
+ * Captures a change snapshot for an engine milestone: right as a prompt is
+ * dispatched, or once a turn completes. When nothing changed since the last
+ * snapshot only the trigger is recorded in the trace, so the backend still
+ * sees the milestone without a redundant upload.
+ */
+ captureSnapshot(sessionId: string, trigger: "prompt" | "turn_completed"): void {
+ const state = this.sessions.get(sessionId);
+ if (!state || state.finished) return;
+ if (state.changeTimer) {
+ clearTimeout(state.changeTimer);
+ state.changeTimer = null;
+ state.changeTrigger = null;
+ }
+ this.enqueue(state, () => this.captureChange(state, trigger));
+ }
+
finishSession(sessionId: string, finalTrace?: unknown): void {
const state = this.sessions.get(sessionId);
if (!state || state.finished) return;
const pendingTrace = state.trace.splice(0);
+ if (finalTrace !== undefined) {
+ for (const candidate of pathCandidates(finalTrace)) this.recordTouchedPath(state, candidate);
+ }
state.finished = true;
if (state.changeTimer) clearTimeout(state.changeTimer);
if (state.scanTimer) clearInterval(state.scanTimer);
@@ -583,7 +1287,7 @@ export class WorkspaceCollector {
await state.changeCaptureTail;
if (finalTrace !== undefined) pendingTrace.push({ at: new Date().toISOString(), type: "session.completed", data: finalTrace });
await this.uploadTrace(state, pendingTrace);
- await this.uploadWorkspace(state, "end");
+ await this.uploadWorkspace(state, "end", "session_end");
this.sessions.delete(sessionId);
});
}
@@ -592,7 +1296,10 @@ export class WorkspaceCollector {
const state = this.sessions.get(sessionId);
if (!state || state.finished) return;
const pendingTrace = state.trace.splice(0);
- if (finalTrace !== undefined) pendingTrace.push({ at: new Date().toISOString(), type: "turn.completed", data: finalTrace });
+ if (finalTrace !== undefined) {
+ for (const candidate of pathCandidates(finalTrace)) this.recordTouchedPath(state, candidate);
+ pendingTrace.push({ at: new Date().toISOString(), type: "turn.completed", data: finalTrace });
+ }
if (pendingTrace.length === 0) return;
this.enqueue(state, async () => {
await state.ready;
@@ -601,26 +1308,74 @@ export class WorkspaceCollector {
});
}
+ /** Resolves once every queued capture and upload for the session has settled. */
+ async idle(sessionId: string): Promise<void> {
+ const state = this.sessions.get(sessionId);
+ if (!state) return;
+ await state.changeCaptureTail.catch(() => undefined);
+ await state.tail.catch(() => undefined);
+ }
+
async stop(): Promise<void> {
+ this.stopped = true;
+ if (this.retryTimer) {
+ clearTimeout(this.retryTimer);
+ this.retryTimer = null;
+ }
for (const sessionId of [...this.sessions.keys()]) this.finishSession(sessionId);
await Promise.allSettled([...this.sessions.values()].map((state) => state.tail));
+ await this.spoolTail.catch(() => undefined);
+ await this.ledgerWriteTail.catch(() => undefined);
}
- private scheduleChange(state: SessionState): void {
+ private scheduleChange(state: SessionState, trigger: Extract<ChangeTrigger, "fs_change" | "periodic">): void {
if (state.finished) return;
if (state.changeTimer) clearTimeout(state.changeTimer);
+ // A filesystem change is the more specific reason; keep it when the
+ // periodic scan also notices the same edit.
+ state.changeTrigger = state.changeTrigger === "fs_change" ? "fs_change" : trigger;
state.changeTimer = setTimeout(() => {
state.changeTimer = null;
- this.enqueue(state, async () => {
- const signature = await workspaceSignature(state.root);
- if (!signature || signature === state.lastSignature) return;
- state.lastSignature = signature;
- await this.uploadWorkspace(state, "change");
- });
+ const reason = state.changeTrigger ?? trigger;
+ state.changeTrigger = null;
+ this.enqueue(state, () => this.captureChange(state, reason));
}, this.changeDebounceMs);
state.changeTimer.unref?.();
}
+ private async captureChange(state: SessionState, trigger: ChangeTrigger): Promise<void> {
+ await state.ready;
+ await state.changeCaptureTail;
+ // A finished session is about to upload its end snapshot, which already
+ // carries everything a queued change capture would.
+ if (state.finished) return;
+ const signature = await workspaceSignature(state.root);
+ const changed = Boolean(signature) && (signature !== state.lastSignature || this.journalHasChanges(state));
+ if (trigger === "prompt" || trigger === "turn_completed") {
+ state.trace.push({ at: new Date().toISOString(), type: "collector.trigger", data: { trigger, captured: changed } });
+ }
+ if (!changed) return;
+ state.lastSignature = signature;
+ await this.uploadWorkspace(state, "change", trigger);
+ }
+
+ /**
+ * Whether the journal holds a real change against the last captured
+ * manifest. Watchers replay events for files written just before they
+ * started, and a traced read of an unchanged file is not an edit; neither
+ * should cost an upload.
+ */
+ private journalHasChanges(state: SessionState): boolean {
+ if (!state.baseline) return state.changeJournal.size > 0;
+ for (const entry of state.changeJournal.values()) {
+ const previous = state.baseline.get(entry.path);
+ if (entry.status === "present" ? previous !== (entry.sha256 ?? sha256Hex(entry.content ?? "")) : previous !== undefined) {
+ return true;
+ }
+ }
+ return false;
+ }
+
private queueChangedPath(state: SessionState, filename: string): void {
if (state.finished) return;
state.changeCaptureTail = state.changeCaptureTail
@@ -649,12 +1404,8 @@ export class WorkspaceCollector {
if (buffer.length > MAX_COLLECTOR_FILE_BYTES || isBinary(buffer)) {
entry = { path, at: new Date().toISOString(), status: "skipped" };
} else {
- entry = {
- path,
- at: new Date().toISOString(),
- status: "present",
- content: redactCollectorText(buffer.toString("utf8")).text,
- };
+ const content = redactCollectorText(buffer.toString("utf8")).text;
+ entry = { path, at: new Date().toISOString(), status: "present", content, sha256: sha256Hex(content) };
}
}
} catch {
@@ -691,23 +1442,60 @@ export class WorkspaceCollector {
});
}
- private async uploadWorkspace(state: SessionState, type: Exclude<SnapshotType, "trace">): Promise<void> {
+ private touchedPathsForUpload(state: SessionState): string[] {
+ return [...state.touchedPaths].slice(0, MAX_TOUCHED_PATHS).map(collectorPathForUpload);
+ }
+
+ private async uploadWorkspace(state: SessionState, type: Exclude<SnapshotType, "trace">, trigger: CollectorTrigger): Promise<void> {
const remaining = MAX_COLLECTOR_SESSION_BYTES - state.sentBytes;
if (remaining <= 1_024) return;
- const files = await collectFiles(
- state.root,
- Math.min(MAX_SNAPSHOT_BYTES, remaining - 1_024),
- state.workspaceId,
- state,
- );
+ const [scan, git, environment] = await Promise.all([
+ scanWorkspace(state.root, state.hashCache, state.baseline, Math.min(MAX_SNAPSHOT_BYTES, remaining - 1_024), type === "start"),
+ collectGitBlock(state.root),
+ this.environment(),
+ ]);
+ // The baseline is the last *captured* manifest: the next change snapshot
+ // reports exactly what moved since this one, whatever the upload outcome.
+ state.baseline = new Map(scan.manifest.map((entry) => [entry.path, entry.sha256]));
+ const rootName = workspaceRootName(state.root);
+ const touchedPaths = this.touchedPathsForUpload(state);
+ const metadata = JSON.stringify({
+ schema_version: COLLECTOR_SCHEMA_VERSION,
+ workspace_id: state.workspaceId,
+ session_id: state.id,
+ session_segment: state.segment,
+ session_resumed: state.resumed,
+ trigger,
+ touched_paths: touchedPaths,
+ ...PRIVACY_POLICY,
+ root_name: rootName,
+ git: { commit: git?.commit ?? null, branch: git?.branch ?? null, dirty: git ? String(git.dirty) : "false" },
+ });
+ const files: CollectorFile[] = [
+ { path: "__omnirush__/workspace.json", content: metadata, sha256: sha256Hex(metadata) },
+ ...scan.files,
+ ];
const journal = type === "change" || type === "end" ? [...state.changeJournal.values()] : [];
if (journal.length > 0) {
- files.push({
- path: "__omnirush__/changes.json",
- content: JSON.stringify({ schema_version: 1, session_id: state.id, entries: journal }),
+ const changes = JSON.stringify({
+ schema_version: 1,
+ session_id: state.id,
+ entries: journal.map((entry) => ({ ...entry, path: collectorPathForUpload(entry.path) })),
});
+ files.push({ path: "__omnirush__/changes.json", content: changes, sha256: sha256Hex(changes) });
}
- const uploaded = await this.uploadEnvelope(state, type, files);
+ const uploaded = await this.uploadEnvelope(state, type, trigger, files, {
+ workspace: { root_name: rootName, git },
+ environment,
+ manifest: scan.manifest.map((entry) => ({ ...entry, path: collectorPathForUpload(entry.path) })),
+ privacy: {
+ ...PRIVACY_POLICY,
+ manifest_truncated: scan.manifestTruncated,
+ files_truncated: scan.contentTruncated,
+ diff_truncated: git?.diff_truncated ?? false,
+ },
+ touched_paths: touchedPaths,
+ });
if (uploaded && journal.length > 0) this.acknowledgeJournal(state, journal);
state.lastSignature = await workspaceSignature(state.root);
}
@@ -716,45 +1504,108 @@ export class WorkspaceCollector {
const remaining = MAX_COLLECTOR_SESSION_BYTES - state.sentBytes;
if (remaining <= 1_024 || traceEvents.length === 0) return;
const bounded = boundedTracePayload(state, traceEvents, Math.min(MAX_TRACE_BYTES, remaining - 1_024));
- await this.uploadEnvelope(state, "trace", [{ path: "__omnirush__/trace.json", content: bounded.toString("utf8") }]);
+ const content = bounded.toString("utf8");
+ let events: unknown[] = [];
+ try {
+ const parsed = JSON.parse(content) as { events?: unknown };
+ if (Array.isArray(parsed.events)) events = parsed.events;
+ } catch {
+ events = [];
+ }
+ await this.uploadEnvelope(state, "trace", "trace_flush", [{ path: "__omnirush__/trace.json", content, sha256: sha256Hex(content) }], {
+ workspace: { root_name: workspaceRootName(state.root), git: null },
+ environment: await this.environment(),
+ manifest: [],
+ privacy: { ...PRIVACY_POLICY },
+ touched_paths: this.touchedPathsForUpload(state),
+ trace: events,
+ });
+ }
+
+ private async transmit(sessionId: string, compressed: Uint8Array, attempts = UPLOAD_ATTEMPTS): Promise<TransmitOutcome> {
+ let lastReason = "collector upload unavailable";
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
+ try {
+ const response = this.uploader
+ ? await this.uploader(sessionId, compressed)
+ : await this.fetcher(this.collectUrl!, {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${this.token}`,
+ "Content-Type": "application/zstd",
+ "X-OmniRush-Session-ID": sessionId,
+ },
+ body: compressed.buffer.slice(compressed.byteOffset, compressed.byteOffset + compressed.byteLength) as ArrayBuffer,
+ signal: AbortSignal.timeout(30_000),
+ });
+ if (response.ok) return { ok: true };
+ await response.body?.cancel().catch(() => undefined);
+ lastReason = `collector upload failed with status ${response.status}`;
+ if (!RETRYABLE_STATUSES.has(response.status)) return { ok: false, retryable: false, reason: lastReason };
+ } catch (error) {
+ lastReason = error instanceof Error ? error.message : "collector upload unavailable";
+ }
+ if (attempt < attempts - 1) {
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, this.uploadRetryDelayMs * 2 ** attempt));
+ }
+ }
+ return { ok: false, retryable: true, reason: lastReason };
}
- private async uploadEnvelope(state: SessionState, snapshotType: SnapshotType, files: CollectorFile[]): Promise<boolean> {
+ private async uploadEnvelope(
+ state: SessionState,
+ snapshotType: SnapshotType,
+ trigger: CollectorTrigger,
+ files: CollectorFile[],
+ extras: Record<string, unknown>,
+ ): Promise<boolean> {
if (!this.collectUrl && !this.uploader) return false;
const sequence = state.sequence + 1;
const payload = Buffer.from(JSON.stringify({
- schema_version: 1,
+ schema_version: COLLECTOR_SCHEMA_VERSION,
session_id: state.id,
session_segment: state.segment,
session_resumed: state.resumed,
sequence,
snapshot_type: snapshotType,
+ trigger,
+ captured_at: new Date().toISOString(),
+ ...extras,
files,
}));
if (state.sentBytes + payload.length > MAX_COLLECTOR_SESSION_BYTES) return false;
const compressed = await compressZstd(payload);
if (compressed.length > MAX_COMPRESSED_BYTES) {
- this.log("warn", "OmniRush collection payload exceeded compressed limit", { sessionId: state.id, snapshotType });
+ this.log("warn", "OmniRush collection payload exceeded compressed limit", { sessionId: state.id, snapshotType, trigger });
return false;
}
- const response = this.uploader
- ? await this.uploader(state.id, compressed)
- : await this.fetcher(this.collectUrl!, {
- method: "POST",
- headers: {
- Authorization: `Bearer ${this.token}`,
- "Content-Type": "application/zstd",
- "X-OmniRush-Session-ID": state.id,
- },
- body: compressed.buffer.slice(compressed.byteOffset, compressed.byteOffset + compressed.byteLength) as ArrayBuffer,
- signal: AbortSignal.timeout(30_000),
- });
- if (!response.ok) {
- await response.body?.cancel().catch(() => undefined);
- throw new Error(`collector upload failed with status ${response.status}`);
+ const outcome = await this.transmit(state.id, compressed);
+ if (!outcome.ok) {
+ if (!outcome.retryable || !this.spoolDir) {
+ await this.recordLedgerOutcome(state.id, "failure").catch(() => undefined);
+ throw new Error(outcome.reason);
+ }
+ await this.spoolEnvelope({ id: "", session_id: state.id, snapshot_type: snapshotType, trigger, sequence, bytes: compressed.length, created_at: new Date().toISOString(), attempts: 1 }, compressed);
+ state.sentBytes += payload.length;
+ state.sequence = sequence;
+ state.failureCount += 1;
+ state.lastFailureAt = new Date().toISOString();
+ await this.persistSession(state).catch(() => undefined);
+ this.log("warn", "OmniRush collection artifact spooled for retry", {
+ sessionId: state.id,
+ snapshotType,
+ trigger,
+ sequence,
+ compressedBytes: compressed.length,
+ reason: outcome.reason,
+ });
+ this.retryFailures += 1;
+ this.scheduleRetry();
+ return true;
}
state.sentBytes += payload.length;
state.sequence = sequence;
+ state.lastSuccessAt = new Date().toISOString();
await this.persistSession(state).catch((error: unknown) => {
this.log("warn", "OmniRush session ledger update failed", {
sessionId: state.id,
@@ -764,9 +1615,174 @@ export class WorkspaceCollector {
this.log("info", "OmniRush collection artifact uploaded", {
sessionId: state.id,
snapshotType,
+ trigger,
+ sequence,
fileCount: files.length,
compressedBytes: compressed.length,
});
return true;
}
+
+ // --- durable retry spool -------------------------------------------------
+
+ private spoolLocked<T>(operation: () => Promise<T>): Promise<T> {
+ const run = this.spoolTail.catch(() => undefined).then(operation);
+ this.spoolTail = run.then(() => undefined, () => undefined);
+ return run;
+ }
+
+ private async listSpool(): Promise<SpoolMeta[]> {
+ if (!this.spoolDir) return [];
+ let names: string[];
+ try {
+ names = await readdir(this.spoolDir);
+ } catch {
+ return [];
+ }
+ const entries: SpoolMeta[] = [];
+ for (const name of names) {
+ if (!name.endsWith(".json")) continue;
+ const id = name.slice(0, -".json".length);
+ try {
+ const meta = parseSpoolMeta(JSON.parse(await readFile(join(this.spoolDir, name), "utf8")));
+ if (!meta || meta.id !== id) throw new Error("invalid spool entry");
+ await lstat(join(this.spoolDir, `${id}.zst`));
+ entries.push(meta);
+ } catch {
+ await this.removeSpoolEntry(id);
+ }
+ }
+ return entries.sort((left, right) => left.id.localeCompare(right.id));
+ }
+
+ private async removeSpoolEntry(id: string): Promise<void> {
+ if (!this.spoolDir) return;
+ await Promise.all([
+ rm(join(this.spoolDir, `${id}.json`), { force: true }),
+ rm(join(this.spoolDir, `${id}.zst`), { force: true }),
+ ]).catch(() => undefined);
+ }
+
+ private async writeSpoolMeta(meta: SpoolMeta): Promise<void> {
+ await writeFileAtomic(join(this.spoolDir!, `${meta.id}.json`), JSON.stringify(meta));
+ }
+
+ private spoolEnvelope(meta: SpoolMeta, compressed: Uint8Array): Promise<void> {
+ return this.spoolLocked(async () => {
+ if (!this.spoolDir) return;
+ await mkdir(this.spoolDir, { recursive: true, mode: 0o700 });
+ const id = spoolId(++this.spoolCounter);
+ // Payload first, then the metadata that makes the entry visible: a crash
+ // in between leaves an orphan that the next listing removes.
+ await writeFileAtomic(join(this.spoolDir, `${id}.zst`), Buffer.from(compressed));
+ await this.writeSpoolMeta({ ...meta, id });
+ await this.enforceSpoolBounds();
+ });
+ }
+
+ private async enforceSpoolBounds(): Promise<void> {
+ const entries = await this.listSpool();
+ let total = entries.reduce((sum, entry) => sum + entry.bytes, 0);
+ let count = entries.length;
+ for (const entry of entries) {
+ if (count <= this.spoolMaxEntries && total <= this.spoolMaxBytes) break;
+ await this.removeSpoolEntry(entry.id);
+ total -= entry.bytes;
+ count -= 1;
+ this.log("warn", "OmniRush collection spool dropped its oldest entry", {
+ sessionId: entry.session_id,
+ snapshotType: entry.snapshot_type,
+ sequence: entry.sequence,
+ });
+ }
+ }
+
+ private scheduleRetry(delayMs?: number): void {
+ if (!this.spoolDir || this.stopped || this.retryTimer) return;
+ const backoff = Math.min(this.retryMaxMs, this.retryBaseMs * 2 ** Math.max(0, this.retryFailures - 1));
+ const delay = delayMs ?? Math.round(backoff * (0.85 + Math.random() * 0.3));
+ this.retryTimer = setTimeout(() => {
+ this.retryTimer = null;
+ void this.drainSpool().catch(() => undefined);
+ }, delay);
+ this.retryTimer.unref?.();
+ }
+
+ /** Delivers spooled uploads oldest first, stopping at the first failure. */
+ drainSpool(): Promise<{ delivered: number; pending: number }> {
+ return this.spoolLocked(async () => {
+ let delivered = 0;
+ if (!this.spoolDir || !this.enabled) return { delivered, pending: 0 };
+ const entries = await this.listSpool();
+ let pending = entries.length;
+ for (const entry of entries) {
+ if (this.stopped) break;
+ let compressed: Buffer;
+ try {
+ compressed = await readFile(join(this.spoolDir, `${entry.id}.zst`));
+ } catch {
+ await this.removeSpoolEntry(entry.id);
+ pending -= 1;
+ continue;
+ }
+ const outcome = await this.transmit(entry.session_id, compressed, 1);
+ if (outcome.ok) {
+ await this.removeSpoolEntry(entry.id);
+ await this.recordLedgerOutcome(entry.session_id, "success").catch(() => undefined);
+ this.retryFailures = 0;
+ delivered += 1;
+ pending -= 1;
+ this.log("info", "OmniRush collection artifact delivered from spool", {
+ sessionId: entry.session_id,
+ snapshotType: entry.snapshot_type,
+ trigger: entry.trigger,
+ sequence: entry.sequence,
+ attempts: entry.attempts + 1,
+ });
+ continue;
+ }
+ if (!outcome.retryable || entry.attempts + 1 >= MAX_SPOOL_ATTEMPTS) {
+ await this.removeSpoolEntry(entry.id);
+ pending -= 1;
+ this.log("warn", "OmniRush collection artifact dropped from spool", {
+ sessionId: entry.session_id,
+ snapshotType: entry.snapshot_type,
+ sequence: entry.sequence,
+ reason: outcome.reason,
+ });
+ continue;
+ }
+ await this.writeSpoolMeta({ ...entry, attempts: entry.attempts + 1, last_attempt_at: new Date().toISOString() }).catch(() => undefined);
+ await this.recordLedgerOutcome(entry.session_id, "failure").catch(() => undefined);
+ this.retryFailures += 1;
+ this.scheduleRetry();
+ break;
+ }
+ return { delivered, pending };
+ });
+ }
+
+ /** Number of spooled uploads and their compressed size on disk. */
+ spoolStatus(): Promise<{ entries: number; bytes: number }> {
+ return this.spoolLocked(async () => {
+ const entries = await this.listSpool();
+ return { entries: entries.length, bytes: entries.reduce((sum, entry) => sum + entry.bytes, 0) };
+ });
+ }
+
+ /**
+ * Discards every spooled upload. Wire this to sign-out and consent
+ * withdrawal: once the account is gone nothing may stay queued on disk.
+ */
+ clearSpool(): Promise<void> {
+ if (this.retryTimer) {
+ clearTimeout(this.retryTimer);
+ this.retryTimer = null;
+ }
+ this.retryFailures = 0;
+ return this.spoolLocked(async () => {
+ if (!this.spoolDir) return;
+ await rm(this.spoolDir, { recursive: true, force: true });
+ });
+ }
}
diff --git a/packages/types/src/desktop-ipc.ts b/packages/types/src/desktop-ipc.ts
index e97b966c..012796f0 100644
--- a/packages/types/src/desktop-ipc.ts
+++ b/packages/types/src/desktop-ipc.ts
@@ -528,7 +528,7 @@ export type DesktopCommandMap = {
args: [options?: { gatewayUrl?: string; deviceName?: string }];
result: { connected: true; userCode: string };
};
- omnirushAccountSignOut: { args: []; result: { connected: false } };
+ omnirushAccountSignOut: { args: []; result: { connected: false; remoteRevoked: boolean } };
automationRunnerConfigure: {
args: [configuration: { baseUrl: string; token: string; runnerId: string } | null];
result: { connected: boolean };