tokensafe-backend-node 0.0.0-stage → 0.2.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.
@@ -0,0 +1,1181 @@
1
+ // src/errors.ts
2
+ var ERROR_CODES = {
3
+ CONFLICT_DETECTED: -32001,
4
+ SYNTAX_ERROR: -32002,
5
+ SECURITY_VIOLATION: -32003,
6
+ TARGET_NOT_FOUND: -32004,
7
+ ACTION_NOT_FOUND: -32005,
8
+ UNSUPPORTED_CAPABILITY: -32006,
9
+ PERMISSION_DENIED: -32007,
10
+ RUNTIME_UNAVAILABLE: -32008,
11
+ RESOURCE_NOT_FOUND: -32009,
12
+ VALIDATION_FAILED: -32011,
13
+ PARSE_ERROR: -32700,
14
+ INVALID_REQUEST: -32600,
15
+ METHOD_NOT_FOUND: -32601,
16
+ INVALID_PARAMS: -32602,
17
+ INTERNAL_ERROR: -32603
18
+ };
19
+ var OumvError = class extends Error {
20
+ code;
21
+ data;
22
+ constructor(code, message, data) {
23
+ super(message);
24
+ this.name = "OumvError";
25
+ this.code = code;
26
+ this.data = data;
27
+ }
28
+ };
29
+ var conflict = (message, data) => new OumvError(ERROR_CODES.CONFLICT_DETECTED, message, data);
30
+ var syntaxError = (message, data) => new OumvError(ERROR_CODES.SYNTAX_ERROR, message, data);
31
+ var securityViolation = (message, data) => new OumvError(ERROR_CODES.SECURITY_VIOLATION, message, data);
32
+ var targetNotFound = (message) => new OumvError(ERROR_CODES.TARGET_NOT_FOUND, message);
33
+ var permissionDenied = (message) => new OumvError(ERROR_CODES.PERMISSION_DENIED, message);
34
+ var resourceNotFound = (message) => new OumvError(ERROR_CODES.RESOURCE_NOT_FOUND, message);
35
+ var validationFailed = (message, data) => new OumvError(ERROR_CODES.VALIDATION_FAILED, message, data);
36
+ var invalidParams = (message) => new OumvError(ERROR_CODES.INVALID_PARAMS, message);
37
+ var unsupported = (message) => new OumvError(ERROR_CODES.UNSUPPORTED_CAPABILITY, message);
38
+
39
+ // src/paths.ts
40
+ import fs from "fs";
41
+ import path from "path";
42
+ var SENSITIVE = /(^|[\\/])(\.env(\..*)?|id_rsa|id_ed25519|\.npmrc|\.pypirc|credentials\.json|secrets\.ya?ml)$/i;
43
+ function resolveWorkspacePath(inputPath, workspaceDir) {
44
+ let canonicalRoot = path.resolve(workspaceDir);
45
+ try {
46
+ if (fs.existsSync(canonicalRoot)) canonicalRoot = fs.realpathSync(canonicalRoot);
47
+ } catch {
48
+ }
49
+ let resolved = path.isAbsolute(inputPath) ? path.resolve(inputPath) : path.resolve(canonicalRoot, inputPath);
50
+ try {
51
+ if (fs.existsSync(resolved)) resolved = fs.realpathSync(resolved);
52
+ } catch {
53
+ }
54
+ const rootWithSep = canonicalRoot.endsWith(path.sep) ? canonicalRoot : canonicalRoot + path.sep;
55
+ if (resolved !== canonicalRoot && !resolved.startsWith(rootWithSep)) {
56
+ throw securityViolation(`SECURITY_VIOLATION: path traversal blocked: ${JSON.stringify(inputPath)} escapes the workspace`);
57
+ }
58
+ if (SENSITIVE.test(resolved)) {
59
+ throw securityViolation(`SECURITY_VIOLATION: access to a credential file is blocked: ${JSON.stringify(inputPath)}`);
60
+ }
61
+ return resolved;
62
+ }
63
+ function splitSourceTarget(target) {
64
+ const [rawPath, symbol] = target.split("#");
65
+ return { path: rawPath.trim(), symbol: symbol?.trim() || void 0 };
66
+ }
67
+
68
+ // src/sessions.ts
69
+ import crypto from "crypto";
70
+ var SessionRegistry = class {
71
+ sessions = /* @__PURE__ */ new Map();
72
+ ttlSeconds;
73
+ constructor(ttlSeconds = 3600) {
74
+ this.ttlSeconds = Math.max(Math.floor(ttlSeconds), 1);
75
+ }
76
+ create() {
77
+ const id = `sess-${crypto.randomBytes(8).toString("hex")}`;
78
+ this.sessions.set(id, Date.now() + this.ttlSeconds * 1e3);
79
+ return id;
80
+ }
81
+ /** Unknown or expired ids are invalid; expiry is enforced on read. */
82
+ validate(id) {
83
+ if (!id) return true;
84
+ const expiresAt = this.sessions.get(id);
85
+ if (expiresAt === void 0) return false;
86
+ if (Date.now() > expiresAt) {
87
+ this.sessions.delete(id);
88
+ return false;
89
+ }
90
+ return true;
91
+ }
92
+ delete(id) {
93
+ if (!id) return false;
94
+ return this.sessions.delete(id);
95
+ }
96
+ count() {
97
+ return this.sessions.size;
98
+ }
99
+ };
100
+
101
+ // src/runtime.ts
102
+ import crypto2 from "crypto";
103
+ import fs2 from "fs";
104
+ import http from "http";
105
+ import path2 from "path";
106
+ import { parse as parseJs } from "@babel/parser";
107
+ var PROTOCOL_VERSION = "1.1.0";
108
+ var OBSERVE_LEVELS = ["L0", "L1", "L2", "L3", "L4"];
109
+ var MAX_TRACES = 128;
110
+ function sha256(content) {
111
+ return "sha256:" + crypto2.createHash("sha256").update(content, "utf-8").digest("hex");
112
+ }
113
+ function intersect(implemented, requested) {
114
+ if (!Array.isArray(requested) || requested.length === 0) return implemented;
115
+ const wanted = new Set(requested.map(String));
116
+ return implemented.filter((item) => wanted.has(item));
117
+ }
118
+ var OumvRuntime = class {
119
+ name;
120
+ version;
121
+ workspaceDir;
122
+ transportPath;
123
+ maxBodyBytes;
124
+ sessions;
125
+ authToken;
126
+ routes = /* @__PURE__ */ new Map();
127
+ traces = [];
128
+ startTime = Date.now();
129
+ enabled;
130
+ transports = ["http"];
131
+ handler;
132
+ dispatchServer;
133
+ dispatchPort = 0;
134
+ constructor(options = {}) {
135
+ this.name = options.name || "tokensafe-node";
136
+ this.version = options.version || "0.2.0";
137
+ this.workspaceDir = path2.resolve(options.workspaceDir || process.cwd());
138
+ this.transportPath = options.transportPath || "/__oumv/rpc";
139
+ this.maxBodyBytes = options.maxBodyBytes ?? 8 * 1024 * 1024;
140
+ this.authToken = options.authToken || "";
141
+ this.sessions = new SessionRegistry(options.sessionTtlSeconds ?? 3600);
142
+ this.handler = options.handler;
143
+ this.enabled = {
144
+ observe: options.capabilities?.observe ?? true,
145
+ understand: options.capabilities?.understand ?? true,
146
+ mutate: options.capabilities?.mutate ?? true,
147
+ verify: options.capabilities?.verify ?? true
148
+ };
149
+ }
150
+ /* ---------------------------------------------------------------- registry */
151
+ registerRoute(method, routePath, handlerName = "handler", middlewares = []) {
152
+ const key = `${method.toUpperCase()} ${routePath}`;
153
+ if (this.routes.has(key)) return;
154
+ this.routes.set(key, {
155
+ method: method.toUpperCase(),
156
+ path: routePath,
157
+ handlerName,
158
+ ...middlewares.length > 0 ? { middlewares } : {}
159
+ });
160
+ }
161
+ listRoutes() {
162
+ return Array.from(this.routes.values());
163
+ }
164
+ /** Records an executed request: the only source of L4/causality evidence. */
165
+ recordTrace(entry) {
166
+ this.traces.push({ ...entry, timestamp: entry.timestamp ?? (/* @__PURE__ */ new Date()).toISOString() });
167
+ if (this.traces.length > MAX_TRACES) this.traces.shift();
168
+ }
169
+ recentTraces() {
170
+ return this.traces.slice();
171
+ }
172
+ setHandler(handler) {
173
+ this.handler = handler;
174
+ }
175
+ setTransports(transports) {
176
+ this.transports = transports;
177
+ }
178
+ /* --------------------------------------------------------------- handshake */
179
+ handshake(params = {}) {
180
+ const capabilities = {
181
+ observe: { levels: [...OBSERVE_LEVELS], formats: ["json"] },
182
+ understand: { causality: true, signalsGraph: false, impactAnalysis: true },
183
+ mutate: { occ: true, syntaxGuard: true },
184
+ verify: { multiMetric: true, surfaceDiff: false }
185
+ };
186
+ if (!this.enabled.understand) {
187
+ capabilities.understand = { causality: false, signalsGraph: false, impactAnalysis: false };
188
+ }
189
+ if (!this.enabled.mutate) capabilities.mutate = { occ: false, syntaxGuard: false };
190
+ if (!this.enabled.verify) capabilities.verify = { multiMetric: false, surfaceDiff: false };
191
+ const requested = params.requestedCapabilities;
192
+ if (requested && typeof requested === "object") {
193
+ capabilities.observe.levels = intersect(capabilities.observe.levels, requested.observe?.levels);
194
+ capabilities.observe.formats = intersect(capabilities.observe.formats, requested.observe?.formats);
195
+ }
196
+ if (!this.enabled.observe) capabilities.observe = { levels: [], formats: [] };
197
+ return {
198
+ protocolVersion: PROTOCOL_VERSION,
199
+ profile: "backend",
200
+ sessionId: this.sessions.create(),
201
+ ttlSeconds: this.sessions.ttlSeconds,
202
+ runtimeInfo: { name: this.name, version: this.version },
203
+ capabilities
204
+ };
205
+ }
206
+ /* ----------------------------------------------------------------- observe */
207
+ observe(params = {}) {
208
+ if (!this.enabled.observe) throw permissionDenied("PERMISSION_DENIED: observe capability is disabled");
209
+ const level = String(params.level || "L0").toUpperCase();
210
+ const format = String(params.format || "json").toLowerCase();
211
+ if (!OBSERVE_LEVELS.includes(level)) throw invalidParams(`INVALID_PARAMS: unknown observe level ${level}`);
212
+ if (format !== "json") throw unsupported(`UNSUPPORTED_CAPABILITY: format ${format} is not implemented`);
213
+ switch (level) {
214
+ case "L0": {
215
+ const memory = process.memoryUsage().rss / (1024 * 1024);
216
+ return {
217
+ level,
218
+ format: "json",
219
+ data: {
220
+ status: "HEALTHY",
221
+ uptimeSeconds: Math.floor((Date.now() - this.startTime) / 1e3),
222
+ activeRoutes: this.routes.size,
223
+ errorCount1m: 0,
224
+ memoryAllocMB: Math.round(memory)
225
+ },
226
+ tokenEstimate: 30
227
+ };
228
+ }
229
+ case "L1":
230
+ return {
231
+ level,
232
+ format: "json",
233
+ data: { endpoints: this.listRoutes() },
234
+ tokenEstimate: 30 + this.routes.size * 15
235
+ };
236
+ case "L2": {
237
+ const target = String(params.target || "").trim();
238
+ if (!target) throw invalidParams("INVALID_PARAMS: target is required for L2");
239
+ const route = this.findRoute(target);
240
+ if (!route) throw targetNotFound(`TARGET_NOT_FOUND: no route matches ${JSON.stringify(target)}`);
241
+ return {
242
+ level,
243
+ format: "json",
244
+ data: {
245
+ target,
246
+ method: route.method,
247
+ path: route.path,
248
+ handlerName: route.handlerName,
249
+ middlewares: route.middlewares ?? [],
250
+ // A mounted Express/Fastify router exposes handler names, not DTOs:
251
+ // saying so is honest, inventing schemas is not.
252
+ note: "route contract from live router registration; request/response DTOs are not reflectable \u2014 use observe L3 for handler source",
253
+ evidence: { provenance: "runtime", sourceAdapter: this.name, confidence: "confirmed" }
254
+ },
255
+ tokenEstimate: 80
256
+ };
257
+ }
258
+ case "L3": {
259
+ const target = String(params.target || "").trim();
260
+ if (!target) throw invalidParams("INVALID_PARAMS: target (path or path#symbol) is required for L3");
261
+ const { path: filePath, symbol } = splitSourceTarget(target);
262
+ const source = this.readSource(filePath, symbol);
263
+ return {
264
+ level,
265
+ format: "json",
266
+ data: source,
267
+ tokenEstimate: Math.ceil(source.source.length / 4)
268
+ };
269
+ }
270
+ case "L4": {
271
+ const target = String(params.target || "").trim();
272
+ const traces = target ? this.traces.filter((trace) => matchesTarget(trace, target)) : this.recentTraces();
273
+ return {
274
+ level,
275
+ format: "json",
276
+ data: {
277
+ ...target ? { target } : {},
278
+ traces,
279
+ traceCount: traces.length,
280
+ ...traces.length === 0 ? { note: "no request has been executed for this target yet \u2014 verify or instrument the app first" } : {},
281
+ evidence: {
282
+ provenance: "runtime",
283
+ sourceAdapter: this.name,
284
+ confidence: traces.length > 0 ? "confirmed" : "unknown"
285
+ }
286
+ },
287
+ tokenEstimate: 40 + traces.length * 12
288
+ };
289
+ }
290
+ }
291
+ }
292
+ /* -------------------------------------------------------------- understand */
293
+ understand(params = {}) {
294
+ if (!this.enabled.understand) throw permissionDenied("PERMISSION_DENIED: understand capability is disabled");
295
+ const query = String(params.query || "causality");
296
+ const target = String(params.target || "").trim();
297
+ if (query === "impact") {
298
+ if (!target) throw invalidParams("INVALID_PARAMS: target is required for impact");
299
+ const route = this.findRoute(target);
300
+ const affected = route?.handlerName ? [route.handlerName] : [];
301
+ return {
302
+ query: "impact",
303
+ target,
304
+ impact: {
305
+ target,
306
+ affectedSymbols: affected,
307
+ breakingRisk: route ? "LOW" : "UNKNOWN",
308
+ summary: route ? `impact derived from the registered route table for ${route.method} ${route.path}` : "no matching route; impact cannot be derived from registration data",
309
+ observed: false,
310
+ evidence: {
311
+ provenance: "static",
312
+ sourceAdapter: this.name,
313
+ confidence: route ? "probable" : "unknown"
314
+ }
315
+ }
316
+ };
317
+ }
318
+ if (query === "causality" || query === "why_state") {
319
+ const matching = target ? this.traces.filter((trace) => matchesTarget(trace, target)) : this.recentTraces();
320
+ const newest = matching[matching.length - 1];
321
+ if (!newest) {
322
+ return {
323
+ query: "causality",
324
+ target,
325
+ causality: {
326
+ target,
327
+ observed: false,
328
+ traceCount: 0,
329
+ traceChain: [],
330
+ rootCause: "",
331
+ note: "no execution trace for this target yet \u2014 run oumv/verify or serve a request first",
332
+ evidence: { provenance: "static", sourceAdapter: this.name, confidence: "unknown" }
333
+ }
334
+ };
335
+ }
336
+ return {
337
+ query: "causality",
338
+ target,
339
+ causality: {
340
+ target,
341
+ observed: true,
342
+ traceCount: matching.length,
343
+ traceChain: matching.slice(-5).map((trace) => ({
344
+ method: trace.method,
345
+ path: trace.path,
346
+ statusCode: trace.statusCode,
347
+ durationMs: trace.durationMs,
348
+ timestamp: trace.timestamp
349
+ })),
350
+ statusCode: newest.statusCode,
351
+ latencyMs: newest.durationMs,
352
+ rootCause: `${newest.method} ${newest.path} -> ${newest.statusCode}`,
353
+ evidence: { provenance: "runtime", sourceAdapter: this.name, confidence: "confirmed" }
354
+ }
355
+ };
356
+ }
357
+ throw unsupported(`UNSUPPORTED_CAPABILITY: understand query ${query}`);
358
+ }
359
+ /* ------------------------------------------------------------ source & edits */
360
+ getSource(params = {}) {
361
+ const filePath = String(params.path ?? params.filePath ?? "").trim();
362
+ if (!filePath) throw invalidParams("INVALID_PARAMS: path is required");
363
+ return this.readSource(filePath, params.symbol ? String(params.symbol) : void 0);
364
+ }
365
+ readSource(filePath, symbol) {
366
+ const resolved = resolveWorkspacePath(filePath, this.workspaceDir);
367
+ if (!fs2.existsSync(resolved) || !fs2.statSync(resolved).isFile()) {
368
+ throw resourceNotFound(`RESOURCE_NOT_FOUND: ${filePath}`);
369
+ }
370
+ const full = fs2.readFileSync(resolved, "utf-8");
371
+ const relative = path2.relative(this.workspaceDir, resolved).split(path2.sep).join("/");
372
+ const version = sha256(full);
373
+ if (!symbol) {
374
+ const lines = full.split("\n").length + (full.endsWith("\n") ? 0 : 1);
375
+ return { path: relative, source: full, version, startLine: 1, endLine: lines };
376
+ }
377
+ const range = extractSymbolRange(full, symbol);
378
+ if (!range) throw resourceNotFound(`RESOURCE_NOT_FOUND: symbol ${JSON.stringify(symbol)} not found in ${relative}`);
379
+ return {
380
+ path: relative,
381
+ symbol,
382
+ source: range.source,
383
+ version,
384
+ startLine: range.startLine,
385
+ endLine: range.endLine
386
+ };
387
+ }
388
+ applyEdit(params = {}) {
389
+ if (!this.enabled.mutate) throw permissionDenied("PERMISSION_DENIED: mutate capability is disabled");
390
+ const requestedPath = String(params.path ?? params.filePath ?? "").trim();
391
+ if (!requestedPath) throw invalidParams("INVALID_PARAMS: path is required");
392
+ const resolved = resolveWorkspacePath(requestedPath, this.workspaceDir);
393
+ if (String(params.mode ?? "replace").toLowerCase() === "create") {
394
+ const replacement2 = String(params.replacement ?? params.source ?? "");
395
+ if (!replacement2) throw invalidParams("INVALID_PARAMS: replacement is required for mode=create");
396
+ if (params.expectedVersion) {
397
+ throw validationFailed("VALIDATION_FAILED: expectedVersion must be omitted for mode=create", {
398
+ reason: "create_forbids_version"
399
+ });
400
+ }
401
+ if (fs2.existsSync(resolved)) {
402
+ throw conflict("CONFLICT_DETECTED: file already exists; use mode=replace with its version", {
403
+ reason: "file_exists"
404
+ });
405
+ }
406
+ const syntax2 = checkSyntax(resolved, replacement2);
407
+ fs2.mkdirSync(path2.dirname(resolved), { recursive: true });
408
+ fs2.writeFileSync(resolved, replacement2, "utf-8");
409
+ return {
410
+ status: "APPLIED",
411
+ path: path2.relative(this.workspaceDir, resolved).split(path2.sep).join("/"),
412
+ newVersion: sha256(replacement2),
413
+ syntaxCheck: syntax2,
414
+ created: true
415
+ };
416
+ }
417
+ if (!fs2.existsSync(resolved) || !fs2.statSync(resolved).isFile()) {
418
+ throw resourceNotFound(`RESOURCE_NOT_FOUND: ${requestedPath}`);
419
+ }
420
+ const current = fs2.readFileSync(resolved, "utf-8");
421
+ const replacement = String(params.replacement ?? params.source ?? "");
422
+ if (!replacement) throw invalidParams("INVALID_PARAMS: replacement is required");
423
+ const syntax = checkSyntax(resolved, replacement);
424
+ const expectedVersion = String(params.expectedVersion ?? "").trim();
425
+ if (!expectedVersion) {
426
+ throw validationFailed(
427
+ "VALIDATION_FAILED: expectedVersion is required to edit an existing file \u2014 call oumv/getSource and pass its version",
428
+ { path: requestedPath, current: sha256(current) }
429
+ );
430
+ }
431
+ const currentVersion = sha256(current);
432
+ if (expectedVersion !== currentVersion) {
433
+ throw conflict(`CONFLICT_DETECTED: expected ${expectedVersion}, current is ${currentVersion}`, {
434
+ expected: expectedVersion,
435
+ current: currentVersion
436
+ });
437
+ }
438
+ const backupPath = path2.join(this.workspaceDir, ".tokensafe", "backups", `${Date.now()}-${path2.basename(resolved)}`);
439
+ let backedUp;
440
+ try {
441
+ fs2.mkdirSync(path2.dirname(backupPath), { recursive: true });
442
+ fs2.writeFileSync(backupPath, current, "utf-8");
443
+ backedUp = path2.relative(this.workspaceDir, backupPath).split(path2.sep).join("/");
444
+ } catch {
445
+ backedUp = void 0;
446
+ }
447
+ fs2.writeFileSync(resolved, replacement, "utf-8");
448
+ return {
449
+ status: "APPLIED",
450
+ path: path2.relative(this.workspaceDir, resolved).split(path2.sep).join("/"),
451
+ ...params.symbol ? { symbol: String(params.symbol) } : {},
452
+ newVersion: sha256(replacement),
453
+ syntaxCheck: syntax,
454
+ ...backedUp ? { backupPath: backedUp } : {}
455
+ };
456
+ }
457
+ /* ------------------------------------------------------------------ verify */
458
+ async verify(params = {}) {
459
+ if (!this.enabled.verify) throw permissionDenied("PERMISSION_DENIED: verify capability is disabled");
460
+ const target = String(params.target ?? "").trim();
461
+ if (!target) throw invalidParams('INVALID_PARAMS: target ("METHOD /path") is required');
462
+ if (!this.handler) throw resourceUnavailable("RUNTIME_UNAVAILABLE: no application handler is mounted for verification");
463
+ const { method, url } = parseVerifyTarget(target);
464
+ await this.ensureDispatchServer();
465
+ const body = params.payload === void 0 ? void 0 : JSON.stringify(params.payload);
466
+ const startedAt = process.hrtime.bigint();
467
+ const response = await new Promise((resolve, reject) => {
468
+ const request = http.request(
469
+ {
470
+ host: "127.0.0.1",
471
+ port: this.dispatchPort,
472
+ method,
473
+ path: url,
474
+ headers: {
475
+ "content-type": "application/json",
476
+ ...body ? { "content-length": Buffer.byteLength(body).toString() } : {},
477
+ ...params.headers && typeof params.headers === "object" ? params.headers : {}
478
+ }
479
+ },
480
+ (res) => {
481
+ let data = "";
482
+ res.setEncoding("utf-8");
483
+ res.on("data", (chunk) => data += chunk);
484
+ res.on("end", () => resolve({ statusCode: res.statusCode ?? 0, body: data }));
485
+ }
486
+ );
487
+ request.on("error", reject);
488
+ if (body) request.write(body);
489
+ request.end();
490
+ });
491
+ const durationMs = Number(process.hrtime.bigint() - startedAt) / 1e6;
492
+ const status = response.statusCode < 400 ? "passed" : "failed";
493
+ this.recordTrace({
494
+ method,
495
+ path: url,
496
+ route: url,
497
+ handler: "loopback",
498
+ statusCode: response.statusCode,
499
+ durationMs
500
+ });
501
+ return {
502
+ status,
503
+ target,
504
+ statusCode: response.statusCode,
505
+ diff: { status: response.statusCode, responseBody: response.body },
506
+ timings: { t_action_ms: durationMs, t_total_ms: durationMs },
507
+ durationMs,
508
+ scope: {
509
+ checked: ["loopback HTTP dispatch against the live handler"],
510
+ notExecuted: ["external processes", "persistent database state"],
511
+ notSupported: ["browser/DOM assertions"]
512
+ }
513
+ };
514
+ }
515
+ async ensureDispatchServer() {
516
+ if (this.dispatchServer) return;
517
+ const server = http.createServer((req, res) => this.handler(req, res));
518
+ await new Promise((resolve, reject) => {
519
+ server.once("error", reject);
520
+ server.listen(0, "127.0.0.1", () => resolve());
521
+ });
522
+ const address = server.address();
523
+ this.dispatchPort = typeof address === "object" && address ? address.port : 0;
524
+ this.dispatchServer = server;
525
+ }
526
+ /** Releases the loopback dispatcher (tests, shutdown hooks). */
527
+ async dispose() {
528
+ if (!this.dispatchServer) return;
529
+ const server = this.dispatchServer;
530
+ this.dispatchServer = void 0;
531
+ this.dispatchPort = 0;
532
+ await new Promise((resolve) => server.close(() => resolve()));
533
+ }
534
+ /* ---------------------------------------------------------------- helpers */
535
+ findRoute(target) {
536
+ const trimmed = target.trim();
537
+ const match = trimmed.match(/^([A-Za-z]+)\s+(\S+)$/);
538
+ if (match) {
539
+ const byRoute = this.routes.get(`${match[1].toUpperCase()} ${match[2]}`);
540
+ if (byRoute) return byRoute;
541
+ }
542
+ for (const route of this.routes.values()) {
543
+ if (route.path === trimmed) return route;
544
+ }
545
+ return void 0;
546
+ }
547
+ };
548
+ function matchesTarget(trace, target) {
549
+ const trimmed = target.trim();
550
+ const upper = trimmed.toUpperCase();
551
+ if (`${trace.method} ${trace.path}`.toUpperCase() === upper) return true;
552
+ if (trace.path === trimmed) return true;
553
+ if (trace.route && trace.route === trimmed) return true;
554
+ return trace.path.includes(trimmed) && trimmed.startsWith("/");
555
+ }
556
+ function parseVerifyTarget(target) {
557
+ const match = target.trim().match(/^([A-Za-z]+)\s+(\S+)$/);
558
+ if (match) return { method: match[1].toUpperCase(), url: match[2] };
559
+ return { method: "POST", url: target.trim() };
560
+ }
561
+ function checkSyntax(filePath, source) {
562
+ if (!/\.(c|m)?(t|j)sx?$/.test(filePath)) return { status: "skipped", tool: "none" };
563
+ try {
564
+ parseJs(source, {
565
+ sourceType: "unambiguous",
566
+ plugins: ["typescript", "jsx", "decorators-legacy"],
567
+ errorRecovery: false
568
+ });
569
+ } catch (error) {
570
+ throw syntaxError(`SYNTAX_ERROR: pre-flight parse failed: ${error.message}`);
571
+ }
572
+ return { status: "passed", tool: "@babel/parser" };
573
+ }
574
+ function extractSymbolRange(source, symbol) {
575
+ const escaped = symbol.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
576
+ const pattern = new RegExp(
577
+ `(?:function\\s+${escaped}\\b|class\\s+${escaped}\\b|(?:const|let|var)\\s+${escaped}\\b|${escaped}\\s*[:=]\\s*(?:async\\s*)?\\(|export\\s+(?:default\\s+)?(?:function|class|const|let)\\s+${escaped}\\b)`
578
+ );
579
+ const match = pattern.exec(source);
580
+ if (!match) return void 0;
581
+ const start = match.index;
582
+ let braceStart = source.indexOf("{", start);
583
+ const arrowEnd = source.indexOf(";", start);
584
+ if (braceStart === -1 || arrowEnd !== -1 && arrowEnd < braceStart) {
585
+ const end2 = arrowEnd === -1 ? source.length : arrowEnd + 1;
586
+ const slice = source.slice(start, end2);
587
+ return {
588
+ source: slice,
589
+ startLine: source.slice(0, start).split("\n").length,
590
+ endLine: source.slice(0, end2).split("\n").length
591
+ };
592
+ }
593
+ let depth = 0;
594
+ let end = braceStart;
595
+ for (let i = braceStart; i < source.length; i += 1) {
596
+ if (source[i] === "{") depth += 1;
597
+ else if (source[i] === "}") {
598
+ depth -= 1;
599
+ if (depth === 0) {
600
+ end = i + 1;
601
+ break;
602
+ }
603
+ }
604
+ }
605
+ return {
606
+ source: source.slice(start, end),
607
+ startLine: source.slice(0, start).split("\n").length,
608
+ endLine: source.slice(0, end).split("\n").length
609
+ };
610
+ }
611
+ function resourceUnavailable(message) {
612
+ return new OumvError(ERROR_CODES.RUNTIME_UNAVAILABLE, message);
613
+ }
614
+
615
+ // src/descriptor.ts
616
+ import crypto3 from "crypto";
617
+ import fs3 from "fs";
618
+ import os from "os";
619
+ import path3 from "path";
620
+ function descriptorPath(workspaceDir, home) {
621
+ const root = process.env.TOKENSAFE_HOME || home || path3.join(os.homedir(), ".tokensafe");
622
+ const canonical = fs3.existsSync(workspaceDir) ? fs3.realpathSync(workspaceDir) : path3.resolve(workspaceDir);
623
+ const digest = crypto3.createHash("sha256").update(canonical).digest("hex").slice(0, 16);
624
+ return path3.join(root, "runtimes", `${digest}.json`);
625
+ }
626
+ function readRegistry(file) {
627
+ try {
628
+ const raw = fs3.readFileSync(file, "utf-8");
629
+ const parsed = JSON.parse(raw);
630
+ return parsed && typeof parsed === "object" ? parsed : {};
631
+ } catch {
632
+ return {};
633
+ }
634
+ }
635
+ function writeRegistry(file, registry) {
636
+ fs3.writeFileSync(file, JSON.stringify(registry, null, 2) + "\n", { encoding: "utf-8", mode: 384 });
637
+ fs3.chmodSync(file, 384);
638
+ }
639
+ function writeDescriptor(workspaceDir, descriptor, home) {
640
+ const file = descriptorPath(workspaceDir, home);
641
+ fs3.mkdirSync(path3.dirname(file), { recursive: true });
642
+ const registry = readRegistry(file);
643
+ registry.backend = descriptor;
644
+ registry.workspaceRoot = fs3.existsSync(workspaceDir) ? fs3.realpathSync(workspaceDir) : path3.resolve(workspaceDir);
645
+ registry.pid = process.pid;
646
+ registry.updatedAt = Date.now();
647
+ writeRegistry(file, registry);
648
+ return file;
649
+ }
650
+ function deleteDescriptor(workspaceDir, home) {
651
+ const file = descriptorPath(workspaceDir, home);
652
+ const registry = readRegistry(file);
653
+ if (Object.keys(registry).length === 0) return;
654
+ delete registry.backend;
655
+ if (registry.frontend) {
656
+ writeRegistry(file, registry);
657
+ return;
658
+ }
659
+ try {
660
+ fs3.unlinkSync(file);
661
+ } catch {
662
+ }
663
+ }
664
+
665
+ // src/transport/dispatcher.ts
666
+ var success = (id, result) => ({
667
+ jsonrpc: "2.0",
668
+ id: id ?? null,
669
+ result
670
+ });
671
+ var failure = (id, code, message, data) => ({
672
+ jsonrpc: "2.0",
673
+ id: id ?? null,
674
+ error: { code, message, ...data ? { data } : {} }
675
+ });
676
+ var Dispatcher = class {
677
+ constructor(runtime) {
678
+ this.runtime = runtime;
679
+ }
680
+ runtime;
681
+ async dispatch(request) {
682
+ const id = request?.id ?? null;
683
+ const method = String(request?.method ?? "");
684
+ const params = request?.params ?? {};
685
+ if (!method) return failure(id, ERROR_CODES.INVALID_REQUEST, "INVALID_REQUEST: method is required");
686
+ if (method === "oumv/disconnect") {
687
+ return success(id, { closed: this.runtime.sessions.delete(params.sessionId) });
688
+ }
689
+ if (method !== "oumv/handshake" && method !== "handshake" && params.sessionId) {
690
+ if (!this.runtime.sessions.validate(String(params.sessionId))) {
691
+ return failure(
692
+ id,
693
+ ERROR_CODES.VALIDATION_FAILED,
694
+ "VALIDATION_FAILED: unknown or expired sessionId \u2014 re-run oumv/handshake",
695
+ { reason: "session_expired", sessionId: params.sessionId }
696
+ );
697
+ }
698
+ }
699
+ try {
700
+ switch (method) {
701
+ case "oumv/handshake":
702
+ case "handshake":
703
+ return success(id, this.runtime.handshake(params));
704
+ case "oumv/observe":
705
+ return success(id, this.runtime.observe(params));
706
+ case "oumv/understand":
707
+ return success(id, this.runtime.understand(params));
708
+ case "oumv/getSource":
709
+ return success(id, this.runtime.getSource(params));
710
+ case "oumv/applyEdit":
711
+ return success(id, this.runtime.applyEdit(params));
712
+ case "oumv/verify":
713
+ return success(id, await this.runtime.verify(params));
714
+ default:
715
+ return failure(id, ERROR_CODES.METHOD_NOT_FOUND, `METHOD_NOT_FOUND: ${method}`);
716
+ }
717
+ } catch (error) {
718
+ if (error instanceof OumvError) {
719
+ return failure(id, error.code, error.message, error.data);
720
+ }
721
+ return failure(id, ERROR_CODES.INTERNAL_ERROR, `INTERNAL_ERROR: ${error?.message ?? String(error)}`);
722
+ }
723
+ }
724
+ };
725
+ function parsePayload(raw) {
726
+ let parsed;
727
+ try {
728
+ parsed = JSON.parse(raw);
729
+ } catch (error) {
730
+ throw new OumvError(ERROR_CODES.PARSE_ERROR, `Parse error: ${error.message}`);
731
+ }
732
+ if (Array.isArray(parsed)) {
733
+ if (parsed.length === 0) throw invalidParams("INVALID_REQUEST: empty batch");
734
+ return parsed;
735
+ }
736
+ if (!parsed || typeof parsed !== "object") {
737
+ throw invalidParams("INVALID_REQUEST: body must be a JSON-RPC object or array");
738
+ }
739
+ return parsed;
740
+ }
741
+ async function dispatchAll(dispatcher, payload) {
742
+ if (!Array.isArray(payload)) {
743
+ const response = await dispatcher.dispatch(payload);
744
+ if (payload.id === void 0 && !response.error) {
745
+ return response;
746
+ }
747
+ return response;
748
+ }
749
+ const responses = [];
750
+ for (const item of payload) {
751
+ if (!item || typeof item !== "object") {
752
+ responses.push(failure(null, ERROR_CODES.INVALID_REQUEST, "INVALID_REQUEST: batch entries must be objects"));
753
+ continue;
754
+ }
755
+ const response = await dispatcher.dispatch(item);
756
+ if (item.id === void 0 && !response.error) continue;
757
+ responses.push(response);
758
+ }
759
+ return responses;
760
+ }
761
+
762
+ // src/transport/http.ts
763
+ function isAuthorized(req, token, requireAuth) {
764
+ const provided = String(
765
+ req.headers["x-oumv-session-token"] ?? (typeof req.headers.authorization === "string" && req.headers.authorization.toLowerCase().startsWith("bearer ") ? req.headers.authorization.slice(7).trim() : "") ?? ""
766
+ );
767
+ if (!token) return !requireAuth;
768
+ if (provided) return provided === token;
769
+ return !requireAuth;
770
+ }
771
+ function createHttpHandler(options) {
772
+ const runtime = options.runtime;
773
+ const dispatcher = new Dispatcher(runtime);
774
+ const token = options.authToken ?? runtime.authToken ?? "";
775
+ const maxBodyBytes = options.maxBodyBytes ?? runtime.maxBodyBytes;
776
+ return async function handle(req, res) {
777
+ const pathname = String(req.originalUrl ?? req.url ?? "").split("?")[0];
778
+ if (pathname !== runtime.transportPath) return false;
779
+ res.setHeader("Access-Control-Allow-Origin", "*");
780
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-OUMV-Session-Token");
781
+ res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
782
+ if (req.method === "OPTIONS") {
783
+ res.statusCode = 204;
784
+ res.end();
785
+ return true;
786
+ }
787
+ if (req.method !== "POST") {
788
+ res.statusCode = 405;
789
+ res.setHeader("Content-Type", "application/json");
790
+ res.end(JSON.stringify({ error: "Method not allowed" }));
791
+ return true;
792
+ }
793
+ if (!isAuthorized(req, token, Boolean(options.requireAuth))) {
794
+ res.statusCode = 401;
795
+ res.setHeader("Content-Type", "application/json");
796
+ res.end(JSON.stringify(failure(null, ERROR_CODES.PERMISSION_DENIED, "PERMISSION_DENIED: invalid OUMV session token")));
797
+ return true;
798
+ }
799
+ const preParsed = req.body;
800
+ const chunks = [];
801
+ let size = 0;
802
+ if (preParsed === void 0) {
803
+ for await (const chunk of req) {
804
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
805
+ size += buffer.length;
806
+ if (size > maxBodyBytes) {
807
+ res.statusCode = 413;
808
+ res.setHeader("Content-Type", "application/json");
809
+ res.end(JSON.stringify(failure(null, ERROR_CODES.INVALID_REQUEST, "INVALID_REQUEST: body too large")));
810
+ return true;
811
+ }
812
+ chunks.push(buffer);
813
+ }
814
+ }
815
+ res.setHeader("Content-Type", "application/json");
816
+ try {
817
+ const payload = preParsed !== void 0 && typeof preParsed === "object" ? preParsed : parsePayload(Buffer.concat(chunks).toString("utf-8"));
818
+ const response = await dispatchAll(dispatcher, payload);
819
+ res.statusCode = 200;
820
+ res.end(JSON.stringify(response));
821
+ } catch (error) {
822
+ res.statusCode = 200;
823
+ res.end(
824
+ JSON.stringify(
825
+ failure(null, error?.code ?? ERROR_CODES.INTERNAL_ERROR, error?.message ?? "INTERNAL_ERROR: unreadable body")
826
+ )
827
+ );
828
+ }
829
+ return true;
830
+ };
831
+ }
832
+
833
+ // src/transport/sse.ts
834
+ function createSseHandler(options) {
835
+ const runtime = options.runtime;
836
+ const heartbeatMs = options.heartbeatMs ?? 15e3;
837
+ const pollMs = options.pollMs ?? 300;
838
+ const eventsPath = runtime.transportPath.replace(/\/rpc$/, "/events");
839
+ const token = options.authToken ?? runtime.authToken ?? "";
840
+ return async function handle(req, res) {
841
+ const pathname = String(req.originalUrl ?? req.url ?? "").split("?")[0];
842
+ if (pathname !== eventsPath) return false;
843
+ if (req.method !== "GET") {
844
+ res.statusCode = 405;
845
+ res.end(JSON.stringify({ error: "SSE requires GET" }));
846
+ return true;
847
+ }
848
+ if (!isAuthorized(req, token, Boolean(options.requireAuth))) {
849
+ res.statusCode = 401;
850
+ res.setHeader("Content-Type", "application/json");
851
+ res.end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32007, message: "PERMISSION_DENIED" } }));
852
+ return true;
853
+ }
854
+ res.writeHead(200, {
855
+ "Content-Type": "text/event-stream",
856
+ "Cache-Control": "no-cache",
857
+ Connection: "keep-alive",
858
+ "X-Accel-Buffering": "no"
859
+ });
860
+ res.write(": connected\n\n");
861
+ let cursor = Number.parseInt(String(req.headers["last-event-id"] ?? "0"), 10);
862
+ if (!Number.isFinite(cursor) || cursor < 0) cursor = 0;
863
+ const flush = () => {
864
+ const traces = runtime.recentTraces();
865
+ for (let index = cursor; index < traces.length; index += 1) {
866
+ res.write(`id: ${index + 1}
867
+ event: trace
868
+ data: ${JSON.stringify(traces[index])}
869
+
870
+ `);
871
+ }
872
+ cursor = traces.length;
873
+ };
874
+ flush();
875
+ const poll = setInterval(flush, pollMs);
876
+ const heartbeat = setInterval(() => {
877
+ res.write(`event: heartbeat
878
+ data: ${JSON.stringify((/* @__PURE__ */ new Date()).toISOString())}
879
+
880
+ `);
881
+ }, heartbeatMs);
882
+ const stop = () => {
883
+ clearInterval(poll);
884
+ clearInterval(heartbeat);
885
+ res.end();
886
+ };
887
+ req.on("close", stop);
888
+ return true;
889
+ };
890
+ }
891
+
892
+ // src/transport/ws.ts
893
+ import { WebSocketServer } from "ws";
894
+ function attachWebSocket(server, options) {
895
+ const runtime = options.runtime;
896
+ const token = options.authToken ?? runtime.authToken ?? "";
897
+ const dispatcher = new Dispatcher(runtime);
898
+ const wss = new WebSocketServer({ noServer: true });
899
+ const sessions = /* @__PURE__ */ new WeakMap();
900
+ const onUpgrade = (req, socket, head) => {
901
+ const pathname = String(req.url || "").split("?")[0];
902
+ if (pathname !== runtime.transportPath) return;
903
+ if (!isAuthorized(req, token, Boolean(options.requireAuth))) {
904
+ socket.write("HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n");
905
+ socket.destroy();
906
+ return;
907
+ }
908
+ wss.handleUpgrade(req, socket, head, (ws) => wss.emit("connection", ws, req));
909
+ };
910
+ server.on("upgrade", onUpgrade);
911
+ wss.on("connection", (ws) => {
912
+ ws.on("message", async (raw) => {
913
+ let payload;
914
+ try {
915
+ payload = JSON.parse(String(raw));
916
+ } catch (error) {
917
+ ws.send(JSON.stringify(failure(null, -32700, `Parse error: ${error.message}`)));
918
+ return;
919
+ }
920
+ const isNotification2 = !Array.isArray(payload) && payload && typeof payload === "object" && payload.id === void 0;
921
+ const response = await dispatchAll(dispatcher, payload);
922
+ if (isNotification2 && !Array.isArray(payload) && !response.error) return;
923
+ if (Array.isArray(payload) && Array.isArray(response) && response.length === 0) return;
924
+ ws.send(JSON.stringify(response));
925
+ if (!Array.isArray(payload) && payload?.method === "oumv/handshake") {
926
+ const sessionId = response?.result?.sessionId;
927
+ if (sessionId) sessions.set(ws, sessionId);
928
+ }
929
+ });
930
+ ws.on("close", () => {
931
+ const sessionId = sessions.get(ws);
932
+ if (sessionId) runtime.sessions.delete(sessionId);
933
+ sessions.delete(ws);
934
+ });
935
+ });
936
+ return {
937
+ close: () => new Promise((resolve) => {
938
+ server.off("upgrade", onUpgrade);
939
+ for (const client of wss.clients) client.terminate();
940
+ wss.close(() => resolve());
941
+ })
942
+ };
943
+ }
944
+
945
+ // src/transport/stdio.ts
946
+ import readline from "readline";
947
+ var isNotification = (request) => Boolean(request) && typeof request === "object" && request.id === void 0;
948
+ function attachStdio(runtime, options = {}) {
949
+ const dispatcher = new Dispatcher(runtime);
950
+ const output = options.output ?? process.stdout;
951
+ const input = options.input ?? process.stdin;
952
+ const write = (body) => {
953
+ if (body !== void 0 && body !== null) output.write(JSON.stringify(body) + "\n");
954
+ };
955
+ const handleLine = async (line) => {
956
+ let payload;
957
+ try {
958
+ payload = parsePayload(line);
959
+ } catch (error) {
960
+ write(failure(null, error?.code ?? -32700, error?.message ?? "Parse error"));
961
+ return;
962
+ }
963
+ if (Array.isArray(payload)) {
964
+ const responses = [];
965
+ for (const request of payload) {
966
+ const response = await dispatcher.dispatch(request);
967
+ if (!isNotification(request)) responses.push(response);
968
+ }
969
+ if (responses.length > 0) write(responses);
970
+ return;
971
+ }
972
+ if (isNotification(payload)) {
973
+ await dispatcher.dispatch(payload);
974
+ return;
975
+ }
976
+ write(await dispatcher.dispatch(payload));
977
+ };
978
+ const rl = readline.createInterface({ input, crlfDelay: Infinity });
979
+ let queue = Promise.resolve();
980
+ rl.on("line", (line) => {
981
+ const trimmed = line.trim();
982
+ if (!trimmed) return;
983
+ queue = queue.then(() => handleLine(trimmed)).catch((error) => {
984
+ process.stderr.write(`tokensafe-oumv-stdio: ${error?.stack ?? error}
985
+ `);
986
+ });
987
+ });
988
+ return { close: () => rl.close() };
989
+ }
990
+
991
+ // src/adapters/express.ts
992
+ function collectExpressRoutes(app) {
993
+ const anyApp = app;
994
+ let stack = [];
995
+ try {
996
+ stack = anyApp._router?.stack ?? [];
997
+ } catch {
998
+ }
999
+ if (stack.length === 0) {
1000
+ try {
1001
+ stack = anyApp.router?.stack ?? [];
1002
+ } catch {
1003
+ }
1004
+ }
1005
+ const routes = [];
1006
+ for (const layer of stack) {
1007
+ if (layer.route) {
1008
+ const methods = Object.keys(layer.route.methods ?? {}).filter((m) => layer.route.methods[m]);
1009
+ const handlerName = layer.route.stack?.find((entry) => entry?.name && entry.name !== "router")?.name;
1010
+ for (const method of methods) {
1011
+ routes.push({ method: method.toUpperCase(), path: layer.route.path, handlerName });
1012
+ }
1013
+ }
1014
+ }
1015
+ return routes;
1016
+ }
1017
+ function mountTokensafe(app, options = {}) {
1018
+ const runtime = options.runtime ?? new OumvRuntime({
1019
+ ...options,
1020
+ workspaceDir: options.workspaceDir ?? process.cwd(),
1021
+ handler: app
1022
+ });
1023
+ for (const route of collectExpressRoutes(app)) {
1024
+ runtime.registerRoute(route.method, route.path, route.handlerName);
1025
+ }
1026
+ runtime.setHandler(app);
1027
+ const httpHandler = createHttpHandler({ runtime, authToken: options.authToken, requireAuth: options.requireAuth });
1028
+ const sseHandler = createSseHandler({ runtime, authToken: options.authToken, requireAuth: options.requireAuth });
1029
+ app.use(runtime.transportPath, (req, res, next) => {
1030
+ void httpHandler(req, res).then((handled) => {
1031
+ if (!handled) next();
1032
+ });
1033
+ });
1034
+ const eventsPath = runtime.transportPath.replace(/\/rpc$/, "/events");
1035
+ app.use(eventsPath, (req, res, next) => {
1036
+ void sseHandler(req, res).then((handled) => {
1037
+ if (!handled) next();
1038
+ });
1039
+ });
1040
+ runtime.setTransports(["http", "sse"]);
1041
+ if (options.publicUrl && options.descriptor !== false) {
1042
+ writeDescriptor(runtime.workspaceDir, {
1043
+ type: "backend",
1044
+ name: runtime.name,
1045
+ version: runtime.version,
1046
+ url: options.publicUrl,
1047
+ ...options.authToken ? { sessionToken: options.authToken } : {},
1048
+ workspace: runtime.workspaceDir,
1049
+ capabilities: { observeLevels: ["L0", "L1", "L2", "L3", "L4"], transports: ["http", "sse"] },
1050
+ startedAt: (/* @__PURE__ */ new Date()).toISOString()
1051
+ });
1052
+ }
1053
+ return {
1054
+ runtime,
1055
+ attachWebSocket: (server) => {
1056
+ const attachment = attachWebSocket(server, { runtime, authToken: options.authToken, requireAuth: options.requireAuth });
1057
+ runtime.setTransports(["http", "sse", "ws"]);
1058
+ return attachment;
1059
+ },
1060
+ dispose: async () => {
1061
+ await runtime.dispose();
1062
+ deleteDescriptor(runtime.workspaceDir);
1063
+ }
1064
+ };
1065
+ }
1066
+ function tracingMiddleware(runtime) {
1067
+ return function oumvTracing(req, res, next) {
1068
+ const startedAt = process.hrtime.bigint();
1069
+ res.once("finish", () => {
1070
+ if (String(req.url || "").startsWith(runtime.transportPath)) return;
1071
+ const durationMs = Number(process.hrtime.bigint() - startedAt) / 1e6;
1072
+ runtime.recordTrace({
1073
+ method: String(req.method || "GET"),
1074
+ path: String(req.url || "/").split("?")[0],
1075
+ route: String(req.url || "/").split("?")[0],
1076
+ handler: "express",
1077
+ statusCode: Number(res.statusCode) || 200,
1078
+ durationMs
1079
+ });
1080
+ });
1081
+ next();
1082
+ };
1083
+ }
1084
+
1085
+ // src/adapters/fastify.ts
1086
+ async function registerTokensafe(fastify, options = {}) {
1087
+ const runtime = options.runtime ?? new OumvRuntime({
1088
+ ...options,
1089
+ workspaceDir: options.workspaceDir ?? process.cwd()
1090
+ });
1091
+ const eventsPath = runtime.transportPath.replace(/\/rpc$/, "/events");
1092
+ fastify.addHook("onRoute", (route) => {
1093
+ if (route.url === runtime.transportPath || route.url === eventsPath) return;
1094
+ const methods = Array.isArray(route.method) ? route.method : [route.method];
1095
+ for (const method of methods) {
1096
+ if (String(method).toUpperCase() === "HEAD") continue;
1097
+ runtime.registerRoute(String(method), route.url, route.handler?.name);
1098
+ }
1099
+ });
1100
+ runtime.setHandler((req, res) => {
1101
+ fastify.routing(req, res);
1102
+ });
1103
+ const httpHandler = createHttpHandler({ runtime, authToken: options.authToken, requireAuth: options.requireAuth });
1104
+ const sseHandler = createSseHandler({ runtime, authToken: options.authToken, requireAuth: options.requireAuth });
1105
+ const bridge = (handler) => async (request, reply) => {
1106
+ if (request.body !== void 0) request.raw.body = request.body;
1107
+ const handled = await handler(request.raw, reply.raw);
1108
+ if (!handled) {
1109
+ reply.callNotFound();
1110
+ return reply;
1111
+ }
1112
+ return reply;
1113
+ };
1114
+ fastify.route({
1115
+ method: ["POST", "OPTIONS"],
1116
+ url: runtime.transportPath,
1117
+ handler: bridge(httpHandler)
1118
+ });
1119
+ fastify.route({
1120
+ method: "GET",
1121
+ url: eventsPath,
1122
+ handler: bridge(sseHandler)
1123
+ });
1124
+ runtime.setTransports(["http", "sse"]);
1125
+ if (options.publicUrl && options.descriptor !== false) {
1126
+ writeDescriptor(runtime.workspaceDir, {
1127
+ type: "backend",
1128
+ name: runtime.name,
1129
+ version: runtime.version,
1130
+ url: options.publicUrl,
1131
+ ...options.authToken ? { sessionToken: options.authToken } : {},
1132
+ workspace: runtime.workspaceDir,
1133
+ capabilities: { observeLevels: ["L0", "L1", "L2", "L3", "L4"], transports: ["http", "sse"] },
1134
+ startedAt: (/* @__PURE__ */ new Date()).toISOString()
1135
+ });
1136
+ }
1137
+ return {
1138
+ runtime,
1139
+ attachWebSocket: () => {
1140
+ const attachment = attachWebSocket(fastify.server, {
1141
+ runtime,
1142
+ authToken: options.authToken,
1143
+ requireAuth: options.requireAuth
1144
+ });
1145
+ runtime.setTransports(["http", "sse", "ws"]);
1146
+ return attachment;
1147
+ },
1148
+ dispose: async () => {
1149
+ await runtime.dispose();
1150
+ deleteDescriptor(runtime.workspaceDir);
1151
+ }
1152
+ };
1153
+ }
1154
+
1155
+ export {
1156
+ ERROR_CODES,
1157
+ OumvError,
1158
+ resolveWorkspacePath,
1159
+ splitSourceTarget,
1160
+ SessionRegistry,
1161
+ PROTOCOL_VERSION,
1162
+ OBSERVE_LEVELS,
1163
+ OumvRuntime,
1164
+ descriptorPath,
1165
+ writeDescriptor,
1166
+ deleteDescriptor,
1167
+ success,
1168
+ failure,
1169
+ Dispatcher,
1170
+ parsePayload,
1171
+ dispatchAll,
1172
+ isAuthorized,
1173
+ createHttpHandler,
1174
+ createSseHandler,
1175
+ attachWebSocket,
1176
+ attachStdio,
1177
+ mountTokensafe,
1178
+ tracingMiddleware,
1179
+ registerTokensafe
1180
+ };
1181
+ //# sourceMappingURL=chunk-DXJ53S4A.js.map