renor-engine 1.2.0 → 1.3.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 (215) hide show
  1. package/README.md +21 -1
  2. package/THIRD-PARTY-NOTICES +2661 -0
  3. package/dist/BUILD.json +6 -0
  4. package/dist/cli.js +1656 -516
  5. package/package.json +16 -80
  6. package/dist/.tsbuildinfo +0 -1
  7. package/dist/api/apiAuth.js +0 -43
  8. package/dist/api/server.js +0 -174
  9. package/dist/buildIdentity.js +0 -149
  10. package/dist/callPhases.js +0 -82
  11. package/dist/cli-extractors.js +0 -46
  12. package/dist/config.js +0 -65
  13. package/dist/context/composer.js +0 -320
  14. package/dist/context/readHonesty.js +0 -478
  15. package/dist/context/rowStore.js +0 -238
  16. package/dist/conversation/formatter.js +0 -81
  17. package/dist/conversation/parser.js +0 -193
  18. package/dist/conversation/types.js +0 -2
  19. package/dist/conversation/writer.js +0 -42
  20. package/dist/db/client.js +0 -149
  21. package/dist/db/handoffTable.js +0 -31
  22. package/dist/db/indexSalvage.js +0 -101
  23. package/dist/db/migrations.js +0 -670
  24. package/dist/db/readCache.js +0 -109
  25. package/dist/db/schema.js +0 -5
  26. package/dist/db/sqlite.js +0 -396
  27. package/dist/db/statements.js +0 -89
  28. package/dist/digests/digestCache.js +0 -146
  29. package/dist/digests/digests.js +0 -597
  30. package/dist/digests/worker.js +0 -350
  31. package/dist/embeddings/caching.js +0 -337
  32. package/dist/embeddings/coalescing.js +0 -177
  33. package/dist/embeddings/interactive.js +0 -103
  34. package/dist/embeddings/local.js +0 -70
  35. package/dist/embeddings/openai.js +0 -106
  36. package/dist/embeddings/rebuild.js +0 -166
  37. package/dist/embeddings/simdScan.js +0 -260
  38. package/dist/embeddings/space.js +0 -21
  39. package/dist/embeddings/types.js +0 -14
  40. package/dist/embeddings/vectorIndex.js +0 -674
  41. package/dist/embeddings/vertex.js +0 -334
  42. package/dist/eval/artifacts.js +0 -42
  43. package/dist/eval/cacheReport.js +0 -146
  44. package/dist/eval/comparison.js +0 -182
  45. package/dist/eval/context700-candidate.js +0 -145
  46. package/dist/eval/evalCache.js +0 -568
  47. package/dist/eval/hashEmbedding.js +0 -35
  48. package/dist/eval/indexSnapshots.js +0 -549
  49. package/dist/eval/longmemeval.js +0 -56
  50. package/dist/eval/metrics.js +0 -181
  51. package/dist/eval/pageDump.js +0 -67
  52. package/dist/eval/renorbenchBaseline.js +0 -486
  53. package/dist/eval/renorbenchDocuments.js +0 -134
  54. package/dist/eval/renorbenchProduct.js +0 -182
  55. package/dist/eval/runLedger.js +0 -279
  56. package/dist/eval/runManifest.js +0 -485
  57. package/dist/eval/scoring.js +0 -197
  58. package/dist/eval/textTokens.js +0 -17
  59. package/dist/evidence/attach.js +0 -264
  60. package/dist/evidence/background.js +0 -147
  61. package/dist/evidence/evidenceCache.js +0 -182
  62. package/dist/evidence/gate.js +0 -37
  63. package/dist/evidence/keyPool.js +0 -85
  64. package/dist/evidence/ollamaChat.js +0 -84
  65. package/dist/evidence/optin.js +0 -165
  66. package/dist/evidence/options.js +0 -151
  67. package/dist/evidence/secondPass.js +0 -294
  68. package/dist/extraction/classifyCapture.js +0 -34
  69. package/dist/extraction/decision-model.js +0 -174
  70. package/dist/extraction/eventExtractor.js +0 -113
  71. package/dist/extraction/extractionClient.js +0 -122
  72. package/dist/extraction/factExtractor.js +0 -46
  73. package/dist/extraction/factsWritePath.js +0 -179
  74. package/dist/extraction/jevDecisionModel.js +0 -307
  75. package/dist/extraction/preferenceExtractor.js +0 -150
  76. package/dist/extraction/secretGuard.js +0 -180
  77. package/dist/extraction/secretScanner.js +0 -665
  78. package/dist/extraction/typedFacts.js +0 -224
  79. package/dist/extraction/writePathAdjudication.js +0 -110
  80. package/dist/importing/apply.js +0 -672
  81. package/dist/importing/bundle-write.js +0 -80
  82. package/dist/importing/cli.js +0 -408
  83. package/dist/importing/existing.js +0 -51
  84. package/dist/importing/facts.js +0 -121
  85. package/dist/importing/forgetImported.js +0 -79
  86. package/dist/importing/hosted.js +0 -467
  87. package/dist/importing/journalLog.js +0 -96
  88. package/dist/importing/markdown.js +0 -98
  89. package/dist/importing/plan.js +0 -201
  90. package/dist/importing/secretScreen.js +0 -113
  91. package/dist/importing/serialize.js +0 -188
  92. package/dist/importing/source.js +0 -463
  93. package/dist/importing/types.js +0 -6
  94. package/dist/indexer/chunker.js +0 -319
  95. package/dist/indexer/dailyEntries.js +0 -63
  96. package/dist/indexer/hasher.js +0 -10
  97. package/dist/indexer/laneRuns.js +0 -48
  98. package/dist/indexer/o200k.js +0 -481
  99. package/dist/indexer/outsideRoot.js +0 -77
  100. package/dist/indexer/parser.js +0 -170
  101. package/dist/indexer/pipeline.js +0 -988
  102. package/dist/indexer/staleness.js +0 -201
  103. package/dist/indexer/tokenizer.js +0 -77
  104. package/dist/indexer/walker.js +0 -170
  105. package/dist/learning/cli.js +0 -113
  106. package/dist/learning/schema.js +0 -144
  107. package/dist/learning/settings.js +0 -45
  108. package/dist/learning/store.js +0 -267
  109. package/dist/learning/tap.js +0 -401
  110. package/dist/mcp/hive.js +0 -88
  111. package/dist/mcp/requestErrors.js +0 -47
  112. package/dist/mcp/server.js +0 -426
  113. package/dist/memory/agentLease.js +0 -43
  114. package/dist/memory/confinedWrite.js +0 -315
  115. package/dist/memory/controls.js +0 -73
  116. package/dist/memory/dailyNote.js +0 -265
  117. package/dist/memory/dreamer/adjudicate.js +0 -215
  118. package/dist/memory/dreamer/apply.js +0 -120
  119. package/dist/memory/dreamer/budget.js +0 -64
  120. package/dist/memory/dreamer/candidates.js +0 -149
  121. package/dist/memory/dreamer/collection.js +0 -104
  122. package/dist/memory/dreamer/dreamer.js +0 -352
  123. package/dist/memory/dreamer/review.js +0 -111
  124. package/dist/memory/durableAppend.js +0 -57
  125. package/dist/memory/factConflicts.js +0 -205
  126. package/dist/memory/factTerms.js +0 -321
  127. package/dist/memory/handoff.js +0 -363
  128. package/dist/memory/hiveNameHeader.cjs +0 -10
  129. package/dist/memory/inventory.js +0 -55
  130. package/dist/memory/invisibleText.js +0 -20
  131. package/dist/memory/lifecycle.js +0 -2014
  132. package/dist/memory/limits.js +0 -13
  133. package/dist/memory/requests.js +0 -183
  134. package/dist/memory/sourceName.js +0 -276
  135. package/dist/memory/statusFacts.js +0 -61
  136. package/dist/memory/whatsNew.js +0 -158
  137. package/dist/memory/writer.js +0 -176
  138. package/dist/memory/writerConflicts.js +0 -85
  139. package/dist/memorymap/memoryMap.js +0 -1594
  140. package/dist/memorymap/replacedJournal.js +0 -58
  141. package/dist/memorymap/replacements.js +0 -410
  142. package/dist/mvp/activity.js +0 -86
  143. package/dist/mvp/agentMemory.js +0 -1803
  144. package/dist/mvp/answerCheck.js +0 -211
  145. package/dist/mvp/auth.js +0 -531
  146. package/dist/mvp/cli.js +0 -86
  147. package/dist/mvp/client-store.js +0 -462
  148. package/dist/mvp/compileCache.js +0 -242
  149. package/dist/mvp/compileSeed.js +0 -33
  150. package/dist/mvp/config.js +0 -292
  151. package/dist/mvp/connectionStatus.js +0 -80
  152. package/dist/mvp/contextDistinct.js +0 -53
  153. package/dist/mvp/contextProfile.js +0 -87
  154. package/dist/mvp/contextRelevance.js +0 -413
  155. package/dist/mvp/directorySurface.js +0 -68
  156. package/dist/mvp/engine.js +0 -1078
  157. package/dist/mvp/exportAll.js +0 -393
  158. package/dist/mvp/factLanePack.js +0 -77
  159. package/dist/mvp/factMarkers.js +0 -65
  160. package/dist/mvp/factsLane.js +0 -203
  161. package/dist/mvp/hiddenSpans.js +0 -585
  162. package/dist/mvp/history.js +0 -414
  163. package/dist/mvp/hitDates.js +0 -31
  164. package/dist/mvp/hitFloor.js +0 -36
  165. package/dist/mvp/identity.js +0 -18
  166. package/dist/mvp/idle.js +0 -113
  167. package/dist/mvp/log.js +0 -118
  168. package/dist/mvp/memoryDir.js +0 -98
  169. package/dist/mvp/posthogMcp.js +0 -210
  170. package/dist/mvp/readScope.js +0 -104
  171. package/dist/mvp/readUsefulness.js +0 -222
  172. package/dist/mvp/sanitize.js +0 -48
  173. package/dist/mvp/schemaRejections.js +0 -91
  174. package/dist/mvp/scope.js +0 -127
  175. package/dist/mvp/server.js +0 -2712
  176. package/dist/mvp/serverCard.js +0 -38
  177. package/dist/mvp/storedSize.js +0 -139
  178. package/dist/mvp/telemetry.js +0 -474
  179. package/dist/net/poolFetch.js +0 -174
  180. package/dist/recall/actionRecall.js +0 -282
  181. package/dist/recall/autoRecall.js +0 -447
  182. package/dist/recall/searchRecall.js +0 -189
  183. package/dist/retrieval/adviceLines.js +0 -195
  184. package/dist/retrieval/adviceQuestion.js +0 -44
  185. package/dist/retrieval/conversationShape.js +0 -44
  186. package/dist/retrieval/dailyEntryTime.js +0 -55
  187. package/dist/retrieval/entityLookup.js +0 -162
  188. package/dist/retrieval/factsFirst.js +0 -188
  189. package/dist/retrieval/keyword.js +0 -84
  190. package/dist/retrieval/ledgerEventTime.js +0 -51
  191. package/dist/retrieval/ledgerLiveness.js +0 -83
  192. package/dist/retrieval/ledgerPresentation.js +0 -161
  193. package/dist/retrieval/noteIdentity.js +0 -57
  194. package/dist/retrieval/orchestrator.js +0 -1224
  195. package/dist/retrieval/plainWording.js +0 -236
  196. package/dist/retrieval/queryHelpers.js +0 -142
  197. package/dist/retrieval/questionSpan.js +0 -475
  198. package/dist/retrieval/rankingTrace.js +0 -184
  199. package/dist/retrieval/readerEvents.js +0 -690
  200. package/dist/retrieval/readerLayout.js +0 -422
  201. package/dist/retrieval/relativeTimeHints.js +0 -113
  202. package/dist/retrieval/semantic.js +0 -67
  203. package/dist/router/routerCache.js +0 -106
  204. package/dist/router/sessionRouter.js +0 -726
  205. package/dist/sharing/cli.js +0 -181
  206. package/dist/sharing/examples.js +0 -136
  207. package/dist/sharing/fields.js +0 -225
  208. package/dist/sharing/loop.js +0 -80
  209. package/dist/sharing/project.js +0 -327
  210. package/dist/sharing/send.js +0 -466
  211. package/dist/sharing/state.js +0 -222
  212. package/dist/sharing/wording.js +0 -48
  213. package/dist/toolRefusal.js +0 -120
  214. package/dist/watcher/watcher.js +0 -77
  215. /package/dist/{indexer/o200k.json → o200k.json} +0 -0
