Skip to content

Formerly KrillinAI, VideoTranslation and Dubbing Tool for 120+ Languages. Open-source AI workspace for creators, powered by Codex. Video downloader, video translation, create videos, images, audios, and edits with Agents in one place. For your Social Media like YouTube, TikTok, Instagram, etc.

fix(daemon): fund automatic probes with platform credentials

Leggett6d422e47110c
diff --git a/apps/daemon/src/api/server.ts b/apps/daemon/src/api/server.ts
index b8a0917b..604d1713 100644
--- a/apps/daemon/src/api/server.ts
+++ b/apps/daemon/src/api/server.ts
@@ -237,11 +237,12 @@ import { registerCodexRoutes } from './routes.codex.js';
import { registerCleanupRoutes } from './routes.cleanup.js';
import { registerCreatorServicesRoutes } from './routes.creator-services.js';
import { registerGatewayAccountRoutes } from './routes.gateway-account.js';
-import { createGatewayAccountService } from '../gateway/account-service.js';
+import { createGatewayAccountService, type GatewayAccountService } from '../gateway/account-service.js';
import { createGatewayClient, GatewayError, type GatewayClient } from '../gateway/client.js';
import { createGatewayRuntimeBindings } from '../gateway/runtime-bindings.js';
import { createOfficialFetch } from '../gateway/official-fetch.js';
import { createOfficialModelAccess } from '../gateway/model-access.js';
+import { preparePlatformProbe } from '../gateway/platform-probe.js';
import { createRuntimeSource } from '../gateway/runtime-source.js';
import { createGatewayCreatorSource } from '../gateway/creator-service-source.js';
import { createCodexAppServerHost } from '../codex/app-server-host-2026-07-28.js';
@@ -304,6 +305,7 @@ export type BuildServerInput = {
codexSessionProvider?: CodexSessionProvider;
codexModelCatalog?: CodexModelCatalog;
getCodexAvailabilityProbe?(): CodexAvailabilityProbe | undefined;
+ onPrepareAvailabilityProbe?(prepare: () => ReturnType<typeof preparePlatformProbe>): void;
memoryHistoryReader?(threadId: string): { items: import('@opencreator/protocol').ThreadHistoryItem[] } | undefined;
creatorServicesConfigStore?: CreatorServicesConfigStore;
videoMetadataService?: VideoMetadataService;
@@ -535,9 +537,12 @@ export async function buildServer(input: BuildServerInput) {
refresh: unavailable, bootstrap: unavailable, avatar: unavailable, logout: unavailable, request: unavailable
};
let officialInjectors: Record<string, import('../agent-tools/run-injection.js').AgentScheduleProcessInjector> = {};
- const gatewayAccount = createGatewayAccountService({
+ const gatewayAccount: GatewayAccountService = createGatewayAccountService({
dataDir, client: gatewayClient,
- modelAccess: createOfficialModelAccess({ dataDir, fetcher: createOfficialFetch({ readProxy: readCommonProxy }), readProxy: readCommonProxy }),
+ modelAccess: createOfficialModelAccess({
+ dataDir, fetcher: createOfficialFetch({ readProxy: readCommonProxy }), readProxy: readCommonProxy,
+ readProbeCredentials: () => gatewayAccount.probeCredentials()
+ }),
hasActiveTasks: () => [appServerRuntimeManager, creatorAppServerRuntimeManager, stickmanContentRuntimeManager]
.some(manager => manager?.listScopes().some(scope => scope.active || scope.pending > 0))
|| creatorRepository.listJobs().some(job => job.status === 'running' || job.stages.some(stage => stage.status === 'queued')) || gatewayCreatorSource?.isBusy() === true,
@@ -1638,6 +1643,7 @@ export async function buildServer(input: BuildServerInput) {
});
if (input.schedulerAutostart === true) scheduler.start();
+ input.onPrepareAvailabilityProbe?.(() => preparePlatformProbe({ account: gatewayAccount, readProxy: readCommonProxy }));
return server;
}
diff --git a/apps/daemon/src/codex/probe.ts b/apps/daemon/src/codex/probe.ts
index fd76079b..fc4a2965 100644
--- a/apps/daemon/src/codex/probe.ts
+++ b/apps/daemon/src/codex/probe.ts
@@ -30,6 +30,7 @@ export type CodexProbeInput = {
forceKillGraceMs?: number;
finalKillSettleMs?: number;
env?: Record<string, string>;
+ baseEnvironment?: NodeJS.ProcessEnv;
signal?: AbortSignal;
};
@@ -84,6 +85,7 @@ export async function probeCodex(input: CodexProbeInput): Promise<CodexProbeResu
forceKillGraceMs: input.forceKillGraceMs ?? CODEX_PROBE_FORCE_KILL_GRACE_MS,
finalKillSettleMs: input.finalKillSettleMs ?? CODEX_PROBE_FINAL_SETTLE_MS,
env: input.env,
+ baseEnvironment: input.baseEnvironment,
onStdoutLine(line) {
const inspected = inspectProbeLine(line);
if (inspected.eventSeen && firstEventMs === undefined) {
diff --git a/apps/daemon/src/gateway/account-service.ts b/apps/daemon/src/gateway/account-service.ts
index 60306552..8533fd9b 100644
--- a/apps/daemon/src/gateway/account-service.ts
+++ b/apps/daemon/src/gateway/account-service.ts
@@ -1,7 +1,7 @@
import type { GatewayAccountState, GatewayBalanceSnapshot, GatewayBalanceState, ServiceSource } from '@opencreator/protocol';
import { z } from 'zod';
import { createGatewayConfigStore, type GatewayCredentials } from './config-store.js';
-import { accountSchema, bootstrapSchema, catalogSchema, GatewayError, type GatewayBootstrap, type GatewayClient, type GatewayDeviceGrant } from './client.js';
+import { accountSchema, bootstrapSchema, catalogSchema, probeCredentialsSchema, GatewayError, type GatewayBootstrap, type GatewayClient, type GatewayDeviceGrant, type GatewayProbeCredentials } from './client.js';
import { officialModelPolicy, withModelCatalog, type OfficialModelAccess } from './model-access.js';
export function createGatewayAccountService(input: {
@@ -30,7 +30,8 @@ export function createGatewayAccountService(input: {
let mutation = Promise.resolve();
let selectedModels: Record<string, string> = {};
let localUses = 0;
- let probeUses = 0;
+ let platformProbeCredentials: GatewayProbeCredentials | undefined;
+ let platformProbeWork: Promise<GatewayProbeCredentials> | undefined;
let accessWork: Promise<void> | undefined;
let accessController: AbortController | undefined;
let accessUpdatedAt = 0;
@@ -72,23 +73,20 @@ export function createGatewayAccountService(input: {
accessUpdatedAt = Date.now();
const controller = new AbortController(); accessController = controller;
accessWork = (async () => {
- const use = await acquireModelUse(true);
- try {
- const original = bootstrapSchema.parse(assertSignedIn()); const expected = generation;
- await input.modelAccess!.refresh(original, controller.signal, async () => {
- await serialize(async () => {
- if (controller.signal.aborted || closing || generation !== expected || state.authState !== 'signed_in'
- || credentials?.account?.id !== original.account.id || credentials.keyVersion !== original.keyVersion) return;
- const next = input.modelAccess!.filter(withModelCatalog(bootstrapSchema.parse(credentials), officialModelPolicy(credentials.models ?? [])));
- if (JSON.stringify(state.models) !== JSON.stringify(next.models) || JSON.stringify(state.selectedModels) !== JSON.stringify(next.defaults)) {
- credentials = { ...credentials, defaults: next.defaults };
- selectedModels = { ...next.defaults }; state.selectedModels = { ...selectedModels }; state.models = next.models;
- await store.writeCredentials(credentials); await saveConfiguration();
- }
- await synchronizeAccessibleRuntime();
- });
+ const original = bootstrapSchema.parse(assertSignedIn()); const expected = generation;
+ await input.modelAccess!.refresh(original, controller.signal, async () => {
+ await serialize(async () => {
+ if (controller.signal.aborted || closing || generation !== expected || state.authState !== 'signed_in'
+ || credentials?.account?.id !== original.account.id || credentials.keyVersion !== original.keyVersion) return;
+ const next = input.modelAccess!.filter(withModelCatalog(bootstrapSchema.parse(credentials), officialModelPolicy(credentials.models ?? [])));
+ if (JSON.stringify(state.models) !== JSON.stringify(next.models) || JSON.stringify(state.selectedModels) !== JSON.stringify(next.defaults)) {
+ credentials = { ...credentials, defaults: next.defaults };
+ selectedModels = { ...next.defaults }; state.selectedModels = { ...selectedModels }; state.models = next.models;
+ await store.writeCredentials(credentials); await saveConfiguration();
+ }
+ await synchronizeAccessibleRuntime();
});
- } finally { await use.release(); }
+ });
})().catch(() => undefined).finally(() => { if (accessController === controller) accessController = undefined; accessWork = undefined; });
}
function initialize(): Promise<void> {
@@ -262,6 +260,7 @@ export function createGatewayAccountService(input: {
}
}
credentials = { ...tokens, accessExpiresAt: new Date(Date.now() + tokens.expiresIn * 1000).toISOString() };
+ platformProbeCredentials = undefined; platformProbeWork = undefined;
await store.writeCredentials(credentials);
if (generation !== current.generation || attempt !== current) return;
state.source = 'gateway'; state.authState = 'signed_in'; attempt = undefined;
@@ -277,20 +276,35 @@ export function createGatewayAccountService(input: {
fail(error); await cancelAuthorization();
}
}
- async function readModelCredentials(probing = false): Promise<{ accountId: string; modelKey: string; keyVersion: string; bindingVersion: string; baseUrl: string; transport?: GatewayBootstrap['transport']; models: GatewayBootstrap['models']; defaults: Record<string, string> }> {
+ async function readModelCredentials(): Promise<{ accountId: string; modelKey: string; keyVersion: string; bindingVersion: string; baseUrl: string; transport?: GatewayBootstrap['transport']; models: GatewayBootstrap['models']; defaults: Record<string, string> }> {
await initialize(); await refresh();
const value = assertSignedIn();
- if (state.source !== 'gateway' || (!probing && state.activationState !== 'ready') || !value.account || !value.modelKey || !value.keyVersion || !value.bindingVersion || !value.baseUrl || !value.models || !value.defaults) throw new GatewayError('services_not_ready');
+ if (state.source !== 'gateway' || state.activationState !== 'ready' || !value.account || !value.modelKey || !value.keyVersion || !value.bindingVersion || !value.baseUrl || !value.models || !value.defaults) throw new GatewayError('services_not_ready');
return { accountId: value.account.id, modelKey: value.modelKey, keyVersion: value.keyVersion, bindingVersion: value.bindingVersion, baseUrl: value.baseUrl, transport: value.transport, models: structuredClone(state.models), defaults: { ...value.defaults } };
}
const modelCredentials = () => readModelCredentials();
+ async function probeCredentials(): Promise<GatewayProbeCredentials> {
+ await initialize(); await refresh();
+ const current = assertSignedIn(); const expected = generation;
+ if (platformProbeCredentials && Date.parse(platformProbeCredentials.expiresAt) > Date.now() + 60_000) return platformProbeCredentials;
+ if (platformProbeWork) return platformProbeWork;
+ const work = (async () => {
+ const value = probeCredentialsSchema.parse(await input.client.request('/api/v1/client/probe-credentials', current.accessToken, {}));
+ if (generation !== expected || state.authState !== 'signed_in' || credentials?.account?.id !== current.account?.id) throw new GatewayError('auth_required', 401);
+ if (value.modelKey === credentials?.modelKey || Date.parse(value.expiresAt) <= Date.now()) throw new GatewayError('services_not_ready');
+ platformProbeCredentials = value;
+ return value;
+ })();
+ platformProbeWork = work;
+ try { return await work; } finally { if (platformProbeWork === work) platformProbeWork = undefined; }
+ }
function reportUsage() {
const result = usageMutation.then(async () => {
if (!credentials?.keyRotation || !credentials.keyVersion || state.authState !== 'signed_in') return undefined;
await refresh();
const current = assertSignedIn(); const expected = generation;
const value = z.object({ keyVersion: z.string().min(1) }).parse(await input.client.request('/api/v1/client/usage', current.accessToken, {
- keyVersion: current.keyVersion, installationId: await store.readDeviceID(), busy: localUses > 0 || probeUses > 0 || input.hasActiveTasks(), pending: input.hasPendingTasks?.() === true
+ keyVersion: current.keyVersion, installationId: await store.readDeviceID(), busy: localUses > 0 || input.hasActiveTasks(), pending: input.hasPendingTasks?.() === true
}));
if (generation !== expected || state.authState !== 'signed_in') throw new GatewayError('auth_required', 401);
return value.keyVersion;
@@ -318,13 +332,13 @@ export function createGatewayAccountService(input: {
selectedModels = { ...visible.defaults }; state.selectedModels = { ...selectedModels };
await saveConfiguration();
}
- async function acquireModelUse(probing = false) {
- await readModelCredentials(probing);
- if (probing) probeUses++; else localUses++;
+ async function acquireModelUse() {
+ await readModelCredentials();
+ localUses++;
let released = false;
const release = async () => {
if (released) return;
- released = true; if (probing) probeUses--; else localUses--;
+ released = true; localUses--;
await reportUsage().catch(() => undefined);
};
try {
@@ -336,7 +350,7 @@ export function createGatewayAccountService(input: {
version = await reportUsage();
}
if (version && version !== credentials?.keyVersion) await synchronizeBinding();
- return { credentials: await readModelCredentials(probing), release };
+ return { credentials: await readModelCredentials(), release };
} catch (error) { await release(); throw error; }
}
const beginModelUse = () => acquireModelUse();
@@ -354,7 +368,7 @@ export function createGatewayAccountService(input: {
runtimeTextModel = undefined;
if (credentials) await input.client.logout(credentials.accessToken).catch(() => undefined);
await store.deleteCredentials(); state.source = 'manual'; state.bindingVersion = null; await saveConfiguration();
- credentials = undefined; balance = null; profileUpdatedAt = 0; catalogUpdatedAt = 0; accessUpdatedAt = 0; accessBlocked = false;
+ credentials = undefined; platformProbeCredentials = undefined; balance = null; profileUpdatedAt = 0; catalogUpdatedAt = 0; accessUpdatedAt = 0; accessBlocked = false;
state = { ...state, authState: 'signed_out', activationState: 'inactive', account: null, models: [], bindingVersion: null, activationError: null };
}).finally(() => { accessPaused = false; });
}
@@ -367,7 +381,7 @@ export function createGatewayAccountService(input: {
}
return {
peekState() { return structuredClone(state); },
- startAuthorization, cancelAuthorization, pollAuthorization, checkAuthorization, refresh, logout, modelCredentials, beginModelUse, readBalance, billing,
+ startAuthorization, cancelAuthorization, pollAuthorization, checkAuthorization, refresh, logout, modelCredentials, beginModelUse, probeCredentials, readBalance, billing,
readPlans() { return input.client.request('/api/v1/plans', ''); },
async readAvatar(accountId: string) {
await initialize(); await refresh();
diff --git a/apps/daemon/src/gateway/client.ts b/apps/daemon/src/gateway/client.ts
index c4b65313..10d2b695 100644
--- a/apps/daemon/src/gateway/client.ts
+++ b/apps/daemon/src/gateway/client.ts
@@ -26,6 +26,11 @@ export const bootstrapSchema = z.object({
models: z.array(modelSchema), defaults: z.record(z.string())
});
export type GatewayBootstrap = z.infer<typeof bootstrapSchema>;
+export const probeCredentialsSchema = z.object({
+ costBearer: z.literal('platform'), modelKey: z.string().min(1), keyVersion: z.string().min(1),
+ baseUrl: z.literal('https://openrouter.ai/api/v1'), expiresAt: z.string().datetime()
+});
+export type GatewayProbeCredentials = z.infer<typeof probeCredentialsSchema>;
export type GatewayTokens = z.infer<typeof tokenSchema>;
export type GatewayDeviceGrant = { attemptId: string; deviceSecret: string; authorizationUrl: string; interval: number; expiresIn: number };
export type GatewayClient = {
diff --git a/apps/daemon/src/gateway/model-access.ts b/apps/daemon/src/gateway/model-access.ts
index 7d262e44..3208a9bc 100644
--- a/apps/daemon/src/gateway/model-access.ts
+++ b/apps/daemon/src/gateway/model-access.ts
@@ -4,7 +4,7 @@ import { join } from 'node:path';
import { z } from 'zod';
import type { GatewayModel } from '@opencreator/protocol';
import { readPrivateJsonFile, writePrivateJsonFile } from '../config/private-json-file.js';
-import type { GatewayBootstrap } from './client.js';
+import { probeCredentialsSchema, type GatewayBootstrap, type GatewayProbeCredentials } from './client.js';
const allowedTTL = 24 * 60 * 60_000;
const blockedTTL = 60 * 60_000;
@@ -49,7 +49,10 @@ const preferred: Record<string, string[]> = {
'google-gemma': ['google/gemma-3-12b-it', 'google/gemma-3-27b-it']
};
-export function createOfficialModelAccess(input: { dataDir: string; fetcher: typeof fetch; readProxy(): Promise<string> }) {
+export function createOfficialModelAccess(input: {
+ dataDir: string; fetcher: typeof fetch; readProxy(): Promise<string>;
+ readProbeCredentials(): Promise<GatewayProbeCredentials>;
+}) {
const path = join(input.dataDir, 'config', 'gateway-model-access.json');
let cache: AccessCache = { version: 1, base: '', network: '', groups: {} };
let loaded: Promise<void> | undefined;
@@ -139,6 +142,10 @@ export function createOfficialModelAccess(input: { dataDir: string; fetcher: typ
return rank(a) - rank(b);
}).slice(0, 12);
const expectedBase = cache.base;
+ if (!pending.length || signal.aborted) return;
+ const credentials = probeCredentialsSchema.parse(await input.readProbeCredentials());
+ if (credentials.costBearer !== 'platform' || credentials.modelKey === bootstrap.modelKey
+ || Date.parse(credentials.expiresAt) <= Date.now() || signal.aborted || cache.base !== expectedBase) return;
const deadline = Date.now() + 20_000;
async function worker() {
while (pending.length && !signal.aborted && Date.now() < deadline && cache.base === expectedBase) {
@@ -149,7 +156,7 @@ export function createOfficialModelAccess(input: { dataDir: string; fetcher: typ
return rank(a.id) - rank(b.id);
});
const representative = (previous?.alternate ? choices.find(model => model.id !== previous.representative) : undefined) ?? choices[0]!;
- const result = await check(representative, bootstrap.modelKey, signal);
+ const result = await check(representative, credentials.modelKey, signal);
if (signal.aborted || cache.base !== expectedBase) return;
cache.groups[group] = {
status: result.status === 'unknown' ? previous?.status ?? 'unknown' : result.status,
diff --git a/apps/daemon/src/gateway/platform-probe.ts b/apps/daemon/src/gateway/platform-probe.ts
new file mode 100644
index 00000000..378a429e
--- /dev/null
+++ b/apps/daemon/src/gateway/platform-probe.ts
@@ -0,0 +1,29 @@
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { GatewayAccountService } from './account-service.js';
+import { createGatewayRuntimeBindings } from './runtime-bindings.js';
+
+export async function preparePlatformProbe(input: {
+ account: Pick<GatewayAccountService, 'readState' | 'probeCredentials'>;
+ readProxy(): Promise<string>;
+}) {
+ const state = await input.account.readState();
+ if (state.authState !== 'signed_in') return undefined;
+ const model = state.models.find(candidate => candidate.id === state.selectedModels?.text
+ && candidate.modality === 'text' && candidate.capabilities.includes('responses'));
+ if (!model) return undefined;
+ const credentials = await input.account.probeCredentials();
+ const home = await mkdtemp(join(tmpdir(), 'opencreator-platform-probe-'));
+ const bindings = createGatewayRuntimeBindings({
+ codexHome: home, baseUrl: credentials.baseUrl, model: model.id, direct: true,
+ readProxy: input.readProxy,
+ readCredentials: async () => ({ accountId: state.account!.id, modelKey: credentials.modelKey, keyVersion: credentials.keyVersion }),
+ closeRuntime: async () => undefined
+ });
+ const cleanup = async () => {
+ try { await bindings.close(); } finally { await rm(home, { recursive: true, force: true }); }
+ };
+ try { return { ...await bindings.prepare(), cleanup }; }
+ catch (error) { await cleanup(); throw error; }
+}
diff --git a/apps/daemon/src/main.ts b/apps/daemon/src/main.ts
index 82fc37dc..d264b604 100644
--- a/apps/daemon/src/main.ts
+++ b/apps/daemon/src/main.ts
@@ -19,6 +19,8 @@ import {
} from './codex/capabilities.js';
import { resolveCodexHome } from './codex/home.js';
import { importLocalCodexConfiguration } from './codex/probe-home.js';
+import { setTimeout as delay } from 'node:timers/promises';
+import type { preparePlatformProbe } from './gateway/platform-probe.js';
import {
CODEX_PROBE_TIMEOUT_MS,
probeCodex
@@ -50,6 +52,7 @@ let releaseRuntimeLock: (() => void) | undefined;
let stopManagedParentWatch: (() => void) | undefined;
let cancelCapabilityRefresh: (() => void) | undefined;
let cancelAvailabilityProbe: (() => void) | undefined;
+let availabilityProbeWork: Promise<void> | undefined;
await main().catch(error => {
emitBootstrapError({
@@ -155,11 +158,13 @@ async function main(): Promise<void> {
startBackgroundRefresh() {}
};
const capabilities = capabilityResolution.state;
+ let prepareAvailabilityProbe: (() => ReturnType<typeof preparePlatformProbe>) | undefined;
const { buildServer } = await import('./api/server.js');
server = await buildServer(createProductionServerInput({
token,
capabilities,
getCodexAvailabilityProbe: () => availabilityProbe,
+ onPrepareAvailabilityProbe(prepare) { prepareAvailabilityProbe = prepare; },
persistentAppServerEnabled:
process.env.OPENCREATOR_PERSISTENT_APP_SERVER !== '0',
...(process.env.OPENCREATOR_E2E_FAKE_CODEX_CONFIG !== undefined
@@ -207,14 +212,19 @@ async function main(): Promise<void> {
if (shouldRunAvailabilityProbe) {
const controller = new AbortController();
cancelAvailabilityProbe = () => controller.abort();
- void runAvailabilityProbe({
+ availabilityProbeWork = runAvailabilityProbe({
codexBin,
- codexHome,
dataDir,
+ prepare: () => prepareAvailabilityProbe!(),
signal: controller.signal,
update(next) {
availabilityProbe = next;
}
+ }).catch(() => {
+ if (!controller.signal.aborted) availabilityProbe = {
+ status: 'failed', checkedAt: new Date().toISOString(),
+ errorCode: 'PLATFORM_PROBE_UNAVAILABLE', message: 'Platform availability probe is unavailable'
+ };
});
}
}
@@ -228,6 +238,7 @@ async function closeServer(): Promise<void> {
stopManagedParentWatch = undefined;
cancelCapabilityRefresh?.();
cancelAvailabilityProbe?.();
+ await availabilityProbeWork;
closeWork ??= server?.close() ?? Promise.resolve();
await closeWork;
releaseRuntimeLock?.();
@@ -401,18 +412,28 @@ function probeErrorMessage(input: {
async function runAvailabilityProbe(input: {
codexBin: string;
- codexHome: string;
dataDir: string;
+ prepare(): ReturnType<typeof preparePlatformProbe>;
signal: AbortSignal;
update(probe: CodexAvailabilityProbe): void;
}): Promise<void> {
- const result = await probeCodex({
- codexBin: input.codexBin,
- codexHome: input.codexHome,
- cwd: join(input.dataDir, 'probe'),
- timeoutMs: CODEX_PROBE_TIMEOUT_MS,
- signal: input.signal
- });
+ let prepared: Awaited<ReturnType<typeof input.prepare>>;
+ while (!input.signal.aborted) {
+ try { prepared = await input.prepare(); } catch { /* Retry when platform credentials become available. */ }
+ if (prepared) break;
+ await delay(30_000, undefined, { signal: input.signal });
+ }
+ if (!prepared) return;
+ if (input.signal.aborted) { await prepared.cleanup(); return; }
+ const result = await (async () => {
+ try {
+ return await probeCodex({
+ codexBin: input.codexBin, codexHome: prepared.codexHome,
+ baseEnvironment: prepared.env, cwd: join(input.dataDir, 'probe'),
+ timeoutMs: CODEX_PROBE_TIMEOUT_MS, signal: input.signal
+ });
+ } finally { await prepared.cleanup(); }
+ })();
if (input.signal.aborted) return;
const checkedAt = new Date().toISOString();
if (result.ready) {
diff --git a/apps/daemon/test/integration/gateway-runtime-protocol.test.ts b/apps/daemon/test/integration/gateway-runtime-protocol.test.ts
index b73e730a..cea5f05f 100644
--- a/apps/daemon/test/integration/gateway-runtime-protocol.test.ts
+++ b/apps/daemon/test/integration/gateway-runtime-protocol.test.ts
@@ -7,6 +7,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { createCodexAppServerHost, type CodexAppServerHost } from '../../src/codex/app-server-host-2026-07-28.js';
import { createGatewayRuntimeBindings } from '../../src/gateway/runtime-bindings.js';
import { createDirectRuntime } from '../../src/gateway/direct-runtime.js';
+import { preparePlatformProbe } from '../../src/gateway/platform-probe.js';
+import * as officialFetch from '../../src/gateway/official-fetch.js';
+import { probeCodex } from '../../src/codex/probe.js';
+import type { GatewayAccountState } from '@opencreator/protocol';
const manifest = JSON.parse(readFileSync(resolve(`../../resources/codex-runtime/${process.platform}-${process.arch}/manifest.json`), 'utf8'));
const codexBin = resolve('../../apps/desktop/.pack/codex-runtime', manifest.binary.relativePath);
@@ -61,7 +65,7 @@ async function fixture(reply: (res: ServerResponse, requests: ModelRequest[]) =>
cwd: root, sandbox: 'danger-full-access', model: 'gpt-5.2',
prompt: 'Report the current directory and then say gateway ready.', timeoutMs: 15_000
});
- return { binding, prepared, host, requests, run };
+ return { binding, prepared, host, requests, run, root, supplierUrl: `http://127.0.0.1:${address.port}/v1/responses` };
}
function event(res: ServerResponse, type: string, value: Record<string, unknown>) {
@@ -95,6 +99,58 @@ const message = {
};
describe('bundled Runtime official gateway boundary', () => {
+ it('runs startup inference with the platform key and user tasks with the user key', async () => {
+ const f = await fixture(res => complete(res, [message]));
+ const fetcher = vi.spyOn(officialFetch, 'createOfficialFetch')
+ .mockReturnValue((_target, options) => fetch(f.supplierUrl, options));
+ cleanup.push(() => { fetcher.mockRestore(); });
+ const account = {
+ readState: async (): Promise<GatewayAccountState> => ({
+ source: 'gateway', authState: 'signed_in', activationState: 'ready',
+ account: { id: 'a', email: 'a@test', verified: true }, bindingVersion: '1',
+ models: [{ id: 'gpt-5.2', modality: 'text', capabilities: ['responses'] }],
+ selectedModels: { text: 'gpt-5.2' }, activationError: null
+ }),
+ probeCredentials: vi.fn(async () => ({
+ costBearer: 'platform' as const, modelKey: 'test-platform-probe-key', keyVersion: 'probe-1',
+ baseUrl: 'https://openrouter.ai/api/v1' as const, expiresAt: new Date(Date.now() + 60_000).toISOString()
+ }))
+ };
+ const prepared = await preparePlatformProbe({ account, readProxy: async () => '' });
+ expect(prepared).toBeDefined();
+ cleanup.push(() => prepared!.cleanup());
+ const result = await probeCodex({
+ codexBin, codexHome: prepared!.codexHome, cwd: join(f.root, 'probe'),
+ baseEnvironment: prepared!.env, timeoutMs: 15_000
+ });
+ expect(result.ready).toBe(true);
+ expect(f.requests).toHaveLength(1);
+ expect(f.requests[0]!.headers.authorization).toBe('Bearer test-platform-probe-key');
+ expect(JSON.stringify(f.requests[0]!.body.input)).toContain('startup availability probe');
+ expect((await f.run().result).turnStatus).toBe('completed');
+ expect(f.requests).toHaveLength(2);
+ expect(f.requests[1]!.headers.authorization).toBe('Bearer test-official-key-a');
+ const home = prepared!.codexHome;
+ await prepared!.cleanup();
+ expect(existsSync(home)).toBe(false);
+ }, 30_000);
+
+ it('waits for platform authorization and fails without submitting a user-funded probe', async () => {
+ const probeCredentials = vi.fn(async () => { throw new Error('platform unavailable'); });
+ const state: GatewayAccountState = {
+ source: 'manual', authState: 'signed_out', activationState: 'inactive',
+ account: null, bindingVersion: null, models: [], activationError: null
+ };
+ const account = { readState: async () => state, probeCredentials };
+ expect(await preparePlatformProbe({ account, readProxy: async () => '' })).toBeUndefined();
+ expect(probeCredentials).not.toHaveBeenCalled();
+ Object.assign(state, {
+ source: 'gateway', authState: 'signed_in', account: { id: 'a', email: 'a@test', verified: true },
+ models: [{ id: 'gpt-5.2', modality: 'text', capabilities: ['responses'] }], selectedModels: { text: 'gpt-5.2' }
+ });
+ await expect(preparePlatformProbe({ account, readProxy: async () => '' })).rejects.toThrow('platform unavailable');
+ expect(probeCredentials).toHaveBeenCalledOnce();
+ });
it('preserves complete tool history through the direct stateless connection', async () => {
const f = await fixture((res, requests) => {
if (requests.length === 1) complete(res, [{ id: 'fc_direct', type: 'function_call', call_id: 'call_direct', name: 'exec_command', arguments: JSON.stringify({ cmd: 'pwd', max_output_tokens: 100 }), status: 'completed' }]);
diff --git a/apps/daemon/test/unit/gateway-account-service.test.ts b/apps/daemon/test/unit/gateway-account-service.test.ts
index 226228cc..413632e5 100644
--- a/apps/daemon/test/unit/gateway-account-service.test.ts
+++ b/apps/daemon/test/unit/gateway-account-service.test.ts
@@ -3,7 +3,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, expect, it, vi } from 'vitest';
import * as module from '../../src/gateway/account-service.js';
-import { GatewayError, type GatewayBootstrap } from '../../src/gateway/client.js';
+import { GatewayError, type GatewayBootstrap, type GatewayProbeCredentials } from '../../src/gateway/client.js';
import { createGatewayConfigStore } from '../../src/gateway/config-store.js';
import Fastify from 'fastify';
import { registerGatewayAccountRoutes } from '../../src/api/routes.gateway-account.js';
@@ -12,8 +12,12 @@ import { createGatewayCreatorSource } from '../../src/gateway/creator-service-so
import { createDefaultCreatorServicesConfig } from '@opencreator/protocol';
const roots: string[] = [];
+const platformCredentials = (): GatewayProbeCredentials => ({
+ costBearer: 'platform', modelKey: 'platform-probe-key', keyVersion: 'probe-v1',
+ baseUrl: 'https://openrouter.ai/api/v1', expiresAt: new Date(Date.now() + 60 * 60_000).toISOString()
+});
afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); });
-async function setup(activate = vi.fn(async () => undefined), close = vi.fn(async () => undefined), hasPendingTasks = () => false, hasActiveTasks = () => false, modelAccess?: (root: string) => OfficialModelAccess) {
+async function setup(activate = vi.fn(async () => undefined), close = vi.fn(async () => undefined), hasPendingTasks = () => false, hasActiveTasks = () => false, modelAccess?: (root: string, readProbeCredentials: () => Promise<GatewayProbeCredentials>) => OfficialModelAccess) {
expect(module).toHaveProperty('createGatewayAccountService', expect.any(Function));
const root = await mkdtemp(join(tmpdir(), 'oc-gateway-account-')); roots.push(root);
let attempt = 0;
@@ -26,9 +30,12 @@ async function setup(activate = vi.fn(async () => undefined), close = vi.fn(asyn
async logout() {},
avatar: vi.fn(async () => ({ data: new Uint8Array([1, 2, 3]), contentType: 'image/png' })),
bootstrap: vi.fn(async (access: string): Promise<GatewayBootstrap> => { const id = access.split('-').at(-1)!; return { schemaVersion: 1 as const, account: { id, email: `${id}@example.test`, verified: true }, modelKey: `cloud-${id}`, keyVersion: '1', bindingVersion: `${id}:1`, baseUrl: 'https://gateway.example/v1', models: [{ id: 'gateway-text', modality: 'text' as const, capabilities: ['responses'] }], defaults: { text: 'gateway-text' } }; }),
- async request() { return {}; }
+ async request(path?: string) { return path === '/api/v1/client/probe-credentials' ? platformCredentials() : {}; }
};
- const service = module.createGatewayAccountService({ dataDir: root, client, activateRuntime: activate, closeRuntime: close, hasActiveTasks, hasPendingTasks, automaticPolling: false, modelAccess: modelAccess?.(root) });
+ const service: module.GatewayAccountService = module.createGatewayAccountService({
+ dataDir: root, client, activateRuntime: activate, closeRuntime: close, hasActiveTasks, hasPendingTasks, automaticPolling: false,
+ modelAccess: modelAccess?.(root, () => service.probeCredentials())
+ });
return { service, root, client, activate, close };
}
@@ -54,6 +61,36 @@ it('returns signed-in state immediately while bootstrap is still preparing model
} finally { release(); await work; await f.service.close(); }
});
+it('keeps platform credentials private and separate from user task credentials', async () => {
+ const f = await setup();
+ const grant = await f.service.startAuthorization(); await f.service.pollAuthorization(grant.attemptId);
+ const request = vi.spyOn(f.client, 'request');
+ const [a, b] = await Promise.all([f.service.probeCredentials(), f.service.probeCredentials()]);
+ expect(a).toEqual(b);
+ expect(request.mock.calls.filter(([path]) => path === '/api/v1/client/probe-credentials')).toHaveLength(1);
+ const task = await f.service.beginModelUse();
+ expect(task.credentials.modelKey).toBe('cloud-1'); await task.release();
+ expect(JSON.stringify(f.service.peekState())).not.toContain(a.modelKey);
+ expect(await readFile(join(f.root, 'config/gateway-credentials.json'), 'utf8')).not.toContain(a.modelKey);
+ await f.service.logout();
+ await expect(f.service.probeCredentials()).rejects.toMatchObject({ code: 'auth_required' });
+ await f.service.close();
+});
+
+it('rejects a platform credential that aliases the user key or has expired', async () => {
+ const f = await setup();
+ const grant = await f.service.startAuthorization(); await f.service.pollAuthorization(grant.attemptId);
+ const request = vi.spyOn(f.client, 'request');
+ request.mockResolvedValueOnce({ ...platformCredentials(), modelKey: 'cloud-1' });
+ await expect(f.service.probeCredentials()).rejects.toMatchObject({ code: 'services_not_ready' });
+ request.mockResolvedValueOnce({ ...platformCredentials(), expiresAt: new Date(Date.now() - 1000).toISOString() });
+ await expect(f.service.probeCredentials()).rejects.toMatchObject({ code: 'services_not_ready' });
+ request.mockRejectedValueOnce(new GatewayError('services_not_ready'));
+ await expect(f.service.probeCredentials()).rejects.toMatchObject({ code: 'services_not_ready' });
+ expect((await f.service.modelCredentials()).modelKey).toBe('cloud-1');
+ await f.service.close();
+});
+
it('coalesces simultaneous authorization polls so a grant is consumed only once', async () => {
const f = await setup();
let release!: () => void;
@@ -99,9 +136,10 @@ it('silently filters official families without blocking model selection or chang
let finishProbe!: () => void;
const waiting = new Promise<void>(resolve => { finishProbe = resolve; });
const requests: string[] = [];
- const f = await setup(undefined, undefined, undefined, undefined, root => createOfficialModelAccess({
- dataDir: root, readProxy: async () => '', fetcher: async (url, options) => {
+ const f = await setup(undefined, undefined, undefined, undefined, (root, readProbeCredentials) => createOfficialModelAccess({
+ dataDir: root, readProbeCredentials, readProxy: async () => '', fetcher: async (url, options) => {
if (String(url).endsWith('/cdn-cgi/trace')) return new Response('ip=203.0.113.1\nloc=JP\n');
+ expect(new Headers(options?.headers).get('authorization')).toBe('Bearer platform-probe-key');
const model = JSON.parse(String(options?.body)).model; requests.push(model);
await waiting;
return model.startsWith('openai/') ? Response.json({ error: { message: 'The request is prohibited due to a violation of provider Terms Of Service.' } }, { status: 403 })
@@ -113,6 +151,7 @@ it('silently filters official families without blocking model selection or chang
f.client.bootstrap.mockResolvedValue(raw);
const usage: Array<{ busy: boolean }> = [];
vi.spyOn(f.client, 'request').mockImplementation(async (path?: string, _access?: string, body?: unknown) => {
+ if (path === '/api/v1/client/probe-credentials') return platformCredentials();
if (path === '/api/v1/client/usage') { usage.push(body as { busy: boolean }); return { keyVersion: raw.keyVersion }; }
return path === '/api/v1/client/models' ? { models: raw.models } : { account: raw.account };
});
@@ -127,7 +166,7 @@ it('silently filters official families without blocking model selection or chang
await expect(f.service.selectModel('text', 'openai/gpt-6-sol')).rejects.toMatchObject({ code: 'invalid_model' });
expect((await f.service.modelCredentials()).models).toEqual(f.service.peekState().models);
expect((await createGatewayConfigStore(f.root).readCredentials())?.models).toHaveLength(6);
- expect(usage.some(value => value.busy)).toBe(true);
+ expect(usage.some(value => value.busy)).toBe(false);
await f.service.close();
expect(usage.at(-1)?.busy).toBe(false);
});
@@ -136,8 +175,8 @@ it('defers a blocked default replacement until idle and recovers after every fam
let active = true; let denyFallback = false; let recover = false;
let finishProbe!: () => void;
const waiting = new Promise<void>(resolve => { finishProbe = resolve; });
- const f = await setup(undefined, undefined, undefined, () => active, root => createOfficialModelAccess({
- dataDir: root, readProxy: async () => '', fetcher: async (url, options) => {
+ const f = await setup(undefined, undefined, undefined, () => active, (root, readProbeCredentials) => createOfficialModelAccess({
+ dataDir: root, readProbeCredentials, readProxy: async () => '', fetcher: async (url, options) => {
if (String(url).endsWith('/cdn-cgi/trace')) return new Response('ip=203.0.113.1\nloc=JP\n');
await waiting;
const model = JSON.parse(String(options?.body)).model;
@@ -150,7 +189,8 @@ it('defers a blocked default replacement until idle and recovers after every fam
const raw = { ...await f.client.bootstrap('access-1'), transport: 'openrouter-direct' as const, baseUrl: 'https://openrouter.ai/api/v1',
models: ['openai/gpt-4.1-mini', 'deepseek/deepseek-v3.2'].map(id => ({ id, modality: 'text' as const, capabilities: ['responses'] })), defaults: { text: 'openai/gpt-4.1-mini' } };
f.client.bootstrap.mockResolvedValue(raw);
- vi.spyOn(f.client, 'request').mockImplementation(async (path?: string) => path === '/api/v1/client/models' ? { models: raw.models } : { account: raw.account });
+ vi.spyOn(f.client, 'request').mockImplementation(async (path?: string) => path === '/api/v1/client/probe-credentials'
+ ? platformCredentials() : path === '/api/v1/client/models' ? { models: raw.models } : { account: raw.account });
const grant = await f.service.startAuthorization(); await f.service.pollAuthorization(grant.attemptId);
active = true; finishProbe();
await expect.poll(() => f.service.peekState().selectedModels?.text).toBe('deepseek/deepseek-v3.2');
@@ -175,8 +215,8 @@ it('defers a blocked default replacement until idle and recovers after every fam
it('aborts an in-flight availability check on logout without applying a late result', async () => {
let started = false; let aborted = false;
- const f = await setup(undefined, undefined, undefined, undefined, root => createOfficialModelAccess({
- dataDir: root, readProxy: async () => '', fetcher: async (url, options) => {
+ const f = await setup(undefined, undefined, undefined, undefined, (root, readProbeCredentials) => createOfficialModelAccess({
+ dataDir: root, readProbeCredentials, readProxy: async () => '', fetcher: async (url, options) => {
if (String(url).endsWith('/cdn-cgi/trace')) return new Response('ip=203.0.113.1\nloc=JP\n');
started = true;
return new Promise<Response>(resolve => options!.signal!.addEventListener('abort', () => {
diff --git a/apps/daemon/test/unit/gateway-model-access.test.ts b/apps/daemon/test/unit/gateway-model-access.test.ts
index a9cdaf92..10937292 100644
--- a/apps/daemon/test/unit/gateway-model-access.test.ts
+++ b/apps/daemon/test/unit/gateway-model-access.test.ts
@@ -24,13 +24,17 @@ async function fixture(models: GatewayModel[], reply: (id: string) => Response |
if (String(target).endsWith('/cdn-cgi/trace')) return new Response(`ip=${ip}\nloc=JP\n`);
const body = JSON.parse(String(options?.body)); calls.push(body.model);
expect(body).toMatchObject({ store: false, stream: false, max_output_tokens: 512 });
- expect(new Headers(options?.headers).get('authorization')).toBe('Bearer private-model-key');
+ expect(new Headers(options?.headers).get('authorization')).toBe('Bearer platform-probe-key');
return reply(body.model);
});
- const input = { dataDir: root, fetcher, readProxy: async () => proxy };
+ const readProbeCredentials = vi.fn(async () => ({
+ costBearer: 'platform' as const, modelKey: 'platform-probe-key', keyVersion: 'probe-v1',
+ baseUrl: 'https://openrouter.ai/api/v1' as const, expiresAt: new Date(Date.now() + 60 * 60_000).toISOString()
+ }));
+ const input = { dataDir: root, fetcher, readProxy: async () => proxy, readProbeCredentials };
const access = createOfficialModelAccess(input); const value = bootstrap(models);
const run = (target = value) => access.refresh(target, new AbortController().signal, async () => undefined);
- return { root, input, access, value, run, calls, fetcher, setIP(value: string) { ip = value; }, setProxy(value: string) { proxy = value; } };
+ return { root, input, access, value, run, calls, fetcher, readProbeCredentials, setIP(value: string) { ip = value; }, setProxy(value: string) { proxy = value; } };
}
it('keeps hosted GPT and Gemini separate from open weight models and removes unsupported catalog entries', () => {
@@ -145,3 +149,32 @@ it('bounds each background pass and stops starting probes after cancellation', a
await f.access.refresh(f.value, controller.signal, async () => undefined);
expect(f.calls).toHaveLength(12);
});
+
+it('never falls back to the user key when platform credentials are unavailable', async () => {
+ const f = await fixture([text('deepseek/deepseek-v3.2')]);
+ f.readProbeCredentials.mockRejectedValueOnce(new Error('platform unavailable'));
+ await expect(f.run()).rejects.toThrow('platform unavailable');
+ expect(f.calls).toEqual([]);
+ await f.run();
+ expect(f.calls).toHaveLength(1);
+});
+
+it.each(['user-key', 'expired'] as const)('does not perform inference with %s platform credentials', async failure => {
+ const f = await fixture([text('deepseek/deepseek-v3.2')]);
+ const credentials = await f.readProbeCredentials();
+ f.readProbeCredentials.mockResolvedValue({
+ ...credentials, ...(failure === 'user-key'
+ ? { modelKey: f.value.modelKey } : { expiresAt: new Date(Date.now() - 1000).toISOString() })
+ });
+ await f.run();
+ expect(f.calls).toEqual([]);
+});
+
+it('keeps cached access results and avoids requesting credentials when no probe is due', async () => {
+ const f = await fixture([text('deepseek/deepseek-v3.2')]);
+ await f.run();
+ f.readProbeCredentials.mockRejectedValue(new Error('platform unavailable'));
+ await f.run();
+ expect(f.readProbeCredentials).toHaveBeenCalledOnce();
+ expect(f.access.filter(f.value).models).toHaveLength(1);
+});