link-assistant-router 1.4.2

Link.Assistant.Router — Claude MAX OAuth proxy and token gateway for Anthropic APIs
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! Tests for the two decisions `with` makes on the user's behalf.

use super::*;

fn args(client: ClientKind, client_args: &[&str]) -> WithArgs {
    WithArgs {
        managed: false,
        global: false,
        undo: false,
        non_interactive: false,
        interactive: false,
        extend_global_config: false,
        isolated_config: false,
        reset_to_default_configuration: false,
        yes: false,
        pick_model: false,
        server: None,
        management_server: None,
        local: false,
        token: None,
        token_stdin: false,
        model: None,
        label: None,
        run_ttl_hours: 1,
        fixed_run_ttl: false,
        run_max_requests: None,
        client,
        client_args: client_args.iter().map(OsString::from).collect(),
    }
}

fn argv(client: ClientKind, client_args: &[&str]) -> Vec<String> {
    rendered(&plan(&args(client, client_args), None, true))
}

fn rendered(launch: &Launch) -> Vec<String> {
    launch
        .arguments
        .iter()
        .map(|value| value.to_string_lossy().into_owned())
        .collect()
}

/// The defect in issue #297: `with claude --resume <id>` added `--print`, so
/// the client was told to resume a session, answer once and exit — with no
/// prompt to answer. Its own error was correct and named neither `--print`
/// nor the router.
#[test]
fn a_client_flag_does_not_turn_a_session_into_a_one_shot_run() {
    for forwarded in [
        &["--resume", "2a42a73e"][..],
        &["--continue"],
        &["--verbose"],
        &["--debug"],
        &["--add-dir", "/tmp"],
        &["--dangerously-skip-permissions"],
    ] {
        let rendered = argv(ClientKind::ClaudeCode, forwarded);
        assert!(
            !rendered.iter().any(|argument| argument == "--print"),
            "{forwarded:?} must launch a session, not a batch run: {rendered:?}"
        );
        assert!(
            rendered.ends_with(
                &forwarded
                    .iter()
                    .map(ToString::to_string)
                    .collect::<Vec<_>>()
            ),
            "the client's own arguments must still reach it: {rendered:?}"
        );
    }
}

/// The other half of the same rule: a bare positional *is* a prompt, so the
/// one-shot case that already worked keeps working with no flag.
#[test]
fn a_bare_positional_is_still_a_one_shot_prompt() {
    let rendered = argv(ClientKind::ClaudeCode, &["fix the tests"]);
    assert!(
        rendered.iter().any(|argument| argument == "--print"),
        "a prompt is a task: {rendered:?}"
    );
    // Codex and OpenCode spell the mode as a subcommand, which must come first.
    assert_eq!(
        argv(ClientKind::Codex, &["fix the tests"]).first(),
        Some(&"exec".to_string())
    );
}

/// Nobody is holding a session when the streams are pipes, so CI and shell
/// pipelines keep their one-shot behaviour without learning a flag.
#[test]
fn a_run_without_a_terminal_is_one_shot() {
    let launch = plan(&args(ClientKind::ClaudeCode, &["--verbose"]), None, false);
    assert!(rendered(&launch).iter().any(|value| value == "--print"));
    assert!(
        launch.note.is_none(),
        "nothing was guessed: there is no terminal to hold a session"
    );
}

/// Both overrides still win over the rule, in both directions.
#[test]
fn the_explicit_flags_win_over_the_rule() {
    let mut interactive = args(ClientKind::ClaudeCode, &["fix the tests"]);
    interactive.interactive = true;
    assert!(
        !rendered(&plan(&interactive, None, true))
            .iter()
            .any(|value| value == "--print")
    );

    let mut one_shot = args(ClientKind::ClaudeCode, &["--resume", "abc"]);
    one_shot.non_interactive = true;
    assert!(
        rendered(&plan(&one_shot, None, true))
            .iter()
            .any(|value| value == "--print")
    );
}

