@wrongstack/core 0.119.1 → 0.141.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 (64) hide show
  1. package/dist/{agent-bridge-PRAbEX-9.d.ts → agent-bridge-r9y6gdn4.d.ts} +1 -1
  2. package/dist/{agent-subagent-runner-DXWImnNV.d.ts → agent-subagent-runner-1GeQE_L0.d.ts} +7 -7
  3. package/dist/{brain-NZZqL8sn.d.ts → brain-Cp_3GIS2.d.ts} +14 -3
  4. package/dist/{compactor-C3stu664.d.ts → compactor-BueGt7LG.d.ts} +9 -1
  5. package/dist/{config-DZV9VK9n.d.ts → config-BaVThgnT.d.ts} +1 -1
  6. package/dist/{context-hvXINa6a.d.ts → context-C7G_MtLV.d.ts} +7 -0
  7. package/dist/coordination/index.d.ts +12 -12
  8. package/dist/coordination/index.js +31 -17
  9. package/dist/coordination/index.js.map +1 -1
  10. package/dist/defaults/index.d.ts +24 -24
  11. package/dist/defaults/index.js +638 -681
  12. package/dist/defaults/index.js.map +1 -1
  13. package/dist/execution/index.d.ts +14 -14
  14. package/dist/execution/index.js +326 -317
  15. package/dist/execution/index.js.map +1 -1
  16. package/dist/extension/index.d.ts +6 -6
  17. package/dist/{goal-preamble-COpt55W8.d.ts → goal-preamble-iuIUTQwk.d.ts} +47 -17
  18. package/dist/{index-Cj3le7TI.d.ts → index-BZdezm3g.d.ts} +8 -8
  19. package/dist/{index-4VVHuTZF.d.ts → index-CPweVoFM.d.ts} +5 -5
  20. package/dist/index.d.ts +47 -47
  21. package/dist/index.js +455 -503
  22. package/dist/index.js.map +1 -1
  23. package/dist/infrastructure/index.d.ts +6 -6
  24. package/dist/infrastructure/index.js +64 -19
  25. package/dist/infrastructure/index.js.map +1 -1
  26. package/dist/kernel/index.d.ts +9 -9
  27. package/dist/kernel/index.js.map +1 -1
  28. package/dist/{llm-selector-Bmx4PsVM.d.ts → llm-selector-CP72f1lC.d.ts} +2 -2
  29. package/dist/{mcp-servers-CofNHOqn.d.ts → mcp-servers-Bl5LTvQg.d.ts} +3 -3
  30. package/dist/models/index.d.ts +5 -5
  31. package/dist/models/index.js +53 -20
  32. package/dist/models/index.js.map +1 -1
  33. package/dist/{models-registry-BzlsjKcy.d.ts → models-registry-D90K9UnM.d.ts} +1 -1
  34. package/dist/{multi-agent-coordinator-CmDmUgq2.d.ts → multi-agent-coordinator-QWEzJDlm.d.ts} +1 -1
  35. package/dist/{null-fleet-bus-CyH2YqP4.d.ts → null-fleet-bus-BUyfqh23.d.ts} +13 -10
  36. package/dist/observability/index.d.ts +2 -2
  37. package/dist/{parallel-eternal-engine-uxVm4y4V.d.ts → parallel-eternal-engine-Dj2SYzha.d.ts} +24 -11
  38. package/dist/{path-resolver-gfoGxpdd.d.ts → path-resolver-DRjQBkoO.d.ts} +3 -3
  39. package/dist/{permission-DhLrgA30.d.ts → permission-B7nKnEvQ.d.ts} +1 -1
  40. package/dist/{permission-policy-DGOvne7i.d.ts → permission-policy-8-6zBmfA.d.ts} +2 -13
  41. package/dist/{pipeline-CqF7uju2.d.ts → pipeline-BG7UgbDc.d.ts} +2 -2
  42. package/dist/{plan-templates-DoKhzenv.d.ts → plan-templates-CkKNPU3I.d.ts} +5 -5
  43. package/dist/{provider-runner-BPlI5sPZ.d.ts → provider-runner-BNpuIyOL.d.ts} +3 -3
  44. package/dist/{retry-policy-B4Q-FZgE.d.ts → retry-policy-rutAfVeR.d.ts} +1 -1
  45. package/dist/sdd/index.d.ts +8 -8
  46. package/dist/sdd/index.js +10 -1
  47. package/dist/sdd/index.js.map +1 -1
  48. package/dist/{secret-vault-B7GnL6o9.d.ts → secret-vault-BTcC_T5v.d.ts} +3 -2
  49. package/dist/security/index.d.ts +5 -7
  50. package/dist/security/index.js +4 -35
  51. package/dist/security/index.js.map +1 -1
  52. package/dist/{selector-BakeMnWR.d.ts → selector-4vDFZKt3.d.ts} +1 -1
  53. package/dist/{session-event-bridge-DE5Oekwx.d.ts → session-event-bridge-DWlvglC2.d.ts} +2 -2
  54. package/dist/{session-reader-DFC81-4p.d.ts → session-reader-BAtCxdaw.d.ts} +1 -1
  55. package/dist/storage/index.d.ts +13 -13
  56. package/dist/storage/index.js +98 -101
  57. package/dist/storage/index.js.map +1 -1
  58. package/dist/types/index.d.ts +18 -18
  59. package/dist/types/index.js +152 -102
  60. package/dist/types/index.js.map +1 -1
  61. package/dist/utils/index.d.ts +37 -13
  62. package/dist/utils/index.js +60 -32
  63. package/dist/utils/index.js.map +1 -1
  64. package/package.json +2 -2
