Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 118 additions & 0 deletions packages/core/src/account/customEngineAuth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
// Custom engine config, device-local. Mirrors saveCodexApiKey: the endpoint config
// (base URL + API key + model) lives in tokens/custom-engine.json with 0o600 perms,
// per device, never synced. spawn.ts turns it into -c model_providers overrides on
// the codex binary; the key rides the CUSTOM_ENGINE_API_KEY env var, never argv.

import { readFile, writeFile, rm } from "node:fs/promises";
import { tokenFile, tokensDir, ensureDir } from "../core/paths.js";
import { engineBinary } from "../runtime/engineRegistry.js";
import { detectCli, type CliReport, type CliStatus } from "../runtime/detect.js";

export interface CustomEngineConfig {
baseUrl: string;
apiKey: string;
model: string;
presetId: string;
label?: string;
}

export interface CustomEnginePreset {
id: string;
label: string;
baseUrl: string;
defaultModel: string;
}

// OpenRouter has been exercised through the Responses API. Other compatible local
// or hosted endpoints can be configured manually without implying provider support.
export const CUSTOM_ENGINE_PRESETS: CustomEnginePreset[] = [
{ id: "openrouter", label: "OpenRouter", baseUrl: "https://openrouter.ai/api/v1", defaultModel: "" },
{ id: "manual", label: "Manual", baseUrl: "", defaultModel: "" },
];

// Connect-UI warning copy lives in the browser-safe leaf (customEngineMeta) so the
// SPA form can import it without this file's node:fs dependency; re-exported here so
// node hosts keep one import site for everything custom-engine.
export { CUSTOM_ENGINE_EGRESS_WARNING, CUSTOM_ENGINE_TOOL_WARNING } from "./customEngineMeta.js";

const PROVIDER = "custom-engine";

// The base URL rides codex argv as a -c override, where ps can read it, so anything
// secret-shaped is stripped before it is stored: userinfo (user:pass@) and the query
// string. The trailing slash is trimmed so the same endpoint always stores one form.
function normalizeBaseUrl(raw: string): string {
let url: URL;
try {
url = new URL(raw.trim());
} catch {
throw new Error("The custom engine base URL is not a valid URL.");
}
if (url.protocol !== "http:" && url.protocol !== "https:") {
throw new Error(`The custom engine base URL must be http or https, got "${url.protocol.slice(0, -1)}".`);
}
// origin + pathname drops userinfo, query, and fragment in one move.
return (url.origin + url.pathname).replace(/\/+$/, "");
}

export async function saveCustomEngineConfig(cfg: CustomEngineConfig): Promise<void> {
// Reject a blank model at the door, not only at spawn (customProviderFlags), so a
// bad config never even reaches disk.
if (!cfg.model.trim()) {
throw new Error("The custom engine needs a model id; codex would otherwise silently use its own default model.");
}
const normalized: CustomEngineConfig = { ...cfg, baseUrl: normalizeBaseUrl(cfg.baseUrl), model: cfg.model.trim() };
await ensureDir(tokensDir());
const path = tokenFile(PROVIDER);
// Unlink before write so the new file is always created with 0o600: if the file
// already existed with looser permissions a plain writeFile would not downgrade them.
await rm(path, { force: true });
await writeFile(path, JSON.stringify(normalized), { mode: 0o600 });
}

export async function loadCustomEngineConfig(): Promise<CustomEngineConfig | null> {
try {
const data = JSON.parse(await readFile(tokenFile(PROVIDER), "utf8")) as CustomEngineConfig;
return data.baseUrl ? data : null;
} catch {
return null;
}
}

export async function clearCustomEngineConfig(): Promise<void> {
await rm(tokenFile(PROVIDER), { force: true });
}

export async function hasCustomEngine(): Promise<boolean> {
return (await loadCustomEngineConfig()) !== null;
}

