@cortexkit/opencode-magic-context 0.46.1 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (203) hide show
  1. package/dist/auto-search-worker.js +115 -0
  2. package/dist/config/index.d.ts.map +1 -1
  3. package/dist/config/live-run-config.d.ts.map +1 -1
  4. package/dist/config/migrate-config-location.d.ts.map +1 -1
  5. package/dist/config/schema/magic-context.d.ts +11 -3
  6. package/dist/config/schema/magic-context.d.ts.map +1 -1
  7. package/dist/{conflict-warning-hook-7fj2b9jw.js → conflict-warning-hook-z44ynfz7.js} +5 -4
  8. package/dist/{context-sh2m2vde.js → context-wq4ffwyb.js} +108 -23
  9. package/dist/{derive-budgets-7nj7r1rv.js → derive-budgets-ke12jnnh.js} +1 -1
  10. package/dist/embedding-worker.js +2 -2
  11. package/dist/features/magic-context/dreamer/task-gates.d.ts.map +1 -1
  12. package/dist/features/magic-context/overflow-detection.d.ts +2 -0
  13. package/dist/features/magic-context/overflow-detection.d.ts.map +1 -1
  14. package/dist/features/magic-context/project-embedding-registry.d.ts +7 -0
  15. package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
  16. package/dist/features/magic-context/search.d.ts +2 -0
  17. package/dist/features/magic-context/search.d.ts.map +1 -1
  18. package/dist/features/magic-context/session-project-storage.d.ts +8 -2
  19. package/dist/features/magic-context/session-project-storage.d.ts.map +1 -1
  20. package/dist/features/magic-context/storage-historian-runs.d.ts +2 -5
  21. package/dist/features/magic-context/storage-historian-runs.d.ts.map +1 -1
  22. package/dist/features/magic-context/storage-meta-persisted.d.ts +12 -0
  23. package/dist/features/magic-context/storage-meta-persisted.d.ts.map +1 -1
  24. package/dist/features/magic-context/storage-meta-session.d.ts.map +1 -1
  25. package/dist/features/magic-context/storage-tags.d.ts +7 -2
  26. package/dist/features/magic-context/storage-tags.d.ts.map +1 -1
  27. package/dist/features/magic-context/storage.d.ts +1 -0
  28. package/dist/features/magic-context/storage.d.ts.map +1 -1
  29. package/dist/features/magic-context/transform-decision-log.d.ts +3 -1
  30. package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
  31. package/dist/hooks/magic-context/active-anthropic-turn.d.ts +8 -0
  32. package/dist/hooks/magic-context/active-anthropic-turn.d.ts.map +1 -0
  33. package/dist/hooks/magic-context/apply-operations.d.ts.map +1 -1
  34. package/dist/hooks/magic-context/auto-search-blocking.fixture.d.ts +2 -0
  35. package/dist/hooks/magic-context/auto-search-blocking.fixture.d.ts.map +1 -0
  36. package/dist/hooks/magic-context/auto-search-deadline.d.ts +7 -0
  37. package/dist/hooks/magic-context/auto-search-deadline.d.ts.map +1 -1
  38. package/dist/hooks/magic-context/auto-search-host-review.fixture.d.ts +3 -0
  39. package/dist/hooks/magic-context/auto-search-host-review.fixture.d.ts.map +1 -0
  40. package/dist/hooks/magic-context/auto-search-lock-review.fixture.d.ts +2 -0
  41. package/dist/hooks/magic-context/auto-search-lock-review.fixture.d.ts.map +1 -0
  42. package/dist/hooks/magic-context/auto-search-long-lock-review.fixture.d.ts +2 -0
  43. package/dist/hooks/magic-context/auto-search-long-lock-review.fixture.d.ts.map +1 -0
  44. package/dist/hooks/magic-context/auto-search-omp-host-review.fixture.d.ts +4 -0
  45. package/dist/hooks/magic-context/auto-search-omp-host-review.fixture.d.ts.map +1 -0
  46. package/dist/hooks/magic-context/auto-search-omp-loader.fixture.d.ts +3 -0
  47. package/dist/hooks/magic-context/auto-search-omp-loader.fixture.d.ts.map +1 -0
  48. package/dist/hooks/magic-context/auto-search-runner.d.ts +1 -1
  49. package/dist/hooks/magic-context/auto-search-runner.d.ts.map +1 -1
  50. package/dist/hooks/magic-context/auto-search-snapshot.fixture.d.ts +4 -0
  51. package/dist/hooks/magic-context/auto-search-snapshot.fixture.d.ts.map +1 -0
  52. package/dist/hooks/magic-context/auto-search-worker-client.d.ts +69 -0
  53. package/dist/hooks/magic-context/auto-search-worker-client.d.ts.map +1 -0
  54. package/dist/hooks/magic-context/auto-search-worker.d.ts +2 -0
  55. package/dist/hooks/magic-context/auto-search-worker.d.ts.map +1 -0
  56. package/dist/hooks/magic-context/caveman-cleanup.d.ts.map +1 -1
  57. package/dist/hooks/magic-context/compartment-runner-types.d.ts +3 -5
  58. package/dist/hooks/magic-context/compartment-runner-types.d.ts.map +1 -1
  59. package/dist/hooks/magic-context/compartment-runner.d.ts +2 -1
  60. package/dist/hooks/magic-context/compartment-runner.d.ts.map +1 -1
  61. package/dist/hooks/magic-context/compartment-trigger.d.ts +3 -1
  62. package/dist/hooks/magic-context/compartment-trigger.d.ts.map +1 -1
  63. package/dist/hooks/magic-context/event-handler.d.ts +1 -1
  64. package/dist/hooks/magic-context/event-handler.d.ts.map +1 -1
  65. package/dist/hooks/magic-context/event-resolvers.d.ts.map +1 -1
  66. package/dist/hooks/magic-context/execute-status.d.ts.map +1 -1
  67. package/dist/hooks/magic-context/final-wire-token-estimate.d.ts +2 -0
  68. package/dist/hooks/magic-context/final-wire-token-estimate.d.ts.map +1 -1
  69. package/dist/hooks/magic-context/heuristic-cleanup.d.ts.map +1 -1
  70. package/dist/hooks/magic-context/historian-drain-gate.d.ts +11 -0
  71. package/dist/hooks/magic-context/historian-drain-gate.d.ts.map +1 -0
  72. package/dist/hooks/magic-context/hook.d.ts +2 -1
  73. package/dist/hooks/magic-context/hook.d.ts.map +1 -1
  74. package/dist/hooks/magic-context/latest-assistant-turn.d.ts +25 -0
  75. package/dist/hooks/magic-context/latest-assistant-turn.d.ts.map +1 -0
  76. package/dist/hooks/magic-context/latest-thinking-recovery.d.ts +61 -0
  77. package/dist/hooks/magic-context/latest-thinking-recovery.d.ts.map +1 -0
  78. package/dist/hooks/magic-context/module-wire.d.ts.map +1 -1
  79. package/dist/hooks/magic-context/opencode-proven-floor.d.ts +6 -0
  80. package/dist/hooks/magic-context/opencode-proven-floor.d.ts.map +1 -0
  81. package/dist/hooks/magic-context/pass-outcome.d.ts.map +1 -1
  82. package/dist/hooks/magic-context/protected-tail-boundary.d.ts.map +1 -1
  83. package/dist/hooks/magic-context/read-session-true-raw-tokens.d.ts.map +1 -1
  84. package/dist/hooks/magic-context/reasoning-budget-status.d.ts +15 -0
  85. package/dist/hooks/magic-context/reasoning-budget-status.d.ts.map +1 -0
  86. package/dist/hooks/magic-context/reasoning-budget.d.ts +40 -0
  87. package/dist/hooks/magic-context/reasoning-budget.d.ts.map +1 -0
  88. package/dist/hooks/magic-context/reasoning-removal.d.ts +6 -6
  89. package/dist/hooks/magic-context/reasoning-removal.d.ts.map +1 -1
  90. package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
  91. package/dist/hooks/magic-context/sentinel.d.ts +4 -0
  92. package/dist/hooks/magic-context/sentinel.d.ts.map +1 -1
  93. package/dist/hooks/magic-context/strip-content.d.ts +7 -3
  94. package/dist/hooks/magic-context/strip-content.d.ts.map +1 -1
  95. package/dist/hooks/magic-context/tag-messages.d.ts +13 -0
  96. package/dist/hooks/magic-context/tag-messages.d.ts.map +1 -1
  97. package/dist/hooks/magic-context/tool-drop-target.d.ts +5 -0
  98. package/dist/hooks/magic-context/tool-drop-target.d.ts.map +1 -1
  99. package/dist/hooks/magic-context/transform-compartment-phase.d.ts +3 -28
  100. package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
  101. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +28 -6
  102. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  103. package/dist/hooks/magic-context/transform.d.ts +3 -1
  104. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  105. package/dist/{index-0d3g3461.js → index-0c82743p.js} +2 -1
  106. package/dist/{index-5p8jdswx.js → index-5a2r0p9f.js} +3 -3
  107. package/dist/{index-sjthx78w.js → index-6d9e1m08.js} +4647 -11000
  108. package/dist/{index-majxda46.js → index-6wkcswft.js} +1 -1
  109. package/dist/index-92bp57hg.js +2063 -0
  110. package/dist/{index-sfnj6h8h.js → index-9pk9exrb.js} +3 -3
  111. package/dist/{index-7qw742ev.js → index-adwfkpex.js} +5 -24
  112. package/dist/{index-3h0ybwah.js → index-bb36vgr3.js} +80 -12
  113. package/dist/{index-pkbcrdqs.js → index-cwf6s3ay.js} +1072 -2422
  114. package/dist/index-fnn5pjtt.js +6554 -0
  115. package/dist/{index-sgthv3f7.js → index-gg8j07zz.js} +1 -1
  116. package/dist/{index-8x2v7gg9.js → index-m5fe6jch.js} +7 -3
  117. package/dist/{v2/server-g0fjrkta.js → index-rrbbspwh.js} +42 -27
  118. package/dist/index-rrrsepyw.js +3464 -0
  119. package/dist/{index-hpecdzec.js → index-w2t4ah5j.js} +948 -501
  120. package/dist/{v2/server-fg34g6a5.js → index-wx8a6bw3.js} +48 -8
  121. package/dist/{index-r5hmbx3t.js → index-x3kwrmqk.js} +146 -3571
  122. package/dist/index-yr3zj7e7.js +23 -0
  123. package/dist/index.d.ts.map +1 -1
  124. package/dist/index.js +624 -65
  125. package/dist/{message-time-backfill-68gj6t3e.js → message-time-backfill-r5epkzj3.js} +1 -1
  126. package/dist/migration-worker.js +7 -5
  127. package/dist/plugin/hooks/create-session-hooks.d.ts +2 -1
  128. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  129. package/dist/plugin/host-stall-profiler-report.d.ts +67 -0
  130. package/dist/plugin/host-stall-profiler-report.d.ts.map +1 -0
  131. package/dist/plugin/host-stall-profiler.d.ts +96 -0
  132. package/dist/plugin/host-stall-profiler.d.ts.map +1 -0
  133. package/dist/plugin/messages-transform.d.ts +21 -6
  134. package/dist/plugin/messages-transform.d.ts.map +1 -1
  135. package/dist/{read-session-chunk-egz7r68d.js → read-session-chunk-4jey7hpt.js} +4 -4
  136. package/dist/{recomp-orchestrator-y15j0rb9.js → recomp-orchestrator-rervg6q4.js} +13 -10
  137. package/dist/{send-session-notification-dyw42dtr.js → send-session-notification-0m68ms3n.js} +4 -3
  138. package/dist/shared/auto-search-lifecycle.d.ts +7 -0
  139. package/dist/shared/auto-search-lifecycle.d.ts.map +1 -0
  140. package/dist/shared/historian-tool-expansions.d.ts +1 -1
  141. package/dist/shared/historian-tool-expansions.d.ts.map +1 -1
  142. package/dist/shared/historian-tool-template.d.ts +2 -2
  143. package/dist/shared/historian-tool-template.d.ts.map +1 -1
  144. package/dist/shared/sqlite.d.ts +16 -1
  145. package/dist/shared/sqlite.d.ts.map +1 -1
  146. package/dist/shared/status-view.d.ts.map +1 -1
  147. package/dist/shared/window-geometry.d.ts +4 -0
  148. package/dist/shared/window-geometry.d.ts.map +1 -1
  149. package/dist/tools/ctx-expand/render.d.ts.map +1 -1
  150. package/dist/{transform-postprocess-phase-bqhz6vdr.js → transform-postprocess-phase-z5hzpsxv.js} +13 -10
  151. package/dist/v2/auto-search-worker.js +115 -0
  152. package/dist/v2/{context-zecmzk5s.js → context-14v1hr8b.js} +3783 -4668
  153. package/dist/v2/{derive-budgets-kdgp4s3r.js → derive-budgets-nc9avxz8.js} +2 -2
  154. package/dist/v2/embedding-worker.js +3 -3
  155. package/dist/v2/hidden-completion.d.ts.map +1 -1
  156. package/dist/v2/hooks/context.d.ts.map +1 -1
  157. package/dist/v2/{message-time-backfill-r6qkem1x.js → message-time-backfill-1f9tzvcs.js} +1 -1
  158. package/dist/v2/migration-worker.js +7 -5
  159. package/dist/v2/{read-session-chunk-8vjp6581.js → read-session-chunk-gyyv7w2r.js} +4 -4
  160. package/dist/v2/{recomp-orchestrator-8ejxvrzz.js → recomp-orchestrator-42vjba7p.js} +17 -14
  161. package/dist/v2/{send-session-notification-qs0j78v6.js → send-session-notification-c0wtscea.js} +5 -4
  162. package/dist/v2/server-3trjk1hx.js +6360 -0
  163. package/dist/v2/{server-e29d7p7c.js → server-50hvkg3v.js} +7 -3
  164. package/dist/v2/{server-y8maxeft.js → server-cpepxy2q.js} +2 -1
  165. package/dist/v2/server-d0sraw7m.js +3403 -0
  166. package/dist/v2/server-e0c1b7a7.js +2063 -0
  167. package/dist/v2/{server-mcfawjgc.js → server-efhwzx05.js} +5 -24
  168. package/dist/v2/{server-3n4q9xme.js → server-fcdehk1s.js} +1 -1
  169. package/dist/{index-q4yp4b52.js → v2/server-fq7kq32k.js} +42 -27
  170. package/dist/v2/{server-jc7y02q0.js → server-nf82q6pt.js} +1117 -7290
  171. package/dist/v2/{server-frbm99q5.js → server-njt3np1k.js} +99 -3465
  172. package/dist/v2/{server-qp5hx1ad.js → server-nm9n3aqq.js} +107 -12
  173. package/dist/v2/{server-c5gz8wph.js → server-rz514f14.js} +7 -2
  174. package/dist/v2/{server-wvjvfhck.js → server-vd4e7174.js} +1 -1
  175. package/dist/{index-fg34g6a5.js → v2/server-wx8a6bw3.js} +48 -8
  176. package/dist/v2/{server-xa4xe3rv.js → server-y10vbq6y.js} +1 -1
  177. package/dist/v2/server-yr3zj7e7.js +23 -0
  178. package/dist/v2/server.js +5 -5
  179. package/dist/v2/{wrapup-orchestrator-0snhvwcv.js → wrapup-orchestrator-nbz854vc.js} +16 -13
  180. package/dist/wrapup-orchestrator-b2dztrar.js +29 -0
  181. package/package.json +3 -3
  182. package/src/config/index.ts +6 -0
  183. package/src/config/live-run-config.test.ts +37 -1
  184. package/src/config/live-run-config.ts +28 -0
  185. package/src/config/migrate-config-location.ts +10 -3
  186. package/src/config/schema/magic-context.test.ts +4 -3
  187. package/src/config/schema/magic-context.ts +18 -6
  188. package/src/shared/auto-search-lifecycle.ts +27 -0
  189. package/src/shared/historian-tool-defaults.json +6 -6
  190. package/src/shared/historian-tool-expansions.ts +65 -8
  191. package/src/shared/historian-tool-preview-defaults.json +13 -0
  192. package/src/shared/historian-tool-template.ts +48 -14
  193. package/src/shared/sqlite-640-review-r2.test.ts +136 -0
  194. package/src/shared/sqlite-640-review.test.ts +183 -0
  195. package/src/shared/sqlite-acquisition-routing.test.ts +18 -0
  196. package/src/shared/sqlite.ts +84 -14
  197. package/src/shared/status-view.test.ts +6 -1
  198. package/src/shared/status-view.ts +15 -1
  199. package/src/shared/tag-transcript.ts +6 -0
  200. package/src/shared/window-geometry.ts +10 -0
  201. package/dist/wrapup-orchestrator-39amhv9s.js +0 -26
  202. /package/dist/{index-en1k8h8m.js → index-5prbx026.js} +0 -0
  203. /package/dist/v2/{index-en1k8h8m.js → index-5prbx026.js} +0 -0
