@kodax-ai/kodax 0.7.50 → 0.7.52

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 (55) hide show
  1. package/CHANGELOG.md +1814 -1773
  2. package/README.md +1215 -1213
  3. package/README_CN.md +636 -634
  4. package/dist/chunks/agent-XXTR7T37.js +2 -0
  5. package/dist/chunks/argument-completer-VMH6VZ4X.js +2 -0
  6. package/dist/chunks/chunk-4RVSFOUT.js +420 -0
  7. package/dist/chunks/chunk-5USNUSTL.js +648 -0
  8. package/dist/chunks/chunk-7X7SOVER.js +492 -0
  9. package/dist/chunks/{chunk-HR64F32V.js → chunk-BFXFSEHK.js} +1 -1
  10. package/dist/chunks/chunk-HMATTIU6.js +574 -0
  11. package/dist/chunks/{chunk-SK4HOYT2.js → chunk-JJTUBNQX.js} +1 -1
  12. package/dist/chunks/chunk-LE6STNVN.js +31 -0
  13. package/dist/chunks/chunk-MFPYZT52.js +301 -0
  14. package/dist/chunks/{compaction-config-DDJSQ4OT.js → compaction-config-UBPCNGC2.js} +1 -1
  15. package/dist/chunks/{construction-bootstrap-4QNM2BVM.js → construction-bootstrap-BXRMA3KL.js} +1 -1
  16. package/dist/chunks/dist-IHH4BYIU.js +2 -0
  17. package/dist/chunks/{dist-OJSNNI7P.js → dist-Z6U7TWKJ.js} +1 -1
  18. package/dist/chunks/utils-6WZHBMCC.js +2 -0
  19. package/dist/index.d.ts +11 -11
  20. package/dist/index.js +4 -4
  21. package/dist/kodax_cli.js +1004 -978
  22. package/dist/provider-capabilities.json +2 -0
  23. package/dist/sdk-agent.d.ts +16 -10
  24. package/dist/sdk-agent.js +1 -1
  25. package/dist/sdk-coding.d.ts +32 -16
  26. package/dist/sdk-coding.js +1 -1
  27. package/dist/sdk-llm.d.ts +3 -5
  28. package/dist/sdk-llm.js +1 -1
  29. package/dist/sdk-mcp.js +1 -1
  30. package/dist/sdk-repl.d.ts +16 -727
  31. package/dist/sdk-repl.js +2 -2
  32. package/dist/sdk-session.d.ts +8 -224
  33. package/dist/sdk-session.js +1 -1
  34. package/dist/sdk-skills.js +1 -1
  35. package/dist/types-chunks/{types.d-rPRl2LSB.d.ts → base.d-BBNUF9nz.d.ts} +271 -3
  36. package/dist/types-chunks/{bash-prefix-extractor.d-B0CIb0N3.d.ts → bash-prefix-extractor.d-DBFZEwop.d.ts} +15 -521
  37. package/dist/types-chunks/{capsule.d-CwBEm6M-.d.ts → capsule.d-CNonpwAZ.d.ts} +3 -3
  38. package/dist/types-chunks/guardrail.d-B18oO1gt.d.ts +518 -0
  39. package/dist/types-chunks/{process.d-BbiXD24v.d.ts → process.d-Bj82oJhD.d.ts} +348 -275
  40. package/dist/types-chunks/{resolver.d-CQfaJbht.d.ts → resolver.d-CCX9NXWP.d.ts} +2 -2
  41. package/dist/types-chunks/sdk-session-D4tqRl0_.d.ts +977 -0
  42. package/dist/types-chunks/{storage.d-J2GqOgaX.d.ts → storage.d-CabW10Nt.d.ts} +78 -3
  43. package/dist/types-chunks/types.d-D4jL-gAA.d.ts +273 -0
  44. package/dist/types-chunks/{utils.d-D_-jrRku.d.ts → utils.d-23Gn14zP.d.ts} +7 -81
  45. package/package.json +3 -3
  46. package/dist/chunks/argument-completer-3WX5B42G.js +0 -2
  47. package/dist/chunks/chunk-5UJQ2GKJ.js +0 -574
  48. package/dist/chunks/chunk-MFOMFMSK.js +0 -1056
  49. package/dist/chunks/chunk-UB5IAZHF.js +0 -476
  50. package/dist/chunks/chunk-XZY4CIDV.js +0 -31
  51. package/dist/chunks/chunk-YJLRBIEW.js +0 -301
  52. package/dist/chunks/dist-T256OSDI.js +0 -2
  53. package/dist/chunks/utils-JHIEOX6Z.js +0 -2
  54. package/dist/types-chunks/base.d-C4jYVjJh.d.ts +0 -270
  55. package/dist/types-chunks/types.d-BnjX2Gn4.d.ts +0 -297
@@ -1,10 +1,7 @@
1
- import { M as McpConnectMode, a as McpServerConfig, b as McpServersConfig, c as McpTransportKind } from './config.d-CJy1WENT.js';
2
- import { g as KodaXGoalState, s as KodaXSessionLineage, x as KodaXSessionScope, y as KodaXSessionStorage, i as KodaXJsonValue, k as KodaXSessionArtifactLedgerEntry, S as SessionErrorMetadata } from './types.d-BnjX2Gn4.js';
3
- import { X as KodaXTokenUsage, n as KodaXMessage, E as KodaXReasoningMode, k as KodaXHarnessProfile, S as KodaXTaskWorkIntent, I as KodaXReviewScale, O as KodaXTaskComplexity, a as KodaXAmaFanoutClass, Q as KodaXTaskRoutingDecision, R as KodaXTaskType, J as KodaXRiskLevel, i as KodaXExecutionMode, c as KodaXAmaProfile, d as KodaXAmaTactic, b as KodaXAmaFanoutPolicy } from './types.d-rPRl2LSB.js';
4
- import { f as AgentMessage, aE as StopHookFn, C as ChildTaskRegistry, a$ as WorkflowEventCorrelation, s as CompactionUpdate, bb as WorkflowProcessEvent, m as AskUserQuestionOptions, k as AskUserMultiOptions, B as Guardrail, b2 as WorkflowIsolation, w as DiscoveredInstance, aI as TaskAbortRegistry, aj as RunnerToolCall, aN as ToolGuardrail } from './process.d-BbiXD24v.js';
1
+ import { U as KodaXGoalState, f as AgentMessage, b0 as StopHookFn, a4 as KodaXSessionLineage, a9 as KodaXSessionScope, aa as KodaXSessionStorage, W as KodaXJsonValue, C as ChildTaskRegistry, bl as WorkflowEventCorrelation, s as CompactionUpdate, bx as WorkflowProcessEvent, m as AskUserQuestionOptions, k as AskUserMultiOptions, y as Guardrail, bo as WorkflowIsolation, Y as KodaXSessionArtifactLedgerEntry, aN as SessionErrorMetadata, v as DiscoveredInstance, b4 as TaskAbortRegistry } from './process.d-Bj82oJhD.js';
2
+ import { _ as KodaXTokenUsage, o as KodaXMessage, G as KodaXReasoningMode, l as KodaXHarnessProfile, V as KodaXTaskWorkIntent, M as KodaXReviewScale, R as KodaXTaskComplexity, a as KodaXAmaFanoutClass, T as KodaXTaskRoutingDecision, U as KodaXTaskType, N as KodaXRiskLevel, j as KodaXExecutionMode, c as KodaXAmaProfile, d as KodaXAmaTactic, b as KodaXAmaFanoutPolicy, f as KodaXBaseProvider } from './base.d-BBNUF9nz.js';
5
3
  import { Diagnostic, Position, Location, Hover, DocumentSymbol, SymbolInformation } from 'vscode-languageserver-protocol';