@@ -1,34 +1,34 @@
1
- export { A as AgentError, k as Capabilities, u as ConfigError, g as ContentBlock, 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, q as SessionData, N as SessionError, S as SessionEvent, h as SessionMetadata, i as SessionStore, r as SessionSummary, a as SessionWriter, V as StopReason, W as StreamEvent, X as StreamHangError, l as TextBlock, Y as ThinkingBlock, T as Tool, Z as ToolCallContext, _ as ToolError, $ as ToolFinalEvent, j as ToolProgressEvent, n as ToolResultBlock, a0 as ToolStreamEvent, m as ToolUseBlock, U as Usage, a1 as WrongStackError, a2 as asBlocks, a3 as asText, a5 as isAgentError, a6 as isConfigError, a7 as isFsError, a8 as isImageBlock, a9 as isPluginError, aa as isSessionError, ab as isTextBlock, ac as isThinkingBlock, ad as isToolError, ae as isToolResultBlock, af as isToolUseBlock, ag as isWrongStackError, ah as toWrongStackError } from '../context-hvXINa6a.js';
2
- export { P as ProviderRunner, R as RunProviderOptions } from '../provider-runner-BPlI5sPZ.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, x as PluginConfig, y as ProviderApiKey, P as ProviderConfig, z as SessionLoggingConfig, S as ShellHook, B as SyncCategory, k as SyncConfig, T as ToolsConfig, E as formatContextWindowModeList, G as getContextWindowMode, J as isContextWindowModeId, K as listContextWindowModes, N as resolveContextWindowPolicy } from '../config-DZV9VK9n.js';
4
- export { a as CompactReport, C as Compactor } from '../compactor-C3stu664.js';
5
- export { a as PermissionDecision, P as PermissionPolicy, T as TrustPolicy } from '../permission-DhLrgA30.js';
1
+ export { A as AgentError, k as Capabilities, u as ConfigError, g as ContentBlock, 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, q as SessionData, N as SessionError, S as SessionEvent, h as SessionMetadata, i as SessionStore, r as SessionSummary, a as SessionWriter, V as StopReason, W as StreamEvent, X as StreamHangError, l as TextBlock, Y as ThinkingBlock, T as Tool, Z as ToolCallContext, _ as ToolError, $ as ToolFinalEvent, j as ToolProgressEvent, n as ToolResultBlock, a0 as ToolStreamEvent, m as ToolUseBlock, U as Usage, a1 as WrongStackError, a2 as asBlocks, a3 as asText, a5 as isAgentError, a6 as isConfigError, a7 as isFsError, a8 as isImageBlock, a9 as isPluginError, aa as isSessionError, ab as isTextBlock, ac as isThinkingBlock, ad as isToolError, ae as isToolResultBlock, af as isToolUseBlock, ag as isWrongStackError, ah as toWrongStackError } from '../context-C7G_MtLV.js';
2
+ export { P as ProviderRunner, R as RunProviderOptions } from '../provider-runner-BNpuIyOL.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, x as PluginConfig, y as ProviderApiKey, P as ProviderConfig, z as SessionLoggingConfig, S as ShellHook, B as SyncCategory, k as SyncConfig, T as ToolsConfig, E as formatContextWindowModeList, G as getContextWindowMode, J as isContextWindowModeId, K as listContextWindowModes, N as resolveContextWindowPolicy } from '../config-BaVThgnT.js';
4
+ export { a as CompactReport, C as Compactor } from '../compactor-BueGt7LG.js';
5
+ export { a as PermissionDecision, P as PermissionPolicy, T as TrustPolicy } from '../permission-B7nKnEvQ.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-DFC81-4p.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-BAtCxdaw.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, m as migratePlaintextSecrets, r as rewriteConfigEncrypted } from '../secret-vault-B7GnL6o9.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-BTcC_T5v.js';
10
10
  export { D as DefaultLogger, a as DefaultLoggerOptions } from '../logger-B9J5puGM.js';