package/dist/index.js CHANGED
@@ -21,7 +21,7 @@ import {
21
21
  record,
22
22
  DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE,
23
23
  DEFAULT_HISTORIAN_TIMEOUT_MS
24
- } from "./index-8x2v7gg9.js";
24
+ } from "./index-m5fe6jch.js";
25
25
  import {
26
26
  denyTaskRoutingToCallerAgents,
27
27
  buildHiddenAgentRegistrations,
@@ -40,9 +40,6 @@ import {
40
40
  dreamerRunConfig,
41
41
  pluginConfigReader,
42
42
  createDreamerOutputCapSampler,
43
- observeSessionActivity,
44
- backfillSessionActivity,
45
- recordSessionProjectIdentity,
46
43
  COMPARTMENT_AGENT_SYSTEM_PROMPT,
47
44
  HISTORIAN_EDITOR_SYSTEM_PROMPT,
48
45
  COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT,
@@ -52,7 +49,6 @@ import {
52
49
  invalidateAutoEmbedSession,
53
50
  getEmbedDrainUiStatus,
54
51
  clearEmbedSessionState,
55
- deleteIndexedMessage,
56
52
  getProtectionWindowForSession,
57
53
  getPersistedReasoningWatermark,
58
54
  setPersistedReasoningWatermark,
@@ -68,7 +64,6 @@ import {
68
64
  clearDetectedContextLimit,
69
65
  getPersistedCompactionMarkerState,
70
66
  removeStrippedPlaceholderId,
71
- armThinkingBindingRecovery,
72
67
  getPendingCompactionMarkerState,
73
68
  clearPendingCompactionMarkerStateIf,
74
69
  getSessionsWithPendingMarker,
@@ -86,14 +81,11 @@ import {
86
81
  recordPromptSessionError,
87
82
  createPromptSurfaceRuntime,
88
83
  setKeepSubagents,
89
- getProjectEmbeddingSnapshot,
90
- getEmbeddingCoverageStatus,
91
- getAutoEmbeddingSessionCoverage,
92
84
  removeCompactionMarkerForSession,
93
85
  checkCompactionMarkerConsistency,
94
86
  clearInjectionCache,
95
87
  clearNoteNudgeTriggerOnly
96
- } from "./index-sjthx78w.js";
88
+ } from "./index-6d9e1m08.js";
97
89
  import"./index-sd3egckz.js";
98
90
  import {
99
91
  reloadWindowOverlay,
@@ -104,8 +96,8 @@ import {
104
96
  deriveHistorianChunkTokens2,
105
97
  resolveKnownHistorianContextLimit2,
106
98
  resolveHistorianContextLimit2
107
- } from "./index-0d3g3461.js";
108
- import"./index-q4yp4b52.js";
99
+ } from "./index-0c82743p.js";
100
+ import"./index-rrbbspwh.js";
109
101
  import {
110
102
  resolveOpenCodeDbPath,
111
103
  openCodeDbPathExists,
@@ -113,7 +105,7 @@ import {
113
105
  claimOpenCodeDbDiagnosticOnce,
114
106
  closeQuietly
115
107
  } from "./index-b35pxds2.js";
116
- import"./index-fg34g6a5.js";
108
+ import"./index-wx8a6bw3.js";
117
109
  import {
118
110
  createSubcCheckoutClaimGate,
119
111
  openCodeEventSessionId,
@@ -131,6 +123,8 @@ import {
131
123
  createDbLkgPersistence,
132
124
  startDreamScheduleTimer,
133
125
  ensureProjectRegisteredFromOpenCodeDirectory,
126
+ recordOpenCodeProvenInputFloor,
127
+ resolveOpenCodeProvenInputFloor,
134
128
  resolveContextWindowGeometry,
135
129
  resolveContextLimit,
136
130
  resolveExecuteThresholdDetail,
@@ -161,6 +155,8 @@ import {
161
155
  clearTransformDecisionSession,
162
156
  scheduleOpenCodeTransformDecisionWrite,
163
157
  maybeDeliverChannel2,
158
+ armLatestThinkingRecovery,
159
+ armBindingRecoverySafely,
164
160
  clearMessageTokensCache,
165
161
  createTransform,
166
162
  createSubcModuleClient,
@@ -180,22 +176,13 @@ import {
180
176
  createCtxSearchTools,
181
177
  parameterDescriptionsFor,
182
178
  MagicContextRpcServer
183
- } from "./index-hpecdzec.js";
179
+ } from "./index-w2t4ah5j.js";
184
180
  import {
185
181
  formatFailClosedBlockingMessage,
186
182
  createFailClosedController,
187
183
  recordHookInitFailure,
188
184
  clearHookInitFailure,
189
185
  getLastHookInitFailure,
190
- setHomeProjectPermission,
191
- ProjectIdentityError,
192
- resolveProjectIdentityStrict,
193
- takeDubiousOwnershipProjectIdentityWarning,
194
- resolveProjectIdentity,
195
- resolveProjectIdentityForSession,
196
- beginBootQuietPeriod,
197
- bootQuietRemainingMs,
198
- scheduleAfterBootQuiet,
199
186
  startBootDeadline,
200
187
  getSchemaFenceRejection,
201
188
  setSqlitePragmaConfig,
@@ -204,7 +191,27 @@ import {
204
191
  openDatabaseAsync,
205
192
  isDatabasePersisted,
206
193
  getDatabasePersistenceError
207
- } from "./index-r5hmbx3t.js";
194
+ } from "./index-rrrsepyw.js";
195
+ import {
196
+ setHomeProjectPermission,
197
+ ProjectIdentityError,
198
+ resolveProjectIdentityStrict,
199
+ takeDubiousOwnershipProjectIdentityWarning,
200
+ resolveProjectIdentity,
201
+ resolveProjectIdentityForSession,
202
+ beginBootQuietPeriod,
203
+ bootQuietRemainingMs,
204
+ scheduleAfterBootQuiet
205
+ } from "./index-x3kwrmqk.js";
206
+ import {
207
+ observeSessionActivity,
208
+ backfillSessionActivity,
209
+ recordSessionProjectIdentity,
210
+ deleteIndexedMessage,
211
+ getProjectEmbeddingSnapshot,
212
+ getEmbeddingCoverageStatus,
213
+ getAutoEmbeddingSessionCoverage
214
+ } from "./index-fnn5pjtt.js";
208
215
  import {
209
216
  deleteTemporalDecision,
210
217
  getCurrentToolSetHash,
@@ -221,21 +228,25 @@ import {
221
228
  recordToolParameters,
222
229
  createDroppedInputToolExecuteBeforeHook,
223
230
  detectThinkingBindingMismatch,
231
+ detectLatestTurnThinkingMismatch,
224
232
  isPrefixBoundThinkingModel,
225
233
  detectOverflow,
234
+ isAnthropicFamilyRoute,
226
235
  readRawSessionMessages2
227
- } from "./index-3h0ybwah.js";
236
+ } from "./index-bb36vgr3.js";
228
237
  import {
229
- isEmbeddingHostBusy,
230
- sendCommandResult2,
231
- sendStatusNotification2
232
- } from "./index-7qw742ev.js";
238
+ isEmbeddingHostBusy
239
+ } from "./index-yr3zj7e7.js";
233
240
  import"./index-fzbvakh0.js";
234
241
  import {
235
242
  observeOpenCodeTurnEvent,
236
243
  clearTrackedOpenCodeSession,
237
244
  findLastAssistantModelFromOpenCodeDb
238
- } from "./index-majxda46.js";
245
+ } from "./index-6wkcswft.js";
246
+ import {
247
+ sendCommandResult2,
248
+ sendStatusNotification2
249
+ } from "./index-adwfkpex.js";
239
250
  import {
240
251
  detectConflicts,
241
252
  resolveCompactionForBoot
@@ -243,7 +254,7 @@ import {
243
254
  import {
244
255
  sendConflictWarning2,
245
256
  cleanupConflictWarnings2
246
- } from "./index-sfnj6h8h.js";
257
+ } from "./index-9pk9exrb.js";
247
258
  import"./index-1zx87sdm.js";
248
259
  import {
249
260
  resolveHistorianModel2,
@@ -257,16 +268,17 @@ import {
257
268
  import {
258
269
  pushNotification2
259
270
  } from "./index-x8a7jmkh.js";
271
+ import"./index-92bp57hg.js";
260
272
  import {
261
273
  createTagger,
262
274
  cavemanWordRulesForLanguage,
263
275
  setCtxReduceRegisteredGlobally,
264
276
  clearToolPermissionDenied,
265
277
  resetDegradedCacheCount2
266
- } from "./index-pkbcrdqs.js";
278
+ } from "./index-cwf6s3ay.js";
267
279
  import {
268
280
  runManagedRecomp2
269
- } from "./index-sgthv3f7.js";
281
+ } from "./index-gg8j07zz.js";
270
282
  import {
271
283
  isValidSemver,
272
284
  compareSemverCore
@@ -274,7 +286,7 @@ import {
274
286
  import"./index-fmsr7v69.js";
275
287
  import {
276
288
  runManagedWrapup2
277
- } from "./index-5p8jdswx.js";
289
+ } from "./index-5a2r0p9f.js";
278
290
  import {
279
291
  __toESM,
280
292
  __commonJS
@@ -9398,14 +9410,6 @@ function captureWindowReport(input) {
9398
9410
  }
9399
9411
 
9400
9412
  // src/hooks/magic-context/context-limit-resolution.ts
9401
- function provenFloorForModel(storedFloor, storedModelKey, modelKey) {
9402
- if (typeof storedFloor !== "number" || !Number.isFinite(storedFloor) || storedFloor <= 0) {
9403
- return 0;
9404
- }
9405
- if (!storedModelKey || !modelKey)
9406
- return 0;
9407
- return piModelRefToCanonical(storedModelKey) === piModelRefToCanonical(modelKey) ? storedFloor : 0;
9408
- }
9409
9413
  function describeContextLimitChange(previous, next) {
9410
9414
  if (previous.limit === next.limit && previous.modelKey === next.modelKey)
9411
9415
  return null;
@@ -9540,11 +9544,20 @@ function createEventHandler2(deps) {
9540
9544
  }
9541
9545
  recordPromptSessionError(errInfo.sessionID, errInfo.error);
9542
9546
  try {
9547
+ if (detectLatestTurnThinkingMismatch(errInfo.error)) {
9548
+ const model = findLastAssistantModelFromOpenCodeDb(errInfo.sessionID);
9549
+ if (!deps.compactionOff && isAnthropicFamilyRoute(model?.providerID, model?.modelID)) {
9550
+ armLatestThinkingRecovery(deps.db, errInfo.sessionID);
9551
+ dropSlot(errInfo.sessionID, "latest-thinking-recovery-arm");
9552
+ deps.onSessionCacheInvalidated?.(errInfo.sessionID);
9553
+ }
9554
+ return;
9555
+ }
9543
9556
  const bindingMismatch = detectThinkingBindingMismatch(errInfo.error);
9544
9557
  if (bindingMismatch.isBindingMismatch) {
9545
9558
  const model = findLastAssistantModelFromOpenCodeDb(errInfo.sessionID);
9546
9559
  if (deps.thinkingBindingRecoveryEnabled !== false && !deps.compactionOff && isPrefixBoundThinkingModel(model?.providerID, model?.modelID)) {
9547
- armThinkingBindingRecovery(deps.db, errInfo.sessionID);
9560
+ armBindingRecoverySafely(deps.db, errInfo.sessionID);
9548
9561
  sessionLog(errInfo.sessionID, `thinking binding recovery armed from session.error (provider paths: failing=${bindingMismatch.failingBlockPath ?? "?"} firstChanged=${bindingMismatch.firstChangedPath ?? "?"})`);
9549
9562
  dropSlot(errInfo.sessionID, "thinking-binding-recovery-arm");
9550
9563
  deps.onSessionCacheInvalidated?.(errInfo.sessionID);
@@ -9651,10 +9664,16 @@ function createEventHandler2(deps) {
9651
9664
  }
9652
9665
  let messageHadOverflowError = false;
9653
9666
  if (info.error !== undefined && info.error !== null) {
9667
+ if (detectLatestTurnThinkingMismatch(info.error) && !deps.compactionOff && isAnthropicFamilyRoute(info.providerID, info.modelID)) {
9668
+ armLatestThinkingRecovery(deps.db, info.sessionID);
9669
+ dropSlot(info.sessionID, "latest-thinking-recovery-arm");
9670
+ deps.onSessionCacheInvalidated?.(info.sessionID);
9671
+ return;
9672
+ }
9654
9673
  const bindingMismatch = detectThinkingBindingMismatch(info.error);
9655
9674
  if (bindingMismatch.isBindingMismatch && deps.thinkingBindingRecoveryEnabled !== false && !deps.compactionOff && isPrefixBoundThinkingModel(info.providerID, info.modelID)) {
9656
9675
  try {
9657
- armThinkingBindingRecovery(deps.db, info.sessionID);
9676
+ armBindingRecoverySafely(deps.db, info.sessionID);
9658
9677
  sessionLog(info.sessionID, `thinking binding recovery armed from message.updated (provider paths: failing=${bindingMismatch.failingBlockPath ?? "?"} firstChanged=${bindingMismatch.firstChangedPath ?? "?"})`);
9659
9678
  dropSlot(info.sessionID, "thinking-binding-recovery-arm");
9660
9679
  deps.onSessionCacheInvalidated?.(info.sessionID);
@@ -9786,7 +9805,7 @@ function createEventHandler2(deps) {
9786
9805
  let refreshLimitsAfterRecording;
9787
9806
  if (hasUsageTokens) {
9788
9807
  const pressureInputTokens = totalInputTokens;
9789
- const requestSucceeded = !messageHadOverflowError;
9808
+ const requestSucceeded = !messageHadOverflowError && !responseFailed;
9790
9809
  const successfulUsageProof = requestSucceeded && !aboveTrustedWall;
9791
9810
  if (requestSucceeded) {
9792
9811
  const rawOverflow = getOverflowState(deps.db, info.sessionID);
@@ -9801,7 +9820,7 @@ function createEventHandler2(deps) {
9801
9820
  if (!responseFailed) {
9802
9821
  updates.lastResponseTime = Math.max(sessionMeta.lastResponseTime, responseTime);
9803
9822
  }
9804
- const observedSafeInputTokens = provenFloorForModel(sessionMeta.observedSafeInputTokens, sessionMeta.lastObservedModelKey, modelKey);
9823
+ const observedSafeInputTokens = resolveOpenCodeProvenInputFloor(deps.db, info.sessionID, modelKey);
9805
9824
  const provenSafeInputTokens = successfulUsageProof ? Math.max(observedSafeInputTokens, pressureInputTokens) : observedSafeInputTokens;
9806
9825
  const readCatalogLimit = () => info.providerID && info.modelID ? getSdkContextLimit(info.providerID, info.modelID) : undefined;
9807
9826
  const resolvePressure = () => {
@@ -9890,6 +9909,9 @@ function createEventHandler2(deps) {
9890
9909
  };
9891
9910
  }
9892
9911
  updateSessionMeta(deps.db, info.sessionID, updates);
9912
+ if (modelKey && updates.observedSafeInputTokens !== undefined) {
9913
+ recordOpenCodeProvenInputFloor(deps.db, info.sessionID, modelKey, updates.observedSafeInputTokens);
9914
+ }
9893
9915
  if (refreshLimitsAfterRecording) {
9894
9916
  await refreshLimitsAfterRecording();
9895
9917
  }
@@ -10343,7 +10365,7 @@ function createMagicContextHook(deps) {
10343
10365
  protectedTokens: deps.config.protected_tokens,
10344
10366
  protectedTokenTierOverrides: deps.config.protectedTokenTierOverrides,
10345
10367
  protectedTools: deps.config.protected_tools,
10346
- clearReasoningAge: deps.config.clear_reasoning_age ?? 50,
10368
+ keepReasoningTokens: deps.config.keep_reasoning_tokens,
10347
10369
  commitClusterTrigger: bootHistorian.commitClusterTrigger,
10348
10370
  historyRefreshSessions,
10349
10371
  deferredHistoryRefreshSessions,
@@ -10794,10 +10816,546 @@ async function createSessionHooksAsync(args) {
10794
10816
  };
10795
10817
  }
10796
10818
 
10819
+ // src/plugin/host-stall-profiler.ts
10820
+ import { chmodSync, existsSync as existsSync5, readdirSync, readFileSync as readFileSync5, unlinkSync } from "node:fs";
10821
+ import * as path4 from "node:path";
10822
+
10823
+ // src/plugin/host-stall-profiler-report.ts
10824
+ import { readFileSync as readFileSync4 } from "node:fs";
10825
+ import * as path3 from "node:path";
10826
+ var MAX_STACK_DEPTH = 64;
10827
+ var TOP_STACK_COUNT = 30;
10828
+ var TOP_FRAME_COUNT = 30;
10829
+ var UNKNOWN_POSITION = 4294967295;
10830
+ var BACKGROUND_OWNERS = new Set(["native", "runtime", "opencode"]);
10831
+ var packageNameCache = new Map;
10832
+ function urlToPath(url) {
10833
+ if (url.startsWith("file://")) {
10834
+ try {
10835
+ return decodeURIComponent(new URL(url).pathname);
10836
+ } catch {
10837
+ return url.slice("file://".length);
10838
+ }
10839
+ }
10840
+ return url;
10841
+ }
10842
+ function nearestPackageName(filePath) {
10843
+ let dir = path3.dirname(filePath);
10844
+ const visited = [];
10845
+ for (let depth = 0;depth < 12; depth++) {
10846
+ const cached = packageNameCache.get(dir);
10847
+ if (cached !== undefined) {
10848
+ for (const seen of visited)
10849
+ packageNameCache.set(seen, cached);
10850
+ return cached;
10851
+ }
10852
+ visited.push(dir);
10853
+ try {
10854
+ const parsed = JSON.parse(readFileSync4(path3.join(dir, "package.json"), "utf8"));
10855
+ const name = typeof parsed.name === "string" && parsed.name ? parsed.name : null;
10856
+ if (name) {
10857
+ for (const seen of visited)
10858
+ packageNameCache.set(seen, name);
10859
+ return name;
10860
+ }
10861
+ } catch {}
10862
+ const parent = path3.dirname(dir);
10863
+ if (parent === dir)
10864
+ break;
10865
+ dir = parent;
10866
+ }
10867
+ for (const seen of visited)
10868
+ packageNameCache.set(seen, null);
10869
+ return null;
10870
+ }
10871
+ function sourceOwner(sourceURL) {
10872
+ if (!sourceURL)
10873
+ return "native";
10874
+ if (/^(?:node|bun|builtin|internal):/.test(sourceURL))
10875
+ return "runtime";
10876
+ if (sourceURL.includes("$bunfs") || sourceURL.includes("~BUN"))
10877
+ return "opencode";
10878
+ const filePath = urlToPath(sourceURL).replaceAll("\\", "/");
10879
+ const modules = [...filePath.matchAll(/\/node_modules\/((?:@[^/]+\/)?[^/]+)/g)];
10880
+ const innermost = modules.at(-1);
10881
+ if (innermost)
10882
+ return `npm:${innermost[1]}`;
10883
+ const pluginDir = filePath.match(/\/plugins?\/([^/]+)$/);
10884
+ if (pluginDir && /\/(?:\.?opencode)\/plugins?\//.test(filePath)) {
10885
+ return `plugin:${pluginDir[1]}`;
10886
+ }
10887
+ const name = nearestPackageName(filePath);
10888
+ return name ? `pkg:${name}` : `file:${filePath}`;
10889
+ }
10890
+ function frameLabel(frame) {
10891
+ const name = frame.name && frame.name.length > 0 ? frame.name : "(anonymous)";
10892
+ if (!frame.sourceURL)
10893
+ return `${name} [native]`;
10894
+ const line = typeof frame.line === "number" && frame.line !== UNKNOWN_POSITION ? `:${frame.line}` : "";
10895
+ return `${name} ${frame.sourceURL}${line}`;
10896
+ }
10897
+ function attributeSample(frames) {
10898
+ for (const frame of frames) {
10899
+ if (!BACKGROUND_OWNERS.has(frame.owner))
10900
+ return frame.owner;
10901
+ }
10902
+ for (const frame of frames) {
10903
+ if (frame.owner !== "native")
10904
+ return frame.owner;
10905
+ }
10906
+ return "native";
10907
+ }
10908
+ function bump(map, key, init) {
10909
+ const existing = map.get(key);
10910
+ if (existing)
10911
+ existing.samples += 1;
10912
+ else
10913
+ map.set(key, { ...init(), samples: 1 });
10914
+ }
10915
+ function topBySamples(values, limit) {
10916
+ return [...values].sort((a, b) => b.samples - a.samples).slice(0, limit);
10917
+ }
10918
+ function aggregateTraces(traces) {
10919
+ const ownerOf = new Map;
10920
+ const owned = (frame) => {
10921
+ const url = frame.sourceURL ?? "";
10922
+ let owner = ownerOf.get(url);
10923
+ if (owner === undefined) {
10924
+ owner = sourceOwner(frame.sourceURL);
10925
+ ownerOf.set(url, owner);
10926
+ }
10927
+ return { label: frameLabel(frame), owner };
10928
+ };
10929
+ const owners = new Map;
10930
+ const topFrames = new Map;
10931
+ const topJsFrames = new Map;
10932
+ const stacks = new Map;
10933
+ let samples = 0;
10934
+ for (const trace of traces) {
10935
+ const raw = Array.isArray(trace.frames) ? trace.frames : [];
10936
+ if (raw.length === 0)
10937
+ continue;
10938
+ samples += 1;
10939
+ const frames = raw.slice(0, MAX_STACK_DEPTH).map(owned);
10940
+ const owner = attributeSample(frames);
10941
+ bump(owners, owner, () => ({ owner }));
10942
+ const leaf = frames[0];
10943
+ bump(topFrames, `${leaf.owner}\x00${leaf.label}`, () => ({
10944
+ frame: leaf.label,
10945
+ owner: leaf.owner
10946
+ }));
10947
+ const jsIndex = raw.findIndex((frame, index) => index < MAX_STACK_DEPTH && !!frame.sourceURL);
10948
+ if (jsIndex >= 0) {
10949
+ const js = frames[jsIndex];
10950
+ bump(topJsFrames, `${js.owner}\x00${js.label}`, () => ({
10951
+ frame: js.label,
10952
+ owner: js.owner
10953
+ }));
10954
+ }
10955
+ const labels = frames.map((frame) => `${frame.label} (${frame.owner})`);
10956
+ if (raw.length > MAX_STACK_DEPTH) {
10957
+ labels.push(`… ${raw.length - MAX_STACK_DEPTH} outer frames omitted`);
10958
+ }
10959
+ bump(stacks, labels.join(`
10960
+ `), () => ({ owner, frames: labels }));
10961
+ }
10962
+ return {
10963
+ samples,
10964
+ owners: topBySamples(owners.values(), Number.POSITIVE_INFINITY).map((entry) => ({
10965
+ ...entry,
10966
+ percent: samples === 0 ? 0 : Math.round(entry.samples / samples * 1000) / 10
10967
+ })),
10968
+ top_frames: topBySamples(topFrames.values(), TOP_FRAME_COUNT),
10969
+ top_js_frames: topBySamples(topJsFrames.values(), TOP_FRAME_COUNT),
10970
+ top_stacks: topBySamples(stacks.values(), TOP_STACK_COUNT)
10971
+ };
10972
+ }
10973
+
10974
+ // src/plugin/host-stall-profiler.ts
10975
+ var HOST_PROFILER_DIRNAME = "host-profiler";
10976
+ var HOST_PROFILER_ENABLE_FILENAME = "enable";
10977
+ var SWITCH_POLL_MS = 30000;
10978
+ var WATCHDOG_INTERVAL_MS = 250;
10979
+ var DEFAULT_STALL_THRESHOLD_MS = 3000;
10980
+ var DEFAULT_SAMPLE_INTERVAL_MS = 10;
10981
+ var MAX_REPORT_FILES = 50;
10982
+ var MAX_SAMPLES_PER_WINDOW = 20000;
10983
+ var MEMORY_SNAPSHOT_EVERY_TICKS = 4;
10984
+ var CALIBRATION_CHUNK_MS = 3;
10985
+ var CALIBRATION_MAX_CHUNKS = 30;
10986
+ function clamp(value, min, max) {
10987
+ return Math.min(max, Math.max(min, value));
10988
+ }
10989
+ function parseEnableFile(content) {
10990
+ const options = {
10991
+ thresholdMs: DEFAULT_STALL_THRESHOLD_MS,
10992
+ sampleIntervalMs: DEFAULT_SAMPLE_INTERVAL_MS
10993
+ };
10994
+ const trimmed = content.trim();
10995
+ if (trimmed === "")
10996
+ return { options, error: null };
10997
+ try {
10998
+ const parsed = JSON.parse(trimmed);
10999
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
11000
+ return { options, error: "enable file is not a JSON object" };
11001
+ }
11002
+ if (typeof parsed.threshold_ms === "number" && Number.isFinite(parsed.threshold_ms)) {
11003
+ options.thresholdMs = clamp(parsed.threshold_ms, 500, 600000);
11004
+ }
11005
+ if (typeof parsed.sample_interval_ms === "number" && Number.isFinite(parsed.sample_interval_ms)) {
11006
+ options.sampleIntervalMs = clamp(parsed.sample_interval_ms, 1, 100);
11007
+ }
11008
+ return { options, error: null };
11009
+ } catch (error) {
11010
+ return {
11011
+ options,
11012
+ error: `enable file is not valid JSON (${error instanceof Error ? error.message : String(error)})`
11013
+ };
11014
+ }
11015
+ }
11016
+ function asJscApi(module) {
11017
+ const candidate = module ?? null;
11018
+ for (const value of [candidate, candidate?.default]) {
11019
+ const api = value;
11020
+ if (api && typeof api.startSamplingProfiler === "function" && typeof api.samplingProfilerStackTraces === "function" && typeof api.profile === "function") {
11021
+ return api;
11022
+ }
11023
+ }
11024
+ return null;
11025
+ }
11026
+ function thin(items, limit) {
11027
+ if (items.length <= limit)
11028
+ return items;
11029
+ const stride = items.length / limit;
11030
+ const out = [];
11031
+ for (let i = 0;i < limit; i++)
11032
+ out.push(items[Math.floor(i * stride)]);
11033
+ return out;
11034
+ }
11035
+ function reportFileStamp(epochMs) {
11036
+ return new Date(epochMs).toISOString().replaceAll(":", "-");
11037
+ }
11038
+ function createHostStallProfiler(deps) {
11039
+ let jsc = null;
11040
+ let unavailable = false;
11041
+ let pollTimer = null;
11042
+ let watchdog = null;
11043
+ let options = {
11044
+ thresholdMs: DEFAULT_STALL_THRESHOLD_MS,
11045
+ sampleIntervalMs: DEFAULT_SAMPLE_INTERVAL_MS
11046
+ };
11047
+ let lastTickAt = 0;
11048
+ let tickCount = 0;
11049
+ let memoryBefore = null;
11050
+ let clockOffsetMs = null;
11051
+ let checking = null;
11052
+ const loggedOnce = new Set;
11053
+ const safeLog = (message) => {
11054
+ try {
11055
+ deps.log(message);
11056
+ } catch {}
11057
+ };
11058
+ const logOnce = (key, message, error) => {
11059
+ if (loggedOnce.has(key))
11060
+ return;
11061
+ loggedOnce.add(key);
11062
+ const detail = error === undefined ? "" : `: ${error instanceof Error ? error.message : String(error)}`;
11063
+ safeLog(`[magic-context] host stall profiler: ${message}${detail}`);
11064
+ };
11065
+ const drain = (api) => {
11066
+ const raw = api.samplingProfilerStackTraces();
11067
+ return Array.isArray(raw?.traces) ? raw.traces : [];
11068
+ };
11069
+ const pauseSampler = (api, intervalMs) => {
11070
+ try {
11071
+ drain(api);
11072
+ } catch {}
11073
+ api.profile(() => {
11074
+ return;
11075
+ }, Math.round(intervalMs * 1000));
11076
+ drain(api);
11077
+ };
11078
+ const calibrate = (api) => {
11079
+ pauseSampler(api, 1);
11080
+ api.startSamplingProfiler();
11081
+ let offset = null;
11082
+ for (let chunk = 0;chunk < CALIBRATION_MAX_CHUNKS && offset === null; chunk++) {
11083
+ const start = deps.now();
11084
+ let end = start;
11085
+ for (let i = 0;i < 50000000 && end - start < CALIBRATION_CHUNK_MS; i++) {
11086
+ end = deps.now();
11087
+ }
11088
+ const stamps = drain(api).map((trace) => trace.timestamp).filter((value) => typeof value === "number" && Number.isFinite(value)).map((seconds) => seconds * 1000);
11089
+ if (stamps.length >= 2) {
11090
+ offset = (Math.max(...stamps) - end + (Math.min(...stamps) - start)) / 2;
11091
+ }
11092
+ }
11093
+ pauseSampler(api, 1);
11094
+ return offset;
11095
+ };
11096
+ const snapshot = (api) => {
11097
+ const read = (fn) => {
11098
+ try {
11099
+ return fn();
11100
+ } catch {
11101
+ return null;
11102
+ }
11103
+ };
11104
+ return {
11105
+ at: new Date(deps.wallNow()).toISOString(),
11106
+ heap_size_bytes: read(() => api.heapSize?.() ?? null),
11107
+ jsc_memory: read(() => api.memoryUsage?.() ?? null),
11108
+ rss_bytes: read(() => deps.rss()),
11109
+ percent_available_memory_in_use: read(() => api.percentAvailableMemoryInUse?.() ?? null)
11110
+ };
11111
+ };
11112
+ const writeReport = (report, endWallMs) => {
11113
+ const dir = deps.profilerDir();
11114
+ ensureStorageDirectorySync(dir, true);
11115
+ chmodSync(dir, 448);
11116
+ const stamp = reportFileStamp(endWallMs);
11117
+ let name = `stall-${stamp}.json`;
11118
+ for (let n = 1;existsSync5(path4.join(dir, name)); n++)
11119
+ name = `stall-${stamp}-${n}.json`;
11120
+ const finalPath = path4.join(dir, name);
11121
+ writeStorageFileAtomicSync(finalPath, `${JSON.stringify(report, null, 2)}
11122
+ `, true);
11123
+ const reports = readdirSync(dir).filter((entry) => /^stall-.*\.json$/.test(entry)).sort();
11124
+ for (const stale of reports.slice(0, Math.max(0, reports.length - MAX_REPORT_FILES))) {
11125
+ try {
11126
+ unlinkSync(path4.join(dir, stale));
11127
+ } catch (error) {
11128
+ logOnce("prune", "could not prune an old report", error);
11129
+ }
11130
+ }
11131
+ return finalPath;
11132
+ };
11133
+ const recordStall = (api, startMs, endMs, traces) => {
11134
+ const after = snapshot(api);
11135
+ const gapMs = endMs - startMs;
11136
+ let windowed = traces;
11137
+ let windowFilter = "since-last-collection";
11138
+ if (clockOffsetMs !== null) {
11139
+ const slackMs = 2 * options.sampleIntervalMs + 20;
11140
+ const lo = startMs + clockOffsetMs - slackMs;
11141
+ const hi = endMs + clockOffsetMs + slackMs;
11142
+ const inWindow = traces.filter((trace) => {
11143
+ const at = typeof trace.timestamp === "number" ? trace.timestamp * 1000 : Number.NaN;
11144
+ return at >= lo && at <= hi;
11145
+ });
11146
+ if (inWindow.length > 0 || traces.length === 0) {
11147
+ windowed = inWindow;
11148
+ windowFilter = "timestamp";
11149
+ } else {
11150
+ windowFilter = "since-last-collection (timestamp filter matched no sample)";
11151
+ }
11152
+ }
11153
+ const kept = thin(windowed, MAX_SAMPLES_PER_WINDOW);
11154
+ const aggregate = aggregateTraces(kept);
11155
+ const endWallMs = deps.wallNow();
11156
+ const startWallMs = endWallMs - gapMs;
11157
+ const report = {
11158
+ kind: "magic-context-host-stall",
11159
+ schema_version: 1,
11160
+ pid: deps.pid,
11161
+ bun_version: deps.bunVersion,
11162
+ platform: process.platform,
11163
+ window: {
11164
+ start: new Date(startWallMs).toISOString(),
11165
+ end: new Date(endWallMs).toISOString(),
11166
+ duration_ms: Math.round(gapMs),
11167
+ lag_ms: Math.round(gapMs - WATCHDOG_INTERVAL_MS),
11168
+ threshold_ms: options.thresholdMs
11169
+ },
11170
+ sampling: {
11171
+ interval_ms: options.sampleIntervalMs,
11172
+ samples_collected: traces.length,
11173
+ samples_in_window: windowed.length,
11174
+ samples_aggregated: kept.length,
11175
+ window_filter: windowFilter,
11176
+ note: aggregate.samples === 0 ? "No JavaScript samples in the window: the main thread was not executing inside the JavaScript VM (idle wait, process suspension, or native work outside any JS call)." : undefined
11177
+ },
11178
+ memory: { before: memoryBefore, after },
11179
+ owners: aggregate.owners,
11180
+ top_frames: aggregate.top_frames,
11181
+ top_js_frames: aggregate.top_js_frames,
11182
+ top_stacks: aggregate.top_stacks
11183
+ };
11184
+ const file = writeReport(report, endWallMs);
11185
+ const top = aggregate.owners[0];
11186
+ safeLog(`[magic-context] host stall profiler: ${Math.round(gapMs)}ms main-thread stall, ${aggregate.samples} samples, top owner ${top ? `${top.owner} (${top.percent}%)` : "none"} → ${file}`);
11187
+ memoryBefore = after;
11188
+ };
11189
+ const tick = () => {
11190
+ const api = jsc;
11191
+ if (!api || watchdog === null)
11192
+ return;
11193
+ try {
11194
+ const now = deps.now();
11195
+ const startMs = lastTickAt;
11196
+ lastTickAt = now;
11197
+ const traces = drain(api);
11198
+ if (now - startMs > options.thresholdMs) {
11199
+ try {
11200
+ recordStall(api, startMs, now, traces);
11201
+ } catch (error) {
11202
+ logOnce("report", "could not write a stall report", error);
11203
+ }
11204
+ }
11205
+ tickCount += 1;
11206
+ if (tickCount % MEMORY_SNAPSHOT_EVERY_TICKS === 0)
11207
+ memoryBefore = snapshot(api);
11208
+ } catch (error) {
11209
+ logOnce("tick", "watchdog tick failed", error);
11210
+ }
11211
+ };
11212
+ const enable = (api, next) => {
11213
+ const startedAt = deps.now();
11214
+ try {
11215
+ options = next;
11216
+ clockOffsetMs = calibrate(api);
11217
+ pauseSampler(api, options.sampleIntervalMs);
11218
+ api.startSamplingProfiler();
11219
+ lastTickAt = deps.now();
11220
+ tickCount = 0;
11221
+ memoryBefore = snapshot(api);
11222
+ watchdog = deps.setInterval(tick, WATCHDOG_INTERVAL_MS);
11223
+ safeLog(`[magic-context] host stall profiler enabled: threshold ${options.thresholdMs}ms, sample interval ${options.sampleIntervalMs}ms, clock calibration ${clockOffsetMs === null ? "unavailable" : "ok"}, setup ${Math.round(deps.now() - startedAt)}ms, reports in ${deps.profilerDir()}`);
11224
+ } catch (error) {
11225
+ watchdog = null;
11226
+ try {
11227
+ pauseSampler(api, options.sampleIntervalMs);
11228
+ } catch {}
11229
+ logOnce("enable", "could not start", error);
11230
+ }
11231
+ };
11232
+ const disable = (reason) => {
11233
+ if (watchdog !== null)
11234
+ deps.clearInterval(watchdog);
11235
+ watchdog = null;
11236
+ memoryBefore = null;
11237
+ if (jsc) {
11238
+ try {
11239
+ pauseSampler(jsc, options.sampleIntervalMs);
11240
+ } catch (error) {
11241
+ logOnce("disable", "could not pause the sampler", error);
11242
+ }
11243
+ }
11244
+ safeLog(`[magic-context] host stall profiler disabled: ${reason}`);
11245
+ };
11246
+ const ensureJsc = async () => {
11247
+ if (jsc)
11248
+ return jsc;
11249
+ try {
11250
+ const api = asJscApi(await deps.loadJsc());
11251
+ if (!api)
11252
+ throw new Error("bun:jsc lacks the sampling profiler API");
11253
+ jsc = api;
11254
+ return api;
11255
+ } catch (error) {
11256
+ unavailable = true;
11257
+ if (pollTimer !== null)
11258
+ deps.clearInterval(pollTimer);
11259
+ pollTimer = null;
11260
+ logOnce("jsc", "bun:jsc is unavailable, profiler disabled for this process", error);
11261
+ return null;
11262
+ }
11263
+ };
11264
+ const runCheck = async () => {
11265
+ if (unavailable)
11266
+ return;
11267
+ try {
11268
+ const enablePath = path4.join(deps.profilerDir(), HOST_PROFILER_ENABLE_FILENAME);
11269
+ if (!existsSync5(enablePath)) {
11270
+ if (watchdog !== null)
11271
+ disable("enable file removed");
11272
+ return;
11273
+ }
11274
+ const parsed = parseEnableFile(readFileSync5(enablePath, "utf8"));
11275
+ if (parsed.error)
11276
+ logOnce(`options:${parsed.error}`, parsed.error);
11277
+ if (watchdog !== null) {
11278
+ if (jsc && parsed.options.sampleIntervalMs !== options.sampleIntervalMs) {
11279
+ pauseSampler(jsc, parsed.options.sampleIntervalMs);
11280
+ jsc.startSamplingProfiler();
11281
+ }
11282
+ options = parsed.options;
11283
+ return;
11284
+ }
11285
+ const api = await ensureJsc();
11286
+ if (!api || watchdog !== null || !existsSync5(enablePath))
11287
+ return;
11288
+ enable(api, parsed.options);
11289
+ } catch (error) {
11290
+ logOnce("check", "enable-file check failed", error);
11291
+ }
11292
+ };
11293
+ const checkNow = () => {
11294
+ if (!checking) {
11295
+ checking = runCheck().finally(() => {
11296
+ checking = null;
11297
+ });
11298
+ }
11299
+ return checking;
11300
+ };
11301
+ return {
11302
+ start() {
11303
+ if (pollTimer !== null || unavailable)
11304
+ return;
11305
+ pollTimer = deps.setInterval(() => void checkNow(), SWITCH_POLL_MS);
11306
+ checkNow();
11307
+ },
11308
+ checkNow,
11309
+ stop() {
11310
+ if (pollTimer !== null)
11311
+ deps.clearInterval(pollTimer);
11312
+ pollTimer = null;
11313
+ if (watchdog !== null)
11314
+ disable("stopped");
11315
+ },
11316
+ isActive: () => watchdog !== null,
11317
+ isUnavailable: () => unavailable
11318
+ };
11319
+ }
11320
+ function hostStallProfilerDir() {
11321
+ return path4.join(getMagicContextStorageDir(), HOST_PROFILER_DIRNAME);
11322
+ }
11323
+ function defaultDeps() {
11324
+ return {
11325
+ profilerDir: hostStallProfilerDir,
11326
+ loadJsc: () => import("bun:jsc"),
11327
+ now: () => performance.now(),
11328
+ wallNow: () => Date.now(),
11329
+ setInterval: (callback, ms) => {
11330
+ const handle = setInterval(callback, ms);
11331
+ handle.unref?.();
11332
+ return handle;
11333
+ },
11334
+ clearInterval: (handle) => clearInterval(handle),
11335
+ rss: () => process.memoryUsage.rss(),
11336
+ log,
11337
+ pid: process.pid,
11338
+ bunVersion: process.versions.bun ?? null
11339
+ };
11340
+ }
11341
+ var PROCESS_PROFILER_KEY = Symbol.for("cortexkit.magic-context.host-stall-profiler");
11342
+ function startHostStallProfilerSwitch() {
11343
+ try {
11344
+ const holder = globalThis;
11345
+ if (holder[PROCESS_PROFILER_KEY])
11346
+ return;
11347
+ const handle = createHostStallProfiler(defaultDeps());
11348
+ holder[PROCESS_PROFILER_KEY] = handle;
11349
+ handle.start();
11350
+ } catch (error) {
11351
+ log("[magic-context] host stall profiler: could not start the enable-file switch", error);
11352
+ }
11353
+ }
11354
+
10797
11355
  // src/plugin/instance-disposal.ts
10798
- import path3 from "node:path";
11356
+ import path5 from "node:path";
10799
11357
  function isDisposedInstanceDirectory(ownDirectory, disposedDirectory) {
10800
- return path3.resolve(disposedDirectory) === path3.resolve(ownDirectory);
11358
+ return path5.resolve(disposedDirectory) === path5.resolve(ownDirectory);
10801
11359
  }
10802
11360
 
10803
11361
  // src/plugin/native-compaction-guard.ts
@@ -10981,26 +11539,26 @@ function unregisterExitAbort(controller) {
10981
11539
  }
10982
11540
 
10983
11541
  // src/v2/hooks/update-check.ts
10984
- import { existsSync as existsSync5, readFileSync as readFileSync4 } from "node:fs";
10985
- import { dirname as dirname3, join as join5 } from "node:path";
11542
+ import { existsSync as existsSync6, readFileSync as readFileSync6 } from "node:fs";
11543
+ import { dirname as dirname4, join as join7 } from "node:path";
10986
11544
  import { fileURLToPath as fileURLToPath2 } from "node:url";
10987
11545
  var cachedPackageInfo;
10988
11546
  function packageInfo() {
10989
11547
  if (cachedPackageInfo)
10990
11548
  return cachedPackageInfo;
10991
- let directory = dirname3(fileURLToPath2(import.meta.url));
11549
+ let directory = dirname4(fileURLToPath2(import.meta.url));
10992
11550
  for (;; ) {
10993
11551
  try {
10994
- const pkg = JSON.parse(readFileSync4(join5(directory, "package.json"), "utf8"));
11552
+ const pkg = JSON.parse(readFileSync6(join7(directory, "package.json"), "utf8"));
10995
11553
  if (pkg.name === "@cortexkit/opencode-magic-context" && typeof pkg.version === "string") {
10996
11554
  cachedPackageInfo = {
10997
11555
  version: pkg.version,
10998
- development: existsSync5(join5(directory, "src/v2/server.ts"))
11556
+ development: existsSync6(join7(directory, "src/v2/server.ts"))
10999
11557
  };
11000
11558
  return cachedPackageInfo;
11001
11559
  }
11002
11560
  } catch {}
11003
- const parent = dirname3(directory);
11561
+ const parent = dirname4(directory);
11004
11562
  if (parent === directory)
11005
11563
  throw new Error("Magic Context package manifest is unavailable");
11006
11564
  directory = parent;
@@ -11065,7 +11623,7 @@ async function setup(context) {
11065
11623
  log("v2 setup() called on a host without session.hook; v1 server lane owns this host, v2 lane inert");
11066
11624
  return async () => {};
11067
11625
  }
11068
- const { registerContext } = await import("./context-sh2m2vde.js");
11626
+ const { registerContext } = await import("./context-wq4ffwyb.js");
11069
11627
  setHarness("opencode2");
11070
11628
  bindStaleBuildNotice({}, import.meta.url, "opencode2");
11071
11629
  const duties = await registerContext(context);
@@ -11093,6 +11651,7 @@ var server = async (ctx) => {
11093
11651
  let deadlinePhase = null;
11094
11652
  emitBootEnteringBreadcrumb(process.pid, ctx.directory, log, flushLogger);
11095
11653
  setHarness("opencode");
11654
+ startHostStallProfilerSwitch();
11096
11655
  const configStartedAt = performance.now();
11097
11656
  beginBootQuietPeriod();
11098
11657
  const configMigrationWarnings = migrateMagicContextConfigLocations(ctx.directory, {
@@ -11135,7 +11694,7 @@ var server = async (ctx) => {
11135
11694
  if (hasBannerEntries)
11136
11695
  setTimeout(async () => {
11137
11696
  try {
11138
- const { sendStatusNotification } = await importPluginModule(() => import("./send-session-notification-dyw42dtr.js"));
11697
+ const { sendStatusNotification } = await importPluginModule(() => import("./send-session-notification-0m68ms3n.js"));
11139
11698
  const clientWithSessions = ctx.client;
11140
11699
  const sessions = await Promise.resolve(clientWithSessions.session?.list?.()).catch(() => null);
11141
11700
  const sessionList = Array.isArray(sessions) ? sessions : sessions?.data;
@@ -11152,7 +11711,7 @@ var server = async (ctx) => {
11152
11711
  log(`[magic-context] opencode_db_missing path=${openCodeDbResolution.path} source=${openCodeDbResolution.source}`);
11153
11712
  setTimeout(async () => {
11154
11713
  try {
11155
- const { sendStatusNotification } = await importPluginModule(() => import("./send-session-notification-dyw42dtr.js"));
11714
+ const { sendStatusNotification } = await importPluginModule(() => import("./send-session-notification-0m68ms3n.js"));
11156
11715
  const clientWithSessions = ctx.client;
11157
11716
  const sessions = await Promise.resolve(clientWithSessions.session?.list?.()).catch(() => null);
11158
11717
  const sessionList = Array.isArray(sessions) ? sessions : sessions?.data;
@@ -11427,12 +11986,12 @@ var server = async (ctx) => {
11427
11986
  {
11428
11987
  const fence = getSchemaFenceRejection();
11429
11988
  if (fence) {
11430
- importPluginModule(() => import("./conflict-warning-hook-7fj2b9jw.js")).then(({ sendSchemaFenceWarning }) => sendSchemaFenceWarning(ctx.client, ctx.directory, fence)).catch((error) => log("[magic-context] schema-fence warning unavailable:", error));
11989
+ importPluginModule(() => import("./conflict-warning-hook-z44ynfz7.js")).then(({ sendSchemaFenceWarning }) => sendSchemaFenceWarning(ctx.client, ctx.directory, fence)).catch((error) => log("[magic-context] schema-fence warning unavailable:", error));
11431
11990
  }
11432
11991
  }
11433
11992
  const serverUrl = ctx.serverUrl;
11434
11993
  const serverUrlStr = serverUrl instanceof URL ? serverUrl.toString().replace(/\/$/, "") : typeof serverUrl === "string" ? serverUrl.replace(/\/$/, "") : undefined;
11435
- importPluginModule(() => import("./send-session-notification-dyw42dtr.js")).then(({ setNotificationServerUrl }) => {
11994
+ importPluginModule(() => import("./send-session-notification-0m68ms3n.js")).then(({ setNotificationServerUrl }) => {
11436
11995
  setNotificationServerUrl(serverUrlStr);
11437
11996
  }).catch((error) => log("[magic-context] notification transport unavailable:", error));
11438
11997
  if (conflictResult?.hasConflict) {
@@ -11455,7 +12014,7 @@ var server = async (ctx) => {
11455
12014
  }) => {
11456
12015
  if (!shouldShowAnnouncement())
11457
12016
  return;
11458
- return importPluginModule(() => import("./conflict-warning-hook-7fj2b9jw.js")).then(({ sendStartupAnnouncement }) => sendStartupAnnouncement(ctx.client, ctx.directory, ANNOUNCEMENT_VERSION, ANNOUNCEMENT_FEATURES, ANNOUNCEMENT_FOOTER, markAnnouncementSeen));
12017
+ return importPluginModule(() => import("./conflict-warning-hook-z44ynfz7.js")).then(({ sendStartupAnnouncement }) => sendStartupAnnouncement(ctx.client, ctx.directory, ANNOUNCEMENT_VERSION, ANNOUNCEMENT_FEATURES, ANNOUNCEMENT_FOOTER, markAnnouncementSeen));
11459
12018
  }).catch(() => {});
11460
12019
  }, 8000);
11461
12020
  }
@@ -11537,8 +12096,8 @@ var server = async (ctx) => {
11537
12096
  gate: checkoutClaimGate,
11538
12097
  projectRoot: ctx.directory,
11539
12098
  onRefusal: async (sessionId, message) => {
11540
- const { sendStatusNotification } = await importPluginModule(() => import("./send-session-notification-dyw42dtr.js"));
11541
- const { abortSessionFailClosed } = await importPluginModule(() => import("./transform-postprocess-phase-bqhz6vdr.js"));
12099
+ const { sendStatusNotification } = await importPluginModule(() => import("./send-session-notification-0m68ms3n.js"));
12100
+ const { abortSessionFailClosed } = await importPluginModule(() => import("./transform-postprocess-phase-z5hzpsxv.js"));
11542
12101
  await sendStatusNotification(ctx.client, sessionId, message, {
11543
12102
  toastDurationMs: 15000
11544
12103
  });
@@ -11550,8 +12109,8 @@ var server = async (ctx) => {
11550
12109
  tryReopenStorage,
11551
12110
  rustReplayParticipant: () => magicContextRuntime.magicContext?.getRustReplayParticipant?.() ?? null,
11552
12111
  onStorageBusyRefusal: async (sessionId, message) => {
11553
- const { sendStatusNotification } = await importPluginModule(() => import("./send-session-notification-dyw42dtr.js"));
11554
- const { abortSessionFailClosed } = await importPluginModule(() => import("./transform-postprocess-phase-bqhz6vdr.js"));
12112
+ const { sendStatusNotification } = await importPluginModule(() => import("./send-session-notification-0m68ms3n.js"));
12113
+ const { abortSessionFailClosed } = await importPluginModule(() => import("./transform-postprocess-phase-z5hzpsxv.js"));
11555
12114
  await sendStatusNotification(ctx.client, sessionId, message, {
11556
12115
  toastDurationMs: 15000
11557
12116
  });