@wrongstack/core 0.51.3 → 0.63.4

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 (62) hide show
  1. package/dist/{agent-bridge-CjbD-i7-.d.ts → agent-bridge-B5rxWrg3.d.ts} +1 -1
  2. package/dist/{agent-subagent-runner-DfvlBx5N.d.ts → agent-subagent-runner-Zc3f37Sg.d.ts} +3 -3
  3. package/dist/{compactor-D1RHFRmF.d.ts → compactor-0vjZ8KTk.d.ts} +1 -1
  4. package/dist/{config-ZRCf7sTu.d.ts → config-BdDuaZmB.d.ts} +143 -2
  5. package/dist/{context-7u93AcGD.d.ts → context-iFMEO2rN.d.ts} +9 -8
  6. package/dist/coordination/index.d.ts +12 -12
  7. package/dist/coordination/index.js.map +1 -1
  8. package/dist/defaults/index.d.ts +22 -22
  9. package/dist/defaults/index.js +285 -108
  10. package/dist/defaults/index.js.map +1 -1
  11. package/dist/{events-Bt44ikPN.d.ts → events-k8CHjcrN.d.ts} +20 -1
  12. package/dist/execution/index.d.ts +14 -14
  13. package/dist/execution/index.js +70 -10
  14. package/dist/execution/index.js.map +1 -1
  15. package/dist/extension/index.d.ts +7 -7
  16. package/dist/{goal-store-BeRsj7YX.d.ts → goal-store-iHltMi5n.d.ts} +1 -1
  17. package/dist/{index-mAWBdLyJ.d.ts → index-Bc6BiP5q.d.ts} +77 -6
  18. package/dist/{index-OzA1XjHL.d.ts → index-CWdW_CJt.d.ts} +10 -8
  19. package/dist/index.d.ts +58 -34
  20. package/dist/index.js +587 -100
  21. package/dist/index.js.map +1 -1
  22. package/dist/infrastructure/index.d.ts +6 -6
  23. package/dist/infrastructure/index.js +1 -1
  24. package/dist/infrastructure/index.js.map +1 -1
  25. package/dist/kernel/index.d.ts +9 -9
  26. package/dist/kernel/index.js +3 -1
  27. package/dist/kernel/index.js.map +1 -1
  28. package/dist/{mcp-servers-DONdo-XM.d.ts → mcp-servers-CwqQDMYy.d.ts} +3 -3
  29. package/dist/models/index.d.ts +3 -3
  30. package/dist/models/index.js +31 -16
  31. package/dist/models/index.js.map +1 -1
  32. package/dist/{models-registry-gwMAo6E3.d.ts → models-registry-Cuq1C8V9.d.ts} +7 -0
  33. package/dist/{multi-agent-Ba9Ni2hC.d.ts → multi-agent-SASYOrWA.d.ts} +2 -2
  34. package/dist/{multi-agent-coordinator-BuKq0q89.d.ts → multi-agent-coordinator-CNUJYq7U.d.ts} +2 -2
  35. package/dist/{null-fleet-bus-C0xd73YP.d.ts → null-fleet-bus-DRoJ0uOY.d.ts} +7 -7
  36. package/dist/observability/index.d.ts +2 -2
  37. package/dist/{path-resolver-nkmdiFgi.d.ts → path-resolver-C5sPVne8.d.ts} +2 -2
  38. package/dist/{permission-B6sldrSp.d.ts → permission-Ld-i5ugf.d.ts} +13 -1
  39. package/dist/{permission-policy-CtNscWOA.d.ts → permission-policy-CL-mPufp.d.ts} +14 -7
  40. package/dist/{plan-templates-BmDdJ7UL.d.ts → plan-templates-ThBHOjaM.d.ts} +4 -4
  41. package/dist/{provider-runner-BGro2qQB.d.ts → provider-runner-DJQa211J.d.ts} +3 -3
  42. package/dist/{retry-policy-KF18W4dg.d.ts → retry-policy-BfBScewS.d.ts} +1 -1
  43. package/dist/sdd/index.d.ts +9 -9
  44. package/dist/sdd/index.js +1 -1
  45. package/dist/sdd/index.js.map +1 -1
  46. package/dist/security/index.d.ts +3 -3
  47. package/dist/security/index.js +115 -13
  48. package/dist/security/index.js.map +1 -1
  49. package/dist/{selector-DmXxpFyM.d.ts → selector-DxhW7ML3.d.ts} +1 -1
  50. package/dist/{session-reader-bfgsy2a0.d.ts → session-reader-q2ThszgG.d.ts} +1 -1
  51. package/dist/storage/index.d.ts +6 -6
  52. package/dist/storage/index.js +57 -37
  53. package/dist/storage/index.js.map +1 -1
  54. package/dist/{system-prompt-CM6zOhd2.d.ts → system-prompt-7LHyBbIf.d.ts} +32 -2
  55. package/dist/{tool-executor-p4tP9tGF.d.ts → tool-executor-CIjpGaRA.d.ts} +5 -4
  56. package/dist/types/index.d.ts +15 -15
  57. package/dist/types/index.js +93 -22
  58. package/dist/types/index.js.map +1 -1
  59. package/dist/utils/index.d.ts +14 -2
  60. package/dist/utils/index.js +18 -1
  61. package/dist/utils/index.js.map +1 -1
  62. package/package.json +1 -1
