@wrongstack/core 0.250.0 → 0.256.0

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 (104) hide show
  1. package/dist/{agent-bridge-4gc0vfW2.d.ts → agent-bridge-BrxWHEOm.d.ts} +1 -1
  2. package/dist/{agent-subagent-runner-Dz-9kiE6.d.ts → agent-subagent-runner-US741uBH.d.ts} +17 -8
  3. package/dist/{brain-sCZ3lCjq.d.ts → brain-TjEEwSpw.d.ts} +18 -1
  4. package/dist/{compactor-BRfg3QPd.d.ts → compactor-C5sT4U7I.d.ts} +1 -1
  5. package/dist/{config-eSsrto5d.d.ts → config-DuAu23zm.d.ts} +16 -1
  6. package/dist/{context-CLz3z_E8.d.ts → context-CGdgA0q6.d.ts} +13 -0
  7. package/dist/coordination/index.d.ts +14 -14
  8. package/dist/coordination/index.js +153 -2
  9. package/dist/coordination/index.js.map +1 -1
  10. package/dist/defaults/index.d.ts +25 -25
  11. package/dist/defaults/index.js +238 -42
  12. package/dist/defaults/index.js.map +1 -1
  13. package/dist/execution/index.d.ts +15 -15
  14. package/dist/execution/index.js +121 -22
  15. package/dist/execution/index.js.map +1 -1
  16. package/dist/execution/prompt-enhancer.d.ts +1 -1
  17. package/dist/extension/index.d.ts +6 -6
  18. package/dist/{goal-preamble-BjJpnLW4.d.ts → goal-preamble-UiEkbNmW.d.ts} +21 -10
  19. package/dist/{index-Dy8OwfBD.d.ts → index-CC0Mcm05.d.ts} +9 -9
  20. package/dist/{index-IehiNryU.d.ts → index-CitPrI3a.d.ts} +20 -7
  21. package/dist/index.d.ts +112 -42
  22. package/dist/index.js +759 -114
  23. package/dist/index.js.map +1 -1
  24. package/dist/infrastructure/index.d.ts +6 -6
  25. package/dist/infrastructure/index.js +12 -0
  26. package/dist/infrastructure/index.js.map +1 -1
  27. package/dist/kernel/index.d.ts +10 -10
  28. package/dist/kernel/index.js.map +1 -1
  29. package/dist/{llm-selector-D22R4AFz.d.ts → llm-selector-CJ4SyAFE.d.ts} +2 -2
  30. package/dist/{mcp-servers-DfXxCASH.d.ts → mcp-servers-D8YnLaEp.d.ts} +3 -3
  31. package/dist/models/index.d.ts +5 -5
  32. package/dist/{models-registry-DpanBg8D.d.ts → models-registry-ByZCdFuQ.d.ts} +1 -1
  33. package/dist/{multi-agent-coordinator-CnbEqpv0.d.ts → multi-agent-coordinator-DqTUEAeC.d.ts} +1 -1
  34. package/dist/{null-fleet-bus-Do1OLYpj.d.ts → null-fleet-bus-B5mfTJXT.d.ts} +17 -6
  35. package/dist/observability/index.d.ts +2 -2
  36. package/dist/{package-outdated-watcher-CA5GGB4C.d.ts → package-outdated-watcher-BSgR_kK-.d.ts} +24 -3
  37. package/dist/{parallel-eternal-engine-UZg1xOzE.d.ts → parallel-eternal-engine-C0juOszP.d.ts} +24 -10
  38. package/dist/{path-resolver-BaP06Owy.d.ts → path-resolver-CbkT-RMU.d.ts} +3 -3
  39. package/dist/{permission-DbWPbuoA.d.ts → permission-CwBBpCoF.d.ts} +1 -1
  40. package/dist/{permission-policy-AOk0LVsV.d.ts → permission-policy-B8rSu908.d.ts} +39 -2
  41. package/dist/{pipeline-D1n-gQI-.d.ts → pipeline-JG8XoudC.d.ts} +43 -3
  42. package/dist/{plan-templates-BUVRY0pU.d.ts → plan-templates-DPiQMkBz.d.ts} +5 -5
  43. package/dist/{provider-runner-D0HgUqwV.d.ts → provider-runner-hM7EXlLI.d.ts} +3 -3
  44. package/dist/{retry-policy-BVnkbMET.d.ts → retry-policy-Tg7LXkoK.d.ts} +1 -1
  45. package/dist/sdd/index.d.ts +8 -8
  46. package/dist/{secret-vault-CeVNiy_f.d.ts → secret-vault-BkYkJWQs.d.ts} +1 -1
  47. package/dist/security/index.d.ts +4 -4
  48. package/dist/security/index.js +89 -18
  49. package/dist/security/index.js.map +1 -1
  50. package/dist/{selector-Cb4_9-hf.d.ts → selector-DWsqVjGf.d.ts} +1 -1
  51. package/dist/{session-event-bridge-BhtkkFFy.d.ts → session-event-bridge-BAFWdgQ3.d.ts} +1 -1
  52. package/dist/{session-reader-CCOssnBS.d.ts → session-reader-CqRvaL5v.d.ts} +1 -1
  53. package/dist/{skill-Bj6Ezqb8.d.ts → skill-DGIXCtdv.d.ts} +6 -0
  54. package/dist/skills/index.d.ts +1 -1
  55. package/dist/storage/index.d.ts +10 -10
  56. package/dist/storage/index.js +8 -1
  57. package/dist/storage/index.js.map +1 -1
  58. package/dist/types/index.d.ts +19 -19
  59. package/dist/types/index.js +95 -25
  60. package/dist/types/index.js.map +1 -1
  61. package/dist/utils/index.d.ts +2 -2
  62. package/dist/utils/index.js +5 -0
  63. package/dist/utils/index.js.map +1 -1
  64. package/package.json +2 -2
  65. package/skills/api-design/SKILL.md +1 -0
  66. package/skills/api-design/SKILL.save.md +26 -0
  67. package/skills/audit-log/SKILL.md +9 -2
  68. package/skills/audit-log/SKILL.save.md +22 -0
  69. package/skills/bug-hunter/SKILL.md +10 -2
  70. package/skills/bug-hunter/SKILL.save.md +33 -0
  71. package/skills/chimera/SKILL.md +12 -18
  72. package/skills/chimera/SKILL.save.md +26 -0
  73. package/skills/docker-deploy/SKILL.md +1 -0
  74. package/skills/docker-deploy/SKILL.save.md +23 -0
  75. package/skills/git-flow/SKILL.md +23 -2
  76. package/skills/git-flow/SKILL.save.md +25 -0
  77. package/skills/multi-agent/SKILL.md +23 -2
  78. package/skills/multi-agent/SKILL.save.md +26 -0
  79. package/skills/node-modern/SKILL.md +2 -1
  80. package/skills/node-modern/SKILL.save.md +21 -0
  81. package/skills/observability/SKILL.md +1 -0
  82. package/skills/observability/SKILL.save.md +34 -0
  83. package/skills/output-standards/SKILL.md +133 -0
  84. package/skills/output-standards/SKILL.save.md +21 -0
  85. package/skills/prompt-engineering/SKILL.md +2 -1
  86. package/skills/prompt-engineering/SKILL.save.md +29 -0
  87. package/skills/react-modern/SKILL.md +2 -1
  88. package/skills/react-modern/SKILL.save.md +24 -0
  89. package/skills/refactor-planner/SKILL.md +9 -2
  90. package/skills/refactor-planner/SKILL.save.md +26 -0
  91. package/skills/research-web/SKILL.md +1 -0
  92. package/skills/research-web/SKILL.save.md +25 -0
  93. package/skills/sdd/SKILL.md +2 -1
  94. package/skills/sdd/SKILL.save.md +19 -0
  95. package/skills/security-scanner/SKILL.md +10 -3
  96. package/skills/security-scanner/SKILL.save.md +23 -0
  97. package/skills/skill-creator/SKILL.md +2 -1
  98. package/skills/skill-creator/SKILL.save.md +20 -0
  99. package/skills/tech-stack/SKILL.md +13 -226
  100. package/skills/tech-stack/SKILL.save.md +25 -0
  101. package/skills/testing/SKILL.md +1 -0
  102. package/skills/testing/SKILL.save.md +22 -0
  103. package/skills/typescript-strict/SKILL.md +2 -1
  104. package/skills/typescript-strict/SKILL.save.md +19 -0
