@t2000/engine 1.15.1 → 1.17.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.
package/dist/index.d.ts CHANGED
@@ -1032,26 +1032,42 @@ interface PendingAction {
1032
1032
  steps?: PendingActionStep[];
1033
1033
  /**
1034
1034
  * [SPEC 7 v0.3 Quote-Refresh] Milliseconds since the upstream read tools
1035
- * that fed this bundle's composition completed. Engine stamps at emit
1035
+ * that fed this action's composition completed. Engine stamps at emit
1036
1036
  * time using `Date.now() - min(tool_result.timestamp)` across the listed
1037
1037
  * `regenerateInput.toolUseIds`. Host renders as a "QUOTE Ns OLD" badge in
1038
- * the PermissionCard header. Only set on bundled `pending_action`s.
1038
+ * the PermissionCard header.
1039
+ *
1040
+ * **[SPEC 15 v0.7 follow-up — 2026-05-04]** Now also stamped on
1041
+ * single-write confirm-tier `pending_action`s when same-turn
1042
+ * regeneratable reads contributed (e.g. a confirm-tier
1043
+ * `swap_execute` whose Cetus quote is referenced via the prior
1044
+ * `swap_quote` read). Pre-v0.7 this was bundle-only.
1039
1045
  */
1040
1046
  quoteAge?: number;
1041
1047
  /**
1042
- * [SPEC 7 v0.3 Quote-Refresh] True when the bundle was composed from
1048
+ * [SPEC 7 v0.3 Quote-Refresh] True when the action was composed from
1043
1049
  * re-runnable read tools (`swap_quote`, `rates_info`, `balance_check`,
1044
1050
  * `portfolio_analysis`). False when amounts came from user-provided
1045
- * inputs that don't depend on upstream quotes. Single-write
1046
- * `pending_action`s set this to `false` (regenerate is N≥2 only).
1051
+ * inputs that don't depend on upstream quotes.
1052
+ *
1053
+ * **[SPEC 15 v0.7 follow-up — 2026-05-04]** Now populated for
1054
+ * single-write confirm-tier actions too — pre-v0.7 single-writes
1055
+ * always emitted `false` because the regenerate path was N≥2 only.
1056
+ * Closing that gap surfaced the Refresh-quote affordance for the
1057
+ * single-write confirm-tier scenario (e.g. $50 swap_execute).
1047
1058
  */
1048
1059
  canRegenerate?: boolean;
1049
1060
  /**
1050
1061
  * [SPEC 7 v0.3 Quote-Refresh] Engine-internal payload listing which
1051
1062
  * upstream read `tool_use` ids to re-fire when the user taps REGENERATE.
1052
1063
  * Host echoes this back via `POST /api/engine/regenerate`; engine re-runs
1053
- * each tool with the same input (no LLM call), rebuilds the bundle, and
1054
- * emits a fresh `pending_action` with new per-step `attemptId`s.
1064
+ * each tool with the same input (no LLM call), rebuilds the action, and
1065
+ * emits a fresh `pending_action` with a fresh `attemptId`.
1066
+ *
1067
+ * **[SPEC 15 v0.7 follow-up — 2026-05-04]** Populated for both
1068
+ * bundle (N≥2) and single-write (N=1) shapes; the engine's
1069
+ * `regenerateBundle()` rebuild branches on `action.steps?.length`
1070
+ * to pick the right composition path.
1055
1071
  */
1056
1072
  regenerateInput?: {
1057
1073
  toolUseIds: string[];
@@ -1803,6 +1819,96 @@ declare function checkValidPair(producer: string, consumer: string): {
1803
1819
  ok: false;
1804
1820
  pair: string;
1805
1821
  };
1822
+ /**
1823
+ * [SPEC 15 v0.7 follow-up — single-write regenerate, 2026-05-04]
1824
+ * Shared helper that derives the Quote-Refresh fields
1825
+ * (`canRegenerate`, `regenerateInput.toolUseIds`, `quoteAge`) from a
1826
+ * collection of same-turn read tool_results. Used by both
1827
+ * `composeBundleFromToolResults` (bundle path, N≥2) AND the engine's
1828
+ * single-write `pending_action` yield path (N=1) — keeping the
1829
+ * derivation in one place so the two paths can't drift on what
1830
+ * counts as "regeneratable" or how `quoteAge` is computed.
1831
+ *
1832
+ * **Why the same logic on N=1.** Pre-v0.7 single-write actions never
1833
+ * carried these fields (the original SPEC 7 P2.4b assumed bundles
1834
+ * only), which left a UX gap: a single-write confirm-tier swap whose
1835
+ * Cetus quote went stale had no Refresh-quote affordance. Bundles
1836
+ * had it; single-writes didn't. v0.7 closes the gap by populating
1837
+ * the same fields here, so the host's PermissionCard can render the
1838
+ * same regenerate slot for either shape and `regenerateBundle()`
1839
+ * can re-fire the same reads regardless of N.
1840
+ *
1841
+ * **Conservative inclusion.** Any same-turn read whose name is in
1842
+ * `REGENERATABLE_READ_TOOLS` contributes — we don't inspect the
1843
+ * write's input shape to confirm the read was actually consumed.
1844
+ * False positives just enable the Refresh button when it could've
1845
+ * stayed off; they don't change correctness (the re-fire is
1846
+ * deterministic and the new bundle's input is recomputed from
1847
+ * scratch).
1848
+ *
1849
+ * **`quoteAge` semantics.** Milliseconds since the stalest
1850
+ * contributing read. `min` not `max` — we report the freshness of
1851
+ * the WORST input because that's what gates UX. Clamped at ≥0
1852
+ * against NTP clock skew (negative ages would render as
1853
+ * "QUOTE -3s OLD" otherwise — see SPEC 7 P2.3 audit BUG 12).
1854
+ *
1855
+ * Returns `{ canRegenerate: false, regenerateToolUseIds: [],
1856
+ * quoteAge: undefined }` when no contributing reads landed — the
1857
+ * caller should NOT spread `regenerateInput` onto the action in
1858
+ * that case (omit the field entirely).
1859
+ */
1860
+ declare function computeRegenerateFields(readResults: Array<{
1861
+ toolUseId: string;
1862
+ toolName: string;
1863
+ timestamp: number;
1864
+ }>): {
1865
+ canRegenerate: boolean;
1866
+ regenerateToolUseIds: string[];
1867
+ quoteAge: number | undefined;
1868
+ };
1869
+ interface BundleCompositionInput {
1870
+ /** All confirm-tier bundleable writes the LLM emitted in this turn. MUST be ≥2. */
1871
+ pendingWrites: PendingToolCall[];
1872
+ /** Tools registered with the engine — for description + modifiableFields lookup. */
1873
+ tools: Tool[];
1874
+ /**
1875
+ * Same-turn earlier read tool_use ids + their results, in the order they
1876
+ * landed. The helper extracts `regenerateInput.toolUseIds` from this set
1877
+ * by intersecting it with the canonical regeneratable-read allow-list
1878
+ * (`REGENERATABLE_READ_TOOLS`).
1879
+ */
1880
+ readResults: Array<{
1881
+ toolUseId: string;
1882
+ toolName: string;
1883
+ timestamp: number;
1884
+ }>;
1885
+ /** Full assistant message blocks for the deferred turn (engine.ts uses this). */
1886
+ assistantContent: ContentBlock[];
1887
+ /** Already-resolved tool_result blocks (early-dispatched reads + auto writes). */
1888
+ completedResults: Array<{
1889
+ toolUseId: string;
1890
+ content: string;
1891
+ isError: boolean;
1892
+ }>;
1893
+ /** Per-write-call optional guard injections (already resolved, not re-run here). */
1894
+ guardInjectionsByCallId?: Record<string, Array<{
1895
+ _gate: string;
1896
+ _hint?: string;
1897
+ _warning?: string;
1898
+ }>>;
1899
+ /** Monotonic turn index — same value the legacy single-write path stamps. */
1900
+ turnIndex: number;
1901
+ }
1902
+ /**
1903
+ * Produce a bundled `PendingAction` from collected pending writes.
1904
+ * Caller MUST have already verified pendingWrites.length >= 2 and that
1905
+ * every entry's tool has `bundleable: true` + `permissionLevel: 'confirm'`.
1906
+ *
1907
+ * The helper additionally re-checks `bundleable: true` on each tool as a
1908
+ * defensive guard against caller bugs (cheap, catches future call sites
1909
+ * that misuse the helper).
1910
+ */
1911
+ declare function composeBundleFromToolResults(input: BundleCompositionInput): PendingAction;
1806
1912
 
1807
1913
  /**
1808
1914
  * SPEC 7 v0.3 Quote-Refresh ReviewCard — engine-side bundle regeneration.
@@ -1906,15 +2012,17 @@ type RegenerateResult = RegenerateSuccess | RegenerateFailure;
1906
2012
  * store after a successful regenerate.
1907
2013
  *
1908
2014
  * **Failure modes.**
1909
- * - `pending_action_not_found` — the action isn't a bundle (no
1910
- * `steps`, or fewer than 2 steps). Single-write actions can't be
1911
- * regenerated by design.
2015
+ * - `pending_action_not_found` — reserved for host-side mismatches
2016
+ * (session expired, attemptId mismatch). The engine itself never
2017
+ * returns this from `regenerateBundle`; the route surfaces it
2018
+ * pre-call. (Pre-v0.7 it also fired here for single-write
2019
+ * actions; lifted as part of single-write regenerate support.)
1912
2020
  * - `cannot_regenerate` — the action's `canRegenerate` flag is
1913
2021
  * false, OR no contributing read tool_use_ids could be located in
1914
2022
  * session history.
1915
- * - `engine_error` — a tool re-execution threw, OR bundle
1916
- * composition rejected (defensive — should not happen if the
1917
- * original bundle was valid).
2023
+ * - `engine_error` — a tool re-execution threw, OR action
2024
+ * rebuild rejected (defensive — should not happen if the
2025
+ * original action was valid).
1918
2026
  *
1919
2027
  * Errors in tool re-execution short-circuit the whole regenerate
1920
2028
  * (bundle composition would inherit a broken read result). The host
@@ -3812,4 +3920,4 @@ declare function getTelemetrySink(): TelemetrySink;
3812
3920
  /** Restore the default noop sink. Used by test teardowns. */
3813
3921
  declare function resetTelemetrySink(): void;
3814
3922
 
3815
- export { type AddressPortfolio, AnthropicProvider, type AnthropicProviderConfig, type AudricHistoryRecord, type AudricPortfolioResult, type AwaitOrFetchOpts, type BalancePrices, type BalanceResult, BalanceTracker, type BuildToolOptions, CANVAS_TEMPLATES, type CanvasTemplate, type ChatParams, type CompactOptions, type ContentBlock, ContextBudget, type ContextBudgetConfig, type ConversationState, type ConversationStateStore, type CostSnapshot, CostTracker, type CostTrackerConfig, DEFAULT_GUARD_CONFIG, DEFAULT_LEASE_SEC, DEFAULT_PERMISSION_CONFIG, DEFAULT_POLL_BUDGET_MS, DEFAULT_POLL_INTERVAL_MS, DEFAULT_SYSTEM_PROMPT, DEFAULT_TOOL_TTL_MS, type DefiCacheEntry, type DefiCacheStore, type DefiProtocol, type DefiSummary, EFFORT_THINKING_BUDGET_CAPS, EarlyToolDispatcher, type EngineConfig, type EngineEvent, type EvalSummaryParseResult, type EvaluationItem, type EvaluationStatus, type FetchLock, type GuardCheckResult, type GuardConfig, type GuardEvent, type GuardInjection, type GuardResult, type GuardRunnerState, type GuardTier, type GuardVerdict, type HarnessShape, type HealthFactorResult, InMemoryDefiCacheStore, InMemoryFetchLock, InMemoryNaviCacheStore, InMemoryWalletCacheStore, InvalidAddressError, type LLMProvider, MAX_BUNDLE_OPS, type McpCallResult, McpClientManager, McpResponseCache, type McpServerConfig, type McpServerConnection, type McpToolAdapterConfig, type McpToolDescriptor, MemorySessionStore, type Message, NAVI_ADDR_TTL_SEC, NAVI_MCP_CONFIG, NAVI_MCP_URL, NAVI_RATES_TTL_SEC, NAVI_SERVER_NAME, type NaviCacheEntry, type NaviCacheStore, type NaviRawCoin, type NaviRawHealthFactor, type NaviRawPool, type NaviRawPosition, type NaviRawPositionsResponse, type NaviRawProtocolStats, type NaviRawRewardsResponse, type NaviReadOptions, NaviTools, type NormalizedAddress, type OutputConfig, PERMISSION_PRESETS, type PendingAction, type PendingActionModifiableField, type PendingActionStep, type PendingReward, type PendingToolCall, type PermissionLevel, type PermissionOperation, type PermissionResponse, type PermissionRule, type PortfolioCoin, type PositionEntry, type PreflightResult, type ProtocolStats, type ProviderEvent, QueryEngine, READ_TOOLS, REGENERATABLE_READ_TOOLS, type RatesResult, type Recipe, type RecipePrerequisite, RecipeRegistry, type RecipeStep, type RecipeStepOnError, type RegenerateFailure, type RegenerateResult, type RegenerateSuccess, type RegenerateTimelineEvent, RetryTracker, type SSEEvent, SUINS_NAME_REGEX, SUI_ADDRESS_REGEX, SUI_ADDRESS_STRICT_REGEX, type SavingsResult, type ServerPositionData, type SessionData, type SessionStore, type StateType, type StopReason, type SuiCoinBalance, SuinsNotRegisteredError, SuinsRpcError, type SystemBlock, type SystemPrompt, TOOL_FLAGS, TOOL_MODIFIABLE_FIELDS, TOOL_TTL_MS, type TelemetrySink, type TelemetryTags, type ThinkingConfig, type ThinkingEffort, type TodoItem$1 as TodoItem, type Tool, type ToolChoice, type ToolContext, type ToolDefinition, type ToolFlags, type ToolJsonSchema, type ToolResult, TxMutex, type UpdateTodoInput, type TodoItem as UpdateTodoItem, type UserFinancialProfile, type UserPermissionConfig, VALID_PAIRS, WRITE_TOOLS, type WalletCacheEntry, type WalletCacheStore, type WalletCoin, _resetNaviCircuitBreaker, activitySummaryTool, adaptAllMcpTools, adaptAllServerTools, adaptMcpTool, applyToolFlags, awaitOrFetch, balanceCheckTool, borrowTool, budgetToolResult, buildCachedSystemPrompt, buildMcpTools, buildProactivenessInstructions, buildProfileContext, buildSelfEvaluationInstruction, buildStateContext, buildTool, bundleShortestTtl, checkValidPair, claimRewardsTool, clampThinkingForEffort, classifyEffort, clearPortfolioCache, clearPortfolioCacheFor, clearPriceMapCache, compactMessages, createGuardRunnerState, engineToSSE, estimateTokens, explainTxTool, extractConversationText, extractMcpText, fetchAddressDefiPortfolio, fetchAddressPortfolio, fetchAudricHistory, fetchAudricPortfolio, fetchAvailableRewards, fetchBalance, fetchHealthFactor, fetchPositions, fetchProtocolStats, fetchRates, fetchSavings, fetchTokenPrices, fetchWalletCoins, findTool, getAudricApiBase, getDefaultTools, getDefiCacheStore, getFetchLock, getMcpManager, getModifiableFields, getNaviCacheStore, getTelemetrySink, getToolFlags, getWalletAddress, getWalletCacheStore, guardArtifactPreview, guardStaleData, harnessShapeForEffort, hasNaviMcp, healthCheckTool, isBundleableTool, loadRecipes, looksLikeSuiNs, microcompact, mppServicesTool, naviKey, normalizeAddressInput, parseEvalSummary, parseMcpJson, parseRecipe, parseSSE, payApiTool, portfolioAnalysisTool, protocolDeepDiveTool, ratesInfoTool, regenerateBundle, registerEngineTools, renderCanvasTool, repayDebtTool, requireAgent, resetDefiCacheStore, resetFetchLock, resetNaviCacheStore, resetTelemetrySink, resetWalletCacheStore, resolveAddressToSuinsViaRpc, resolvePermissionTier, resolveSuinsTool, resolveSuinsViaRpc, resolveUsdValue, runGuards, runTools, saveContactTool, saveDepositTool, savingsInfoTool, sendTransferTool, serializeSSE, setDefiCacheStore, setFetchLock, setNaviCacheStore, setTelemetrySink, setWalletCacheStore, spendingAnalyticsTool, swapExecuteTool, swapQuoteTool, tokenPricesTool, toolNameToOperation, toolsToDefinitions, transactionHistoryTool, transformBalance, transformHealthFactor, transformPositions, transformRates, transformRewards, transformSavings, updateGuardStateAfterToolResult, updateTodoTool, validateHistory, voloStakeTool, voloStatsTool, voloUnstakeTool, webSearchTool, withdrawTool, yieldSummaryTool };
3923
+ export { type AddressPortfolio, AnthropicProvider, type AnthropicProviderConfig, type AudricHistoryRecord, type AudricPortfolioResult, type AwaitOrFetchOpts, type BalancePrices, type BalanceResult, BalanceTracker, type BuildToolOptions, type BundleCompositionInput, CANVAS_TEMPLATES, type CanvasTemplate, type ChatParams, type CompactOptions, type ContentBlock, ContextBudget, type ContextBudgetConfig, type ConversationState, type ConversationStateStore, type CostSnapshot, CostTracker, type CostTrackerConfig, DEFAULT_GUARD_CONFIG, DEFAULT_LEASE_SEC, DEFAULT_PERMISSION_CONFIG, DEFAULT_POLL_BUDGET_MS, DEFAULT_POLL_INTERVAL_MS, DEFAULT_SYSTEM_PROMPT, DEFAULT_TOOL_TTL_MS, type DefiCacheEntry, type DefiCacheStore, type DefiProtocol, type DefiSummary, EFFORT_THINKING_BUDGET_CAPS, EarlyToolDispatcher, type EngineConfig, type EngineEvent, type EvalSummaryParseResult, type EvaluationItem, type EvaluationStatus, type FetchLock, type GuardCheckResult, type GuardConfig, type GuardEvent, type GuardInjection, type GuardResult, type GuardRunnerState, type GuardTier, type GuardVerdict, type HarnessShape, type HealthFactorResult, InMemoryDefiCacheStore, InMemoryFetchLock, InMemoryNaviCacheStore, InMemoryWalletCacheStore, InvalidAddressError, type LLMProvider, MAX_BUNDLE_OPS, type McpCallResult, McpClientManager, McpResponseCache, type McpServerConfig, type McpServerConnection, type McpToolAdapterConfig, type McpToolDescriptor, MemorySessionStore, type Message, NAVI_ADDR_TTL_SEC, NAVI_MCP_CONFIG, NAVI_MCP_URL, NAVI_RATES_TTL_SEC, NAVI_SERVER_NAME, type NaviCacheEntry, type NaviCacheStore, type NaviRawCoin, type NaviRawHealthFactor, type NaviRawPool, type NaviRawPosition, type NaviRawPositionsResponse, type NaviRawProtocolStats, type NaviRawRewardsResponse, type NaviReadOptions, NaviTools, type NormalizedAddress, type OutputConfig, PERMISSION_PRESETS, type PendingAction, type PendingActionModifiableField, type PendingActionStep, type PendingReward, type PendingToolCall, type PermissionLevel, type PermissionOperation, type PermissionResponse, type PermissionRule, type PortfolioCoin, type PositionEntry, type PreflightResult, type ProtocolStats, type ProviderEvent, QueryEngine, READ_TOOLS, REGENERATABLE_READ_TOOLS, type RatesResult, type Recipe, type RecipePrerequisite, RecipeRegistry, type RecipeStep, type RecipeStepOnError, type RegenerateFailure, type RegenerateResult, type RegenerateSuccess, type RegenerateTimelineEvent, RetryTracker, type SSEEvent, SUINS_NAME_REGEX, SUI_ADDRESS_REGEX, SUI_ADDRESS_STRICT_REGEX, type SavingsResult, type ServerPositionData, type SessionData, type SessionStore, type StateType, type StopReason, type SuiCoinBalance, SuinsNotRegisteredError, SuinsRpcError, type SystemBlock, type SystemPrompt, TOOL_FLAGS, TOOL_MODIFIABLE_FIELDS, TOOL_TTL_MS, type TelemetrySink, type TelemetryTags, type ThinkingConfig, type ThinkingEffort, type TodoItem$1 as TodoItem, type Tool, type ToolChoice, type ToolContext, type ToolDefinition, type ToolFlags, type ToolJsonSchema, type ToolResult, TxMutex, type UpdateTodoInput, type TodoItem as UpdateTodoItem, type UserFinancialProfile, type UserPermissionConfig, VALID_PAIRS, WRITE_TOOLS, type WalletCacheEntry, type WalletCacheStore, type WalletCoin, _resetNaviCircuitBreaker, activitySummaryTool, adaptAllMcpTools, adaptAllServerTools, adaptMcpTool, applyToolFlags, awaitOrFetch, balanceCheckTool, borrowTool, budgetToolResult, buildCachedSystemPrompt, buildMcpTools, buildProactivenessInstructions, buildProfileContext, buildSelfEvaluationInstruction, buildStateContext, buildTool, bundleShortestTtl, checkValidPair, claimRewardsTool, clampThinkingForEffort, classifyEffort, clearPortfolioCache, clearPortfolioCacheFor, clearPriceMapCache, compactMessages, composeBundleFromToolResults, computeRegenerateFields, createGuardRunnerState, engineToSSE, estimateTokens, explainTxTool, extractConversationText, extractMcpText, fetchAddressDefiPortfolio, fetchAddressPortfolio, fetchAudricHistory, fetchAudricPortfolio, fetchAvailableRewards, fetchBalance, fetchHealthFactor, fetchPositions, fetchProtocolStats, fetchRates, fetchSavings, fetchTokenPrices, fetchWalletCoins, findTool, getAudricApiBase, getDefaultTools, getDefiCacheStore, getFetchLock, getMcpManager, getModifiableFields, getNaviCacheStore, getTelemetrySink, getToolFlags, getWalletAddress, getWalletCacheStore, guardArtifactPreview, guardStaleData, harnessShapeForEffort, hasNaviMcp, healthCheckTool, isBundleableTool, loadRecipes, looksLikeSuiNs, microcompact, mppServicesTool, naviKey, normalizeAddressInput, parseEvalSummary, parseMcpJson, parseRecipe, parseSSE, payApiTool, portfolioAnalysisTool, protocolDeepDiveTool, ratesInfoTool, regenerateBundle, registerEngineTools, renderCanvasTool, repayDebtTool, requireAgent, resetDefiCacheStore, resetFetchLock, resetNaviCacheStore, resetTelemetrySink, resetWalletCacheStore, resolveAddressToSuinsViaRpc, resolvePermissionTier, resolveSuinsTool, resolveSuinsViaRpc, resolveUsdValue, runGuards, runTools, saveContactTool, saveDepositTool, savingsInfoTool, sendTransferTool, serializeSSE, setDefiCacheStore, setFetchLock, setNaviCacheStore, setTelemetrySink, setWalletCacheStore, spendingAnalyticsTool, swapExecuteTool, swapQuoteTool, tokenPricesTool, toolNameToOperation, toolsToDefinitions, transactionHistoryTool, transformBalance, transformHealthFactor, transformPositions, transformRates, transformRewards, transformSavings, updateGuardStateAfterToolResult, updateTodoTool, validateHistory, voloStakeTool, voloStatsTool, voloUnstakeTool, webSearchTool, withdrawTool, yieldSummaryTool };
package/dist/index.js CHANGED
@@ -6799,6 +6799,18 @@ function shouldChainCoin(producer, consumer) {
6799
6799
  if (!out || !inA) return false;
6800
6800
  return out === inA;
6801
6801
  }
6802
+ function computeRegenerateFields(readResults) {
6803
+ const regenerateToolUseIds = readResults.filter((r) => REGENERATABLE_READ_TOOLS.has(r.toolName)).map((r) => r.toolUseId);
6804
+ const canRegenerate = regenerateToolUseIds.length > 0;
6805
+ let quoteAge;
6806
+ if (canRegenerate) {
6807
+ const stalest = Math.min(
6808
+ ...readResults.filter((r) => REGENERATABLE_READ_TOOLS.has(r.toolName)).map((r) => r.timestamp)
6809
+ );
6810
+ quoteAge = Math.max(0, Date.now() - stalest);
6811
+ }
6812
+ return { canRegenerate, regenerateToolUseIds, quoteAge };
6813
+ }
6802
6814
  function composeBundleFromToolResults(input) {
6803
6815
  if (input.pendingWrites.length < 2) {
6804
6816
  throw new Error(
@@ -6837,15 +6849,7 @@ function composeBundleFromToolResults(input) {
6837
6849
  });
6838
6850
  }
6839
6851
  }
6840
- const regenerateToolUseIds = input.readResults.filter((r) => REGENERATABLE_READ_TOOLS.has(r.toolName)).map((r) => r.toolUseId);
6841
- const canRegenerate = regenerateToolUseIds.length > 0;
6842
- let quoteAge;
6843
- if (regenerateToolUseIds.length > 0) {
6844
- const stalest = Math.min(
6845
- ...input.readResults.filter((r) => REGENERATABLE_READ_TOOLS.has(r.toolName)).map((r) => r.timestamp)
6846
- );
6847
- quoteAge = Math.max(0, Date.now() - stalest);
6848
- }
6852
+ const { canRegenerate, regenerateToolUseIds, quoteAge } = computeRegenerateFields(input.readResults);
6849
6853
  const allGuardInjections = [];
6850
6854
  if (input.guardInjectionsByCallId) {
6851
6855
  for (const call of input.pendingWrites) {
@@ -7978,6 +7982,7 @@ ${recipeCtx}`;
7978
7982
  const writeGuardInjections = guardInjectionsByCallId[pendingWrite.call.id];
7979
7983
  const modifiableFields = getModifiableFields(pendingWrite.call.name);
7980
7984
  const attemptId = randomUUID();
7985
+ const singleWriteRegen = computeRegenerateFields(turnReadToolResults);
7981
7986
  yield {
7982
7987
  type: "pending_action",
7983
7988
  action: {
@@ -7994,7 +7999,12 @@ ${recipeCtx}`;
7994
7999
  ...writeGuardInjections?.length ? { guardInjections: writeGuardInjections } : {},
7995
8000
  ...modifiableFields?.length ? { modifiableFields } : {},
7996
8001
  turnIndex,
7997
- attemptId
8002
+ attemptId,
8003
+ ...singleWriteRegen.canRegenerate ? {
8004
+ canRegenerate: true,
8005
+ regenerateInput: { toolUseIds: singleWriteRegen.regenerateToolUseIds },
8006
+ ...singleWriteRegen.quoteAge !== void 0 ? { quoteAge: singleWriteRegen.quoteAge } : {}
8007
+ } : {}
7998
8008
  }
7999
8009
  };
8000
8010
  recordTurnOutcome("pending_action_single");
@@ -8222,13 +8232,6 @@ function harnessShapeForEffort(effort) {
8222
8232
  }
8223
8233
  }
8224
8234
  async function regenerateBundle(engine, action) {
8225
- if (!action.steps || action.steps.length < 2) {
8226
- return {
8227
- success: false,
8228
- reason: "pending_action_not_found",
8229
- message: "Action is not a multi-step bundle"
8230
- };
8231
- }
8232
8235
  if (action.canRegenerate !== true) {
8233
8236
  return {
8234
8237
  success: false,
@@ -8342,11 +8345,6 @@ async function regenerateBundle(engine, action) {
8342
8345
  { role: "user", content: synthUserBlocks }
8343
8346
  ];
8344
8347
  engine.loadMessages([...messages, ...synthMessages]);
8345
- const pendingWrites = action.steps.map((step) => ({
8346
- id: step.toolUseId,
8347
- name: step.toolName,
8348
- input: step.input
8349
- }));
8350
8348
  const readResults = newReads.map((r) => ({
8351
8349
  toolUseId: r.toolUseId,
8352
8350
  toolName: r.toolName,
@@ -8355,20 +8353,61 @@ async function regenerateBundle(engine, action) {
8355
8353
  const assistantContent = action.assistantContent ?? [];
8356
8354
  const completedResults = action.completedResults ?? [];
8357
8355
  let newPendingAction;
8358
- try {
8359
- newPendingAction = composeBundleFromToolResults({
8360
- pendingWrites,
8361
- tools,
8362
- readResults,
8356
+ if (action.steps && action.steps.length >= 2) {
8357
+ const pendingWrites = action.steps.map((step) => ({
8358
+ id: step.toolUseId,
8359
+ name: step.toolName,
8360
+ input: step.input
8361
+ }));
8362
+ try {
8363
+ newPendingAction = composeBundleFromToolResults({
8364
+ pendingWrites,
8365
+ tools,
8366
+ readResults,
8367
+ assistantContent,
8368
+ completedResults,
8369
+ turnIndex: action.turnIndex
8370
+ });
8371
+ } catch (err) {
8372
+ return {
8373
+ success: false,
8374
+ reason: "engine_error",
8375
+ message: err instanceof Error ? err.message : "Bundle rebuild failed"
8376
+ };
8377
+ }
8378
+ } else {
8379
+ const tool = findTool(tools, action.toolName);
8380
+ if (!tool) {
8381
+ return {
8382
+ success: false,
8383
+ reason: "engine_error",
8384
+ message: `Unknown tool '${action.toolName}' in single-write rebuild`
8385
+ };
8386
+ }
8387
+ const call = {
8388
+ id: action.toolUseId,
8389
+ name: action.toolName,
8390
+ input: action.input
8391
+ };
8392
+ const description = describeAction(tool, call);
8393
+ const modifiableFields = getModifiableFields(action.toolName);
8394
+ const { canRegenerate, regenerateToolUseIds, quoteAge } = computeRegenerateFields(readResults);
8395
+ newPendingAction = {
8396
+ toolName: action.toolName,
8397
+ toolUseId: action.toolUseId,
8398
+ input: action.input,
8399
+ description,
8363
8400
  assistantContent,
8364
8401
  completedResults,
8365
- turnIndex: action.turnIndex
8366
- });
8367
- } catch (err) {
8368
- return {
8369
- success: false,
8370
- reason: "engine_error",
8371
- message: err instanceof Error ? err.message : "Bundle rebuild failed"
8402
+ ...action.guardInjections?.length ? { guardInjections: action.guardInjections } : {},
8403
+ ...modifiableFields?.length ? { modifiableFields } : {},
8404
+ turnIndex: action.turnIndex,
8405
+ attemptId: randomUUID(),
8406
+ ...canRegenerate ? {
8407
+ canRegenerate: true,
8408
+ regenerateInput: { toolUseIds: regenerateToolUseIds },
8409
+ ...quoteAge !== void 0 ? { quoteAge } : {}
8410
+ } : {}
8372
8411
  };
8373
8412
  }
8374
8413
  return { success: true, newPendingAction, timelineEvents };
@@ -9485,6 +9524,6 @@ function sanitizeAnthropicMessages(messages) {
9485
9524
  return merged;
9486
9525
  }
9487
9526
 
9488
- export { AnthropicProvider, BalanceTracker, CANVAS_TEMPLATES, ContextBudget, CostTracker, DEFAULT_GUARD_CONFIG, DEFAULT_LEASE_SEC, DEFAULT_PERMISSION_CONFIG, DEFAULT_POLL_BUDGET_MS, DEFAULT_POLL_INTERVAL_MS, DEFAULT_SYSTEM_PROMPT, DEFAULT_TOOL_TTL_MS, EFFORT_THINKING_BUDGET_CAPS, EarlyToolDispatcher, InMemoryDefiCacheStore, InMemoryFetchLock, InMemoryNaviCacheStore, InMemoryWalletCacheStore, InvalidAddressError, MAX_BUNDLE_OPS, McpClientManager, McpResponseCache, MemorySessionStore, NAVI_ADDR_TTL_SEC, NAVI_MCP_CONFIG, NAVI_MCP_URL, NAVI_RATES_TTL_SEC, NAVI_SERVER_NAME, NaviTools, PERMISSION_PRESETS, QueryEngine, READ_TOOLS, REGENERATABLE_READ_TOOLS, RecipeRegistry, RetryTracker, SUINS_NAME_REGEX, SUI_ADDRESS_REGEX, SUI_ADDRESS_STRICT_REGEX, SuinsNotRegisteredError, SuinsRpcError, TOOL_FLAGS, TOOL_MODIFIABLE_FIELDS, TOOL_TTL_MS, TxMutex, VALID_PAIRS, WRITE_TOOLS, _resetNaviCircuitBreaker, activitySummaryTool, adaptAllMcpTools, adaptAllServerTools, adaptMcpTool, applyToolFlags, awaitOrFetch, balanceCheckTool, borrowTool, budgetToolResult, buildCachedSystemPrompt, buildMcpTools, buildProactivenessInstructions, buildProfileContext, buildSelfEvaluationInstruction, buildStateContext, buildTool, bundleShortestTtl, checkValidPair, claimRewardsTool, clampThinkingForEffort, classifyEffort, clearPortfolioCache, clearPortfolioCacheFor, clearPriceMapCache, compactMessages, createGuardRunnerState, engineToSSE, estimateTokens, explainTxTool, extractConversationText, extractMcpText, fetchAddressDefiPortfolio, fetchAddressPortfolio, fetchAudricHistory, fetchAudricPortfolio, fetchAvailableRewards, fetchBalance, fetchHealthFactor, fetchPositions, fetchProtocolStats, fetchRates, fetchSavings, fetchTokenPrices, fetchWalletCoins, findTool, getAudricApiBase, getDefaultTools, getDefiCacheStore, getFetchLock, getMcpManager, getModifiableFields, getNaviCacheStore, getTelemetrySink, getToolFlags, getWalletAddress, getWalletCacheStore, guardArtifactPreview, guardStaleData, harnessShapeForEffort, hasNaviMcp, healthCheckTool, isBundleableTool, loadRecipes, looksLikeSuiNs, microcompact, mppServicesTool, naviKey, normalizeAddressInput, parseEvalSummary, parseMcpJson, parseRecipe, parseSSE, payApiTool, portfolioAnalysisTool, protocolDeepDiveTool, ratesInfoTool, regenerateBundle, registerEngineTools, renderCanvasTool, repayDebtTool, requireAgent, resetDefiCacheStore, resetFetchLock, resetNaviCacheStore, resetTelemetrySink, resetWalletCacheStore, resolveAddressToSuinsViaRpc, resolvePermissionTier, resolveSuinsTool, resolveSuinsViaRpc, resolveUsdValue, runGuards, runTools, saveContactTool, saveDepositTool, savingsInfoTool, sendTransferTool, serializeSSE, setDefiCacheStore, setFetchLock, setNaviCacheStore, setTelemetrySink, setWalletCacheStore, spendingAnalyticsTool, swapExecuteTool, swapQuoteTool, tokenPricesTool, toolNameToOperation, toolsToDefinitions, transactionHistoryTool, transformBalance, transformHealthFactor, transformPositions, transformRates, transformRewards, transformSavings, updateGuardStateAfterToolResult, updateTodoTool, validateHistory, voloStakeTool, voloStatsTool, voloUnstakeTool, webSearchTool, withdrawTool, yieldSummaryTool };
9527
+ export { AnthropicProvider, BalanceTracker, CANVAS_TEMPLATES, ContextBudget, CostTracker, DEFAULT_GUARD_CONFIG, DEFAULT_LEASE_SEC, DEFAULT_PERMISSION_CONFIG, DEFAULT_POLL_BUDGET_MS, DEFAULT_POLL_INTERVAL_MS, DEFAULT_SYSTEM_PROMPT, DEFAULT_TOOL_TTL_MS, EFFORT_THINKING_BUDGET_CAPS, EarlyToolDispatcher, InMemoryDefiCacheStore, InMemoryFetchLock, InMemoryNaviCacheStore, InMemoryWalletCacheStore, InvalidAddressError, MAX_BUNDLE_OPS, McpClientManager, McpResponseCache, MemorySessionStore, NAVI_ADDR_TTL_SEC, NAVI_MCP_CONFIG, NAVI_MCP_URL, NAVI_RATES_TTL_SEC, NAVI_SERVER_NAME, NaviTools, PERMISSION_PRESETS, QueryEngine, READ_TOOLS, REGENERATABLE_READ_TOOLS, RecipeRegistry, RetryTracker, SUINS_NAME_REGEX, SUI_ADDRESS_REGEX, SUI_ADDRESS_STRICT_REGEX, SuinsNotRegisteredError, SuinsRpcError, TOOL_FLAGS, TOOL_MODIFIABLE_FIELDS, TOOL_TTL_MS, TxMutex, VALID_PAIRS, WRITE_TOOLS, _resetNaviCircuitBreaker, activitySummaryTool, adaptAllMcpTools, adaptAllServerTools, adaptMcpTool, applyToolFlags, awaitOrFetch, balanceCheckTool, borrowTool, budgetToolResult, buildCachedSystemPrompt, buildMcpTools, buildProactivenessInstructions, buildProfileContext, buildSelfEvaluationInstruction, buildStateContext, buildTool, bundleShortestTtl, checkValidPair, claimRewardsTool, clampThinkingForEffort, classifyEffort, clearPortfolioCache, clearPortfolioCacheFor, clearPriceMapCache, compactMessages, composeBundleFromToolResults, computeRegenerateFields, createGuardRunnerState, engineToSSE, estimateTokens, explainTxTool, extractConversationText, extractMcpText, fetchAddressDefiPortfolio, fetchAddressPortfolio, fetchAudricHistory, fetchAudricPortfolio, fetchAvailableRewards, fetchBalance, fetchHealthFactor, fetchPositions, fetchProtocolStats, fetchRates, fetchSavings, fetchTokenPrices, fetchWalletCoins, findTool, getAudricApiBase, getDefaultTools, getDefiCacheStore, getFetchLock, getMcpManager, getModifiableFields, getNaviCacheStore, getTelemetrySink, getToolFlags, getWalletAddress, getWalletCacheStore, guardArtifactPreview, guardStaleData, harnessShapeForEffort, hasNaviMcp, healthCheckTool, isBundleableTool, loadRecipes, looksLikeSuiNs, microcompact, mppServicesTool, naviKey, normalizeAddressInput, parseEvalSummary, parseMcpJson, parseRecipe, parseSSE, payApiTool, portfolioAnalysisTool, protocolDeepDiveTool, ratesInfoTool, regenerateBundle, registerEngineTools, renderCanvasTool, repayDebtTool, requireAgent, resetDefiCacheStore, resetFetchLock, resetNaviCacheStore, resetTelemetrySink, resetWalletCacheStore, resolveAddressToSuinsViaRpc, resolvePermissionTier, resolveSuinsTool, resolveSuinsViaRpc, resolveUsdValue, runGuards, runTools, saveContactTool, saveDepositTool, savingsInfoTool, sendTransferTool, serializeSSE, setDefiCacheStore, setFetchLock, setNaviCacheStore, setTelemetrySink, setWalletCacheStore, spendingAnalyticsTool, swapExecuteTool, swapQuoteTool, tokenPricesTool, toolNameToOperation, toolsToDefinitions, transactionHistoryTool, transformBalance, transformHealthFactor, transformPositions, transformRates, transformRewards, transformSavings, updateGuardStateAfterToolResult, updateTodoTool, validateHistory, voloStakeTool, voloStatsTool, voloUnstakeTool, webSearchTool, withdrawTool, yieldSummaryTool };
9489
9528
  //# sourceMappingURL=index.js.map
9490
9529
  //# sourceMappingURL=index.js.map