agentpier-runner 0.1.0 → 0.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.
@@ -1,5 +1,5 @@
1
1
  import { spawn } from 'node:child_process';
2
- import { mkdtemp, rm } from 'node:fs/promises';
2
+ import { mkdtemp, readFile, rm } from 'node:fs/promises';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  export const CLI_BIN = { claude: 'claude', chatgpt: 'codex', antigravity: 'gemini' };
@@ -9,14 +9,16 @@ export function cliCommand(provider, model, system, prompt) {
9
9
  case 'claude':
10
10
  return {
11
11
  bin: CLI_BIN.claude,
12
- args: ['-p', '--output-format', 'json', '--model', model, '--system-prompt', system, '--tools', '', '--no-session-persistence', '--strict-mcp-config'],
12
+ // An empty model runs on the plan's default.
13
+ args: ['-p', '--output-format', 'json', ...(model ? ['--model', model] : []), '--system-prompt', system, '--tools', '', '--no-session-persistence', '--strict-mcp-config'],
13
14
  stdin: prompt,
14
15
  };
15
16
  case 'chatgpt':
16
- // Codex has no system-prompt flag, so the room's instructions lead the prompt.
17
+ // Codex has no system-prompt flag, so the room's instructions lead the prompt. An empty model
18
+ // runs on Codex's own configured default.
17
19
  return {
18
20
  bin: CLI_BIN.chatgpt,
19
- args: ['exec', '--model', model, '--sandbox', 'read-only', '--ephemeral', '--skip-git-repo-check', '--color', 'never', '-'],
21
+ args: ['exec', ...(model ? ['--model', model] : []), '--sandbox', 'read-only', '--ephemeral', '--skip-git-repo-check', '--color', 'never', '-'],
20
22
  stdin: `${system}\n\n${prompt}`,
21
23
  };
22
24
  case 'antigravity':
@@ -43,7 +45,7 @@ export function parseCliOutput(provider, stdout) {
43
45
  const data = JSON.parse(stdout);
44
46
  if (data && typeof data === 'object' && 'result' in data && typeof data.result === 'string') {
45
47
  if ('is_error' in data && data.is_error === true)
46
- return { ok: false, reason: 'Claude Code could not answer. Check that `claude` is signed in.' };
48
+ return { ok: false, reason: `Claude Code: ${cliError(data.result) || 'could not answer. Check that `claude` is signed in.'}` };
47
49
  const text = data.result.trim();
48
50
  return text ? { ok: true, text } : { ok: false, reason: 'Claude Code sent an empty reply.' };
49
51
  }
@@ -54,25 +56,41 @@ export function parseCliOutput(provider, stdout) {
54
56
  const text = stdout.trim();
55
57
  return text ? { ok: true, text } : { ok: false, reason: `${provider === 'chatgpt' ? 'Codex' : 'Gemini CLI'} sent an empty reply.` };
56
58
  }
59
+ /** Long runs of letters and digits, as keys and tokens look; replaced before any CLI text is shown. */
60
+ const KEY_LIKE = /\b(?:sk-[\w-]{8,}|[A-Za-z0-9_-]{32,})\b/g;
61
+ /**
62
+ * What a CLI said went wrong, short enough to show in the room: the last line that looks like an
63
+ * error (or the last line), with key-like strings removed and JSON error messages unwrapped.
64
+ */
65
+ export function cliError(text) {
66
+ const lines = text.split('\n').map((l) => l.trim()).filter(Boolean);
67
+ const line = [...lines].reverse().find((l) => /error|refus|limit|not supported|denied|login|sign in|expired|quota/i.test(l)) ?? lines.at(-1) ?? '';
68
+ const message = line.match(/"message"\s*:\s*"((?:[^"\\]|\\.)*)"/)?.[1] ?? line.replace(/^ERROR:\s*/, '');
69
+ return message.replace(KEY_LIKE, '…').slice(0, 240);
70
+ }
57
71
  /** Runs one CLI in an empty temporary folder with the prompt on stdin, and stops it after `timeoutMs`. */
