@cortexkit/opencode-magic-context 0.33.0 → 0.34.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 (265) hide show
  1. package/dist/config/agent-disable.d.ts +22 -0
  2. package/dist/config/agent-disable.d.ts.map +1 -1
  3. package/dist/config/index.d.ts.map +1 -1
  4. package/dist/config/project-security.d.ts +7 -0
  5. package/dist/config/project-security.d.ts.map +1 -1
  6. package/dist/config/schema/magic-context.d.ts +144 -24
  7. package/dist/config/schema/magic-context.d.ts.map +1 -1
  8. package/dist/config/transform-mode.d.ts +2 -0
  9. package/dist/config/transform-mode.d.ts.map +1 -1
  10. package/dist/{conflict-warning-hook-bwa99a04.js → conflict-warning-hook-fvpfvt0w.js} +1 -1
  11. package/dist/{derive-budgets-e9j09sjr.js → derive-budgets-9crp0cvd.js} +1 -1
  12. package/dist/features/builtin-commands/commands.d.ts +1 -1
  13. package/dist/features/builtin-commands/commands.d.ts.map +1 -1
  14. package/dist/features/magic-context/compaction-marker.d.ts +106 -0
  15. package/dist/features/magic-context/compaction-marker.d.ts.map +1 -1
  16. package/dist/features/magic-context/compartment-chunk-embedding.d.ts +0 -2
  17. package/dist/features/magic-context/compartment-chunk-embedding.d.ts.map +1 -1
  18. package/dist/features/magic-context/dreamer/classify.d.ts.map +1 -1
  19. package/dist/features/magic-context/dreamer/evaluate-smart-notes.d.ts.map +1 -1
  20. package/dist/features/magic-context/dreamer/map-memories.d.ts.map +1 -1
  21. package/dist/features/magic-context/dreamer/refresh-primers.d.ts.map +1 -1
  22. package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
  23. package/dist/features/magic-context/dreamer/task-registry.d.ts +0 -1
  24. package/dist/features/magic-context/dreamer/task-registry.d.ts.map +1 -1
  25. package/dist/features/magic-context/dreamer/verify.d.ts.map +1 -1
  26. package/dist/features/magic-context/fail-closed-block.d.ts +10 -0
  27. package/dist/features/magic-context/fail-closed-block.d.ts.map +1 -1
  28. package/dist/features/magic-context/git-commits/index.d.ts +2 -2
  29. package/dist/features/magic-context/git-commits/index.d.ts.map +1 -1
  30. package/dist/features/magic-context/git-commits/storage-git-commit-embeddings.d.ts +0 -2
  31. package/dist/features/magic-context/git-commits/storage-git-commit-embeddings.d.ts.map +1 -1
  32. package/dist/features/magic-context/git-commits/storage-git-commits.d.ts +0 -13
  33. package/dist/features/magic-context/git-commits/storage-git-commits.d.ts.map +1 -1
  34. package/dist/features/magic-context/memory/embedding-identity.d.ts.map +1 -1
  35. package/dist/features/magic-context/memory/embedding-local.d.ts +7 -1
  36. package/dist/features/magic-context/memory/embedding-local.d.ts.map +1 -1
  37. package/dist/features/magic-context/memory/embedding.d.ts +1 -2
  38. package/dist/features/magic-context/memory/embedding.d.ts.map +1 -1
  39. package/dist/features/magic-context/memory/memory-migration.d.ts +0 -6
  40. package/dist/features/magic-context/memory/memory-migration.d.ts.map +1 -1
  41. package/dist/features/magic-context/memory/project-identity.d.ts +2 -6
  42. package/dist/features/magic-context/memory/project-identity.d.ts.map +1 -1
  43. package/dist/features/magic-context/memory/storage-memory-embeddings.d.ts +0 -1
  44. package/dist/features/magic-context/memory/storage-memory-embeddings.d.ts.map +1 -1
  45. package/dist/features/magic-context/memory/storage-memory.d.ts +1 -6
  46. package/dist/features/magic-context/memory/storage-memory.d.ts.map +1 -1
  47. package/dist/features/magic-context/memory/verification-paths.d.ts +0 -1
  48. package/dist/features/magic-context/memory/verification-paths.d.ts.map +1 -1
  49. package/dist/features/magic-context/migrations.d.ts.map +1 -1
  50. package/dist/features/magic-context/mural/compress-cues.d.ts.map +1 -1
  51. package/dist/features/magic-context/mural/render-mural.d.ts.map +1 -1
  52. package/dist/features/magic-context/mural/storage-mural.d.ts +0 -1
  53. package/dist/features/magic-context/mural/storage-mural.d.ts.map +1 -1
  54. package/dist/features/magic-context/overflow-detection.d.ts +8 -1
  55. package/dist/features/magic-context/overflow-detection.d.ts.map +1 -1
  56. package/dist/features/magic-context/project-embedding-registry.d.ts +16 -2
  57. package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
  58. package/dist/features/magic-context/scheduler.d.ts.map +1 -1
  59. package/dist/features/magic-context/schema-fence-probe.d.ts +28 -0
  60. package/dist/features/magic-context/schema-fence-probe.d.ts.map +1 -0
  61. package/dist/features/magic-context/sidekick/agent.d.ts.map +1 -1
  62. package/dist/features/magic-context/smart-notes/capabilities.d.ts +0 -2
  63. package/dist/features/magic-context/smart-notes/capabilities.d.ts.map +1 -1
  64. package/dist/features/magic-context/smart-notes/compiler.d.ts +0 -1
  65. package/dist/features/magic-context/smart-notes/compiler.d.ts.map +1 -1
  66. package/dist/features/magic-context/smart-notes/types.d.ts +0 -16
  67. package/dist/features/magic-context/smart-notes/types.d.ts.map +1 -1
  68. package/dist/features/magic-context/storage-db.d.ts +35 -1
  69. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  70. package/dist/features/magic-context/storage-meta-persisted.d.ts +38 -5
  71. package/dist/features/magic-context/storage-meta-persisted.d.ts.map +1 -1
  72. package/dist/features/magic-context/storage-meta.d.ts +1 -1
  73. package/dist/features/magic-context/storage-meta.d.ts.map +1 -1
  74. package/dist/features/magic-context/storage.d.ts +1 -1
  75. package/dist/features/magic-context/storage.d.ts.map +1 -1
  76. package/dist/features/magic-context/user-memory/review-user-memories.d.ts.map +1 -1
  77. package/dist/features/magic-context/user-memory/storage-user-memory.d.ts +0 -2
  78. package/dist/features/magic-context/user-memory/storage-user-memory.d.ts.map +1 -1
  79. package/dist/hooks/auto-update-checker/types.d.ts +0 -3
  80. package/dist/hooks/auto-update-checker/types.d.ts.map +1 -1
  81. package/dist/hooks/magic-context/boundary-execution.d.ts +1 -1
  82. package/dist/hooks/magic-context/boundary-execution.d.ts.map +1 -1
  83. package/dist/hooks/magic-context/cache-busting-signals.d.ts +1 -1
  84. package/dist/hooks/magic-context/cache-busting-signals.d.ts.map +1 -1
  85. package/dist/hooks/magic-context/channel2-delivery.d.ts.map +1 -1
  86. package/dist/hooks/magic-context/child-session-spawn.d.ts +26 -0
  87. package/dist/hooks/magic-context/child-session-spawn.d.ts.map +1 -0
  88. package/dist/hooks/magic-context/command-handler.d.ts +2 -0
  89. package/dist/hooks/magic-context/command-handler.d.ts.map +1 -1
  90. package/dist/hooks/magic-context/compaction-marker-manager.d.ts +49 -0
  91. package/dist/hooks/magic-context/compaction-marker-manager.d.ts.map +1 -1
  92. package/dist/hooks/magic-context/compaction-off-transition.d.ts +96 -0
  93. package/dist/hooks/magic-context/compaction-off-transition.d.ts.map +1 -0
  94. package/dist/hooks/magic-context/compartment-parser.d.ts +12 -0
  95. package/dist/hooks/magic-context/compartment-parser.d.ts.map +1 -1
  96. package/dist/hooks/magic-context/compartment-runner-historian.d.ts +2 -0
  97. package/dist/hooks/magic-context/compartment-runner-historian.d.ts.map +1 -1
  98. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  99. package/dist/hooks/magic-context/compartment-runner-mapping.d.ts +0 -12
  100. package/dist/hooks/magic-context/compartment-runner-mapping.d.ts.map +1 -1
  101. package/dist/hooks/magic-context/compartment-runner-partial-recomp.d.ts.map +1 -1
  102. package/dist/hooks/magic-context/compartment-runner-recomp.d.ts.map +1 -1
  103. package/dist/hooks/magic-context/compartment-trigger.d.ts +12 -5
  104. package/dist/hooks/magic-context/compartment-trigger.d.ts.map +1 -1
  105. package/dist/hooks/magic-context/ctx-reduce-availability.d.ts +47 -1
  106. package/dist/hooks/magic-context/ctx-reduce-availability.d.ts.map +1 -1
  107. package/dist/hooks/magic-context/emergency-drop.d.ts +2 -2
  108. package/dist/hooks/magic-context/event-handler.d.ts +7 -0
  109. package/dist/hooks/magic-context/event-handler.d.ts.map +1 -1
  110. package/dist/hooks/magic-context/event-resolvers.d.ts +13 -21
  111. package/dist/hooks/magic-context/event-resolvers.d.ts.map +1 -1
  112. package/dist/hooks/magic-context/final-wire-token-estimate.d.ts +2 -0
  113. package/dist/hooks/magic-context/final-wire-token-estimate.d.ts.map +1 -1
  114. package/dist/hooks/magic-context/heuristic-cleanup.d.ts +1 -1
  115. package/dist/hooks/magic-context/historian-prompt.generated.d.ts +1 -1
  116. package/dist/hooks/magic-context/historian-prompt.generated.d.ts.map +1 -1
  117. package/dist/hooks/magic-context/hook-handlers.d.ts +1 -0
  118. package/dist/hooks/magic-context/hook-handlers.d.ts.map +1 -1
  119. package/dist/hooks/magic-context/hook.d.ts +11 -1
  120. package/dist/hooks/magic-context/hook.d.ts.map +1 -1
  121. package/dist/hooks/magic-context/inject-compartments.d.ts +18 -0
  122. package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
  123. package/dist/hooks/magic-context/protected-tail-boundary.d.ts.map +1 -1
  124. package/dist/hooks/magic-context/read-session-db.d.ts.map +1 -1
  125. package/dist/hooks/magic-context/read-session-true-raw-tokens.d.ts.map +1 -1
  126. package/dist/hooks/magic-context/rust-mode-transform.d.ts +3 -0
  127. package/dist/hooks/magic-context/rust-mode-transform.d.ts.map +1 -1
  128. package/dist/hooks/magic-context/send-session-notification.d.ts +20 -1
  129. package/dist/hooks/magic-context/send-session-notification.d.ts.map +1 -1
  130. package/dist/hooks/magic-context/sentinel.d.ts +39 -0
  131. package/dist/hooks/magic-context/sentinel.d.ts.map +1 -1
  132. package/dist/hooks/magic-context/tag-messages.d.ts.map +1 -1
  133. package/dist/hooks/magic-context/tool-drop-target.d.ts +19 -0
  134. package/dist/hooks/magic-context/tool-drop-target.d.ts.map +1 -1
  135. package/dist/hooks/magic-context/transform-compartment-phase.d.ts +3 -0
  136. package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
  137. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +30 -0
  138. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  139. package/dist/hooks/magic-context/transform.d.ts +27 -0
  140. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  141. package/dist/{index-kxz4tn6m.js → index-56yjaeb2.js} +56 -4
  142. package/dist/{index-bmkea2dq.js → index-b563sga5.js} +40 -287
  143. package/dist/{index-y1c9tcm3.js → index-cn960ffd.js} +101 -20
  144. package/dist/{index-k5y60ymm.js → index-dtas91s5.js} +27 -6
  145. package/dist/index-fcyvznch.js +279 -0
  146. package/dist/{index-63dq2g4d.js → index-ry8rh8cv.js} +138 -24
  147. package/dist/{index-h86twgsp.js → index-s0mdn690.js} +2113 -1067
  148. package/dist/index.d.ts.map +1 -1
  149. package/dist/index.js +1356 -627
  150. package/dist/plugin/embedding-bootstrap.d.ts.map +1 -1
  151. package/dist/plugin/hooks/create-session-hooks.d.ts +19 -8
  152. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  153. package/dist/plugin/messages-transform.d.ts +10 -0
  154. package/dist/plugin/messages-transform.d.ts.map +1 -1
  155. package/dist/plugin/rpc-handlers.d.ts +3 -7
  156. package/dist/plugin/rpc-handlers.d.ts.map +1 -1
  157. package/dist/plugin/tool-registry.d.ts +8 -0
  158. package/dist/plugin/tool-registry.d.ts.map +1 -1
  159. package/dist/{recomp-orchestrator-yh7pepvx.js → recomp-orchestrator-8e82vmvb.js} +6 -5
  160. package/dist/send-session-notification-6njqewzk.js +20 -0
  161. package/dist/shared/conflict-detector.d.ts +38 -1
  162. package/dist/shared/conflict-detector.d.ts.map +1 -1
  163. package/dist/shared/conflict-fixer.d.ts +18 -1
  164. package/dist/shared/conflict-fixer.d.ts.map +1 -1
  165. package/dist/shared/context-limit-provenance.d.ts +3 -0
  166. package/dist/shared/context-limit-provenance.d.ts.map +1 -0
  167. package/dist/shared/escalation-bands.d.ts +9 -0
  168. package/dist/shared/escalation-bands.d.ts.map +1 -0
  169. package/dist/shared/format-threshold.d.ts +1 -1
  170. package/dist/shared/models-dev-cache.d.ts +29 -3
  171. package/dist/shared/models-dev-cache.d.ts.map +1 -1
  172. package/dist/shared/rpc-server.d.ts.map +1 -1
  173. package/dist/shared/rpc-types.d.ts +46 -1
  174. package/dist/shared/rpc-types.d.ts.map +1 -1
  175. package/dist/shared/sqlite.d.ts +9 -4
  176. package/dist/shared/sqlite.d.ts.map +1 -1
  177. package/dist/shared/storage-permissions.d.ts +5 -0
  178. package/dist/shared/storage-permissions.d.ts.map +1 -0
  179. package/dist/{storage-meta-session-1phy0b1z.js → storage-meta-session-xt41zbw4.js} +2 -1
  180. package/dist/{task-config-dn9k9szr.js → task-config-5nx3qfz8.js} +1 -2
  181. package/dist/tui/compaction-off.d.ts +13 -0
  182. package/dist/tui/compaction-off.d.ts.map +1 -0
  183. package/dist/tui/data/context-db.d.ts.map +1 -1
  184. package/dist/tui-compiled/compaction-off.d.ts +13 -0
  185. package/dist/tui-compiled/compaction-off.d.ts.map +1 -0
  186. package/dist/tui-compiled/data/context-db.d.ts.map +1 -1
  187. package/package.json +8 -3
  188. package/src/agents/dreamer.ts +68 -0
  189. package/src/agents/hidden-agent-registrations.ts +331 -0
  190. package/src/agents/historian.ts +3 -0
  191. package/src/agents/language-directive.test.ts +138 -0
  192. package/src/agents/language-directive.ts +121 -0
  193. package/src/agents/magic-context-prompt.language.test.ts +35 -0
  194. package/src/agents/magic-context-prompt.test.ts +292 -0
  195. package/src/agents/magic-context-prompt.ts +182 -0
  196. package/src/agents/permissions.test.ts +252 -0
  197. package/src/agents/permissions.ts +186 -0
  198. package/src/agents/sidekick.ts +1 -0
  199. package/src/agents/smart-note-compiler.ts +1 -0
  200. package/src/config/agent-disable.ts +106 -0
  201. package/src/config/compaction-accessor-guard.test.ts +82 -0
  202. package/src/config/compaction-backcompat.test.ts +52 -0
  203. package/src/config/index.test.ts +904 -0
  204. package/src/config/index.ts +601 -0
  205. package/src/config/migrate-config-location.test.ts +332 -0
  206. package/src/config/migrate-config-location.ts +635 -0
  207. package/src/config/migrate-dreamer-v2.test.ts +287 -0
  208. package/src/config/migrate-dreamer-v2.ts +336 -0
  209. package/src/config/migrate-experimental.ts +159 -0
  210. package/src/config/project-security.test.ts +366 -0
  211. package/src/config/project-security.ts +588 -0
  212. package/src/config/prune-config-leaf.test.ts +78 -0
  213. package/src/config/prune-config-leaf.ts +68 -0
  214. package/src/config/removed-config-keys.test.ts +116 -0
  215. package/src/config/schema/agent-overrides.ts +45 -0
  216. package/src/config/schema/magic-context.test.ts +358 -0
  217. package/src/config/schema/magic-context.ts +1002 -0
  218. package/src/config/transform-mode.test.ts +62 -0
  219. package/src/config/transform-mode.ts +34 -0
  220. package/src/config/variable.test.ts +323 -0
  221. package/src/config/variable.ts +192 -0
  222. package/src/features/magic-context/defaults.ts +1 -0
  223. package/src/features/magic-context/dreamer/cron.ts +243 -0
  224. package/src/features/magic-context/dreamer/task-registry.ts +104 -0
  225. package/src/shared/conflict-detector.test.ts +251 -1
  226. package/src/shared/conflict-detector.ts +84 -5
  227. package/src/shared/conflict-fixer.test.ts +309 -0
  228. package/src/shared/conflict-fixer.ts +82 -5
  229. package/src/shared/context-limit-provenance.ts +6 -0
  230. package/src/shared/escalation-bands.test.ts +23 -0
  231. package/src/shared/escalation-bands.ts +18 -0
  232. package/src/shared/format-threshold.ts +1 -1
  233. package/src/shared/models-dev-cache.test.ts +171 -0
  234. package/src/shared/models-dev-cache.ts +195 -38
  235. package/src/shared/rpc-server.ts +27 -18
  236. package/src/shared/rpc-types.ts +46 -1
  237. package/src/shared/sqlite.ts +13 -33
  238. package/src/shared/storage-permissions.ts +20 -0
  239. package/src/tui/compaction-off.test.ts +56 -0
  240. package/src/tui/compaction-off.ts +29 -0
  241. package/src/tui/data/context-db.ts +6 -0
  242. package/src/tui/index.tsx +113 -65
  243. package/src/tui/slots/sidebar-content.tsx +139 -83
  244. package/src/tui-compiled/compaction-off.ts +29 -0
  245. package/src/tui-compiled/data/context-db.ts +6 -0
  246. package/src/tui-compiled/index.tsx +558 -455
  247. package/src/tui-compiled/slots/sidebar-content.tsx +237 -161
  248. package/dist/config/schema.d.ts +0 -3
  249. package/dist/config/schema.d.ts.map +0 -1
  250. package/dist/features/magic-context/plugin-messages.d.ts +0 -75
  251. package/dist/features/magic-context/plugin-messages.d.ts.map +0 -1
  252. package/dist/hooks/magic-context/compartment-runner-state-xml.d.ts +0 -21
  253. package/dist/hooks/magic-context/compartment-runner-state-xml.d.ts.map +0 -1
  254. package/dist/index-anhrfygk.js +0 -57
  255. package/dist/send-session-notification-tghq9gnh.js +0 -11
  256. package/dist/shared/opencode-compaction-detector.d.ts +0 -2
  257. package/dist/shared/opencode-compaction-detector.d.ts.map +0 -1
  258. package/dist/shared/transcript-opencode.d.ts +0 -71
  259. package/dist/shared/transcript-opencode.d.ts.map +0 -1
  260. package/dist/tools/index.d.ts +0 -6
  261. package/dist/tools/index.d.ts.map +0 -1
  262. package/src/shared/opencode-compaction-detector.test.ts +0 -239
  263. package/src/shared/opencode-compaction-detector.ts +0 -81
  264. package/src/shared/transcript-opencode.ts +0 -302
  265. /package/dist/{index-v7fmc1s2.js → index-ygcng9t8.js} +0 -0
