@gmickel/gno 2.15.0 → 2.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/README.md +1 -1
  2. package/assets/skill/cli-reference.md +4 -2
  3. package/assets/spa-production.json.gz +0 -0
  4. package/browser-extension/artifacts/{gno-browser-clipper-v2.15.0.zip → gno-browser-clipper-v2.16.0.zip} +0 -0
  5. package/browser-extension/artifacts/gno-browser-clipper-v2.16.0.zip.sha256 +1 -0
  6. package/browser-extension/dist/manifest.json +1 -1
  7. package/package.json +1 -1
  8. package/spec/cli.md +1 -1
  9. package/src/cli/commands/agents/commands.ts +1 -1
  10. package/src/cli/commands/ask.ts +1 -1
  11. package/src/cli/commands/context-build.ts +1 -1
  12. package/src/cli/commands/embed.ts +2 -2
  13. package/src/cli/commands/links.ts +1 -1
  14. package/src/cli/commands/mcp/install.ts +2 -2
  15. package/src/cli/commands/mcp/status.ts +1 -1
  16. package/src/cli/commands/mcp/uninstall.ts +1 -1
  17. package/src/cli/commands/query.ts +1 -1
  18. package/src/cli/commands/shared.ts +4 -4
  19. package/src/cli/commands/skill/install.ts +1 -1
  20. package/src/cli/commands/skill/paths-cmd.ts +1 -1
  21. package/src/cli/commands/skill/uninstall.ts +1 -1
  22. package/src/cli/commands/status.ts +75 -58
  23. package/src/cli/config-cache.ts +86 -0
  24. package/src/cli/globals.ts +64 -0
  25. package/src/cli/program.ts +20 -36
  26. package/src/cli/run.ts +121 -67
  27. package/src/cli/runtime-health.ts +132 -122
  28. package/src/cli/session-binding.ts +11 -2
  29. package/src/config/saver.ts +8 -0
  30. package/src/converters/adapters/browser-export/formats.ts +25 -15
  31. package/src/converters/adapters/email/adapter.ts +37 -53
  32. package/src/converters/adapters/email/html.ts +37 -20
  33. package/src/converters/adapters/email/mime.ts +71 -39
  34. package/src/converters/adapters/ical/adapter.ts +20 -12
  35. package/src/converters/adapters/jsonl/adapter.ts +8 -6
  36. package/src/converters/adapters/shared/html-text.ts +55 -37
  37. package/src/converters/adapters/shared/ooxml-protection.ts +5 -13
  38. package/src/converters/adapters/shared/utf8-lines.ts +69 -31
  39. package/src/converters/adapters/transcript/adapter.ts +12 -7
  40. package/src/converters/adapters/xlsx/adapter.ts +10 -7
  41. package/src/converters/adapters/xlsx/sheet-markdown.ts +93 -50
  42. package/src/converters/canonicalize.ts +17 -3
  43. package/src/converters/native/markdown.ts +24 -17
  44. package/src/converters/native/plaintext.ts +5 -6
  45. package/src/converters/registry.ts +130 -8
  46. package/src/core/activation-status.ts +4 -8
  47. package/src/core/change-diff.ts +38 -11
  48. package/src/core/context-compiler.ts +17 -18
  49. package/src/core/context-evidence.ts +116 -25
  50. package/src/core/context-verifier.ts +70 -31
  51. package/src/core/file-lock.ts +10 -2
  52. package/src/core/graph-analysis.ts +3 -3
  53. package/src/core/link-inventory-markdown.ts +2 -2
  54. package/src/core/links.ts +20 -87
  55. package/src/core/memory-fence.ts +16 -9
  56. package/src/core/memory-recall.ts +168 -34
  57. package/src/core/path-rules.ts +143 -0
  58. package/src/core/section-parse.ts +16 -6
  59. package/src/core/typed-metadata.ts +68 -0
  60. package/src/core/wiki-link-syntax.ts +88 -0
  61. package/src/embed/backlog.ts +142 -60
  62. package/src/embed/retry.ts +39 -33
  63. package/src/embed/variant-backlog.ts +546 -114
  64. package/src/embed/variant-retry.ts +157 -48
  65. package/src/index.ts +3 -3
  66. package/src/ingestion/budget-error-codes.ts +13 -0
  67. package/src/ingestion/chunker.ts +60 -49
  68. package/src/ingestion/compiled-context.ts +4 -5
  69. package/src/ingestion/convert-file.ts +1 -1
  70. package/src/ingestion/document-metadata.ts +16 -9
  71. package/src/ingestion/excluded-ranges.ts +97 -0
  72. package/src/ingestion/file-processor.ts +122 -37
  73. package/src/ingestion/frontmatter.ts +35 -7
  74. package/src/ingestion/graph-reconciliation.ts +187 -51
  75. package/src/ingestion/language.ts +66 -61
  76. package/src/ingestion/position.ts +5 -5
  77. package/src/ingestion/prepare-file.ts +50 -29
  78. package/src/ingestion/record-adapter-canonical.ts +37 -26
  79. package/src/ingestion/record-adapter.ts +46 -26
  80. package/src/ingestion/record-container.ts +121 -53
  81. package/src/ingestion/record-path.ts +5 -2
  82. package/src/ingestion/source-availability/darwin-io.ts +10 -7
  83. package/src/ingestion/source-availability/darwin-path.ts +21 -3
  84. package/src/ingestion/source-availability/readers.ts +51 -0
  85. package/src/ingestion/strip.ts +39 -105
  86. package/src/ingestion/sync.ts +692 -386
  87. package/src/ingestion/typed-metadata.ts +10 -4
  88. package/src/ingestion/walker.ts +485 -158
  89. package/src/llm/cache.ts +128 -84
  90. package/src/llm/http-inference.ts +112 -35
  91. package/src/llm/http-policy.ts +101 -0
  92. package/src/llm/httpEmbedding.ts +8 -1
  93. package/src/llm/httpGeneration.ts +5 -1
  94. package/src/llm/httpRerank.ts +5 -1
  95. package/src/llm/inference-scope.ts +15 -2
  96. package/src/llm/lazy-ports.ts +33 -3
  97. package/src/llm/lockfile.ts +34 -7
  98. package/src/llm/model-cleanup.ts +24 -0
  99. package/src/llm/native-worker/client.ts +23 -12
  100. package/src/llm/native-worker/dispatcher.ts +19 -9
  101. package/src/llm/native-worker/embedding-identity.ts +42 -16
  102. package/src/llm/native-worker/entry.ts +2 -1
  103. package/src/llm/native-worker/owner.ts +1 -0
  104. package/src/llm/native-worker/ports.ts +86 -23
  105. package/src/llm/native-worker/protocol.ts +386 -55
  106. package/src/llm/nodeLlamaCpp/adapter.ts +46 -29
  107. package/src/llm/nodeLlamaCpp/embedding.ts +93 -40
  108. package/src/llm/nodeLlamaCpp/generation.ts +194 -30
  109. package/src/llm/nodeLlamaCpp/lifecycle.ts +2 -0
  110. package/src/llm/nodeLlamaCpp/rerank-capacity.ts +101 -23
  111. package/src/llm/nodeLlamaCpp/rerank.ts +253 -44
  112. package/src/llm/types.ts +14 -0
  113. package/src/mcp/context.ts +342 -23
  114. package/src/mcp/http-transport.ts +21 -3
  115. package/src/mcp/tool-profile-types.ts +62 -0
  116. package/src/mcp/tool-profile.ts +32 -56
  117. package/src/mcp/tools/context.ts +5 -1
  118. package/src/mcp/tools/index.ts +269 -191
  119. package/src/mcp/tools/links.ts +7 -5
  120. package/src/mcp/tools/query.ts +60 -37
  121. package/src/mcp/tools/vsearch.ts +25 -14
  122. package/src/pipeline/answer.ts +133 -40
  123. package/src/pipeline/claim-verification.ts +293 -189
  124. package/src/pipeline/claim-verifier.ts +6 -7
  125. package/src/pipeline/egress-lineage.ts +37 -26
  126. package/src/pipeline/exclude.ts +34 -11
  127. package/src/pipeline/expansion.ts +233 -19
  128. package/src/pipeline/filters.ts +169 -33
  129. package/src/pipeline/graph-retrieval.ts +117 -61
  130. package/src/pipeline/hybrid.ts +598 -329
  131. package/src/pipeline/hydration.ts +86 -24
  132. package/src/pipeline/intent.ts +15 -7
  133. package/src/pipeline/owner-fusion.ts +61 -19
  134. package/src/pipeline/query-language.ts +15 -2
  135. package/src/pipeline/rerank.ts +15 -22
  136. package/src/pipeline/search.ts +193 -72
  137. package/src/pipeline/snippet.ts +15 -2
  138. package/src/pipeline/temporal.ts +51 -10
  139. package/src/pipeline/vsearch.ts +250 -152
  140. package/src/publish/attachment-raster.ts +2 -16
  141. package/src/publish/encrypted-export.ts +15 -5
  142. package/src/serve/browse-tree.ts +50 -42
  143. package/src/serve/connectors.ts +2 -1
  144. package/src/serve/context.ts +13 -4
  145. package/src/serve/doc-events.ts +3 -0
  146. package/src/serve/public/app.tsx +49 -21
  147. package/src/serve/public/components/BrowseTreeSidebar.tsx +163 -23
  148. package/src/serve/public/components/CaptureModal.tsx +14 -10
  149. package/src/serve/public/components/ai-elements/code-block.tsx +87 -50
  150. package/src/serve/public/components/editor/MarkdownPreview.tsx +99 -67
  151. package/src/serve/public/globals.built.css +1 -1
  152. package/src/serve/public/globals.css +19 -0
  153. package/src/serve/public/hooks/useCaptureModal.tsx +23 -10
  154. package/src/serve/public/lib/metadata-filter.ts +234 -9
  155. package/src/serve/public/pages/Browse.tsx +61 -27
  156. package/src/serve/public/pages/DocView.tsx +44 -25
  157. package/src/serve/public/pages/GraphView.tsx +8 -3
  158. package/src/serve/resident-runtime.ts +199 -48
  159. package/src/serve/routes/api.ts +98 -67
  160. package/src/serve/routes/links.ts +18 -4
  161. package/src/serve/server.ts +1370 -1180
  162. package/src/serve/spa-bundle-source.ts +52 -27
  163. package/src/serve/status.ts +101 -52
  164. package/src/serve/watch-reconciliation-fallback.ts +11 -7
  165. package/src/serve/watch-reconciliation-shared.ts +42 -4
  166. package/src/serve/watch-reconciliation.ts +21 -8
  167. package/src/serve/watch-service-events.ts +7 -1
  168. package/src/serve/watch-service-hosts.ts +3 -1
  169. package/src/serve/watch-service.ts +46 -21
  170. package/src/serve/watch-snapshot-scan.ts +6 -15
  171. package/src/sessions/archive.ts +20 -8
  172. package/src/sessions/sanitize.ts +38 -18
  173. package/src/sessions/service.ts +180 -102
  174. package/src/store/migrations/037-performance-indexes.ts +56 -0
  175. package/src/store/migrations/index.ts +2 -0
  176. package/src/store/sqlite/adapter.ts +1217 -651
  177. package/src/store/sqlite/chunking-policy.ts +15 -1
  178. package/src/store/sqlite/eligibility.ts +110 -70
  179. package/src/store/sqlite/graph-neighbors.ts +71 -46
  180. package/src/store/sqlite/graph-reference-state.ts +27 -3
  181. package/src/store/sqlite/graph-similarity.ts +59 -12
  182. package/src/store/sqlite/metadata-predicate.ts +123 -28
  183. package/src/store/sqlite/retrieval-trace-management-store.ts +126 -33
  184. package/src/store/sqlite/retrieval-trace-retention.ts +88 -76
  185. package/src/store/sqlite/retrieval-trace-rows.ts +7 -3
  186. package/src/store/types.ts +32 -0
  187. package/src/store/vector/eligibility.ts +39 -0
  188. package/src/store/vector/lazy.ts +17 -0
  189. package/src/store/vector/partition-index.ts +28 -45
  190. package/src/store/vector/proof-cache.ts +103 -0
  191. package/src/store/vector/sqlite-vec.ts +230 -139
  192. package/src/store/vector/stats.ts +29 -73
  193. package/src/store/vector/status.ts +151 -52
  194. package/src/store/vector/stored-vectors.ts +131 -45
  195. package/src/store/vector/types.ts +10 -0
  196. package/src/store/vector/variant-search.ts +771 -109
  197. package/src/store/vector/variants.ts +495 -139
  198. package/browser-extension/artifacts/gno-browser-clipper-v2.15.0.zip.sha256 +0 -1
