@vtxmacro/cli 2026.10.51 → 2026.10.52

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/vtx.js CHANGED
@@ -122,7 +122,7 @@ var init_routing = __esm({
122
122
  var agent_cli_release_default;
123
123
  var init_agent_cli_release = __esm({
124
124
  "agent-cli-release.json"() {
125
- agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.51", codex_package_name: "@openai/codex", codex_version: "0.155.0", copilot_sdk_package_name: "@github/copilot-sdk", copilot_sdk_version: "1.0.0-beta.8", copilot_cli_package_name: "@github/copilot", copilot_cli_version: "1.0.80", deepseek_harness_version: "0.1.1-rc.2", deepseek_harness_packages: ["@deepseek-ai/dsh-agent", "@deepseek-ai/dsh-agent-instructions", "@deepseek-ai/dsh-agent-loop", "@deepseek-ai/dsh-agent-spine-demo", "@deepseek-ai/dsh-anonymous-user-id", "@deepseek-ai/dsh-atomic-write", "@deepseek-ai/dsh-attachment", "@deepseek-ai/dsh-brand", "@deepseek-ai/dsh-code-runtime", "@deepseek-ai/dsh-credentials", "@deepseek-ai/dsh-fs", "@deepseek-ai/dsh-goal", "@deepseek-ai/dsh-goal-round-driver", "@deepseek-ai/dsh-home-paths", "@deepseek-ai/dsh-invariants", "@deepseek-ai/dsh-jobs", "@deepseek-ai/dsh-jobs-local", "@deepseek-ai/dsh-launch-environment", "@deepseek-ai/dsh-llm", "@deepseek-ai/dsh-llm-deepseek", "@deepseek-ai/dsh-llm-retry", "@deepseek-ai/dsh-output-retention", "@deepseek-ai/dsh-sandbox", "@deepseek-ai/dsh-sandbox-policy", "@deepseek-ai/dsh-scope", "@deepseek-ai/dsh-session", "@deepseek-ai/dsh-session-checkpoint-policy", "@deepseek-ai/dsh-session-persistence", "@deepseek-ai/dsh-session-persistence-jsonl", "@deepseek-ai/dsh-session-projection", "@deepseek-ai/dsh-session-title", "@deepseek-ai/dsh-settings", "@deepseek-ai/dsh-shell", "@deepseek-ai/dsh-shell-env", "@deepseek-ai/dsh-skill", "@deepseek-ai/dsh-skill-filesystem", "@deepseek-ai/dsh-subprocess", "@deepseek-ai/dsh-system-prompt", "@deepseek-ai/dsh-timeout", "@deepseek-ai/dsh-tool-bash", "@deepseek-ai/dsh-tool-goal", "@deepseek-ai/dsh-tool-jobs", "@deepseek-ai/dsh-tool-skill", "@deepseek-ai/dsh-tools", "@deepseek-ai/dsh-typert-protocol", "@deepseek-ai/dsh-user-approval"], deepseek_cordis_package_name: "@deepseek-ai/cordis", deepseek_cordis_version: "4.0.1", deepseek_support_packages: { "@deepseek-ai/cordis-plugin-timer": "1.1.3" }, platforms: { "linux-x64": { package_name: "@openai/codex-linux-x64", target: "x86_64-unknown-linux-musl", binary_name: "codex", sha256: "660e159a49e823ac8e5986cb238f73158ce4b957d40d9292f8de90862644b501" }, "win32-x64": { package_name: "@openai/codex-win32-x64", target: "x86_64-pc-windows-msvc", binary_name: "codex.exe", sha256: "e4c11374bd9de8ad5c3b7617fd4654bb7839901edb0863f9930666863c7a021b" } }, pi_coding_agent_package_name: "@earendil-works/pi-coding-agent", pi_ai_package_name: "@earendil-works/pi-ai", pi_version: "0.85.1", pi_support_packages: ["@earendil-works/pi-agent-core", "@earendil-works/pi-telemetry", "@earendil-works/pi-tui", "@earendil-works/chord"], grok_version: "1.0.30", grok_platforms: { "linux-x64": { package_name: "@xai-official/grok-linux-x64", binary_name: "grok", sha256: "504dd6546ab991b75d36698242875ce461489cd1f8cd84285873cb55bd5c7d54" }, "win32-x64": { package_name: "@xai-official/grok-win32-x64", binary_name: "grok.exe", sha256: "48736d1a4342a801ea26d0ecde4c516b653f791399065adaa55973f83abd8867" } } };
125
+ agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.52", codex_package_name: "@openai/codex", codex_version: "0.155.0", copilot_sdk_package_name: "@github/copilot-sdk", copilot_sdk_version: "1.0.0-beta.8", copilot_cli_package_name: "@github/copilot", copilot_cli_version: "1.0.80", deepseek_harness_version: "0.1.1-rc.2", deepseek_harness_packages: ["@deepseek-ai/dsh-agent", "@deepseek-ai/dsh-agent-instructions", "@deepseek-ai/dsh-agent-loop", "@deepseek-ai/dsh-agent-spine-demo", "@deepseek-ai/dsh-anonymous-user-id", "@deepseek-ai/dsh-atomic-write", "@deepseek-ai/dsh-attachment", "@deepseek-ai/dsh-brand", "@deepseek-ai/dsh-code-runtime", "@deepseek-ai/dsh-credentials", "@deepseek-ai/dsh-fs", "@deepseek-ai/dsh-goal", "@deepseek-ai/dsh-goal-round-driver", "@deepseek-ai/dsh-home-paths", "@deepseek-ai/dsh-invariants", "@deepseek-ai/dsh-jobs", "@deepseek-ai/dsh-jobs-local", "@deepseek-ai/dsh-launch-environment", "@deepseek-ai/dsh-llm", "@deepseek-ai/dsh-llm-deepseek", "@deepseek-ai/dsh-llm-retry", "@deepseek-ai/dsh-output-retention", "@deepseek-ai/dsh-sandbox", "@deepseek-ai/dsh-sandbox-policy", "@deepseek-ai/dsh-scope", "@deepseek-ai/dsh-session", "@deepseek-ai/dsh-session-checkpoint-policy", "@deepseek-ai/dsh-session-persistence", "@deepseek-ai/dsh-session-persistence-jsonl", "@deepseek-ai/dsh-session-projection", "@deepseek-ai/dsh-session-title", "@deepseek-ai/dsh-settings", "@deepseek-ai/dsh-shell", "@deepseek-ai/dsh-shell-env", "@deepseek-ai/dsh-skill", "@deepseek-ai/dsh-skill-filesystem", "@deepseek-ai/dsh-subprocess", "@deepseek-ai/dsh-system-prompt", "@deepseek-ai/dsh-timeout", "@deepseek-ai/dsh-tool-bash", "@deepseek-ai/dsh-tool-goal", "@deepseek-ai/dsh-tool-jobs", "@deepseek-ai/dsh-tool-skill", "@deepseek-ai/dsh-tools", "@deepseek-ai/dsh-typert-protocol", "@deepseek-ai/dsh-user-approval"], deepseek_cordis_package_name: "@deepseek-ai/cordis", deepseek_cordis_version: "4.0.1", deepseek_support_packages: { "@deepseek-ai/cordis-plugin-timer": "1.1.3" }, platforms: { "linux-x64": { package_name: "@openai/codex-linux-x64", target: "x86_64-unknown-linux-musl", binary_name: "codex", sha256: "660e159a49e823ac8e5986cb238f73158ce4b957d40d9292f8de90862644b501" }, "win32-x64": { package_name: "@openai/codex-win32-x64", target: "x86_64-pc-windows-msvc", binary_name: "codex.exe", sha256: "e4c11374bd9de8ad5c3b7617fd4654bb7839901edb0863f9930666863c7a021b" } }, pi_coding_agent_package_name: "@earendil-works/pi-coding-agent", pi_ai_package_name: "@earendil-works/pi-ai", pi_version: "0.85.1", pi_support_packages: ["@earendil-works/pi-agent-core", "@earendil-works/pi-telemetry", "@earendil-works/pi-tui", "@earendil-works/chord"], grok_version: "1.0.30", grok_platforms: { "linux-x64": { package_name: "@xai-official/grok-linux-x64", binary_name: "grok", sha256: "504dd6546ab991b75d36698242875ce461489cd1f8cd84285873cb55bd5c7d54" }, "win32-x64": { package_name: "@xai-official/grok-win32-x64", binary_name: "grok.exe", sha256: "48736d1a4342a801ea26d0ecde4c516b653f791399065adaa55973f83abd8867" } } };
126
126
  }
127
127
  });
128
128
 
@@ -98696,9 +98696,8 @@ async function reportClientRuntimeDecision(profileId, payload, options) {
98696
98696
  if (payload.externalInferenceBindings !== void 0) {
98697
98697
  extras.external_inference_bindings = payload.externalInferenceBindings;
98698
98698
  }
98699
- if (payload.externalAgentInstruction !== void 0) {
98700
- extras.external_agent_instruction = payload.externalAgentInstruction ?? null;
98701
- }
98699
+ if (payload.externalAgentInstruction !== void 0) extras.external_agent_instruction = payload.externalAgentInstruction ?? null;
98700
+ if (payload.unsentOrder) extras.unsent_order = { decision: payload.unsentOrder.decision, units: payload.unsentOrder.units, constraint_reason_code: payload.unsentOrder.constraintReasonCode };
98702
98701
  const body = buildClientRuntimeBody(payload, extras);
98703
98702
  const digestPromise = globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(body)).then((digest2) => Array.from(new Uint8Array(digest2), (byte) => byte.toString(HEX_RADIX).padStart(BYTE_HEX_DIGITS, "0")).join(""));
98704
98703
  const idempotencyKey = options?.idempotencyKey || createIdempotencyKey("runtime-decision");
@@ -98890,7 +98889,8 @@ async function reportClientRuntimeError(profileId, payload, options) {
98890
98889
  execution_reason_code: payload.executionReasonCode ?? null,
98891
98890
  execution_stage: payload.executionStage ?? null,
98892
98891
  dispatch_outcome: payload.dispatchOutcome ?? null,
98893
- provider_failure: payload.providerFailure ?? null
98892
+ provider_failure: payload.providerFailure ?? null,
98893
+ ...payload.externalAgentInstruction ? { external_agent_instruction: payload.externalAgentInstruction } : {}
98894
98894
  }),
98895
98895
  options
98896
98896
  );
