@forgeax/engine-dsh 0.0.0-dev.8d955ade1c79

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 (45) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +63 -0
  3. package/cordis.patch.yml +5 -0
  4. package/dist/.tsbuildinfo +1 -0
  5. package/dist/__tests__/dsh-host.test.d.ts +16 -0
  6. package/dist/__tests__/dsh-host.test.d.ts.map +1 -0
  7. package/dist/__tests__/engine-host.test.d.ts +2 -0
  8. package/dist/__tests__/engine-host.test.d.ts.map +1 -0
  9. package/dist/__tests__/engine-preview.test.d.ts +2 -0
  10. package/dist/__tests__/engine-preview.test.d.ts.map +1 -0
  11. package/dist/__tests__/intelligence.test.d.ts +2 -0
  12. package/dist/__tests__/intelligence.test.d.ts.map +1 -0
  13. package/dist/__tests__/launch-binding-owner.test-d.d.ts +2 -0
  14. package/dist/__tests__/launch-binding-owner.test-d.d.ts.map +1 -0
  15. package/dist/__tests__/protocol.test.d.ts +2 -0
  16. package/dist/__tests__/protocol.test.d.ts.map +1 -0
  17. package/dist/client.d.ts +12 -0
  18. package/dist/client.d.ts.map +1 -0
  19. package/dist/embedded.d.ts +2 -0
  20. package/dist/embedded.d.ts.map +1 -0
  21. package/dist/embedded.mjs +220 -0
  22. package/dist/embedded.mjs.map +1 -0
  23. package/dist/engine-host.d.ts +43 -0
  24. package/dist/engine-host.d.ts.map +1 -0
  25. package/dist/engine-host.mjs +331 -0
  26. package/dist/engine-host.mjs.map +1 -0
  27. package/dist/engine-preview.d.ts +12 -0
  28. package/dist/engine-preview.d.ts.map +1 -0
  29. package/dist/engine-preview.mjs +70 -0
  30. package/dist/engine-preview.mjs.map +1 -0
  31. package/dist/index.d.ts +26 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.mjs +157 -0
  34. package/dist/index.mjs.map +1 -0
  35. package/dist/intelligence.d.ts +5 -0
  36. package/dist/intelligence.d.ts.map +1 -0
  37. package/dist/intelligence.mjs +60 -0
  38. package/dist/intelligence.mjs.map +1 -0
  39. package/dist/protocol.d.ts +59 -0
  40. package/dist/protocol.d.ts.map +1 -0
  41. package/dist/protocol.mjs +31 -0
  42. package/dist/protocol.mjs.map +1 -0
  43. package/lib/client.js +295 -0
  44. package/lib/client.js.map +1 -0
  45. package/package.json +103 -0
