claude_runner 1.1.0

CLI for executing Claude Code via builder pattern; YAML schema constants for command registration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
use crate::VerbosityLevel;
use claude_runner_core::EffortLevel;
use error_tools::{ Error, Result };

/// Strategy for `--expect` output validation.
///
/// Determines how `run_print_mode` behaves when the captured output does not
/// match any value listed in `--expect`.
pub( crate ) enum ExpectStrategy
{
  /// Exit 3 immediately on first mismatch (default).
  Fail,
  /// Re-invoke the subprocess up to `--expect-retries` more times; exit 3 if exhausted.
  Retry,
  /// Print the fallback value and exit 0 regardless of subprocess output.
  Default( String ),
}

impl core::str::FromStr for ExpectStrategy
{
  type Err = String;
  fn from_str( s : &str ) -> core::result::Result< Self, Self::Err >
  {
    match s
    {
      "fail"  => Ok( ExpectStrategy::Fail ),
      "retry" => Ok( ExpectStrategy::Retry ),
      _ if s.starts_with( "default:" ) =>
      {
        let val = s[ "default:".len() .. ].to_string();
        Ok( ExpectStrategy::Default( val ) )
      }
      _ => Err( format!(
        "invalid --expect-strategy value: {s}\nExpected: fail, retry, or default:<VALUE>"
      ) ),
    }
  }
}

/// Parsed CLI arguments.
#[ allow( clippy::struct_excessive_bools ) ]
#[ derive( Default ) ]
pub( crate ) struct CliArgs
{
  pub( crate ) message              : Option< String >,
  pub( crate ) print_mode           : bool,
  pub( crate ) interactive          : bool,
  pub( crate ) new_session          : bool,
  pub( crate ) model                : Option< String >,
  pub( crate ) verbose              : bool,
  pub( crate ) no_skip_permissions  : bool,
  pub( crate ) max_tokens           : Option< u32 >,
  pub( crate ) session_dir          : Option< String >,
  pub( crate ) dir                  : Option< String >,
  pub( crate ) dry_run              : bool,
  pub( crate ) trace                : bool,
  pub( crate ) verbosity            : Option< VerbosityLevel >,
  pub( crate ) help                 : bool,
  pub( crate ) system_prompt        : Option< String >,
  pub( crate ) append_system_prompt : Option< String >,
  pub( crate ) no_ultrathink        : bool,
  pub( crate ) effort               : Option< EffortLevel >,
  pub( crate ) no_effort_max        : bool,
  pub( crate ) no_chrome            : bool,
  pub( crate ) no_persist           : bool,
  pub( crate ) json_schema          : Option< String >,
  pub( crate ) mcp_config           : Vec< String >,
  pub( crate ) file                 : Option< String >,
  pub( crate ) strip_fences         : bool,
  pub( crate ) keep_claudecode      : bool,
  pub( crate ) subdir               : Option< String >,
  pub( crate ) output_file          : Option< String >,
  pub( crate ) expect               : Option< String >,
  pub( crate ) expect_strategy      : Option< ExpectStrategy >,
  pub( crate ) expect_retries       : Option< u8 >,
  pub( crate ) max_sessions         : Option< u32 >,
  pub( crate ) retry_on_rate_limit  : Option< u8 >,
  pub( crate ) retry_delay          : Option< u32 >,
  pub( crate ) timeout              : Option< u32 >,
}

/// Consume the next argv element as a flag's value.
pub( super ) fn next_value<'a>( tokens : &'a [ String ], idx : usize, flag : &str ) -> Result< &'a str >
{
  tokens.get( idx ).map( String::as_str ).ok_or_else( ||
    Error::msg( format!( "{flag} requires a value" ) )
  )
}

/// Parse a raw string as a u32 token limit with a clear error message.
///
/// Called from `parse_value_flag()`. Isolates multi-line parse logic so each
/// value-consuming arm in `parse_value_flag` stays single-expression.
fn parse_token_limit( raw : &str ) -> Result< u32 >
{
  raw.parse::< u32 >().map_err( | _ |
    Error::msg( format!(
      "invalid --max-tokens value: {raw}\n\
       Expected unsigned integer 0–4294967295"
    ) )
  )
}

