@cortexkit/opencode-magic-context 0.37.0 → 0.38.1

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 (150) hide show
  1. package/README.md +2 -0
  2. package/dist/{announcement-6c1g4es4.js → announcement-5eg4t64s.js} +6 -6
  3. package/dist/config/schema/magic-context.d.ts +1 -1
  4. package/dist/{conflict-warning-hook-an4fxhwf.js → conflict-warning-hook-f406ggbw.js} +5 -5
  5. package/dist/{derive-budgets-0f8xpyw2.js → derive-budgets-xk8cy5e6.js} +5 -5
  6. package/dist/{emscripten-module-ap8t3st0.js → emscripten-module-49k43zfy.js} +1 -1
  7. package/dist/{emscripten-module-682pfzaa.js → emscripten-module-ex4v0x4z.js} +1 -1
  8. package/dist/{emscripten-module-r5h7aghp.js → emscripten-module-jfs3d1dq.js} +1 -1
  9. package/dist/{emscripten-module-bkktz927.js → emscripten-module-ss4g4spn.js} +1 -1
  10. package/dist/features/magic-context/dreamer/classify-prompt.d.ts +5 -1
  11. package/dist/features/magic-context/dreamer/classify-prompt.d.ts.map +1 -1
  12. package/dist/features/magic-context/dreamer/classify.d.ts.map +1 -1
  13. package/dist/features/magic-context/dreamer/manifest-parser.d.ts +8 -0
  14. package/dist/features/magic-context/dreamer/manifest-parser.d.ts.map +1 -1
  15. package/dist/features/magic-context/dreamer/map-memories-prompt.d.ts +7 -1
  16. package/dist/features/magic-context/dreamer/map-memories-prompt.d.ts.map +1 -1
  17. package/dist/features/magic-context/dreamer/map-memories.d.ts +18 -0
  18. package/dist/features/magic-context/dreamer/map-memories.d.ts.map +1 -1
  19. package/dist/features/magic-context/dreamer/retrospective-orphan-sweep.d.ts +17 -6
  20. package/dist/features/magic-context/dreamer/retrospective-orphan-sweep.d.ts.map +1 -1
  21. package/dist/features/magic-context/dreamer/storage-dream-runs.d.ts +5 -0
  22. package/dist/features/magic-context/dreamer/storage-dream-runs.d.ts.map +1 -1
  23. package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
  24. package/dist/features/magic-context/dreamer/verify-prompt.d.ts +5 -1
  25. package/dist/features/magic-context/dreamer/verify-prompt.d.ts.map +1 -1
  26. package/dist/features/magic-context/dreamer/verify.d.ts.map +1 -1
  27. package/dist/features/magic-context/fail-closed-block.d.ts +6 -1
  28. package/dist/features/magic-context/fail-closed-block.d.ts.map +1 -1
  29. package/dist/features/magic-context/memory/storage-memory.d.ts.map +1 -1
  30. package/dist/features/magic-context/memory/types.d.ts +16 -0
  31. package/dist/features/magic-context/memory/types.d.ts.map +1 -1
  32. package/dist/features/magic-context/message-index.d.ts +3 -2
  33. package/dist/features/magic-context/message-index.d.ts.map +1 -1
  34. package/dist/features/magic-context/migrations.d.ts.map +1 -1
  35. package/dist/features/magic-context/reclaim-protection.d.ts +13 -0
  36. package/dist/features/magic-context/reclaim-protection.d.ts.map +1 -0
  37. package/dist/features/magic-context/storage-db.d.ts +7 -2
  38. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  39. package/dist/features/magic-context/storage-embedding-measurements.d.ts +1 -1
  40. package/dist/features/magic-context/storage-embedding-measurements.d.ts.map +1 -1
  41. package/dist/features/magic-context/storage-meta-persisted.d.ts +7 -6
  42. package/dist/features/magic-context/storage-meta-persisted.d.ts.map +1 -1
  43. package/dist/features/magic-context/storage-meta-session.d.ts.map +1 -1
  44. package/dist/features/magic-context/storage-session-tables.d.ts +18 -0
  45. package/dist/features/magic-context/storage-session-tables.d.ts.map +1 -0
  46. package/dist/features/magic-context/storage-tags.d.ts +13 -5
  47. package/dist/features/magic-context/storage-tags.d.ts.map +1 -1
  48. package/dist/features/magic-context/transform-decision-log.d.ts +22 -0
  49. package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
  50. package/dist/{ffi-d8pnn3mn.js → ffi-bbm9vkfa.js} +1 -1
  51. package/dist/{ffi-04jzypzk.js → ffi-kb5r0x1j.js} +1 -1
  52. package/dist/{ffi-t8b862vx.js → ffi-qnrt0y78.js} +1 -1
  53. package/dist/{ffi-9wvt2wwz.js → ffi-yx2hpf4p.js} +1 -1
  54. package/dist/hooks/auto-update-checker/checker.d.ts +8 -1
  55. package/dist/hooks/auto-update-checker/checker.d.ts.map +1 -1
  56. package/dist/hooks/auto-update-checker/index.d.ts.map +1 -1
  57. package/dist/hooks/magic-context/channel2-cycle.d.ts +16 -0
  58. package/dist/hooks/magic-context/channel2-cycle.d.ts.map +1 -0
  59. package/dist/hooks/magic-context/channel2-delivery.d.ts +3 -9
  60. package/dist/hooks/magic-context/channel2-delivery.d.ts.map +1 -1
  61. package/dist/hooks/magic-context/command-handler.d.ts +2 -0
  62. package/dist/hooks/magic-context/command-handler.d.ts.map +1 -1
  63. package/dist/hooks/magic-context/ctx-reduce-nudge.d.ts +33 -103
  64. package/dist/hooks/magic-context/ctx-reduce-nudge.d.ts.map +1 -1
  65. package/dist/hooks/magic-context/emergency-drop.d.ts.map +1 -1
  66. package/dist/hooks/magic-context/empty-task-output.d.ts +16 -0
  67. package/dist/hooks/magic-context/empty-task-output.d.ts.map +1 -0
  68. package/dist/hooks/magic-context/event-handler.d.ts.map +1 -1
  69. package/dist/hooks/magic-context/execute-status.d.ts +2 -1
  70. package/dist/hooks/magic-context/execute-status.d.ts.map +1 -1
  71. package/dist/hooks/magic-context/fold-execution-gate.d.ts +2 -0
  72. package/dist/hooks/magic-context/fold-execution-gate.d.ts.map +1 -0
  73. package/dist/hooks/magic-context/hook-handlers.d.ts.map +1 -1
  74. package/dist/hooks/magic-context/hook.d.ts.map +1 -1
  75. package/dist/hooks/magic-context/inject-compartments.d.ts +6 -0
  76. package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
  77. package/dist/hooks/magic-context/live-session-state.d.ts +3 -0
  78. package/dist/hooks/magic-context/live-session-state.d.ts.map +1 -1
  79. package/dist/hooks/magic-context/rust-mode-transform.d.ts +4 -2
  80. package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
  81. package/dist/hooks/magic-context/strip-content.d.ts +10 -8
  82. package/dist/hooks/magic-context/strip-content.d.ts.map +1 -1
  83. package/dist/hooks/magic-context/supersession-reclaim.d.ts.map +1 -1
  84. package/dist/hooks/magic-context/system-prompt-hash.d.ts.map +1 -1
  85. package/dist/hooks/magic-context/tail-hygiene-walk.d.ts +78 -0
  86. package/dist/hooks/magic-context/tail-hygiene-walk.d.ts.map +1 -0
  87. package/dist/hooks/magic-context/tool-reclaim.d.ts.map +1 -1
  88. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +7 -0
  89. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  90. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  91. package/dist/{index-cae89eas.js → index-1h9t9xb5.js} +2 -2
  92. package/dist/{index-wckvcay0.js → index-1yh8g550.js} +8 -6
  93. package/dist/index-22mw8km4.js +558 -0
  94. package/dist/{index-cgyfn1s2.js → index-2wchnyk6.js} +4 -2
  95. package/dist/{index-0ze9p983.js → index-5znjkjws.js} +9996 -7043
  96. package/dist/{index-4cz5nfxf.js → index-btj2qhmc.js} +5 -5
  97. package/dist/{index-q0t189ay.js → index-mg1yx1ph.js} +28 -36
  98. package/dist/{index-ayd60xnw.js → index-rgdqj8nj.js} +3 -3
  99. package/dist/{index-ygcng9t8.js → index-rpgg35ms.js} +50 -50
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/index.js +776 -846
  102. package/dist/{module-ES6BEMUI-atfbtnbp.js → module-ES6BEMUI-1yjdz59c.js} +4 -4
  103. package/dist/{module-asyncify-2EFITU5U-7xckhw8w.js → module-asyncify-2EFITU5U-fdkx4fhy.js} +1 -1
  104. package/dist/plugin/dream-timer.d.ts +5 -0
  105. package/dist/plugin/dream-timer.d.ts.map +1 -1
  106. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  107. package/dist/plugin/messages-transform.d.ts.map +1 -1
  108. package/dist/plugin/rpc-handlers.d.ts +2 -0
  109. package/dist/plugin/rpc-handlers.d.ts.map +1 -1
  110. package/dist/{prompt-context-jpe2dstn.js → prompt-context-29qkb28f.js} +1 -1
  111. package/dist/{recomp-orchestrator-c3ff16k7.js → recomp-orchestrator-p030kxtc.js} +15 -15
  112. package/dist/{resolve-fallbacks-5n5tvge1.js → resolve-fallbacks-qf0ekmz9.js} +3 -3
  113. package/dist/{rpc-notifications-4d22ybn5.js → rpc-notifications-1ffm755w.js} +6 -6
  114. package/dist/{safe-notification-target-b693f9x3.js → safe-notification-target-tepzc2xa.js} +3 -3
  115. package/dist/{send-session-notification-dxske5zm.js → send-session-notification-6v5b72b4.js} +7 -7
  116. package/dist/shared/harness-provider-map.d.ts +6 -0
  117. package/dist/shared/harness-provider-map.d.ts.map +1 -1
  118. package/dist/shared/models-dev-cache.d.ts +2 -0
  119. package/dist/shared/models-dev-cache.d.ts.map +1 -1
  120. package/dist/shared/rpc-server.d.ts.map +1 -1
  121. package/dist/shared/rpc-types.d.ts +15 -0
  122. package/dist/shared/rpc-types.d.ts.map +1 -1
  123. package/dist/shared/rpc-utils.d.ts +9 -0
  124. package/dist/shared/rpc-utils.d.ts.map +1 -1
  125. package/dist/shared/tail-hygiene-status.d.ts +15 -0
  126. package/dist/shared/tail-hygiene-status.d.ts.map +1 -0
  127. package/dist/shared/window-geometry.d.ts +3 -2
  128. package/dist/shared/window-geometry.d.ts.map +1 -1
  129. package/dist/{storage-meta-session-mk4gsnke.js → storage-meta-session-2306t3j7.js} +8 -8
  130. package/dist/{task-config-gbp7r23g.js → task-config-at3adc59.js} +6 -6
  131. package/package.json +4 -2
  132. package/src/config/schema/magic-context.test.ts +1 -0
  133. package/src/config/schema/magic-context.ts +5 -5
  134. package/src/shared/harness-provider-map.test.ts +36 -0
  135. package/src/shared/harness-provider-map.ts +8 -0
  136. package/src/shared/models-dev-cache.test.ts +25 -0
  137. package/src/shared/models-dev-cache.ts +5 -4
  138. package/src/shared/rpc-server.ts +1 -0
  139. package/src/shared/rpc-types.ts +16 -0
  140. package/src/shared/rpc-utils.test.ts +25 -0
  141. package/src/shared/rpc-utils.ts +80 -0
  142. package/src/shared/tail-hygiene-status.ts +57 -0
  143. package/src/shared/window-geometry.test.ts +34 -1
  144. package/src/shared/window-geometry.ts +37 -40
  145. package/src/tui/index.tsx +12 -2
  146. package/src/tui/slots/sidebar-content.tsx +17 -5
  147. package/src/tui/tui-compiled-runtime-imports.test.ts +3 -0
  148. package/src/tui-compiled/index.tsx +312 -290
  149. package/src/tui-compiled/slots/sidebar-content.tsx +316 -287
  150. package/dist/index-crke4z5j.js +0 -3022