@@ -1,242 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.compileCacheOverlap = compileCacheOverlap;
7
- exports.releaseSeedDir = releaseSeedDir;
8
- exports.enableWorkspaceCompileCache = enableWorkspaceCompileCache;
9
- const node_fs_1 = __importDefault(require("node:fs"));
10
- const node_module_1 = __importDefault(require("node:module"));
11
- const node_path_1 = __importDefault(require("node:path"));
12
- const log_1 = require("./log");
13
- const log = (0, log_1.createLogger)('engine');
14
- /**
15
- * This workspace's own Node compile cache, enabled before anything heavy loads.
16
- *
17
- * WHY IT IS HERE AND NOT IN cli.ts: cli.ts's own imports are resolved before any
18
- * statement in it runs, so a call there would enable the cache AFTER the modules
19
- * that dominate a cold start had already been compiled. This module is imported
20
- * first for its side effect, and nothing heavy is imported above it.
21
- *
22
- * WHY IT IS PER WORKSPACE: the cache is a write. Two workspaces sharing one
23
- * directory would be one workspace's engine creating files another workspace's
24
- * engine owns, which on a host where each workspace runs as its own OS account is
25
- * a cross-tenant write channel. The directory therefore comes from
26
- * MVP_COMPILE_CACHE_DIR, which provision-renor-tenant.sh derives per workspace
27
- * (`/var/lib/renor/<slug>/cache/compile`) rather than from a shared value. With the
28
- * variable unset there is NO cache: nothing is derived from MVP_MEMORY_DIR.
29
- *
30
- * WHY IT IS NEVER IN A DATA TREE: a cache directory that overlaps the memory,
31
- * history or auth trees is neither created nor enabled here (Node writes its
32
- * entries at exit, so enabling first would leave them behind even though
33
- * loadMvpConfig then refuses the start), because those trees are indexed,
34
- * exported, or hold client secrets.
35
- *
36
- * WHY A FAILURE IS NOT FATAL: this is a speed optimisation, not a correctness
37
- * input. Node's own contract for enableCompileCache is to report rather than
38
- * throw, and the engine must start on a read-only or unwritable cache dir, on a
39
- * Node build without compile-cache support, and with NODE_DISABLE_COMPILE_CACHE=1.
40
- * A refusal is reported once, on stderr, and startup continues — measurably
41
- * slower on some hosts, never wrong.
42
- */
43
- /** Reported once per process, and only when the cache was not enabled. */
44
- let reported = false;
45
- /**
46
- * Why `dir` may not be a compile cache, or null when it may.
47
- *
48
- * ONE implementation, used twice: here, BEFORE the directory is created and the cache enabled
49
- * (a refused start must leave nothing behind in a data tree: Node writes its entries at process
50
- * exit, including the exit after a refusal), and by loadMvpConfig, which turns it into the
51
- * startup refusal. Dependency-free on purpose: this module runs before anything heavy loads.
52
- */
53
- function compileCacheOverlap(dir, trees) {
54
- const inside = (a, b) => a !== b && b.startsWith(a + node_path_1.default.sep);
55
- const overlapsEither = (a, b) => a === b || inside(a, b) || inside(b, a);
56
- const labelled = [
57
- ['the fact memory directory (MVP_MEMORY_DIR)', trees.memoryDir],
58
- ['the promoted history directory (MVP_HISTORY_DIR)', trees.historyDir],
59
- ['the OAuth client registry (MVP_AUTH_STATE_PATH)', trees.authStatePath],
60
- ];
61
- for (const [label, tree] of labelled) {
62
- if (tree && overlapsEither(dir, tree)) {
63
- return `MVP_COMPILE_CACHE_DIR (${dir}) must not be equal to, contain, or sit inside ${label}. `
64
- + 'It is a rebuildable cache of compiled code, not user data, and a cache inside a data tree '
65
- + 'would be indexed, exported, or shipped with the workspace.';
66
- }
67
- }
68
- return null;
69
- }
70
- function resolvedEnvPath(name) {
71
- const raw = (process.env[name] ?? '').trim();
72
- return raw === '' ? null : node_path_1.default.resolve(raw);
73
- }
74
- /**
75
- * Why an EXISTING cache directory may not be used, or null. A cache is loaded as code, so it
76
- * must be a real directory (not a symlink) that only this process's user can write: a
77
- * group- or world-writable one lets another account plant what this engine compiles from.
78
- */
79
- function unsafeExistingDir(dir) {
80
- let st;
81
- try {
82
- st = node_fs_1.default.lstatSync(dir);
83
- }
84
- catch (err) {
85
- return `cannot inspect ${dir} (${err.code ?? 'error'})`;
86
- }
87
- if (st.isSymbolicLink())
88
- return `${dir} is a symlink`;
89
- if (!st.isDirectory())
90
- return `${dir} is not a directory`;
91
- if ((st.mode & 0o022) !== 0) {
92
- return `${dir} is writable by group or others (mode ${(st.mode & 0o777).toString(8)})`;
93
- }
94
- if (typeof process.geteuid === 'function' && st.uid !== process.geteuid()) {
95
- return `${dir} is owned by another user (uid ${st.uid})`;
96
- }
97
- return null;
98
- }
99
- function declined(reason) {
100
- if (!reported) {
101
- reported = true;
102
- log.warn('compile_cache_off', { reason, detail: 'the engine starts normally without it' });
103
- }
104
- return { enabled: false, directory: null, reason, seeded: 0 };
105
- }
106
- /**
107
- * The release's compile-cache seed, copied into this workspace's own (empty) cache.
108
- *
109
- * WHY: Node keys a cache entry by the file's path, so every release path starts a workspace's cache empty
110
- * (provision-renor-tenant.sh empties it when the pin moves), and the first wake after each release compiled the whole
111
- * module graph again: about 400 ms of CPU on the harness's small workspace, which a hosted unit's CPUQuota stretches to
112
- * about twice that in wall time. deploy-remote.sh runs `dist/mvp/compileSeed.js` once per release, at the release's final
113
- * path, into `<release>/.compile-seed`; the engine copies those entries into the cache it owns when that cache is empty.
114
- *
115
- * WHY A COPY AND NOT A SHARED CACHE: the per-workspace cache above is one account's own write. Pointing every workspace at
116
- * the release's directory would make it a shared one (or a read of one whose owner is another account). The copy keeps the
117
- * invariant: the engine only ever loads code from a directory it owns, which only it can write, and that the seed
118
- * filled before the first start.
119
- *
120
- * WHAT IS TRUSTED: only a seed directory that root (or this very account) owns and no group or other can write, holding
121
- * regular files, in the sub-directory Node names for this Node build and V8 flags (it ends in the owner's uid; the build
122
- * account's uid is not this workspace's, so the name is compared without it). Anything else is not read. A failure is
123
- * never fatal: the cache fills as it always did.
124
- */
125
- const SEED_ENTRY = /^[0-9a-f]{8}$/;
126
- const MAX_SEED_ENTRIES = 4096;
127
- const MAX_SEED_ENTRY_BYTES = 32 * 1024 * 1024;
128
- /** The directory deploy-remote.sh seeds for the release this code runs from, unless MVP_COMPILE_SEED_DIR names another. */
129
- function releaseSeedDir() {
130
- const explicit = resolvedEnvPath('MVP_COMPILE_SEED_DIR');
131
- return explicit ?? node_path_1.default.resolve(__dirname, '..', '..', '.compile-seed');
132
- }
133
- function trustedSeedDir(dir) {
134
- let st;
135
- try {
136
- st = node_fs_1.default.lstatSync(dir);
137
- }
138
- catch {
139
- return false;
140
- }
141
- if (!st.isDirectory() || st.isSymbolicLink() || (st.mode & 0o022) !== 0)
142
- return false;
143
- const me = typeof process.geteuid === 'function' ? process.geteuid() : st.uid;
144
- return st.uid === 0 || st.uid === me;
145
- }
146
- /** `v22.23.2-x64-9de703df-1000` -> `v22.23.2-x64-9de703df`: Node's cache sub-directory without the uid it ends in. */
147
- function withoutUid(name) {
148
- const m = /^(v[0-9][\w.]*-[\w]+-[0-9a-f]+)-\d+$/.exec(name);
149
- return m ? m[1] : null;
150
- }
151
- /**
152
- * Copy the seed into `target` (the versioned directory Node is using) when it holds no entries. Returns how many entries
153
- * were copied. An entry that is half written (a start killed during the copy) is rejected by Node's own checksum and compiled again.
154
- */
155
- function seedFromRelease(target) {
156
- try {
157
- const seedRoot = releaseSeedDir();
158
- if (!trustedSeedDir(seedRoot))
159
- return 0;
160
- const want = withoutUid(node_path_1.default.basename(target));
161
- if (want === null)
162
- return 0;
163
- const sub = node_fs_1.default.readdirSync(seedRoot).find(name => withoutUid(name) === want);
164
- if (sub === undefined)
165
- return 0;
166
- const from = node_path_1.default.join(seedRoot, sub);
167
- if (!trustedSeedDir(from))
168
- return 0;
169
- node_fs_1.default.mkdirSync(target, { recursive: true, mode: 0o700 });
170
- if (node_fs_1.default.readdirSync(target).length > 0)
171
- return 0; // this workspace already has its own entries: never mix
172
- let copied = 0;
173
- for (const entry of node_fs_1.default.readdirSync(from, { withFileTypes: true })) {
174
- if (!entry.isFile() || !SEED_ENTRY.test(entry.name))
175
- continue;
176
- if (copied >= MAX_SEED_ENTRIES)
177
- break;
178
- const src = node_path_1.default.join(from, entry.name);
179
- if (node_fs_1.default.statSync(src).size > MAX_SEED_ENTRY_BYTES)
180
- continue;
181
- // Straight to the final name: Node checks each entry's size and checksum before it uses one and compiles again when
182
- // they do not match, so an entry a killed start left half written costs a compile, never a wrong result. A temporary
183
- // name and a rename would add 30 ms of syscalls for 588 entries.
184
- node_fs_1.default.copyFileSync(src, node_path_1.default.join(target, entry.name), node_fs_1.default.constants.COPYFILE_EXCL);
185
- copied++;
186
- }
187
- return copied;
188
- }
189
- catch {
190
- return 0; // a speed optimisation: whatever went wrong, the engine starts and fills its cache as it always did
191
- }
192
- }
193
- /**
194
- * Enable the cache and report what Node decided. Safe to call more than once;
195
- * Node returns ALREADY_ENABLED and the first directory wins.
196
- *
197
- * Only an EXPLICIT MVP_COMPILE_CACHE_DIR enables a cache. There is deliberately no derived
198
- * default: a directory worked out from MVP_MEMORY_DIR can land in a shared place (a memory
199
- * directory of /tmp/x derives /tmp/cache/compile), and a shared compile cache is a cross-user
200
- * write. The provisioner names a per-workspace directory in every env file it writes.
201
- */
202
- function enableWorkspaceCompileCache() {
203
- const explicit = resolvedEnvPath('MVP_COMPILE_CACHE_DIR');
204
- if (explicit === null) {
205
- return { enabled: false, directory: null, reason: 'MVP_COMPILE_CACHE_DIR is not set', seeded: 0 };
206
- }
207
- // BEFORE mkdir and before enabling: a directory inside a data tree is skipped, never created.
208
- // loadMvpConfig still refuses the start with the full message afterwards.
209
- const overlap = compileCacheOverlap(explicit, {
210
- memoryDir: resolvedEnvPath('MVP_MEMORY_DIR'),
211
- historyDir: resolvedEnvPath('MVP_HISTORY_DIR'),
212
- authStatePath: resolvedEnvPath('MVP_AUTH_STATE_PATH'),
213
- });
214
- if (overlap !== null) {
215
- return { enabled: false, directory: null, reason: 'MVP_COMPILE_CACHE_DIR overlaps a data tree; no cache written', seeded: 0 };
216
- }
217
- if (typeof node_module_1.default.enableCompileCache !== 'function') {
218
- return declined('this Node build has no module.enableCompileCache');
219
- }
220
- // Create it here rather than trusting it to exist: the engine is the thing that writes into
221
- // it, and a 0700 directory it owns is the narrowest grant that lets it. mkdir with recursive
222
- // ignores EEXIST, so this is idempotent. A failure is not fatal: the checks below report it.
223
- try {
224
- node_fs_1.default.mkdirSync(explicit, { recursive: true, mode: 0o700 });
225
- }
226
- catch {
227
- // Reported through the checks below; nothing to add here.
228
- }
229
- const unsafe = unsafeExistingDir(explicit);
230
- if (unsafe !== null)
231
- return declined(unsafe);
232
- const result = node_module_1.default.enableCompileCache(explicit);
233
- const accepted = result.status === node_module_1.default.constants.compileCacheStatus.ENABLED
234
- || result.status === node_module_1.default.constants.compileCacheStatus.ALREADY_ENABLED;
235
- if (!accepted) {
236
- return declined(result.status === node_module_1.default.constants.compileCacheStatus.DISABLED
237
- ? 'disabled by NODE_DISABLE_COMPILE_CACHE'
238
- : result.message ?? `status ${result.status}`);
239
- }
240
- const directory = result.directory ?? explicit;
241
- return { enabled: true, directory, reason: null, seeded: seedFromRelease(node_module_1.default.getCompileCacheDir() ?? directory) };
242
- }
@@ -1,33 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- // Fills a compile-cache directory for THIS release, for deploy-remote.sh to run once at the release's final path:
7
- //
8
- // MVP_COMPILE_CACHE_DIR=<release>/.compile-seed node <release>/dist/mvp/compileSeed.js
9
- //
10
- // It does what cli.ts does before it serves: enables the cache first, then loads the modules the engine loads at start (the
11
- // config, the server and everything under it, telemetry, the PostHog glue), and exits 0, which is when Node writes its entries.
12
- // It starts no server, reads no workspace and needs no environment beyond the cache directory. The engine copies the result into
13
- // each workspace's own cache on its first start of the release (compileCache.ts, seedFromRelease).
14
- const compileCache_1 = require("./compileCache");
15
- const node_path_1 = __importDefault(require("node:path"));
16
- const log_1 = require("./log");
17
- const log = (0, log_1.createLogger)('engine');
18
- const report = (0, compileCache_1.enableWorkspaceCompileCache)();
19
- try {
20
- if (!report.enabled) {
21
- log.warn('compile_seed_skipped', { reason: report.reason });
22
- process.exit(2);
23
- }
24
- // Plain requires, after the cache is on, for the same reason cli.ts enables it first: these are the heavy modules.
25
- for (const module of ['./config', './server', './telemetry', './posthogMcp'])
26
- require(module);
27
- log.info('compile_seed_loaded', { directory: report.directory ? node_path_1.default.basename(report.directory) : null });
28
- process.exit(0);
29
- }
30
- catch (err) {
31
- log.error('compile_seed_failed', {}, err);
32
- process.exit(1);
33
- }
@@ -1,292 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.DEFAULT_LEDGER_REL = void 0;
7
- exports.loadMvpConfig = loadMvpConfig;
8
- const path_1 = __importDefault(require("path"));
9
- const settings_1 = require("../learning/settings");
10
- const state_1 = require("../sharing/state");
11
- const compileCache_1 = require("./compileCache");
12
- exports.DEFAULT_LEDGER_REL = 'System/Memory Events Ledger.md';
13
- /** Values printed in the documentation (and the commonest guesses): anyone who has read the README can sign in with them. */
14
- const KNOWN_WEAK_OWNER_PASSWORDS = new Set([
15
- 'replace-this-password', 'choose-a-long-secret', '<owner-secret>', 'owner-secret', 'your-password-here',
16
- 'password', 'password1', 'password123', '12345678', '123456789', 'qwertyui', 'qwerty123', 'changeme', 'change-me', 'letmein1',
17
- ]);
18
- function weakOwnerPasswordReason(password) {
19
- const lower = password.toLowerCase();
20
- if (KNOWN_WEAK_OWNER_PASSWORDS.has(lower))
21
- return 'it is an example value from the documentation or a very common password';
22
- if (new Set(lower).size === 1)
23
- return 'it is one character repeated';
24
- return null;
25
- }
26
- function requiredEnv(name, hint) {
27
- const value = process.env[name];
28
- if (!value || value.trim() === '') {
29
- throw new Error(`Missing required configuration ${name}: ${hint}`);
30
- }
31
- return value.trim();
32
- }
33
- /**
34
- * Where this workspace keeps its Node compile cache.
35
- *
36
- * Three properties, each a correctness property rather than taste:
37
- *
38
- * - INSIDE this workspace's own state tree, named explicitly: provision-renor-tenant.sh writes
39
- * `/var/lib/renor/<slug>/cache/compile` into every env file, and that whole tree is the unit's
40
- * only ReadWritePaths entry. There is NO derived default (null when unset): a path worked out
41
- * from the memory directory can land in a shared place such as /tmp/cache/compile.
42
- * - NEVER inside a data tree. The memory directory is indexed and exported, the history directory
43
- * is promoted transcripts, and the auth path holds client secrets; Node's compiled-code blobs
44
- * belong in none of them. Overlap in EITHER direction throws.
45
- * - NEVER shared. Overlap is checked against THIS workspace's trees, but a path pointing into a
46
- * sibling workspace is not detectable from inside this process — so the provisioner derives
47
- * the path per workspace instead of reading a shared configuration value, and refuses an env
48
- * file that names anything else.
49
- */
50
- function resolveCompileCacheDir(memoryDir, historyDir, authStatePath) {
51
- const raw = (process.env.MVP_COMPILE_CACHE_DIR ?? '').trim();
52
- if (raw === '')
53
- return null;
54
- const dir = path_1.default.resolve(raw);
55
- const refusal = (0, compileCache_1.compileCacheOverlap)(dir, { memoryDir, historyDir, authStatePath });
56
- if (refusal !== null)
57
- throw new Error(refusal);
58
- return dir;
59
- }
60
- function loadMvpConfig() {
61
- const memoryDir = requiredEnv('MVP_MEMORY_DIR', 'dedicated owner memory directory for this product (create a NEW folder, e.g. ~/memory-company-data)');
62
- const port = Number(process.env.MVP_PORT ?? 3471);
63
- if (!Number.isInteger(port) || port <= 0 || port > 65535) {
64
- throw new Error('MVP_PORT must be an integer between 1 and 65535');
65
- }
66
- const baseUrlRaw = requiredEnv('MVP_BASE_URL', 'the externally reachable base URL of this service, e.g. http://localhost:3471 for local tests or your public https URL for ChatGPT');
67
- let baseUrl;
68
- try {
69
- baseUrl = new URL(baseUrlRaw);
70
- }
71
- catch {
72
- throw new Error(`MVP_BASE_URL is not a valid URL: ${baseUrlRaw}`);
73
- }
74
- if (baseUrl.hash || baseUrl.search) {
75
- throw new Error('MVP_BASE_URL must not contain a query or fragment');
76
- }
77
- // Owner identity: the ONLY account that can complete authorization.
78
- const ownerEmail = requiredEnv('MVP_OWNER_EMAIL', 'the single owner login email; no other identity may authorize').toLowerCase();
79
- const ownerPassword = requiredEnv('MVP_OWNER_PASSWORD', 'the owner login secret (env-only; never commit it to Git or write it into the memory directory)');
80
- if (ownerPassword.length < 8) {
81
- throw new Error('MVP_OWNER_PASSWORD must be at least 8 characters');
82
- }
83
- // The README's example is public: anyone who can reach the login page signs in with it, so refuse to start on it.
84
- const weakReason = weakOwnerPasswordReason(ownerPassword);
85
- if (weakReason) {
86
- throw new Error(`MVP_OWNER_PASSWORD is too weak: ${weakReason}. Choose your own secret, for example: export MVP_OWNER_PASSWORD="$(openssl rand -base64 18)"`);
87
- }
88
- const accessTokenTtlSeconds = Number(process.env.MVP_ACCESS_TOKEN_TTL_SECONDS ?? 3600);
89
- if (!Number.isFinite(accessTokenTtlSeconds) || accessTokenTtlSeconds < 60) {
90
- throw new Error('MVP_ACCESS_TOKEN_TTL_SECONDS must be at least 60');
91
- }
92
- // AUTH-B1: exact callback-URI allowlist for DCR. Deny by default: unset or
93
- // empty means NO client may register until the owner names exact callbacks.
94
- const allowedCallbackUris = (process.env.MVP_ALLOWED_CALLBACK_URIS ?? '')
95
- .split(',').map(s => s.trim()).filter(Boolean);
96
- for (const uri of allowedCallbackUris) {
97
- try {
98
- new URL(uri);
99
- }
100
- catch {
101
- throw new Error(`MVP_ALLOWED_CALLBACK_URIS contains an invalid URL: ${uri}`);
102
- }
103
- if (/[\s]/.test(uri)) {
104
- throw new Error('MVP_ALLOWED_CALLBACK_URIS entries must be exact URIs without whitespace');
105
- }
106
- }
107
- // AUTH-B3: bounded failed-login limiter knobs (operator-tunable, sane defaults).
108
- const loginMaxFailures = Number(process.env.MVP_LOGIN_MAX_FAILURES ?? 5);
109
- if (!Number.isInteger(loginMaxFailures) || loginMaxFailures < 1 || loginMaxFailures > 100) {
110
- throw new Error('MVP_LOGIN_MAX_FAILURES must be an integer between 1 and 100');
111
- }
112
- const loginLockoutMs = Number(process.env.MVP_LOGIN_LOCKOUT_MS ?? 30_000);
113
- if (!Number.isInteger(loginLockoutMs) || loginLockoutMs < 1 || loginLockoutMs > 3_600_000) {
114
- throw new Error('MVP_LOGIN_LOCKOUT_MS must be an integer between 1 and 3600000');
115
- }
116
- const memoryDirResolved = path_1.default.resolve(memoryDir);
117
- // CLIENT-PERSISTENCE: explicit private OAuth client-registry path. The
118
- // registry holds registered client metadata (incl. client secrets), so it
119
- // must live outside the memory and history trees in both directions.
120
- const authStatePathRaw = requiredEnv('MVP_AUTH_STATE_PATH', 'private path of the persistent OAuth client registry, e.g. /path/to/private-runtime/auth/clients.json '
121
- + '(file inside a NEW owner-only 0700 directory OUTSIDE the memory/history/export directories; never in Git)');
122
- const authStatePath = path_1.default.resolve(authStatePathRaw);
123
- // SSE-CHATGPT: transport mode. Default stays JSON (stateless) — the exact
124
- // behavior every existing test pins. 'false'/'0' opts into SSE responses.
125
- const gatewaySecret = (process.env.MVP_GATEWAY_SECRET ?? '').trim();
126
- const mcpJsonRaw = (process.env.MVP_MCP_JSON ?? 'true').trim().toLowerCase();
127
- if (mcpJsonRaw !== 'true' && mcpJsonRaw !== 'false' && mcpJsonRaw !== '1' && mcpJsonRaw !== '0') {
128
- throw new Error('MVP_MCP_JSON must be true or false');
129
- }
130
- const mcpJsonResponse = mcpJsonRaw === 'true' || mcpJsonRaw === '1';
131
- const mcpMaxSessions = Number(process.env.MVP_MCP_MAX_SESSIONS ?? 100);
132
- // Each retained session holds a full MCP server (about 0.3 MB measured), so the ceiling is 1,000: 10,000 would
133
- // extrapolate to roughly 3 GB of heap, past Node's default limit.
134
- if (!Number.isInteger(mcpMaxSessions) || mcpMaxSessions < 1) {
135
- throw new Error('MVP_MCP_MAX_SESSIONS must be an integer of at least 1');
136
- }
137
- if (mcpMaxSessions > 1_000) {
138
- throw new Error(`MVP_MCP_MAX_SESSIONS is ${mcpMaxSessions}; the largest accepted value is 1000 (each session costs about 0.3 MB of heap)`);
139
- }
140
- const mcpSessionTtlMs = Number(process.env.MVP_MCP_SESSION_TTL_MS ?? 3_600_000);
141
- if (!Number.isInteger(mcpSessionTtlMs) || mcpSessionTtlMs < 1_000 || mcpSessionTtlMs > 86_400_000) {
142
- throw new Error('MVP_MCP_SESSION_TTL_MS must be an integer between 1000 and 86400000');
143
- }
144
- const embeddingRaw = (process.env.MVP_EMBEDDING_PROVIDER ?? process.env.EMBEDDING_PROVIDER ?? 'none').trim().toLowerCase();
145
- if (embeddingRaw !== 'none' && embeddingRaw !== 'local' && embeddingRaw !== 'openai' && embeddingRaw !== 'vertex') {
146
- throw new Error('MVP_EMBEDDING_PROVIDER must be none, local, openai, or vertex');
147
- }
148
- const embeddingProvider = embeddingRaw;
149
- let embeddingApiKey;
150
- let embeddingModel;
151
- let embeddingBaseURL;
152
- let embeddingDims;
153
- let vertexKeyFile;
154
- let vertexProject;
155
- let vertexLocation;
156
- if (embeddingProvider === 'openai') {
157
- const key = (process.env.MVP_EMBEDDING_API_KEY ?? process.env.OPENAI_API_KEY ?? '').trim();
158
- if (!key)
159
- throw new Error('MVP_EMBEDDING_API_KEY (or OPENAI_API_KEY) is required when MVP_EMBEDDING_PROVIDER=openai');
160
- embeddingApiKey = key;
161
- embeddingModel = (process.env.MVP_EMBEDDING_MODEL ?? process.env.EMBEDDING_MODEL ?? 'voyage-4-large').trim();
162
- embeddingBaseURL = (process.env.MVP_EMBEDDING_BASE_URL ?? process.env.EMBEDDING_BASE_URL ?? 'https://api.voyageai.com/v1').trim();
163
- const dimsRaw = process.env.MVP_EMBEDDING_DIMS ?? process.env.EMBEDDING_DIMS ?? '1024';
164
- embeddingDims = Number(dimsRaw);
165
- if (!Number.isInteger(embeddingDims) || embeddingDims < 8 || embeddingDims > 8192) {
166
- throw new Error('MVP_EMBEDDING_DIMS must be an integer between 8 and 8192');
167
- }
168
- }
169
- else if (embeddingProvider === 'vertex') {
170
- const keyFile = (process.env.MVP_VERTEX_KEY_FILE
171
- ?? process.env.GOOGLE_APPLICATION_CREDENTIALS
172
- ?? process.env.RENOR_EVAL_VERTEX_KEY_FILE
173
- ?? '').trim();
174
- if (!keyFile) {
175
- throw new Error('MVP_VERTEX_KEY_FILE (or GOOGLE_APPLICATION_CREDENTIALS) is required when MVP_EMBEDDING_PROVIDER=vertex');
176
- }
177
- vertexKeyFile = path_1.default.resolve(keyFile);
178
- vertexProject = (process.env.MVP_VERTEX_PROJECT
179
- ?? process.env.RENOR_EVAL_VERTEX_PROJECT
180
- ?? '').trim();
181
- if (!/^[a-z0-9-]+$/.test(vertexProject)) {
182
- throw new Error('MVP_VERTEX_PROJECT (or RENOR_EVAL_VERTEX_PROJECT) is required when MVP_EMBEDDING_PROVIDER=vertex');
183
- }
184
- vertexLocation = (process.env.MVP_VERTEX_LOCATION
185
- ?? process.env.RENOR_EVAL_VERTEX_LOCATION
186
- ?? '').trim();
187
- if (!vertexLocation) {
188
- throw new Error('MVP_VERTEX_LOCATION (or RENOR_EVAL_VERTEX_LOCATION) is required when MVP_EMBEDDING_PROVIDER=vertex');
189
- }
190
- if (!/^[a-z0-9-]+$/.test(vertexLocation)) {
191
- throw new Error('MVP_VERTEX_LOCATION must be a valid GCP location like europe-west4');
192
- }
193
- embeddingModel = (process.env.MVP_EMBEDDING_MODEL ?? process.env.EMBEDDING_MODEL ?? process.env.RENOR_EVAL_MODEL ?? 'gemini-embedding-001').trim();
194
- const dimsRaw = process.env.MVP_EMBEDDING_DIMS ?? process.env.EMBEDDING_DIMS ?? process.env.RENOR_EVAL_EMBEDDING_DIMS ?? '768';
195
- embeddingDims = Number(dimsRaw);
196
- if (!Number.isInteger(embeddingDims) || ![768, 1536, 3072].includes(embeddingDims)) {
197
- throw new Error('MVP_EMBEDDING_DIMS for vertex must be 768, 1536, or 3072');
198
- }
199
- }
200
- else if (embeddingProvider === 'local') {
201
- embeddingModel = (process.env.MVP_EMBEDDING_MODEL ?? process.env.EMBEDDING_MODEL ?? 'Xenova/multilingual-e5-base').trim();
202
- const dimsRaw = process.env.MVP_EMBEDDING_DIMS ?? process.env.EMBEDDING_DIMS;
203
- if (dimsRaw) {
204
- embeddingDims = Number(dimsRaw);
205
- if (!Number.isInteger(embeddingDims) || embeddingDims < 8 || embeddingDims > 8192) {
206
- throw new Error('MVP_EMBEDDING_DIMS must be an integer between 8 and 8192');
207
- }
208
- }
209
- }
210
- let explicitDbPath = null;
211
- const rawDb = process.env.MVP_DB_PATH;
212
- if (rawDb && rawDb.trim() !== '') {
213
- explicitDbPath = path_1.default.resolve(rawDb.trim());
214
- if (explicitDbPath.endsWith('.md')) {
215
- throw new Error('MVP_DB_PATH must not be a Markdown file');
216
- }
217
- }
218
- // On-demand (RENOR_ON_DEMAND): the one switch, off unless explicitly on. Only enable it
219
- // for a workspace whose clients reach it through the gateway, with the gateway's own
220
- // RENOR_ON_DEMAND on: nothing else starts a sleeping engine.
221
- const onDemandRaw = (process.env.RENOR_ON_DEMAND ?? '').trim().toLowerCase();
222
- if (!['', '0', 'false', '1', 'true'].includes(onDemandRaw)) {
223
- throw new Error('RENOR_ON_DEMAND must be 1/true or 0/false');
224
- }
225
- let idleExitMs = null;
226
- if (onDemandRaw === '1' || onDemandRaw === 'true') {
227
- const idleSeconds = Number(process.env.RENOR_ON_DEMAND_IDLE_SECONDS ?? 600);
228
- if (!Number.isInteger(idleSeconds) || idleSeconds < 1 || idleSeconds > 86_400) {
229
- throw new Error('RENOR_ON_DEMAND_IDLE_SECONDS must be an integer between 1 and 86400');
230
- }
231
- idleExitMs = idleSeconds * 1000;
232
- }
233
- const overlaps = (a, b) => a === b || a.startsWith(b + path_1.default.sep);
234
- if (overlaps(authStatePath, memoryDirResolved)) {
235
- throw new Error('MVP_AUTH_STATE_PATH must not be inside the fact memory directory (MVP_MEMORY_DIR)');
236
- }
237
- if (authStatePath.endsWith('.md')) {
238
- throw new Error('MVP_AUTH_STATE_PATH must not be a Markdown file');
239
- }
240
- // Promoted-history directory: optional, explicit, and strictly disjoint
241
- // from the fact memory directory (no overlap in either direction).
242
- let historyDir = null;
243
- const rawHistoryDir = process.env.MVP_HISTORY_DIR;
244
- if (rawHistoryDir && rawHistoryDir.trim() !== '') {
245
- historyDir = path_1.default.resolve(rawHistoryDir.trim());
246
- const inside = (a, b) => a !== b && b.startsWith(a + path_1.default.sep);
247
- if (historyDir === memoryDirResolved
248
- || inside(historyDir, memoryDirResolved)
249
- || inside(memoryDirResolved, historyDir)) {
250
- throw new Error('MVP_HISTORY_DIR must not be equal to or overlap the fact memory directory (MVP_MEMORY_DIR)');
251
- }
252
- if (overlaps(authStatePath, historyDir) || overlaps(historyDir, authStatePath)) {
253
- throw new Error('MVP_AUTH_STATE_PATH must not be equal to or overlap the promoted history directory (MVP_HISTORY_DIR)');
254
- }
255
- }
256
- // This workspace's own compile cache. A wrong location is REFUSED, not repaired: silently
257
- // relocating it would hide the misconfiguration that, in a shared directory, is precisely the
258
- // cross-tenant write this exists to prevent.
259
- const compileCacheDir = resolveCompileCacheDir(memoryDirResolved, historyDir, authStatePath);
260
- return {
261
- memoryDir: memoryDirResolved,
262
- dbPath: explicitDbPath ?? path_1.default.join(path_1.default.resolve(memoryDir), '.memory-index', 'index.db'),
263
- ledgerRelPath: process.env.MVP_LEDGER_REL ?? exports.DEFAULT_LEDGER_REL,
264
- baseUrl,
265
- port,
266
- ownerEmail,
267
- ownerPassword,
268
- accessTokenTtlSeconds,
269
- gatewaySecret,
270
- allowedCallbackUris,
271
- loginMaxFailures,
272
- loginLockoutMs,
273
- historyDir,
274
- authStatePath,
275
- mcpJsonResponse,
276
- mcpMaxSessions,
277
- mcpSessionTtlMs,
278
- embeddingProvider,
279
- embeddingApiKey,
280
- embeddingModel,
281
- embeddingBaseURL,
282
- embeddingDims,
283
- vertexKeyFile,
284
- vertexProject,
285
- vertexLocation,
286
- explicitDbPath,
287
- idleExitMs,
288
- compileCacheDir,
289
- learning: (0, settings_1.learningSettings)(memoryDirResolved),
290
- sharingDir: (0, state_1.sharingDirFor)(memoryDirResolved),
291
- };
292
- }
@@ -1,80 +0,0 @@
1
- "use strict";
2
- /**
3
- * Which Renor an agent is talking to, said once and whenever something is wrong.
4
- *
5
- * Agents could not tell that they were connected to the wrong server, or that a connection had silently dropped:
6
- * absence was silent. So the first tool reply of an MCP session carries one short status block, and so does every
7
- * error a tool returns, with a sentence on how to reconnect. A later successful reply of the same session carries
8
- * nothing, so the status costs a few dozen tokens once per session, not a line on every reply.
9
- *
10
- * The status is an extra trailing text block on the reply. The block a tool always returned is untouched, so
11
- * nothing that reads a reply by its first block changes.
12
- *
13
- * It is on only for a hosted workspace (the provisioner writes MVP_INSTANCE_ID, the workspace's slug, into every
14
- * tenant's environment); an engine run any other way answers as it always did.
15
- */
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.ConnectionAnnouncer = exports.HOSTED_MCP_URL = void 0;
18
- exports.connectionStatusFromEnv = connectionStatusFromEnv;
19
- exports.connectionStatusBlock = connectionStatusBlock;
20
- /** The one public MCP URL every hosted workspace is reached through (the gateway routes it to the workspace). */
21
- exports.HOSTED_MCP_URL = 'https://mcp.renor.cloud/mcp';
22
- /**
23
- * The status of the hosted workspace this process serves, or null when it is not one (no MVP_INSTANCE_ID, or
24
- * RENOR_CONNECTION_STATUS=0, the way to switch it off).
25
- */
26
- function connectionStatusFromEnv(env) {
27
- if ((env.RENOR_CONNECTION_STATUS ?? '').trim() === '0')
28
- return null;
29
- const workspace = (env.MVP_INSTANCE_ID ?? '').trim().toLowerCase();
30
- // The slug shape the control plane issues; anything else is not a hosted workspace's name.
31
- if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(workspace))
32
- return null;
33
- return { workspace, url: exports.HOSTED_MCP_URL };
34
- }
35
- /** What an agent is told on its first reply: where it is, and what to do if that is not where it expected to be. */
36
- function firstSentence(status) {
37
- return `Connected to Renor's hosted workspace "${status.workspace}" at ${status.url}; if that is not the workspace you expect, tell the user.`;
38
- }
39
- /** What an agent is told on an error: where it is, and how to connect again. */
40
- function errorSentence(status) {
41
- return `Renor hosted workspace "${status.workspace}" at ${status.url}. If Renor stops answering or refuses you, reconnect: sign in again through your client's MCP settings for ${status.url}.`;
42
- }
43
- /** The one-line text block: a stable machine-readable field, and one short sentence. */
44
- function connectionStatusBlock(status, kind) {
45
- const message = kind === 'first' ? firstSentence(status) : errorSentence(status);
46
- return {
47
- type: 'text',
48
- text: JSON.stringify({ renor_connection: { hosted: true, workspace: status.workspace, url: status.url }, message }),
49
- };
50
- }
51
- /**
52
- * Decides, per MCP session, which replies carry the status. One of these per session server: the first tool reply
53
- * takes the announcement (a session that has none to announce, because it has no session to begin, never does), and
54
- * an error always carries it.
55
- */
56
- class ConnectionAnnouncer {
57
- status;
58
- announced;
59
- constructor(status, announceFirst) {
60
- this.status = status;
61
- this.announced = !announceFirst;
62
- }
63
- /** The reply, with the status block appended where it belongs, or the reply itself where it does not. */
64
- decorate(result, first) {
65
- if (this.status === null || !Array.isArray(result?.content))
66
- return result;
67
- const error = result.isError === true;
68
- if (!error && !first)
69
- return result;
70
- return { ...result, content: [...result.content, connectionStatusBlock(this.status, error ? 'error' : 'first')] };
71
- }
72
- /** Called when a tool call starts: true for exactly one call in the session, the first. */
73
- takeFirst() {
74
- if (this.announced)
75
- return false;
76
- this.announced = true;
77
- return true;
78
- }
79
- }
80
- exports.ConnectionAnnouncer = ConnectionAnnouncer;