@@ -1,34 +1,34 @@
1
- export { A as AgentError, k as Capabilities, u as ConfigError, g as ContentBlock, C as Context, v as ContextInit, E as ERROR_CODES, w as ErrorCode, x as ErrorSeverity, y as ErrorSubsystem, F as FileSnapshot, z as FsError, I as ImageBlock, J as JSONSchema, M as Message, B as MessageRole, f as Permission, D as PluginError, P as Provider, e as ProviderError, G as ProviderErrorBody, R as Request, b as Response, p as ResumedSession, K as RiskTier, o as RunOptions, N as SddError, q as SessionData, O as SessionError, S as SessionEvent, h as SessionMetadata, i as SessionStore, r as SessionSummary, a as SessionWriter, W as StopReason, X as StreamEvent, Y as StreamHangError, n as TextBlock, Z as ThinkingBlock, s as TodoItem, T as Tool, _ as ToolCallContext, $ as ToolError, a0 as ToolFinalEvent, j as ToolProgressEvent, m as ToolResultBlock, a1 as ToolStreamEvent, l as ToolUseBlock, U as Usage, a2 as WrongStackError, a3 as asBlocks, a4 as asText, a6 as isAgentError, a7 as isConfigError, a8 as isFsError, a9 as isImageBlock, aa as isPluginError, ab as isSddError, ac as isSessionError, ad as isTextBlock, ae as isThinkingBlock, af as isToolError, ag as isToolResultBlock, ah as isToolUseBlock, ai as isWrongStackError, aj as toWrongStackError } from '../context-CLz3z_E8.js';
2
- export { P as ProviderRunner, R as RunProviderOptions } from '../provider-runner-D0HgUqwV.js';
3
- export { A as AutonomyConfig, n as CONTEXT_WINDOW_MODES, h as Config, j as ConfigLoader, i as ConfigStore, o as ContextConfig, C as ContextWindowAggressiveOn, p as ContextWindowConfigLike, q as ContextWindowMode, r as ContextWindowModeId, g as ContextWindowPolicy, s as ContextWindowThresholds, t as CustomModelDefinition, D as DEFAULT_CONTEXT_WINDOW_MODE_ID, F as FeaturesConfig, f as HookEntry, H as HookEvent, l as HookInput, e as HookMatcher, m as HookOutcome, I as InProcessHook, u as IndexingConfig, L as LaunchConfig, v as LogConfig, c as MCPServerConfig, d as ModelMatrixEntry, w as ModelsDevModel, a as ModelsDevPayload, x as ModelsDevProvider, M as ModelsRegistry, y as PluginConfig, z as ProviderApiKey, P as ProviderConfig, b as ResolvedModel, R as ResolvedProvider, B as SessionLoggingConfig, S as ShellHook, E as SyncCategory, k as SyncConfig, T as ToolsConfig, W as WireFamily, G as formatContextWindowModeList, J as getContextWindowMode, K as isContextWindowModeId, N as listContextWindowModes, O as resolveContextWindowPolicy } from '../config-eSsrto5d.js';
4
- export { a as CompactReport, C as Compactor } from '../compactor-BRfg3QPd.js';
5
- export { a as PermissionDecision, P as PermissionPolicy, T as TrustPolicy } from '../permission-DbWPbuoA.js';
1
+ export { A as AgentError, k as Capabilities, u as ConfigError, g as ContentBlock, C as Context, v as ContextInit, E as ERROR_CODES, w as ErrorCode, x as ErrorSeverity, y as ErrorSubsystem, F as FileSnapshot, z as FsError, I as ImageBlock, J as JSONSchema, M as Message, B as MessageRole, f as Permission, D as PluginError, P as Provider, e as ProviderError, G as ProviderErrorBody, R as Request, b as Response, p as ResumedSession, K as RiskTier, o as RunOptions, N as SddError, q as SessionData, O as SessionError, S as SessionEvent, h as SessionMetadata, i as SessionStore, r as SessionSummary, a as SessionWriter, W as StopReason, X as StreamEvent, Y as StreamHangError, n as TextBlock, Z as ThinkingBlock, s as TodoItem, T as Tool, _ as ToolCallContext, $ as ToolError, a0 as ToolFinalEvent, j as ToolProgressEvent, m as ToolResultBlock, a1 as ToolStreamEvent, l as ToolUseBlock, U as Usage, a2 as WrongStackError, a3 as asBlocks, a4 as asText, a6 as isAgentError, a7 as isConfigError, a8 as isFsError, a9 as isImageBlock, aa as isPluginError, ab as isSddError, ac as isSessionError, ad as isTextBlock, ae as isThinkingBlock, af as isToolError, ag as isToolResultBlock, ah as isToolUseBlock, ai as isWrongStackError, aj as toWrongStackError } from '../context-CGdgA0q6.js';
2
+ export { P as ProviderRunner, R as RunProviderOptions } from '../provider-runner-hM7EXlLI.js';
3
+ export { A as AutonomyConfig, n as CONTEXT_WINDOW_MODES, h as Config, j as ConfigLoader, i as ConfigStore, o as ContextConfig, C as ContextWindowAggressiveOn, p as ContextWindowConfigLike, q as ContextWindowMode, r as ContextWindowModeId, g as ContextWindowPolicy, s as ContextWindowThresholds, t as CustomModelDefinition, D as DEFAULT_CONTEXT_WINDOW_MODE_ID, F as FeaturesConfig, f as HookEntry, H as HookEvent, l as HookInput, e as HookMatcher, m as HookOutcome, I as InProcessHook, u as IndexingConfig, L as LaunchConfig, v as LogConfig, c as MCPServerConfig, d as ModelMatrixEntry, w as ModelsDevModel, a as ModelsDevPayload, x as ModelsDevProvider, M as ModelsRegistry, y as PluginConfig, z as ProviderApiKey, P as ProviderConfig, b as ResolvedModel, R as ResolvedProvider, B as SessionLoggingConfig, S as ShellHook, E as SyncCategory, k as SyncConfig, T as ToolsConfig, W as WireFamily, G as formatContextWindowModeList, J as getContextWindowMode, K as isContextWindowModeId, N as listContextWindowModes, O as resolveContextWindowPolicy } from '../config-DuAu23zm.js';
4
+ export { a as CompactReport, C as Compactor } from '../compactor-C5sT4U7I.js';
5
+ export { a as PermissionDecision, P as PermissionPolicy, T as TrustPolicy } from '../permission-CwBBpCoF.js';
6
6
  export { C as CheckpointInfo, R as RewindResult, a as RewindResultExtended, S as SessionRewinder } from '../session-rewinder-C9HnMkhP.js';