11
- export { D as DefaultPathResolver, a as DefaultTokenCounter } from '../path-resolver-gfoGxpdd.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-NZZqL8sn.js';
13
- import { I as IterationStage, f as ParallelIterationStage } from '../parallel-eternal-engine-uxVm4y4V.js';
14
- export { C as CompactorOptions, g as DEFAULT_RECOVERY_STRATEGIES, D as DefaultErrorHandler, a as DefaultRetryPolicy, H as HybridCompactor, R as RecoveryStrategy, T as ToolExecutor, h as buildRecoveryStrategies } from '../parallel-eternal-engine-uxVm4y4V.js';
11
+ export { D as DefaultPathResolver, a as DefaultTokenCounter } from '../path-resolver-DRjQBkoO.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-Cp_3GIS2.js';
13
+ import { I as IterationStage, f as ParallelIterationStage } from '../parallel-eternal-engine-Dj2SYzha.js';
14
+ export { C as CompactorOptions, g as DEFAULT_RECOVERY_STRATEGIES, D as DefaultErrorHandler, a as DefaultRetryPolicy, H as HybridCompactor, R as RecoveryStrategy, T as ToolExecutor, h as buildRecoveryStrategies } from '../parallel-eternal-engine-Dj2SYzha.js';
15
15
  export { b as SkillEntry, S as SkillLoader, a as SkillManifest } from '../skill-Bj6Ezqb8.js';
16
- export { B as BuildContext, b as ModelCapabilities, a as Renderer, S as SystemPromptBuilder } from '../pipeline-CqF7uju2.js';
16
+ export { B as BuildContext, b as ModelCapabilities, a as Renderer, S as SystemPromptBuilder } from '../pipeline-BG7UgbDc.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-DXWImnNV.js';
19
- export { D as DefaultModelsRegistry, a as DefaultModelsRegistryOptions, c as classifyFamily } from '../models-registry-BzlsjKcy.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-1GeQE_L0.js';
19
+ export { D as DefaultModelsRegistry, a as DefaultModelsRegistryOptions, c as classifyFamily } from '../models-registry-D90K9UnM.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-PRAbEX-9.js';
21
+ export { I as InMemoryAgentBridge, a as InMemoryBridgeTransport, c as createMessage } from '../agent-bridge-r9y6gdn4.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-4VVHuTZF.js';
25
+ export { S as SystemPromptContributor } from '../index-CPweVoFM.js';
26
26
  import '../logger-B63L5bTg.js';
27
- import '../retry-policy-B4Q-FZgE.js';
27
+ import '../retry-policy-rutAfVeR.js';
28
28
  import '../secret-vault-DoISxaKO.js';
29
29
  import '../path-resolver-CPRj4bFY.js';
30
30
  import '../goal-store-CV9Yz2X_.js';
31
- import '../multi-agent-coordinator-CmDmUgq2.js';
31
+ import '../multi-agent-coordinator-QWEzJDlm.js';
32
32
  import 'node:events';
33
33
 
34
34
  /** Union of serial and parallel autonomy engine stage types (from EternalAutonomyEngine / ParallelEternalEngine). */
