gencow 0.1.299 → 0.2.1

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 (151) hide show
  1. package/bin/gencow.mjs +0 -6
  2. package/core/package.json +1 -1
  3. package/docs/packaging.md +14 -4
  4. package/lib/cli-artifact-guard.mjs +53 -3
  5. package/lib/cli-dev-runtime.mjs +1 -0
  6. package/lib/cli-project-runtime.mjs +26 -14
  7. package/lib/codegen-command.mjs +16 -0
  8. package/lib/coding-guardrails.mjs +2 -0
  9. package/lib/dashboard-artifact.mjs +65 -0
  10. package/lib/dashboard-assets.mjs +20 -0
  11. package/lib/db-command.mjs +121 -80
  12. package/lib/db-migration-command-steps.mjs +19 -16
  13. package/lib/db-push-command.mjs +1 -1
  14. package/lib/deploy-codegen-preflight.mjs +1 -0
  15. package/lib/dev-cloud-command.mjs +1 -1
  16. package/lib/dev-local-command.mjs +19 -56
  17. package/lib/document-local-converter.mjs +11 -0
  18. package/lib/local-dashboard-plan.mjs +60 -0
  19. package/lib/local-database-commands.mjs +127 -0
  20. package/lib/local-development-migrations.mjs +157 -0
  21. package/lib/local-drizzle-database.config.mjs +10 -0
  22. package/lib/local-runtime-features.mjs +12 -0
  23. package/lib/rag-selection.mjs +7 -0
  24. package/lib/runtime-local-worker.mjs +116 -0
  25. package/lib/runtime-mode.mjs +3 -0
  26. package/lib/standalone-codegen-adapter.mjs +91 -0
  27. package/lib/ts-codegen-import-extension.mjs +228 -19
  28. package/package.json +15 -8
  29. package/runtime/config.mjs +218 -2
  30. package/runtime/engine/chunk-2HA4CUMS.mjs +90 -0
  31. package/runtime/engine/chunk-2JLO3KMM.mjs +305 -0
  32. package/runtime/engine/chunk-2SR2M7SR.mjs +1045 -0
  33. package/runtime/engine/chunk-3D7MHEUC.mjs +253 -0
  34. package/runtime/engine/chunk-3R7COBWG.mjs +309 -0
  35. package/runtime/engine/chunk-3ZKA54UW.mjs +1560 -0
  36. package/runtime/engine/chunk-45I4YR2J.mjs +9 -0
  37. package/runtime/engine/chunk-4MLRXO7F.mjs +74 -0
  38. package/runtime/engine/chunk-5575APCJ.mjs +215 -0
  39. package/runtime/engine/chunk-5GUJZQF3.mjs +114 -0
  40. package/runtime/engine/chunk-5MXY3T75.mjs +428 -0
  41. package/runtime/engine/chunk-5TACQ2US.mjs +44 -0
  42. package/runtime/engine/chunk-66G4YEDT.mjs +3104 -0
  43. package/runtime/engine/chunk-67YO53WW.mjs +1426 -0
  44. package/runtime/engine/chunk-6GQRM7XY.mjs +87 -0
  45. package/runtime/engine/chunk-6JO72SPP.mjs +68 -0
  46. package/runtime/engine/chunk-6W653LXI.mjs +13 -0
  47. package/runtime/engine/chunk-7ITSMI3S.mjs +69 -0
  48. package/runtime/engine/chunk-7KUJ2H2S.mjs +128 -0
  49. package/runtime/engine/chunk-A5BMQ5IC.mjs +45 -0
  50. package/runtime/engine/chunk-ADF3UR6L.mjs +428 -0
  51. package/runtime/engine/chunk-AEBW7XZJ.mjs +4510 -0
  52. package/runtime/engine/chunk-AGPQ5XIV.mjs +156 -0
  53. package/runtime/engine/chunk-CPU4OZSX.mjs +753 -0
  54. package/runtime/engine/chunk-CSWPPWBL.mjs +50 -0
  55. package/runtime/engine/chunk-DPWXSMWO.mjs +53 -0
  56. package/runtime/engine/chunk-EAIELFKU.mjs +151 -0
  57. package/runtime/engine/chunk-EDU5CBKT.mjs +10 -0
  58. package/runtime/engine/chunk-EQCTAET7.mjs +173 -0
  59. package/runtime/engine/chunk-EQCXDF2Z.mjs +70 -0
  60. package/runtime/engine/chunk-F3G4UGV4.mjs +330 -0
  61. package/runtime/engine/chunk-F62NUNOO.mjs +26 -0
  62. package/runtime/engine/chunk-FKPNIFRP.mjs +2492 -0
  63. package/runtime/engine/chunk-FM23RGVI.mjs +81 -0
  64. package/runtime/engine/chunk-FW5AK4YP.mjs +1041 -0
  65. package/runtime/engine/chunk-GDWYAGWV.mjs +23 -0
  66. package/runtime/engine/chunk-GO5PZUYW.mjs +53 -0
  67. package/runtime/engine/chunk-GOLP7OSG.mjs +340 -0
  68. package/runtime/engine/chunk-GSLM44EF.mjs +242 -0
  69. package/runtime/engine/chunk-GYAJ7OX2.mjs +125 -0
  70. package/runtime/engine/chunk-I3GWR43K.mjs +14 -0
  71. package/runtime/engine/chunk-IFMOTJNU.mjs +106 -0
  72. package/runtime/engine/chunk-IKQKBE2G.mjs +128 -0
  73. package/runtime/engine/chunk-ITH2NEKM.mjs +282 -0
  74. package/runtime/engine/chunk-J6SDRCG4.mjs +96 -0
  75. package/runtime/engine/chunk-JODRNM3S.mjs +29596 -0
  76. package/runtime/engine/chunk-JUDKX53X.mjs +137 -0
  77. package/runtime/engine/chunk-K2YZVPJ4.mjs +827 -0
  78. package/runtime/engine/chunk-KEZJUXEE.mjs +151 -0
  79. package/runtime/engine/chunk-KVLTJFCH.mjs +234 -0
  80. package/runtime/engine/chunk-KX2PRQPS.mjs +126 -0
  81. package/runtime/engine/chunk-LEW5ZMLR.mjs +76 -0
  82. package/runtime/engine/chunk-LINVSJEM.mjs +175 -0
  83. package/runtime/engine/chunk-M7K2ICSM.mjs +11 -0
  84. package/runtime/engine/chunk-MZXDXSDC.mjs +292 -0
  85. package/runtime/engine/chunk-N2TA2IK2.mjs +678 -0
  86. package/runtime/engine/chunk-N4LTCKJP.mjs +695 -0
  87. package/runtime/engine/chunk-N6GCLOUX.mjs +13 -0
  88. package/runtime/engine/chunk-NAG2OXS5.mjs +37 -0
  89. package/runtime/engine/chunk-NNZ2QJUG.mjs +381 -0
  90. package/runtime/engine/chunk-NZPPLDNW.mjs +15 -0
  91. package/runtime/engine/chunk-ODWM57W6.mjs +138 -0
  92. package/runtime/engine/chunk-P5IIXAIE.mjs +23 -0
  93. package/runtime/engine/chunk-PBOXB2BV.mjs +6 -0
  94. package/runtime/engine/chunk-PMOJLN2P.mjs +8 -0
  95. package/runtime/engine/chunk-PZFMKFHO.mjs +180 -0
  96. package/runtime/engine/chunk-QL2TQX2N.mjs +114 -0
  97. package/runtime/engine/chunk-RITT2RSJ.mjs +258 -0
  98. package/runtime/engine/chunk-RODBVJ5M.mjs +135 -0
  99. package/runtime/engine/chunk-RW65MPVY.mjs +261 -0
  100. package/runtime/engine/chunk-S67UYPB6.mjs +25 -0
  101. package/runtime/engine/chunk-SVJCOUI3.mjs +47 -0
  102. package/runtime/engine/chunk-TCN3ZASV.mjs +957 -0
  103. package/runtime/engine/chunk-U2NRG6KC.mjs +32 -0
  104. package/runtime/engine/chunk-UM3F7HUV.mjs +432 -0
  105. package/runtime/engine/chunk-VWU7JJ3P.mjs +146 -0
  106. package/runtime/engine/chunk-WDTKPPMU.mjs +310 -0
  107. package/runtime/engine/chunk-WJOO4XTB.mjs +31 -0
  108. package/runtime/engine/chunk-XNFVL2OY.mjs +63 -0
  109. package/runtime/engine/chunk-XPWJXP2J.mjs +58 -0
  110. package/runtime/engine/chunk-Y3HSBJ3I.mjs +1132 -0
  111. package/runtime/engine/chunk-YMH4RYSX.mjs +317 -0
  112. package/runtime/engine/chunk-YNOMPSGS.mjs +8 -0
  113. package/runtime/engine/chunk-YRBAYTEZ.mjs +251 -0
  114. package/runtime/engine/chunk-YRHM272W.mjs +528 -0
  115. package/runtime/engine/chunk-ZQUZAGIQ.mjs +149 -0
  116. package/runtime/engine/chunk-ZXMM7QFP.mjs +176 -0
  117. package/runtime/engine/chunk-ZZJSIPV2.mjs +262 -0
  118. package/runtime/engine/composition.mjs +325 -0
  119. package/runtime/engine/document-local.mjs +504 -0
  120. package/runtime/engine/graph.json +4134 -0
  121. package/runtime/engine/index.mjs +265 -0
  122. package/runtime/engine/local-postgres-support.mjs +69 -0
  123. package/runtime/engine/local.mjs +3275 -0
  124. package/runtime/engine/pglite-directory-lock.mjs +8 -0
  125. package/runtime/engine/rag.mjs +11 -0
  126. package/runtime/engine/search.mjs +18 -0
  127. package/runtime/framework-migrations/foundation-bootstrap/rag.sql +115 -0
  128. package/runtime/framework-migrations/foundation-bootstrap/workflow.sql +194 -0
  129. package/runtime/framework-migrations/journal-bootstrap/migration.sql +26 -0
  130. package/runtime/framework-migrations/manifest.json +56 -0
  131. package/runtime/framework-migrations/rag/20261006111509_mushy_warhawk/migration.sql +121 -0
  132. package/runtime/framework-migrations/rag/20261013234621_rag_v2_lifecycle_markers/migration.sql +6 -0
  133. package/runtime/framework-migrations/workflow/20261006111508_perpetual_star_brand/migration.sql +31 -0
  134. package/runtime/runtime-metadata.json +27 -0
  135. package/runtime/tooling.mjs +10399 -8951
  136. package/scripts/bundle-runtime-config.mjs +23 -0
  137. package/scripts/bundle-runtime.mjs +100 -0
  138. package/scripts/bundle-runtime.test.mjs +33 -0
  139. package/scripts/bundle-shared.mjs +3 -0
  140. package/scripts/copy-dashboard.mjs +16 -0
  141. package/scripts/pre-publish-check.mjs +23 -11
  142. package/templateFeature/ai/ai-facade.ts +38 -15
  143. package/templateFeature/ai/manifest.json +1 -0
  144. package/templateFeature/sso/sso-auth-callback.tsx +37 -5
  145. package/templateFeature/tools/manifest.json +5 -2
  146. package/templateFeature/tools/tools.ts +3 -3
  147. package/runtime/server.mjs +0 -14389
  148. package/scripts/bundle-server.mjs +0 -223
  149. package/server/config.js +0 -1
  150. package/server/index.js +0 -1
  151. package/server/package.json +0 -6