@@ -13,42 +13,113 @@ import type { EgressLineage } from "../core/egress-provenance";
13
13
  import type { JobManager } from "../core/job-manager";
14
14
  import type { NativeDisposeOptions } from "../llm/native-worker/owned-exit";
15
15
  import type { ModelLease } from "../llm/nodeLlamaCpp/lifecycle";
16
+ import type {
17
+ EmbeddingPort,
18
+ GenerationPort,
19
+ LlmResult,
20
+ RerankPort,
21
+ } from "../llm/types";
16
22
  import type { ResidentStatus } from "../serve/status-model";
17
23
  import type { SqliteAdapter } from "../store/sqlite/adapter";
18
24
  import type { StoreResult } from "../store/types";
25
+ import type { VectorIndexPort } from "../store/vector";
19
26
  import type { McpToolProfile } from "./tool-profile";
20
27
 
21
28
  import { MCP_SERVER_NAME, VERSION } from "../app/constants";
22
- import { LlmAdapter } from "../llm/nodeLlamaCpp/adapter";
29
+ import {
30
+ type CreatePortOptions,
31
+ LlmAdapter,
32
+ } from "../llm/nodeLlamaCpp/adapter";
23
33
  import { createStandaloneResidentStatus } from "../serve/resident-status";
34
+ import { createVectorIndexPort } from "../store/vector";
35
+ import { getStoredEmbeddingDimensions } from "../store/vector/freshness";
36
+ import { createLazyVectorIndex } from "../store/vector/lazy";
24
37
  import { registerResources } from "./resources/index";
