Skip to content
Closed
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
126 changes: 126 additions & 0 deletions packages/core/src/account/customEngineAuth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
// 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;
}

// Starting points so connecting is a pick + key paste instead of a URL hunt. Only "manual"
// (a loopback endpoint) and "lmstudio" have carried a real turn; the hosted entries are the
// advertised base URLs and must speak the Responses wire to work through codex. "manual" is the escape hatch: any endpoint, all fields typed by hand.
// A defaultModel of "" does NOT mean the endpoint picks one: saveCustomEngineConfig
// rejects a blank model, so the connect form must require a model id for those presets.
export const CUSTOM_ENGINE_PRESETS: CustomEnginePreset[] = [
{ id: "deepseek", label: "DeepSeek", baseUrl: "https://api.deepseek.com/v1", defaultModel: "deepseek-chat" },
{ id: "qwen", label: "Qwen", baseUrl: "https://dashscope.aliyuncs.com/compatible-mode/v1", defaultModel: "qwen-max" },
{ id: "glm", label: "GLM", baseUrl: "https://open.bigmodel.cn/api/paas/v4", defaultModel: "glm-4-plus" },
{ id: "kimi", label: "Kimi", baseUrl: "https://api.moonshot.cn/v1", defaultModel: "kimi-k2" },
{ id: "ollama", label: "Ollama", baseUrl: "http://localhost:11434/v1", defaultModel: "" },
{ id: "lmstudio", label: "LM Studio", baseUrl: "http://localhost:1234/v1", defaultModel: "" },
{ 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> {
if ((report ?? await detectCli())[engineBinary("custom")] === "missing") return "missing";
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
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
40 changes: 26 additions & 14 deletions packages/core/src/chat/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ import type { ApprovalChannel } from "../runtime/approval/channel.js";
import type { SkillCard, MarketRequest } from "./marketMessages.js";
import { access, writeFile } from "node:fs/promises";
import { join } from "node:path";
import type { ChatModelOption } from "./modelOptions.js";
import { customModelOption, type ChatModelOption } from "./modelOptions.js";
import { loadCustomEngineConfig, customEngineStatus } from "../account/customEngineAuth.js";
import { ENGINE_KEYS, ENGINE_REGISTRY, type EngineKey } from "../runtime/engineRegistry.js";

// Format a token count with thousands separators (e.g. 167000 → "167,000") for the
// /context breakdown notice.
Expand Down Expand Up @@ -126,7 +128,7 @@ export interface ChatEnv {
rpcStatus?(): Promise<import("./marketMessages.js").RpcStatus>;
// Optional model catalog override from the host. VSCode uses this for Codex so the
// picker can show the actual models exposed by the logged-in app-server account.
modelOptions?(cli: "claude" | "codex"): Promise<ChatModelOption[] | null>;
modelOptions?(cli: EngineKey): Promise<ChatModelOption[] | null>;
// OPTIONAL multi-tab guard: vscode can open the same session in two panels (two
// tabs writing one log races), so it claims a session before opening and yields
// false to abort if another panel already holds it. One-socket surfaces (server,
Expand Down Expand Up @@ -184,11 +186,11 @@ async function exists(path: string): Promise<boolean> {
}
}

async function initInstructionsFile(cli: "claude" | "codex", cwd: string): Promise<{ file: string; created: boolean }> {
const file = cli === "codex" ? "AGENTS.md" : "CLAUDE.md";
async function initInstructionsFile(cli: EngineKey, cwd: string): Promise<{ file: string; created: boolean }> {
const file = ENGINE_REGISTRY[cli].memoryFile;
const path = join(cwd, file);
if (await exists(path)) return { file, created: false };
const tool = cli === "codex" ? "Codex" : "Claude Code";
const tool = cli === "claude" ? "Claude Code" : "Codex";
await writeFile(path, [
`# ${file}`,
"",
Expand Down Expand Up @@ -241,11 +243,12 @@ export function createChatSession(
lastUsage?: number;
lastWindow?: number;
};
const slots: Record<"claude" | "codex", Slot> = {
const slots: Record<EngineKey, Slot> = {
claude: { handle: null, parked: new Set(), mode: "acceptEdits", restage: null },
codex: { handle: null, parked: new Set(), mode: "auto", restage: null },
custom: { handle: null, parked: new Set(), mode: "auto", restage: null },
};
let cli: "claude" | "codex" = "claude"; // which tab is showing
let cli: EngineKey = "claude"; // which tab is showing
const slot = () => slots[cli];

// Handles with a turn in flight (set in ensureHandle when a turn starts, cleared in
Expand All @@ -260,7 +263,7 @@ export function createChatSession(
// onTurnEnd awaits it to write the matching `ended` mark, and only that turn's.
const turnMarks = new Map<SessionHandle, Promise<string | null>>();

function isVisibleHandle(forCli: "claude" | "codex", h: SessionHandle): boolean {
function isVisibleHandle(forCli: EngineKey, h: SessionHandle): boolean {
return cli === forCli && slots[forCli].handle === h;
}

Expand Down Expand Up @@ -297,7 +300,7 @@ export function createChatSession(
// background reply doesn't bleed into the other tab's log). The message already
// carries its own .cli (stamped by the runtime), so the UI badges the real engine
// per-message — correct even for a cross-CLI session.
function wire(forCli: "claude" | "codex", h: SessionHandle) {
function wire(forCli: EngineKey, h: SessionHandle) {
h.onMessage((msg) => { if (isVisibleHandle(forCli, h)) transport.send({ type: "message", msg }); });
// nft skill firing cue; local plaintext skills are filtered in runtime/index.
h.onSkill((skill) => {
Expand Down Expand Up @@ -502,7 +505,7 @@ export function createChatSession(
transport.send({ type: "skillShopping", on });
}

async function pushModelOptions(forCli: "claude" | "codex") {
async function pushModelOptions(forCli: EngineKey) {
if (!env.modelOptions) return;
const options = await env.modelOptions(forCli).catch(() => null);
// Empty/failed probe → leave the webview on its static baseline (listClaudeModelOptions
Expand Down Expand Up @@ -552,6 +555,15 @@ export function createChatSession(
// only pushed codex, so a fresh claude session never received its dynamic list and
// kept showing the static baseline. Switching engines pushes the other side.
void pushModelOptions(cli);
// The custom tab ships hidden; a modelOptions push for "custom" is the signal
// that the custom engine is USABLE, so it is gated on customEngineStatus (config
// saved AND codex binary present). A config without the binary would reveal a
// tab that can only die with a raw spawn error.
void (async () => {
if ((await customEngineStatus()) !== "ok") return;
const cfg = await loadCustomEngineConfig();
if (cfg) transport.send({ type: "modelOptions", cli: "custom", options: customModelOption(cfg.model, cfg.label || ENGINE_REGISTRY.custom.label) });
})().catch(() => {});
// install the wallet's owned skills so they're present + discoverable this
// session (issue #17). Fire-and-forget: a chain hiccup must not delay the chat;
// refresh the panel once it lands.
Expand Down Expand Up @@ -583,7 +595,7 @@ export function createChatSession(
// you on an empty screen. We show a loading flash, hand the session to the new
// slot, and repaint — the next send resumes it (history re-injected into the
// new cli). If nothing was open, just switch to a blank chat as before.
if ((m.cli === "claude" || m.cli === "codex") && m.cli !== cli) {
if (ENGINE_KEYS.includes(m.cli) && m.cli !== cli) {
const carry = slot().pendingId; // the session the OLD engine was showing
cli = m.cli;
void pushModelOptions(cli);
Expand Down Expand Up @@ -703,7 +715,7 @@ export function createChatSession(
// have per-category token data from the engines, so we report the totals we do have.
if (command === "context") {
const s = slot();
const window = s.lastWindow ?? (cli === "codex" ? 256_000 : 200_000);
const window = s.lastWindow ?? (cli === "claude" ? 200_000 : 256_000);
if (s.lastUsage === undefined) {
transport.send({ type: "notice", text: `Context: 0 / ${fmtTok(window)} tokens. Send a message to measure usage.` });
break;
Expand Down Expand Up @@ -753,7 +765,7 @@ export function createChatSession(
if (typeof m.sessionId === "string") {
await rt.deleteSession(m.sessionId);
// if the deleted one is open in either slot, clear that slot
for (const k of ["claude", "codex"] as const) {
for (const k of ENGINE_KEYS) {
const s = slots[k];
if (m.sessionId === (s.handle?.sessionId ?? s.pendingId)) {
if (s.handle) stopHandle(s, s.handle);
Expand Down Expand Up @@ -1040,7 +1052,7 @@ export function createChatSession(

return {
stop() {
for (const s of [slots.claude, slots.codex]) {
for (const s of Object.values(slots)) {
if (s.handle) stopHandle(s, s.handle);
for (const h of [...s.parked]) stopHandle(s, h);
}
Expand Down
12 changes: 9 additions & 3 deletions packages/core/src/chat/slashCommands.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
export type SlashEngine = "claude" | "codex";
import type { EngineKey } from "../runtime/engineRegistry.js";

export type SlashEngine = EngineKey;

export interface SlashCommandSpec {
name: string;
Expand All @@ -9,10 +11,14 @@ export interface SlashCommandSpec {

const both = ["claude", "codex"] as SlashEngine[];

// The custom engine runs through the codex binary, so it speaks every codex command.
const withCustom = (c: SlashCommandSpec): SlashCommandSpec =>
c.engines.includes("codex") ? { ...c, engines: [...c.engines, "custom"] } : c;

// Curated from the public Claude Code commands reference and Codex CLI/IDE slash
// command references. AgentNet-local commands are included where this surface owns
// the behavior instead of the native CLI.
export const CHAT_SLASH_COMMANDS: SlashCommandSpec[] = [
export const CHAT_SLASH_COMMANDS: SlashCommandSpec[] = ([
{ name: "login", desc: "sign in to the active engine", engines: both, args: "[code]" },
{ name: "logout", desc: "sign out of the active engine", engines: both },
{ name: "new", desc: "start a fresh chat", engines: both },
Expand Down Expand Up @@ -139,4 +145,4 @@ export const CHAT_SLASH_COMMANDS: SlashCommandSpec[] = [
{ name: "quit", desc: "exit the native CLI session", engines: ["codex"] },
{ name: "debug-config", desc: "inspect Codex config layers", engines: ["codex"] },
{ name: "title", desc: "configure terminal title fields", engines: ["codex"] },
];
] as SlashCommandSpec[]).map(withCustom);
2 changes: 1 addition & 1 deletion packages/core/src/chat/ui/panel.generated.ts

Large diffs are not rendered by default.

Loading
Loading