@caupulican/pi-adaptative 0.81.26 → 0.81.29

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 (286) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/dist/cli/args.d.ts.map +1 -1
  3. package/dist/cli/args.js +3 -2
  4. package/dist/cli/args.js.map +1 -1
  5. package/dist/core/agent-session-services.d.ts +4 -0
  6. package/dist/core/agent-session-services.d.ts.map +1 -1
  7. package/dist/core/agent-session-services.js +19 -2
  8. package/dist/core/agent-session-services.js.map +1 -1
  9. package/dist/core/agent-session.d.ts +30 -12
  10. package/dist/core/agent-session.d.ts.map +1 -1
  11. package/dist/core/agent-session.js +128 -36
  12. package/dist/core/agent-session.js.map +1 -1
  13. package/dist/core/auth-storage.d.ts +6 -0
  14. package/dist/core/auth-storage.d.ts.map +1 -1
  15. package/dist/core/auth-storage.js +35 -0
  16. package/dist/core/auth-storage.js.map +1 -1
  17. package/dist/core/autonomy/bounded-completion.d.ts.map +1 -1
  18. package/dist/core/autonomy/bounded-completion.js +59 -19
  19. package/dist/core/autonomy/bounded-completion.js.map +1 -1
  20. package/dist/core/autonomy/contracts.d.ts +2 -0
  21. package/dist/core/autonomy/contracts.d.ts.map +1 -1
  22. package/dist/core/autonomy/contracts.js.map +1 -1
  23. package/dist/core/autonomy/lane-tool-surface.d.ts +31 -0
  24. package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -0
  25. package/dist/core/autonomy/lane-tool-surface.js +96 -0
  26. package/dist/core/autonomy/lane-tool-surface.js.map +1 -0
  27. package/dist/core/autonomy/lane-tracker.d.ts +5 -0
  28. package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
  29. package/dist/core/autonomy/lane-tracker.js +14 -3
  30. package/dist/core/autonomy/lane-tracker.js.map +1 -1
  31. package/dist/core/background-lane-controller.d.ts +28 -4
  32. package/dist/core/background-lane-controller.d.ts.map +1 -1
  33. package/dist/core/background-lane-controller.js +237 -28
  34. package/dist/core/background-lane-controller.js.map +1 -1
  35. package/dist/core/billing-failover-controller.d.ts.map +1 -1
  36. package/dist/core/billing-failover-controller.js +1 -1
  37. package/dist/core/billing-failover-controller.js.map +1 -1
  38. package/dist/core/context/current-work-memory.d.ts +9 -0
  39. package/dist/core/context/current-work-memory.d.ts.map +1 -0
  40. package/dist/core/context/current-work-memory.js +61 -0
  41. package/dist/core/context/current-work-memory.js.map +1 -0
  42. package/dist/core/context/file-store-memory-provider.d.ts +9 -0
  43. package/dist/core/context/file-store-memory-provider.d.ts.map +1 -0
  44. package/dist/core/context/file-store-memory-provider.js +106 -0
  45. package/dist/core/context/file-store-memory-provider.js.map +1 -0
  46. package/dist/core/context/long-term-memory-trigger.d.ts +15 -0
  47. package/dist/core/context/long-term-memory-trigger.d.ts.map +1 -0
  48. package/dist/core/context/long-term-memory-trigger.js +39 -0
  49. package/dist/core/context/long-term-memory-trigger.js.map +1 -0
  50. package/dist/core/context/memory-prompt-block.d.ts +3 -1
  51. package/dist/core/context/memory-prompt-block.d.ts.map +1 -1
  52. package/dist/core/context/memory-prompt-block.js +20 -3
  53. package/dist/core/context/memory-prompt-block.js.map +1 -1
  54. package/dist/core/context/memory-prompt-budget.d.ts +17 -0
  55. package/dist/core/context/memory-prompt-budget.d.ts.map +1 -0
  56. package/dist/core/context/memory-prompt-budget.js +64 -0
  57. package/dist/core/context/memory-prompt-budget.js.map +1 -0
  58. package/dist/core/context/memory-provider-contract.d.ts.map +1 -1
  59. package/dist/core/context/memory-provider-contract.js +2 -5
  60. package/dist/core/context/memory-provider-contract.js.map +1 -1
  61. package/dist/core/context/memory-tier-composer.d.ts +27 -0
  62. package/dist/core/context/memory-tier-composer.d.ts.map +1 -0
  63. package/dist/core/context/memory-tier-composer.js +79 -0
  64. package/dist/core/context/memory-tier-composer.js.map +1 -0
  65. package/dist/core/context-gc.d.ts.map +1 -1
  66. package/dist/core/context-gc.js +2 -0
  67. package/dist/core/context-gc.js.map +1 -1
  68. package/dist/core/context-pipeline.d.ts +5 -3
  69. package/dist/core/context-pipeline.d.ts.map +1 -1
  70. package/dist/core/context-pipeline.js +15 -5
  71. package/dist/core/context-pipeline.js.map +1 -1
  72. package/dist/core/cost/cost-summary.d.ts +3 -1
  73. package/dist/core/cost/cost-summary.d.ts.map +1 -1
  74. package/dist/core/cost/cost-summary.js +3 -3
  75. package/dist/core/cost/cost-summary.js.map +1 -1
  76. package/dist/core/cost-guard.d.ts +17 -7
  77. package/dist/core/cost-guard.d.ts.map +1 -1
  78. package/dist/core/cost-guard.js +33 -10
  79. package/dist/core/cost-guard.js.map +1 -1
  80. package/dist/core/default-tool-surface.d.ts +9 -0
  81. package/dist/core/default-tool-surface.d.ts.map +1 -0
  82. package/dist/core/default-tool-surface.js +18 -0
  83. package/dist/core/default-tool-surface.js.map +1 -0
  84. package/dist/core/delegation/worker-result.d.ts.map +1 -1
  85. package/dist/core/delegation/worker-result.js +3 -0
  86. package/dist/core/delegation/worker-result.js.map +1 -1
  87. package/dist/core/delegation/worker-runner.d.ts +11 -5
  88. package/dist/core/delegation/worker-runner.d.ts.map +1 -1
  89. package/dist/core/delegation/worker-runner.js +77 -16
  90. package/dist/core/delegation/worker-runner.js.map +1 -1
  91. package/dist/core/extensions/loader.d.ts.map +1 -1
  92. package/dist/core/extensions/loader.js +15 -0
  93. package/dist/core/extensions/loader.js.map +1 -1
  94. package/dist/core/extensions/runner.d.ts +2 -0
  95. package/dist/core/extensions/runner.d.ts.map +1 -1
  96. package/dist/core/extensions/runner.js +7 -0
  97. package/dist/core/extensions/runner.js.map +1 -1
  98. package/dist/core/extensions/types.d.ts +9 -0
  99. package/dist/core/extensions/types.d.ts.map +1 -1
  100. package/dist/core/extensions/types.js.map +1 -1
  101. package/dist/core/failure-corpus.d.ts.map +1 -1
  102. package/dist/core/failure-corpus.js +2 -4
  103. package/dist/core/failure-corpus.js.map +1 -1
  104. package/dist/core/footer-data-provider.d.ts.map +1 -1
  105. package/dist/core/footer-data-provider.js +9 -1
  106. package/dist/core/footer-data-provider.js.map +1 -1
  107. package/dist/core/goals/goal-continuation-prompt.d.ts.map +1 -1
  108. package/dist/core/goals/goal-continuation-prompt.js +4 -3
  109. package/dist/core/goals/goal-continuation-prompt.js.map +1 -1
  110. package/dist/core/http-dispatcher.d.ts +12 -0
  111. package/dist/core/http-dispatcher.d.ts.map +1 -1
  112. package/dist/core/http-dispatcher.js +42 -4
  113. package/dist/core/http-dispatcher.js.map +1 -1
  114. package/dist/core/local-runtime-controller.d.ts +16 -0
  115. package/dist/core/local-runtime-controller.d.ts.map +1 -1
  116. package/dist/core/local-runtime-controller.js +107 -28
  117. package/dist/core/local-runtime-controller.js.map +1 -1
  118. package/dist/core/memory/memory-manager.d.ts +8 -3
  119. package/dist/core/memory/memory-manager.d.ts.map +1 -1
  120. package/dist/core/memory/memory-manager.js +27 -11
  121. package/dist/core/memory/memory-manager.js.map +1 -1
  122. package/dist/core/memory/memory-provider.d.ts +5 -1
  123. package/dist/core/memory/memory-provider.d.ts.map +1 -1
  124. package/dist/core/memory/memory-provider.js.map +1 -1
  125. package/dist/core/memory/providers/file-store.d.ts +3 -1
  126. package/dist/core/memory/providers/file-store.d.ts.map +1 -1
  127. package/dist/core/memory/providers/file-store.js +7 -2
  128. package/dist/core/memory/providers/file-store.js.map +1 -1
  129. package/dist/core/memory/providers/transcript-recall.d.ts +1 -0
  130. package/dist/core/memory/providers/transcript-recall.d.ts.map +1 -1
  131. package/dist/core/memory/providers/transcript-recall.js +4 -7
  132. package/dist/core/memory/providers/transcript-recall.js.map +1 -1
  133. package/dist/core/memory-controller.d.ts +36 -10
  134. package/dist/core/memory-controller.d.ts.map +1 -1
  135. package/dist/core/memory-controller.js +137 -21
  136. package/dist/core/memory-controller.js.map +1 -1
  137. package/dist/core/model-registry.d.ts +25 -0
  138. package/dist/core/model-registry.d.ts.map +1 -1
  139. package/dist/core/model-registry.js +91 -8
  140. package/dist/core/model-registry.js.map +1 -1
  141. package/dist/core/model-resolver.d.ts.map +1 -1
  142. package/dist/core/model-resolver.js +30 -11
  143. package/dist/core/model-resolver.js.map +1 -1
  144. package/dist/core/model-router-controller.d.ts.map +1 -1
  145. package/dist/core/model-router-controller.js +33 -29
  146. package/dist/core/model-router-controller.js.map +1 -1
  147. package/dist/core/model-selection-controller.d.ts +3 -0
  148. package/dist/core/model-selection-controller.d.ts.map +1 -1
  149. package/dist/core/model-selection-controller.js +8 -1
  150. package/dist/core/model-selection-controller.js.map +1 -1
  151. package/dist/core/models/local-runtime.d.ts +2 -0
  152. package/dist/core/models/local-runtime.d.ts.map +1 -1
  153. package/dist/core/models/local-runtime.js +10 -4
  154. package/dist/core/models/local-runtime.js.map +1 -1
  155. package/dist/core/models/perf-profile.d.ts.map +1 -1
  156. package/dist/core/models/perf-profile.js +95 -33
  157. package/dist/core/models/perf-profile.js.map +1 -1
  158. package/dist/core/models/runtime-arbiter.d.ts +11 -0
  159. package/dist/core/models/runtime-arbiter.d.ts.map +1 -1
  160. package/dist/core/models/runtime-arbiter.js +35 -13
  161. package/dist/core/models/runtime-arbiter.js.map +1 -1
  162. package/dist/core/profile-filter-controller.d.ts +11 -0
  163. package/dist/core/profile-filter-controller.d.ts.map +1 -1
  164. package/dist/core/profile-filter-controller.js +56 -11
  165. package/dist/core/profile-filter-controller.js.map +1 -1
  166. package/dist/core/profile-registry.d.ts +2 -2
  167. package/dist/core/profile-registry.d.ts.map +1 -1
  168. package/dist/core/profile-registry.js +58 -7
  169. package/dist/core/profile-registry.js.map +1 -1
  170. package/dist/core/reflection-controller.d.ts +9 -7
  171. package/dist/core/reflection-controller.d.ts.map +1 -1
  172. package/dist/core/reflection-controller.js +81 -12
  173. package/dist/core/reflection-controller.js.map +1 -1
  174. package/dist/core/research/research-runner.d.ts +2 -2
  175. package/dist/core/research/research-runner.d.ts.map +1 -1
  176. package/dist/core/research/research-runner.js +8 -6
  177. package/dist/core/research/research-runner.js.map +1 -1
  178. package/dist/core/resource-loader.d.ts +4 -2
  179. package/dist/core/resource-loader.d.ts.map +1 -1
  180. package/dist/core/resource-loader.js +11 -1
  181. package/dist/core/resource-loader.js.map +1 -1
  182. package/dist/core/runtime-builder.d.ts +30 -3
  183. package/dist/core/runtime-builder.d.ts.map +1 -1
  184. package/dist/core/runtime-builder.js +140 -40
  185. package/dist/core/runtime-builder.js.map +1 -1
  186. package/dist/core/sdk.d.ts +8 -7
  187. package/dist/core/sdk.d.ts.map +1 -1
  188. package/dist/core/sdk.js +38 -5
  189. package/dist/core/sdk.js.map +1 -1
  190. package/dist/core/security/secret-text.d.ts +3 -0
  191. package/dist/core/security/secret-text.d.ts.map +1 -0
  192. package/dist/core/security/secret-text.js +26 -0
  193. package/dist/core/security/secret-text.js.map +1 -0
  194. package/dist/core/settings-manager.d.ts +59 -17
  195. package/dist/core/settings-manager.d.ts.map +1 -1
  196. package/dist/core/settings-manager.js +300 -51
  197. package/dist/core/settings-manager.js.map +1 -1
  198. package/dist/core/skills.d.ts.map +1 -1
  199. package/dist/core/skills.js +1 -1
  200. package/dist/core/skills.js.map +1 -1
  201. package/dist/core/system-prompt-builder.d.ts +7 -0
  202. package/dist/core/system-prompt-builder.d.ts.map +1 -1
  203. package/dist/core/system-prompt-builder.js +23 -1
  204. package/dist/core/system-prompt-builder.js.map +1 -1
  205. package/dist/core/tool-gate-controller.d.ts +3 -0
  206. package/dist/core/tool-gate-controller.d.ts.map +1 -1
  207. package/dist/core/tool-gate-controller.js +20 -15
  208. package/dist/core/tool-gate-controller.js.map +1 -1
  209. package/dist/core/tool-selection/expected-utility.d.ts +51 -0
  210. package/dist/core/tool-selection/expected-utility.d.ts.map +1 -0
  211. package/dist/core/tool-selection/expected-utility.js +85 -0
  212. package/dist/core/tool-selection/expected-utility.js.map +1 -0
  213. package/dist/core/tool-selection/tool-performance-store.d.ts +82 -0
  214. package/dist/core/tool-selection/tool-performance-store.d.ts.map +1 -0
  215. package/dist/core/tool-selection/tool-performance-store.js +249 -0
  216. package/dist/core/tool-selection/tool-performance-store.js.map +1 -0
  217. package/dist/core/tool-selection/tool-selection-controller.d.ts +41 -0
  218. package/dist/core/tool-selection/tool-selection-controller.d.ts.map +1 -0
  219. package/dist/core/tool-selection/tool-selection-controller.js +199 -0
  220. package/dist/core/tool-selection/tool-selection-controller.js.map +1 -0
  221. package/dist/core/tools/delegate-status.d.ts +9 -0
  222. package/dist/core/tools/delegate-status.d.ts.map +1 -0
  223. package/dist/core/tools/delegate-status.js +52 -0
  224. package/dist/core/tools/delegate-status.js.map +1 -0
  225. package/dist/core/tools/delegate.d.ts +10 -0
  226. package/dist/core/tools/delegate.d.ts.map +1 -1
  227. package/dist/core/tools/delegate.js +36 -13
  228. package/dist/core/tools/delegate.js.map +1 -1
  229. package/dist/core/tools/run-toolkit-script.d.ts +3 -0
  230. package/dist/core/tools/run-toolkit-script.d.ts.map +1 -1
  231. package/dist/core/tools/run-toolkit-script.js +17 -7
  232. package/dist/core/tools/run-toolkit-script.js.map +1 -1
  233. package/dist/main.d.ts.map +1 -1
  234. package/dist/main.js +2 -0
  235. package/dist/main.js.map +1 -1
  236. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  237. package/dist/modes/interactive/components/footer.js +8 -1
  238. package/dist/modes/interactive/components/footer.js.map +1 -1
  239. package/dist/modes/interactive/components/settings-selector.d.ts +2 -0
  240. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  241. package/dist/modes/interactive/components/settings-selector.js +69 -29
  242. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  243. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  244. package/dist/modes/interactive/components/thinking-selector.js +2 -0
  245. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  246. package/dist/modes/interactive/config-backup.d.ts +7 -1
  247. package/dist/modes/interactive/config-backup.d.ts.map +1 -1
  248. package/dist/modes/interactive/config-backup.js +196 -32
  249. package/dist/modes/interactive/config-backup.js.map +1 -1
  250. package/dist/modes/interactive/interactive-mode.d.ts +1 -1
  251. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  252. package/dist/modes/interactive/interactive-mode.js +22 -28
  253. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  254. package/dist/modes/interactive/local-model-commands.d.ts.map +1 -1
  255. package/dist/modes/interactive/local-model-commands.js +2 -0
  256. package/dist/modes/interactive/local-model-commands.js.map +1 -1
  257. package/dist/modes/interactive/profile-menu-controller.d.ts +6 -4
  258. package/dist/modes/interactive/profile-menu-controller.d.ts.map +1 -1
  259. package/dist/modes/interactive/profile-menu-controller.js +248 -65
  260. package/dist/modes/interactive/profile-menu-controller.js.map +1 -1
  261. package/dist/modes/interactive/report-commands.d.ts.map +1 -1
  262. package/dist/modes/interactive/report-commands.js +8 -2
  263. package/dist/modes/interactive/report-commands.js.map +1 -1
  264. package/dist/modes/interactive/settings-selector-flow.d.ts.map +1 -1
  265. package/dist/modes/interactive/settings-selector-flow.js +8 -0
  266. package/dist/modes/interactive/settings-selector-flow.js.map +1 -1
  267. package/dist/modes/interactive/theme/theme-schema.json +1 -1
  268. package/dist/modes/interactive/theme/theme.d.ts +1 -1
  269. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  270. package/dist/modes/interactive/theme/theme.js +3 -1
  271. package/dist/modes/interactive/theme/theme.js.map +1 -1
  272. package/docs/extensions.md +32 -0
  273. package/docs/integration-sweep-builder-blueprint-2026-07-09.md +365 -0
  274. package/docs/integration-sweep-resume-2026-07-09.md +407 -0
  275. package/docs/resources.md +15 -7
  276. package/docs/settings.md +56 -5
  277. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  278. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  279. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  280. package/examples/extensions/preset.ts +2 -2
  281. package/examples/extensions/sandbox/package-lock.json +2 -2
  282. package/examples/extensions/sandbox/package.json +1 -1
  283. package/examples/extensions/with-deps/package-lock.json +2 -2
  284. package/examples/extensions/with-deps/package.json +1 -1
  285. package/npm-shrinkwrap.json +44 -35
  286. package/package.json +4 -4
