@elvatis_com/openclaw-cli-bridge-elvatis 1.9.1 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli-runner.ts CHANGED
@@ -1,19 +1,25 @@
1
1
  /**
2
2
  * cli-runner.ts
3
3
  *
4
- * Spawns CLI subprocesses (gemini, claude) and captures their output.
5
- * Input: OpenAI-format messages → formatted prompt string → CLI stdin.
4
+ * Spawns CLI subprocesses (gemini, claude, codex, opencode, pi) and captures their output.
5
+ * Input: OpenAI-format messages → formatted prompt string → CLI stdin (or CLI arg).
6
6
  *
7
- * Both Gemini and Claude receive the prompt via stdin to avoid:
8
- * - E2BIG (arg list too long) for large conversation histories
9
- * - Gemini agentic mode (triggered by @file syntax + workspace cwd)
7
+ * Prompt delivery:
8
+ * - Gemini/Claude/Codex receive the prompt via stdin to avoid E2BIG and agentic mode.
9
+ * - OpenCode receives the prompt as a CLI argument (`opencode run "prompt"`).
10
+ * - Pi receives the prompt via `-p "prompt"` flag.
10
11
  *
11
- * Gemini is always spawned with cwd = tmpdir() so it doesn't scan the
12
- * workspace and enter agentic mode.
12
+ * Workdir isolation:
13
+ * - Gemini: defaults to tmpdir() (prevents agentic workspace scanning).
14
+ * - Claude/Codex: defaults to homedir().
15
+ * - OpenCode/Pi: defaults to homedir().
16
+ * - All runners accept an explicit `workdir` override via RouteOptions.
13
17
  */
14
18
 
15
- import { spawn } from "node:child_process";
19
+ import { spawn, execSync } from "node:child_process";
16
20
  import { tmpdir, homedir } from "node:os";
21
+ import { existsSync } from "node:fs";
22
+ import { join } from "node:path";
17
23
  import { ensureClaudeToken, refreshClaudeToken } from "./claude-auth.js";
18
24
 
19
25
  /** Max messages to include in the prompt sent to the CLI. */
@@ -198,6 +204,41 @@ export function runCli(
198
204
  });
199
205
  }
200
206
 
207
+ /**
208
+ * Spawn a CLI with the prompt delivered as a CLI argument (not stdin).
209
+ * Used by OpenCode which expects `opencode run "prompt"`.
210
+ */
211
+ export function runCliWithArg(
212
+ cmd: string,
213
+ args: string[],
214
+ timeoutMs = 120_000,
215
+ opts: RunCliOptions = {}
216
+ ): Promise<CliRunResult> {
217
+ const cwd = opts.cwd ?? homedir();
218
+
219
+ return new Promise((resolve, reject) => {
220
+ const proc = spawn(cmd, args, {
221
+ timeout: timeoutMs,
222
+ env: buildMinimalEnv(),
223
+ cwd,
224
+ });
225
+
226
+ let stdout = "";
227
+ let stderr = "";
228
+
229
+ proc.stdout.on("data", (d: Buffer) => { stdout += d.toString(); });
230
+ proc.stderr.on("data", (d: Buffer) => { stderr += d.toString(); });
231
+
232
+ proc.on("close", (code) => {
233
+ resolve({ stdout: stdout.trim(), stderr: stderr.trim(), exitCode: code ?? 0 });
234
+ });
235
+
236
+ proc.on("error", (err) => {
237
+ reject(new Error(`Failed to spawn '${cmd}': ${err.message}`));
238
+ });
239
+ });
240
+ }
241
+
201
242
  // ──────────────────────────────────────────────────────────────────────────────
202
243
  // Gemini CLI
203
244
  // ──────────────────────────────────────────────────────────────────────────────