@@ -1,4 +1,5 @@
1
- import { T as TextBlock, c as ContentBlock, Q as Tool } from './context-7u93AcGD.js';
1
+ import { l as HookEvent, n as HookMatcher, I as InProcessHook, s as ShellHook, H as HookEntry } from './config-BdDuaZmB.js';
2
+ import { T as TextBlock, c as ContentBlock, Q as Tool } from './context-iFMEO2rN.js';
2
3
 
3
4
  /**
4
5
  * Container — dependency injection with explicit bind / override / decorate.
@@ -160,6 +161,35 @@ declare class Pipeline<T> {
160
161
  private ensureUnique;
161
162
  }
162
163
 
164
+ /**
165
+ * Registry of lifecycle hooks (both in-process and shell). One instance is
166
+ * shared per session: the boot path loads `config.hooks` as shell entries and
167
+ * plugins add in-process entries via `PluginAPI.registerHook`. The
168
+ * `HookRunner` reads from it at each lifecycle phase.
169
+ */
170
+ declare class HookRegistry {
171
+ private readonly entries;
172
+ /** Register an in-process hook. Returns an unsubscribe function. */
173
+ registerInProcess(event: HookEvent, matcher: HookMatcher | undefined, hook: InProcessHook, owner?: string): () => void;
174
+ /** Register a single shell hook. Returns an unsubscribe function. */
175
+ registerShell(event: HookEvent, hook: ShellHook): () => void;
176
+ /** Bulk-load shell hooks from a `config.hooks` map. */
177
+ loadShellHooks(hooks: Partial<Record<HookEvent, ShellHook[]>> | undefined): void;
178
+ /** All entries registered for an event, in registration order. */
179
+ list(event: HookEvent): readonly HookEntry[];
180
+ /** True when any entry is registered for the event. */
181
+ has(event: HookEvent): boolean;
182
+ /** Drop every registered hook (used in teardown / tests). */
183
+ clear(): void;
184
+ private remove;
185
+ }
186
+ /**
187
+ * Does a hook matcher apply to a tool name? `*` (or empty) matches everything;
188
+ * otherwise the matcher is a case-insensitive pipe-delimited list of exact
189
+ * tool names (`"edit|write"`). Non-tool events pass `undefined` and always match.
190
+ */
191
+ declare function hookMatcherMatches(matcher: HookMatcher, toolName: string | undefined): boolean;
192
+
163
193
  interface Renderer {
164
194
  write(text: string | TextBlock): void;
165
195
  writeLine(text?: string): void;
@@ -201,4 +231,4 @@ interface SystemPromptBuilder {
201
231
  build(ctx: BuildContext): Promise<TextBlock[]>;
202
232
  }
203
233
 
204
- export { type BindOptions as B, Container as C, type Decorator as D, type Factory as F, type Middleware as M, type NextFn as N, Pipeline as P, type ReadonlyPipeline as R, type SystemPromptBuilder as S, type Token as T, type BuildContext as a, type MiddlewareHandler as b, type ModelCapabilities as c, type PipelineOptions as d, type Renderer as e };
234
+ export { type BindOptions as B, Container as C, type Decorator as D, type Factory as F, HookRegistry as H, type Middleware as M, type NextFn as N, Pipeline as P, type ReadonlyPipeline as R, type SystemPromptBuilder as S, type Token as T, type BuildContext as a, type MiddlewareHandler as b, type ModelCapabilities as c, type PipelineOptions as d, type Renderer as e, hookMatcherMatches as h };
@@ -1,8 +1,8 @@
1
- import { d as Context, n as ProviderError, Q as Tool, _ as ToolUseBlock, Y as ToolResultBlock } from './context-7u93AcGD.js';
2
- import { a as Compactor, C as CompactReport } from './compactor-D1RHFRmF.js';
3
- import { R as RecoveryDecision, E as ErrorHandler, a as RetryPolicy } from './retry-policy-KF18W4dg.js';
1
+ import { d as Context, n as ProviderError, Q as Tool, _ as ToolUseBlock, Y as ToolResultBlock } from './context-iFMEO2rN.js';
2
+ import { a as Compactor, C as CompactReport } from './compactor-0vjZ8KTk.js';
3
+ import { R as RecoveryDecision, E as ErrorHandler, a as RetryPolicy } from './retry-policy-BfBScewS.js';
4
4
  import { b as ModelsRegistry } from './models-registry-BcYJDKLm.js';
5
- import { y as ToolExecutorOptions, z as ToolExecutorStrategy, T as ToolBatchResult } from './index-mAWBdLyJ.js';
5
+ import { G as ToolExecutorOptions, I as ToolExecutorStrategy, T as ToolBatchResult } from './index-Bc6BiP5q.js';
6
6
 
7
7
  interface CompactorOptions {
8
8
  preserveK?: number;
@@ -98,6 +98,7 @@ declare class ToolExecutor {
98
98
  private unknownToolResult;
99
99
  private malformedInputResult;
100
100
  private deniedResult;
101
+ private blockedByHookResult;
101
102
  private decrementBudget;
102
103
  /**
103
104
  * Compute the suggestedPattern string for a tool+input pair.
@@ -1,29 +1,29 @@
1
- export { A as AgentError, a as Capabilities, b as ConfigError, c as ContentBlock, E as ERROR_CODES, g as ErrorCode, h as ErrorSeverity, i as ErrorSubsystem, F as FileSnapshot, j as FsError, I as ImageBlock, J as JSONSchema, M as Message, k as MessageRole, P as Permission, l as PluginError, m as Provider, n as ProviderError, o as ProviderErrorBody, p as Request, q as Response, r as ResumedSession, s as RiskTier, S as SessionData, v as SessionError, w as SessionEvent, x as SessionMetadata, y as SessionStore, z as SessionSummary, B as SessionWriter, H as StopReason, K as StreamEvent, T as TextBlock, L as ThinkingBlock, Q as Tool, U as ToolCallContext, V as ToolError, W as ToolFinalEvent, X as ToolProgressEvent, Y as ToolResultBlock, Z as ToolStreamEvent, _ as ToolUseBlock, $ as Usage, a0 as WrongStackError, a1 as asBlocks, a2 as asText, a4 as isAgentError, a5 as isConfigError, a6 as isFsError, a7 as isImageBlock, a8 as isPluginError, a9 as isSessionError, aa as isTextBlock, ab as isThinkingBlock, ac as isToolError, ad as isToolResultBlock, ae as isToolUseBlock, af as isWrongStackError, ag as toWrongStackError } from '../context-7u93AcGD.js';
2
- export { P as ProviderRunner, R as RunProviderOptions } from '../provider-runner-BGro2qQB.js';
3
- export { A as AutonomyConfig, C as CONTEXT_WINDOW_MODES, a as Config, b as ConfigLoader, c as ConfigStore, d as ContextConfig, e as ContextWindowAggressiveOn, f as ContextWindowConfigLike, g as ContextWindowMode, h as ContextWindowModeId, i as ContextWindowPolicy, j as ContextWindowThresholds, D as DEFAULT_CONTEXT_WINDOW_MODE_ID, F as FeaturesConfig, L as LogConfig, M as MCPServerConfig, k as ModelMatrixEntry, P as PluginConfig, l as ProviderApiKey, m as ProviderConfig, S as SessionLoggingConfig, n as SyncCategory, o as SyncConfig, T as ToolsConfig, p as formatContextWindowModeList, q as getContextWindowMode, r as isContextWindowModeId, s as listContextWindowModes, t as resolveContextWindowPolicy } from '../config-ZRCf7sTu.js';
4
- export { C as CompactReport, a as Compactor } from '../compactor-D1RHFRmF.js';
5
- export { P as PermissionDecision, a as PermissionPolicy, T as TrustPolicy } from '../permission-B6sldrSp.js';
1
+ export { A as AgentError, a as Capabilities, b as ConfigError, c as ContentBlock, E as ERROR_CODES, g as ErrorCode, h as ErrorSeverity, i as ErrorSubsystem, F as FileSnapshot, j as FsError, I as ImageBlock, J as JSONSchema, M as Message, k as MessageRole, P as Permission, l as PluginError, m as Provider, n as ProviderError, o as ProviderErrorBody, p as Request, q as Response, r as ResumedSession, s as RiskTier, S as SessionData, v as SessionError, w as SessionEvent, x as SessionMetadata, y as SessionStore, z as SessionSummary, B as SessionWriter, H as StopReason, K as StreamEvent, T as TextBlock, L as ThinkingBlock, Q as Tool, U as ToolCallContext, V as ToolError, W as ToolFinalEvent, X as ToolProgressEvent, Y as ToolResultBlock, Z as ToolStreamEvent, _ as ToolUseBlock, $ as Usage, a0 as WrongStackError, a1 as asBlocks, a2 as asText, a4 as isAgentError, a5 as isConfigError, a6 as isFsError, a7 as isImageBlock, a8 as isPluginError, a9 as isSessionError, aa as isTextBlock, ab as isThinkingBlock, ac as isToolError, ad as isToolResultBlock, ae as isToolUseBlock, af as isWrongStackError, ag as toWrongStackError } from '../context-iFMEO2rN.js';
2
+ export { P as ProviderRunner, R as RunProviderOptions } from '../provider-runner-DJQa211J.js';
3
+ export { A as AutonomyConfig, C as CONTEXT_WINDOW_MODES, a as Config, b as ConfigLoader, c as ConfigStore, d as ContextConfig, e as ContextWindowAggressiveOn, f as ContextWindowConfigLike, g as ContextWindowMode, h as ContextWindowModeId, i as ContextWindowPolicy, j as ContextWindowThresholds, k as CustomModelDefinition, D as DEFAULT_CONTEXT_WINDOW_MODE_ID, F as FeaturesConfig, H as HookEntry, l as HookEvent, m as HookInput, n as HookMatcher, o as HookOutcome, I as InProcessHook, L as LogConfig, M as MCPServerConfig, p as ModelMatrixEntry, P as PluginConfig, q as ProviderApiKey, r as ProviderConfig, S as SessionLoggingConfig, s as ShellHook, t as SyncCategory, u as SyncConfig, T as ToolsConfig, v as formatContextWindowModeList, w as getContextWindowMode, x as isContextWindowModeId, y as listContextWindowModes, z as resolveContextWindowPolicy } from '../config-BdDuaZmB.js';
4
+ export { C as CompactReport, a as Compactor } from '../compactor-0vjZ8KTk.js';
5
+ export { P as PermissionDecision, a as PermissionPolicy, T as TrustPolicy } from '../permission-Ld-i5ugf.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, a as Attachment, b as AttachmentKind, c as AttachmentMeta, d as AttachmentRef, e as AttachmentStore, D as DefaultSessionReader } from '../session-reader-bfgsy2a0.js';
7
+ export { A as AddAttachmentInput, a as Attachment, b as AttachmentKind, c as AttachmentMeta, d as AttachmentRef, e as AttachmentStore, D as DefaultSessionReader } from '../session-reader-q2ThszgG.js';
8
8
  export { D as DEFAULT_AUTONOMY_CONFIG, a as DEFAULT_CONTEXT_CONFIG, b as DEFAULT_SESSION_LOGGING_CONFIG, c as DEFAULT_TOOLS_CONFIG } from '../default-config-DEXI4jsl.js';
9
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-scrubber-7rSC_emZ.js';
10
10
  export { D as DefaultLogger, a as DefaultLoggerOptions } from '../logger-bOzkF5LL.js';
11
- export { D as DefaultPathResolver, a as DefaultTokenCounter } from '../path-resolver-nkmdiFgi.js';
11
+ export { D as DefaultPathResolver, a as DefaultTokenCounter } from '../path-resolver-C5sPVne8.js';
12
12
  export { M as MemoryEntry, a as MemoryScope, b as MemoryStore } from '../memory-CEXuo7sz.js';
13
- export { C as CompactorOptions, D as DEFAULT_RECOVERY_STRATEGIES, a as DefaultErrorHandler, b as DefaultRetryPolicy, H as HybridCompactor, R as RecoveryStrategy, T as ToolExecutor, c as buildRecoveryStrategies } from '../tool-executor-p4tP9tGF.js';
13
+ export { C as CompactorOptions, D as DEFAULT_RECOVERY_STRATEGIES, a as DefaultErrorHandler, b as DefaultRetryPolicy, H as HybridCompactor, R as RecoveryStrategy, T as ToolExecutor, c as buildRecoveryStrategies } from '../tool-executor-CIjpGaRA.js';
14
14
  export { S as SkillEntry, a as SkillLoader, b as SkillManifest } from '../skill-CxuWrsKK.js';
15
- export { a as BuildContext, c as ModelCapabilities, e as Renderer, S as SystemPromptBuilder } from '../system-prompt-CM6zOhd2.js';
15
+ export { a as BuildContext, c as ModelCapabilities, e as Renderer, S as SystemPromptBuilder } from '../system-prompt-7LHyBbIf.js';
16
16
  export { I as InputReader, P as PromptOption } from '../input-reader-E-ffP2ee.js';
17
- export { M as MCPRegistryView, j as MetricsSinkView, P as Plugin, k as PluginAPI, l as PluginCapabilities, m as PluginDependency, n as PluginPipelines, o as ProviderFactory, r as ProviderRegistryView, S as SessionWriterView, u as SlashCommand, v as SlashCommandRegistryView, w as SystemPromptContributor, F as ToolRegistryView } from '../index-mAWBdLyJ.js';
18
- export { D as DefaultModelsRegistry, a as DefaultModelsRegistryOptions, c as classifyFamily } from '../models-registry-gwMAo6E3.js';
17
+ export { M as MCPRegistryView, l as MetricsSinkView, P as Plugin, m as PluginAPI, n as PluginCapabilities, o as PluginDependency, p as PluginPipelines, s as ProviderFactory, v as ProviderRegistryView, S as SessionWriterView, y as SlashCommand, z as SlashCommandRegistryView, C as SystemPromptContributor, K as ToolRegistryView } from '../index-Bc6BiP5q.js';
18
+ export { D as DefaultModelsRegistry, a as DefaultModelsRegistryOptions, c as classifyFamily } from '../models-registry-Cuq1C8V9.js';
19
19
  export { D as DEFAULT_MODES, M as Mode, a as ModeConfig, b as ModeManifest, c as ModeStore } from '../mode-CV077NjV.js';
20
- export { I as InMemoryAgentBridge, a as InMemoryBridgeTransport, c as createMessage } from '../agent-bridge-CjbD-i7-.js';
21
- export { C as CoordinatorEvents, k as CoordinatorStatus, D as DoneCondition, M as MultiAgentConfig, l as MultiAgentCoordinator, S as SpawnResult, n as SubagentConfig, o as SubagentContext, p as SubagentError, q as SubagentErrorKind, r as SubagentRunContext, s as SubagentRunOutcome, t as SubagentRunner, T as TaskDelegation, u as TaskResult, v as TaskSpec } from '../multi-agent-Ba9Ni2hC.js';
20
+ export { I as InMemoryAgentBridge, a as InMemoryBridgeTransport, c as createMessage } from '../agent-bridge-B5rxWrg3.js';
21
+ export { C as CoordinatorEvents, k as CoordinatorStatus, D as DoneCondition, M as MultiAgentConfig, l as MultiAgentCoordinator, S as SpawnResult, n as SubagentConfig, o as SubagentContext, p as SubagentError, q as SubagentErrorKind, r as SubagentRunContext, s as SubagentRunOutcome, t as SubagentRunner, T as TaskDelegation, u as TaskResult, v as TaskSpec } from '../multi-agent-SASYOrWA.js';
22
22
  export { C as CriticalPathResult, 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, T as TaskAssignment, i as TaskDependency, j as TaskEdge, k as TaskFilter, l as TaskGraph, m as TaskNode, n as TaskPriority, o as TaskProgress, p as TaskSort, q as TaskStatus, r as TaskType, s as computeTaskProgress, t as findCriticalPath, u as topologicalSort } from '../task-graph-D1YQbpxF.js';
23
23
  export { A as AggregateHealth, H as HealthCheck, a as HealthCheckResult, b as HealthRegistry, c as HealthStatus, M as MetricLabels, d as MetricSeries, e as MetricsSink, f as MetricsSnapshot, S as Span, T as Tracer } from '../observability-BhnVLBLS.js';
24
- import '../events-Bt44ikPN.js';
24
+ import '../events-k8CHjcrN.js';
25
25
  import '../logger-DDd5C--Z.js';
26
- import '../retry-policy-KF18W4dg.js';
26
+ import '../retry-policy-BfBScewS.js';
27
27
  import '../models-registry-BcYJDKLm.js';
28
28
  import '../secret-vault-DoISxaKO.js';
29
29
  import '../secret-scrubber-3MHDDAtm.js';
@@ -1265,7 +1265,7 @@ var DefaultPathResolver = class {
1265
1265
  var NETWORK_ERR_RE = /ECONN|ETIMEDOUT|ETIME|ENOTFOUND|EAI_AGAIN|fetch failed/i;
1266
1266
 
1267
1267
  // src/execution/error-handler.ts
1268
- var CONTEXT_OVERFLOW_RE = /context|too long|tokens/i;
1268
+ var CONTEXT_OVERFLOW_RE = /context|too long|tokens|exceeds the context window|context window/i;
1269
1269
  function buildRecoveryStrategies(opts) {
1270
1270
  return [
1271
1271
  {
@@ -1273,7 +1273,7 @@ function buildRecoveryStrategies(opts) {
1273
1273
  compactor: opts?.compactor,
1274
1274
  async attempt(err, ctx) {
1275
1275
  if (!(err instanceof ProviderError)) return null;
1276
- if (err.status !== 413 && !CONTEXT_OVERFLOW_RE.test(err.message)) return null;
1276
+ if (err.status !== 413 && !isContextOverflowError(err)) return null;
1277
1277
  if (this.compactor) {
1278
1278
  try {
1279
1279
  const report = await this.compactor.compact(ctx, { aggressive: true });
@@ -1336,6 +1336,14 @@ function buildRecoveryStrategies(opts) {
1336
1336
  ];
1337
1337
  }
1338
1338
  var DEFAULT_RECOVERY_STRATEGIES = buildRecoveryStrategies();
1339
+ function isContextOverflowError(err) {
1340
+ return CONTEXT_OVERFLOW_RE.test([
1341
+ err.message,
1342
+ err.body?.message,
1343
+ err.body?.type,
1344
+ err.body?.raw
1345
+ ].filter(Boolean).join("\n"));
1346
+ }
1339
1347
  var DefaultErrorHandler = class {
1340
1348
  strategies;
1341
1349
  constructor(strategies = DEFAULT_RECOVERY_STRATEGIES) {
@@ -1352,7 +1360,7 @@ var DefaultErrorHandler = class {
1352
1360
  if (err.status === 429) return { kind: "rate_limit", retryable: true };
1353
1361
  if (err.status === 529) return { kind: "overloaded", retryable: true };
1354
1362
  if (err.status >= 500) return { kind: "server", retryable: true };
1355
- if (err.status === 413 || CONTEXT_OVERFLOW_RE.test(err.message)) {
1363
+ if (err.status === 413 || isContextOverflowError(err)) {
1356
1364
  return { kind: "context_overflow", retryable: false };
1357
1365
  }
1358
1366
  if (err.status >= 400) return { kind: "client", retryable: false };
@@ -1573,6 +1581,7 @@ function stripUndefined(obj) {
1573
1581
  // src/models/models-registry.ts
1574
1582
  var DEFAULT_URL = "https://models.dev/api.json";
1575
1583
  var DEFAULT_TTL_SECONDS = 24 * 3600;
1584
+ var DEFAULT_REFRESH_TIMEOUT_MS = 15e3;
1576
1585
  var FAMILY_BY_NPM = {
1577
1586
  "@ai-sdk/anthropic": "anthropic",
1578
1587
  "@ai-sdk/google-vertex/anthropic": "anthropic",
@@ -1609,6 +1618,7 @@ var DefaultModelsRegistry = class {
1609
1618
  fetchImpl;
1610
1619
  seed;
1611
1620
  maxStaleAgeMs;
1621
+ refreshTimeoutMs;
1612
1622
  overlay;
1613
1623
  overlayUrl;
1614
1624
  overlayFile;
@@ -1621,6 +1631,7 @@ var DefaultModelsRegistry = class {
1621
1631
  this.seed = opts.seed;
1622
1632
  const maxStaleSeconds = opts.maxStaleAgeSeconds ?? 7 * 24 * 3600;
1623
1633
  this.maxStaleAgeMs = maxStaleSeconds * 1e3;
1634
+ this.refreshTimeoutMs = opts.refreshTimeoutMs ?? DEFAULT_REFRESH_TIMEOUT_MS;
1624
1635
  this.overlay = opts.overlay;
1625
1636
  this.overlayUrl = opts.overlayUrl;
1626
1637
  this.overlayFile = opts.overlayFile;
@@ -1672,22 +1683,34 @@ var DefaultModelsRegistry = class {
1672
1683
  }
1673
1684
  /** Fetch + cache the models.dev base. Throws on failure (used by `refresh`). */
1674
1685
  async refreshBase() {
1675
- const res = await this.fetchImpl(this.url, {
1676
- method: "GET",
1677
- headers: { accept: "application/json" }
1678
- });
1679
- if (!res.ok) {
1680
- throw new Error(`ModelsRegistry: HTTP ${res.status} fetching ${this.url}`);
1681
- }
1682
- const json = await res.json();
1683
- this.fetchedAt = /* @__PURE__ */ new Date();
1684
- const envelope = {
1685
- fetchedAt: this.fetchedAt.toISOString(),
1686
- url: this.url,
1687
- payload: json
1688
- };
1689
- await atomicWrite(this.cacheFile, JSON.stringify(envelope));
1690
- return json;
1686
+ const controller = new AbortController();
1687
+ const timeout = setTimeout(() => controller.abort(), this.refreshTimeoutMs);
1688
+ try {
1689
+ const res = await this.fetchImpl(this.url, {
1690
+ method: "GET",
1691
+ headers: { accept: "application/json" },
1692
+ signal: controller.signal
1693
+ });
1694
+ clearTimeout(timeout);
1695
+ if (!res.ok) {
1696
+ throw new Error(`ModelsRegistry: HTTP ${res.status} fetching ${this.url}`);
1697
+ }
1698
+ const json = await res.json();
1699
+ this.fetchedAt = /* @__PURE__ */ new Date();
1700
+ const envelope = {
1701
+ fetchedAt: this.fetchedAt.toISOString(),
1702
+ url: this.url,
1703
+ payload: json
1704
+ };
1705
+ await atomicWrite(this.cacheFile, JSON.stringify(envelope));
1706
+ return json;
1707
+ } catch (err) {
1708
+ clearTimeout(timeout);
1709
+ if (err instanceof Error && err.name === "AbortError") {
1710
+ throw new Error(`ModelsRegistry: fetch timed out after ${this.refreshTimeoutMs}ms`);
1711
+ }
1712
+ throw err;
1713
+ }
1691
1714
  }
1692
1715
  /**
1693
1716
  * Resolve the curated overlay, memoised. Order: in-memory `overlay` →
@@ -2604,8 +2627,9 @@ var ToolExecutor = class {
2604
2627
  */
2605
2628
  async executeBatch(toolUses, ctx, strategy) {
2606
2629
  let budget = this.opts.perIterationOutputCapBytes ?? 1e5;
2607
- const runOne = async (use) => {
2630
+ const runOne = async (use0) => {
2608
2631
  const start = Date.now();
2632
+ let use = use0;
2609
2633
  const tool = this.registry.get(use.name);
2610
2634
  if (!tool) {
2611
2635
  const result = this.unknownToolResult(use, () => this.registry.list().map((t) => t.name));
@@ -2638,10 +2662,36 @@ Please call the tool again with arguments that match its inputSchema. You can us
2638
2662
  budget = this.decrementBudget(result, budget);
2639
2663
  return { result, tool, durationMs: Date.now() - start };
2640
2664
  }
2665
+ if (this.opts.hookRunner?.has("PreToolUse")) {
2666
+ const pre = await this.opts.hookRunner.preToolUse(tool.name, use.input, ctx);
2667
+ if (pre.block) {
2668
+ const result = this.blockedByHookResult(use, pre.reason);
2669
+ budget = this.decrementBudget(result, budget);
2670
+ return { result, tool, durationMs: Date.now() - start };
2671
+ }
2672
+ if (pre.input) {
2673
+ const reval = validateAgainstSchema(pre.input, tool.inputSchema);
2674
+ if (!reval.ok) {
2675
+ const errorDetails = reval.errors.map((e) => ` - ${e.path || "input"}: ${e.message}`).join("\n");
2676
+ const result = {
2677
+ type: "tool_result",
2678
+ tool_use_id: use.id,
2679
+ content: `A PreToolUse hook rewrote the arguments for "${tool.name}" into an invalid shape.
2680
+
2681
+ Validation errors:
2682
+ ${errorDetails}`,
2683
+ is_error: true
2684
+ };
2685
+ budget = this.decrementBudget(result, budget);
2686
+ return { result, tool, durationMs: Date.now() - start };
2687
+ }
2688
+ use = { ...use, input: pre.input };
2689
+ }
2690
+ }
2641
2691
  const decision = await this.opts.permissionPolicy.evaluate(tool, use.input, ctx);
2642
2692
  let effectivePermission = decision.permission;
2643
2693
  const policy = this.opts.permissionPolicy;
2644
- const yolo = policy.getYolo?.() === true || policy.getForceAllYolo?.() === true;
2694
+ const yolo = policy.getYolo?.() === true || policy.getYoloDestructive?.() === true || policy.getForceAllYolo?.() === true;
2645
2695
  if (toolDangerousCaps.length > 0 && effectivePermission === "auto" && !yolo) {
2646
2696
  effectivePermission = "confirm";
2647
2697
  }
@@ -2684,7 +2734,20 @@ Please call the tool again with arguments that match its inputSchema. You can us
2684
2734
  "tool.has_dangerous_capabilities": toolCapsForAudit.length > 0
2685
2735
  });
2686
2736
  try {
2687
- const result = await this.executeTool(tool, use, ctx, budget);
2737
+ let result = await this.executeTool(tool, use, ctx, budget);
2738
+ if (this.opts.hookRunner?.has("PostToolUse")) {
2739
+ const post = await this.opts.hookRunner.postToolUse(
2740
+ tool.name,
2741
+ use.input,
2742
+ { content: String(result.content), isError: !!result.is_error },
2743
+ ctx
2744
+ );
2745
+ if (post.additionalContext) {
2746
+ result = { ...result, content: `${result.content}
2747
+
2748
+ ${post.additionalContext}` };
2749
+ }
2750
+ }
2688
2751
  budget = this.decrementBudget(result, budget);
2689
2752
  span?.setAttribute("tool.is_error", !!result.is_error);
2690
2753
  span?.setAttribute(
@@ -2873,6 +2936,14 @@ ${excerpt}`;
2873
2936
  is_error: true
2874
2937
  };
2875
2938
  }
2939
+ blockedByHookResult(use, reason) {
2940
+ return {
2941
+ type: "tool_result",
2942
+ tool_use_id: use.id,
2943
+ content: `Tool "${use.name}" was blocked by a PreToolUse hook: ${reason ?? "no reason given"}`,
2944
+ is_error: true
2945
+ };
2946
+ }
2876
2947
  decrementBudget(result, budget) {
2877
2948
  const contentBytes = typeof result.content === "string" ? Buffer.byteLength(result.content, "utf8") : Buffer.byteLength(JSON.stringify(result.content), "utf8");
2878
2949
  return Math.max(0, budget - contentBytes);