/// Parse a raw string as an `EffortLevel` with a clear error message.
///
/// Called from `parse_value_flag()`. Delegates to `EffortLevel::from_str`.
fn parse_effort_level( raw : &str ) -> Result< EffortLevel >
{
  raw.parse::< EffortLevel >().map_err( Error::msg )
}

/// Parse a raw string as an `ExpectStrategy` with a clear error message.
///
/// Called from `parse_value_flag()`. Delegates to `ExpectStrategy::from_str`.
fn parse_expect_strategy( raw : &str ) -> Result< ExpectStrategy >
{
  raw.parse::< ExpectStrategy >().map_err( Error::msg )
}

/// Parse a raw string as a bounded u8 (0–255) with a labeled error message.
///
/// Used for flags like `--expect-retries` and `--retry-on-rate-limit`.
pub( crate ) fn parse_u8_bounded( raw : &str, flag_name : &str ) -> Result< u8 >
{
  raw.parse::< u32 >()
    .ok()
    .and_then( | v | u8::try_from( v ).ok() )
    .ok_or_else( || Error::msg( format!(
      "invalid {flag_name} value: {raw}\nExpected integer 0–255"
    ) ) )
}

/// Parse a raw string as a u32 flag value with a labeled error message and hint.
///
/// Used for flags like `--max-sessions`, `--retry-delay`, and `--timeout`.
fn parse_u32_flag( raw : &str, flag_name : &str, hint : &str ) -> Result< u32 >
{
  raw.parse::< u32 >().map_err( | _ |
    Error::msg( format!(
      "invalid {flag_name} value: {raw}\nExpected unsigned integer{hint}"
    ) )
  )
}

/// Parse a value-consuming flag (`--flag value` pair) into `parsed`.
///
/// Handles flags that are forwarded to the Claude command line or modify
/// the subprocess environment. Falls through to `parse_runner_value_flag`
/// for runner-behavior flags (output capture, validation, concurrency, timeouts).
///
/// Returns `true` when `token` is a recognised value-consuming flag and its
/// following value was consumed into `parsed`. Returns `false` when `token`
/// is not a known value-consuming flag (caller decides whether to treat it
/// as unknown). `next` is the index of the token immediately after `token`.
fn parse_value_flag(
  token  : &str,
  tokens : &[ String ],
  next   : usize,
  parsed : &mut CliArgs,
) -> Result< bool >
{
  match token
  {
    "--effort" =>
    {
      parsed.effort = Some(
        parse_effort_level( next_value( tokens, next, "--effort" )? )?
      );
    }
    "--system-prompt" =>
    {
      parsed.system_prompt = Some( next_value( tokens, next, "--system-prompt" )?.to_string() );
    }
    "--append-system-prompt" =>
    {
      parsed.append_system_prompt = Some( next_value( tokens, next, "--append-system-prompt" )?.to_string() );
    }
    "--model" =>
    {
      parsed.model = Some( next_value( tokens, next, "--model" )?.to_string() );
    }
    "--max-tokens" =>
    {
      parsed.max_tokens = Some( parse_token_limit( next_value( tokens, next, "--max-tokens" )? )? );
    }
    "--session-dir" =>
    {
      parsed.session_dir = Some( next_value( tokens, next, "--session-dir" )?.to_string() );
    }
    "--dir" =>
    {
      parsed.dir = Some( next_value( tokens, next, "--dir" )?.to_string() );
    }
    "--json-schema" =>
    {
      parsed.json_schema = Some( next_value( tokens, next, "--json-schema" )?.to_string() );
    }
    "--mcp-config" =>
    {
      parsed.mcp_config.push( next_value( tokens, next, "--mcp-config" )?.to_string() );
    }
    "--file" =>
    {
      parsed.file = Some( next_value( tokens, next, "--file" )?.to_string() );
    }
    // Fix(BUG-230): reject subdir names containing `/` — spec requires single name component
    // Root cause: no validation; `create_dir_all` silently created nested dirs for `a/b`
    // Pitfall: must reject `/` in the value, not just leading `/` — any separator violates
    // the "directory name component" type constraint in 028_subdir.md
    "--subdir" =>
    {
      let val = next_value( tokens, next, "--subdir" )?;
      if val.contains( '/' )
      {
        return Err( Error::msg(
          "--subdir must be a single directory name component (no '/' separators)"
        ) );
      }
      parsed.subdir = Some( val.to_string() );
    }
    "--verbosity" =>
    {
      let raw = next_value( tokens, next, "--verbosity" )?;
      parsed.verbosity = Some( raw.parse::< VerbosityLevel >().map_err( Error::msg )? );
    }
    _ => return parse_runner_value_flag( token, tokens, next, parsed ),
  }
  Ok( true )
}

