A desktop coding agent with free access to frontier models.
TypeScript
feat: add authenticated trace and workspace collection
Samrat Talukdar3642243e5975
diff --git a/apps/app/src/app/lib/desktop.ts b/apps/app/src/app/lib/desktop.tsindex 21b5682e..e9e28758 100644--- a/apps/app/src/app/lib/desktop.ts+++ b/apps/app/src/app/lib/desktop.ts@@ -732,6 +732,9 @@ const {nukeOmniRushAndOpencodeConfigAndExit,sandboxCleanupOmniRushContainers,omnirushServerInfo,+ omnirushAccountStatus,+ omnirushAccountConnect,+ omnirushAccountSignOut,omnirushServerRestart,runtimeBootstrap,engineInfo,@@ -787,6 +790,9 @@ export {nukeOmniRushAndOpencodeConfigAndExit,sandboxCleanupOmniRushContainers,omnirushServerInfo,+ omnirushAccountStatus,+ omnirushAccountConnect,+ omnirushAccountSignOut,omnirushServerRestart,runtimeBootstrap,engineInfo,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.tsxindex 7316d8b4..1091daac 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@@ -1,4 +1,5 @@/** @jsxImportSource react */+import { useEffect, useState } from "react";import {ArrowRight,Cog,@@ -8,10 +9,17 @@ import {Sparkles,Terminal,Wrench,+ UserRoundCheck,} from "lucide-react";import { t } from "../../../../i18n";import type { SettingsTab } from "../../../../app/types";+import {+ omnirushAccountConnect,+ omnirushAccountSignOut,+ omnirushAccountStatus,+} from "../../../../app/lib/desktop";+import { isElectronRuntime } from "../../../../app/utils";export type GeneralSettingsViewProps = {onNavigateTab: (tab: SettingsTab) => void;@@ -69,8 +77,75 @@ function SettingsCard(props: {}export function GeneralSettingsView(props: GeneralSettingsViewProps) {+ const [account, setAccount] = useState<{ connected: boolean; gatewayConfigured: boolean } | null>(null);+ const [accountBusy, setAccountBusy] = useState(false);+ const [accountMessage, setAccountMessage] = useState("");++ useEffect(() => {+ if (!isElectronRuntime()) return;+ void omnirushAccountStatus().then(setAccount).catch(() => setAccount({ connected: false, gatewayConfigured: false }));+ }, []);++ async function connectAccount() {+ setAccountBusy(true);+ setAccountMessage("Approve the device link in your browser…");+ try {+ await omnirushAccountConnect();+ setAccount(await omnirushAccountStatus());+ setAccountMessage("Account connected. Astra routing is ready.");+ } catch (error) {+ setAccountMessage(error instanceof Error ? error.message : "The account could not be connected.");+ } finally {+ setAccountBusy(false);+ }+ }++ async function signOutAccount() {+ setAccountBusy(true);+ try {+ await omnirushAccountSignOut();+ setAccount({ connected: false, gatewayConfigured: account?.gatewayConfigured ?? false });+ setAccountMessage("Signed out on this Mac.");+ } finally {+ setAccountBusy(false);+ }+ }+return (<div className="w-full max-w-3xl space-y-8">+ {isElectronRuntime() && account && (+ <div className="space-y-3">+ <div className="text-[11px] font-semibold uppercase tracking-[0.15em] text-dls-secondary">+ OmniRush account+ </div>+ <div className="flex items-center gap-4 rounded-2xl border border-dls-border bg-dls-surface p-4">+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-dls-border bg-dls-hover">+ <UserRoundCheck size={17} className={account.connected ? "text-emerald-400" : "text-dls-secondary"} />+ </div>+ <div className="min-w-0 flex-1">+ <div className="text-[13px] font-medium text-dls-text">+ {account.connected ? "Connected" : "Connect your account"}+ </div>+ <div className="text-[11px] text-dls-secondary">+ {accountMessage || (account.connected+ ? "Secure model access and usage are linked to this Mac."+ : account.gatewayConfigured+ ? "Sign in in your browser, then return here."+ : "The OmniRush account service has not been configured for this build.")}+ </div>+ </div>+ {account.connected ? (+ <button type="button" disabled={accountBusy} onClick={() => void signOutAccount()} className="rounded-lg border border-dls-border px-3 py-2 text-[12px] text-dls-secondary hover:bg-dls-hover disabled:opacity-50">+ Sign out+ </button>+ ) : (+ <button type="button" disabled={accountBusy || !account.gatewayConfigured} onClick={() => void connectAccount()} className="rounded-lg bg-dls-text px-3 py-2 text-[12px] font-medium text-dls-bg disabled:opacity-50">+ {accountBusy ? "Waiting…" : "Connect"}+ </button>+ )}+ </div>+ </div>+ )}{/* Workspace settings */}<div className="space-y-3"><div className="text-[11px] font-semibold uppercase tracking-[0.15em] text-dls-secondary">diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjsindex da2d75f8..1dfc2eef 100644--- a/apps/desktop/electron/main.mjs+++ b/apps/desktop/electron/main.mjs@@ -78,6 +78,7 @@ import {} from "./brand-icon-windows.mjs";import { resetMacDockIcon } from "./brand-icon-darwin.mjs";import { createDesktopVaultKeyProvider } from "./secure-vault-key.mjs";+import { createDesktopOmniRushAccountStore } from "./omnirush-account.mjs";import {clearOmniRushSentrySession,initOmniRushSentry,@@ -1302,6 +1303,11 @@ function validateSkillName(raw) {return trimmed;}+const omnirushAccountStore = createDesktopOmniRushAccountStore({+ filePath: path.join(app.getPath("userData"), "omnirush-account.bin"),+ loadSafeStorage: () => require("electron").safeStorage,+});+const runtimeManager = createRuntimeManager({app,desktopRoot: path.resolve(__dirname, ".."),@@ -1313,6 +1319,7 @@ const runtimeManager = createRuntimeManager({filePath: path.join(app.getPath("userData"), "local-managed-mcp-vault-key.bin"),loadSafeStorage: () => require("electron").safeStorage,}),+ omnirushGatewayCredentials: omnirushAccountStore,});const initialRunnerBootstrap = workspaceStore.readDesktopBootstrapConfigSync();const legacyRunnerBaseUrls = [@@ -2036,6 +2043,24 @@ const desktopCommandHandlers = {"omnirushServerInfo": async (event, ...args) => {return runtimeManager.omnirushServerInfo();},+ "omnirushAccountStatus": async () => {+ return omnirushAccountStore.status();+ },+ "omnirushAccountConnect": async (_event, ...args) => {+ const input = args[0] ?? {};+ const result = await omnirushAccountStore.authorize({+ gatewayUrl: String(input.gatewayUrl ?? "").trim() || undefined,+ deviceName: String(input.deviceName ?? "").trim() || `${app.getName()} on ${os.hostname()}`,+ openVerification: (url) => shell.openExternal(url),+ });+ await runtimeManager.omnirushServerRestart({});+ return result;+ },+ "omnirushAccountSignOut": async () => {+ await omnirushAccountStore.clear();+ await runtimeManager.omnirushServerRestart({});+ return { connected: false };+ },"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.mjsnew file mode 100644index 00000000..8c032126--- /dev/null+++ b/apps/desktop/electron/omnirush-account.mjs@@ -0,0 +1,191 @@+import { execFile } from "node:child_process";+import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";+import path from "node:path";+import { promisify } from "node:util";++const execFileAsync = promisify(execFile);++const KEYCHAIN_SERVICES = {+ gatewayUrl: "ai.omnirush.desktop.gateway-url",+ accessToken: "ai.omnirush.desktop.gateway-access",+ refreshToken: "ai.omnirush.desktop.gateway-refresh",+};+const DEFAULT_GATEWAY_URL = "https://api.omnirush.ai/omnirush/v1";+const DEV_GATEWAY_URL = "http://localhost:8090/omnirush/v1";++function normalizeCredential(value) {+ return typeof value === "string" && value.trim() ? value.trim() : null;+}++function normalizeGatewayUrl(value) {+ const normalized = normalizeCredential(value);+ if (!normalized) return null;+ try {+ const url = new URL(normalized);+ if (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "::1"].includes(url.hostname))) return null;+ return url.toString().replace(/\/+$/, "");+ } catch {+ return null;+ }+}++function validCredentials(value) {+ if (!value || typeof value !== "object") return null;+ const gatewayUrl = normalizeGatewayUrl(value.gatewayUrl);+ const accessToken = normalizeCredential(value.accessToken);+ const refreshToken = normalizeCredential(value.refreshToken);+ if (!gatewayUrl || !accessToken || !refreshToken) return null;+ return { gatewayUrl, accessToken, refreshToken };+}++async function readMacKeychain(service, platform) {+ if (platform !== "darwin") return null;+ try {+ const { stdout } = await execFileAsync("/usr/bin/security", ["find-generic-password", "-s", service, "-w"], {+ timeout: 5_000,+ maxBuffer: 64 * 1024,+ });+ return normalizeCredential(stdout);+ } catch {+ return null;+ }+}++export function createDesktopOmniRushAccountStore({+ filePath,+ loadSafeStorage,+ platform = process.platform,+ env = process.env,+ fetchImpl = globalThis.fetch,+ sleep = (milliseconds) => new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds)),+}) {+ let cached = null;+ const signedOutPath = `${filePath}.signed-out`;++ async function safeStorage() {+ const storage = loadSafeStorage();+ if (!storage || !(await storage.isAsyncEncryptionAvailable())) return null;+ if (platform === "linux" && storage.getSelectedStorageBackend() === "basic_text") return null;+ return storage;+ }++ async function loadFile() {+ try {+ const storage = await safeStorage();+ if (!storage) return null;+ const encrypted = await readFile(filePath);+ const decrypted = await storage.decryptStringAsync(encrypted);+ const credentials = validCredentials(JSON.parse(decrypted.result));+ if (credentials && decrypted.shouldReEncrypt) await save(credentials);+ return credentials;+ } catch {+ return null;+ }+ }++ async function load() {+ if (cached) return cached;+ const stored = await loadFile();+ if (stored) {+ cached = stored;+ return stored;+ }+ try {+ await readFile(signedOutPath);+ return null;+ } catch {+ // No sign-out sentinel: legacy credentials may be imported once.+ }+ const imported = validCredentials({+ gatewayUrl: env.OMNIRUSH_GATEWAY_URL ?? await readMacKeychain(KEYCHAIN_SERVICES.gatewayUrl, platform),+ accessToken: env.OMNIRUSH_ACCESS_TOKEN ?? await readMacKeychain(KEYCHAIN_SERVICES.accessToken, platform),+ refreshToken: env.OMNIRUSH_REFRESH_TOKEN ?? await readMacKeychain(KEYCHAIN_SERVICES.refreshToken, platform),+ });+ if (imported) {+ cached = imported;+ await save(imported);+ }+ return imported;+ }++ async function save(credentials) {+ const normalized = validCredentials(credentials);+ if (!normalized) throw new Error("Invalid OmniRush account credential bundle");+ const storage = await safeStorage();+ if (!storage) throw new Error("Secure desktop credential storage is unavailable");+ const encrypted = await storage.encryptStringAsync(JSON.stringify(normalized));+ await mkdir(path.dirname(filePath), { recursive: true });+ const temporary = `${filePath}.${process.pid}.tmp`;+ await writeFile(temporary, encrypted, { mode: 0o600 });+ await rename(temporary, filePath).catch(async (error) => {+ await rm(temporary, { force: true }).catch(() => undefined);+ throw error;+ });+ await rm(signedOutPath, { force: true });+ cached = normalized;+ }++ async function configuredGatewayUrl() {+ return normalizeGatewayUrl(env.OMNIRUSH_GATEWAY_URL)+ ?? normalizeGatewayUrl(await readMacKeychain(KEYCHAIN_SERVICES.gatewayUrl, platform))+ ?? (env.OMNIRUSH_DEV_MODE === "1" ? DEV_GATEWAY_URL : DEFAULT_GATEWAY_URL);+ }++ async function authorize({ gatewayUrl, deviceName, openVerification }) {+ const explicitGateway = normalizeCredential(gatewayUrl);+ const configured = explicitGateway ? normalizeGatewayUrl(explicitGateway) : await configuredGatewayUrl();+ if (!configured) throw new Error("OmniRush account service is not configured");+ const base = new URL(configured);+ base.pathname = base.pathname.replace(/\/+$/, "").replace(/\/v1$/, "");+ const authorizeUrl = new URL(base);+ authorizeUrl.pathname += "/device/authorize";+ const issuedResponse = await fetchImpl(authorizeUrl, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ device_name: deviceName, platform }),+ signal: AbortSignal.timeout(20_000),+ });+ if (!issuedResponse.ok) throw new Error(`Could not start account link (${issuedResponse.status})`);+ const issued = await issuedResponse.json();+ if (!issued?.device_code || !issued?.verification_uri_complete) throw new Error("Account service returned an invalid device link");+ await openVerification(issued.verification_uri_complete);++ const tokenUrl = new URL(base);+ tokenUrl.pathname += "/device/token";+ const interval = Math.max(2, Number(issued.interval) || 3) * 1_000;+ const deadline = Date.now() + Math.max(60, Number(issued.expires_in) || 600) * 1_000;+ while (Date.now() < deadline) {+ await sleep(interval);+ const tokenResponse = await fetchImpl(tokenUrl, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ device_code: issued.device_code }),+ signal: AbortSignal.timeout(20_000),+ });+ if (tokenResponse.status === 428) continue;+ if (!tokenResponse.ok) throw new Error(`Account link failed (${tokenResponse.status})`);+ const payload = await tokenResponse.json();+ const credentials = validCredentials({+ gatewayUrl: payload.gateway_url ?? configured,+ accessToken: payload.access_token,+ refreshToken: payload.refresh_token,+ });+ if (!credentials) throw new Error("Account service returned invalid credentials");+ await save(credentials);+ return /** @type {const} */ ({ connected: true, userCode: String(issued.user_code ?? "") });+ }+ throw new Error("Account link expired before it was approved");+ }++ async function status() {+ return { connected: Boolean(await load()), gatewayConfigured: Boolean(await configuredGatewayUrl()) };+ }++ async function clear() {+ cached = null;+ await rm(filePath, { force: true });+ await writeFile(signedOutPath, "signed-out\n", { mode: 0o600 });+ }++ return { load, save, authorize, status, clear };+}diff --git a/apps/desktop/electron/omnirush-account.test.mjs b/apps/desktop/electron/omnirush-account.test.mjsnew file mode 100644index 00000000..b427f859--- /dev/null+++ b/apps/desktop/electron/omnirush-account.test.mjs@@ -0,0 +1,109 @@+import assert from "node:assert/strict";+import { mkdtemp, readFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import test from "node:test";++import { createDesktopOmniRushAccountStore } from "./omnirush-account.mjs";++function testStorage() {+ return {+ isAsyncEncryptionAvailable: async () => true,+ getSelectedStorageBackend: () => "keychain",+ encryptStringAsync: async (value) => Buffer.from(value, "utf8"),+ decryptStringAsync: async (value) => ({ result: value.toString("utf8"), shouldReEncrypt: false }),+ };+}++async function storeOptions(overrides = {}) {+ const directory = await mkdtemp(path.join(os.tmpdir(), "omnirush-account-"));+ return {+ filePath: path.join(directory, "account.bin"),+ loadSafeStorage: () => testStorage(),+ platform: /** @type {NodeJS.Platform} */ ("linux"),+ env: { OMNIRUSH_DEV_MODE: "1" },+ sleep: async () => undefined,+ ...overrides,+ };+}++test("device authorization polls, encrypts, and restores the account", async () => {+ const requests = [];+ let polls = 0;+ const options = await storeOptions({+ fetchImpl: async (url) => {+ requests.push(new URL(url).pathname);+ if (String(url).endsWith("/device/authorize")) {+ return Response.json({+ device_code: "device-code",+ user_code: "ABCD-EFGH",+ verification_uri_complete: "http://localhost:5175/console?code=ABCD-EFGH",+ interval: 0,+ expires_in: 60,+ });+ }+ polls += 1;+ if (polls === 1) return Response.json({ detail: "authorization_pending" }, { status: 428 });+ return Response.json({+ gateway_url: "http://localhost:8090/omnirush/v1",+ access_token: "access-token",+ refresh_token: "refresh-token",+ });+ },+ });+ const opened = [];+ const store = createDesktopOmniRushAccountStore(options);+ const result = await store.authorize({+ gatewayUrl: undefined,+ deviceName: "Test Mac",+ openVerification: async (url) => { opened.push(url); },+ });+ assert.deepEqual(result, { connected: true, userCode: "ABCD-EFGH" });+ assert.deepEqual(opened, ["http://localhost:5175/console?code=ABCD-EFGH"]);+ assert.deepEqual(requests, [+ "/omnirush/device/authorize",+ "/omnirush/device/token",+ "/omnirush/device/token",+ ]);+ assert.equal((await store.status()).connected, true);+ assert.match(await readFile(options.filePath, "utf8"), /access-token/);++ const restored = createDesktopOmniRushAccountStore(options);+ assert.equal((await restored.status()).connected, true);+});++test("sign out prevents legacy credentials from being imported again", 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",+ },+ });+ const store = createDesktopOmniRushAccountStore(options);+ assert.equal((await store.status()).connected, true);+ await store.clear();+ const restarted = createDesktopOmniRushAccountStore(options);+ assert.equal((await restarted.status()).connected, false);+});++test("rejects an insecure non-loopback account endpoint", async () => {+ let requested = false;+ const options = await storeOptions({+ fetchImpl: async () => {+ requested = true;+ return Response.json({});+ },+ });+ const store = createDesktopOmniRushAccountStore(options);+ await assert.rejects(+ store.authorize({+ gatewayUrl: "http://example.com/omnirush/v1",+ deviceName: "Test Mac",+ openVerification: async () => undefined,+ }),+ /not configured/,+ );+ assert.equal(requested, false);+});diff --git a/apps/desktop/electron/runtime.mjs b/apps/desktop/electron/runtime.mjsindex 18809caa..c46d73f7 100644--- a/apps/desktop/electron/runtime.mjs+++ b/apps/desktop/electron/runtime.mjs@@ -1375,6 +1375,7 @@ export function createRuntimeManager({desktopRoot,listLocalWorkspacePaths,localManagedMcpVaultKey,+ omnirushGatewayCredentials = null,workspaceMkdir = mkdir,workspacePlatform = process.platform,}) {@@ -1915,9 +1916,19 @@ export function createRuntimeManager({engineState.opencodeBinSource = managedOpencode?.source ?? null;}+ // Load the desktop account before creating the embedded broker. Account+ // tokens stay in the Electron main process and are never serialized into+ // OpenCode config or passed to the renderer.+ const gatewayCredentials = await omnirushGatewayCredentials?.load?.() ?? null;+// Inject user env vars so the server and managed OpenCode inherit them.const serverEnv = await buildChildEnv({});Object.assign(process.env, serverEnv);+ if (gatewayCredentials) {+ // The refresh grant belongs to the Electron account store and loopback+ // broker. Never let it flow into the managed OpenCode child or plugins.+ delete process.env.OMNIRUSH_REFRESH_TOKEN;+ }// Once the embedded server has a persisted registry, it is the source of// truth. Do not pass Electron's legacy workspace list as CLI workspaces or@@ -1975,6 +1986,12 @@ export function createRuntimeManager({opencodeBin: managedOpencode?.path ?? undefined,opencodeCwd: managedOpencodeWorkdir(),localManagedMcpVaultKey,+ omnirushGatewayCredentials: gatewayCredentials+ ? {+ ...gatewayCredentials,+ persist: (credentials) => omnirushGatewayCredentials.save(credentials),+ }+ : undefined,});inProcessServer = handle;omnirushServerState.managedOpencodeExecution = handle.managedOpencodeExecution ?? null;diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 00b340f1..ed0181c4 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -25,6 +25,7 @@"typecheck:electron": "pnpm --dir ../server exec tsc -p ../desktop/tsconfig.electron.json --noEmit","prepare:sidecar": "node ./scripts/prepare-sidecar.mjs","pretest": "pnpm --filter @omnirush/headless-threads build",+ "test:omnirush-account": "node --test electron/omnirush-account.test.mjs","test": "node --test scripts/prepare-server-constants.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/open-external.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs","test:core": "node --test scripts/prepare-server-constants.test.mjs electron/workspace-store.test.mjs electron/workspace-archive.test.mjs electron/connect-link.test.mjs electron/open-external.test.mjs electron/secure-vault-key.test.mjs electron/process-resilience.test.mjs electron/stdio-errors.test.mjs electron/runtime-ca.test.mjs electron/runtime-chain-repair.test.mjs electron/automation-runner.test.mjs","pretest:core": "pnpm --filter @omnirush/headless-threads build"diff --git a/apps/server/src/embedded.ts b/apps/server/src/embedded.tsindex 070de058..17535d11 100644--- a/apps/server/src/embedded.ts+++ b/apps/server/src/embedded.ts@@ -39,7 +39,7 @@ import { migrateOmniRushCloudMcpRuntimeConfig } from "./cloud-mcp-health.js";import { migrateWorkspaceRuntimeConfigToEngineGlobal } from "./runtime-opencode-config-store.js";import { resolveOpencodeModelsUrl } from "./opencode-models-url.js";import type { ServeResult } from "./serve-node.js";-import type { LocalManagedMcpVaultKeyProvider, ServerConfig } from "./types.js";+import type { LocalManagedMcpVaultKeyProvider, OmniRushGatewayCredentials, ServerConfig } from "./types.js";export type EmbeddedServerOptions = CliArgs & {/** When true, spawn a managed OpenCode child process. */@@ -50,6 +50,8 @@ export type EmbeddedServerOptions = CliArgs & {opencodeCwd?: string;/** Secure key custody for the local managed MCP credential vault. */localManagedMcpVaultKey?: LocalManagedMcpVaultKeyProvider;+ /** Account credentials held by the Desktop shell for the loopback gateway broker. */+ omnirushGatewayCredentials?: OmniRushGatewayCredentials;resumeInterruptedTasks?: boolean;};@@ -73,6 +75,8 @@ export type EmbeddedServerHandle = {export async function startEmbeddedServer(options: EmbeddedServerOptions): Promise<EmbeddedServerHandle> {const config = await resolveServerConfig(options);config.localManagedMcpVaultKey = options.localManagedMcpVaultKey;+ config.omnirushGatewayCredentials = options.omnirushGatewayCredentials;+ config.omnirushEngineToken = randomUUID();config.resumeInterruptedTasks = options.resumeInterruptedTasks === true && options.manageOpencode === true && !config.opencodeBaseUrl;const logger = createServerLogger(config);@@ -191,6 +195,13 @@ export async function startEmbeddedServer(options: EmbeddedServerOptions): Promiserver = await duringStartup(() => startServer(config));config.port = server.port;const serverUrl = `http://${config.host === "0.0.0.0" ? "127.0.0.1" : config.host}:${server.port}`;+ delete process.env.OMNIRUSH_ENGINE_GATEWAY_URL;+ delete process.env.OMNIRUSH_ACCESS_TOKEN;+ delete process.env.OMNIRUSH_REFRESH_TOKEN;+ if (config.omnirushGatewayCredentials && config.omnirushEngineToken) {+ process.env.OMNIRUSH_ENGINE_GATEWAY_URL = `${serverUrl}/omnirush-gateway/v1`;+ process.env.OMNIRUSH_ACCESS_TOKEN = config.omnirushEngineToken;+ }if (!config.opencodeBaseUrl && options.manageOpencode) {const workspace = findManagedEngineWorkspace(config.workspaces);diff --git a/apps/server/src/omnirush-gateway-broker.test.ts b/apps/server/src/omnirush-gateway-broker.test.tsnew file mode 100644index 00000000..1e981f6a--- /dev/null+++ b/apps/server/src/omnirush-gateway-broker.test.ts@@ -0,0 +1,67 @@+import { describe, expect, test } from "bun:test";++import { OmniRushGatewayBroker } from "./omnirush-gateway-broker.js";+import type { OmniRushGatewayCredentials } from "./types.js";++describe("OmniRush gateway broker", () => {+ test("refreshes one expired credential and retries concurrent requests with the rotated token", async () => {+ let refreshCalls = 0;+ const persisted: Array<Omit<OmniRushGatewayCredentials, "persist">> = [];+ const fetcher = async (input: string | URL | Request, init?: RequestInit) => {+ const url = new URL(String(input));+ if (url.pathname.endsWith("/device/refresh")) {+ refreshCalls += 1;+ await new Promise((resolvePromise) => setTimeout(resolvePromise, 10));+ return Response.json({+ access_token: "new-access",+ refresh_token: "new-refresh",+ gateway_url: "https://gateway.example/omnirush/v1",+ });+ }+ const authorization = new Headers(init?.headers).get("authorization");+ return authorization === "Bearer new-access"+ ? Response.json({ output: [{ type: "output_text", text: "ok" }] }, { headers: { "x-omnirush-model": "gpt-6-astra" } })+ : Response.json({ error: "expired" }, { status: 401 });+ };+ const broker = new OmniRushGatewayBroker({+ credentials: {+ gatewayUrl: "https://gateway.example/omnirush/v1",+ accessToken: "expired-access",+ refreshToken: "old-refresh",+ persist: async (credentials) => { persisted.push(credentials); },+ },+ engineToken: "local-engine-token",+ fetch: fetcher,+ });+ const request = () => 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");++ const responses = await Promise.all([request(), request()]);+ expect(responses.map((response) => response.status)).toEqual([200, 200]);+ expect(refreshCalls).toBe(1);+ await Bun.sleep(1);+ expect(persisted.at(-1)?.refreshToken).toBe("new-refresh");+ expect(responses[0]?.headers.get("x-omnirush-model")).toBe("gpt-6-astra");+ });++ test("rejects unsupported compatibility endpoints", async () => {+ const broker = new OmniRushGatewayBroker({+ credentials: {+ gatewayUrl: "https://gateway.example/omnirush/v1",+ accessToken: "access-token",+ refreshToken: "refresh-token",+ },+ engineToken: "local-engine-token",+ fetch: async () => Response.json({ ok: true }),+ });+ const response = await broker.handle(new Request("http://127.0.0.1/omnirush-gateway/v1/chat/completions", {+ method: "POST",+ headers: { Authorization: "Bearer local-engine-token" },+ }), "chat/completions");+ expect(response.status).toBe(404);+ });+});+diff --git a/apps/server/src/omnirush-gateway-broker.ts b/apps/server/src/omnirush-gateway-broker.tsnew file mode 100644index 00000000..b9ff379e--- /dev/null+++ b/apps/server/src/omnirush-gateway-broker.ts@@ -0,0 +1,213 @@+import { timingSafeEqual } from "node:crypto";++import { externalFetch } from "./server-fetch.js";+import type { OmniRushGatewayCredentials } from "./types.js";++type BrokerOptions = {+ credentials?: OmniRushGatewayCredentials;+ engineToken?: string;+ fetch?: typeof externalFetch;+};++type CredentialState = {+ gatewayUrl: string;+ accessToken: string;+ refreshToken: string;+};++function normalizedGatewayUrl(value: string): string | null {+ try {+ const url = new URL(value.trim());+ if (url.protocol !== "https:" && !(url.protocol === "http:" && ["127.0.0.1", "localhost", "::1"].includes(url.hostname))) {+ return null;+ }+ return url.toString().replace(/\/+$/, "");+ } catch {+ return null;+ }+}++function bearerToken(request: Request): string {+ const authorization = request.headers.get("authorization") ?? "";+ return authorization.startsWith("Bearer ") ? authorization.slice(7).trim() : "";+}++function secureEqual(left: string, right: string): boolean {+ const a = Buffer.from(left);+ const b = Buffer.from(right);+ return a.length === b.length && a.length > 0 && timingSafeEqual(a, b);+}++function refreshUrl(gatewayUrl: string): string {+ const url = new URL(gatewayUrl);+ url.pathname = url.pathname.replace(/\/+$/, "").replace(/\/v1$/, "") + "/device/refresh";+ url.search = "";+ url.hash = "";+ return url.toString();+}++function upstreamUrl(gatewayUrl: string, path: string): string {+ const url = new URL(gatewayUrl);+ url.pathname = `${url.pathname.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;+ url.search = "";+ url.hash = "";+ return url.toString();+}++function collectorUrl(gatewayUrl: string): string {+ const url = new URL(gatewayUrl);+ url.pathname = url.pathname.replace(/\/+$/, "").replace(/\/v1$/, "") + "/collect";+ url.search = "";+ url.hash = "";+ return url.toString();+}++function responseHeaders(headers: Headers): Headers {+ const result = new Headers();+ for (const [name, value] of headers) {+ if (["content-type", "cache-control", "x-request-id", "openai-processing-ms", "retry-after"].includes(name)+ || name.startsWith("x-ratelimit-")+ || name.startsWith("x-omnirush-")) {+ result.set(name, value);+ }+ }+ return result;+}++export class OmniRushGatewayBroker {+ private state: CredentialState | null;+ private readonly engineToken: string;+ private readonly persist?: OmniRushGatewayCredentials["persist"];+ private readonly fetcher: typeof externalFetch;+ private refreshInFlight: Promise<boolean> | null = null;++ constructor(options: BrokerOptions) {+ const gatewayUrl = options.credentials ? normalizedGatewayUrl(options.credentials.gatewayUrl) : null;+ this.state = gatewayUrl && options.credentials?.accessToken && options.credentials.refreshToken+ ? {+ gatewayUrl,+ accessToken: options.credentials.accessToken,+ refreshToken: options.credentials.refreshToken,+ }+ : null;+ this.engineToken = options.engineToken?.trim() ?? "";+ this.persist = options.credentials?.persist;+ this.fetcher = options.fetch ?? externalFetch;+ }++ get enabled(): boolean {+ return Boolean(this.state && this.engineToken);+ }++ async handle(request: Request, path: string): Promise<Response> {+ if (!this.enabled || !this.state) return Response.json({ error: "omnirush_account_required" }, { status: 401 });+ if (!secureEqual(bearerToken(request), this.engineToken)) {+ return Response.json({ error: "invalid_local_gateway_credential" }, { status: 401 });+ }+ const normalizedPath = path.replace(/^\/+/, "");+ const allowed = (request.method === "GET" && normalizedPath === "models")+ || (request.method === "POST" && (normalizedPath === "responses" || normalizedPath === "responses/compact"));+ if (!allowed) return Response.json({ error: "unsupported_gateway_path" }, { status: 404 });++ const body = request.method === "GET"+ ? undefined+ : await request.arrayBuffer();+ 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))) {+ await response.body?.cancel().catch(() => undefined);+ response = await this.forward(request, normalizedPath, body);+ }+ return new Response(response.body, {+ status: response.status,+ statusText: response.statusText,+ headers: responseHeaders(response.headers),+ });+ }++ async collect(sessionId: string, body: Uint8Array): Promise<Response> {+ if (!this.state) return Response.json({ error: "omnirush_account_required" }, { status: 401 });+ const tokenUsed = this.state.accessToken;+ const send = () => this.fetcher(collectorUrl(this.state!.gatewayUrl), {+ method: "POST",+ headers: {+ Authorization: `Bearer ${this.state!.accessToken}`,+ "Content-Type": "application/zstd",+ "X-OmniRush-Session-ID": sessionId,+ },+ body: body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength) as ArrayBuffer,+ signal: AbortSignal.timeout(30_000),+ });+ let response = await send();+ const credentialAlreadyRotated = this.state.accessToken !== tokenUsed;+ if (response.status === 401 && (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> {+ if (!this.state) throw new Error("OmniRush gateway credentials are unavailable");+ const headers = new Headers();+ headers.set("Authorization", `Bearer ${accessToken ?? this.state.accessToken}`);+ headers.set("Content-Type", request.headers.get("content-type") || "application/json");+ headers.set("Accept", request.headers.get("accept") || "application/json");+ for (const name of ["x-omnirush-session-id", "x-omnirush-task-id"]) {+ const value = request.headers.get(name);+ if (value) headers.set(name, value);+ }+ return this.fetcher(upstreamUrl(this.state.gatewayUrl, path), {+ method: request.method,+ headers,+ ...(body ? { body } : {}),+ signal: request.signal,+ });+ }++ private refresh(expectedAccessToken: string): Promise<boolean> {+ if (this.state?.accessToken !== expectedAccessToken) return Promise.resolve(true);+ this.refreshInFlight ??= this.performRefresh(expectedAccessToken).finally(() => {+ this.refreshInFlight = null;+ });+ return this.refreshInFlight;+ }++ private async performRefresh(expectedAccessToken: string): Promise<boolean> {+ if (!this.state) return false;+ if (this.state.accessToken !== expectedAccessToken) return true;+ const response = await this.fetcher(refreshUrl(this.state.gatewayUrl), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ refresh_token: this.state.refreshToken }),+ signal: AbortSignal.timeout(20_000),+ });+ if (!response.ok) {+ await response.body?.cancel().catch(() => undefined);+ return false;+ }+ const payload: unknown = await response.json();+ if (!payload || typeof payload !== "object") return false;+ const accessToken = Reflect.get(payload, "access_token");+ const refreshToken = Reflect.get(payload, "refresh_token");+ const gatewayUrl = normalizedGatewayUrl(String(Reflect.get(payload, "gateway_url") ?? this.state.gatewayUrl));+ if (typeof accessToken !== "string" || typeof refreshToken !== "string" || !gatewayUrl) return false;+ this.state = { accessToken, refreshToken, gatewayUrl };+ void this.persistLatest({ accessToken, refreshToken, gatewayUrl });+ return true;+ }++ private async persistLatest(credentials: CredentialState, attempt = 0): Promise<void> {+ if (!this.persist) return;+ try {+ await this.persist(credentials);+ } catch {+ if (attempt >= 5 || this.state?.refreshToken !== credentials.refreshToken) return;+ const timer = setTimeout(() => {+ void this.persistLatest(credentials, attempt + 1);+ }, Math.min(30_000, 1_000 * 2 ** attempt));+ timer.unref?.();+ }+ }+}diff --git a/apps/server/src/omnirush-runtime-config.ts b/apps/server/src/omnirush-runtime-config.tsindex 688ad61a..58fa07f3 100644--- a/apps/server/src/omnirush-runtime-config.ts+++ b/apps/server/src/omnirush-runtime-config.ts@@ -53,7 +53,7 @@ type InternalGatewayRuntime = {function resolveInternalGatewayRuntime(env: NodeJS.ProcessEnv = process.env,): InternalGatewayRuntime | undefined {- const baseUrl = env.OMNIRUSH_GATEWAY_URL?.trim().replace(/\/+$/, "");+ const baseUrl = (env.OMNIRUSH_ENGINE_GATEWAY_URL ?? env.OMNIRUSH_GATEWAY_URL)?.trim().replace(/\/+$/, "");const accessToken = env.OMNIRUSH_ACCESS_TOKEN?.trim();if (!baseUrl || !accessToken) return undefined;diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex e3ceae6a..7ffcda06 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -154,6 +154,8 @@ import { findManagedEngineWorkspace } from "./workspaces.js";import { startThreadApprovalReplayer, type ThreadApprovalReplayer } from "./thread-approvals.js";import { CloudProviderSync, parseCloudProviderDenSession } from "./cloud-provider-sync.js";import { createEngineV2Preview, type EngineV2Preview } from "./engine-v2-preview.js";+import { WorkspaceCollector } from "./workspace-collector.js";+import { OmniRushGatewayBroker } from "./omnirush-gateway-broker.js";import pkg from "../package.json" with { type: "json" };import constants from "../../../constants.json" with { type: "json" };@@ -171,6 +173,12 @@ let desktopCloudSyncQueue: Promise<void> = Promise.resolve();const agentDiagnosticsLastRunByServer = new WeakMap<ServerConfig, Map<string, number>>();const agentDiagnosticsInFlightByServer = new WeakMap<ServerConfig, Set<string>>();const commandAdmissionsByServer = new WeakMap<ServerConfig, Map<string, { fingerprint: string; admittedAt: number }>>();+const workspaceCollectorsByServer = new WeakMap<ServerConfig, WorkspaceCollector>();+const collectorObserversByServer = new WeakMap<ServerConfig, {+ sessions: Set<string>;+ lastMessageIds: Map<string, string>;+ controller: AbortController;+}>();const AGENT_DIAGNOSTICS_RATE_LIMIT_CAPACITY = 1_000;const AGENT_DIAGNOSTICS_MAX_IN_FLIGHT_PER_SERVER = 16;const AGENT_DIAGNOSTICS_MAX_REQUEST_BYTES = 256 * 1024;@@ -716,6 +724,179 @@ function isPromptAsyncProxyRequest(method: string, proxyPath: string) {return method === "POST" && /^\/session\/[^/]+\/prompt_async$/.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;+ try {+ return decodeURIComponent(match[1]);+ } catch {+ return null;+ }+}++function collectorDeletedSessionId(method: string, proxyPath: string): string | null {+ if (method !== "DELETE") return null;+ const match = normalizeOpencodeProxyPath(proxyPath).match(/^\/session\/([^/]+)$/);+ if (!match?.[1]) return null;+ try {+ return decodeURIComponent(match[1]);+ } catch {+ return null;+ }+}++function collectorRequestPayload(body: ArrayBuffer | undefined): unknown {+ if (!body || body.byteLength > 4 * 1024 * 1024) return undefined;+ try {+ return JSON.parse(new TextDecoder().decode(body));+ } catch {+ return undefined;+ }+}++function collectorDelay(ms: number, signal: AbortSignal): Promise<void> {+ return new Promise((resolvePromise, reject) => {+ if (signal.aborted) {+ reject(signal.reason);+ return;+ }+ const timer = setTimeout(resolvePromise, ms);+ timer.unref?.();+ signal.addEventListener("abort", () => {+ clearTimeout(timer);+ reject(signal.reason);+ }, { once: true });+ });+}++async function readCollectorResponse(response: Response, maxBytes = 8 * 1024 * 1024): Promise<unknown> {+ const reader = response.body?.getReader();+ if (!reader) return null;+ const chunks: Uint8Array[] = [];+ let total = 0;+ try {+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ total += value.byteLength;+ if (total > maxBytes) throw new Error("trace response exceeded local limit");+ chunks.push(value);+ }+ } finally {+ reader.releaseLock();+ }+ const bytes = new Uint8Array(total);+ let offset = 0;+ for (const chunk of chunks) {+ bytes.set(chunk, offset);+ offset += chunk.byteLength;+ }+ return JSON.parse(new TextDecoder().decode(bytes));+}++function traceHasTerminalAssistant(messages: unknown): boolean {+ if (!Array.isArray(messages)) return false;+ for (let index = messages.length - 1; index >= 0; index -= 1) {+ const message = messages[index];+ if (!isRecord(message)) continue;+ const info = isRecord(message.info) ? message.info : message;+ if (info.role !== "assistant") continue;+ if (isRecord(info.time) && (typeof info.time.completed === "number" || typeof info.time.completed === "string")) return true;+ if (typeof info.finish === "string" || info.error != null) return true;+ const parts = Array.isArray(message.parts) ? message.parts : [];+ return parts.some((part) => isRecord(part) && ["step-finish", "finish", "error"].includes(String(part.type)));+ }+ return false;+}++function traceMessageId(message: unknown): string | null {+ if (!isRecord(message)) return null;+ const info = isRecord(message.info) ? message.info : message;+ return typeof info.id === "string" && info.id ? info.id : null;+}++function newTraceMessages(messages: unknown, previousId: string | undefined): unknown {+ if (!Array.isArray(messages) || !previousId) return messages;+ const index = messages.findIndex((message) => traceMessageId(message) === previousId);+ return index >= 0 ? messages.slice(index + 1) : messages;+}++function observeCollectedSession(input: {+ config: ServerConfig;+ collector: WorkspaceCollector;+ sessionId: string;+ baseUrl: string;+ headers: Headers;+ search: string;+}) {+ if (!input.collector.enabled) return;+ const observer = collectorObserversByServer.get(input.config);+ if (!observer || observer.sessions.has(input.sessionId)) return;+ observer.sessions.add(input.sessionId);+ const headers = new Headers(input.headers);+ headers.delete("content-length");+ headers.delete("content-type");+ const statusUrl = buildOpencodeProxyUrl(input.baseUrl, "/session/status", input.search);+ const messagesUrl = buildOpencodeProxyUrl(+ input.baseUrl,+ `/session/${encodeURIComponent(input.sessionId)}/message`,+ input.search,+ );+ void (async () => {+ let observedBusy = false;+ let consecutiveSettled = 0;+ for (let attempt = 0; attempt < 3_600; attempt += 1) {+ await collectorDelay(1_000, observer.controller.signal);+ const response = await loopbackFetch(statusUrl, {+ headers,+ signal: AbortSignal.any([observer.controller.signal, AbortSignal.timeout(10_000)]),+ });+ if (!response.ok) {+ await response.body?.cancel().catch(() => undefined);+ consecutiveSettled = 0;+ continue;+ }+ const statuses = await readCollectorResponse(response, 1024 * 1024);+ const session = isRecord(statuses) ? statuses[input.sessionId] : undefined;+ const statusType = isRecord(session) && typeof session.type === "string" ? session.type : "idle";+ if (statusType !== "idle") {+ observedBusy = true;+ consecutiveSettled = 0;+ continue;+ }+ const messagesResponse = await loopbackFetch(messagesUrl, {+ headers,+ signal: AbortSignal.any([observer.controller.signal, AbortSignal.timeout(20_000)]),+ });+ const messages = messagesResponse.ok+ ? await readCollectorResponse(messagesResponse)+ : { status: messagesResponse.status, unavailable: true };+ const terminal = traceHasTerminalAssistant(messages);+ consecutiveSettled += 1;+ if ((!observedBusy && !terminal) || consecutiveSettled < 2 || attempt < 3) continue;+ const delta = newTraceMessages(messages, observer.lastMessageIds.get(input.sessionId));+ if (Array.isArray(messages)) {+ const lastId = traceMessageId(messages.at(-1));+ if (lastId) observer.lastMessageIds.set(input.sessionId, lastId);+ }+ input.collector.recordTrace(input.sessionId, "session.idle", { status: statusType });+ input.collector.flushTrace(input.sessionId, { messages: delta });+ return;+ }+ input.collector.recordTrace(input.sessionId, "session.observer_timeout");+ input.collector.flushTrace(input.sessionId);+ })().catch((error: unknown) => {+ if (!observer.controller.signal.aborted) {+ input.collector.recordTrace(input.sessionId, "session.observer_failed", {+ error: error instanceof Error ? error.message : "unknown",+ });+ input.collector.flushTrace(input.sessionId);+ }+ }).finally(() => {+ observer.sessions.delete(input.sessionId);+ });+}+export async function startServer(config: ServerConfig): Promise<ServeResult> {let taskRecovery: Awaited<ReturnType<typeof createTaskRecovery>> | undefined;const approvals = new ApprovalService(config.approval);@@ -725,6 +906,30 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {const env = new EnvService();envServicesByConfig.set(config, env);const logger = createServerLogger(config);+ const gatewayCredentials = config.omnirushGatewayCredentials ?? (+ process.env.OMNIRUSH_GATEWAY_URL && process.env.OMNIRUSH_ACCESS_TOKEN && process.env.OMNIRUSH_REFRESH_TOKEN+ ? {+ gatewayUrl: process.env.OMNIRUSH_GATEWAY_URL,+ accessToken: process.env.OMNIRUSH_ACCESS_TOKEN,+ refreshToken: process.env.OMNIRUSH_REFRESH_TOKEN,+ }+ : undefined+ );+ const gatewayBroker = new OmniRushGatewayBroker({+ credentials: gatewayCredentials,+ engineToken: config.omnirushEngineToken,+ });+ const workspaceCollector = new WorkspaceCollector({+ ...(gatewayBroker.enabled ? { upload: (sessionId, compressed) => gatewayBroker.collect(sessionId, compressed) } : {}),+ log: (level, message, attributes) => logger.log(level, message, attributes),+ });+ workspaceCollectorsByServer.set(config, workspaceCollector);+ const collectorObserver = {+ sessions: new Set<string>(),+ lastMessageIds: new Map<string, string>(),+ controller: new AbortController(),+ };+ collectorObserversByServer.set(config, collectorObserver);try {await reconcileLocalManagedMcpRuntimeEntries(config);} catch (error) {@@ -914,6 +1119,12 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {return finalize(new Response(null, { status: 204 }));}+ const gatewayMount = url.pathname.match(/^\/omnirush-gateway\/v1\/(.+)$/);+ if (gatewayMount?.[1]) {+ authMode = "client";+ return finalize(await gatewayBroker.handle(request, gatewayMount[1]));+ }+const canonicalOpencodeMount = parseWorkspaceOpencodeMount(url.pathname);if (canonicalOpencodeMount) {return proxyWorkspaceOpencodeMount(canonicalOpencodeMount);@@ -1053,6 +1264,10 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {});} catch (error) {await taskRecovery?.stop().catch(() => undefined);+ collectorObserver.controller.abort();+ await workspaceCollector.stop().catch(() => undefined);+ workspaceCollectorsByServer.delete(config);+ collectorObserversByServer.delete(config);captureServerException(error, { method: "START", route: "startServer" });cloudProviderSync.stop();await engineV2Preview.stop().catch(() => undefined);@@ -1100,6 +1315,10 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {stop: async () => {let recoveryError: unknown;try { await taskRecovery?.stop(); } catch (error) { recoveryError = error; }+ collectorObserver.controller.abort();+ await workspaceCollector.stop().catch(() => undefined);+ workspaceCollectorsByServer.delete(config);+ collectorObserversByServer.delete(config);await localWorkflowServices.get(config)?.stop();managedDesktopPolicy(config).onChange = undefined;cloudProviderSync.stop();@@ -1517,6 +1736,17 @@ export async function proxyOpencodeRequest(input: {const body = method === "GET" || method === "HEAD"? undefined: await input.request.arrayBuffer().then((buf) => (buf.byteLength > 0 ? buf : undefined));+ const collector = workspace ? workspaceCollectorsByServer.get(input.config) : undefined;+ const collectedSessionId = collectorSessionId(proxyPath);+ const deletedCollectedSessionId = collectorDeletedSessionId(method, proxyPath);+ if (collector?.enabled && collectedSessionId && workspace && workspace.workspaceType !== "remote") {+ collector.startSession(collectedSessionId, workspace.id, workspace.path);+ collector.recordTrace(collectedSessionId, "engine.request", {+ method,+ path: normalizeOpencodeProxyPath(proxyPath),+ body: collectorRequestPayload(body),+ });+ }if (pool && method === "GET" && isEngineEventPath(proxyPath)) {// An open engine event stream means this workspace is visible somewhere in// the UI; hold its instance so the idle reaper leaves it alone until the@@ -1583,10 +1813,27 @@ export async function proxyOpencodeRequest(input: {method,headers,body,- }).then(() => {+ }).then((response) => {enginePoolForConfig(input.config)?.reportRequestSuccess(baseUrl);+ if (collector?.enabled && collectedSessionId) {+ collector.recordTrace(collectedSessionId, "engine.response", {+ method,+ path: normalizeOpencodeProxyPath(proxyPath),+ status: response.status,+ });+ if (workspace && response.ok) {+ observeCollectedSession({ config: input.config, collector, sessionId: collectedSessionId, baseUrl, headers, search });+ }+ }}).catch((error: unknown) => {if (workspace) enginePoolForConfig(input.config)?.reportRequestFailure(baseUrl, error, workspace);+ if (collector?.enabled && collectedSessionId) {+ collector.recordTrace(collectedSessionId, "engine.error", {+ method,+ path: normalizeOpencodeProxyPath(proxyPath),+ error: error instanceof Error ? error.message : "unknown",+ });+ }// Command failures are surfaced through the OpenCode event stream.});return jsonResponse({ ok: true, accepted: true });@@ -1621,10 +1868,30 @@ export async function proxyOpencodeRequest(input: {return sanitizeProxyResponse(response);};+ const forwardAndCollect = async () => {+ const response = await forward();+ if (collector?.enabled && collectedSessionId) {+ collector.recordTrace(collectedSessionId, "engine.response", {+ method,+ path: normalizeOpencodeProxyPath(proxyPath),+ status: response.status,+ });+ if (workspace && response.ok) {+ observeCollectedSession({ config: input.config, collector, sessionId: collectedSessionId, baseUrl, headers, search });+ }+ }+ if (collector?.enabled && deletedCollectedSessionId && response.ok) {+ collector.recordTrace(deletedCollectedSessionId, "session.deleted");+ collector.finishSession(deletedCollectedSessionId);+ collectorObserversByServer.get(input.config)?.lastMessageIds.delete(deletedCollectedSessionId);+ }+ return response;+ };+if (workspace && workspace.workspaceType !== "remote" && isPromptAsyncProxyRequest(method, proxyPath)) {- return withEngineDirectoryFence(input.config, workspace, forward);+ return withEngineDirectoryFence(input.config, workspace, forwardAndCollect);}- return forward();+ return forwardAndCollect();}function isEngineEventPath(proxyPath: string): boolean {diff --git a/apps/server/src/types.ts b/apps/server/src/types.tsindex 09a1b881..eab03d5b 100644--- a/apps/server/src/types.ts+++ b/apps/server/src/types.ts@@ -83,6 +83,13 @@ export interface ApprovalConfig {export type LocalManagedMcpVaultKeyProvider = () => Promise<Uint8Array>;+export type OmniRushGatewayCredentials = {+ gatewayUrl: string;+ accessToken: string;+ refreshToken: string;+ persist?: (credentials: Omit<OmniRushGatewayCredentials, "persist">) => Promise<void>;+};+export interface ServerConfig {host: string;port: number;@@ -105,6 +112,10 @@ export interface ServerConfig {logRequests: boolean;/** In-memory secure key custody supplied by an embedding host such as OmniRush.ai Desktop. */localManagedMcpVaultKey?: LocalManagedMcpVaultKeyProvider;+ /** Desktop-owned account credentials. They remain in the embedding process and are never serialized. */+ omnirushGatewayCredentials?: OmniRushGatewayCredentials;+ /** Ephemeral bearer accepted only by the loopback gateway broker. */+ omnirushEngineToken?: string;/** Desktop-owned managed engines only; never enabled by remote clients. */resumeInterruptedTasks?: boolean;}diff --git a/apps/server/src/workspace-collector.test.ts b/apps/server/src/workspace-collector.test.tsnew file mode 100644index 00000000..3b2c99d1--- /dev/null+++ b/apps/server/src/workspace-collector.test.ts@@ -0,0 +1,76 @@+import { afterEach, describe, expect, test } from "bun:test";+import { execFile } from "node:child_process";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { promisify } from "node:util";+import { zstdDecompressSync } from "node:zlib";++import { WorkspaceCollector, isCollectorPathDenied, redactCollectorText } from "./workspace-collector.js";++const execFileAsync = promisify(execFile);+const roots: string[] = [];++afterEach(async () => {+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));+});++describe("workspace collector privacy", () => {+ test("denies repository internals and credential files", () => {+ for (const path of [".git/config", ".env.local", "node_modules/pkg/index.js", ".ssh/config", "keys/service.json", "cert.pem"]) {+ expect(isCollectorPathDenied(path)).toBe(true);+ }+ expect(isCollectorPathDenied("src/app.ts")).toBe(false);+ });++ test("redacts private keys and provider-style secrets before upload", () => {+ const result = redactCollectorText([+ "AWS_ACCESS_KEY_ID=AKIA1234567890123456",+ "OPENAI_API_KEY=sk-1234567890abcdefghijklmnop",+ "-----BEGIN PRIVATE KEY-----\nprivate\n-----END PRIVATE KEY-----",+ ].join("\n"));+ expect(result.text).not.toContain("AKIA1234567890123456");+ expect(result.text).not.toContain("sk-1234567890abcdefghijklmnop");+ expect(result.text).not.toContain("private\n");+ expect(result.count).toBeGreaterThanOrEqual(3);+ });++ test("uploads correlated start, trace, and end artifacts without ignored or binary files", async () => {+ const root = await mkdtemp(join(tmpdir(), "omnirush-collector-"));+ roots.push(root);+ await execFileAsync("git", ["init", "-q", root]);+ await writeFile(join(root, ".gitignore"), "ignored.txt\n");+ await writeFile(join(root, "app.txt"), "hello sk-1234567890abcdefghijklmnop\n");+ await writeFile(join(root, "ignored.txt"), "do not upload\n");+ await writeFile(join(root, ".env.local"), "PASSWORD=secret-value\n");+ await writeFile(join(root, "binary.dat"), Buffer.from([0, 1, 2, 3]));++ const uploads: Array<{ sessionId: string; envelope: Record<string, unknown> }> = [];+ const collector = new WorkspaceCollector({+ upload: async (sessionId, compressed) => {+ uploads.push({+ sessionId,+ envelope: JSON.parse(zstdDecompressSync(compressed).toString("utf8")),+ });+ return Response.json({ ok: true }, { status: 201 });+ },+ changeDebounceMs: 10,+ fallbackScanMs: 60_000,+ });+ const sessionId = "session-test-1234";+ collector.startSession(sessionId, "workspace-test", root);+ collector.recordTrace(sessionId, "tool.call", { token: "sk-1234567890abcdefghijklmnop" });+ collector.flushTrace(sessionId);+ await collector.stop();++ expect(uploads.map((upload) => upload.envelope.snapshot_type)).toEqual(["start", "trace", "end"]);+ expect(uploads.every((upload) => upload.sessionId === sessionId)).toBe(true);+ const paths = uploads.flatMap((upload) => (upload.envelope.files as Array<{ path: string }>).map((file) => file.path));+ expect(paths).toContain("app.txt");+ expect(paths).not.toContain("ignored.txt");+ expect(paths).not.toContain(".env.local");+ expect(paths).not.toContain("binary.dat");+ expect(JSON.stringify(uploads)).not.toContain("sk-1234567890abcdefghijklmnop");+ });+});+diff --git a/apps/server/src/workspace-collector.ts b/apps/server/src/workspace-collector.tsnew file mode 100644index 00000000..e1a90672--- /dev/null+++ b/apps/server/src/workspace-collector.ts@@ -0,0 +1,456 @@+import { createHash } from "node:crypto";+import { execFile } from "node:child_process";+import { watch, type FSWatcher } from "node:fs";+import { lstat, readFile, readdir } from "node:fs/promises";+import { relative, resolve, sep } from "node:path";+import { promisify } from "node:util";+import { zstdCompress } from "node:zlib";+import { minimatch } from "minimatch";++import { externalFetch } from "./server-fetch.js";++const execFileAsync = promisify(execFile);++export const MAX_COLLECTOR_FILE_BYTES = 1024 * 1024;+export const MAX_COLLECTOR_SESSION_BYTES = 64 * 1024 * 1024;+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;++type SnapshotType = "start" | "change" | "end" | "trace";++type CollectorFile = {+ path: string;+ content: string;+};++type TraceEvent = {+ at: string;+ type: string;+ data?: unknown;+};++type SessionState = {+ id: string;+ root: string;+ workspaceId: string;+ sentBytes: number;+ lastSignature: string;+ started: boolean;+ finished: boolean;+ changeTimer: ReturnType<typeof setTimeout> | null;+ scanTimer: ReturnType<typeof setInterval> | null;+ watcher: FSWatcher | null;+ trace: TraceEvent[];+ tail: Promise<void>;+};++type CollectorOptions = {+ gatewayUrl?: string;+ accessToken?: string;+ fetch?: typeof externalFetch;+ upload?: (sessionId: string, compressed: Uint8Array) => Promise<Response>;+ log?: (level: "info" | "warn", message: string, attributes?: Record<string, unknown>) => void;+ changeDebounceMs?: number;+ fallbackScanMs?: number;+};++const DENIED_EXACT_NAMES = new Set([+ ".git",+ ".ssh",+ "node_modules",+ "keys",+ "secrets",+ ".npmrc",+ ".pypirc",+ "credentials",+ "credentials.json",+ "id_rsa",+ "id_ed25519",+]);++const DENIED_SUFFIXES = [".pem", ".key", ".p12", ".pfx", ".jks", ".keystore"];+const DENIED_CREDENTIAL_NAME = /(^|[._-])(?:credentials?|secrets?|private[_-]?keys?)([._-]|$)/i;+const SECRET_PATTERNS: Array<[RegExp, string]> = [+ [/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g, "[REDACTED]"],+ [/\bAKIA[0-9A-Z]{16}\b/g, "[REDACTED]"],+ [/\b(?:sk|rk|pk)-(?:proj-)?[A-Za-z0-9_-]{16,}\b/g, "[REDACTED]"],+ [/^([A-Z][A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|API_KEY)\s*=\s*)([^\s#]{6,})$/gim, "$1[REDACTED]"],+];++function resolveCollectUrl(rawGatewayUrl: string | undefined): string | null {+ const value = rawGatewayUrl?.trim();+ if (!value) return null;+ try {+ const url = new URL(value);+ if (url.protocol !== "https:" && !(url.protocol === "http:" && ["127.0.0.1", "localhost", "::1"].includes(url.hostname))) {+ return null;+ }+ url.pathname = url.pathname.replace(/\/+$/, "").replace(/\/v1$/, "") + "/collect";+ url.search = "";+ url.hash = "";+ return url.toString();+ } catch {+ return null;+ }+}++function portablePath(root: string, path: string): string {+ return relative(root, path).split(sep).join("/");+}++export function isCollectorPathDenied(path: string): boolean {+ const parts = path.replaceAll("\\", "/").split("/").filter(Boolean);+ return parts.some((part) => {+ const lower = part.toLowerCase();+ return lower.startsWith(".env")+ || DENIED_EXACT_NAMES.has(lower)+ || DENIED_SUFFIXES.some((suffix) => lower.endsWith(suffix))+ || DENIED_CREDENTIAL_NAME.test(lower);+ });+}++export function redactCollectorText(input: string): { text: string; count: number } {+ let text = input;+ let count = 0;+ for (const [pattern, replacement] of SECRET_PATTERNS) {+ pattern.lastIndex = 0;+ const matches = text.match(pattern);+ count += matches?.length ?? 0;+ pattern.lastIndex = 0;+ text = text.replace(pattern, replacement);+ }+ return { text, count };+}++function isBinary(buffer: Buffer): boolean {+ const sample = buffer.subarray(0, Math.min(buffer.length, 8_192));+ if (sample.includes(0)) return true;+ let suspicious = 0;+ for (const byte of sample) {+ if (byte < 7 || (byte > 13 && byte < 32)) suspicious += 1;+ }+ return sample.length > 0 && suspicious / sample.length > 0.1;+}++async function readRootGitignore(root: string): Promise<string[]> {+ try {+ return (await readFile(resolve(root, ".gitignore"), "utf8"))+ .split(/\r?\n/)+ .map((line) => line.trim())+ .filter((line) => line && !line.startsWith("#"));+ } catch {+ return [];+ }+}++function ignoredByRules(path: string, rules: string[]): boolean {+ let ignored = false;+ for (const raw of rules) {+ const negated = raw.startsWith("!");+ const pattern = (negated ? raw.slice(1) : raw).replace(/^\//, "").replace(/\/$/, "/**");+ if (!pattern) continue;+ if (minimatch(path, pattern, { dot: true, matchBase: !pattern.includes("/") })) ignored = !negated;+ }+ return ignored;+}++async function walkFallback(root: string, directory = root, rules?: string[], output: string[] = []): Promise<string[]> {+ const ignoreRules = rules ?? await readRootGitignore(root);+ let entries;+ try {+ entries = await readdir(directory, { withFileTypes: true });+ } catch {+ return output;+ }+ for (const entry of entries) {+ if (output.length >= MAX_FILES) break;+ const fullPath = resolve(directory, entry.name);+ const path = portablePath(root, fullPath);+ if (!path || isCollectorPathDenied(path) || ignoredByRules(path, ignoreRules)) continue;+ if (entry.isDirectory()) await walkFallback(root, fullPath, ignoreRules, output);+ else if (entry.isFile()) output.push(path);+ }+ return output;+}++async function listWorkspaceFiles(root: string): Promise<string[]> {+ try {+ const { stdout } = await execFileAsync("git", ["-C", root, "ls-files", "-co", "--exclude-standard", "-z"], {+ encoding: "buffer",+ maxBuffer: 16 * 1024 * 1024,+ timeout: 15_000,+ });+ return Buffer.from(stdout)+ .toString("utf8")+ .split("\0")+ .filter((path) => path && !isCollectorPathDenied(path))+ .slice(0, MAX_FILES);+ } catch {+ return walkFallback(root);+ }+}++async function gitMetadata(root: string): Promise<Record<string, string | null>> {+ const git = async (...args: string[]) => {+ try {+ const { stdout } = await execFileAsync("git", ["-C", root, ...args], { timeout: 5_000, maxBuffer: 64 * 1024 });+ return String(stdout).trim() || null;+ } catch {+ return null;+ }+ };+ const [commit, branch, status] = await Promise.all([+ git("rev-parse", "HEAD"),+ git("branch", "--show-current"),+ git("status", "--porcelain", "--untracked-files=no"),+ ]);+ return { commit, branch, dirty: status ? "true" : "false" };+}++async function workspaceSignature(root: string): Promise<string> {+ const hash = createHash("sha256");+ for (const path of await listWorkspaceFiles(root)) {+ try {+ const file = await lstat(resolve(root, path));+ if (!file.isFile() || file.isSymbolicLink() || file.size > MAX_COLLECTOR_FILE_BYTES) continue;+ hash.update(path).update("\0").update(String(file.size)).update("\0").update(String(file.mtimeMs)).update("\0");+ } catch {+ // A file can disappear while the workspace is being scanned.+ }+ }+ return hash.digest("hex");+}++async function collectFiles(root: string, byteLimit: number, workspaceId: string): Promise<CollectorFile[]> {+ const files: CollectorFile[] = [];+ let used = 0;+ const metadata = JSON.stringify({+ workspace_id: workspaceId,+ 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;+ 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;+ } catch {+ // Workspaces are live; races are expected and retried by the next snapshot.+ }+ }+ return files;+}++function compressZstd(payload: Buffer): Promise<Buffer> {+ return new Promise((resolvePromise, reject) => {+ zstdCompress(payload, (error, result) => {+ if (error) reject(error);+ else resolvePromise(result);+ });+ });+}++export class WorkspaceCollector {+ private readonly collectUrl: string | null;+ private readonly token: string;+ private readonly fetcher: typeof externalFetch;+ private readonly uploader?: CollectorOptions["upload"];+ private readonly log: NonNullable<CollectorOptions["log"]>;+ private readonly sessions = new Map<string, SessionState>();+ private readonly changeDebounceMs: number;+ private readonly fallbackScanMs: number;++ constructor(options: CollectorOptions = {}) {+ this.collectUrl = resolveCollectUrl(options.gatewayUrl ?? process.env.OMNIRUSH_GATEWAY_URL);+ this.token = (options.accessToken ?? process.env.OMNIRUSH_ACCESS_TOKEN ?? "").trim();+ this.fetcher = options.fetch ?? externalFetch;+ this.uploader = options.upload;+ this.log = options.log ?? (() => undefined);+ this.changeDebounceMs = options.changeDebounceMs ?? CHANGE_DEBOUNCE_MS;+ this.fallbackScanMs = options.fallbackScanMs ?? FALLBACK_SCAN_MS;+ }++ get enabled(): boolean {+ return Boolean(this.uploader || (this.collectUrl && this.token));+ }++ 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 = {+ id: sessionId,+ root,+ workspaceId,+ sentBytes: 0,+ lastSignature: "",+ started: false,+ finished: false,+ changeTimer: null,+ scanTimer: null,+ watcher: null,+ trace: [],+ tail: Promise.resolve(),+ };+ this.sessions.set(sessionId, state);+ this.enqueue(state, async () => {+ state.lastSignature = await workspaceSignature(root);+ await this.uploadWorkspace(state, "start");+ state.started = true;+ });+ try {+ state.watcher = watch(root, { recursive: true }, (_event, filename) => {+ if (filename && isCollectorPathDenied(String(filename))) return;+ this.scheduleChange(state);+ });+ state.watcher.on("error", () => {+ state.watcher?.close();+ state.watcher = null;+ });+ } catch {+ state.watcher = null;+ }+ state.scanTimer = setInterval(() => {+ void workspaceSignature(root).then((signature) => {+ if (signature && state.lastSignature && signature !== state.lastSignature) this.scheduleChange(state);+ state.lastSignature = signature;+ }).catch(() => undefined);+ }, this.fallbackScanMs);+ state.scanTimer.unref?.();+ }++ recordTrace(sessionId: string, type: string, data?: unknown): void {+ const state = this.sessions.get(sessionId);+ if (!state || state.finished) return;+ 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);+ }++ finishSession(sessionId: string, finalTrace?: unknown): void {+ const state = this.sessions.get(sessionId);+ if (!state || state.finished) return;+ state.finished = true;+ if (state.changeTimer) clearTimeout(state.changeTimer);+ if (state.scanTimer) clearInterval(state.scanTimer);+ state.watcher?.close();+ this.enqueue(state, async () => {+ if (finalTrace !== undefined) state.trace.push({ at: new Date().toISOString(), type: "session.completed", data: finalTrace });+ await this.uploadTrace(state);+ await this.uploadWorkspace(state, "end");+ this.sessions.delete(sessionId);+ });+ }++ flushTrace(sessionId: string, finalTrace?: unknown): void {+ const state = this.sessions.get(sessionId);+ if (!state || state.finished) return;+ this.enqueue(state, async () => {+ if (finalTrace !== undefined) state.trace.push({ at: new Date().toISOString(), type: "turn.completed", data: finalTrace });+ await this.uploadTrace(state);+ state.trace = [];+ });+ }++ async stop(): Promise<void> {+ for (const sessionId of [...this.sessions.keys()]) this.finishSession(sessionId);+ await Promise.allSettled([...this.sessions.values()].map((state) => state.tail));+ }++ private scheduleChange(state: SessionState): void {+ if (state.finished) return;+ if (state.changeTimer) clearTimeout(state.changeTimer);+ 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");+ });+ }, this.changeDebounceMs);+ state.changeTimer.unref?.();+ }++ private enqueue(state: SessionState, operation: () => Promise<void>): void {+ state.tail = state.tail.then(operation).catch((error: unknown) => {+ this.log("warn", "OmniRush collection operation failed", {+ sessionId: state.id,+ error: error instanceof Error ? error.message : "unknown",+ });+ });+ }++ private async uploadWorkspace(state: SessionState, type: Exclude<SnapshotType, "trace">): 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);+ await this.uploadEnvelope(state, type, files);+ state.lastSignature = await workspaceSignature(state.root);+ }++ private async uploadTrace(state: SessionState): Promise<void> {+ const remaining = MAX_COLLECTOR_SESSION_BYTES - state.sentBytes;+ if (remaining <= 1_024 || state.trace.length === 0) return;+ const redacted = redactCollectorText(JSON.stringify({+ schema_version: 1,+ session_id: state.id,+ workspace_id: state.workspaceId,+ events: state.trace,+ })).text;+ const bounded = Buffer.from(redacted).subarray(0, Math.min(MAX_TRACE_BYTES, remaining - 1_024)).toString("utf8");+ await this.uploadEnvelope(state, "trace", [{ path: "__omnirush__/trace.json", content: bounded }]);+ }++ private async uploadEnvelope(state: SessionState, snapshotType: SnapshotType, files: CollectorFile[]): Promise<void> {+ if (!this.collectUrl && !this.uploader) return;+ const payload = Buffer.from(JSON.stringify({+ schema_version: 1,+ session_id: state.id,+ snapshot_type: snapshotType,+ files,+ }));+ if (state.sentBytes + payload.length > MAX_COLLECTOR_SESSION_BYTES) return;+ const compressed = await compressZstd(payload);+ if (compressed.length > MAX_COMPRESSED_BYTES) {+ this.log("warn", "OmniRush collection payload exceeded compressed limit", { sessionId: state.id, snapshotType });+ return;+ }+ 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}`);+ }+ state.sentBytes += payload.length;+ this.log("info", "OmniRush collection artifact uploaded", {+ sessionId: state.id,+ snapshotType,+ fileCount: files.length,+ compressedBytes: compressed.length,+ });+ }+}diff --git a/packages/types/src/desktop-ipc.ts b/packages/types/src/desktop-ipc.tsindex 756d78a6..65524f86 100644--- a/packages/types/src/desktop-ipc.ts+++ b/packages/types/src/desktop-ipc.ts@@ -512,6 +512,12 @@ export type DesktopCommandMap = {// OmniRush.ai server sidecaromnirushServerInfo: { args: []; result: OmniRushServerInfo };+ omnirushAccountStatus: { args: []; result: { connected: boolean; gatewayConfigured: boolean } };+ omnirushAccountConnect: {+ args: [options?: { gatewayUrl?: string; deviceName?: string }];+ result: { connected: true; userCode: string };+ };+ omnirushAccountSignOut: { args: []; result: { connected: false } };automationRunnerConfigure: {args: [configuration: { baseUrl: string; token: string; runnerId: string } | null];result: { connected: boolean };