7
- export { a as AddAttachmentInput, c as Attachment, d as AttachmentKind, e as AttachmentMeta, b as AttachmentRef, A as AttachmentStore, D as DefaultSessionReader } from '../session-reader-CCOssnBS.js';
7
+ export { a as AddAttachmentInput, c as Attachment, d as AttachmentKind, e as AttachmentMeta, b as AttachmentRef, A as AttachmentStore, D as DefaultSessionReader } from '../session-reader-CqRvaL5v.js';
8
8
  export { D as DEFAULT_AUTONOMY_CONFIG, a as DEFAULT_CONTEXT_CONFIG, b as DEFAULT_SESSION_LOGGING_CONFIG, c as DEFAULT_SESSION_PRUNE_DAYS, d as DEFAULT_TOOLS_CONFIG } from '../default-config-CXsDvOmP.js';
9
- export { D as DefaultSecretScrubber, a as DefaultSecretVault, S as SecretVaultOptions, d as decryptConfigSecrets, e as encryptConfigSecrets, i as isSecretField, m as migratePlaintextSecrets, r as rewriteConfigEncrypted } from '../secret-vault-CeVNiy_f.js';
9
+ export { D as DefaultSecretScrubber, a as DefaultSecretVault, S as SecretVaultOptions, d as decryptConfigSecrets, e as encryptConfigSecrets, i as isSecretField, m as migratePlaintextSecrets, r as rewriteConfigEncrypted } from '../secret-vault-BkYkJWQs.js';
10
10
  export { D as DefaultLogger, a as DefaultLoggerOptions, L as LogFormat, n as noOpLogger } from '../logger-DmmQhf4P.js';