@@ -945,6 +945,16 @@ function expectDefined(value, label) {
945
945
 
946
946
  // src/utils/token-estimate.ts
947
947
  var RoughTokenEstimate = (text, charsPerToken = 3.5) => Math.max(1, Math.ceil(text.length / charsPerToken));
948
+ var CALIBRATION_GLOBAL_KEY = "__global__";
949
+ var _cals = /* @__PURE__ */ new Map();
950
+ function calState(key) {
951
+ let state = _cals.get(key);
952
+ if (!state) {
953
+ state = { ratio: 1, count: 0, prevEst: 0 };
954
+ _cals.set(key, state);
955
+ }
956
+ return state;
957
+ }
948
958
  var ESTIMATE_CACHE = /* @__PURE__ */ new Map();
949
959
  var ESTIMATE_CACHE_MAX_SIZE = 1e4;
950
960
  function getCachedEstimate(key, compute) {
@@ -976,10 +986,25 @@ function estimateToolResultTokens(content) {
976
986
  function estimateTextTokens(text) {
977
987
  return RoughTokenEstimate(text);
978
988
  }
989
+ function estimateMessageTokens(messages) {
990
+ let total = 0;
991
+ for (const m of messages) {
992
+ if (typeof m.content === "string") {
993
+ total += estimateTextTokens(m.content);
994
+ } else {
995
+ for (const b of m.content) {
996
+ if (b.type === "text") total += estimateTextTokens(b.text);
997
+ else if (b.type === "tool_use") total += estimateToolInputTokens(b.input);
998
+ else if (b.type === "tool_result") total += estimateToolResultTokens(b.content);
999
+ }
1000
+ }
1001
+ }
1002
+ return total;
1003
+ }
979
1004
  function estimateToolDefTokens(tool) {
980
1005
  return RoughTokenEstimate(tool.name) + RoughTokenEstimate(tool.description ?? "") + RoughTokenEstimate(JSON.stringify(tool.inputSchema));
981
1006
  }
982
- function estimateRequestTokens(messages, systemPrompt, tools) {
1007
+ function estimateRequestTokens(messages, systemPrompt, tools, calibrationKey = CALIBRATION_GLOBAL_KEY) {
983
1008
  let messagesTokens = 0;
984
1009
  if (typeof messages === "string") {
985
1010
  messagesTokens = RoughTokenEstimate(messages);
@@ -1018,6 +1043,7 @@ function estimateRequestTokens(messages, systemPrompt, tools) {
1018
1043
  toolsTokens += estimateToolDefTokens(t);
1019
1044
  }
1020
1045
  const total = messagesTokens + systemTokens + toolsTokens;
1046
+ calState(calibrationKey).prevEst = total;
1021
1047
  return {
1022
1048
  messages: messagesTokens,
1023
1049
  systemPrompt: systemTokens,
@@ -1118,34 +1144,121 @@ function isEmptyMessage(msg) {
1118
1144
  return msg.content.length === 0;
1119
1145
  }
1120
1146
 
1147
+ // src/execution/compaction-core.ts
1148
+ var estimateMessages = estimateMessageTokens;
1149
+ function hasTextContent(m) {
1150
+ if (typeof m.content === "string") return m.content.trim().length > 0;
1151
+ return m.content.some((b) => b.type === "text" && b.text.trim().length > 0);
1152
+ }
1153
+ function findPreserveStart(messages, preserveK) {
1154
+ let pairCount = 0;
1155
+ let preserveStart = messages.length;
1156
+ for (let i = messages.length - 1; i >= 0 && pairCount < preserveK; i--) {
1157
+ const m = messages[i];
1158
+ if (!m) continue;
1159
+ if (m.role === "user" || m.role === "assistant") {
1160
+ pairCount++;
1161
+ preserveStart = i;
1162
+ }
1163
+ }
1164
+ for (let i = preserveStart; i < messages.length; i++) {
1165
+ const m = messages[i];
1166
+ if (!m || typeof m.content === "string" || !Array.isArray(m.content)) continue;
1167
+ const hasToolUse2 = m.content.some((b) => b.type === "tool_use");
1168
+ if (hasToolUse2 && i + 1 < messages.length) {
1169
+ const next = messages[i + 1];
1170
+ if (next && next.role === "user" && typeof next.content !== "string" && Array.isArray(next.content) && next.content.some((b) => b.type === "tool_result")) {
1171
+ preserveStart = i + 1;
1172
+ }
1173
+ }
1174
+ }
1175
+ return preserveStart;
1176
+ }
1177
+ function eliseOldToolResults(messages, opts) {
1178
+ const preserveStart = findPreserveStart(messages, opts.preserveK);
1179
+ let saved = 0;
1180
+ let changed = false;
1181
+ const next = new Array(messages.length);
1182
+ for (let i = 0; i < messages.length; i++) {
1183
+ const msg = messages[i];
1184
+ if (i >= preserveStart || !msg || !Array.isArray(msg.content)) {
1185
+ next[i] = msg;
1186
+ continue;
1187
+ }
1188
+ const original = msg.content;
1189
+ const newContent = original.map((b) => {
1190
+ if (b.type !== "tool_result") return b;
1191
+ const tokens = estimateToolResultTokens(b.content);
1192
+ if (tokens < opts.eliseThreshold) return b;
1193
+ saved += tokens;
1194
+ const elided = {
1195
+ type: "tool_result",
1196
+ tool_use_id: b.tool_use_id,
1197
+ content: `[elided: ~${tokens} tokens]`,
1198
+ is_error: b.is_error
1199
+ };
1200
+ return elided;
1201
+ });
1202
+ if (newContent.every((b, idx) => b === original[idx])) {
1203
+ next[i] = msg;
1204
+ } else {
1205
+ next[i] = { ...msg, content: newContent };
1206
+ changed = true;
1207
+ }
1208
+ }
1209
+ return { messages: changed ? next : messages, saved, changed };
1210
+ }
1211
+ function buildLosslessDigest(messages) {
1212
+ const lines = [];
1213
+ for (const m of messages) {
1214
+ let text;
1215
+ let omitted = 0;
1216
+ if (typeof m.content === "string") {
1217
+ text = m.content;
1218
+ } else {
1219
+ const parts = [];
1220
+ for (const b of m.content) {
1221
+ if (isTextBlock(b)) parts.push(b.text);
1222
+ else if (b.type === "tool_use" || b.type === "tool_result") omitted++;
1223
+ }
1224
+ text = parts.join(" ");
1225
+ }
1226
+ if (text.trim().length === 0 && omitted === 0) continue;
1227
+ const marker = omitted > 0 ? ` [${omitted} tool call(s) omitted \u2014 see session log]` : "";
1228
+ lines.push(`[${m.role}]: ${text}${marker}`);
1229
+ }
1230
+ return lines.join("\n");
1231
+ }
1232
+
1121
1233
  // src/execution/compactor.ts
1122
1234
  var HybridCompactor = class {
1123
1235
  preserveK;
1124
1236
  eliseThreshold;
1125
- estimator;
1126
1237
  constructor(opts = {}) {
1127
1238
  this.preserveK = opts.preserveK ?? 5;
1128
1239
  this.eliseThreshold = opts.eliseThreshold ?? 2e3;
1129
- this.estimator = opts.estimator ?? estimateTextTokens;
1130
1240
  }
1131
1241
  async compact(ctx, opts = {}) {
1132
- const beforeTokens = this.estimateMessages(ctx.messages);
1242
+ const beforeTokens = estimateMessages(ctx.messages);
1133
1243
  const beforeFull = this.estimateFullRequest(ctx);
1134
1244
  const reductions = [];
1135
1245
  const policy = readContextWindowPolicy(ctx);
1136
1246
  const preserveK = policy?.preserveK ?? this.preserveK;
1137
1247
  const eliseThreshold = policy?.eliseThreshold ?? this.eliseThreshold;
1138
- const phase1Saved = this.eliseOldToolResults(ctx, preserveK, eliseThreshold);
1139
- if (phase1Saved > 0) reductions.push({ phase: "elision", saved: phase1Saved });
1248
+ const elide = eliseOldToolResults(ctx.messages, { preserveK, eliseThreshold });
1249
+ if (elide.changed) ctx.state.replaceMessages(elide.messages);
1250
+ if (elide.saved > 0) reductions.push({ phase: "elision", saved: elide.saved });
1251
+ let collapsedDigest;
1140
1252
  if (opts.aggressive) {
1141
- const phase2Saved = this.collapseAncientTurns(ctx, preserveK);
1142
- if (phase2Saved > 0) reductions.push({ phase: "summary", saved: phase2Saved });
1253
+ const phase2 = this.collapseAncientTurns(ctx, preserveK);
1254
+ if (phase2.saved > 0) reductions.push({ phase: "summary", saved: phase2.saved });
1255
+ collapsedDigest = phase2.digest;
1143
1256
  }
1144
1257
  const repaired = repairToolUseAdjacency(ctx.messages);
1145
1258
  if (repaired.report.changed) {
1146
1259
  ctx.state.replaceMessages(repaired.messages);
1147
1260
  }
1148
- const afterTokens = this.estimateMessages(ctx.messages);
1261
+ const afterTokens = estimateMessages(ctx.messages);
1149
1262
  const afterFull = this.estimateFullRequest(ctx);
1150
1263
  return {
1151
1264
  before: beforeTokens,
@@ -1153,6 +1266,7 @@ var HybridCompactor = class {
1153
1266
  fullRequestTokensBefore: beforeFull,
1154
1267
  fullRequestTokensAfter: afterFull,
1155
1268
  reductions,
1269
+ collapsedDigest,
1156
1270
  repaired: repaired.report.changed ? {
1157
1271
  removedToolUses: repaired.report.removedToolUses,
1158
1272
  removedToolResults: repaired.report.removedToolResults,
@@ -1165,72 +1279,23 @@ var HybridCompactor = class {
1165
1279
  * This is the accurate figure for context-window pressure monitoring.
1166
1280
  */
1167
1281
  estimateFullRequest(ctx) {
1168
- const breakdown = estimateRequestTokens(ctx.messages, ctx.systemPrompt, ctx.tools ?? []);
1169
- return breakdown.total;
1170
- }
1171
- eliseOldToolResults(ctx, preserveK = this.preserveK, eliseThreshold = this.eliseThreshold) {
1172
- const messages = ctx.messages;
1173
- let pairCount = 0;
1174
- let preserveStart = messages.length;
1175
- for (let i = messages.length - 1; i >= 0 && pairCount < preserveK; i--) {
1176
- const m = messages[i];
1177
- if (!m) continue;
1178
- if (m.role === "user" || m.role === "assistant") {
1179
- pairCount++;
1180
- preserveStart = i;
1181
- }
1182
- }
1183
- for (let i = preserveStart; i < messages.length; i++) {
1184
- const m = messages[i];
1185
- if (!m || typeof m.content === "string" || !Array.isArray(m.content)) continue;
1186
- const hasToolUse2 = m.content.some((b) => b.type === "tool_use");
1187
- if (hasToolUse2 && i + 1 < messages.length) {
1188
- const next = messages[i + 1];
1189
- if (next && next.role === "user" && typeof next.content !== "string" && Array.isArray(next.content) && next.content.some((b) => b.type === "tool_result")) {
1190
- preserveStart = i + 1;
1191
- }
1192
- }
1193
- }
1194
- let saved = 0;
1195
- let changed = false;
1196
- const nextMessages = new Array(messages.length);
1197
- for (let i = 0; i < messages.length; i++) {
1198
- const msg = messages[i];
1199
- if (i >= preserveStart) {
1200
- nextMessages[i] = msg;
1201
- continue;
1202
- }
1203
- if (!msg || !Array.isArray(msg.content)) {
1204
- nextMessages[i] = msg;
1205
- continue;
1206
- }
1207
- const newContent = msg.content.map((b) => {
1208
- if (b.type !== "tool_result") return b;
1209
- const tokens = estimateToolResultTokens(b.content);
1210
- if (tokens < eliseThreshold) return b;
1211
- saved += tokens;
1212
- const elided = {
1213
- type: "tool_result",
1214
- tool_use_id: b.tool_use_id,
1215
- content: `[elided: ~${tokens} tokens]`,
1216
- is_error: b.is_error
1217
- };
1218
- return elided;
1219
- });
1220
- if (newContent.length === msg.content.length && newContent.every((b, idx) => b === msg.content[idx])) {
1221
- nextMessages[i] = msg;
1222
- } else {
1223
- nextMessages[i] = { ...msg, content: newContent };
1224
- changed = true;
1225
- }
1226
- }
1227
- if (changed) ctx.state.replaceMessages(nextMessages);
1228
- return saved;
1282
+ return estimateRequestTokens(ctx.messages, ctx.systemPrompt, ctx.tools ?? []).total;
1229
1283
  }
1284
+ /**
1285
+ * Lossless rule-based collapse of ancient turns into a single digest message.
1286
+ *
1287
+ * Preserves ALL textual content of the collapsed range — user instructions,
1288
+ * assistant decisions/conclusions, and any prior digests (chained forward so
1289
+ * the digest stays lossless across repeated compactions). Only `tool_use` /
1290
+ * `tool_result` protocol blocks are dropped and replaced with a count marker;
1291
+ * their full payload already lives in the session log. No sub-LLM call.
1292
+ *
1293
+ * Returns the token savings and the digest text (for audit logging).
1294
+ */
1230
1295
  collapseAncientTurns(ctx, preserveK = this.preserveK) {
1231
1296
  const messages = ctx.messages;
1232
1297
  const cutTarget = Math.max(0, messages.length - preserveK * 2);
1233
- if (cutTarget <= 0) return 0;
1298
+ if (cutTarget <= 0) return { saved: 0 };
1234
1299
  let boundary = -1;
1235
1300
  for (let i = cutTarget; i < messages.length; i++) {
1236
1301
  const m = messages[i];
@@ -1240,34 +1305,20 @@ var HybridCompactor = class {
1240
1305
  break;
1241
1306
  }
1242
1307
  }
1243
- if (boundary <= 0) return 0;
1308
+ if (boundary <= 0) return { saved: 0 };
1244
1309
  const removed = messages.slice(0, boundary);
1245
- const removedTokens = this.estimateMessages(removed);
1246
- const summary = [
1247
- {
1248
- role: "user",
1249
- content: `[previous_session_summary: ${removed.length} earlier turns compacted. Todo state preserved in context.]`
1250
- },
1251
- { role: "assistant", content: "Continuing from compacted context." }
1252
- ];
1310
+ const removedTokens = estimateMessages(removed);
1311
+ const digest = buildLosslessDigest(removed) || `${removed.length} earlier turns (no textual content; tool I/O omitted \u2014 see session log)`;
1312
+ const summaryMsg = {
1313
+ role: "system",
1314
+ content: `[prior_turns_digest: ${digest}]`
1315
+ };
1253
1316
  const tail = ctx.messages.slice(boundary);
1254
- ctx.state.replaceMessages([...summary, ...tail]);
1255
- return Math.max(0, removedTokens - this.estimateMessages(summary));
1256
- }
1257
- estimateMessages(messages) {
1258
- let total = 0;
1259
- for (const m of messages) {
1260
- if (typeof m.content === "string") {
1261
- total += this.estimator(m.content);
1262
- } else {
1263
- for (const b of m.content) {
1264
- if (b.type === "text") total += this.estimator(b.text);
1265
- else if (b.type === "tool_use") total += estimateToolInputTokens(b.input);
1266
- else if (b.type === "tool_result") total += estimateToolResultTokens(b.content);
1267
- }
1268
- }
1269
- }
1270
- return total;
1317
+ ctx.state.replaceMessages([summaryMsg, ...tail]);
1318
+ return {
1319
+ saved: Math.max(0, removedTokens - estimateMessages([summaryMsg])),
1320
+ digest
1321
+ };
1271
1322
  }
1272
1323
  };
1273
1324
  function readContextWindowPolicy(ctx) {
@@ -1279,10 +1330,6 @@ function readContextWindowPolicy(ctx) {
1279
1330
  }
1280
1331
  return candidate;
1281
1332
  }
1282
- function hasTextContent(m) {
1283
- if (typeof m.content === "string") return m.content.trim().length > 0;
1284
- return m.content.some((b) => b.type === "text" && b.text.trim().length > 0);
1285
- }
1286
1333
  var PROJECT_MARKERS = [
1287
1334
  ".git",
1288
1335
  "package.json",
@@ -2527,6 +2574,8 @@ function topologicalSort(graph) {
2527
2574
  var ToolCapabilities = {
2528
2575
  /** Can execute arbitrary commands in the user's shell (the `bash` tool). */
2529
2576
  SHELL_ARBITRARY: "shell.arbitrary",
2577
+ /** Can execute a restricted set of commands (the `exec` tool). */
2578
+ SHELL_RESTRICTED: "shell.restricted",
2530
2579
  /** Can write / modify / delete files inside the project. */
2531
2580
  FS_WRITE: "fs.write",
2532
2581
  /** Can write files outside the current project root (very high risk). */
@@ -2542,6 +2591,7 @@ var ToolCapabilities = {
2542
2591
  };
2543
2592
  var DANGEROUS_FOR_SUBAGENTS = [
2544
2593
  ToolCapabilities.SHELL_ARBITRARY,
2594
+ ToolCapabilities.SHELL_RESTRICTED,
2545
2595
  ToolCapabilities.FS_WRITE,
2546
2596
  ToolCapabilities.FS_WRITE_OUTSIDE_PROJECT,
2547
2597
  ToolCapabilities.MCP_PROXY,
@@ -3431,6 +3481,6 @@ function renderPlainText(meta, events) {
3431
3481
  return lines.join("\n");
3432
3482
  }
3433
3483
 
3434
- export { AgentError, CONTEXT_WINDOW_MODES, ConfigError, DEFAULT_AUTONOMY_CONFIG, DEFAULT_CONTEXT_CONFIG, DEFAULT_CONTEXT_WINDOW_MODE_ID, DEFAULT_MODES, DEFAULT_RECOVERY_STRATEGIES, DEFAULT_SESSION_LOGGING_CONFIG, DEFAULT_SESSION_PRUNE_DAYS, DEFAULT_SPEC_TEMPLATE, DEFAULT_TOOLS_CONFIG, DefaultErrorHandler, DefaultLogger, DefaultModelsRegistry, DefaultPathResolver, DefaultRetryPolicy, DefaultSecretScrubber, DefaultSecretVault, DefaultSessionReader, DefaultTokenCounter, ERROR_CODES, FsError, HybridCompactor, InMemoryAgentBridge, InMemoryBridgeTransport, MEMORY_TYPE_LABELS, PluginError, ProviderError, SessionError, StreamHangError, ToolError, ToolExecutor, WrongStackError, asBlocks, asText, buildRecoveryStrategies, classifyFamily, computeTaskProgress, createMessage, decryptConfigSecrets, encryptConfigSecrets, findCriticalPath, formatContextWindowModeList, getContextWindowMode, isAgentError, isConfigError, isContextWindowModeId, isFsError, isImageBlock, isPluginError, isSessionError, isTextBlock, isThinkingBlock, isToolError, isToolResultBlock, isToolUseBlock, isWrongStackError, listContextWindowModes, migratePlaintextSecrets, resolveContextWindowPolicy, rewriteConfigEncrypted, toWrongStackError, topologicalSort };
3484
+ export { AgentError, CONTEXT_WINDOW_MODES, ConfigError, DEFAULT_AUTONOMY_CONFIG, DEFAULT_CONTEXT_CONFIG, DEFAULT_CONTEXT_WINDOW_MODE_ID, DEFAULT_MODES, DEFAULT_RECOVERY_STRATEGIES, DEFAULT_SESSION_LOGGING_CONFIG, DEFAULT_SESSION_PRUNE_DAYS, DEFAULT_SPEC_TEMPLATE, DEFAULT_TOOLS_CONFIG, DefaultErrorHandler, DefaultLogger, DefaultModelsRegistry, DefaultPathResolver, DefaultRetryPolicy, DefaultSecretScrubber, DefaultSecretVault, DefaultSessionReader, DefaultTokenCounter, ERROR_CODES, FsError, HybridCompactor, InMemoryAgentBridge, InMemoryBridgeTransport, MEMORY_TYPE_LABELS, PluginError, ProviderError, SessionError, StreamHangError, ToolError, ToolExecutor, WrongStackError, asBlocks, asText, buildRecoveryStrategies, classifyFamily, computeTaskProgress, createMessage, decryptConfigSecrets, encryptConfigSecrets, findCriticalPath, formatContextWindowModeList, getContextWindowMode, isAgentError, isConfigError, isContextWindowModeId, isFsError, isImageBlock, isPluginError, isSecretField, isSessionError, isTextBlock, isThinkingBlock, isToolError, isToolResultBlock, isToolUseBlock, isWrongStackError, listContextWindowModes, migratePlaintextSecrets, resolveContextWindowPolicy, rewriteConfigEncrypted, toWrongStackError, topologicalSort };
3435
3485
  //# sourceMappingURL=index.js.map
3436
3486
  //# sourceMappingURL=index.js.map