@swifty.js/swifty 0.0.27 → 0.0.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +47 -37
  2. package/dist/agent-YR6YK26C.js +4 -0
  3. package/dist/anthropic-5GRR5JCT.js +4 -0
  4. package/dist/checker-N5TIJEN5.js +4 -0
  5. package/dist/chunk-D34FUVGU.js +4 -0
  6. package/dist/{chunk-UGJVMFGH.js → chunk-K5ZK27BX.js} +1 -1
  7. package/dist/chunk-LIMEBKCY.js +408 -0
  8. package/dist/chunk-OTVZGPHD.js +121 -0
  9. package/dist/chunk-POHIQUFP.js +301 -0
  10. package/dist/chunk-QCKJLO6X.js +4 -0
  11. package/dist/chunk-QFSCPD63.js +4 -0
  12. package/dist/chunk-TMEX7RFA.js +4 -0
  13. package/dist/chunk-Y6SQB5FG.js +4 -0
  14. package/dist/lib/agent-5WEKVRTD.js +11 -0
  15. package/dist/lib/{anthropic-RYPJDHQM.js → anthropic-KWO3KLNV.js} +4 -5
  16. package/dist/lib/{checker-6BW4222R.js → checker-AXHPKVBY.js} +2 -2
  17. package/dist/lib/{chunk-HK2Z6WP4.js → chunk-2IVEVG5N.js} +5 -1
  18. package/dist/lib/{chunk-XFSN4LMA.js → chunk-3FBS5NB7.js} +71 -18
  19. package/dist/lib/{chunk-GNI7YX6F.js → chunk-DJ6AILPN.js} +70 -24
  20. package/dist/lib/chunk-GCY44T7S.js +2346 -0
  21. package/dist/lib/{chunk-PZ42NAFA.js → chunk-KG4MJGKQ.js} +19 -21
  22. package/dist/lib/{chunk-2AUSNVIB.js → chunk-KZSBR4FO.js} +44 -37
  23. package/dist/lib/chunk-PIL7M52F.js +127 -0
  24. package/dist/lib/chunk-Z4CYHTII.js +392 -0
  25. package/dist/lib/index.d.ts +227 -132
  26. package/dist/lib/index.js +2195 -1602
  27. package/dist/lib/{openai-VX5VBXZ4.js → openai-PBF7EWNJ.js} +2 -3
  28. package/dist/lib/{tool-filter-VF7TZRE5.js → tool-filter-R6HDDJHE.js} +1 -1
  29. package/dist/main.js +203 -194
  30. package/dist/{openai-5FDSLJNM.js → openai-QQ2K7GPF.js} +14 -14
  31. package/dist/{server-F666APPN.js → server-G23HCFLI.js} +21 -21
  32. package/dist/{tool-filter-NO7I3HFD.js → tool-filter-VBP6WOGO.js} +1 -1
  33. package/package.json +2 -2
  34. package/dist/agent-OMC6YIMW.js +0 -4
  35. package/dist/anthropic-T5K4BQPB.js +0 -4
  36. package/dist/checker-TOQVEG3P.js +0 -4
  37. package/dist/chunk-5I2WXSGV.js +0 -90
  38. package/dist/chunk-A2VR3BC4.js +0 -4
  39. package/dist/chunk-A57FEYSN.js +0 -4
  40. package/dist/chunk-BRC5L644.js +0 -130
  41. package/dist/chunk-FZPTNGTU.js +0 -4
  42. package/dist/chunk-G6YIQW3Z.js +0 -238
  43. package/dist/chunk-I2XG2PXV.js +0 -4
  44. package/dist/chunk-LVSHXIBK.js +0 -389
  45. package/dist/chunk-SULWNDNC.js +0 -4
  46. package/dist/chunk-WO6DL7OB.js +0 -35
  47. package/dist/lib/agent-U7MIUCKT.js +0 -9
  48. package/dist/lib/chunk-2QILP24G.js +0 -1120
  49. package/dist/lib/chunk-3LU4APFB.js +0 -339
  50. package/dist/lib/chunk-OO2CLOEE.js +0 -88
  51. package/dist/lib/chunk-RKJYTYQM.js +0 -1285
@@ -47,6 +47,88 @@ declare class RecoveryState {
47
47
  buildRecoveryAttachment(toolSchemaNames: string[]): string;
48
48
  }
49
49
 
50
+ /**
51
+ * Copyright (c) 2026 hangtiancheng
52
+ *
53
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
54
+ * of this software and associated documentation files (the "Software"), to deal
55
+ * in the Software without restriction, including without limitation the rights
56
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
57
+ * copies of the Software, and to permit persons to whom the Software is
58
+ * furnished to do so, subject to the following conditions:
59
+ *
60
+ * The above copyright notice and this permission notice shall be included in
61
+ * all copies or substantial portions of the Software.
62
+ *
63
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
64
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
65
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
66
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
67
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
68
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
69
+ * SOFTWARE.
70
+ */
71
+ type DecisionEffect = "allow" | "deny" | "ask";
72
+ type PermissionMode = "default" | "acceptEdits" | "plan" | "bypassPermissions";
73
+ interface Decision {
74
+ effect: DecisionEffect;
75
+ reason: string;
76
+ }
77
+ type RuleEffect = DecisionEffect;
78
+ interface Rule {
79
+ tool: string;
80
+ pattern: string;
81
+ effect: RuleEffect;
82
+ }
83
+ declare function extractContent(toolName: string, args: Record<string, unknown>): string;
84
+ declare class PathSandbox {
85
+ private allowedRoots;
86
+ private denyWritePaths;
87
+ private projectDir;
88
+ constructor(projectDir: string);
89
+ addRoot(root: string): void;
90
+ addDenyWrite(path: string): void;
91
+ /**
92
+ * Check whether a path is in the deny-write list.
93
+ * denyWrite has the highest priority — even if the path is within an allowed root, writes are still denied.
94
+ */
95
+ checkDenyWrite(filePath: string): Decision | null;
96
+ check(filePath: string): Decision | null;
97
+ }
98
+ declare function evaluateRules(rules: Rule[], toolName: string, content: string): RuleEffect | null;
99
+ declare class RuleEngine {
100
+ private userPath;
101
+ private projectPath;
102
+ private localPath;
103
+ private cache;
104
+ constructor(workDir: string);
105
+ private rulesFor;
106
+ snapshot(): Rule[];
107
+ evaluate(toolName: string, content: string): RuleEffect | null;
108
+ appendLocalRule(rule: Rule): void;
109
+ }
110
+ declare function isSafeCommand(command: string): boolean;
111
+ declare class PermissionChecker {
112
+ private readonly workDir;
113
+ mode: PermissionMode;
114
+ planFilePath: string;
115
+ sandboxEnabled: boolean;
116
+ sandboxAutoAllow: boolean;
117
+ private sandbox;
118
+ private ruleEngine;
119
+ constructor(workDir: string, mode?: PermissionMode);
120
+ forWorkDir(workDir: string): PermissionChecker;
121
+ check(toolName: string, category: "read" | "write" | "command", args: Record<string, unknown>): Decision;
122
+ allowExtraRoot(path: string): void;
123
+ allowAlways(toolName: string, args: Record<string, unknown>): void;
124
+ /**
125
+ * Generate a human-readable description of the tool action for display in HITL confirmation dialogs.
126
+ * Prioritizes extracting fields defined in contentFields (e.g., command, file_path);
127
+ * falls back to a key:value summary of parameters if no match is found.
128
+ */
129
+ describeToolAction(toolName: string, args: Record<string, unknown>): string;
130
+ }
131
+
50
132
  /**
51
133
  * Copyright (c) 2026 hangtiancheng
52
134
  *
@@ -72,6 +154,7 @@ declare class FileStateCache {
72
154
  private cache;
73
155
  /** Called after a successful ReadFile to register the file as "seen". */
74
156
  record(filePath: string, lastModifiedTimeMs: number): void;
157
+ has(filePath: string): boolean;
75
158
  /**
76
159
  * Gate check before EditFile / WriteFile
77
160
  */
@@ -173,6 +256,8 @@ interface ToolContext {
173
256
  abortSignal?: AbortSignal;
174
257
  fileHistory?: FileHistory | undefined;
175
258
  fileStateCache?: FileStateCache | undefined;
259
+ permissionChecker?: PermissionChecker;
260
+ onPermissionRequest?: (toolName: string, args: Record<string, unknown>, decision: Decision) => Promise<"allow" | "deny" | "allowAlways">;
176
261
  }
