apps 0.0.1-beta.5 → 0.0.1-beta.55

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 (188) hide show
  1. package/README.md +68 -44
  2. package/framework-reference.json +1 -1
  3. package/js/chunk-47F7VXST.js +221 -0
  4. package/js/chunk-5FHWNLCI.js +88 -0
  5. package/js/{chunk-M3B3DE4K.js → chunk-74YVXBKY.js} +463 -218
  6. package/js/chunk-7UUHJR2Q.js +49 -0
  7. package/js/{chunk-CYYBFC2K.js → chunk-AQU56EPI.js} +9 -5
  8. package/js/chunk-BTSIG4NQ.js +1885 -0
  9. package/js/chunk-CDXQDN7W.js +92 -0
  10. package/js/{chunk-UK573G7W.js → chunk-EOPQ727L.js} +87 -51
  11. package/js/{chunk-27F7W2LG.js → chunk-H2CJWXA3.js} +2 -2
  12. package/js/{chunk-JU7VHODU.js → chunk-H72MEDMN.js} +65 -10
  13. package/js/{chunk-CDL5PM2Q.js → chunk-IFJU5SYQ.js} +19082 -18402
  14. package/js/{chunk-UDDE5KOR.js → chunk-JK5S2N2S.js} +148 -34
  15. package/js/{chunk-RJDDBDSN.js → chunk-JM7LOD2W.js} +628 -85
  16. package/js/{chunk-VFZKSM3T.js → chunk-JPEUKEV4.js} +3 -3
  17. package/js/{chunk-FWQC6I3C.js → chunk-KGCTYL2S.js} +523 -63
  18. package/js/{chunk-KUMBKVJD.js → chunk-KLYSEHUD.js} +2 -2
  19. package/js/chunk-L4K2K22P.js +42 -0
  20. package/js/chunk-LTDHQJ2Z.js +171 -0
  21. package/js/chunk-MWKHKOTL.js +240 -0
  22. package/js/chunk-OD3KFKZD.js +1617 -0
  23. package/js/{chunk-57RKNWL2.js → chunk-PD6I2SDG.js} +4 -4
  24. package/js/chunk-PXXZ6ABC.js +266 -0
  25. package/js/chunk-QEBRH5AP.js +729 -0
  26. package/js/chunk-TLWLJ7PD.js +4342 -0
  27. package/js/{chunk-IJX4CYZO.js → chunk-TUMGL2OC.js} +228 -264
  28. package/js/{chunk-XHO2ZX6W.js → chunk-UM62MBJQ.js} +96 -41
  29. package/js/{chunk-IPI4MFSN.js → chunk-XBG7HHXC.js} +2 -2
  30. package/js/chunk-XCSG7FT7.js +340 -0
  31. package/js/client.js +142 -94
  32. package/js/contracts.js +123 -33
  33. package/js/effect.js +19 -21
  34. package/js/{es-APDZKREY.js → es-DIULA3ZF.js} +62 -1659
  35. package/js/graphql.js +63 -60
  36. package/js/host.js +83 -60
  37. package/js/index.js +262 -222
  38. package/js/mcp/effect.js +23 -23
  39. package/js/mcp/stdio.js +48 -40
  40. package/js/mcp.js +109 -72
  41. package/js/openapi.js +4129 -1419
  42. package/js/react.js +2 -3
  43. package/js/skills/effect.js +6 -3
  44. package/js/skills.js +208 -82
  45. package/js/storage/facet.js +1 -540
  46. package/js/ui/auth/contracts.js +2 -2
  47. package/js/ui/auth.js +5 -5
  48. package/js/ui/contracts.js +5 -4
  49. package/js/ui/serving.js +8517 -214
  50. package/package.json +2 -3
  51. package/runtime.json +1 -1
  52. package/types/app-cache/src/index.d.ts +10 -1
  53. package/types/apps/src/contracts/api-response-error.d.ts +4 -0
  54. package/types/apps/src/contracts/app.d.ts +9 -8
  55. package/types/apps/src/contracts/cache.d.ts +20 -0
  56. package/types/apps/src/contracts/context.d.ts +19 -11
  57. package/types/apps/src/contracts/elicitation.d.ts +6 -6
  58. package/types/apps/src/contracts/events.d.ts +93 -0
  59. package/types/apps/src/contracts/failure.d.ts +30 -1
  60. package/types/apps/src/contracts/graphql.d.ts +2 -1
  61. package/types/apps/src/contracts/host.d.ts +57 -18
  62. package/types/apps/src/contracts/live.d.ts +2 -0
  63. package/types/apps/src/contracts/mcp.d.ts +96 -10
  64. package/types/apps/src/contracts/network.d.ts +84 -0
  65. package/types/apps/src/contracts/openapi-compile.d.ts +32 -3
  66. package/types/apps/src/contracts/openapi.d.ts +45 -9
  67. package/types/apps/src/contracts/operations.d.ts +8 -9
  68. package/types/apps/src/contracts/protocol-version.d.ts +2 -2
  69. package/types/apps/src/contracts/protocols/1.d.ts +733 -81
  70. package/types/apps/src/contracts/protocols/10.d.ts +1450 -0
  71. package/types/apps/src/contracts/protocols/2.d.ts +69 -26
  72. package/types/apps/src/contracts/protocols/3.d.ts +133 -33
  73. package/types/apps/src/contracts/protocols/4.d.ts +1306 -0
  74. package/types/apps/src/contracts/protocols/5.d.ts +1200 -0
  75. package/types/apps/src/contracts/protocols/6.d.ts +1629 -0
  76. package/types/apps/src/contracts/protocols/7.d.ts +1785 -0
  77. package/types/apps/src/contracts/protocols/8.d.ts +1182 -0
  78. package/types/apps/src/contracts/protocols/9.d.ts +1104 -0
  79. package/types/apps/src/contracts/protocols/current.d.ts +2476 -0
  80. package/types/apps/src/contracts/protocols/oauth-6.d.ts +74 -0
  81. package/types/apps/src/contracts/protocols/oauth.d.ts +134 -0
  82. package/types/apps/src/contracts/provider-error.d.ts +9 -0
  83. package/types/apps/src/contracts/provider.d.ts +115 -10
  84. package/types/apps/src/contracts/router.d.ts +59 -0
  85. package/types/apps/src/contracts/skills.d.ts +50 -13
  86. package/types/apps/src/contracts/sql.d.ts +58 -0
  87. package/types/apps/src/contracts/ui.d.ts +19 -1
  88. package/types/apps/src/contracts/workflows.d.ts +6 -0
  89. package/types/apps/src/facet.d.ts +4 -5
  90. package/types/apps/src/graphql.d.ts +1 -3
  91. package/types/apps/src/host.d.ts +5 -0
  92. package/types/apps/src/implementation/account-router.d.ts +13 -0
  93. package/types/apps/src/implementation/app.d.ts +5 -4
  94. package/types/apps/src/implementation/authoring.d.ts +25 -5
  95. package/types/apps/src/implementation/browser-scripts.gen.d.ts +6 -0
  96. package/types/apps/src/implementation/cache.d.ts +4 -0
  97. package/types/apps/src/implementation/catalog-cache.d.ts +43 -5
  98. package/types/apps/src/implementation/elicitation.d.ts +18 -15
  99. package/types/apps/src/implementation/events.d.ts +59 -0
  100. package/types/apps/src/implementation/failure-detail.d.ts +25 -3
  101. package/types/apps/src/implementation/graphql-catalog.d.ts +4 -7
  102. package/types/apps/src/implementation/graphql.d.ts +4 -3
  103. package/types/apps/src/implementation/input-problems.d.ts +6 -2
  104. package/types/apps/src/implementation/invocation-timing.d.ts +16 -0
  105. package/types/apps/src/implementation/live.d.ts +2 -2
  106. package/types/apps/src/implementation/mcp-call.d.ts +6 -5
  107. package/types/apps/src/implementation/mcp-catalog.d.ts +7 -8
  108. package/types/apps/src/implementation/mcp-client.d.ts +49 -25
  109. package/types/apps/src/implementation/mcp-stdio.d.ts +1 -1
  110. package/types/apps/src/implementation/mcp-tools.d.ts +2 -1
  111. package/types/apps/src/implementation/mcp.d.ts +52 -25
  112. package/types/apps/src/implementation/network.d.ts +16 -0
  113. package/types/apps/src/implementation/openapi-compile.d.ts +27 -6
  114. package/types/apps/src/implementation/openapi-document.d.ts +46 -19
  115. package/types/apps/src/implementation/openapi-names.d.ts +9 -4
  116. package/types/apps/src/implementation/openapi-request.d.ts +10 -2
  117. package/types/apps/src/implementation/openapi-source.d.ts +8 -6
  118. package/types/apps/src/implementation/openapi-upgrade.d.ts +4 -0
  119. package/types/apps/src/implementation/operations.d.ts +43 -5
  120. package/types/apps/src/implementation/optimistic.d.ts +1 -1
  121. package/types/apps/src/implementation/protocol-operations.d.ts +6 -4
  122. package/types/apps/src/implementation/provider-error.d.ts +28 -1
  123. package/types/apps/src/implementation/provider.d.ts +19 -5
  124. package/types/apps/src/implementation/query-commit.d.ts +1 -1
  125. package/types/apps/src/implementation/router-catalog.d.ts +223 -0
  126. package/types/apps/src/implementation/router.d.ts +70 -0
  127. package/types/apps/src/implementation/runtime-yield.d.ts +7 -0
  128. package/types/apps/src/implementation/schema.d.ts +95 -11
  129. package/types/apps/src/implementation/skills.d.ts +18 -24
  130. package/types/apps/src/implementation/sql.d.ts +71 -0
  131. package/types/apps/src/implementation/ui-account-notice.d.ts +9 -0
  132. package/types/apps/src/implementation/ui-auth.d.ts +1 -1
  133. package/types/apps/src/implementation/ui-client.d.ts +2 -2
  134. package/types/apps/src/implementation/ui-document.d.ts +5 -0
  135. package/types/apps/src/implementation/ui-errors.d.ts +1 -1
  136. package/types/apps/src/implementation/ui-serving.d.ts +11 -5
  137. package/types/apps/src/implementation/ui-watch.d.ts +1 -1
  138. package/types/apps/src/implementation/upstream-error.d.ts +7 -0
  139. package/types/apps/src/implementation/webhooks.d.ts +1 -1
  140. package/types/apps/src/implementation/workflow-context.d.ts +1 -1
  141. package/types/apps/src/implementation/workflows.d.ts +1 -1
  142. package/types/apps/src/index.d.ts +32 -13
  143. package/types/apps/src/mcp-stdio.d.ts +2 -5
  144. package/types/apps/src/mcp.d.ts +25 -5
  145. package/types/apps/src/openapi.d.ts +6 -6
  146. package/types/apps/src/react.d.ts +1 -1
  147. package/types/apps/src/skills.d.ts +10 -8
  148. package/types/telemetry/src/app-records.d.ts +42 -0
  149. package/types/telemetry/src/browser-operations.d.ts +7 -4
  150. package/types/telemetry/src/browser.d.ts +8 -3
  151. package/types/telemetry/src/config.d.ts +2 -2
  152. package/types/telemetry/src/index.d.ts +1 -0
  153. package/types/telemetry/src/layer.d.ts +2 -2
  154. package/types/telemetry/src/ownership.d.ts +56 -0
  155. package/types/telemetry/src/recorded-failure.d.ts +29 -0
  156. package/types/telemetry/src/relay.d.ts +2 -2
  157. package/types/telemetry/src/transport.d.ts +8 -1
  158. package/types/utils/src/api-error.d.ts +55 -0
  159. package/types/utils/src/connection-failure.d.ts +33 -0
  160. package/types/utils/src/recorded-message.d.ts +18 -0
  161. package/types/utils/src/user-facing-error.d.ts +83 -0
  162. package/js/chunk-3XKZDQLM.js +0 -93
  163. package/js/chunk-4M277YTM.js +0 -136
  164. package/js/chunk-67EVWIGJ.js +0 -224
  165. package/js/chunk-C3VAOK5B.js +0 -215
  166. package/js/chunk-DQAZTA4I.js +0 -2375
  167. package/js/chunk-G7T27IWB.js +0 -63
  168. package/js/chunk-LUVSFETN.js +0 -1347
  169. package/js/chunk-N7YDVXYJ.js +0 -186
  170. package/js/chunk-PJJ24GU7.js +0 -877
  171. package/js/chunk-PZB6T6KU.js +0 -19
  172. package/js/chunk-SB3V4YVR.js +0 -18
  173. package/js/chunk-TDNYXSIX.js +0 -29
  174. package/js/chunk-W4DMKWAB.js +0 -35
  175. package/js/chunk-YEPYT6SD.js +0 -85
  176. package/js/chunk-ZQINWV4W.js +0 -630
  177. package/types/app-data/src/implementation/cursor.d.ts +0 -10
  178. package/types/app-data/src/implementation/index-key.d.ts +0 -7
  179. package/types/app-data/src/implementation/promise.d.ts +0 -68
  180. package/types/app-data/src/implementation/range.d.ts +0 -8
  181. package/types/app-data/src/implementation/schema.d.ts +0 -18
  182. package/types/app-data/src/implementation/sqlite.d.ts +0 -11
  183. package/types/app-data/src/index.d.ts +0 -4
  184. package/types/apps/src/contracts/dynamic-tools.d.ts +0 -13
  185. package/types/apps/src/contracts/storage.d.ts +0 -68
  186. package/types/apps/src/implementation/account-operations.d.ts +0 -151
  187. package/types/apps/src/implementation/dynamic-tools.d.ts +0 -8
  188. package/types/apps/src/implementation/storage.d.ts +0 -15