6
4
  import { C as CapabilityKind, b as CapabilityResult } from './capability.d-3C62G8Eq.js';
7
- import { K as KodaXBaseProvider } from './base.d-C4jYVjJh.js';
8
5
  import { a as CostTracker } from './cost-tracker.d-wRtyEW9d.js';
9
6
 
10
7
  /**
@@ -1080,18 +1077,6 @@ interface ProviderResiliencePolicy extends ProviderResilienceConfig {
1080
1077
  provider: string;
1081
1078
  }
1082
1079
 
1083
- /**
1084
- * FEATURE_200 Phase F (v0.7.45) — MCP domain types extracted from types.ts.
1085
- * Thin KodaX-facing aliases over the @kodax-ai/agent MCP types. Re-exported
1086
- * from ../types.ts so all `../types` importers are unaffected.
1087
- */
1088
-
1089
- type KodaXMcpTransport = McpTransportKind;
1090
- type KodaXMcpConnectMode = McpConnectMode;
1091
- type KodaXMcpServerConfig = McpServerConfig;
1092
- /** Flat map of MCP server configs, keyed under `mcpServers` in config.json. */
1093
- type KodaXMcpServersConfig = McpServersConfig;
1094
-
1095
1080
  /**
1096
1081
  * FEATURE_200 Phase F (v0.7.45) — Todo domain types extracted from types.ts.
1097
1082
  * Self-contained (no other coding-type deps); re-exported from ../types.ts
@@ -1334,8 +1319,8 @@ interface KodaXEvents {
1334
1319
  * prompt contents in queue order. Empty arrays are not surfaced.
1335
1320
  */
1336
1321
  onMidTurnUserMessages?: (contents: readonly string[]) => void;
1337
- onRetry?: (reason: string, attempt: number, maxAttempts: number) => void;
1338
- onProviderRateLimit?: (attempt: number, maxRetries: number, delayMs: number) => void;
1322
+ onRetry?: (reason: string, attempt: number, maxAttempts: number, meta?: KodaXActivityEventMeta) => void;
1323
+ onProviderRateLimit?: (attempt: number, maxRetries: number, delayMs: number, meta?: KodaXActivityEventMeta) => void;
1339
1324
  /**
1340
1325
  * FEATURE_130 (v0.7.36) — structured retry-after notification.
1341
1326
  *
@@ -1360,7 +1345,7 @@ interface KodaXEvents {
1360
1345
  source: 'retry-after-seconds' | 'retry-after-date' | 'retry-after-ms' | 'exponential-backoff';
1361
1346
  attempt: number;
1362
1347
  maxAttempts: number;
1363
- }) => void;
1348
+ }, meta?: KodaXActivityEventMeta) => void;
1364
1349
  onRepoIntelligenceTrace?: (event: KodaXRepoIntelligenceTraceEvent) => void;
1365
1350
  /**
1366
1351
  * FEATURE_097 (v0.7.34): emitted whenever the Scout-seeded todo list
@@ -1373,7 +1358,7 @@ interface KodaXEvents {
1373
1358
  */
1374
1359
  onTodoUpdate?: (items: TodoList) => void;
1375
1360
  /** Structured provider recovery event (Feature 045) */
1376
- onProviderRecovery?: (event: ProviderRecoveryEvent) => void;
1361
+ onProviderRecovery?: (event: ProviderRecoveryEvent, meta?: KodaXActivityEventMeta) => void;
1377
1362
  onComplete?: () => void;
1378
1363
  onError?: (error: Error) => void;
1379
1364
  onManagedTaskStatus?: (status: KodaXManagedTaskStatusEvent) => void;