@@ -98933,9 +98933,7 @@ async function reportClientRuntimeTradeSync(profileId, payload, options) {
98933
98933
  if (typeof payload.isExecuting === "boolean") {
98934
98934
  extras.is_executing = payload.isExecuting;
98935
98935
  }
98936
- if (payload.externalAgentInstruction !== void 0) {
98937
- extras.external_agent_instruction = payload.externalAgentInstruction ?? null;
98938
- }
98936
+ if (payload.externalAgentInstruction !== void 0) extras.external_agent_instruction = payload.externalAgentInstruction ?? null;
98939
98937
  return postClientRuntime(
98940
98938
  "/runtime/trade-sync",
98941
98939
  profileId,
@@ -104809,10 +104807,10 @@ var init_prompt_number_contract = __esm({
104809
104807
  }
104810
104808
  });
104811
104809
 
104812
- // lib/runtime/server-execution-capacity.ts
104813
- var capacityUnitsUsedForPosition, allocatePlanCapacity;
104814
- var init_server_execution_capacity = __esm({
104815
- "lib/runtime/server-execution-capacity.ts"() {
104810
+ // lib/runtime/execution-capacity.ts
104811
+ var capacityUnitsUsedForPosition, openCapacityRoom, allocatePlanCapacity, withCapacityTrim;
104812
+ var init_execution_capacity = __esm({
104813
+ "lib/runtime/execution-capacity.ts"() {
104816
104814
  "use strict";
104817
104815
  init_define_VTX_CLAUDE_CODE_POLICY();
104818
104816
  init_define_VTX_EXO_POLICY();
@@ -104839,7 +104837,7 @@ var init_server_execution_capacity = __esm({
104839
104837
  }
104840
104838
  return Math.max(0, unitsUsed);
104841
104839
  };
104842
- allocatePlanCapacity = (positions, plans, limits) => {
104840
+ openCapacityRoom = (positions, limits) => {
104843
104841
  let globalUnits = 0;
104844
104842
  const exchangeUsage = /* @__PURE__ */ new Map();
104845
104843
  for (const position of positions) {
@@ -104856,14 +104854,33 @@ var init_server_execution_capacity = __esm({
104856
104854
  const remainingExchangeByDex = new Map(
104857
104855
  [...exchangeUsage].map(([dex, used]) => [dex, exchangeLimit - used])
104858
104856
  );
104857
+ const signedUnits = (symbol2) => {
104858
+ const normalized = normalizeHyperliquidMarketSymbol(symbol2);
104859
+ const position = positions.find((candidate) => normalizeHyperliquidMarketSymbol(candidate.symbol) === normalized);
104860
+ return position ? signedUnitsFromEntryPosition(position.size, position.entry_price, limits.unit_size) : 0;
104861
+ };
104862
+ const remainingExchange = (symbol2) => remainingExchangeByDex.get(getHyperliquidMarketDex(symbol2)) ?? exchangeLimit;
104863
+ return {
104864
+ signedUnits,
104865
+ caps: (symbol2) => ({
104866
+ remaining_global_units: remainingGlobal,
104867
+ remaining_exchange_units: remainingExchange(symbol2),
104868
+ remaining_asset_units: Math.trunc(limits.max_trades_per_asset || 0) - Math.abs(signedUnits(symbol2))
104869
+ }),
104870
+ take: (symbol2, decision, acceptedUnits) => {
104871
+ const currentAbsUnits = Math.abs(signedUnits(symbol2));
104872
+ const target = classifyExecutionIntent(decision, acceptedUnits, signedUnits(symbol2));
104873
+ const added = Math.max(0, Math.abs(target.targetSignedUnits) - currentAbsUnits);
104874
+ remainingGlobal = Math.max(0, remainingGlobal - added);
104875
+ remainingExchangeByDex.set(getHyperliquidMarketDex(symbol2), Math.max(0, remainingExchange(symbol2) - added));
104876
+ }
104877
+ };
104878
+ };
104879
+ allocatePlanCapacity = (positions, plans, limits) => {
104880
+ const room = openCapacityRoom(positions, limits);
104859
104881
  return plans.map((rawPlan) => {
104860
104882
  const symbol2 = normalizeHyperliquidMarketSymbol(rawPlan.symbol);
104861
104883
  const units = Math.trunc(rawPlan.units);
104862
- const dex = getHyperliquidMarketDex(symbol2);
104863
- const remainingExchange = remainingExchangeByDex.get(dex) ?? exchangeLimit;
104864
- const position = positions.find((candidate) => normalizeHyperliquidMarketSymbol(candidate.symbol) === symbol2);
104865
- const signedUnits = position ? signedUnitsFromEntryPosition(position.size, position.entry_price, limits.unit_size) : 0;
104866
- const currentAbsUnits = Math.abs(signedUnits);
104867
104884
  const acceptance = evaluateRuntimeDecisionAcceptance({
104868
104885
  decision: rawPlan.decision,
104869
104886
  units,
@@ -104872,24 +104889,26 @@ var init_server_execution_capacity = __esm({
104872
104889
  kill_switch_active: false,
104873
104890
  // The cycle's prompt allowance was applied with the decision.
104874
104891
  max_trades_per_prompt: units,
104875
- remaining_global_units: remainingGlobal,
104876
- remaining_exchange_units: remainingExchange,
104877
- remaining_asset_units: Math.trunc(limits.max_trades_per_asset || 0) - currentAbsUnits,
104878
- current_symbol_signed_units: signedUnits,
104892
+ ...room.caps(symbol2),
104893
+ current_symbol_signed_units: room.signedUnits(symbol2),
104879
104894
  model_allowed: true,
104880
104895
  provider_allowed: true
104881
104896
  }
104882
104897
  });
104883
104898
  const acceptedUnits = acceptance.accepted ? acceptance.normalized_units : 0;
104884
- if (acceptance.accepted) {
104885
- const target = classifyExecutionIntent(rawPlan.decision, acceptedUnits, signedUnits);
104886
- const globalDelta = Math.max(0, Math.abs(target.targetSignedUnits) - currentAbsUnits);
104887
- remainingGlobal = Math.max(0, remainingGlobal - globalDelta);
104888
- remainingExchangeByDex.set(dex, Math.max(0, remainingExchange - globalDelta));
104889
- }
104899
+ if (acceptance.accepted) room.take(symbol2, rawPlan.decision, acceptedUnits);
104890
104900
  return { symbol: symbol2, accepted: acceptance.accepted, units: acceptedUnits, reason_code: acceptance.reason_code };
104891
104901
  });
104892
104902
  };
104903
+ withCapacityTrim = (result, trim) => {
104904
+ const decisionOrders = result.executionReports.filter((report) => report.status === "executed" && (report.action === "BUY" || report.action === "SELL") && (result.intent !== "flip" || report.execution_metadata?.decision_leg === "entry"));
104905
+ const trimmed = decisionOrders[decisionOrders.length - 1];
104906
+ if (!trimmed) return result;
104907
+ return {
104908
+ ...result,
104909
+ executionReports: result.executionReports.map((report) => report === trimmed ? { ...report, execution_metadata: { ...report.execution_metadata, ...trim } } : report)
104910
+ };
104911
+ };
104893
104912
  }
104894
104913
  });
104895
104914
 
@@ -106932,7 +106951,7 @@ var init_native_protection_device = __esm({
106932
106951
  });
106933
106952
 
106934
106953
  // lib/runtime/runtime-execution.ts
106935
- var clientProtectiveMutationAuthority, executionReadPriority, serverEntryLeverageAlreadyHeld, fetchClientRuntimeOpenOrders, createRuntimeId, _extractFilledSize, firstMemberAcknowledgement, _extractOrderId, _toExecutionMetadata, _extractClientMutationId, _stableMutationIdentity, trailingStopMemory, protectiveGroupMemory, protectiveGroupReadFailures, windowHandoffCleanupAttempts, clientRuntimeProtectionStorage, resolveClientRuntimeProtectionStorage, setClientRuntimeProtectionStorage, trailingStopStorageKey, readTrackedTrailingStops, writeTrackedTrailingStops, rememberTrailingStop, protectiveGroupStorageKey, LOST_LEG_EVIDENCE_MAX_AGE_MS, EPISODE_END_FILL_LOOKBACK_MS, withClientProtectivePlanSetLock, readClientProtectiveGroups, writeClientProtectiveGroups, hasClientProtectiveGroupReadFailure, readFreshClientProtectiveGroups, stableProtectionSnapshot, exactClientProtectiveGroupSnapshot, exactClientProtectiveGroupSetSnapshot, storableClientProtectiveGroup, replaceExactClientProtectiveGroup, replaceExactClientProtectiveGroupSet, isClientRuntimeLeaseOwnershipError, hasClientRuntimeProtectionState, clearClientRuntimeVetoedProtectiveIntent, rethrowWindowHandoffAfterProtectiveReplacementVeto, canPersistClientProtectiveGroups, removeTrackedTrailingStop, replaceTrackedTrailingStop, replaceProtectiveLeg, replacementJournalEntryOrderId, buildProtectiveReplacementJournalGroup, isProtectiveReplacementJournalGroup, reserveProtectiveLegReplacement, ensureProtectiveReplacementJournalCompanion, buildVetoedProtectiveReplacementCleanup, assertExactProtectiveReplacementDispatchAuthority, transitionProtectiveReplacementAcknowledgement, transitionTerminalProtectiveReplacement, pendingProtectiveReplacementReport, isConfiguredProtectionRequested, protectiveAction, executedProtectiveReport, isExactClientPositionTpslPair, deviceOwnsClientProtectiveLegKind, isAdoptionNarrowedPositionTpslLeg, hasAmbiguousClientPositionTpslAuthority, protectiveStableShapeMatches, observedProtectiveGroupingMatches, protectiveLiveShapeMatches, protectiveTerminalShapeMatches, cancelClientProtectiveLeg, buildPendingProtectivePlan, persistPendingClientProtectiveGroup, attachmentMemberNeverLanded, storedClientProtectiveCover, attachClientProtectivePlan, resolveJournaledAttachmentContinuity, protectiveMemberRested, ledgerOrderIdsByClientOrderId, journaledAttachmentNeverLanded, recoverJournaledClientProtectiveAttachments, readClientOrderMutation, readPendingEntryMutation, clientOrderNeverLandsAfterMs, requireClientRuntimeConfigSeconds, replacePendingEntryRecovery, recoverPendingClientProtectiveGroups, recoverPendingProtectiveReplacements, liveProtectiveOrderShape, observedStandaloneProtectiveGroup, migrateTrackedTrailingStopsToStandalone, nativeSettingsOf, nativePassEnded, nativeProtectionIo, nativeStorageReport, readNativeRecord, reconcileNativeProtectionForDecision, reconcileClientProtectiveGroups, cancelAllClientProtectiveGroups, tightenClientTrailingStops, throwIfAborted2, sleep2, isDefinitiveEntryRejection, resolveExchangeSizeDecimals, roundAssetSize, resolvePositionSize, readServerOrderMarkPrice, serverOrderMetadataRetry, resolveCurrentPositionSize, buildPositionSnapshot, signedRemainingExposureAfterConfirmedReduction, runtimeProtectionAuthority, runtimeProtectionListings, runtimeProtectionListing, resolveServerNativeEntry, SERVER_NATIVE_LEGACY_REFUSAL, isServerNativeLegacyRefusal, serverUserCancelLookup, serverModeProtectionOwner, runtimeProtectionOwners, resolveRuntimeProtectionOwner, drainServerProtectionForRuntime, drainServerProtectionIfOwned, verifyNoLiveClientProtectiveTriggers, clientExecutionMutations, CLIENT_EXECUTION_QUEUE_TIMEOUT_MESSAGE, withClientExecutionMutation, withClientProtectivePlanSetMutation, allocateServerExecutionCapacity, withClientProtectiveAdoptionMutation, executeClientRuntimeDecisionLocked, unsentDecisionOrderReport, withCapacityTrim, SERVER_AUDIT_RECORDED_ELSEWHERE, serverExecutionAuditOutcome, decisionLegOf, withExecutionAuditId, executeClientRuntimeDecision, waitForFlipCloseFreshness, maintainClientRuntimeTrailingStops, listPendingClientProtectiveSymbols, listStoredClientProtectiveSymbols, hasUnresolvedClientProtectiveIdentity, resolveClientProtectiveIdentitiesForAdoption, exportClientProtectiveGroupsForAdoption, adoptionGroupKey, applyClientProtectiveAdoptionOutcomes, hasStoredClientProtectiveGroupsForWallet, hasPendingClientProtectiveGroups, recoverManualClientProtectiveGroups, clientRuntimeDecisionSizesOrders, COMMITTED_EXECUTION_REPORTS, COMMITTED_DECISION_ORDER, getCommittedExecutionReports, getCommittedDecisionOrder, withCommittedExecutionReports, executeClientRuntimeDecisionUnlocked;
106954
+ var clientProtectiveMutationAuthority, executionReadPriority, serverEntryLeverageAlreadyHeld, fetchClientRuntimeOpenOrders, createRuntimeId, _extractFilledSize, firstMemberAcknowledgement, _extractOrderId, _toExecutionMetadata, _extractClientMutationId, _stableMutationIdentity, trailingStopMemory, protectiveGroupMemory, protectiveGroupReadFailures, windowHandoffCleanupAttempts, clientRuntimeProtectionStorage, resolveClientRuntimeProtectionStorage, setClientRuntimeProtectionStorage, trailingStopStorageKey, readTrackedTrailingStops, writeTrackedTrailingStops, rememberTrailingStop, protectiveGroupStorageKey, LOST_LEG_EVIDENCE_MAX_AGE_MS, EPISODE_END_FILL_LOOKBACK_MS, withClientProtectivePlanSetLock, readClientProtectiveGroups, writeClientProtectiveGroups, hasClientProtectiveGroupReadFailure, readFreshClientProtectiveGroups, stableProtectionSnapshot, exactClientProtectiveGroupSnapshot, exactClientProtectiveGroupSetSnapshot, storableClientProtectiveGroup, replaceExactClientProtectiveGroup, replaceExactClientProtectiveGroupSet, isClientRuntimeLeaseOwnershipError, hasClientRuntimeProtectionState, clearClientRuntimeVetoedProtectiveIntent, rethrowWindowHandoffAfterProtectiveReplacementVeto, canPersistClientProtectiveGroups, removeTrackedTrailingStop, replaceTrackedTrailingStop, replaceProtectiveLeg, replacementJournalEntryOrderId, buildProtectiveReplacementJournalGroup, isProtectiveReplacementJournalGroup, reserveProtectiveLegReplacement, ensureProtectiveReplacementJournalCompanion, buildVetoedProtectiveReplacementCleanup, assertExactProtectiveReplacementDispatchAuthority, transitionProtectiveReplacementAcknowledgement, transitionTerminalProtectiveReplacement, pendingProtectiveReplacementReport, isConfiguredProtectionRequested, protectiveAction, executedProtectiveReport, isExactClientPositionTpslPair, deviceOwnsClientProtectiveLegKind, isAdoptionNarrowedPositionTpslLeg, hasAmbiguousClientPositionTpslAuthority, protectiveStableShapeMatches, observedProtectiveGroupingMatches, protectiveLiveShapeMatches, protectiveTerminalShapeMatches, cancelClientProtectiveLeg, buildPendingProtectivePlan, persistPendingClientProtectiveGroup, attachmentMemberNeverLanded, storedClientProtectiveCover, attachClientProtectivePlan, resolveJournaledAttachmentContinuity, protectiveMemberRested, ledgerOrderIdsByClientOrderId, journaledAttachmentNeverLanded, recoverJournaledClientProtectiveAttachments, readClientOrderMutation, readPendingEntryMutation, clientOrderNeverLandsAfterMs, requireClientRuntimeConfigSeconds, replacePendingEntryRecovery, recoverPendingClientProtectiveGroups, recoverPendingProtectiveReplacements, liveProtectiveOrderShape, observedStandaloneProtectiveGroup, migrateTrackedTrailingStopsToStandalone, nativeSettingsOf, nativePassEnded, nativeProtectionIo, nativeStorageReport, readNativeRecord, reconcileNativeProtectionForDecision, reconcileClientProtectiveGroups, cancelAllClientProtectiveGroups, tightenClientTrailingStops, throwIfAborted2, sleep2, isDefinitiveEntryRejection, resolveExchangeSizeDecimals, roundAssetSize, resolvePositionSize, readServerOrderMarkPrice, serverOrderMetadataRetry, resolveCurrentPositionSize, buildPositionSnapshot, signedRemainingExposureAfterConfirmedReduction, runtimeProtectionAuthority, runtimeProtectionListings, runtimeProtectionListing, resolveServerNativeEntry, SERVER_NATIVE_LEGACY_REFUSAL, isServerNativeLegacyRefusal, serverUserCancelLookup, serverModeProtectionOwner, runtimeProtectionOwners, resolveRuntimeProtectionOwner, drainServerProtectionForRuntime, drainServerProtectionIfOwned, verifyNoLiveClientProtectiveTriggers, clientExecutionMutations, CLIENT_EXECUTION_QUEUE_TIMEOUT_MESSAGE, withClientExecutionMutation, withClientProtectivePlanSetMutation, allocateServerExecutionCapacity, withClientProtectiveAdoptionMutation, executeClientRuntimeDecisionLocked, unsentDecisionOrderReport, SERVER_AUDIT_RECORDED_ELSEWHERE, serverExecutionAuditOutcome, decisionLegOf, withExecutionAuditId, executeClientRuntimeDecision, waitForFlipCloseFreshness, maintainClientRuntimeTrailingStops, listPendingClientProtectiveSymbols, listStoredClientProtectiveSymbols, hasUnresolvedClientProtectiveIdentity, resolveClientProtectiveIdentitiesForAdoption, exportClientProtectiveGroupsForAdoption, adoptionGroupKey, applyClientProtectiveAdoptionOutcomes, hasStoredClientProtectiveGroupsForWallet, hasPendingClientProtectiveGroups, recoverManualClientProtectiveGroups, clientRuntimeDecisionSizesOrders, COMMITTED_EXECUTION_REPORTS, COMMITTED_DECISION_ORDER, getCommittedExecutionReports, getCommittedDecisionOrder, withCommittedExecutionReports, executeClientRuntimeDecisionUnlocked;
106936
106955
  var init_runtime_execution = __esm({
106937
106956
  "lib/runtime/runtime-execution.ts"() {
106938
106957
  "use strict";
@@ -106948,7 +106967,7 @@ var init_runtime_execution = __esm({
106948
106967
  init_api2();
106949
106968
  init_client_exchange_mutations();
106950
106969
  init_hyperliquid_order_status();
106951
- init_server_execution_capacity();
106970
+ init_execution_capacity();
106952
106971
  init_protective_actions();
106953
106972
  init_browser_trading();
106954
106973
  init_execution_guard_contract();
@@ -112690,15 +112709,6 @@ var init_runtime_execution = __esm({
112690
112709
  ...input.executionContext.decisionSnapshotId ? { decision_snapshot_id: input.executionContext.decisionSnapshotId } : {}
112691
112710
  }
112692
112711
  });
112693
- withCapacityTrim = (result, trim) => {
112694
- const decisionOrders = result.executionReports.filter((report) => report.status === "executed" && (report.action === "BUY" || report.action === "SELL") && (result.intent !== "flip" || report.execution_metadata?.decision_leg === "entry"));
112695
- const trimmed = decisionOrders[decisionOrders.length - 1];
112696
- if (!trimmed) return result;
112697
- return {
112698
- ...result,
112699
- executionReports: result.executionReports.map((report) => report === trimmed ? { ...report, execution_metadata: { ...report.execution_metadata, ...trim } } : report)
112700
- };
112701
- };
112702
112712
  SERVER_AUDIT_RECORDED_ELSEWHERE = /* @__PURE__ */ new Set([
112703
112713
  "suppressed_duplicate_decision",
112704
112714
  "same_intent_cooldown",
@@ -115549,7 +115559,7 @@ var init_browser_observability = __esm({
115549
115559
  init_define_VTX_GROK_POLICY();
115550
115560
  init_define_VTX_PI_MODEL_POLICY();
115551
115561
  init_runtime_policy_generated2();
115552
- CLIENT_SOURCE_VERSION = typeof process !== "undefined" && true && "6284a7b4880c39e52d48be2d18084f99f2d8b46f".trim() && "6284a7b4880c39e52d48be2d18084f99f2d8b46f".trim() !== "unstamped" ? "6284a7b4880c39e52d48be2d18084f99f2d8b46f".trim() : null;
115562
+ CLIENT_SOURCE_VERSION = typeof process !== "undefined" && true && "05e1243254ebccb6045684218396b0d4cd9f6495".trim() && "05e1243254ebccb6045684218396b0d4cd9f6495".trim() !== "unstamped" ? "05e1243254ebccb6045684218396b0d4cd9f6495".trim() : null;
115553
115563
  listenersInstalled = false;
115554
115564
  state = {
115555
115565
  loadedAtMs: Date.now(),
@@ -117850,6 +117860,10 @@ var init_copy_trading_evidence = __esm({
117850
117860
  });
117851
117861
 
117852
117862
  // lib/runtime/copy-trading-execution.ts
117863
+ function copyOrderReduceOnly(input) {
117864
+ const { desiredPosition, actualPosition, size } = input;
117865
+ return Math.abs(desiredPosition) <= COPY_TRADING_SIZE_EPSILON || actualPosition * (desiredPosition - actualPosition) < 0 && Math.abs(size) <= Math.abs(actualPosition) + COPY_TRADING_SIZE_EPSILON;
117866
+ }
117853
117867
  function capCopiedToActual(copied, actual) {
117854
117868
  if (Math.abs(copied) <= COPY_TRADING_SIZE_EPSILON) return 0;
117855
117869
  if (copied * actual <= 0) return 0;
@@ -117884,7 +117898,7 @@ function copiedTargetNow(reconciliation, recordedTarget, actualPosition) {
117884
117898
  );
117885
117899
  return { copiedNow, targetNow, kept: copiedTargetBesideOwnPosition(targetNow, copiedNow, actualPosition) };
117886
117900
  }
117887
- var _extractOrderResponseStates, executeClientCopyTradingIntent, _copyCancelOrderId, executeClientCopyTradingOrderAction;
117901
+ var _extractOrderResponseStates, CLIENT_COPY_TRADING_EXECUTION, executeClientCopyTradingIntent, executeCopyTradingIntent, _copyCancelOrderId, executeClientCopyTradingOrderAction, executeCopyTradingOrderAction;
117888
117902
  var init_copy_trading_execution = __esm({
117889
117903
  "lib/runtime/copy-trading-execution.ts"() {
117890
117904
  "use strict";
@@ -117928,21 +117942,34 @@ var init_copy_trading_execution = __esm({
117928
117942
  });
117929
117943
  return parsed.every((item) => item != null) ? parsed : null;
117930
117944
  };
117931
- executeClientCopyTradingIntent = async (input) => {
117945
+ CLIENT_COPY_TRADING_EXECUTION = {
117946
+ runtimeMode: "client",
117947
+ pendingStatus: "pending_client",
117948
+ marketOrder: (input) => executeClientMarketOrder(input),
117949
+ limitOrder: (input) => executeClientLimitOrder(input),
117950
+ triggerOrder: (input) => executeClientTriggerOrder(input),
117951
+ orderBatch: (input) => executeClientOrderBatch(input),
117952
+ modifyOrder: (input) => executeClientModifyOrder(input),
117953
+ cancelOrder: (input) => executeClientCancelOrder(input),
117954
+ sizePrecision: (input) => quantizeHyperliquidOrderSize(input),
117955
+ orderStatusEvidence: (context, orderId) => readCopyOrderStatusEvidence(context, orderId)
117956
+ };
117957
+ executeClientCopyTradingIntent = (input) => executeCopyTradingIntent(input, CLIENT_COPY_TRADING_EXECUTION);
117958
+ executeCopyTradingIntent = async (input, execution) => {
117932
117959
  throwIfAborted2(input.signal);
117933
117960
  const intent = input.intent;
117934
- if (intent.status !== "pending_client") {
117961
+ if (intent.status !== execution.pendingStatus) {
117935
117962
  return {
117936
117963
  status: "skipped",
117937
117964
  orderId: null,
117938
- message: `Copy Trading intent is not pending_client: ${intent.status}`
117965
+ message: `Copy Trading intent is not ${execution.pendingStatus}: ${intent.status}`
117939
117966
  };
117940
117967
  }
117941
- if (intent.runtime_mode !== "client") {
117968
+ if (intent.runtime_mode !== execution.runtimeMode) {
117942
117969
  return {
117943
117970
  status: "skipped",
117944
117971
  orderId: null,
117945
- message: `Copy Trading intent runtime mode is not client: ${intent.runtime_mode}`
117972
+ message: `Copy Trading intent runtime mode is not ${execution.runtimeMode}: ${intent.runtime_mode}`
117946
117973
  };
117947
117974
  }
117948
117975
  let destinationSide = intent.destination_side;
@@ -117986,7 +118013,7 @@ var init_copy_trading_execution = __esm({
117986
118013
  };
117987
118014
  }
117988
118015
  try {
117989
- let sizePrecision = await quantizeHyperliquidOrderSize({
118016
+ let sizePrecision = await execution.sizePrecision({
117990
118017
  publicRequestPriority: reduceOnly ? "trading_reduce" : "trading_execute",
117991
118018
  symbol: intent.symbol,
117992
118019
  size: destinationSize,
@@ -118055,7 +118082,7 @@ var init_copy_trading_execution = __esm({
118055
118082
  destinationSide = liveDelta > 0 ? "buy" : "sell";
118056
118083
  destinationSize = Math.abs(liveDelta);
118057
118084
  exactFullCloseBeforeQuantization = Math.abs(desiredPosition) <= tolerance && Math.abs(actualPosition) > tolerance;
118058
- reduceOnly = Math.abs(desiredPosition) <= tolerance || (actualPosition > 0 && liveDelta < 0 && desiredPosition >= 0 || actualPosition < 0 && liveDelta > 0 && desiredPosition <= 0);
118085
+ reduceOnly = copyOrderReduceOnly({ desiredPosition, actualPosition, size: destinationSize });
118059
118086
  maxOrderNotional = copyOrderNotionalCap(
118060
118087
  followerOrderNotionalCap,
118061
118088
  platformOrderNotionalCap,
@@ -118160,8 +118187,8 @@ var init_copy_trading_execution = __esm({
118160
118187
  }
118161
118188
  };
118162
118189
  }
118163
- if (desiredPosition != null && Math.abs(desiredPosition) <= COPY_TRADING_SIZE_EPSILON) {
118164
- reduceOnly = true;
118190
+ if (desiredPosition != null && Number.isFinite(desiredPosition) && actualPosition != null && Number.isFinite(actualPosition)) {
118191
+ reduceOnly = copyOrderReduceOnly({ desiredPosition, actualPosition, size: destinationSize });
118165
118192
  }
118166
118193
  const stableIdentity = _stableMutationIdentity(
118167
118194
  intent.sanitized_metadata?.client_mutation_id,
@@ -118175,7 +118202,7 @@ var init_copy_trading_execution = __esm({
118175
118202
  actual_destination_position: actualPosition
118176
118203
  } : {}
118177
118204
  };
118178
- const response = await executeClientMarketOrder({
118205
+ const response = await execution.marketOrder({
118179
118206
  profileId: String(input.profileId),
118180
118207
  runtimeSessionId: input.runtimeSessionId,
118181
118208
  runtimeLeaseToken: input.runtimeLeaseToken,
@@ -118250,16 +118277,17 @@ var init_copy_trading_execution = __esm({
118250
118277
  const cloid = String(destinationOrderId || "").trim().toLowerCase();
118251
118278
  return /^0x[0-9a-f]{32}$/.test(cloid) ? cloid : null;
118252
118279
  };
118253
- executeClientCopyTradingOrderAction = async (input) => {
118280
+ executeClientCopyTradingOrderAction = (input) => executeCopyTradingOrderAction(input, CLIENT_COPY_TRADING_EXECUTION);
118281
+ executeCopyTradingOrderAction = async (input, execution) => {
118254
118282
  throwIfAborted2(input.signal);
118255
118283
  const action = input.action;
118256
- if (action.status !== "pending_client") {
118284
+ if (action.status !== execution.pendingStatus) {
118257
118285
  return {
118258
118286
  status: "skipped",
118259
118287
  destinationOrderId: null,
118260
118288
  destinationOrderState: null,
118261
118289
  orderMemberResults: null,
118262
- message: `Copy Trading order action is not pending_client: ${action.status}`
118290
+ message: `Copy Trading order action is not ${execution.pendingStatus}: ${action.status}`
118263
118291
  };
118264
118292
  }
118265
118293
  const stableIdentity = _stableMutationIdentity(
@@ -118282,7 +118310,7 @@ var init_copy_trading_execution = __esm({
118282
118310
  };
118283
118311
  const cancelledOrderStatusEvidence = async (orderId) => {
118284
118312
  if (orderId == null) return {};
118285
- const evidence = await readCopyOrderStatusEvidence(
118313
+ const evidence = await execution.orderStatusEvidence(
118286
118314
  { config: input.config ?? null, signal: input.signal, walletAddress: input.walletAddress },
118287
118315
  orderId
118288
118316
  );
@@ -118294,7 +118322,7 @@ var init_copy_trading_execution = __esm({
118294
118322
  if (orderId == null) {
118295
118323
  throw new RuntimeReasonError("Copy Trading cancel action is missing a valid destination order id.", "internal_data_error");
118296
118324
  }
118297
- await executeClientCancelOrder({
118325
+ await execution.cancelOrder({
118298
118326
  ...common,
118299
118327
  orderId
118300
118328
  });
@@ -118314,7 +118342,7 @@ var init_copy_trading_execution = __esm({
118314
118342
  }
118315
118343
  let response;
118316
118344
  if (action.action_type === "create" && Array.isArray(action.order_members) && action.order_members.length > 1) {
118317
- response = await executeClientOrderBatch({
118345
+ response = await execution.orderBatch({
118318
118346
  ...common,
118319
118347
  members: action.order_members.map((member) => ({
118320
118348
  side: member.side,
@@ -118336,7 +118364,7 @@ var init_copy_trading_execution = __esm({
118336
118364
  if (typeof previousOrderId === "number" && previousOrderId <= 0 || typeof previousOrderId === "string" && !/^0x[0-9a-f]{32}$/.test(previousOrderId)) {
118337
118365
  throw new RuntimeReasonError("Copy Trading modify action is missing a valid previous destination order id.", "internal_data_error");
118338
118366
  }
118339
- response = await executeClientModifyOrder({
118367
+ response = await execution.modifyOrder({
118340
118368
  ...common,
118341
118369
  orderId: previousOrderId,
118342
118370
  side: action.side,
@@ -118350,7 +118378,7 @@ var init_copy_trading_execution = __esm({
118350
118378
  triggerIsMarket: action.trigger_is_market ?? void 0
118351
118379
  });
118352
118380
  } else if (action.order_kind === "trigger") {
118353
- response = await executeClientTriggerOrder({
118381
+ response = await execution.triggerOrder({
118354
118382
  ...common,
118355
118383
  side: action.side,
118356
118384
  size,
@@ -118361,7 +118389,7 @@ var init_copy_trading_execution = __esm({
118361
118389
  triggerIsMarket: action.trigger_is_market ?? void 0
118362
118390
  });
118363
118391
  } else {
118364
- response = await executeClientLimitOrder({
118392
+ response = await execution.limitOrder({
118365
118393
  ...common,
118366
118394
  side: action.side,
118367
118395
  size,
@@ -118414,6 +118442,28 @@ var init_copy_trading_execution = __esm({
118414
118442
  }
118415
118443
  });
118416
118444
 
118445
+ // lib/runtime/agent-instruction-carry.ts
118446
+ var carryAgentInstruction, carriedAgentInstruction;
118447
+ var init_agent_instruction_carry = __esm({
118448
+ "lib/runtime/agent-instruction-carry.ts"() {
118449
+ "use strict";
118450
+ init_define_VTX_CLAUDE_CODE_POLICY();
118451
+ init_define_VTX_EXO_POLICY();
118452
+ init_define_VTX_GROK_POLICY();
118453
+ init_define_VTX_PI_MODEL_POLICY();
118454
+ carryAgentInstruction = (error48, binding) => {
118455
+ if (!binding || !error48 || typeof error48 !== "object" && typeof error48 !== "function") return error48;
118456
+ error48.runtimeExternalAgentInstruction = binding;
118457
+ return error48;
118458
+ };
118459
+ carriedAgentInstruction = (error48) => {
118460
+ if (!error48 || typeof error48 !== "object" && typeof error48 !== "function") return null;
118461
+ const binding = error48.runtimeExternalAgentInstruction;
118462
+ return binding && typeof binding === "object" ? binding : null;
118463
+ };
118464
+ }
118465
+ });
118466
+
118417
118467
  // lib/trade-history-order-id.ts
118418
118468
  var INTEGER_ID_PATTERN, toSafeIntegerAlias, addOrderIdLookupKey, collectOrderIdLookupKeys;
118419
118469
  var init_trade_history_order_id = __esm({
@@ -119033,7 +119083,7 @@ var init_portfolio_evidence = __esm({
119033
119083
  });
119034
119084
 
119035
119085
  // lib/runtime/host-wake-schedule.ts
119036
- var marker, markBatchableTimer, markDeferrableTimer;
119086
+ var marker, markBatchableTimer, markDeferrableTimer, longRequests, startLongRequest;
119037
119087
  var init_host_wake_schedule = __esm({
119038
119088
  "lib/runtime/host-wake-schedule.ts"() {
119039
119089
  "use strict";
@@ -119050,6 +119100,15 @@ var init_host_wake_schedule = __esm({
119050
119100
  marker?.(handle, "deferrable", options);
119051
119101
  return handle;
119052
119102
  };
119103
+ longRequests = 0;
119104
+ startLongRequest = (run) => {
119105
+ longRequests += 1;
119106
+ try {
119107
+ return run();
119108
+ } finally {
119109
+ longRequests -= 1;
119110
+ }
119111
+ };
119053
119112
  }
119054
119113
  });
119055
119114
 
@@ -122308,6 +122367,7 @@ var init_provider_client = __esm({
122308
122367
  init_provider_observability();
122309
122368
  init_api2();
122310
122369
  init_network_debug();
122370
+ init_host_wake_schedule();
122311
122371
  init_abort();
122312
122372
  init_runtime_redaction();
122313
122373
  init_error_surface_contract();
@@ -122939,7 +122999,7 @@ var init_provider_client = __esm({
122939
122999
  providerResponseSignals = /* @__PURE__ */ new WeakMap();
122940
123000
  fetchProvider = async (url2, init2) => {
122941
123001
  if (init2.signal?.aborted) throw init2.signal.reason ?? new DOMException("Cancelled", "AbortError");
122942
- const response = await awaitProviderOperation(fetch(url2, init2), init2.signal);
123002
+ const response = await awaitProviderOperation(startLongRequest(() => fetch(url2, init2)), init2.signal);
122943
123003
  if (init2.signal) providerResponseSignals.set(response, init2.signal);
122944
123004
  return response;
122945
123005
  };
@@ -123572,12 +123632,12 @@ var init_provider_client = __esm({
123572
123632
  response = null;
123573
123633
  const marker2 = beginProviderDispatch(body);
123574
123634
  dispatchMarker = marker2;
123575
- const dispatched = useRelay ? await relayNativeProviderRequest(provider, String(apiKey || "").trim(), body, {
123635
+ const dispatched = useRelay ? await startLongRequest(() => relayNativeProviderRequest(provider, String(apiKey || "").trim(), body, {
123576
123636
  profileId: profileId == null ? void 0 : Number(profileId),
123577
123637
  signal,
123578
123638
  planId: relayPlan?.id,
123579
123639
  traceId: trace.id
123580
- }) : await fetchProvider(dispatchUrl, {
123640
+ })) : await fetchProvider(dispatchUrl, {
123581
123641
  method: "POST",
123582
123642
  headers: requestHeaders,
123583
123643
  body: JSON.stringify(body),
@@ -124360,11 +124420,11 @@ var init_provider_client = __esm({
124360
124420
  if (new TextEncoder().encode(JSON.stringify(payload)).byteLength > egress.budget.policy.max_request_bytes) throw new Error("Google egress request exceeds configured limit.");
124361
124421
  egress.budget.attempts += 1;
124362
124422
  if (egress.route === "node") {
124363
- const relayed = await awaitProviderOperation(relayGoogleEgressRequest(model, apiKey, payload, {
124423
+ const relayed = await awaitProviderOperation(startLongRequest(() => relayGoogleEgressRequest(model, apiKey, payload, {
124364
124424
  profileId: egress.profileId,
124365
124425
  signal,
124366
124426
  timeoutSeconds: egress.timeoutSeconds
124367
- }), signal);
124427
+ })), signal);
124368
124428
  if (signal) providerResponseSignals.set(relayed, signal);
124369
124429
  return relayed;
124370
124430
  }
@@ -126811,7 +126871,7 @@ __export(local_analysis_exports, {
126811
126871
  runLocalRuntimeCycle: () => runLocalRuntimeCycle,
126812
126872
  summarizeReviewFailureExplanation: () => summarizeReviewFailureExplanation
126813
126873
  });
126814
- var cycleCandles, CYCLE_TIMEOUT_FLOOR_MS, DECISION_SETTLEMENT_RESERVE_MAX_BUDGET_DIVISOR, MIN_AGENT_INSTRUCTION_RETRY_AFTER_MS, PROMPT_PARITY_ERROR_DETAIL_MAX_CHARS, EXTERNAL_INFERENCE_RUNTIME_POLL_INTERVAL_MS, EXTERNAL_INFERENCE_RESULT_WAIT_MS, TRUNCATION_ELLIPSIS2, assertPromptModelController, resolveRuntimeReasoningControlsForModel, observeRuntimeCycle, observeAccountState, aiOrderSlippageFraction, buildServerBehaviorStateArtifacts, serverBehaviorStateArtifacts, ClientRuntimeAgentInstructionEmpty, isClientRuntimeAgentInstructionEmpty, ClientRuntimeAiSchedulePaused, ClientRuntimeAiScheduleStillActive, isClientRuntimeAiScheduleStillActive, ServerDispatchAccountStateStale, isServerDispatchAccountStateStale, isClientRuntimeAiSchedulePaused, acceptancePositionCaps, accountSnapshotCapturedAt, buildClaimedAgentRuntimeCycleResult, resolveRuntimeMarginModePreference, resolveRuntimeLeveragePreference, resolveBooleanSetting, CLIENT_RUNTIME_LIVE_CONTEXT_UNAVAILABLE_ERRORS, BEHAVIOR_STATE_UNAVAILABLE_ERROR, CriticalBehaviorStateError, BEHAVIOR_MEMORY_UNAVAILABLE_ERROR, BehaviorMemoryUnavailableError, clampNumber, resolveExternalInferenceRuntimeTimeoutSeconds, toPositiveFinite3, compactSnippet, hashRuntimeDebugText, EFFECTIVE_INPUT_MANIFEST_SCHEMA_VERSION, PROMPT_ASSEMBLY_DEFINITION_VERSION, RUNTIME_SOURCE_DEFINITION_VERSION, DECISION_INPUT_DEFINITION_VERSION, CONTEXT_ENVELOPE_DEFINITION_VERSION, CLIENT_RUNTIME_SOURCE_VERSION, CLIENT_MAIN_PROMPT_RENDERER, CLIENT_REVIEW_PROMPT_RENDERER, resolveEffectivePromptRuntimeProvenance, canonicalManifestValue, canonicalManifestJson, sha256ManifestHex, effectiveInputComponent, buildEffectiveInputManifest, MANIFEST_COMPONENT_NAME, derivePromptVisibleSections, decodeDecisionTracePayload, extractDecisionSymbolTrace, formatDecisionSymbolTrace, formatActionableDecisionSymbols, decisionRecordsBySymbol, normalizePromptSymbols, JSON_MODEL_OUTPUT_FENCE_PATTERN, currentModelOutputJsonText, STRICT_MODEL_OUTPUT_KEYS, currentModelOutputValidationErrors, currentModelOutputMatchesContract, projectCurrentModelDecisionContent, modelOutputValidationError, SERVER_UNREADABLE_REPLY_HOLD_REASONING, buildMissingDecisionHold, buildDecisionPlansFromResponse, buildReviewCandidatePlansFromResponse, forceUnavailableSymbolsToHold, extractTemplatePlaceholders, requireReviewPrimaryUserPromptTemplate, containsCompetingBehaviorStateMarkup, containsCompetingMainBehaviorStateMarkup, requireStrategyReviewTemplates, preflightStrategyReviewPromptContract, extractRuntimeReasoningSelection, isAbortError, isRuntimeTimeoutAbortReason, summarizeReviewFailureExplanation, buildReviewFailureHoldReason, createAbortError2, settleRuntimeCyclePromise, unwrapRuntimeCycleSettledResult, normalizeDecisionLabel, normalizeRuntimeSymbol, PromptContractFetchError, isLivePromptContextUnavailableError, buildFailClosedHoldResult, buildPromptConstructionFailureResult, buildLivePromptContextUnavailableFailureResult, pickFirstString, normalizeRuntimeStringList, requirePositiveRuntimeLimit, resolveRuntimeTradingScope, normalizeRuntimeProviderAlias, resolveCatalogModelEntry, createClientRuntimeProviderSetupError, createProviderSetupRejectionError, evaluateModelEligibility, extractReviewRuntimeReasoningSelection, isUsableRuntimeSettingsFallback, resolveRuntimeSettings, formatRuntimeDurationMs, normalizeRuntimeTimingNote, appendRuntimeTimingEvent, reportPromptParityTelemetry, resolveLocalRuntimeSecretRequirements, resolveLocalRuntimeSecretProvider, AI_INDICATOR_KEYS_NEWER_THAN_SOME_SERVERS, sortTradingTimeframes, normalizePromptIdentityTimestamp, resolveCompletedCandleBoundary, normalizeAiIndicatorFlags, getPromptLookback, resolvePromptRelativeVolumeContext, promptRelativeVolumeBaseline, CANDLE_CLOSE_TICKER_TIMEFRAME, candleCloseTicker, promptMarketAsOfTimestamp, deviceMarketReads, buildPromptCandlesPayload, formatUtcTimestampWithWeekday, formatUtcNowWithWeekday, formatPromptPrice, capacityUnitSize, buildPromptAccountStatusValue, buildPromptPositionsValue, sanitizePromptSymbol, fillTimeMs, fillSize, normalizeFillSide, normalizeFillOrderId, normalizeFillRiskOrderIdentity, fillStartPosition, fillSortValue, sortFillsAscending, sortFillsDescending, inferEntryFromStartPositionChain, inferEntryFromCurrentPositionSize, calculateCurrentPositionState, calculatePositionEntryTimes, countPositionAdds, latestPositionRiskIncreaseTimeMs, latestPositionRiskIncreaseEvidence, compactPromptRiskIncrease, roundPositiveDecimalHalfUp, compactPromptLastTrade, ENTRY_TRADE_FIELDS, PREVIOUS_DECISION_FIELDS, PREVIOUS_CAMPAIGN_FIELDS, hasExactKeys2, isNonnegativeInteger, isFiniteNumber, isExactEnumString, isNonemptyPromptText, isCampaignReasoningText, projectBackendDecisionMemoryItem, requireRenderedStrategyBehaviorState, canonicalFillSideForRiskEvidence, isValidRiskEvidenceFill, isValidCampaignBoundaryFill, normalizeFillHistoryCoverage, resolveFillHistoryCoverageForSymbol, buildPromptBehaviorStateArtifacts, buildReviewSystemPrompt, formatReviewUserPrompt, assemblePromptContextVars, buildPromptBehaviorStateValue, buildLocalRuntimePromptArtifacts, createRuntimeId2, asRecord, buildRuntimeConstraintRejectionMessage, hasDeviceProviderSecret, requireNonEmptyStringField, requirePositiveIntegerField, compareContractVersion, parsePromptContractTimestamp, assertPromptContractCompatibility, assertPromptContractTemporalBounds, sleepWithAbort, requireAgentPollRetryAfterMs, materializeClaimedClientRuntimeAgentInstruction, attachClientRuntimeErrorProvenance, isExternalRuntimeProviderResult, invokeClientExternalInference, assertPromptContractBindingTupleEqual, assertPromptContractScopeMatch, fetchBoundPromptContracts, carryReturnedModelCalls, runLocalRuntimeCycle;
126874
+ var cycleCandles, CYCLE_TIMEOUT_FLOOR_MS, DECISION_SETTLEMENT_RESERVE_MAX_BUDGET_DIVISOR, MIN_AGENT_INSTRUCTION_RETRY_AFTER_MS, PROMPT_PARITY_ERROR_DETAIL_MAX_CHARS, EXTERNAL_INFERENCE_RUNTIME_POLL_INTERVAL_MS, EXTERNAL_INFERENCE_RESULT_WAIT_MS, TRUNCATION_ELLIPSIS2, assertPromptModelController, resolveRuntimeReasoningControlsForModel, observeRuntimeCycle, observeAccountState, aiOrderSlippageFraction, buildServerBehaviorStateArtifacts, serverBehaviorStateArtifacts, ClientRuntimeAgentInstructionEmpty, isClientRuntimeAgentInstructionEmpty, ClientRuntimeAiSchedulePaused, ClientRuntimeAiScheduleStillActive, isClientRuntimeAiScheduleStillActive, ServerDispatchAccountStateStale, isServerDispatchAccountStateStale, isClientRuntimeAiSchedulePaused, judgesPositionCaps, NO_POSITION_CAPS, POSITION_CAP_REFUSALS, judgeCyclePlans, capacityTrimOf, tradabilityExecutionBlock, accountSnapshotCapturedAt, buildClaimedAgentRuntimeCycleResult, resolveRuntimeMarginModePreference, resolveRuntimeLeveragePreference, resolveBooleanSetting, CLIENT_RUNTIME_LIVE_CONTEXT_UNAVAILABLE_ERRORS, BEHAVIOR_STATE_UNAVAILABLE_ERROR, CriticalBehaviorStateError, BEHAVIOR_MEMORY_UNAVAILABLE_ERROR, BehaviorMemoryUnavailableError, clampNumber, resolveExternalInferenceRuntimeTimeoutSeconds, toPositiveFinite3, compactSnippet, hashRuntimeDebugText, EFFECTIVE_INPUT_MANIFEST_SCHEMA_VERSION, PROMPT_ASSEMBLY_DEFINITION_VERSION, RUNTIME_SOURCE_DEFINITION_VERSION, DECISION_INPUT_DEFINITION_VERSION, CONTEXT_ENVELOPE_DEFINITION_VERSION, CLIENT_RUNTIME_SOURCE_VERSION, CLIENT_MAIN_PROMPT_RENDERER, CLIENT_REVIEW_PROMPT_RENDERER, resolveEffectivePromptRuntimeProvenance, canonicalManifestValue, canonicalManifestJson, sha256ManifestHex, effectiveInputComponent, buildEffectiveInputManifest, MANIFEST_COMPONENT_NAME, derivePromptVisibleSections, decodeDecisionTracePayload, extractDecisionSymbolTrace, formatDecisionSymbolTrace, formatActionableDecisionSymbols, decisionRecordsBySymbol, normalizePromptSymbols, JSON_MODEL_OUTPUT_FENCE_PATTERN, currentModelOutputJsonText, STRICT_MODEL_OUTPUT_KEYS, currentModelOutputValidationErrors, currentModelOutputMatchesContract, projectCurrentModelDecisionContent, modelOutputValidationError, SERVER_UNREADABLE_REPLY_HOLD_REASONING, buildMissingDecisionHold, buildDecisionPlansFromResponse, buildReviewCandidatePlansFromResponse, forceUnavailableSymbolsToHold, extractTemplatePlaceholders, requireReviewPrimaryUserPromptTemplate, containsCompetingBehaviorStateMarkup, containsCompetingMainBehaviorStateMarkup, requireStrategyReviewTemplates, preflightStrategyReviewPromptContract, extractRuntimeReasoningSelection, isAbortError, isRuntimeTimeoutAbortReason, summarizeReviewFailureExplanation, buildReviewFailureHoldReason, createAbortError2, settleRuntimeCyclePromise, unwrapRuntimeCycleSettledResult, normalizeDecisionLabel, normalizeRuntimeSymbol, PromptContractFetchError, isLivePromptContextUnavailableError, buildFailClosedHoldResult, buildPromptConstructionFailureResult, buildLivePromptContextUnavailableFailureResult, pickFirstString, normalizeRuntimeStringList, requirePositiveRuntimeLimit, resolveRuntimeTradingScope, normalizeRuntimeProviderAlias, resolveCatalogModelEntry, createClientRuntimeProviderSetupError, createProviderSetupRejectionError, evaluateModelEligibility, extractReviewRuntimeReasoningSelection, isUsableRuntimeSettingsFallback, resolveRuntimeSettings, formatRuntimeDurationMs, normalizeRuntimeTimingNote, appendRuntimeTimingEvent, reportPromptParityTelemetry, resolveLocalRuntimeSecretRequirements, resolveLocalRuntimeSecretProvider, AI_INDICATOR_KEYS_NEWER_THAN_SOME_SERVERS, sortTradingTimeframes, normalizePromptIdentityTimestamp, resolveCompletedCandleBoundary, normalizeAiIndicatorFlags, getPromptLookback, resolvePromptRelativeVolumeContext, promptRelativeVolumeBaseline, CANDLE_CLOSE_TICKER_TIMEFRAME, candleCloseTicker, promptMarketAsOfTimestamp, deviceMarketReads, buildPromptCandlesPayload, formatUtcTimestampWithWeekday, formatUtcNowWithWeekday, formatPromptPrice, capacityUnitSize, buildPromptAccountStatusValue, buildPromptPositionsValue, sanitizePromptSymbol, fillTimeMs, fillSize, normalizeFillSide, normalizeFillOrderId, normalizeFillRiskOrderIdentity, fillStartPosition, fillSortValue, sortFillsAscending, sortFillsDescending, inferEntryFromStartPositionChain, inferEntryFromCurrentPositionSize, calculateCurrentPositionState, calculatePositionEntryTimes, countPositionAdds, latestPositionRiskIncreaseTimeMs, latestPositionRiskIncreaseEvidence, compactPromptRiskIncrease, roundPositiveDecimalHalfUp, compactPromptLastTrade, ENTRY_TRADE_FIELDS, PREVIOUS_DECISION_FIELDS, PREVIOUS_CAMPAIGN_FIELDS, hasExactKeys2, isNonnegativeInteger, isFiniteNumber, isExactEnumString, isNonemptyPromptText, isCampaignReasoningText, projectBackendDecisionMemoryItem, requireRenderedStrategyBehaviorState, canonicalFillSideForRiskEvidence, isValidRiskEvidenceFill, isValidCampaignBoundaryFill, normalizeFillHistoryCoverage, resolveFillHistoryCoverageForSymbol, buildPromptBehaviorStateArtifacts, buildReviewSystemPrompt, formatReviewUserPrompt, assemblePromptContextVars, buildPromptBehaviorStateValue, buildLocalRuntimePromptArtifacts, createRuntimeId2, asRecord, buildRuntimeConstraintRejectionMessage, hasDeviceProviderSecret, requireNonEmptyStringField, requirePositiveIntegerField, compareContractVersion, parsePromptContractTimestamp, assertPromptContractCompatibility, assertPromptContractTemporalBounds, sleepWithAbort, requireAgentPollRetryAfterMs, materializeClaimedClientRuntimeAgentInstruction, attachClientRuntimeErrorProvenance, isExternalRuntimeProviderResult, invokeClientExternalInference, assertPromptContractBindingTupleEqual, assertPromptContractScopeMatch, fetchBoundPromptContracts, carryReturnedModelCalls, runLocalRuntimeCycle;
126815
126875
  var init_local_analysis = __esm({
126816
126876
  "lib/runtime/local-analysis.ts"() {
126817
126877
  "use strict";
@@ -126822,7 +126882,8 @@ var init_local_analysis = __esm({
126822
126882
  init_provider_status();
126823
126883
  init_provider_credit();
126824
126884
  init_sl_tp_execution_settings();
126825
- init_server_execution_capacity();
126885
+ init_execution_capacity();
126886
+ init_agent_instruction_carry();
126826
126887
  init_runtime_error_reason_rules();
126827
126888
  init_retired_model_source();
126828
126889
  init_byokProviderRegistry();
@@ -126994,7 +127055,77 @@ var init_local_analysis = __esm({
126994
127055
  };
126995
127056
  isServerDispatchAccountStateStale = (value) => value instanceof Error && value.name === "ServerDispatchAccountStateStale";
126996
127057
  isClientRuntimeAiSchedulePaused = (value) => value instanceof ClientRuntimeAiSchedulePaused;
126997
- acceptancePositionCaps = (executionMode, caps) => executionMode === "server" ? { remaining_global_units: null, remaining_exchange_units: null, remaining_asset_units: null } : caps;
127058
+ judgesPositionCaps = (executionMode, mode) => executionMode !== "server" && mode !== "assistant";
127059
+ NO_POSITION_CAPS = { remaining_global_units: null, remaining_exchange_units: null, remaining_asset_units: null };
127060
+ POSITION_CAP_REFUSALS = /* @__PURE__ */ new Set(["global_capacity_reached", "exchange_capacity_reached", "asset_capacity_reached", "capacity_reached"]);
127061
+ judgeCyclePlans = (input) => {
127062
+ let remainingAllowance = input.allowance;
127063
+ const orderCount = input.plans.filter((plan) => (plan.decision === "BUY" || plan.decision === "SELL") && Math.trunc(Number(plan.units)) > 0).length;
127064
+ const judgements = new Array(input.plans.length);
127065
+ const judgingOrder = input.reductionsFirst ? reductionFirstOrder(input.plans.map((plan) => ({
127066
+ decision: plan.decision,
127067
+ units: plan.units,
127068
+ signedUnits: input.room.signedUnits(plan.symbol)
127069
+ }))) : input.plans.map((_, slot) => slot);
127070
+ for (const slot of judgingOrder) {
127071
+ const plan = input.plans[slot];
127072
+ const signedUnits = input.room.signedUnits(plan.symbol);
127073
+ const allowanceUnits = Math.min(Math.max(0, Math.trunc(Number(plan.units) || 0)), remainingAllowance);
127074
+ const acceptance = evaluateRuntimeDecisionAcceptance({
127075
+ decision: plan.decision,
127076
+ units: plan.units,
127077
+ constraints: {
127078
+ ...input.constraints,
127079
+ max_trades_per_prompt: remainingAllowance,
127080
+ ...input.positionCaps ? input.room.caps(plan.symbol) : NO_POSITION_CAPS,
127081
+ current_symbol_signed_units: signedUnits
127082
+ }
127083
+ });
127084
+ if (!acceptance.accepted) {
127085
+ const capRefused = POSITION_CAP_REFUSALS.has(String(acceptance.reason_code)) && orderCount > 1;
127086
+ const allowanceRefused = acceptance.reason_code === "max_per_prompt_zero" && input.plans.length > 1 && remainingAllowance < input.allowance;
127087
+ if (!capRefused && !allowanceRefused) return { judgements, refused: { reasonCode: acceptance.reason_code } };
127088
+ judgements[slot] = { kind: "unsent", reasonCode: acceptance.reason_code || "capacity_reached" };
127089
+ input.onJudged?.(slot, judgements[slot], remainingAllowance);
127090
+ continue;
127091
+ }
127092
+ const classified = classifyExecutionIntent(acceptance.decision, acceptance.normalized_units, signedUnits);
127093
+ const minimum = classified.intent === "open" && input.tradability.openEnabled ? input.tradability.openMinimum : classified.intent === "add" && input.tradability.increaseEnabled ? input.tradability.increaseMinimum : null;
127094
+ if (input.tradability.enabled && minimum !== null && (plan.tradability == null || plan.tradability < minimum)) {
127095
+ judgements[slot] = {
127096
+ kind: "blocked",
127097
+ decision: acceptance.decision,
127098
+ units: acceptance.normalized_units,
127099
+ intent: classified.intent === "open" ? "open" : "add",
127100
+ minimum
127101
+ };
127102
+ input.onJudged?.(slot, judgements[slot], remainingAllowance);
127103
+ continue;
127104
+ }
127105
+ if (classified.side !== null) {
127106
+ remainingAllowance = Math.max(0, remainingAllowance - acceptance.normalized_units);
127107
+ input.room.take(plan.symbol, acceptance.decision, acceptance.normalized_units);
127108
+ }
127109
+ judgements[slot] = {
127110
+ kind: "accepted",
127111
+ decision: acceptance.decision,
127112
+ units: acceptance.normalized_units,
127113
+ signedUnits,
127114
+ ...input.positionCaps && classified.side !== null && acceptance.normalized_units < allowanceUnits ? { trimmedFrom: allowanceUnits } : {}
127115
+ };
127116
+ input.onJudged?.(slot, judgements[slot], remainingAllowance);
127117
+ }
127118
+ return { judgements, refused: null };
127119
+ };
127120
+ capacityTrimOf = (judgement) => judgement.kind === "accepted" && judgement.trimmedFrom !== void 0 ? { capacityTrim: { requestedUnits: judgement.trimmedFrom, constraintReasonCode: "units_capped" } } : {};
127121
+ tradabilityExecutionBlock = (tradability, intent, minimum) => ({
127122
+ reasonCode: "tradability_below_minimum",
127123
+ control: "tradability",
127124
+ intent,
127125
+ tradability: tradability ?? null,
127126
+ minimum,
127127
+ message: `Tradability ${tradability == null ? "missing" : String(tradability)} is below the ${intent === "open" ? "Open" : "Add"} minimum of ${minimum}. No order was placed.`
127128
+ });
126998
127129
  accountSnapshotCapturedAt = (executionMode, accountStateFetchedAtMs) => new Date(
126999
127130
  (executionMode === "server" ? accountStateFetchedAtMs : null) ?? Date.now()
127000
127131
  ).toISOString();
@@ -127087,10 +127218,7 @@ var init_local_analysis = __esm({
127087
127218
  if (!position) return 0;
127088
127219
  return signedUnitsFromEntryPosition(position.size, position.entry_price, tradeSize);
127089
127220
  };
127090
- const globalUnitsUsed = Array.from(positionBySymbol.keys()).reduce(
127091
- (total, positionSymbol) => total + Math.abs(signedUnitsForSymbol(positionSymbol)),
127092
- 0
127093
- );
127221
+ for (const positionSymbol of positionBySymbol.keys()) signedUnitsForSymbol(positionSymbol);
127094
127222
  const maxTradesPerPrompt = Math.max(0, Math.trunc(clampNumber(
127095
127223
  settings.max_trades_per_prompt,
127096
127224
  config2.default_max_trades_per_prompt
@@ -127107,13 +127235,13 @@ var init_local_analysis = __esm({
127107
127235
  settings.max_trades_per_exchange,
127108
127236
  maxTradesGlobal
127109
127237
  )));
127110
- const exchangeUnitsUsed = /* @__PURE__ */ new Map();
127111
- for (const positionSymbol of positionBySymbol.keys()) {
127112
- const venue = getHyperliquidMarketDex(positionSymbol);
127113
- exchangeUnitsUsed.set(venue, (exchangeUnitsUsed.get(venue) ?? 0) + Math.abs(signedUnitsForSymbol(positionSymbol)));
127114
- }
127115
- let remainingPromptUnits = maxTradesPerPrompt;
127116
- let remainingGlobalUnits = Math.max(0, maxTradesGlobal - globalUnitsUsed);
127238
+ const capacityRoom = openCapacityRoom(accountState.positions, {
127239
+ unit_size: tradeSize,
127240
+ capacity_unit_size: tradeSize,
127241
+ max_trades_global: maxTradesGlobal,
127242
+ max_trades_per_exchange: maxTradesPerExchange,
127243
+ max_trades_per_asset: maxTradesPerAsset
127244
+ });
127117
127245
  const marginMode = resolveRuntimeMarginModePreference(settings, config2);
127118
127246
  const buildExecutionContext = (planSymbol) => {
127119
127247
  const price = priceForSymbol(planSymbol);
@@ -127168,81 +127296,63 @@ var init_local_analysis = __esm({
127168
127296
  Math.round(clampNumber(settings.tradability_increase_minimum, config2.default_tradability_increase_minimum))
127169
127297
  )
127170
127298
  );
127171
- const executionPlans = decisionPlans.map((entry) => {
127172
- const currentSignedUnits = signedUnitsForSymbol(entry.symbol);
127173
- const intent = classifyExecutionIntent(entry.decision, entry.units, currentSignedUnits).intent;
127174
- const applicableTradabilityMinimum = intent === "open" && tradabilityOpenEnabled ? tradabilityOpenMinimum : intent === "add" && tradabilityIncreaseEnabled ? tradabilityIncreaseMinimum : null;
127299
+ const { judgements, refused } = judgeCyclePlans({
127300
+ plans: decisionPlans,
127301
+ room: capacityRoom,
127302
+ positionCaps: judgesPositionCaps(runtimeInput.executionMode, runtimeInput.mode),
127303
+ // The Agent's own order, its instruction's market first: the Agent
127304
+ // ranked its plans, and its market's order is the one the decision
127305
+ // records (the user's choice over judging reductions first here).
127306
+ reductionsFirst: false,
127307
+ allowance: maxTradesPerPrompt,
127308
+ constraints: {
127309
+ runtime_disabled: settings.main_model_enabled === false,
127310
+ kill_switch_active: false,
127311
+ max_trades_per_prompt: maxTradesPerPrompt,
127312
+ remaining_global_units: null,
127313
+ remaining_asset_units: null,
127314
+ model_allowed: true,
127315
+ provider_allowed: true
127316
+ },
127317
+ tradability: {
127318
+ enabled: tradabilityEnabled,
127319
+ openEnabled: tradabilityOpenEnabled,
127320
+ increaseEnabled: tradabilityIncreaseEnabled,
127321
+ openMinimum: tradabilityOpenMinimum,
127322
+ increaseMinimum: tradabilityIncreaseMinimum
127323
+ }
127324
+ });
127325
+ if (refused) {
127326
+ throw new Error(buildRuntimeConstraintRejectionMessage({
127327
+ reasonCode: refused.reasonCode,
127328
+ constraintsRecord: {},
127329
+ model: instruction.model,
127330
+ provider: "external_agent"
127331
+ }));
127332
+ }
127333
+ const executionPlans = decisionPlans.map((entry, slot) => {
127175
127334
  const executionContext = buildExecutionContext(entry.symbol);
127176
- if (tradabilityEnabled && applicableTradabilityMinimum !== null && (entry.tradability === null || entry.tradability < applicableTradabilityMinimum)) {
127177
- const blockIntent = intent === "open" ? "open" : "add";
127335
+ const judgement = judgements[slot];
127336
+ if (judgement.kind === "blocked") {
127178
127337
  return {
127179
127338
  ...entry,
127339
+ decision: judgement.decision,
127340
+ units: judgement.units,
127180
127341
  executionContext,
127181
- executionBlock: {
127182
- reasonCode: "tradability_below_minimum",
127183
- control: "tradability",
127184
- intent: blockIntent,
127185
- tradability: entry.tradability,
127186
- minimum: applicableTradabilityMinimum,
127187
- message: `Tradability ${entry.tradability ?? "missing"} is below the ${blockIntent === "open" ? "Open" : "Add"} minimum of ${applicableTradabilityMinimum}. No order was placed.`
127188
- }
127342
+ executionBlock: tradabilityExecutionBlock(entry.tradability, judgement.intent, judgement.minimum)
127189
127343
  };
127190
127344
  }
127191
- const remainingAssetUnits = Math.max(0, maxTradesPerAsset - Math.abs(currentSignedUnits));
127192
- const accepted = evaluateRuntimeDecisionAcceptance({
127193
- decision: entry.decision,
127194
- units: entry.units,
127195
- constraints: {
127196
- runtime_disabled: settings.main_model_enabled === false,
127197
- kill_switch_active: false,
127198
- max_trades_per_prompt: remainingPromptUnits,
127199
- ...acceptancePositionCaps(runtimeInput.executionMode, {
127200
- remaining_exchange_units: Math.max(0, maxTradesPerExchange - (exchangeUnitsUsed.get(getHyperliquidMarketDex(entry.symbol)) ?? 0)),
127201
- remaining_global_units: remainingGlobalUnits,
127202
- remaining_asset_units: remainingAssetUnits
127203
- }),
127204
- current_symbol_signed_units: currentSignedUnits,
127205
- model_allowed: true,
127206
- provider_allowed: true
127207
- }
127208
- });
127209
- if (!accepted.accepted) {
127210
- if (decisionPlans.length > 1 && remainingPromptUnits < maxTradesPerPrompt && (accepted.reason_code === "exchange_capacity_reached" || accepted.reason_code === "global_capacity_reached" || accepted.reason_code === "asset_capacity_reached" || accepted.reason_code === "capacity_reached" || accepted.reason_code === "max_per_prompt_zero")) {
127211
- return {
127212
- ...entry,
127213
- decision: "HOLD",
127214
- units: 0,
127215
- reasoning: `Skipped by client runtime constraints: ${accepted.reason_code}`,
127216
- executionContext,
127217
- ...entry.decision === "BUY" || entry.decision === "SELL" ? { unsentOrder: { decision: entry.decision, units: entry.units, constraintReasonCode: accepted.reason_code } } : {}
127218
- };
127219
- }
127220
- throw new Error(buildRuntimeConstraintRejectionMessage({
127221
- reasonCode: accepted.reason_code,
127222
- constraintsRecord: {},
127223
- model: instruction.model,
127224
- provider: "external_agent"
127225
- }));
127345
+ if (judgement.kind === "unsent") {
127346
+ return {
127347
+ ...entry,
127348
+ decision: "HOLD",
127349
+ units: 0,
127350
+ reasoning: `Skipped by client runtime constraints: ${judgement.reasonCode}`,
127351
+ executionContext,
127352
+ ...entry.decision === "BUY" || entry.decision === "SELL" ? { unsentOrder: { decision: entry.decision, units: entry.units, constraintReasonCode: judgement.reasonCode } } : {}
127353
+ };
127226
127354
  }
127227
- const classified = classifyExecutionIntent(
127228
- accepted.decision,
127229
- accepted.normalized_units,
127230
- currentSignedUnits
127231
- );
127232
- const exposureIncrease = Math.max(
127233
- 0,
127234
- Math.abs(classified.targetSignedUnits) - Math.abs(currentSignedUnits)
127235
- );
127236
- remainingPromptUnits = Math.max(0, remainingPromptUnits - accepted.normalized_units);
127237
- remainingGlobalUnits = Math.max(0, remainingGlobalUnits - exposureIncrease);
127238
- const venue = getHyperliquidMarketDex(entry.symbol);
127239
- exchangeUnitsUsed.set(venue, (exchangeUnitsUsed.get(venue) ?? 0) + exposureIncrease);
127240
- return {
127241
- ...entry,
127242
- decision: accepted.decision,
127243
- units: accepted.normalized_units,
127244
- executionContext
127245
- };
127355
+ return { ...entry, decision: judgement.decision, units: judgement.units, executionContext, ...capacityTrimOf(judgement) };
127246
127356
  });
127247
127357
  const selected = executionPlans.find(
127248
127358
  (entry) => normalizeRuntimeSymbol(entry.symbol) === normalizeRuntimeSymbol(symbol2)
@@ -127428,9 +127538,9 @@ var init_local_analysis = __esm({
127428
127538
  RUNTIME_SOURCE_DEFINITION_VERSION = "runtime-source-v1";
127429
127539
  DECISION_INPUT_DEFINITION_VERSION = "decision-input-v1";
127430
127540
  CONTEXT_ENVELOPE_DEFINITION_VERSION = "context-envelope-v2.1";
127431
- CLIENT_RUNTIME_SOURCE_VERSION = typeof process !== "undefined" && true && "6284a7b4880c39e52d48be2d18084f99f2d8b46f".trim() && !["unknown", "unstamped", "development"].includes(
127432
- "6284a7b4880c39e52d48be2d18084f99f2d8b46f".trim().toLowerCase()
127433
- ) ? "6284a7b4880c39e52d48be2d18084f99f2d8b46f".trim() : null;
127541
+ CLIENT_RUNTIME_SOURCE_VERSION = typeof process !== "undefined" && true && "05e1243254ebccb6045684218396b0d4cd9f6495".trim() && !["unknown", "unstamped", "development"].includes(
127542
+ "05e1243254ebccb6045684218396b0d4cd9f6495".trim().toLowerCase()
127543
+ ) ? "05e1243254ebccb6045684218396b0d4cd9f6495".trim() : null;
127434
127544
  CLIENT_MAIN_PROMPT_RENDERER = "client_runtime.buildLocalRuntimePromptArtifacts:v1";
127435
127545
  CLIENT_REVIEW_PROMPT_RENDERER = "client_runtime.review_prompt_assembly:v1";
127436
127546
  resolveEffectivePromptRuntimeProvenance = (input) => ({
@@ -130579,18 +130689,22 @@ ${stringifyPromptJson(parts.candlesPayload)}
130579
130689
  }
130580
130690
  input.onCycleWorkStarted?.();
130581
130691
  if (claimedAgentInstruction) {
130582
- return attachDecisionSettlementDeadline(await buildClaimedAgentRuntimeCycleResult({
130583
- runtimeInput: input,
130584
- config: config2,
130585
- settings,
130586
- settingsFallbackUsed,
130587
- instruction: claimedAgentInstruction,
130588
- cycleId,
130589
- decisionSnapshotId,
130590
- decisionSnapshotCapturedAt,
130591
- signal: timeoutController.signal,
130592
- cycleStartedAtMs
130593
- }));
130692
+ try {
130693
+ return attachDecisionSettlementDeadline(await buildClaimedAgentRuntimeCycleResult({
130694
+ runtimeInput: input,
130695
+ config: config2,
130696
+ settings,
130697
+ settingsFallbackUsed,
130698
+ instruction: claimedAgentInstruction,
130699
+ cycleId,
130700
+ decisionSnapshotId,
130701
+ decisionSnapshotCapturedAt,
130702
+ signal: timeoutController.signal,
130703
+ cycleStartedAtMs
130704
+ }));
130705
+ } catch (error48) {
130706
+ throw carryAgentInstruction(error48, claimedAgentInstruction.binding);
130707
+ }
130594
130708
  }
130595
130709
  const preferredModel = String(settings.preferred_model || "").trim();
130596
130710
  if (!preferredModel) {
@@ -132339,19 +132453,15 @@ ${stringifyPromptJson(parts.candlesPayload)}
132339
132453
  });
132340
132454
  }
132341
132455
  }
132342
- let remainingPromptUnits = Math.max(0, Math.trunc(Number(runtimeConstraints.max_trades_per_prompt) || 0));
132343
- let remainingGlobalUnits = runtimeConstraints.remaining_global_units;
132344
- const exchangeUnitsUsed = /* @__PURE__ */ new Map();
132345
- for (const positionSymbol of positionBySymbol.keys()) {
132346
- const venue = getHyperliquidMarketDex(positionSymbol);
132347
- exchangeUnitsUsed.set(venue, (exchangeUnitsUsed.get(venue) ?? 0) + Math.abs(computePlanSignedUnits(positionSymbol)));
132348
- }
132349
- if (runtimeConstraints.remaining_exchange_units != null) {
132350
- const venue = getHyperliquidMarketDex(symbol2);
132351
- exchangeUnitsUsed.set(venue, Math.max(exchangeUnitsUsed.get(venue) ?? 0, maxTradesPerExchange - runtimeConstraints.remaining_exchange_units));
132352
- }
132353
- const initialPromptUnits = remainingPromptUnits;
132354
- const initialGlobalUnits = remainingGlobalUnits;
132456
+ const cycleAllowance = Math.max(0, Math.trunc(Number(runtimeConstraints.max_trades_per_prompt) || 0));
132457
+ for (const positionSymbol of positionBySymbol.keys()) computePlanSignedUnits(positionSymbol);
132458
+ const capacityRoom = openCapacityRoom(positions, {
132459
+ unit_size: metadataTradeSize,
132460
+ capacity_unit_size: capacityUnitSize(metadataTradeSize, config2.default_ai_trade_amount),
132461
+ max_trades_global: maxTradesGlobal,
132462
+ max_trades_per_exchange: maxTradesPerExchange,
132463
+ max_trades_per_asset: maxTradesPerAsset
132464
+ });
132355
132465
  const tradabilityEnabled = resolveBooleanSetting(
132356
132466
  settings,
132357
132467
  "tradability_enabled",
@@ -132381,141 +132491,96 @@ ${stringifyPromptJson(parts.candlesPayload)}
132381
132491
  Math.round(Number(settings.tradability_increase_minimum ?? config2.default_tradability_increase_minimum))
132382
132492
  )
132383
132493
  );
132384
- const acceptExecutionPlan = (entry) => {
132385
- const planSymbol = normalizeRuntimeSymbol(entry.symbol);
132386
- const isPrimaryPlanSymbol = planSymbol === normalizeRuntimeSymbol(symbol2);
132387
- const planSignedUnits = computePlanSignedUnits(entry.symbol);
132388
- const initialClassifiedPlan = classifyExecutionIntent(entry.decision, entry.units, planSignedUnits);
132389
- const applicableMinimum = initialClassifiedPlan.intent === "open" && tradabilityOpenEnabled ? tradabilityOpenMinimum : initialClassifiedPlan.intent === "add" && tradabilityIncreaseEnabled ? tradabilityIncreaseMinimum : null;
132390
- if (tradabilityEnabled && applicableMinimum !== null && (entry.tradability == null || entry.tradability < applicableMinimum)) {
132391
- appendRuntimeDebugEvent({
132392
- label: "execution_plan_tradability_rejected",
132393
- note: [
132394
- `symbol=${planSymbol || entry.symbol}`,
132395
- `intent=${initialClassifiedPlan.intent}`,
132396
- `tradability=${entry.tradability ?? "missing"}`,
132397
- `minimum=${applicableMinimum}`
132398
- ].join(" "),
132399
- outcome: "ok"
132400
- });
132401
- const scoreLabel = entry.tradability == null ? "missing" : String(entry.tradability);
132402
- const blockIntent = initialClassifiedPlan.intent === "open" ? "open" : "add";
132403
- const intentLabel = blockIntent === "open" ? "Open" : "Add";
132404
- return {
132405
- symbol: entry.symbol,
132406
- decision: entry.decision,
132407
- units: entry.units,
132408
- tradability: entry.tradability,
132409
- reasoning: entry.reasoning,
132410
- executionContext: buildExecutionContextForSymbol(entry.symbol),
132411
- executionBlock: {
132412
- reasonCode: "tradability_below_minimum",
132413
- control: "tradability",
132414
- intent: blockIntent,
132415
- tradability: entry.tradability ?? null,
132416
- minimum: applicableMinimum,
132417
- message: `Tradability ${scoreLabel} is below the ${intentLabel} minimum of ${applicableMinimum}. No order was placed.`
132418
- }
132419
- };
132420
- }
132421
- const remainingAssetUnits = runtimeConstraints.remaining_asset_units == null ? null : isPrimaryPlanSymbol ? runtimeConstraints.remaining_asset_units : Math.max(0, maxTradesPerAsset - Math.abs(planSignedUnits));
132422
- const planConstraints = {
132423
- ...localAcceptanceConstraints,
132424
- max_trades_per_prompt: remainingPromptUnits,
132425
- ...acceptancePositionCaps(input.executionMode, {
132426
- remaining_global_units: remainingGlobalUnits,
132427
- remaining_exchange_units: Math.max(0, maxTradesPerExchange - (exchangeUnitsUsed.get(getHyperliquidMarketDex(entry.symbol)) ?? 0)),
132428
- remaining_asset_units: remainingAssetUnits
132429
- }),
132430
- current_symbol_signed_units: planSignedUnits
132431
- };
132432
- const planAcceptance = evaluateRuntimeDecisionAcceptance({
132433
- decision: entry.decision,
132434
- units: entry.units,
132435
- constraints: planConstraints
132436
- });
132437
- if (!planAcceptance.accepted) {
132438
- const aggregateCapacityConsumed = remainingPromptUnits < initialPromptUnits || remainingGlobalUnits !== initialGlobalUnits;
132439
- const capacityReason = planAcceptance.reason_code === "global_capacity_reached" || planAcceptance.reason_code === "exchange_capacity_reached" || planAcceptance.reason_code === "asset_capacity_reached" || planAcceptance.reason_code === "capacity_reached" || planAcceptance.reason_code === "max_per_prompt_zero";
132440
- if (finalDecisionPlans.length > 1 && aggregateCapacityConsumed && capacityReason) {
132494
+ const { judgements, refused } = judgeCyclePlans({
132495
+ plans: finalDecisionPlans,
132496
+ room: capacityRoom,
132497
+ positionCaps: judgesPositionCaps(input.executionMode, input.mode),
132498
+ reductionsFirst: true,
132499
+ allowance: cycleAllowance,
132500
+ constraints: localAcceptanceConstraints,
132501
+ tradability: {
132502
+ enabled: tradabilityEnabled,
132503
+ openEnabled: tradabilityOpenEnabled,
132504
+ increaseEnabled: tradabilityIncreaseEnabled,
132505
+ openMinimum: tradabilityOpenMinimum,
132506
+ increaseMinimum: tradabilityIncreaseMinimum
132507
+ },
132508
+ onJudged: (slot, judgement, remainingAllowance) => {
132509
+ const entry = finalDecisionPlans[slot];
132510
+ const planSymbol = normalizeRuntimeSymbol(entry.symbol) || entry.symbol;
132511
+ const roomCaps = capacityRoom.caps(entry.symbol);
132512
+ if (judgement.kind === "blocked") {
132513
+ appendRuntimeDebugEvent({
132514
+ label: "execution_plan_tradability_rejected",
132515
+ note: [
132516
+ `symbol=${planSymbol}`,
132517
+ `intent=${judgement.intent}`,
132518
+ `tradability=${entry.tradability ?? "missing"}`,
132519
+ `minimum=${judgement.minimum}`
132520
+ ].join(" "),
132521
+ outcome: "ok"
132522
+ });
132523
+ } else if (judgement.kind === "unsent") {
132441
132524
  appendRuntimeDebugEvent({
132442
132525
  label: "execution_plan_capacity_skipped",
132443
132526
  note: [
132444
- `symbol=${planSymbol || entry.symbol}`,
132445
- `reason=${planAcceptance.reason_code || "capacity_reached"}`,
132446
- `remaining_prompt=${remainingPromptUnits}`,
132447
- `remaining_global=${remainingGlobalUnits ?? "unbounded"}`
132527
+ `symbol=${planSymbol}`,
132528
+ `reason=${judgement.reasonCode}`,
132529
+ `remaining_prompt=${remainingAllowance}`,
132530
+ `remaining_global=${roomCaps.remaining_global_units}`
132531
+ ].join(" ")
132532
+ });
132533
+ } else {
132534
+ appendRuntimeDebugEvent({
132535
+ label: "execution_plan_capacity",
132536
+ note: [
132537
+ `symbol=${planSymbol}`,
132538
+ `signed_units=${judgement.signedUnits}`,
132539
+ `accepted_units=${judgement.units}`,
132540
+ `remaining_prompt=${remainingAllowance}`,
132541
+ `remaining_global=${roomCaps.remaining_global_units}`,
132542
+ `remaining_asset=${roomCaps.remaining_asset_units}`
132448
132543
  ].join(" ")
132449
132544
  });
132450
- return {
132451
- symbol: entry.symbol,
132452
- decision: "HOLD",
132453
- units: 0,
132454
- tradability: entry.tradability,
132455
- reasoning: `Skipped by client runtime constraints: ${planAcceptance.reason_code || "capacity_reached"}`,
132456
- executionContext: buildExecutionContextForSymbol(entry.symbol),
132457
- ...entry.decision === "BUY" || entry.decision === "SELL" ? {
132458
- unsentOrder: {
132459
- decision: entry.decision,
132460
- units: entry.units,
132461
- constraintReasonCode: planAcceptance.reason_code || "capacity_reached"
132462
- }
132463
- } : {}
132464
- };
132465
- }
132466
- throw new Error(buildRuntimeConstraintRejectionMessage({
132467
- reasonCode: planAcceptance.reason_code,
132468
- constraintsRecord: runtimeConstraintsRecord,
132469
- model: finalModel,
132470
- provider: finalProvider,
132471
- modelEligibilityReason: modelEligibility.reason
132472
- }));
132473
- }
132474
- const classifiedPlan = classifyExecutionIntent(
132475
- planAcceptance.decision,
132476
- planAcceptance.normalized_units,
132477
- planSignedUnits
132478
- );
132479
- if (classifiedPlan.side !== null) {
132480
- remainingPromptUnits = Math.max(0, remainingPromptUnits - planAcceptance.normalized_units);
132481
- const currentAbsUnits = Math.abs(planSignedUnits);
132482
- const targetAbsUnits = Math.abs(classifiedPlan.targetSignedUnits);
132483
- const globalDelta = Math.max(0, targetAbsUnits - currentAbsUnits);
132484
- const venue = getHyperliquidMarketDex(entry.symbol);
132485
- exchangeUnitsUsed.set(venue, (exchangeUnitsUsed.get(venue) ?? 0) + globalDelta);
132486
- if (remainingGlobalUnits !== null && globalDelta > 0) {
132487
- remainingGlobalUnits = Math.max(0, remainingGlobalUnits - globalDelta);
132488
132545
  }
132489
132546
  }
132490
- appendRuntimeDebugEvent({
132491
- label: "execution_plan_capacity",
132492
- note: [
132493
- `symbol=${planSymbol || entry.symbol}`,
132494
- `signed_units=${planSignedUnits}`,
132495
- `accepted_units=${planAcceptance.normalized_units}`,
132496
- `remaining_prompt=${remainingPromptUnits}`,
132497
- `remaining_global=${remainingGlobalUnits ?? "unbounded"}`,
132498
- `remaining_asset=${remainingAssetUnits ?? "unbounded"}`
132499
- ].join(" ")
132500
- });
132501
- return {
132547
+ });
132548
+ if (refused) {
132549
+ throw new Error(buildRuntimeConstraintRejectionMessage({
132550
+ reasonCode: refused.reasonCode,
132551
+ constraintsRecord: runtimeConstraintsRecord,
132552
+ model: finalModel,
132553
+ provider: finalProvider,
132554
+ modelEligibilityReason: modelEligibility.reason
132555
+ }));
132556
+ }
132557
+ const acceptedExecutionPlans = finalDecisionPlans.map((entry, slot) => {
132558
+ const judgement = judgements[slot];
132559
+ const base = {
132502
132560
  symbol: entry.symbol,
132503
- decision: planAcceptance.decision,
132504
- units: planAcceptance.normalized_units,
132505
132561
  tradability: entry.tradability,
132506
132562
  reasoning: entry.reasoning,
132507
132563
  executionContext: buildExecutionContextForSymbol(entry.symbol)
132508
132564
  };
132509
- };
132510
- const acceptedBySlot = /* @__PURE__ */ new Map();
132511
- for (const slot of reductionFirstOrder(finalDecisionPlans.map((entry) => ({
132512
- decision: entry.decision,
132513
- units: entry.units,
132514
- signedUnits: computePlanSignedUnits(entry.symbol)
132515
- })))) {
132516
- acceptedBySlot.set(slot, acceptExecutionPlan(finalDecisionPlans[slot]));
132517
- }
132518
- const acceptedExecutionPlans = finalDecisionPlans.map((_, slot) => acceptedBySlot.get(slot));
132565
+ if (judgement.kind === "blocked") {
132566
+ return {
132567
+ ...base,
132568
+ decision: judgement.decision,
132569
+ units: judgement.units,
132570
+ executionBlock: tradabilityExecutionBlock(entry.tradability, judgement.intent, judgement.minimum)
132571
+ };
132572
+ }
132573
+ if (judgement.kind === "unsent") {
132574
+ return {
132575
+ ...base,
132576
+ decision: "HOLD",
132577
+ units: 0,
132578
+ reasoning: `Skipped by client runtime constraints: ${judgement.reasonCode}`,
132579
+ ...entry.decision === "BUY" || entry.decision === "SELL" ? { unsentOrder: { decision: entry.decision, units: entry.units, constraintReasonCode: judgement.reasonCode } } : {}
132580
+ };
132581
+ }
132582
+ return { ...base, decision: judgement.decision, units: judgement.units, ...capacityTrimOf(judgement) };
132583
+ });
132519
132584
  const selectedAcceptedPlan = acceptedExecutionPlans.find((entry) => normalizeRuntimeSymbol(entry.symbol) === normalizeRuntimeSymbol(symbol2)) ?? acceptedExecutionPlans[0];
132520
132585
  const acceptance = {
132521
132586
  accepted: true,
@@ -132781,6 +132846,8 @@ var init_engine = __esm({
132781
132846
  init_exchange_mutation_fence();
132782
132847
  init_hyperliquid_account_state_adapter();
132783
132848
  init_hyperliquid_market_symbol();
132849
+ init_agent_instruction_carry();
132850
+ init_execution_capacity();
132784
132851
  init_client_killswitch();
132785
132852
  init_perp_dex_scope();
132786
132853
  init_api2();
@@ -136504,6 +136571,10 @@ var init_engine = __esm({
136504
136571
  ),
136505
136572
  externalInferenceBindings: result.externalInferenceBindings ?? [],
136506
136573
  externalAgentInstruction: result.externalAgentInstruction ?? null,
136574
+ // The cycle's market's order its own limits refused: the decision
136575
+ // reports HOLD for it, and an Agent or external model's authority
136576
+ // (which names the order) accepts that HOLD as not sent.
136577
+ unsentOrder: result.executionPlans?.find((plan) => normalizeHyperliquidMarketSymbol(plan.symbol) === normalizeHyperliquidMarketSymbol(result.executionContext.symbol))?.unsentOrder ?? null,
136507
136578
  mode: runtimeMode
136508
136579
  }, {
136509
136580
  signal: analysisAbortController.signal,
@@ -136526,13 +136597,44 @@ var init_engine = __esm({
136526
136597
  }))
136527
136598
  });
136528
136599
  }
136529
- throw decisionError;
136600
+ throw carryAgentInstruction(decisionError, result.externalAgentInstruction);
136530
136601
  }
136531
136602
  if (!decisionResponse) {
136532
136603
  await this._recoverFromNoDecisionCycle(requestId, "decision_submit", "empty_decision_response");
136533
136604
  return;
136534
136605
  }
136606
+ const settleUnsentAgentDecision = async (why) => {
136607
+ if (runtimeMode !== "trader" || !result.externalAgentInstruction || this._executionFinalizationRequired) return;
136608
+ await reportClientRuntimeTradeSync(profileId, {
136609
+ sessionId,
136610
+ deviceId,
136611
+ schedulerInstanceId: this._instanceId,
136612
+ mode: runtimeMode,
136613
+ lastRunAt: runStartedAt,
136614
+ syncedAt: result.completedAt,
136615
+ analysisRunId: requestId,
136616
+ analysisMode: runtimeMode,
136617
+ cycleId: result.cycleId,
136618
+ decisionSnapshotId: result.decisionSnapshotId,
136619
+ executionSnapshotId: null,
136620
+ contractVersion: result.contractVersion,
136621
+ contractHash: result.contractHash,
136622
+ policyGenerationId: result.policyGenerationId,
136623
+ executions: [],
136624
+ isAnalyzing: false,
136625
+ isExecuting: false,
136626
+ externalAgentInstruction: result.externalAgentInstruction
136627
+ }, {
136628
+ requestTimeoutMs: this._settlementRequestTimeoutMs ?? void 0,
136629
+ idempotencyKey: `runtime-trade-sync-${createRuntimeUuid2()}`
136630
+ }).catch((settleError) => appendRuntimeDebugEvent({
136631
+ label: "agent_instruction_unsent_settle_failed",
136632
+ note: `stage=${why} error=${getSanitizedRuntimeErrorMessage(settleError) || "unknown"}`,
136633
+ outcome: "error"
136634
+ }));
136635
+ };
136535
136636
  if (analysisAbortController.signal.aborted || this._isStopping || this._analysisRequestId !== requestId) {
136637
+ await settleUnsentAgentDecision("cycle_ended_after_decision");
136536
136638
  return;
136537
136639
  }
136538
136640
  this._setRuntimeStatus(decisionResponse.runtime, "decision");
@@ -136549,6 +136651,7 @@ var init_engine = __esm({
136549
136651
  note: `cycle_id=${result.cycleId} reconciled=${String(decisionResponse.decision_reconciled === true)}`,
136550
136652
  outcome: "ok"
136551
136653
  });
136654
+ await settleUnsentAgentDecision("decision_saved_after_execution_deadline");
136552
136655
  this._notifyListeners();
136553
136656
  return;
136554
136657
  }
@@ -136557,6 +136660,7 @@ var init_engine = __esm({
136557
136660
  if (runtimeMode === "trader") {
136558
136661
  observeCycle({ stage: "execution" });
136559
136662
  if (shouldAbortForContractInvalidation("pre_trade_execution")) {
136663
+ await settleUnsentAgentDecision("pre_trade_execution");
136560
136664
  return;
136561
136665
  }
136562
136666
  if (hasActionableDecision) {
@@ -136581,6 +136685,7 @@ var init_engine = __esm({
136581
136685
  });
136582
136686
  const config2 = await this.refreshExecutionConfig(profileId);
136583
136687
  if (shouldAbortForContractInvalidation("post_execution_config_refresh")) {
136688
+ await settleUnsentAgentDecision("post_execution_config_refresh");
136584
136689
  return;
136585
136690
  }
136586
136691
  const executionResults = [];
@@ -136608,6 +136713,22 @@ var init_engine = __esm({
136608
136713
  capacityPlans.forEach(({ planIndex }, index) => serverCapacityByPlan.set(planIndex, allocations[index]));
136609
136714
  }
136610
136715
  const runPlan = async (plan, planIndex) => {
136716
+ const withPlanCapacityTrim = (planResult) => {
136717
+ if (plan.capacityTrim) {
136718
+ return withCapacityTrim(planResult, {
136719
+ requested_units: plan.capacityTrim.requestedUnits,
136720
+ accepted_units: plan.units,
136721
+ constraint_reason_code: plan.capacityTrim.constraintReasonCode
136722
+ });
136723
+ }
136724
+ const allocation = serverCapacityByPlan.get(planIndex);
136725
+ const decidedUnits = Math.trunc(Number(plan.units) || 0);
136726
+ return allocation && !("unavailable" in allocation) && allocation.accepted && allocation.units < decidedUnits ? withCapacityTrim(planResult, {
136727
+ requested_units: decidedUnits,
136728
+ accepted_units: allocation.units,
136729
+ constraint_reason_code: allocation.reason_code ?? "units_capped"
136730
+ }) : planResult;
136731
+ };
136611
136732
  let planEntryOrderDispatched = false;
136612
136733
  let planExitOrderDispatched = false;
136613
136734
  const decisionWallet = String(
@@ -136709,6 +136830,7 @@ var init_engine = __esm({
136709
136830
  },
136710
136831
  shouldCancelBeforeExchangeOrderDispatch: () => this._windowHandoffRequested
136711
136832
  });
136833
+ if (plan.capacityTrim) executionResult = withPlanCapacityTrim(executionResult);
136712
136834
  } catch (executionError) {
136713
136835
  const committedReports = getCommittedExecutionReports(executionError);
136714
136836
  const committedOrder = getCommittedDecisionOrder(executionError);
@@ -136717,7 +136839,7 @@ var init_engine = __esm({
136717
136839
  const handoffCleanup = getClientRuntimeWindowHandoffCleanup(executionError);
136718
136840
  if (handoffCleanup || committedReports.length > 0) {
136719
136841
  this._executionFinalizationRequired = true;
136720
- return { control: "break", result: {
136842
+ return { control: "break", result: withPlanCapacityTrim({
136721
136843
  status: committedReports.length > 0 ? "executed" : "skipped",
136722
136844
  intent: "hold",
136723
136845
  side: null,
@@ -136731,7 +136853,7 @@ var init_engine = __esm({
136731
136853
  ...handoffCleanup ? { handoffCleanup } : {},
136732
136854
  executionSnapshotId: `handoff-cleanup-${planIndex + 1}-${Date.now()}`,
136733
136855
  executionSnapshotCapturedAt: (/* @__PURE__ */ new Date()).toISOString()
136734
- } };
136856
+ }) };
136735
136857
  }
136736
136858
  return { control: "break" };
136737
136859
  }
@@ -136779,6 +136901,7 @@ var init_engine = __esm({
136779
136901
  }
136780
136902
  }]
136781
136903
  };
136904
+ executionResult = withPlanCapacityTrim(executionResult);
136782
136905
  if (abortedAfterCommittedOrder) {
136783
136906
  this._executionFinalizationRequired = true;
136784
136907
  return { control: "break", result: executionResult };
@@ -136903,6 +137026,7 @@ var init_engine = __esm({
136903
137026
  }
136904
137027
  const outcome = await runPlan(executionPlans[planIndex], planIndex);
136905
137028
  if (outcome.control === "return") {
137029
+ await settleUnsentAgentDecision("plan_ended_cycle");
136906
137030
  return;
136907
137031
  }
136908
137032
  if (outcome.result) {
@@ -136981,9 +137105,11 @@ var init_engine = __esm({
136981
137105
  outcome: "ok"
136982
137106
  });
136983
137107
  if (!this._executionFinalizationRequired && (analysisAbortController.signal.aborted || this._isStopping || this._analysisRequestId !== requestId)) {
137108
+ await settleUnsentAgentDecision("cycle_ended_before_trade_sync");
136984
137109
  return;
136985
137110
  }
136986
137111
  if (!this._executionFinalizationRequired && shouldAbortForContractInvalidation("pre_trade_sync_submit")) {
137112
+ await settleUnsentAgentDecision("pre_trade_sync_submit");
136987
137113
  return;
136988
137114
  }
136989
137115
  const tradeSyncPayload = {
@@ -137647,7 +137773,8 @@ var init_engine = __esm({
137647
137773
  executionReasonCode: executionProjection?.reason_code ?? null,
137648
137774
  executionStage: executionProjection?.execution_stage ?? null,
137649
137775
  dispatchOutcome: executionProjection?.dispatch_outcome ?? null,
137650
- providerFailure: serverModelFailure?.report ?? null
137776
+ providerFailure: serverModelFailure?.report ?? null,
137777
+ externalAgentInstruction: carriedAgentInstruction(reason)
137651
137778
  },
137652
137779
  {
137653
137780
  requestTimeoutMs: this._settlementRequestTimeoutMs ?? void 0