@@ -0,0 +1,1885 @@
1
+ import {
2
+ makeCache
3
+ } from "./chunk-AQU56EPI.js";
4
+ import {
5
+ accountSecrets,
6
+ boundFailureMessage,
7
+ describeFailure,
8
+ failureDetail,
9
+ leavingProviderError,
10
+ parseMcpError,
11
+ parseSkillLoadFailed,
12
+ readCatalog,
13
+ routerSkills
14
+ } from "./chunk-QEBRH5AP.js";
15
+ import {
16
+ appInvocationFetch
17
+ } from "./chunk-7UUHJR2Q.js";
18
+ import {
19
+ folderSkillsEffect
20
+ } from "./chunk-XBG7HHXC.js";
21
+ import {
22
+ ResponseStatusError,
23
+ declaredEvents,
24
+ isApp,
25
+ makeEmitter,
26
+ toEffectApp
27
+ } from "./chunk-PXXZ6ABC.js";
28
+ import {
29
+ declaredOperations,
30
+ locate,
31
+ nativeOperation
32
+ } from "./chunk-47F7VXST.js";
33
+ import {
34
+ accountProviderError,
35
+ appCode,
36
+ fromPromise,
37
+ httpProviderError,
38
+ method,
39
+ parseProviderError,
40
+ toPromise
41
+ } from "./chunk-LTDHQJ2Z.js";
42
+ import {
43
+ AccountCheckResult,
44
+ DeclaredProvider,
45
+ DeclaredRequirements,
46
+ ElicitationFailed,
47
+ ElicitationResponse,
48
+ FormElicitation,
49
+ HostAccountsInvalid,
50
+ HostDeclarationInvalid,
51
+ HostError,
52
+ HostEvaluationFailed,
53
+ HostInputInvalid,
54
+ HostKindMismatch,
55
+ HostOperationFailed,
56
+ HostOperationNotFound,
57
+ HostOutputInvalid,
58
+ HostRequest,
59
+ HostRequestInvalid,
60
+ HostToolApprovalRequired,
61
+ HostToolBlocked,
62
+ HostToolNotFound,
63
+ HostToolPolicyFailed,
64
+ HostedRouter,
65
+ HostedTool,
66
+ HostedToolSummary,
67
+ HostedWebhook,
68
+ HostedWorkflow,
69
+ InvocationDeadline,
70
+ InvocationTimingSink,
71
+ ManualWebhookSetup,
72
+ ManyAccounts,
73
+ NonRetryableError,
74
+ OpenapiResponseError,
75
+ ResolvedAccounts,
76
+ ToolResultObservation,
77
+ TrustedToolApproval,
78
+ WebhookResponseData,
79
+ WorkflowDuration,
80
+ WorkflowFailure,
81
+ WorkflowName,
82
+ WorkflowReplay,
83
+ WorkflowStepOptions,
84
+ WorkflowValue,
85
+ approvalElicitation,
86
+ defaultWebhookTransportLimits,
87
+ maxInputProblems,
88
+ migrationsDirectory,
89
+ reservedTablePrefix,
90
+ workflowDurationMillis
91
+ } from "./chunk-TLWLJ7PD.js";
92
+ import {
93
+ CacheError
94
+ } from "./chunk-MWKHKOTL.js";
95
+ import {
96
+ AppSkills,
97
+ SkillFile
98
+ } from "./chunk-H72MEDMN.js";
99
+ import {
100
+ allowedValues,
101
+ decoderOf,
102
+ echoableKey,
103
+ importedJsonSchema,
104
+ importedSchemaKeys,
105
+ jsonSchemaDecoder,
106
+ jsonSchemaDocument,
107
+ maxAlternativeKeys,
108
+ missingKey,
109
+ missingKeyText,
110
+ objectShape,
111
+ unionShape
112
+ } from "./chunk-KGCTYL2S.js";
113
+ import {
114
+ captureTelemetry,
115
+ makeOwnershipAccounting,
116
+ measuredSpan,
117
+ owned
118
+ } from "./chunk-JM7LOD2W.js";
119
+ import {
120
+ JsonObject,
121
+ JsonValue
122
+ } from "./chunk-H2CJWXA3.js";
123
+ import {
124
+ Base64_exports,
125
+ Cause_exports,
126
+ Clock_exports,
127
+ Effect_exports,
128
+ Match_exports,
129
+ Option_exports,
130
+ Redacted_exports,
131
+ SchemaAST_exports,
132
+ SchemaIssue_exports,
133
+ Schema_exports,
134
+ Stream_exports
135
+ } from "./chunk-IFJU5SYQ.js";
136
+
137
+ // src/implementation/invocation-timing.ts
138
+ var elicitationWaitSpan = "app.elicitation.wait";
139
+ var workflowControlSpan = "app.workflow.control";
140
+ var timedInvocation = (operation) => (effect) => Effect_exports.gen(function* () {
141
+ const report = yield* InvocationTimingSink;
142
+ return yield* effect.pipe(
143
+ measuredSpan(`app.${operation}`, {}, (start) => {
144
+ const accounting = makeOwnershipAccounting(start, "executor");
145
+ return {
146
+ around: accounting.observe,
147
+ end: (end, span) => {
148
+ const spent = accounting.read(end);
149
+ report({
150
+ elapsedMs: Number(end - start) / 1e6,
151
+ upstreamMs: spent.upstream,
152
+ elicitationMs: spent.person,
153
+ authoredMs: spent.app
154
+ });
155
+ span.attribute("executor.upstream.wait_ms", spent.upstream);
156
+ span.attribute("executor.elicitation.wait_ms", spent.person);
157
+ span.attribute("executor.authored_ms", spent.app);
158
+ span.attribute("executor.overhead_ms", spent.executor);
159
+ }
160
+ };
161
+ })
162
+ );
163
+ });
164
+
165
+ // src/implementation/elicitation.ts
166
+ var prepareElicitation = (input) => Effect_exports.gen(function* () {
167
+ const request = yield* Schema_exports.decodeUnknownEffect(FormElicitation)(input, {
168
+ onExcessProperty: "error"
169
+ }).pipe(Effect_exports.mapError(() => new ElicitationFailed({ reason: "invalid-request" })));
170
+ const content = yield* jsonSchemaDecoder(request.requestedSchema).pipe(
171
+ Effect_exports.mapError(() => new ElicitationFailed({ reason: "invalid-request" }))
172
+ );
173
+ const respond = (input2) => Effect_exports.gen(function* () {
174
+ const response = yield* Schema_exports.decodeUnknownEffect(ElicitationResponse)(input2).pipe(
175
+ Effect_exports.catchTag(
176
+ "SchemaError",
177
+ () => Effect_exports.fail(new ElicitationFailed({ reason: "invalid-response" }))
178
+ )
179
+ );
180
+ if (response.action === "accept") {
181
+ const fields = response.content === void 0 ? {} : response.content;
182
+ yield* Schema_exports.decodeUnknownEffect(content)(fields).pipe(
183
+ Effect_exports.mapError(() => new ElicitationFailed({ reason: "invalid-response" }))
184
+ );
185
+ return { ...response, content: fields };
186
+ }
187
+ return response;
188
+ });
189
+ return { request, respond };
190
+ });
191
+ var makeElicit = (handler, signal, telemetry) => toPromise(
192
+ (input) => Effect_exports.gen(function* () {
193
+ if (handler === void 0) return yield* new ElicitationFailed({ reason: "unavailable" });
194
+ const form = yield* prepareElicitation(input);
195
+ return yield* handler(form.request, signal).pipe(
196
+ owned("person", elicitationWaitSpan),
197
+ Effect_exports.flatMap(form.respond)
198
+ );
199
+ }),
200
+ signal,
201
+ telemetry
202
+ );
203
+
204
+ // src/contracts/approval.ts
205
+ var ApprovalDecision = Schema_exports.Literals(["approved", "denied", "user-approval"]);
206
+
207
+ // src/implementation/workflow-context.ts
208
+ var workflowSafe = (work, secrets) => work.pipe(
209
+ Effect_exports.catchCause((cause) => {
210
+ if (Cause_exports.hasInterrupts(cause)) return Effect_exports.interrupt;
211
+ const error = Cause_exports.squash(cause);
212
+ if (Schema_exports.is(WorkflowFailure)(error)) return Effect_exports.fail(error);
213
+ const { errorName, message } = failureDetail(error, secrets);
214
+ return Effect_exports.fail(
215
+ new WorkflowFailure({
216
+ reason: "execution",
217
+ retryable: !(error instanceof NonRetryableError),
218
+ ...errorName === void 0 ? {} : { errorName },
219
+ ...message === void 0 ? {} : { message }
220
+ })
221
+ );
222
+ })
223
+ );
224
+ var inStep = (step) => (failure) => failure.step === void 0 ? new WorkflowFailure({
225
+ reason: failure.reason,
226
+ retryable: failure.retryable,
227
+ step: step.slice(0, 200),
228
+ ...failure.errorName === void 0 ? {} : { errorName: failure.errorName },
229
+ ...failure.message.length === 0 ? {} : { message: failure.message }
230
+ }) : failure;
231
+ var makeWorkflowContext = (execution, definition, fresh, signal) => Effect_exports.gen(function* () {
232
+ const services = yield* Effect_exports.context();
233
+ const counts = /* @__PURE__ */ new Map();
234
+ const identify = (kind, name) => Effect_exports.gen(function* () {
235
+ yield* Schema_exports.decodeUnknownEffect(WorkflowName)(name).pipe(
236
+ Effect_exports.mapError(() => new WorkflowFailure({ reason: "input", retryable: false }))
237
+ );
238
+ const key = JSON.stringify([kind, name]);
239
+ const count = (counts.get(key) ?? 0) + 1;
240
+ counts.set(key, count);
241
+ const digest = yield* Effect_exports.tryPromise({
242
+ try: () => crypto.subtle.digest(
243
+ "SHA-256",
244
+ new TextEncoder().encode(JSON.stringify([execution.runId, kind, name, count]))
245
+ ),
246
+ catch: () => new WorkflowFailure({ reason: "execution", retryable: false })
247
+ });
248
+ return Array.from(
249
+ new Uint8Array(digest),
250
+ (byte) => byte.toString(16).padStart(2, "0")
251
+ ).join("");
252
+ });
253
+ const attempt = (options, work) => {
254
+ const timeout = workflowDurationMillis(options.timeout ?? "10 minutes");
255
+ if (timeout === void 0)
256
+ return Effect_exports.fail(new WorkflowFailure({ reason: "input", retryable: false }));
257
+ return work.pipe(
258
+ Effect_exports.timeout(timeout),
259
+ Effect_exports.catchTag(
260
+ "TimeoutError",
261
+ () => (
262
+ // Both the capability deadline and the native engine deadline describe
263
+ // the same cancellation, regardless of which timer fires first.
264
+ Effect_exports.fail(new WorkflowFailure({ reason: "engine", retryable: true }))
265
+ )
266
+ )
267
+ );
268
+ };
269
+ const runStep = (name, options, callback) => Effect_exports.gen(function* () {
270
+ const stepId = yield* identify("do", name);
271
+ const parsed = yield* Schema_exports.decodeUnknownEffect(WorkflowStepOptions)(options).pipe(
272
+ Effect_exports.mapError(() => new WorkflowFailure({ reason: "input", retryable: false }))
273
+ );
274
+ return yield* execution.driver.do(
275
+ `do:${name.slice(0, 100)}:${stepId}`,
276
+ parsed,
277
+ () => attempt(
278
+ parsed,
279
+ Effect_exports.scoped(
280
+ Effect_exports.gen(function* () {
281
+ const controller = yield* Effect_exports.acquireRelease(
282
+ Effect_exports.sync(() => new AbortController()),
283
+ (controller2) => Effect_exports.sync(() => controller2.abort())
284
+ );
285
+ const step2 = yield* fresh(stepId, AbortSignal.any([signal, controller.signal]));
286
+ const result = yield* workflowSafe(
287
+ fromPromise(callback, "step")(step2.context),
288
+ step2.secrets
289
+ );
290
+ return yield* Schema_exports.decodeUnknownEffect(WorkflowValue)(result).pipe(
291
+ Effect_exports.mapError(
292
+ () => new WorkflowFailure({
293
+ reason: "output",
294
+ retryable: false,
295
+ message: "The step returned a value that is not JSON, such as undefined, or is larger than 1 MiB. Return null for no result."
296
+ })
297
+ )
298
+ );
299
+ })
300
+ ).pipe(Effect_exports.provideContext(services))
301
+ )
302
+ ).pipe(Effect_exports.mapError(inStep(name)));
303
+ });
304
+ const operationStep = (kind, name, operation, input, options) => Effect_exports.gen(function* () {
305
+ const target = nativeOperation(operation);
306
+ const root = definition.tools?.kind === "router" ? definition.tools : void 0;
307
+ const match = declaredOperations(root).find(
308
+ (entry) => entry.operation === target && entry.operation.kind === kind
309
+ );
310
+ if (target === void 0 || match === void 0)
311
+ return yield* new WorkflowFailure({ reason: "operation", retryable: false });
312
+ const args = yield* Schema_exports.decodeUnknownEffect(JsonValue)(input).pipe(
313
+ Effect_exports.mapError(() => new WorkflowFailure({ reason: "input", retryable: false }))
314
+ );
315
+ const parsed = yield* Schema_exports.decodeUnknownEffect(WorkflowStepOptions)(options).pipe(
316
+ Effect_exports.mapError(() => new WorkflowFailure({ reason: "input", retryable: false }))
317
+ );
318
+ const stepId = yield* identify(kind, name);
319
+ const timeout = workflowDurationMillis(parsed.timeout ?? "10 minutes");
320
+ if (timeout === void 0)
321
+ return yield* new WorkflowFailure({ reason: "input", retryable: false });
322
+ return yield* execution.driver.do(
323
+ `${kind}:${name.slice(0, 100)}:${stepId}`,
324
+ parsed,
325
+ () => attempt(
326
+ parsed,
327
+ execution.invoke({ kind, name: match.name, input: args, stepId, timeout }).pipe(Effect_exports.provideContext(services))
328
+ )
329
+ ).pipe(Effect_exports.mapError(inStep(name)));
330
+ });
331
+ const invoke = (effect) => toPromise(() => effect.pipe(Effect_exports.provideContext(services)), signal)();
332
+ const step = {
333
+ do: (name, options, run) => {
334
+ const callback = typeof options === "function" ? options : run;
335
+ if (callback === void 0)
336
+ return Promise.reject(new WorkflowFailure({ reason: "input", retryable: false }));
337
+ return invoke(runStep(name, typeof options === "function" ? {} : options, callback));
338
+ },
339
+ runQuery: (name, operation, input, options = {}) => invoke(operationStep("query", name, operation, input, options)),
340
+ runMutation: (name, operation, input, options = {}) => invoke(operationStep("mutation", name, operation, input, options)),
341
+ sleep: (name, duration) => invoke(
342
+ Schema_exports.decodeUnknownEffect(WorkflowDuration)(duration).pipe(
343
+ Effect_exports.mapError(() => new WorkflowFailure({ reason: "input", retryable: false })),
344
+ Effect_exports.flatMap(
345
+ (parsed) => identify("sleep", name).pipe(
346
+ Effect_exports.flatMap(
347
+ (id) => execution.driver.sleep(`sleep:${name.slice(0, 100)}:${id}`, parsed)
348
+ )
349
+ )
350
+ )
351
+ )
352
+ ),
353
+ sleepUntil: (name, timestamp) => invoke(
354
+ identify("until", name).pipe(
355
+ Effect_exports.flatMap(
356
+ (id) => execution.driver.sleepUntil(
357
+ `until:${name.slice(0, 100)}:${id}`,
358
+ timestamp instanceof Date ? timestamp.getTime() : timestamp
359
+ )
360
+ )
361
+ )
362
+ )
363
+ };
364
+ return { runId: execution.runId, step };
365
+ });
366
+
367
+ // src/implementation/input-problems.ts
368
+ var nativeObjectShape = (ast, limit) => objectShape(
369
+ ast.propertySignatures.flatMap(
370
+ ({ name, type }) => typeof name === "string" ? [{ name, optional: SchemaAST_exports.isOptional(SchemaAST_exports.toEncoded(type)) }] : []
371
+ ),
372
+ ast.indexSignatures.length > 0,
373
+ limit
374
+ );
375
+ var unionMembers = (ast) => SchemaAST_exports.isUnion(ast) ? ast.types.flatMap(unionMembers) : SchemaAST_exports.isUndefined(ast) || SchemaAST_exports.isVoid(ast) ? [] : [ast];
376
+ var fixedValues = (ast) => {
377
+ if (SchemaAST_exports.isLiteral(ast)) return [ast.literal];
378
+ if (SchemaAST_exports.isEnum(ast)) return ast.enums.map(([, value]) => value);
379
+ if (!SchemaAST_exports.isUnion(ast)) return void 0;
380
+ const members = unionMembers(ast).map(fixedValues);
381
+ return members.length > 0 && members.every((values) => values !== void 0) ? members.flat() : void 0;
382
+ };
383
+ var describeMember = (ast) => Match_exports.value(ast).pipe(
384
+ Match_exports.when(
385
+ SchemaAST_exports.isObjects,
386
+ (objects) => objects.propertySignatures.length > 0 ? nativeObjectShape(objects, maxAlternativeKeys) : "object"
387
+ ),
388
+ Match_exports.when(SchemaAST_exports.isArrays, () => "array"),
389
+ Match_exports.when(SchemaAST_exports.isTemplateLiteral, () => "a string matching a template"),
390
+ Match_exports.when(SchemaAST_exports.isString, () => "string"),
391
+ Match_exports.when(SchemaAST_exports.isNumber, () => "number"),
392
+ Match_exports.when(SchemaAST_exports.isBoolean, () => "boolean"),
393
+ Match_exports.when(SchemaAST_exports.isNull, () => "null"),
394
+ Match_exports.orElse(() => "a value with other constraints")
395
+ );
396
+ var memberSelector = (members) => {
397
+ const [first] = members;
398
+ if (members.length < 2 || first === void 0 || !SchemaAST_exports.isObjects(first)) return void 0;
399
+ return first.propertySignatures.map(({ name }) => name).find(
400
+ (name) => typeof name === "string" && members.every(
401
+ (member) => SchemaAST_exports.isObjects(member) && member.propertySignatures.some(
402
+ (property) => property.name === name && fixedValues(SchemaAST_exports.toEncoded(property.type)) !== void 0
403
+ )
404
+ )
405
+ );
406
+ };
407
+ var unionExpectation = (ast) => {
408
+ const members = unionMembers(ast);
409
+ const fixed = members.map(fixedValues);
410
+ const values = fixed.flatMap((memberValues) => memberValues === void 0 ? [] : memberValues);
411
+ const others = members.filter((_, index) => fixed[index] === void 0);
412
+ if (others.length === 0) return allowedValues(values);
413
+ return unionShape(
414
+ [
415
+ ...values.length === 0 ? [] : [allowedValues(values)],
416
+ ...new Set(others.map(describeMember))
417
+ ],
418
+ memberSelector(members)
419
+ );
420
+ };
421
+ var expectedUnion = (ast) => `Expected ${unionExpectation(ast)}`;
422
+ var expectedValue = (ast) => {
423
+ const encoded = SchemaAST_exports.toEncoded(ast);
424
+ const values = fixedValues(encoded);
425
+ if (values !== void 0) return allowedValues(values);
426
+ const members = unionMembers(encoded);
427
+ const [only] = members;
428
+ if (only === void 0) return void 0;
429
+ if (members.length > 1 && SchemaAST_exports.isUnion(encoded)) return unionExpectation(encoded);
430
+ if (SchemaAST_exports.isObjects(only) && only.propertySignatures.length > 0)
431
+ return nativeObjectShape(only);
432
+ const described = describeMember(only);
433
+ return described === "a value with other constraints" ? void 0 : described;
434
+ };
435
+ var leafHook = (issue) => SchemaIssue_exports.hasInput(issue) ? "Invalid value" : Match_exports.value(issue).pipe(
436
+ Match_exports.tag("InvalidType", ({ ast }) => {
437
+ const values = fixedValues(ast);
438
+ return values !== void 0 ? `Expected ${allowedValues(values)}` : SchemaAST_exports.isObjects(ast) && ast.propertySignatures.length > 0 ? `Expected ${nativeObjectShape(ast)}` : SchemaIssue_exports.defaultLeafHook(issue);
439
+ }),
440
+ Match_exports.orElse(SchemaIssue_exports.defaultLeafHook)
441
+ );
442
+ var checkHook = (issue) => SchemaIssue_exports.hasInput(issue) || SchemaIssue_exports.hasInput(issue.issue) ? SchemaIssue_exports.defaultCheckHook(issue) ?? "Invalid value" : SchemaIssue_exports.defaultCheckHook(issue);
443
+ var format = SchemaIssue_exports.makeFormatterStandardSchemaV1({ leafHook, checkHook });
444
+ var declaredKey = (parent, key) => parent !== void 0 && SchemaAST_exports.isObjects(parent) ? parent.propertySignatures.find(({ name }) => name === key)?.type : void 0;
445
+ var nativeKeys = (parent) => (key) => parent.indexSignatures.length > 0 || parent.propertySignatures.some(({ name }) => name === key);
446
+ var located = (issue, path, parent) => Match_exports.value(issue).pipe(
447
+ Match_exports.tag("Pointer", (pointer) => {
448
+ const declared = pointer.issue._tag === "MissingKey" && pointer.path.length === 1 ? declaredKey(parent, pointer.path[0]) : void 0;
449
+ return declared === void 0 || parent === void 0 || !SchemaAST_exports.isObjects(parent) ? located(pointer.issue, [...path, ...pointer.path]) : [
450
+ {
451
+ path: [...path, ...pointer.path],
452
+ message: missingKey(expectedValue(declared)),
453
+ accepts: nativeKeys(parent)
454
+ }
455
+ ];
456
+ }),
457
+ Match_exports.tag(
458
+ "Composite",
459
+ ({ ast, issues }) => issues.flatMap((issue2) => located(issue2, path, ast))
460
+ ),
461
+ Match_exports.tag("Encoding", (encoding) => located(encoding.issue, path)),
462
+ Match_exports.tag(
463
+ "AnyOf",
464
+ ({ ast, issues }) => issues.length === 0 ? [{ path, message: expectedUnion(ast) }] : issues.flatMap((issue2) => located(issue2, path))
465
+ ),
466
+ Match_exports.orElse((issue2) => {
467
+ const accepts = issue2._tag === "Filter" ? importedSchemaKeys(issue2.filter) : void 0;
468
+ return format(issue2).issues.map((problem) => ({
469
+ path: [
470
+ ...path,
471
+ ...(problem.path ?? []).map((key) => typeof key === "object" ? key.key : key)
472
+ ],
473
+ message: problem.message,
474
+ ...accepts === void 0 ? {} : { accepts }
475
+ }));
476
+ })
477
+ );
478
+ var segment = (key) => typeof key === "number" ? `[${key}]` : typeof key === "string" && echoableKey(key) ? `.${key}` : "[key]";
479
+ var rendered = (path) => `input${path.map(segment).join("")}`;
480
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
481
+ var valueAt = (input, path) => path.reduce(
482
+ (value, key) => Array.isArray(value) && typeof key === "number" ? value[key] : isRecord(value) && typeof key === "string" && Object.hasOwn(value, key) ? value[key] : void 0,
483
+ input
484
+ );
485
+ var spelling = (key) => key.toLowerCase().replace(/[-_]/g, "");
486
+ var suppliedElsewhere = (input, path, accepts) => {
487
+ const key = path.at(-1);
488
+ if (typeof key !== "string" || !echoableKey(key)) return void 0;
489
+ const at = path.slice(0, -1);
490
+ const holder = valueAt(input, at);
491
+ if (!isRecord(holder)) return void 0;
492
+ const candidates = Object.keys(holder).filter((name) => echoableKey(name) && !accepts(name));
493
+ const respelled = candidates.find((name) => name !== key && spelling(name) === spelling(key));
494
+ const deeper = candidates.find((name) => {
495
+ const child = holder[name];
496
+ return isRecord(child) && Object.hasOwn(child, key);
497
+ });
498
+ const found = respelled !== void 0 ? [...at, respelled] : deeper !== void 0 ? [...at, deeper, key] : void 0;
499
+ return found === void 0 ? void 0 : `The input has ${String(found.at(-1))} at ${rendered(found)}; did you mean ${rendered(path)}?`;
500
+ };
501
+ var inputInvalid = (error, input) => {
502
+ if (!Schema_exports.isSchemaError(error)) return new HostInputInvalid();
503
+ const problems = located(error.issue, []).slice(0, maxInputProblems).map(({ path, message, accepts }) => {
504
+ const elsewhere = accepts !== void 0 && message.startsWith(missingKeyText) ? suppliedElsewhere(input, path, accepts) : void 0;
505
+ return `${rendered(path)}: ${message}${elsewhere === void 0 ? "" : `. ${elsewhere}`}`.slice(
506
+ 0,
507
+ 512
508
+ );
509
+ });
510
+ return new HostInputInvalid({ problems });
511
+ };
512
+
513
+ // src/implementation/webhooks.ts
514
+ var safe = (work, error) => Effect_exports.suspend(work).pipe(
515
+ Effect_exports.catchCause(
516
+ (cause) => Cause_exports.hasInterrupts(cause) ? Effect_exports.interrupt : Effect_exports.fail(error)
517
+ )
518
+ );
519
+ var dispatchWebhook = (definition, command, context, accounts) => Effect_exports.gen(function* () {
520
+ const hooks = definition.webhooks ?? {};
521
+ if (command.operation === "webhooks") {
522
+ return yield* Effect_exports.forEach(
523
+ Object.entries(hooks),
524
+ ([name, hook2]) => safe(
525
+ () => Effect_exports.gen(function* () {
526
+ if (!Object.hasOwn(accounts, hook2.account))
527
+ return yield* new HostDeclarationInvalid();
528
+ const describe = (schema) => {
529
+ const imported = importedJsonSchema(schema);
530
+ if (imported !== void 0) return Schema_exports.decodeUnknownEffect(JsonObject)(imported);
531
+ const document = Schema_exports.toJsonSchemaDocument(schema);
532
+ return Schema_exports.decodeUnknownEffect(JsonObject)({
533
+ ...document.schema,
534
+ $defs: document.definitions
535
+ });
536
+ };
537
+ const configSchema = yield* describe(hook2.config);
538
+ if (hook2.setup === void 0 ? hook2.register === void 0 || hook2.unregister === void 0 : hook2.register !== void 0 || hook2.unregister !== void 0)
539
+ return yield* new HostDeclarationInvalid();
540
+ const setup = hook2.setup === void 0 ? void 0 : {
541
+ ...yield* Schema_exports.decodeUnknownEffect(ManualWebhookSetup)(hook2.setup),
542
+ stateSchema: yield* describe(hook2.state)
543
+ };
544
+ return yield* Schema_exports.decodeUnknownEffect(HostedWebhook)({
545
+ name,
546
+ account: hook2.account,
547
+ configSchema,
548
+ ...setup === void 0 ? {} : { setup }
549
+ });
550
+ }),
551
+ new HostDeclarationInvalid()
552
+ )
553
+ );
554
+ }
555
+ const hook = Object.hasOwn(hooks, command.name) ? hooks[command.name] : void 0;
556
+ if (hook === void 0) return yield* new HostOperationNotFound();
557
+ const selected = accounts[hook.account];
558
+ const source = Array.isArray(selected) ? selected.find((account2) => account2.id === command.sourceAccount) : selected;
559
+ if (source === void 0 || source.id !== command.sourceAccount)
560
+ return yield* new HostInputInvalid();
561
+ const bound = context.accounts[hook.account];
562
+ const account = Array.isArray(bound) ? bound.find(
563
+ (value) => typeof value === "object" && value !== null && "id" in value && value.id === source.id
564
+ ) : bound;
565
+ const config = yield* safe(
566
+ () => Schema_exports.decodeUnknownEffect(hook.config)(command.config),
567
+ new HostInputInvalid()
568
+ );
569
+ if (command.operation === "webhook-validate")
570
+ return yield* safe(
571
+ () => Schema_exports.decodeUnknownEffect(JsonValue)(config),
572
+ new HostInputInvalid()
573
+ );
574
+ const input = {
575
+ config,
576
+ subscriptionId: command.subscriptionId,
577
+ account,
578
+ callbackUrl: command.callbackUrl,
579
+ secret: command.secret
580
+ };
581
+ const invoke = (callback, value) => safe(() => callback(context, value), new HostOperationFailed());
582
+ if (command.operation === "webhook-complete") {
583
+ if (hook.setup === void 0) return yield* new HostInputInvalid();
584
+ return yield* safe(
585
+ () => Schema_exports.decodeUnknownEffect(hook.state)(command.state).pipe(
586
+ Effect_exports.flatMap(Schema_exports.decodeUnknownEffect(JsonValue))
587
+ ),
588
+ new HostInputInvalid()
589
+ );
590
+ }
591
+ if (command.operation === "webhook-register") {
592
+ if (hook.register === void 0 || hook.setup !== void 0)
593
+ return yield* new HostOperationFailed();
594
+ const state2 = yield* invoke(hook.register, input);
595
+ return yield* safe(
596
+ () => Schema_exports.decodeUnknownEffect(hook.state)(state2).pipe(
597
+ Effect_exports.flatMap(Schema_exports.decodeUnknownEffect(JsonValue))
598
+ ),
599
+ new HostOutputInvalid()
600
+ );
601
+ }
602
+ const state = command.state === null ? null : yield* safe(
603
+ () => Schema_exports.decodeUnknownEffect(hook.state)(command.state),
604
+ new HostInputInvalid()
605
+ );
606
+ if (command.operation === "webhook-unregister") {
607
+ if (hook.unregister === void 0 || hook.setup !== void 0)
608
+ return yield* new HostOperationFailed();
609
+ yield* invoke(hook.unregister, { ...input, state });
610
+ return null;
611
+ }
612
+ const body = yield* Effect_exports.fromResult(Base64_exports.decode(command.request.body)).pipe(
613
+ Effect_exports.mapError(() => new HostInputInvalid())
614
+ );
615
+ if (body.byteLength > defaultWebhookTransportLimits.maxBodyBytes)
616
+ return yield* new HostInputInvalid();
617
+ const request = yield* safe(
618
+ () => Effect_exports.sync(
619
+ () => new Request(command.request.url, {
620
+ method: command.request.method,
621
+ headers: command.request.headers,
622
+ ...context.signal === void 0 ? {} : { signal: context.signal },
623
+ ...command.request.method === "GET" || command.request.method === "HEAD" ? {} : { body: Uint8Array.from(body) }
624
+ })
625
+ ),
626
+ new HostInputInvalid()
627
+ );
628
+ const response = yield* invoke(hook.handle, { ...input, state, request });
629
+ if (!(response instanceof Response)) return yield* new HostOutputInvalid();
630
+ const chunks = [];
631
+ let size = 0;
632
+ const stream = response.body;
633
+ if (stream !== null)
634
+ yield* Stream_exports.fromReadableStream({
635
+ evaluate: () => stream,
636
+ onError: () => new HostOutputInvalid()
637
+ }).pipe(
638
+ Stream_exports.runForEach(
639
+ (chunk) => Effect_exports.gen(function* () {
640
+ size += chunk.byteLength;
641
+ if (size > defaultWebhookTransportLimits.maxBodyBytes)
642
+ return yield* new HostOutputInvalid();
643
+ chunks.push(chunk);
644
+ })
645
+ ),
646
+ appCode("webhook")
647
+ );
648
+ const bytes = new Uint8Array(size);
649
+ let offset = 0;
650
+ for (const chunk of chunks) {
651
+ bytes.set(chunk, offset);
652
+ offset += chunk.byteLength;
653
+ }
654
+ const headers = {};
655
+ response.headers.forEach((value, name) => {
656
+ headers[name] = value;
657
+ });
658
+ return yield* safe(
659
+ () => Schema_exports.decodeUnknownEffect(WebhookResponseData)({
660
+ status: response.status,
661
+ headers,
662
+ body: Base64_exports.encode(new Uint8Array(bytes))
663
+ }),
664
+ new HostOutputInvalid()
665
+ );
666
+ });
667
+
668
+ // src/implementation/sql.ts
669
+ var receipts = `${reservedTablePrefix}step_receipts`;
670
+ var stepEvents = `${reservedTablePrefix}step_events`;
671
+ var migrationsTable = `${reservedTablePrefix}migrations`;
672
+ var legacyRows = `${reservedTablePrefix}legacy_rows`;
673
+ var materialize = (cursor) => {
674
+ const rows = cursor.toArray();
675
+ return {
676
+ columnNames: cursor.columnNames,
677
+ rowsRead: cursor.rowsRead,
678
+ rowsWritten: cursor.rowsWritten,
679
+ toArray: () => [...rows],
680
+ one: () => {
681
+ if (rows.length !== 1)
682
+ throw new Error(`Expected exactly one row, but the statement returned ${rows.length}.`);
683
+ return rows[0];
684
+ },
685
+ [Symbol.iterator]: () => rows[Symbol.iterator]()
686
+ };
687
+ };
688
+ var isThenable = (value) => (typeof value === "object" || typeof value === "function") && value !== null && "then" in value && typeof value.then === "function";
689
+ var missingDatabase = () => {
690
+ throw new Error(
691
+ `This app has no database. Add its first migration, such as ${migrationsDirectory}/0001_create_notes.sql with a CREATE TABLE statement, and deploy again.`
692
+ );
693
+ };
694
+ var noDatabase = { exec: missingDatabase, transaction: missingDatabase };
695
+ var settings = [
696
+ "foreign_keys",
697
+ "defer_foreign_keys",
698
+ "ignore_check_constraints",
699
+ "legacy_alter_table",
700
+ "recursive_triggers",
701
+ "reverse_unordered_selects"
702
+ ];
703
+ var readSettings = (storage) => new Map(
704
+ settings.map((name) => [name, Number(storage.sql.exec(`PRAGMA ${name}`).toArray()[0]?.[name])])
705
+ );
706
+ var changedSetting = (storage, baseline) => {
707
+ const current = readSettings(storage);
708
+ return settings.find((name) => current.get(name) !== baseline.get(name));
709
+ };
710
+ var restoreSettings = (storage, baseline) => {
711
+ const current = readSettings(storage);
712
+ for (const [name, value] of baseline)
713
+ if (current.get(name) !== value) storage.sql.exec(`PRAGMA ${name} = ${value}`);
714
+ storage.sql.exec("PRAGMA case_sensitive_like = OFF");
715
+ };
716
+ var ReadRolledBack = class extends Error {
717
+ };
718
+ var authorSql = (storage, options) => {
719
+ let closed = false;
720
+ const live = () => {
721
+ if (closed || options.signal.aborted)
722
+ throw new Error("This call has ended, so its ctx.sql no longer runs statements.");
723
+ };
724
+ let open = false;
725
+ let transactions = 0;
726
+ const baseline = readSettings(storage);
727
+ const checkSettings = () => {
728
+ const changed = changedSetting(storage, baseline);
729
+ if (changed !== void 0)
730
+ throw refuse(
731
+ new Error(
732
+ `SQLite connection settings belong to Executor, so app code cannot change PRAGMA ${changed}; the statement was rolled back. Migrations may change settings while they run.`
733
+ )
734
+ );
735
+ };
736
+ const changes = () => Number(storage.sql.exec("SELECT total_changes() AS n").toArray()[0]?.n);
737
+ let violation;
738
+ const refuse = (error) => {
739
+ if (open) violation ??= error;
740
+ return error;
741
+ };
742
+ const run = (query, bindings, mode) => {
743
+ try {
744
+ return runStatement(query, bindings, mode);
745
+ } finally {
746
+ restoreSettings(storage, baseline);
747
+ }
748
+ };
749
+ const runStatement = (query, bindings, mode) => {
750
+ live();
751
+ if (mode === "write") {
752
+ const statement = () => {
753
+ const cursor = materialize(storage.sql.exec(query, ...bindings));
754
+ checkSettings();
755
+ return cursor;
756
+ };
757
+ if (!open) return storage.transactionSync(statement);
758
+ try {
759
+ return statement();
760
+ } catch (error) {
761
+ refuse(error instanceof Error ? error : new Error(String(error)));
762
+ throw error;
763
+ }
764
+ }
765
+ if (open) {
766
+ return runStatement(query, bindings, "write");
767
+ }
768
+ const before = changes();
769
+ let read;
770
+ let changed = false;
771
+ try {
772
+ storage.transactionSync(() => {
773
+ read = materialize(storage.sql.exec(query, ...bindings));
774
+ changed = changes() !== before;
775
+ checkSettings();
776
+ throw new ReadRolledBack();
777
+ });
778
+ } catch (error) {
779
+ if (!(error instanceof ReadRolledBack)) throw error;
780
+ }
781
+ if (changed || read === void 0)
782
+ throw new Error(
783
+ options.step !== void 0 ? "A workflow step mutation writes only inside ctx.sql.transaction(...), so a retried step applies its writes once." : "Queries are read-only. Change data from a mutation."
784
+ );
785
+ return read;
786
+ };
787
+ const reader = {
788
+ exec: (query, ...bindings) => run(query, bindings, "read")
789
+ };
790
+ const transactionHandle = () => {
791
+ let active = true;
792
+ const tx = {
793
+ exec: (query, ...bindings) => {
794
+ if (!active)
795
+ throw new Error("This transaction has ended, so its tx no longer runs statements.");
796
+ return run(query, bindings, "write");
797
+ }
798
+ };
799
+ return {
800
+ tx,
801
+ end: () => {
802
+ active = false;
803
+ }
804
+ };
805
+ };
806
+ const transaction = (work) => {
807
+ live();
808
+ if (open) throw new Error("ctx.sql.transaction(...) cannot be nested.");
809
+ const step = options.step;
810
+ if (step !== void 0 && transactions > 0)
811
+ throw new Error(
812
+ "A workflow step mutation opens at most one ctx.sql.transaction(...), which records the step's result."
813
+ );
814
+ transactions += 1;
815
+ violation = void 0;
816
+ const handle = transactionHandle();
817
+ const emittedBefore = options.emitted?.length;
818
+ const discardEmitted = () => {
819
+ if (options.emitted !== void 0 && emittedBefore !== void 0)
820
+ options.emitted.length = emittedBefore;
821
+ };
822
+ const body = () => {
823
+ open = true;
824
+ try {
825
+ const complete = () => {
826
+ const value = work(handle.tx);
827
+ if (isThenable(value))
828
+ throw new Error(
829
+ "ctx.sql.transaction(...) callbacks are synchronous and cannot await. Call outside services before or after the transaction."
830
+ );
831
+ if (violation !== void 0) throw violation;
832
+ return value;
833
+ };
834
+ if (step === void 0) return complete();
835
+ storage.sql.exec(
836
+ `CREATE TABLE IF NOT EXISTS ${receipts} (id TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, result TEXT NOT NULL) WITHOUT ROWID`
837
+ );
838
+ const saved = storage.sql.exec(`SELECT fingerprint, result FROM ${receipts} WHERE id = ?`, step.key).toArray()[0];
839
+ storage.sql.exec(
840
+ `CREATE TABLE IF NOT EXISTS ${stepEvents} (id TEXT PRIMARY KEY, events TEXT NOT NULL) WITHOUT ROWID`
841
+ );
842
+ if (saved !== void 0) {
843
+ if (saved.fingerprint !== step.fingerprint)
844
+ throw new Error("This workflow step already ran with different input.");
845
+ const replayed = storage.sql.exec(`SELECT events FROM ${stepEvents} WHERE id = ?`, step.key).toArray()[0];
846
+ if (replayed !== void 0 && options.emitted !== void 0)
847
+ options.emitted.push(...JSON.parse(String(replayed.events)));
848
+ return JSON.parse(String(saved.result));
849
+ }
850
+ const encoded = JSON.stringify(complete() ?? null);
851
+ const emitted = options.emitted?.slice(emittedBefore ?? 0) ?? [];
852
+ if (emitted.length > 0)
853
+ storage.sql.exec(
854
+ `INSERT INTO ${stepEvents} (id, events) VALUES (?, ?)`,
855
+ step.key,
856
+ JSON.stringify(emitted)
857
+ );
858
+ storage.sql.exec(
859
+ `INSERT INTO ${receipts} (id, fingerprint, result) VALUES (?, ?, ?)`,
860
+ step.key,
861
+ step.fingerprint,
862
+ encoded
863
+ );
864
+ return JSON.parse(encoded);
865
+ } finally {
866
+ open = false;
867
+ handle.end();
868
+ }
869
+ };
870
+ try {
871
+ return storage.transactionSync(body);
872
+ } catch (error) {
873
+ discardEmitted();
874
+ throw error;
875
+ }
876
+ };
877
+ const writer = {
878
+ // A step's writes go through its one transaction, which also records its receipt.
879
+ exec: (query, ...bindings) => run(query, bindings, options.step ? "read" : "write"),
880
+ transaction
881
+ };
882
+ return {
883
+ reader,
884
+ writer,
885
+ close: () => {
886
+ closed = true;
887
+ }
888
+ };
889
+ };
890
+ var MigrationFileInvalid = class extends Schema_exports.TaggedError()(
891
+ "MigrationFileInvalid",
892
+ { path: Schema_exports.String, reason: Schema_exports.String }
893
+ ) {
894
+ get message() {
895
+ return `${this.path}: ${this.reason}`;
896
+ }
897
+ };
898
+ var MigrationHistoryChanged = class extends Schema_exports.TaggedError()(
899
+ "MigrationHistoryChanged",
900
+ { reason: Schema_exports.String }
901
+ ) {
902
+ get message() {
903
+ return `${this.reason} Applied migrations cannot change: restore the original file and add a new migration instead. Nothing was applied; the previous deployment is still active.`;
904
+ }
905
+ };
906
+ var MigrationFailed = class extends Schema_exports.TaggedError()("MigrationFailed", {
907
+ path: Schema_exports.String,
908
+ reason: Schema_exports.String
909
+ }) {
910
+ get message() {
911
+ return `${this.path} failed: ${this.reason}. No migrations were applied; the previous deployment is still active.`;
912
+ }
913
+ };
914
+ var migrationName = /^(\d+)_[A-Za-z0-9_-]+\.sql$/;
915
+ var sha256 = (text) => (
916
+ // oxlint-disable-next-line executor/authored-code-through-adapter -- Web Crypto
917
+ Effect_exports.promise(() => crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))).pipe(
918
+ Effect_exports.map(
919
+ (digest) => Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")
920
+ )
921
+ )
922
+ );
923
+ var hasMigrations = (files) => files.some(
924
+ (file) => file.path.startsWith(`${migrationsDirectory}/`) && file.path.endsWith(".sql")
925
+ );
926
+ var migrationsOf = (files) => Effect_exports.gen(function* () {
927
+ const found = [];
928
+ for (const file of files) {
929
+ if (!file.path.startsWith(`${migrationsDirectory}/`) || !file.path.endsWith(".sql")) continue;
930
+ const name = file.path.slice(migrationsDirectory.length + 1);
931
+ const match = migrationName.exec(name);
932
+ if (name.includes("/") || match === null)
933
+ return yield* new MigrationFileInvalid({
934
+ path: file.path,
935
+ reason: "migrations are files directly in migrations/ named like 0001_create_notes.sql: a number that orders them, an underscore, then a name."
936
+ });
937
+ const content = file.content.replaceAll("\r\n", "\n");
938
+ found.push({
939
+ path: file.path,
940
+ order: Number(match[1]),
941
+ content,
942
+ hash: yield* sha256(content)
943
+ });
944
+ }
945
+ const ordered = [...found].sort((left, right) => left.order - right.order);
946
+ for (const [index, migration] of ordered.entries()) {
947
+ const previous = ordered[index - 1];
948
+ if (previous !== void 0 && previous.order === migration.order)
949
+ return yield* new MigrationFileInvalid({
950
+ path: migration.path,
951
+ reason: `it has the same number as ${previous.path}; give each migration its own number.`
952
+ });
953
+ }
954
+ return ordered;
955
+ });
956
+ var History = Schema_exports.Array(
957
+ Schema_exports.Struct({ id: Schema_exports.Number, path: Schema_exports.String, hash: Schema_exports.String })
958
+ );
959
+ var migrate = (storage, files) => Effect_exports.gen(function* () {
960
+ const migrations = yield* migrationsOf(files);
961
+ const baseline = readSettings(storage);
962
+ return yield* Effect_exports.sync(
963
+ () => storage.transactionSync(() => {
964
+ storage.sql.exec(
965
+ `CREATE TABLE IF NOT EXISTS ${migrationsTable} (id INTEGER PRIMARY KEY, path TEXT NOT NULL, hash TEXT NOT NULL, applied_at TEXT NOT NULL)`
966
+ );
967
+ const stored = storage.sql.exec("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'app_rows'").toArray().length > 0;
968
+ storage.sql.exec(`DROP VIEW IF EXISTS ${legacyRows}`);
969
+ storage.sql.exec(
970
+ `CREATE VIEW ${legacyRows} (table_name, id, body) AS ${stored ? "SELECT table_name, id, body FROM app_rows" : "SELECT '', '', '' WHERE 0"}`
971
+ );
972
+ const history = Schema_exports.decodeUnknownSync(History)(
973
+ storage.sql.exec(`SELECT id, path, hash FROM ${migrationsTable} ORDER BY id`).toArray()
974
+ );
975
+ for (const [index, applied] of history.entries()) {
976
+ const current = migrations[index];
977
+ if (current === void 0)
978
+ throw new MigrationHistoryChanged({
979
+ reason: `${applied.path} was applied to this app's database but is no longer in migrations/.`
980
+ });
981
+ if (current.path !== applied.path)
982
+ throw new MigrationHistoryChanged({
983
+ reason: `Migration ${index + 1} was applied as ${applied.path}, but the build has ${current.path} in its place.`
984
+ });
985
+ if (current.hash !== applied.hash)
986
+ throw new MigrationHistoryChanged({
987
+ reason: `${applied.path} changed after it was applied to this app's database.`
988
+ });
989
+ }
990
+ const pending = migrations.slice(history.length);
991
+ const appliedAt = (/* @__PURE__ */ new Date()).toISOString();
992
+ for (const [offset, migration] of pending.entries()) {
993
+ try {
994
+ storage.sql.exec(migration.content);
995
+ } catch (error) {
996
+ throw new MigrationFailed({
997
+ path: migration.path,
998
+ reason: error instanceof Error ? error.message : String(error)
999
+ });
1000
+ }
1001
+ storage.sql.exec(
1002
+ `INSERT INTO ${migrationsTable} (id, path, hash, applied_at) VALUES (?, ?, ?, ?)`,
1003
+ history.length + offset + 1,
1004
+ migration.path,
1005
+ migration.hash,
1006
+ appliedAt
1007
+ );
1008
+ }
1009
+ return pending.map((migration, offset) => ({
1010
+ id: history.length + offset + 1,
1011
+ name: migration.path
1012
+ }));
1013
+ })
1014
+ ).pipe(
1015
+ // Both are thrown inside the transaction so that it rolls back; they are expected failures.
1016
+ Effect_exports.catchDefect(
1017
+ (defect) => Schema_exports.is(MigrationFailed)(defect) || Schema_exports.is(MigrationHistoryChanged)(defect) ? Effect_exports.fail(defect) : Effect_exports.die(defect)
1018
+ ),
1019
+ Effect_exports.ensuring(Effect_exports.sync(() => restoreSettings(storage, baseline)))
1020
+ );
1021
+ });
1022
+
1023
+ // src/implementation/cache.ts
1024
+ var unavailableCache = {
1025
+ transport: () => Effect_exports.fail(new CacheError({ reason: "unavailable" })),
1026
+ background: () => Effect_exports.die(new Error("Cache background runner is unavailable"))
1027
+ };
1028
+ var authorCache = (host, accounts, signal, telemetry, deadline) => {
1029
+ const scoped = (scope, callerSignal = signal) => {
1030
+ const cache = makeCache(host.transport, host.background, scope, deadline);
1031
+ const load = (read, options) => cache[read]({
1032
+ key: options.key,
1033
+ schema: decoderOf(options.schema),
1034
+ freshFor: options.freshFor,
1035
+ ...options.staleFor === void 0 ? {} : { staleFor: options.staleFor },
1036
+ ...options.stale === void 0 ? {} : { stale: options.stale },
1037
+ load: Effect_exports.acquireUseRelease(
1038
+ Effect_exports.sync(() => new AbortController()),
1039
+ (controller) => appInvocationFetch(controller.signal).pipe(
1040
+ Effect_exports.flatMap(
1041
+ (fetch) => fromPromise(
1042
+ method(options, "load"),
1043
+ "loader"
1044
+ )({
1045
+ fetch,
1046
+ signal: controller.signal,
1047
+ cache: scoped(scope, controller.signal)
1048
+ })
1049
+ )
1050
+ ),
1051
+ (controller) => Effect_exports.sync(() => controller.abort())
1052
+ )
1053
+ });
1054
+ const service = (method2, operation) => toPromise(
1055
+ (...args) => operation(...args).pipe(
1056
+ owned("executor", "app.cache.call", { attributes: { "cache.method": method2 } })
1057
+ ),
1058
+ callerSignal,
1059
+ telemetry
1060
+ );
1061
+ return {
1062
+ get: service("get", (options) => load("get", options)),
1063
+ revalidate: service(
1064
+ "revalidate",
1065
+ (options) => load("revalidate", options)
1066
+ ),
1067
+ read: service(
1068
+ "read",
1069
+ (key, schema) => cache.read([key]).pipe(
1070
+ Effect_exports.flatMap((entries) => {
1071
+ const entry = entries[0];
1072
+ return entry === void 0 || entry === null ? Effect_exports.succeed(void 0) : Schema_exports.decodeUnknownEffect(decoderOf(schema))(entry.value);
1073
+ })
1074
+ )
1075
+ ),
1076
+ readMany: service(
1077
+ "readMany",
1078
+ (keys, schema) => cache.read(keys).pipe(
1079
+ Effect_exports.flatMap(
1080
+ (entries) => Effect_exports.forEach(
1081
+ entries,
1082
+ (entry) => entry === null ? Effect_exports.succeed(void 0) : Schema_exports.decodeUnknownEffect(decoderOf(schema))(entry.value)
1083
+ )
1084
+ )
1085
+ )
1086
+ ),
1087
+ write: service("write", cache.write),
1088
+ invalidate: service("invalidate", cache.invalidate),
1089
+ forAccount: (account) => {
1090
+ const bound = Object.values(accounts).flatMap((value) => Array.isArray(value) ? value : [value]).find((value) => value.id === account.id);
1091
+ if (bound === void 0) throw new CacheError({ reason: "invalid" });
1092
+ return scoped(
1093
+ { account: bound.id, method: bound.method, generation: bound.generation },
1094
+ callerSignal
1095
+ );
1096
+ }
1097
+ };
1098
+ };
1099
+ return scoped("shared");
1100
+ };
1101
+
1102
+ // src/implementation/host.ts
1103
+ var WireCatalog = Schema_exports.Struct({
1104
+ tools: Schema_exports.Array(Schema_exports.Union([HostedTool, HostedToolSummary])),
1105
+ routers: Schema_exports.Array(HostedRouter)
1106
+ });
1107
+ function safe2(work, failure) {
1108
+ return Effect_exports.suspend(work).pipe(
1109
+ Effect_exports.catchCause(
1110
+ (cause) => Cause_exports.hasInterrupts(cause) ? Effect_exports.interrupt : Effect_exports.fail(failure)
1111
+ )
1112
+ );
1113
+ }
1114
+ var evaluationSafe = (work, secrets) => work.pipe(
1115
+ Effect_exports.catchCause((cause) => {
1116
+ if (Cause_exports.hasInterrupts(cause)) return Effect_exports.interrupt;
1117
+ const error = Cause_exports.squash(cause);
1118
+ const provider = parseProviderError(error);
1119
+ const skills = parseSkillLoadFailed(error);
1120
+ const mcp = parseMcpError(error, secrets);
1121
+ return Effect_exports.fail(
1122
+ Option_exports.isSome(provider) ? leavingProviderError(provider.value, secrets, "discover") : Option_exports.isSome(skills) ? skills.value : Option_exports.isSome(mcp) ? mcp.value : new HostEvaluationFailed(failureDetail(error, secrets))
1123
+ );
1124
+ })
1125
+ );
1126
+ var declarationInvalid = (summary, cause, secrets = []) => new HostDeclarationInvalid({
1127
+ source: "app",
1128
+ errorName: "HostDeclarationInvalid",
1129
+ message: boundFailureMessage(
1130
+ cause === void 0 ? summary : `${summary}: ${describeFailure(cause)}`,
1131
+ secrets
1132
+ )
1133
+ });
1134
+ var declarationSafe = (work, summary) => Effect_exports.suspend(work).pipe(
1135
+ Effect_exports.catchCause(
1136
+ (cause) => Cause_exports.hasInterrupts(cause) ? Effect_exports.interrupt : Effect_exports.fail(declarationInvalid(summary, Cause_exports.squash(cause)))
1137
+ )
1138
+ );
1139
+ function declaredExposure(exposure) {
1140
+ const named = (kind) => Object.entries(exposure ?? {}).filter(([, value]) => value === kind).map(([field]) => field).sort();
1141
+ const plain = named("plain");
1142
+ const raw = named("raw");
1143
+ return { ...plain.length === 0 ? {} : { plain }, ...raw.length === 0 ? {} : { raw } };
1144
+ }
1145
+ function providerDeclaration(provider) {
1146
+ return declarationSafe(
1147
+ () => Effect_exports.gen(function* () {
1148
+ const auth = /* @__PURE__ */ new Map();
1149
+ for (const [name, method2] of Object.entries(provider.auth)) {
1150
+ switch (method2._tag) {
1151
+ case "secrets":
1152
+ auth.set(name, {
1153
+ type: "secrets",
1154
+ label: method2.label,
1155
+ fields: yield* jsonSchemaDocument(method2.fields),
1156
+ ...declaredExposure(method2.exposure)
1157
+ });
1158
+ break;
1159
+ case "oauth2":
1160
+ auth.set(name, {
1161
+ type: "oauth2",
1162
+ ...method2.config,
1163
+ response: yield* jsonSchemaDocument(method2.response),
1164
+ ...declaredExposure(method2.exposure)
1165
+ });
1166
+ break;
1167
+ }
1168
+ }
1169
+ return yield* Schema_exports.decodeUnknownEffect(DeclaredProvider)({
1170
+ name: provider.name,
1171
+ auth: Object.fromEntries(auth),
1172
+ // Order and repetition carry no meaning, so neither changes the provider's identity.
1173
+ ...provider.hosts === void 0 ? {} : { hosts: [...new Set(provider.hosts)].sort() }
1174
+ });
1175
+ }),
1176
+ `Account provider "${provider.name}" has an invalid declaration`
1177
+ );
1178
+ }
1179
+ function requirements(slots, sql, events) {
1180
+ return Effect_exports.gen(function* () {
1181
+ const accounts = /* @__PURE__ */ new Map();
1182
+ for (const [slot, selection] of Object.entries(slots)) {
1183
+ const provider = selection instanceof ManyAccounts ? selection.provider : selection;
1184
+ accounts.set(slot, {
1185
+ cardinality: selection instanceof ManyAccounts ? "many" : "one",
1186
+ definition: yield* providerDeclaration(provider),
1187
+ ...provider.health === void 0 ? {} : { health: true }
1188
+ });
1189
+ }
1190
+ return yield* Schema_exports.decodeUnknownEffect(DeclaredRequirements)({
1191
+ accounts: Object.fromEntries(accounts),
1192
+ capabilities: { skills: true, toolIndex: true, skillSources: true, scheduledTools: true },
1193
+ ...sql ? { sql: true } : {},
1194
+ ...events === void 0 || Object.keys(events).length === 0 ? {} : {
1195
+ events: yield* declarationSafe(
1196
+ () => declaredEvents(events),
1197
+ "The app's event declarations are invalid"
1198
+ )
1199
+ }
1200
+ }).pipe(
1201
+ Effect_exports.mapError(
1202
+ (cause) => declarationInvalid("The app's account declarations are invalid", cause)
1203
+ )
1204
+ );
1205
+ });
1206
+ }
1207
+ function canonical(value) {
1208
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
1209
+ if (value !== null && typeof value === "object") {
1210
+ return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(",")}}`;
1211
+ }
1212
+ return JSON.stringify(value);
1213
+ }
1214
+ function withoutHosts({ hosts: _hosts, ...provider }) {
1215
+ return provider;
1216
+ }
1217
+ function bindAccounts(slots, declarations, context) {
1218
+ return safe2(
1219
+ () => Effect_exports.gen(function* () {
1220
+ const selected = yield* Schema_exports.decodeUnknownEffect(ResolvedAccounts)(
1221
+ Redacted_exports.value(context.accounts)
1222
+ );
1223
+ if (Object.keys(selected).some((slot) => !Object.hasOwn(slots, slot))) {
1224
+ return yield* Effect_exports.fail(new HostAccountsInvalid());
1225
+ }
1226
+ const bound = /* @__PURE__ */ new Map();
1227
+ for (const [slot, selection] of Object.entries(slots)) {
1228
+ const requirement = declarations.accounts[slot];
1229
+ const supplied = Object.hasOwn(selected, slot) ? selected[slot] : void 0;
1230
+ if (requirement === void 0 || supplied === void 0)
1231
+ return yield* Effect_exports.fail(new HostAccountsInvalid());
1232
+ const provider = selection instanceof ManyAccounts ? selection.provider : selection;
1233
+ const many = selection instanceof ManyAccounts;
1234
+ if (many !== Array.isArray(supplied))
1235
+ return yield* Effect_exports.fail(new HostAccountsInvalid());
1236
+ const accounts = Array.isArray(supplied) ? supplied : [supplied];
1237
+ const ids = /* @__PURE__ */ new Set();
1238
+ const values = [];
1239
+ for (const account of accounts) {
1240
+ if (ids.has(account.id)) return yield* Effect_exports.fail(new HostAccountsInvalid());
1241
+ ids.add(account.id);
1242
+ if (canonical(withoutHosts(account.provider)) !== canonical(withoutHosts(requirement.definition)) || !Object.hasOwn(provider.auth, account.method))
1243
+ return yield* Effect_exports.fail(new HostAccountsInvalid());
1244
+ const method2 = provider.auth[account.method];
1245
+ if (method2 === void 0) return yield* Effect_exports.fail(new HostAccountsInvalid());
1246
+ const fields = yield* Schema_exports.decodeUnknownEffect(
1247
+ method2._tag === "secrets" ? method2.fields : method2.response
1248
+ )(account.fields);
1249
+ values.push({ id: account.id, method: account.method, fields });
1250
+ }
1251
+ if (many) bound.set(slot, values);
1252
+ else {
1253
+ const account = values[0];
1254
+ if (account === void 0) return yield* Effect_exports.fail(new HostAccountsInvalid());
1255
+ bound.set(slot, account);
1256
+ }
1257
+ }
1258
+ return { accounts: Object.fromEntries(bound) };
1259
+ }),
1260
+ new HostAccountsInvalid()
1261
+ );
1262
+ }
1263
+ var fetchLifetime = (signal, background) => Effect_exports.acquireRelease(
1264
+ Effect_exports.sync(() => {
1265
+ const controller = new AbortController();
1266
+ let refreshes = 0;
1267
+ let ended = false;
1268
+ const settle = () => {
1269
+ if (ended && refreshes === 0) controller.abort();
1270
+ };
1271
+ const end = () => {
1272
+ ended = true;
1273
+ settle();
1274
+ };
1275
+ signal.addEventListener("abort", end, { once: true });
1276
+ if (signal.aborted) end();
1277
+ const settled = Effect_exports.sync(() => {
1278
+ refreshes -= 1;
1279
+ settle();
1280
+ });
1281
+ return {
1282
+ signal: controller.signal,
1283
+ close: () => {
1284
+ signal.removeEventListener("abort", end);
1285
+ end();
1286
+ },
1287
+ /** Counted from the hand-off, so a refresh that has not started yet keeps the fetch. */
1288
+ background: (task) => Effect_exports.suspend(() => {
1289
+ refreshes += 1;
1290
+ return background(task.pipe(Effect_exports.ensuring(settled))).pipe(
1291
+ Effect_exports.onError(() => settled)
1292
+ );
1293
+ })
1294
+ };
1295
+ }),
1296
+ (lifetime) => Effect_exports.sync(lifetime.close)
1297
+ );
1298
+ function dispatch(app, request, context, signal, emitted) {
1299
+ return Effect_exports.scoped(
1300
+ Effect_exports.gen(function* () {
1301
+ if (!isApp(app))
1302
+ return yield* Effect_exports.fail(
1303
+ declarationInvalid("The app module's default export is not an app created by defineApp")
1304
+ );
1305
+ const native = toEffectApp(app);
1306
+ const secrets = accountSecrets(context.accounts);
1307
+ const ownsSql = hasMigrations(context.files ?? []);
1308
+ const declared = yield* requirements(native.accounts, ownsSql, native.events);
1309
+ if (request.operation === "requirements")
1310
+ return yield* safe2(
1311
+ () => Schema_exports.decodeUnknownEffect(JsonValue)(declared),
1312
+ new HostDeclarationInvalid()
1313
+ );
1314
+ if (request.operation === "migrate") {
1315
+ if (!ownsSql) return yield* new HostOperationNotFound();
1316
+ const storage2 = context.storage;
1317
+ if (storage2 === void 0)
1318
+ return yield* new HostOperationFailed(
1319
+ failureDetail(new Error("This host gave the app no SQL storage."), secrets)
1320
+ );
1321
+ const sources = yield* Schema_exports.decodeUnknownEffect(Schema_exports.Array(SkillFile))(
1322
+ context.files ?? []
1323
+ ).pipe(Effect_exports.mapError(() => new HostDeclarationInvalid()));
1324
+ const applied = yield* migrate(storage2, sources).pipe(
1325
+ Effect_exports.mapError((error) => new HostOperationFailed(failureDetail(error, secrets))),
1326
+ Effect_exports.withSpan("app.sql.migrate")
1327
+ );
1328
+ return yield* safe2(
1329
+ () => Schema_exports.decodeUnknownEffect(JsonValue)(applied),
1330
+ new HostOutputInvalid()
1331
+ );
1332
+ }
1333
+ const lifetime = yield* Effect_exports.acquireRelease(
1334
+ Effect_exports.sync(() => new AbortController()),
1335
+ (controller) => Effect_exports.sync(() => controller.abort())
1336
+ );
1337
+ const invocationSignal = AbortSignal.any([signal, lifetime.signal]);
1338
+ const storage = context.storage;
1339
+ const sqlSession = (step) => !ownsSql ? Effect_exports.succeed({ reader: noDatabase, writer: noDatabase }) : storage === void 0 ? Effect_exports.fail(
1340
+ new HostOperationFailed(
1341
+ failureDetail(new Error("This host gave the app no SQL storage."), secrets)
1342
+ )
1343
+ ) : Effect_exports.acquireRelease(
1344
+ Effect_exports.sync(
1345
+ () => authorSql(storage, {
1346
+ signal: invocationSignal,
1347
+ emitted,
1348
+ ...step === void 0 ? {} : { step }
1349
+ })
1350
+ ),
1351
+ (session2) => Effect_exports.sync(session2.close)
1352
+ );
1353
+ const deadline = context.deadline === void 0 ? void 0 : yield* safe2(
1354
+ () => Schema_exports.decodeUnknownEffect(InvocationDeadline)(context.deadline),
1355
+ new HostInputInvalid()
1356
+ );
1357
+ const withinDeadline = (work) => Effect_exports.gen(function* () {
1358
+ if (deadline === void 0) return yield* work;
1359
+ const remaining = deadline - (yield* Clock_exports.currentTimeMillis);
1360
+ if (remaining <= 0)
1361
+ return yield* new WorkflowFailure({ reason: "engine", retryable: true });
1362
+ const result = yield* work.pipe(
1363
+ Effect_exports.timeout(remaining),
1364
+ Effect_exports.catchTag(
1365
+ "TimeoutError",
1366
+ () => Effect_exports.fail(new WorkflowFailure({ reason: "engine", retryable: true }))
1367
+ )
1368
+ );
1369
+ if ((yield* Clock_exports.currentTimeMillis) >= deadline)
1370
+ return yield* new WorkflowFailure({ reason: "engine", retryable: true });
1371
+ return result;
1372
+ });
1373
+ if (request.operation === "account-check")
1374
+ return yield* checkAccount(
1375
+ native.accounts,
1376
+ declared,
1377
+ request.requirement,
1378
+ context,
1379
+ invocationSignal,
1380
+ deadline
1381
+ ).pipe(withinDeadline);
1382
+ let running;
1383
+ const delivery = (request2, signal2) => Effect_exports.suspend(
1384
+ () => running !== void 0 && context.elicitation !== void 0 ? context.elicitation(request2, signal2).pipe(
1385
+ // Delivering the question and waiting for its answer is the person's time.
1386
+ owned("person", "app.tool.elicitation"),
1387
+ Effect_exports.provideContext(running.context)
1388
+ ) : Effect_exports.fail(new ElicitationFailed({ reason: "unavailable" }))
1389
+ );
1390
+ const unavailableWorkflow = () => Effect_exports.fail(new WorkflowFailure({ reason: "unavailable", retryable: false }));
1391
+ const telemetry = yield* captureTelemetry;
1392
+ const control = (operation, work) => work.pipe(
1393
+ owned("executor", workflowControlSpan, {
1394
+ attributes: { "executor.workflow.operation": operation }
1395
+ })
1396
+ );
1397
+ const workflowControls = {
1398
+ start: toPromise(
1399
+ (input2) => control(
1400
+ "start",
1401
+ context.workflowControls === void 0 ? unavailableWorkflow() : context.workflowControls.start(input2)
1402
+ ),
1403
+ invocationSignal,
1404
+ telemetry.context
1405
+ ),
1406
+ get: toPromise(
1407
+ (input2) => control(
1408
+ "get",
1409
+ context.workflowControls === void 0 ? unavailableWorkflow() : context.workflowControls.get(input2)
1410
+ ),
1411
+ invocationSignal,
1412
+ telemetry.context
1413
+ ),
1414
+ list: toPromise(
1415
+ (input2) => control(
1416
+ "list",
1417
+ context.workflowControls === void 0 ? unavailableWorkflow() : context.workflowControls.list(input2)
1418
+ ),
1419
+ invocationSignal,
1420
+ telemetry.context
1421
+ ),
1422
+ terminate: toPromise(
1423
+ (input2) => control(
1424
+ "terminate",
1425
+ context.workflowControls === void 0 ? unavailableWorkflow() : context.workflowControls.terminate(input2)
1426
+ ),
1427
+ invocationSignal,
1428
+ telemetry.context
1429
+ )
1430
+ };
1431
+ const workflowReads = {
1432
+ get: workflowControls.get,
1433
+ list: workflowControls.list
1434
+ };
1435
+ const files = yield* Schema_exports.decodeUnknownEffect(Schema_exports.Array(SkillFile))(
1436
+ context.files ?? []
1437
+ ).pipe(Effect_exports.mapError(() => new HostDeclarationInvalid()));
1438
+ let cacheCommands = 0;
1439
+ const hostCache = context.cache ?? unavailableCache;
1440
+ const fetching = yield* fetchLifetime(signal, hostCache.background);
1441
+ const bound = {
1442
+ cache: authorCache(
1443
+ {
1444
+ ...hostCache,
1445
+ transport: (command) => {
1446
+ cacheCommands += 1;
1447
+ return hostCache.transport(command);
1448
+ },
1449
+ background: fetching.background
1450
+ },
1451
+ Redacted_exports.value(context.accounts),
1452
+ invocationSignal,
1453
+ telemetry.context,
1454
+ deadline
1455
+ ),
1456
+ files,
1457
+ ...yield* bindAccounts(native.accounts, declared, context).pipe(
1458
+ Effect_exports.withSpan("app.accounts.bind")
1459
+ ),
1460
+ workflows: workflowReads,
1461
+ signal: invocationSignal,
1462
+ fetch: yield* appInvocationFetch(fetching.signal),
1463
+ elicit: makeElicit(delivery, invocationSignal, telemetry.context)
1464
+ };
1465
+ const accountIds = Object.values(bound.accounts).flatMap(
1466
+ (selected) => (Array.isArray(selected) ? selected : [selected]).map(
1467
+ (account) => account.id
1468
+ )
1469
+ );
1470
+ const emitter = (sourceAccount) => makeEmitter({
1471
+ events: native.events ?? {},
1472
+ accounts: accountIds,
1473
+ ...sourceAccount === void 0 ? {} : { sourceAccount },
1474
+ emitted
1475
+ });
1476
+ const definition = yield* evaluationSafe(native.evaluate(bound), secrets).pipe(
1477
+ Effect_exports.withSpan("app.evaluate")
1478
+ );
1479
+ if (request.operation === "skills") {
1480
+ const declared2 = definition.skills ?? (yield* folderSkillsEffect({ files }).pipe(
1481
+ Effect_exports.mapError(() => new HostDeclarationInvalid())
1482
+ ));
1483
+ const source = definition.dynamicSkills;
1484
+ const before = cacheCommands;
1485
+ const dynamic = source === void 0 ? [] : yield* evaluationSafe(Effect_exports.suspend(source.list), secrets).pipe(
1486
+ Effect_exports.withSpan("app.skills.load")
1487
+ );
1488
+ const cached = source !== void 0 && cacheCommands > before;
1489
+ const authored = new Set([...declared2, ...dynamic].map((skill) => skill.name));
1490
+ const routed = (yield* routerSkills(definition.tools).pipe(
1491
+ Effect_exports.withSpan("app.skills.routers")
1492
+ )).filter((skill) => !authored.has(skill.name));
1493
+ const skills = yield* Schema_exports.decodeUnknownEffect(AppSkills)([
1494
+ ...declared2,
1495
+ ...dynamic,
1496
+ ...routed
1497
+ ]).pipe(Effect_exports.mapError(() => new HostDeclarationInvalid()));
1498
+ return request.sources === true ? { skills, dynamic: source !== void 0, cached } : skills;
1499
+ }
1500
+ if (request.operation === "workflows") {
1501
+ return yield* Effect_exports.forEach(
1502
+ Object.entries(definition.workflows ?? {}),
1503
+ ([name, entry]) => safe2(
1504
+ () => Effect_exports.gen(function* () {
1505
+ return yield* Schema_exports.decodeUnknownEffect(HostedWorkflow)({
1506
+ name,
1507
+ ...entry.description === void 0 ? {} : { description: entry.description },
1508
+ inputSchema: yield* jsonSchemaDocument(entry.input),
1509
+ ...entry.output === void 0 ? {} : { outputSchema: yield* jsonSchemaDocument(entry.output) }
1510
+ });
1511
+ }),
1512
+ new HostDeclarationInvalid()
1513
+ )
1514
+ );
1515
+ }
1516
+ if (request.operation === "workflow-validate" || request.operation === "workflow-run") {
1517
+ const entry = definition.workflows !== void 0 && Object.hasOwn(definition.workflows, request.name) ? definition.workflows[request.name] : void 0;
1518
+ if (entry === void 0)
1519
+ return yield* new WorkflowFailure({ reason: "not_found", retryable: false });
1520
+ const input2 = yield* safe2(
1521
+ () => Schema_exports.decodeUnknownEffect(entry.input)(request.input),
1522
+ new WorkflowFailure({ reason: "input", retryable: false })
1523
+ );
1524
+ if (request.operation === "workflow-validate")
1525
+ return yield* safe2(
1526
+ () => Schema_exports.decodeUnknownEffect(WorkflowValue)(input2),
1527
+ new WorkflowFailure({ reason: "input", retryable: false })
1528
+ );
1529
+ const execution = context.workflow;
1530
+ if (execution === void 0)
1531
+ return yield* new WorkflowFailure({ reason: "unavailable", retryable: false });
1532
+ const workflowContext = yield* makeWorkflowContext(
1533
+ execution,
1534
+ definition,
1535
+ (stepId, signal2) => Effect_exports.gen(function* () {
1536
+ const current = yield* execution.resolve();
1537
+ const accounts = yield* safe2(
1538
+ () => bindAccounts(native.accounts, declared, current),
1539
+ new WorkflowFailure({ reason: "credentials", retryable: false })
1540
+ );
1541
+ return {
1542
+ context: {
1543
+ ...accounts,
1544
+ cache: authorCache(
1545
+ context.cache ?? unavailableCache,
1546
+ Redacted_exports.value(current.accounts),
1547
+ signal2,
1548
+ (yield* captureTelemetry).context
1549
+ ),
1550
+ files,
1551
+ fetch: yield* appInvocationFetch(signal2),
1552
+ signal: signal2,
1553
+ runId: execution.runId,
1554
+ stepId,
1555
+ idempotencyKey: stepId
1556
+ },
1557
+ // The resolved values, not the app's decoded fields, which may be `Redacted`.
1558
+ secrets: accountSecrets(current.accounts)
1559
+ };
1560
+ }),
1561
+ invocationSignal
1562
+ );
1563
+ const output = yield* workflowSafe(entry.run(workflowContext, input2), secrets);
1564
+ const outputSchema = entry.output;
1565
+ const decoded = outputSchema === void 0 ? output : yield* safe2(
1566
+ () => Schema_exports.decodeUnknownEffect(outputSchema)(output),
1567
+ new WorkflowFailure({
1568
+ reason: "output",
1569
+ retryable: false,
1570
+ message: "The workflow's result does not match its declared output schema."
1571
+ })
1572
+ );
1573
+ return yield* safe2(
1574
+ () => Schema_exports.decodeUnknownEffect(WorkflowValue)(decoded),
1575
+ new WorkflowFailure({
1576
+ reason: "output",
1577
+ retryable: false,
1578
+ message: "The workflow returned a value that is not JSON, such as undefined, or is larger than 1 MiB. Return null for no result."
1579
+ })
1580
+ );
1581
+ }
1582
+ if (request.operation === "inspect") {
1583
+ const summary = request.detail === "summary";
1584
+ const catalog = yield* readCatalog(definition.tools, {
1585
+ summary,
1586
+ secrets,
1587
+ ...request.tools === void 0 ? {} : { wanted: new Set(request.tools) },
1588
+ ...request.scheduled === true ? { scheduled: true } : {},
1589
+ schedules: (name) => Object.entries(definition.schedules ?? {}).filter(([, schedule]) => schedule.tool === name).map(([name2, { tool: _tool, ...schedule }]) => ({ name: name2, ...schedule }))
1590
+ }).pipe(Effect_exports.withSpan("app.catalog.read"));
1591
+ return yield* safe2(
1592
+ () => Schema_exports.encodeEffect(WireCatalog)(catalog).pipe(
1593
+ Effect_exports.flatMap(Schema_exports.decodeUnknownEffect(JsonValue))
1594
+ ),
1595
+ new HostDeclarationInvalid()
1596
+ );
1597
+ }
1598
+ if (request.operation === "webhook-complete" || request.operation === "webhook-validate" || request.operation === "webhooks" || request.operation === "webhook-register" || request.operation === "webhook-handle" || request.operation === "webhook-unregister") {
1599
+ const session2 = yield* sqlSession();
1600
+ return yield* dispatchWebhook(
1601
+ definition,
1602
+ request,
1603
+ {
1604
+ files,
1605
+ cache: bound.cache,
1606
+ accounts: bound.accounts,
1607
+ workflows: workflowControls,
1608
+ signal: bound.signal,
1609
+ fetch: bound.fetch,
1610
+ sql: session2.writer,
1611
+ events: emitter("sourceAccount" in request ? request.sourceAccount : void 0)
1612
+ },
1613
+ Redacted_exports.value(context.accounts)
1614
+ );
1615
+ }
1616
+ const toolName = request.operation === "call" ? request.tool : request.name;
1617
+ const location = locate(definition.tools, toolName);
1618
+ const tool = location === void 0 ? void 0 : location.kind === "operation" ? location.operation : yield* evaluationSafe(location.source.resolve(location.name), secrets).pipe(
1619
+ Effect_exports.withSpan("app.tool.resolve")
1620
+ );
1621
+ if (tool === void 0)
1622
+ return yield* request.operation === "call" ? new HostToolNotFound() : new HostOperationNotFound();
1623
+ const requested = request.operation === "call" ? request.kind : request.operation === "query" ? "query" : "mutation";
1624
+ if (requested !== void 0 && tool.kind !== requested)
1625
+ return yield* new HostKindMismatch({ tool: toolName, requested, actual: tool.kind });
1626
+ const kind = tool.kind === "query" ? "query" : "mutate";
1627
+ const input = yield* Effect_exports.suspend(
1628
+ () => Schema_exports.decodeUnknownEffect(tool.input)(request.input)
1629
+ ).pipe(
1630
+ Effect_exports.catchCause(
1631
+ (cause) => Cause_exports.hasInterrupts(cause) ? Effect_exports.interrupt : Effect_exports.fail(inputInvalid(Cause_exports.squash(cause), request.input))
1632
+ )
1633
+ );
1634
+ if (context.approval !== void 0) {
1635
+ const approved = yield* safe2(
1636
+ () => Schema_exports.decodeUnknownEffect(TrustedToolApproval)(context.approval),
1637
+ new HostInputInvalid()
1638
+ );
1639
+ const decoded = yield* safe2(
1640
+ () => Schema_exports.decodeUnknownEffect(JsonValue)(input),
1641
+ new HostInputInvalid()
1642
+ );
1643
+ if (approved.tool !== toolName || !Schema_exports.toEquivalence(JsonValue)(approved.input, decoded)) {
1644
+ return yield* new HostInputInvalid();
1645
+ }
1646
+ } else if (tool.approval !== void 0) {
1647
+ const approval = tool.approval;
1648
+ const decision = yield* safe2(
1649
+ () => approval({ toolName, toolInput: input, signal: invocationSignal }).pipe(
1650
+ Effect_exports.withSpan("app.tool.approval", {
1651
+ attributes: { "executor.tool.name": toolName }
1652
+ }),
1653
+ Effect_exports.flatMap(Schema_exports.decodeUnknownEffect(ApprovalDecision))
1654
+ ),
1655
+ new HostToolPolicyFailed()
1656
+ );
1657
+ yield* Match_exports.value(decision).pipe(
1658
+ Match_exports.when("approved", () => Effect_exports.void),
1659
+ Match_exports.when("denied", () => Effect_exports.fail(new HostToolBlocked())),
1660
+ Match_exports.when(
1661
+ "user-approval",
1662
+ () => safe2(() => Schema_exports.decodeUnknownEffect(JsonValue)(input), new HostInputInvalid()).pipe(
1663
+ Effect_exports.flatMap(
1664
+ (input2) => Effect_exports.fail(
1665
+ new HostToolApprovalRequired({
1666
+ input: input2,
1667
+ elicitation: approvalElicitation(toolName, input2)
1668
+ })
1669
+ )
1670
+ )
1671
+ )
1672
+ ),
1673
+ Match_exports.exhaustive
1674
+ );
1675
+ }
1676
+ const replay = context.replay === void 0 ? void 0 : yield* safe2(
1677
+ () => Schema_exports.decodeUnknownEffect(WorkflowReplay)(context.replay),
1678
+ new HostInputInvalid()
1679
+ );
1680
+ if (replay !== void 0 && kind !== "mutate") return yield* new HostInputInvalid();
1681
+ const session = yield* sqlSession(replay);
1682
+ const execute = () => Effect_exports.gen(function* () {
1683
+ const output = yield* Effect_exports.gen(function* () {
1684
+ running = yield* captureTelemetry;
1685
+ const fetch = yield* appInvocationFetch(fetching.signal);
1686
+ return yield* tool.run(
1687
+ {
1688
+ ...bound,
1689
+ fetch,
1690
+ workflows: kind === "mutate" ? workflowControls : workflowReads,
1691
+ sql: kind === "mutate" ? session.writer : session.reader,
1692
+ ...kind === "mutate" ? { events: emitter() } : {}
1693
+ },
1694
+ input
1695
+ );
1696
+ }).pipe(
1697
+ Effect_exports.ensuring(
1698
+ Effect_exports.sync(() => {
1699
+ running = void 0;
1700
+ })
1701
+ ),
1702
+ Effect_exports.catchCause((cause) => {
1703
+ if (Cause_exports.hasInterrupts(cause)) return Effect_exports.interrupt;
1704
+ const error = Cause_exports.squash(cause);
1705
+ const provider = parseProviderError(error);
1706
+ const response = Schema_exports.decodeUnknownOption(OpenapiResponseError)(error);
1707
+ const mcp = parseMcpError(error, secrets);
1708
+ const failure = Schema_exports.decodeUnknownOption(ElicitationFailed)(error);
1709
+ return Effect_exports.fail(
1710
+ Option_exports.isSome(provider) ? leavingProviderError(provider.value, secrets, "call") : Option_exports.isSome(response) ? new OpenapiResponseError({
1711
+ code: response.value.code,
1712
+ status: response.value.status,
1713
+ message: response.value.message,
1714
+ ...response.value.recovery === void 0 ? {} : { recovery: response.value.recovery }
1715
+ }) : Option_exports.isSome(mcp) ? mcp.value : Option_exports.isSome(failure) ? failure.value : new HostOperationFailed(failureDetail(error, secrets))
1716
+ );
1717
+ }),
1718
+ Effect_exports.withSpan("app.operation.execute", {
1719
+ attributes: { "executor.tool.name": toolName, "executor.operation": kind }
1720
+ })
1721
+ );
1722
+ const outputSchema = tool.output;
1723
+ const decoded = outputSchema === void 0 ? output : yield* safe2(
1724
+ () => Schema_exports.decodeUnknownEffect(outputSchema)(output),
1725
+ new HostOutputInvalid()
1726
+ );
1727
+ return yield* safe2(
1728
+ () => Schema_exports.decodeUnknownEffect(JsonValue)(decoded),
1729
+ new HostOutputInvalid()
1730
+ );
1731
+ });
1732
+ return yield* withinDeadline(execute());
1733
+ })
1734
+ );
1735
+ }
1736
+ function checkAccount(slots, declared, requirement, context, signal, deadline) {
1737
+ return Effect_exports.gen(function* () {
1738
+ const selection = Object.hasOwn(slots, requirement) ? slots[requirement] : void 0;
1739
+ const slot = Object.hasOwn(declared.accounts, requirement) ? declared.accounts[requirement] : void 0;
1740
+ if (selection === void 0 || slot === void 0) return yield* new HostAccountsInvalid();
1741
+ const provider = selection instanceof ManyAccounts ? selection.provider : selection;
1742
+ const health = provider.health;
1743
+ if (health === void 0) return yield* new HostOperationNotFound();
1744
+ const { accounts } = yield* bindAccounts(
1745
+ { [requirement]: provider },
1746
+ { accounts: { [requirement]: { ...slot, cardinality: "one" } } },
1747
+ context
1748
+ ).pipe(Effect_exports.withSpan("app.accounts.bind"));
1749
+ const account = accounts[requirement];
1750
+ if (account === void 0 || !("id" in account)) return yield* new HostAccountsInvalid();
1751
+ const result = yield* Effect_exports.suspend(
1752
+ () => Effect_exports.gen(function* () {
1753
+ return yield* health.run({
1754
+ account,
1755
+ fetch: yield* appInvocationFetch(signal),
1756
+ signal,
1757
+ ...deadline === void 0 ? {} : { deadline }
1758
+ });
1759
+ })
1760
+ ).pipe(
1761
+ Effect_exports.catchCause((cause) => {
1762
+ if (Cause_exports.hasInterrupts(cause)) return Effect_exports.interrupt;
1763
+ const error = Cause_exports.squash(cause);
1764
+ const status = Schema_exports.decodeUnknownOption(ResponseStatusError)(error);
1765
+ const classified = Option_exports.isSome(status) ? Option_exports.fromNullishOr(httpProviderError(status.value.status)) : parseProviderError(error);
1766
+ const secrets = accountSecrets(context.accounts);
1767
+ return Effect_exports.fail(
1768
+ Option_exports.isSome(classified) ? leavingProviderError(accountProviderError(classified.value, account.id), secrets) : new HostOperationFailed(failureDetail(error, secrets))
1769
+ );
1770
+ }),
1771
+ Effect_exports.withSpan("app.account.check")
1772
+ );
1773
+ return yield* safe2(
1774
+ () => Schema_exports.decodeUnknownEffect(AccountCheckResult)(result ?? {}).pipe(
1775
+ Effect_exports.flatMap(Schema_exports.encodeEffect(AccountCheckResult)),
1776
+ Effect_exports.flatMap(Schema_exports.decodeUnknownEffect(JsonValue))
1777
+ ),
1778
+ new HostOutputInvalid()
1779
+ );
1780
+ });
1781
+ }
1782
+ var errorStatus = Match_exports.type().pipe(
1783
+ Match_exports.tagsExhaustive({
1784
+ ProviderError: () => 502,
1785
+ McpError: () => 502,
1786
+ SkillLoadFailed: () => 502,
1787
+ OpenapiResponseError: () => 502,
1788
+ WorkflowFailure: () => 422,
1789
+ HostRequestInvalid: () => 400,
1790
+ HostAccountsInvalid: () => 422,
1791
+ HostInputInvalid: () => 422,
1792
+ HostOperationNotFound: () => 404,
1793
+ HostKindMismatch: () => 409,
1794
+ HostToolNotFound: () => 404,
1795
+ HostToolBlocked: () => 403,
1796
+ HostToolApprovalRequired: () => 409,
1797
+ HostToolPolicyFailed: () => 500,
1798
+ HostOperationFailed: () => 500,
1799
+ DatabaseLimitExceeded: () => 422,
1800
+ DatabaseFieldReserved: () => 422,
1801
+ HostDeclarationInvalid: () => 500,
1802
+ HostEvaluationFailed: () => 500,
1803
+ HostOutputInvalid: () => 500,
1804
+ ElicitationFailed: () => 422
1805
+ })
1806
+ );
1807
+ var createAppHandler = (app) => (request, context) => Effect_exports.gen(function* () {
1808
+ if (request.method !== "POST") return yield* Effect_exports.fail(new HostRequestInvalid());
1809
+ const input = yield* Effect_exports.tryPromise({
1810
+ try: () => request.json(),
1811
+ catch: () => new HostRequestInvalid()
1812
+ });
1813
+ const command = yield* Schema_exports.decodeUnknownEffect(HostRequest)(input, {
1814
+ onExcessProperty: "error"
1815
+ }).pipe(Effect_exports.mapError(() => new HostRequestInvalid()));
1816
+ yield* Effect_exports.annotateCurrentSpan({
1817
+ "executor.operation": command.operation,
1818
+ ...command.operation === "call" ? { "executor.tool.name": command.tool } : {}
1819
+ });
1820
+ let toolError = false;
1821
+ const emitted = [];
1822
+ const value = yield* dispatch(app, command, context, request.signal, emitted).pipe(
1823
+ Effect_exports.provideService(ToolResultObservation, {
1824
+ failed: () => {
1825
+ toolError = true;
1826
+ }
1827
+ }),
1828
+ // Name what failed on the span; the bounded message stays in the reply only. The host
1829
+ // records an app's own error names and codes as `unrecognized` (telemetry `app-records`).
1830
+ Effect_exports.tapError(
1831
+ (error) => (error._tag === "HostEvaluationFailed" || error._tag === "HostOperationFailed" || error._tag === "HostDeclarationInvalid") && error.errorName !== void 0 ? Effect_exports.annotateCurrentSpan({
1832
+ "error.type": error.errorName,
1833
+ ...error.source === void 0 ? {} : { "executor.failure.source": error.source },
1834
+ ...error.code === void 0 ? {} : { "executor.failure.code": error.code }
1835
+ }) : Effect_exports.void
1836
+ ),
1837
+ // Tool operations time themselves, dividing their time by who owned the work in progress.
1838
+ // Other operations do not.
1839
+ command.operation === "call" || command.operation === "query" || command.operation === "mutate" ? timedInvocation(command.operation) : Effect_exports.withSpan(`app.${command.operation}`)
1840
+ );
1841
+ if (toolError)
1842
+ yield* Effect_exports.annotateCurrentSpan({
1843
+ "executor.outcome": "failed",
1844
+ "error.type": "McpToolError"
1845
+ });
1846
+ return Response.json({
1847
+ ok: true,
1848
+ value,
1849
+ ...toolError ? { toolError: true } : {},
1850
+ ...emitted.length === 0 ? {} : { events: emitted }
1851
+ });
1852
+ }).pipe(
1853
+ Effect_exports.catch(
1854
+ (error) => Schema_exports.encodeEffect(HostError)(error).pipe(
1855
+ Effect_exports.map(
1856
+ (encoded) => Response.json({ ok: false, error: encoded }, { status: errorStatus(error) })
1857
+ ),
1858
+ Effect_exports.orDie
1859
+ )
1860
+ ),
1861
+ Effect_exports.catchCause(
1862
+ (cause) => Cause_exports.hasInterrupts(cause) ? Effect_exports.interrupt : (
1863
+ // The cause can carry any text the app threw; its caller receives that, not the log.
1864
+ Effect_exports.logError("The app's request failed unexpectedly").pipe(
1865
+ Effect_exports.andThen(
1866
+ Schema_exports.encodeEffect(HostError)(
1867
+ declarationInvalid(
1868
+ "The app failed while it was loaded",
1869
+ Cause_exports.squash(cause),
1870
+ accountSecrets(context.accounts)
1871
+ )
1872
+ )
1873
+ ),
1874
+ Effect_exports.map((error) => Response.json({ ok: false, error }, { status: 500 })),
1875
+ Effect_exports.orDie
1876
+ )
1877
+ )
1878
+ )
1879
+ );
1880
+
1881
+ export {
1882
+ prepareElicitation,
1883
+ ApprovalDecision,
1884
+ createAppHandler
1885
+ };