/// Parse runner-behavior value flags into `parsed`.
///
/// Handles flags that control output capture, expect validation, session concurrency,
/// retry logic, and subprocess timeouts — none of which are forwarded to the claude
/// command line directly.
fn parse_runner_value_flag(
  token  : &str,
  tokens : &[ String ],
  next   : usize,
  parsed : &mut CliArgs,
) -> Result< bool >
{
  match token
  {
    "--output-file" =>
    {
      parsed.output_file = Some( next_value( tokens, next, "--output-file" )?.to_string() );
    }
    "--expect" =>
    {
      parsed.expect = Some( next_value( tokens, next, "--expect" )?.to_string() );
    }
    "--expect-strategy" =>
    {
      parsed.expect_strategy = Some(
        parse_expect_strategy( next_value( tokens, next, "--expect-strategy" )? )?
      );
    }
    "--expect-retries" =>
    {
      parsed.expect_retries = Some(
        parse_u8_bounded( next_value( tokens, next, "--expect-retries" )?, "--expect-retries" )?
      );
    }
    "--max-sessions" =>
    {
      parsed.max_sessions = Some(
        parse_u32_flag( next_value( tokens, next, "--max-sessions" )?, "--max-sessions", " (0 = unlimited)" )?
      );
    }
    "--retry-on-rate-limit" =>
    {
      parsed.retry_on_rate_limit = Some(
        parse_u8_bounded( next_value( tokens, next, "--retry-on-rate-limit" )?, "--retry-on-rate-limit" )?
      );
    }
    "--retry-delay" =>
    {
      parsed.retry_delay = Some(
        parse_u32_flag( next_value( tokens, next, "--retry-delay" )?, "--retry-delay", " (seconds)" )?
      );
    }
    "--timeout" =>
    {
      parsed.timeout = Some(
        parse_u32_flag( next_value( tokens, next, "--timeout" )?, "--timeout", " (seconds; 0 = unlimited)" )?
      );
    }
    _ => return Ok( false ),
  }
  Ok( true )
}