11
- export { D as DefaultPathResolver, a as DefaultTokenCounter } from '../path-resolver-BaP06Owy.js';
12
- export { p as MEMORY_TYPE_LABELS, q as MemoryClearedPayload, r as MemoryConsolidatedPayload, k as MemoryEntry, s as MemoryForgottenPayload, t as MemoryPriority, m as MemoryRelevanceContext, u as MemoryRememberedPayload, M as MemoryScope, l as MemoryStore, v as MemoryType, S as ScoredEntry } from '../brain-sCZ3lCjq.js';
13
- import { I as IterationStage, g as ParallelIterationStage } from '../parallel-eternal-engine-UZg1xOzE.js';
14
- export { C as CompactorOptions, D as DEFAULT_RECOVERY_STRATEGIES, a as DefaultErrorHandler, b as DefaultRetryPolicy, H as HybridCompactor, R as RecoveryStrategy, T as ToolExecutor, h as buildRecoveryStrategies } from '../parallel-eternal-engine-UZg1xOzE.js';
15
- export { b as SkillEntry, S as SkillLoader, a as SkillManifest } from '../skill-Bj6Ezqb8.js';
16
- export { B as BuildContext, m as ModelCapabilities, a as Renderer, S as SystemPromptBuilder } from '../pipeline-D1n-gQI-.js';
11
+ export { D as DefaultPathResolver, a as DefaultTokenCounter } from '../path-resolver-CbkT-RMU.js';
12
+ export { p as MEMORY_TYPE_LABELS, q as MemoryClearedPayload, r as MemoryConsolidatedPayload, k as MemoryEntry, s as MemoryForgottenPayload, t as MemoryPriority, m as MemoryRelevanceContext, u as MemoryRememberedPayload, M as MemoryScope, l as MemoryStore, v as MemoryType, S as ScoredEntry } from '../brain-TjEEwSpw.js';
13
+ import { I as IterationStage, g as ParallelIterationStage } from '../parallel-eternal-engine-C0juOszP.js';
14
+ export { C as CompactorOptions, D as DEFAULT_RECOVERY_STRATEGIES, a as DefaultErrorHandler, b as DefaultRetryPolicy, H as HybridCompactor, R as RecoveryStrategy, T as ToolExecutor, h as buildRecoveryStrategies } from '../parallel-eternal-engine-C0juOszP.js';
15
+ export { b as SkillEntry, S as SkillLoader, a as SkillManifest } from '../skill-DGIXCtdv.js';
16
+ export { B as BuildContext, q as ModelCapabilities, a as Renderer, S as SystemPromptBuilder } from '../pipeline-JG8XoudC.js';
17
17
  export { I as InputReader, P as PromptOption } from '../input-reader-E-ffP2ee.js';