25
38
  import { registerTools } from "./tools/index";
26
39
 
27
40
  export interface AsyncMutex {
28
41
  acquire(): Promise<() => void>;
42
+ /** Shared read lock for concurrent read-only tools; falls back to exclusive acquire() on test doubles. */
43
+ acquireRead?(): Promise<() => void>;
29
44
  }
30
45
 
46
+ /**
47
+ * Fair async reader-writer lock.
48
+ * - `acquireRead()` allows concurrent read-only tools when no writer is active or queued.
49
+ * - `acquire()` grants exclusive access for write tools, jobs, and shutdown, draining
50
+ * all active readers and queuing subsequent readers behind it to prevent writer starvation.
51
+ */
31
52
  export class Mutex implements AsyncMutex {
32
- #locked = false;
33
- readonly #queue: Array<() => void> = [];
53
+ #activeReaders = 0;
54
+ #writerActive = false;
55
+ readonly #waiters: Array<{ kind: "read" | "write"; grant: () => void }> = [];
34
56
 
35
57
  acquire(): Promise<() => void> {
36
58
  return new Promise((resolve) => {
37
- const tryAcquire = (): void => {
38
- if (this.#locked) {
39
- this.#queue.push(tryAcquire);
40
- return;
41
- }
42
- this.#locked = true;
43
- resolve(() => this.#release());
59
+ const grant = (): void => {
60
+ this.#writerActive = true;
61
+ let released = false;
62
+ resolve(() => {
63
+ if (released) return;
64
+ released = true;
65
+ this.#writerActive = false;
66
+ this.#drain();
67
+ });
44
68
  };
45
- tryAcquire();
69
+ if (
70
+ !this.#writerActive &&
71
+ this.#activeReaders === 0 &&
72
+ this.#waiters.length === 0
73
+ ) {
74
+ grant();
75
+ return;
76
+ }
77
+ this.#waiters.push({ kind: "write", grant });
46
78
  });
47
79
  }
48
80
 
49
- #release(): void {
50
- this.#locked = false;
51
- this.#queue.shift()?.();
81
+ acquireRead(): Promise<() => void> {
82
+ return new Promise((resolve) => {
83
+ const grant = (): void => {
84
+ this.#activeReaders += 1;
85
+ let released = false;
86
+ resolve(() => {
87
+ if (released) return;
88
+ released = true;
89
+ this.#activeReaders -= 1;
90
+ if (this.#activeReaders === 0) {
91
+ this.#drain();
92
+ }
93
+ });
94
+ };
95
+ if (!this.#writerActive && this.#waiters.length === 0) {
96
+ grant();
97
+ return;
98
+ }
99
+ this.#waiters.push({ kind: "read", grant });
100
+ });
101
+ }
102
+
103
+ #drain(): void {
104
+ if (this.#writerActive) {
105
+ return;
106
+ }
107
+ while (this.#waiters.length > 0) {
108
+ const next = this.#waiters[0];
109
+ if (!next) {
110
+ break;
111
+ }
112
+ if (next.kind === "read") {
113
+ this.#waiters.shift();
114
+ next.grant();
115
+ continue;
116
+ }
117
+ if (this.#activeReaders === 0) {
118
+ this.#waiters.shift();
119
+ next.grant();
120
+ }
121
+ break;
122
+ }
52
123
  }
53
124
  }
54
125
 
@@ -92,6 +163,26 @@ export interface ToolContext {
92
163
  isShuttingDown: () => boolean;
93
164
  getResidentStatus?: () => ResidentStatus;
94
165
  getModelAdapter?: () => LlmAdapter;
166
+ getCachedEmbeddingPort?: (
167
+ uri: string,
168
+ options: CreatePortOptions
169
+ ) => Promise<LlmResult<EmbeddingPort>>;
170
+ getCachedExpansionPort?: (
171
+ uri: string,
172
+ options: CreatePortOptions
173
+ ) => Promise<LlmResult<GenerationPort>>;
174
+ getCachedRerankPort?: (
175
+ uri: string,
176
+ options: CreatePortOptions
177
+ ) => Promise<LlmResult<RerankPort>>;
178
+ getCachedVectorIndex?: (
179
+ modelUri: string,
180
+ dimensions: number
181
+ ) => Promise<StoreResult<VectorIndexPort>>;
182
+ getCachedLazyVectorIndex?: (
183
+ modelUri: string,
184
+ embedPort: EmbeddingPort
185
+ ) => Promise<VectorIndexPort | null>;
95
186
  disposeModels?: (options?: NativeDisposeOptions) => Promise<void>;
96
187
  acquireModelLease?: () => ModelLease;
97
188
  markContentMutation?: () => void;
@@ -162,6 +253,20 @@ export function createToolContext(
162
253
  options: CreateToolContextOptions
163
254
  ): ToolContext {
164
255
  const adapters = new Map<Config, LlmAdapter>();
256
+ let cachedPortConfig: Config | null = null;
257
+ let cachedPortGeneration = 0;
258
+ // Cache ONLY successfully initialized ports so concurrent callers never
259
+ // inherit another caller's cancellation scope during cold initialization.
260
+ const cachedEmbedPorts = new Map<string, EmbeddingPort>();
261
+ const cachedExpandPorts = new Map<string, GenerationPort>();
262
+ const cachedRerankPorts = new Map<string, RerankPort>();
263
+ // Ports superseded by a config reload remain live for any in-flight caller
264
+ // until shutdown (`disposeModels`) drains requests and disposes all ports.
265
+ const retiredPorts = new Set<{ dispose(): Promise<void> }>();
266
+ const cachedVectorIndexes = new Map<
267
+ string,
268
+ Promise<StoreResult<VectorIndexPort>>
269
+ >();
165
270
  let modelsClosed = false;
166
271
  const requestSnapshot = new AsyncLocalStorage<ToolContextSnapshot>();
167
272
  const currentSnapshot = (): ToolContextSnapshot =>
@@ -171,12 +276,78 @@ export function createToolContext(
171
276
  return { config, collections: config.collections };
172
277
  })();
173
278
 
279
+ const portCacheKey = (
280
+ uri: string,
281
+ portOptions?: CreatePortOptions
282
+ ): string => {
283
+ const egress = portOptions?.egressCollections;
284
+ const egressKey =
285
+ egress === undefined || egress === "all"
286
+ ? "*"
287
+ : [...egress].sort().join("\u0000");
288
+ const policy = portOptions?.policy;
289
+ const policyKey = policy
290
+ ? `${policy.offline ? 1 : 0}:${policy.allowDownload ? 1 : 0}`
291
+ : "default";
292
+ return `${uri}\u0001${egressKey}\u0001${policyKey}`;
293
+ };
294
+
295
+ const evictCachedPortsForConfigChange = (): void => {
296
+ cachedPortGeneration += 1;
297
+ for (const port of cachedEmbedPorts.values()) {
298
+ retiredPorts.add(port);
299
+ }
300
+ for (const port of cachedExpandPorts.values()) {
301
+ retiredPorts.add(port);
302
+ }
303
+ for (const port of cachedRerankPorts.values()) {
304
+ retiredPorts.add(port);
305
+ }
306
+ cachedEmbedPorts.clear();
307
+ cachedExpandPorts.clear();
308
+ cachedRerankPorts.clear();
309
+ cachedVectorIndexes.clear();
310
+ cachedPortConfig = null;
311
+ };
312
+
313
+ const disposeAllCachedPorts = async (): Promise<void> => {
314
+ evictCachedPortsForConfigChange();
315
+ const disposals: Promise<unknown>[] = [];
316
+ for (const port of retiredPorts) {
317
+ disposals.push(Promise.resolve().then(() => port.dispose()));
318
+ }
319
+ retiredPorts.clear();
320
+ await Promise.allSettled(disposals);
321
+ };
322
+
323
+ const ensurePortCacheForConfig = (config: Config): void => {
324
+ if (cachedPortConfig !== null && cachedPortConfig !== config) {
325
+ evictCachedPortsForConfigChange();
326
+ }
327
+ cachedPortConfig = config;
328
+ };
329
+
330
+ const resolveModelAdapter = (config: Config): LlmAdapter => {
331
+ if (modelsClosed) throw new Error("Resident runtime is shutting down");
332
+ const shared = options.getModelAdapter?.(config);
333
+ if (shared) return shared;
334
+ let adapter = adapters.get(config);
335
+ if (!adapter) {
336
+ adapter = new LlmAdapter(config);
337
+ adapters.set(config, adapter);
338
+ }
339
+ return adapter;
340
+ };
341
+
174
342
  return {
175
343
  store: options.store,
176
344
  get config() {
177
345
  return currentSnapshot().config;
178
346
  },
179
347
  set config(config: Config) {
348
+ if (cachedPortConfig !== null && cachedPortConfig !== config) {
349
+ evictCachedPortsForConfigChange();
350
+ }
180
351
  options.setConfig?.(config);
181
352
  },
182
353
  get collections() {
@@ -198,20 +369,168 @@ export function createToolContext(
198
369
  getResidentStatus:
199
370
  options.getResidentStatus ??
200
371
  (() => createStandaloneResidentStatus("stdio")),
201
- getModelAdapter: () => {
202
- if (modelsClosed) throw new Error("Resident runtime is shutting down");
372
+ getModelAdapter: () => resolveModelAdapter(currentSnapshot().config),
373
+ getCachedEmbeddingPort: async (uri, portOptions) => {
203
374
  const config = currentSnapshot().config;
204
- const shared = options.getModelAdapter?.(config);
205
- if (shared) return shared;
206
- let adapter = adapters.get(config);
207
- if (!adapter) {
208
- adapter = new LlmAdapter(config);
209
- adapters.set(config, adapter);
375
+ const llm = resolveModelAdapter(config);
376
+ ensurePortCacheForConfig(config);
377
+ const key = portCacheKey(uri, portOptions);
378
+ const cached = cachedEmbedPorts.get(key);
379
+ if (cached) {
380
+ return { ok: true, value: cached };
381
+ }
382
+ const generation = cachedPortGeneration;
383
+ const res = await llm.createEmbeddingPort(uri, portOptions);
384
+ if (!res.ok) {
385
+ return res;
386
+ }
387
+ if (modelsClosed) {
388
+ await res.value.dispose();
389
+ return {
390
+ ok: false,
391
+ error: {
392
+ code: "MODEL_LOAD_FAILED",
393
+ message: "Resident runtime is shutting down",
394
+ retryable: false,
395
+ },
396
+ };
397
+ }
398
+ if (generation !== cachedPortGeneration) {
399
+ // Keep the opened port live for this in-flight snapshot caller;
400
+ // disposeModels() will clean it up after shutdown drains requests.
401
+ retiredPorts.add(res.value);
402
+ return res;
403
+ }
404
+ const existing = cachedEmbedPorts.get(key);
405
+ if (existing) {
406
+ // Do NOT call res.value.dispose() while existing is active: native
407
+ // ports share the same ModelManager slot and dispose() unloads it.
408
+ // Defer disposal to shutdown (`disposeModels`) via retiredPorts.
409
+ retiredPorts.add(res.value);
410
+ return { ok: true, value: existing };
411
+ }
412
+ cachedEmbedPorts.set(key, res.value);
413
+ return res;
414
+ },
415
+ getCachedExpansionPort: async (uri, portOptions) => {
416
+ const config = currentSnapshot().config;
417
+ const llm = resolveModelAdapter(config);
418
+ ensurePortCacheForConfig(config);
419
+ const key = portCacheKey(uri, portOptions);
420
+ const cached = cachedExpandPorts.get(key);
421
+ if (cached) {
422
+ return { ok: true, value: cached };
423
+ }
424
+ const generation = cachedPortGeneration;
425
+ const res = await llm.createExpansionPort(uri, portOptions);
426
+ if (!res.ok) {
427
+ return res;
428
+ }
429
+ if (modelsClosed) {
430
+ await res.value.dispose();
431
+ return {
432
+ ok: false,
433
+ error: {
434
+ code: "MODEL_LOAD_FAILED",
435
+ message: "Resident runtime is shutting down",
436
+ retryable: false,
437
+ },
438
+ };
439
+ }
440
+ if (generation !== cachedPortGeneration) {
441
+ retiredPorts.add(res.value);
442
+ return res;
443
+ }
444
+ const existing = cachedExpandPorts.get(key);
445
+ if (existing) {
446
+ retiredPorts.add(res.value);
447
+ return { ok: true, value: existing };
448
+ }
449
+ cachedExpandPorts.set(key, res.value);
450
+ return res;
451
+ },
452
+ getCachedRerankPort: async (uri, portOptions) => {
453
+ const config = currentSnapshot().config;
454
+ const llm = resolveModelAdapter(config);
455
+ ensurePortCacheForConfig(config);
456
+ const key = portCacheKey(uri, portOptions);
457
+ const cached = cachedRerankPorts.get(key);
458
+ if (cached) {
459
+ return { ok: true, value: cached };
460
+ }
461
+ const generation = cachedPortGeneration;
462
+ const res = await llm.createRerankPort(uri, portOptions);
463
+ if (!res.ok) {
464
+ return res;
465
+ }
466
+ if (modelsClosed) {
467
+ await res.value.dispose();
468
+ return {
469
+ ok: false,
470
+ error: {
471
+ code: "MODEL_LOAD_FAILED",
472
+ message: "Resident runtime is shutting down",
473
+ retryable: false,
474
+ },
475
+ };
476
+ }
477
+ if (generation !== cachedPortGeneration) {
478
+ retiredPorts.add(res.value);
479
+ return res;
480
+ }
481
+ const existing = cachedRerankPorts.get(key);
482
+ if (existing) {
483
+ retiredPorts.add(res.value);
484
+ return { ok: true, value: existing };
485
+ }
486
+ cachedRerankPorts.set(key, res.value);
487
+ return res;
488
+ },
489
+ getCachedVectorIndex: (modelUri, dimensions) => {
490
+ const config = currentSnapshot().config;
491
+ ensurePortCacheForConfig(config);
492
+ const key = `${modelUri}\u0000${dimensions}`;
493
+ let pending = cachedVectorIndexes.get(key);
494
+ if (!pending) {
495
+ pending = createVectorIndexPort(options.store.getRawDb(), {
496
+ model: modelUri,
497
+ dimensions,
498
+ }).then((res) => {
499
+ if (!res.ok) cachedVectorIndexes.delete(key);
500
+ return res;
501
+ });
502
+ cachedVectorIndexes.set(key, pending);
503
+ }
504
+ return pending;
505
+ },
506
+ getCachedLazyVectorIndex: async (modelUri, embedPort) => {
507
+ const config = currentSnapshot().config;
508
+ ensurePortCacheForConfig(config);
509
+ const db = options.store.getRawDb();
510
+ const storedDimensions = getStoredEmbeddingDimensions(db, modelUri);
511
+ if (storedDimensions !== undefined) {
512
+ const key = `${modelUri}\u0000${storedDimensions}`;
513
+ let pending = cachedVectorIndexes.get(key);
514
+ if (!pending) {
515
+ pending = createVectorIndexPort(db, {
516
+ model: modelUri,
517
+ dimensions: storedDimensions,
518
+ }).then((res) => {
519
+ if (!res.ok) cachedVectorIndexes.delete(key);
520
+ return res;
521
+ });
522
+ cachedVectorIndexes.set(key, pending);
523
+ }
524
+ const res = await pending;
525
+ return res.ok ? res.value : null;
210
526
  }
211
- return adapter;
527
+ // Never cache an uninitialized lazy wrapper holding a caller-scoped
528
+ // embedPort (its egress policy is specific to this request).
529
+ return createLazyVectorIndex(db, modelUri, embedPort);
212
530
  },
213
531
  disposeModels: async (disposeOptions) => {
214
532
  modelsClosed = true;
533
+ await disposeAllCachedPorts();
215
534
  await Promise.all(
216
535
  [...adapters.values()].map((adapter) => adapter.dispose(disposeOptions))
217
536
  );
@@ -182,6 +182,9 @@ function wrapStreamingResponse(
182
182
  return new Response(body, response);
183
183
  }
184
184
 
185
+ const REQUEST_IDENTITY_CACHE_MAX = 256;
186
+ const requestIdentityCache = new Map<string, string>();
187
+
185
188
  /**
186
189
  * Opaque per-caller label for memory provenance and other per-session state.
187
190
  *
@@ -194,11 +197,24 @@ function deriveRequestIdentity(
194
197
  serverInstanceId: string,
195
198
  securityIdentity: string
196
199
  ): string {
200
+ const key = `${serverInstanceId}\u0000${securityIdentity}`;
201
+ const cached = requestIdentityCache.get(key);
202
+ if (cached !== undefined) {
203
+ return cached;
204
+ }
197
205
  const digest = new Bun.CryptoHasher("sha256")
198
- .update(`${serverInstanceId}\u0000${securityIdentity}`)
206
+ .update(key)
199
207
  .digest("hex")
200
208
  .slice(0, REQUEST_IDENTITY_DIGEST_LENGTH);
201
- return `http:${digest}`;
209
+ const label = `http:${digest}`;
210
+ if (requestIdentityCache.size >= REQUEST_IDENTITY_CACHE_MAX) {
211
+ const oldestKey = requestIdentityCache.keys().next().value;
212
+ if (oldestKey !== undefined) {
213
+ requestIdentityCache.delete(oldestKey);
214
+ }
215
+ }
216
+ requestIdentityCache.set(key, label);
217
+ return label;
202
218
  }
203
219
 
204
220
  const policyChangedResponse = (): Response =>
@@ -334,7 +350,9 @@ export class HttpMcpTransport {
334
350
  let parsedBody = context.parsedBody;
335
351
  if (request.method === "POST" && parsedBody === undefined) {
336
352
  try {
337
- parsedBody = await request.clone().json();
353
+ // Both legacy and modern handlers receive `parsedBody` explicitly,
354
+ // so reading request.json() directly avoids cloning the request stream.
355
+ parsedBody = await request.json();
338
356
  } catch {
339
357
  finish();
340
358
  return jsonRpcError(400, -32_700, "Parse error: Invalid JSON");
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Zero-dependency MCP tool profile types and parser.
3
+ * Extracted from src/mcp/tool-profile so CLI startup and installers do not
4
+ * pull in zod or LLM inference-scope modules just to parse profile flags.
5
+ *
6
+ * @module src/mcp/tool-profile-types
7
+ */
8
+
9
+ export const MCP_TOOL_PROFILES = ["core", "full"] as const;
10
+
11
+ export type McpToolProfile = (typeof MCP_TOOL_PROFILES)[number];
12
+
13
+ export const DEFAULT_MCP_TOOL_PROFILE: McpToolProfile = "full";
14
+
15
+ /** Read tools the core profile advertises without `--enable-write`. */
16
+ export const MCP_CORE_READ_TOOL_NAMES: ReadonlySet<string> = new Set([
17
+ "gno_query",
18
+ "gno_search",
19
+ "gno_get",
20
+ "gno_multi_get",
21
+ "gno_context",
22
+ "gno_changes",
23
+ "gno_recall",
24
+ ]);
25
+
26
+ /**
27
+ * Write tools the core profile adds with `--enable-write`.
28
+ *
29
+ * `gno_job_status` is deliberately absent: `gno_capture` and `gno_remember`
30
+ * complete synchronously (neither starts a JobManager job), so nothing the
31
+ * core profile exposes ever returns a job ID to poll.
32
+ */
33
+ export const MCP_CORE_WRITE_TOOL_NAMES: ReadonlySet<string> = new Set([
34
+ "gno_capture",
35
+ "gno_remember",
36
+ ]);
37
+
38
+ export function isMcpToolProfile(value: unknown): value is McpToolProfile {
39
+ return (
40
+ typeof value === "string" &&
41
+ (MCP_TOOL_PROFILES as readonly string[]).includes(value)
42
+ );
43
+ }
44
+
45
+ /** Parse a CLI/config value; `undefined` means "not given" (caller applies precedence). */
46
+ export function parseMcpToolProfile(
47
+ value: unknown
48
+ ): McpToolProfile | undefined {
49
+ if (value === undefined) return undefined;
50
+ if (isMcpToolProfile(value)) return value;
51
+ throw new Error(
52
+ `Invalid tool profile: ${JSON.stringify(value)}. Must be one of: ${MCP_TOOL_PROFILES.join(", ")}.`
53
+ );
54
+ }
55
+
56
+ /** Tool names a profile advertises; `null` means every registered tool. */
57
+ export function mcpToolProfileAllowlist(
58
+ profile: McpToolProfile
59
+ ): ReadonlySet<string> | null {
60
+ if (profile === "full") return null;
61
+ return new Set([...MCP_CORE_READ_TOOL_NAMES, ...MCP_CORE_WRITE_TOOL_NAMES]);
62
+ }
@@ -20,61 +20,27 @@ import type {
20
20
  import { z } from "zod";
21
21
 
22
22
  import { withInferenceScope } from "../llm/inference-scope";
23
+ import {
24
+ DEFAULT_MCP_TOOL_PROFILE,
25
+ isMcpToolProfile,
26
+ MCP_CORE_READ_TOOL_NAMES,
27
+ MCP_CORE_WRITE_TOOL_NAMES,
28
+ MCP_TOOL_PROFILES,
29
+ type McpToolProfile,
30
+ mcpToolProfileAllowlist,
31
+ parseMcpToolProfile,
32
+ } from "./tool-profile-types";
23
33
 
24
- export const MCP_TOOL_PROFILES = ["core", "full"] as const;
25
-
26
- export type McpToolProfile = (typeof MCP_TOOL_PROFILES)[number];
27
-
28
- export const DEFAULT_MCP_TOOL_PROFILE: McpToolProfile = "full";
29
-
30
- /** Read tools the core profile advertises without `--enable-write`. */
31
- export const MCP_CORE_READ_TOOL_NAMES: ReadonlySet<string> = new Set([
32
- "gno_query",
33
- "gno_search",
34
- "gno_get",
35
- "gno_multi_get",
36
- "gno_context",
37
- "gno_changes",
38
- "gno_recall",
39
- ]);
40
-
41
- /**
42
- * Write tools the core profile adds with `--enable-write`.
43
- *
44
- * `gno_job_status` is deliberately absent: `gno_capture` and `gno_remember`
45
- * complete synchronously (neither starts a JobManager job), so nothing the
46
- * core profile exposes ever returns a job ID to poll.
47
- */
48
- export const MCP_CORE_WRITE_TOOL_NAMES: ReadonlySet<string> = new Set([
49
- "gno_capture",
50
- "gno_remember",
51
- ]);
52
-
53
- export function isMcpToolProfile(value: unknown): value is McpToolProfile {
54
- return (
55
- typeof value === "string" &&
56
- (MCP_TOOL_PROFILES as readonly string[]).includes(value)
57
- );
58
- }
59
-
60
- /** Parse a CLI/config value; `undefined` means "not given" (caller applies precedence). */
61
- export function parseMcpToolProfile(
62
- value: unknown
63
- ): McpToolProfile | undefined {
64
- if (value === undefined) return undefined;
65
- if (isMcpToolProfile(value)) return value;
66
- throw new Error(
67
- `Invalid tool profile: ${JSON.stringify(value)}. Must be one of: ${MCP_TOOL_PROFILES.join(", ")}.`
68
- );
69
- }
70
-
71
- /** Tool names a profile advertises; `null` means every registered tool. */
72
- export function mcpToolProfileAllowlist(
73
- profile: McpToolProfile
74
- ): ReadonlySet<string> | null {
75
- if (profile === "full") return null;
76
- return new Set([...MCP_CORE_READ_TOOL_NAMES, ...MCP_CORE_WRITE_TOOL_NAMES]);
77
- }
34
+ export {
35
+ DEFAULT_MCP_TOOL_PROFILE,
36
+ isMcpToolProfile,
37
+ MCP_CORE_READ_TOOL_NAMES,
38
+ MCP_CORE_WRITE_TOOL_NAMES,
39
+ MCP_TOOL_PROFILES,
40
+ type McpToolProfile,
41
+ mcpToolProfileAllowlist,
42
+ parseMcpToolProfile,
43
+ };
78
44
 
79
45
  /**
80
46
  * Registration through a profile. Mirrors `McpServer.registerTool`'s
@@ -139,11 +105,21 @@ export function createProfileToolRegistrar(
139
105
  };
140
106
  }
141
107
 
108
+ const strictSchemaCache = new WeakMap<z.ZodObject, z.ZodObject>();
109
+
142
110
  /**
143
111
  * Unknown argument keys fail validation with the key named instead of being
144
112
  * dropped: a misspelled scope or receipt key must not silently widen a read
145
113
  * or skip a write fence.
146
114
  */
147
- function rejectUnknownKeys<T>(schema: T): T {
148
- return (schema instanceof z.ZodObject ? schema.strict() : schema) as T;
115
+ export function rejectUnknownKeys<T>(schema: T): T {
116
+ if (!(schema instanceof z.ZodObject)) {
117
+ return schema;
118
+ }
119
+ let strict = strictSchemaCache.get(schema);
120
+ if (!strict) {
121
+ strict = schema.strict();
122
+ strictSchemaCache.set(schema, strict);
123
+ }
124
+ return strict as unknown as T;
149
125
  }
@@ -84,7 +84,11 @@ const runContextTool = async (
84
84
  })
85
85
  );
86
86
  }
87
- const release = await context.toolMutex.acquire();
87
+ const isHttpRequest = context.getEgressContext?.() !== undefined;
88
+ const release =
89
+ isHttpRequest && context.toolMutex.acquireRead
90
+ ? await context.toolMutex.acquireRead()
91
+ : await context.toolMutex.acquire();
88
92
  try {
89
93
  const data = await (context.runWithSnapshot?.(operation) ?? operation());
90
94
  return asToolResult(data);