/// The launcher is silent when it does the obvious thing.
///
/// A flagged interactive launch is most launches for an interactive tool, and
/// each one printed advice above the client's own banner about an option the
/// user had not asked about. The bare invocation was the silent one, so advice
/// arrived in inverse proportion to how much the user needed it (issue #330).
#[test]
fn an_ordinary_interactive_launch_says_nothing_of_its_own() {
    for forwarded in [&["--verbose"][..], &["--model", "claude-opus-5"], &[]] {
        let launch = plan(&args(ClientKind::ClaudeCode, forwarded), None, true);
        assert!(
            launch.note.is_none(),
            "{forwarded:?} went as typed and needs no announcement: {:?}",
            launch.note
        );
    }
    // A one-shot run with a prompt is equally unremarkable.
    assert!(
        plan(
            &args(ClientKind::ClaudeCode, &["fix the tests"]),
            None,
            true
        )
        .note
        .is_none()
    );
}

/// The defect in issue #295: a bare launch replaced the model the user had
/// configured with whatever sorted first in the catalog for that vendor.
#[test]
fn a_bare_launch_names_no_model() {
    for client in ClientKind::ALL {
        if requires_a_model(client) || client.integration().model_arg.is_none() {
            continue;
        }
        let rendered = argv(client, &[]);
        assert!(
            !rendered.iter().any(|argument| argument == "--model"),
            "{client} was given a model nobody asked for: {rendered:?}"
        );
    }
}

/// Asking for one still works, and the id reaches the client unchanged.
#[test]
fn an_explicit_model_is_passed_through() {
    let launch = plan(&args(ClientKind::ClaudeCode, &[]), Some("opus[1m]"), true);
    assert!(
        rendered(&launch)
            .windows(2)
            .any(|pair| pair == ["--model", "opus[1m]"]),
        "{:?}",
        rendered(&launch)
    );
}

/// A client whose configuration embeds the catalog cannot start without a
/// model, so that one is still filled in — it is the client's requirement
/// rather than a preference being overridden.
#[test]
fn a_client_that_cannot_start_without_a_model_still_gets_one() {
    for client in [
        ClientKind::Opencode,
        ClientKind::QwenCode,
        ClientKind::Agent,
    ] {
        assert!(requires_a_model(client), "{client}");
    }
    for client in [
        ClientKind::ClaudeCode,
        ClientKind::Codex,
        ClientKind::GeminiCli,
        ClientKind::GrokCli,
    ] {
        assert!(!requires_a_model(client), "{client}");
    }
    let launch = plan(&args(ClientKind::Opencode, &[]), Some("some-model"), true);
    assert!(
        rendered(&launch)
            .windows(2)
            .any(|pair| pair == ["--model", "link-assistant/some-model"]),
        "opencode namespaces the id it was given: {:?}",
        rendered(&launch)
    );
}

/// A model the client was told about itself is never overridden.
#[test]
fn a_model_the_client_was_given_wins() {
    let launch = plan(
        &args(ClientKind::ClaudeCode, &["--model", "theirs"]),
        Some("ours"),
        true,
    );
    let rendered = rendered(&launch);
    assert_eq!(
        rendered.iter().filter(|value| *value == "--model").count(),
        1,
        "{rendered:?}"
    );
    assert!(
        rendered.iter().any(|value| value == "theirs"),
        "{rendered:?}"
    );
}

#[test]
fn colliding_wrapper_flags_after_client_are_forwarded() {
    let rendered = argv(ClientKind::Codex, &["--global", "hi"]);
    assert!(rendered.ends_with(&["--global".to_string(), "hi".to_string()]));
    // `--global` is a flag, so the mode comes from the terminal rule; this
    // path has one, and the trailing `hi` is not in first position.
    assert_ne!(rendered.first().map(String::as_str), Some("exec"));
}

#[test]
fn explicit_separator_is_not_forwarded() {
    let rendered = argv(ClientKind::Opencode, &["--", "run", "hi"]);
    assert_eq!(rendered.first().map(String::as_str), Some("run"));
    assert_eq!(
        rendered.iter().filter(|arg| arg.as_str() == "run").count(),
        1
    );
}

#[test]
fn command_mode_word_inside_prompt_is_not_treated_as_the_subcommand() {
    let rendered = argv(ClientKind::Opencode, &["explain", "run"]);
    assert_eq!(rendered.first().map(String::as_str), Some("run"));
    assert!(rendered.ends_with(&["explain".to_string(), "run".to_string()]));
}

#[test]
fn every_current_native_command_stays_in_command_position() {
    for client in ClientKind::ALL {
        for command in native_commands(client) {
            for terminal in [true, false] {
                let launch = plan(&args(client, &[command, "--help"]), None, terminal);
                assert_eq!(
                    rendered(&launch),
                    [command.to_string(), "--help".to_string()],
                    "{client} {command} terminal={terminal}"
                );
                assert!(!launch.one_shot, "native commands are not inference tasks");
            }
        }
    }
}

