-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdispatcher-plugin.ts
More file actions
1055 lines (981 loc) · 50.1 KB
/
Copy pathdispatcher-plugin.ts
File metadata and controls
1055 lines (981 loc) · 50.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { Plugin, PluginContext, IHttpServer } from '@objectstack/core';
import { HttpDispatcher, HttpDispatcherResult } from './http-dispatcher.js';
import {
buildSecurityHeaders,
type SecurityHeadersOptions,
} from './security/index.js';
import {
NoopMetricsRegistry,
NoopErrorReporter,
instrumentRouteHandler,
type MetricsRegistry,
type ErrorReporter,
} from './observability/index.js';
export interface DispatcherPluginConfig {
/**
* API path prefix for all endpoints.
* @default '/api/v1'
*/
prefix?: string;
/**
* Project-scoping configuration. Must match the REST API
* `enableProjectScoping` / `projectResolution` fields so AI / automation
* routes stay in lockstep with /data and /meta.
*
* When `enableProjectScoping` is true and `projectResolution` is:
* - `required` — only `/environments/:environmentId/...` variants are registered.
* - `optional` / `auto` — both unscoped and scoped variants are registered
* (the scoped handler forwards `req.params.environmentId` into context).
*/
scoping?: {
enableProjectScoping?: boolean;
projectResolution?: 'required' | 'optional' | 'auto';
};
/**
* Enforce per-project membership (`sys_environment_member`) on scoped
* data-plane routes. Returns 403 for non-members unless they are
* staff (platform org) or the project is the well-known system
* project.
*
* Defaults to `true` when `scoping.enableProjectScoping` is enabled;
* explicitly set to `false` for tests and single-tenant deployments
* where membership has not been seeded.
*/
enforceProjectMembership?: boolean;
/**
* Security response headers. When provided, every response routed
* through this plugin gets the headers merged in (route-specific
* headers still win on conflict).
*
* Pass `false` to disable. Pass `true` (or omit) to enable with
* conservative API-server defaults (CSP=deny-all, XCTO=nosniff,
* X-Frame-Options=DENY, etc.). Pass an object to customize — see
* {@link SecurityHeadersOptions}.
*
* @default true
*/
securityHeaders?: boolean | SecurityHeadersOptions;
/**
* Observability wiring. All fields optional; defaults are noop
* (zero overhead, no behavior change).
*
* - `metrics`: registry receiving `http_requests_total`,
* `http_request_duration_ms`, `http_request_errors_total` for
* every route this plugin mounts. Plug in `prom-client` /
* `@opentelemetry/api-metrics` / your own adapter.
*
* - `errorReporter`: invoked on 5xx responses with the thrown
* error and `{ requestId, method, route }`. Plug in Sentry /
* Datadog / Rollbar.
*
* - `generateRequestId`: customize the format of minted request
* ids (default: `req_<uuid>` via `crypto.randomUUID`). The
* incoming `X-Request-Id` header is honored when present and
* well-formed, regardless of this setting.
*
* - `requestIdHeader`: response header name to echo the id back
* on. Defaults to `X-Request-Id`.
*/
observability?: {
metrics?: MetricsRegistry;
errorReporter?: ErrorReporter;
generateRequestId?: () => string;
requestIdHeader?: string;
};
}
/**
* Route definition emitted by service plugins (e.g. AIServicePlugin) via hooks.
* Minimal interface — matches the shape produced by `buildAIRoutes()`.
*/
interface RouteDefinition {
method: 'GET' | 'POST' | 'PATCH' | 'DELETE';
path: string;
description: string;
handler: (req: any) => Promise<any>;
}
/**
* Register a single RouteDefinition on the HTTP server.
* Returns true if the route was successfully registered.
*/
function mountRouteOnServer(
route: RouteDefinition,
server: IHttpServer,
routePath: string,
securityHeaders?: Record<string, string>,
resolveUser?: (headers: Record<string, any>) => Promise<any | undefined>,
): boolean {
const handler = async (req: any, res: any) => {
try {
// Resolve the authenticated user from request headers (cookie /
// bearer) so route handlers can attribute the request to an
// actor — wires up `req.user` for AI routes, action endpoints,
// anything that needs identity-aware execution.
let user: any;
if (resolveUser) {
try {
user = await resolveUser(req.headers ?? {});
} catch {
/* fall through anonymous — route's `auth: true` guard runs separately */
}
}
const result = await route.handler({
body: req.body,
params: req.params,
query: req.query,
headers: req.headers,
user,
});
if (result.stream && result.events) {
// SSE streaming response
res.status(result.status);
if (securityHeaders) {
for (const [k, v] of Object.entries(securityHeaders)) {
res.header(k, v);
}
}
// Apply headers from the route result if available
if (result.headers) {
for (const [k, v] of Object.entries(result.headers)) {
res.header(k, String(v));
}
} else {
res.header('Content-Type', 'text/event-stream');
res.header('Cache-Control', 'no-cache');
res.header('Connection', 'keep-alive');
}
// Write the stream — events are pre-encoded SSE strings
if (typeof res.write === 'function' && typeof res.end === 'function') {
for await (const event of result.events) {
res.write(typeof event === 'string' ? event : `data: ${JSON.stringify(event)}\n\n`);
}
res.end();
} else {
// Fallback: collect events into array
const events = [];
for await (const event of result.events) {
events.push(event);
}
res.json({ events });
}
} else {
res.status(result.status);
if (securityHeaders) {
for (const [k, v] of Object.entries(securityHeaders)) {
res.header(k, v);
}
}
if (result.body !== undefined) {
res.json(result.body);
} else {
res.end();
}
}
} catch (err: any) {
errorResponseBase(err, res, securityHeaders);
}
};
const m = route.method.toLowerCase();
if (m === 'get' && typeof server.get === 'function') {
server.get(routePath, handler);
return true;
} else if (m === 'post' && typeof server.post === 'function') {
server.post(routePath, handler);
return true;
} else if (m === 'delete' && typeof server.delete === 'function') {
server.delete(routePath, handler);
return true;
} else if (m === 'patch' && typeof server.patch === 'function') {
server.patch(routePath, handler);
return true;
}
return false;
}
/**
* Send an HttpDispatcherResult through IHttpResponse.
* Differentiates between handled, unhandled (404), and special results.
*
* @param securityHeaders headers to merge into every response (under
* the route-specific headers so the dispatcher can override on a
* per-route basis when truly needed).
*/
function sendResultBase(
result: HttpDispatcherResult,
res: any,
securityHeaders?: Record<string, string>,
): void {
const applySecurityHeaders = () => {
if (!securityHeaders) return;
for (const [k, v] of Object.entries(securityHeaders)) {
// Don't clobber route-set headers — `res.header` semantics
// vary by adapter, so we set unconditionally and rely on the
// call ordering (security headers first, route headers
// overwrite below).
res.header(k, v);
}
};
if (result.handled) {
if (result.response) {
res.status(result.response.status);
applySecurityHeaders();
if (result.response.headers) {
for (const [k, v] of Object.entries(result.response.headers)) {
res.header(k, v);
}
}
res.json(result.response.body);
return;
}
if (result.result) {
// Special results from the dispatcher's `result.result` channel.
// Currently the only shape we handle here is the SSE/streaming
// descriptor returned by AI routes:
// { status, stream: true, events: AsyncIterable<string>,
// headers?: Record<string, string>, contentType?: string }
// Anything else falls through to JSON so older callers keep
// working.
const r = result.result as any;
const isStream = r && typeof r === 'object' && (r.type === 'stream' || r.stream === true) && r.events;
if (isStream && typeof res.write === 'function' && typeof res.end === 'function') {
res.status(typeof r.status === 'number' ? r.status : 200);
applySecurityHeaders();
if (r.headers && typeof r.headers === 'object') {
for (const [k, v] of Object.entries(r.headers)) {
res.header(k, String(v));
}
} else {
res.header('Content-Type', r.contentType || 'text/event-stream');
res.header('Cache-Control', 'no-cache');
res.header('Connection', 'keep-alive');
}
// Flip the adapter's `isStreaming` flag synchronously so the
// outer handler can return before the AsyncIterable is fully
// drained. Without this empty write, the Hono adapter would
// see no streaming activity by the time the route handler
// resolves and would close the body, truncating the SSE.
res.write('');
// Drain the events in the background; the adapter's
// ReadableStream stays open until res.end() fires.
(async () => {
try {
for await (const event of r.events as AsyncIterable<unknown>) {
if (event == null) continue;
res.write(typeof event === 'string' ? event : `data: ${JSON.stringify(event)}\n\n`);
}
} catch (streamErr) {
try {
res.write(`event: error\ndata: ${JSON.stringify({ message: streamErr instanceof Error ? streamErr.message : String(streamErr) })}\n\n`);
} catch { /* connection already gone */ }
} finally {
try { res.end(); } catch { /* idem */ }
}
})();
return;
}
res.status(200);
applySecurityHeaders();
res.json(result.result);
return;
}
}
// Semantic 404: no route matched — include diagnostic info
res.status(404);
applySecurityHeaders();
res.json({
success: false,
error: {
message: 'Not Found',
code: 404,
type: 'ROUTE_NOT_FOUND',
hint: 'No handler matched this request. Check the API discovery endpoint for available routes.',
},
});
}
function errorResponseBase(err: any, res: any, securityHeaders?: Record<string, string>): void {
const code = err.statusCode || 500;
res.status(code);
if (securityHeaders) {
for (const [k, v] of Object.entries(securityHeaders)) {
res.header(k, v);
}
}
// Side-channel: remember the original error so the observability
// wrapper can hand it to errorReporter on 5xx. Handlers catch the
// error and call us here instead of re-throwing, so this is the
// only place we still have it.
if (code >= 500) {
try {
(res as any).__obsRecordedError = err;
} catch {
// res is a frozen / proxy object — skip
}
}
res.json({
success: false,
error: { message: err.message || 'Internal Server Error', code },
});
}
/**
* Dispatcher Plugin
*
* Bridges legacy HttpDispatcher handlers to the IHttpServer route-registration model.
* Registers routes for domains NOT covered by @objectstack/rest:
* - /.well-known/objectstack (discovery)
* - /auth (authentication)
* - /graphql (GraphQL)
* - /analytics (BI queries)
* - /packages (package management)
* - /i18n (internationalization — locales, translations, field labels)
* - /storage (file storage)
* - /automation (CRUD + triggers + runs)
*
* Usage:
* ```ts
* import { createDispatcherPlugin } from '@objectstack/runtime';
* runtime.use(createDispatcherPlugin({ prefix: '/api/v1' }));
* ```
*/
export function createDispatcherPlugin(config: DispatcherPluginConfig = {}): Plugin {
return {
name: 'com.objectstack.runtime.dispatcher',
version: '1.0.0',
init: async (_ctx: PluginContext) => {
// Consumer-only plugin — no services registered
},
start: async (ctx: PluginContext) => {
let server: IHttpServer | undefined;
try {
server = ctx.getService<IHttpServer>('http.server');
} catch {
// No HTTP server available — skip silently
return;
}
if (!server) return;
const kernel = ctx.getKernel();
// Default: enable membership enforcement iff environment-scoping is on.
// Tests / single-tenant deploys can opt out via the explicit flag.
const enforceMembership =
config.enforceProjectMembership ?? (config.scoping?.enableProjectScoping ?? false);
const dispatcher = new HttpDispatcher(kernel, undefined, {
enforceProjectMembership: enforceMembership,
});
const prefix = config.prefix || '/api/v1';
// ── Security: resolve once at startup; applied on every response.
// Defaults to ON because every production API server should be
// sending these headers. Opt out with `securityHeaders: false`
// (only sensible for tests or when an upstream reverse proxy is
// already setting them).
const securityHeaders: Record<string, string> | undefined =
config.securityHeaders === false
? undefined
: buildSecurityHeaders(
typeof config.securityHeaders === 'object'
? config.securityHeaders
: {},
);
// Locally-shadowed wrappers — every `sendResult(...)` /
// `errorResponse(...)` call below picks these up via lexical
// scope, so the 50+ route handlers don't need to thread the
// security headers through manually.
const sendResult = (result: HttpDispatcherResult, res: any) =>
sendResultBase(result, res, securityHeaders);
const errorResponse = (err: any, res: any) =>
errorResponseBase(err, res, securityHeaders);
// ── Observability ──────────────────────────────────────────
// Noop defaults; production hosts inject real adapters.
const metrics: MetricsRegistry =
config.observability?.metrics ?? new NoopMetricsRegistry();
const errorReporter: ErrorReporter =
config.observability?.errorReporter ?? new NoopErrorReporter();
const generateRequestId = config.observability?.generateRequestId;
const requestIdHeader =
config.observability?.requestIdHeader ?? 'X-Request-Id';
/**
* Wrap the IHttpServer so every route registration is
* automatically instrumented. We only override the three
* verb methods the dispatcher uses; everything else passes
* through unchanged.
*/
const rawServer = server;
server = new Proxy(rawServer, {
get(target, prop, receiver) {
if (prop === 'get' || prop === 'post' || prop === 'delete') {
const method = String(prop).toUpperCase();
const original = (target as any)[prop];
if (typeof original !== 'function') return original;
return (route: string, handler: any) => {
return original.call(
target,
route,
instrumentRouteHandler(method, route, handler, {
metrics,
errorReporter,
generateRequestId,
requestIdHeader,
}),
);
};
}
return Reflect.get(target, prop, receiver);
},
}) as IHttpServer;
// ── Discovery (.well-known) ─────────────────────────────────
server.get('/.well-known/objectstack', async (_req: any, res: any) => {
if (securityHeaders) {
for (const [k, v] of Object.entries(securityHeaders)) {
res.header(k, v);
}
}
// Discovery reflects MUTABLE runtime config (which routes/services
// are live — e.g. `mcp` only when OS_MCP_SERVER_ENABLED=true). It
// must never be cached by an edge/CDN, or a config change (enable
// MCP) leaves clients reading a stale payload that still says the
// route is absent — the Integrations UI then shows "MCP not
// enabled" against a live server (cloud#152). The body is computed
// fresh per request; the only staleness is the HTTP cache layer.
res.header('Cache-Control', 'no-store');
res.json({ data: await dispatcher.getDiscoveryInfo(prefix) });
});
// ── Discovery (versioned API path) ──────────────────────────
server.get(`${prefix}/discovery`, async (_req: any, res: any) => {
if (securityHeaders) {
for (const [k, v] of Object.entries(securityHeaders)) {
res.header(k, v);
}
}
// See the .well-known handler above: discovery must not be cached
// (mutable runtime config; cloud#152 stale `routes.mcp`).
res.header('Cache-Control', 'no-store');
res.json({ data: await dispatcher.getDiscoveryInfo(prefix) });
});
// ── Health ──────────────────────────────────────────────────
server.get(`${prefix}/health`, async (_req: any, res: any) => {
try {
const result = await dispatcher.dispatch('GET', '/health', undefined, {}, { request: _req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
// ── Readiness ───────────────────────────────────────────────
// Like /health, the dispatcher owns the /ready branch but it is
// only reachable over HTTP once mounted EXPLICITLY here (there is
// no catch-all). 200 while the kernel is `running`, 503 while it is
// booting or shutting down — the contract the EE multi-node
// rolling-restart drain gate polls (cloud ADR-0018) so a load
// balancer stops routing to a replica before it closes.
server.get(`${prefix}/ready`, async (_req: any, res: any) => {
try {
const result = await dispatcher.dispatch('GET', '/ready', undefined, {}, { request: _req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
// ── Auth ────────────────────────────────────────────────────
// NOTE: /auth/* wildcard is mounted by AuthProxyPlugin (cloud)
// or AuthPlugin (single-tenant) directly on the raw Hono app —
// those handlers can return native Web `Response` objects which
// is what better-auth produces. The dispatcher cannot represent
// a streaming Response cleanly through `IHttpServer.send`, so
// we deliberately do NOT register a dispatcher wildcard here.
//
// Legacy explicit /auth/login retained for self-hosted clients
// that still POST there; superseded by the wildcard above for
// the better-auth surface (sign-up/email, sign-in/email, …).
server.post(`${prefix}/auth/login`, async (req: any, res: any) => {
try {
const result = await dispatcher.handleAuth('login', 'POST', req.body, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
// ── GraphQL ─────────────────────────────────────────────────
server.post(`${prefix}/graphql`, async (req: any, res: any) => {
try {
const result = await dispatcher.handleGraphQL(req.body, { request: req });
if (securityHeaders) {
for (const [k, v] of Object.entries(securityHeaders)) {
res.header(k, v);
}
}
res.json(result);
} catch (err: any) {
errorResponse(err, res);
}
});
// ── Analytics ───────────────────────────────────────────────
// Route via dispatch() (not handleAnalytics directly) so the host
// dispatcher's project-aware kernel swap runs first — the per-project
// kernel owns the `analytics` service (registered by ObjectQLPlugin).
server.post(`${prefix}/analytics/query`, async (req: any, res: any) => {
try {
const result = await dispatcher.dispatch('POST', '/analytics/query', req.body, req.query, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
server.get(`${prefix}/analytics/meta`, async (req: any, res: any) => {
try {
const result = await dispatcher.dispatch('GET', '/analytics/meta', undefined, req.query, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
server.post(`${prefix}/analytics/sql`, async (req: any, res: any) => {
try {
const result = await dispatcher.dispatch('POST', '/analytics/sql', req.body, req.query, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
// ── MCP (Streamable HTTP) + API keys (ADR-0036) ─────────────
// Mounted explicitly (there is no catch-all) and routed through
// dispatch() so the host's project-aware kernel swap + execution
// context resolution run first. /mcp accepts POST (JSON-RPC), GET
// (SSE) and DELETE (session end) — the transport reads the method
// from the request, the dispatcher gates on OS_MCP_SERVER_ENABLED
// and the resolved principal. NOTE: the dispatch() branches alone
// are unreachable over HTTP without these registrations.
const mountMcp = (method: 'GET' | 'POST' | 'DELETE') => {
const register = method === 'GET' ? server.get : method === 'DELETE' ? server.delete : server.post;
register.call(server, `${prefix}/mcp`, async (req: any, res: any) => {
try {
const result = await dispatcher.dispatch(method, '/mcp', req.body, req.query, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
};
mountMcp('POST');
mountMcp('GET');
mountMcp('DELETE');
server.post(`${prefix}/keys`, async (req: any, res: any) => {
try {
const result = await dispatcher.dispatch('POST', '/keys', req.body, req.query, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
// ── Packages ────────────────────────────────────────────────
server.get(`${prefix}/packages`, async (req: any, res: any) => {
try {
const result = await dispatcher.handlePackages('', 'GET', {}, req.query, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
server.post(`${prefix}/packages`, async (req: any, res: any) => {
try {
const result = await dispatcher.handlePackages('', 'POST', req.body, {}, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
server.get(`${prefix}/packages/:id/export`, async (req: any, res: any) => {
try {
const result = await dispatcher.handlePackages(`/${req.params.id}/export`, 'GET', {}, req.query, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
server.get(`${prefix}/packages/:id`, async (req: any, res: any) => {
try {
const result = await dispatcher.handlePackages(`/${req.params.id}`, 'GET', {}, req.query, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
server.delete(`${prefix}/packages/:id`, async (req: any, res: any) => {
try {
const result = await dispatcher.handlePackages(`/${req.params.id}`, 'DELETE', {}, {}, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
server.patch(`${prefix}/packages/:id/enable`, async (req: any, res: any) => {
try {
const result = await dispatcher.handlePackages(`/${req.params.id}/enable`, 'PATCH', {}, {}, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
server.patch(`${prefix}/packages/:id/disable`, async (req: any, res: any) => {
try {
const result = await dispatcher.handlePackages(`/${req.params.id}/disable`, 'PATCH', {}, {}, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
server.post(`${prefix}/packages/:id/publish`, async (req: any, res: any) => {
try {
const result = await dispatcher.handlePackages(`/${req.params.id}/publish`, 'POST', req.body, {}, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
// ADR-0033 — publish every pending draft bound to a package ("publish
// whole app"). Distinct from /publish (which needs the metadata
// service): this promotes sys_metadata draft rows via the protocol.
server.post(`${prefix}/packages/:id/publish-drafts`, async (req: any, res: any) => {
try {
const result = await dispatcher.handlePackages(`/${req.params.id}/publish-drafts`, 'POST', req.body, {}, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
server.post(`${prefix}/packages/:id/revert`, async (req: any, res: any) => {
try {
const result = await dispatcher.handlePackages(`/${req.params.id}/revert`, 'POST', req.body, {}, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
// ── Storage ─────────────────────────────────────────────────
server.post(`${prefix}/storage/upload`, async (req: any, res: any) => {
try {
// For file uploads the body *is* the file (parsed by adapter)
const result = await dispatcher.handleStorage('upload', 'POST', req.body, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
server.get(`${prefix}/storage/file/:id`, async (req: any, res: any) => {
try {
const result = await dispatcher.handleStorage(`file/${req.params.id}`, 'GET', undefined, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
// ── i18n ────────────────────────────────────────────────────
// Route via dispatch() (not handleI18n directly) so the host
// dispatcher's project-aware kernel swap runs first. Without this,
// i18n requests hit the host kernel's in-memory fallback (which
// is always empty) instead of the per-project I18nServicePlugin
// populated by ArtifactKernelFactory with the artifact's
// translation bundles.
server.get(`${prefix}/i18n/locales`, async (req: any, res: any) => {
try {
const result = await dispatcher.dispatch('GET', '/i18n/locales', undefined, req.query, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
server.get(`${prefix}/i18n/translations/:locale`, async (req: any, res: any) => {
try {
const result = await dispatcher.dispatch('GET', `/i18n/translations/${req.params.locale}`, undefined, req.query, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
server.get(`${prefix}/i18n/labels/:object/:locale`, async (req: any, res: any) => {
try {
const result = await dispatcher.dispatch('GET', `/i18n/labels/${req.params.object}/${req.params.locale}`, undefined, req.query, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
// ── Automation ──────────────────────────────────────────────
// Registered at both `${prefix}/automation/...` and
// `${prefix}/environments/:environmentId/automation/...` when project
// scoping is enabled. Always dispatched through
// `dispatcher.dispatch()` so the multi-kernel host can swap
// to the per-project kernel before resolving the
// `automation` service (which lives on the project kernel,
// not the host kernel, in ObjectOS multi-tenant mode).
const registerAutomationRoutes = (base: string) => {
server!.get(`${base}/automation`, async (req: any, res: any) => {
try {
const result = await dispatcher.dispatch('GET', '/automation', undefined, req.query, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
server!.post(`${base}/automation`, async (req: any, res: any) => {
try {
const result = await dispatcher.dispatch('POST', '/automation', req.body, req.query, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
server!.get(`${base}/automation/:name`, async (req: any, res: any) => {
try {
const result = await dispatcher.dispatch('GET', `/automation/${req.params.name}`, undefined, req.query, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
server!.put(`${base}/automation/:name`, async (req: any, res: any) => {
try {
const result = await dispatcher.dispatch('PUT', `/automation/${req.params.name}`, req.body, req.query, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
server!.delete(`${base}/automation/:name`, async (req: any, res: any) => {
try {
const result = await dispatcher.dispatch('DELETE', `/automation/${req.params.name}`, undefined, req.query, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
server!.post(`${base}/automation/trigger/:name`, async (req: any, res: any) => {
try {
const result = await dispatcher.dispatch('POST', `/automation/trigger/${req.params.name}`, req.body, req.query, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
server!.post(`${base}/automation/:name/trigger`, async (req: any, res: any) => {
try {
const result = await dispatcher.dispatch('POST', `/automation/${req.params.name}/trigger`, req.body, req.query, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
server!.post(`${base}/automation/:name/toggle`, async (req: any, res: any) => {
try {
const result = await dispatcher.dispatch('POST', `/automation/${req.params.name}/toggle`, req.body, req.query, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
server!.get(`${base}/automation/:name/runs`, async (req: any, res: any) => {
try {
const result = await dispatcher.dispatch('GET', `/automation/${req.params.name}/runs`, undefined, req.query, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
server!.get(`${base}/automation/:name/runs/:runId`, async (req: any, res: any) => {
try {
const result = await dispatcher.dispatch('GET', `/automation/${req.params.name}/runs/${req.params.runId}`, undefined, req.query, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
// Screen-flow runtime (ADR-0019): resume a paused run with a
// screen node's collected input, and re-fetch its pending screen.
server!.post(`${base}/automation/:name/runs/:runId/resume`, async (req: any, res: any) => {
try {
const result = await dispatcher.dispatch('POST', `/automation/${req.params.name}/runs/${req.params.runId}/resume`, req.body, req.query, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
server!.get(`${base}/automation/:name/runs/:runId/screen`, async (req: any, res: any) => {
try {
const result = await dispatcher.dispatch('GET', `/automation/${req.params.name}/runs/${req.params.runId}/screen`, undefined, req.query, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
};
// ── AI / Assistants ─────────────────────────────────────────
// The AI service plugin registers a large, dynamic surface
// (chat, models, conversations, tools, agents, assistants)
// whose exact routes are built at start() time from the
// service's tool / agent registries. To support multi-tenant
// hosts where the AI service lives on per-project kernels,
// mount a method-wildcard catch-all that always dispatches
// through `dispatcher.dispatch()` — that triggers the kernel
// swap and then routes via `handleAI`, which looks up the
// AI service on the current (project) kernel.
const registerAIRoutes = (base: string) => {
const wildcards: Array<['get'|'post'|'delete'|'put', string]> = [
['get', `${base}/ai/*`],
['post', `${base}/ai/*`],
['delete', `${base}/ai/*`],
['put', `${base}/ai/*`],
];
for (const [method, pattern] of wildcards) {
(server as any) => {
try {
// Reconstruct the AI subpath without the prefix
// so dispatch() routes via the /ai branch.
const fullPath: string = req.path ?? '';
const idx = fullPath.lastIndexOf('/ai');
const aiSubPath = idx >= 0 ? fullPath.slice(idx) : '/ai';
const result = await dispatcher.dispatch(method.toUpperCase(), aiSubPath, req.body, req.query, { request: req });
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
}
};
// ── Actions (server-registered handlers, e.g. CRM convertLead) ───
// Bridges UI `script` / `modal` actions to ObjectQL handlers
// registered via `engine.registerAction(object, action, fn)`.
const registerActionRoutes = (base: string) => {
server!.post(`${base}/actions/:object/:action`, async (req: any, res: any) => {
try {
const ctx: any = { request: req };
if (req.params?.environmentId) ctx.environmentId = req.params.environmentId;
const result = await dispatcher.handleActions(`/${req.params.object}/${req.params.action}`, 'POST', req.body, ctx);
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
server!.post(`${base}/actions/:object/:action/:recordId`, async (req: any, res: any) => {
try {
const ctx: any = { request: req };
if (req.params?.environmentId) ctx.environmentId = req.params.environmentId;
const result = await dispatcher.handleActions(`/${req.params.object}/${req.params.action}/${req.params.recordId}`, 'POST', req.body, ctx);
sendResult(result, res);
} catch (err: any) {
errorResponse(err, res);
}
});
};
const enableProjectScoping = config.scoping?.enableProjectScoping ?? false;
const projectResolution = config.scoping?.projectResolution ?? 'auto';
if (enableProjectScoping && projectResolution === 'required') {
registerAutomationRoutes(`${prefix}/environments/:environmentId`);
registerActionRoutes(`${prefix}/environments/:environmentId`);
registerAIRoutes(`${prefix}/environments/:environmentId`);
} else {
registerAutomationRoutes(prefix);
registerActionRoutes(prefix);
registerAIRoutes(prefix);
if (enableProjectScoping) {
registerAutomationRoutes(`${prefix}/environments/:environmentId`);
registerActionRoutes(`${prefix}/environments/:environmentId`);
registerAIRoutes(`${prefix}/environments/:environmentId`);
}
}
ctx.logger.info('Dispatcher bridge routes registered', { prefix, enableProjectScoping, projectResolution });
// Resolve the authenticated user from a request's headers by
// delegating to the AuthService's `getSession` API (better-auth
// compatible). Returns a slim user shape that route handlers
// can rely on without touching the underlying auth provider.
//
// Defensive: any failure → undefined (anonymous). The route's
// `auth: true` guard still runs separately so unauthenticated
// hits to protected routes are rejected upstream.
const resolveRequestUser = async (headers: Record<string, any>): Promise<any | undefined> => {
try {
const authService: any = ctx.getService('auth');
if (!authService) return undefined;
let api: any = authService.api;
if (!api && typeof authService.getApi === 'function') {
api = await authService.getApi();
}
if (!api?.getSession) return undefined;
const headersInstance = headers instanceof Headers
? headers
: new Headers(headers as Record<string, string>);
const sessionData = await api.getSession({ headers: headersInstance });
const userId: string | undefined = sessionData?.user?.id ?? sessionData?.session?.userId;
if (!userId) return undefined;
// AI-route req.user permissions (incl. the synthesized `ai_seat`) are
// populated from the ExecutionContext by the /ai/* dispatch path
// (http-dispatcher → resolveExecutionContext, the single scope-correct
// source). This concrete-route resolver returns an empty set.
return {
userId,
id: userId,
displayName: sessionData?.user?.name ?? sessionData?.user?.email ?? userId,
email: sessionData?.user?.email,
roles: [],
permissions: [],
organizationId: sessionData?.session?.activeOrganizationId,
};
} catch {
return undefined;
}
};
// ── Dynamic service routes (AI, etc.) ───────────────────
// Listen for route definitions emitted by service plugins.
// The AIServicePlugin emits 'ai:routes' with RouteDefinition[].
//
// When environment-scoping is enabled, each AI route is mounted on
// BOTH `${prefix}${path}` and `${prefix}/environments/:environmentId${path}`
// (or only the scoped variant when `projectResolution === 'required'`).
const toScopedPath = (routePath: string): string => {
// routePath may already include /api/v1; splice /environments/:environmentId