@@ -1679,6 +1664,8 @@ interface KodaXChildAgentResult {
1679
1664
  actualIterations?: number;
1680
1665
  /** Best-known token usage for this child run. Used by workflow budget accounting. */
1681
1666
  totalTokensUsed?: number;
1667
+ /** True when the child exhausted its iteration budget before completing. */
1668
+ limitReached?: boolean;
1682
1669
  /**
1683
1670
  * True when the child's `runKodaX` exited via CAP-083 AbortError silent
1684
1671
  * terminal (`KodaXResult.interrupted === true`). Surfaces the
@@ -2349,6 +2336,11 @@ interface KodaXToolExecutionContext {
2349
2336
  selfManual?: KodaXSelfManualConfig;
2350
2337
  /** Working directory used to resolve relative paths and execute shell commands. */
2351
2338
  executionCwd?: string;
2339
+ /**
2340
+ * Active skill invocation for the current managed run. Child dispatch uses
2341
+ * this to preserve the skill's support-file roots in sub-agent briefings.
2342
+ */
2343
+ skillInvocation?: KodaXSkillInvocationContext;
2352
2344
  /**
2353
2345
  * FEATURE_217 (v0.7.49): parent dir for `isolation:'worktree'` workflow child
2354
2346
  * worktrees. Workflow runs point this at `<runDir>/worktrees` so worktrees are
@@ -2640,504 +2632,6 @@ interface KodaXToolExecutionContext {
2640
2632
  goalContext?: GoalToolsContext;
2641
2633
  }
2642
2634
 
2643
- /**
2644
- * AGENTS.md - Project-level AI Context Rules Loader
2645
- *
2646
- * This module implements loading of project-level context rules from AGENTS.md files,
2647
- * inspired by pi-mono's implementation.
2648
- *
2649
- * Priority: global < root < ... < current directory < .kodax/
2650
- */
2651
- interface AgentsFile {
2652
- path: string;
2653
- content: string;
2654
- scope: 'global' | 'project' | 'directory';
2655
- }
2656
- interface LoadAgentsOptions {
2657
- /** Pass cwd explicitly for deterministic prompt building; process.cwd() is only a legacy fallback. */
2658
- cwd?: string;
2659
- kodaxDir?: string;
2660
- projectRoot?: string;
2661
- }
2662
- /**
2663
- * Get KodaX global directory.
2664
- *
2665
- * Routes through {@link getAgentConfigHome} (v0.7.35.1 FEATURE_145 3-tier
2666
- * resolution: programmatic override > KODAX_HOME env > ~/.kodax default).
2667
- */
2668
- declare function getKodaxGlobalDir(): string;
2669
- /**
2670
- * Load all AGENTS files
2671
- * Priority: global < root < ... < current directory < .kodax/
2672
- */
2673
- declare function loadAgentsFiles(options?: LoadAgentsOptions): AgentsFile[];
2674
- /**
2675
- * Format AGENTS files for system prompt
2676
- */
2677
- declare function formatAgentsForPrompt(files: AgentsFile[]): string;
2678
-
2679
- /**
2680
- * Auto-Mode Rules Loader — FEATURE_092 Phase 2b.2 (v0.7.33).
2681
- *
2682
- * Three-layer trust model for `auto-rules.jsonc` files consumed by the
2683
- * auto-mode classifier:
2684
- *
2685
- * 1. ~/.kodax/auto-rules.jsonc — user-level, always trusted
2686
- * 2. <project>/.kodax/auto-rules.jsonc — shared, opt-in (sha256 fingerprint)
2687
- * 3. <project>/.kodax/auto-rules.local.jsonc — workspace-local, gitignored, trusted
2688
- *
2689
- * Why opt-in for the shared file: a malicious PR could land an
2690
- * `auto-rules.jsonc` claiming "allow any curl" and the user wouldn't
2691
- * notice. First-checkout opt-in via fingerprint forces the user to
2692
- * acknowledge the file by content. If the fingerprint changes later,
2693
- * the file is silently skipped until re-trusted — failures favor safety.
2694
- *
2695
- * Schema (each field optional, defaults to []):
2696
- * {
2697
- * "allow": string[], // patterns the classifier defaults to allowing
2698
- * "soft_deny": string[], // patterns the classifier defaults to blocking
2699
- * "environment": string[] // background context the classifier sees verbatim
2700
- * }
2701
- *
2702
- * Merge: layers concatenated in order (user → project → local). Identical
2703
- * strings deduplicated by stable insertion (later layers win position only
2704
- * when the string is unique per layer).
2705
- */
2706
- interface AutoRules {
2707
- readonly allow: readonly string[];
2708
- readonly soft_deny: readonly string[];
2709
- readonly environment: readonly string[];
2710
- }
2711
- type RulesOrigin = 'user' | 'project' | 'local';
2712
- interface LoadedRulesSource {
2713
- readonly origin: RulesOrigin;
2714
- readonly path: string;
2715
- readonly fingerprint: string;
2716
- }
2717
- interface SkippedRulesSource {
2718
- readonly origin: 'project';
2719
- readonly path: string;
2720
- readonly fingerprint: string;
2721
- readonly reason: 'untrusted' | 'fingerprint-changed';
2722
- }
2723
- interface RulesLoadError {
2724
- readonly path: string;
2725
- readonly message: string;
2726
- }
2727
- interface RulesLoadResult {
2728
- readonly merged: AutoRules;
2729
- readonly sources: readonly LoadedRulesSource[];
2730
- readonly skipped: readonly SkippedRulesSource[];
2731
- readonly errors: readonly RulesLoadError[];
2732
- }
2733
- interface LoadAutoRulesOptions {
2734
- readonly userKodaxDir: string;
2735
- readonly projectRoot: string;
2736
- }
2737
- interface TrustState {
2738
- readonly trusted: Readonly<Record<string, string>>;
2739
- }
2740
- declare function computeRulesFingerprint(content: string): string;
2741
- declare function readTrustState(userKodaxDir: string): Promise<TrustState>;
2742
- interface TrustOptions {
2743
- readonly userKodaxDir: string;
2744
- }
2745
- declare function trustProjectRules(rulesPath: string, fingerprint: string, opts: TrustOptions): Promise<void>;
2746
- type ParseAutoRulesResult = {
2747
- readonly ok: true;
2748
- readonly rules: AutoRules;
2749
- } | {
2750
- readonly ok: false;
2751
- readonly error: string;
2752
- };
2753
- declare function parseAutoRules(src: string): ParseAutoRulesResult;
2754
- declare function loadAutoRules(opts: LoadAutoRulesOptions): Promise<RulesLoadResult>;
2755
-
2756
- /**
2757
- * Tool-Call Signals — FEATURE_158 Step 2 (v0.7.39).
2758
- *
2759
- * Mechanical pattern matches over a tool call. Signals are NOT verdicts;
2760
- * the classifier consumes them as informational input alongside transcript
2761
- * + user rules and produces the final decision (allow / block / escalate).
2762
- *
2763
- * Two invariants the producers must hold:
2764
- *
2765
- * 1. **Pure**: same `call` + `projectRoot` ⇒ same signals. No I/O, no
2766
- * timestamps, no env reads inside collectors. Collectors run on every
2767
- * non-Tier-1 tool call, so they must be cheap and deterministic.
2768
- *
2769
- * 2. **Fact-only**: a `protected_path` signal says "this command names
2770
- * path X which is under ~/.kodax/", not "this should be blocked".
2771
- * Severity stays on the producer side (e.g. `dangerous_pattern.severity`)
2772
- * so the classifier can weight signals, but the verdict is not encoded
2773
- * here.
2774
- *
2775
- * Tier 0 (absolute deny) is a separate module — signals are pre-verdict
2776
- * material consumed by Tier 2 (LLM classifier). The two paths are not
2777
- * coupled: Tier 0 catches a fixed catastrophic-pattern set; signals
2778
- * describe a wider surface for the classifier to reason about.
2779
- *
2780
- * Design ref: ADR-025, FEATURE_158 (docs/features/v0.7.39.md).
2781
- */
2782
-
2783
- /**
2784
- * One mechanical signal about a tool call. Discriminated union — consumers
2785
- * narrow on `kind` to access the kind-specific fields.
2786
- */
2787
- type ToolCallSignal = {
2788
- readonly kind: 'dangerous_pattern';
2789
- /** Pattern source (e.g. regex .source) that matched. */
2790
- readonly pattern: string;
2791
- /**
2792
- * Severity hint for the classifier.
2793
- * `high` — destructive intent typical (e.g. `git push --force`,
2794
- * `chmod 777`, `curl | bash`). Classifier should lean
2795
- * toward escalate/block.
2796
- * `medium` — risk-shaped but contextual (e.g. broad `rm`, `sudo`).
2797
- * Classifier weighs against transcript context.
2798
- */
2799
- readonly severity: 'high' | 'medium';
2800
- } | {
2801
- readonly kind: 'protected_path';
2802
- /** Path token that triggered the match (as it appeared in the call). */
2803
- readonly path: string;
2804
- /**
2805
- * `project-kodax` — under `<projectRoot>/.kodax/`
2806
- * `user-kodax` — under `~/.kodax/` (credentials zone)
2807
- */
2808
- readonly zone: 'project-kodax' | 'user-kodax';
2809
- } | {
2810
- readonly kind: 'outside_project';
2811
- readonly path: string;
2812
- } | {
2813
- readonly kind: 'shell_redirect_outside';
2814
- /** Redirection target path (`>`, `>>`, `tee` etc.). */
2815
- readonly target: string;
2816
- } | {
2817
- readonly kind: 'package_install';
2818
- readonly manager: 'npm' | 'pnpm' | 'yarn' | 'pip' | 'cargo' | 'apt' | 'brew';
2819
- } | {
2820
- readonly kind: 'git_write';
2821
- readonly verb: 'commit' | 'push' | 'reset' | 'clean' | 'rebase' | 'cherry-pick' | 'revert';
2822
- } | {
2823
- readonly kind: 'network';
2824
- readonly tool: 'curl' | 'wget' | 'fetch';
2825
- } | {
2826
- readonly kind: 'file_modification';
2827
- readonly targets: readonly string[];
2828
- };
2829
- /**
2830
- * Pulls signals from one tool call. A collector declares which tool names
2831
- * it applies to via `toolNames`; the dispatcher in `collectAllSignals`
2832
- * skips non-matching collectors so each one only sees calls it was
2833
- * designed for.
2834
- *
2835
- * `collect` returns the signals; an empty array is fine and the common
2836
- * case for benign calls.
2837
- */
2838
- interface SignalCollector {
2839
- /**
2840
- * Tool names this collector reacts to (lowercase). Other tool names
2841
- * never reach `collect`. Empty set = matches nothing (effectively
2842
- * disabled — useful only for tests).
2843
- */
2844
- readonly toolNames: ReadonlySet<string>;
2845
- /**
2846
- * Inspect the call and produce zero or more signals.
2847
- *
2848
- * Must be pure: no I/O, no timing, no global state reads. The
2849
- * `projectRoot` argument is the only environmental context — pass
2850
- * the same value through every call site to keep results stable.
2851
- */
2852
- collect(call: RunnerToolCall, projectRoot: string): readonly ToolCallSignal[];
2853
- }
2854
- /**
2855
- * Run every applicable collector on `call` and return the merged signal
2856
- * list. Order preserved: collectors run in array order; per-collector
2857
- * signal order preserved within their slice.
2858
- *
2859
- * Duplicates intentionally not deduped here — different collectors may
2860
- * legitimately surface the same kind for different reasons (e.g. a
2861
- * `protected_path` from a bash redirect target AND a `protected_path`
2862
- * from an argv token in the same command). The classifier prompt
2863
- * tolerates duplicates; dedup would risk dropping load-bearing context.
2864
- */
2865
- declare function collectAllSignals(call: RunnerToolCall, projectRoot: string, collectors: readonly SignalCollector[]): readonly ToolCallSignal[];
2866
-
2867
- /**
2868
- * Denial Tracker — FEATURE_092 Phase 2b.4 (v0.7.33).
2869
- *
2870
- * Tracks classifier blocks per session. When either threshold is crossed,
2871
- * the auto-mode engine downgrades from `llm` to `rules` (mode stays `auto`).
2872
- *
2873
- * - 3 consecutive blocks → likely an unproductive loop (agent not adapting)
2874
- * - 20 cumulative blocks → broader classifier-noise pattern in this session
2875
- *
2876
- * Both are session-scoped, shared with subagents (per design doc, to defend
2877
- * against threshold-bypass via spawning).
2878
- *
2879
- * Pure functional API: each operation returns a new tracker. No mutation.
2880
- */
2881
- declare const CONSECUTIVE_THRESHOLD = 3;
2882
- declare const CUMULATIVE_THRESHOLD = 20;
2883
- interface DenialTracker {
2884
- readonly consecutive: number;
2885
- readonly cumulative: number;
2886
- }
2887
- declare function createDenialTracker(): DenialTracker;
2888
- declare function recordBlock(t: DenialTracker): DenialTracker;
2889
- declare function recordAllow(t: DenialTracker): DenialTracker;
2890
- declare function shouldFallback$1(t: DenialTracker): boolean;
2891
-
2892
- /**
2893
- * Circuit Breaker — FEATURE_092 Phase 2b.4 (v0.7.33).
2894
- *
2895
- * Sliding-window error counter for classifier failures (timeouts, 5xx, 429,
2896
- * unparseable outputs). When ≥ 5 errors land within a 10-minute window, the
2897
- * auto-mode engine downgrades from `llm` to `rules` (mode stays `auto`) so
2898
- * the user is not blocked by a degraded classifier path.
2899
- *
2900
- * Pure functional API: each operation returns a new breaker. No mutation.
2901
- * Memory bound: stale timestamps are pruned on each recordError call so
2902
- * the timestamps array never grows unbounded.
2903
- */
2904
- declare const ERROR_THRESHOLD = 5;
2905
- declare const WINDOW_MS: number;
2906
- interface CircuitBreaker {
2907
- readonly timestamps: readonly number[];
2908
- }
2909
- declare function createCircuitBreaker(): CircuitBreaker;
2910
- declare function recordError(b: CircuitBreaker, now: number): CircuitBreaker;
2911
- declare function shouldFallback(b: CircuitBreaker, now: number): boolean;
2912
-
2913
- /**
2914
- * AutoModeToolGuardrail — FEATURE_092 Phase 2b.6 (v0.7.33).
2915
- *
2916
- * Assembles the auto-mode classifier modules (rules + projection +
2917
- * classify + denial-tracker + circuit-breaker + model-resolver) into a
2918
- * `ToolGuardrail` that the Runner calls via `beforeTool` on every
2919
- * tool invocation.
2920
- *
2921
- * Decision flow (per design doc "三层权限金字塔"):
2922
- *
2923
- * 1. Tool projection is '' (Tier 1) → allow (zero token cost)
2924
- * 2. Engine has been downgraded to rules → escalate (user confirms)
2925
- * 3. denialTracker.shouldFallback (3/20) → engine downgrade, then escalate
2926
- * 4. circuitBreaker.shouldFallback (5/10m) → engine downgrade, then escalate
2927
- * 5. classify(...) sideQuery
2928
- * allow → allow (record allow → reset consecutive)
2929
- * block → block + reason (record block)
2930
- * escalate → escalate + reason (record error)
2931
- * AbortError thrown → re-throw (propagate user cancel)
2932
- *
2933
- * State (mutable, session-scoped):
2934
- * - engine: 'llm' | 'rules' (starts at 'llm', downgrades on threshold)
2935
- * - denialTracker (immutable type, swapped on each event)
2936
- * - circuitBreaker (immutable type, swapped on each event)
2937
- *
2938
- * Subagent sharing:
2939
- * The factory accepts an optional `sharedState` ref; passing the same ref
2940
- * to a subagent's guardrail means denial / circuit / engine state is
2941
- * shared (per design doc "防绕阈值"). Without it each guardrail is
2942
- * independent.
2943
- *
2944
- * Capability check, Tier 2 path-shortcuts, and the explicit
2945
- * `supportsAutoModeClassifier` provider flag are deferred to follow-up
2946
- * phases — v1 of the guardrail relies on Tier 1 (projection==='') as the
2947
- * structural opt-out and forwards everything else to the classifier.
2948
- */
2949
-
2950
- type AutoModeEngine = 'llm' | 'rules';
2951
- interface AutoModeSharedState {
2952
- engine: AutoModeEngine;
2953
- denials: DenialTracker;
2954
- breaker: CircuitBreaker;
2955
- }
2956
- /**
2957
- * User answer for an escalated tool-call. The guardrail translates this into
2958
- * the actual `GuardrailVerdict` returned to the Runner. `'block'` preserves
2959
- * the original escalation reason as the verdict reason so downstream consumers
2960
- * see why the tool was blocked.
2961
- */
2962
- type AutoModeAskUserVerdict = 'allow' | 'block';
2963
- /**
2964
- * Optional REPL-supplied prompt callback for the 6 escalate paths in
2965
- * `beforeTool` (engine-downgraded, denial-threshold-just-crossed,
2966
- * breaker-just-tripped, classifier-error, classifier-decision-escalate,
2967
- * provider-not-configured). When supplied, the guardrail calls this and
2968
- * translates the user's answer into `'allow'` or `'block'`. When NOT
2969
- * supplied, the guardrail returns `'escalate'` as before — the Runner will
2970
- * then throw `GuardrailEscalateError` (preserves backward compat with
2971
- * SDK-side guardrail consumers that have no askUser surface).
2972
- *
2973
- * Rejection propagates: if the user cancels (Ctrl-C in the prompt), throw
2974
- * an AbortError-shaped exception and the Runner aborts the run cleanly.
2975
- */
2976
- type AutoModeAskUser = (call: RunnerToolCall, reason: string,
2977
- /**
2978
- * FEATURE_158 (v0.7.39): static-analysis signals collected for this tool
2979
- * call. Optional + readonly so existing callers without signal-aware UI
2980
- * keep working. REPL uses these to render Scope/Risk labels on the
2981
- * confirm dialog (replacing the input-marker path from FEATURE_066).
2982
- */
2983
- signals?: readonly ToolCallSignal[]) => Promise<AutoModeAskUserVerdict>;
2984
- interface AutoModeGuardrailConfig {
2985
- readonly rules: AutoRules;
2986
- readonly claudeMd?: string;
2987
- /**
2988
- * FEATURE_092 phase 2b.7b: optional user-prompt callback for escalate
2989
- * paths. See `AutoModeAskUser` for semantics.
2990
- */
2991
- readonly askUser?: AutoModeAskUser;
2992
- /**
2993
- * Look up a tool's `toClassifierInput` projection by tool name.
2994
- * Returns `undefined` when the tool isn't in the registry — guardrail
2995
- * treats that as "no projection ⇒ Tier 1 skip" (conservative for
2996
- * unknown tools is debatable; v1 favors not blocking on noise).
2997
- */
2998
- readonly getToolProjection: (toolName: string) => ((input: unknown) => string) | undefined;
2999
- /**
3000
- * Resolve a provider name to an instance. Returns `undefined` when
3001
- * unconfigured / unknown — the guardrail then escalates.
3002
- */
3003
- readonly resolveProvider: (providerName: string) => KodaXBaseProvider | undefined;
3004
- readonly defaultProvider: string;
3005
- readonly defaultModel: string;
3006
- /**
3007
- * FEATURE_092 v0.7.34 hotfix-3 — defaultProvider/defaultModel staleness fix.
3008
- *
3009
- * When supplied, these are called on EVERY classify() invocation, so the
3010
- * classifier follows the user's current main session provider/model even
3011
- * after `/model` or `/provider` mid-session swaps. Falls back to
3012
- * `defaultProvider` / `defaultModel` (static strings) when unset, preserving
3013
- * backward compatibility for SDK consumers that pass string literals.
3014
- */
3015
- readonly getDefaultProvider?: () => string;
3016
- readonly getDefaultModel?: () => string;
3017
- readonly cliFlag?: string;
3018
- readonly envVar?: string;
3019
- readonly sessionOverride?: string;
3020
- readonly userSettings?: string;
3021
- /**
3022
- * Optional cost-tracker accessors. The classifier writes its tokens to
3023
- * the tracker under `querySource: 'auto_mode'` (handled inside sideQuery).
3024
- */
3025
- readonly getCostTracker?: () => CostTracker | undefined;
3026
- readonly setCostTracker?: (t: CostTracker) => void;
3027
- /** Optional logger for engine-downgrade and config warnings. */
3028
- readonly log?: (level: 'info' | 'warn', msg: string) => void;
3029
- /**
3030
- * Fired whenever the active engine changes — both on automatic downgrades
3031
- * (denial threshold / circuit breaker) AND on manual `setEngine(...)`
3032
- * calls. UI surfaces (status bar engine indicator, slash-command
3033
- * confirmations) subscribe here so the displayed engine stays in sync
3034
- * with the guardrail's internal state without the user having to trigger
3035
- * another mode toggle just to refresh the bar.
3036
- */
3037
- readonly onEngineChange?: (engine: AutoModeEngine) => void;
3038
- /**
3039
- * Optional shared state for subagent threshold-bypass defense
3040
- * (design doc "防绕阈值"). When supplied, the parent and child
3041
- * guardrails reference the SAME object — engine downgrades and
3042
- * tracker advances are visible across the session boundary.
3043
- */
3044
- readonly sharedState?: AutoModeSharedState;
3045
- /**
3046
- * FEATURE_092 phase 2b.7b slice C: starting engine. Defaults to `'llm'`.
3047
- * Set to `'rules'` to skip the classifier entirely from session start
3048
- * (the rules-mode escalate path runs immediately on the first non-Tier-1
3049
- * tool call). Resolved by the REPL from `~/.kodax/config.json`
3050
- * `autoMode.engine` and the `KODAX_AUTO_MODE_ENGINE` env var.
3051
- */
3052
- readonly initialEngine?: AutoModeEngine;
3053
- /**
3054
- * FEATURE_092 phase 2b.7b slice C: classifier sideQuery timeout in ms.
3055
- * Defaults to 8000. Resolved by the REPL from `~/.kodax/config.json`
3056
- * `autoMode.timeoutMs`.
3057
- */
3058
- readonly timeoutMs?: number;
3059
- /**
3060
- * Project root for signal collectors. File-tool collector uses this to
3061
- * detect `outside_project` vs project-relative paths. Bash collector
3062
- * doesn't use it (command-string-level) but threads it for uniform
3063
- * collector contract.
3064
- *
3065
- * Required by FEATURE_158: if omitted, the default coding-side
3066
- * collectors produce no `outside_project` signal (degrades gracefully),
3067
- * but **REPL-injected `extraCollectors` will likely require it**.
3068
- * SDK consumers without a project root should set `projectRoot: ''`
3069
- * and supply no `extraCollectors`.
3070
- */
3071
- readonly projectRoot?: string;
3072
- /**
3073
- * Override the default signal-collector set. When unset, defaults to
3074
- * `[bashSignalCollector, fileSignalCollector]` — coding-side
3075
- * command-string + file-tool collectors that don't depend on REPL
3076
- * path utilities.
3077
- *
3078
- * Use `extraCollectors` instead if you want to **add** collectors
3079
- * without replacing the defaults.
3080
- */
3081
- readonly signalCollectors?: readonly SignalCollector[];
3082
- /**
3083
- * Additional signal collectors to merge with `signalCollectors`.
3084
- * Primary use: REPL injects a path-aware bash collector built on its
3085
- * own `extractPathsFromCommand` / `isAlwaysConfirmPath` utilities
3086
- * (those live in `@kodax/repl` for historical reasons; lifting them
3087
- * is out-of-scope for FEATURE_158 — see design doc layer-boundary
3088
- * decision).
3089
- *
3090
- * Order: defaults run first, then extras (preserves per-collector
3091
- * signal order).
3092
- */
3093
- readonly extraCollectors?: readonly SignalCollector[];
3094
- /**
3095
- * Speculative-classify quiet window (ms). When a classifier promise
3096
- * settles within this window, the guardrail uses the verdict directly
3097
- * (no confirm dialog). When the window expires, the call escalates to
3098
- * the user; the background classifier is left running for cost-tracker
3099
- * settlement but its eventual result is discarded in v1 (UI doesn't
3100
- * adopt late verdicts yet).
3101
- *
3102
- * Precedence: explicit arg > `KODAX_AUTO_SPECULATIVE_WINDOW_MS` env >
3103
- * `DEFAULT_WINDOW_MS = 500`. Set to 0 to disable speculative race
3104
- * (degrades to synchronous classify).
3105
- */
3106
- readonly speculativeWindowMs?: number;
3107
- }
3108
- /**
3109
- * Snapshot of the auto-mode guardrail's session-scoped state. Returned by
3110
- * `getStats()` for diagnostic surfaces (`/auto-denials`) and the status bar
3111
- * engine indicator. The DenialTracker / CircuitBreaker types are immutable
3112
- * value objects, so this is a copy of the references — caller cannot mutate
3113
- * guardrail state through it.
3114
- */
3115
- interface AutoModeStats {
3116
- readonly engine: AutoModeEngine;
3117
- readonly denials: DenialTracker;
3118
- readonly breaker: CircuitBreaker;
3119
- }
3120
- interface AutoModeToolGuardrail extends ToolGuardrail {
3121
- /** Current engine for this session. */
3122
- getEngine(): AutoModeEngine;
3123
- /** Snapshot of engine + denial tracker + circuit breaker. */
3124
- getStats(): AutoModeStats;
3125
- /**
3126
- * Manually set the engine. Used by `/auto-engine` slash command to flip
3127
- * back to 'llm' after an automatic downgrade or to flip to 'rules' for
3128
- * manual testing. The downgrade thresholds still operate normally — a
3129
- * subsequent threshold cross will downgrade again.
3130
- */
3131
- setEngine(engine: AutoModeEngine): void;
3132
- /** Test-only alias for getEngine(). Backward-compat for test files. */
3133
- getEngineForTest(): AutoModeEngine;
3134
- /** Test-only alias for getStats(). Backward-compat for test files. */
3135
- getStatsForTest(): AutoModeStats;
3136
- /** Test-only override: swap the provider mid-test (for downgrade scenarios). */
3137
- setProviderForTest(provider: KodaXBaseProvider): void;
3138
- }
3139
- declare function createAutoModeToolGuardrail(config: AutoModeGuardrailConfig): AutoModeToolGuardrail;
3140
-
3141
2635
  /**
3142
2636
  * Bash Command Prefix Extractor — FEATURE_153 (v0.7.38).
3143
2637
  *
@@ -3287,5 +2781,5 @@ interface CreateBashPrefixExtractorOptions {
3287
2781
  */
3288
2782
  declare function createBashPrefixExtractor(opts: CreateBashPrefixExtractorOptions): BashPrefixExtractor;
3289
2783
 
3290
- export { BASH_POLICY_SPEC as B, CONSECUTIVE_THRESHOLD as C, ERROR_THRESHOLD as E, LSP_SERVERS as aH, LspService as aL, WINDOW_MS as b7, shouldFallback as bA, shutdownDefaultLspService as bB, trustProjectRules as bC, withGoalBeforeNextTurn as bD, withGoalStopHook as bE, workflowStartOutcomeConsumesTurn as bF, buildGoalRuntimeBinding as bf, collectAllSignals as bg, computeRulesFingerprint as bh, createAutoModeToolGuardrail as bi, createBashPrefixExtractor as bj, createCircuitBreaker as bk, createDenialTracker as bl, decideWorkflowInvocation as bm, extractCommandPrefix as bn, formatAgentsForPrompt as bo, getDefaultLspService as bp, getKodaxGlobalDir as bq, loadAgentsFiles as br, loadAutoRules as bs, makeDisabledGoalToolsContext as bt, parseAutoRules as bu, readTrustState as bv, recordAllow as bw, recordBlock as bx, recordError as by, shouldFallback$1 as bz, CUMULATIVE_THRESHOLD as k };
3291
- export type { KodaXManualTopicInput as $, AgentsFile as A, DenialTracker as D, FailureStage as F, GoalBlockedResult as G, KodaXChildAgentResult as H, KodaXChildContextBundle as I, KodaXChildExecutionResult as J, KodaXActivityEventMeta as K, KodaXCompactionOverride as L, KodaXContextOptions as M, KodaXContextTokenSnapshot as N, KodaXEvents as O, KodaXFanoutBranchLifecycle as P, KodaXFanoutBranchRecord as Q, KodaXFanoutBranchTransition as R, KodaXFanoutSchedulerInput as S, KodaXFanoutSchedulerPlan as T, KodaXInputArtifact as U, KodaXManagedBudgetSnapshot as V, KodaXManagedProtocolPayload as W, KodaXManagedTask as X, KodaXManagedTaskRuntimeState as Y, KodaXManagedTaskStatusEvent as Z, KodaXManualTopicId as _, AutoModeAskUser as a, RulesLoadResult as a$, KodaXMcpConnectMode as a0, KodaXMcpServerConfig as a1, KodaXMcpServersConfig as a2, KodaXMcpTransport as a3, KodaXMemoryStrategy as a4, KodaXOptions as a5, KodaXOrchestrationVerdict as a6, KodaXParentReductionContract as a7, KodaXProviderPolicyHints as a8, KodaXRepoIntelligenceCapability as a9, KodaXTaskVerificationCriterion as aA, KodaXTaskWorkItem as aB, KodaXToolEventMeta as aC, KodaXToolExecutionContext as aD, KodaXVerificationScorecard as aE, KodaXVerificationScorecardCriterion as aF, KodaXWorkflowEventMeta as aG, LoadAgentsOptions as aI, LoadedRulesSource as aJ, LspServerInfo as aK, LspServiceConfig as aM, ProviderExecutionState as aN, ProviderRecoveryEvent as aO, ProviderResilienceConfig as aP, ProviderResiliencePolicy as aQ, RecoveryAction as aR, RecoveryDecision as aS, RecoveryLadderStep as aT, RecoveryResult as aU, ResilienceClassification as aV, ResilienceErrorClass as aW, ResolveKodaXManualInput as aX, ResolveKodaXManualOptions as aY, ResolveKodaXManualResult as aZ, RulesLoadError as a_, KodaXRepoIntelligenceMode as aa, KodaXRepoIntelligenceResolvedMode as ab, KodaXRepoIntelligenceTrace as ac, KodaXRepoIntelligenceTraceEvent as ad, KodaXRepoRoutingSignals as ae, KodaXResult as af, KodaXRoleRoundSummary as ag, KodaXRuntimeVerificationContract as ah, KodaXSelfManualConfig as ai, KodaXSessionControl as aj, KodaXSessionMutators as ak, KodaXSessionOptions as al, KodaXSkillInvocationContext as am, KodaXSkillMap as an, KodaXSkillProjectionConfidence as ao, KodaXTaskCapabilityHint as ap, KodaXTaskContract as aq, KodaXTaskEvidenceArtifact as ar, KodaXTaskEvidenceBundle as as, KodaXTaskEvidenceEntry as at, KodaXTaskRole as au, KodaXTaskRoleAssignment as av, KodaXTaskStatus as aw, KodaXTaskSurface as ax, KodaXTaskToolPolicy as ay, KodaXTaskVerificationContract as az, AutoModeAskUserVerdict as b, SignalCollector as b0, SkippedRulesSource as b1, TodoItem as b2, TodoList as b3, TodoStatus as b4, ToolCallSignal as b5, TrustState as b6, WorkflowHostPolicy as b8, WorkflowInvocationAction as b9, WorkflowInvocationPolicyDecision as ba, WorkflowInvocationPolicyInput as bb, WorkflowInvocationSource as bc, WorkflowInvocationTrigger as bd, WorkflowStartOutcome as be, AutoModeEngine as c, AutoModeGuardrailConfig as d, AutoModeSharedState as e, AutoModeStats as f, AutoModeToolGuardrail as g, AutoRules as h, BashPrefixExtractor as i, BashPrefixResult as j, ChildSnapshotEvent as l, CircuitBreaker as m, CreateBashPrefixExtractorOptions as n, DiagnosticsRequest as o, ExtensionRuntimeContract as p, ExtractCommandPrefixOptions as q, GoalCompleteResult as r, GoalCreateInput as s, GoalLifecycleContext as t, GoalRuntimeBinding as u, GoalRuntimeBindingDeps as v, GoalToolsContext as w, KodaXAgentMode as x, KodaXBudgetDisclosureZone as y, KodaXBudgetExtensionRequest as z };
2784
+ export { BASH_POLICY_SPEC as B, buildGoalRuntimeBinding as aQ, createBashPrefixExtractor as aR, decideWorkflowInvocation as aS, extractCommandPrefix as aT, getDefaultLspService as aU, makeDisabledGoalToolsContext as aV, shutdownDefaultLspService as aW, withGoalBeforeNextTurn as aX, withGoalStopHook as aY, workflowStartOutcomeConsumesTurn as aZ, LSP_SERVERS as ap, LspService as ar };
2785
+ export type { KodaXRuntimeVerificationContract as $, KodaXManagedBudgetSnapshot as A, ChildSnapshotEvent as C, DiagnosticsRequest as D, ExtensionRuntimeContract as E, FailureStage as F, GoalBlockedResult as G, KodaXManagedProtocolPayload as H, KodaXManagedTask as I, KodaXManagedTaskRuntimeState as J, KodaXActivityEventMeta as K, KodaXManagedTaskStatusEvent as L, KodaXManualTopicId as M, KodaXManualTopicInput as N, KodaXMemoryStrategy as O, KodaXOptions as P, KodaXOrchestrationVerdict as Q, KodaXParentReductionContract as R, KodaXProviderPolicyHints as S, KodaXRepoIntelligenceCapability as T, KodaXRepoIntelligenceMode as U, KodaXRepoIntelligenceResolvedMode as V, KodaXRepoIntelligenceTrace as W, KodaXRepoIntelligenceTraceEvent as X, KodaXRepoRoutingSignals as Y, KodaXResult as Z, KodaXRoleRoundSummary as _, BashPrefixExtractor as a, KodaXSelfManualConfig as a0, KodaXSessionControl as a1, KodaXSessionMutators as a2, KodaXSessionOptions as a3, KodaXSkillInvocationContext as a4, KodaXSkillMap as a5, KodaXSkillProjectionConfidence as a6, KodaXTaskCapabilityHint as a7, KodaXTaskContract as a8, KodaXTaskEvidenceArtifact as a9, RecoveryResult as aA, ResilienceClassification as aB, ResilienceErrorClass as aC, ResolveKodaXManualInput as aD, ResolveKodaXManualOptions as aE, ResolveKodaXManualResult as aF, TodoItem as aG, TodoList as aH, TodoStatus as aI, WorkflowHostPolicy as aJ, WorkflowInvocationAction as aK, WorkflowInvocationPolicyDecision as aL, WorkflowInvocationPolicyInput as aM, WorkflowInvocationSource as aN, WorkflowInvocationTrigger as aO, WorkflowStartOutcome as aP, KodaXTaskEvidenceBundle as aa, KodaXTaskEvidenceEntry as ab, KodaXTaskRole as ac, KodaXTaskRoleAssignment as ad, KodaXTaskStatus as ae, KodaXTaskSurface as af, KodaXTaskToolPolicy as ag, KodaXTaskVerificationContract as ah, KodaXTaskVerificationCriterion as ai, KodaXTaskWorkItem as aj, KodaXToolEventMeta as ak, KodaXToolExecutionContext as al, KodaXVerificationScorecard as am, KodaXVerificationScorecardCriterion as an, KodaXWorkflowEventMeta as ao, LspServerInfo as aq, LspServiceConfig as as, ProviderExecutionState as at, ProviderRecoveryEvent as au, ProviderResilienceConfig as av, ProviderResiliencePolicy as aw, RecoveryAction as ax, RecoveryDecision as ay, RecoveryLadderStep as az, BashPrefixResult as b, CreateBashPrefixExtractorOptions as c, ExtractCommandPrefixOptions as d, GoalCompleteResult as e, GoalCreateInput as f, GoalLifecycleContext as g, GoalRuntimeBinding as h, GoalRuntimeBindingDeps as i, GoalToolsContext as j, KodaXAgentMode as k, KodaXBudgetDisclosureZone as l, KodaXBudgetExtensionRequest as m, KodaXChildAgentResult as n, KodaXChildContextBundle as o, KodaXChildExecutionResult as p, KodaXCompactionOverride as q, KodaXContextOptions as r, KodaXContextTokenSnapshot as s, KodaXEvents as t, KodaXFanoutBranchLifecycle as u, KodaXFanoutBranchRecord as v, KodaXFanoutBranchTransition as w, KodaXFanoutSchedulerInput as x, KodaXFanoutSchedulerPlan as y, KodaXInputArtifact as z };
@@ -1,6 +1,6 @@
1
- import { n as KodaXMessage } from './types.d-rPRl2LSB.js';
2
- import { f as AgentMessage, ap as SessionEntry, an as Session, a3 as QueueEventListener, a4 as QueuedMessage, E as EnqueueInput, v as DequeueFilter, aq as SessionExtension, p as CompactionDetails, z as FileOperations, b5 as WorkflowMeta, b6 as WorkflowModelHint, b7 as WorkflowModule } from './process.d-BbiXD24v.js';
3
- import { s as KodaXSessionLineage, i as KodaXJsonValue, a as KodaXCompactMemorySeed, o as KodaXSessionEntry, z as KodaXSessionTreeNode, r as KodaXSessionLabelEntry, q as KodaXSessionGoalEntry, v as KodaXSessionNavigationOptions, k as KodaXSessionArtifactLedgerEntry } from './types.d-BnjX2Gn4.js';
1
+ import { o as KodaXMessage } from './base.d-BBNUF9nz.js';
2
+ import { Q as QueueEventListener, e as QueuedMessage, E as EnqueueInput, D as DequeueFilter } from './types.d-D4jL-gAA.js';
3
+ import { f as AgentMessage, aM as SessionEntry, aK as Session, aO as SessionExtension, a4 as KodaXSessionLineage, W as KodaXJsonValue, p as CompactionDetails, O as KodaXCompactMemorySeed, a0 as KodaXSessionEntry, ab as KodaXSessionTreeNode, a3 as KodaXSessionLabelEntry, a2 as KodaXSessionGoalEntry, a7 as KodaXSessionNavigationOptions, Y as KodaXSessionArtifactLedgerEntry, x as FileOperations, br as WorkflowMeta, bs as WorkflowModelHint, bt as WorkflowModule } from './process.d-Bj82oJhD.js';
4
4
 
5
5
  /**
6
6
  * @kodax-ai/agent Constants