58
72
  export const runCli = async (cmd, { timeoutMs }) => {
59
73
  const cwd = await mkdtemp(path.join(os.tmpdir(), 'agentpier-turn-'));
60
74
  try {
61
75
  return await new Promise((resolve) => {
62
76
  let stdout = '';
77
+ let stderr = '';
63
78
  let settled = false;
64
79
  const done = (r) => { if (!settled) {
65
80
  settled = true;
66
81
  clearTimeout(timer);
67
82
  resolve(r);
68
83
  } };
69
- const child = spawn(cmd.bin, cmd.args, { cwd, env: cliEnv(process.env), stdio: ['pipe', 'pipe', 'ignore'] });
84
+ const child = spawn(cmd.bin, cmd.args, { cwd, env: cliEnv(process.env), stdio: ['pipe', 'pipe', 'pipe'] });
70
85
  const timer = setTimeout(() => { child.kill('SIGKILL'); done({ ok: false, code: 'timeout' }); }, timeoutMs);
71
86
  child.stdout.setEncoding('utf8');
72
87
  child.stdout.on('data', (d) => { if (stdout.length < 1_000_000)
73
88
  stdout += d; });
89
+ child.stderr.setEncoding('utf8');
90
+ // Only the end matters: that is where CLIs print the error they stopped on.
91
+ child.stderr.on('data', (d) => { stderr = (stderr + d).slice(-8000); });
74
92
  child.on('error', (err) => done({ ok: false, code: err.code === 'ENOENT' ? 'missing' : 'failed' }));
75
- child.on('close', (code) => done(code === 0 ? { ok: true, stdout } : { ok: false, code: 'failed' }));
93
+ child.on('close', (code) => done(code === 0 ? { ok: true, stdout } : { ok: false, code: 'failed', detail: cliError(stderr || stdout), stdout }));
76
94
  child.stdin.on('error', () => { });
77
95
  child.stdin.end(cmd.stdin);
78
96
  });
@@ -87,3 +105,22 @@ export async function detectClis(run = runCli) {
87
105
  const [claude, chatgpt, antigravity] = await Promise.all([check('claude'), check('chatgpt'), check('antigravity')]);
88
106
  return { claude, chatgpt, antigravity };
89
107
  }
108
+ /**
109
+ * The models Codex may use with the account it is signed in with, from the list Codex itself
110
+ * keeps in ~/.codex/models_cache.json (shown models only, in Codex's order). A ChatGPT plan allows
111
+ * fewer models than the API, so a room's choice can be refused; this is what to fall back to.
112
+ */
113
+ export async function codexPlanModels(home = path.join(os.homedir(), '.codex')) {
114
+ try {
115
+ const data = JSON.parse(await readFile(path.join(home, 'models_cache.json'), 'utf8'));
116
+ const models = data && typeof data === 'object' && 'models' in data && Array.isArray(data.models) ? data.models : [];
117
+ return models
118
+ .filter((m) => !!m && typeof m === 'object' && 'slug' in m && typeof m.slug === 'string')
119
+ .filter((m) => m.visibility !== 'hide')
120
+ .sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0))
121
+ .map((m) => m.slug);
122
+ }
123
+ catch {
124
+ return [];
125
+ }
126
+ }
@@ -1,5 +1,5 @@
1
1
  import { clean, conversation, MODELS, parseTurnRequest, systemPrompt } from "../../../supabase/functions/room-turn/turn.js";
2
- import { cliCommand, parseCliOutput } from "./cli.js";
2
+ import { cliCommand, codexPlanModels, parseCliOutput } from "./cli.js";
3
3
  /** How long one turn may take on a CLI before Runner stops it. */
4
4
  export const TURN_TIMEOUT_MS = 180_000;
