@flowdular/sdk 0.1.0 → 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.
Files changed (174) hide show
  1. package/.ai/skills/test-hardening/SKILL.md +1 -1
  2. package/README.md +69 -12
  3. package/assets/flowdular-banner.png +0 -0
  4. package/modules/agents/package.json +1 -1
  5. package/modules/auth/package.json +1 -1
  6. package/modules/auth/src/client/AuthenticationCore.tsrx +3 -1
  7. package/modules/auth/src/server/endpoints.ts +3 -1
  8. package/modules/auth/src/server/runtime.ts +4 -0
  9. package/modules/automations/package.json +1 -1
  10. package/modules/automations-workflows-integration/package.json +1 -1
  11. package/modules/profile/package.json +1 -1
  12. package/modules/sandbox/package.json +1 -1
  13. package/modules/system/package.json +1 -1
  14. package/modules/users/package.json +1 -1
  15. package/modules/workflows/package.json +1 -1
  16. package/package.json +5 -13
  17. package/packages/ai-provider/package.json +1 -1
  18. package/packages/cli-protocol/package.json +1 -1
  19. package/packages/client/package.json +1 -1
  20. package/packages/client/src/routing.ts +39 -2
  21. package/packages/client/src/shell/BrandMark.tsrx +5 -1
  22. package/packages/client/src/shell/navigation.ts +3 -1
  23. package/packages/client/src/state.ts +6 -2
  24. package/packages/contracts/package.json +1 -1
  25. package/packages/contracts/schemas/project.schema.json +16 -42
  26. package/packages/database/package.json +1 -1
  27. package/packages/database-pglite/package.json +1 -1
  28. package/packages/database-testing/package.json +1 -1
  29. package/packages/dev-console/package.json +1 -1
  30. package/packages/harness/package.json +1 -1
  31. package/packages/kernel/package.json +1 -1
  32. package/packages/server/package.json +1 -1
  33. package/packages/server/src/application-routes.ts +80 -8
  34. package/packages/server/src/index.ts +4 -1
  35. package/packages/server/src/web-html.ts +9 -5
  36. package/packages/server/src/web.ts +59 -7
  37. package/packages/ui/package.json +1 -1
  38. package/packages/coding-agent/package.json +0 -44
  39. package/packages/coding-agent/src/drivers/byok.ts +0 -322
  40. package/packages/coding-agent/src/drivers/claude-code.ts +0 -290
  41. package/packages/coding-agent/src/drivers/codex.ts +0 -281
  42. package/packages/coding-agent/src/index.ts +0 -56
  43. package/packages/coding-agent/src/registry.ts +0 -119
  44. package/packages/coding-agent/src/roles/contract.ts +0 -60
  45. package/packages/coding-agent/src/roles/defaults.ts +0 -134
  46. package/packages/coding-agent/src/roles/handoff.ts +0 -41
  47. package/packages/coding-agent/src/roles/registry.ts +0 -156
  48. package/packages/coding-agent/src/roles/skills.ts +0 -72
  49. package/packages/coding-agent/src/roles/sync.ts +0 -88
  50. package/packages/coding-agent/src/types.ts +0 -102
  51. package/packages/coding-agent/src/workspace.ts +0 -275
  52. package/packages/sandbox/README.md +0 -691
  53. package/packages/sandbox/bin/flowdular-sandbox.mjs +0 -393
  54. package/packages/sandbox/dist/client/assets/App-ClMOrpyg.js +0 -11
  55. package/packages/sandbox/dist/client/assets/PreviewHost-BHiHrfbQ.js +0 -1
  56. package/packages/sandbox/dist/client/assets/auto-buGEq6de.js +0 -3
  57. package/packages/sandbox/dist/client/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
  58. package/packages/sandbox/dist/client/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
  59. package/packages/sandbox/dist/client/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
  60. package/packages/sandbox/dist/client/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
  61. package/packages/sandbox/dist/client/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
  62. package/packages/sandbox/dist/client/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
  63. package/packages/sandbox/dist/client/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
  64. package/packages/sandbox/dist/client/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
  65. package/packages/sandbox/dist/client/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
  66. package/packages/sandbox/dist/client/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
  67. package/packages/sandbox/dist/client/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
  68. package/packages/sandbox/dist/client/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
  69. package/packages/sandbox/dist/client/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
  70. package/packages/sandbox/dist/client/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
  71. package/packages/sandbox/dist/client/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
  72. package/packages/sandbox/dist/client/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
  73. package/packages/sandbox/dist/client/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
  74. package/packages/sandbox/dist/client/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
  75. package/packages/sandbox/dist/client/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
  76. package/packages/sandbox/dist/client/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
  77. package/packages/sandbox/dist/client/assets/ibm-plex-sans-cyrillic-ext-wght-normal-d45eAU9y.woff2 +0 -0
  78. package/packages/sandbox/dist/client/assets/ibm-plex-sans-cyrillic-wght-normal-BAAhND-U.woff2 +0 -0
  79. package/packages/sandbox/dist/client/assets/ibm-plex-sans-greek-wght-normal-CmyJS8uq.woff2 +0 -0
  80. package/packages/sandbox/dist/client/assets/ibm-plex-sans-latin-ext-wght-normal-CIII54If.woff2 +0 -0
  81. package/packages/sandbox/dist/client/assets/ibm-plex-sans-latin-wght-normal-IvpUvPa2.woff2 +0 -0
  82. package/packages/sandbox/dist/client/assets/ibm-plex-sans-vietnamese-wght-normal-Dg1JeJN0.woff2 +0 -0
  83. package/packages/sandbox/dist/client/assets/index-CvwhlQ87.js +0 -4
  84. package/packages/sandbox/dist/client/assets/styles-BPWaGf55.js +0 -3
  85. package/packages/sandbox/dist/client/assets/styles-Dx1_KOag.css +0 -1
  86. package/packages/sandbox/dist/client/favicon.svg +0 -1
  87. package/packages/sandbox/dist/server/assets/auto-CVGNYyb3.js +0 -12785
  88. package/packages/sandbox/dist/server/assets/chunk-DDJLRBDX-3OUNo51g.js +0 -4125
  89. package/packages/sandbox/dist/server/assets/nodefs-DVSI7kG0.js +0 -24
  90. package/packages/sandbox/dist/server/assets/opfs-ahp-D56iokt1.js +0 -388
  91. package/packages/sandbox/dist/server/assets/token-Bvaq7Anz.js +0 -55
  92. package/packages/sandbox/dist/server/assets/token-util-BqSvdIPQ.js +0 -3
  93. package/packages/sandbox/dist/server/assets/token-util-CktFFT4z.js +0 -494
  94. package/packages/sandbox/dist/server/entry.js +0 -91671
  95. package/packages/sandbox/dist/server/favicon.svg +0 -1
  96. package/packages/sandbox/dist/server/index.html +0 -161
  97. package/packages/sandbox/index.html +0 -159
  98. package/packages/sandbox/octane.config.ts +0 -36
  99. package/packages/sandbox/package.json +0 -83
  100. package/packages/sandbox/public/favicon.svg +0 -1
  101. package/packages/sandbox/public/og.png +0 -0
  102. package/packages/sandbox/src/App.tsrx +0 -924
  103. package/packages/sandbox/src/client/ApprovalHandoff.tsrx +0 -39
  104. package/packages/sandbox/src/client/ChatPane.tsrx +0 -694
  105. package/packages/sandbox/src/client/ConnectView.tsrx +0 -86
  106. package/packages/sandbox/src/client/DiffPane.tsrx +0 -150
  107. package/packages/sandbox/src/client/EjectModal.tsrx +0 -571
  108. package/packages/sandbox/src/client/GateResults.tsrx +0 -60
  109. package/packages/sandbox/src/client/GitHubSettingsModal.tsrx +0 -219
  110. package/packages/sandbox/src/client/NewSessionForm.tsrx +0 -214
  111. package/packages/sandbox/src/client/SessionBar.tsrx +0 -151
  112. package/packages/sandbox/src/client/SessionPicker.tsrx +0 -472
  113. package/packages/sandbox/src/client/SpecEditor.tsrx +0 -109
  114. package/packages/sandbox/src/client/SpecReviewCard.tsrx +0 -321
  115. package/packages/sandbox/src/client/WorkCard.tsrx +0 -128
  116. package/packages/sandbox/src/client/WorkbenchModal.tsrx +0 -161
  117. package/packages/sandbox/src/client/WorkspaceMenu.tsrx +0 -100
  118. package/packages/sandbox/src/client/api.ts +0 -797
  119. package/packages/sandbox/src/client/attachments.ts +0 -73
  120. package/packages/sandbox/src/client/dashboard.ts +0 -46
  121. package/packages/sandbox/src/client/github-settings.ts +0 -48
  122. package/packages/sandbox/src/client/highlight.ts +0 -105
  123. package/packages/sandbox/src/client/i18n.ts +0 -32
  124. package/packages/sandbox/src/client/locales/en.json +0 -466
  125. package/packages/sandbox/src/client/locales/pl.json +0 -466
  126. package/packages/sandbox/src/client/session-labels.ts +0 -77
  127. package/packages/sandbox/src/client/state.ts +0 -108
  128. package/packages/sandbox/src/index.ts +0 -10
  129. package/packages/sandbox/src/preview/PreviewHost.tsrx +0 -373
  130. package/packages/sandbox/src/preview/load-module.ts +0 -16
  131. package/packages/sandbox/src/server/attachments.ts +0 -308
  132. package/packages/sandbox/src/server/auto-review.ts +0 -181
  133. package/packages/sandbox/src/server/checkpoints.ts +0 -90
  134. package/packages/sandbox/src/server/config.ts +0 -460
  135. package/packages/sandbox/src/server/dashboard.ts +0 -245
  136. package/packages/sandbox/src/server/delivery/configuration.ts +0 -193
  137. package/packages/sandbox/src/server/delivery/git-pr.ts +0 -1473
  138. package/packages/sandbox/src/server/delivery/index.ts +0 -83
  139. package/packages/sandbox/src/server/delivery/local.ts +0 -151
  140. package/packages/sandbox/src/server/delivery/official-modules.ts +0 -516
  141. package/packages/sandbox/src/server/delivery/plan.ts +0 -218
  142. package/packages/sandbox/src/server/delivery/policies.ts +0 -239
  143. package/packages/sandbox/src/server/delivery/record.ts +0 -41
  144. package/packages/sandbox/src/server/delivery/steps.ts +0 -464
  145. package/packages/sandbox/src/server/delivery/types.ts +0 -158
  146. package/packages/sandbox/src/server/dependencies.ts +0 -88
  147. package/packages/sandbox/src/server/diff.ts +0 -230
  148. package/packages/sandbox/src/server/gates.ts +0 -388
  149. package/packages/sandbox/src/server/index.ts +0 -139
  150. package/packages/sandbox/src/server/path-guard.ts +0 -282
  151. package/packages/sandbox/src/server/planning.ts +0 -749
  152. package/packages/sandbox/src/server/platform-client.ts +0 -189
  153. package/packages/sandbox/src/server/preview-database-host.ts +0 -340
  154. package/packages/sandbox/src/server/preview-database-protocol.ts +0 -163
  155. package/packages/sandbox/src/server/preview-database-proxy.ts +0 -356
  156. package/packages/sandbox/src/server/preview-database.ts +0 -109
  157. package/packages/sandbox/src/server/preview-ipc.ts +0 -15
  158. package/packages/sandbox/src/server/preview-modules.ts +0 -83
  159. package/packages/sandbox/src/server/preview-revision.ts +0 -44
  160. package/packages/sandbox/src/server/preview-runtime.ts +0 -467
  161. package/packages/sandbox/src/server/preview-worker-manager.ts +0 -436
  162. package/packages/sandbox/src/server/preview-worker.ts +0 -168
  163. package/packages/sandbox/src/server/reference.ts +0 -251
  164. package/packages/sandbox/src/server/routes.ts +0 -2258
  165. package/packages/sandbox/src/server/runtime.ts +0 -188
  166. package/packages/sandbox/src/server/session-owner.ts +0 -23
  167. package/packages/sandbox/src/server/sessions.ts +0 -849
  168. package/packages/sandbox/src/server/spec.ts +0 -471
  169. package/packages/sandbox/src/server/turn-lifecycle.ts +0 -56
  170. package/packages/sandbox/src/server/turns.ts +0 -993
  171. package/packages/sandbox/src/server/workspace-install.ts +0 -266
  172. package/packages/sandbox/src/server/workspace-root.ts +0 -73
  173. package/packages/sandbox/src/styles.css +0 -1573
  174. package/packages/sandbox/vite.config.ts +0 -133