@@ -0,0 +1,279 @@
1
+ import {
2
+ log
3
+ } from "./index-k1esqfwk.js";
4
+ import {
5
+ getDataDir
6
+ } from "./index-kvrcg31b.js";
7
+
8
+ // src/shared/sqlite-helpers.ts
9
+ function closeQuietly(db) {
10
+ if (!db)
11
+ return;
12
+ try {
13
+ db.close();
14
+ } catch {}
15
+ }
16
+
17
+ // src/hooks/magic-context/read-session-db.ts
18
+ import { existsSync } from "node:fs";
19
+ import { join } from "node:path";
20
+
21
+ // src/shared/sqlite.ts
22
+ var isBun = typeof process !== "undefined" && typeof process.versions?.bun === "string";
23
+ var bunSpec = "bun:" + "sqlite";
24
+ var nodeSpec = "node:" + "sqlite";
25
+ var sqliteModule = isBun ? await import(bunSpec) : await import(nodeSpec);
26
+ var DatabaseImpl = isBun ? sqliteModule.Database : buildNodeSqliteDatabaseClass(sqliteModule.DatabaseSync);
27
+ function buildNodeSqliteDatabaseClass(DatabaseSync) {
28
+ const SAVEPOINT = "mc_tx_sp";
29
+
30
+ class NodeSqliteDatabase extends DatabaseSync {
31
+ constructor(filename, options) {
32
+ const translated = { ...options };
33
+ if (options && "readonly" in options) {
34
+ translated.readOnly = options.readonly;
35
+ delete translated.readonly;
36
+ }
37
+ super(typeof filename === "string" ? filename : ":memory:", translated);
38
+ }
39
+ prepare(sql) {
40
+ const stmt = super.prepare(sql);
41
+ for (const method of ["run", "get", "all"]) {
42
+ const original = stmt[method].bind(stmt);
43
+ stmt[method] = (...args) => args.length === 1 && Array.isArray(args[0]) ? original(...args[0]) : original(...args);
44
+ }
45
+ return stmt;
46
+ }
47
+ transaction(fn) {
48
+ const self = this;
49
+ const execute = (mode, receiver, args) => {
50
+ const nested = self.isTransaction === true;
51
+ self.exec(nested ? `SAVEPOINT ${SAVEPOINT}` : `BEGIN${mode ? ` ${mode}` : ""}`);
52
+ try {
53
+ const result = fn.apply(receiver, args);
54
+ self.exec(nested ? `RELEASE ${SAVEPOINT}` : "COMMIT");
55
+ return result;
56
+ } catch (error) {
57
+ if (nested) {
58
+ self.exec(`ROLLBACK TO ${SAVEPOINT}`);
59
+ self.exec(`RELEASE ${SAVEPOINT}`);
60
+ } else {
61
+ self.exec("ROLLBACK");
62
+ }
63
+ throw error;
64
+ }
65
+ };
66
+ const wrapped = function(...args) {
67
+ return execute("", this, args);
68
+ };
69
+ wrapped.default = function(...args) {
70
+ return execute("", this, args);
71
+ };
72
+ wrapped.deferred = function(...args) {
73
+ return execute("DEFERRED", this, args);
74
+ };
75
+ wrapped.immediate = function(...args) {
76
+ return execute("IMMEDIATE", this, args);
77
+ };
78
+ wrapped.exclusive = function(...args) {
79
+ return execute("EXCLUSIVE", this, args);
80
+ };
81
+ return wrapped;
82
+ }
83
+ }
84
+ return NodeSqliteDatabase;
85
+ }
86
+ var Database = DatabaseImpl;
87
+ var privilegeDepth = new WeakMap;
88
+ function isInTransaction(db) {
89
+ const candidate = db;
90
+ return candidate.inTransaction === true || candidate.isTransaction === true;
91
+ }
92
+ function withPrivilegedWriter(db, operation) {
93
+ const previousDepth = privilegeDepth.get(db) ?? 0;
94
+ const nested = isInTransaction(db);
95
+ const savepoint = "mc_privilege_scope";
96
+ if (nested) {
97
+ db.exec(`SAVEPOINT ${savepoint}`);
98
+ } else {
99
+ db.exec("BEGIN IMMEDIATE");
100
+ }
101
+ privilegeDepth.set(db, previousDepth + 1);
102
+ try {
103
+ db.prepare("INSERT INTO context_privilege_state(id, enabled) VALUES (1, 1) ON CONFLICT(id) DO UPDATE SET enabled = 1").run();
104
+ const result = operation();
105
+ if (previousDepth === 0) {
106
+ db.prepare("UPDATE context_privilege_state SET enabled = 0 WHERE id = 1").run();
107
+ }
108
+ if (nested) {
109
+ db.exec(`RELEASE ${savepoint}`);
110
+ } else {
111
+ db.exec("COMMIT");
112
+ }
113
+ if (previousDepth > 0)
114
+ privilegeDepth.set(db, previousDepth);
115
+ else
116
+ privilegeDepth.delete(db);
117
+ return result;
118
+ } catch (error) {
119
+ try {
120
+ if (nested) {
121
+ db.exec(`ROLLBACK TO ${savepoint}`);
122
+ db.exec(`RELEASE ${savepoint}`);
123
+ } else {
124
+ db.exec("ROLLBACK");
125
+ }
126
+ } finally {
127
+ if (previousDepth > 0)
128
+ privilegeDepth.set(db, previousDepth);
129
+ else
130
+ privilegeDepth.delete(db);
131
+ }
132
+ throw error;
133
+ }
134
+ }
135
+
136
+ // src/hooks/magic-context/read-session-db.ts
137
+ function getOpenCodeDbPath() {
138
+ return join(getDataDir(), "opencode", "opencode.db");
139
+ }
140
+ function openCodeDbExists() {
141
+ return existsSync(getOpenCodeDbPath());
142
+ }
143
+ var cachedReadOnlyDb = null;
144
+ function closeCachedReadOnlyDb() {
145
+ if (!cachedReadOnlyDb) {
146
+ return;
147
+ }
148
+ try {
149
+ closeQuietly(cachedReadOnlyDb.db);
150
+ } catch (error) {
151
+ log("[magic-context] failed to close cached OpenCode read-only DB:", error);
152
+ } finally {
153
+ cachedReadOnlyDb = null;
154
+ }
155
+ }
156
+ function getReadOnlySessionDb() {
157
+ const dbPath = getOpenCodeDbPath();
158
+ if (cachedReadOnlyDb?.path === dbPath) {
159
+ return cachedReadOnlyDb.db;
160
+ }
161
+ closeCachedReadOnlyDb();
162
+ const db = new Database(dbPath, { readonly: true });
163
+ cachedReadOnlyDb = { path: dbPath, db };
164
+ return db;
165
+ }
166
+ function withReadOnlySessionDb(fn) {
167
+ return fn(getReadOnlySessionDb());
168
+ }
169
+ function getRawSessionMessageCountFromDb(db, sessionId) {
170
+ const row = db.prepare(`SELECT COUNT(*) as count FROM message WHERE session_id = ?
171
+ AND NOT (COALESCE(json_extract(data, '$.summary'), 0) = 1
172
+ AND COALESCE(json_extract(data, '$.finish'), '') = 'stop')`).get(sessionId);
173
+ return typeof row?.count === "number" ? row.count : 0;
174
+ }
175
+ function isMidTurn(_deps, sessionId) {
176
+ try {
177
+ return withReadOnlySessionDb((db) => isMidTurnFromOpenCodeDb(db, sessionId));
178
+ } catch (error) {
179
+ log("[magic-context] failed to inspect OpenCode mid-turn state:", error);
180
+ return false;
181
+ }
182
+ }
183
+ function isMidTurnFromOpenCodeDb(db, sessionId) {
184
+ const latestAssistant = db.prepare(`SELECT id,
185
+ json_extract(data, '$.finish') as finish,
186
+ time_created as timeCreated
187
+ FROM message
188
+ WHERE session_id = ?
189
+ AND json_extract(data, '$.role') = 'assistant'
190
+ ORDER BY time_created DESC
191
+ LIMIT 1`).get(sessionId);
192
+ if (typeof latestAssistant?.id !== "string")
193
+ return false;
194
+ if (hasNewerRealUserMessage(db, sessionId, latestAssistant.timeCreated))
195
+ return false;
196
+ if (latestAssistant.finish === "tool-calls")
197
+ return true;
198
+ const partRows = db.prepare("SELECT data FROM part WHERE session_id = ? AND message_id = ?").all(sessionId, latestAssistant.id);
199
+ return partRows.some((row) => {
200
+ if (typeof row.data !== "string" || row.data.length === 0)
201
+ return false;
202
+ try {
203
+ const part = JSON.parse(row.data);
204
+ return part.type === "tool" && part.providerExecuted !== true;
205
+ } catch {
206
+ return false;
207
+ }
208
+ });
209
+ }
210
+ function hasNewerRealUserMessage(db, sessionId, latestAssistantTimeCreated) {
211
+ if (typeof latestAssistantTimeCreated !== "number")
212
+ return false;
213
+ const row = db.prepare(`SELECT 1 as one
214
+ FROM message m
215
+ WHERE m.session_id = ?
216
+ AND m.time_created > ?
217
+ AND json_extract(m.data, '$.role') = 'user'
218
+ AND NOT (
219
+ EXISTS (SELECT 1 FROM part p WHERE p.message_id = m.id)
220
+ AND NOT EXISTS (
221
+ SELECT 1 FROM part p
222
+ WHERE p.message_id = m.id
223
+ AND COALESCE(json_extract(p.data, '$.synthetic'), 0) NOT IN (1, 'true')
224
+ AND json_extract(p.data, '$.metadata.marker.kind') IS NULL
225
+ AND COALESCE(json_extract(p.data, '$.ignored'), 0) NOT IN (1, 'true')
226
+ )
227
+ )
228
+ LIMIT 1`).get(sessionId, latestAssistantTimeCreated);
229
+ return row?.one === 1;
230
+ }
231
+ function getMessageTimesFromOpenCodeDb(sessionId, messageIds) {
232
+ const result = new Map;
233
+ if (messageIds.length === 0)
234
+ return result;
235
+ try {
236
+ withReadOnlySessionDb((db) => {
237
+ const placeholders = messageIds.map(() => "?").join(",");
238
+ const rows = db.prepare(`SELECT id, time_created FROM message WHERE session_id = ? AND id IN (${placeholders})`).all(sessionId, ...messageIds);
239
+ for (const row of rows) {
240
+ if (typeof row.id === "string" && typeof row.time_created === "number") {
241
+ result.set(row.id, row.time_created);
242
+ }
243
+ }
244
+ });
245
+ } catch (error) {
246
+ log("[magic-context] failed to resolve message times from OpenCode DB:", error);
247
+ }
248
+ return result;
249
+ }
250
+ function findLastAssistantModelFromOpenCodeDb(sessionId) {
251
+ try {
252
+ return withReadOnlySessionDb((db) => {
253
+ const row = db.prepare(`SELECT json_extract(data, '$.providerID') as providerID,
254
+ json_extract(data, '$.modelID') as modelID,
255
+ json_extract(data, '$.agent') as agent
256
+ FROM message
257
+ WHERE session_id = ?
258
+ AND json_extract(data, '$.role') = 'assistant'
259
+ AND json_extract(data, '$.providerID') IS NOT NULL
260
+ AND json_extract(data, '$.modelID') IS NOT NULL
261
+ ORDER BY time_created DESC
262
+ LIMIT 1`).get(sessionId);
263
+ if (!row || typeof row.providerID !== "string" || typeof row.modelID !== "string") {
264
+ return null;
265
+ }
266
+ const agent = typeof row.agent === "string" && row.agent.length > 0 ? row.agent : undefined;
267
+ return {
268
+ providerID: row.providerID,
269
+ modelID: row.modelID,
270
+ ...agent ? { agent } : {}
271
+ };
272
+ });
273
+ } catch (error) {
274
+ log("[magic-context] failed to recover live model from OpenCode DB:", error);
275
+ return null;
276
+ }
277
+ }
278
+
279
+ export { Database, withPrivilegedWriter, closeQuietly, openCodeDbExists, withReadOnlySessionDb, getRawSessionMessageCountFromDb, isMidTurn, getMessageTimesFromOpenCodeDb, findLastAssistantModelFromOpenCodeDb };
@@ -9,11 +9,46 @@ import {
9
9
  // src/shared/models-dev-cache.ts
10
10
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
11
11
  import { join } from "node:path";
12
+
13
+ // src/shared/harness-provider-map.ts
14
+ var PI_TO_CANONICAL_PROVIDER = {
15
+ "openai-codex": "openai",
16
+ "google-antigravity": "google"
17
+ };
18
+ function remapProviderPrefix(ref, map) {
19
+ if (typeof ref !== "string")
20
+ return ref;
21
+ const slash = ref.indexOf("/");
22
+ if (slash <= 0)
23
+ return ref;
24
+ const provider = ref.slice(0, slash);
25
+ const mapped = map[provider];
26
+ return mapped ? `${mapped}${ref.slice(slash)}` : ref;
27
+ }
28
+ function piModelRefToCanonical(ref) {
29
+ return remapProviderPrefix(ref, PI_TO_CANONICAL_PROVIDER);
30
+ }
31
+
32
+ // src/shared/storage-permissions.ts
33
+ var enforcePrivateStoragePermissions = true;
34
+ function setStoragePrivatePermissionEnforcement(enforce) {
35
+ enforcePrivateStoragePermissions = enforce;
36
+ }
37
+ function shouldEnforcePrivateStoragePermissions() {
38
+ return enforcePrivateStoragePermissions;
39
+ }
40
+
41
+ // src/shared/models-dev-cache.ts
12
42
  var MIN_SANE_LIMIT = 20000;
13
43
  var MAX_SANE_LIMIT = 3000000;
14
44
  function isSaneLimit(limit) {
15
45
  return typeof limit === "number" && limit >= MIN_SANE_LIMIT && limit <= MAX_SANE_LIMIT;
16
46
  }
47
+ var SEPARATE_OUTPUT_QUOTA_PROVIDERS = new Set(["google", "google-antigravity"]);
48
+ var MIN_PLAUSIBLE_CONTEXT_LIMIT = 1024;
49
+ var OUTPUT_RESERVE_CAP_RATIO = 0.25;
50
+ var outputReserveConfig;
51
+ var reserveClampLogSeen = new Set;
17
52
  var apiCache = null;
18
53
  var apiLoadedAt = 0;
19
54
  var persistSeedLoaded = false;
@@ -30,12 +65,16 @@ function loadPersistedApiCacheOnce() {
30
65
  const map = new Map;
31
66
  for (const [key, persisted] of Object.entries(obj)) {
32
67
  const limit = typeof persisted === "number" ? persisted : persisted.limit;
68
+ const contextLimit = typeof persisted === "number" ? undefined : persisted.contextLimit;
33
69
  const inputLimit = typeof persisted === "number" ? undefined : persisted.inputLimit;
70
+ const outputLimit = typeof persisted === "number" ? undefined : persisted.outputLimit;
34
71
  const vision = typeof persisted === "number" ? false : persisted.vision === true;
35
- if (isSaneLimit(limit)) {
72
+ if (isSaneLimit(contextLimit) || isSaneLimit(limit)) {
36
73
  map.set(key, {
37
- limit,
74
+ limit: isSaneLimit(limit) ? limit : undefined,
75
+ contextLimit: isSaneLimit(contextLimit) ? contextLimit : undefined,
38
76
  inputLimit: isSaneLimit(inputLimit) ? inputLimit : undefined,
77
+ outputLimit: isFinitePositive(outputLimit) ? outputLimit : undefined,
39
78
  vision
40
79
  });
41
80
  }
@@ -54,7 +93,9 @@ function persistApiCache() {
54
93
  if (isSaneLimit(value.limit)) {
55
94
  obj[key] = {
56
95
  limit: value.limit,
96
+ contextLimit: isSaneLimit(value.contextLimit) ? value.contextLimit : undefined,
57
97
  inputLimit: isSaneLimit(value.inputLimit) ? value.inputLimit : undefined,
98
+ outputLimit: isFinitePositive(value.outputLimit) ? value.outputLimit : undefined,
58
99
  vision: value.vision === true
59
100
  };
60
101
  }
@@ -64,30 +105,95 @@ function persistApiCache() {
64
105
  mkdirSync(dir, { recursive: true });
65
106
  const target = persistFilePath();
66
107
  const tmp = `${target}.${process.pid}.tmp`;
67
- writeFileSync(tmp, JSON.stringify(obj), { encoding: "utf-8", mode: 384 });
108
+ if (shouldEnforcePrivateStoragePermissions()) {
109
+ writeFileSync(tmp, JSON.stringify(obj), { encoding: "utf-8", mode: 384 });
110
+ } else {
111
+ writeFileSync(tmp, JSON.stringify(obj), { encoding: "utf-8" });
112
+ }
68
113
  renameSync(tmp, target);
69
114
  } catch {}
70
115
  }
71
- function resolveLimit(limit) {
116
+ function isFinitePositive(value) {
117
+ return typeof value === "number" && Number.isFinite(value) && value > 0;
118
+ }
119
+ function modelKeyLookupOrder(providerID, modelID) {
120
+ const full = `${providerID}/${modelID}`;
121
+ const canonicalFull = piModelRefToCanonical(full);
122
+ const candidates = [full, canonicalFull, modelID];
123
+ const colon = modelID.lastIndexOf(":");
124
+ if (colon > 0) {
125
+ const bareModel = modelID.slice(0, colon);
126
+ const providerBare = `${providerID}/${bareModel}`;
127
+ candidates.push(providerBare, piModelRefToCanonical(providerBare), bareModel);
128
+ }
129
+ return [...new Set(candidates)];
130
+ }
131
+ function configuredOutputReserve(config, providerID, modelID) {
132
+ if (typeof config === "number")
133
+ return Number.isFinite(config) && config >= 0 ? config : undefined;
134
+ if (!config)
135
+ return;
136
+ for (const candidate of modelKeyLookupOrder(providerID, modelID)) {
137
+ const value = config[candidate];
138
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0)
139
+ return value;
140
+ }
141
+ return Number.isFinite(config.default) && config.default >= 0 ? config.default : undefined;
142
+ }
143
+ function logReserveClampOnce(key, message) {
144
+ if (reserveClampLogSeen.has(key))
145
+ return;
146
+ reserveClampLogSeen.add(key);
147
+ sessionLog("global", `models-dev-cache: ${message}`);
148
+ }
149
+ function setOutputReserveConfig(config) {
150
+ outputReserveConfig = config;
151
+ }
152
+ function resolveLimit(limit, providerID, modelID, reserveConfig = outputReserveConfig) {
72
153
  if (!limit)
73
154
  return;
74
- if (typeof limit.input === "number" && limit.input > 0)
75
- return limit.input;
76
- if (typeof limit.context === "number" && limit.context > 0)
77
- return limit.context;
78
- return;
155
+ const context = isFinitePositive(limit.context) ? limit.context : undefined;
156
+ const input = isFinitePositive(limit.input) ? limit.input : undefined;
157
+ if (input !== undefined && (context === undefined || input < context))
158
+ return input;
159
+ if (context === undefined)
160
+ return;
161
+ const configuredReserve = configuredOutputReserve(reserveConfig, providerID, modelID);
162
+ let reserve;
163
+ if (configuredReserve !== undefined) {
164
+ reserve = configuredReserve;
165
+ } else if (SEPARATE_OUTPUT_QUOTA_PROVIDERS.has(providerID)) {
166
+ reserve = 0;
167
+ } else {
168
+ const output = isFinitePositive(limit.output) ? limit.output : 0;
169
+ const cap = context * OUTPUT_RESERVE_CAP_RATIO;
170
+ reserve = Math.min(output, cap);
171
+ if (output > cap) {
172
+ logReserveClampOnce(`cap|${providerID}/${modelID}|${context}|${output}`, `output reserve capped at 25% for ${providerID}/${modelID}: ${output} → ${cap}`);
173
+ }
174
+ }
175
+ const floor = Math.max(MIN_PLAUSIBLE_CONTEXT_LIMIT, context * 0.5);
176
+ const maxReserve = Math.max(0, context - floor);
177
+ if (reserve > maxReserve) {
178
+ logReserveClampOnce(`floor|${providerID}/${modelID}|${context}|${reserve}`, `output reserve clamped for ${providerID}/${modelID}: ${reserve} → ${maxReserve} (usable floor ${floor})`);
179
+ reserve = maxReserve;
180
+ }
181
+ return Math.floor(context - reserve);
79
182
  }
80
183
  function setCachedModelMetadata(cache, key, model) {
81
- const limit = resolveLimit(model?.limit);
184
+ const contextLimit = model?.limit?.context;
82
185
  const inputLimit = model?.limit?.input;
83
- if (!isSaneLimit(limit)) {
186
+ const outputLimit = model?.limit?.output;
187
+ const rawLimit = isSaneLimit(contextLimit) ? contextLimit : isSaneLimit(inputLimit) ? inputLimit : undefined;
188
+ if (rawLimit === undefined)
84
189
  return;
85
- }
86
190
  const values = [model?.capabilities, model?.modalities, model?.input, model?.attachment];
87
191
  const vision = values.some((value2) => JSON.stringify(value2 ?? "").toLowerCase().includes("image") || JSON.stringify(value2 ?? "").toLowerCase().includes("vision"));
88
192
  const value = {
89
- limit,
193
+ limit: rawLimit,
194
+ contextLimit: isSaneLimit(contextLimit) ? contextLimit : undefined,
90
195
  inputLimit: isSaneLimit(inputLimit) ? inputLimit : undefined,
196
+ outputLimit: isFinitePositive(outputLimit) ? outputLimit : undefined,
91
197
  vision
92
198
  };
93
199
  cache.set(key, value);
@@ -152,10 +258,21 @@ async function refreshModelLimitsOnce(client) {
152
258
  return false;
153
259
  }
154
260
  }
155
- function getSdkContextLimit(providerID, modelID) {
261
+ function getSdkContextLimit(providerID, modelID, detectedContextLimit, options) {
156
262
  loadPersistedApiCacheOnce();
157
- const fromApi = lookupLimitWithTagFallback(apiCache, providerID, modelID);
158
- return isSaneLimit(fromApi) ? fromApi : undefined;
263
+ const metadata = lookupMetadataWithTagFallback(apiCache, providerID, modelID);
264
+ if (!metadata)
265
+ return;
266
+ const rawContext = metadata.contextLimit ?? metadata.limit;
267
+ const promptOnlyDetected = options?.detectedLimitProvenance === "prompt_only" && isFinitePositive(detectedContextLimit) ? detectedContextLimit : undefined;
268
+ const context = promptOnlyDetected === undefined && isFinitePositive(detectedContextLimit) && isFinitePositive(rawContext) ? Math.min(rawContext, detectedContextLimit) : promptOnlyDetected === undefined && isFinitePositive(detectedContextLimit) ? detectedContextLimit : rawContext;
269
+ const inputCandidates = [metadata.inputLimit, promptOnlyDetected].filter(isFinitePositive);
270
+ const input = inputCandidates.length > 0 ? Math.min(...inputCandidates) : undefined;
271
+ return resolveLimit({
272
+ context,
273
+ input,
274
+ output: metadata.outputLimit
275
+ }, providerID, modelID, options?.reservation === "none" ? 0 : undefined);
159
276
  }
160
277
  function modelSupportsVision(providerID, modelID) {
161
278
  loadPersistedApiCacheOnce();
@@ -167,18 +284,15 @@ function modelSupportsVision(providerID, modelID) {
167
284
  const colon = modelID.lastIndexOf(":");
168
285
  return colon > 0 ? apiCache.get(`${providerID}/${modelID.slice(0, colon)}`)?.vision === true : false;
169
286
  }
170
- function lookupLimitWithTagFallback(cache, providerID, modelID) {
287
+ function lookupMetadataWithTagFallback(cache, providerID, modelID) {
171
288
  if (!cache)
172
289
  return;
173
- const exact = cache.get(`${providerID}/${modelID}`)?.limit;
174
- if (typeof exact === "number")
290
+ const exact = cache.get(`${providerID}/${modelID}`);
291
+ if (exact)
175
292
  return exact;
176
293
  const colonIdx = modelID.lastIndexOf(":");
177
294
  if (colonIdx > 0) {
178
- const baseModel = modelID.slice(0, colonIdx);
179
- const fallback = cache.get(`${providerID}/${baseModel}`)?.limit;
180
- if (typeof fallback === "number")
181
- return fallback;
295
+ return cache.get(`${providerID}/${modelID.slice(0, colonIdx)}`);
182
296
  }
183
297
  return;
184
298
  }
@@ -224,4 +338,4 @@ function resolveHistorianContextLimit(historianModelOverride) {
224
338
  return DEFAULT_HISTORIAN_CONTEXT_FALLBACK;
225
339
  }
226
340
 
227
- export { isSaneLimit, refreshModelLimitsFromApi, refreshModelLimitsAfterAuthOnce, getSdkContextLimit, modelSupportsVision, deriveTriggerBudget, deriveHistorianChunkTokens, resolveHistorianContextLimit };
341
+ export { piModelRefToCanonical, setStoragePrivatePermissionEnforcement, shouldEnforcePrivateStoragePermissions, isSaneLimit, setOutputReserveConfig, refreshModelLimitsFromApi, refreshModelLimitsAfterAuthOnce, getSdkContextLimit, modelSupportsVision, deriveTriggerBudget, deriveHistorianChunkTokens, resolveHistorianContextLimit };