claude-yes 1.17.0 → 1.18.0

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/cli-idle.spec.ts CHANGED
@@ -6,7 +6,7 @@ import { sleepms } from './utils';
6
6
  // 2025-08-11 ok
7
7
  it.skip('CLI --exit-on-idle flag with custom timeout', async () => {
8
8
  const p = exec(
9
- `bunx tsx ./cli.ts --verbose --logFile=./cli-idle.log --exit-on-idle=3s "say hello and wait"`
9
+ `bunx tsx ./cli.ts --verbose --logFile=./cli-idle.log --exit-on-idle=3s "say hello and wait"`,
10
10
  );
11
11
  const tr = new TransformStream<string, string>();
12
12
  const output = await sflow(tr.readable).by(fromStdio(p)).log().text();
package/cli.test.ts CHANGED
@@ -1,11 +1,11 @@
1
- import { execaCommand } from 'execa';
2
- import { fromStdio } from 'from-node-stream';
3
1
  import { exec } from 'node:child_process';
4
2
  import { existsSync } from 'node:fs';
5
3
  import { readFile, unlink } from 'node:fs/promises';
4
+ import { execaCommand } from 'execa';
5
+ import { fromStdio } from 'from-node-stream';
6
6
  import sflow from 'sflow';
7
7
  import { beforeAll, describe, expect, it } from 'vitest';
8
- import { createIdleWatcher } from './createIdleWatcher';
8
+ import { IdleWaiter } from './idleWaiter';
9
9
  import { sleepms } from './utils';
10
10
 
11
11
  it('Write file with auto bypass prompts', async () => {
@@ -17,7 +17,7 @@ it('Write file with auto bypass prompts', async () => {
17
17
  }
18
18
 
19
19
  const p = exec(
20
- `bunx tsx ./cli.ts --logFile=./cli-rendered.log --exit-on-idle=3s "just write {on: 1} into ./.cache/flag.json and wait"`
20
+ `bunx tsx ./cli.ts --logFile=./cli-rendered.log --exit-on-idle=3s "just write {on: 1} into ./.cache/flag.json and wait"`,
21
21
  );
22
22
  const pExitCode = new Promise<number | null>((r) => p.once('exit', r));
23
23
 
@@ -34,12 +34,13 @@ it('Write file with auto bypass prompts', async () => {
34
34
 
35
35
  // ping function to exit claude when idle
36
36
 
37
- const { ping } = createIdleWatcher(() => exit(), 3000);
37
+ const idleWaiter = new IdleWaiter();
38
+ idleWaiter.wait(3000).then(() => exit());
38
39
 
39
40
  const output = await sflow(tr.readable)
40
41
  .by(fromStdio(p))
41
42
  .log()
42
- .forEach(() => ping())
43
+ .forEach(() => idleWaiter.ping())
43
44
  .text();
44
45
 
45
46
  // expect the file exists
package/cli.ts CHANGED
@@ -1,35 +1,44 @@
1
1
  #!/usr/bin/env node
2
- import ms from 'enhanced-ms';
2
+ import enhancedMs from 'enhanced-ms';
3
3
  import yargs from 'yargs';
4
4
  import { hideBin } from 'yargs/helpers';
5
5
  import claudeYes from '.';
6
6
 
7
7
  // cli entry point
8
8
  const argv = yargs(hideBin(process.argv))
9
- .usage('Usage: $0 [options] [--] [claude args]')
9
+ .usage('Usage: $0 [options] [claude args] [--] [prompts...]')
10
10
  .example(
11
11
  '$0 --exit-on-idle=30s --continue-on-crash "help me solve all todos in my codebase"',
12
- 'Run Claude with a 30 seconds idle timeout and continue on crash'
12
+ 'Run Claude with a 30 seconds idle timeout and continue on crash',
13
13
  )
14
- .option('exit-on-idle', {
15
- type: 'string',
16
- default: '60s',
17
- description:
18
- 'Exit after being idle for specified duration, default 1min, set to 0 to disable this behaviour',
19
- })
20
14
  .option('continue-on-crash', {
21
15
  type: 'boolean',
22
16
  default: true,
23
- description: 'Continue running even if Claude crashes',
17
+ description:
18
+ 'spawn Claude with --continue if it crashes, only works for claude',
24
19
  })
25
20
  .option('log-file', {
26
21
  type: 'string',
27
- description: 'Path to log file for output logging',
22
+ description: 'Log file to write to',
23
+ })
24
+ .option('cli', {
25
+ type: 'string',
26
+ description:
27
+ 'Claude CLI command, e.g. "claude,gemini,codex,cursor,copilot", default is "claude"',
28
+ })
29
+ .option('prompt', {
30
+ type: 'string',
31
+ description: 'Prompt to send to Claude',
32
+ alias: 'p',
28
33
  })
29
34
  .option('verbose', {
30
35
  type: 'boolean',
31
- default: false,
32
36
  description: 'Enable verbose logging',
37
+ default: false,
38
+ })
39
+ .option('exit-on-idle', {
40
+ type: 'string',
41
+ description: 'Exit after a period of inactivity, e.g., "5s" or "1m"',
33
42
  })
34
43
  .parserConfiguration({
35
44
  'unknown-options-as-args': true,
@@ -37,9 +46,38 @@ const argv = yargs(hideBin(process.argv))
37
46
  })
38
47
  .parseSync();
39
48
 
49
+ // detect cli name for cli, while package.json have multiple bin link: {"claude-yes": "cli.js", "codex-yes": "cli.js", "gemini-yes": "cli.js"}
50
+ if (!argv.cli) {
51
+ const cliName = process.argv[1]?.split('/').pop()?.split('-')[0];
52
+ argv.cli = cliName || 'claude';
53
+ }
54
+
55
+ // Support: everything after a literal `--` is a prompt string. Example:
56
+ // claude-yes --exit-on-idle=30s -- "help me refactor this"
57
+ // In that example the prompt will be `help me refactor this` and won't be
58
+ // passed as args to the underlying CLI binary.
59
+ const rawArgs = process.argv.slice(2);
60
+ const dashIndex = rawArgs.indexOf('--');
61
+ let promptFromDash: string | undefined = undefined;
62
+ let cliArgsForSpawn: string[] = [];
63
+ if (dashIndex !== -1) {
64
+ // join everything after `--` into a single prompt string
65
+ const after = rawArgs.slice(dashIndex + 1);
66
+ promptFromDash = after.join(' ');
67
+ // use everything before `--` as the cli args
68
+ cliArgsForSpawn = rawArgs.slice(0, dashIndex).map(String);
69
+ } else {
70
+ // fallback to yargs parsed positional args when `--` is not used
71
+ cliArgsForSpawn = argv._.map((e) => String(e));
72
+ }
73
+
74
+ console.clear();
40
75
  const { exitCode, logs } = await claudeYes({
41
- exitOnIdle: argv.exitOnIdle != null ? ms(argv.exitOnIdle) : undefined,
42
- claudeArgs: argv._.map((e) => String(e)),
76
+ cli: argv.cli,
77
+ // prefer explicit --prompt / -p; otherwise use the text after `--` if present
78
+ prompt: argv.prompt || promptFromDash,
79
+ exitOnIdle: argv.exitOnIdle ? enhancedMs(argv.exitOnIdle) : undefined,
80
+ cliArgs: cliArgsForSpawn,
43
81
  continueOnCrash: argv.continueOnCrash,
44
82
  logFile: argv.logFile,
45
83
  verbose: argv.verbose,
@@ -0,0 +1,337 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ var __create = Object.create;
4
+ var __getProtoOf = Object.getPrototypeOf;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __toESM = (mod, isNodeMode, target) => {
9
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
10
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
11
+ for (let key of __getOwnPropNames(mod))
12
+ if (!__hasOwnProp.call(to, key))
13
+ __defProp(to, key, {
14
+ get: () => mod[key],
15
+ enumerable: true
16
+ });
17
+ return to;
18
+ };
19
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
20
+
21
+ // cli.ts
22
+ import enhancedMs from "enhanced-ms";
23
+ import yargs from "yargs";
24
+ import { hideBin } from "yargs/helpers";
25
+
26
+ // dist/index.js
27
+ import { fromReadable, fromWritable } from "from-node-stream";
28
+ import { mkdir, writeFile } from "fs/promises";
29
+ import path from "path";
30
+ import DIE from "phpdie";
31
+ import sflow from "sflow";
32
+ import { TerminalTextRender } from "terminal-render";
33
+ class IdleWaiter {
34
+ lastActivityTime = Date.now();
35
+ checkInterval = 100;
36
+ constructor() {
37
+ this.ping();
38
+ }
39
+ ping() {
40
+ this.lastActivityTime = Date.now();
41
+ return this;
42
+ }
43
+ async wait(ms) {
44
+ while (this.lastActivityTime >= Date.now() - ms)
45
+ await new Promise((resolve) => setTimeout(resolve, this.checkInterval));
46
+ }
47
+ }
48
+
49
+ class ReadyManager {
50
+ isReady = false;
51
+ readyQueue = [];
52
+ wait() {
53
+ return new Promise((resolve) => {
54
+ if (this.isReady)
55
+ return resolve();
56
+ this.readyQueue.push(resolve);
57
+ });
58
+ }
59
+ unready() {
60
+ this.isReady = false;
61
+ }
62
+ ready() {
63
+ this.isReady = true;
64
+ if (!this.readyQueue.length)
65
+ return;
66
+ this.readyQueue.splice(0).map((resolve) => resolve());
67
+ }
68
+ }
69
+ function removeControlCharacters(str) {
70
+ return str.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, "");
71
+ }
72
+ var CLI_CONFIGURES = {
73
+ claude: {
74
+ ready: /^> /,
75
+ enter: [/❯ 1. Yes/, /❯ 1. Dark mode✔/, /Press Enter to continue…/],
76
+ fatal: [
77
+ /No conversation found to continue/,
78
+ /⎿ {2}Claude usage limit reached\./
79
+ ]
80
+ },
81
+ gemini: {
82
+ ready: /Type your message/,
83
+ enter: [/│ ● 1. Yes, allow once/]
84
+ },
85
+ codex: {
86
+ ready: /⏎ send/,
87
+ enter: [/ > 1. Approve/, /> 1. Yes, allow Codex to work in this folder/],
88
+ fatal: [/Error: The cursor position could not be read within/],
89
+ ensureArgs: (args) => {
90
+ if (!args.includes("--search"))
91
+ return ["--search", ...args];
92
+ return args;
93
+ }
94
+ },
95
+ copilot: {
96
+ ready: /^ > /,
97
+ enter: [/ │ ❯ 1. Yes, proceed/, /❯ 1. Yes/]
98
+ },
99
+ cursor: {
100
+ binary: "cursor-agent",
101
+ ready: /\/ commands/,
102
+ enter: [/→ Run \(once\) \(y\) \(enter\)/, /▶ \[a\] Trust this workspace/]
103
+ }
104
+ };
105
+ async function claudeYes({
106
+ cli = "claude",
107
+ cliArgs = [],
108
+ prompt,
109
+ continueOnCrash,
110
+ cwd,
111
+ env,
112
+ exitOnIdle,
113
+ logFile,
114
+ removeControlCharactersFromStdout = false,
115
+ verbose = false
116
+ } = {}) {
117
+ const continueArgs = {
118
+ codex: "resume --last".split(" "),
119
+ claude: "--continue".split(" "),
120
+ gemini: []
121
+ };
122
+ process.stdin.setRawMode?.(true);
123
+ let isFatal = false;
124
+ const stdinReady = new ReadyManager;
125
+ const shellOutputStream = new TransformStream;
126
+ const outputWriter = shellOutputStream.writable.getWriter();
127
+ const pty = await import("node-pty").catch(async () => await import("bun-pty")).catch(async () => DIE("Please install node-pty or bun-pty, run this: bun install bun-pty"));
128
+ const getPtyOptions = () => ({
129
+ name: "xterm-color",
130
+ ...getTerminalDimensions(),
131
+ cwd: cwd ?? process.cwd(),
132
+ env: env ?? process.env
133
+ });
134
+ const cliConf = CLI_CONFIGURES[cli] || {};
135
+ cliArgs = cliConf.ensureArgs?.(cliArgs) ?? cliArgs;
136
+ const cliCommand = cliConf?.binary || cli;
137
+ let shell = pty.spawn(cliCommand, cliArgs, getPtyOptions());
138
+ const pendingExitCode = Promise.withResolvers();
139
+ let pendingExitCodeValue = null;
140
+ async function onData(data) {
141
+ await outputWriter.write(data);
142
+ }
143
+ shell.onData(onData);
144
+ shell.onExit(function onExit({ exitCode: exitCode2 }) {
145
+ stdinReady.unready();
146
+ const agentCrashed = exitCode2 !== 0;
147
+ const continueArg = continueArgs[cli];
148
+ if (agentCrashed && continueOnCrash && continueArg) {
149
+ if (!continueArg) {
150
+ return console.warn(`continueOnCrash is only supported for ${Object.keys(continueArgs).join(", ")} currently, not ${cli}`);
151
+ }
152
+ if (isFatal) {
153
+ console.log(`${cli} crashed with "No conversation found to continue", exiting...`);
154
+ return pendingExitCode.resolve(pendingExitCodeValue = exitCode2);
155
+ }
156
+ console.log(`${cli} crashed, restarting...`);
157
+ shell = pty.spawn(cli, continueArg, getPtyOptions());
158
+ shell.onData(onData);
159
+ shell.onExit(onExit);
160
+ return;
161
+ }
162
+ return pendingExitCode.resolve(pendingExitCodeValue = exitCode2);
163
+ });
164
+ process.stdout.on("resize", () => {
165
+ const { cols, rows } = getTerminalDimensions();
166
+ shell.resize(cols, rows);
167
+ });
168
+ const terminalRender = new TerminalTextRender;
169
+ const isStillWorkingQ = () => terminalRender.render().replace(/\s+/g, " ").match(/esc to interrupt|to run in background/);
170
+ const idleWaiter = new IdleWaiter;
171
+ if (exitOnIdle)
172
+ idleWaiter.wait(exitOnIdle).then(async () => {
173
+ if (isStillWorkingQ()) {
174
+ console.log("[${cli}-yes] ${cli} is idle, but seems still working, not exiting yet");
175
+ return;
176
+ }
177
+ console.log("[${cli}-yes] ${cli} is idle, exiting...");
178
+ await exitAgent();
179
+ });
180
+ sflow(fromReadable(process.stdin)).map((buffer) => buffer.toString()).by({
181
+ writable: new WritableStream({
182
+ write: async (data) => {
183
+ await stdinReady.wait();
184
+ shell.write(data);
185
+ }
186
+ }),
187
+ readable: shellOutputStream.readable
188
+ }).forEach(() => idleWaiter.ping()).forEach((text) => {
189
+ terminalRender.write(text);
190
+ if (process.stdin.isTTY)
191
+ return;
192
+ if (text.includes("\x1B[6n"))
193
+ return;
194
+ const rendered = terminalRender.render();
195
+ const row = rendered.split(`
196
+ `).length + 1;
197
+ const col = (rendered.split(`
198
+ `).slice(-1)[0]?.length || 0) + 1;
199
+ shell.write(`\x1B[${row};${col}R`);
200
+ }).forkTo((e) => e.map((e2) => removeControlCharacters(e2)).map((e2) => e2.replaceAll("\r", "")).lines({ EOL: "NONE" }).forEach(async (e2, i) => {
201
+ const conf = CLI_CONFIGURES[cli] || {};
202
+ if (!conf)
203
+ return;
204
+ try {
205
+ if (conf.ready) {
206
+ if (cli === "gemini" && conf.ready instanceof RegExp) {
207
+ if (e2.match(conf.ready) && i > 80)
208
+ return stdinReady.ready();
209
+ } else if (e2.match(conf.ready)) {
210
+ return stdinReady.ready();
211
+ }
212
+ }
213
+ if (conf.enter && Array.isArray(conf.enter)) {
214
+ for (const rx of conf.enter) {
215
+ if (e2.match(rx))
216
+ return await sendEnter();
217
+ }
218
+ } else if (conf.enter && conf.enter instanceof RegExp) {
219
+ if (e2.match(conf.enter))
220
+ return await sendEnter();
221
+ }
222
+ if (conf.fatal && Array.isArray(conf.fatal)) {
223
+ for (const rx of conf.fatal) {
224
+ if (e2.match(rx))
225
+ return isFatal = true;
226
+ }
227
+ } else if (conf.fatal && conf.fatal instanceof RegExp) {
228
+ if (e2.match(conf.fatal))
229
+ return isFatal = true;
230
+ }
231
+ } catch (err) {
232
+ return;
233
+ }
234
+ }).run()).map((e) => removeControlCharactersFromStdout ? removeControlCharacters(e) : e).to(fromWritable(process.stdout)).then(() => null);
235
+ if (prompt)
236
+ (async () => {
237
+ await sendMessage(prompt);
238
+ })();
239
+ const exitCode = await pendingExitCode.promise;
240
+ console.log(`[${cli}-yes] ${cli} exited with code ${exitCode}`);
241
+ if (logFile) {
242
+ verbose && console.log(`[${cli}-yes] Writing rendered logs to ${logFile}`);
243
+ const logFilePath = path.resolve(logFile);
244
+ await mkdir(path.dirname(logFilePath), { recursive: true }).catch(() => null);
245
+ await writeFile(logFilePath, terminalRender.render());
246
+ }
247
+ return { exitCode, logs: terminalRender.render() };
248
+ async function sendEnter(waitms = 1000) {
249
+ const st = Date.now();
250
+ await idleWaiter.wait(waitms);
251
+ const et = Date.now();
252
+ process.stdout.write(`\ridleWaiter.wait(${waitms}) took ${et - st}ms\r`);
253
+ shell.write("\r");
254
+ }
255
+ async function sendMessage(message) {
256
+ await stdinReady.wait();
257
+ shell.write(message);
258
+ idleWaiter.ping();
259
+ await sendEnter();
260
+ }
261
+ async function exitAgent() {
262
+ continueOnCrash = false;
263
+ await sendMessage("/exit");
264
+ let exited = false;
265
+ await Promise.race([
266
+ pendingExitCode.promise.then(() => exited = true),
267
+ new Promise((resolve) => setTimeout(() => {
268
+ if (exited)
269
+ return;
270
+ shell.kill();
271
+ resolve();
272
+ }, 5000))
273
+ ]);
274
+ }
275
+ function getTerminalDimensions() {
276
+ return {
277
+ cols: Math.max(process.stdout.columns, 80),
278
+ rows: process.stdout.rows
279
+ };
280
+ }
281
+ }
282
+
283
+ // cli.ts
284
+ var argv = yargs(hideBin(process.argv)).usage("Usage: $0 [options] [claude args] [--] [prompts...]").example('$0 --exit-on-idle=30s --continue-on-crash "help me solve all todos in my codebase"', "Run Claude with a 30 seconds idle timeout and continue on crash").option("continue-on-crash", {
285
+ type: "boolean",
286
+ default: true,
287
+ description: "spawn Claude with --continue if it crashes, only works for claude"
288
+ }).option("log-file", {
289
+ type: "string",
290
+ description: "Log file to write to"
291
+ }).option("cli", {
292
+ type: "string",
293
+ description: 'Claude CLI command, e.g. "claude,gemini,codex,cursor,copilot", default is "claude"'
294
+ }).option("prompt", {
295
+ type: "string",
296
+ description: "Prompt to send to Claude",
297
+ alias: "p"
298
+ }).option("verbose", {
299
+ type: "boolean",
300
+ description: "Enable verbose logging",
301
+ default: false
302
+ }).option("exit-on-idle", {
303
+ type: "string",
304
+ description: 'Exit after a period of inactivity, e.g., "5s" or "1m"'
305
+ }).parserConfiguration({
306
+ "unknown-options-as-args": true,
307
+ "halt-at-non-option": true
308
+ }).parseSync();
309
+ if (!argv.cli) {
310
+ const cliName = process.argv[1]?.split("/").pop()?.split("-")[0];
311
+ argv.cli = cliName || "claude";
312
+ }
313
+ var rawArgs = process.argv.slice(2);
314
+ var dashIndex = rawArgs.indexOf("--");
315
+ var promptFromDash = undefined;
316
+ var cliArgsForSpawn = [];
317
+ if (dashIndex !== -1) {
318
+ const after = rawArgs.slice(dashIndex + 1);
319
+ promptFromDash = after.join(" ");
320
+ cliArgsForSpawn = rawArgs.slice(0, dashIndex).map(String);
321
+ } else {
322
+ cliArgsForSpawn = argv._.map((e) => String(e));
323
+ }
324
+ console.clear();
325
+ var { exitCode, logs } = await claudeYes({
326
+ cli: argv.cli,
327
+ prompt: argv.prompt || promptFromDash,
328
+ exitOnIdle: argv.exitOnIdle ? enhancedMs(argv.exitOnIdle) : undefined,
329
+ cliArgs: cliArgsForSpawn,
330
+ continueOnCrash: argv.continueOnCrash,
331
+ logFile: argv.logFile,
332
+ verbose: argv.verbose
333
+ });
334
+ process.exit(exitCode ?? 1);
335
+
336
+ //# debugId=C444081B11389E6E64756E2164756E21
337
+ //# sourceMappingURL=cli.js.map