// The custom engine's status in CliReport's own vocabulary, so a custom row reads like the
// claude and codex rows everywhere: "missing" = no codex binary (custom runs through it),
// "no-login" = the binary is there but no endpoint is saved (the saved config IS its
// sign-in), "ok" = a custom session can actually spawn. One derivation for every host
// and surface instead of each re-deriving "codex present AND config saved". Pass a
// CliReport when one is already in hand; without one detectCli runs, the same probe
// behind every engine status line (it resolves the binary through engineBin.ts, so a
// GUI-launched host without a shell PATH still finds it).
export async function customEngineStatus(report?: CliReport): Promise<CliStatus> {
const status = (report ?? await detectCli())[engineBinary("custom")];
if (status === "missing" || status === "node-missing") return status;
return (await hasCustomEngine()) ? "ok" : "no-login";
}

// Masked view for the UI: endpoint host + last 4 chars of the key, rest dotted (like
// maskedHeliusKey). null when no config is stored; a keyless local endpoint shows
// just the host. The full key never leaves the host as plain text.
export async function maskedCustomEngine(): Promise<string | null> {
const cfg = await loadCustomEngineConfig();
if (!cfg) return null;
let host = cfg.baseUrl;
try {
host = new URL(cfg.baseUrl).host;
} catch {
// not a parseable URL: show the raw value
}
if (!cfg.apiKey) return host;
const tail = cfg.apiKey.slice(-4);
return `${host} · ${cfg.apiKey.length <= 4 ? tail : "••••" + tail}`;
}
10 changes: 10 additions & 0 deletions packages/core/src/account/customEngineMeta.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Custom engine warning copy, split from customEngineAuth because that file needs
// node:fs while the SPA connect form must render these strings verbatim from a
// browser bundle. This leaf stays node-free (like engineRegistry) so every surface
// reads the one definition instead of hardcoding drifting copies.

// Shown verbatim by any connect UI before a custom endpoint is saved.
export const CUSTOM_ENGINE_EGRESS_WARNING =
"Custom engines send your prompts, files, and tool output to the endpoint you configure. Only connect endpoints you trust with that data.";
export const CUSTOM_ENGINE_TOOL_WARNING =
"The endpoint and selected model must support the OpenAI Responses API and tool calling. Chat Completions-only endpoints need a compatible adapter.";
5 changes: 3 additions & 2 deletions packages/core/src/account/sessionLog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
// This file is the single source of the storage format — change it here only.

import type { ChatMessage, CanonicalSession } from "../runtime/contract.js";
import { coerceEngineKey, type EngineKey } from "../runtime/engineRegistry.js";
import { encryptForWallet, decryptForWallet, type SessionKey } from "../core/crypto.js";

