-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathconfig.ts
More file actions
executable file
·2208 lines (2108 loc) · 86.3 KB
/
Copy pathconfig.ts
File metadata and controls
executable file
·2208 lines (2108 loc) · 86.3 KB
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {
ApprovalMode,
AuthType,
Config,
DEFAULT_QWEN_EMBEDDING_MODEL,
FileDiscoveryService,
getAllGeminiMdFilenames,
loadServerHierarchicalMemory,
type LoadServerHierarchicalMemoryOptions,
type LoadServerHierarchicalMemoryResponse,
setGeminiMdFilename as setServerGeminiMdFilename,
resolveTelemetrySettings,
FatalConfigError,
Storage,
InputFormat,
OutputFormat,
SessionService,
ideContextStore,
type ResumedSessionData,
type LspClient,
type ToolName,
ToolNames,
NativeLspClient,
createDebugLogger,
NativeLspService,
isBareMode,
isSafeModeEnv,
isToolEnabled,
isTlsVerificationDisabled,
SchemaValidator,
type ConfigParameters,
type MCPServerConfig,
} from '@qwen-code/qwen-code-core';
import { extensionsCommand } from '../commands/extensions.js';
import { hooksCommand } from '../commands/hooks.js';
import { normalizeDisabledToolList } from './normalizeDisabledTools.js';
import type { LoadedSettings, Settings } from './settings.js';
import { loadSettings, SettingScope } from './settings.js';
import {
resolveCliGenerationConfig,
getAuthTypeFromEnv,
} from '../utils/modelConfigUtils.js';
import yargs, { type Argv } from 'yargs';
import { hideBin } from 'yargs/helpers';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { homedir } from 'node:os';
import { randomUUID } from 'node:crypto';
import stripJsonComments from 'strip-json-comments';
import { resolvePath } from '../utils/resolvePath.js';
import { getCliVersion } from '../utils/version.js';
import { loadSandboxConfig } from './sandboxConfig.js';
import { appEvents } from '../utils/events.js';
import { mcpCommand } from '../commands/mcp.js';
import { channelCommand } from '../commands/channel.js';
import { authCommand } from '../commands/auth.js';
import { reviewCommand } from '../commands/review.js';
import { serveCommand } from '../commands/serve.js';
import { sessionsCommand } from '../commands/sessions.js';
// UUID v4 regex pattern for validation
const SESSION_ID_REGEX =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}(-agent-[a-zA-Z0-9_.-]+)?$/i;
/**
* Validates if a string is a valid session ID format.
* Accepts a standard UUID, or a UUID followed by `-agent-{suffix}`
* (used by Arena to give each agent a deterministic session ID).
*/
export function isValidSessionId(value: string): boolean {
return SESSION_ID_REGEX.test(value);
}
import { isWorkspaceTrusted } from './trustedFolders.js';
import { assembleMcpServers } from './mcpServers.js';
import { getPendingGatedMcpServers } from './mcpApprovals.js';
import { writeStderrLine } from '../utils/stdioHelpers.js';
import {
parseDurationSeconds,
validateMaxToolCalls,
validateMaxWallTimeSetting,
} from '../utils/runBudget.js';
import { detectSystemLanguage } from '../i18n/index.js';
const debugLogger = createDebugLogger('CONFIG');
function resolveLocaleForExtensions(settings: Settings): string {
const envLang = process.env['QWEN_CODE_LANG'];
if (envLang) return envLang;
const settingsLang = settings.general?.language as string | undefined;
if (settingsLang && settingsLang !== 'auto') return settingsLang;
return detectSystemLanguage();
}
const VALID_APPROVAL_MODE_VALUES = [
'plan',
'default',
'auto-edit',
'auto',
'yolo',
] as const;
function formatApprovalModeError(value: string): Error {
return new Error(
`Invalid approval mode: ${value}. Valid values are: ${VALID_APPROVAL_MODE_VALUES.join(
', ',
)}`,
);
}
function parseApprovalModeValue(value: string): ApprovalMode {
const normalized = value.trim().toLowerCase();
switch (normalized) {
case 'plan':
return ApprovalMode.PLAN;
case 'default':
return ApprovalMode.DEFAULT;
case 'yolo':
return ApprovalMode.YOLO;
case 'auto_edit':
case 'autoedit':
case 'auto-edit':
return ApprovalMode.AUTO_EDIT;
case 'auto':
return ApprovalMode.AUTO;
default:
throw formatApprovalModeError(value);
}
}
export interface CliArgs {
query: string | undefined;
model: string | undefined;
sandbox: boolean | string | undefined;
sandboxImage: string | undefined;
debug: boolean | undefined;
prompt: string | undefined;
promptInteractive: string | undefined;
systemPrompt: string | undefined;
appendSystemPrompt: string | undefined;
yolo: boolean | undefined;
bare: boolean | undefined;
safeMode?: boolean | undefined;
approvalMode: string | undefined;
telemetry: boolean | undefined;
telemetryTarget: string | undefined;
telemetryOtlpEndpoint: string | undefined;
telemetryOtlpProtocol: string | undefined;
telemetryLogPrompts: boolean | undefined;
telemetryOutfile: string | undefined;
allowedMcpServerNames: string[] | undefined;
mcpConfig: string | undefined;
allowedTools: string[] | undefined;
acp: boolean | undefined;
experimentalAcp: boolean | undefined;
experimentalLsp: boolean | undefined;
extensions: string[] | undefined;
listExtensions: boolean | undefined;
openaiLogging: boolean | undefined;
openaiApiKey: string | undefined;
openaiBaseUrl: string | undefined;
openaiLoggingDir: string | undefined;
proxy: string | undefined;
insecure?: boolean | undefined;
includeDirectories: string[] | undefined;
screenReader: boolean | undefined;
inputFormat?: string | undefined;
outputFormat: string | undefined;
includePartialMessages?: boolean;
/**
* If chat recording is disabled, the chat history would not be recorded,
* so --continue and --resume would not take effect.
*/
chatRecording: boolean | undefined;
/** Resume the most recent session for the current project */
continue: boolean | undefined;
/** Resume a specific session by its ID */
resume: string | undefined;
/** Specify a session ID without session resumption */
sessionId: string | undefined;
/**
* Create a new forked session from the resumed session. Must be used with
* --resume or --continue.
*/
forkSession?: boolean | undefined;
/** Internal: preserve the outer session ID when relaunching in a sandbox */
sandboxSessionId?: string | undefined;
/**
* Start the session inside a git worktree. Accepted forms:
* - bare `--worktree` (empty string from yargs) → auto-generated slug
* - `--worktree foo` / `--worktree=foo` → explicit slug
* - `--worktree=#123` / `--worktree https://github.com/o/r/pull/123` → PR ref
*
* Consumed by `setupStartupWorktree()` before `loadCliConfig()`. When set,
* the CLI chdirs into `<repoRoot>/.qwen/worktrees/<slug>/` and the entire
* session runs inside that worktree.
*/
worktree?: string | undefined;
maxSessionTurns: number | undefined;
maxWallTime: string | undefined;
maxToolCalls: number | undefined;
coreTools: string[] | undefined;
excludeTools: string[] | undefined;
disabledSlashCommands: string[] | undefined;
authType: string | undefined;
channel: string | undefined;
jsonFd?: number | undefined;
jsonFile?: string | undefined;
jsonSchema?: string | undefined;
inputFile?: string | undefined;
}
/**
* Returns true if the root of the given schema can accept a JSON object.
*
* JSON Schema applies sibling keywords conjunctively, so `type`, `anyOf`,
* `oneOf`, and `allOf` at the same level must EACH allow an object — they
* can't rescue one another. For example, `{type:"object", anyOf:[{type:"string"}]}`
* is unsatisfiable for any value because `type` requires object while
* `anyOf` requires string. Walk all four rather than returning on the
* first hit.
*
* For `anyOf` / `oneOf`, at least one branch must admit object (a value
* only has to match one branch). For `allOf`, every branch must admit
* object (a value has to match all of them). Root `$ref` is rejected
* unconditionally — Ajv applies `$ref` conjunctively with sibling
* keywords, so even `{type:"object", $ref:"#/$defs/Foo"}` is
* unsatisfiable when `Foo` resolves to a non-object schema. We don't
* follow refs ourselves (local-only resolution would still need to
* handle remote / recursive refs) so users wanting composition should
* inline the schema at the root or use `allOf`.
*
* The `$ref` rejection is **root-only**. Sub-schemas inside `anyOf` /
* `oneOf` / `allOf` recurse with `isRoot=false`, where a `$ref` is
* treated as opaque (assume-object-compatible) and deferred to Ajv at
* runtime — otherwise common composition shapes like
* `{anyOf:[{$ref:"#/$defs/Foo"}, {type:"string"}]}` would be wrongly
* rejected at parse time even though Ajv can resolve them.
*/
function schemaRootAcceptsObject(
schema: Record<string, unknown>,
isRoot = true,
): boolean {
if (isRoot && typeof schema['$ref'] === 'string') {
// Reject any root `$ref`. The previous "accept when sibling
// `type:"object"` is present" carve-out was unsound: Ajv applies
// both keywords, so `{type:"object", $ref:"#/$defs/Foo",
// $defs:{Foo:{type:"array"}}}` parses fine but no object argument
// can satisfy both at runtime — the model would loop forever on
// validation failures.
return false;
}
const rawType = schema['type'];
const typeIncludesObject =
rawType !== undefined &&
(Array.isArray(rawType) ? rawType : [rawType]).includes('object');
if (rawType !== undefined && !typeIncludesObject) {
return false;
}
// Root `const` / `enum` pin the value to specific literals. If those
// literals can never be a JSON object (e.g. `{const: 1}` or
// `{enum: ["a", "b"]}`), no object satisfies the schema — reject.
if ('const' in schema) {
const constVal = schema['const'];
if (
typeof constVal !== 'object' ||
constVal === null ||
Array.isArray(constVal)
) {
return false;
}
}
const enumVal = schema['enum'];
if (Array.isArray(enumVal)) {
const anyObjectMember = enumVal.some(
(v) => typeof v === 'object' && v !== null && !Array.isArray(v),
);
if (!anyObjectMember) return false;
}
// JSON Schema (draft-06+) treats `true` and `false` as valid subschemas
// for any keyword that accepts a schema: `true` matches every value,
// `false` matches nothing. Honour those alongside object subschemas so
// shapes like `{anyOf:[true]}` or `{allOf:[true,{type:"object"}]}` pass
// and `{anyOf:[false]}` is rejected.
const variantAcceptsObject = (v: unknown): boolean => {
if (v === true) return true;
if (v === false) return false;
if (typeof v === 'object' && v !== null && !Array.isArray(v)) {
// isRoot=false: nested branches don't trigger the root-only `$ref`
// rejection — the parent's keyword scope already pins the
// sub-schema's role to "candidate value type", and Ajv will
// resolve the ref at runtime.
return schemaRootAcceptsObject(v as Record<string, unknown>, false);
}
return false;
};
for (const key of ['anyOf', 'oneOf'] as const) {
const variants = schema[key];
if (Array.isArray(variants)) {
// Empty anyOf/oneOf is unsatisfiable per JSON Schema — no value can
// match a member of an empty union. Reject rather than treating it
// as "no constraint".
if (variants.length === 0) return false;
if (!variants.some(variantAcceptsObject)) return false;
}
}
const allOf = schema['allOf'];
if (Array.isArray(allOf) && allOf.length > 0) {
// allOf is conjunctive — `false` in any branch makes the schema
// unsatisfiable, `true` is neutral.
if (!allOf.every(variantAcceptsObject)) return false;
}
// Best-effort `not` handling: when `not` directly forbids object via its
// own `type` keyword (e.g. `{not:{type:"object"}}` or
// `{not:{type:["object","null"]}}`), the schema can never be satisfied
// by an object — reject. We don't try to do full satisfiability analysis
// for arbitrary `not` schemas (e.g. `not:{const:"foo"}` is fine, but
// `not:{anyOf:[{type:"object"},…]}` would also reject objects); those
// fall through to Ajv at runtime.
const notSchema = schema['not'];
if (
typeof notSchema === 'object' &&
notSchema !== null &&
!Array.isArray(notSchema)
) {
const notRecord = notSchema as Record<string, unknown>;
const notType = notRecord['type'];
if (notType !== undefined) {
const types = Array.isArray(notType) ? notType : [notType];
// If `not` is JUST `{type: "object"[…]}` (no additional keywords),
// every object value matches the `not` subschema and so gets
// excluded — schema is unsatisfiable for objects, reject.
//
// If `not` has additional constraints alongside `type` (e.g.
// `{not:{type:"object",required:["error"]}}`), those constraints
// NARROW what `not` excludes: only objects matching ALL of `not`'s
// keywords are rejected, so objects that fail any of the
// narrowing constraints survive. Example: `{}` satisfies
// `{not:{type:"object",required:["error"]}}` because the value
// lacks the `error` key. Rejecting at parse time would be a
// false positive — defer to Ajv at runtime.
if (types.includes('object') && Object.keys(notRecord).length === 1) {
return false;
}
}
}
// Best-effort `if/then/else` handling for the decidable cases. The
// semantics: if the value matches `if`, it must match `then`; otherwise
// it must match `else` (defaults to `true`). For root-acceptance we can
// only decide statically when `if` is itself a constant boolean
// subschema:
// `if: true` → every object matches `if`, so it MUST match `then`.
// `if: false` → no value matches `if`, so it must match `else`.
// Other shapes for `if` (object schemas) depend on the candidate value
// and fall through to Ajv at runtime — we can't decide acceptance
// without seeing the value.
if ('if' in schema) {
const ifSchema = schema['if'];
if (ifSchema === true) {
// Object MUST match `then` (if absent, defaults to `true`, no
// constraint on root acceptance).
const thenSchema = schema['then'];
if (thenSchema !== undefined && !variantAcceptsObject(thenSchema)) {
return false;
}
} else if (ifSchema === false) {
// Object MUST match `else` (if absent, defaults to `true`).
const elseSchema = schema['else'];
if (elseSchema !== undefined && !variantAcceptsObject(elseSchema)) {
return false;
}
}
// ifSchema is an object schema — runtime Ajv decides; do nothing.
}
// No narrowing at the root — lenient default, treated as object-compatible.
return true;
}
/** 4 MiB — well above any real schema, well below an accidental
* gigabyte-sized file that would OOM `fs.readFileSync` + `JSON.parse`.
*/
const MAX_JSON_SCHEMA_FILE_BYTES = 4 * 1024 * 1024;
/**
* Resolves the `--json-schema` argument into a parsed JSON Schema object.
*
* Accepts either a JSON literal or `@path/to/schema.json`. Fails fast with a
* FatalConfigError if the input can't be read/parsed/compiled — invalid
* schemas should not silently skip validation at runtime.
*/
export function resolveJsonSchemaArg(
raw: string | undefined,
): Record<string, unknown> | undefined {
if (raw === undefined) {
return undefined;
}
const trimmed = raw.trim();
if (trimmed.length === 0) {
throw new FatalConfigError('--json-schema cannot be empty.');
}
let payload: string;
let payloadSource: 'inline' | 'file' = 'inline';
let payloadSourcePath: string | undefined;
if (trimmed.startsWith('@')) {
const resolvedPath = resolvePath(trimmed.slice(1));
payloadSource = 'file';
payloadSourcePath = resolvedPath;
try {
// Stat first so we can refuse non-regular files (directories,
// character devices like `/dev/zero`, FIFOs that would block
// synchronously) and cap by size before pulling bytes into memory.
// The cap (`MAX_JSON_SCHEMA_FILE_BYTES`) is set well above any real
// schema and well below an accidental gigabyte-sized file that
// would OOM `fs.readFileSync` + `JSON.parse`.
const stat = fs.statSync(resolvedPath);
if (!stat.isFile()) {
throw new FatalConfigError(
`--json-schema "@${resolvedPath}" must be a regular file.`,
);
}
if (stat.size > MAX_JSON_SCHEMA_FILE_BYTES) {
throw new FatalConfigError(
`--json-schema file "${resolvedPath}" is ${stat.size} bytes ` +
`(>${MAX_JSON_SCHEMA_FILE_BYTES}). Refusing to read; this is ` +
'almost certainly a wrong-path argument. Schemas should be ' +
'small enough to fit in a few KiB; decompose with `$ref` if ' +
'you need a large family of types.',
);
}
payload = fs.readFileSync(resolvedPath, 'utf8');
} catch (err) {
if (err instanceof FatalConfigError) throw err;
throw new FatalConfigError(
`--json-schema could not read "${resolvedPath}": ${
err instanceof Error ? err.message : String(err)
}`,
);
}
} else {
payload = trimmed;
}
let parsed: unknown;
try {
parsed = JSON.parse(payload);
} catch (err) {
// For inline JSON the user IS the source — echoing the SyntaxError
// (which on Node ≥18 embeds a 10-char input snippet) is fine. For
// @path, the error message would leak a prefix of the file's bytes
// through stderr to whatever wrapping process surfaces it; emit a
// generic message instead.
if (payloadSource === 'file') {
throw new FatalConfigError(
`--json-schema content of "${payloadSourcePath}" is not valid JSON.`,
);
}
throw new FatalConfigError(
`--json-schema is not valid JSON: ${
err instanceof Error ? err.message : String(err)
}`,
);
}
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
throw new FatalConfigError(
'--json-schema must be a JSON object describing a schema.',
);
}
// The schema will be installed as a TOOL PARAMETER schema. All function-
// calling APIs (Gemini/OpenAI/Anthropic) require tool arguments to be a
// JSON object, so a schema that cannot accept objects registers an
// unusable synthetic tool the model could never satisfy. `schemaRootAcceptsObject`
// walks `type`/`const`/`enum`/`anyOf`/`oneOf`/`allOf`/`not`/`if` (with
// best-effort decidable cases for the harder shapes); the strict Ajv
// compile below catches structural validity. The two together cover both
// "schema can be parsed" and "schema can be satisfied by an object value".
if (!schemaRootAcceptsObject(parsed as Record<string, unknown>)) {
throw new FatalConfigError(
'--json-schema root must accept object-typed values (tool parameters ' +
'are always JSON objects). At least one branch of a root anyOf/oneOf ' +
'must be satisfiable by an object, and a root `type` (when present) ' +
'must include "object".',
);
}
// Ajv compile-time validation. SchemaValidator.validate is deliberately
// lenient at runtime (falls back to no-op on compile failure to support
// exotic MCP schemas) — but `--json-schema` is explicit user intent, so
// surface a bad schema here rather than letting it silently no-op later.
const compileError = SchemaValidator.compileStrict(parsed);
if (compileError) {
throw new FatalConfigError(
`--json-schema is not a valid JSON Schema: ${compileError}`,
);
}
return parsed as Record<string, unknown>;
}
function normalizeOutputFormat(
format: string | OutputFormat | undefined,
): OutputFormat | undefined {
if (!format) {
return undefined;
}
if (format === OutputFormat.STREAM_JSON) {
return OutputFormat.STREAM_JSON;
}
if (format === 'json' || format === OutputFormat.JSON) {
return OutputFormat.JSON;
}
return OutputFormat.TEXT;
}
export async function parseArguments(): Promise<CliArgs> {
let rawArgv = hideBin(process.argv);
// hack: if the first argument is the CLI entry point, remove it
if (
rawArgv.length > 0 &&
(rawArgv[0].endsWith('/dist/qwen-cli/cli.js') ||
rawArgv[0].endsWith('/dist/cli.js') ||
rawArgv[0].endsWith('/dist/cli/cli.js'))
) {
rawArgv = rawArgv.slice(1);
}
const yargsInstance = yargs(rawArgv)
.locale('en')
.scriptName('qwen')
.usage(
'Usage: qwen [options] [command]\n\nQwen Code - Launch an interactive CLI, use -p/--prompt for non-interactive mode',
)
.option('telemetry', {
type: 'boolean',
description:
'Enable telemetry? This flag specifically controls if telemetry is sent. Other --telemetry-* flags set specific values but do not enable telemetry on their own.',
})
.option('telemetry-target', {
type: 'string',
choices: ['local', 'gcp'],
description:
'Set the telemetry target (local or gcp). Overrides settings files.',
})
.option('telemetry-otlp-endpoint', {
type: 'string',
description:
'Set the OTLP endpoint for telemetry. Overrides environment variables and settings files.',
})
.option('telemetry-otlp-protocol', {
type: 'string',
choices: ['grpc', 'http'],
description:
'Set the OTLP protocol for telemetry (grpc or http). Overrides settings files.',
})
.option('telemetry-log-prompts', {
type: 'boolean',
description:
'Enable or disable logging of user prompts for telemetry. Overrides settings files.',
})
.option('telemetry-outfile', {
type: 'string',
description: 'Redirect all telemetry output to the specified file.',
})
.deprecateOption(
'telemetry',
'Use the "telemetry.enabled" setting in settings.json instead. This flag will be removed in a future version.',
)
.deprecateOption(
'telemetry-target',
'Use the "telemetry.target" setting in settings.json instead. This flag will be removed in a future version.',
)
.deprecateOption(
'telemetry-otlp-endpoint',
'Use the "telemetry.otlpEndpoint" setting in settings.json instead. This flag will be removed in a future version.',
)
.deprecateOption(
'telemetry-otlp-protocol',
'Use the "telemetry.otlpProtocol" setting in settings.json instead. This flag will be removed in a future version.',
)
.deprecateOption(
'telemetry-log-prompts',
'Use the "telemetry.logPrompts" setting in settings.json instead. This flag will be removed in a future version.',
)
.deprecateOption(
'telemetry-outfile',
'Use the "telemetry.outfile" setting in settings.json instead. This flag will be removed in a future version.',
)
.option('debug', {
alias: 'd',
type: 'boolean',
description: 'Run in debug mode?',
default: false,
})
.option('bare', {
type: 'boolean',
description:
'Minimal mode: skip implicit startup auto-discovery and only honor explicitly provided CLI inputs.',
default: false,
})
.option('safe-mode', {
type: 'boolean',
description:
'Disable all customizations (context files, hooks, extensions, skills, MCP servers) for troubleshooting.',
})
.option('proxy', {
type: 'string',
description: 'Proxy for Qwen Code, like schema://user:password@host:port',
})
.deprecateOption(
'proxy',
'Use the "proxy" setting in settings.json instead. This flag will be removed in a future version.',
)
.option('insecure', {
type: 'boolean',
description:
'Skip TLS certificate verification for API connections (for self-signed certs in trusted/lab environments). Equivalent to setting QWEN_TLS_INSECURE=1. WARNING: removes protection against man-in-the-middle attacks.',
default: false,
})
.option('chat-recording', {
type: 'boolean',
description:
'Enable chat recording to disk. If false, chat history is not saved and --continue/--resume will not work.',
})
.command('$0 [query..]', 'Launch Qwen Code CLI', (yargsInstance: Argv) =>
yargsInstance
.positional('query', {
description:
'Positional prompt. Defaults to one-shot; use -i/--prompt-interactive for interactive.',
})
.option('model', {
alias: 'm',
type: 'string',
description: `Model`,
})
.option('prompt', {
alias: 'p',
type: 'string',
description: 'Prompt. Appended to input on stdin (if any).',
})
.option('prompt-interactive', {
alias: 'i',
type: 'string',
description:
'Execute the provided prompt and continue in interactive mode',
})
.option('system-prompt', {
type: 'string',
description:
'Override the main session system prompt for this run. Can be combined with --append-system-prompt.',
})
.option('append-system-prompt', {
type: 'string',
description:
'Append instructions to the main session system prompt for this run. Can be combined with --system-prompt.',
})
.option('sandbox', {
alias: 's',
type: 'boolean',
description: 'Run in sandbox?',
})
.option('sandbox-image', {
type: 'string',
description: 'Sandbox image URI.',
})
.option('yolo', {
alias: 'y',
type: 'boolean',
description:
'Automatically accept all actions (aka YOLO mode, see https://www.youtube.com/watch?v=xvFZjo5PgG0 for more details)?',
default: false,
})
.option('approval-mode', {
type: 'string',
choices: ['plan', 'default', 'auto-edit', 'auto', 'yolo'],
description:
'Set the approval mode: plan (plan only), default (prompt for approval), auto-edit (auto-approve edit tools), auto (LLM classifier auto-approves safe actions, blocks risky ones), yolo (auto-approve all tools)',
})
.option('acp', {
type: 'boolean',
description: 'Starts the agent in ACP mode',
})
.option('experimental-acp', {
type: 'boolean',
description:
'Starts the agent in ACP mode (deprecated, use --acp instead)',
hidden: true,
})
.option('experimental-skills', {
type: 'boolean',
description:
'Deprecated: Skills are now enabled by default. This flag is ignored.',
hidden: true,
})
.option('experimental-lsp', {
type: 'boolean',
description:
'Enable experimental LSP (Language Server Protocol) feature for code intelligence',
default: false,
})
.option('channel', {
type: 'string',
choices: ['VSCode', 'ACP', 'SDK', 'CI', 'desktop'],
description: 'Channel identifier (VSCode, ACP, SDK, CI, desktop)',
})
.option('allowed-mcp-server-names', {
type: 'array',
string: true,
description: 'Allowed MCP server names',
coerce: (mcpServerNames: string[]) =>
// Handle comma-separated values
mcpServerNames.flatMap((mcpServerName) =>
mcpServerName.split(',').map((m) => m.trim()),
),
})
.option('mcp-config', {
type: 'string',
description:
'MCP server configuration as JSON string or file path. Can be a path to a JSON file or inline JSON with {"mcpServers": {...}} format.',
})
.option('allowed-tools', {
type: 'array',
string: true,
description: 'Tools that are allowed to run without confirmation',
coerce: (tools: string[]) =>
// Handle comma-separated values
tools.flatMap((tool) => tool.split(',').map((t) => t.trim())),
})
.option('extensions', {
alias: 'e',
type: 'array',
string: true,
description:
'A list of extensions to use. If not provided, all extensions are used.',
coerce: (extensions: string[]) =>
// Handle comma-separated values
extensions.flatMap((extension) =>
extension.split(',').map((e) => e.trim()),
),
})
.option('list-extensions', {
alias: 'l',
type: 'boolean',
description: 'List all available extensions and exit.',
})
.option('include-directories', {
alias: 'add-dir',
type: 'array',
string: true,
description:
'Additional directories to include in the workspace (comma-separated or multiple --include-directories)',
coerce: (dirs: string[]) =>
// Handle comma-separated values
dirs.flatMap((dir) => dir.split(',').map((d) => d.trim())),
})
.option('openai-logging', {
type: 'boolean',
description:
'Enable logging of OpenAI API calls for debugging and analysis',
})
.option('openai-logging-dir', {
type: 'string',
description:
'Custom directory path for OpenAI API logs. Overrides settings files.',
})
.option('openai-api-key', {
type: 'string',
description: 'OpenAI API key to use for authentication',
})
.option('openai-base-url', {
type: 'string',
description: 'OpenAI base URL (for custom endpoints)',
})
.option('screen-reader', {
type: 'boolean',
description: 'Enable screen reader mode for accessibility.',
})
.option('input-format', {
type: 'string',
choices: ['text', 'stream-json'],
description: 'The format consumed from standard input.',
default: 'text',
})
.option('output-format', {
alias: 'o',
type: 'string',
description: 'The format of the CLI output.',
choices: ['text', 'json', 'stream-json'],
})
.option('include-partial-messages', {
type: 'boolean',
description:
'Include partial assistant messages when using stream-json output.',
default: false,
})
.option('json-fd', {
type: 'number',
description:
'File descriptor for structured JSON event output (dual output mode). ' +
'The TUI renders normally on stdout while JSON events are written to this fd. ' +
'The caller must provide this fd via spawn stdio configuration.',
})
.option('json-file', {
type: 'string',
description:
'File path for structured JSON event output (dual output mode). ' +
'Can be a regular file, FIFO (named pipe), or /dev/fd/N.',
})
.option('json-schema', {
type: 'string',
description:
"JSON Schema that the model's final output must conform to " +
'(headless mode only). Accepts a JSON literal or "@path/to/schema.json". ' +
'Registers a synthetic `structured_output` tool; the session ends on ' +
'the first valid call.',
})
.option('input-file', {
type: 'string',
description:
'File path for receiving remote input commands (bidirectional sync). ' +
'An external process writes JSONL commands; the TUI watches and processes them.',
})
.option('continue', {
alias: 'c',
type: 'boolean',
description:
'Resume the most recent session for the current project.',
default: false,
})
.option('resume', {
alias: 'r',
type: 'string',
description:
'Resume a specific session by its ID. Use without an ID to show session picker.',
})
.option('session-id', {
type: 'string',
description: 'Specify a session ID for this run.',
})
.option('fork-session', {
type: 'boolean',
description:
'Create a new forked session from the resumed session. Must be used with --resume or --continue.',
default: false,
})
.option('sandbox-session-id', {
type: 'string',
hidden: true,
})
.option('worktree', {
type: 'string',
description:
'Start the session inside a git worktree at <repoRoot>/.qwen/worktrees/<slug>/. ' +
'Pass a slug (`--worktree my-feature`), a PR reference (`--worktree=#123` or a full ' +
'GitHub pull-request URL), or use bare `--worktree` to auto-generate a slug. ' +
'On exit, the WorktreeExitDialog prompts to keep or remove the worktree.',
})
.option('max-session-turns', {
type: 'number',
description: 'Maximum number of session turns',
})
.option('max-wall-time', {
type: 'string',
description:
'Run-level wall-clock budget for headless / unattended runs. Accepts seconds (e.g. `90`), or a duration string with unit (e.g. `30s`, `5m`, `1h`, `1.5h`). Minimum 1s — sub-second values (`500ms`, `0.5`) are rejected as typos; max ~24 days. Aborts the run with exit code 55 when exceeded.',
})
.option('max-tool-calls', {
type: 'number',
description:
'Maximum cumulative tool calls executed during the run (success or failure; `structured_output` under --json-schema is exempt). Aborts with exit code 55 when exceeded. -1 / unset means no limit; 0 means "no tool calls allowed" (first call aborts). Capped at 1,000,000 to catch typos.',
})
.option('core-tools', {
type: 'array',
string: true,
description: 'Core tool paths',
coerce: (tools: string[]) =>
tools.flatMap((tool) => tool.split(',').map((t) => t.trim())),
})
.option('exclude-tools', {
type: 'array',
string: true,
description: 'Tools to exclude',
coerce: (tools: string[]) =>
tools.flatMap((tool) => tool.split(',').map((t) => t.trim())),
})
.option('disabled-slash-commands', {
type: 'array',
string: true,
description:
'Slash command names to hide/disable (comma-separated or ' +
'repeated). Merged with the `slashCommands.disabled` setting ' +
'and QWEN_DISABLED_SLASH_COMMANDS. Matched case-insensitively ' +
'against the final command name.',
coerce: (names: string[]) =>
names.flatMap((n) => n.split(',').map((t) => t.trim())),
})
.option('allowed-tools', {
type: 'array',
string: true,
description: 'Tools to allow, will bypass confirmation',
coerce: (tools: string[]) =>
tools.flatMap((tool) => tool.split(',').map((t) => t.trim())),
})
.option('auth-type', {
type: 'string',
choices: [
AuthType.USE_OPENAI,
AuthType.USE_ANTHROPIC,
AuthType.QWEN_OAUTH,
AuthType.USE_GEMINI,
AuthType.USE_VERTEX_AI,
],
description: 'Authentication type',
})
.deprecateOption(
'sandbox-image',
'Use the "tools.sandboxImage" setting in settings.json instead. This flag will be removed in a future version.',
)
.deprecateOption(
'prompt',
'Use the positional prompt instead. This flag will be removed in a future version.',
)
// Ensure validation flows through .fail() for clean UX
.fail((msg: string, err: Error | undefined, yargs: Argv) => {
writeStderrLine(msg || err?.message || 'Unknown error');
yargs.showHelp();
process.exit(1);
})
.check((argv: { [x: string]: unknown }) => {
// The 'query' positional can be a string (for one arg) or string[] (for multiple).
// This guard safely checks if any positional argument was provided.
const query = argv['query'] as string | string[] | undefined;
const hasPositionalQuery = Array.isArray(query)
? query.length > 0
: !!query;
if (argv['prompt'] && hasPositionalQuery) {
return 'Cannot use both a positional prompt and the --prompt (-p) flag together';
}
if (argv['prompt'] && argv['promptInteractive']) {
return 'Cannot use both --prompt (-p) and --prompt-interactive (-i) together';
}
if (argv['yolo'] && argv['approvalMode']) {
return 'Cannot use both --yolo (-y) and --approval-mode together. Use --approval-mode=yolo instead.';
}
if (
argv['includePartialMessages'] &&
argv['outputFormat'] !== OutputFormat.STREAM_JSON
) {
return '--include-partial-messages requires --output-format stream-json';
}
if (
argv['inputFormat'] === 'stream-json' &&
argv['outputFormat'] !== OutputFormat.STREAM_JSON
) {
return '--input-format stream-json requires --output-format stream-json';
}
if (argv['continue'] && argv['resume']) {
return 'Cannot use both --continue and --resume together. Use --continue to resume the latest session, or --resume <sessionId> to resume a specific session.';
}
const hasResume = argv['resume'] !== undefined;
if (argv['sessionId'] && (argv['continue'] || hasResume)) {
return 'Cannot use --session-id with --continue or --resume. Use --session-id to start a new session with a specific ID, or use --continue/--resume to resume an existing session.';
}
if (argv['forkSession'] && !(argv['continue'] || hasResume)) {
return '--fork-session must be used with --resume or --continue.';
}
if (
argv['sandboxSessionId'] &&
(argv['sessionId'] || argv['continue'] || argv['resume'])
) {
return 'Cannot use internal --sandbox-session-id with --session-id, --continue, or --resume.';
}
if (
argv['sessionId'] &&
!isValidSessionId(argv['sessionId'] as string)
) {
return `Invalid --session-id: "${argv['sessionId']}". Must be a valid UUID (e.g., "123e4567-e89b-12d3-a456-426614174000").`;
}
if (
argv['sandboxSessionId'] &&
!isValidSessionId(argv['sandboxSessionId'] as string)