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,1132 @@
1
+ import {
2
+ filesystemFailure,
3
+ filesystemMetadataInvalid,
4
+ filesystemObjectNotFound
5
+ } from "./chunk-GYAJ7OX2.mjs";
6
+ import {
7
+ assertRuntimeFileSize
8
+ } from "./chunk-GDWYAGWV.mjs";
9
+ import {
10
+ ragJobError,
11
+ ragJobStages,
12
+ ragJobStatuses,
13
+ readRagJobs
14
+ } from "./chunk-JUDKX53X.mjs";
15
+ import {
16
+ RuntimeSearchError,
17
+ RuntimeSearchRlsContextError
18
+ } from "./chunk-LEW5ZMLR.mjs";
19
+ import {
20
+ isRagIngestErrorCode,
21
+ ragEmbeddingGatewayRetryError,
22
+ ragIngestError,
23
+ runtimeWorkflowProviderRetry
24
+ } from "./chunk-4MLRXO7F.mjs";
25
+ import {
26
+ schedulerFailure
27
+ } from "./chunk-NAG2OXS5.mjs";
28
+ import {
29
+ requestContextInputError
30
+ } from "./chunk-IKQKBE2G.mjs";
31
+ import {
32
+ DocumentConversionError,
33
+ isDocumentConversionErrorCode
34
+ } from "./chunk-6JO72SPP.mjs";
35
+ import {
36
+ RuntimeCapabilityUnavailableError,
37
+ RuntimeDiagnosticError,
38
+ WorkflowNonRetryableError,
39
+ WorkflowStepTimeoutError,
40
+ formatRuntimeDiagnostic,
41
+ isRuntimeRequestFailureCode,
42
+ parseWorkflowDurationMs,
43
+ runtimeDiagnostic,
44
+ runtimeDocumentRecoveryAction,
45
+ searchFailurePresentations,
46
+ serializeWorkflowValue
47
+ } from "./chunk-AEBW7XZJ.mjs";
48
+
49
+ // ../runtime/dist/workflow/control-errors.js
50
+ var RuntimeWorkflowAbortError = class extends Error {
51
+ code;
52
+ constructor(code) {
53
+ super(code === "user_cancelled" ? "Workflow cancellation requested" : code === "active_timeout" ? "Workflow execution deadline elapsed" : code === "runtime_shutdown" ? "Runtime generation is closing" : "Workflow lease is no longer live");
54
+ this.code = code;
55
+ this.name = "WorkflowAbortError";
56
+ }
57
+ };
58
+ function throwIfRuntimeWorkflowAborted(signal) {
59
+ if (!signal.aborted)
60
+ return;
61
+ const code = signal.reason?.code;
62
+ throw new RuntimeWorkflowAbortError(code === "user_cancelled" || code === "active_timeout" || code === "runtime_shutdown" ? code : "lease_lost");
63
+ }
64
+ function workflowControlDiagnostic(runId, cause, retrying = false) {
65
+ const cancelled = cause === "cancelled";
66
+ return {
67
+ code: cancelled ? "RUNTIME_WORKFLOW_CANCELLED" : cause === "lifecycle_timeout" ? "RUNTIME_WORKFLOW_LIFECYCLE_TIMEOUT" : "RUNTIME_WORKFLOW_ACTIVE_TIMEOUT",
68
+ stage: "request",
69
+ servingStarted: "unchanged",
70
+ dataImpact: "unknown",
71
+ retryable: retrying,
72
+ retryPrecondition: retrying ? "The expired attempt was fenced. Recovery scheduled the same run after the persisted backoff; do not start a replacement." : cancelled ? "Cancellation is terminal. Already-started external effects may have happened; inspect them before an explicit replay." : "The persisted deadline elapsed. Inspect prior effects and correct the workflow duration/policy before an explicit retry/replay.",
73
+ nextAction: `Inspect workflows.get using POST /api/query with ${JSON.stringify({ json: { name: "workflows.get", args: { id: runId } } })}. ` + (retrying ? "Wait for the scheduled retry of this same run; do not edit internal state." : "Review completed steps and external effects before using the existing authorized retry/replay controls; do not edit internal state."),
74
+ capability: "application",
75
+ correlationId: runId
76
+ };
77
+ }
78
+ function workflowControlMessage(runId, cause, retrying = false) {
79
+ return formatRuntimeDiagnostic(workflowControlDiagnostic(runId, cause, retrying));
80
+ }
81
+
82
+ // ../runtime/dist/workflow/database-rejection.js
83
+ import { DrizzleQueryError } from "drizzle-orm/errors";
84
+ function isWorkflowDatabaseRejection(error) {
85
+ return error instanceof DrizzleQueryError || error instanceof Error && "code" in error && typeof error.code === "string" && /^[0-9A-Z]{5}$/.test(error.code);
86
+ }
87
+
88
+ // ../runtime/dist/workflow/wait-persistence.js
89
+ var WorkflowWaitPersistenceError = class extends RuntimeDiagnosticError {
90
+ errorCode = "workflow_wait_persistence_unavailable";
91
+ cause;
92
+ constructor(runId, cause) {
93
+ super({
94
+ code: "RUNTIME_WORKFLOW_WAIT_PERSISTENCE_UNAVAILABLE",
95
+ stage: "workflow",
96
+ servingStarted: "unchanged",
97
+ capability: "database",
98
+ dataImpact: "unknown",
99
+ retryable: false,
100
+ retryPrecondition: "The workflow database owner must restore write readiness. Inspect this run's signal receipts, completed checkpoints and prior effects before existing authorized recovery controls.",
101
+ nextAction: `Inspect workflows.get using POST /api/query with ${JSON.stringify({ json: { name: "workflows.get", args: { id: runId } } })}. Preserve this run. After owner recovery and receipt/effect inspection, use an existing same-run retry control only if this environment provides one; do not edit internal state, blindly resend signals, or start a replacement run.`,
102
+ correlationId: runId
103
+ });
104
+ this.cause = cause;
105
+ }
106
+ };
107
+ async function persistWorkflowWait(runId, operation) {
108
+ try {
109
+ return await operation();
110
+ } catch (error) {
111
+ if (isWorkflowDatabaseRejection(error))
112
+ throw new WorkflowWaitPersistenceError(runId, error);
113
+ throw error;
114
+ }
115
+ }
116
+
117
+ // ../runtime/dist/workflow/checkpoint-persistence.js
118
+ var labels = Object.freeze({
119
+ read: "checkpoint read",
120
+ begin: "checkpoint admission",
121
+ complete: "checkpoint commit",
122
+ fail: "checkpoint failure recording",
123
+ unknown: "checkpoint persistence"
124
+ });
125
+ var WorkflowCheckpointPersistenceError = class extends RuntimeDiagnosticError {
126
+ errorCode = "workflow_checkpoint_persistence_unavailable";
127
+ cause;
128
+ constructor(runId, operation, cause) {
129
+ const request = JSON.stringify({ json: { name: "workflows.get", args: { id: runId } } }).replace(/[\u007f-\uffff]/g, (value) => "\\u" + value.charCodeAt(0).toString(16).padStart(4, "0"));
130
+ super({
131
+ code: "RUNTIME_WORKFLOW_CHECKPOINT_PERSISTENCE_UNAVAILABLE",
132
+ stage: "workflow",
133
+ capability: "database",
134
+ servingStarted: "unchanged",
135
+ dataImpact: "unknown",
136
+ retryable: false,
137
+ retryPrecondition: `The workflow database owner must restore ${labels[operation]} readiness. Inspect this same run's completed checkpoints and prior effects before existing authorized recovery controls; a persistence rejection does not prove effects rolled back.`,
138
+ nextAction: `Inspect workflows.get using POST /api/query with ${request}. Preserve this same run and its completed checkpoints. After owner recovery and prior effect inspection, use an existing same-run retry control only if this environment provides one; do not edit internal state, retry individual steps blindly, or start a replacement run.`,
139
+ correlationId: runId
140
+ });
141
+ this.cause = cause;
142
+ }
143
+ };
144
+ async function persistWorkflowCheckpoint(runId, operation, execute) {
145
+ try {
146
+ return await execute();
147
+ } catch (error) {
148
+ if (isWorkflowDatabaseRejection(error))
149
+ throw new WorkflowCheckpointPersistenceError(runId, operation, error);
150
+ throw error;
151
+ }
152
+ }
153
+
154
+ // ../runtime/dist/rag/search-errors.js
155
+ var actions = {
156
+ SEARCH_INPUT_INVALID: "Supply rag_chunks, declared chunk_text/lexical_text fields, a valid corpus/visibility, bounded filters/pagination, and finite dimension1536 nonzero vectors for vector/hybrid retrieval. No provider or write was admitted.",
157
+ SEARCH_SCOPE_OWNER_MISMATCH: "Search the private corpus as its authenticated owner; ownerUserId must match your identity. No provider or write was admitted.",
158
+ SEARCH_INDEX_NOT_READY: "Restore the selected managed RAG startup readiness for this same database, then retry the read. Preserve existing sources and jobs; do not edit managed tables or migration journals.",
159
+ RAG_SEARCH_TABLE_UNAVAILABLE: "Use rag_chunks for the selected RAG retrieval capability. Select a separate trusted search adapter for other application tables; unrelated RAG operations remain available.",
160
+ RAG_SEARCH_SCOPE_ENDED: "Borrow search from an active request or Workflow scope. The ended or changed identity cannot authorize a result; this read changed no data.",
161
+ RAG_SEARCH_UNAVAILABLE: "Restore the selected database connection and read access, then retry the same read. Preserve existing data; no provider call or RAG write was admitted."
162
+ };
163
+ var RuntimeRagSearchError = class extends RuntimeDiagnosticError {
164
+ constructor(code, correlationId) {
165
+ super({
166
+ code,
167
+ stage: "request",
168
+ capability: code === "RAG_SEARCH_UNAVAILABLE" || code === "SEARCH_INDEX_NOT_READY" ? "database" : "application",
169
+ servingStarted: "unchanged",
170
+ dataImpact: "none",
171
+ retryable: false,
172
+ retryPrecondition: "Correct the named input, active scope or selected database readiness before resubmitting the read.",
173
+ nextAction: actions[code],
174
+ ...correlationId ? { correlationId } : {}
175
+ });
176
+ }
177
+ };
178
+ function ragSearchError(code, correlationId) {
179
+ return new RuntimeRagSearchError(code, correlationId);
180
+ }
181
+ function isRagSearchCode(code) {
182
+ return Object.hasOwn(actions, code);
183
+ }
184
+
185
+ // ../runtime/dist/workflow/capability-diagnostic.js
186
+ var unavailableLabels = /* @__PURE__ */ new Map([
187
+ ["storage", "storage adapter"],
188
+ ["database", "database provider"],
189
+ ["system database", "database provider"],
190
+ ["scheduler", "Runtime scheduler integration"],
191
+ ["realtime", "realtime adapter"],
192
+ ["services", "workflow service adapter"],
193
+ ["search", "search adapter"],
194
+ ["vector search", "vector search adapter"],
195
+ ["hybrid search", "hybrid search adapter"],
196
+ ["grounding", "grounding adapter"],
197
+ ["retry", "ctx.retry capability"]
198
+ ]);
199
+ function inspectionId(runId) {
200
+ return /^[A-Za-z0-9._:-]{1,128}$/u.test(runId) ? JSON.stringify(runId) : "<run ID from the start result>";
201
+ }
202
+ function isWorkflowProviderError(error) {
203
+ return error instanceof RuntimeDiagnosticError && (runtimeWorkflowProviderRetry(error) !== void 0 || error instanceof RuntimeSearchError || error instanceof RuntimeSearchRlsContextError || error instanceof RuntimeRagSearchError || error.diagnostic.capability === "scheduler" || error.diagnostic.capability === "storage" || error.diagnostic.capability === "application" && /^(?:DOCUMENT|RAG)_[A-Z0-9_]+$/u.test(error.diagnostic.code) || error.diagnostic.capability === "database" && (error instanceof WorkflowWaitPersistenceError || error instanceof WorkflowCheckpointPersistenceError));
204
+ }
205
+ function workflowProviderDiagnostic(error, runId, correlationId) {
206
+ const providerRetry = runtimeWorkflowProviderRetry(error);
207
+ if (providerRetry)
208
+ return { ...error.diagnostic, correlationId };
209
+ if (error instanceof WorkflowWaitPersistenceError || error instanceof WorkflowCheckpointPersistenceError)
210
+ return { ...error.diagnostic, correlationId };
211
+ return {
212
+ ...error.diagnostic,
213
+ stage: "workflow",
214
+ dataImpact: "unknown",
215
+ retryPrecondition: `${error.diagnostic.retryPrecondition} Inspect this run's completed checkpoints and earlier external effects before retrying it.`,
216
+ nextAction: `${error.diagnostic.nextAction} Inspect workflows.get({ id: ${inspectionId(runId)} }) and preserve this run. After correcting the diagnosed condition and verifying earlier effects, use an existing same-run retry control if available; do not start a replacement run as a blind retry.`,
217
+ correlationId
218
+ };
219
+ }
220
+ function workflowCapabilityDiagnostic(error, runId, correlationId) {
221
+ const label = unavailableLabels.get(error.capability) ?? "required Runtime adapter";
222
+ const readiness = error.capability === "scheduler" ? "Runtime scheduler integration is available for this generation" : `the selected Runtime generation supplies the ${label}`;
223
+ return {
224
+ ...error.diagnostic,
225
+ stage: "workflow",
226
+ dataImpact: "unknown",
227
+ retryable: false,
228
+ retryPrecondition: `${readiness}, and completed checkpoints and earlier external effects have been inspected for this run.`,
229
+ nextAction: `Inspect workflows.get({ id: ${inspectionId(runId)} }) for the current run and its completed steps. Preserve this run and verify earlier effects. Once ${readiness}, use an existing same-run retry control if this environment provides one; do not start a replacement run as a blind retry.`,
230
+ correlationId
231
+ };
232
+ }
233
+ function verifiedTerminalStepAuthentication(code, message, runId) {
234
+ if (code !== "RUNTIME_AUTHENTICATION_REQUIRED" || message.length > 16384)
235
+ return void 0;
236
+ const correlationId = /^Correlation ID: ([A-Za-z0-9._-]{1,128})$/mu.exec(message)?.[1];
237
+ if (!correlationId)
238
+ return void 0;
239
+ const diagnostic = workflowProviderDiagnostic(new RuntimeSearchError(code, correlationId), runId, correlationId);
240
+ return formatRuntimeDiagnostic(diagnostic) === message ? diagnostic : void 0;
241
+ }
242
+
243
+ // ../runtime/dist/workflow/failure-message.js
244
+ function workflowInspectionCommand(runId) {
245
+ return JSON.stringify({ json: { name: "workflows.get", args: { id: runId } } }).replace(/[\u007f-\uffff]/g, (value) => "\\u" + value.charCodeAt(0).toString(16).padStart(4, "0"));
246
+ }
247
+ function workflowFailureMessage(message, runId, retryScheduled) {
248
+ if (typeof message === "string")
249
+ return message;
250
+ if (message.kind === "diagnostic")
251
+ return workflowDiagnosticFailureMessage(message.diagnostic, retryScheduled);
252
+ const command = workflowInspectionCommand(runId);
253
+ return formatRuntimeDiagnostic({
254
+ code: "RUNTIME_WORKFLOW_HANDLER_FAILED",
255
+ stage: "workflow",
256
+ capability: "application",
257
+ servingStarted: "unchanged",
258
+ dataImpact: "unknown",
259
+ retryable: retryScheduled,
260
+ retryPrecondition: retryScheduled ? "Automatic retry is already scheduled for this same run after its persisted backoff. Inspect completed checkpoints and prior effects; do not start a replacement run." : "No automatic retry remains. Inspect completed checkpoints and prior effects, and diagnose the workflow source and selected dependencies before any supported same-run retry.",
261
+ nextAction: `Inspect workflows.get using POST /api/query with ${command}. Preserve this run and review its status, completed checkpoints and prior effects. Check the workflow source and selected dependency status; do not blindly retry effects or edit workflow records.`,
262
+ correlationId: message.correlationId
263
+ });
264
+ }
265
+ function workflowDiagnosticFailureMessage(diagnostic, retryScheduled) {
266
+ if (retryScheduled)
267
+ return formatRuntimeDiagnostic({ ...diagnostic, retryable: true });
268
+ return formatRuntimeDiagnostic({
269
+ ...diagnostic,
270
+ retryable: false,
271
+ retryPrecondition: `${diagnostic.retryPrecondition} No automatic retry remains for this run. Inspect completed checkpoints and prior effects before any existing explicit same-run recovery.`,
272
+ nextAction: `${diagnostic.nextAction} No automatic retry remains for this run. Preserve this run and inspect its completed checkpoints and prior effects before any supported explicit same-run recovery; do not start replacement work or blindly repeat external effects.`
273
+ });
274
+ }
275
+ function workflowStepFailureMessage(runId, correlationId) {
276
+ return formatRuntimeDiagnostic({
277
+ code: "RUNTIME_WORKFLOW_STEP_FAILED",
278
+ stage: "workflow",
279
+ capability: "application",
280
+ servingStarted: "unchanged",
281
+ dataImpact: "unknown",
282
+ retryable: false,
283
+ retryPrecondition: "A failed step does not schedule a retry. Inspect this run's current status for its workflow-level retry decision; verify completed checkpoints and prior effects before supported same-run recovery.",
284
+ nextAction: `Inspect workflows.get using POST /api/query with ${workflowInspectionCommand(runId)}. Preserve this run and review completed checkpoints, prior effects, workflow source and selected dependency status. Do not rerun a failed step individually or start a replacement run as a blind retry.`,
285
+ correlationId
286
+ });
287
+ }
288
+
289
+ // ../runtime/dist/rag/source-errors.js
290
+ var ragSourceErrorCodes = [
291
+ "RAG_SOURCE_BUSY",
292
+ "RAG_SOURCE_STATE_INVALID",
293
+ "RAG_WRITE_FENCE_LOST",
294
+ "RAG_WRITE_OUTCOME_UNKNOWN",
295
+ "RAG_CONVERTED_RESULT_INVALID",
296
+ "RAG_ARTIFACT_SIZE_LIMIT_EXCEEDED",
297
+ "RAG_INDEX_STATE_INVALID",
298
+ "RAG_SERVER_CHECKPOINT_INCOMPATIBLE",
299
+ "RAG_INDEX_SIZE_LIMIT_EXCEEDED",
300
+ "RAG_EMBEDDING_RESULT_INVALID"
301
+ ];
302
+ function ragSourceError(code, correlationId, dataImpact = "none") {
303
+ const actions2 = {
304
+ RAG_SOURCE_BUSY: "Inspect the existing source job with rag_ingest_jobs.get and its workflows.get run. Wait for its canonical owner to settle; do not start replacement conversion work.",
305
+ RAG_SOURCE_STATE_INVALID: "Preserve this source and its jobs. Inspect rag_ingest_jobs.get and workflows.get for the same identities; resume only after the owning runtime establishes compatible scoped state. Do not edit internal rows.",
306
+ RAG_WRITE_FENCE_LOST: "Stop this stale attempt. Inspect the same rag_ingest_jobs.get job and workflows.get run; only the current verified owner may continue. Do not reuse late provider output under a replacement identity.",
307
+ RAG_WRITE_OUTCOME_UNKNOWN: "Inspect the same rag_ingest_jobs.get job and its committed source artifacts before resuming. The write may have committed; never blindly repeat external conversion or delete existing data.",
308
+ RAG_CONVERTED_RESULT_INVALID: "Restore the selected converter's valid normalized text, pages, sections and provider trace. Inspect the same rag_ingest_jobs.get job and prior provider effects before resuming; do not blindly redispatch conversion.",
309
+ RAG_ARTIFACT_SIZE_LIMIT_EXCEEDED: "Reduce the document or converter output to the RAG persistence limits: 8 MiB total converted result and 1 MiB page/section/trace metadata. Inspect the same rag_ingest_jobs.get job and prior provider effects before a safe same-run resume; do not automatically redispatch conversion.",
310
+ RAG_INDEX_STATE_INVALID: "Preserve the same source and job. Inspect rag_ingest_jobs.get and workflows.get; only the verified owner may establish a compatible committed artifact and scoped index. Do not edit internal rows or blindly repeat conversion or embedding calls.",
311
+ RAG_SERVER_CHECKPOINT_INCOMPATIBLE: "Preserve the existing source and same Workflow. This Runtime cannot safely interpret the saved Server RAG checkpoint; inspect the same rag_ingest_jobs.get and workflows.get identity and resume only after a compatible Runtime adapter is available. Do not start replacement work or edit retained checkpoints.",
312
+ RAG_INDEX_SIZE_LIMIT_EXCEEDED: "Reduce the document or section plan to the RAG index limits: 4096 sections, 8192 chunks and 16 MiB serialized plan. Inspect the same job and earlier effects before safe resumption; no index writes from this rejected operation committed.",
313
+ RAG_EMBEDDING_RESULT_INVALID: "Restore the configured embedding model and finite 1536-dimensional results that remain nonzero after float32 conversion, in batches of at most 16. Inspect the same job and prior provider effects before resuming; do not blindly repeat paid embedding calls."
314
+ };
315
+ return new RuntimeDiagnosticError({
316
+ code,
317
+ stage: "workflow",
318
+ capability: "application",
319
+ servingStarted: "unchanged",
320
+ dataImpact,
321
+ retryable: false,
322
+ retryPrecondition: "The canonical source/job and workflow owner must establish a valid same-run fence and verify prior committed effects before resuming.",
323
+ nextAction: actions2[code],
324
+ correlationId
325
+ });
326
+ }
327
+
328
+ // ../runtime/dist/workflow/journal-step-policy.js
329
+ var StepOutputSerializationError = class extends WorkflowNonRetryableError {
330
+ constructor(message, options) {
331
+ super(message, options);
332
+ }
333
+ };
334
+ function computeWorkflowStepBackoffMs(backoff, attempt) {
335
+ const initial = backoff?.initial == null ? 5e3 : parseWorkflowDurationMs(backoff.initial, "step backoff.initial");
336
+ const max = backoff?.max == null ? 6e5 : parseWorkflowDurationMs(backoff.max, "step backoff.max");
337
+ const raw = Math.min(max, initial * (backoff?.factor ?? 3) ** Math.max(0, attempt - 1));
338
+ return backoff?.jitter === false ? raw : Math.min(max, Math.round(raw * (0.8 + Math.random() * 0.4)));
339
+ }
340
+ async function runWorkflowStepWithTimeout(stepName, timeoutMs, stepCtx, fn, track) {
341
+ if (timeoutMs == null)
342
+ return track(fn(stepCtx));
343
+ const timeoutError = new WorkflowStepTimeoutError(stepName, timeoutMs);
344
+ const attempt = new AbortController();
345
+ const signal = AbortSignal.any([stepCtx.abortSignal, attempt.signal]);
346
+ let timer;
347
+ const expired = new Promise((_, reject) => {
348
+ timer = setTimeout(() => {
349
+ attempt.abort(timeoutError);
350
+ reject(timeoutError);
351
+ }, timeoutMs);
352
+ });
353
+ const running = track(fn({
354
+ ...stepCtx,
355
+ abortSignal: signal,
356
+ throwIfAborted: () => {
357
+ if (signal.aborted)
358
+ throw signal.reason;
359
+ }
360
+ }));
361
+ running.catch(() => {
362
+ });
363
+ try {
364
+ return await Promise.race([running, expired]);
365
+ } finally {
366
+ clearTimeout(timer);
367
+ }
368
+ }
369
+
370
+ // ../runtime/dist/workflow/checkpoint-value.js
371
+ import { sql as sql2 } from "drizzle-orm";
372
+
373
+ // ../runtime/dist/workflow/server-json.js
374
+ import { sql } from "drizzle-orm";
375
+ function workflowV2JsonString(value) {
376
+ return JSON.stringify(value ?? {}, (_key, current) => typeof current === "string" ? sanitizeWorkflowV2JsonString(current) : current);
377
+ }
378
+ function sanitizeWorkflowV2JsonString(value) {
379
+ return value.replace(/\u0000/g, "").replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/g, "").replace(/(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "");
380
+ }
381
+
382
+ // ../runtime/dist/workflow/checkpoint-value.js
383
+ function serializeWorkflowCheckpoint(value, legacy) {
384
+ const json = workflowV2JsonString(legacy ? serializeWorkflowValue(value) : value ?? null);
385
+ if (json === void 0)
386
+ throw new TypeError("Unsupported checkpoint value");
387
+ return Object.freeze(legacy ? { json, codec: "envelope" } : { json });
388
+ }
389
+ function workflowCheckpointJson(checkpoint) {
390
+ return sql2`${checkpoint.json}::text::jsonb`;
391
+ }
392
+
393
+ // ../runtime/dist/workflow/checkpoint-policy.js
394
+ var RuntimeWorkflowCheckpointError = class extends RuntimeDiagnosticError {
395
+ errorCode;
396
+ constructor(kind, correlationId, reason = "size") {
397
+ super({
398
+ code: reason === "size" ? "RUNTIME_WORKFLOW_CHECKPOINT_TOO_LARGE" : "RUNTIME_WORKFLOW_CHECKPOINT_NOT_SERIALIZABLE",
399
+ stage: "request",
400
+ servingStarted: "unchanged",
401
+ dataImpact: "unknown",
402
+ retryable: false,
403
+ retryPrecondition: reason === "size" ? "Reduce the step/result checkpoint to a small reference before retrying; completed checkpoints and prior external effects remain." : "Return a JSON-serializable step/result (or undefined) before retrying; completed checkpoints and prior external effects remain.",
404
+ nextAction: reason === "size" ? "Store large payloads in an application table/storage object and return an id/reference/count/checksum. Inspect the current run before using the existing workflow retry control." : "Correct cycles, BigInt or throwing serialization in the workflow's step/result and return JSON data or a small reference. Inspect workflows.get for the current run before the existing retry control; preserve completed checkpoints and verify prior effects instead of blindly replaying.",
405
+ capability: "application",
406
+ correlationId
407
+ });
408
+ this.errorCode = reason === "size" ? kind === "step" ? "workflow_step_output_too_large" : "workflow_result_too_large" : kind === "step" ? "workflow_step_output_not_serializable" : "workflow_result_not_serializable";
409
+ }
410
+ };
411
+ var WorkflowCheckpointPolicyError = class extends RuntimeWorkflowCheckpointError {
412
+ sizeBytes;
413
+ hardLimitBytes;
414
+ workflowName;
415
+ stepKey;
416
+ constructor(input) {
417
+ super("step", input.correlationId);
418
+ this.name = "WorkflowCheckpointPolicyError";
419
+ this.sizeBytes = input.sizeBytes;
420
+ this.hardLimitBytes = input.hardLimitBytes;
421
+ this.workflowName = input.workflowName;
422
+ this.stepKey = input.stepKey;
423
+ }
424
+ };
425
+ var WorkflowResultPolicyError = class extends RuntimeWorkflowCheckpointError {
426
+ sizeBytes;
427
+ hardLimitBytes;
428
+ workflowName;
429
+ constructor(input) {
430
+ super("result", input.correlationId);
431
+ this.name = "WorkflowResultPolicyError";
432
+ this.sizeBytes = input.sizeBytes;
433
+ this.hardLimitBytes = input.hardLimitBytes;
434
+ this.workflowName = input.workflowName;
435
+ }
436
+ };
437
+ function enforceWorkflowCheckpoint(input) {
438
+ let checkpoint;
439
+ try {
440
+ checkpoint = serializeWorkflowCheckpoint(input.value, input.kind === "step" && input.attempt.claim.commandProtocol === 2);
441
+ } catch (error) {
442
+ if (error instanceof RuntimeCapabilityUnavailableError || isWorkflowProviderError(error))
443
+ throw error;
444
+ if (input.kind === "step" && input.attempt.claim.commandProtocol === 2) {
445
+ const reason = error instanceof Error ? error.message : String(error);
446
+ throw new StepOutputSerializationError(`Step "${input.stepName}" returned a value that cannot be saved as JSON (${reason}). Return plain JSON data: convert BigInt with toString() and Map/Set with Object.fromEntries()/Array.from().`, { cause: error });
447
+ }
448
+ throw new RuntimeWorkflowCheckpointError(input.kind, input.attempt.correlationId, "serialization");
449
+ }
450
+ const bytes = new TextEncoder().encode(checkpoint.json).byteLength;
451
+ if (bytes > input.policy.checkpointSoftBytes) {
452
+ try {
453
+ input.logger.warn("runtime.workflow.checkpoint.limit", {
454
+ "workflow.id": input.attempt.claim.id,
455
+ "workflow.checkpoint_bytes": bytes,
456
+ "runtime.public_code": bytes > input.policy.checkpointHardBytes ? "RUNTIME_WORKFLOW_CHECKPOINT_TOO_LARGE" : "RUNTIME_WORKFLOW_CHECKPOINT_SOFT_LIMIT"
457
+ });
458
+ } catch {
459
+ }
460
+ }
461
+ if (bytes > input.policy.checkpointHardBytes && (input.policy.checkpointMode === "enforce" || input.policy.checkpointMode === "platform_enforce" && input.attempt.claim.name.startsWith("__gencow."))) {
462
+ const common = {
463
+ correlationId: input.attempt.correlationId,
464
+ sizeBytes: bytes,
465
+ hardLimitBytes: input.policy.checkpointHardBytes,
466
+ workflowName: input.attempt.claim.name
467
+ };
468
+ throw input.kind === "step" ? new WorkflowCheckpointPolicyError({ ...common, stepKey: input.stepKey ?? input.stepName ?? "" }) : new WorkflowResultPolicyError(common);
469
+ }
470
+ return checkpoint;
471
+ }
472
+
473
+ // ../runtime/dist/workflow/wait-errors.js
474
+ var WorkflowWaitTimeoutError = class extends RuntimeDiagnosticError {
475
+ errorCode = "wait_timeout";
476
+ constructor(runId) {
477
+ super({
478
+ code: "RUNTIME_WORKFLOW_WAIT_TIMEOUT",
479
+ stage: "request",
480
+ servingStarted: "unchanged",
481
+ dataImpact: "unknown",
482
+ retryable: false,
483
+ retryPrecondition: "The persisted occurrence deadline elapsed without an eligible signal. Inspect prior effects before an explicit workflow retry/replay.",
484
+ nextAction: `Inspect workflows.get using POST /api/query with ${JSON.stringify({ json: { name: "workflows.get", args: { id: runId } } })}. Correct event delivery before using the existing retry/replay control; a late signal cannot resurrect a terminal run.`,
485
+ capability: "application",
486
+ correlationId: runId
487
+ });
488
+ }
489
+ };
490
+ var WorkflowWaitStateError = class extends RuntimeDiagnosticError {
491
+ errorCode = "workflow_wait_state_unrecoverable";
492
+ constructor(runId) {
493
+ super({
494
+ code: "RUNTIME_WORKFLOW_WAIT_STATE_UNRECOVERABLE",
495
+ stage: "request",
496
+ servingStarted: "unchanged",
497
+ dataImpact: "unknown",
498
+ retryable: false,
499
+ retryPrecondition: "An existing consumed signal/receipt cannot be safely associated with this occurrence. Repeating the same wait cannot reconstruct its history.",
500
+ nextAction: `Inspect workflows.get using POST /api/query with ${JSON.stringify({ json: { name: "workflows.get", args: { id: runId } } })} and prior effects. Use the existing explicit replay/migration recovery contract only after review; do not edit receipts or applied state.`,
501
+ capability: "application",
502
+ correlationId: runId
503
+ });
504
+ }
505
+ };
506
+ var WorkflowPauseSignal = class extends Error {
507
+ intent;
508
+ constructor(intent) {
509
+ super("Runtime workflow paused");
510
+ this.intent = intent;
511
+ this.name = "WorkflowPauseSignal";
512
+ }
513
+ };
514
+
515
+ // ../runtime/dist/workflow/legacy-errors.js
516
+ var WorkflowLegacyStateError = class extends RuntimeDiagnosticError {
517
+ errorCode = "workflow_legacy_state_unrecoverable";
518
+ constructor(id) {
519
+ super({
520
+ code: "RUNTIME_WORKFLOW_LEGACY_STATE_UNRECOVERABLE",
521
+ stage: "request",
522
+ servingStarted: "unchanged",
523
+ dataImpact: "unknown",
524
+ retryable: false,
525
+ retryPrecondition: "Existing legacy checkpoint/wait metadata cannot be safely resumed. Retain its original data and review prior effects before an explicit replay.",
526
+ nextAction: `Inspect workflows.get using POST /api/query with ${JSON.stringify({ json: { name: "workflows.get", args: { id } } })}. Use existing authorized migration/replay controls after review; do not edit or delete checkpoints/events.`,
527
+ capability: "application",
528
+ correlationId: id
529
+ });
530
+ }
531
+ };
532
+
533
+ // ../runtime/dist/workflow/read-failure-presentation.js
534
+ var workflowProviderCodes = /* @__PURE__ */ new Set([
535
+ "AI_ADMISSION_UNAVAILABLE",
536
+ "AI_TIER_QUEUE_WAIT_EXCEEDED",
537
+ "AI_PROVIDER_ROUTING_UNAVAILABLE"
538
+ ]);
539
+ var workflowControlCauseCoverage = {
540
+ cancelled: true,
541
+ workflow_active_timeout: true,
542
+ active_timeout: true,
543
+ lifecycle_timeout: true,
544
+ resume_queue_timeout: true,
545
+ workflow_max_duration: true
546
+ };
547
+ var workflowControlCauses = Object.keys(workflowControlCauseCoverage);
548
+ function workflowCheckpointFailure(code, correlationId) {
549
+ for (const kind of ["step", "result"]) {
550
+ for (const reason of ["size", "serialization"]) {
551
+ const failure = new RuntimeWorkflowCheckpointError(kind, correlationId, reason);
552
+ if (failure.errorCode === code || failure.diagnostic.code === code)
553
+ return failure;
554
+ }
555
+ }
556
+ return void 0;
557
+ }
558
+ function workflowOwnedReadFailureCandidates(code, runId) {
559
+ const candidates = [
560
+ new WorkflowWaitTimeoutError(runId),
561
+ new WorkflowWaitStateError(runId),
562
+ new WorkflowLegacyStateError(runId),
563
+ new WorkflowWaitPersistenceError(runId, null),
564
+ ...["read", "begin", "complete", "fail", "unknown"].map((operation) => new WorkflowCheckpointPersistenceError(runId, operation, null))
565
+ ];
566
+ return candidates.filter((failure) => "errorCode" in failure && failure.errorCode === code || failure.diagnostic.code === code);
567
+ }
568
+ function workflowOwnedReadFailure(code, runId) {
569
+ const candidates = workflowOwnedReadFailureCandidates(code, runId);
570
+ if (!candidates.length)
571
+ return void 0;
572
+ const unknown = new WorkflowCheckpointPersistenceError(runId, "unknown", null);
573
+ if ("errorCode" in unknown && unknown.errorCode === code || unknown.diagnostic.code === code)
574
+ return unknown;
575
+ return candidates[0];
576
+ }
577
+ function safeWorkflowReadDiagnostic(input, runId, correlationId, retryable = input.retryable) {
578
+ const diagnostic = { ...input, correlationId, retryable };
579
+ const payload = JSON.stringify({ json: { name: "workflows.get", args: { id: runId } } });
580
+ const safePayload = payload.replace(/[\u007f-\uffff]/g, (value) => "\\u" + value.charCodeAt(0).toString(16).padStart(4, "0"));
581
+ return {
582
+ ...diagnostic,
583
+ nextAction: diagnostic.nextAction.replaceAll(payload, safePayload)
584
+ };
585
+ }
586
+ function workflowOwnedReadDiagnostic(failure, runId, correlationId, retryable = failure.diagnostic.retryable) {
587
+ return safeWorkflowReadDiagnostic(failure.diagnostic, runId, correlationId, retryable);
588
+ }
589
+ function workflowControlReadFailureCandidates(code, runId) {
590
+ return workflowControlCauses.filter((cause) => cause === code).map((cause) => ({ cause, diagnostic: workflowControlDiagnostic(runId, cause) }));
591
+ }
592
+ function workflowSearchReadFailureCandidates(code, runId, correlationId) {
593
+ const diagnostics = [];
594
+ if (code === requestContextInputError().diagnostic.code) {
595
+ const mapper = requestContextInputError();
596
+ diagnostics.push(workflowProviderDiagnostic(new RuntimeDiagnosticError({ ...mapper.diagnostic, correlationId }), runId, correlationId));
597
+ }
598
+ if (Object.hasOwn(searchFailurePresentations, code)) {
599
+ for (const context of ["database", "binding"]) {
600
+ const producer = new RuntimeSearchError(code, correlationId, "request", context);
601
+ diagnostics.push(workflowProviderDiagnostic(producer, runId, correlationId));
602
+ }
603
+ }
604
+ if (isRagSearchCode(code)) {
605
+ diagnostics.push(workflowProviderDiagnostic(new RuntimeRagSearchError(code, correlationId), runId, correlationId));
606
+ }
607
+ return diagnostics;
608
+ }
609
+ function workflowSearchReadFallback(code, runId, correlationId) {
610
+ const mapper = workflowSearchReadFailureCandidates(code, runId, correlationId);
611
+ if (code === requestContextInputError().diagnostic.code)
612
+ return mapper[0];
613
+ const search = Object.hasOwn(searchFailurePresentations, code);
614
+ const rag = isRagSearchCode(code);
615
+ if (search && rag)
616
+ return void 0;
617
+ if (search)
618
+ return void 0;
619
+ return rag ? mapper[0] : void 0;
620
+ }
621
+ function isWorkflowCheckpointFailureCode(code) {
622
+ return workflowCheckpointFailure(code, "checkpoint-code-check") !== void 0;
623
+ }
624
+ function isWorkflowControlFailureCode(code) {
625
+ return workflowControlCauses.some((cause) => cause === code);
626
+ }
627
+ function isWorkflowSearchFailureCode(code) {
628
+ return code === requestContextInputError().diagnostic.code || Object.hasOwn(searchFailurePresentations, code) || isRagSearchCode(code);
629
+ }
630
+ function isTerminalStepFailure(code) {
631
+ return code === "workflow_step_failed";
632
+ }
633
+ function isKnownWorkflowFailureCode(code) {
634
+ return isRuntimeRequestFailureCode(code) || workflowProviderCodes.has(code) || isWorkflowCheckpointFailureCode(code) || isWorkflowControlFailureCode(code) || isWorkflowSearchFailureCode(code) || workflowOwnedReadFailure(code, "owned-code-check") !== void 0;
635
+ }
636
+ function workflowInspectionId(id) {
637
+ return JSON.stringify(id).replace(/[\u007f-\uffff]/g, (value) => "\\u" + value.charCodeAt(0).toString(16).padStart(4, "0"));
638
+ }
639
+ function workflowSafeCorrelation(id) {
640
+ return /^[A-Za-z0-9._-]{1,128}$/u.test(id) ? id : "existing-run";
641
+ }
642
+ function withExactWorkflowInspection(message, id) {
643
+ const command = "workflows.get({ id: " + workflowInspectionId(id) + " })";
644
+ const request = JSON.stringify({ json: { name: "workflows.get", args: { id } } }).replace(/[\u007f-\uffff]/g, (value) => "\\u" + value.charCodeAt(0).toString(16).padStart(4, "0"));
645
+ const httpCommand = "POST /api/query with " + request;
646
+ return message.includes(command) || message.includes(httpCommand) ? message : message + "\nInspect " + command + " for this same run and preserve its checkpoints and prior effects.";
647
+ }
648
+ function publicWorkflowCode(code) {
649
+ return code === "active_timeout" ? "workflow_active_timeout" : code;
650
+ }
651
+ function mayNeedWorkflowFailureRow(summary) {
652
+ const active = summary.status === "failed" || summary.derivedStatus === "queued";
653
+ const cancelled = summary.status === "cancelled" && summary.errorCode === "cancelled";
654
+ return (active || cancelled) && (summary.errorCode === "workflow_error" || isTerminalStepFailure(summary.errorCode) || Boolean(summary.errorCode && isKnownWorkflowFailureCode(summary.errorCode)));
655
+ }
656
+ function sourceMatchesSummary(summary, row) {
657
+ if (row.error_code === "cancelled" || summary.errorCode === "cancelled")
658
+ return row.error_code === "cancelled" && row.status === "cancelled" && summary.errorCode === "cancelled" && summary.status === "cancelled";
659
+ return summary.errorCode === publicWorkflowCode(row.error_code) && (row.status === "failed" && summary.status === "failed" || row.status === "queued" && summary.status === "pending" && summary.derivedStatus === "queued");
660
+ }
661
+ function persistedProviderMessage(diagnostic, status) {
662
+ return formatRuntimeDiagnostic({ ...diagnostic, retryable: status === "queued" });
663
+ }
664
+ function knownWorkflowProducerMessage(code, id, status, stored, mode = "run") {
665
+ if (stored.length > 16384)
666
+ return void 0;
667
+ const correlation = /^Correlation ID: ([A-Za-z0-9._-]{1,128})$/mu.exec(stored)?.[1];
668
+ const candidates = [];
669
+ const retryCorrections = [];
670
+ const addProviderCandidate = (diagnostic) => {
671
+ const presented = mode === "step" ? formatRuntimeDiagnostic(diagnostic) : persistedProviderMessage(diagnostic, status);
672
+ candidates.push(presented);
673
+ if (mode === "run")
674
+ candidates.push(workflowDiagnosticFailureMessage(diagnostic, status === "queued"));
675
+ const source = formatRuntimeDiagnostic(diagnostic);
676
+ if (mode === "run" && source !== presented)
677
+ retryCorrections.push({ stored: source, presented });
678
+ };
679
+ if (mode === "run" && (code === "RUNTIME_WORKFLOW_HANDLER_FAILED" || code === "workflow_error") && correlation)
680
+ candidates.push(workflowFailureMessage({ kind: "handler", correlationId: correlation }, id, status === "queued"));
681
+ if ((mode === "run" && code === "RUNTIME_WORKFLOW_STEP_FAILED" || mode === "step" && code === "step_error") && correlation)
682
+ candidates.push(workflowStepFailureMessage(id, correlation));
683
+ if (mode === "run" && code === "workflow_error")
684
+ return candidates.find((message) => message === stored);
685
+ for (const { cause } of workflowControlReadFailureCandidates(code, id)) {
686
+ const controlRetryStates = mode === "step" ? [false] : [false, true];
687
+ for (const retrying of controlRetryStates) {
688
+ const source = formatRuntimeDiagnostic({
689
+ ...workflowControlDiagnostic(id, cause, retrying),
690
+ correlationId: id
691
+ });
692
+ if (source !== stored)
693
+ continue;
694
+ const diagnostic = workflowControlDiagnostic(id, cause, mode === "run" ? status === "queued" : retrying);
695
+ return withExactWorkflowInspection(formatRuntimeDiagnostic(safeWorkflowReadDiagnostic(diagnostic, id, workflowSafeCorrelation(id))), id);
696
+ }
697
+ }
698
+ if (!correlation)
699
+ return void 0;
700
+ for (const diagnostic of workflowSearchReadFailureCandidates(code, id, correlation))
701
+ addProviderCandidate(diagnostic);
702
+ for (const ownedFailure of workflowOwnedReadFailureCandidates(code, id)) {
703
+ const ownedDiagnostic = { ...ownedFailure.diagnostic, correlationId: correlation };
704
+ const source = formatRuntimeDiagnostic(ownedDiagnostic);
705
+ const exactWriterMessage = mode === "run" && [true, false].some((retrying) => workflowDiagnosticFailureMessage(ownedDiagnostic, retrying) === stored);
706
+ if (source === stored || exactWriterMessage) {
707
+ const diagnostic = workflowOwnedReadDiagnostic(ownedFailure, id, correlation, mode === "run" ? status === "queued" : ownedFailure.diagnostic.retryable);
708
+ return withExactWorkflowInspection(formatRuntimeDiagnostic(diagnostic), id);
709
+ }
710
+ }
711
+ const checkpointFailure = workflowCheckpointFailure(code, correlation);
712
+ if (checkpointFailure) {
713
+ const source = formatRuntimeDiagnostic(checkpointFailure.diagnostic);
714
+ const presented = formatRuntimeDiagnostic({
715
+ ...checkpointFailure.diagnostic,
716
+ retryable: status === "queued"
717
+ });
718
+ candidates.push(presented);
719
+ candidates.push(workflowDiagnosticFailureMessage(checkpointFailure.diagnostic, status === "queued"));
720
+ if (source !== presented)
721
+ retryCorrections.push({ stored: source, presented });
722
+ }
723
+ if (isDocumentConversionErrorCode(code)) {
724
+ for (const dependency of [void 0, "pdf-parse", "mammoth", "provided-parser"]) {
725
+ const producer = new DocumentConversionError(code, correlation, dependency);
726
+ addProviderCandidate(workflowProviderDiagnostic(producer, id, correlation));
727
+ }
728
+ }
729
+ if (ragSourceErrorCodes.includes(code))
730
+ addProviderCandidate(workflowProviderDiagnostic(ragSourceError(code, correlation), id, correlation));
731
+ if (isRagIngestErrorCode(code))
732
+ addProviderCandidate(workflowProviderDiagnostic(ragIngestError(code, correlation), id, correlation));
733
+ if (code === "RUNTIME_AUTHENTICATION_REQUIRED")
734
+ addProviderCandidate(workflowProviderDiagnostic(new RuntimeSearchError(code, correlation), id, correlation));
735
+ if (code === "RUNTIME_SCHEDULER_INPUT_INVALID")
736
+ addProviderCandidate(workflowProviderDiagnostic(schedulerFailure(code, "Provide a finite, non-negative delay.", "request", correlation), id, correlation));
737
+ const storageCandidates = [];
738
+ if (code === "RUNTIME_STORAGE_METADATA_INVALID")
739
+ storageCandidates.push(filesystemMetadataInvalid());
740
+ if (code === "RUNTIME_STORAGE_OBJECT_NOT_FOUND")
741
+ storageCandidates.push(filesystemObjectNotFound());
742
+ if (code === "RUNTIME_STORAGE_ACCESS_DENIED") {
743
+ for (const osCode of ["EACCES", "EPERM", "EROFS"]) {
744
+ const failure = filesystemFailure({ code: osCode }, true);
745
+ if (failure instanceof RuntimeDiagnosticError)
746
+ storageCandidates.push(failure);
747
+ }
748
+ }
749
+ if (code === "RUNTIME_STORAGE_PROVIDER_UNAVAILABLE") {
750
+ for (const write of [false, true]) {
751
+ const failure = filesystemFailure({ code: "EIO" }, write);
752
+ if (failure instanceof RuntimeDiagnosticError)
753
+ storageCandidates.push(failure);
754
+ }
755
+ }
756
+ if (code === "RUNTIME_STORAGE_FILE_TOO_LARGE") {
757
+ const limit = /Submit a file of at most (\d{1,16}) bytes only if the operation is still intended\./u.exec(stored)?.[1];
758
+ const parsedLimit = limit === void 0 ? null : Number(limit);
759
+ if (Number.isSafeInteger(parsedLimit) && parsedLimit >= 0 && parsedLimit < Number.MAX_SAFE_INTEGER) {
760
+ try {
761
+ assertRuntimeFileSize(parsedLimit + 1, parsedLimit);
762
+ } catch (error) {
763
+ if (error instanceof RuntimeDiagnosticError)
764
+ storageCandidates.push(error);
765
+ }
766
+ }
767
+ }
768
+ for (const producer of storageCandidates) {
769
+ const workflowDiagnostic = workflowProviderDiagnostic(producer, id, correlation);
770
+ addProviderCandidate(workflowDiagnostic);
771
+ }
772
+ if (["AI_ADMISSION_UNAVAILABLE", "AI_TIER_QUEUE_WAIT_EXCEEDED", "AI_PROVIDER_ROUTING_UNAVAILABLE"].includes(code)) {
773
+ const delay = /gateway-requested (\d{1,16}) ms provider delay/u.exec(stored)?.[1];
774
+ const delayMs = delay === void 0 ? null : Number(delay);
775
+ const parsedDelay = Number.isSafeInteger(delayMs) && delayMs >= 0 ? delayMs : null;
776
+ for (const candidateDelay of parsedDelay === null ? [null] : [null, parsedDelay]) {
777
+ const producer = ragEmbeddingGatewayRetryError(correlation, code, candidateDelay);
778
+ candidates.push(mode === "step" ? formatRuntimeDiagnostic(producer.diagnostic) : workflowDiagnosticFailureMessage(producer.diagnostic, status === "queued"));
779
+ }
780
+ }
781
+ if (code === "RUNTIME_CAPABILITY_UNAVAILABLE") {
782
+ for (const capability of [
783
+ "storage",
784
+ "database",
785
+ "system database",
786
+ "scheduler",
787
+ "realtime",
788
+ "services",
789
+ "search",
790
+ "vector search",
791
+ "hybrid search",
792
+ "grounding",
793
+ "retry"
794
+ ]) {
795
+ const diagnostic = workflowCapabilityDiagnostic(new RuntimeCapabilityUnavailableError(capability, { correlationId: correlation }), id, correlation);
796
+ candidates.push(mode === "step" ? formatRuntimeDiagnostic(diagnostic) : persistedProviderMessage(diagnostic, status));
797
+ if (mode === "run")
798
+ candidates.push(workflowDiagnosticFailureMessage(diagnostic, status === "queued"));
799
+ }
800
+ }
801
+ return candidates.find((message) => message === stored) ?? (mode === "run" ? retryCorrections.find((candidate) => candidate.stored === stored)?.presented : void 0);
802
+ }
803
+ function workflowFailurePresentation(row) {
804
+ const terminalOrRetrying = row.status === "failed" || row.status === "queued";
805
+ const canonicalCancellation = row.status === "cancelled" && row.error_code === "cancelled";
806
+ if (!terminalOrRetrying && !canonicalCancellation || !row.error_code)
807
+ return void 0;
808
+ if (row.error_code === "cancelled" && !canonicalCancellation)
809
+ return void 0;
810
+ if (row.status === "cancelled" && !canonicalCancellation)
811
+ return void 0;
812
+ if (row.error_code !== "workflow_error" && !isKnownWorkflowFailureCode(row.error_code))
813
+ return void 0;
814
+ const id = row.id;
815
+ const stored = row.error_message ?? "";
816
+ const exact = knownWorkflowProducerMessage(row.error_code, id, row.status, stored);
817
+ if (row.error_code === "workflow_error") {
818
+ const producer = row.producer_code;
819
+ const known = producer && (isKnownWorkflowFailureCode(producer) || isDocumentConversionErrorCode(producer) || isRagIngestErrorCode(producer) || producer === "RUNTIME_CAPABILITY_UNAVAILABLE") ? knownWorkflowProducerMessage(producer, id, row.status, stored) : void 0;
820
+ return known || exact ? withExactWorkflowInspection(known ?? exact, id) : void 0;
821
+ }
822
+ if (exact && (row.status !== "queued" || exact.includes("Retryable: yes")))
823
+ return withExactWorkflowInspection(exact, id);
824
+ const retryable = row.status === "queued";
825
+ const inspection = workflowInspectionId(id);
826
+ const safeCorrelation = workflowSafeCorrelation(id);
827
+ const control = workflowControlReadFailureCandidates(row.error_code, id).find(({ cause }) => cause === row.error_code);
828
+ if (control) {
829
+ const diagnostic = workflowControlDiagnostic(id, control.cause, retryable);
830
+ return withExactWorkflowInspection(formatRuntimeDiagnostic(safeWorkflowReadDiagnostic(diagnostic, id, safeCorrelation, retryable)), id);
831
+ }
832
+ const search = workflowSearchReadFallback(row.error_code, id, safeCorrelation);
833
+ if (search)
834
+ return withExactWorkflowInspection(persistedProviderMessage(search, row.status), id);
835
+ const ownedFailure = workflowOwnedReadFailure(row.error_code, id);
836
+ if (ownedFailure) {
837
+ return withExactWorkflowInspection(formatRuntimeDiagnostic(workflowOwnedReadDiagnostic(ownedFailure, id, safeCorrelation, retryable)), id);
838
+ }
839
+ const checkpointFailure = workflowCheckpointFailure(row.error_code, safeCorrelation);
840
+ if (checkpointFailure) {
841
+ return withExactWorkflowInspection(formatRuntimeDiagnostic({
842
+ ...checkpointFailure.diagnostic,
843
+ retryable,
844
+ correlationId: safeCorrelation
845
+ }), id);
846
+ }
847
+ const documentRecovery = runtimeDocumentRecoveryAction(row.error_code);
848
+ const auth = row.error_code === "RUNTIME_AUTHENTICATION_REQUIRED" ? workflowProviderDiagnostic(new RuntimeSearchError("RUNTIME_AUTHENTICATION_REQUIRED", safeCorrelation, "workflow"), id, safeCorrelation) : void 0;
849
+ return formatRuntimeDiagnostic({
850
+ code: row.error_code === "workflow_error" ? "RUNTIME_WORKFLOW_HANDLER_FAILED" : row.error_code,
851
+ stage: "workflow",
852
+ capability: auth ? "auth" : "application",
853
+ servingStarted: "unchanged",
854
+ dataImpact: "unknown",
855
+ retryable,
856
+ retryPrecondition: auth ? (retryable ? "The canonical Workflow owner has already scheduled this same run for retry. " : "No automatic retry remains for this run. ") + auth.retryPrecondition + " Inspect this same run's completed checkpoints before any supported same-run retry." : retryable ? "The canonical Workflow owner has already scheduled this same run for retry; inspect completed checkpoints and prior effects before it resumes." : "No automatic retry remains for this run. Inspect this same run's completed checkpoints and prior effects before any supported same-run recovery.",
857
+ nextAction: documentRecovery ? documentRecovery + " Inspect workflows.get({ id: " + inspection + " }) and preserve this same run; do not replay prior external effects." : auth ? auth.nextAction + " Inspect workflows.get({ id: " + inspection + " }) and preserve this same run; " + (retryable ? "sign in with the intended owner before the already scheduled same-run retry proceeds." : "sign in with the intended owner before any supported explicit same-run retry.") + " Do not replay prior external effects blindly." : "Inspect workflows.get({ id: " + inspection + " }) and review this same run's status, completed checkpoints and prior effects. " + (retryable ? "The canonical Workflow owner has already scheduled this same run for retry." : "No automatic retry remains for this run.") + " Preserve its identity; resolve the diagnosed workflow or selected dependency condition before any supported same-run retry. Do not start replacement work or blindly repeat external effects.",
858
+ correlationId: safeCorrelation
859
+ });
860
+ }
861
+ var publicWorkflowProducerCodes = /* @__PURE__ */ new Set([
862
+ "RAG_EMBEDDING_PROVIDER_UNAVAILABLE",
863
+ "RAG_EMBEDDING_OUTCOME_UNKNOWN",
864
+ "DOCUMENT_CONVERSION_MODE_REQUIRED",
865
+ "RAG_SEARCH_TABLE_UNAVAILABLE",
866
+ "RUNTIME_CAPABILITY_UNAVAILABLE",
867
+ "RUNTIME_AUTHENTICATION_REQUIRED",
868
+ "RUNTIME_DATABASE_RLS_CONTEXT_INVALID",
869
+ "SEARCH_DATABASE_ACCESS_DENIED",
870
+ "SEARCH_DATABASE_TIMEOUT",
871
+ "SEARCH_DATABASE_UNAVAILABLE"
872
+ ]);
873
+ function verifiedWorkflowPublicProducer(row) {
874
+ const code = row.producer_code;
875
+ if (!code || !publicWorkflowProducerCodes.has(code))
876
+ return void 0;
877
+ if (isTerminalStepFailure(row.error_code)) {
878
+ if (row.status !== "failed" || code !== "RUNTIME_AUTHENTICATION_REQUIRED")
879
+ return void 0;
880
+ } else if (row.error_code !== "workflow_error" || row.status !== "failed" && row.status !== "queued") {
881
+ return void 0;
882
+ }
883
+ const message = knownWorkflowProducerMessage(code, row.id, row.status, row.error_message ?? "");
884
+ return message ? { code, message } : void 0;
885
+ }
886
+ function verifiedWorkflowRagJobFailure(row) {
887
+ if (row.status !== "failed")
888
+ return void 0;
889
+ const code = row.error_code === "workflow_error" ? row.producer_code : row.error_code;
890
+ if (!code || row.error_code !== "workflow_checkpoint_persistence_unavailable" && !isDocumentConversionErrorCode(code))
891
+ return void 0;
892
+ const message = knownWorkflowProducerMessage(code, row.id, row.status, row.error_message ?? "");
893
+ return message ? withExactWorkflowInspection(message, row.id) : void 0;
894
+ }
895
+ function workflowStepFailurePresentation(id, row) {
896
+ if (row.status !== "failed")
897
+ return void 0;
898
+ const exact = row.error_code ? knownWorkflowProducerMessage(row.error_code, id, "failed", row.error_message ?? "", "step") : void 0;
899
+ if (exact)
900
+ return withExactWorkflowInspection(exact, id);
901
+ const producer = row.producer_code;
902
+ if (row.error_code === "step_error" && producer && (isKnownWorkflowFailureCode(producer) || isDocumentConversionErrorCode(producer) || isRagIngestErrorCode(producer) || producer === "RUNTIME_CAPABILITY_UNAVAILABLE")) {
903
+ const known = knownWorkflowProducerMessage(producer, id, "failed", row.error_message ?? "", "step");
904
+ if (known)
905
+ return withExactWorkflowInspection(known, id);
906
+ }
907
+ return workflowStepFailureMessage(id, workflowSafeCorrelation(id));
908
+ }
909
+ function applyWorkflowStepFailures(id, value, rows) {
910
+ const byKey = new Map(rows.map((row) => [row.step_key, row]));
911
+ return {
912
+ ...value,
913
+ steps: value.steps.map((step) => {
914
+ if (step.status !== "failed")
915
+ return step;
916
+ const row = byKey.get(step.name);
917
+ if (!row || row.status !== "failed")
918
+ return step;
919
+ const error = workflowStepFailurePresentation(id, row);
920
+ return error ? { ...step, error } : step;
921
+ })
922
+ };
923
+ }
924
+ function applyWorkflowFailure(value, row) {
925
+ if (!row || !sourceMatchesSummary(value, row))
926
+ return value;
927
+ const verified = verifiedWorkflowPublicProducer(row);
928
+ const error = verified ? withExactWorkflowInspection(verified.message, row.id) : workflowFailurePresentation(row);
929
+ if (!error && row.error_code === "workflow_error")
930
+ return { ...value, errorDetail: null };
931
+ if (!error)
932
+ return value;
933
+ return { ...value, error, errorCode: verified?.code ?? value.errorCode };
934
+ }
935
+
936
+ // ../runtime/dist/rag/job-diagnostic.js
937
+ var sourceCodes = new Set(ragSourceErrorCodes);
938
+ var controls = /* @__PURE__ */ new Set([
939
+ "cancelled",
940
+ "workflow_active_timeout",
941
+ "active_timeout",
942
+ "lifecycle_timeout",
943
+ "resume_queue_timeout",
944
+ "workflow_max_duration"
945
+ ]);
946
+ var embeddingGatewayCodes = /* @__PURE__ */ new Set([
947
+ "AI_ADMISSION_UNAVAILABLE",
948
+ "AI_TIER_QUEUE_WAIT_EXCEEDED",
949
+ "AI_PROVIDER_ROUTING_UNAVAILABLE"
950
+ ]);
951
+ function ragJobDiagnostic(row, options = {}) {
952
+ if (row.observed_status !== "failed" && row.observed_status !== "canceled")
953
+ return null;
954
+ if (controls.has(row.error_code ?? ""))
955
+ return workflowControlMessage(safeRunId(row.workflow_id), row.error_code);
956
+ const message = row.error_message ?? "";
957
+ const correlation = /^Correlation ID: ([A-Za-z0-9._-]{1,128})$/mu.exec(message)?.[1];
958
+ const workflow = {
959
+ id: row.workflow_id,
960
+ status: row.observed_status,
961
+ error_code: row.error_code,
962
+ error_message: row.error_message,
963
+ producer_code: row.producer_code
964
+ };
965
+ const workflowFailure = verifiedWorkflowRagJobFailure(workflow);
966
+ if (workflowFailure)
967
+ return workflowFailure;
968
+ const verifiedCode = verifiedWorkflowPublicProducer(workflow)?.code;
969
+ const code = verifiedCode && isRagIngestErrorCode(verifiedCode) ? verifiedCode : row.error_code ?? "";
970
+ if (code === "workflow_checkpoint_persistence_unavailable") {
971
+ return new WorkflowCheckpointPersistenceError(safeRunId(row.workflow_id), "unknown", void 0).message;
972
+ }
973
+ if (embeddingGatewayCodes.has(code)) {
974
+ const delayText = /gateway-requested (\d{1,16}) ms provider delay/u.exec(message)?.[1];
975
+ const parsedDelay = delayText === void 0 ? null : Number(delayText);
976
+ const retry = ragEmbeddingGatewayRetryError(correlation ?? safeRunId(row.workflow_id), code, Number.isSafeInteger(parsedDelay) && parsedDelay >= 0 ? parsedDelay : null);
977
+ if (message === workflowDiagnosticFailureMessage(retry.diagnostic, true) || message === workflowDiagnosticFailureMessage(retry.diagnostic, false))
978
+ return message;
979
+ return formatRuntimeDiagnostic({
980
+ ...retry.diagnostic,
981
+ dataImpact: "unknown",
982
+ retryable: false,
983
+ retryPrecondition: "Inspect this same run's provider outcome and completed checkpoints before an authorized same-run retry.",
984
+ nextAction: `The trusted embedding gateway returned ${code}. Inspect rag_ingest_jobs.get and workflows.get for this same run, preserve committed source/index data, and do not start replacement work or blindly repeat provider calls.`,
985
+ correlationId: safeRunId(row.workflow_id)
986
+ });
987
+ }
988
+ if (isRagIngestErrorCode(code)) {
989
+ const impact = /^Data impact: (none|committed|unknown)$/mu.exec(message)?.[1];
990
+ const producer = ragIngestError(code, correlation ?? safeRunId(row.workflow_id), impact ?? "unknown");
991
+ if (message === producer.message || message === formatRuntimeDiagnostic(workflowProviderDiagnostic(producer, safeRunId(row.workflow_id), producer.diagnostic.correlationId)))
992
+ return message;
993
+ return ragIngestError(code, safeRunId(row.workflow_id)).message;
994
+ }
995
+ const candidates = options.jobDiagnosticCandidates ? options.jobDiagnosticCandidates(code, correlation) : isDocumentConversionErrorCode(code) ? [void 0, "pdf-parse", "mammoth"].map((dependency) => new DocumentConversionError(code, correlation, dependency)) : [];
996
+ for (const producer of candidates) {
997
+ if (message === producer.message || message === formatRuntimeDiagnostic(workflowProviderDiagnostic(producer, safeRunId(row.workflow_id), correlation ?? safeRunId(row.workflow_id))))
998
+ return message;
999
+ }
1000
+ if (sourceCodes.has(row.error_code ?? "")) {
1001
+ const impact = /^Data impact: (none|committed|unknown)$/mu.exec(message)?.[1];
1002
+ const producer = ragSourceError(row.error_code, correlation ?? safeRunId(row.workflow_id), impact ?? "unknown");
1003
+ if (message === producer.message || message === formatRuntimeDiagnostic(workflowProviderDiagnostic(producer, safeRunId(row.workflow_id), producer.diagnostic.correlationId)))
1004
+ return message;
1005
+ return ragSourceError(row.error_code, safeRunId(row.workflow_id), "unknown").message;
1006
+ }
1007
+ const diagnosis = {
1008
+ code: row.error_code ?? "RUNTIME_OPERATION_EXECUTION_FAILED",
1009
+ stage: "workflow",
1010
+ capability: "application",
1011
+ servingStarted: "unchanged",
1012
+ dataImpact: "unknown",
1013
+ retryable: false,
1014
+ retryPrecondition: "Inspect this same run's completed checkpoints and prior external effects before an authorized same-run retry.",
1015
+ nextAction: `Inspect rag_ingest_jobs.get and workflows.get for this same job/run. Preserve their identities; do not edit internal rows or blindly repeat conversion.`,
1016
+ correlationId: safeRunId(row.workflow_id)
1017
+ };
1018
+ const known = isRuntimeRequestFailureCode(diagnosis.code);
1019
+ return formatRuntimeDiagnostic({
1020
+ ...diagnosis,
1021
+ code: known ? diagnosis.code : "RUNTIME_OPERATION_EXECUTION_FAILED"
1022
+ });
1023
+ }
1024
+ function safeRunId(id) {
1025
+ return /^[A-Za-z0-9._-]{1,128}$/u.test(id) ? id : "existing-run";
1026
+ }
1027
+
1028
+ // ../runtime/dist/adapters/rag/pgvector/job-store.js
1029
+ function createRagJobStore(database, options = {}) {
1030
+ const captured = Object.freeze({ jobDiagnosticCandidates: options.jobDiagnosticCandidates });
1031
+ return Object.freeze({
1032
+ scope(requireIdentity) {
1033
+ async function read(filters) {
1034
+ try {
1035
+ const before = requireIdentity();
1036
+ if (!before)
1037
+ throw new RuntimeDiagnosticError({
1038
+ code: "RUNTIME_AUTHENTICATION_REQUIRED",
1039
+ stage: "request",
1040
+ capability: "auth",
1041
+ servingStarted: "unchanged",
1042
+ dataImpact: "none",
1043
+ retryable: false,
1044
+ retryPrecondition: "Authenticate before inspecting RAG jobs.",
1045
+ nextAction: "Sign in as the intended job owner and repeat this read. No data changed."
1046
+ });
1047
+ const identity = before.id;
1048
+ const assertScope = () => {
1049
+ if (requireIdentity()?.id !== identity)
1050
+ throw ragJobError("RAG_JOB_OBSERVATION_UNAVAILABLE");
1051
+ };
1052
+ const result = await readRagJobs(database, identity, filters, assertScope);
1053
+ assertScope();
1054
+ return result.map((row) => project(row, captured));
1055
+ } catch (error) {
1056
+ if (runtimeDiagnostic(error))
1057
+ throw error;
1058
+ throw ragJobError("RAG_JOB_OBSERVATION_UNAVAILABLE");
1059
+ }
1060
+ }
1061
+ async function get(input) {
1062
+ if (!input || typeof input.id !== "string" || !input.id.trim() || input.id.length > 128)
1063
+ throw ragJobError("RAG_JOB_INPUT_INVALID");
1064
+ return (await read({ id: input.id.trim() }))[0] ?? null;
1065
+ }
1066
+ async function list(input) {
1067
+ if (!input || input.limit !== void 0 && (typeof input.limit !== "number" || !Number.isFinite(input.limit)) || input.status !== void 0 && input.status !== "" && !ragJobStatuses.includes(input.status) || input.corpus !== void 0 && typeof input.corpus !== "string")
1068
+ throw ragJobError("RAG_JOB_INPUT_INVALID");
1069
+ return read({
1070
+ limit: input.limit === void 0 ? 20 : Math.max(1, Math.min(100, Math.floor(input.limit))),
1071
+ status: input.status || void 0,
1072
+ corpus: input.corpus?.trim() || void 0
1073
+ });
1074
+ }
1075
+ return Object.freeze({ get, list });
1076
+ }
1077
+ });
1078
+ }
1079
+ function project(row, options) {
1080
+ if (!row.valid)
1081
+ throw ragJobError("RAG_JOB_STATE_INVALID");
1082
+ const terminal = ["completed", "failed", "canceled"].includes(row.observed_status);
1083
+ return {
1084
+ id: row.id,
1085
+ workflowId: row.workflow_id,
1086
+ sourceId: row.source_id,
1087
+ corpus: row.corpus,
1088
+ visibility: row.visibility_scope,
1089
+ ownerUserId: row.owner_user_id,
1090
+ status: row.observed_status,
1091
+ stage: terminal ? row.observed_status : row.stage !== null && ragJobStages.includes(row.stage) && !["completed", "failed", "canceled"].includes(row.stage) ? row.stage : row.observed_status,
1092
+ providerTrace: row.provider_trace,
1093
+ metrics: row.metrics,
1094
+ error: ragJobDiagnostic(row, options),
1095
+ startedAt: new Date(row.started_at).toISOString(),
1096
+ completedAt: row.terminal_at ? new Date(row.terminal_at).toISOString() : null
1097
+ };
1098
+ }
1099
+
1100
+ export {
1101
+ ragSourceError,
1102
+ WorkflowWaitPersistenceError,
1103
+ persistWorkflowWait,
1104
+ WorkflowCheckpointPersistenceError,
1105
+ persistWorkflowCheckpoint,
1106
+ ragSearchError,
1107
+ isRagSearchCode,
1108
+ isWorkflowProviderError,
1109
+ workflowProviderDiagnostic,
1110
+ workflowCapabilityDiagnostic,
1111
+ verifiedTerminalStepAuthentication,
1112
+ StepOutputSerializationError,
1113
+ computeWorkflowStepBackoffMs,
1114
+ runWorkflowStepWithTimeout,
1115
+ workflowV2JsonString,
1116
+ serializeWorkflowCheckpoint,
1117
+ workflowCheckpointJson,
1118
+ RuntimeWorkflowCheckpointError,
1119
+ enforceWorkflowCheckpoint,
1120
+ WorkflowWaitTimeoutError,
1121
+ WorkflowWaitStateError,
1122
+ WorkflowPauseSignal,
1123
+ workflowFailureMessage,
1124
+ workflowStepFailureMessage,
1125
+ RuntimeWorkflowAbortError,
1126
+ throwIfRuntimeWorkflowAborted,
1127
+ workflowControlMessage,
1128
+ mayNeedWorkflowFailureRow,
1129
+ applyWorkflowStepFailures,
1130
+ applyWorkflowFailure,
1131
+ createRagJobStore
1132
+ };