@@ -215,17 +256,20 @@ export function runCli(
215
256
  * Gemini CLI: -p "" triggers headless mode; stdin content is the actual prompt
216
257
  * (per Gemini docs: "prompt is appended to input on stdin (if any)").
217
258
  *
218
- * cwd = tmpdir() — neutral empty-ish dir, prevents workspace context scanning.
259
+ * cwd = tmpdir() by default — neutral empty-ish dir, prevents workspace context scanning.
260
+ * Override with explicit workdir.
219
261
  */
220
262
  export async function runGemini(
221
263
  prompt: string,
222
264
  modelId: string,
223
- timeoutMs: number
265
+ timeoutMs: number,
266
+ workdir?: string
224
267
  ): Promise<string> {
225
268
  const model = stripPrefix(modelId);
226
269
  // -p "" = headless mode trigger; actual prompt arrives via stdin
227
270
  const args = ["-m", model, "-p", ""];
228
- const result = await runCli("gemini", args, prompt, timeoutMs, { cwd: tmpdir() });
271
+ const cwd = workdir ?? tmpdir();
272
+ const result = await runCli("gemini", args, prompt, timeoutMs, { cwd });
229
273
 
230
274
  // Filter out [WARN] lines from stderr (Gemini emits noisy permission warnings)
231
275
  const cleanStderr = result.stderr
@@ -248,11 +292,13 @@ export async function runGemini(
248
292
  /**
249
293
  * Run Claude Code CLI in headless mode with prompt delivered via stdin.
250
294
  * Strips the model prefix ("cli-claude/claude-opus-4-6" → "claude-opus-4-6").
295
+ * cwd = homedir() by default. Override with explicit workdir.
251
296
  */
252
297
  export async function runClaude(
253
298
  prompt: string,
254
299
  modelId: string,
255
- timeoutMs: number
300
+ timeoutMs: number,
301
+ workdir?: string
256
302
  ): Promise<string> {
257
303
  // Proactively refresh OAuth token if it's about to expire (< 5 min remaining).
258
304
  // No-op for API-key users.
@@ -267,7 +313,8 @@ export async function runClaude(
267
313
  "--model", model,
268
314
  ];
269
315
 
270
- const result = await runCli("claude", args, prompt, timeoutMs);
316
+ const cwd = workdir ?? homedir();
317
+ const result = await runCli("claude", args, prompt, timeoutMs, { cwd });
271
318
 
272
319
  // On 401: attempt one token refresh + retry before giving up.
273
320
  if (result.exitCode !== 0 && result.stdout.length === 0) {
@@ -275,7 +322,7 @@ export async function runClaude(
275
322
  if (stderr.includes("401") || stderr.includes("Invalid authentication credentials") || stderr.includes("authentication_error")) {
276
323
  // Refresh and retry once
277
324
  await refreshClaudeToken();
278
- const retry = await runCli("claude", args, prompt, timeoutMs);
325
+ const retry = await runCli("claude", args, prompt, timeoutMs, { cwd });
279
326
  if (retry.exitCode !== 0 && retry.stdout.length === 0) {
280
327
  const retryStderr = retry.stderr || "(no output)";
281
328
  if (retryStderr.includes("401") || retryStderr.includes("authentication_error") || retryStderr.includes("Invalid authentication credentials")) {
@@ -294,6 +341,97 @@ export async function runClaude(
294
341
  return result.stdout;
295
342
  }
296
343
 
344
+ // ──────────────────────────────────────────────────────────────────────────────
345
+ // Codex CLI
346
+ // ──────────────────────────────────────────────────────────────────────────────
347
+
348
+ /**
349
+ * Ensure the workdir is a git repository. Codex CLI requires a git repo.
350
+ * If the directory exists but is not a git repo, run `git init`.
351
+ */
352
+ function ensureGitRepo(dir: string): void {
353
+ if (!existsSync(join(dir, ".git"))) {
354
+ execSync("git init", { cwd: dir, stdio: "ignore" });
355
+ }
356
+ }
357
+
358
+ /**
359
+ * Run Codex CLI in non-interactive mode with prompt via stdin.
360
+ * cwd = homedir() by default. Override with explicit workdir.
361
+ * Auto-initializes git if workdir is not already a git repo.
362
+ */
363
+ export async function runCodex(
364
+ prompt: string,
365
+ modelId: string,
366
+ timeoutMs: number,
367
+ workdir?: string
368
+ ): Promise<string> {
369
+ const model = stripPrefix(modelId);
370
+ const args = ["--model", model, "--quiet", "--full-auto"];
371
+ const cwd = workdir ?? homedir();
372
+
373
+ // Codex requires a git repo in the working directory
374
+ ensureGitRepo(cwd);
375
+
376
+ const result = await runCli("codex", args, prompt, timeoutMs, { cwd });
377
+
378
+ if (result.exitCode !== 0 && result.stdout.length === 0) {
379
+ throw new Error(`codex exited ${result.exitCode}: ${result.stderr || "(no output)"}`);
380
+ }
381
+
382
+ return result.stdout || result.stderr;
383
+ }
384
+
385
+ // ──────────────────────────────────────────────────────────────────────────────
386
+ // OpenCode CLI
387
+ // ──────────────────────────────────────────────────────────────────────────────
388
+
389
+ /**
390
+ * Run OpenCode CLI. Prompt is passed as a CLI argument: `opencode run "prompt"`.
391
+ * cwd = homedir() by default. Override with explicit workdir.
392
+ */
393
+ export async function runOpenCode(
394
+ prompt: string,
395
+ _modelId: string,
396
+ timeoutMs: number,
397
+ workdir?: string
398
+ ): Promise<string> {
399
+ const args = ["run", prompt];
400
+ const cwd = workdir ?? homedir();
401
+ const result = await runCliWithArg("opencode", args, timeoutMs, { cwd });
402
+
403
+ if (result.exitCode !== 0 && result.stdout.length === 0) {
404
+ throw new Error(`opencode exited ${result.exitCode}: ${result.stderr || "(no output)"}`);
405
+ }
406
+
407
+ return result.stdout || result.stderr;
408
+ }
409
+
410
+ // ──────────────────────────────────────────────────────────────────────────────
411
+ // Pi CLI
412
+ // ──────────────────────────────────────────────────────────────────────────────
413
+
414
+ /**
415
+ * Run Pi CLI in non-interactive mode: `pi -p "prompt"`.
416
+ * cwd = homedir() by default. Override with explicit workdir.
417
+ */
418
+ export async function runPi(
419
+ prompt: string,
420
+ _modelId: string,
421
+ timeoutMs: number,
422
+ workdir?: string
423
+ ): Promise<string> {
424
+ const args = ["-p", prompt];
425
+ const cwd = workdir ?? homedir();
426
+ const result = await runCliWithArg("pi", args, timeoutMs, { cwd });
427
+
428
+ if (result.exitCode !== 0 && result.stdout.length === 0) {
429
+ throw new Error(`pi exited ${result.exitCode}: ${result.stderr || "(no output)"}`);
430
+ }
431
+
432
+ return result.stdout || result.stderr;
433
+ }
434
+
297
435
  // ──────────────────────────────────────────────────────────────────────────────
298
436
  // Model allowlist (T-103)
299
437
  // ──────────────────────────────────────────────────────────────────────────────
@@ -319,6 +457,16 @@ export const DEFAULT_ALLOWED_CLI_MODELS: ReadonlySet<string> = new Set([
319
457
  // Aliases (map to preview variants internally)
320
458
  "cli-gemini/gemini-3-pro", // alias → gemini-3-pro-preview
321
459
  "cli-gemini/gemini-3-flash", // alias → gemini-3-flash-preview
460
+ // Codex CLI
461
+ "openai-codex/gpt-5.3-codex",
462
+ "openai-codex/gpt-5.3-codex-spark",
463
+ "openai-codex/gpt-5.2-codex",
464
+ "openai-codex/gpt-5.4",
465
+ "openai-codex/gpt-5.1-codex-mini",
466
+ // OpenCode CLI
467
+ "opencode/default",
468
+ // Pi CLI
469
+ "pi/default",
322
470
  ]);
323
471
 
324
472
  /** Normalize model aliases to their canonical CLI model names. */
@@ -341,12 +489,20 @@ export interface RouteOptions {
341
489
  * Defaults to DEFAULT_ALLOWED_CLI_MODELS.
342
490
  */
343
491
  allowedModels?: ReadonlySet<string> | null;
492
+ /**
493
+ * Working directory for the CLI subprocess.
494
+ * Overrides the per-runner default (tmpdir for gemini, homedir for others).
495
+ */
496
+ workdir?: string;
344
497
  }
345
498
 
346
499
  /**
347
500
  * Route a chat completion to the correct CLI based on model prefix.
348
- * cli-gemini/<id> → gemini CLI
349
- * cli-claude/<id> → claude CLI
501
+ * cli-gemini/<id> → gemini CLI
502
+ * cli-claude/<id> → claude CLI
503
+ * openai-codex/<id> → codex CLI
504
+ * opencode/<id> → opencode CLI
505
+ * pi/<id> → pi CLI
350
506
  *
351
507
  * Enforces DEFAULT_ALLOWED_CLI_MODELS by default (T-103).
352
508
  * Pass `allowedModels: null` to skip the allowlist check.
@@ -379,11 +535,14 @@ export async function routeToCliRunner(
379
535
  // Resolve aliases (e.g. gemini-3-pro → gemini-3-pro-preview) after allowlist check
380
536
  const resolved = normalizeModelAlias(normalized);
381
537
 
382
- if (resolved.startsWith("cli-gemini/")) return runGemini(prompt, resolved, timeoutMs);
383
- if (resolved.startsWith("cli-claude/")) return runClaude(prompt, resolved, timeoutMs);
538
+ if (resolved.startsWith("cli-gemini/")) return runGemini(prompt, resolved, timeoutMs, opts.workdir);
539
+ if (resolved.startsWith("cli-claude/")) return runClaude(prompt, resolved, timeoutMs, opts.workdir);
540
+ if (resolved.startsWith("openai-codex/")) return runCodex(prompt, resolved, timeoutMs, opts.workdir);
541
+ if (resolved.startsWith("opencode/")) return runOpenCode(prompt, resolved, timeoutMs, opts.workdir);
542
+ if (resolved.startsWith("pi/")) return runPi(prompt, resolved, timeoutMs, opts.workdir);
384
543
 
385
544
  throw new Error(
386
- `Unknown CLI bridge model: "${model}". Use "vllm/cli-gemini/<model>" or "vllm/cli-claude/<model>".`
545
+ `Unknown CLI bridge model: "${model}". Use "vllm/cli-gemini/<model>", "vllm/cli-claude/<model>", "openai-codex/<model>", "opencode/<model>", or "pi/<model>".`
387
546
  );
388
547
  }
389
548
 
@@ -0,0 +1,127 @@
1
+ /**
2
+ * codex-auth-import.ts
3
+ *
4
+ * Auto-imports Codex CLI OAuth credentials from ~/.codex/auth.json into
5
+ * OpenClaw's agent auth store (~/.openclaw/agents/main/agent/auth-profiles.json).
6
+ *
7
+ * This solves Issue #2: the provider is registered but actual API calls fail
8
+ * because the auth store doesn't have the credentials. The user shouldn't need
9
+ * to run `openclaw models auth login` manually when Codex CLI is already logged in.
10
+ *
11
+ * Strategy:
12
+ * 1. Read credentials from ~/.codex/auth.json (via codex-auth.ts)
13
+ * 2. Read the existing auth-profiles.json
14
+ * 3. Upsert the "openai-codex:default" profile with fresh tokens
15
+ * 4. Write back atomically
16
+ *
17
+ * This runs on plugin startup and on OAuth refresh.
18
+ */
19
+
20
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
21
+ import { homedir } from "node:os";
22
+ import { join, dirname } from "node:path";
23
+ import { readCodexCredentials, DEFAULT_CODEX_AUTH_PATH } from "./codex-auth.js";
24
+
25
+ /** Default path to the OpenClaw agent auth store. */
26
+ const DEFAULT_AUTH_STORE_PATH = join(
27
+ homedir(),
28
+ ".openclaw",
29
+ "agents",
30
+ "main",
31
+ "agent",
32
+ "auth-profiles.json"
33
+ );
34
+
35
+ /** Auth profile entry format (matches OpenClaw's auth-profiles.json schema). */
36
+ interface AuthProfile {
37
+ type: "oauth" | "token";
38
+ provider: string;
39
+ access?: string;
40
+ refresh?: string;
41
+ expires?: number;
42
+ email?: string;
43
+ accountId?: string;
44
+ token?: string;
45
+ }
46
+
47
+ interface AuthStore {
48
+ version: number;
49
+ profiles: Record<string, AuthProfile>;
50
+ }
51
+
52
+ /**
53
+ * Import Codex CLI credentials into the OpenClaw agent auth store.
54
+ *
55
+ * Returns an object describing the result:
56
+ * - imported: true if credentials were written
57
+ * - skipped: true if credentials are already up-to-date
58
+ * - error: error message if import failed
59
+ */
60
+ export async function importCodexAuth(opts?: {
61
+ codexAuthPath?: string;
62
+ authStorePath?: string;
63
+ log?: (msg: string) => void;
64
+ }): Promise<{ imported: boolean; skipped: boolean; error?: string }> {
65
+ const codexAuthPath = opts?.codexAuthPath ?? DEFAULT_CODEX_AUTH_PATH;
66
+ const authStorePath = opts?.authStorePath ?? DEFAULT_AUTH_STORE_PATH;
67
+ const log = opts?.log ?? (() => {});
68
+
69
+ // Step 1: Read Codex CLI credentials
70
+ let creds;
71
+ try {
72
+ creds = await readCodexCredentials(codexAuthPath);
73
+ } catch (err) {
74
+ const msg = `Codex auth not available: ${(err as Error).message}`;
75
+ log(msg);
76
+ return { imported: false, skipped: false, error: msg };
77
+ }
78
+
79
+ // Step 2: Read existing auth store (or create skeleton)
80
+ let store: AuthStore;
81
+ try {
82
+ if (existsSync(authStorePath)) {
83
+ store = JSON.parse(readFileSync(authStorePath, "utf8")) as AuthStore;
84
+ } else {
85
+ store = { version: 1, profiles: {} };
86
+ }
87
+ } catch (err) {
88
+ const msg = `Cannot read auth store at ${authStorePath}: ${(err as Error).message}`;
89
+ log(msg);
90
+ return { imported: false, skipped: false, error: msg };
91
+ }
92
+
93
+ // Step 3: Check if update is needed
94
+ const profileKey = "openai-codex:default";
95
+ const existing = store.profiles[profileKey];
96
+
97
+ if (
98
+ existing &&
99
+ existing.access === creds.accessToken &&
100
+ existing.refresh === (creds.refreshToken ?? existing.refresh)
101
+ ) {
102
+ log(`Codex auth already up-to-date in ${profileKey}`);
103
+ return { imported: false, skipped: true };
104
+ }
105
+
106
+ // Step 4: Upsert the profile
107
+ store.profiles[profileKey] = {
108
+ type: "oauth",
109
+ provider: "openai-codex",
110
+ access: creds.accessToken,
111
+ ...(creds.refreshToken ? { refresh: creds.refreshToken } : {}),
112
+ ...(creds.expiresAt ? { expires: creds.expiresAt } : {}),
113
+ ...(creds.email ? { email: creds.email } : {}),
114
+ };
115
+
116
+ // Step 5: Write back atomically
117
+ try {
118
+ mkdirSync(dirname(authStorePath), { recursive: true });
119
+ writeFileSync(authStorePath, JSON.stringify(store, null, 4) + "\n", "utf8");
120
+ log(`Codex auth imported into ${profileKey}`);
121
+ return { imported: true, skipped: false };
122
+ } catch (err) {
123
+ const msg = `Failed to write auth store: ${(err as Error).message}`;
124
+ log(msg);
125
+ return { imported: false, skipped: false, error: msg };
126
+ }
127
+ }
@@ -51,7 +51,7 @@ const STABLE_INTERVAL_MS = 500; // ms between stability checks
51
51
 
52
52
  function resolveModel(m?: string): string {
53
53
  const clean = (m ?? "grok-3").replace("web-grok/", "");
54
- const allowed = ["grok-3", "grok-3-fast", "grok-3-mini", "grok-3-mini-fast"];
54
+ const allowed = ["grok-4", "grok-3", "grok-3-fast", "grok-3-mini", "grok-3-mini-fast"];
55
55
  return allowed.includes(clean) ? clean : "grok-3";
56
56
  }
57
57