18
- export { O as CoordinatorEvents, C as CoordinatorStatus, D as DoneCondition, I as MCPRegistryView, L as MetricsSinkView, c as MultiAgentConfig, M as MultiAgentCoordinator, N as Plugin, P as PluginAPI, Q as PluginCapabilities, R as PluginDependency, E as PluginPipelines, _ as ProviderFactory, H as ProviderRegistryView, K as SessionWriterView, z as SlashCommand, J as SlashCommandRegistryView, e as SpawnResult, S as SubagentConfig, U as SubagentContext, V as SubagentError, W as SubagentErrorKind, X as SubagentRunContext, Y as SubagentRunOutcome, d as SubagentRunner, Z as TaskDelegation, f as TaskResult, T as TaskSpec, G as ToolRegistryView } from '../agent-subagent-runner-Dz-9kiE6.js';
19
- export { D as DefaultModelsRegistry, a as DefaultModelsRegistryOptions, c as classifyFamily } from '../models-registry-DpanBg8D.js';
18
+ export { Q as CoordinatorEvents, C as CoordinatorStatus, D as DoneCondition, I as MCPRegistryView, L as MetricsSinkView, c as MultiAgentConfig, M as MultiAgentCoordinator, O as Plugin, P as PluginAPI, N as PluginCapabilities, R as PluginDependency, E as PluginPipelines, _ as ProviderFactory, H as ProviderRegistryView, K as SessionWriterView, z as SlashCommand, J as SlashCommandRegistryView, e as SpawnResult, S as SubagentConfig, U as SubagentContext, V as SubagentError, W as SubagentErrorKind, X as SubagentRunContext, Y as SubagentRunOutcome, d as SubagentRunner, Z as TaskDelegation, f as TaskResult, T as TaskSpec, G as ToolRegistryView } from '../agent-subagent-runner-US741uBH.js';
19
+ export { D as DefaultModelsRegistry, a as DefaultModelsRegistryOptions, c as classifyFamily } from '../models-registry-ByZCdFuQ.js';
20
20
  export { D as DEFAULT_MODES, b as Mode, a as ModeConfig, c as ModeManifest, M as ModeStore } from '../mode-CZlO9iU1.js';
21
- export { I as InMemoryAgentBridge, a as InMemoryBridgeTransport, c as createMessage } from '../agent-bridge-4gc0vfW2.js';
21
+ export { I as InMemoryAgentBridge, a as InMemoryBridgeTransport, c as createMessage } from '../agent-bridge-BrxWHEOm.js';
22
22
  export { D as DEFAULT_SPEC_TEMPLATE, S as SpecAnalysis, a as SpecApiEndpoint, b as SpecRequirement, c as SpecSection, d as SpecSectionType, e as SpecStatus, f as SpecTemplate, g as SpecValidationResult, h as Specification } from '../spec-TBi3Jr6T.js';
23
23
  export { C as CriticalPathResult, f as TaskAssignment, g as TaskDependency, h as TaskEdge, i as TaskFilter, d as TaskGraph, e as TaskNode, a as TaskPriority, c as TaskProgress, j as TaskSort, b as TaskStatus, T as TaskType, k as computeTaskProgress, l as findCriticalPath, t as topologicalSort } from '../task-graph-u1q9Jkyk.js';
24
24
  export { A as AggregateHealth, a as HealthCheck, b as HealthCheckResult, H as HealthRegistry, c as HealthStatus, d as MetricLabels, e as MetricSeries, M as MetricsSink, f as MetricsSnapshot, S as Span, T as Tracer } from '../observability-D-HZN_mF.js';
25
- export { S as SystemPromptContributor } from '../index-IehiNryU.js';
25
+ export { S as SystemPromptContributor } from '../index-CitPrI3a.js';
26
26
  import '../logger-B63L5bTg.js';
27
- import '../retry-policy-BVnkbMET.js';
27
+ import '../retry-policy-Tg7LXkoK.js';
28
28
  import '../secret-vault-BJDY28ev.js';
29
29
  import '../path-resolver-CPRj4bFY.js';
30
30
  import '../goal-store-CV9Yz2X_.js';
31
- import '../multi-agent-coordinator-CnbEqpv0.js';
31
+ import '../multi-agent-coordinator-DqTUEAeC.js';
32
32
  import 'node:events';
33
33
 
34
34
  /** Union of serial and parallel autonomy engine stage types (from EternalAutonomyEngine / ParallelEternalEngine). */