@@ -1,467 +0,0 @@
1
- import { randomBytes } from 'node:crypto';
2
- import { mkdir, readFile, stat, writeFile } from 'node:fs/promises';
3
- import { join } from 'node:path';
4
- import { pathToFileURL } from 'node:url';
5
- import type { ServerRoute } from '@octanejs/app-core';
6
- import { createRouter, type Router } from '@octanejs/app-core';
7
- import {
8
- createModuleSettingsRuntime,
9
- createPlatformAgentRegistry,
10
- createPlatformCapabilityRegistry,
11
- createPlatformToolRegistry,
12
- type ModuleSettingRecord,
13
- type ModuleSettingValue,
14
- type ModuleSettingsRuntime,
15
- type PlatformToolRegistry,
16
- } from '@flowdular/sdk/kernel';
17
- import {
18
- createAuthRoutes,
19
- createAuthRuntime,
20
- type AuthRuntime,
21
- type PlatformServerComposition,
22
- type PlatformServerContext,
23
- } from '@flowdular/sdk/modules/auth/server';
24
- import {
25
- modulePathOf,
26
- sessionPaths,
27
- type SandboxSession,
28
- type SessionModule,
29
- } from './sessions.ts';
30
- import type { DatabaseProvider } from '@flowdular/sdk/database';
31
- import { createIsolatedPreviewRuntime } from './preview-worker-manager.ts';
32
- import {
33
- resolvePreviewModules,
34
- type PreviewModuleSource,
35
- } from './preview-modules.ts';
36
- import { previewRevision } from './preview-revision.ts';
37
-
38
- export const PREVIEW_COOKIE = 'coreloom_preview';
39
- const PREVIEW_TENANT = 'Preview workspace';
40
- const PREVIEW_SLUG = 'preview';
41
- const PREVIEW_EMAIL = 'preview@sandbox.local';
42
-
43
- export interface PreviewCredentials {
44
- readonly email: string;
45
- readonly password: string;
46
- }
47
-
48
- export interface PreviewModuleComposition {
49
- readonly id: string;
50
- readonly directory: string;
51
- readonly routes: number;
52
- readonly hasClient: boolean;
53
- readonly error: string | null;
54
- readonly support?: boolean;
55
- }
56
-
57
- export interface PreviewComposition {
58
- readonly sessionId: string;
59
- readonly revision: string;
60
- readonly moduleId: string;
61
- readonly modules: readonly PreviewModuleComposition[];
62
- readonly auth: AuthRuntime;
63
- readonly credentials: PreviewCredentials;
64
- readonly router: Router;
65
- readonly routes: readonly ServerRoute[];
66
- readonly moduleScopes: readonly string[];
67
- readonly error: string | null;
68
- /* The parent invokes draft routes across the process boundary. */
69
- request(request: Request): Promise<Response>;
70
- /* Releases what the draft compositions hold (database handles, timers). */
71
- dispose(): void | Promise<void>;
72
- }
73
-
74
- interface DraftComposition extends PlatformServerComposition {
75
- readonly close?: () => void;
76
- }
77
-
78
- interface DraftModule {
79
- readonly createServerComposition?: (
80
- context: PlatformServerContext,
81
- ) => DraftComposition;
82
- }
83
-
84
- /* Preview settings live in memory for the life of the composition: a draft
85
- reads and writes them like the platform would, and nothing outlives the
86
- session. */
87
- function memorySettings(): ModuleSettingsRuntime {
88
- const records = new Map<string, ModuleSettingRecord>();
89
- const keyOf = (tenantId: string, moduleId: string, key: string) =>
90
- `${tenantId}\0${moduleId}\0${key}`;
91
- return createModuleSettingsRuntime({
92
- load: (tenantId, moduleId) => {
93
- const values: Record<string, ModuleSettingValue> = {};
94
- for (const record of records.values()) {
95
- if (record.tenantId === tenantId && record.moduleId === moduleId) {
96
- values[record.key] = record.value;
97
- }
98
- }
99
- return values;
100
- },
101
- save: (record) => {
102
- records.set(keyOf(record.tenantId, record.moduleId, record.key), record);
103
- },
104
- clear: (tenantId, moduleId, key) => {
105
- records.delete(keyOf(tenantId, moduleId, key));
106
- },
107
- });
108
- }
109
-
110
- interface DraftManifest {
111
- readonly moduleDefinition?: { readonly permissions?: readonly string[] };
112
- readonly permissions?: readonly string[];
113
- }
114
-
115
- async function exists(path: string): Promise<boolean> {
116
- try {
117
- await stat(path);
118
- return true;
119
- } catch {
120
- return false;
121
- }
122
- }
123
-
124
- /* Each session gets its own authentication runtime and database, so a preview
125
- runs with a real principal, real scopes, and a real CSRF contract instead of
126
- a stub. Everything lives inside the session directory and is thrown away
127
- with it. Sign-up stays closed: the only account is the one seeded here. */
128
- async function createPreviewAuth(
129
- databases: DatabaseProvider,
130
- session: SandboxSession,
131
- workspaceRoot: string,
132
- ): Promise<{ auth: AuthRuntime; credentials: PreviewCredentials }> {
133
- const paths = sessionPaths(workspaceRoot, session.id, session.moduleSuffix);
134
- const auth = createAuthRuntime({
135
- databases,
136
- secureCookies: false,
137
- cookieName: 'coreloom_preview_session',
138
- sessionTtlMs: 12 * 60 * 60 * 1000,
139
- allowSignUp: false,
140
- emailConfirmation: false,
141
- signInProviders: [],
142
- });
143
- /* A throwaway credential for one ephemeral preview database, kept beside it
144
- so the preview can sign in again after a reload. It never reaches the
145
- connected application. */
146
- const credentialPath = join(paths.data, 'preview-credentials.json');
147
- let credentials: PreviewCredentials;
148
- try {
149
- credentials = JSON.parse(
150
- await readFile(credentialPath, 'utf8'),
151
- ) as PreviewCredentials;
152
- } catch {
153
- credentials = {
154
- email: PREVIEW_EMAIL,
155
- password: `preview-${randomBytes(12).toString('base64url')}`,
156
- };
157
- await mkdir(paths.data, { recursive: true, mode: 0o700 });
158
- await writeFile(credentialPath, JSON.stringify(credentials), {
159
- encoding: 'utf8',
160
- mode: 0o600,
161
- });
162
- }
163
- if (!(await (await auth.service()).findAccountAccess(credentials.email))) {
164
- await (
165
- await auth.service()
166
- ).signUp({
167
- email: credentials.email,
168
- password: credentials.password,
169
- displayName: 'Sandbox preview',
170
- organizationName: PREVIEW_TENANT,
171
- organizationSlug: PREVIEW_SLUG,
172
- });
173
- }
174
- return { auth, credentials };
175
- }
176
-
177
- async function loadDraftComposition(
178
- session: SandboxSession,
179
- module: PreviewModuleSource,
180
- workspaceRoot: string,
181
- context: Omit<PlatformServerContext, 'workspaceRoot'>,
182
- revision: string,
183
- ): Promise<{
184
- readonly composition: DraftComposition | null;
185
- readonly moduleScopes: readonly string[];
186
- readonly hasClient: boolean;
187
- readonly error: string | null;
188
- }> {
189
- const paths = sessionPaths(workspaceRoot, session.id, session.moduleSuffix);
190
- const modulePath = module.path;
191
- const platformEntry = `${pathToFileURL(join(modulePath, 'src/platform.ts')).href}?revision=${revision}`;
192
- const indexEntry = `${pathToFileURL(join(modulePath, 'src/index.ts')).href}?revision=${revision}`;
193
- const hasClient = await exists(join(modulePath, 'src/client/index.ts'));
194
- try {
195
- const draft = (await import(platformEntry)) as DraftModule;
196
- if (!draft.createServerComposition) {
197
- return {
198
- composition: null,
199
- moduleScopes: [],
200
- hasClient,
201
- error: `${module.id} does not export createServerComposition from src/platform.ts yet.`,
202
- };
203
- }
204
- const composition = draft.createServerComposition({
205
- ...context,
206
- agentDefinitions: context.agentDefinitions.forModule(module.id),
207
- workspaceRoot: paths.root,
208
- });
209
- if (composition.settings) context.settings.declare(composition.settings);
210
- let moduleScopes: readonly string[] = [];
211
- try {
212
- const manifest = (await import(indexEntry)) as DraftManifest;
213
- moduleScopes =
214
- manifest.moduleDefinition?.permissions ?? manifest.permissions ?? [];
215
- } catch {
216
- moduleScopes = [];
217
- }
218
- return { composition, moduleScopes, hasClient, error: null };
219
- } catch (error) {
220
- return {
221
- composition: null,
222
- moduleScopes: [],
223
- hasClient,
224
- error:
225
- error instanceof Error
226
- ? `${module.id}: ${error.message.slice(0, 400)}`
227
- : `The ${module.id} server composition could not be loaded.`,
228
- };
229
- }
230
- }
231
-
232
- async function disposeAll(
233
- compositions: readonly DraftComposition[],
234
- ): Promise<void> {
235
- const reversed = [...compositions].reverse();
236
- for (const composition of reversed) {
237
- try {
238
- await composition.stop?.();
239
- } catch {
240
- /* Continue so one broken producer cannot leave the others running. */
241
- }
242
- }
243
- for (const composition of reversed) {
244
- try {
245
- await composition.dispose?.();
246
- composition.close?.();
247
- } catch {
248
- /* A draft that fails to release is the draft's bug; the preview must
249
- still move on to the next revision. */
250
- }
251
- }
252
- }
253
-
254
- /* A candidate preview is prepared as one generation. No draft may start until
255
- every prepare hook has passed and the previous generation has released its
256
- resources. A failed candidate cleans up only itself. */
257
- export async function activatePreviewDrafts(
258
- drafts: readonly DraftComposition[],
259
- retireCurrent: () => void | Promise<void>,
260
- ): Promise<readonly string[]> {
261
- try {
262
- for (const draft of drafts) await draft.prepare?.();
263
- } catch (error) {
264
- await disposeAll(drafts);
265
- throw error;
266
- }
267
-
268
- await retireCurrent();
269
- const errors: string[] = [];
270
- for (const draft of drafts) {
271
- try {
272
- draft.start?.();
273
- } catch (error) {
274
- errors.push(
275
- error instanceof Error
276
- ? error.message.slice(0, 400)
277
- : 'A draft start hook failed.',
278
- );
279
- }
280
- }
281
- return errors;
282
- }
283
-
284
- export interface PreviewRuntime {
285
- compose(session: SandboxSession): Promise<PreviewComposition>;
286
- cached(sessionId: string): PreviewComposition | null;
287
- forget(sessionId: string): void | Promise<void>;
288
- /* Releases every session worker and draft composition owned by this runtime. */
289
- dispose(): void;
290
- }
291
-
292
- /* The preview API is a composition, not a proxy: the draft modules' own routes
293
- answer first, the session's authentication routes answer next, and anything
294
- left over falls through to the connected application. */
295
- /* Called only by preview-worker.ts. Draft session source must not be imported
296
- into the long-lived sandbox server process. The caller owns `databases`: one
297
- engine per session, shared by the preview's own authentication and by every
298
- draft generation, because two engines over one data directory would fight. */
299
- export function createInProcessPreviewRuntime(
300
- workspaceRoot: string,
301
- databases: DatabaseProvider,
302
- ): PreviewRuntime {
303
- const compositions = new Map<string, PreviewComposition>();
304
-
305
- return {
306
- cached: (sessionId) => compositions.get(sessionId) ?? null,
307
- forget: (sessionId) => {
308
- void Promise.resolve(compositions.get(sessionId)?.dispose()).catch(
309
- () => undefined,
310
- );
311
- compositions.delete(sessionId);
312
- },
313
- dispose: () => {
314
- for (const composition of compositions.values()) {
315
- void Promise.resolve(composition.dispose()).catch(() => undefined);
316
- }
317
- compositions.clear();
318
- },
319
- compose: async (session) => {
320
- const paths = sessionPaths(
321
- workspaceRoot,
322
- session.id,
323
- session.moduleSuffix,
324
- );
325
- const sources = await resolvePreviewModules(workspaceRoot, session);
326
- const revision = await previewRevision(sources);
327
- const current = compositions.get(session.id);
328
- if (current && current.revision === revision) return current;
329
-
330
- const { auth, credentials } = current
331
- ? { auth: current.auth, credentials: current.credentials }
332
- : await createPreviewAuth(databases, session, workspaceRoot);
333
- const drafts: DraftComposition[] = [];
334
- const routes: ServerRoute[] = [];
335
- const moduleScopes = new Set<string>();
336
- const modules: PreviewModuleComposition[] = [];
337
- const errors: string[] = [];
338
- const agentDefinitions = createPlatformAgentRegistry();
339
- const context: Omit<PlatformServerContext, 'workspaceRoot'> = {
340
- environment: process.env,
341
- auth,
342
- settings: memorySettings(),
343
- agentTools: createPlatformToolRegistry() as PlatformToolRegistry,
344
- agentDefinitions,
345
- capabilities: createPlatformCapabilityRegistry(),
346
- databases,
347
- };
348
- for (const module of sources) {
349
- const draft = await loadDraftComposition(
350
- session,
351
- module,
352
- workspaceRoot,
353
- context,
354
- revision,
355
- );
356
- if (draft.composition) {
357
- drafts.push(draft.composition);
358
- routes.push(...draft.composition.routes);
359
- }
360
- for (const scope of draft.moduleScopes) moduleScopes.add(scope);
361
- if (draft.error) errors.push(draft.error);
362
- modules.push({
363
- id: module.id,
364
- support: module.support,
365
- directory: module.directory,
366
- routes: draft.composition?.routes.length ?? 0,
367
- hasClient: draft.hasClient,
368
- error: draft.error,
369
- });
370
- }
371
- agentDefinitions.seal();
372
-
373
- const account = await (
374
- await auth.service()
375
- ).findAccountAccess(credentials.email);
376
- if (account && moduleScopes.size > 0) {
377
- const tenant = account.tenants[0];
378
- if (tenant) {
379
- await (
380
- await auth.service()
381
- ).grantMembershipScopes(account.accountId, tenant.tenantId, [
382
- ...moduleScopes,
383
- ]);
384
- }
385
- }
386
-
387
- /* Preparation is generation-wide. The current preview stays alive when
388
- any candidate rejects its durable-state preflight. */
389
- try {
390
- errors.push(
391
- ...(await activatePreviewDrafts(drafts, () => current?.dispose())),
392
- );
393
- } catch (error) {
394
- if (!current) auth.dispose();
395
- throw error;
396
- }
397
- const all = [...routes, ...createAuthRoutes(auth)];
398
- const composition: PreviewComposition = {
399
- sessionId: session.id,
400
- revision,
401
- moduleId: session.moduleId,
402
- modules,
403
- auth,
404
- credentials,
405
- routes: all,
406
- router: createRouter([...all]),
407
- moduleScopes: [...moduleScopes],
408
- error: errors.length > 0 ? errors.join(' ') : null,
409
- request: async () =>
410
- new Response(
411
- JSON.stringify({
412
- error: {
413
- code: 'PREVIEW_WORKER_ONLY',
414
- message: 'Preview requests run in the isolated worker.',
415
- },
416
- }),
417
- { status: 500, headers: { 'content-type': 'application/json' } },
418
- ),
419
- /* The session engine outlives a generation, so retiring one releases
420
- the drafts and nothing else. */
421
- dispose: () => disposeAll(drafts),
422
- };
423
- compositions.set(session.id, composition);
424
- return composition;
425
- },
426
- };
427
- }
428
-
429
- export function createPreviewRuntime(workspaceRoot: string): PreviewRuntime {
430
- return createIsolatedPreviewRuntime(workspaceRoot);
431
- }
432
-
433
- interface ProcessPreviewSlot {
434
- readonly workspaceRoot: string;
435
- readonly runtime: PreviewRuntime;
436
- }
437
-
438
- const PROCESS_PREVIEW_SLOT = Symbol.for('flowdular.sandbox.preview-runtime');
439
-
440
- function processPreviewState(): Record<symbol, ProcessPreviewSlot | undefined> {
441
- return globalThis as unknown as Record<
442
- symbol,
443
- ProcessPreviewSlot | undefined
444
- >;
445
- }
446
-
447
- /* Octane reloads its server route configuration inside the same Vite process.
448
- A module-local runtime belongs to only one generation and its workers become
449
- unreachable when the next generation replaces the routes. Keep exactly one
450
- process-owned runtime instead. A workspace switch retires the previous one. */
451
- export function processPreviewRuntime(workspaceRoot: string): PreviewRuntime {
452
- const state = processPreviewState();
453
- const current = state[PROCESS_PREVIEW_SLOT];
454
- if (current?.workspaceRoot === workspaceRoot) return current.runtime;
455
- current?.runtime.dispose();
456
- const runtime = createPreviewRuntime(workspaceRoot);
457
- state[PROCESS_PREVIEW_SLOT] = { workspaceRoot, runtime };
458
- return runtime;
459
- }
460
-
461
- /* Tests and explicit host teardown can release the process singleton. Normal
462
- process exit also closes IPC, which makes every worker terminate itself. */
463
- export function disposeProcessPreviewRuntime(): void {
464
- const state = processPreviewState();
465
- state[PROCESS_PREVIEW_SLOT]?.runtime.dispose();
466
- delete state[PROCESS_PREVIEW_SLOT];
467
- }