@@ -0,0 +1,220 @@
1
+ import { createServer } from 'http';
2
+ import { Context } from '@forgeax/engine-plugin';
3
+ import { randomUUID } from 'crypto';
4
+ import { World, createWorldContext, Update } from '@forgeax/engine-ecs';
5
+
6
+ // src/embedded.ts
7
+
8
+ // src/protocol.ts
9
+ var FEDERATION_PROTOCOL_VERSION = 1;
10
+ var FEDERATION_ROUTE_PREFIX = "/forgeax-federation/v1";
11
+
12
+ // src/index.ts
13
+ var inject = ["webServer"];
14
+ async function apply(ctx, config = {}) {
15
+ const identity = config.identity ?? `dsh-${randomUUID()}`;
16
+ const leases = /* @__PURE__ */ new Set();
17
+ let tick = 0;
18
+ let state = 0;
19
+ let embeddedContext;
20
+ let timer;
21
+ const disposers = [];
22
+ let disposed = false;
23
+ ctx.effect(
24
+ () => async () => {
25
+ if (disposed) return;
26
+ disposed = true;
27
+ for (const dispose of disposers.reverse()) dispose();
28
+ leases.clear();
29
+ if (timer !== void 0) clearInterval(timer);
30
+ await embeddedContext?.fiber.dispose();
31
+ },
32
+ "forgeax-federation: routes and embedded engine"
33
+ );
34
+ if (config.engineEndpoint === void 0) {
35
+ const world = new World();
36
+ embeddedContext = await createWorldContext(world);
37
+ world.addSystem(Update, {
38
+ name: "forgeax-federation-headless-tick",
39
+ queries: [],
40
+ fn: () => {
41
+ tick += 1;
42
+ }
43
+ }).unwrap();
44
+ timer = setInterval(() => {
45
+ const result = world.update(1 / 30);
46
+ if (!result.ok) ctx.logger.warn(result.error);
47
+ }, 1e3 / 30);
48
+ }
49
+ const status = () => ({
50
+ protocol: FEDERATION_PROTOCOL_VERSION,
51
+ identity,
52
+ ready: true,
53
+ realm: "dsh",
54
+ capabilities: ["lease", "community-probe", "engine-projection"],
55
+ leases: leases.size,
56
+ engine: config.engineEndpoint === void 0 ? { binding: "embedded", ready: true, frameId: tick, tick, state } : { binding: "external", endpoint: config.engineEndpoint, ready: true }
57
+ });
58
+ disposers.push(
59
+ ctx.webServer.register({
60
+ kind: "exact",
61
+ path: `${FEDERATION_ROUTE_PREFIX}/status`,
62
+ handler(_request, response) {
63
+ writeJson(response, 200, status());
64
+ }
65
+ }),
66
+ ctx.webServer.register({
67
+ kind: "exact",
68
+ path: `${FEDERATION_ROUTE_PREFIX}/activity`,
69
+ async handler(request, response) {
70
+ if (request.method !== "POST") {
71
+ writeJson(response, 405, { code: "federation-method-not-allowed" });
72
+ return;
73
+ }
74
+ const candidate = ctx.get("forgeaxIntelligenceCapability");
75
+ if (candidate === void 0 || typeof candidate.run !== "function") {
76
+ writeJson(response, 404, { code: "federation-intelligence-capability-missing" });
77
+ return;
78
+ }
79
+ const body = await readJsonBody(request);
80
+ if (typeof body !== "object" || body === null || typeof Reflect.get(body, "input") !== "string" || typeof Reflect.get(body, "sessionId") !== "string") {
81
+ writeJson(response, 400, { code: "federation-activity-invalid" });
82
+ return;
83
+ }
84
+ writeJson(
85
+ response,
86
+ 200,
87
+ await candidate.run(Reflect.get(body, "input"), Reflect.get(body, "sessionId"))
88
+ );
89
+ }
90
+ }),
91
+ ctx.webServer.register({
92
+ kind: "exact",
93
+ path: `${FEDERATION_ROUTE_PREFIX}/lease`,
94
+ handler(request, response) {
95
+ if (request.method === "POST") {
96
+ const leaseId = randomUUID();
97
+ leases.add(leaseId);
98
+ writeJson(response, 201, { leaseId });
99
+ return;
100
+ }
101
+ if (request.method === "DELETE") {
102
+ const leaseId = new URL(request.url ?? "/", "http://localhost").searchParams.get(
103
+ "leaseId"
104
+ );
105
+ if (leaseId !== null) leases.delete(leaseId);
106
+ writeJson(response, 200, { released: leaseId !== null });
107
+ return;
108
+ }
109
+ writeJson(response, 405, { code: "federation-method-not-allowed" });
110
+ }
111
+ }),
112
+ ctx.webServer.register({
113
+ kind: "exact",
114
+ path: `${FEDERATION_ROUTE_PREFIX}/community`,
115
+ async handler(_request, response) {
116
+ const candidate = ctx.get("forgeaxFederationCapability");
117
+ if (candidate === void 0 || typeof candidate.inspect !== "function") {
118
+ writeJson(response, 404, { code: "federation-community-capability-missing" });
119
+ return;
120
+ }
121
+ writeJson(response, 200, await candidate.inspect());
122
+ }
123
+ }),
124
+ ctx.webServer.register({
125
+ kind: "exact",
126
+ path: `${FEDERATION_ROUTE_PREFIX}/engine/control`,
127
+ handler(request, response) {
128
+ if (request.method !== "POST" || config.engineEndpoint !== void 0) {
129
+ writeJson(response, 409, { code: "federation-engine-control-unavailable" });
130
+ return;
131
+ }
132
+ state = state === 0 ? 1 : 0;
133
+ writeJson(response, 200, status().engine);
134
+ }
135
+ })
136
+ );
137
+ }
138
+ async function readJsonBody(request) {
139
+ const chunks = [];
140
+ let size = 0;
141
+ for await (const chunk of request) {
142
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
143
+ size += buffer.byteLength;
144
+ if (size > 65536) throw new Error("federation request exceeds 65536 bytes");
145
+ chunks.push(buffer);
146
+ }
147
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
148
+ }
149
+ function writeJson(response, status, value) {
150
+ response.writeHead(status, {
151
+ "cache-control": "no-store",
152
+ "content-type": "application/json; charset=utf-8"
153
+ });
154
+ response.end(JSON.stringify(value));
155
+ }
156
+
157
+ // src/embedded.ts
158
+ var EmbeddedWebServer = class {
159
+ routes = /* @__PURE__ */ new Set();
160
+ register(route) {
161
+ this.routes.add(route);
162
+ return () => this.routes.delete(route);
163
+ }
164
+ match(pathname) {
165
+ return [...this.routes].find(
166
+ (route) => route.kind === "exact" ? pathname === route.path : pathname === route.path || pathname.startsWith(`${route.path}/`)
167
+ );
168
+ }
169
+ };
170
+ var routes = new EmbeddedWebServer();
171
+ var server = createServer((request, response) => {
172
+ const pathname = new URL(request.url ?? "/", "http://localhost").pathname;
173
+ const route = routes.match(pathname);
174
+ if (route === void 0) {
175
+ response.writeHead(404);
176
+ response.end();
177
+ return;
178
+ }
179
+ Promise.resolve(route.handler(request, response)).catch(() => {
180
+ if (!response.headersSent) response.writeHead(500);
181
+ response.end();
182
+ });
183
+ });
184
+ await new Promise((resolve, reject) => {
185
+ server.once("error", reject);
186
+ server.listen(0, "127.0.0.1", () => resolve());
187
+ });
188
+ var context = new Context();
189
+ var carrier = {
190
+ name: "embedded-webserver",
191
+ provide: "webServer",
192
+ apply(ctx) {
193
+ const provide = ctx.provide;
194
+ provide.call(ctx, "webServer", routes);
195
+ }
196
+ };
197
+ await context.plugin(carrier);
198
+ await context.plugin({
199
+ name: "forgeax-federation",
200
+ inject,
201
+ apply
202
+ });
203
+ var address = server.address();
204
+ process.stdout.write(`forgeax embedded: http://127.0.0.1:${address.port}
205
+ `);
206
+ var closing = false;
207
+ var close = async () => {
208
+ if (closing) return;
209
+ closing = true;
210
+ await context.fiber.dispose();
211
+ await new Promise((resolve) => server.close(() => resolve()));
212
+ };
213
+ process.once("SIGTERM", () => {
214
+ void close().then(() => process.exit(0));
215
+ });
216
+ process.once("SIGINT", () => {
217
+ void close().then(() => process.exit(0));
218
+ });
219
+ //# sourceMappingURL=embedded.mjs.map
220
+ //# sourceMappingURL=embedded.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/protocol.ts","../src/index.ts","../src/embedded.ts"],"names":[],"mappings":";;;;;;;;AAAO,IAAM,2BAAA,GAA8B,CAAA;AACpC,IAAM,uBAAA,GAA0B,wBAAA;;;AC8ChC,IAAM,MAAA,GAAS,CAAC,WAAW,CAAA;AAGlC,eAAsB,KAAA,CAAM,GAAA,EAAqB,MAAA,GAAiB,EAAC,EAAkB;AACnF,EAAA,MAAM,QAAA,GAAW,MAAA,CAAO,QAAA,IAAY,CAAA,IAAA,EAAO,YAAY,CAAA,CAAA;AACvD,EAAA,MAAM,MAAA,uBAAa,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1' as const;\n\nexport type FederationBinding = 'attach' | 'external' | 'embedded';\nexport type FederationOwnership = 'lease' | 'instance';\n\nexport interface FederationStatus {\n readonly protocol: typeof FEDERATION_PROTOCOL_VERSION;\n readonly identity: string;\n readonly ready: true;\n readonly realm: 'dsh';\n readonly capabilities: readonly string[];\n readonly leases: number;\n readonly engine: EngineProjection;\n}\n\nexport type EngineProjection = EngineEndpointProjection | EmbeddedEngineProjection;\n\nexport interface EngineEndpointProjection {\n readonly binding: 'external';\n readonly endpoint: string;\n readonly ready: true;\n}\n\nexport interface EmbeddedEngineProjection {\n readonly binding: 'embedded';\n readonly ready: true;\n readonly frameId: number;\n readonly tick: number;\n readonly state: number;\n}\n\nexport interface FederationLease {\n readonly leaseId: string;\n}\n\nexport interface FederationCommunityCapability {\n readonly id: string;\n readonly value: string;\n}\n\nexport interface FederationActivityResult {\n readonly output: string;\n}\n\nexport interface EnginePreviewStatus {\n readonly protocol: typeof FEDERATION_PROTOCOL_VERSION;\n readonly kind: 'forgeax-engine-status';\n readonly binding: 'external';\n readonly ready: true;\n readonly frameId: number;\n readonly tick: number;\n readonly state: number;\n}\n\nexport interface EnginePreviewPoll {\n readonly protocol: typeof FEDERATION_PROTOCOL_VERSION;\n readonly kind: 'forgeax-engine-poll';\n}\n\nexport interface EnginePreviewControl {\n readonly protocol: typeof FEDERATION_PROTOCOL_VERSION;\n readonly kind: 'forgeax-engine-control';\n readonly action: 'toggle';\n}\n\nexport type EnginePreviewRequest = EnginePreviewPoll | EnginePreviewControl;\n\nexport function isEnginePreviewRequest(value: unknown): value is EnginePreviewRequest {\n if (typeof value !== 'object' || value === null) return false;\n const record = value as Record<string, unknown>;\n if (record.protocol !== FEDERATION_PROTOCOL_VERSION) return false;\n if (record.kind === 'forgeax-engine-poll') return true;\n return record.kind === 'forgeax-engine-control' && record.action === 'toggle';\n}\n\nexport function isEnginePreviewStatus(value: unknown): value is EnginePreviewStatus {\n if (typeof value !== 'object' || value === null) return false;\n const record = value as Record<string, unknown>;\n return (\n record.protocol === FEDERATION_PROTOCOL_VERSION &&\n record.kind === 'forgeax-engine-status' &&\n record.binding === 'external' &&\n record.ready === true &&\n typeof record.frameId === 'number' &&\n typeof record.tick === 'number' &&\n typeof record.state === 'number'\n );\n}\n\nexport function isFederationStatus(value: unknown): value is FederationStatus {\n if (typeof value !== 'object' || value === null) return false;\n const record = value as Record<string, unknown>;\n return (\n record.protocol === FEDERATION_PROTOCOL_VERSION &&\n record.realm === 'dsh' &&\n record.ready === true &&\n typeof record.identity === 'string' &&\n Array.isArray(record.capabilities) &&\n record.capabilities.every((capability) => typeof capability === 'string') &&\n Number.isInteger(record.leases) &&\n (record.leases as number) >= 0 &&\n isEngineProjection(record.engine)\n );\n}\n\nfunction isEngineProjection(value: unknown): value is EngineProjection {\n if (typeof value !== 'object' || value === null) return false;\n const record = value as Record<string, unknown>;\n if (record.ready !== true) return false;\n if (record.binding === 'external') return typeof record.endpoint === 'string';\n return (\n record.binding === 'embedded' &&\n typeof record.frameId === 'number' &&\n typeof record.tick === 'number' &&\n typeof record.state === 'number'\n );\n}\n","import { randomUUID } from 'node:crypto';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\n\nimport { createWorldContext, Update, World } from '@forgeax/engine-ecs';\nimport type { Context } from '@forgeax/engine-plugin';\n\nimport {\n FEDERATION_PROTOCOL_VERSION,\n FEDERATION_ROUTE_PREFIX,\n type FederationActivityResult,\n type FederationCommunityCapability,\n type FederationStatus,\n} from './protocol';\n\ninterface WebRoute {\n readonly kind: 'exact' | 'prefix';\n readonly path: string;\n readonly handler: (request: IncomingMessage, response: ServerResponse) => void | Promise<void>;\n}\n\ninterface WebServerService {\n register(route: WebRoute): () => void;\n}\n\ninterface DshHostContext {\n readonly webServer: WebServerService;\n readonly logger: { warn(error: unknown): void };\n effect(callback: () => void | (() => void | Promise<void>), label?: string): void;\n get(name: string): unknown;\n}\n\ninterface CommunityProbeService {\n inspect(): FederationCommunityCapability | Promise<FederationCommunityCapability>;\n}\n\ninterface IntelligenceCapabilityService {\n run(\n input: string,\n sessionId: string,\n ): FederationActivityResult | Promise<FederationActivityResult>;\n}\n\nexport interface Config {\n readonly engineEndpoint?: string;\n readonly identity?: string;\n}\n\nexport const inject = ['webServer'];\n\n/** DSH-native Host half. DSH's Loader mounts this ordinary plugin from the package patch. */\nexport async function apply(ctx: DshHostContext, config: Config = {}): Promise<void> {\n const identity = config.identity ?? `dsh-${randomUUID()}`;\n const leases = new Set<string>();\n let tick = 0;\n let state = 0;\n let embeddedContext: Context | undefined;\n let timer: ReturnType<typeof setInterval> | undefined;\n const disposers: Array<() => void> = [];\n let disposed = false;\n\n ctx.effect(\n () => async () => {\n if (disposed) return;\n disposed = true;\n for (const dispose of disposers.reverse()) dispose();\n leases.clear();\n if (timer !== undefined) clearInterval(timer);\n await embeddedContext?.fiber.dispose();\n },\n 'forgeax-federation: routes and embedded engine',\n );\n\n if (config.engineEndpoint === undefined) {\n const world = new World();\n embeddedContext = await createWorldContext(world);\n world\n .addSystem(Update, {\n name: 'forgeax-federation-headless-tick',\n queries: [],\n fn: () => {\n tick += 1;\n },\n })\n .unwrap();\n timer = setInterval(() => {\n const result = world.update(1 / 30);\n if (!result.ok) ctx.logger.warn(result.error);\n }, 1000 / 30);\n }\n\n const status = (): FederationStatus => ({\n protocol: FEDERATION_PROTOCOL_VERSION,\n identity,\n ready: true,\n realm: 'dsh',\n capabilities: ['lease', 'community-probe', 'engine-projection'],\n leases: leases.size,\n engine:\n config.engineEndpoint === undefined\n ? { binding: 'embedded', ready: true, frameId: tick, tick, state }\n : { binding: 'external', endpoint: config.engineEndpoint, ready: true },\n });\n\n disposers.push(\n ctx.webServer.register({\n kind: 'exact',\n path: `${FEDERATION_ROUTE_PREFIX}/status`,\n handler(_request, response) {\n writeJson(response, 200, status());\n },\n }),\n ctx.webServer.register({\n kind: 'exact',\n path: `${FEDERATION_ROUTE_PREFIX}/activity`,\n async handler(request, response) {\n if (request.method !== 'POST') {\n writeJson(response, 405, { code: 'federation-method-not-allowed' });\n return;\n }\n const candidate = ctx.get('forgeaxIntelligenceCapability') as\n | IntelligenceCapabilityService\n | undefined;\n if (candidate === undefined || typeof candidate.run !== 'function') {\n writeJson(response, 404, { code: 'federation-intelligence-capability-missing' });\n return;\n }\n const body = await readJsonBody(request);\n if (\n typeof body !== 'object' ||\n body === null ||\n typeof Reflect.get(body, 'input') !== 'string' ||\n typeof Reflect.get(body, 'sessionId') !== 'string'\n ) {\n writeJson(response, 400, { code: 'federation-activity-invalid' });\n return;\n }\n writeJson(\n response,\n 200,\n await candidate.run(Reflect.get(body, 'input'), Reflect.get(body, 'sessionId')),\n );\n },\n }),\n ctx.webServer.register({\n kind: 'exact',\n path: `${FEDERATION_ROUTE_PREFIX}/lease`,\n handler(request, response) {\n if (request.method === 'POST') {\n const leaseId = randomUUID();\n leases.add(leaseId);\n writeJson(response, 201, { leaseId });\n return;\n }\n if (request.method === 'DELETE') {\n const leaseId = new URL(request.url ?? '/', 'http://localhost').searchParams.get(\n 'leaseId',\n );\n if (leaseId !== null) leases.delete(leaseId);\n writeJson(response, 200, { released: leaseId !== null });\n return;\n }\n writeJson(response, 405, { code: 'federation-method-not-allowed' });\n },\n }),\n ctx.webServer.register({\n kind: 'exact',\n path: `${FEDERATION_ROUTE_PREFIX}/community`,\n async handler(_request, response) {\n const candidate = ctx.get('forgeaxFederationCapability') as\n | CommunityProbeService\n | undefined;\n if (candidate === undefined || typeof candidate.inspect !== 'function') {\n writeJson(response, 404, { code: 'federation-community-capability-missing' });\n return;\n }\n writeJson(response, 200, await candidate.inspect());\n },\n }),\n ctx.webServer.register({\n kind: 'exact',\n path: `${FEDERATION_ROUTE_PREFIX}/engine/control`,\n handler(request, response) {\n if (request.method !== 'POST' || config.engineEndpoint !== undefined) {\n writeJson(response, 409, { code: 'federation-engine-control-unavailable' });\n return;\n }\n state = state === 0 ? 1 : 0;\n writeJson(response, 200, status().engine);\n },\n }),\n );\n}\n\nasync function readJsonBody(request: IncomingMessage): Promise<unknown> {\n const chunks: Buffer[] = [];\n let size = 0;\n for await (const chunk of request) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n size += buffer.byteLength;\n if (size > 65_536) throw new Error('federation request exceeds 65536 bytes');\n chunks.push(buffer);\n }\n return JSON.parse(Buffer.concat(chunks).toString('utf8')) as unknown;\n}\n\nfunction writeJson(response: ServerResponse, status: number, value: unknown): void {\n response.writeHead(status, {\n 'cache-control': 'no-store',\n 'content-type': 'application/json; charset=utf-8',\n });\n response.end(JSON.stringify(value));\n}\n","import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';\nimport type { AddressInfo } from 'node:net';\n\nimport { Context, type Plugin } from '@forgeax/engine-plugin';\n\nimport { apply as federationApply, inject as federationInject } from './index';\n\ninterface Route {\n readonly kind: 'exact' | 'prefix';\n readonly path: string;\n readonly handler: (request: IncomingMessage, response: ServerResponse) => void | Promise<void>;\n}\n\nclass EmbeddedWebServer {\n private readonly routes = new Set<Route>();\n\n register(route: Route): () => void {\n this.routes.add(route);\n return () => this.routes.delete(route);\n }\n\n match(pathname: string): Route | undefined {\n return [...this.routes].find((route) =>\n route.kind === 'exact'\n ? pathname === route.path\n : pathname === route.path || pathname.startsWith(`${route.path}/`),\n );\n }\n}\n\nconst routes = new EmbeddedWebServer();\nconst server = createServer((request, response) => {\n const pathname = new URL(request.url ?? '/', 'http://localhost').pathname;\n const route = routes.match(pathname);\n if (route === undefined) {\n response.writeHead(404);\n response.end();\n return;\n }\n Promise.resolve(route.handler(request, response)).catch(() => {\n if (!response.headersSent) response.writeHead(500);\n response.end();\n });\n});\n\nawait new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(0, '127.0.0.1', () => resolve());\n});\n\nconst context = new Context();\nconst carrier: Plugin = {\n name: 'embedded-webserver',\n provide: 'webServer',\n apply(ctx) {\n const provide = ctx.provide as unknown as (name: string, value: unknown) => void;\n provide.call(ctx, 'webServer', routes);\n },\n};\nawait context.plugin(carrier);\nawait context.plugin({\n name: 'forgeax-federation',\n inject: federationInject,\n apply: federationApply as unknown as Plugin['apply'],\n});\n\nconst address = server.address() as AddressInfo;\nprocess.stdout.write(`forgeax embedded: http://127.0.0.1:${address.port}\\n`);\n\nlet closing = false;\nconst close = async (): Promise<void> => {\n if (closing) return;\n closing = true;\n await context.fiber.dispose();\n await new Promise<void>((resolve) => server.close(() => resolve()));\n};\n\nprocess.once('SIGTERM', () => {\n void close().then(() => process.exit(0));\n});\nprocess.once('SIGINT', () => {\n void close().then(() => process.exit(0));\n});\n"]}
@@ -0,0 +1,43 @@
1
+ import type { Plugin } from '@forgeax/engine-plugin';
2
+ import { type Result } from '@forgeax/engine-types';
3
+ import { type FederationActivityResult, type FederationBinding, type FederationCommunityCapability, type FederationOwnership, type FederationStatus } from './protocol';
4
+ declare module '@forgeax/engine-plugin' {
5
+ interface EngineContextServices {
6
+ dshRealm: DshRealmConnection;
7
+ }
8
+ }
9
+ export type DshRealmErrorCode = 'dsh-target-unavailable' | 'dsh-target-incompatible' | 'dsh-launch-failed' | 'dsh-handshake-timeout' | 'dsh-lease-failed' | 'dsh-community-failed';
10
+ export declare class DshRealmError extends Error {
11
+ readonly code: DshRealmErrorCode;
12
+ readonly expected: string;
13
+ readonly hint: string;
14
+ readonly detail: Readonly<Record<string, unknown>>;
15
+ constructor(code: DshRealmErrorCode, expected: string, hint: string, detail: Readonly<Record<string, unknown>>, cause?: unknown);
16
+ }
17
+ export interface DshRealmPluginOptions {
18
+ /** Attach to an already-running compatible DSH realm. Never closes that realm. */
19
+ readonly endpoint?: string;
20
+ /** Explicit DSH executable. Omit to discover `dsh` on PATH. */
21
+ readonly executable?: string;
22
+ readonly profile?: string;
23
+ readonly home?: string;
24
+ readonly cwd?: string;
25
+ readonly handshakeTimeoutMs?: number;
26
+ readonly allowEmbedded?: boolean;
27
+ }
28
+ export interface DshRealmConnection {
29
+ readonly endpoint: string;
30
+ readonly binding: FederationBinding;
31
+ readonly ownership: FederationOwnership;
32
+ readonly status: FederationStatus;
33
+ community(): Promise<FederationCommunityCapability>;
34
+ activity(input: string, sessionId: string, signal?: AbortSignal): Promise<FederationActivityResult>;
35
+ }
36
+ export interface ConnectedRealm {
37
+ readonly connection: DshRealmConnection;
38
+ dispose(): Promise<void>;
39
+ }
40
+ /** Engine-side Realm Host Plugin. It publishes no service until handshake and lease acquisition succeed. */
41
+ export declare function dshRealmPlugin(options?: DshRealmPluginOptions): Plugin;
42
+ export declare function connectDshRealm(options?: DshRealmPluginOptions): Promise<Result<ConnectedRealm, DshRealmError>>;
43
+ //# sourceMappingURL=engine-host.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine-host.d.ts","sourceRoot":"","sources":["../src/engine-host.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAW,KAAK,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAE7D,OAAO,EAGL,KAAK,wBAAwB,EAC7B,KAAK,iBAAiB,EACtB,KAAK,6BAA6B,EAElC,KAAK,mBAAmB,EACxB,KAAK,gBAAgB,EAEtB,MAAM,YAAY,CAAC;AAEpB,OAAO,QAAQ,wBAAwB,CAAC;IACtC,UAAU,qBAAqB;QAC7B,QAAQ,EAAE,kBAAkB,CAAC;KAC9B;CACF;AAED,MAAM,MAAM,iBAAiB,GACzB,wBAAwB,GACxB,yBAAyB,GACzB,mBAAmB,GACnB,uBAAuB,GACvB,kBAAkB,GAClB,sBAAsB,CAAC;AAE3B,qBAAa,aAAc,SAAQ,KAAK;IACtC,QAAQ,CAAC,IAAI,EAAE,iBAAiB,CAAC;IACjC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;gBAGjD,IAAI,EAAE,iBAAiB,E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,MAAM,CAAC,cAAc,EAAE,aAAa,CAAC,CAAC,CAehD"}
@@ -0,0 +1,331 @@
1
+ import { spawn } from 'child_process';
2
+ import { access } from 'fs/promises';
3
+ import { delimiter, join } from 'path';
4
+ import { fileURLToPath } from 'url';
5
+ import { ok, err } from '@forgeax/engine-types';
6
+
7
+ // src/engine-host.ts
8
+
9
+ // src/protocol.ts
10
+ var FEDERATION_PROTOCOL_VERSION = 1;
11
+ var FEDERATION_ROUTE_PREFIX = "/forgeax-federation/v1";
12
+ function isFederationStatus(value) {
13
+ if (typeof value !== "object" || value === null) return false;
14
+ const record = value;
15
+ return record.protocol === FEDERATION_PROTOCOL_VERSION && record.realm === "dsh" && record.ready === true && typeof record.identity === "string" && Array.isArray(record.capabilities) && record.capabilities.every((capability) => typeof capability === "string") && Number.isInteger(record.leases) && record.leases >= 0 && isEngineProjection(record.engine);
16
+ }
17
+ function isEngineProjection(value) {
18
+ if (typeof value !== "object" || value === null) return false;
19
+ const record = value;
20
+ if (record.ready !== true) return false;
21
+ if (record.binding === "external") return typeof record.endpoint === "string";
22
+ return record.binding === "embedded" && typeof record.frameId === "number" && typeof record.tick === "number" && typeof record.state === "number";
23
+ }
24
+
25
+ // src/engine-host.ts
26
+ var DshRealmError = class extends Error {
27
+ code;
28
+ expected;
29
+ hint;
30
+ detail;
31
+ constructor(code, expected, hint, detail, cause) {
32
+ super(`${code}: ${expected}`, cause === void 0 ? void 0 : { cause });
33
+ this.name = "DshRealmError";
34
+ this.code = code;
35
+ this.expected = expected;
36
+ this.hint = hint;
37
+ this.detail = detail;
38
+ }
39
+ };
40
+ function dshRealmPlugin(options = {}) {
41
+ return {
42
+ name: "dsh-realm",
43
+ provide: "dshRealm",
44
+ async apply(ctx) {
45
+ const result = await connectDshRealm(options);
46
+ if (!result.ok) throw result.error;
47
+ const connected = result.value;
48
+ ctx.effect(() => () => connected.dispose(), "dsh-realm: binding ownership");
49
+ ctx.provide("dshRealm", connected.connection);
50
+ }
51
+ };
52
+ }
53
+ async function connectDshRealm(options = {}) {
54
+ try {
55
+ return ok(await resolveDshRealm(options));
56
+ } catch (cause) {
57
+ if (cause instanceof DshRealmError) return err(cause);
58
+ return err(
59
+ new DshRealmError(
60
+ "dsh-launch-failed",
61
+ "the DSH realm binding to initialize",
62
+ "Inspect the selected endpoint, executable, profile, and process diagnostics.",
63
+ { binding: options.endpoint === void 0 ? "launch" : "attach" },
64
+ cause
65
+ )
66
+ );
67
+ }
68
+ }
69
+ async function resolveDshRealm(options) {
70
+ const timeoutMs = options.handshakeTimeoutMs ?? 1e4;
71
+ if (options.endpoint !== void 0) {
72
+ return attach(options.endpoint, timeoutMs);
73
+ }
74
+ const executable = options.executable === void 0 ? await discoverOnPath("dsh") : options.executable;
75
+ if (executable !== void 0) {
76
+ return launchExternal(executable, options, timeoutMs);
77
+ }
78
+ if (options.allowEmbedded === false) {
79
+ throw new DshRealmError(
80
+ "dsh-target-unavailable",
81
+ "a compatible explicit endpoint or local dsh executable",
82
+ "Install DeepSeek Harness, pass executable/endpoint, or allow the packaged minimum fallback.",
83
+ { binding: "external" }
84
+ );
85
+ }
86
+ return launchEmbedded(timeoutMs);
87
+ }
88
+ async function attach(endpoint, timeoutMs) {
89
+ const normalized = normalizeEndpoint(endpoint);
90
+ const status = await waitForStatus(normalized, timeoutMs, "attach");
91
+ const leaseId = await acquireLease(normalized);
92
+ let disposed = false;
93
+ return {
94
+ connection: connection(normalized, "attach", "lease", status),
95
+ async dispose() {
96
+ if (disposed) return;
97
+ disposed = true;
98
+ await releaseLease(normalized, leaseId);
99
+ }
100
+ };
101
+ }
102
+ async function launchExternal(executable, options, timeoutMs) {
103
+ const args = ["--profile", options.profile ?? "web", "--host", "127.0.0.1", "--port", "0"];
104
+ const child = spawn(executable, args, {
105
+ cwd: options.cwd,
106
+ env: {
107
+ ...process.env,
108
+ ...options.home === void 0 ? {} : { DSH_HOME: options.home }
109
+ }
110
+ });
111
+ return finishLaunch(child, "external", timeoutMs, executable);
112
+ }
113
+ async function launchEmbedded(timeoutMs) {
114
+ const entry = fileURLToPath(new URL("./embedded.mjs", import.meta.url));
115
+ const child = spawn(process.execPath, [entry], { env: process.env });
116
+ return finishLaunch(child, "embedded", timeoutMs, entry);
117
+ }
118
+ async function finishLaunch(child, binding, timeoutMs, target) {
119
+ try {
120
+ const endpoint = await readLaunchEndpoint(child, timeoutMs, target);
121
+ const status = await waitForStatus(endpoint, timeoutMs, binding);
122
+ const leaseId = await acquireLease(endpoint);
123
+ let disposed = false;
124
+ return {
125
+ connection: connection(endpoint, binding, "instance", status),
126
+ async dispose() {
127
+ if (disposed) return;
128
+ disposed = true;
129
+ await releaseLease(endpoint, leaseId).catch(() => void 0);
130
+ await stopChild(child);
131
+ }
132
+ };
133
+ } catch (error) {
134
+ await stopChild(child);
135
+ throw error;
136
+ }
137
+ }
138
+ function connection(endpoint, binding, ownership, status) {
139
+ return {
140
+ endpoint,
141
+ binding,
142
+ ownership,
143
+ status,
144
+ async community() {
145
+ const response = await fetch(`${endpoint}${FEDERATION_ROUTE_PREFIX}/community`);
146
+ if (!response.ok) {
147
+ throw new DshRealmError(
148
+ "dsh-community-failed",
149
+ "the DSH-native community capability to answer through the bridge",
150
+ "Install and enable a DSH plugin that provides forgeaxFederationCapability.",
151
+ { endpoint, status: response.status }
152
+ );
153
+ }
154
+ return await response.json();
155
+ },
156
+ async activity(input, sessionId, signal) {
157
+ const response = await fetch(`${endpoint}${FEDERATION_ROUTE_PREFIX}/activity`, {
158
+ method: "POST",
159
+ headers: { "content-type": "application/json" },
160
+ body: JSON.stringify({ input, sessionId }),
161
+ ...signal === void 0 ? {} : { signal }
162
+ });
163
+ if (!response.ok) {
164
+ throw new DshRealmError(
165
+ "dsh-community-failed",
166
+ "a DSH-native intelligence capability to answer through the bridge",
167
+ "Install and enable a DSH plugin that provides forgeaxIntelligenceCapability.",
168
+ { endpoint, status: response.status }
169
+ );
170
+ }
171
+ const value = await response.json();
172
+ if (typeof value.output !== "string") {
173
+ throw new DshRealmError(
174
+ "dsh-community-failed",
175
+ "the DSH intelligence bridge to return text output",
176
+ "Use a capability plugin compatible with federation protocol 1.",
177
+ { endpoint, received: value }
178
+ );
179
+ }
180
+ return { output: value.output };
181
+ }
182
+ };
183
+ }
184
+ async function waitForStatus(endpoint, timeoutMs, binding) {
185
+ const deadline = Date.now() + timeoutMs;
186
+ let last;
187
+ while (Date.now() < deadline) {
188
+ try {
189
+ const response = await fetch(`${endpoint}${FEDERATION_ROUTE_PREFIX}/status`);
190
+ if (response.ok) {
191
+ const value = await response.json();
192
+ if (!isFederationStatus(value) || value.protocol !== FEDERATION_PROTOCOL_VERSION) {
193
+ throw new DshRealmError(
194
+ "dsh-target-incompatible",
195
+ `DSH federation protocol ${FEDERATION_PROTOCOL_VERSION}`,
196
+ "Use a connector version that matches this Engine package.",
197
+ { binding, endpoint, received: value }
198
+ );
199
+ }
200
+ return value;
201
+ }
202
+ last = response.status;
203
+ } catch (error) {
204
+ if (error instanceof DshRealmError) throw error;
205
+ last = error;
206
+ }
207
+ await new Promise((resolve) => setTimeout(resolve, 50));
208
+ }
209
+ throw new DshRealmError(
210
+ "dsh-handshake-timeout",
211
+ `a ready federation endpoint within ${timeoutMs}ms`,
212
+ "Install @forgeax/engine-dsh into the selected DSH profile and inspect its native Loader diagnostics.",
213
+ { binding, endpoint, last }
214
+ );
215
+ }
216
+ async function acquireLease(endpoint) {
217
+ const response = await fetch(`${endpoint}${FEDERATION_ROUTE_PREFIX}/lease`, { method: "POST" });
218
+ if (!response.ok) {
219
+ throw new DshRealmError(
220
+ "dsh-lease-failed",
221
+ "a lease-scoped bridge activation",
222
+ "The target must support lease acquisition and release before attach is safe.",
223
+ { endpoint, status: response.status }
224
+ );
225
+ }
226
+ const lease = await response.json();
227
+ if (typeof lease.leaseId !== "string") {
228
+ throw new DshRealmError(
229
+ "dsh-lease-failed",
230
+ "a string leaseId",
231
+ "Update the target connector to the matching protocol version.",
232
+ { endpoint, received: lease }
233
+ );
234
+ }
235
+ return lease.leaseId;
236
+ }
237
+ async function releaseLease(endpoint, leaseId) {
238
+ await fetch(
239
+ `${endpoint}${FEDERATION_ROUTE_PREFIX}/lease?leaseId=${encodeURIComponent(leaseId)}`,
240
+ { method: "DELETE" }
241
+ );
242
+ }
243
+ function readLaunchEndpoint(child, timeoutMs, target) {
244
+ return new Promise((resolve, reject) => {
245
+ let output = "";
246
+ const timer = setTimeout(() => {
247
+ cleanup();
248
+ reject(
249
+ new DshRealmError(
250
+ "dsh-launch-failed",
251
+ "the launched realm to print its loopback URL",
252
+ "Inspect the native DSH startup and Loader diagnostics.",
253
+ { target, output }
254
+ )
255
+ );
256
+ }, timeoutMs);
257
+ const onData = (chunk) => {
258
+ output += chunk.toString("utf8");
259
+ const matched = output.match(/(?:dsh web|forgeax embedded):\s+(http:\/\/127\.0\.0\.1:\d+)/);
260
+ if (matched?.[1] === void 0) return;
261
+ cleanup();
262
+ resolve(matched[1]);
263
+ };
264
+ const onExit = (code) => {
265
+ cleanup();
266
+ reject(
267
+ new DshRealmError(
268
+ "dsh-launch-failed",
269
+ "the launched realm to remain alive through readiness",
270
+ "Inspect the native process output and profile composition.",
271
+ { target, code, output }
272
+ )
273
+ );
274
+ };
275
+ const onError = (cause) => {
276
+ cleanup();
277
+ reject(
278
+ new DshRealmError(
279
+ "dsh-launch-failed",
280
+ "the selected DSH executable to start",
281
+ "Pass an executable file that can launch the selected native DSH profile.",
282
+ { target, output },
283
+ cause
284
+ )
285
+ );
286
+ };
287
+ const cleanup = () => {
288
+ clearTimeout(timer);
289
+ child.stdout.off("data", onData);
290
+ child.stderr.off("data", onData);
291
+ child.off("exit", onExit);
292
+ child.off("error", onError);
293
+ };
294
+ child.stdout.on("data", onData);
295
+ child.stderr.on("data", onData);
296
+ child.once("exit", onExit);
297
+ child.once("error", onError);
298
+ });
299
+ }
300
+ async function stopChild(child) {
301
+ if (child.exitCode !== null || child.signalCode !== null) return;
302
+ const exited = new Promise((resolve) => child.once("exit", () => resolve()));
303
+ child.kill("SIGTERM");
304
+ const graceful = await Promise.race([
305
+ exited.then(() => true),
306
+ new Promise((resolve) => setTimeout(() => resolve(false), 2e3))
307
+ ]);
308
+ if (!graceful && child.exitCode === null) {
309
+ child.kill("SIGKILL");
310
+ await exited;
311
+ }
312
+ }
313
+ async function discoverOnPath(name) {
314
+ const paths = process.env.PATH?.split(delimiter) ?? [];
315
+ for (const directory of paths) {
316
+ const candidate = join(directory, name);
317
+ try {
318
+ await access(candidate);
319
+ return candidate;
320
+ } catch {
321
+ }
322
+ }
323
+ return void 0;
324
+ }
325
+ function normalizeEndpoint(endpoint) {
326
+ return endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
327
+ }
328
+
329
+ export { DshRealmError, connectDshRealm, dshRealmPlugin };
330
+ //# sourceMappingURL=engine-host.mjs.map
331
+ //# sourceMappingURL=engine-host.mjs.map