// A log record: either session meta (first line) or one chat message.
Expand Down Expand Up @@ -45,7 +46,7 @@ export async function decodeLog(
if (!text) return null;

let sessionId = "";
let cli: "claude" | "codex" = "claude";
let cli: EngineKey = "claude";
let title = "";
let ts = 0;
let lastDevice: { id: string; label: string } | undefined = undefined;
Expand All @@ -59,7 +60,7 @@ export async function decodeLog(
const rec = JSON.parse(new TextDecoder().decode(plain)) as LogRecord;
if (rec.kind === "meta") {
sessionId = rec.sessionId;
cli = rec.cli as "claude" | "codex";
cli = coerceEngineKey(rec.cli); // unknown cli strings read as codex-like
title = rec.title;
ts = rec.ts;
lastDevice = rec.lastDevice;
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/account/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const PERF = !!process.env.AGENTNET_PERF;
function toSessionMeta(
sessionId: string,
title: string,
cli: "claude" | "codex",
cli: SessionMeta["cli"],
ts: number,
lastDevice?: SessionMeta["lastDevice"],
model?: string,
Expand Down
11 changes: 11 additions & 0 deletions packages/core/src/chat/contextNotice.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { expect, it } from "vitest";
import { contextNotice } from "./contextNotice.js";

it("retains the standard engine breakdown and supplied window", () => {
expect(contextNotice("claude", 10000, 100000)).toContain("10,000 / 100,000 (10%)");
expect(contextNotice("codex")).toContain("256,000");
});
it("Custom never presents a Codex fallback as provider capacity", () => {
expect(contextNotice("custom", 12000, 256000)).toBe("Context (custom): 12,000 tokens used. Provider context limit unknown.");
expect(contextNotice("custom")).toContain("usage not reported yet");
});
23 changes: 23 additions & 0 deletions packages/core/src/chat/contextNotice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import type { EngineKey } from "../runtime/engineRegistry.js";

// Shared by the terminal and host-dispatched /context command.
export function contextNotice(cli: EngineKey, used?: number, reportedWindow?: number): string {
const fmt = (n: number) => Math.round(n).toLocaleString("en-US");
// Custom runs through Codex, whose reported window may be its own fallback.
// It is not evidence of the configured provider's capacity or compaction policy.
if (cli === "custom") {
return used === undefined
? "Context: usage not reported yet. Provider context limit unknown."
: `Context (custom): ${fmt(used)} tokens used. Provider context limit unknown.`;
}
const window = reportedWindow ?? (cli === "claude" ? 200_000 : 256_000);
if (used === undefined) return `Context: 0 / ${fmt(window)} tokens. Send a message to measure usage.`;
const free = Math.max(0, window - used);
const pct = Math.round((used / window) * 100);
const threshold = Math.max(0, window - 33_000);
const tpct = Math.round((threshold / window) * 100);
return `Context window (${cli})\n`
+ ` used ${fmt(used)} / ${fmt(window)} (${pct}%)\n`
+ ` free ${fmt(free)}\n`
+ ` auto-compact at ~${fmt(threshold)} (${tpct}%)`;
}
21 changes: 20 additions & 1 deletion packages/core/src/chat/modelOptions.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
export type EngineKey = "claude" | "codex";
import type { EngineKey } from "../runtime/engineRegistry.js";

export type { EngineKey } from "../runtime/engineRegistry.js";

export type ChatModelOption = {
value?: string;
Expand Down Expand Up @@ -48,8 +50,25 @@ export const CHAT_MODEL_OPTIONS: Record<EngineKey, ChatModelOption[]> = {
description: "General GPT model · exact value: gpt-5.5",
},
],
// The custom engine has no catalog: its one model is whatever the saved endpoint
// config names, which lives on the host side. Surfaces build the entry with
// customModelOption from the stored config and push it over their live channel.
custom: [],
};

// Picker entry for the configured custom-endpoint model. Empty only for a legacy
// config saved before saveCustomEngineConfig required a model id; spawn rejects
// those configs, so an empty list here matches an engine that cannot run.
export function customModelOption(model: string, label?: string): ChatModelOption[] {
if (!model) return [];
return [{
value: model,
chipLabel: model,
label: model,
description: (label ? label + " · " : "") + "configured endpoint model",
}];
}

export function findChatModelOption(cli: EngineKey, model?: string): ChatModelOption | undefined {
const opts = CHAT_MODEL_OPTIONS[cli];
return opts.find((opt) => (opt.value ?? "default") === (model ?? "default"));
Expand Down
20 changes: 19 additions & 1 deletion packages/core/src/chat/session.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { mkdtemp, readFile, rm } from "node:fs/promises";
import { join } from "node:path";
import { tmpdir } from "node:os";

function fakeHandle(id: string, cli: "claude" | "codex") {
function fakeHandle(id: string, cli: "claude" | "codex" | "custom") {
const usageCbs: Array<(n: number, window?: number) => void> = [];
const compactCbs: Array<() => void> = [];
const msgCbs: Array<(msg: any) => void> = [];
Expand Down Expand Up @@ -674,3 +674,21 @@ describe("chat/session — feed anchor re-prime after a bumping blog comment (is
expect(getBlogFeed).toHaveBeenCalledWith(undefined, "latest", true);
});
});

describe("Custom context reporting", () => {
it("never derives provider capacity or compaction from a Codex window", async () => {
const { handles, fromUI, transport, chat } = harness();
try {
fromUI({ type: "platform", cli: "custom" });
fromUI({ type: "slashCommand", command: "context" });
await flush();
expect(transport.send).toHaveBeenCalledWith({ type: "notice", text: "Context: usage not reported yet. Provider context limit unknown." });
fromUI({ type: "send", text: "fixture" });
await flush();
handles[0].emitUsage(12000, 256000);
fromUI({ type: "slashCommand", command: "context" });
await flush();
expect(transport.send).toHaveBeenCalledWith({ type: "notice", text: "Context (custom): 12,000 tokens used. Provider context limit unknown." });
} finally { chat.stop(); }
});
});
Loading
Loading