-
Notifications
You must be signed in to change notification settings - Fork 3k
Expand file tree
/
Copy pathconfig.ts
More file actions
4230 lines (3871 loc) · 148 KB
/
Copy pathconfig.ts
File metadata and controls
4230 lines (3871 loc) · 148 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
*/
// Node built-ins
import type { EventEmitter } from 'node:events';
import * as fs from 'node:fs';
import * as fsPromises from 'node:fs/promises';
import * as path from 'node:path';
import process from 'node:process';
// External dependencies
import { ProxyAgent, setGlobalDispatcher } from 'undici';
// Types
import type {
ContentGenerator,
ContentGeneratorConfig,
} from '../core/contentGenerator.js';
import type { ContentGeneratorConfigSources } from '../core/contentGenerator.js';
import type { MCPOAuthConfig } from '../mcp/oauth-provider.js';
import type { ShellExecutionConfig } from '../services/shellExecutionService.js';
import type { AnyToolInvocation } from '../tools/tools.js';
import type { ArenaManager } from '../agents/arena/ArenaManager.js';
import { ArenaAgentClient } from '../agents/arena/ArenaAgentClient.js';
// Core
import { BaseLlmClient } from '../core/baseLlmClient.js';
import { GeminiClient } from '../core/client.js';
import {
AuthType,
createContentGenerator,
resolveContentGeneratorConfigWithSources,
} from '../core/contentGenerator.js';
import { getRuntimeContentGenerator } from '../agents/runtime/agent-context.js';
// Services
import { FileDiscoveryService } from '../services/fileDiscoveryService.js';
import { FileHistoryService } from '../services/fileHistoryService.js';
import {
type FileSystemService,
StandardFileSystemService,
type FileEncodingType,
} from '../services/fileSystemService.js';
import { GitService } from '../services/gitService.js';
import { GitWorktreeService } from '../services/gitWorktreeService.js';
import { cleanupStaleAgentWorktrees } from '../services/worktreeCleanup.js';
import { CronScheduler } from '../services/cronScheduler.js';
import {
MemoryPressureMonitor,
DEFAULT_PRESSURE_CONFIG,
validateMemoryPressureConfig,
type MemoryPressureConfig,
} from '../services/memoryPressureMonitor.js';
// Tools — only lightweight imports; tool classes are lazy-loaded via dynamic import
import {
MCPServerStatus,
getMCPServerStatus,
type SendSdkMcpMessage,
} from '../tools/mcp-client.js';
import { setGeminiMdFilename } from '../memory/const.js';
import { canUseRipgrep } from '../utils/ripgrepUtils.js';
import { recordStartupEvent } from '../utils/startupEventSink.js';
import { ToolRegistry, type ToolFactory } from '../tools/tool-registry.js';
import type { McpBudgetEvent } from '../tools/mcp-client-manager.js';
import { ToolNames } from '../tools/tool-names.js';
import type { LspClient, LspStatusSnapshot } from '../lsp/types.js';
import type { InstructionLoadReason } from '../hooks/types.js';
// Other modules
import { ideContextStore } from '../ide/ideContext.js';
import { InputFormat, OutputFormat } from '../output/types.js';
import { PromptRegistry } from '../prompts/prompt-registry.js';
import { SkillManager } from '../skills/skill-manager.js';
import { PermissionManager } from '../permissions/permission-manager.js';
import {
type AutoModeDenialState,
createDenialState,
resetDenialState,
} from '../permissions/denialTracking.js';
import { SubagentManager } from '../subagents/subagent-manager.js';
import type { SubagentConfig } from '../subagents/types.js';
import { BackgroundTaskRegistry } from '../agents/background-tasks.js';
import { MonitorRegistry } from '../services/monitorRegistry.js';
import { BackgroundAgentResumeService } from '../agents/background-agent-resume.js';
import { BackgroundShellRegistry } from '../services/backgroundShellRegistry.js';
import { FileReadCache } from '../services/fileReadCache.js';
import { resolveStopHookBlockingCap } from '../hooks/stopHookCap.js';
import {
DEFAULT_OTLP_ENDPOINT,
DEFAULT_TELEMETRY_TARGET,
isTelemetrySdkInitialized,
initializeTelemetry,
shutdownTelemetry,
refreshSessionContext,
logStartSession,
logRipgrepFallback,
RipgrepFallbackEvent,
StartSessionEvent,
type TelemetryTarget,
} from '../telemetry/index.js';
import {
ExtensionManager,
type Extension,
} from '../extension/extensionManager.js';
import {
HookSystem,
createHookOutput,
createInstructionsLoadedCallback,
} from '../hooks/index.js';
import { MessageBus } from '../confirmation-bus/message-bus.js';
import {
MessageBusType,
type HookExecutionRequest,
type HookExecutionResponse,
} from '../confirmation-bus/types.js';
import {
PermissionMode,
NotificationType,
type PermissionDeniedReason,
type PermissionSuggestion,
type HookEventName,
type HookDefinition,
type PostToolBatchToolCall,
} from '../hooks/types.js';
import { fireNotificationHook } from '../core/toolHookTriggers.js';
// Utils
import { shouldAttemptBrowserLaunch } from '../utils/browser.js';
import { FileExclusions } from '../utils/ignorePatterns.js';
import { shouldDefaultToNodePty } from '../utils/shell-utils.js';
import { WorkspaceContext } from '../utils/workspaceContext.js';
import { type ToolName } from '../utils/tool-utils.js';
import { getErrorMessage } from '../utils/errors.js';
import { normalizeProxyUrl } from '../utils/proxyUtils.js';
// Local config modules
import type { FileFilteringOptions } from './constants.js';
import {
DEFAULT_FILE_FILTERING_OPTIONS,
DEFAULT_MEMORY_FILE_FILTERING_OPTIONS,
} from './constants.js';
import { DEFAULT_QWEN_EMBEDDING_MODEL } from './models.js';
import { Storage } from './storage.js';
import { ChatRecordingService } from '../services/chatRecordingService.js';
import {
clearRuntimeStatus,
writeRuntimeStatus,
} from '../utils/runtimeStatus.js';
import {
SessionService,
type ResumedSessionData,
} from '../services/sessionService.js';
import { randomUUID } from 'node:crypto';
import { loadServerHierarchicalMemory } from '../utils/memoryDiscovery.js';
import { ConditionalRulesRegistry } from '../utils/rulesDiscovery.js';
import {
createDebugLogger,
setDebugLogSession,
type DebugLogger,
} from '../utils/debugLogger.js';
import { getAutoMemoryRoot } from '../memory/paths.js';
import { readAutoMemoryIndex } from '../memory/store.js';
import { MemoryManager } from '../memory/manager.js';
import { CommitAttributionService } from '../services/commitAttribution.js';
const gitCoAuthorLogger = createDebugLogger('GIT_CO_AUTHOR');
const memoryPressureConfigLogger = createDebugLogger('MEMORY_PRESSURE');
import {
ModelsConfig,
type ModelProvidersConfig,
type AvailableModel,
type RuntimeModelSnapshot,
} from '../models/index.js';
import { resolveModelId } from '../utils/modelId.js';
import type { ClaudeMarketplaceConfig } from '../extension/claude-converter.js';
// Re-export types
export type { AnyToolInvocation, FileFilteringOptions, MCPOAuthConfig };
export {
DEFAULT_FILE_FILTERING_OPTIONS,
DEFAULT_MEMORY_FILE_FILTERING_OPTIONS,
};
export enum ApprovalMode {
PLAN = 'plan',
DEFAULT = 'default',
AUTO_EDIT = 'auto-edit',
AUTO = 'auto',
YOLO = 'yolo',
}
export const APPROVAL_MODES = Object.values(ApprovalMode);
/**
* Thrown by `Config.setApprovalMode` when the requested mode would grant
* privileged tool autonomy in a folder the user has not marked as trusted.
*
* Why: the daemon mutation route at `POST /session/:id/approval-mode` needs
* to recognize this specific class of rejection and translate it into a
* structured `errorKind: 'auth_env_error'` rather than a generic 500.
* Using a named subclass lets the bridge match by `err.name` without
* depending on the message text (which would drift across i18n).
*/
export class TrustGateError extends Error {
constructor(message: string) {
super(message);
this.name = 'TrustGateError';
}
}
/**
* Information about an approval mode including display name and description.
*/
export interface ApprovalModeInfo {
id: ApprovalMode;
name: string;
description: string;
}
/**
* Detailed information about each approval mode.
* Used for UI display and protocol responses.
*/
export const APPROVAL_MODE_INFO: Record<ApprovalMode, ApprovalModeInfo> = {
[ApprovalMode.PLAN]: {
id: ApprovalMode.PLAN,
name: 'Plan',
description: 'Analyze only, do not modify files or execute commands',
},
[ApprovalMode.DEFAULT]: {
id: ApprovalMode.DEFAULT,
name: 'Default',
description: 'Require approval for file edits or shell commands',
},
[ApprovalMode.AUTO_EDIT]: {
id: ApprovalMode.AUTO_EDIT,
name: 'Auto Edit',
description: 'Automatically approve file edits',
},
[ApprovalMode.AUTO]: {
id: ApprovalMode.AUTO,
name: 'Auto',
description: 'LLM classifier auto-approves safe actions, blocks risky ones',
},
[ApprovalMode.YOLO]: {
id: ApprovalMode.YOLO,
name: 'YOLO',
description: 'Automatically approve all tools',
},
};
/**
* Settings for the AUTO approval mode classifier.
*
* `hints` and `environment` are natural-language strings injected additively
* into the classifier's system prompt; they do NOT use rule-matching syntax.
* Use `permissions.allow / ask / deny` for hard rules.
*/
export interface AutoModeSettings {
hints?: {
/** Natural-language descriptions of actions the user wants AUTO mode to allow. */
allow?: string[];
/** Natural-language descriptions of actions the user wants AUTO mode to block. */
deny?: string[];
};
/** Environment / context lines injected into the classifier's system prompt. */
environment?: string[];
}
export interface AccessibilitySettings {
enableLoadingPhrases?: boolean;
screenReader?: boolean;
}
export interface BugCommandSettings {
urlTemplate: string;
}
export interface ChatCompressionSettings {
/**
* Estimated tokens for a single inline image / document part when
* apportioning chars across history during compression size estimation.
* Also used as the placeholder budget when stripping inline media
* out of the side-query compaction prompt. Default 1600.
* Env override: `QWEN_IMAGE_TOKEN_ESTIMATE`.
*/
imageTokenEstimate?: number;
/**
* Number of most-recently-touched files whose current content is
* restored (embedded or referenced) after auto-compaction. Default 5.
* Env override: `QWEN_COMPACT_MAX_RECENT_FILES`.
*/
maxRecentFilesToRetain?: number;
/**
* Number of most-recent images (tool screenshots / user pastes)
* restored after auto-compaction. Default 3.
* Env override: `QWEN_COMPACT_MAX_RECENT_IMAGES`.
*/
maxRecentImagesToRetain?: number;
/**
* When true, auto-compaction also fires once the number of
* tool-returned images accumulated in history reaches
* `screenshotTriggerThreshold`, independent of token usage. Aimed at
* computer-use sessions where frequent screenshots dilute model
* attention without necessarily exceeding the token budget. Default true.
* Env override: `QWEN_COMPACT_SCREENSHOT_TRIGGER` (`1`/`true`/`0`/`false`).
*/
enableScreenshotTrigger?: boolean;
/**
* Tool-returned image count at or above which the screenshot trigger
* fires (only when `enableScreenshotTrigger`). Default 50.
* Env override: `QWEN_COMPACT_SCREENSHOT_THRESHOLD`.
*/
screenshotTriggerThreshold?: number;
}
/**
* Settings for clearing stale context after idle periods.
* Threshold values of -1 mean "never clear" (disabled).
*/
export interface ClearContextOnIdleSettings {
/** Minutes idle before clearing old tool results. Default 60. Use -1 to disable. */
toolResultsThresholdMinutes?: number;
/** Number of most-recent tool results to preserve. Default 5. */
toolResultsNumToKeep?: number;
}
export interface TelemetrySettings {
enabled?: boolean;
target?: TelemetryTarget;
otlpEndpoint?: string;
otlpProtocol?: 'grpc' | 'http';
/** Per-signal endpoint override for traces (HTTP only). Used as-is without path appending. */
otlpTracesEndpoint?: string;
/** Per-signal endpoint override for logs (HTTP only). Used as-is without path appending. */
otlpLogsEndpoint?: string;
/** Per-signal endpoint override for metrics (HTTP only). Used as-is without path appending. */
otlpMetricsEndpoint?: string;
logPrompts?: boolean;
includeSensitiveSpanAttributes?: boolean;
outfile?: string;
/**
* Static resource attributes attached to every span/log/metric the SDK
* exports (OTLP or file outfile — they share the same Resource).
* Merged with `OTEL_RESOURCE_ATTRIBUTES`; settings win on key conflict.
* Reserved keys (`service.version`, `session.id`) are dropped with a
* `diag.warn`.
*/
resourceAttributes?: Record<string, string>;
/** Per-signal cardinality controls. */
metrics?: TelemetryMetricsSettings;
/**
* Human-readable diagnostics produced while resolving
* `resourceAttributes` (drops, coercions, reserved-key strips).
* Populated by `resolveTelemetrySettings()`; the SDK emits a one-time
* console summary at startup when this is non-empty so users notice
* silent drops without scanning the OTel debug log.
*
* Not a user-settable field — operators should leave it unset.
*/
resourceAttributeWarnings?: string[];
}
export interface TelemetryMetricsSettings {
/**
* Include `session.id` on every metric data point. Default: false.
*
* WARNING: each CLI session creates a new value, causing unbounded
* metric time-series fan-out at the backend. Only enable for
* short-term debugging — spans and logs still carry session.id.
*/
includeSessionId?: boolean;
}
/**
* Security-relevant settings controlling what client-side correlation
* data qwen-code writes into outbound LLM API requests.
*
* **Why this is a separate namespace from `telemetry.*`:** telemetry
* controls data flow into the user's OWN observability backend (OTLP
* collector / file outfile). The settings here control data flow OUT of
* the qwen-code process and INTO third-party LLM provider request
* streams (DashScope, OpenAI, Anthropic, etc.). Different recipients =
* different consent decision, so a different settings tree. See PR
* #4390 review (LaZzyMan) for the framing rationale.
*
* All values default to off / no propagation. Operators who want to
* propagate trace context for server-side trace stitching (e.g. ARMS
* Tracing + DashScope) opt in explicitly.
*/
export interface OutboundCorrelationSettings {
/**
* Inject W3C `traceparent` header on outbound HTTP requests
* originated by undici / global `fetch` (LLM SDK calls, MCP
* StreamableHTTP clients, WebFetch tool, etc.). Default: `false`.
*
* When `false`, the SDK is configured with a no-op
* `TextMapPropagator` so trace context stays internal to the user's
* OTLP collector (operator still gets client HTTP spans, but the
* trace id is not written onto third-party request streams).
*
* When `true`, the OTel default W3C composite propagator
* (`tracecontext` + `baggage`) is installed and `traceparent` is
* written on every outbound `fetch`. Useful when the LLM provider
* also reports into the operator's OTel collector — e.g. ARMS
* Tracing + DashScope — for cross-process trace stitching.
*/
propagateTraceContext?: boolean;
}
export interface OutputSettings {
format?: OutputFormat;
}
export interface GitCoAuthorSettings {
commit: boolean;
pr: boolean;
name?: string;
email?: string;
}
/**
* Shape accepted by the Config constructor for the `gitCoAuthor` param.
*
* A plain `boolean` is accepted for backward compatibility: older settings
* (shipped before commit and PR attribution were split) stored this field as
* a single boolean, and we treat that as applying to both sub-toggles so
* nobody's stored preference silently flips.
*/
export type GitCoAuthorParam = boolean | { commit?: boolean; pr?: boolean };
function normalizeGitCoAuthor(value: GitCoAuthorParam | undefined): {
commit: boolean;
pr: boolean;
} {
if (typeof value === 'boolean') {
return { commit: value, pr: value };
}
// Default to `true` (the schema default) ONLY when the sub-field
// is genuinely absent. For PRESENT-but-non-boolean values, honor
// common string forms (`"true"`/`"yes"`/`"on"`/`"1"` → true,
// `"false"`/`"no"`/`"off"`/`"0"`/`""` → false) and treat anything
// else as opt-out. settings.json is user-editable, and the previous
// "default-to-true on mismatch" policy meant a hand-edited
// `{ "commit": "false" }` silently activated attribution against
// the user's clear intent. Safer-by-default: ambiguous values
// disable rather than enable.
const pickBool = (v: unknown, fieldName: string): boolean => {
if (v === undefined) return true;
if (typeof v === 'boolean') return v;
if (typeof v === 'string') {
const lowered = v.trim().toLowerCase();
if (
lowered === 'true' ||
lowered === 'yes' ||
lowered === 'on' ||
lowered === '1'
) {
return true;
}
// Known disable-intent forms — silent (matches user intent).
const knownDisable = ['false', 'no', 'off', '0', 'disabled', ''];
if (!knownDisable.includes(lowered)) {
// Unrecognised string — disable (safer-by-default) but log
// so a user wondering "why is my setting being ignored?"
// can see the actual coercion in QWEN_DEBUG_LOG_FILE.
gitCoAuthorLogger.warn(
`Unrecognized string value for general.gitCoAuthor.${fieldName}: ${JSON.stringify(v)}; treating as false. Accepted forms: true/yes/on/1, false/no/off/0/empty.`,
);
}
return false;
}
if (typeof v === 'number') return v === 1;
return false;
};
return {
commit: pickBool(value?.commit, 'commit'),
pr: pickBool(value?.pr, 'pr'),
};
}
export type ExtensionOriginSource = 'QwenCode' | 'Claude' | 'Gemini';
export interface ExtensionInstallMetadata {
source: string;
type: 'git' | 'local' | 'link' | 'github-release' | 'npm';
originSource?: ExtensionOriginSource;
releaseTag?: string; // Only present for github-release and npm installs.
registryUrl?: string; // Only present for npm installs.
ref?: string;
autoUpdate?: boolean;
allowPreRelease?: boolean;
marketplaceConfig?: ClaudeMarketplaceConfig;
pluginName?: string;
}
export const DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD = 25_000;
export const DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES = 1000;
export class MCPServerConfig {
constructor(
// For stdio transport
readonly command?: string,
readonly args?: string[],
readonly env?: Record<string, string>,
readonly cwd?: string,
// For sse transport
readonly url?: string,
// For streamable http transport
readonly httpUrl?: string,
readonly headers?: Record<string, string>,
// For websocket transport
readonly tcp?: string,
// Common
readonly timeout?: number,
readonly trust?: boolean,
// Metadata
readonly description?: string,
readonly includeTools?: string[],
readonly excludeTools?: string[],
readonly extensionName?: string,
// OAuth configuration
readonly oauth?: MCPOAuthConfig,
readonly authProviderType?: AuthProviderType,
// Service Account Configuration
/* targetAudience format: CLIENT_ID.apps.googleusercontent.com */
readonly targetAudience?: string,
/* targetServiceAccount format: <service-account-name>@<project-num>.iam.gserviceaccount.com */
readonly targetServiceAccount?: string,
// SDK MCP server type - 'sdk' indicates server runs in SDK process
readonly type?: 'sdk',
/**
* Per-server cap on the discovery handshake (`connect` + `tools/list` +
* `prompts/list` + `resources/list`). Defaults: 30s for stdio servers,
* 5s for remote HTTP/SSE. Tool-call timeout (`timeout` above) is
* unaffected — a long-running tool invocation is not a startup
* pathology. Appended at the end of the parameter list to avoid
* shifting positional arguments at the many `new MCPServerConfig(...)`
* call sites.
*/
readonly discoveryTimeoutMs?: number,
) {}
}
/**
* Check if an MCP server config represents an SDK server
*/
export function isSdkMcpServerConfig(config: MCPServerConfig): boolean {
return config.type === 'sdk';
}
export enum AuthProviderType {
DYNAMIC_DISCOVERY = 'dynamic_discovery',
GOOGLE_CREDENTIALS = 'google_credentials',
SERVICE_ACCOUNT_IMPERSONATION = 'service_account_impersonation',
}
export interface SandboxConfig {
command: 'docker' | 'podman' | 'sandbox-exec';
image: string;
}
/**
* Settings shared across multi-agent collaboration features
* (Arena, Team, Swarm).
*/
/**
* General-purpose worktree settings (Phase D-2). Distinct from
* {@link AgentsCollabSettings.arena.worktreeBaseDir}, which only governs
* Arena multi-model worktrees.
*/
export interface WorktreeSettings {
/**
* Directories under the main repository to symlink into every
* general-purpose worktree on creation (the `enter_worktree` tool,
* `agent isolation: "worktree"`, and the `--worktree` startup flag).
*
* Paths must be relative to the repo root; absolute paths and any
* entry containing `..` are rejected by the service. Entries that
* resolve to git-internal paths (`.git`, `.qwen`) are also rejected
* — symlinking those would either break git inside the worktree or
* create a worktrees-inside-worktrees loop. Missing source dirs and
* pre-existing destinations are silently skipped.
*/
symlinkDirectories?: readonly string[];
}
export interface AgentsCollabSettings {
/** Display mode for multi-agent sessions ('in-process' | 'tmux' | 'iterm2') */
displayMode?: string;
/** Arena-specific settings */
arena?: {
/** Custom base directory for Arena worktrees (default: ~/.qwen/arena) */
worktreeBaseDir?: string;
/** Preserve worktrees and state files after session ends */
preserveArtifacts?: boolean;
/** Maximum rounds (turns) per agent. No limit if unset. */
maxRoundsPerAgent?: number;
/** Total timeout in seconds for the Arena session. No limit if unset. */
timeoutSeconds?: number;
};
}
export interface ConfigParameters {
sessionId?: string;
sessionData?: ResumedSessionData;
embeddingModel?: string;
sandbox?: SandboxConfig;
targetDir: string;
debugMode: boolean;
includePartialMessages?: boolean;
question?: string;
systemPrompt?: string;
appendSystemPrompt?: string;
coreTools?: string[];
allowedTools?: string[];
excludeTools?: string[];
/**
* Pre-merged list of slash command names that should be hidden from the
* CLI surface. Matched case-insensitively on the final (post-rename)
* command name. Sourced from settings (`slashCommands.disabled`, UNION
* merged across scopes), the `--disabled-slash-commands` CLI flag, and
* the `QWEN_DISABLED_SLASH_COMMANDS` environment variable.
*/
disabledSlashCommands?: string[];
/**
* Tool names hidden from the registry at construction time. Unlike
* `permissions.deny` (which keeps the tool registered and rejects
* invocation), tools listed here are not registered at all and never
* appear in `/tools`, `getAllTools()`, or function-call discovery.
* Sourced from `settings.tools.disabled` and the daemon mutation route
* `POST /workspace/tools/:name/enable {enabled:false}` (#4175 Wave 4 PR
* 17). Active sessions retain already-registered tools — the disabled
* set is consulted at register time, so toggling takes effect on the
* next ACP child spawn or `ToolRegistry.refresh()`.
*/
disabledTools?: string[];
/** Merged permission rules from all sources (settings + CLI args). */
permissions?: {
allow?: string[];
ask?: string[];
deny?: string[];
/** Settings consumed by the AUTO approval mode classifier. */
autoMode?: AutoModeSettings;
};
toolDiscoveryCommand?: string;
toolCallCommand?: string;
mcpServerCommand?: string;
mcpServers?: Record<string, MCPServerConfig>;
lsp?: {
enabled?: boolean;
};
lspClient?: LspClient;
userMemory?: string;
geminiMdFileCount?: number;
approvalMode?: ApprovalMode;
contextFileName?: string | string[];
accessibility?: AccessibilitySettings;
telemetry?: TelemetrySettings;
outboundCorrelation?: OutboundCorrelationSettings;
gitCoAuthor?: GitCoAuthorParam;
usageStatisticsEnabled?: boolean;
/**
* If true, disables the per-session FileReadCache short-circuit
* (file_unchanged placeholder). Useful for sessions that may undergo
* context compaction or transcript transformation, where the model
* cannot reliably retrieve a previously-emitted full file content
* from prior tool results. Defaults to false (cache active).
*/
fileReadCacheDisabled?: boolean;
fileFiltering?: {
respectGitIgnore?: boolean;
respectQwenIgnore?: boolean;
enableRecursiveFileSearch?: boolean;
enableFuzzySearch?: boolean;
};
checkpointing?: boolean;
fileCheckpointingEnabled?: boolean;
/** Directory where approved plan files are stored. Must resolve inside targetDir. */
plansDirectory?: string;
proxy?: string;
cwd: string;
fileDiscoveryService?: FileDiscoveryService;
includeDirectories?: string[];
bugCommand?: BugCommandSettings;
model?: string;
outputLanguageFilePath?: string;
maxSessionTurns?: number;
/**
* Wall-clock budget for an unattended run, in seconds. `-1` (default)
* means no limit. Enforced by the CLI's non-interactive run loop —
* see `RunBudgetEnforcer` in `packages/cli/src/utils/runBudget.ts`.
* Issue: QwenLM/qwen-code#4103.
*/
maxWallTimeSeconds?: number;
/**
* Cumulative tool-call budget across the entire run. `-1` means no
* limit. Counts every `executeToolCall` invocation (incl. failed
* tools, since the model is still consuming tokens reading the error).
*/
maxToolCalls?: number;
clearContextOnIdle?: ClearContextOnIdleSettings;
sessionTokenLimit?: number;
experimentalZedIntegration?: boolean;
cronEnabled?: boolean;
computerUseEnabled?: boolean;
emitToolUseSummaries?: boolean;
listExtensions?: boolean;
overrideExtensions?: string[];
allowedMcpServers?: string[];
excludedMcpServers?: string[];
noBrowser?: boolean;
folderTrustFeature?: boolean;
folderTrust?: boolean;
ideMode?: boolean;
authType?: AuthType;
generationConfig?: Partial<ContentGeneratorConfig>;
/**
* Optional source map for generationConfig fields (e.g. CLI/env/settings attribution).
* This is used to produce per-field source badges in the UI.
*/
generationConfigSources?: ContentGeneratorConfigSources;
cliVersion?: string;
loadMemoryFromIncludeDirectories?: boolean;
importFormat?: 'tree' | 'flat';
chatRecording?: boolean;
chatCompression?: ChatCompressionSettings;
interactive?: boolean;
trustedFolder?: boolean;
defaultFileEncoding?: FileEncodingType;
useRipgrep?: boolean;
useBuiltinRipgrep?: boolean;
shouldUseNodePtyShell?: boolean;
skipNextSpeakerCheck?: boolean;
shellExecutionConfig?: ShellExecutionConfig;
skipLoopDetection?: boolean;
truncateToolOutputThreshold?: number;
truncateToolOutputLines?: number;
eventEmitter?: EventEmitter;
output?: OutputSettings;
inputFormat?: InputFormat;
outputFormat?: OutputFormat;
skipStartupContext?: boolean;
bareMode?: boolean;
sdkMode?: boolean;
sessionSubagents?: SubagentConfig[];
channel?: string;
/**
* File descriptor number for structured JSON event output (dual output mode).
* When set, Qwen Code outputs structured JSON events to this fd while
* continuing to render the TUI on stdout. The caller must provide this fd
* via spawn stdio configuration.
* Mutually exclusive with jsonFile.
*/
jsonFd?: number;
/**
* File path for structured JSON event output (dual output mode).
* Can be a regular file, FIFO (named pipe), or /dev/fd/N.
* Mutually exclusive with jsonFd.
*/
jsonFile?: string;
/**
* JSON Schema that the model's final output must conform to. When set, a
* synthetic `structured_output` tool is registered and the non-interactive
* CLI ends the session the first time the model calls it with valid args.
* Only meaningful in headless mode (`qwen -p`).
*/
jsonSchema?: Record<string, unknown>;
/**
* File path for receiving remote input commands (bidirectional sync mode).
* An external process writes JSONL commands to this file, and the TUI
* watches it to process messages as if the user typed them.
*/
inputFile?: string;
/** Model providers configuration grouped by authType */
modelProvidersConfig?: ModelProvidersConfig;
/** Multi-agent collaboration settings (Arena, Team, Swarm) */
agents?: AgentsCollabSettings;
/** General-purpose worktree settings (Phase D-2). */
worktree?: WorktreeSettings;
/** Enable managed auto-memory background extraction and dream. Defaults to true. */
enableManagedAutoMemory?: boolean;
/** Enable managed auto-dream consolidation separately from extraction. Defaults to true. */
enableManagedAutoDream?: boolean;
/** Enable automatic project skill review after tool-heavy sessions. Defaults to false. */
enableAutoSkill?: boolean;
/**
* Lightweight model for background tasks (memory extraction, dream, /btw side questions).
* When set and valid for the current auth type, forked agents use this model instead of
* the main session model, reducing latency and cost.
* Corresponds to the `fastModel` setting (configurable via `/model --fast`).
*/
fastModel?: string;
/**
* Disable all hooks (default: false, hooks enabled).
* Migration note: This replaces the deprecated hooksConfig.enabled setting.
* Users with old settings.json containing hooksConfig.enabled should migrate
* to use disableAllHooks instead (note: inverted logic - enabled:true → disableAllHooks:false).
*/
disableAllHooks?: boolean;
/**
* Maximum consecutive blocking Stop/SubagentStop hook decisions before the
* runtime overrides the hook loop and allows the turn to end.
*/
stopHookBlockingCap?: number;
/**
* User-level hooks configuration (from user settings).
* These hooks are always loaded regardless of folder trust status.
*/
userHooks?: Record<string, unknown>;
/**
* Project-level hooks configuration (from workspace settings).
* These hooks are only loaded in trusted folders.
* When undefined or the folder is untrusted, project hooks are skipped.
*/
projectHooks?: Record<string, unknown>;
hooks?: Record<string, unknown>;
/** Glob patterns to exclude from .qwen/rules/ loading. */
contextRuleExcludes?: string[];
/** Warnings generated during configuration resolution */
warnings?: string[];
/** Allowed HTTP hook URLs whitelist (from security.allowedHttpHookUrls) */
allowedHttpHookUrls?: string[];
/**
* Callback for persisting a permission rule to settings.
* Injected by the CLI layer; core uses this to write allow/ask/deny rules
* to project or user settings when the user clicks "Always Allow".
*
* @param scope - 'project' for workspace settings, 'user' for user settings.
* @param ruleType - 'allow' | 'ask' | 'deny'.
* @param rule - The raw rule string, e.g. "Bash(git *)" or "Edit".
*/
onPersistPermissionRule?: (
scope: 'project' | 'user',
ruleType: 'allow' | 'ask' | 'deny',
rule: string,
) => Promise<void>;
}
function normalizeConfigOutputFormat(
format: OutputFormat | undefined,
): OutputFormat | undefined {
if (!format) {
return undefined;
}
switch (format) {
case 'stream-json':
return OutputFormat.STREAM_JSON;
case 'json':
case OutputFormat.JSON:
return OutputFormat.JSON;
case 'text':
case OutputFormat.TEXT:
default:
return OutputFormat.TEXT;
}
}
function loadMemoryPressureConfig(): MemoryPressureConfig {
const config: MemoryPressureConfig = { ...DEFAULT_PRESSURE_CONFIG };
try {
config.softPressureRatio = readMemoryPressureRatioEnv(
'QWEN_MEMORY_PRESSURE_SOFT',
config.softPressureRatio,
);
config.hardPressureRatio = readMemoryPressureRatioEnv(
'QWEN_MEMORY_PRESSURE_HARD',
config.hardPressureRatio,
);
config.criticalRatio = readMemoryPressureRatioEnv(
'QWEN_MEMORY_PRESSURE_CRITICAL',
config.criticalRatio,
);
if (process.env['QWEN_MEMORY_ENABLE_GC'] === '1') {
config.enableExplicitGC = true;
}
validateMemoryPressureConfig(config);
} catch (err) {
const fallbackMsg =
'[QWEN] WARNING: Invalid memory pressure config; using defaults. ' +
`Error: ${getErrorMessage(err)}`;
process.stderr.write(`${fallbackMsg}\n`);
memoryPressureConfigLogger.warn(fallbackMsg);
return { ...DEFAULT_PRESSURE_CONFIG };
}
return config;
}
function readMemoryPressureRatioEnv(envName: string, fallback: number): number {
const raw = process.env[envName];
if (!raw) {
return fallback;
}
const parsed = Number(raw);
if (!Number.isFinite(parsed)) {
throw new Error(`${envName} must be a finite number`);
}
return parsed;
}
/**
* Options for Config.initialize()
*/
export interface ConfigInitializeOptions {
/**
* Callback for sending MCP messages to SDK servers via control plane.
* Required for SDK MCP server support in SDK mode.
*/
sendSdkMcpMessage?: SendSdkMcpMessage;
/**
* Skip Gemini client chat initialization. Useful for bootstrap paths that
* need config services (hooks, tools, MCP) before a real session exists.
*/
skipGeminiInitialization?: boolean;
}
const DEFAULT_BARE_CORE_TOOLS = [
ToolNames.READ_FILE,
ToolNames.EDIT,
ToolNames.NOTEBOOK_EDIT,
ToolNames.SHELL,
];
// Tracks whether the first Config in this process has claimed the global
// QWEN_CODE_SESSION_ID env var. Prevents throwaway Config instances from
// overwriting the real session's ID while still allowing nested qwen-code
// processes to claim their own (they start with a fresh module scope).
let sessionEnvClaimed = false;
export class Config {
private sessionId: string;
private sessionData?: ResumedSessionData;
/**
* One-shot notice produced by `setupStartupWorktree` (Phase D-1) when the
* CLI was launched with `--worktree`. The active entry point (TUI XOR
* headless) reads it via {@link consumePendingStartupWorktreeNotice} on
* the model's first prompt and skips Phase C's `restoreWorktreeContext`
* for that turn — startup wins over the resumed-session sidecar. ACP is
* gated out earlier in `gemini.tsx` (mutex with `--worktree`) so it
* never reaches this slot.
*
* @invariant At most one consumer per process. If a future entry path
* sets this slot without ever consuming, the string persists until
* process exit (which dies with the process — no leak).
*/
private pendingStartupWorktreeNotice: string | null = null;
private debugLogger: DebugLogger;
private toolRegistry!: ToolRegistry;
/**
* PR 14b fix #2 (codex review round 1): callback stashed BEFORE
* `initialize()` runs and applied as soon as `toolRegistry` is up,
* so the manager's `setOnBudgetEvent` is wired before
* `startMcpDiscoveryInBackground` (or legacy blocking discovery)
* fires the first pass. Pre-fix the acpAgent registered after
* `initialize()` returned, missing the first pass entirely under
* `QWEN_CODE_LEGACY_MCP_BLOCKING=1` and racing against background
* discovery completion under the default mode.
*/
private pendingMcpBudgetCallback?: (event: McpBudgetEvent) => void;
private promptRegistry!: PromptRegistry;
private subagentManager!: SubagentManager;
private memoryPressureConfig?: MemoryPressureConfig;
private memoryPressureMonitor?: MemoryPressureMonitor;
private readonly backgroundTaskRegistry = new BackgroundTaskRegistry();
private readonly monitorRegistry = new MonitorRegistry();
private backgroundAgentResumeService?: BackgroundAgentResumeService;
private readonly backgroundShellRegistry = new BackgroundShellRegistry();
// Field initializer runs once on the parent Config; child Configs
// built via Object.create(parent) intentionally do NOT pick this up
// — see getFileReadCache() for the per-instance lazy initialization
// that keeps subagent caches isolated from the parent's.
private fileReadCache: FileReadCache = new FileReadCache();
private extensionManager!: ExtensionManager;
private skillManager: SkillManager | null = null;
private permissionManager: PermissionManager | null = null;
private modelInvocableCommandsProvider:
| (() => ReadonlyArray<{ name: string; description: string }>)
| null = null;
private modelInvocableCommandsExecutor:
| ((name: string, args?: string) => Promise<string | null>)
| null = null;
private fileSystemService: FileSystemService;
private contentGeneratorConfig!: ContentGeneratorConfig;
private contentGeneratorConfigSources: ContentGeneratorConfigSources = {};
private contentGenerator!: ContentGenerator;
private readonly embeddingModel: string;
private modelsConfig!: ModelsConfig;
private readonly modelProvidersConfig?: ModelProvidersConfig;