@@ -0,0 +1,558 @@
1
+ import {
2
+ piModelRefToCanonical
3
+ } from "./index-2wchnyk6.js";
4
+ import {
5
+ withReadOnlySessionDb
6
+ } from "./index-sw8gnq34.js";
7
+ import {
8
+ log
9
+ } from "./index-8pqfcghm.js";
10
+ import {
11
+ getHarness
12
+ } from "./index-mmrhhk9a.js";
13
+
14
+ // src/features/magic-context/storage-meta-session.ts
15
+ import { Buffer as Buffer2 } from "node:buffer";
16
+
17
+ // src/features/magic-context/resolve-subagent-fallback.ts
18
+ function resolveIsSubagentFromOpenCodeDb(sessionId) {
19
+ try {
20
+ return withReadOnlySessionDb((openCodeDb) => {
21
+ const row = openCodeDb.prepare("SELECT parent_id FROM session WHERE id = ?").get(sessionId);
22
+ if (!row)
23
+ return null;
24
+ return typeof row.parent_id === "string" && row.parent_id.length > 0;
25
+ });
26
+ } catch (error) {
27
+ log(`[magic-context] resolveIsSubagentFromOpenCodeDb failed for ${sessionId}:`, error);
28
+ return null;
29
+ }
30
+ }
31
+
32
+ // src/features/magic-context/storage-meta-shared.ts
33
+ import { Buffer } from "node:buffer";
34
+ var SESSION_META_SELECT_COLUMNS = [
35
+ "session_id",
36
+ "last_response_time",
37
+ "cache_ttl",
38
+ "counter",
39
+ "last_nudge_tokens",
40
+ "last_nudge_band",
41
+ "last_transform_error",
42
+ "is_subagent",
43
+ "last_context_percentage",
44
+ "last_input_tokens",
45
+ "observed_safe_input_tokens",
46
+ "cache_alert_sent",
47
+ "times_execute_threshold_reached",
48
+ "compartment_in_progress",
49
+ "system_prompt_hash",
50
+ "system_prompt_tokens",
51
+ "conversation_tokens",
52
+ "tool_call_tokens",
53
+ "cleared_reasoning_through_tag",
54
+ "tool_reclaim_watermark",
55
+ "last_todo_state",
56
+ "cached_m0_bytes",
57
+ "cached_m0_mural_data_url",
58
+ "cached_m0_mural_hash",
59
+ "cached_m1_bytes",
60
+ "cached_m0_project_memory_epoch",
61
+ "cached_m0_workspace_fingerprint",
62
+ "cached_m0_project_user_profile_version",
63
+ "cached_m0_max_compartment_seq",
64
+ "cached_m0_max_memory_id",
65
+ "cached_m0_max_mutation_id",
66
+ "cached_m0_max_memory_mutation_id",
67
+ "cached_m0_project_docs_hash",
68
+ "cached_m0_materialized_at",
69
+ "cached_m0_session_facts_version",
70
+ "cached_m0_upgrade_state",
71
+ "cached_m0_system_hash",
72
+ "cached_m0_tool_set_hash",
73
+ "cached_m0_model_key",
74
+ "cached_m0_project_identity",
75
+ "last_observed_model_key",
76
+ "last_usage_context_limit",
77
+ "prior_boundary_ordinal",
78
+ "protected_tail_policy_version",
79
+ "protected_tail_drain_window_started_at",
80
+ "protected_tail_drain_tokens",
81
+ "recovery_no_eligible_head_count",
82
+ "force_emergency_bypass_window_start",
83
+ "force_emergency_bypass_used",
84
+ "emergency_drain_active",
85
+ "historian_drain_failure_at",
86
+ "upgrade_reminded_at",
87
+ "upgrade_reminder_last_sent_at",
88
+ "upgrade_reminder_count",
89
+ "pi_stable_id_scheme"
90
+ ];
91
+ var META_COLUMNS = {
92
+ lastResponseTime: "last_response_time",
93
+ cacheTtl: "cache_ttl",
94
+ counter: "counter",
95
+ lastNudgeTokens: "last_nudge_tokens",
96
+ lastNudgeBand: "last_nudge_band",
97
+ lastTransformError: "last_transform_error",
98
+ isSubagent: "is_subagent",
99
+ lastContextPercentage: "last_context_percentage",
100
+ lastInputTokens: "last_input_tokens",
101
+ observedSafeInputTokens: "observed_safe_input_tokens",
102
+ cacheAlertSent: "cache_alert_sent",
103
+ timesExecuteThresholdReached: "times_execute_threshold_reached",
104
+ compartmentInProgress: "compartment_in_progress",
105
+ systemPromptHash: "system_prompt_hash",
106
+ systemPromptTokens: "system_prompt_tokens",
107
+ conversationTokens: "conversation_tokens",
108
+ toolCallTokens: "tool_call_tokens",
109
+ clearedReasoningThroughTag: "cleared_reasoning_through_tag",
110
+ toolReclaimWatermark: "tool_reclaim_watermark",
111
+ lastTodoState: "last_todo_state",
112
+ cachedM0Bytes: "cached_m0_bytes",
113
+ cachedM0MuralDataUrl: "cached_m0_mural_data_url",
114
+ cachedM0MuralHash: "cached_m0_mural_hash",
115
+ cachedM1Bytes: "cached_m1_bytes",
116
+ cachedM0ProjectMemoryEpoch: "cached_m0_project_memory_epoch",
117
+ cachedM0WorkspaceFingerprint: "cached_m0_workspace_fingerprint",
118
+ cachedM0ProjectUserProfileVersion: "cached_m0_project_user_profile_version",
119
+ cachedM0MaxCompartmentSeq: "cached_m0_max_compartment_seq",
120
+ cachedM0MaxMemoryId: "cached_m0_max_memory_id",
121
+ cachedM0MaxMutationId: "cached_m0_max_mutation_id",
122
+ cachedM0MaxMemoryMutationId: "cached_m0_max_memory_mutation_id",
123
+ cachedM0ProjectDocsHash: "cached_m0_project_docs_hash",
124
+ cachedM0MaterializedAt: "cached_m0_materialized_at",
125
+ cachedM0SessionFactsVersion: "cached_m0_session_facts_version",
126
+ cachedM0UpgradeState: "cached_m0_upgrade_state",
127
+ cachedM0SystemHash: "cached_m0_system_hash",
128
+ cachedM0ToolSetHash: "cached_m0_tool_set_hash",
129
+ cachedM0ModelKey: "cached_m0_model_key",
130
+ cachedM0ProjectIdentity: "cached_m0_project_identity",
131
+ lastObservedModelKey: "last_observed_model_key",
132
+ lastUsageContextLimit: "last_usage_context_limit",
133
+ priorBoundaryOrdinal: "prior_boundary_ordinal",
134
+ protectedTailPolicyVersion: "protected_tail_policy_version",
135
+ protectedTailDrainWindowStartedAt: "protected_tail_drain_window_started_at",
136
+ protectedTailDrainTokens: "protected_tail_drain_tokens",
137
+ recoveryNoEligibleHeadCount: "recovery_no_eligible_head_count",
138
+ forceEmergencyBypassWindowStart: "force_emergency_bypass_window_start",
139
+ forceEmergencyBypassUsed: "force_emergency_bypass_used",
140
+ emergencyDrainActive: "emergency_drain_active",
141
+ historianDrainFailureAt: "historian_drain_failure_at",
142
+ upgradeRemindedAt: "upgrade_reminded_at",
143
+ upgradeReminderLastSentAt: "upgrade_reminder_last_sent_at",
144
+ upgradeReminderCount: "upgrade_reminder_count",
145
+ piStableIdScheme: "pi_stable_id_scheme"
146
+ };
147
+ var BOOLEAN_META_KEYS = new Set(["isSubagent", "compartmentInProgress", "cacheAlertSent"]);
148
+ var NULL_BIND_META_KEYS = new Set([
149
+ "cachedM0Bytes",
150
+ "cachedM0MuralDataUrl",
151
+ "cachedM0MuralHash",
152
+ "cachedM1Bytes",
153
+ "cachedM0ProjectMemoryEpoch",
154
+ "cachedM0WorkspaceFingerprint",
155
+ "cachedM0ProjectUserProfileVersion",
156
+ "cachedM0MaxCompartmentSeq",
157
+ "cachedM0MaxMemoryId",
158
+ "cachedM0MaxMutationId",
159
+ "cachedM0MaxMemoryMutationId",
160
+ "cachedM0ProjectDocsHash",
161
+ "cachedM0MaterializedAt",
162
+ "cachedM0SessionFactsVersion",
163
+ "cachedM0UpgradeState",
164
+ "cachedM0ProjectIdentity",
165
+ "lastObservedModelKey",
166
+ "upgradeRemindedAt",
167
+ "upgradeReminderLastSentAt",
168
+ "piStableIdScheme"
169
+ ]);
170
+ function isStringOrNull(value) {
171
+ return value === null || typeof value === "string";
172
+ }
173
+ function isNumberOrNull(value) {
174
+ return value === null || typeof value === "number";
175
+ }
176
+ function isBlobOrNull(value) {
177
+ return value === null || Buffer.isBuffer(value) || value instanceof Uint8Array;
178
+ }
179
+ function toBufferOrNull(value) {
180
+ if (value === null)
181
+ return null;
182
+ if (Buffer.isBuffer(value))
183
+ return value;
184
+ return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
185
+ }
186
+ function isSessionMetaRow(row) {
187
+ if (row === null || typeof row !== "object")
188
+ return false;
189
+ const r = row;
190
+ return typeof r.session_id === "string" && typeof r.last_response_time === "number" && isStringOrNull(r.cache_ttl) && typeof r.counter === "number" && typeof r.last_nudge_tokens === "number" && isStringOrNull(r.last_nudge_band) && isStringOrNull(r.last_transform_error) && typeof r.is_subagent === "number" && typeof r.last_context_percentage === "number" && typeof r.last_input_tokens === "number" && isNumberOrNull(r.observed_safe_input_tokens) && isNumberOrNull(r.cache_alert_sent) && isNumberOrNull(r.times_execute_threshold_reached) && isNumberOrNull(r.compartment_in_progress) && (r.system_prompt_hash === null || typeof r.system_prompt_hash === "string" || typeof r.system_prompt_hash === "number") && isNumberOrNull(r.system_prompt_tokens) && isNumberOrNull(r.conversation_tokens) && isNumberOrNull(r.tool_call_tokens) && isNumberOrNull(r.cleared_reasoning_through_tag) && isStringOrNull(r.last_todo_state) && isBlobOrNull(r.cached_m0_bytes) && isStringOrNull(r.cached_m0_mural_data_url) && isStringOrNull(r.cached_m0_mural_hash) && isBlobOrNull(r.cached_m1_bytes) && isNumberOrNull(r.cached_m0_project_memory_epoch) && isStringOrNull(r.cached_m0_workspace_fingerprint) && isNumberOrNull(r.cached_m0_project_user_profile_version) && isNumberOrNull(r.cached_m0_max_compartment_seq) && isNumberOrNull(r.cached_m0_max_memory_id) && isNumberOrNull(r.cached_m0_max_mutation_id) && isNumberOrNull(r.cached_m0_max_memory_mutation_id) && isStringOrNull(r.cached_m0_project_docs_hash) && isNumberOrNull(r.cached_m0_materialized_at) && isNumberOrNull(r.cached_m0_session_facts_version) && isStringOrNull(r.cached_m0_upgrade_state) && isStringOrNull(r.cached_m0_system_hash) && isStringOrNull(r.cached_m0_tool_set_hash) && isStringOrNull(r.cached_m0_model_key) && isStringOrNull(r.cached_m0_project_identity) && isStringOrNull(r.last_observed_model_key) && isNumberOrNull(r.last_usage_context_limit) && isNumberOrNull(r.prior_boundary_ordinal) && isNumberOrNull(r.protected_tail_policy_version) && isNumberOrNull(r.protected_tail_drain_window_started_at) && isNumberOrNull(r.protected_tail_drain_tokens) && isNumberOrNull(r.recovery_no_eligible_head_count) && isNumberOrNull(r.force_emergency_bypass_window_start) && isNumberOrNull(r.force_emergency_bypass_used) && isNumberOrNull(r.upgrade_reminded_at) && isNumberOrNull(r.upgrade_reminder_last_sent_at) && isNumberOrNull(r.upgrade_reminder_count) && isNumberOrNull(r.pi_stable_id_scheme) && isNumberOrNull(r.tool_reclaim_watermark);
191
+ }
192
+ function getDefaultSessionMeta(sessionId) {
193
+ return {
194
+ sessionId,
195
+ lastResponseTime: 0,
196
+ cacheTtl: "5m",
197
+ counter: 0,
198
+ lastNudgeTokens: 0,
199
+ lastNudgeBand: null,
200
+ lastTransformError: null,
201
+ isSubagent: false,
202
+ lastContextPercentage: 0,
203
+ lastInputTokens: 0,
204
+ observedSafeInputTokens: 0,
205
+ cacheAlertSent: false,
206
+ timesExecuteThresholdReached: 0,
207
+ compartmentInProgress: false,
208
+ systemPromptHash: "",
209
+ systemPromptTokens: 0,
210
+ conversationTokens: 0,
211
+ toolCallTokens: 0,
212
+ clearedReasoningThroughTag: 0,
213
+ toolReclaimWatermark: 0,
214
+ lastTodoState: "",
215
+ cachedM0Bytes: null,
216
+ cachedM0MuralDataUrl: null,
217
+ cachedM0MuralHash: null,
218
+ cachedM1Bytes: null,
219
+ cachedM0ProjectMemoryEpoch: null,
220
+ cachedM0WorkspaceFingerprint: null,
221
+ cachedM0ProjectUserProfileVersion: null,
222
+ cachedM0MaxCompartmentSeq: null,
223
+ cachedM0MaxMemoryId: null,
224
+ cachedM0MaxMutationId: null,
225
+ cachedM0MaxMemoryMutationId: null,
226
+ cachedM0ProjectDocsHash: null,
227
+ cachedM0MaterializedAt: null,
228
+ cachedM0SessionFactsVersion: null,
229
+ cachedM0UpgradeState: null,
230
+ cachedM0SystemHash: null,
231
+ cachedM0ToolSetHash: null,
232
+ cachedM0ModelKey: null,
233
+ cachedM0ProjectIdentity: null,
234
+ lastObservedModelKey: null,
235
+ lastUsageContextLimit: 0,
236
+ priorBoundaryOrdinal: 1,
237
+ protectedTailPolicyVersion: 0,
238
+ protectedTailDrainWindowStartedAt: 0,
239
+ protectedTailDrainTokens: 0,
240
+ recoveryNoEligibleHeadCount: 0,
241
+ forceEmergencyBypassWindowStart: 0,
242
+ forceEmergencyBypassUsed: 0,
243
+ upgradeRemindedAt: null,
244
+ upgradeReminderLastSentAt: null,
245
+ upgradeReminderCount: 0,
246
+ piStableIdScheme: null
247
+ };
248
+ }
249
+ function ensureSessionMetaRow(db, sessionId) {
250
+ const defaults = getDefaultSessionMeta(sessionId);
251
+ db.prepare("INSERT OR IGNORE INTO session_meta (session_id, harness, last_response_time, cache_ttl, counter, last_nudge_tokens, last_nudge_band, last_transform_error, is_subagent, last_context_percentage, last_input_tokens, observed_safe_input_tokens, cache_alert_sent, times_execute_threshold_reached, compartment_in_progress, system_prompt_hash, cleared_reasoning_through_tag) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(sessionId, getHarness(), defaults.lastResponseTime, defaults.cacheTtl, defaults.counter, defaults.lastNudgeTokens, defaults.lastNudgeBand ?? "", defaults.lastTransformError ?? "", defaults.isSubagent ? 1 : 0, defaults.lastContextPercentage, defaults.lastInputTokens, defaults.observedSafeInputTokens, defaults.cacheAlertSent ? 1 : 0, defaults.timesExecuteThresholdReached, defaults.compartmentInProgress ? 1 : 0, defaults.systemPromptHash ?? "", defaults.clearedReasoningThroughTag);
252
+ }
253
+ function toSessionMeta(row) {
254
+ const nudgeBandRaw = typeof row.last_nudge_band === "string" ? row.last_nudge_band : "";
255
+ const transformErrorRaw = typeof row.last_transform_error === "string" ? row.last_transform_error : "";
256
+ const cacheTtlRaw = typeof row.cache_ttl === "string" && row.cache_ttl.length > 0 ? row.cache_ttl : "5m";
257
+ const systemPromptHashRaw = row.system_prompt_hash == null ? "" : row.system_prompt_hash;
258
+ const lastTodoStateRaw = typeof row.last_todo_state === "string" ? row.last_todo_state : "";
259
+ const numOrZero = (value) => typeof value === "number" ? value : 0;
260
+ const numOrNull = (value) => typeof value === "number" ? value : null;
261
+ const stringOrNull = (value) => typeof value === "string" ? value : null;
262
+ return {
263
+ sessionId: row.session_id,
264
+ lastResponseTime: row.last_response_time,
265
+ cacheTtl: cacheTtlRaw,
266
+ counter: row.counter,
267
+ lastNudgeTokens: row.last_nudge_tokens,
268
+ lastNudgeBand: nudgeBandRaw.length > 0 ? nudgeBandRaw : null,
269
+ lastTransformError: transformErrorRaw.length > 0 ? transformErrorRaw : null,
270
+ isSubagent: row.is_subagent === 1,
271
+ lastContextPercentage: row.last_context_percentage,
272
+ lastInputTokens: row.last_input_tokens,
273
+ observedSafeInputTokens: numOrZero(row.observed_safe_input_tokens),
274
+ cacheAlertSent: numOrZero(row.cache_alert_sent) === 1,
275
+ timesExecuteThresholdReached: numOrZero(row.times_execute_threshold_reached),
276
+ compartmentInProgress: row.compartment_in_progress === 1,
277
+ systemPromptHash: String(systemPromptHashRaw),
278
+ systemPromptTokens: numOrZero(row.system_prompt_tokens),
279
+ conversationTokens: numOrZero(row.conversation_tokens),
280
+ toolCallTokens: numOrZero(row.tool_call_tokens),
281
+ clearedReasoningThroughTag: numOrZero(row.cleared_reasoning_through_tag),
282
+ toolReclaimWatermark: numOrZero(row.tool_reclaim_watermark),
283
+ lastTodoState: lastTodoStateRaw,
284
+ cachedM0Bytes: toBufferOrNull(row.cached_m0_bytes),
285
+ cachedM0MuralDataUrl: stringOrNull(row.cached_m0_mural_data_url),
286
+ cachedM0MuralHash: stringOrNull(row.cached_m0_mural_hash),
287
+ cachedM1Bytes: toBufferOrNull(row.cached_m1_bytes),
288
+ cachedM0ProjectMemoryEpoch: numOrNull(row.cached_m0_project_memory_epoch),
289
+ cachedM0WorkspaceFingerprint: stringOrNull(row.cached_m0_workspace_fingerprint),
290
+ cachedM0ProjectUserProfileVersion: numOrNull(row.cached_m0_project_user_profile_version),
291
+ cachedM0MaxCompartmentSeq: numOrNull(row.cached_m0_max_compartment_seq),
292
+ cachedM0MaxMemoryId: numOrNull(row.cached_m0_max_memory_id),
293
+ cachedM0MaxMutationId: numOrNull(row.cached_m0_max_mutation_id),
294
+ cachedM0MaxMemoryMutationId: numOrNull(row.cached_m0_max_memory_mutation_id),
295
+ cachedM0ProjectDocsHash: stringOrNull(row.cached_m0_project_docs_hash),
296
+ cachedM0MaterializedAt: numOrNull(row.cached_m0_materialized_at),
297
+ cachedM0SessionFactsVersion: numOrNull(row.cached_m0_session_facts_version),
298
+ cachedM0UpgradeState: stringOrNull(row.cached_m0_upgrade_state),
299
+ cachedM0SystemHash: stringOrNull(row.cached_m0_system_hash),
300
+ cachedM0ToolSetHash: stringOrNull(row.cached_m0_tool_set_hash),
301
+ cachedM0ModelKey: stringOrNull(row.cached_m0_model_key),
302
+ cachedM0ProjectIdentity: stringOrNull(row.cached_m0_project_identity),
303
+ lastObservedModelKey: stringOrNull(row.last_observed_model_key),
304
+ lastUsageContextLimit: numOrZero(row.last_usage_context_limit),
305
+ priorBoundaryOrdinal: Math.max(1, numOrZero(row.prior_boundary_ordinal) || 1),
306
+ protectedTailPolicyVersion: numOrZero(row.protected_tail_policy_version),
307
+ protectedTailDrainWindowStartedAt: numOrZero(row.protected_tail_drain_window_started_at),
308
+ protectedTailDrainTokens: numOrZero(row.protected_tail_drain_tokens),
309
+ recoveryNoEligibleHeadCount: numOrZero(row.recovery_no_eligible_head_count),
310
+ forceEmergencyBypassWindowStart: numOrZero(row.force_emergency_bypass_window_start),
311
+ forceEmergencyBypassUsed: numOrZero(row.force_emergency_bypass_used),
312
+ upgradeRemindedAt: numOrNull(row.upgrade_reminded_at),
313
+ upgradeReminderLastSentAt: numOrNull(row.upgrade_reminder_last_sent_at),
314
+ upgradeReminderCount: numOrZero(row.upgrade_reminder_count),
315
+ piStableIdScheme: numOrNull(row.pi_stable_id_scheme)
316
+ };
317
+ }
318
+ function persistCachedM0(db, sessionId, payload) {
319
+ ensureSessionMetaRow(db, sessionId);
320
+ db.prepare(`UPDATE session_meta SET
321
+ cached_m0_bytes = ?,
322
+ cached_m0_mural_data_url = ?,
323
+ cached_m0_mural_hash = ?,
324
+ cached_m0_project_memory_epoch = ?,
325
+ cached_m0_workspace_fingerprint = ?,
326
+ cached_m0_project_user_profile_version = ?,
327
+ cached_m0_max_compartment_seq = ?,
328
+ cached_m0_max_memory_id = ?,
329
+ cached_m0_max_mutation_id = ?,
330
+ cached_m0_max_memory_mutation_id = ?,
331
+ cached_m1_bytes = ?,
332
+ cached_m0_project_docs_hash = ?,
333
+ cached_m0_materialized_at = ?,
334
+ cached_m0_session_facts_version = ?,
335
+ cached_m0_upgrade_state = ?,
336
+ cached_m0_system_hash = ?,
337
+ cached_m0_model_key = ?,
338
+ cached_m0_project_identity = ?
339
+ WHERE session_id = ?`).run(Buffer.from(payload.m0Bytes), payload.muralDataUrl ?? null, payload.muralHash ?? null, payload.projectMemoryEpoch, payload.workspaceFingerprint ?? null, payload.projectUserProfileVersion, payload.maxCompartmentSeq, payload.maxMemoryId, payload.maxMutationId, payload.maxMemoryMutationId ?? null, payload.m1Bytes ? Buffer.from(payload.m1Bytes) : null, payload.projectDocsHash, payload.materializedAt, payload.sessionFactsVersion, payload.upgradeState, payload.systemHash ?? "", payload.modelKey ? piModelRefToCanonical(payload.modelKey) : "", payload.projectIdentity ?? null, sessionId);
340
+ }
341
+ function clearCachedM0M1(db, sessionId) {
342
+ ensureSessionMetaRow(db, sessionId);
343
+ const existingColumns = new Set(db.prepare("PRAGMA table_info(session_meta)").all().map((column) => column.name));
344
+ const clears = [
345
+ ["cached_m0_bytes", null],
346
+ ["cached_m0_mural_data_url", null],
347
+ ["cached_m0_mural_hash", null],
348
+ ["cached_m1_bytes", null],
349
+ ["cached_m0_project_memory_epoch", null],
350
+ ["cached_m0_workspace_fingerprint", null],
351
+ ["cached_m0_project_user_profile_version", null],
352
+ ["cached_m0_max_compartment_seq", null],
353
+ ["cached_m0_max_memory_id", null],
354
+ ["cached_m0_max_mutation_id", null],
355
+ ["cached_m0_max_memory_mutation_id", null],
356
+ ["cached_m0_project_docs_hash", null],
357
+ ["cached_m0_materialized_at", null],
358
+ ["cached_m0_session_facts_version", null],
359
+ ["cached_m0_upgrade_state", null],
360
+ ["cached_m0_system_hash", null],
361
+ ["cached_m0_tool_set_hash", null],
362
+ ["cached_m0_model_key", null],
363
+ ["cached_m0_project_identity", null],
364
+ ["cached_m0_last_baseline_end_message_id", null],
365
+ ["memory_block_cache", ""],
366
+ ["memory_block_count", 0],
367
+ ["memory_block_ids", ""]
368
+ ];
369
+ const setClauses = [];
370
+ const values = [];
371
+ for (const [column, value] of clears) {
372
+ if (!existingColumns.has(column))
373
+ continue;
374
+ setClauses.push(`${column} = ?`);
375
+ values.push(value);
376
+ }
377
+ if (setClauses.length === 0)
378
+ return;
379
+ db.prepare(`UPDATE session_meta SET ${setClauses.join(", ")} WHERE session_id = ?`).run(...values, sessionId);
380
+ }
381
+
382
+ // src/features/magic-context/storage-session-tables.ts
383
+ var SESSION_SCOPED_TABLES = [
384
+ { table: "pending_ops", harnessScoped: true },
385
+ { table: "source_contents", harnessScoped: true },
386
+ { table: "tool_owner_backfill_state" },
387
+ { table: "tags", harnessScoped: true },
388
+ { table: "session_meta", harnessScoped: true },
389
+ { table: "session_projects", harnessScoped: true },
390
+ { table: "compartment_chunk_embeddings", harnessScoped: true },
391
+ { table: "compartments", harnessScoped: true },
392
+ { table: "compression_depth", harnessScoped: true },
393
+ { table: "session_facts", harnessScoped: true },
394
+ { table: "compartment_state_lease" },
395
+ { table: "notes", harnessScoped: true, extraPredicate: "type = 'session'" },
396
+ { table: "recomp_compartments", harnessScoped: true },
397
+ { table: "recomp_facts", harnessScoped: true },
398
+ { table: "user_memory_candidates" },
399
+ { table: "primer_candidates", harnessScoped: true },
400
+ { table: "m0_mutation_log" },
401
+ { table: "compartment_events", harnessScoped: true },
402
+ { table: "subagent_invocations", harnessScoped: true },
403
+ { table: "historian_runs", harnessScoped: true },
404
+ { table: "plugin_messages" },
405
+ { table: "transform_decisions", harnessScoped: true },
406
+ { table: "synapse_batch_ledger" },
407
+ { table: "embedding_measurement_corpus" },
408
+ { table: "pending_session_cleanup", harnessScoped: true },
409
+ { table: "message_history_fts" },
410
+ { table: "message_history_source", harnessScoped: true },
411
+ { table: "message_history_index", harnessScoped: true }
412
+ ];
413
+ function deleteSessionScopedRows(db, sessionIds, harness) {
414
+ if (sessionIds.length === 0)
415
+ return;
416
+ const placeholders = sessionIds.map(() => "?").join(", ");
417
+ for (const definition of SESSION_SCOPED_TABLES) {
418
+ const predicates = [`session_id IN (${placeholders})`];
419
+ if (definition.extraPredicate)
420
+ predicates.push(definition.extraPredicate);
421
+ const bindHarness = harness !== undefined && definition.harnessScoped === true;
422
+ if (bindHarness)
423
+ predicates.push("harness = ?");
424
+ const statement = db.prepare(`DELETE FROM ${definition.table} WHERE ${predicates.join(" AND ")}`);
425
+ if (bindHarness)
426
+ statement.run(...sessionIds, harness);
427
+ else
428
+ statement.run(...sessionIds);
429
+ }
430
+ }
431
+
432
+ // src/features/magic-context/storage-meta-session.ts
433
+ var SESSION_META_FALLBACK_SELECTS = {
434
+ cache_ttl: "'5m' AS cache_ttl",
435
+ last_nudge_band: "'' AS last_nudge_band",
436
+ last_transform_error: "'' AS last_transform_error",
437
+ system_prompt_hash: "'' AS system_prompt_hash",
438
+ last_todo_state: "'' AS last_todo_state",
439
+ tool_reclaim_watermark: "0 AS tool_reclaim_watermark",
440
+ cached_m0_bytes: "NULL AS cached_m0_bytes",
441
+ cached_m0_mural_data_url: "NULL AS cached_m0_mural_data_url",
442
+ cached_m0_mural_hash: "NULL AS cached_m0_mural_hash",
443
+ cached_m1_bytes: "NULL AS cached_m1_bytes",
444
+ cached_m0_project_memory_epoch: "NULL AS cached_m0_project_memory_epoch",
445
+ cached_m0_project_user_profile_version: "NULL AS cached_m0_project_user_profile_version",
446
+ cached_m0_max_compartment_seq: "NULL AS cached_m0_max_compartment_seq",
447
+ cached_m0_max_memory_id: "NULL AS cached_m0_max_memory_id",
448
+ cached_m0_max_mutation_id: "NULL AS cached_m0_max_mutation_id",
449
+ cached_m0_max_memory_mutation_id: "NULL AS cached_m0_max_memory_mutation_id",
450
+ cached_m0_project_docs_hash: "NULL AS cached_m0_project_docs_hash",
451
+ cached_m0_materialized_at: "NULL AS cached_m0_materialized_at",
452
+ cached_m0_session_facts_version: "NULL AS cached_m0_session_facts_version",
453
+ cached_m0_upgrade_state: "NULL AS cached_m0_upgrade_state",
454
+ cached_m0_system_hash: "NULL AS cached_m0_system_hash",
455
+ cached_m0_tool_set_hash: "NULL AS cached_m0_tool_set_hash",
456
+ cached_m0_model_key: "NULL AS cached_m0_model_key",
457
+ cached_m0_project_identity: "NULL AS cached_m0_project_identity",
458
+ last_observed_model_key: "NULL AS last_observed_model_key",
459
+ upgrade_reminded_at: "NULL AS upgrade_reminded_at",
460
+ upgrade_reminder_last_sent_at: "NULL AS upgrade_reminder_last_sent_at",
461
+ upgrade_reminder_count: "0 AS upgrade_reminder_count"
462
+ };
463
+ var sessionMetaSelectColumnsCache = new WeakMap;
464
+ function getSessionMetaSelectColumns(db) {
465
+ const cached = sessionMetaSelectColumnsCache.get(db);
466
+ if (cached !== undefined)
467
+ return cached;
468
+ const existingColumns = new Set(db.prepare("PRAGMA table_info(session_meta)").all().map((column) => column.name));
469
+ const projection = SESSION_META_SELECT_COLUMNS.map((column) => {
470
+ if (existingColumns.has(column))
471
+ return column;
472
+ return SESSION_META_FALLBACK_SELECTS[column] ?? `0 AS ${column}`;
473
+ }).join(", ");
474
+ sessionMetaSelectColumnsCache.set(db, projection);
475
+ return projection;
476
+ }
477
+ function getOrCreateSessionMeta(db, sessionId) {
478
+ const result = db.prepare(`SELECT ${getSessionMetaSelectColumns(db)} FROM session_meta WHERE session_id = ?`).get(sessionId);
479
+ if (isSessionMetaRow(result)) {
480
+ return toSessionMeta(result);
481
+ }
482
+ const defaults = getDefaultSessionMeta(sessionId);
483
+ const fallbackSubagent = getHarness() === "opencode" ? resolveIsSubagentFromOpenCodeDb(sessionId) : null;
484
+ if (fallbackSubagent === true) {
485
+ defaults.isSubagent = true;
486
+ }
487
+ ensureSessionMetaRow(db, sessionId);
488
+ if (fallbackSubagent === true) {
489
+ db.prepare("UPDATE session_meta SET is_subagent = 1 WHERE session_id = ?").run(sessionId);
490
+ }
491
+ return defaults;
492
+ }
493
+ function updateSessionMeta(db, sessionId, updates) {
494
+ const setClauses = [];
495
+ const values = [];
496
+ for (const [key, column] of Object.entries(META_COLUMNS)) {
497
+ const value = updates[key];
498
+ if (value === undefined)
499
+ continue;
500
+ if (value === null) {
501
+ setClauses.push(`${column} = ?`);
502
+ values.push(NULL_BIND_META_KEYS.has(key) ? null : "");
503
+ } else if ((key === "cachedM0Bytes" || key === "cachedM1Bytes") && value instanceof Uint8Array) {
504
+ setClauses.push(`${column} = ?`);
505
+ values.push(Buffer2.from(value.buffer, value.byteOffset, value.byteLength));
506
+ } else if (BOOLEAN_META_KEYS.has(key)) {
507
+ setClauses.push(`${column} = ?`);
508
+ values.push(value ? 1 : 0);
509
+ } else if (typeof value === "string" || typeof value === "number") {
510
+ setClauses.push(`${column} = ?`);
511
+ values.push(key === "lastObservedModelKey" && typeof value === "string" ? piModelRefToCanonical(value) : value);
512
+ }
513
+ }
514
+ if (setClauses.length === 0) {
515
+ return;
516
+ }
517
+ db.transaction(() => {
518
+ ensureSessionMetaRow(db, sessionId);
519
+ db.prepare(`UPDATE session_meta SET ${setClauses.join(", ")} WHERE session_id = ?`).run(...values, sessionId);
520
+ })();
521
+ }
522
+ function advanceToolReclaimWatermark(db, sessionId, maxTagNumber) {
523
+ if (maxTagNumber <= 0)
524
+ return;
525
+ db.transaction(() => {
526
+ ensureSessionMetaRow(db, sessionId);
527
+ db.prepare("UPDATE session_meta SET tool_reclaim_watermark = MAX(COALESCE(tool_reclaim_watermark, 0), ?) WHERE session_id = ?").run(maxTagNumber, sessionId);
528
+ })();
529
+ }
530
+ function markSessionCleanupPending(db, sessionId) {
531
+ db.prepare(`INSERT INTO pending_session_cleanup (session_id, harness, requested_at, last_attempt_at)
532
+ VALUES (?, ?, ?, NULL)
533
+ ON CONFLICT(session_id) DO UPDATE SET
534
+ harness = excluded.harness,
535
+ requested_at = MIN(pending_session_cleanup.requested_at, excluded.requested_at)`).run(sessionId, getHarness(), Date.now());
536
+ }
537
+ function retryPendingSessionCleanups(db, limit = 200) {
538
+ const rows = db.prepare("SELECT session_id FROM pending_session_cleanup ORDER BY requested_at ASC, session_id ASC LIMIT ?").all(Math.max(1, Math.floor(limit)));
539
+ const failedSessionIds = [];
540
+ let cleared = 0;
541
+ for (const row of rows) {
542
+ try {
543
+ db.prepare("UPDATE pending_session_cleanup SET last_attempt_at = ? WHERE session_id = ?").run(Date.now(), row.session_id);
544
+ clearSession(db, row.session_id);
545
+ cleared += 1;
546
+ } catch {
547
+ failedSessionIds.push(row.session_id);
548
+ }
549
+ }
550
+ return { attempted: rows.length, cleared, failedSessionIds };
551
+ }
552
+ function clearSession(db, sessionId) {
553
+ db.transaction(() => {
554
+ deleteSessionScopedRows(db, [sessionId]);
555
+ })();
556
+ }
557
+
558
+ export { ensureSessionMetaRow, persistCachedM0, clearCachedM0M1, deleteSessionScopedRows, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, markSessionCleanupPending, retryPendingSessionCleanups, clearSession };
@@ -9,11 +9,13 @@ var PI_TO_CANONICAL_PROVIDER = {
9
9
  };
10
10
  var CANONICAL_TO_OMP_PROVIDER = {
11
11
  openai: "openai-codex",
12
- google: "google-antigravity"
12
+ google: "google-antigravity",
13
+ opencode: "opencode-zen"
13
14
  };
14
15
  var OMP_TO_CANONICAL_PROVIDER = {
15
16
  "openai-codex": "openai",
16
- "google-antigravity": "google"
17
+ "google-antigravity": "google",
18
+ "opencode-zen": "opencode"
17
19
  };
18
20
  function remapProviderPrefix(ref, map) {
19
21
  if (typeof ref !== "string")