177
262
  /**
178
263
  * How MCP tools enter the context, written into ToolRegistry by mcp/strategy
@@ -321,6 +406,7 @@ declare class ConversationManager {
321
406
  hasReminderContaining(marker: string): boolean;
322
407
  injectLongTermMemory(instructions: string, memories: string, skills?: string): void;
323
408
  appendMessages(msgs: Message[]): void;
409
+ fork(): ConversationManager;
324
410
  len(): number;
325
411
  truncateTo(index: number): void;
326
412
  reset(): void;
@@ -359,6 +445,15 @@ declare class ConversationManager {
359
445
  declare class ConfigError extends Error {
360
446
  constructor(message: string);
361
447
  }
448
+ /** The single global config file: $HOME/.swifty/config.yaml. */
449
+ declare function globalConfigPath(): string;
450
+ /**
451
+ * PI-equivalent thinking levels. `off` disables reasoning entirely; the rest
452
+ * map to a provider-native effort string (openai / openai-compat) or a thinking
453
+ * token budget (anthropic).
454
+ */
455
+ declare const THINKING_LEVELS: readonly ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
456
+ type ThinkingLevel = (typeof THINKING_LEVELS)[number];
362
457
  declare const ProviderConfigSchema: z.ZodObject<{
363
458
  name: z.ZodString;
364
459
  protocol: z.ZodEnum<{
@@ -369,16 +464,55 @@ declare const ProviderConfigSchema: z.ZodObject<{
369
464
  base_url: z.ZodString;
370
465
  model: z.ZodString;
371
466
  api_key: z.ZodOptional<z.ZodString>;
372
- thinking: z.ZodOptional<z.ZodBoolean>;
467
+ thinking: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodEnum<{
468
+ off: "off";
469
+ minimal: "minimal";
470
+ low: "low";
471
+ medium: "medium";
472
+ high: "high";
473
+ xhigh: "xhigh";
474
+ max: "max";
475
+ }>]>>;
373
476
  context_window: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
374
477
  max_output_tokens: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
375
478
  }, z.core.$strip>;
376
479
  type ProviderConfig = z.infer<typeof ProviderConfigSchema>;
377
- declare function lookupModelContextWindow(model: string): number;
378
- declare function getContextWindow(p: ProviderConfig): number;
379
- declare function getContextWindowAsync(p: ProviderConfig, fetcher?: (p: ProviderConfig) => Promise<number>): Promise<number>;
380
- declare function _resetContextWindowCache(): void;
381
- declare function getMaxOutputTokens(p: ProviderConfig): number;
480
+ declare const DEFAULT_THINKING_LEVEL: ThinkingLevel;
481
+ declare const DEFAULT_CONTEXT_WINDOW = 1000000;
482
+ /**
483
+ * Fallback output-token ceiling used when `max_output_tokens` is unset (PI's
484
+ * custom-model `maxTokens` default).
485
+ */
486
+ declare const DEFAULT_MAX_OUTPUT_TOKENS = 128000;
487
+ /**
488
+ * PI-equivalent thinking token budgets, used by the anthropic budget-based
489
+ * thinking path. Must stay below DEFAULT_MAX_OUTPUT_TOKENS so the answer keeps
490
+ * room after the thinking budget is reserved.
491
+ */
492
+ declare const THINKING_BUDGETS: Record<Exclude<ThinkingLevel, "off">, number>;
493
+ declare function isValidThinkingLevel(value: string): value is ThinkingLevel;
494
+ /**
495
+ * Default thinking level per protocol. Anthropic historically enabled extended
496
+ * thinking by default; the OpenAI protocols never sent a reasoning parameter
497
+ * before, and non-reasoning models reject `reasoning_effort`, so they only opt
498
+ * in when `thinking` is configured explicitly.
499
+ */
500
+ declare function defaultThinkingLevelFor(protocol: ProviderConfig["protocol"]): ThinkingLevel;
501
+ /** Normalize the config `thinking` field (level or legacy boolean) to a level. */
502
+ declare function getThinkingLevel(provider: ProviderConfig): ThinkingLevel;
503
+ /** Thinking token budget for a level; 0 when thinking is off. */
504
+ declare function thinkingBudgetForLevel(level: ThinkingLevel): number;
505
+ /** Map a PI thinking level to an OpenAI reasoning effort string. */
506
+ declare function toReasoningEffort(level: ThinkingLevel): "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
507
+ declare function withProviderDefaults(provider: ProviderConfig): ProviderConfig;
508
+ declare function getContextWindow(provider: ProviderConfig): number;
509
+ /**
510
+ * Effective output cap for a provider. Configured value wins, otherwise the
511
+ * 128k fallback applies; the result never exceeds the context window (PI's
512
+ * `clampMaxTokensToContext`). This keeps small-output models from being sent an
513
+ * over-large `max_tokens` while still letting users lower the cap.
514
+ */
515
+ declare function getMaxOutputTokens(provider: ProviderConfig): number;
382
516
  declare function resolveAPIKey(p: ProviderConfig): string;
383
517
  declare const MCPServerConfigSchema: z.ZodObject<{
384
518
  name: z.ZodString;
@@ -424,7 +558,15 @@ declare const AppConfigSchema: z.ZodObject<{
424
558
  base_url: z.ZodString;
425
559
  model: z.ZodString;
426
560
  api_key: z.ZodOptional<z.ZodString>;
427
- thinking: z.ZodOptional<z.ZodBoolean>;
561
+ thinking: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodEnum<{
562
+ off: "off";
563
+ minimal: "minimal";
564
+ low: "low";
565
+ medium: "medium";
566
+ high: "high";
567
+ xhigh: "xhigh";
568
+ max: "max";
569
+ }>]>>;
428
570
  context_window: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
429
571
  max_output_tokens: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
430
572
  }, z.core.$strip>>;
@@ -465,8 +607,9 @@ declare const AppConfigSchema: z.ZodObject<{
465
607
  /** Whether fork is available. Defaults to enabled when not specified in config. */
466
608
  declare function forkEnabled(cfg: AppConfig): boolean;
467
609
  type AppConfig = z.infer<typeof AppConfigSchema>;
468
- declare function mergeConfig(base: AppConfig, override: AppConfig): AppConfig;
469
- declare function loadConfig(path?: string): AppConfig;
610
+ declare function loadConfig(path?: string, options?: {
611
+ allowEmptyProviders?: boolean;
612
+ }): AppConfig;
470
613
 
471
614
  /**
472
615
  * Copyright (c) 2026 hangtiancheng
@@ -503,6 +646,10 @@ interface HookResult {
503
646
  success: boolean;
504
647
  reject: boolean;
505
648
  }
649
+ interface HookRuntimeOptions {
650
+ workDir?: string;
651
+ abortSignal?: AbortSignal;
652
+ }
506
653
  declare class HookEngine {
507
654
  private hooks;
508
655
  private firedOnce;
@@ -511,8 +658,8 @@ declare class HookEngine {
511
658
  constructor(hooks: HookConfig[]);
512
659
  recordNotification(message: string): void;
513
660
  drainNotifications(): string[];
514
- fire(event: EventName, context: HookContext): Promise<HookResult[]>;
515
- firePreToolHooks(toolName: string, args: Record<string, unknown>): Promise<{
661
+ fire(event: EventName, context: HookContext, options?: HookRuntimeOptions): Promise<HookResult[]>;
662
+ firePreToolHooks(toolName: string, args: Record<string, unknown>, options?: HookRuntimeOptions): Promise<{
516
663
  rejected: boolean;
517
664
  reason: string;
518
665
  }>;
@@ -603,10 +750,13 @@ declare class OpenAIClient implements LLMClient {
603
750
  private model;
604
751
  private systemPrompt;
605
752
  private maxOutputTokens;
753
+ private thinkingLevel;
606
754
  constructor(config: ProviderConfig, systemPrompt: string);
607
755
  stream(conversation: ConversationManager, toolSchemas: ToolSchema[], abortSignal?: AbortSignal): AsyncGenerator<StreamEvent>;
608
756
  setSystemPrompt(prompt: string): void;
609
757
  setMaxOutputTokens(maxTokens: number): void;
758
+ setThinkingLevel(level: ThinkingLevel): void;
759
+ getThinkingLevel(): ThinkingLevel;
610
760
  }
611
761
  type OpenAIMessageParam = OpenAI.Responses.EasyInputMessage | OpenAI.Responses.ResponseFunctionToolCall | OpenAI.Responses.ResponseInputItem.FunctionCallOutput | OpenAI.Responses.ResponseReasoningItem;
612
762
  declare function buildOpenAIInput(messages: Message[]): OpenAIMessageParam[];
@@ -615,9 +765,12 @@ declare class OpenAICompatClient implements LLMClient {
615
765
  private model;
616
766
  private systemPrompt;
617
767
  private maxOutputTokens;
768
+ private thinkingLevel;
618
769
  constructor(config: ProviderConfig, systemPrompt: string);
619
770
  setSystemPrompt(prompt: string): void;
620
771
  setMaxOutputTokens(maxTokens: number): void;
772
+ setThinkingLevel(level: ThinkingLevel): void;
773
+ getThinkingLevel(): ThinkingLevel;
621
774
  stream(conversation: ConversationManager, toolSchemas: ToolSchema[], abortSignal?: AbortSignal): AsyncGenerator<StreamEvent>;
622
775
  }
623
776
  declare function buildChatCompletionMessages(messages: Message[]): OpenAI.ChatCompletionMessageParam[];
@@ -669,16 +822,17 @@ declare class AnthropicClient implements LLMClient {
669
822
  private client;
670
823
  private model;
671
824
  /**
672
- * Whether supports/enable thinking, default false
825
+ * PI-equivalent thinking level; maps to a thinking token budget.
673
826
  */
674
- private thinking;
827
+ private thinkingLevel;
675
828
  private systemPrompt;
676
829
  private maxOutputTokens;
677
830
  /** Currently not used */
678
- private contextWindow;
679
831
  constructor(config: ProviderConfig, systemPrompt: string);
680
832
  setSystemPrompt(prompt: string): void;
681
833
  setMaxOutputTokens(maxTokens: number): void;
834
+ setThinkingLevel(level: ThinkingLevel): void;
835
+ getThinkingLevel(): ThinkingLevel;
682
836
  stream(conversation: ConversationManager, toolSchemas: ToolSchema[], abortSignal?: AbortSignal): AsyncGenerator<StreamEvent>;
683
837
  }
684
838
  /**
@@ -686,13 +840,18 @@ declare class AnthropicClient implements LLMClient {
686
840
  */
687
841
  declare function markLastUserTailForCache(messages: Anthropic.Messages.MessageParam[]): void;
688
842
 
689
- interface LLMClient extends Partial<MaxTokensSetter> {
843
+ interface LLMClient extends Partial<MaxTokensSetter>, Partial<ThinkingLevelControl> {
690
844
  stream(conversationManager: ConversationManager, toolSchemas: ToolSchema[], abortSignal?: AbortSignal): AsyncGenerator<StreamEvent>;
691
845
  setSystemPrompt(prompt: string): void;
692
846
  }
693
847
  interface MaxTokensSetter {
694
848
  setMaxOutputTokens(maxTokens: number): void;
695
849
  }
850
+ /** Runtime control of the PI-equivalent thinking level. */
851
+ interface ThinkingLevelControl {
852
+ setThinkingLevel(level: ThinkingLevel): void;
853
+ getThinkingLevel(): ThinkingLevel;
854
+ }
696
855
  declare function createClient(config: ProviderConfig, systemPrompt: string): Promise<AnthropicClient | OpenAIClient | OpenAICompatClient>;
697
856
 
698
857
  /**
@@ -785,86 +944,6 @@ declare class MemoryManager {
785
944
  renderReminder(memories: RelevantMemory[]): string;
786
945
  }
787
946
 
788
- /**
789
- * Copyright (c) 2026 hangtiancheng
790
- *
791
- * Permission is hereby granted, free of charge, to any person obtaining a copy
792
- * of this software and associated documentation files (the "Software"), to deal
793
- * in the Software without restriction, including without limitation the rights
794
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
795
- * copies of the Software, and to permit persons to whom the Software is
796
- * furnished to do so, subject to the following conditions:
797
- *
798
- * The above copyright notice and this permission notice shall be included in
799
- * all copies or substantial portions of the Software.
800
- *
801
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
802
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
803
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
804
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
805
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
806
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
807
- * SOFTWARE.
808
- */
809
- type DecisionEffect = "allow" | "deny" | "ask";
810
- type PermissionMode = "default" | "acceptEdits" | "plan" | "bypassPermissions";
811
- interface Decision {
812
- effect: DecisionEffect;
813
- reason: string;
814
- }
815
- type RuleEffect = DecisionEffect;
816
- interface Rule {
817
- tool: string;
818
- pattern: string;
819
- effect: RuleEffect;
820
- }
821
- declare function extractContent(toolName: string, args: Record<string, unknown>): string;
822
- declare class PathSandbox {
823
- private allowedRoots;
824
- private denyWritePaths;
825
- private projectDir;
826
- constructor(projectDir: string);
827
- addRoot(root: string): void;
828
- addDenyWrite(path: string): void;
829
- /**
830
- * Check whether a path is in the deny-write list.
831
- * denyWrite has the highest priority — even if the path is within an allowed root, writes are still denied.
832
- */
833
- checkDenyWrite(filePath: string): Decision | null;
834
- check(filePath: string): Decision | null;
835
- }
836
- declare function evaluateRules(rules: Rule[], toolName: string, content: string): RuleEffect | null;
837
- declare class RuleEngine {
838
- private userPath;
839
- private projectPath;
840
- private localPath;
841
- private cache;
842
- constructor(workDir: string);
843
- private rulesFor;
844
- snapshot(): Rule[];
845
- evaluate(toolName: string, content: string): RuleEffect | null;
846
- appendLocalRule(rule: Rule): void;
847
- }
848
- declare function isSafeCommand(command: string): boolean;
849
- declare class PermissionChecker {
850
- mode: PermissionMode;
851
- planFilePath: string;
852
- sandboxEnabled: boolean;
853
- sandboxAutoAllow: boolean;
854
- private sandbox;
855
- private ruleEngine;
856
- constructor(workDir: string, mode?: PermissionMode);
857
- check(toolName: string, category: "read" | "write" | "command", args: Record<string, unknown>): Decision;
858
- allowExtraRoot(path: string): void;
859
- allowAlways(toolName: string, args: Record<string, unknown>): void;
860
- /**
861
- * Generate a human-readable description of the tool action for display in HITL confirmation dialogs.
862
- * Prioritizes extracting fields defined in contentFields (e.g., command, file_path);
863
- * falls back to a key:value summary of parameters if no match is found.
864
- */
865
- describeToolAction(toolName: string, args: Record<string, unknown>): string;
866
- }
867
-
868
947
  /**
869
948
  * Copyright (c) 2026 hangtiancheng
870
949
  *
@@ -1218,6 +1297,7 @@ declare class Agent {
1218
1297
  private memoryRecallValue?;
1219
1298
  private onMemoriesSurfaced?;
1220
1299
  constructor(config: AgentConfig);
1300
+ private restoreContext;
1221
1301
  run(): AsyncGenerator<AgentEvent>;
1222
1302
  private fireLifecycle;
1223
1303
  private interruptibleSleep;
@@ -1295,6 +1375,7 @@ declare class StreamingExecutor {
1295
1375
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1296
1376
  * SOFTWARE.
1297
1377
  */
1378
+
1298
1379
  type CommandType = "local" | "local_ui" | "prompt" | "skill_fork";
1299
1380
  interface CommandContext {
1300
1381
  workDir: string;
@@ -1313,6 +1394,12 @@ interface CommandContext {
1313
1394
  memoryClear?: () => void;
1314
1395
  /** Returns the current model name */
1315
1396
  model?: string;
1397
+ /** Returns the current thinking level */
1398
+ thinkingLevel?: () => ThinkingLevel;
1399
+ /** Sets the thinking level for the active client */
1400
+ setThinkingLevel?: (level: ThinkingLevel) => void;
1401
+ /** Persists the thinking level to the global config; throws on failure */
1402
+ persistThinkingLevel?: (level: ThinkingLevel) => void;
1316
1403
  }
1317
1404
  interface Command {
1318
1405
  name: string;
@@ -1672,6 +1759,8 @@ interface Member {
1672
1759
  name: string;
1673
1760
  active: boolean;
1674
1761
  cancel?: () => void;
1762
+ /** Resolves when the in-process teammate's current loop has fully stopped. */
1763
+ done?: Promise<void>;
1675
1764
  mailbox: FileMailbox;
1676
1765
  uiState?: TeammateUIState;
1677
1766
  /** Optional: Conversation manager for the teammate; when set, the transcript is persisted on exit. */
@@ -1688,7 +1777,7 @@ interface Member {
1688
1777
  worktreePath?: string;
1689
1778
  joinedAt?: number;
1690
1779
  }
1691
- type RunAgent = (task: string, onEvent?: AgentEventCallback) => Promise<string>;
1780
+ type RunAgent = (task: string, onEvent?: AgentEventCallback, abortSignal?: AbortSignal) => Promise<string>;
1692
1781
  declare class Team {
1693
1782
  name: string;
1694
1783
  mode: TeamMode;
@@ -2113,8 +2202,8 @@ declare function estimateMessages(messages: Message[]): number;
2113
2202
  declare function estimateTokens(conv: ConversationManager): number;
2114
2203
  declare function computeKeepStartIndex(messages: Message[]): number;
2115
2204
  declare function currentContextTokens(conv: ConversationManager, anchor?: UsageAnchor): number;
2116
- declare function manageContext(conv: ConversationManager, client: LLMClient, contextWindow: number, maxOutput: number, trackingState: AutoCompactTrackingState, recoveryState: RecoveryState | null, toolSchemaNames: string[], toolSchemas: ToolSchema[], sessionFilePath?: string): Promise<CompactResult>;
2117
- declare function forceCompact(conv: ConversationManager, client: LLMClient, recoveryState: RecoveryState | null, toolSchemaNames: string[], toolSchemas: ToolSchema[], sessionFilePath?: string): Promise<CompactResult>;
2205
+ declare function manageContext(conv: ConversationManager, client: LLMClient, contextWindow: number, maxOutput: number, trackingState: AutoCompactTrackingState, recoveryState: RecoveryState | null, toolSchemaNames: string[], toolSchemas: ToolSchema[], sessionFilePath?: string, abortSignal?: AbortSignal): Promise<CompactResult>;
2206
+ declare function forceCompact(conv: ConversationManager, client: LLMClient, recoveryState: RecoveryState | null, toolSchemaNames: string[], toolSchemas: ToolSchema[], sessionFilePath?: string, abortSignal?: AbortSignal): Promise<CompactResult>;
2118
2207
 
2119
2208
  /**
2120
2209
  * Copyright (c) 2026 hangtiancheng
@@ -2174,11 +2263,11 @@ declare const REJECTED_TOOL_RESULT = "The user rejected this tool use. Nothing w
2174
2263
  * Returns a copy of the messages with the pairing relationships repaired; the input
2175
2264
  * is not modified.
2176
2265
  *
2177
- * It does two things: appends a tool_result marked as an error (immediately after)
2178
- * for any tool_use that has no result, and drops orphan tool_results whose matching
2179
- * tool_use cannot be found. The patched content is not written back to the
2180
- * conversation history: the history should faithfully record what actually happened,
2181
- * while the patching exists only to make this particular request valid.
2266
+ * Results must immediately follow their assistant turn, before any ordinary user
2267
+ * content. Group consecutive result messages, fill missing results at that turn
2268
+ * boundary, and drop orphan or duplicate results. The patched content is not written
2269
+ * back to the conversation history: the history should faithfully record what actually
2270
+ * happened, while the patching exists only to make this particular request valid.
2182
2271
  */
2183
2272
  declare function ensureToolPairing(messages: Message[]): Message[];
2184
2273
 
@@ -2449,7 +2538,7 @@ declare class MCPClient {
2449
2538
  getInstructions(): string;
2450
2539
  listTools(): Promise<MCPTool[]>;
2451
2540
  /** Calls a tool and preserves both its text fallback and provider-native rich content. */
2452
- callTool(name: string, args: Record<string, unknown>): Promise<ToolResult>;
2541
+ callTool(name: string, args: Record<string, unknown>, abortSignal?: AbortSignal): Promise<ToolResult>;
2453
2542
  disconnect(): Promise<void>;
2454
2543
  }
2455
2544
 
@@ -2635,7 +2724,7 @@ declare class MCPToolWrapper implements MCPToolLike {
2635
2724
  /** In eager mode the defer flag is cleared so MCP tools go straight into tools[]. */
2636
2725
  setDeferLoading(on: boolean): void;
2637
2726
  schema(): ToolSchema;
2638
- execute(_ctx: ToolContext, args: Record<string, unknown>): Promise<ToolResult>;
2727
+ execute(ctx: ToolContext, args: Record<string, unknown>): Promise<ToolResult>;
2639
2728
  }
2640
2729
 
2641
2730
  /**
@@ -2733,8 +2822,6 @@ declare class MemoryExtractor {
2733
2822
  private buildExtractionPrompt;
2734
2823
  /** Core extraction logic: child agent + tools */
2735
2824
  private doExtract;
2736
- /** Extract file paths from WriteFile/EditFile tool calls in conversation messages */
2737
- private extractWrittenPaths;
2738
2825
  /**
2739
2826
  * Text protocol fallback: when the sub-agent did not invoke any tools but
2740
2827
  * instead emitted structured text blocks (MEMORY_NAME/MEMORY_TYPE/MEMORY_DESC/MEMORY_BODY,
@@ -2783,10 +2870,9 @@ interface InstructionSource {
2783
2870
  *
2784
2871
  * Discovery order (later entries take higher precedence — the model attends
2785
2872
  * more to content appearing later):
2786
- * 1. User-global: ~/.swifty/SWIFTY.md, ~/.swifty/AGENTS.md
2787
- * 2. Project: SWIFTY.md, AGENTS.md, and .swifty/SWIFTY.md in every
2873
+ * 1. User-global: ~/.swifty/AGENTS.md
2874
+ * 2. Project: AGENTS.md, and .swifty/AGENTS.md in every
2788
2875
  * directory from the git root down to workDir
2789
- * 3. workDir/SWIFTY.local.md (local private override)
2790
2876
  *
2791
2877
  * Supports @include directives:
2792
2878
  * - @./relative/path, @~/home/path, @/absolute/path
@@ -3052,6 +3138,11 @@ declare class SkillCatalog {
3052
3138
  get(name: string): Skill | undefined;
3053
3139
  has(name: string): boolean;
3054
3140
  }
3141
+ declare function parseSkillFile(content: string): {
3142
+ meta: SkillMeta;
3143
+ body: string;
3144
+ frontmatter: Record<string, unknown>;
3145
+ } | null;
3055
3146
  /**
3056
3147
  * Build the Skill listing for the system prompt: only names and one-line
3057
3148
  * descriptions are included; the full SOP is fetched on demand via LoadSkill.
@@ -3194,6 +3285,7 @@ declare class RemoteServer {
3194
3285
  private opts;
3195
3286
  private agentHandle;
3196
3287
  private streaming;
3288
+ private compactController;
3197
3289
  private turnCount;
3198
3290
  private readonly eventLogger;
3199
3291
  private pendingPermissions;
@@ -3243,6 +3335,7 @@ declare class RemoteServer {
3243
3335
  run(): Promise<void>;
3244
3336
  /** Stops the server and cleans up all connections. */
3245
3337
  stop(): void;
3338
+ private cancelActiveRun;
3246
3339
  }
3247
3340
 
3248
3341
  /**
@@ -3293,6 +3386,8 @@ declare function buildTeammateRegistry(opts: {
3293
3386
  catalog: SkillCatalog;
3294
3387
  skillHost: SkillHost;
3295
3388
  mcpServers?: MCPServerConfig[];
3389
+ /** The running teammate retains this manager and disconnects it on exit. */
3390
+ mcpManager?: MCPManager;
3296
3391
  /** Used to decide the MCP loading mode: total schema volume is weighed against the context window */
3297
3392
  baseUrl?: string;
3298
3393
  contextWindow?: number;
@@ -3618,7 +3713,7 @@ declare class InstallSkillTool implements Tool {
3618
3713
  private onInstalled?;
3619
3714
  name: string;
3620
3715
  description: string;
3621
- category: "read";
3716
+ category: "write";
3622
3717
  constructor(workDir: string, catalog: SkillCatalog, onInstalled?: (() => void) | undefined);
3623
3718
  schema(): ToolSchema;
3624
3719
  execute(ctx: ToolContext, args: Record<string, unknown>): Promise<ToolResult>;
@@ -3747,22 +3842,22 @@ declare class AgentTool implements Tool {
3747
3842
  private teamRunAgentFactory?;
3748
3843
  private spawnHandler;
3749
3844
  private forkHandler?;
3750
- constructor(workDir: string, registry: ToolRegistry, spawnHandler: (def: AgentDefinition, prompt: string, bg: boolean, modelOverride?: string, workDirOverride?: string) => Promise<string>, conversation?: ConversationManager, forkHandler?: (prompt: string, conversation: ConversationManager, registry: ToolRegistry, modelOverride?: string) => Promise<string>);
3845
+ constructor(workDir: string, registry: ToolRegistry, spawnHandler: (def: AgentDefinition, prompt: string, bg: boolean, modelOverride?: string, workDirOverride?: string, context?: ToolContext) => Promise<string>, conversation?: ConversationManager, forkHandler?: (prompt: string, conversation: ConversationManager, registry: ToolRegistry, modelOverride?: string, context?: ToolContext) => Promise<string>);
3751
3846
  /**
3752
3847
  * Sets the team manager and teammate run callback, enabling the team_name parameter.
3753
3848
  * Once configured, the Agent tool can spawn teammates directly without requiring a separate SpawnTeammate tool.
3754
3849
  */
3755
- setTeamManager(mgr: TeamManager, runAgentFactory: (registry: ToolRegistry, checker?: PermissionChecker) => RunAgent): void;
3850
+ setTeamManager(mgr: TeamManager, runAgentFactory: (registry: ToolRegistry, checker?: PermissionChecker, workDir?: string) => RunAgent): void;
3756
3851
  schema(): ToolSchema;
3757
3852
  private buildDescription;
3758
- execute(_ctx: ToolContext, args: Record<string, unknown>): Promise<ToolResult>;
3853
+ execute(ctx: ToolContext, args: Record<string, unknown>): Promise<ToolResult>;
3759
3854
  /**
3760
3855
  * Team-member mode: Spawns a persistent teammate in the specified team.
3761
3856
  * Delegates to Team.spawnTeammate() to start the idle-poll main loop.
3762
3857
  */
3763
3858
  private runAsTeammate;
3764
3859
  /**
3765
- * Fork mode: Inherits parent conversation context and runs in the background.
3860
+ * Fork mode: Inherits a snapshot of parent conversation context.
3766
3861
  * Unlike definition mode, the forked subagent can see the full history of the parent conversation,
3767
3862
  * achieving byte alignment for the prompt-cache prefix to improve cache hit rate.
3768
3863
  */
@@ -3829,10 +3924,17 @@ type AgentEventSink = (event: {
3829
3924
  };
3830
3925
  text?: string;
3831
3926
  }) => void;
3927
+ interface SubagentRunOptions {
3928
+ abortSignal?: AbortSignal;
3929
+ background?: boolean;
3930
+ onPermissionRequest?: AgentConfig["onPermissionRequest"];
3931
+ permissionMode?: PermissionChecker["mode"];
3932
+ conversation?: ConversationManager;
3933
+ }
3832
3934
  declare function spawnSubagent(definition: AgentDefinition, prompt: string, parentClient: LLMClient, parentRegistry: ToolRegistry, parentProvider: ProviderConfig, workDir: string, onProgress?: (p: {
3833
3935
  turn?: number;
3834
3936
  lastTool?: string;
3835
- }) => void, onEvent?: AgentEventSink, modelOverride?: string, checkerOverride?: PermissionChecker): Promise<string>;
3937
+ }) => void, onEvent?: AgentEventSink, modelOverride?: string, checkerOverride?: PermissionChecker, options?: SubagentRunOptions): Promise<string>;
3836
3938
 
3837
3939
  /**
3838
3940
  * Copyright (c) 2026 hangtiancheng
@@ -4401,13 +4503,13 @@ declare class BashTool implements Tool {
4401
4503
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
4402
4504
  * SOFTWARE.
4403
4505
  */
4404
- declare const BASH_DESCRIPTION = "\nExecute a shell command and return stdout and stderr.\n\nOn Windows, prefer the PowerShell tool over Bash for shell commands.\n\nIMPORTANT: Avoid using this tool to run cat, head, tail, sed, awk or echo commands. Instead use the dedicated ReadFile, EditFile, or WriteFile tools which provide a better experience.\n\nUsage Notes\n\n- The working directory persists between commands, but shell state does not.\n- Always quote file paths containing spaces with double quotes.\n- Try to maintain your current working directory using absolute paths, avoid cd unless the user explicitly requests it.\n- Optional timeout in seconds (max 600s). Default 120s.\n- When issuing multiple independent commands, make separate tool calls instead of chaining with &&.\n- Use && to chain sequential dependent commands. Use ; only when you don't care if earlier commands failed.\n\nGit Safety Protocol\n\n- NEVER run destructive git commands (push --force, reset --hard, checkout ., clean -f, branch -D) unless the user explicitly requests it.\n- NEVER skip hooks (--no-verify) unless the user explicitly requests it.\n- Prefer creating a new commit rather than amending an existing one.\n- Commit identity: adds a header: Co-Authored-By: Swifty <usr161043261@outlook.com>\n\nAvoiding unnecessary sleep commands. Do NOT retry failing commands in a sleep loop -- diagnose the root cause instead.\nWhen using find, search from \".\" or a specific path, not \"/\" -- scanning the full filesystem is too expensive.\n";
4405
- declare const POWERSHELL_DESCRIPTION = "\nExecute a PowerShell command and return stdout and stderr.\n\nThis is the RECOMMENDED shell tool on Windows -- prefer it over Bash there. It runs powershell.exe on Windows and pwsh (PowerShell Core) on other platforms.\n\nIMPORTANT: Avoid using this tool to run Get-Content, Select-String, or Write-Output/echo commands. Instead use the dedicated ReadFile, EditFile, or WriteFile tools which provide a better experience.\n\nUsage Notes\n\n- The working directory persists between commands, but shell state does not.\n- Always quote file paths containing spaces with double quotes.\n- Try to maintain your current working directory using absolute paths, avoid Set-Location/cd unless the user explicitly requests it.\n- Optional timeout in seconds (max 600s). Default 120s.\n- When issuing multiple independent commands, make separate tool calls instead of chaining with ;.\n- Use ; to chain sequential dependent commands (&& also works on PowerShell 7+).\n\nGit Safety Protocol\n\n- NEVER run destructive git commands (push --force, reset --hard, checkout ., clean -f, branch -D) unless the user explicitly requests it.\n- NEVER skip hooks (--no-verify) unless the user explicitly requests it.\n- Prefer creating a new commit rather than amending an existing one.\n- Commit identity: adds a header: Co-Authored-By: Swifty <usr161043261@outlook.com>\n\nAvoiding unnecessary Start-Sleep commands. Do NOT retry failing commands in a sleep loop -- diagnose the root cause instead.\nWhen using Get-ChildItem -Recurse, search from \".\" or a specific path, not the drive root -- scanning the full filesystem is too expensive.\n";
4406
- declare const READ_FILE_DESCRIPTION = "\nRead a file and return its contents with line numbers.\n\nUsage Notes\n\n- The file_path should be an absolute path when possible.\n- By default reads up to 2000 lines from the beginning of the file.\n- Use offset and limit to read specific parts of large files. Only read what you need.\n- Results are returned with line numbers (1-based) for easy reference.\n- This tool can only read files, not directories. Use glob to list directory contents.\n- Do NOT re-read a file you just edited to verify -- EditFile would have errored if the change failed.\n- This tool can read image files (png, jpg, jpeg, gif, webp). Image contents are returned as visual content for multimodal analysis. Line numbers and offset/limit parameters do NOT apply to image files.\n";
4407
- declare const EDIT_FILE_DESCRIPTION = "\nReplace an extract string in a file, The old_string MUST appear exactly once in the file.\n\nUsage Notes\n\n- You MUST read the file with ReadFile before editing, this tool will fail otherwise.\n- When editing text from ReadFile output, preserve the exact indentation (tabs/spaces) as shown.\n- Always prefer editing existing files over creating new ones.\n- The edit will FAIL if old_string is not unique in the file, provide more surrounding context to make it unique.\n- Use the smallest old_string that is clearly unique -- 2-4 adjacent lines is usually sufficient.\n- The new_string MUST be different from old_string.\n";
4408
- declare const WRITE_FILE_DESCRIPTION = "\nWrite content to a file, creating parent directories if needed. Overwrites existing files.\n\nUsage Notes\n\n- If modifying an existing file, prefer EditFile over WriteFile -- it only sends the diff.\n- Use this tool only to create new files or for complete rewrites.\n- You MUST read existing files with ReadFile before overwriting them.\n- NEVER create documentation files (*.md) or README files unless explicitly requested.\n";
4409
- declare const GLOB_DESCRIPTION = "\nFind files matching a glob pattern, returning relative paths sorted by modification time (newest first).\n\nUsage Notes\n\n- Supports patterns like \"**/*.ts\", \"src/js/*.js\", \"*.{ts,tsx}\".\n- Search from \".\" or a specific path, never from \"/\".\n- Hidden (dot) files and directories are included.\n- Automatically skips .git, node_modules, __pycache__, and similar directories.\n- Use this instead of find or ls command via Bash.\n";
4410
- declare const GREP_DESCRIPTION = "\nSearch file content using a regex pattern (case-insensitive), returning file:line:content matches.\n\nUsage Notes\n\n- Supports full regex syntax (e.g., \"log.*Error\", \"func\\s+\\w+\").\n- Filter files with the include parameter (e.g., \"*.ts\", \"*.{ts,tsx}\", \"src/**/*.js\").\n- Include patterns containing \"/\" match the path relative to the working directory; bare patterns like \"*.ts\" match file names at any depth.\n- Search from \".\" or a specific path, never from \"/\".\n- Automatically skips .git, node_modules, __pycache__, and similar directories.\n- Use this instead of grep or rg commands via Bash.\n";
4506
+ declare const BASH_DESCRIPTION = "\nExecute a shell command and return stdout and stderr.\n\nOn Windows, prefer the PowerShell tool over Bash for shell commands.\n\nIMPORTANT: Avoid using this tool to run cat, head, tail, sed, awk or echo commands. Instead use the dedicated ReadFile, EditFile, or WriteFile tools which provide a better experience.\n\nUsage Notes\n\n- Each call starts in the Agent's working directory with a fresh shell. Changes made by cd, variables, functions, and shell options do not persist to the next call.\n- Always quote file paths containing spaces with double quotes.\n- To run in a subdirectory, use cd with a quoted path followed by && and the command in the same call.\n- Optional timeout in seconds (max 600s). Default 120s.\n- When issuing multiple independent commands, make separate tool calls instead of chaining with &&.\n- Use && to chain sequential dependent commands. Use ; only when you don't care if earlier commands failed.\n\nGit Safety Protocol\n\n- NEVER run destructive git commands (push --force, reset --hard, checkout ., clean -f, branch -D) unless the user explicitly requests it.\n- NEVER skip hooks (--no-verify) unless the user explicitly requests it.\n- Prefer creating a new commit rather than amending an existing one.\n- Commit identity: adds a header: Co-Authored-By: Swifty <usr161043261@outlook.com>\n\nAvoiding unnecessary sleep commands. Do NOT retry failing commands in a sleep loop -- diagnose the root cause instead.\nWhen using find, search from \".\" or a specific path, not \"/\" -- scanning the full filesystem is too expensive.\n";
4507
+ declare const POWERSHELL_DESCRIPTION = "\nExecute a PowerShell command and return stdout and stderr.\n\nThis is the RECOMMENDED shell tool on Windows -- prefer it over Bash there. It runs powershell.exe on Windows and pwsh (PowerShell Core) on other platforms.\n\nIMPORTANT: Avoid using this tool to run Get-Content, Select-String, or Write-Output/echo commands. Instead use the dedicated ReadFile, EditFile, or WriteFile tools which provide a better experience.\n\nUsage Notes\n\n- Each call starts in the Agent's working directory with a fresh shell. Set-Location, variables, and shell options do not persist to the next call.\n- Always quote file paths containing spaces with double quotes.\n- To run in a subdirectory, use Set-Location -LiteralPath with a quoted path in the same call.\n- Optional timeout in seconds (max 600s). Default 120s.\n- When issuing multiple independent commands, make separate tool calls instead of chaining with ;.\n- A semicolon does not stop after failure. Check $LASTEXITCODE after native commands and use -ErrorAction Stop for dependent cmdlets. Do not assume PowerShell 7 syntax is available on Windows PowerShell.\n\nGit Safety Protocol\n\n- NEVER run destructive git commands (push --force, reset --hard, checkout ., clean -f, branch -D) unless the user explicitly requests it.\n- NEVER skip hooks (--no-verify) unless the user explicitly requests it.\n- Prefer creating a new commit rather than amending an existing one.\n- Commit identity: adds a header: Co-Authored-By: Swifty <usr161043261@outlook.com>\n\nAvoiding unnecessary Start-Sleep commands. Do NOT retry failing commands in a sleep loop -- diagnose the root cause instead.\nWhen using Get-ChildItem -Recurse, search from \".\" or a specific path, not the drive root -- scanning the full filesystem is too expensive.\n";
4508
+ declare const READ_FILE_DESCRIPTION = "\nRead a file and return its contents with line numbers.\n\nUsage Notes\n\n- file_path may be absolute or relative to the Agent's working directory.\n- By default reads up to 2000 lines from the beginning of the file.\n- offset is the number of lines to skip (0-based); limit is the maximum number of lines to return. To start at displayed line 101, use offset=100. Only read what you need.\n- Results are returned with line numbers (1-based) for easy reference.\n- This tool reads files, not directories. Use Glob to find files and Grep to locate relevant lines.\n- Large output may be saved to a readback file. Follow the returned path or request a narrower range when more content is needed.\n- A successful read refreshes the file state used by EditFile and WriteFile. If a write reports that a file changed externally, read it again before retrying.\n- This tool can read image files (png, jpg, jpeg, gif, webp). Image contents are returned as visual content for multimodal analysis. Line numbers and offset/limit parameters do NOT apply to image files.\n";
4509
+ declare const EDIT_FILE_DESCRIPTION = "\nReplace an exact text string in an existing file and return a diff of the change.\n\nUsage Notes\n\n- You MUST read the file with ReadFile before editing, this tool will fail otherwise.\n- Preserve exact whitespace and indentation from the file; exclude ReadFile's line-number prefixes.\n- Always prefer editing existing files over creating new ones.\n- By default old_string must occur exactly once. Include more surrounding context to disambiguate, or set replace_all=true only when every occurrence should change.\n- Use the smallest old_string that is clearly unique -- 2-4 adjacent lines is usually sufficient.\n- old_string must be non-empty. new_string must differ from old_string and may be empty to delete the matched text.\n- file_path may be absolute or relative to the Agent's working directory. A stale-file error requires another ReadFile and a revised edit.\n";
4510
+ declare const WRITE_FILE_DESCRIPTION = "\nWrite content to a file, creating parent directories if needed. Overwrites existing files.\n\nUsage Notes\n\n- If modifying an existing file, prefer EditFile over WriteFile -- it only sends the diff.\n- Use this tool only to create new files or for complete rewrites.\n- You MUST read existing files with ReadFile before overwriting them.\n- file_path may be absolute or relative to the Agent's working directory. content is the complete UTF-8 text, including any desired trailing newline; an empty string creates or truncates an empty file.\n- Create documentation when the requested task or active workflow requires it; avoid unrelated files.\n";
4511
+ declare const GLOB_DESCRIPTION = "\nFind files matching a glob pattern, returning paths relative to the search base, sorted by modification time (newest first).\n\nUsage Notes\n\n- Supports patterns like \"**/*.ts\", \"src/js/*.js\", \"*.{ts,tsx}\".\n- Search from \".\" or a specific path, never from \"/\".\n- Hidden (dot) files and directories are included.\n- Automatically skips .git, node_modules, __pycache__, and similar directories.\n- Returns at most 1000 matches. When limited, narrow the search; the result is not an exhaustive listing.\n- Use this instead of find or ls command via Bash.\n";
4512
+ declare const GREP_DESCRIPTION = "\nSearch file content using a regex pattern (case-insensitive), returning file:line:content matches.\n\nUsage Notes\n\n- Searches one line at a time using JavaScript-style regular expressions (e.g., \"log.*Error\"). Escape backslashes in JSON strings. Multiline matches and every PCRE extension are not supported.\n- Filter files with the include parameter (e.g., \"*.ts\", \"*.{ts,tsx}\", \"src/**/*.js\").\n- Include patterns containing \"/\" match the path relative to the working directory; bare patterns like \"*.ts\" match file names at any depth.\n- Search from \".\" or a specific path, never from \"/\".\n- Automatically skips .git, node_modules, __pycache__, and similar directories.\n- Use this instead of grep or rg commands via Bash.\n- Returns at most 500 matching lines. Narrow the search if the result limit is reached. Use ReadFile for surrounding context.\n";
4411
4513
 
4412
4514
  /**
4413
4515
  * Copyright (c) 2026 hangtiancheng
@@ -4663,14 +4765,7 @@ declare class McpCallTool implements Tool {
4663
4765
  deferred: boolean;
4664
4766
  constructor(registry: ToolRegistry);
4665
4767
  schema(): ToolSchema;
4666
- /**
4667
- * Try in order: full name / server+short name / unique short-name suffix match.
4668
- *
4669
- * The model very often passes only the short name (roughly three in ten calls in
4670
- * practice), so this must be tolerant — otherwise it needlessly costs a retry
4671
- * round.
4672
- */
4673
- private resolve;
4768
+ resolveTarget(args: Record<string, unknown>): MCPToolLike | undefined;
4674
4769
  private availableNames;
4675
4770
  execute(ctx: ToolContext, args: Record<string, unknown>): Promise<ToolResult>;
4676
4771
  }
@@ -5344,4 +5439,4 @@ declare class TaskUpdateTool implements Tool {
5344
5439
  execute(ctx: ToolContext, args: Record<string, unknown>): Promise<ToolResult>;
5345
5440
  }
5346
5441
 
5347
- export { ASYNC_AGENT_ALLOWED_TOOLS, Agent, type AgentConfig, type AgentDefinition, type AgentEvent, type AgentEventCallback, AgentEventLogger, type AgentEventSink, type AgentProgress, AgentProgressSchema, type AgentTask, AgentTool, AnthropicClient, type AppConfig, AskUserQuestionTool, type Asker, AuthenticationError, AutoCompactTrackingState, BASH_DESCRIPTION, BUILTIN_AGENTS, type Backup, BashTool, BwrapSandbox, CHARS_PER_TOKEN, COMPACT_BOUNDARY, CUSTOM_AGENT_DISALLOWED_TOOLS, CodeReviewManager, type CodeReviewMember, type CodeReviewTeam, type Command, type CommandContext, CommandRegistry, type CommandType, CommandUsageTracker, type CommentIssue, type CommentResolution, type CompactBoundaryPayload, type CompactResult, ConfigError, type ConnectResult, ContextTooLongError, ConversationManager, type CriticAssessment, type CriticEvaluation, DEFAULT_EAGER_THRESHOLD_PERCENT, type Decision, type DecisionEffect, type DetectedIde, type DiffResult, EDIT_FILE_DESCRIPTION, EditFileTool, EnterWorktreeTool, type EnvironmentContext, type EventLogger, type EventName, ExitPlanModeTool, ExitWorktreeTool, FORK_QUERY_SOURCE, type FileFeedback, FileHistory, type FileMailMessage, FileMailbox, FileStateCache, GLOB_DESCRIPTION, GREP_DESCRIPTION, GlobTool, GrepTool, type HookConfig, HookConfigSchema, type HookContext, HookEngine, type HookResult, INTERRUPTED_TOOL_RESULT, type IdeAtMention, type IdeConnection, ImageTooLargeError, InstallSkillTool, type InstructionSource, type KeptMessage, type LLMClient, LLMError, ListTeamsTool, LoadSkillTool, MAX_DIMENSION_PX, MAX_HISTORY_ENTRIES, MAX_IMAGES_PER_MESSAGE, MAX_IMAGE_BYTES_PASSTHROUGH, MCPClient, MCPManager, type MCPServerConfig, type MCPTool, type MCPToolLike, MCPToolWrapper, MCP_CALL_TOOL_NAME, MCP_NAME_SEP, MCP_TOOL_PREFIX, MSG_PLAN_APPROVAL_REQUEST, MSG_PLAN_APPROVAL_RESPONSE, MSG_SHUTDOWN_REQUEST, MSG_SHUTDOWN_RESPONSE, MSG_TEXT, type MaxTokensSetter, McpCallTool, type McpLoadingMode, type Member, MemoryConsolidator, MemoryExtractor, type MemoryFile, type MemoryHeader, MemoryManager, type Message, NATIVE_TOOL_USE_BETA, NameRegistry, NetworkError, OpenAIClient, OpenAICompatClient, type OpenAIMessageParam, POWERSHELL_DESCRIPTION, PathSandbox, PermissionChecker, type PermissionMode, PowerShellTool, type PrintArgs, PromptBuilder, type ProviderConfig, ProviderConfigSchema, type Question, type QuestionOption, READ_FILE_DESCRIPTION, REJECTED_TOOL_RESULT, RateLimitError, ReadFileTool, type RecallResult, RecoveryState, type RelevantMemory, type RemoteAgentHandle, RemoteServer, type RestoredMessage, type ReviewComment, type ReviewRequest, ReviewSession, type ReviewSummary, RuleEngine, type RunAgent, type RunCallbacks, SHUTDOWN_PREFIX, SKIP_DIRS, SUBAGENT_DISALLOWED_TOOLS, type Sandbox, type SandboxConfig, type SandboxYamlConfig, type SaveClipboardImageResult, SeatbeltSandbox, type Section, SendMessageTool, type SessionInfo, type SessionMessage, type SharedTask, SharedTaskStore, type Skill, SkillCatalog, type SkillForkHost, type SkillHost, type SkillMeta, type Snapshot, type SpawnConfig, SpawnTeammateTool, type Task$1 as StoredTask, type StreamEvent, StreamingExecutor, SyntheticOutputTool, TEAMMATE_DISALLOWED_TOOLS, TOOL_RESULT_PREVIEW_CHARS, TOOL_SEARCH_TOOL_NAME, type Task, TaskCreateTool$1 as TaskCreateTool, TaskGetTool$1 as TaskGetTool, TaskList, TaskListTool$1 as TaskListTool, TaskManager, type TaskStatus, TaskStopTool, TaskStore, type TaskUpdateFields, TaskUpdateTool$1 as TaskUpdateTool, Team, TeamCreateTool, TeamDeleteTool, type TeamFile, TeamManager, type TeamMemberEntry, TeamMemberEntrySchema, type TeamMode, TaskCreateTool as TeamTaskCreateTool, TaskGetTool as TeamTaskGetTool, TaskListTool as TeamTaskListTool, TaskUpdateTool as TeamTaskUpdateTool, type TeammateUIState, TeammateUIStateSchema, type ThinkingBlock, type Tool, type ToolActivity, ToolActivitySchema, type ToolCategory, type ToolContext, ToolRegistry, type ToolResult, type ToolResultBlock, type ToolResultContentBlock, type ToolResultRecord, type ToolSchema, ToolSearchTool, type ToolUseBlock, type ToolUseRecord, type TranscriptEntry, type UsageAnchor, type UsageInfo, WRITE_FILE_DESCRIPTION, WebSocketTransport, type WorktreeResult, WriteFileTool, _resetContextWindowCache, append, applyBudget, applyMode, approved, asCriticEvaluation, asError, asErrorString, asImageMediaType, asRecord, asString, boolArg, buildAnthropicMessages, buildChatCompletionMessages, buildDiff, buildMcpToolName, buildOpenAIInput, buildPlanModeExitReminder, buildPlanModeReentryReminder, buildPlanModeReminder, buildSkillSection, buildSystemPrompt, buildTeammateRegistry, buildWorktreeNotice, cleanExpiredSessions, clipboardImageFileName, cloneRegistryForFork, closeLogger, coerceBySchema, computeCompactThreshold, computeKeepStartIndex, connectToIde, contentToText, coordinatorActive, coordinatorReminder, coordinatorToolFilter, createAgentWorktree, createChildLogger, createClient, createDefaultCodeReviewTeam, createDefaultRegistry, createModelResolver, createProgress, createRemoteAgent, createSandbox, currentContextTokens, decideAndApply, decideMode, detectBackend, detectBackendFromEnv, detectEnvironment, detectIde, discoverInstructions, doingTasksSection, ensureToolPairing, environmentSection, estimateMessages, estimateSchemaTokens, estimateTokens, evaluateRules, executingActionsSection, expandAtRefs, expandAtRefsWithImages, extractContent, fetchModelContextWindow, fileHistoryDir, filterToolsForAgent, forceCompact, forkEnabled, formatTokens, getContextWindow, getContextWindowAsync, getCurrentBranch, getCurrentPlanPath, getMaxOutputTokens, getMediaType, getNameRegistry, getOrCreatePlanPath, getSessionFilePath, handleCodeReviewCommand, hasWorktreeChanges, identitySection, initLogger, intArg, isCoordinatorTool, isCriticEvaluation, isDiffTool, isImagePath, isMcpToolLike, isObject, isOfficialAnthropicEndpoint, isPngBuffer, isRecord, isSafeCommand, isShutdownRequest, isSpillReadback, isToolResultContentBlock, listSessions, load, loadAgentDefinitions, loadConfig, loadImageAttachment, loadInstructions, loadPlan, loadSession, loadTranscript, loadUserCommands, logger, lookupModelContextWindow, manageContext, markLastUserTailForCache, markToolsForCache, maybeResizeAndDownsampleImage, mcpCallPermissionContent, mcpContentToToolOutput, mcpToolNamePrefix, measureSchemaChars, memoryAge, memoryAgeDays, memoryFreshnessText, mergeConfig, needsToolSearchBeta, newRequestId, newSessionId, normalizeToolResultContentBlock, outputEfficiencySection, parse, parsePrintFlags, parseTeammateFlags, persistLargeResult, planApprovalRequest, planApprovalResponse, planExists, quickSort, randomCompletionVerb, randomVerb, readTeamFile, readWorktreeHeadSha, rebuildFromSession, record, recordError, recordExit, recordTokens, recordToolUse, recover, removeAgentWorktree, renderBody, replaceToolResultContent, resetPlanPath, resolveAPIKey, resolveGitDir, resolveModelId, runFork, runInline, runPrintMode, runTeammate, safeJSONParse, sanitizeNameSegment, sanitizeSegment, sanitizeTeamName, saveClipboardImage, saveCompactBoundary, saveMessage, savePlan, saveTranscript, shutdownRequest, shutdownResponse, sniffMediaType, spawnSubagent, spawnTeammate, storeClipboardImage, strArg, strList, summarizeActivities, systemSection, teamConfigPath, teamDir, teamsBaseDir, toDisplayPreview, toTry, toneStyleSection, toolResultsToRecords, toolUsesToRecords, usingToolsSection, validate, version, writeTeamFile };
5442
+ export { ASYNC_AGENT_ALLOWED_TOOLS, Agent, type AgentConfig, type AgentDefinition, type AgentEvent, type AgentEventCallback, AgentEventLogger, type AgentEventSink, type AgentProgress, AgentProgressSchema, type AgentTask, AgentTool, AnthropicClient, type AppConfig, AskUserQuestionTool, type Asker, AuthenticationError, AutoCompactTrackingState, BASH_DESCRIPTION, BUILTIN_AGENTS, type Backup, BashTool, BwrapSandbox, CHARS_PER_TOKEN, COMPACT_BOUNDARY, CUSTOM_AGENT_DISALLOWED_TOOLS, CodeReviewManager, type CodeReviewMember, type CodeReviewTeam, type Command, type CommandContext, CommandRegistry, type CommandType, CommandUsageTracker, type CommentIssue, type CommentResolution, type CompactBoundaryPayload, type CompactResult, ConfigError, type ConnectResult, ContextTooLongError, ConversationManager, type CriticAssessment, type CriticEvaluation, DEFAULT_CONTEXT_WINDOW, DEFAULT_EAGER_THRESHOLD_PERCENT, DEFAULT_MAX_OUTPUT_TOKENS, DEFAULT_THINKING_LEVEL, type Decision, type DecisionEffect, type DetectedIde, type DiffResult, EDIT_FILE_DESCRIPTION, EditFileTool, EnterWorktreeTool, type EnvironmentContext, type EventLogger, type EventName, ExitPlanModeTool, ExitWorktreeTool, FORK_QUERY_SOURCE, type FileFeedback, FileHistory, type FileMailMessage, FileMailbox, FileStateCache, GLOB_DESCRIPTION, GREP_DESCRIPTION, GlobTool, GrepTool, type HookConfig, HookConfigSchema, type HookContext, HookEngine, type HookResult, type HookRuntimeOptions, INTERRUPTED_TOOL_RESULT, type IdeAtMention, type IdeConnection, ImageTooLargeError, InstallSkillTool, type InstructionSource, type KeptMessage, type LLMClient, LLMError, ListTeamsTool, LoadSkillTool, MAX_DIMENSION_PX, MAX_HISTORY_ENTRIES, MAX_IMAGES_PER_MESSAGE, MAX_IMAGE_BYTES_PASSTHROUGH, MCPClient, MCPManager, type MCPServerConfig, type MCPTool, type MCPToolLike, MCPToolWrapper, MCP_CALL_TOOL_NAME, MCP_NAME_SEP, MCP_TOOL_PREFIX, MSG_PLAN_APPROVAL_REQUEST, MSG_PLAN_APPROVAL_RESPONSE, MSG_SHUTDOWN_REQUEST, MSG_SHUTDOWN_RESPONSE, MSG_TEXT, type MaxTokensSetter, McpCallTool, type McpLoadingMode, type Member, MemoryConsolidator, MemoryExtractor, type MemoryFile, type MemoryHeader, MemoryManager, type Message, NATIVE_TOOL_USE_BETA, NameRegistry, NetworkError, OpenAIClient, OpenAICompatClient, type OpenAIMessageParam, POWERSHELL_DESCRIPTION, PathSandbox, PermissionChecker, type PermissionMode, PowerShellTool, type PrintArgs, PromptBuilder, type ProviderConfig, ProviderConfigSchema, type Question, type QuestionOption, READ_FILE_DESCRIPTION, REJECTED_TOOL_RESULT, RateLimitError, ReadFileTool, type RecallResult, RecoveryState, type RelevantMemory, type RemoteAgentHandle, RemoteServer, type RestoredMessage, type ReviewComment, type ReviewRequest, ReviewSession, type ReviewSummary, RuleEngine, type RunAgent, type RunCallbacks, SHUTDOWN_PREFIX, SKIP_DIRS, SUBAGENT_DISALLOWED_TOOLS, type Sandbox, type SandboxConfig, type SandboxYamlConfig, type SaveClipboardImageResult, SeatbeltSandbox, type Section, SendMessageTool, type SessionInfo, type SessionMessage, type SharedTask, SharedTaskStore, type Skill, SkillCatalog, type SkillForkHost, type SkillHost, type SkillMeta, type Snapshot, type SpawnConfig, SpawnTeammateTool, type Task$1 as StoredTask, type StreamEvent, StreamingExecutor, type SubagentRunOptions, SyntheticOutputTool, TEAMMATE_DISALLOWED_TOOLS, THINKING_BUDGETS, THINKING_LEVELS, TOOL_RESULT_PREVIEW_CHARS, TOOL_SEARCH_TOOL_NAME, type Task, TaskCreateTool$1 as TaskCreateTool, TaskGetTool$1 as TaskGetTool, TaskList, TaskListTool$1 as TaskListTool, TaskManager, type TaskStatus, TaskStopTool, TaskStore, type TaskUpdateFields, TaskUpdateTool$1 as TaskUpdateTool, Team, TeamCreateTool, TeamDeleteTool, type TeamFile, TeamManager, type TeamMemberEntry, TeamMemberEntrySchema, type TeamMode, TaskCreateTool as TeamTaskCreateTool, TaskGetTool as TeamTaskGetTool, TaskListTool as TeamTaskListTool, TaskUpdateTool as TeamTaskUpdateTool, type TeammateUIState, TeammateUIStateSchema, type ThinkingBlock, type ThinkingLevel, type ThinkingLevelControl, type Tool, type ToolActivity, ToolActivitySchema, type ToolCategory, type ToolContext, ToolRegistry, type ToolResult, type ToolResultBlock, type ToolResultContentBlock, type ToolResultRecord, type ToolSchema, ToolSearchTool, type ToolUseBlock, type ToolUseRecord, type TranscriptEntry, type UsageAnchor, type UsageInfo, WRITE_FILE_DESCRIPTION, WebSocketTransport, type WorktreeResult, WriteFileTool, append, applyBudget, applyMode, approved, asCriticEvaluation, asError, asErrorString, asImageMediaType, asRecord, asString, boolArg, buildAnthropicMessages, buildChatCompletionMessages, buildDiff, buildMcpToolName, buildOpenAIInput, buildPlanModeExitReminder, buildPlanModeReentryReminder, buildPlanModeReminder, buildSkillSection, buildSystemPrompt, buildTeammateRegistry, buildWorktreeNotice, cleanExpiredSessions, clipboardImageFileName, cloneRegistryForFork, closeLogger, coerceBySchema, computeCompactThreshold, computeKeepStartIndex, connectToIde, contentToText, coordinatorActive, coordinatorReminder, coordinatorToolFilter, createAgentWorktree, createChildLogger, createClient, createDefaultCodeReviewTeam, createDefaultRegistry, createModelResolver, createProgress, createRemoteAgent, createSandbox, currentContextTokens, decideAndApply, decideMode, defaultThinkingLevelFor, detectBackend, detectBackendFromEnv, detectEnvironment, detectIde, discoverInstructions, doingTasksSection, ensureToolPairing, environmentSection, estimateMessages, estimateSchemaTokens, estimateTokens, evaluateRules, executingActionsSection, expandAtRefs, expandAtRefsWithImages, extractContent, fetchModelContextWindow, fileHistoryDir, filterToolsForAgent, forceCompact, forkEnabled, formatTokens, getContextWindow, getCurrentBranch, getCurrentPlanPath, getMaxOutputTokens, getMediaType, getNameRegistry, getOrCreatePlanPath, getSessionFilePath, getThinkingLevel, globalConfigPath, handleCodeReviewCommand, hasWorktreeChanges, identitySection, initLogger, intArg, isCoordinatorTool, isCriticEvaluation, isDiffTool, isImagePath, isMcpToolLike, isObject, isOfficialAnthropicEndpoint, isPngBuffer, isRecord, isSafeCommand, isShutdownRequest, isSpillReadback, isToolResultContentBlock, isValidThinkingLevel, listSessions, load, loadAgentDefinitions, loadConfig, loadImageAttachment, loadInstructions, loadPlan, loadSession, loadTranscript, loadUserCommands, logger, manageContext, markLastUserTailForCache, markToolsForCache, maybeResizeAndDownsampleImage, mcpCallPermissionContent, mcpContentToToolOutput, mcpToolNamePrefix, measureSchemaChars, memoryAge, memoryAgeDays, memoryFreshnessText, needsToolSearchBeta, newRequestId, newSessionId, normalizeToolResultContentBlock, outputEfficiencySection, parse, parsePrintFlags, parseSkillFile, parseTeammateFlags, persistLargeResult, planApprovalRequest, planApprovalResponse, planExists, quickSort, randomCompletionVerb, randomVerb, readTeamFile, readWorktreeHeadSha, rebuildFromSession, record, recordError, recordExit, recordTokens, recordToolUse, recover, removeAgentWorktree, renderBody, replaceToolResultContent, resetPlanPath, resolveAPIKey, resolveGitDir, resolveModelId, runFork, runInline, runPrintMode, runTeammate, safeJSONParse, sanitizeNameSegment, sanitizeSegment, sanitizeTeamName, saveClipboardImage, saveCompactBoundary, saveMessage, savePlan, saveTranscript, shutdownRequest, shutdownResponse, sniffMediaType, spawnSubagent, spawnTeammate, storeClipboardImage, strArg, strList, summarizeActivities, systemSection, teamConfigPath, teamDir, teamsBaseDir, thinkingBudgetForLevel, toDisplayPreview, toReasoningEffort, toTry, toneStyleSection, toolResultsToRecords, toolUsesToRecords, usingToolsSection, validate, version, withProviderDefaults, writeTeamFile };