@@ -981,6 +981,10 @@ var DefaultTokenCounter = class {
981
981
  const price = model ? this.priceCache.get(model) : void 0;
982
982
  if (price) {
983
983
  this.applyPrice(usage, price);
984
+ this.events?.emit("token.accounted", {
985
+ usage: this.total(),
986
+ cost: { input: this.costInput, output: this.costOutput, total: this.costInput + this.costOutput }
987
+ });
984
988
  } else if (this.registry && this.providerId && model) {
985
989
  if (this.priceCache.size >= PRICE_CACHE_MAX_SIZE) {
986
990
  const keys = [...this.priceCache.keys()];
@@ -991,6 +995,10 @@ var DefaultTokenCounter = class {
991
995
  const p = priceFromModel(m);
992
996
  this.priceCache.set(model, p);
993
997
  this.applyPrice(usage, p);
998
+ this.events?.emit("token.accounted", {
999
+ usage: this.total(),
1000
+ cost: { input: this.costInput, output: this.costOutput, total: this.costInput + this.costOutput }
1001
+ });
994
1002
  }
995
1003
  }).catch(() => {
996
1004
  this.events?.emit("token.cost_estimate_unavailable", { model: model ?? "<unknown>" });
@@ -1013,6 +1021,10 @@ var DefaultTokenCounter = class {
1013
1021
  }
1014
1022
  this.priceCache.set(resolved.modelId, price);
1015
1023
  this.applyPrice(usage, price);
1024
+ this.events?.emit("token.accounted", {
1025
+ usage: this.total(),
1026
+ cost: { input: this.costInput, output: this.costOutput, total: this.costInput + this.costOutput }
1027
+ });
1016
1028
  }
1017
1029
  total() {
1018
1030
  return {
@@ -1910,9 +1922,28 @@ var PATTERNS = [
1910
1922
  }
1911
1923
  ];
1912
1924
  var SCRUB_CHUNK_BYTES = 64 * 1024;
1925
+ function hasCredentialAnchors(text) {
1926
+ return text.includes("-----BEGIN") || // Private keys (most unique → cheap reject)
1927
+ text.includes("sk-") || // Anthropic + OpenAI keys
1928
+ text.includes("sk_") || // Stripe live/test keys
1929
+ text.includes("ghp_") || // GitHub PAT v1
1930
+ text.includes("github_pat_") || // GitHub PAT v2
1931
+ text.includes("eyJ") || // JWT
1932
+ text.includes("AKIA") || // AWS access key
1933
+ text.includes("AIza") || // GCP service key
1934
+ text.includes("xox") || // Slack token (xoxa/xoxb/xoxp/xoxo/xoxs)
1935
+ text.includes("Bearer ") || // Bearer token (space suffix reduces false positives)
1936
+ text.includes("/bot") || // Telegram bot token (URL path pattern)
1937
+ text.includes("_KEY=") || // High-entropy env vars: API_KEY=, SECRET_KEY=, ...
1938
+ text.includes("_TOKEN=") || // ACCESS_TOKEN=, AUTH_TOKEN=, ...
1939
+ text.includes("_SECRET=") || // API_SECRET=, CLIENT_SECRET=, ...
1940
+ text.includes("_PASSWORD=") || // DB_PASSWORD=, ROOT_PASSWORD=, ...
1941
+ text.includes("mongodb://") || text.includes("mongodb+srv://") || text.includes("postgres://") || text.includes("postgresql://") || text.includes("mysql://") || text.includes("redis://");
1942
+ }
1913
1943
  var DefaultSecretScrubber = class {
1914
1944
  scrub(text) {
1915
1945
  if (!text) return text;
1946
+ if (!hasCredentialAnchors(text)) return text;
1916
1947
  if (text.length <= SCRUB_CHUNK_BYTES) {
1917
1948
  return this.scrubOne(text);
1918
1949
  }
@@ -1930,6 +1961,7 @@ var DefaultSecretScrubber = class {
1930
1961
  return out.join("");
1931
1962
  }
1932
1963
  scrubOne(text) {
1964
+ if (!hasCredentialAnchors(text)) return text;
1933
1965
  let out = text;
1934
1966
  for (const p of PATTERNS) {
1935
1967
  out = out.replace(p.regex, (_match, group1, group2) => {
@@ -3181,7 +3213,7 @@ var ToolExecutor = class _ToolExecutor {
3181
3213
  const tool = this.registry.get(use.name);
3182
3214
  if (!tool) {
3183
3215
  const result = this.unknownToolResult(use, () => this.registry.list().map((t) => t.name));
3184
- budget = this.decrementBudget(result, budget);
3216
+ budget = this.budgetForString(result.content, budget);
3185
3217
  return { result, tool, durationMs: Date.now() - start };
3186
3218
  }
3187
3219
  const validation = validateAgainstSchema(use.input, tool.inputSchema);
@@ -3198,20 +3230,20 @@ ${errorDetails}
3198
3230
  Please call the tool again with arguments that match its inputSchema. You can use the "tool-help" tool with name="${tool.name}" to see the exact expected schema.`,
3199
3231
  is_error: true
3200
3232
  };
3201
- budget = this.decrementBudget(result, budget);
3233
+ budget = this.budgetForString(result.content, budget);
3202
3234
  return { result, tool, durationMs: Date.now() - start };
3203
3235
  }
3204
3236
  const toolDangerousCaps = getDangerousCapabilities(tool);
3205
3237
  if (hasMalformedArguments(use.input)) {
3206
3238
  const result = this.malformedInputResult(use, extractMalformedRaw(use.input));
3207
- budget = this.decrementBudget(result, budget);
3239
+ budget = this.budgetForString(result.content, budget);
3208
3240
  return { result, tool, durationMs: Date.now() - start };
3209
3241
  }
3210
3242
  if (this.opts.hookRunner?.has("PreToolUse")) {
3211
3243
  const pre = await this.opts.hookRunner.preToolUse(tool.name, use.input, ctx);
3212
3244
  if (pre.block) {
3213
3245
  const result = this.blockedByHookResult(use, pre.reason);
3214
- budget = this.decrementBudget(result, budget);
3246
+ budget = this.budgetForString(result.content, budget);
3215
3247
  return { result, tool, durationMs: Date.now() - start };
3216
3248
  }
3217
3249
  if (pre.input) {
@@ -3227,7 +3259,7 @@ Validation errors:
3227
3259
  ${errorDetails}`,
3228
3260
  is_error: true
3229
3261
  };
3230
- budget = this.decrementBudget(result, budget);
3262
+ budget = this.budgetForString(result.content, budget);
3231
3263
  return { result, tool, durationMs: Date.now() - start };
3232
3264
  }
3233
3265
  use = { ...use, input: pre.input };
@@ -3242,7 +3274,7 @@ ${errorDetails}`,
3242
3274
  }
3243
3275
  if (effectivePermission === "deny") {
3244
3276
  const result = this.deniedResult(use, decision.reason);
3245
- budget = this.decrementBudget(result, budget);
3277
+ budget = this.budgetForString(result.content, budget);
3246
3278
  return { result, tool, durationMs: Date.now() - start };
3247
3279
  }
3248
3280
  if (effectivePermission === "confirm") {
@@ -3255,7 +3287,7 @@ ${errorDetails}`,
3255
3287
  content: `Tool "${tool.name}" denied by user.`,
3256
3288
  is_error: true
3257
3289
  };
3258
- budget = this.decrementBudget(result, budget);
3290
+ budget = this.budgetForString(result.content, budget);
3259
3291
  return { result, tool, durationMs: Date.now() - start };
3260
3292
  }
3261
3293
  } else {
@@ -3279,7 +3311,8 @@ ${errorDetails}`,
3279
3311
  "tool.has_dangerous_capabilities": toolCapsForAudit.length > 0
3280
3312
  });
3281
3313
  try {
3282
- let result = await this.executeTool(tool, use, ctx, budget);
3314
+ let { block: result, bytes } = await this.executeTool(tool, use, ctx, budget);
3315
+ budget -= bytes;
3283
3316
  if (this.opts.hookRunner?.has("PostToolUse")) {
3284
3317
  const post = await this.opts.hookRunner.postToolUse(
3285
3318
  tool.name,
@@ -3288,12 +3321,13 @@ ${errorDetails}`,
3288
3321
  ctx
3289
3322
  );
3290
3323
  if (post.additionalContext) {
3291
- result = { ...result, content: `${result.content}
3324
+ const appended = `
3292
3325
 
3293
- ${post.additionalContext}` };
3326
+ ${post.additionalContext}`;
3327
+ result = { ...result, content: `${result.content}${appended}` };
3328
+ budget = Math.max(0, budget - Buffer.byteLength(appended, "utf8"));
3294
3329
  }
3295
3330
  }
3296
- budget = this.decrementBudget(result, budget);
3297
3331
  span?.setAttribute("tool.is_error", !!result.is_error);
3298
3332
  span?.setAttribute(
3299
3333
  "tool.output_bytes",
@@ -3310,7 +3344,7 @@ ${post.additionalContext}` };
3310
3344
  content: `Tool "${tool.name}" threw: ${scrubbed}`,
3311
3345
  is_error: true
3312
3346
  };
3313
- budget = this.decrementBudget(result, budget);
3347
+ budget = this.budgetForString(result.content, budget);
3314
3348
  if (err instanceof Error) span?.recordError(err);
3315
3349
  span?.setAttribute("tool.is_error", true);
3316
3350
  return { result, tool, durationMs: Date.now() - start };
@@ -3330,7 +3364,7 @@ ${post.additionalContext}` };
3330
3364
  content: `Tool "${use.name}" execution failed: ${scrubbed}`,
3331
3365
  is_error: true
3332
3366
  };
3333
- budget = this.decrementBudget(result, budget);
3367
+ budget = this.budgetForString(result.content, budget);
3334
3368
  return { result, tool: this.registry.get(use.name), durationMs: 0 };
3335
3369
  }
3336
3370
  };
@@ -3379,14 +3413,20 @@ ${post.additionalContext}` };
3379
3413
  const output = await this.runWithTimeout(tool, use.input, ctx.signal, ctx, use.id);
3380
3414
  const text = this.serializer.serialize(output);
3381
3415
  const scrubbed = this.opts.secretScrubber.scrub(text);
3382
- const { text: capped } = this.serializer.enforceCap(scrubbed, budget);
3416
+ const { text: capped, newBudget } = this.serializer.enforceCap(scrubbed, budget);
3383
3417
  this.opts.renderer?.writeToolResult(tool.name, capped, false);
3384
3418
  return {
3385
- type: "tool_result",
3386
- tool_use_id: use.id,
3387
- name: tool.name,
3388
- content: capped,
3389
- is_error: false
3419
+ block: {
3420
+ type: "tool_result",
3421
+ tool_use_id: use.id,
3422
+ name: tool.name,
3423
+ content: capped,
3424
+ is_error: false
3425
+ },
3426
+ // `budget - newBudget` is the exact byte count enforceCap spent
3427
+ // (capped at `budget` so a truncated output shows as `budget`
3428
+ // consumed, matching the pre-fix `decrementBudget` semantics).
3429
+ bytes: budget - newBudget
3390
3430
  };
3391
3431
  }
3392
3432
  async runWithTimeout(tool, input, parentSignal, ctx, toolUseId) {
@@ -3526,9 +3566,19 @@ ${excerpt}`;
3526
3566
  is_error: true
3527
3567
  };
3528
3568
  }