5
5
  /**
@@ -23,16 +23,32 @@ export async function roomTurnOnCli(body, deps) {
23
23
  const prompt = conversation(turn)
24
24
  .map((m) => (m.role === 'assistant' ? `[Your earlier message]\n${m.text}` : m.text))
25
25
  .join('\n\n');
26
- const result = await deps.run(cliCommand(me.ai, model, systemPrompt(turn), prompt), { timeoutMs: TURN_TIMEOUT_MS });
26
+ const system = systemPrompt(turn);
27
+ const ask = async (withModel) => {
28
+ const result = await deps.run(cliCommand(me.ai, withModel, system, prompt), { timeoutMs: TURN_TIMEOUT_MS });
29
+ // Claude Code can exit non-zero and still print its error as JSON on stdout.
30
+ const out = result.ok ? parseCliOutput(me.ai, result.stdout) : result.stdout?.trim().startsWith('{') ? parseCliOutput(me.ai, result.stdout) : null;
31
+ return { result, out };
32
+ };
33
+ let { result, out } = await ask(model);
34
+ // A plan without access to the chosen model: try once more on a model the plan does allow.
35
+ // Claude Code picks its plan's default; Codex gets the first model its own cache lists for this
36
+ // account (or its configured default when there is no cache).
37
+ const refusedModel = (text) => /model/i.test(text) && /(not exist|access|not supported|not available|invalid|unknown)/i.test(text);
38
+ if ((me.ai === 'claude' || me.ai === 'chatgpt') && ((out && !out.ok && refusedModel(out.reason)) || (!result.ok && refusedModel(result.detail ?? '')))) {
39
+ const allowed = me.ai === 'chatgpt' ? await (deps.codexModels ?? (() => codexPlanModels()))() : [];
40
+ ({ result, out } = await ask(allowed.find((m) => m !== model) ?? ''));
41
+ }
42
+ if (out && !out.ok)
43
+ return { ok: false, code: 'failed', reason: out.reason };
27
44
  if (!result.ok) {
28
45
  if (result.code === 'missing')
29
46
  return { ok: false, code: 'not_installed', reason: `${tool} isn't installed on this computer.` };
30
47
  if (result.code === 'timeout')
31
48
  return { ok: false, code: 'timeout', reason: `${tool} took too long to answer.` };
32
- return { ok: false, code: 'failed', reason: `${tool} could not answer. Check that it is signed in.` };
49
+ return { ok: false, code: 'failed', reason: result.detail ? `${tool}: ${result.detail}` : `${tool} could not answer. Check that it is signed in.` };
33
50
  }
34
- const out = parseCliOutput(me.ai, result.stdout);
35
- if (!out.ok)
36
- return { ok: false, code: 'failed', reason: out.reason };
51
+ if (!out)
52
+ return { ok: false, code: 'failed', reason: `${tool} sent a reply Runner could not read.` };
37
53
  return { ok: true, text: clean(out.text, me.name) };
38
54
  }
@@ -6,7 +6,7 @@ import { agentBySlug, agents } from "./agents.js";
6
6
  import { MODEL, parseEffort, runTask } from "./run.js";
7
7
  import { detectClis, runCli } from "./cli.js";
8
8
  import { roomTurnOnCli } from "./room.js";
9
- export const VERSION = '0.1.0';
9
+ export const VERSION = '0.1.1';
10
10
  const MAX_BODY = 20_000;
11
11
  /** A room turn carries up to 40 thread lines of 4,000 characters. */
12
12
  const MAX_TURN_BODY = 400_000;
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "agentpier-runner",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "type": "module",
5
- "description": "Runs AgentPier agents on your own computer, limited to the folders you share and the permissions each agent has.",
5
+ "description": "Connect your AgentPier rooms to the coding CLIs signed in on your computer: Claude Code, Codex and Gemini CLI, on your own plans.",
6
6
  "license": "UNLICENSED",
7
7
  "repository": {
8
8
  "type": "git",