#[test]
fn separator_is_future_proof_exact_argv_mode() {
    for client in ClientKind::ALL {
        if client == ClientKind::Cursor {
            continue;
        }
        let launch = plan(
            &args(client, &["--", "future-command", "--flag"]),
            None,
            false,
        );
        assert_eq!(
            rendered(&launch),
            ["future-command".to_string(), "--flag".to_string()],
            "{client}"
        );
        assert!(!launch.one_shot);
    }
}

#[test]
fn codex_cloud_is_rejected_before_launch_planning() {
    for command in ["cloud", "cloud-tasks"] {
        assert!(unsupported_native_command(&args(ClientKind::Codex, &[command])).is_some());
        assert!(unsupported_native_command(&args(ClientKind::Codex, &["--", command])).is_some());
    }
    assert!(
        unsupported_native_command(&args(ClientKind::Codex, &["exec", "explain cloud"])).is_none()
    );
    assert!(unsupported_native_command(&args(ClientKind::ClaudeCode, &["cloud"])).is_none());
}

/// Claude Code 2.1.263 resolves authentication once for the whole process.
/// A Router bearer therefore makes every Claude.ai-only operation fail even
/// when the untouched stored login has the required scopes (issue #520).
/// Reject explicit requests before server discovery or token minting instead
/// of launching a client that cannot perform what was requested.
#[test]
fn claude_ai_only_operations_are_rejected_before_launch() {
    for arguments in [
        vec!["remote-control"],
        vec!["--remote-control"],
        vec!["--remote-control=work"],
        vec!["--rc"],
        vec!["--cloud", "audit"],
        vec!["--cloud=session_synthetic"],
        vec!["--environment", "ccpool_synthetic"],
        vec!["--teleport", "session_synthetic"],
        vec!["ultrareview", "main"],
        vec!["--", "--remote-control"],
    ] {
        let error = unsupported_native_command(&args(ClientKind::ClaudeCode, &arguments))
            .unwrap_or_else(|| panic!("{arguments:?} must fail before launch"));
        assert!(error.contains("Claude.ai"), "{arguments:?}: {error}");
        assert!(
            error.contains("no Router token was minted"),
            "{arguments:?}: {error}"
        );
    }
}

#[test]
fn ordinary_claude_inference_arguments_remain_routable() {
    for arguments in [
        vec!["fix the tests"],
        vec!["--model", "sonnet", "fix the tests"],
        vec!["--resume", "local-session"],
        vec!["--chrome", "fix the tests"],
        vec!["mcp", "list"],
    ] {
        assert!(
            unsupported_native_command(&args(ClientKind::ClaudeCode, &arguments)).is_none(),
            "{arguments:?} is not an explicit Claude.ai-only operation"
        );
    }
}

#[test]
fn codex_cloud_is_found_after_every_current_root_option_shape() {
    for arguments in [
        vec!["--profile", "audit", "cloud", "list"],
        vec!["--profile=audit", "cloud", "list"],
        vec!["-c", "model='gpt-5'", "cloud", "list"],
        vec!["-cmodel='gpt-5'", "cloud", "list"],
        vec!["--config", "model='gpt-5'", "cloud-tasks", "list"],
        vec!["--enable", "feature-name", "cloud", "list"],
        vec!["--disable=feature-name", "cloud-tasks", "list"],
        vec!["--search", "--oss", "--profile", "audit", "cloud", "list"],
        vec!["--", "cloud", "list"],
    ] {
        assert!(
            unsupported_native_command(&args(ClientKind::Codex, &arguments)).is_some(),
            "{arguments:?}"
        );
    }
}

#[test]
fn codex_cloud_words_used_as_option_values_or_prompts_are_not_commands() {
    for arguments in [
        vec!["--profile", "cloud", "exec", "task"],
        vec!["-c", "cloud", "exec", "task"],
        vec!["--enable", "cloud", "exec", "task"],
        vec!["exec", "explain cloud"],
        vec!["--unknown-option", "cloud", "exec", "task"],
    ] {
        assert!(
            unsupported_native_command(&args(ClientKind::Codex, &arguments)).is_none(),
            "{arguments:?}"
        );
    }
}