3529
- decrementBudget(result, budget) {
3530
- const contentBytes = typeof result.content === "string" ? Buffer.byteLength(result.content, "utf8") : Buffer.byteLength(JSON.stringify(result.content), "utf8");
3531
- return Math.max(0, budget - contentBytes);
3569
+ /**
3570
+ * Subtract a string-content result's UTF-8 byte length from the
3571
+ * iteration output budget. Used for synthesized results (unknown tool,
3572
+ * validation error, blocked, threw) where the content is a small
3573
+ * string built in the executor. The success path no longer goes
3574
+ * through here — `executeTool` carries the exact byte count it spent
3575
+ * in its return value, derived from `enforceCap`'s `newBudget`.
3576
+ *
3577
+ * Floors the result at 0 to match the pre-fix `decrementBudget`
3578
+ * semantics (over-budget spends don't underflow the running total).
3579
+ */
3580
+ budgetForString(content, budget) {
3581
+ return Math.max(0, budget - Buffer.byteLength(content, "utf8"));
3532
3582
  }
3533
3583
  /**
3534
3584
  * Compute the suggestedPattern string for a tool+input pair.
@@ -3634,10 +3684,19 @@ var ConversationState = class {
3634
3684
  this.emit({ kind: "message_appended", message });
3635
3685
  }
3636
3686
  replaceMessages(messages) {
3687
+ let hasToolBlock = false;
3637
3688
  for (const m of messages) {
3638
3689
  if (m._estTokens === void 0) {
3639
3690
  m._estTokens = computeMessageTokens(m);
3640
3691
  }
3692
+ if (!hasToolBlock && Array.isArray(m.content)) {
3693
+ for (const b of m.content) {
3694
+ if (b.type === "tool_use" || b.type === "tool_result") {
3695
+ hasToolBlock = true;
3696
+ break;
3697
+ }
3698
+ }
3699
+ }
3641
3700
  }
3642
3701
  const arr = this.ctx.messages;
3643
3702
  if (messages.length < arr.length) {
@@ -3646,9 +3705,7 @@ var ConversationState = class {
3646
3705
  for (let i = 0; i < messages.length; i++) {
3647
3706
  arr[i] = messages[i];
3648
3707
  }
3649
- if (messages.some(
3650
- (m) => Array.isArray(m.content) && m.content.some((b) => b.type === "tool_use" || b.type === "tool_result")
3651
- )) {
3708
+ if (hasToolBlock) {
3652
3709
  this.ctx.toolAdjacencyDirty = true;
3653
3710
  }
3654
3711
  this.emit({ kind: "messages_replaced", messages: [...messages] });
@@ -3724,6 +3781,19 @@ var Context = class {
3724
3781
  * on iterations where no tool content was added (pure text responses).
3725
3782
  */
3726
3783
  toolAdjacencyDirty = false;
3784
+ /**
3785
+ * H1: pre-computed total-request token estimate from the most recent
3786
+ * `estimateRequestTokens()` call in the agent loop's pre-flight step.
3787
+ * The middleware that decides when to compact, the `emitContextPct`
3788
+ * helper that drives the live context-fill bar, and the pre-flight
3789
+ * itself all need this number; previously each one walked the same
3790
+ * messages/system/tools arrays independently. Stashing it here lets
3791
+ * the three call sites share a single compute per iteration.
3792
+ *
3793
+ * The value is the **uncalibrated** total. Callers that want the
3794
+ * calibrated number apply the per-(provider,model) ratio themselves.
3795
+ */
3796
+ lastRequestTokens = void 0;
3727
3797
  constructor(init) {
3728
3798
  this.systemPrompt = init.systemPrompt;
3729
3799
  this.provider = init.provider;