@@ -41,6 +41,9 @@ export class LocalRuntimeController {
41
41
  /** Server URLs confirmed reachable THIS session — skips the health-check round trip on every
42
42
  * local-routed turn once warm. Keyed the same way as _runtimes. */
43
43
  _confirmedUp = new Set();
44
+ /** All live runtime adapters participate in one session-wide residency view. */
45
+ _residencyAdapters = new Map();
46
+ _recentEvictions = [];
44
47
  deps;
45
48
  constructor(deps) {
46
49
  this.deps = deps;
@@ -102,28 +105,36 @@ export class LocalRuntimeController {
102
105
  this._confirmedUp.delete(this.confirmationKey(model, serverUrl));
103
106
  }
104
107
  }
105
- async ensureOllamaResident(model, runtime) {
106
- let bytes = 0;
107
- try {
108
- const installed = await runtime.list();
109
- bytes = installed.find((entry) => matchesInstalledLocalModel(model.id, entry.name))?.sizeBytes ?? 0;
110
- }
111
- catch {
112
- // Residency is best-effort; a list failure falls back to a zero-byte admission request.
108
+ async ensureOllamaResident(model, runtime, knownSizeBytes) {
109
+ let bytes = knownSizeBytes ?? 0;
110
+ if (knownSizeBytes === undefined) {
111
+ try {
112
+ const installed = await runtime.list();
113
+ bytes = installed.find((entry) => matchesInstalledLocalModel(model.id, entry.name))?.sizeBytes ?? 0;
114
+ }
115
+ catch {
116
+ // Residency is best-effort; a list failure falls back to a zero-byte admission request.
117
+ }
113
118
  }
114
- const arbiter = new RuntimeResidencyArbiter({
115
- budgetBytes: Math.floor(totalmem() * 0.85),
116
- adapters: [new OllamaRuntimeResidencyAdapter("ollama", runtime)],
117
- });
119
+ const serverUrl = this.deriveOllamaServerUrl(model.baseUrl);
120
+ const adapterId = `ollama:${serverUrl}`;
121
+ this._residencyAdapters.set(adapterId, new OllamaRuntimeResidencyAdapter(adapterId, runtime));
122
+ const arbiter = this.createResidencyArbiter();
118
123
  try {
119
- const plan = await arbiter.ensureResident("ollama", {
124
+ const nowMs = Date.now();
125
+ const plan = await arbiter.ensureResident(adapterId, {
120
126
  model: model.id,
121
127
  bytes,
122
128
  role: "active",
123
129
  priority: 100,
124
- nowMs: Date.now(),
130
+ nowMs,
125
131
  pinActiveModel: model.id,
132
+ recentEvictions: this._recentEvictions,
133
+ // Cold Ollama loads can legitimately take several minutes. The actual adaptive stream
134
+ // owns that wait; readiness must not front-run it with a 60-second empty generation.
135
+ loadModel: false,
126
136
  });
137
+ this.recordEvictions(plan.evict, model.id, nowMs, adapterId);
127
138
  return plan.status === "fits" ? { ok: true } : { ok: false, reason: `residency_refused:${plan.reason}` };
128
139
  }
129
140
  catch (error) {
@@ -131,25 +142,86 @@ export class LocalRuntimeController {
131
142
  }
132
143
  }
133
144
  async ensureTransformersResident(model, runtime) {
134
- const arbiter = new RuntimeResidencyArbiter({
135
- budgetBytes: Math.floor(totalmem() * 0.85),
136
- adapters: [new TransformersRuntimeResidencyAdapter(`transformers:${model.id}`, runtime, model.id, 0)],
137
- });
145
+ const serverUrl = this.deriveOpenAICompatServerUrl(model.baseUrl);
146
+ const adapterId = `transformers:${model.id}:${serverUrl}`;
147
+ this._residencyAdapters.set(adapterId, new TransformersRuntimeResidencyAdapter(adapterId, runtime, model.id, 0));
148
+ const arbiter = this.createResidencyArbiter();
138
149
  try {
139
- const plan = await arbiter.ensureResident(`transformers:${model.id}`, {
150
+ const nowMs = Date.now();
151
+ const plan = await arbiter.ensureResident(adapterId, {
140
152
  model: model.id,
141
153
  bytes: 0,
142
154
  role: "active",
143
155
  priority: 100,
144
- nowMs: Date.now(),
156
+ nowMs,
145
157
  pinActiveModel: model.id,
158
+ recentEvictions: this._recentEvictions,
159
+ loadModel: false,
146
160
  });
161
+ this.recordEvictions(plan.evict, model.id, nowMs, adapterId);
147
162
  return plan.status === "fits" ? { ok: true } : { ok: false, reason: `residency_refused:${plan.reason}` };
148
163
  }
149
164
  catch (error) {
150
165
  return { ok: false, reason: `residency_error:${error instanceof Error ? error.message : String(error)}` };
151
166
  }
152
167
  }
168
+ createResidencyArbiter() {
169
+ return new RuntimeResidencyArbiter({
170
+ budgetBytes: Math.floor(totalmem() * 0.85),
171
+ adapters: [...this._residencyAdapters.values()],
172
+ });
173
+ }
174
+ recordEvictions(evicted, loaded, atMs, loadedAdapterId) {
175
+ for (const resident of evicted) {
176
+ this._recentEvictions.push({
177
+ evicted: resident.model,
178
+ loaded,
179
+ atMs,
180
+ evictedAdapterId: resident.adapterId,
181
+ loadedAdapterId,
182
+ });
183
+ }
184
+ const cutoff = atMs - 5 * 60_000;
185
+ while (this._recentEvictions[0]?.atMs < cutoff)
186
+ this._recentEvictions.shift();
187
+ }
188
+ /**
189
+ * Readiness gate for every isolated/background completion. Unlike the foreground route gate it
190
+ * never prompts or changes tiers: lanes either use the configured model or fail visibly.
191
+ */
192
+ async ensureIsolatedModelReady(model) {
193
+ if (!this.isManagedLocalProvider(model.provider))
194
+ return;
195
+ const readiness = model.provider === OLLAMA_PROVIDER
196
+ ? await this.ensureLocalModelReady(model)
197
+ : await this.ensureTransformersModelReady(model);
198
+ if (readiness.ready)
199
+ return;
200
+ const guide = readiness.installGuide?.length ? `\n${readiness.installGuide.join("\n")}` : "";
201
+ throw new Error(`Managed local model ${this.deps.formatModel(model)} is unavailable for isolated execution (${readiness.reason}).${guide}`);
202
+ }
203
+ /**
204
+ * Readiness gate for a manually selected/default foreground model when no router route owns the
205
+ * turn. Interactive sessions may offer the same managed-install consent as routed turns; the
206
+ * selected model is never silently replaced.
207
+ */
208
+ async ensureForegroundModelReady(model) {
209
+ if (!this.isManagedLocalProvider(model.provider))
210
+ return;
211
+ let readiness = model.provider === OLLAMA_PROVIDER
212
+ ? await this.ensureLocalModelReady(model)
213
+ : await this.ensureTransformersModelReady(model);
214
+ if (!readiness.ready) {
215
+ readiness =
216
+ model.provider === OLLAMA_PROVIDER
217
+ ? await this.maybeInstallOllamaOnConsent(model, readiness)
218
+ : await this.maybeInstallTransformersOnConsent(model, readiness);
219
+ }
220
+ if (readiness.ready)
221
+ return;
222
+ const detail = readiness.installAttemptError ?? readiness.installGuide?.join("\n") ?? readiness.reason;
223
+ throw new Error(`Managed local model ${this.deps.formatModel(model)} is unavailable: ${detail}`);
224
+ }
153
225
  /**
154
226
  * Ensure a routed managed-local model is actually reachable before the turn calls it. No-op (and
155
227
  * free) for non-local/API models. Caches a "confirmed up this session" flag per server (and per
@@ -169,16 +241,23 @@ export class LocalRuntimeController {
169
241
  const runtime = this.getLocalRuntime(serverUrl);
170
242
  const status = await runtime.detect();
171
243
  if (status.serverUp) {
172
- if (status.activeStore?.kind === "pi-owned") {
173
- const resident = await this.ensureOllamaResident(model, runtime);
174
- if (!resident.ok)
175
- return { ready: false, reason: resident.reason ?? "residency_refused" };
176
- this._confirmedUp.add(confirmedKey);
177
- return { ready: true, reason: "already_running" };
244
+ // Server ownership is not a capability boundary. Reuse a configured user/system server
245
+ // when it exposes the requested model; this preserves its accelerator settings and warm
246
+ // cache instead of forcing a slower duplicate Pi-owned process/store.
247
+ const installedEntry = status.serverModels.find((entry) => matchesInstalledLocalModel(model.id, entry.name));
248
+ if (!installedEntry) {
249
+ return {
250
+ ready: false,
251
+ reason: `model_missing_on_server:${model.id}:${status.activeStore?.path ?? "external/unknown"}`,
252
+ };
178
253
  }
254
+ const resident = await this.ensureOllamaResident(model, runtime, installedEntry.sizeBytes);
255
+ if (!resident.ok)
256
+ return { ready: false, reason: resident.reason ?? "residency_refused" };
257
+ this._confirmedUp.add(confirmedKey);
179
258
  return {
180
- ready: false,
181
- reason: `wrong_store:${status.activeStore?.path ?? "external/unknown"}:${status.activeStore?.modelCount ?? 0}:${status.ownedModelsDir}`,
259
+ ready: true,
260
+ reason: status.managedByPi ? "already_running_managed" : "already_running_configured_server",
182
261
  };
183
262
  }
184
263
  if (!status.binaryPath) {
@@ -1 +1 @@
1
- {"version":3,"file":"local-runtime-controller.js","sourceRoot":"","sources":["../../src/core/local-runtime-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAKnC,OAAO,EAAE,wBAAwB,EAAE,eAAe,EAA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,SAAS,CAAC,KAAK;gBACtB,QAAQ,EAAE;oBACT,GAAG,OAAO,CAAC,QAAQ;oBACnB,IAAI,EAAE,SAAS,CAAC,IAAI;oBACpB,YAAY,EAAE,OAAO,CAAC,QAAQ,CAAC,IAAI;oBACnC,UAAU,EAAE,gCAAgC;oBAC5C,OAAO,EAAE;wBACR,GAAG,OAAO,CAAC,QAAQ,CAAC,OAAO;wBAC3B,0BAA0B,SAAS,CAAC,MAAM,mBAAmB,SAAS,CAAC,IAAI,EAAE;qBAC7E;oBACD,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,SAAS,CAAC,KAAK,CAAC;iBAC7C;aACD,CAAC;QACH,CAAC;QACD,OAAO,OAAO,CAAC;IAAA,CACf;CACD","sourcesContent":["/**\n * Local-runtime (Ollama) lifecycle controller.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the cached, per-server\n * {@link OllamaRuntime} instances, the \"confirmed up this session\" flag, and the router's readiness\n * gate for a turn routed to a local (`ollama`) model — including the #31 install-on-consent flow and\n * the #27 graceful tier-escalation fallback. Takes narrow deps (agent dir, a last-assistant-message\n * accessor, the session's UI context/event emitter, and the router's own tier resolver) rather than\n * the whole AgentSession.\n */\n\nimport { totalmem } from \"node:os\";\nimport type { Api, AssistantMessage, Model } from \"@caupulican/pi-ai\";\nimport type { AgentSessionEvent } from \"./agent-session.ts\";\nimport type { RouteDecision } from \"./autonomy/contracts.ts\";\nimport type { ExtensionUIContext } from \"./extensions/index.ts\";\nimport { HF_TRANSFORMERS_PROVIDER, OLLAMA_PROVIDER } from \"./models/local-registration.ts\";\nimport {\n\ttype LocalRuntimeDeps,\n\tOllamaRuntime,\n\tresolveTransformersBaseUrl,\n\tTransformersRuntime,\n} from \"./models/local-runtime.ts\";\nimport { matchesInstalledLocalModel } from \"./models/model-ref.ts\";\nimport {\n\tOllamaRuntimeResidencyAdapter,\n\tRuntimeResidencyArbiter,\n\tTransformersRuntimeResidencyAdapter,\n} from \"./models/runtime-arbiter.ts\";\n\n/** User-facing router tiers in ascending order — \"learning\" is never selected for a user turn, so\n * it has no place in the escalation ladder (#27's ensureRouteModelReady walks this forward only). */\nconst MODEL_ROUTER_TIER_ORDER: readonly (\"cheap\" | \"medium\" | \"expensive\")[] = [\"cheap\", \"medium\", \"expensive\"];\n\n/** How long the #31 \"install ollama now?\" confirm waits before auto-dismissing (same as a \"No\") —\n * long enough to read and decide, short enough that an unattended session doesn't hang a turn on it. */\nconst OLLAMA_INSTALL_CONFIRM_TIMEOUT_MS = 30_000;\n\nfunction parseWrongOllamaStoreReason(\n\treason: string,\n): { activePath: string; modelCount: number; ownedPath: string } | undefined {\n\tif (!reason.startsWith(\"wrong_store:\")) return undefined;\n\tconst parts = reason.slice(\"wrong_store:\".length).split(\":\");\n\tif (parts.length < 3) return undefined;\n\tconst [activePath, countText, ...ownedPathParts] = parts;\n\tconst modelCount = Number(countText);\n\treturn {\n\t\tactivePath,\n\t\tmodelCount: Number.isFinite(modelCount) ? modelCount : 0,\n\t\townedPath: ownedPathParts.join(\":\"),\n\t};\n}\n\nexport interface LocalRuntimeControllerDeps {\n\t/** Root directory OllamaRuntime instances are scoped under — fixed for the session's lifetime. */\n\tagentDir: string;\n\t/** Test-injectable seams for OllamaRuntime's own fetch/spawn/exists calls; unset in production. */\n\tlocalRuntimeDeps?: LocalRuntimeDeps;\n\t/** The session's last assistant message, to detect a just-failed local call and drop a stale\n\t * \"confirmed up\" flag. */\n\tgetLastAssistantMessage(): AssistantMessage | undefined;\n\t/** The session's live interactive UI context, if any — undefined in headless/RPC/print modes. */\n\tgetUIContext(): ExtensionUIContext | undefined;\n\t/** Emits a session event (only ever `warning` / `routing_start` / `routing_end` from this controller). */\n\temit(event: AgentSessionEvent): void;\n\t/** Resolves the model configured for a router tier, respecting configured auth — owned by the\n\t * router itself, not this controller. */\n\tresolveConfiguredTierModel(tier: \"medium\" | \"expensive\"): Model<Api> | undefined;\n\t/** `${provider}/${id}` label for a model, for warning/confirm text. */\n\tformatModel(model: Model<Api>): string;\n}\n\nexport class LocalRuntimeController {\n\t/** Lazy, cached by baseUrl so the router path and any other caller share one instance per server. */\n\tprivate readonly _runtimes = new Map<string, OllamaRuntime>();\n\t/** Lazy, cached by model+baseUrl so the router and `/models` share one sidecar handle per HF model. */\n\tprivate readonly _transformersRuntimes = new Map<string, TransformersRuntime>();\n\t/** Server URLs confirmed reachable THIS session — skips the health-check round trip on every\n\t * local-routed turn once warm. Keyed the same way as _runtimes. */\n\tprivate readonly _confirmedUp = new Set<string>();\n\n\tprivate readonly deps: LocalRuntimeControllerDeps;\n\n\tconstructor(deps: LocalRuntimeControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/**\n\t * Shared {@link OllamaRuntime} for a given server, lazily created and cached by baseUrl so every\n\t * caller — the router's readiness gate below and any host UI's own model-lifecycle commands\n\t * (e.g. `/models`) — sees and can stop the SAME pi-managed process instead of each tracking its\n\t * own untracked child.\n\t */\n\tgetLocalRuntime(baseUrl?: string): OllamaRuntime {\n\t\tconst key = baseUrl ?? \"default\";\n\t\tlet runtime = this._runtimes.get(key);\n\t\tif (!runtime) {\n\t\t\truntime = new OllamaRuntime({ agentDir: this.deps.agentDir, baseUrl, deps: this.deps.localRuntimeDeps });\n\t\t\tthis._runtimes.set(key, runtime);\n\t\t}\n\t\treturn runtime;\n\t}\n\n\tgetTransformersRuntime(modelId: string, baseUrl?: string): TransformersRuntime {\n\t\tconst resolvedBaseUrl = baseUrl?.replace(/\\/$/, \"\") ?? resolveTransformersBaseUrl(modelId);\n\t\tconst key = `${modelId}\\0${resolvedBaseUrl}`;\n\t\tlet runtime = this._transformersRuntimes.get(key);\n\t\tif (!runtime) {\n\t\t\truntime = new TransformersRuntime({\n\t\t\t\tagentDir: this.deps.agentDir,\n\t\t\t\tmodelId,\n\t\t\t\tbaseUrl: resolvedBaseUrl,\n\t\t\t\tdeps: this.deps.localRuntimeDeps,\n\t\t\t});\n\t\t\tthis._transformersRuntimes.set(key, runtime);\n\t\t}\n\t\treturn runtime;\n\t}\n\n\t/** models.json registers a local model's baseUrl as `<server>/v1` (OpenAI-compat); the runtime's\n\t * own health/boot endpoints are on the Ollama-native server root. */\n\tderiveOllamaServerUrl(modelBaseUrl: string): string {\n\t\treturn modelBaseUrl.replace(/\\/v1\\/?$/, \"\");\n\t}\n\n\tprivate deriveOpenAICompatServerUrl(modelBaseUrl: string): string {\n\t\treturn modelBaseUrl.replace(/\\/v1\\/?$/, \"\");\n\t}\n\n\tprivate isManagedLocalProvider(provider: string): boolean {\n\t\treturn provider === OLLAMA_PROVIDER || provider === HF_TRANSFORMERS_PROVIDER;\n\t}\n\n\t/**\n\t * If the last assistant message in this session was an error from THIS exact local server, a\n\t * cached \"confirmed up\" flag would be stale (the server may have died mid-session) — drop it so\n\t * the next ensure-check is a real one instead of trusting stale state.\n\t */\n\tprivate confirmationKey(model: Model<Api>, serverUrl: string): string {\n\t\treturn model.provider === HF_TRANSFORMERS_PROVIDER ? `${serverUrl}\\0${model.id}` : serverUrl;\n\t}\n\n\tprivate invalidateIfLastCallFailed(model: Model<Api>, serverUrl: string): void {\n\t\tconst lastAssistant = this.deps.getLastAssistantMessage();\n\t\tif (\n\t\t\tlastAssistant?.stopReason === \"error\" &&\n\t\t\tlastAssistant.provider === model.provider &&\n\t\t\tlastAssistant.model === model.id\n\t\t) {\n\t\t\tthis._confirmedUp.delete(this.confirmationKey(model, serverUrl));\n\t\t}\n\t}\n\n\tprivate async ensureOllamaResident(\n\t\tmodel: Model<Api>,\n\t\truntime: OllamaRuntime,\n\t): Promise<{ ok: boolean; reason?: string }> {\n\t\tlet bytes = 0;\n\t\ttry {\n\t\t\tconst installed = await runtime.list();\n\t\t\tbytes = installed.find((entry) => matchesInstalledLocalModel(model.id, entry.name))?.sizeBytes ?? 0;\n\t\t} catch {\n\t\t\t// Residency is best-effort; a list failure falls back to a zero-byte admission request.\n\t\t}\n\t\tconst arbiter = new RuntimeResidencyArbiter({\n\t\t\tbudgetBytes: Math.floor(totalmem() * 0.85),\n\t\t\tadapters: [new OllamaRuntimeResidencyAdapter(\"ollama\", runtime)],\n\t\t});\n\t\ttry {\n\t\t\tconst plan = await arbiter.ensureResident(\"ollama\", {\n\t\t\t\tmodel: model.id,\n\t\t\t\tbytes,\n\t\t\t\trole: \"active\",\n\t\t\t\tpriority: 100,\n\t\t\t\tnowMs: Date.now(),\n\t\t\t\tpinActiveModel: model.id,\n\t\t\t});\n\t\t\treturn plan.status === \"fits\" ? { ok: true } : { ok: false, reason: `residency_refused:${plan.reason}` };\n\t\t} catch (error) {\n\t\t\treturn { ok: false, reason: `residency_error:${error instanceof Error ? error.message : String(error)}` };\n\t\t}\n\t}\n\n\tprivate async ensureTransformersResident(\n\t\tmodel: Model<Api>,\n\t\truntime: TransformersRuntime,\n\t): Promise<{ ok: boolean; reason?: string }> {\n\t\tconst arbiter = new RuntimeResidencyArbiter({\n\t\t\tbudgetBytes: Math.floor(totalmem() * 0.85),\n\t\t\tadapters: [new TransformersRuntimeResidencyAdapter(`transformers:${model.id}`, runtime, model.id, 0)],\n\t\t});\n\t\ttry {\n\t\t\tconst plan = await arbiter.ensureResident(`transformers:${model.id}`, {\n\t\t\t\tmodel: model.id,\n\t\t\t\tbytes: 0,\n\t\t\t\trole: \"active\",\n\t\t\t\tpriority: 100,\n\t\t\t\tnowMs: Date.now(),\n\t\t\t\tpinActiveModel: model.id,\n\t\t\t});\n\t\t\treturn plan.status === \"fits\" ? { ok: true } : { ok: false, reason: `residency_refused:${plan.reason}` };\n\t\t} catch (error) {\n\t\t\treturn { ok: false, reason: `residency_error:${error instanceof Error ? error.message : String(error)}` };\n\t\t}\n\t}\n\n\t/**\n\t * Ensure a routed managed-local model is actually reachable before the turn calls it. No-op (and\n\t * free) for non-local/API models. Caches a \"confirmed up this session\" flag per server (and per\n\t * Transformers model) so steady-state routing pays the health-check round trip once; invalidated\n\t * above when a prior local call failed so a dead sidecar gets re-detected instead of trusted.\n\t */\n\tasync ensureLocalModelReady(\n\t\tmodel: Model<Api>,\n\t): Promise<{ ready: boolean; reason: string; installGuide?: string[] }> {\n\t\tif (model.provider !== OLLAMA_PROVIDER) {\n\t\t\treturn { ready: true, reason: \"not_local\" };\n\t\t}\n\t\tconst serverUrl = this.deriveOllamaServerUrl(model.baseUrl);\n\t\tconst confirmedKey = this.confirmationKey(model, serverUrl);\n\t\tthis.invalidateIfLastCallFailed(model, serverUrl);\n\t\tif (this._confirmedUp.has(confirmedKey)) {\n\t\t\treturn { ready: true, reason: \"confirmed_up_cached\" };\n\t\t}\n\t\tconst runtime = this.getLocalRuntime(serverUrl);\n\t\tconst status = await runtime.detect();\n\t\tif (status.serverUp) {\n\t\t\tif (status.activeStore?.kind === \"pi-owned\") {\n\t\t\t\tconst resident = await this.ensureOllamaResident(model, runtime);\n\t\t\t\tif (!resident.ok) return { ready: false, reason: resident.reason ?? \"residency_refused\" };\n\t\t\t\tthis._confirmedUp.add(confirmedKey);\n\t\t\t\treturn { ready: true, reason: \"already_running\" };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tready: false,\n\t\t\t\treason: `wrong_store:${status.activeStore?.path ?? \"external/unknown\"}:${status.activeStore?.modelCount ?? 0}:${status.ownedModelsDir}`,\n\t\t\t};\n\t\t}\n\t\tif (!status.binaryPath) {\n\t\t\treturn { ready: false, reason: \"binary_missing\", installGuide: runtime.installGuide() };\n\t\t}\n\t\tconst started = await runtime.start();\n\t\tif (started.started) {\n\t\t\tconst resident = await this.ensureOllamaResident(model, runtime);\n\t\t\tif (!resident.ok) return { ready: false, reason: resident.reason ?? \"residency_refused\" };\n\t\t\tthis._confirmedUp.add(confirmedKey);\n\t\t}\n\t\treturn { ready: started.started, reason: started.reason };\n\t}\n\n\tasync ensureTransformersModelReady(\n\t\tmodel: Model<Api>,\n\t): Promise<{ ready: boolean; reason: string; installGuide?: string[] }> {\n\t\tif (model.provider !== HF_TRANSFORMERS_PROVIDER) {\n\t\t\treturn { ready: true, reason: \"not_transformers\" };\n\t\t}\n\t\tconst serverUrl = this.deriveOpenAICompatServerUrl(model.baseUrl);\n\t\tconst confirmedKey = this.confirmationKey(model, serverUrl);\n\t\tthis.invalidateIfLastCallFailed(model, serverUrl);\n\t\tif (this._confirmedUp.has(confirmedKey)) {\n\t\t\treturn { ready: true, reason: \"confirmed_up_cached\" };\n\t\t}\n\t\tconst runtime = this.getTransformersRuntime(model.id, serverUrl);\n\t\tconst status = await runtime.detect();\n\t\tif (status.serverUp) {\n\t\t\tconst resident = await this.ensureTransformersResident(model, runtime);\n\t\t\tif (!resident.ok) return { ready: false, reason: resident.reason ?? \"residency_refused\" };\n\t\t\tthis._confirmedUp.add(confirmedKey);\n\t\t\treturn { ready: true, reason: \"already_running\" };\n\t\t}\n\t\tif (!status.runtimeInstalled) {\n\t\t\treturn { ready: false, reason: \"runtime_missing\", installGuide: runtime.installGuide() };\n\t\t}\n\t\tconst started = await runtime.start();\n\t\tif (started.started || started.reason === \"already_running\") {\n\t\t\tconst resident = await this.ensureTransformersResident(model, runtime);\n\t\t\tif (!resident.ok) return { ready: false, reason: resident.reason ?? \"residency_refused\" };\n\t\t\tthis._confirmedUp.add(confirmedKey);\n\t\t\treturn { ready: true, reason: started.reason };\n\t\t}\n\t\treturn { ready: false, reason: started.reason };\n\t}\n\n\t/**\n\t * #31: the ONE case a routed local model's unreadiness can be fixed automatically is a missing\n\t * ollama binary — an unreachable server can't be helped by installing, so that reason is left to\n\t * the graceful-fallback warning below unchanged. Only offered when there's an interactive UI to\n\t * ask through: headless/RPC/print sessions have no UI context and fall straight through, same as\n\t * declining or timing out (both resolve confirm() to false). Reverses \"pi never runs installers\n\t * itself\" specifically for this one path — the user is asked first, the download is pi's own\n\t * (never curl|sh), and it lands in pi's own runtimes dir (see OllamaRuntime.installManaged).\n\t *\n\t * Pauses/resumes the routing working-indicator around the confirm dialog itself (re-emitting\n\t * routing_end/routing_start — both already idempotent, see interactive-mode.ts's handlers) so an\n\t * animated spinner doesn't fight a dialog the user is trying to read and answer; the indicator\n\t * comes back for the download/extract that follows a \"yes\", which is genuine processing feedback.\n\t */\n\tprivate async maybeInstallOllamaOnConsent(\n\t\tmodel: Model<Api>,\n\t\treadiness: { ready: boolean; reason: string; installGuide?: string[] },\n\t): Promise<{ ready: boolean; reason: string; installGuide?: string[]; installAttemptError?: string }> {\n\t\tconst ui = this.deps.getUIContext();\n\t\tif (!ui || readiness.ready || readiness.reason !== \"binary_missing\") return readiness;\n\n\t\tconst modelLabel = this.deps.formatModel(model);\n\t\tthis.deps.emit({ type: \"routing_end\" });\n\t\tlet confirmed: boolean;\n\t\ttry {\n\t\t\tconfirmed = await ui.confirm(\n\t\t\t\t\"Install Ollama?\",\n\t\t\t\t`Ollama isn't installed, so the local model \"${modelLabel}\" can't run. Pi can download and ` +\n\t\t\t\t\t\"install it now (a large one-time download, possibly over 1 GB depending on your platform) \" +\n\t\t\t\t\t\"into its own runtimes folder — never curl|sh, never touching anything outside pi's own \" +\n\t\t\t\t\t\"directory. Install it now?\",\n\t\t\t\t{ timeout: OLLAMA_INSTALL_CONFIRM_TIMEOUT_MS },\n\t\t\t);\n\t\t} finally {\n\t\t\tthis.deps.emit({ type: \"routing_start\" });\n\t\t}\n\t\tif (!confirmed) return readiness;\n\n\t\tconst serverUrl = this.deriveOllamaServerUrl(model.baseUrl);\n\t\tconst runtime = this.getLocalRuntime(serverUrl);\n\t\tlet installResult: { ok: boolean; error?: string };\n\t\ttry {\n\t\t\tinstallResult = await runtime.installManaged((status) => ui.setStatus(\"ollama-install\", status));\n\t\t} finally {\n\t\t\tui.setStatus(\"ollama-install\", undefined);\n\t\t}\n\t\tif (!installResult.ok) {\n\t\t\treturn { ready: false, reason: \"install_failed\", installAttemptError: installResult.error };\n\t\t}\n\t\treturn this.ensureLocalModelReady(model);\n\t}\n\n\tprivate async maybeInstallTransformersOnConsent(\n\t\tmodel: Model<Api>,\n\t\treadiness: { ready: boolean; reason: string; installGuide?: string[] },\n\t): Promise<{ ready: boolean; reason: string; installGuide?: string[]; installAttemptError?: string }> {\n\t\tconst ui = this.deps.getUIContext();\n\t\tif (!ui || readiness.ready || readiness.reason !== \"runtime_missing\") return readiness;\n\n\t\tconst modelLabel = this.deps.formatModel(model);\n\t\tthis.deps.emit({ type: \"routing_end\" });\n\t\tlet confirmed: boolean;\n\t\ttry {\n\t\t\tconfirmed = await ui.confirm(\n\t\t\t\t\"Install Transformers runtime?\",\n\t\t\t\t`The Hugging Face model \"${modelLabel}\" needs a pi-managed Python venv with Transformers ` +\n\t\t\t\t\t\"and CPU PyTorch before it can run. Pi will install those packages into its own runtimes \" +\n\t\t\t\t\t\"folder, download the model into a pi-owned Hugging Face cache, and leave system Python, \" +\n\t\t\t\t\t\"your Ollama models, and your user HF cache untouched. Install it now?\",\n\t\t\t\t{ timeout: OLLAMA_INSTALL_CONFIRM_TIMEOUT_MS },\n\t\t\t);\n\t\t} finally {\n\t\t\tthis.deps.emit({ type: \"routing_start\" });\n\t\t}\n\t\tif (!confirmed) return readiness;\n\n\t\tconst serverUrl = this.deriveOpenAICompatServerUrl(model.baseUrl);\n\t\tconst runtime = this.getTransformersRuntime(model.id, serverUrl);\n\t\tlet installResult: { ok: boolean; error?: string };\n\t\ttry {\n\t\t\tinstallResult = await runtime.installManaged((status) => ui.setStatus(\"transformers-install\", status));\n\t\t} finally {\n\t\t\tui.setStatus(\"transformers-install\", undefined);\n\t\t}\n\t\tif (!installResult.ok) {\n\t\t\treturn { ready: false, reason: \"install_failed\", installAttemptError: installResult.error };\n\t\t}\n\t\tlet downloadResult: { ok: boolean; error?: string };\n\t\ttry {\n\t\t\tdownloadResult = await runtime.downloadModel((status) => ui.setStatus(\"transformers-download\", status));\n\t\t} finally {\n\t\t\tui.setStatus(\"transformers-download\", undefined);\n\t\t}\n\t\tif (!downloadResult.ok) {\n\t\t\treturn { ready: false, reason: \"download_failed\", installAttemptError: downloadResult.error };\n\t\t}\n\t\treturn this.ensureTransformersModelReady(model);\n\t}\n\n\t/**\n\t * Router-swap gate (#27): a turn routed to a local model (any tier, including an executor-direct\n\t * route — both carry tier \"cheap\") must not dead-end the turn just because ollama isn't up.\n\t * Never a SILENT swap: every fallback is announced in a warning that states (i) the local model\n\t * was unavailable and WHY — binary missing surfaces the install guide inline; any other reason\n\t * gets a \"check that ollama is running\" hint — and (ii) which tier is now handling the turn, so\n\t * the cost shift is never a surprise. Escalates cheap -> medium -> expensive, skipping any\n\t * unconfigured intermediate tier, reusing the router's own existing \"model unavailable\"\n\t * resolution (resolveConfiguredTierModel) rather than inventing a new fallback mechanism.\n\t * Escalation is bounded: tier strictly increases each hop, so it terminates within two hops.\n\t *\n\t * Before the warning/escalation below: #31's consent gate gets one shot at fixing a missing\n\t * binary interactively (see maybeInstallOllamaOnConsent) — declining, timing out, running\n\t * headless, or the install attempt itself failing all fall through here unchanged, just with an\n\t * honest reason (an install that failed is worded as a failed install, not re-labeled as if\n\t * nothing was ever tried).\n\t */\n\tasync ensureRouteModelReady(\n\t\tresolved: { decision: RouteDecision; model: Model<Api> } | undefined,\n\t): Promise<{ decision: RouteDecision; model: Model<Api> } | undefined> {\n\t\tlet current = resolved;\n\t\twhile (current && this.isManagedLocalProvider(current.model.provider)) {\n\t\t\tlet readiness: { ready: boolean; reason: string; installGuide?: string[]; installAttemptError?: string } =\n\t\t\t\tcurrent.model.provider === OLLAMA_PROVIDER\n\t\t\t\t\t? await this.ensureLocalModelReady(current.model)\n\t\t\t\t\t: await this.ensureTransformersModelReady(current.model);\n\t\t\tif (!readiness.ready) {\n\t\t\t\treadiness =\n\t\t\t\t\tcurrent.model.provider === OLLAMA_PROVIDER\n\t\t\t\t\t\t? await this.maybeInstallOllamaOnConsent(current.model, readiness)\n\t\t\t\t\t\t: await this.maybeInstallTransformersOnConsent(current.model, readiness);\n\t\t\t}\n\t\t\tif (readiness.ready) return current;\n\n\t\t\t// Walk the remaining tiers in order (never back down to cheap) and take the first one that\n\t\t\t// actually resolves — an unconfigured intermediate tier (e.g. no mediumModel set) must be\n\t\t\t// skipped, not treated as \"no fallback available\".\n\t\t\tconst startIndex = MODEL_ROUTER_TIER_ORDER.indexOf(current.decision.tier as \"cheap\" | \"medium\" | \"expensive\");\n\t\t\tlet escalated: { tier: \"medium\" | \"expensive\"; model: Model<Api> } | undefined;\n\t\t\tfor (let i = startIndex + 1; startIndex !== -1 && i < MODEL_ROUTER_TIER_ORDER.length; i++) {\n\t\t\t\tconst tier = MODEL_ROUTER_TIER_ORDER[i] as \"medium\" | \"expensive\";\n\t\t\t\tconst model = this.deps.resolveConfiguredTierModel(tier);\n\t\t\t\tif (model) {\n\t\t\t\t\tescalated = { tier, model };\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst modelLabel = this.deps.formatModel(current.model);\n\t\t\tconst localRuntimeName = current.model.provider === OLLAMA_PROVIDER ? \"ollama\" : \"Transformers\";\n\t\t\tconst wrongStore = parseWrongOllamaStoreReason(readiness.reason);\n\t\t\tconst whyText = readiness.installAttemptError\n\t\t\t\t? `pi tried to install it just now, but the install attempt failed: ${readiness.installAttemptError}`\n\t\t\t\t: readiness.installGuide\n\t\t\t\t\t? [\n\t\t\t\t\t\t\tcurrent.model.provider === OLLAMA_PROVIDER\n\t\t\t\t\t\t\t\t? \"the ollama binary is not installed.\"\n\t\t\t\t\t\t\t\t: \"the pi-managed Transformers runtime is not installed.\",\n\t\t\t\t\t\t\t...readiness.installGuide,\n\t\t\t\t\t\t].join(\"\\n\")\n\t\t\t\t\t: wrongStore\n\t\t\t\t\t\t? `an Ollama server is already running with store ${wrongStore.activePath} (${wrongStore.modelCount} model(s)); pi's owned store is ${wrongStore.ownedPath}. Stop the other server or run /models import, then retry.`\n\t\t\t\t\t\t: current.model.provider === OLLAMA_PROVIDER\n\t\t\t\t\t\t\t? `its ${localRuntimeName} server is not reachable (${readiness.reason}) — check that ollama is running.`\n\t\t\t\t\t\t\t: `its ${localRuntimeName} server is not reachable (${readiness.reason}) — check that the runtime is running.`;\n\t\t\tconst fallbackText = escalated\n\t\t\t\t? `Falling back to the ${escalated.tier} tier for this turn.`\n\t\t\t\t: \"No other tier is configured — falling back to the session's default model.\";\n\t\t\tthis.deps.emit({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tmessage: `Local model \"${modelLabel}\" is unavailable: ${whyText}\\n${fallbackText}`,\n\t\t\t});\n\n\t\t\tif (!escalated) return undefined; // no higher tier resolves — caller falls back to the session default\n\t\t\tcurrent = {\n\t\t\t\tmodel: escalated.model,\n\t\t\t\tdecision: {\n\t\t\t\t\t...current.decision,\n\t\t\t\t\ttier: escalated.tier,\n\t\t\t\t\tfallbackFrom: current.decision.tier,\n\t\t\t\t\treasonCode: \"local_model_not_ready_fallback\",\n\t\t\t\t\treasons: [\n\t\t\t\t\t\t...current.decision.reasons,\n\t\t\t\t\t\t`Local model not ready (${readiness.reason}); escalated to ${escalated.tier}`,\n\t\t\t\t\t],\n\t\t\t\t\tmodel: this.deps.formatModel(escalated.model),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\treturn current;\n\t}\n}\n"]}
1
+ {"version":3,"file":"local-runtime-controller.js","sourceRoot":"","sources":["../../src/core/local-runtime-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAKnC,OAAO,EAAE,wBAAwB,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AAC3F,OAAO,EAEN,aAAa,EACb,0BAA0B,EAC1B,mBAAmB,GACnB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AACnE,OAAO,EACN,6BAA6B,EAG7B,uBAAuB,EACvB,mCAAmC,GACnC,MAAM,6BAA6B,CAAC;AAErC;qGACqG;AACrG,MAAM,uBAAuB,GAAkD,CAAC,OAAO,EAAE,QAAQ,EAAE,WAAW,CAAC,CAAC;AAEhH;wGACwG;AACxG,MAAM,iCAAiC,GAAG,MAAM,CAAC;AAEjD,S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;4BACzG,CAAC,CAAC,OAAO,gBAAgB,6BAA6B,SAAS,CAAC,MAAM,0CAAwC,CAAC;YACnH,MAAM,YAAY,GAAG,SAAS;gBAC7B,CAAC,CAAC,uBAAuB,SAAS,CAAC,IAAI,sBAAsB;gBAC7D,CAAC,CAAC,8EAA4E,CAAC;YAChF,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;gBACd,IAAI,EAAE,SAAS;gBACf,OAAO,EAAE,gBAAgB,UAAU,qBAAqB,OAAO,KAAK,YAAY,EAAE;aAClF,CAAC,CAAC;YAEH,IAAI,CAAC,SAAS;gBAAE,OAAO,SAAS,CAAC,CAAC,uEAAqE;YACvG,OAAO,GAAG;gBACT,KAAK,EAAE,SAAS,CAAC,KAAK;gBACtB,QAAQ,EAAE;oBACT,GAAG,OAAO,CAAC,QAAQ;oBACnB,IAAI,EAAE,SAAS,CAAC,IAAI;oBACpB,YAAY,EAAE,OAAO,CAAC,QAAQ,CAAC,IAAI;oBACnC,UAAU,EAAE,gCAAgC;oBAC5C,OAAO,EAAE;wBACR,GAAG,OAAO,CAAC,QAAQ,CAAC,OAAO;wBAC3B,0BAA0B,SAAS,CAAC,MAAM,mBAAmB,SAAS,CAAC,IAAI,EAAE;qBAC7E;oBACD,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,SAAS,CAAC,KAAK,CAAC;iBAC7C;aACD,CAAC;QACH,CAAC;QACD,OAAO,OAAO,CAAC;IAAA,CACf;CACD","sourcesContent":["/**\n * Local-runtime (Ollama) lifecycle controller.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the cached, per-server\n * {@link OllamaRuntime} instances, the \"confirmed up this session\" flag, and the router's readiness\n * gate for a turn routed to a local (`ollama`) model — including the #31 install-on-consent flow and\n * the #27 graceful tier-escalation fallback. Takes narrow deps (agent dir, a last-assistant-message\n * accessor, the session's UI context/event emitter, and the router's own tier resolver) rather than\n * the whole AgentSession.\n */\n\nimport { totalmem } from \"node:os\";\nimport type { Api, AssistantMessage, Model } from \"@caupulican/pi-ai\";\nimport type { AgentSessionEvent } from \"./agent-session.ts\";\nimport type { RouteDecision } from \"./autonomy/contracts.ts\";\nimport type { ExtensionUIContext } from \"./extensions/index.ts\";\nimport { HF_TRANSFORMERS_PROVIDER, OLLAMA_PROVIDER } from \"./models/local-registration.ts\";\nimport {\n\ttype LocalRuntimeDeps,\n\tOllamaRuntime,\n\tresolveTransformersBaseUrl,\n\tTransformersRuntime,\n} from \"./models/local-runtime.ts\";\nimport { matchesInstalledLocalModel } from \"./models/model-ref.ts\";\nimport {\n\tOllamaRuntimeResidencyAdapter,\n\ttype RuntimeEvictionRecord,\n\ttype RuntimeResidencyAdapter,\n\tRuntimeResidencyArbiter,\n\tTransformersRuntimeResidencyAdapter,\n} from \"./models/runtime-arbiter.ts\";\n\n/** User-facing router tiers in ascending order — \"learning\" is never selected for a user turn, so\n * it has no place in the escalation ladder (#27's ensureRouteModelReady walks this forward only). */\nconst MODEL_ROUTER_TIER_ORDER: readonly (\"cheap\" | \"medium\" | \"expensive\")[] = [\"cheap\", \"medium\", \"expensive\"];\n\n/** How long the #31 \"install ollama now?\" confirm waits before auto-dismissing (same as a \"No\") —\n * long enough to read and decide, short enough that an unattended session doesn't hang a turn on it. */\nconst OLLAMA_INSTALL_CONFIRM_TIMEOUT_MS = 30_000;\n\nfunction parseWrongOllamaStoreReason(\n\treason: string,\n): { activePath: string; modelCount: number; ownedPath: string } | undefined {\n\tif (!reason.startsWith(\"wrong_store:\")) return undefined;\n\tconst parts = reason.slice(\"wrong_store:\".length).split(\":\");\n\tif (parts.length < 3) return undefined;\n\tconst [activePath, countText, ...ownedPathParts] = parts;\n\tconst modelCount = Number(countText);\n\treturn {\n\t\tactivePath,\n\t\tmodelCount: Number.isFinite(modelCount) ? modelCount : 0,\n\t\townedPath: ownedPathParts.join(\":\"),\n\t};\n}\n\nexport interface LocalRuntimeControllerDeps {\n\t/** Root directory OllamaRuntime instances are scoped under — fixed for the session's lifetime. */\n\tagentDir: string;\n\t/** Test-injectable seams for OllamaRuntime's own fetch/spawn/exists calls; unset in production. */\n\tlocalRuntimeDeps?: LocalRuntimeDeps;\n\t/** The session's last assistant message, to detect a just-failed local call and drop a stale\n\t * \"confirmed up\" flag. */\n\tgetLastAssistantMessage(): AssistantMessage | undefined;\n\t/** The session's live interactive UI context, if any — undefined in headless/RPC/print modes. */\n\tgetUIContext(): ExtensionUIContext | undefined;\n\t/** Emits a session event (only ever `warning` / `routing_start` / `routing_end` from this controller). */\n\temit(event: AgentSessionEvent): void;\n\t/** Resolves the model configured for a router tier, respecting configured auth — owned by the\n\t * router itself, not this controller. */\n\tresolveConfiguredTierModel(tier: \"medium\" | \"expensive\"): Model<Api> | undefined;\n\t/** `${provider}/${id}` label for a model, for warning/confirm text. */\n\tformatModel(model: Model<Api>): string;\n}\n\nexport class LocalRuntimeController {\n\t/** Lazy, cached by baseUrl so the router path and any other caller share one instance per server. */\n\tprivate readonly _runtimes = new Map<string, OllamaRuntime>();\n\t/** Lazy, cached by model+baseUrl so the router and `/models` share one sidecar handle per HF model. */\n\tprivate readonly _transformersRuntimes = new Map<string, TransformersRuntime>();\n\t/** Server URLs confirmed reachable THIS session — skips the health-check round trip on every\n\t * local-routed turn once warm. Keyed the same way as _runtimes. */\n\tprivate readonly _confirmedUp = new Set<string>();\n\t/** All live runtime adapters participate in one session-wide residency view. */\n\tprivate readonly _residencyAdapters = new Map<string, RuntimeResidencyAdapter>();\n\tprivate readonly _recentEvictions: RuntimeEvictionRecord[] = [];\n\n\tprivate readonly deps: LocalRuntimeControllerDeps;\n\n\tconstructor(deps: LocalRuntimeControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/**\n\t * Shared {@link OllamaRuntime} for a given server, lazily created and cached by baseUrl so every\n\t * caller — the router's readiness gate below and any host UI's own model-lifecycle commands\n\t * (e.g. `/models`) — sees and can stop the SAME pi-managed process instead of each tracking its\n\t * own untracked child.\n\t */\n\tgetLocalRuntime(baseUrl?: string): OllamaRuntime {\n\t\tconst key = baseUrl ?? \"default\";\n\t\tlet runtime = this._runtimes.get(key);\n\t\tif (!runtime) {\n\t\t\truntime = new OllamaRuntime({ agentDir: this.deps.agentDir, baseUrl, deps: this.deps.localRuntimeDeps });\n\t\t\tthis._runtimes.set(key, runtime);\n\t\t}\n\t\treturn runtime;\n\t}\n\n\tgetTransformersRuntime(modelId: string, baseUrl?: string): TransformersRuntime {\n\t\tconst resolvedBaseUrl = baseUrl?.replace(/\\/$/, \"\") ?? resolveTransformersBaseUrl(modelId);\n\t\tconst key = `${modelId}\\0${resolvedBaseUrl}`;\n\t\tlet runtime = this._transformersRuntimes.get(key);\n\t\tif (!runtime) {\n\t\t\truntime = new TransformersRuntime({\n\t\t\t\tagentDir: this.deps.agentDir,\n\t\t\t\tmodelId,\n\t\t\t\tbaseUrl: resolvedBaseUrl,\n\t\t\t\tdeps: this.deps.localRuntimeDeps,\n\t\t\t});\n\t\t\tthis._transformersRuntimes.set(key, runtime);\n\t\t}\n\t\treturn runtime;\n\t}\n\n\t/** models.json registers a local model's baseUrl as `<server>/v1` (OpenAI-compat); the runtime's\n\t * own health/boot endpoints are on the Ollama-native server root. */\n\tderiveOllamaServerUrl(modelBaseUrl: string): string {\n\t\treturn modelBaseUrl.replace(/\\/v1\\/?$/, \"\");\n\t}\n\n\tprivate deriveOpenAICompatServerUrl(modelBaseUrl: string): string {\n\t\treturn modelBaseUrl.replace(/\\/v1\\/?$/, \"\");\n\t}\n\n\tprivate isManagedLocalProvider(provider: string): boolean {\n\t\treturn provider === OLLAMA_PROVIDER || provider === HF_TRANSFORMERS_PROVIDER;\n\t}\n\n\t/**\n\t * If the last assistant message in this session was an error from THIS exact local server, a\n\t * cached \"confirmed up\" flag would be stale (the server may have died mid-session) — drop it so\n\t * the next ensure-check is a real one instead of trusting stale state.\n\t */\n\tprivate confirmationKey(model: Model<Api>, serverUrl: string): string {\n\t\treturn model.provider === HF_TRANSFORMERS_PROVIDER ? `${serverUrl}\\0${model.id}` : serverUrl;\n\t}\n\n\tprivate invalidateIfLastCallFailed(model: Model<Api>, serverUrl: string): void {\n\t\tconst lastAssistant = this.deps.getLastAssistantMessage();\n\t\tif (\n\t\t\tlastAssistant?.stopReason === \"error\" &&\n\t\t\tlastAssistant.provider === model.provider &&\n\t\t\tlastAssistant.model === model.id\n\t\t) {\n\t\t\tthis._confirmedUp.delete(this.confirmationKey(model, serverUrl));\n\t\t}\n\t}\n\n\tprivate async ensureOllamaResident(\n\t\tmodel: Model<Api>,\n\t\truntime: OllamaRuntime,\n\t\tknownSizeBytes?: number,\n\t): Promise<{ ok: boolean; reason?: string }> {\n\t\tlet bytes = knownSizeBytes ?? 0;\n\t\tif (knownSizeBytes === undefined) {\n\t\t\ttry {\n\t\t\t\tconst installed = await runtime.list();\n\t\t\t\tbytes = installed.find((entry) => matchesInstalledLocalModel(model.id, entry.name))?.sizeBytes ?? 0;\n\t\t\t} catch {\n\t\t\t\t// Residency is best-effort; a list failure falls back to a zero-byte admission request.\n\t\t\t}\n\t\t}\n\t\tconst serverUrl = this.deriveOllamaServerUrl(model.baseUrl);\n\t\tconst adapterId = `ollama:${serverUrl}`;\n\t\tthis._residencyAdapters.set(adapterId, new OllamaRuntimeResidencyAdapter(adapterId, runtime));\n\t\tconst arbiter = this.createResidencyArbiter();\n\t\ttry {\n\t\t\tconst nowMs = Date.now();\n\t\t\tconst plan = await arbiter.ensureResident(adapterId, {\n\t\t\t\tmodel: model.id,\n\t\t\t\tbytes,\n\t\t\t\trole: \"active\",\n\t\t\t\tpriority: 100,\n\t\t\t\tnowMs,\n\t\t\t\tpinActiveModel: model.id,\n\t\t\t\trecentEvictions: this._recentEvictions,\n\t\t\t\t// Cold Ollama loads can legitimately take several minutes. The actual adaptive stream\n\t\t\t\t// owns that wait; readiness must not front-run it with a 60-second empty generation.\n\t\t\t\tloadModel: false,\n\t\t\t});\n\t\t\tthis.recordEvictions(plan.evict, model.id, nowMs, adapterId);\n\t\t\treturn plan.status === \"fits\" ? { ok: true } : { ok: false, reason: `residency_refused:${plan.reason}` };\n\t\t} catch (error) {\n\t\t\treturn { ok: false, reason: `residency_error:${error instanceof Error ? error.message : String(error)}` };\n\t\t}\n\t}\n\n\tprivate async ensureTransformersResident(\n\t\tmodel: Model<Api>,\n\t\truntime: TransformersRuntime,\n\t): Promise<{ ok: boolean; reason?: string }> {\n\t\tconst serverUrl = this.deriveOpenAICompatServerUrl(model.baseUrl);\n\t\tconst adapterId = `transformers:${model.id}:${serverUrl}`;\n\t\tthis._residencyAdapters.set(adapterId, new TransformersRuntimeResidencyAdapter(adapterId, runtime, model.id, 0));\n\t\tconst arbiter = this.createResidencyArbiter();\n\t\ttry {\n\t\t\tconst nowMs = Date.now();\n\t\t\tconst plan = await arbiter.ensureResident(adapterId, {\n\t\t\t\tmodel: model.id,\n\t\t\t\tbytes: 0,\n\t\t\t\trole: \"active\",\n\t\t\t\tpriority: 100,\n\t\t\t\tnowMs,\n\t\t\t\tpinActiveModel: model.id,\n\t\t\t\trecentEvictions: this._recentEvictions,\n\t\t\t\tloadModel: false,\n\t\t\t});\n\t\t\tthis.recordEvictions(plan.evict, model.id, nowMs, adapterId);\n\t\t\treturn plan.status === \"fits\" ? { ok: true } : { ok: false, reason: `residency_refused:${plan.reason}` };\n\t\t} catch (error) {\n\t\t\treturn { ok: false, reason: `residency_error:${error instanceof Error ? error.message : String(error)}` };\n\t\t}\n\t}\n\n\tprivate createResidencyArbiter(): RuntimeResidencyArbiter {\n\t\treturn new RuntimeResidencyArbiter({\n\t\t\tbudgetBytes: Math.floor(totalmem() * 0.85),\n\t\t\tadapters: [...this._residencyAdapters.values()],\n\t\t});\n\t}\n\n\tprivate recordEvictions(\n\t\tevicted: readonly { adapterId: string; model: string }[],\n\t\tloaded: string,\n\t\tatMs: number,\n\t\tloadedAdapterId: string,\n\t): void {\n\t\tfor (const resident of evicted) {\n\t\t\tthis._recentEvictions.push({\n\t\t\t\tevicted: resident.model,\n\t\t\t\tloaded,\n\t\t\t\tatMs,\n\t\t\t\tevictedAdapterId: resident.adapterId,\n\t\t\t\tloadedAdapterId,\n\t\t\t});\n\t\t}\n\t\tconst cutoff = atMs - 5 * 60_000;\n\t\twhile (this._recentEvictions[0]?.atMs < cutoff) this._recentEvictions.shift();\n\t}\n\n\t/**\n\t * Readiness gate for every isolated/background completion. Unlike the foreground route gate it\n\t * never prompts or changes tiers: lanes either use the configured model or fail visibly.\n\t */\n\tasync ensureIsolatedModelReady(model: Model<Api>): Promise<void> {\n\t\tif (!this.isManagedLocalProvider(model.provider)) return;\n\t\tconst readiness =\n\t\t\tmodel.provider === OLLAMA_PROVIDER\n\t\t\t\t? await this.ensureLocalModelReady(model)\n\t\t\t\t: await this.ensureTransformersModelReady(model);\n\t\tif (readiness.ready) return;\n\t\tconst guide = readiness.installGuide?.length ? `\\n${readiness.installGuide.join(\"\\n\")}` : \"\";\n\t\tthrow new Error(\n\t\t\t`Managed local model ${this.deps.formatModel(model)} is unavailable for isolated execution (${readiness.reason}).${guide}`,\n\t\t);\n\t}\n\n\t/**\n\t * Readiness gate for a manually selected/default foreground model when no router route owns the\n\t * turn. Interactive sessions may offer the same managed-install consent as routed turns; the\n\t * selected model is never silently replaced.\n\t */\n\tasync ensureForegroundModelReady(model: Model<Api>): Promise<void> {\n\t\tif (!this.isManagedLocalProvider(model.provider)) return;\n\t\tlet readiness: {\n\t\t\tready: boolean;\n\t\t\treason: string;\n\t\t\tinstallGuide?: string[];\n\t\t\tinstallAttemptError?: string;\n\t\t} =\n\t\t\tmodel.provider === OLLAMA_PROVIDER\n\t\t\t\t? await this.ensureLocalModelReady(model)\n\t\t\t\t: await this.ensureTransformersModelReady(model);\n\t\tif (!readiness.ready) {\n\t\t\treadiness =\n\t\t\t\tmodel.provider === OLLAMA_PROVIDER\n\t\t\t\t\t? await this.maybeInstallOllamaOnConsent(model, readiness)\n\t\t\t\t\t: await this.maybeInstallTransformersOnConsent(model, readiness);\n\t\t}\n\t\tif (readiness.ready) return;\n\t\tconst detail = readiness.installAttemptError ?? readiness.installGuide?.join(\"\\n\") ?? readiness.reason;\n\t\tthrow new Error(`Managed local model ${this.deps.formatModel(model)} is unavailable: ${detail}`);\n\t}\n\n\t/**\n\t * Ensure a routed managed-local model is actually reachable before the turn calls it. No-op (and\n\t * free) for non-local/API models. Caches a \"confirmed up this session\" flag per server (and per\n\t * Transformers model) so steady-state routing pays the health-check round trip once; invalidated\n\t * above when a prior local call failed so a dead sidecar gets re-detected instead of trusted.\n\t */\n\tasync ensureLocalModelReady(\n\t\tmodel: Model<Api>,\n\t): Promise<{ ready: boolean; reason: string; installGuide?: string[] }> {\n\t\tif (model.provider !== OLLAMA_PROVIDER) {\n\t\t\treturn { ready: true, reason: \"not_local\" };\n\t\t}\n\t\tconst serverUrl = this.deriveOllamaServerUrl(model.baseUrl);\n\t\tconst confirmedKey = this.confirmationKey(model, serverUrl);\n\t\tthis.invalidateIfLastCallFailed(model, serverUrl);\n\t\tif (this._confirmedUp.has(confirmedKey)) {\n\t\t\treturn { ready: true, reason: \"confirmed_up_cached\" };\n\t\t}\n\t\tconst runtime = this.getLocalRuntime(serverUrl);\n\t\tconst status = await runtime.detect();\n\t\tif (status.serverUp) {\n\t\t\t// Server ownership is not a capability boundary. Reuse a configured user/system server\n\t\t\t// when it exposes the requested model; this preserves its accelerator settings and warm\n\t\t\t// cache instead of forcing a slower duplicate Pi-owned process/store.\n\t\t\tconst installedEntry = status.serverModels.find((entry) => matchesInstalledLocalModel(model.id, entry.name));\n\t\t\tif (!installedEntry) {\n\t\t\t\treturn {\n\t\t\t\t\tready: false,\n\t\t\t\t\treason: `model_missing_on_server:${model.id}:${status.activeStore?.path ?? \"external/unknown\"}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst resident = await this.ensureOllamaResident(model, runtime, installedEntry.sizeBytes);\n\t\t\tif (!resident.ok) return { ready: false, reason: resident.reason ?? \"residency_refused\" };\n\t\t\tthis._confirmedUp.add(confirmedKey);\n\t\t\treturn {\n\t\t\t\tready: true,\n\t\t\t\treason: status.managedByPi ? \"already_running_managed\" : \"already_running_configured_server\",\n\t\t\t};\n\t\t}\n\t\tif (!status.binaryPath) {\n\t\t\treturn { ready: false, reason: \"binary_missing\", installGuide: runtime.installGuide() };\n\t\t}\n\t\tconst started = await runtime.start();\n\t\tif (started.started) {\n\t\t\tconst resident = await this.ensureOllamaResident(model, runtime);\n\t\t\tif (!resident.ok) return { ready: false, reason: resident.reason ?? \"residency_refused\" };\n\t\t\tthis._confirmedUp.add(confirmedKey);\n\t\t}\n\t\treturn { ready: started.started, reason: started.reason };\n\t}\n\n\tasync ensureTransformersModelReady(\n\t\tmodel: Model<Api>,\n\t): Promise<{ ready: boolean; reason: string; installGuide?: string[] }> {\n\t\tif (model.provider !== HF_TRANSFORMERS_PROVIDER) {\n\t\t\treturn { ready: true, reason: \"not_transformers\" };\n\t\t}\n\t\tconst serverUrl = this.deriveOpenAICompatServerUrl(model.baseUrl);\n\t\tconst confirmedKey = this.confirmationKey(model, serverUrl);\n\t\tthis.invalidateIfLastCallFailed(model, serverUrl);\n\t\tif (this._confirmedUp.has(confirmedKey)) {\n\t\t\treturn { ready: true, reason: \"confirmed_up_cached\" };\n\t\t}\n\t\tconst runtime = this.getTransformersRuntime(model.id, serverUrl);\n\t\tconst status = await runtime.detect();\n\t\tif (status.serverUp) {\n\t\t\tconst resident = await this.ensureTransformersResident(model, runtime);\n\t\t\tif (!resident.ok) return { ready: false, reason: resident.reason ?? \"residency_refused\" };\n\t\t\tthis._confirmedUp.add(confirmedKey);\n\t\t\treturn { ready: true, reason: \"already_running\" };\n\t\t}\n\t\tif (!status.runtimeInstalled) {\n\t\t\treturn { ready: false, reason: \"runtime_missing\", installGuide: runtime.installGuide() };\n\t\t}\n\t\tconst started = await runtime.start();\n\t\tif (started.started || started.reason === \"already_running\") {\n\t\t\tconst resident = await this.ensureTransformersResident(model, runtime);\n\t\t\tif (!resident.ok) return { ready: false, reason: resident.reason ?? \"residency_refused\" };\n\t\t\tthis._confirmedUp.add(confirmedKey);\n\t\t\treturn { ready: true, reason: started.reason };\n\t\t}\n\t\treturn { ready: false, reason: started.reason };\n\t}\n\n\t/**\n\t * #31: the ONE case a routed local model's unreadiness can be fixed automatically is a missing\n\t * ollama binary — an unreachable server can't be helped by installing, so that reason is left to\n\t * the graceful-fallback warning below unchanged. Only offered when there's an interactive UI to\n\t * ask through: headless/RPC/print sessions have no UI context and fall straight through, same as\n\t * declining or timing out (both resolve confirm() to false). Reverses \"pi never runs installers\n\t * itself\" specifically for this one path — the user is asked first, the download is pi's own\n\t * (never curl|sh), and it lands in pi's own runtimes dir (see OllamaRuntime.installManaged).\n\t *\n\t * Pauses/resumes the routing working-indicator around the confirm dialog itself (re-emitting\n\t * routing_end/routing_start — both already idempotent, see interactive-mode.ts's handlers) so an\n\t * animated spinner doesn't fight a dialog the user is trying to read and answer; the indicator\n\t * comes back for the download/extract that follows a \"yes\", which is genuine processing feedback.\n\t */\n\tprivate async maybeInstallOllamaOnConsent(\n\t\tmodel: Model<Api>,\n\t\treadiness: { ready: boolean; reason: string; installGuide?: string[] },\n\t): Promise<{ ready: boolean; reason: string; installGuide?: string[]; installAttemptError?: string }> {\n\t\tconst ui = this.deps.getUIContext();\n\t\tif (!ui || readiness.ready || readiness.reason !== \"binary_missing\") return readiness;\n\n\t\tconst modelLabel = this.deps.formatModel(model);\n\t\tthis.deps.emit({ type: \"routing_end\" });\n\t\tlet confirmed: boolean;\n\t\ttry {\n\t\t\tconfirmed = await ui.confirm(\n\t\t\t\t\"Install Ollama?\",\n\t\t\t\t`Ollama isn't installed, so the local model \"${modelLabel}\" can't run. Pi can download and ` +\n\t\t\t\t\t\"install it now (a large one-time download, possibly over 1 GB depending on your platform) \" +\n\t\t\t\t\t\"into its own runtimes folder — never curl|sh, never touching anything outside pi's own \" +\n\t\t\t\t\t\"directory. Install it now?\",\n\t\t\t\t{ timeout: OLLAMA_INSTALL_CONFIRM_TIMEOUT_MS },\n\t\t\t);\n\t\t} finally {\n\t\t\tthis.deps.emit({ type: \"routing_start\" });\n\t\t}\n\t\tif (!confirmed) return readiness;\n\n\t\tconst serverUrl = this.deriveOllamaServerUrl(model.baseUrl);\n\t\tconst runtime = this.getLocalRuntime(serverUrl);\n\t\tlet installResult: { ok: boolean; error?: string };\n\t\ttry {\n\t\t\tinstallResult = await runtime.installManaged((status) => ui.setStatus(\"ollama-install\", status));\n\t\t} finally {\n\t\t\tui.setStatus(\"ollama-install\", undefined);\n\t\t}\n\t\tif (!installResult.ok) {\n\t\t\treturn { ready: false, reason: \"install_failed\", installAttemptError: installResult.error };\n\t\t}\n\t\treturn this.ensureLocalModelReady(model);\n\t}\n\n\tprivate async maybeInstallTransformersOnConsent(\n\t\tmodel: Model<Api>,\n\t\treadiness: { ready: boolean; reason: string; installGuide?: string[] },\n\t): Promise<{ ready: boolean; reason: string; installGuide?: string[]; installAttemptError?: string }> {\n\t\tconst ui = this.deps.getUIContext();\n\t\tif (!ui || readiness.ready || readiness.reason !== \"runtime_missing\") return readiness;\n\n\t\tconst modelLabel = this.deps.formatModel(model);\n\t\tthis.deps.emit({ type: \"routing_end\" });\n\t\tlet confirmed: boolean;\n\t\ttry {\n\t\t\tconfirmed = await ui.confirm(\n\t\t\t\t\"Install Transformers runtime?\",\n\t\t\t\t`The Hugging Face model \"${modelLabel}\" needs a pi-managed Python venv with Transformers ` +\n\t\t\t\t\t\"and CPU PyTorch before it can run. Pi will install those packages into its own runtimes \" +\n\t\t\t\t\t\"folder, download the model into a pi-owned Hugging Face cache, and leave system Python, \" +\n\t\t\t\t\t\"your Ollama models, and your user HF cache untouched. Install it now?\",\n\t\t\t\t{ timeout: OLLAMA_INSTALL_CONFIRM_TIMEOUT_MS },\n\t\t\t);\n\t\t} finally {\n\t\t\tthis.deps.emit({ type: \"routing_start\" });\n\t\t}\n\t\tif (!confirmed) return readiness;\n\n\t\tconst serverUrl = this.deriveOpenAICompatServerUrl(model.baseUrl);\n\t\tconst runtime = this.getTransformersRuntime(model.id, serverUrl);\n\t\tlet installResult: { ok: boolean; error?: string };\n\t\ttry {\n\t\t\tinstallResult = await runtime.installManaged((status) => ui.setStatus(\"transformers-install\", status));\n\t\t} finally {\n\t\t\tui.setStatus(\"transformers-install\", undefined);\n\t\t}\n\t\tif (!installResult.ok) {\n\t\t\treturn { ready: false, reason: \"install_failed\", installAttemptError: installResult.error };\n\t\t}\n\t\tlet downloadResult: { ok: boolean; error?: string };\n\t\ttry {\n\t\t\tdownloadResult = await runtime.downloadModel((status) => ui.setStatus(\"transformers-download\", status));\n\t\t} finally {\n\t\t\tui.setStatus(\"transformers-download\", undefined);\n\t\t}\n\t\tif (!downloadResult.ok) {\n\t\t\treturn { ready: false, reason: \"download_failed\", installAttemptError: downloadResult.error };\n\t\t}\n\t\treturn this.ensureTransformersModelReady(model);\n\t}\n\n\t/**\n\t * Router-swap gate (#27): a turn routed to a local model (any tier, including an executor-direct\n\t * route — both carry tier \"cheap\") must not dead-end the turn just because ollama isn't up.\n\t * Never a SILENT swap: every fallback is announced in a warning that states (i) the local model\n\t * was unavailable and WHY — binary missing surfaces the install guide inline; any other reason\n\t * gets a \"check that ollama is running\" hint — and (ii) which tier is now handling the turn, so\n\t * the cost shift is never a surprise. Escalates cheap -> medium -> expensive, skipping any\n\t * unconfigured intermediate tier, reusing the router's own existing \"model unavailable\"\n\t * resolution (resolveConfiguredTierModel) rather than inventing a new fallback mechanism.\n\t * Escalation is bounded: tier strictly increases each hop, so it terminates within two hops.\n\t *\n\t * Before the warning/escalation below: #31's consent gate gets one shot at fixing a missing\n\t * binary interactively (see maybeInstallOllamaOnConsent) — declining, timing out, running\n\t * headless, or the install attempt itself failing all fall through here unchanged, just with an\n\t * honest reason (an install that failed is worded as a failed install, not re-labeled as if\n\t * nothing was ever tried).\n\t */\n\tasync ensureRouteModelReady(\n\t\tresolved: { decision: RouteDecision; model: Model<Api> } | undefined,\n\t): Promise<{ decision: RouteDecision; model: Model<Api> } | undefined> {\n\t\tlet current = resolved;\n\t\twhile (current && this.isManagedLocalProvider(current.model.provider)) {\n\t\t\tlet readiness: { ready: boolean; reason: string; installGuide?: string[]; installAttemptError?: string } =\n\t\t\t\tcurrent.model.provider === OLLAMA_PROVIDER\n\t\t\t\t\t? await this.ensureLocalModelReady(current.model)\n\t\t\t\t\t: await this.ensureTransformersModelReady(current.model);\n\t\t\tif (!readiness.ready) {\n\t\t\t\treadiness =\n\t\t\t\t\tcurrent.model.provider === OLLAMA_PROVIDER\n\t\t\t\t\t\t? await this.maybeInstallOllamaOnConsent(current.model, readiness)\n\t\t\t\t\t\t: await this.maybeInstallTransformersOnConsent(current.model, readiness);\n\t\t\t}\n\t\t\tif (readiness.ready) return current;\n\n\t\t\t// Walk the remaining tiers in order (never back down to cheap) and take the first one that\n\t\t\t// actually resolves — an unconfigured intermediate tier (e.g. no mediumModel set) must be\n\t\t\t// skipped, not treated as \"no fallback available\".\n\t\t\tconst startIndex = MODEL_ROUTER_TIER_ORDER.indexOf(current.decision.tier as \"cheap\" | \"medium\" | \"expensive\");\n\t\t\tlet escalated: { tier: \"medium\" | \"expensive\"; model: Model<Api> } | undefined;\n\t\t\tfor (let i = startIndex + 1; startIndex !== -1 && i < MODEL_ROUTER_TIER_ORDER.length; i++) {\n\t\t\t\tconst tier = MODEL_ROUTER_TIER_ORDER[i] as \"medium\" | \"expensive\";\n\t\t\t\tconst model = this.deps.resolveConfiguredTierModel(tier);\n\t\t\t\tif (model) {\n\t\t\t\t\tescalated = { tier, model };\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst modelLabel = this.deps.formatModel(current.model);\n\t\t\tconst localRuntimeName = current.model.provider === OLLAMA_PROVIDER ? \"ollama\" : \"Transformers\";\n\t\t\tconst wrongStore = parseWrongOllamaStoreReason(readiness.reason);\n\t\t\tconst whyText = readiness.installAttemptError\n\t\t\t\t? `pi tried to install it just now, but the install attempt failed: ${readiness.installAttemptError}`\n\t\t\t\t: readiness.installGuide\n\t\t\t\t\t? [\n\t\t\t\t\t\t\tcurrent.model.provider === OLLAMA_PROVIDER\n\t\t\t\t\t\t\t\t? \"the ollama binary is not installed.\"\n\t\t\t\t\t\t\t\t: \"the pi-managed Transformers runtime is not installed.\",\n\t\t\t\t\t\t\t...readiness.installGuide,\n\t\t\t\t\t\t].join(\"\\n\")\n\t\t\t\t\t: wrongStore\n\t\t\t\t\t\t? `an Ollama server is already running with store ${wrongStore.activePath} (${wrongStore.modelCount} model(s)); pi's owned store is ${wrongStore.ownedPath}. Stop the other server or run /models import, then retry.`\n\t\t\t\t\t\t: current.model.provider === OLLAMA_PROVIDER\n\t\t\t\t\t\t\t? `its ${localRuntimeName} server is not reachable (${readiness.reason}) — check that ollama is running.`\n\t\t\t\t\t\t\t: `its ${localRuntimeName} server is not reachable (${readiness.reason}) — check that the runtime is running.`;\n\t\t\tconst fallbackText = escalated\n\t\t\t\t? `Falling back to the ${escalated.tier} tier for this turn.`\n\t\t\t\t: \"No other tier is configured — falling back to the session's default model.\";\n\t\t\tthis.deps.emit({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tmessage: `Local model \"${modelLabel}\" is unavailable: ${whyText}\\n${fallbackText}`,\n\t\t\t});\n\n\t\t\tif (!escalated) return undefined; // no higher tier resolves — caller falls back to the session default\n\t\t\tcurrent = {\n\t\t\t\tmodel: escalated.model,\n\t\t\t\tdecision: {\n\t\t\t\t\t...current.decision,\n\t\t\t\t\ttier: escalated.tier,\n\t\t\t\t\tfallbackFrom: current.decision.tier,\n\t\t\t\t\treasonCode: \"local_model_not_ready_fallback\",\n\t\t\t\t\treasons: [\n\t\t\t\t\t\t...current.decision.reasons,\n\t\t\t\t\t\t`Local model not ready (${readiness.reason}); escalated to ${escalated.tier}`,\n\t\t\t\t\t],\n\t\t\t\t\tmodel: this.deps.formatModel(escalated.model),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\treturn current;\n\t}\n}\n"]}
@@ -1,5 +1,10 @@
1
+ import type { MemoryPromptBudget } from "../context/memory-prompt-budget.ts";
2
+ import { type MemoryEgressPolicy } from "../context/memory-provider-contract.ts";
1
3
  import type { ToolDefinition } from "../extensions/types.ts";
2
4
  import type { MemoryLifecycleContext, MemoryProvider } from "./memory-provider.ts";
5
+ export interface MemoryPrefetchOptions {
6
+ externalEgressPolicy?: MemoryEgressPolicy;
7
+ }
3
8
  export declare class MemoryManager {
4
9
  private readonly providers;
5
10
  private readonly activeProviders;
@@ -9,16 +14,16 @@ export declare class MemoryManager {
9
14
  private static readonly RESERVED_CORE_TOOL_NAMES;
10
15
  registerProvider(p: MemoryProvider): void;
11
16
  initializeAll(sessionId: string, ctx: MemoryLifecycleContext): Promise<void>;
12
- buildSystemPromptBlock(): string;
17
+ buildSystemPromptBlock(budget?: MemoryPromptBudget): string;
13
18
  /**
14
19
  * Compose the memory block freshly from the providers, BYPASSING the frozen cache used by the
15
20
  * system prompt. Used by end-of-loop reflection so its confront-before-write sees the live memory
16
21
  * (including writes made earlier in the same session) without churning the prefix-cache-stable
17
22
  * system prompt block.
18
23
  */
19
- buildSystemPromptBlockFresh(): string;
24
+ buildSystemPromptBlockFresh(budget?: MemoryPromptBudget): string;
20
25
  private _composeSystemPromptBlock;
21
- prefetch(query: string): Promise<string>;
26
+ prefetch(query: string, options?: MemoryPrefetchOptions): Promise<string>;
22
27
  syncTurn(user: string, assistant: string): Promise<void>;
23
28
  onPreCompress(): Promise<string>;
24
29
  onSessionEnd(): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"memory-manager.d.ts","sourceRoot":"","sources":["../../../src/core/memory/memory-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,KAAK,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEnF,qBAAa,aAAa;IACzB,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAwB;IAClD,OAAO,CAAC,QAAQ,CAAC,eAAe,CAA0B;IAC1D,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAA0B;IAC9D,OAAO,CAAC,GAAG,CAAC,CAAyB;IACrC,OAAO,CAAC,sBAAsB,CAAC,CAAS;IAGxC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,wBAAwB,CAY7C;IAEI,gBAAgB,CAAC,CAAC,EAAE,cAAc,GAAG,IAAI,CA8B/C;IAEY,aAAa,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,sBAAsB,GAAG,OAAO,CAAC,IAAI,CAAC,CAkBxF;IAEM,sBAAsB,IAAI,MAAM,CAOtC;IAED;;;;;OAKG;IACI,2BAA2B,IAAI,MAAM,CAE3C;IAED,OAAO,CAAC,yBAAyB;IAkBpB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAgBpD;IAEY,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAepE;IAEY,aAAa,IAAI,OAAO,CAAC,MAAM,CAAC,CAgB5C;IAEY,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC,CAezC;IAEY,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,CAcxC;IAEM,kBAAkB,IAAI,cAAc,EAAE,CAa5C;IAEM,iBAAiB,IAAI,MAAM,EAAE,CAgBnC;IAEM,KAAK,IAAI,IAAI,CAMnB;CACD","sourcesContent":["import type { ToolDefinition } from \"../extensions/types.ts\";\nimport type { MemoryLifecycleContext, MemoryProvider } from \"./memory-provider.ts\";\n\nexport class MemoryManager {\n\tprivate readonly providers: MemoryProvider[] = [];\n\tprivate readonly activeProviders: Set<string> = new Set();\n\tprivate readonly registeredToolNames: Set<string> = new Set();\n\tprivate ctx?: MemoryLifecycleContext;\n\tprivate systemPromptBlockCache?: string;\n\n\t// Core reserved tool names to prevent hijacking or schema corruption.\n\tprivate static readonly RESERVED_CORE_TOOL_NAMES = new Set([\n\t\t\"read\",\n\t\t\"write\",\n\t\t\"grep\",\n\t\t\"find\",\n\t\t\"ls\",\n\t\t\"bash\",\n\t\t\"ask_user\",\n\t\t\"skillify\",\n\t\t\"skill_audit\",\n\t\t\"skill_search\",\n\t\t\"skill_open\",\n\t]);\n\n\tpublic registerProvider(p: MemoryProvider): void {\n\t\tif (this.providers.some((prov) => prov.name === p.name)) {\n\t\t\tthrow new Error(`Memory provider ${p.name} is already registered.`);\n\t\t}\n\n\t\tif (p.getToolDefinitions) {\n\t\t\tlet tools: ToolDefinition[] = [];\n\t\t\ttry {\n\t\t\t\ttools = p.getToolDefinitions() ?? [];\n\t\t\t} catch (err) {\n\t\t\t\tthrow new Error(`Failed to get tool definitions from provider ${p.name}: ${String(err)}`);\n\t\t\t}\n\n\t\t\tfor (const tool of tools) {\n\t\t\t\tif (MemoryManager.RESERVED_CORE_TOOL_NAMES.has(tool.name)) {\n\t\t\t\t\tthrow new Error(`Memory provider ${p.name} tried to register reserved core tool: ${tool.name}`);\n\t\t\t\t}\n\t\t\t\tif (this.registeredToolNames.has(tool.name)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Memory provider tool name collision: ${tool.name} is already registered. First-registration-wins.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const tool of tools) {\n\t\t\t\tthis.registeredToolNames.add(tool.name);\n\t\t\t}\n\t\t}\n\n\t\tthis.providers.push(p);\n\t}\n\n\tpublic async initializeAll(sessionId: string, ctx: MemoryLifecycleContext): Promise<void> {\n\t\tthis.ctx = ctx;\n\t\tthis.activeProviders.clear();\n\t\tthis.systemPromptBlockCache = undefined;\n\n\t\tfor (const p of this.providers) {\n\t\t\ttry {\n\t\t\t\tconst available = await p.isAvailable();\n\t\t\t\tif (!available) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tawait p.initialize(sessionId, ctx);\n\t\t\t\tthis.activeProviders.add(p.name);\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed to initialize and was deactivated:`, err);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic buildSystemPromptBlock(): string {\n\t\tif (this.systemPromptBlockCache !== undefined) {\n\t\t\treturn this.systemPromptBlockCache;\n\t\t}\n\n\t\tthis.systemPromptBlockCache = this._composeSystemPromptBlock();\n\t\treturn this.systemPromptBlockCache;\n\t}\n\n\t/**\n\t * Compose the memory block freshly from the providers, BYPASSING the frozen cache used by the\n\t * system prompt. Used by end-of-loop reflection so its confront-before-write sees the live memory\n\t * (including writes made earlier in the same session) without churning the prefix-cache-stable\n\t * system prompt block.\n\t */\n\tpublic buildSystemPromptBlockFresh(): string {\n\t\treturn this._composeSystemPromptBlock();\n\t}\n\n\tprivate _composeSystemPromptBlock(): string {\n\t\tconst blocks: string[] = [];\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.systemPromptBlock) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst block = p.systemPromptBlock();\n\t\t\t\tif (block) {\n\t\t\t\t\tblocks.push(block);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed to generate system prompt block:`, err);\n\t\t\t}\n\t\t}\n\t\treturn blocks.join(\"\\n\\n\");\n\t}\n\n\tpublic async prefetch(query: string): Promise<string> {\n\t\tconst results: string[] = [];\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.prefetch) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst text = await p.prefetch(query);\n\t\t\t\tif (text) {\n\t\t\t\t\tresults.push(text);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed during prefetch:`, err);\n\t\t\t}\n\t\t}\n\t\treturn results.join(\"\\n\\n\");\n\t}\n\n\tpublic async syncTurn(user: string, assistant: string): Promise<void> {\n\t\tif (this.ctx?.isChildSession) {\n\t\t\treturn; // Write-gated: skip writes in child sessions\n\t\t}\n\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.syncTurn) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait p.syncTurn(user, assistant);\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed during syncTurn:`, err);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic async onPreCompress(): Promise<string> {\n\t\tconst insights: string[] = [];\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.onPreCompress) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst insight = await p.onPreCompress();\n\t\t\t\tif (insight) {\n\t\t\t\t\tinsights.push(insight);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed during onPreCompress:`, err);\n\t\t\t}\n\t\t}\n\t\treturn insights.join(\"\\n\\n\");\n\t}\n\n\tpublic async onSessionEnd(): Promise<void> {\n\t\tif (this.ctx?.isChildSession) {\n\t\t\treturn; // Write-gated: skip writes in child sessions\n\t\t}\n\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.onSessionEnd) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait p.onSessionEnd();\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed during onSessionEnd:`, err);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic async shutdownAll(): Promise<void> {\n\t\t// Shutdown in reverse registration order\n\t\tconst reversed = [...this.providers].reverse();\n\t\tfor (const p of reversed) {\n\t\t\tif (!this.activeProviders.has(p.name)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait p.shutdown();\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed to shutdown cleanly:`, err);\n\t\t\t}\n\t\t}\n\t\tthis.activeProviders.clear();\n\t}\n\n\tpublic getToolDefinitions(): ToolDefinition[] {\n\t\tconst tools: ToolDefinition[] = [];\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.getToolDefinitions) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\ttools.push(...p.getToolDefinitions());\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Failed to get tool definitions from provider ${p.name}:`, err);\n\t\t\t}\n\t\t}\n\t\treturn tools;\n\t}\n\n\tpublic getContextMarkers(): string[] {\n\t\tconst markers = new Set<string>();\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.getContextMarkers) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst list = p.getContextMarkers() ?? [];\n\t\t\t\tfor (const m of list) {\n\t\t\t\t\tmarkers.add(m);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Failed to get context markers from provider ${p.name}:`, err);\n\t\t\t}\n\t\t}\n\t\treturn [...markers];\n\t}\n\n\tpublic reset(): void {\n\t\tthis.providers.length = 0;\n\t\tthis.activeProviders.clear();\n\t\tthis.registeredToolNames.clear();\n\t\tthis.systemPromptBlockCache = undefined;\n\t\tthis.ctx = undefined;\n\t}\n}\n"]}
1
+ {"version":3,"file":"memory-manager.d.ts","sourceRoot":"","sources":["../../../src/core/memory/memory-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,oCAAoC,CAAC;AAC7E,OAAO,EAGN,KAAK,kBAAkB,EACvB,MAAM,wCAAwC,CAAC;AAChD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAE7D,OAAO,KAAK,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAA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DEFAULT_EXTERNAL_MEMORY_EGRESS_POLICY,\n\thasSecretLikeMemoryText,\n\ttype MemoryEgressPolicy,\n} from \"../context/memory-provider-contract.ts\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport { wrapUntrustedText } from \"../security/untrusted-boundary.ts\";\nimport type { MemoryLifecycleContext, MemoryProvider } from \"./memory-provider.ts\";\n\nexport interface MemoryPrefetchOptions {\n\texternalEgressPolicy?: MemoryEgressPolicy;\n}\n\nexport class MemoryManager {\n\tprivate readonly providers: MemoryProvider[] = [];\n\tprivate readonly activeProviders: Set<string> = new Set();\n\tprivate readonly registeredToolNames: Set<string> = new Set();\n\tprivate ctx?: MemoryLifecycleContext;\n\tprivate systemPromptBlockCache?: { key: string; text: string };\n\n\t// Core reserved tool names to prevent hijacking or schema corruption.\n\tprivate static readonly RESERVED_CORE_TOOL_NAMES = new Set([\n\t\t\"read\",\n\t\t\"write\",\n\t\t\"grep\",\n\t\t\"find\",\n\t\t\"ls\",\n\t\t\"bash\",\n\t\t\"ask_user\",\n\t\t\"skillify\",\n\t\t\"skill_audit\",\n\t\t\"skill_search\",\n\t\t\"skill_open\",\n\t]);\n\n\tpublic registerProvider(p: MemoryProvider): void {\n\t\tif (this.providers.some((prov) => prov.name === p.name)) {\n\t\t\tthrow new Error(`Memory provider ${p.name} is already registered.`);\n\t\t}\n\n\t\tif (p.getToolDefinitions) {\n\t\t\tlet tools: ToolDefinition[] = [];\n\t\t\ttry {\n\t\t\t\ttools = p.getToolDefinitions() ?? [];\n\t\t\t} catch (err) {\n\t\t\t\tthrow new Error(`Failed to get tool definitions from provider ${p.name}: ${String(err)}`);\n\t\t\t}\n\n\t\t\tfor (const tool of tools) {\n\t\t\t\tif (MemoryManager.RESERVED_CORE_TOOL_NAMES.has(tool.name)) {\n\t\t\t\t\tthrow new Error(`Memory provider ${p.name} tried to register reserved core tool: ${tool.name}`);\n\t\t\t\t}\n\t\t\t\tif (this.registeredToolNames.has(tool.name)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Memory provider tool name collision: ${tool.name} is already registered. First-registration-wins.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const tool of tools) {\n\t\t\t\tthis.registeredToolNames.add(tool.name);\n\t\t\t}\n\t\t}\n\n\t\tthis.providers.push(p);\n\t}\n\n\tpublic async initializeAll(sessionId: string, ctx: MemoryLifecycleContext): Promise<void> {\n\t\tthis.ctx = ctx;\n\t\tthis.activeProviders.clear();\n\t\tthis.systemPromptBlockCache = undefined;\n\n\t\tfor (const p of this.providers) {\n\t\t\ttry {\n\t\t\t\tconst available = await p.isAvailable();\n\t\t\t\tif (!available) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tawait p.initialize(sessionId, ctx);\n\t\t\t\tthis.activeProviders.add(p.name);\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed to initialize and was deactivated:`, err);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic buildSystemPromptBlock(budget?: MemoryPromptBudget): string {\n\t\tconst key =\n\t\t\tbudget === undefined\n\t\t\t\t? \"none\"\n\t\t\t\t: `${budget.enabled}:${budget.compact}:${budget.maxLines}:${budget.maxEstimatedTokens}:${budget.maxChars}`;\n\t\tif (this.systemPromptBlockCache !== undefined && this.systemPromptBlockCache.key === key) {\n\t\t\treturn this.systemPromptBlockCache.text;\n\t\t}\n\n\t\tconst text = this._composeSystemPromptBlock(budget);\n\t\tthis.systemPromptBlockCache = { key, text };\n\t\treturn text;\n\t}\n\n\t/**\n\t * Compose the memory block freshly from the providers, BYPASSING the frozen cache used by the\n\t * system prompt. Used by end-of-loop reflection so its confront-before-write sees the live memory\n\t * (including writes made earlier in the same session) without churning the prefix-cache-stable\n\t * system prompt block.\n\t */\n\tpublic buildSystemPromptBlockFresh(budget?: MemoryPromptBudget): string {\n\t\treturn this._composeSystemPromptBlock(budget);\n\t}\n\n\tprivate _composeSystemPromptBlock(budget?: MemoryPromptBudget): string {\n\t\tconst blocks: string[] = [];\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.systemPromptBlock) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst block = p.systemPromptBlock(budget);\n\t\t\t\tif (block) {\n\t\t\t\t\tblocks.push(block);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed to generate system prompt block:`, err);\n\t\t\t}\n\t\t}\n\t\treturn blocks.join(\"\\n\\n\");\n\t}\n\n\tpublic async prefetch(query: string, options: MemoryPrefetchOptions = {}): Promise<string> {\n\t\tconst results: string[] = [];\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.prefetch) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (p.egress !== \"local\") {\n\t\t\t\tconst policy = options.externalEgressPolicy ?? DEFAULT_EXTERNAL_MEMORY_EGRESS_POLICY;\n\t\t\t\tif (\n\t\t\t\t\t!policy.enabled ||\n\t\t\t\t\t!policy.allowExternalEgress ||\n\t\t\t\t\t!policy.allowQueryText ||\n\t\t\t\t\tquery.length > policy.maxOutboundChars ||\n\t\t\t\t\t(policy.redactSecretLikeText && hasSecretLikeMemoryText(query))\n\t\t\t\t) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst text = await p.prefetch(query);\n\t\t\t\tif (text) {\n\t\t\t\t\tresults.push(wrapUntrustedText(text, `memory:${p.name}`));\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed during prefetch:`, err);\n\t\t\t}\n\t\t}\n\t\treturn results.join(\"\\n\\n\");\n\t}\n\n\tpublic async syncTurn(user: string, assistant: string): Promise<void> {\n\t\tif (this.ctx?.isChildSession) {\n\t\t\treturn; // Write-gated: skip writes in child sessions\n\t\t}\n\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.syncTurn) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait p.syncTurn(user, assistant);\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed during syncTurn:`, err);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic async onPreCompress(): Promise<string> {\n\t\tconst insights: string[] = [];\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.onPreCompress) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst insight = await p.onPreCompress();\n\t\t\t\tif (insight) {\n\t\t\t\t\tinsights.push(insight);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed during onPreCompress:`, err);\n\t\t\t}\n\t\t}\n\t\treturn insights.join(\"\\n\\n\");\n\t}\n\n\tpublic async onSessionEnd(): Promise<void> {\n\t\tif (this.ctx?.isChildSession) {\n\t\t\treturn; // Write-gated: skip writes in child sessions\n\t\t}\n\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.onSessionEnd) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait p.onSessionEnd();\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed during onSessionEnd:`, err);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic async shutdownAll(): Promise<void> {\n\t\t// Shutdown in reverse registration order\n\t\tconst reversed = [...this.providers].reverse();\n\t\tfor (const p of reversed) {\n\t\t\tif (!this.activeProviders.has(p.name)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait p.shutdown();\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed to shutdown cleanly:`, err);\n\t\t\t}\n\t\t}\n\t\tthis.activeProviders.clear();\n\t}\n\n\tpublic getToolDefinitions(): ToolDefinition[] {\n\t\tconst tools: ToolDefinition[] = [];\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.getToolDefinitions) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\ttools.push(...p.getToolDefinitions());\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Failed to get tool definitions from provider ${p.name}:`, err);\n\t\t\t}\n\t\t}\n\t\treturn tools;\n\t}\n\n\tpublic getContextMarkers(): string[] {\n\t\tconst markers = new Set<string>();\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.getContextMarkers) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst list = p.getContextMarkers() ?? [];\n\t\t\t\tfor (const m of list) {\n\t\t\t\t\tmarkers.add(m);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Failed to get context markers from provider ${p.name}:`, err);\n\t\t\t}\n\t\t}\n\t\treturn [...markers];\n\t}\n\n\tpublic reset(): void {\n\t\tthis.providers.length = 0;\n\t\tthis.activeProviders.clear();\n\t\tthis.registeredToolNames.clear();\n\t\tthis.systemPromptBlockCache = undefined;\n\t\tthis.ctx = undefined;\n\t}\n}\n"]}
@@ -1,3 +1,5 @@
1
+ import { DEFAULT_EXTERNAL_MEMORY_EGRESS_POLICY, hasSecretLikeMemoryText, } from "../context/memory-provider-contract.js";
2
+ import { wrapUntrustedText } from "../security/untrusted-boundary.js";
1
3
  export class MemoryManager {
2
4
  providers = [];
3
5
  activeProviders = new Set();
@@ -62,12 +64,16 @@ export class MemoryManager {
62
64
  }
63
65
  }
64
66
  }
65
- buildSystemPromptBlock() {
66
- if (this.systemPromptBlockCache !== undefined) {
67
- return this.systemPromptBlockCache;
67
+ buildSystemPromptBlock(budget) {
68
+ const key = budget === undefined
69
+ ? "none"
70
+ : `${budget.enabled}:${budget.compact}:${budget.maxLines}:${budget.maxEstimatedTokens}:${budget.maxChars}`;
71
+ if (this.systemPromptBlockCache !== undefined && this.systemPromptBlockCache.key === key) {
72
+ return this.systemPromptBlockCache.text;
68
73
  }
69
- this.systemPromptBlockCache = this._composeSystemPromptBlock();
70
- return this.systemPromptBlockCache;
74
+ const text = this._composeSystemPromptBlock(budget);
75
+ this.systemPromptBlockCache = { key, text };
76
+ return text;
71
77
  }
72
78
  /**
73
79
  * Compose the memory block freshly from the providers, BYPASSING the frozen cache used by the
@@ -75,17 +81,17 @@ export class MemoryManager {
75
81
  * (including writes made earlier in the same session) without churning the prefix-cache-stable
76
82
  * system prompt block.
77
83
  */
78
- buildSystemPromptBlockFresh() {
79
- return this._composeSystemPromptBlock();
84
+ buildSystemPromptBlockFresh(budget) {
85
+ return this._composeSystemPromptBlock(budget);
80
86
  }
81
- _composeSystemPromptBlock() {
87
+ _composeSystemPromptBlock(budget) {
82
88
  const blocks = [];
83
89
  for (const p of this.providers) {
84
90
  if (!this.activeProviders.has(p.name) || !p.systemPromptBlock) {
85
91
  continue;
86
92
  }
87
93
  try {
88
- const block = p.systemPromptBlock();
94
+ const block = p.systemPromptBlock(budget);
89
95
  if (block) {
90
96
  blocks.push(block);
91
97
  }
@@ -96,16 +102,26 @@ export class MemoryManager {
96
102
  }
97
103
  return blocks.join("\n\n");
98
104
  }
99
- async prefetch(query) {
105
+ async prefetch(query, options = {}) {
100
106
  const results = [];
101
107
  for (const p of this.providers) {
102
108
  if (!this.activeProviders.has(p.name) || !p.prefetch) {
103
109
  continue;
104
110
  }
111
+ if (p.egress !== "local") {
112
+ const policy = options.externalEgressPolicy ?? DEFAULT_EXTERNAL_MEMORY_EGRESS_POLICY;
113
+ if (!policy.enabled ||
114
+ !policy.allowExternalEgress ||
115
+ !policy.allowQueryText ||
116
+ query.length > policy.maxOutboundChars ||
117
+ (policy.redactSecretLikeText && hasSecretLikeMemoryText(query))) {
118
+ continue;
119
+ }
120
+ }
105
121
  try {
106
122
  const text = await p.prefetch(query);
107
123
  if (text) {
108
- results.push(text);
124
+ results.push(wrapUntrustedText(text, `memory:${p.name}`));
109
125
  }
110
126
  }
111
127
  catch (err) {
@@ -1 +1 @@
1
- {"version":3,"file":"memory-manager.js","sourceRoot":"","sources":["../../../src/core/memory/memory-manager.ts"],"names":[],"mappings":"AAGA,MAAM,OAAO,aAAa;IACR,SAAS,GAAqB,EAAE,CAAC;IACjC,eAAe,GAAgB,IAAI,GAAG,EAAE,CAAC;IACzC,mBAAmB,GAAgB,IAAI,GAAG,EAAE,CAAC;IACtD,GAAG,CAA0B;IAC7B,sBAAsB,CAAU;IAExC,sEAAsE;IAC9D,MAAM,CAAU,wBAAwB,GAAG,IAAI,GAAG,CAAC;QAC1D,MAAM;QACN,OAAO;QACP,MAAM;QACN,MAAM;QACN,IAAI;QACJ,MAAM;QACN,UAAU;QACV,UAAU;QACV,aAAa;QACb,cAAc;QACd,YAAY;KACZ,CAAC,CAAC;IAEI,gBAAgB,CAAC,CAAiB,EAAQ;QAChD,IAAI,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC;YACzD,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC,IAAI,yBAAyB,CAAC,CAAC;QACrE,CAAC;QAED,IAAI,CAAC,CAAC,kBAAkB,EAAE,CAAC;YAC1B,IAAI,KAAK,GAAqB,EAAE,CAAC;YACjC,IAAI,CAAC;gBACJ,KAAK,GAAG,CAAC,CAAC,kBAAkB,EAAE,IAAI,EAAE,CAAC;YACtC,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACd,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YAC3F,CAAC;YAED,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;g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AC,CAAC,CAAC,iBAAiB,EAAE,CAAC;gBAC/D,SAAS;YACV,CAAC;YACD,IAAI,CAAC;gBACJ,MAAM,IAAI,GAAG,CAAC,CAAC,iBAAiB,EAAE,IAAI,EAAE,CAAC;gBACzC,KAAK,MAAM,CAAC,IAAI,IAAI,EAAE,CAAC;oBACtB,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;gBAChB,CAAC;YACF,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACd,OAAO,CAAC,KAAK,CAAC,+CAA+C,CAAC,CAAC,IAAI,GAAG,EAAE,GAAG,CAAC,CAAC;YAC9E,CAAC;QACF,CAAC;QACD,OAAO,CAAC,GAAG,OAAO,CAAC,CAAC;IAAA,CACpB;IAEM,KAAK,GAAS;QACpB,IAAI,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC;QAC1B,IAAI,CAAC,eAAe,CAAC,KAAK,EAAE,CAAC;QAC7B,IAAI,CAAC,mBAAmB,CAAC,KAAK,EAAE,CAAC;QACjC,IAAI,CAAC,sBAAsB,GAAG,SAAS,CAAC;QACxC,IAAI,CAAC,GAAG,GAAG,SAAS,CAAC;IAAA,CACrB;CACD","sourcesContent":["import type { ToolDefinition } from \"../extensions/types.ts\";\nimport type { MemoryLifecycleContext, MemoryProvider } from \"./memory-provider.ts\";\n\nexport class MemoryManager {\n\tprivate readonly providers: MemoryProvider[] = [];\n\tprivate readonly activeProviders: Set<string> = new Set();\n\tprivate readonly registeredToolNames: Set<string> = new Set();\n\tprivate ctx?: MemoryLifecycleContext;\n\tprivate systemPromptBlockCache?: string;\n\n\t// Core reserved tool names to prevent hijacking or schema corruption.\n\tprivate static readonly RESERVED_CORE_TOOL_NAMES = new Set([\n\t\t\"read\",\n\t\t\"write\",\n\t\t\"grep\",\n\t\t\"find\",\n\t\t\"ls\",\n\t\t\"bash\",\n\t\t\"ask_user\",\n\t\t\"skillify\",\n\t\t\"skill_audit\",\n\t\t\"skill_search\",\n\t\t\"skill_open\",\n\t]);\n\n\tpublic registerProvider(p: MemoryProvider): void {\n\t\tif (this.providers.some((prov) => prov.name === p.name)) {\n\t\t\tthrow new Error(`Memory provider ${p.name} is already registered.`);\n\t\t}\n\n\t\tif (p.getToolDefinitions) {\n\t\t\tlet tools: ToolDefinition[] = [];\n\t\t\ttry {\n\t\t\t\ttools = p.getToolDefinitions() ?? [];\n\t\t\t} catch (err) {\n\t\t\t\tthrow new Error(`Failed to get tool definitions from provider ${p.name}: ${String(err)}`);\n\t\t\t}\n\n\t\t\tfor (const tool of tools) {\n\t\t\t\tif (MemoryManager.RESERVED_CORE_TOOL_NAMES.has(tool.name)) {\n\t\t\t\t\tthrow new Error(`Memory provider ${p.name} tried to register reserved core tool: ${tool.name}`);\n\t\t\t\t}\n\t\t\t\tif (this.registeredToolNames.has(tool.name)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Memory provider tool name collision: ${tool.name} is already registered. First-registration-wins.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const tool of tools) {\n\t\t\t\tthis.registeredToolNames.add(tool.name);\n\t\t\t}\n\t\t}\n\n\t\tthis.providers.push(p);\n\t}\n\n\tpublic async initializeAll(sessionId: string, ctx: MemoryLifecycleContext): Promise<void> {\n\t\tthis.ctx = ctx;\n\t\tthis.activeProviders.clear();\n\t\tthis.systemPromptBlockCache = undefined;\n\n\t\tfor (const p of this.providers) {\n\t\t\ttry {\n\t\t\t\tconst available = await p.isAvailable();\n\t\t\t\tif (!available) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tawait p.initialize(sessionId, ctx);\n\t\t\t\tthis.activeProviders.add(p.name);\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed to initialize and was deactivated:`, err);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic buildSystemPromptBlock(): string {\n\t\tif (this.systemPromptBlockCache !== undefined) {\n\t\t\treturn this.systemPromptBlockCache;\n\t\t}\n\n\t\tthis.systemPromptBlockCache = this._composeSystemPromptBlock();\n\t\treturn this.systemPromptBlockCache;\n\t}\n\n\t/**\n\t * Compose the memory block freshly from the providers, BYPASSING the frozen cache used by the\n\t * system prompt. Used by end-of-loop reflection so its confront-before-write sees the live memory\n\t * (including writes made earlier in the same session) without churning the prefix-cache-stable\n\t * system prompt block.\n\t */\n\tpublic buildSystemPromptBlockFresh(): string {\n\t\treturn this._composeSystemPromptBlock();\n\t}\n\n\tprivate _composeSystemPromptBlock(): string {\n\t\tconst blocks: string[] = [];\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.systemPromptBlock) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst block = p.systemPromptBlock();\n\t\t\t\tif (block) {\n\t\t\t\t\tblocks.push(block);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed to generate system prompt block:`, err);\n\t\t\t}\n\t\t}\n\t\treturn blocks.join(\"\\n\\n\");\n\t}\n\n\tpublic async prefetch(query: string): Promise<string> {\n\t\tconst results: string[] = [];\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.prefetch) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst text = await p.prefetch(query);\n\t\t\t\tif (text) {\n\t\t\t\t\tresults.push(text);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed during prefetch:`, err);\n\t\t\t}\n\t\t}\n\t\treturn results.join(\"\\n\\n\");\n\t}\n\n\tpublic async syncTurn(user: string, assistant: string): Promise<void> {\n\t\tif (this.ctx?.isChildSession) {\n\t\t\treturn; // Write-gated: skip writes in child sessions\n\t\t}\n\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.syncTurn) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait p.syncTurn(user, assistant);\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed during syncTurn:`, err);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic async onPreCompress(): Promise<string> {\n\t\tconst insights: string[] = [];\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.onPreCompress) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst insight = await p.onPreCompress();\n\t\t\t\tif (insight) {\n\t\t\t\t\tinsights.push(insight);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed during onPreCompress:`, err);\n\t\t\t}\n\t\t}\n\t\treturn insights.join(\"\\n\\n\");\n\t}\n\n\tpublic async onSessionEnd(): Promise<void> {\n\t\tif (this.ctx?.isChildSession) {\n\t\t\treturn; // Write-gated: skip writes in child sessions\n\t\t}\n\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.onSessionEnd) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait p.onSessionEnd();\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed during onSessionEnd:`, err);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic async shutdownAll(): Promise<void> {\n\t\t// Shutdown in reverse registration order\n\t\tconst reversed = [...this.providers].reverse();\n\t\tfor (const p of reversed) {\n\t\t\tif (!this.activeProviders.has(p.name)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait p.shutdown();\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed to shutdown cleanly:`, err);\n\t\t\t}\n\t\t}\n\t\tthis.activeProviders.clear();\n\t}\n\n\tpublic getToolDefinitions(): ToolDefinition[] {\n\t\tconst tools: ToolDefinition[] = [];\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.getToolDefinitions) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\ttools.push(...p.getToolDefinitions());\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Failed to get tool definitions from provider ${p.name}:`, err);\n\t\t\t}\n\t\t}\n\t\treturn tools;\n\t}\n\n\tpublic getContextMarkers(): string[] {\n\t\tconst markers = new Set<string>();\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.getContextMarkers) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst list = p.getContextMarkers() ?? [];\n\t\t\t\tfor (const m of list) {\n\t\t\t\t\tmarkers.add(m);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Failed to get context markers from provider ${p.name}:`, err);\n\t\t\t}\n\t\t}\n\t\treturn [...markers];\n\t}\n\n\tpublic reset(): void {\n\t\tthis.providers.length = 0;\n\t\tthis.activeProviders.clear();\n\t\tthis.registeredToolNames.clear();\n\t\tthis.systemPromptBlockCache = undefined;\n\t\tthis.ctx = undefined;\n\t}\n}\n"]}
1
+ {"version":3,"file":"memory-manager.js","sourceRoot":"","sources":["../../../src/core/memory/memory-manager.ts"],"names":[],"mappings":"AACA,OAAO,EACN,qCAAqC,EACrC,uBAAuB,GAEvB,MAAM,wCAAwC,CAAC;AAEhD,OAAO,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AAOtE,MAAM,OAAO,aAAa;IACR,SAAS,GAAqB,EAAE,CAAC;IACjC,eAAe,GAAgB,IAAI,GAAG,EAAE,CAAC;IACzC,mBAAmB,GAAgB,IAAI,GAAG,EAAE,CAAC;IACtD,GAAG,CAA0B;IAC7B,sBAAsB,CAAiC;IAE/D,sEAAsE;IAC9D,MAAM,CAAU,wBAAwB,GAAG,IAAI,GAAG,CAAC;QAC1D,MAAM;QACN,OAAO;QACP,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LICY,\n\thasSecretLikeMemoryText,\n\ttype MemoryEgressPolicy,\n} from \"../context/memory-provider-contract.ts\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport { wrapUntrustedText } from \"../security/untrusted-boundary.ts\";\nimport type { MemoryLifecycleContext, MemoryProvider } from \"./memory-provider.ts\";\n\nexport interface MemoryPrefetchOptions {\n\texternalEgressPolicy?: MemoryEgressPolicy;\n}\n\nexport class MemoryManager {\n\tprivate readonly providers: MemoryProvider[] = [];\n\tprivate readonly activeProviders: Set<string> = new Set();\n\tprivate readonly registeredToolNames: Set<string> = new Set();\n\tprivate ctx?: MemoryLifecycleContext;\n\tprivate systemPromptBlockCache?: { key: string; text: string };\n\n\t// Core reserved tool names to prevent hijacking or schema corruption.\n\tprivate static readonly RESERVED_CORE_TOOL_NAMES = new Set([\n\t\t\"read\",\n\t\t\"write\",\n\t\t\"grep\",\n\t\t\"find\",\n\t\t\"ls\",\n\t\t\"bash\",\n\t\t\"ask_user\",\n\t\t\"skillify\",\n\t\t\"skill_audit\",\n\t\t\"skill_search\",\n\t\t\"skill_open\",\n\t]);\n\n\tpublic registerProvider(p: MemoryProvider): void {\n\t\tif (this.providers.some((prov) => prov.name === p.name)) {\n\t\t\tthrow new Error(`Memory provider ${p.name} is already registered.`);\n\t\t}\n\n\t\tif (p.getToolDefinitions) {\n\t\t\tlet tools: ToolDefinition[] = [];\n\t\t\ttry {\n\t\t\t\ttools = p.getToolDefinitions() ?? [];\n\t\t\t} catch (err) {\n\t\t\t\tthrow new Error(`Failed to get tool definitions from provider ${p.name}: ${String(err)}`);\n\t\t\t}\n\n\t\t\tfor (const tool of tools) {\n\t\t\t\tif (MemoryManager.RESERVED_CORE_TOOL_NAMES.has(tool.name)) {\n\t\t\t\t\tthrow new Error(`Memory provider ${p.name} tried to register reserved core tool: ${tool.name}`);\n\t\t\t\t}\n\t\t\t\tif (this.registeredToolNames.has(tool.name)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Memory provider tool name collision: ${tool.name} is already registered. First-registration-wins.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const tool of tools) {\n\t\t\t\tthis.registeredToolNames.add(tool.name);\n\t\t\t}\n\t\t}\n\n\t\tthis.providers.push(p);\n\t}\n\n\tpublic async initializeAll(sessionId: string, ctx: MemoryLifecycleContext): Promise<void> {\n\t\tthis.ctx = ctx;\n\t\tthis.activeProviders.clear();\n\t\tthis.systemPromptBlockCache = undefined;\n\n\t\tfor (const p of this.providers) {\n\t\t\ttry {\n\t\t\t\tconst available = await p.isAvailable();\n\t\t\t\tif (!available) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tawait p.initialize(sessionId, ctx);\n\t\t\t\tthis.activeProviders.add(p.name);\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed to initialize and was deactivated:`, err);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic buildSystemPromptBlock(budget?: MemoryPromptBudget): string {\n\t\tconst key =\n\t\t\tbudget === undefined\n\t\t\t\t? \"none\"\n\t\t\t\t: `${budget.enabled}:${budget.compact}:${budget.maxLines}:${budget.maxEstimatedTokens}:${budget.maxChars}`;\n\t\tif (this.systemPromptBlockCache !== undefined && this.systemPromptBlockCache.key === key) {\n\t\t\treturn this.systemPromptBlockCache.text;\n\t\t}\n\n\t\tconst text = this._composeSystemPromptBlock(budget);\n\t\tthis.systemPromptBlockCache = { key, text };\n\t\treturn text;\n\t}\n\n\t/**\n\t * Compose the memory block freshly from the providers, BYPASSING the frozen cache used by the\n\t * system prompt. Used by end-of-loop reflection so its confront-before-write sees the live memory\n\t * (including writes made earlier in the same session) without churning the prefix-cache-stable\n\t * system prompt block.\n\t */\n\tpublic buildSystemPromptBlockFresh(budget?: MemoryPromptBudget): string {\n\t\treturn this._composeSystemPromptBlock(budget);\n\t}\n\n\tprivate _composeSystemPromptBlock(budget?: MemoryPromptBudget): string {\n\t\tconst blocks: string[] = [];\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.systemPromptBlock) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst block = p.systemPromptBlock(budget);\n\t\t\t\tif (block) {\n\t\t\t\t\tblocks.push(block);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed to generate system prompt block:`, err);\n\t\t\t}\n\t\t}\n\t\treturn blocks.join(\"\\n\\n\");\n\t}\n\n\tpublic async prefetch(query: string, options: MemoryPrefetchOptions = {}): Promise<string> {\n\t\tconst results: string[] = [];\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.prefetch) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (p.egress !== \"local\") {\n\t\t\t\tconst policy = options.externalEgressPolicy ?? DEFAULT_EXTERNAL_MEMORY_EGRESS_POLICY;\n\t\t\t\tif (\n\t\t\t\t\t!policy.enabled ||\n\t\t\t\t\t!policy.allowExternalEgress ||\n\t\t\t\t\t!policy.allowQueryText ||\n\t\t\t\t\tquery.length > policy.maxOutboundChars ||\n\t\t\t\t\t(policy.redactSecretLikeText && hasSecretLikeMemoryText(query))\n\t\t\t\t) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst text = await p.prefetch(query);\n\t\t\t\tif (text) {\n\t\t\t\t\tresults.push(wrapUntrustedText(text, `memory:${p.name}`));\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed during prefetch:`, err);\n\t\t\t}\n\t\t}\n\t\treturn results.join(\"\\n\\n\");\n\t}\n\n\tpublic async syncTurn(user: string, assistant: string): Promise<void> {\n\t\tif (this.ctx?.isChildSession) {\n\t\t\treturn; // Write-gated: skip writes in child sessions\n\t\t}\n\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.syncTurn) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait p.syncTurn(user, assistant);\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed during syncTurn:`, err);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic async onPreCompress(): Promise<string> {\n\t\tconst insights: string[] = [];\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.onPreCompress) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst insight = await p.onPreCompress();\n\t\t\t\tif (insight) {\n\t\t\t\t\tinsights.push(insight);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed during onPreCompress:`, err);\n\t\t\t}\n\t\t}\n\t\treturn insights.join(\"\\n\\n\");\n\t}\n\n\tpublic async onSessionEnd(): Promise<void> {\n\t\tif (this.ctx?.isChildSession) {\n\t\t\treturn; // Write-gated: skip writes in child sessions\n\t\t}\n\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.onSessionEnd) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait p.onSessionEnd();\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed during onSessionEnd:`, err);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic async shutdownAll(): Promise<void> {\n\t\t// Shutdown in reverse registration order\n\t\tconst reversed = [...this.providers].reverse();\n\t\tfor (const p of reversed) {\n\t\t\tif (!this.activeProviders.has(p.name)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait p.shutdown();\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Memory provider ${p.name} failed to shutdown cleanly:`, err);\n\t\t\t}\n\t\t}\n\t\tthis.activeProviders.clear();\n\t}\n\n\tpublic getToolDefinitions(): ToolDefinition[] {\n\t\tconst tools: ToolDefinition[] = [];\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.getToolDefinitions) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\ttools.push(...p.getToolDefinitions());\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Failed to get tool definitions from provider ${p.name}:`, err);\n\t\t\t}\n\t\t}\n\t\treturn tools;\n\t}\n\n\tpublic getContextMarkers(): string[] {\n\t\tconst markers = new Set<string>();\n\t\tfor (const p of this.providers) {\n\t\t\tif (!this.activeProviders.has(p.name) || !p.getContextMarkers) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst list = p.getContextMarkers() ?? [];\n\t\t\t\tfor (const m of list) {\n\t\t\t\t\tmarkers.add(m);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(`Failed to get context markers from provider ${p.name}:`, err);\n\t\t\t}\n\t\t}\n\t\treturn [...markers];\n\t}\n\n\tpublic reset(): void {\n\t\tthis.providers.length = 0;\n\t\tthis.activeProviders.clear();\n\t\tthis.registeredToolNames.clear();\n\t\tthis.systemPromptBlockCache = undefined;\n\t\tthis.ctx = undefined;\n\t}\n}\n"]}