/// The defect in the issue #297 follow-up: for four clients the injected mode
/// argument takes the prompt as its *value*, and it was inserted immediately
/// before whatever the user passed. With a flag there, that flag landed where
/// the prompt belongs — Claude Code fails loudly, these four risk the next
/// argument being read as prompt text.
#[test]
fn a_mode_argument_that_takes_a_prompt_is_not_placed_before_a_flag() {
    for client in [
        ClientKind::GeminiCli,
        ClientKind::GrokCli,
        ClientKind::QwenCode,
        ClientKind::Agent,
    ] {
        assert!(
            client.integration().non_interactive_arg_takes_a_value,
            "{client} spells its mode as a flag taking the prompt"
        );
        let mut one_shot = args(client, &["--yolo"]);
        one_shot.non_interactive = true;
        let launch = plan(&one_shot, None, true);
        let rendered = rendered(&launch);
        let mode = client
            .integration()
            .non_interactive_arg
            .expect("these clients have one");
        assert!(
            !rendered
                .windows(2)
                .any(|pair| pair[0] == mode && pair[1] == "--yolo"),
            "{client}: the user's flag was placed where the prompt value belongs: {rendered:?}"
        );
        assert!(
            launch.note.is_some(),
            "{client}: a mode that could not be applied must say so"
        );
    }
}

/// With a prompt present the mode is applied as before, and the prompt follows
/// it immediately — which is what makes the value placement correct.
#[test]
fn a_prompt_still_gets_the_mode_argument() {
    let launch = plan(&args(ClientKind::GeminiCli, &["fix the tests"]), None, true);
    let rendered = rendered(&launch);
    assert!(
        rendered
            .windows(2)
            .any(|pair| pair == ["-p", "fix the tests"]),
        "{rendered:?}"
    );
}

/// A mode the user already asked for is not asked for again. The comparison
/// was exact against one string, so Claude Code's own `-p` was not recognised
/// as the `--print` it is and both ended up on the command line (issue #297).
#[test]
fn a_mode_the_user_already_spelled_is_not_repeated() {
    let rendered = argv(ClientKind::ClaudeCode, &["-p", "hi"]);
    assert!(
        !rendered.iter().any(|value| value == "--print"),
        "the mode was added on top of the user's own spelling: {rendered:?}"
    );
    assert_eq!(rendered, ["-p", "hi"], "{rendered:?}");
}

/// Codex refuses to run outside a git repository because that check is what
/// stops an agent editing a directory with nothing to diff and nothing to
/// revert. The router turned it off for every run it supplied `exec` for, and
/// left it on when the user typed `exec` themselves (issue #310).
#[test]
fn the_clients_own_git_guard_is_left_alone() {
    for forwarded in [&["fix the tests"][..], &["exec", "fix the tests"]] {
        let rendered = argv(ClientKind::Codex, forwarded);
        assert!(
            !rendered
                .iter()
                .any(|value| value == "--skip-git-repo-check"),
            "{forwarded:?}: {rendered:?}"
        );
    }
}

/// The per-run token outlives the session it was minted for.
///
/// `with` launches an interactive client and stays attached for as long as the
/// user works, so a one-hour token was guaranteed to expire in use — the only
/// question was how far in. The token is revoked when the client exits, so the
/// run already bounds its life and the clock was a second bound that could
/// only ever fire early (issue #341).
#[test]
fn the_per_run_token_outlives_an_ordinary_session() {
    use clap::Parser as _;

    let parsed = crate::cli::Cli::try_parse_from(["router", "with", "claude"])
        .expect("a bare launch parses");
    let Some(crate::cli::Command::With(args)) = parsed.command else {
        panic!("with is the command");
    };
    assert!(
        args.run_ttl_hours >= 12,
        "a coding session routinely runs for hours; {} is short enough to expire in use",
        args.run_ttl_hours
    );

    // And the flag still overrides it, for a caller who wants a tighter bound.
    let parsed =
        crate::cli::Cli::try_parse_from(["router", "with", "--run-ttl-hours", "2", "claude"])
            .expect("the flag parses");
    let Some(crate::cli::Command::With(args)) = parsed.command else {
        panic!("with is the command");
    };
    assert_eq!(args.run_ttl_hours, 2, "an explicit lifetime is honoured");
}