@@ -0,0 +1,253 @@
1
+ import {
2
+ runtimeDatabaseSetupError
3
+ } from "./chunk-SVJCOUI3.mjs";
4
+
5
+ // ../runtime/dist/database-setup/plan.js
6
+ import { isDeepStrictEqual } from "node:util";
7
+ function invalid() {
8
+ throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_COMPONENT_INVALID");
9
+ }
10
+ function identifier(value) {
11
+ return typeof value === "string" && value.length > 0 && Buffer.byteLength(value) <= 63 && !/[\u0000-\u001f\u007f]/u.test(value);
12
+ }
13
+ function declarationId(value) {
14
+ return typeof value === "string" && /^[a-z][a-z0-9-]{0,62}$/u.test(value);
15
+ }
16
+ function list(values, valid, nonempty = false) {
17
+ if (!Array.isArray(values) || nonempty && values.length === 0 || values.some((value) => !valid(value)))
18
+ invalid();
19
+ }
20
+ function distinct(values) {
21
+ if (new Set(values).size !== values.length)
22
+ invalid();
23
+ }
24
+ function constraint(value) {
25
+ if (!value || !["primary", "unique", "foreign"].includes(value.kind))
26
+ invalid();
27
+ list(value.columns, identifier, true);
28
+ distinct(value.columns);
29
+ if (value.creationIndexName !== void 0 && (value.kind === "foreign" || !identifier(value.creationIndexName)))
30
+ invalid();
31
+ if (value.kind === "foreign") {
32
+ if (!value.target || !identifier(value.target.schema) || !identifier(value.target.table))
33
+ invalid();
34
+ list(value.target.columns, identifier, true);
35
+ if (value.columns.length !== value.target.columns.length || !["a", "r", "c", "n", "d"].includes(value.target.deleteAction) || value.target.updateAction !== void 0 && !["a", "r", "c", "n", "d"].includes(value.target.updateAction))
36
+ invalid();
37
+ } else if (value.target !== void 0)
38
+ invalid();
39
+ }
40
+ function object(value) {
41
+ if (!value || !identifier(value.schema))
42
+ invalid();
43
+ if (value.kind !== "sequence" || value.name !== void 0) {
44
+ if (!identifier(value.name))
45
+ invalid();
46
+ }
47
+ switch (value.kind) {
48
+ case "table":
49
+ if (value.rowSecurity !== void 0 && typeof value.rowSecurity !== "boolean" || value.forceRowSecurity !== void 0 && typeof value.forceRowSecurity !== "boolean")
50
+ invalid();
51
+ list(value.columns, (column) => Boolean(column && identifier(column.name) && typeof column.type === "string" && column.type.length > 0 && typeof column.nullable === "boolean" && (column.defaultValue === null || typeof column.defaultValue === "string")), true);
52
+ distinct(value.columns.map((column) => column.name));
53
+ list(value.constraints, (entry) => {
54
+ constraint(entry);
55
+ return entry.columns.every((name) => value.columns.some((column) => column.name === name));
56
+ });
57
+ break;
58
+ case "index":
59
+ if (!identifier(value.table) || value.predicate !== null && typeof value.predicate !== "string")
60
+ invalid();
61
+ list(value.keys, (key) => typeof key === "string" && key.length > 0, true);
62
+ list(value.descending, (key) => value.keys.includes(key));
63
+ break;
64
+ case "sequence":
65
+ if (!identifier(value.table) || !identifier(value.column))
66
+ invalid();
67
+ if (value.creationName !== void 0 && !identifier(value.creationName))
68
+ invalid();
69
+ break;
70
+ case "constraint":
71
+ if (!identifier(value.table))
72
+ invalid();
73
+ constraint(value.contract);
74
+ break;
75
+ case "function":
76
+ if (value.language !== "plpgsql" || value.returnType !== "trigger" || value.securityDefiner !== false || typeof value.body !== "string" || !value.body.trim())
77
+ invalid();
78
+ list(value.configuration, (setting) => typeof setting === "string" && setting.length > 0);
79
+ break;
80
+ case "trigger":
81
+ if (!identifier(value.table) || !identifier(value.functionSchema) || !identifier(value.functionName) || value.type !== 5 || typeof value.deferrable !== "boolean" || typeof value.initiallyDeferred !== "boolean" || value.enabled !== "A" || value.argumentCount !== 0 || value.predicate !== null)
82
+ invalid();
83
+ break;
84
+ default:
85
+ invalid();
86
+ }
87
+ if (value.kind === "table" || value.kind === "sequence") {
88
+ list(value.paths, (path) => path === "application" || path === "maintenance", true);
89
+ list(value.privileges, (privilege) => (value.kind === "sequence" ? ["USAGE", "SELECT"] : ["SELECT", "INSERT", "UPDATE", "DELETE"]).includes(privilege), true);
90
+ distinct(value.paths);
91
+ distinct(value.privileges);
92
+ }
93
+ }
94
+ function ownershipKey(value) {
95
+ if (value.kind === "constraint")
96
+ return JSON.stringify(["constraint", value.schema, value.table, value.name]);
97
+ if (value.kind === "trigger")
98
+ return JSON.stringify(["trigger", value.schema, value.table, value.name]);
99
+ if (value.kind === "function")
100
+ return JSON.stringify(["function", value.schema, value.name, "()"]);
101
+ if (value.kind === "sequence" && value.name === void 0)
102
+ return JSON.stringify(["owned-sequence", value.schema, value.table, value.column]);
103
+ return JSON.stringify(["relation", value.schema, value.name]);
104
+ }
105
+ function freeze(value, seen = /* @__PURE__ */ new WeakSet()) {
106
+ if (value && typeof value === "object" && !seen.has(value)) {
107
+ seen.add(value);
108
+ for (const child of Object.values(value))
109
+ freeze(child, seen);
110
+ Object.freeze(value);
111
+ }
112
+ return value;
113
+ }
114
+ function captureRuntimeDatabaseSchemaComponents(input) {
115
+ if (!Array.isArray(input))
116
+ invalid();
117
+ const selected = /* @__PURE__ */ new Map();
118
+ const owners = /* @__PURE__ */ new Set();
119
+ const sequenceOwners = /* @__PURE__ */ new Set();
120
+ for (const entry of input) {
121
+ if (!entry || !declarationId(entry.id) || selected.has(entry.id) || !Number.isSafeInteger(entry.contractVersion) || entry.contractVersion < 1 || typeof entry.inspect !== "function")
122
+ invalid();
123
+ list(entry.dependsOn, declarationId);
124
+ distinct(entry.dependsOn);
125
+ list(entry.objects, (value) => {
126
+ object(value);
127
+ return true;
128
+ });
129
+ const own = /* @__PURE__ */ new Map();
130
+ for (const value of entry.objects) {
131
+ const key = ownershipKey(value);
132
+ if (owners.has(key))
133
+ invalid();
134
+ owners.add(key);
135
+ own.set(key, value);
136
+ const creationNames = value.kind === "table" ? value.constraints.flatMap((constraint2) => constraint2.creationIndexName ? [constraint2.creationIndexName] : []) : value.kind === "sequence" && value.creationName ? [value.creationName] : [];
137
+ for (const name of creationNames) {
138
+ const createdKey = JSON.stringify(["relation", value.schema, name]);
139
+ if (createdKey === key)
140
+ continue;
141
+ if (owners.has(createdKey))
142
+ invalid();
143
+ owners.add(createdKey);
144
+ }
145
+ if (value.kind === "sequence") {
146
+ const target = JSON.stringify([value.schema, value.table, value.column]);
147
+ if (sequenceOwners.has(target))
148
+ invalid();
149
+ sequenceOwners.add(target);
150
+ }
151
+ }
152
+ list(entry.steps, (step) => Boolean(step && declarationId(step.id)));
153
+ distinct(entry.steps.map((step) => step.id));
154
+ for (const step of entry.steps) {
155
+ list(step.statements, (statement) => typeof statement === "string" && statement.trim().length > 0 && Buffer.byteLength(statement) <= 65536);
156
+ if (step.statements.length > 256)
157
+ invalid();
158
+ list(step.affectedObjects, (value) => {
159
+ object(value);
160
+ return isDeepStrictEqual(own.get(ownershipKey(value)), value);
161
+ });
162
+ list(step.grants, (grant) => {
163
+ object(grant.object);
164
+ const declared = own.get(ownershipKey(grant.object));
165
+ if (!declared || declared.kind !== "table" && declared.kind !== "sequence")
166
+ invalid();
167
+ list(grant.paths, (path) => declared.paths.includes(path), true);
168
+ list(grant.privileges, (privilege) => declared.privileges.includes(privilege), true);
169
+ return isDeepStrictEqual(declared, grant.object) && step.affectedObjects.some((value) => ownershipKey(value) === ownershipKey(grant.object));
170
+ });
171
+ if ((step.statements.length || step.grants.length) && step.affectedObjects.length === 0)
172
+ invalid();
173
+ }
174
+ try {
175
+ selected.set(entry.id, freeze({
176
+ id: entry.id,
177
+ contractVersion: entry.contractVersion,
178
+ dependsOn: [...entry.dependsOn],
179
+ objects: structuredClone(entry.objects),
180
+ steps: structuredClone(entry.steps),
181
+ inspect: entry.inspect
182
+ }));
183
+ } catch {
184
+ invalid();
185
+ }
186
+ }
187
+ return freeze([...selected.values()]);
188
+ }
189
+ function admitRuntimeDatabaseSchemaPlan(input) {
190
+ const selected = new Map(captureRuntimeDatabaseSchemaComponents(input).map((entry) => [entry.id, entry]));
191
+ for (const entry of selected.values()) {
192
+ for (const trigger of entry.objects.filter((value) => value.kind === "trigger")) {
193
+ for (const [kind, schema, name] of [
194
+ ["table", trigger.schema, trigger.table],
195
+ ["function", trigger.functionSchema, trigger.functionName]
196
+ ]) {
197
+ const owner = [...selected.values()].find((component) => component.objects.some((value) => value.kind === kind && value.schema === schema && "name" in value && value.name === name));
198
+ if (!owner || owner.id !== entry.id && !entry.dependsOn.includes(owner.id))
199
+ invalid();
200
+ }
201
+ }
202
+ }
203
+ const ordered = [];
204
+ const remaining = new Set(selected.keys());
205
+ while (remaining.size) {
206
+ const available = [...remaining].filter((id2) => selected.get(id2).dependsOn.every((dependency) => selected.has(dependency) && !remaining.has(dependency))).sort();
207
+ if (available.length === 0)
208
+ invalid();
209
+ const id = available[0];
210
+ remaining.delete(id);
211
+ ordered.push(selected.get(id));
212
+ }
213
+ return freeze({ components: ordered, objects: ordered.flatMap((entry) => [...entry.objects]) });
214
+ }
215
+ function inspectRuntimeDatabaseSchemaPlan(plan, snapshot) {
216
+ const captured = freeze(structuredClone(snapshot));
217
+ const inspected = plan.components.map((component) => {
218
+ let result;
219
+ try {
220
+ result = component.inspect(captured);
221
+ } catch {
222
+ invalid();
223
+ }
224
+ if (result && typeof result === "object" && "then" in result) {
225
+ void Promise.resolve(result).catch(() => {
226
+ });
227
+ invalid();
228
+ }
229
+ if (!result || typeof result !== "object")
230
+ invalid();
231
+ if (result.state === "incompatible") {
232
+ if (!["shape-incompatible", "required-access-unavailable"].includes(result.reason))
233
+ invalid();
234
+ throw runtimeDatabaseSetupError(result.reason === "shape-incompatible" ? "RUNTIME_DATABASE_SETUP_SCHEMA_INCOMPATIBLE" : "RUNTIME_DATABASE_SETUP_ACCESS_UNAVAILABLE");
235
+ }
236
+ if (result.state === "ready")
237
+ return freeze({ component, steps: [] });
238
+ if (result.state !== "compatible-change")
239
+ invalid();
240
+ list(result.stepIds, declarationId, true);
241
+ distinct(result.stepIds);
242
+ if (result.stepIds.some((id) => !component.steps.some((step) => step.id === id)))
243
+ invalid();
244
+ return freeze({ component, steps: component.steps.filter((step) => result.stepIds.includes(step.id)) });
245
+ });
246
+ return freeze(inspected);
247
+ }
248
+
249
+ export {
250
+ captureRuntimeDatabaseSchemaComponents,
251
+ admitRuntimeDatabaseSchemaPlan,
252
+ inspectRuntimeDatabaseSchemaPlan
253
+ };
@@ -0,0 +1,309 @@
1
+ import {
2
+ isRuntimeWorkflowProviderRetryCode,
3
+ ragEmbeddingGatewayRetryError,
4
+ ragIngestError,
5
+ runtimeWorkflowProviderRetry
6
+ } from "./chunk-4MLRXO7F.mjs";
7
+ import {
8
+ RuntimeCompositionError,
9
+ runtimeStartupError
10
+ } from "./chunk-IFMOTJNU.mjs";
11
+ import {
12
+ RuntimeDiagnosticError,
13
+ runtimeDiagnostic
14
+ } from "./chunk-AEBW7XZJ.mjs";
15
+
16
+ // ../runtime/dist/rag/embedding-configuration.js
17
+ import { randomUUID } from "node:crypto";
18
+ var ragEmbeddingEnvironmentNames = Object.freeze([
19
+ "GENCOW_AI_PROXY_URL",
20
+ "GENCOW_AI_PROXY_URL_ALT",
21
+ "GENCOW_AI_PROXY_TOKEN",
22
+ "GENCOW_RAG_ALLOW_DIRECT_OPENAI_FALLBACK",
23
+ "OPENAI_API_KEY"
24
+ ]);
25
+ var ragEmbeddingModel = "text-embedding-3-small";
26
+ function captureRagEmbeddingEnvironment(environment) {
27
+ return Object.freeze(Object.fromEntries(ragEmbeddingEnvironmentNames.map((name) => [name, environment[name]])));
28
+ }
29
+ function invalid() {
30
+ throw new RuntimeDiagnosticError({
31
+ code: "RAG_EMBEDDING_CONFIGURATION_INVALID",
32
+ stage: "startup",
33
+ capability: "application",
34
+ servingStarted: false,
35
+ dataImpact: "none",
36
+ retryable: false,
37
+ correlationId: randomUUID(),
38
+ retryPrecondition: "Correct the selected trusted embedding supplier configuration before restarting this generation.",
39
+ nextAction: "Configure a valid trusted embedding proxy URL and token, without URL credentials, query or fragment. Direct OpenAI requires the existing explicit standalone permission and no proxy configuration. Preserve existing data; no embedding call was made by this configuration stage."
40
+ });
41
+ }
42
+ function target(rawUrl, token, gateway) {
43
+ if (rawUrl.length > 2048 || token.length > 8192 || /[\u0000-\u001f\u007f]/u.test(token))
44
+ invalid();
45
+ let url;
46
+ try {
47
+ url = new URL(rawUrl);
48
+ } catch {
49
+ invalid();
50
+ }
51
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash)
52
+ invalid();
53
+ url.pathname = url.pathname.replace(/\/+$/u, "");
54
+ if (!url.pathname.endsWith("/embeddings"))
55
+ url.pathname += "/embeddings";
56
+ return Object.freeze({ endpoint: url.href, token, gateway });
57
+ }
58
+ function resolveRagEmbeddingTarget(environment, allowDirect) {
59
+ const captured = captureRagEmbeddingEnvironment(environment);
60
+ const token = captured.GENCOW_AI_PROXY_TOKEN?.trim();
61
+ const urls = [captured.GENCOW_AI_PROXY_URL, captured.GENCOW_AI_PROXY_URL_ALT].map((value) => value?.trim()).filter((value) => !!value);
62
+ if (token || urls.length) {
63
+ if (!token || !urls.length)
64
+ return null;
65
+ const targets = urls.map((url) => target(url, token, true));
66
+ return targets[0];
67
+ }
68
+ const key = captured.OPENAI_API_KEY?.trim();
69
+ if (!allowDirect || captured.GENCOW_RAG_ALLOW_DIRECT_OPENAI_FALLBACK !== "1" || !key || key.length < 20 || /^sk-\.{2,}$/u.test(key) || key.includes("your-key") || key.includes("YOUR_KEY"))
70
+ return null;
71
+ return target("https://api.openai.com/v1/embeddings", key, false);
72
+ }
73
+
74
+ // ../runtime/dist/rag/config.js
75
+ import { randomUUID as randomUUID2 } from "node:crypto";
76
+ function captureRuntimeRagSelection(input) {
77
+ if (input !== null && typeof input === "object" && !Array.isArray(input) && Object.keys(input).every((key) => key === "adapter") && (input.adapter === void 0 || input.adapter === "pgvector"))
78
+ return Object.freeze({ adapter: "pgvector" });
79
+ throw new RuntimeCompositionError({
80
+ code: "RUNTIME_RAG_SELECTION_INVALID",
81
+ stage: "startup",
82
+ capability: "application",
83
+ servingStarted: false,
84
+ dataImpact: "none",
85
+ retryable: false,
86
+ retryPrecondition: "Correct the RAG selection before running the same command again.",
87
+ nextAction: "In CLI projects, set localFeatures.rag to {} (default pgvector) or set it to false to opt out. Direct Runtime hosts select their own RAG provider. Rerun the same command. No files or database state changed.",
88
+ correlationId: randomUUID2()
89
+ });
90
+ }
91
+
92
+ // ../runtime/dist/rag/embedding-response.js
93
+ var maxResponseBytes = 1024 * 1024;
94
+ function record(value) {
95
+ return !!value && typeof value === "object" && !Array.isArray(value);
96
+ }
97
+ async function readEmbeddingResponse(response, signal) {
98
+ if (!response.body)
99
+ throw new Error("Missing embedding response");
100
+ const reader = response.body.getReader(), chunks = [];
101
+ let bytes = 0, complete = false, cancellation;
102
+ const cancel = () => cancellation ??= reader.cancel().catch(() => {
103
+ });
104
+ const abort = () => {
105
+ void cancel();
106
+ };
107
+ signal.addEventListener("abort", abort, { once: true });
108
+ try {
109
+ const length = response.headers.get("content-length"), contentType = response.headers.get("content-type") ?? "";
110
+ if (length && (!/^\d+$/u.test(length) || Number(length) > maxResponseBytes) || !/^application\/(?:json|[\w.-]+\+json)(?:\s*;|$)/iu.test(contentType))
111
+ throw new Error("Invalid embedding response headers");
112
+ while (true) {
113
+ signal.throwIfAborted();
114
+ const next = await reader.read();
115
+ if (next.done) {
116
+ complete = true;
117
+ break;
118
+ }
119
+ bytes += next.value.byteLength;
120
+ if (bytes > maxResponseBytes)
121
+ throw new Error("Embedding response limit exceeded");
122
+ chunks.push(next.value.slice());
123
+ }
124
+ signal.throwIfAborted();
125
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks, bytes)));
126
+ } finally {
127
+ signal.removeEventListener("abort", abort);
128
+ if (!complete || cancellation)
129
+ await cancel();
130
+ reader.releaseLock();
131
+ }
132
+ }
133
+ function parseRetryAfterHeaderMs(value, nowMs = Date.now()) {
134
+ const trimmed = value?.trim();
135
+ if (!trimmed)
136
+ return null;
137
+ const seconds = Number(trimmed);
138
+ if (Number.isFinite(seconds) && seconds >= 0) {
139
+ const delay2 = Math.ceil(seconds * 1e3);
140
+ return Number.isSafeInteger(delay2) ? delay2 : null;
141
+ }
142
+ const dateMs = Date.parse(trimmed);
143
+ if (!Number.isFinite(dateMs))
144
+ return null;
145
+ const delay = Math.max(0, dateMs - nowMs);
146
+ return Number.isSafeInteger(delay) ? delay : null;
147
+ }
148
+ function classifyPreProviderEmbeddingRefusal(target2, response, body) {
149
+ if (!target2.gateway || response.redirected || !record(body) || !record(body.error) || !record(body.diagnostic))
150
+ return null;
151
+ const code = response.headers.get("x-gencow-error-code"), d = body.diagnostic;
152
+ if (!code || body.error.code !== code || d.state_changed !== false || d.retryable !== true)
153
+ return null;
154
+ if (code === "AI_ADMISSION_UNAVAILABLE" && response.status === 503 || code === "AI_TIER_QUEUE_WAIT_EXCEEDED" && response.status === 429) {
155
+ if (!(d.capability === "ai_embed" && ["tier_admission", "provider_admission"].includes(String(d.stage))))
156
+ return null;
157
+ return Object.freeze({ providerCode: code, retryDelayMs: parseRetryAfterHeaderMs(response.headers.get("retry-after")) });
158
+ }
159
+ const routingUnavailable = code === "AI_PROVIDER_ROUTING_UNAVAILABLE" && response.status === 503 && d.capability === "openai_account_pool" && d.stage === "provider_route";
160
+ return routingUnavailable ? Object.freeze({ providerCode: code, retryDelayMs: parseRetryAfterHeaderMs(response.headers.get("retry-after")) }) : null;
161
+ }
162
+ function decodeEmbeddingVectors(body, count, snapshotVector) {
163
+ if (!record(body) || body.model !== void 0 && body.model !== ragEmbeddingModel || !Array.isArray(body.data) || body.data.length !== count)
164
+ throw new Error("Invalid embedding result");
165
+ const output = Array.from({ length: count });
166
+ body.data.forEach((item, fallbackIndex) => {
167
+ if (!record(item))
168
+ throw new Error("Invalid embedding result");
169
+ const index = Object.hasOwn(item, "index") ? item.index : fallbackIndex;
170
+ if (typeof index !== "number" || !Number.isInteger(index) || index < 0 || index >= count || output[index] !== void 0)
171
+ throw new Error("Invalid embedding result");
172
+ output[index] = snapshotVector(item.embedding);
173
+ });
174
+ if (output.some((value) => !value))
175
+ throw new Error("Incomplete embedding result");
176
+ return Object.freeze(output);
177
+ }
178
+
179
+ // ../runtime/dist/rag/embedding-platform-api.js
180
+ function createRuntimeRagEmbeddingApi(target2, fetchImpl) {
181
+ return Object.freeze({
182
+ async embed(input) {
183
+ const response = await fetchImpl(target2.endpoint, {
184
+ method: "POST",
185
+ redirect: "error",
186
+ signal: input.signal,
187
+ headers: { Authorization: `Bearer ${target2.token}`, "Content-Type": "application/json" },
188
+ body: JSON.stringify({ model: input.model, input: input.texts })
189
+ });
190
+ const result = await readEmbeddingResponse(response, input.signal);
191
+ input.signal.throwIfAborted();
192
+ const refusal = classifyPreProviderEmbeddingRefusal(target2, response, result);
193
+ if (refusal)
194
+ return Object.freeze({
195
+ kind: "pre-provider-rejected",
196
+ providerCode: refusal.providerCode,
197
+ retryDelayMs: refusal.retryDelayMs
198
+ });
199
+ if (response.status !== 200 || response.redirected)
200
+ throw new Error("Unknown embedding outcome");
201
+ const vectors = decodeEmbeddingVectors(result, input.texts.length, (value) => value);
202
+ return Object.freeze({ kind: "completed", model: ragEmbeddingModel, vectors });
203
+ }
204
+ });
205
+ }
206
+
207
+ // ../runtime/dist/rag/embedding-rejection.js
208
+ var rejected = /* @__PURE__ */ new WeakMap();
209
+ function issueEmbeddingRejection(input, code, providerRetry) {
210
+ const error = code === "RAG_EMBEDDING_ADMISSION_REJECTED" && providerRetry ? ragEmbeddingGatewayRetryError(input.correlationId, providerRetry.providerCode, providerRetry.retryDelayMs) : ragIngestError(code, input.correlationId, "committed");
211
+ rejected.set(error, Object.freeze({
212
+ model: ragEmbeddingModel,
213
+ appId: input.appId,
214
+ workflowId: input.workflowId,
215
+ correlationId: input.correlationId,
216
+ items: Object.freeze(input.items.map((item) => Object.freeze({ id: item.id, checksum: item.checksum })))
217
+ }));
218
+ return error;
219
+ }
220
+ function isEmbeddingRefusalClaim(error) {
221
+ const code = runtimeDiagnostic(error)?.code;
222
+ return code === "RAG_EMBEDDING_ADMISSION_REJECTED" || code === "RAG_EMBEDDING_REQUEST_INVALID" || code !== void 0 && isRuntimeWorkflowProviderRetryCode(code) || runtimeWorkflowProviderRetry(error) !== void 0;
223
+ }
224
+ function isKnownEmbeddingRejection(error, input, model = ragEmbeddingModel) {
225
+ if (!error || typeof error !== "object")
226
+ return false;
227
+ const saved = rejected.get(error);
228
+ return !!saved && saved.model === model && saved.appId === input.appId && saved.workflowId === input.workflowId && saved.correlationId === input.correlationId && saved.items.length === input.items.length && saved.items.every((item, i) => item.id === input.items[i]?.id && item.checksum === input.items[i]?.checksum);
229
+ }
230
+ function consumeEmbeddingRejection(error, input, model = ragEmbeddingModel) {
231
+ if (!isKnownEmbeddingRejection(error, input, model))
232
+ return false;
233
+ rejected.delete(error);
234
+ return true;
235
+ }
236
+
237
+ // ../runtime/dist/rag/embedding-provider.js
238
+ function createConfiguredRagEmbeddingTransport(environment, binding, options) {
239
+ const target2 = resolveRagEmbeddingTarget(environment, options.allowDirect !== false);
240
+ if (!target2)
241
+ return null;
242
+ const appId = binding.appId, api = options.api ?? createRuntimeRagEmbeddingApi(target2, options.fetchImpl ?? globalThis.fetch), snapshotVector = options.snapshotVector;
243
+ const embedMethod = api.embed;
244
+ if (typeof embedMethod !== "function")
245
+ throw runtimeStartupError("RUNTIME_COMPONENT_DEPENDENCY_INVALID", "Supply a trusted embedding API with an embed method before starting this generation.");
246
+ const embed = embedMethod.bind(api);
247
+ return Object.freeze({
248
+ model: ragEmbeddingModel,
249
+ async embed(input) {
250
+ if (!Array.isArray(input.items) || !input.items.length || input.items.length > 16)
251
+ throw ragIngestError("RAG_EMBEDDING_REQUEST_INVALID", input.correlationId, "committed");
252
+ let items;
253
+ try {
254
+ items = Array.from({ length: input.items.length }, (_, index) => {
255
+ if (!Object.hasOwn(input.items, index))
256
+ throw new Error("Missing embedding item");
257
+ const item = input.items[index];
258
+ return Object.freeze({ id: item.id, text: item.text, checksum: item.checksum });
259
+ });
260
+ } catch {
261
+ throw ragIngestError("RAG_EMBEDDING_REQUEST_INVALID", input.correlationId, "committed");
262
+ }
263
+ const request = Object.freeze({ ...input, items: Object.freeze(items) });
264
+ if (input.appId !== appId || new Set(items.map((item) => item.id)).size !== items.length || items.some((item) => typeof item.id !== "string" || !item.id || item.id.length > 256 || typeof item.text !== "string" || !item.text.trim() || item.text.length > 5600 || Buffer.byteLength(item.text) > 5600 || typeof item.checksum !== "string" || !/^[a-f0-9]{64}$/u.test(item.checksum)))
265
+ throw issueEmbeddingRejection(request, "RAG_EMBEDDING_REQUEST_INVALID");
266
+ const body = JSON.stringify({ model: ragEmbeddingModel, input: items.map((item) => item.text) });
267
+ if (Buffer.byteLength(body) > 768 * 1024)
268
+ throw issueEmbeddingRejection(request, "RAG_EMBEDDING_REQUEST_INVALID");
269
+ const signal = AbortSignal.any([input.signal, AbortSignal.timeout(3e4)]);
270
+ let refusal;
271
+ try {
272
+ signal.throwIfAborted();
273
+ const result = await embed(Object.freeze({
274
+ model: ragEmbeddingModel,
275
+ texts: Object.freeze(items.map((item) => item.text)),
276
+ signal,
277
+ correlationId: input.correlationId
278
+ }));
279
+ signal.throwIfAborted();
280
+ if (result.kind === "pre-provider-rejected") {
281
+ if (![
282
+ "AI_ADMISSION_UNAVAILABLE",
283
+ "AI_TIER_QUEUE_WAIT_EXCEEDED",
284
+ "AI_PROVIDER_ROUTING_UNAVAILABLE"
285
+ ].includes(result.providerCode) || result.retryDelayMs !== null && (!Number.isSafeInteger(result.retryDelayMs) || result.retryDelayMs < 0))
286
+ throw new Error("Invalid embedding refusal");
287
+ refusal = { providerCode: result.providerCode, retryDelayMs: result.retryDelayMs };
288
+ } else {
289
+ if (result.kind !== "completed" || result.model !== ragEmbeddingModel || !Array.isArray(result.vectors) || result.vectors.length !== items.length)
290
+ throw new Error("Invalid embedding result");
291
+ return Object.freeze(Array.from(result.vectors, snapshotVector));
292
+ }
293
+ } catch {
294
+ throw ragIngestError("RAG_EMBEDDING_OUTCOME_UNKNOWN", input.correlationId);
295
+ }
296
+ throw issueEmbeddingRejection(request, "RAG_EMBEDDING_ADMISSION_REJECTED", refusal);
297
+ }
298
+ });
299
+ }
300
+
301
+ export {
302
+ ragEmbeddingEnvironmentNames,
303
+ captureRagEmbeddingEnvironment,
304
+ isEmbeddingRefusalClaim,
305
+ isKnownEmbeddingRejection,
306
+ consumeEmbeddingRejection,
307
+ captureRuntimeRagSelection,
308
+ createConfiguredRagEmbeddingTransport
309
+ };