apps 0.0.1-beta.1 → 0.0.1-beta.100

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