/// Parse argv into structured CLI arguments.
///
/// Mirrors Claude Code's native `--flag value` syntax.
/// Positional (non-flag) arguments are joined with space to form the message.
///
/// `--help`/`-h` wins regardless of other flags or unknown tokens: if either appears
/// anywhere in `tokens`, parsing short-circuits and returns `CliArgs { help: true, .. }`.
#[ allow( clippy::too_many_lines ) ]
pub( crate ) fn parse_args( tokens : &[ String ] ) -> Result< CliArgs >
{
  // --help/-h always wins — return early before any other token is parsed.
  // This ensures help is shown even when unknown flags or other errors are present.
  // Fix(BUG-221): parse_args returned Err on the first unknown flag,
  // so main() never reached the cli.help check even when --help was present in argv.
  // Root cause: early Err return on unknown flags prevented the help check from firing.
  // Pitfall: checking cli.help after parse_args completes is insufficient — the Err path
  // in main() exits before any field of CliArgs is consulted.
  if tokens.iter().any( | t | t == "--help" || t == "-h" )
  {
    return Ok( CliArgs
    {
      help                 : true,
      message              : None,
      print_mode           : false,
      interactive          : false,
      new_session          : false,
      model                : None,
      verbose              : false,
      no_skip_permissions  : false,
      max_tokens           : None,
      session_dir          : None,
      dir                  : None,
      dry_run              : false,
      trace                : false,
      verbosity            : None,
      system_prompt        : None,
      append_system_prompt : None,
      no_ultrathink        : false,
      effort               : None,
      no_effort_max        : false,
      no_chrome            : false,
      no_persist           : false,
      json_schema          : None,
      mcp_config           : Vec::new(),
      file                 : None,
      strip_fences         : false,
      keep_claudecode      : false,
      subdir               : None,
      output_file          : None,
      expect               : None,
      expect_strategy      : None,
      expect_retries       : None,
      max_sessions         : None,
      retry_on_rate_limit  : None,
      retry_delay          : None,
      timeout              : None,
    } );
  }

  let mut parsed = CliArgs::default();
  let mut positional : Vec< String > = Vec::new();
  let mut i = 0;

  while i < tokens.len()
  {
    let token = tokens[ i ].as_str();
    match token
    {
      "-h" | "--help" =>
      {
        parsed.help = true;
      }
      "-p" | "--print" =>
      {
        parsed.print_mode = true;
      }
      "--interactive" =>
      {
        parsed.interactive = true;
      }
      "--new-session" =>
      {
        parsed.new_session = true;
      }
      "--verbose" =>
      {
        parsed.verbose = true;
      }
      "--no-skip-permissions" =>
      {
        parsed.no_skip_permissions = true;
      }
      "--dry-run" =>
      {
        parsed.dry_run = true;
      }
      "--trace" =>
      {
        parsed.trace = true;
      }
      "--no-ultrathink" =>
      {
        parsed.no_ultrathink = true;
      }
      "--no-effort-max" =>
      {
        parsed.no_effort_max = true;
      }
      "--no-chrome" =>
      {
        parsed.no_chrome = true;
      }
      "--no-persist" =>
      {
        parsed.no_persist = true;
      }
      "--strip-fences" =>
      {
        parsed.strip_fences = true;
      }
      "--keep-claudecode" =>
      {
        parsed.keep_claudecode = true;
      }
      "--" =>
      {
        // Everything after `--` is positional.
        // Fix(BUG-220): filter empty tokens here too — `clr -- ""`
        // must behave like bare `clr`, not forward a degenerate "\n\nultrathink" message.
        // Root cause: positional.extend() copies all tokens verbatim; the empty-token
        // guard in the `_` arm does not apply to the `--` code path.
        // Pitfall: filter at the individual-token level (not the joined string) so that
        // whitespace-only strings like " " are still valid messages and pass through.
        positional.extend( tokens[ i + 1 .. ].iter().filter( | t | !t.is_empty() ).cloned() );
        break;
      }
      s if s.starts_with( '-' ) =>
      {
        if parse_value_flag( s, tokens, i + 1, &mut parsed )?
        {
          i += 1; // advance past the consumed value token
        }
        else
        {
          return Err( Error::msg( format!( "unknown option: {s}\nRun with --help for usage." ) ) );
        }
      }
      _ =>
      {
        // Fix(BUG-219): skip empty tokens so `clr ""` behaves like
        // bare `clr` (no message, no --print, no degenerate "\n\nultrathink" forwarded).
        // Root cause: empty string was pushed to positional, joined to message=Some(""),
        // then the ultrathink suffix produced "\n\nultrathink" for an empty payload.
        // Pitfall: filter individual empty tokens, not the joined string — whitespace-only
        // strings like " " are valid non-empty messages and must not be filtered out.
        if !tokens[ i ].is_empty()
        {
          positional.push( tokens[ i ].clone() );
        }
      }
    }
    i += 1;
  }

  if !positional.is_empty()
  {
    parsed.message = Some( positional.join( " " ) );
  }

  Ok( parsed )
}