apps 0.0.1-beta.9 → 0.0.1-beta.91

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 (191) hide show
  1. package/README.md +56 -38
  2. package/framework-reference.json +1 -1
  3. package/js/chunk-3LEVTFD4.js +712 -0
  4. package/js/chunk-5FHWNLCI.js +88 -0
  5. package/js/{chunk-FL2QR3XW.js → chunk-5MDA7MKL.js} +338 -73
  6. package/js/chunk-6XQLA5NC.js +5047 -0
  7. package/js/{chunk-M3B3DE4K.js → chunk-74YVXBKY.js} +463 -218
  8. package/js/chunk-7PHHWYV4.js +335 -0
  9. package/js/chunk-DADXWWRZ.js +449 -0
  10. package/js/{chunk-27F7W2LG.js → chunk-DDHBUKXX.js} +18 -2
  11. package/js/{chunk-UK573G7W.js → chunk-EOPQ727L.js} +87 -51
  12. package/js/{chunk-5T57N25Q.js → chunk-GQ33QSNB.js} +583 -69
  13. package/js/{chunk-JU7VHODU.js → chunk-H72MEDMN.js} +65 -10
  14. package/js/chunk-I5C7FD5Z.js +171 -0
  15. package/js/{chunk-CDL5PM2Q.js → chunk-IFJU5SYQ.js} +19082 -18402
  16. package/js/{chunk-VFZKSM3T.js → chunk-JPEUKEV4.js} +3 -3
  17. package/js/{chunk-KUMBKVJD.js → chunk-KLYSEHUD.js} +2 -2
  18. package/js/{chunk-RFVIONFX.js → chunk-KUCCHNVY.js} +123 -44
  19. package/js/chunk-OD3KFKZD.js +1617 -0
  20. package/js/{chunk-57RKNWL2.js → chunk-PD6I2SDG.js} +4 -4
  21. package/js/{chunk-72JNVHPK.js → chunk-PYQLOLOC.js} +4 -3
  22. package/js/{chunk-ODEIDRGW.js → chunk-QWQM3CLH.js} +795 -176
  23. package/js/{chunk-IJX4CYZO.js → chunk-TUMGL2OC.js} +228 -264
  24. package/js/{chunk-IPI4MFSN.js → chunk-XBG7HHXC.js} +2 -2
  25. package/js/chunk-XPRZTLHD.js +1915 -0
  26. package/js/chunk-YNJ5CZMJ.js +93 -0
  27. package/js/chunk-YRGL4QEF.js +49 -0
  28. package/js/{chunk-Z5M2LQOZ.js → chunk-YWFUWTUJ.js} +113 -58
  29. package/js/client.js +142 -78
  30. package/js/contracts.js +142 -21
  31. package/js/effect.js +18 -19
  32. package/js/{es-APDZKREY.js → es-DIULA3ZF.js} +62 -1659
  33. package/js/graphql.js +49 -40
  34. package/js/host.js +85 -62
  35. package/js/index.js +165 -70
  36. package/js/mcp/effect.js +21 -21
  37. package/js/mcp.js +76 -56
  38. package/js/openapi.js +4189 -1411
  39. package/js/react.js +2 -3
  40. package/js/skills/effect.js +6 -3
  41. package/js/skills.js +208 -81
  42. package/js/storage/facet.js +1 -540
  43. package/js/ui/auth/contracts.js +2 -2
  44. package/js/ui/auth.js +5 -5
  45. package/js/ui/contracts.js +5 -4
  46. package/js/ui/serving.js +8605 -225
  47. package/package.json +3 -8
  48. package/runtime.json +1 -1
  49. package/types/app-cache/src/contracts/cache.d.ts +18 -0
  50. package/types/app-cache/src/index.d.ts +34 -2
  51. package/types/apps/src/contracts/api-response-error.d.ts +4 -0
  52. package/types/apps/src/contracts/app.d.ts +60 -11
  53. package/types/apps/src/contracts/cache.d.ts +20 -0
  54. package/types/apps/src/contracts/context.d.ts +60 -17
  55. package/types/apps/src/contracts/elicitation.d.ts +23 -7
  56. package/types/apps/src/contracts/events.d.ts +94 -0
  57. package/types/apps/src/contracts/failure.d.ts +30 -1
  58. package/types/apps/src/contracts/graphql.d.ts +2 -1
  59. package/types/apps/src/contracts/host.d.ts +1446 -17
  60. package/types/apps/src/contracts/icons.d.ts +28 -0
  61. package/types/apps/src/contracts/live.d.ts +2 -0
  62. package/types/apps/src/contracts/mcp.d.ts +81 -20
  63. package/types/apps/src/contracts/network.d.ts +120 -0
  64. package/types/apps/src/contracts/openapi-compile.d.ts +82 -3
  65. package/types/apps/src/contracts/openapi.d.ts +41 -9
  66. package/types/apps/src/contracts/operations.d.ts +14 -7
  67. package/types/apps/src/contracts/placement.d.ts +102 -0
  68. package/types/apps/src/contracts/protocol-version.d.ts +2 -2
  69. package/types/apps/src/contracts/protocols/1.d.ts +733 -81
  70. package/types/apps/src/contracts/protocols/10.d.ts +1450 -0
  71. package/types/apps/src/contracts/protocols/11.d.ts +1149 -0
  72. package/types/apps/src/contracts/protocols/12.d.ts +3310 -0
  73. package/types/apps/src/contracts/protocols/2.d.ts +69 -26
  74. package/types/apps/src/contracts/protocols/3.d.ts +133 -33
  75. package/types/apps/src/contracts/protocols/4.d.ts +122 -45
  76. package/types/apps/src/contracts/protocols/5.d.ts +157 -47
  77. package/types/apps/src/contracts/protocols/6.d.ts +1629 -0
  78. package/types/apps/src/contracts/protocols/7.d.ts +1785 -0
  79. package/types/apps/src/contracts/protocols/8.d.ts +1182 -0
  80. package/types/apps/src/contracts/protocols/9.d.ts +1104 -0
  81. package/types/apps/src/contracts/protocols/current.d.ts +6669 -0
  82. package/types/apps/src/contracts/protocols/oauth-6.d.ts +74 -0
  83. package/types/apps/src/contracts/protocols/oauth.d.ts +134 -0
  84. package/types/apps/src/contracts/provider-error.d.ts +9 -0
  85. package/types/apps/src/contracts/provider.d.ts +90 -6
  86. package/types/apps/src/contracts/schedules.d.ts +7 -1
  87. package/types/apps/src/contracts/schema.d.ts +21 -0
  88. package/types/apps/src/contracts/skills.d.ts +50 -13
  89. package/types/apps/src/contracts/sql.d.ts +63 -0
  90. package/types/apps/src/contracts/ui.d.ts +44 -14
  91. package/types/apps/src/contracts/webhooks.d.ts +24 -7
  92. package/types/apps/src/contracts/workflows.d.ts +19 -17
  93. package/types/apps/src/facet.d.ts +4 -5
  94. package/types/apps/src/host.d.ts +5 -0
  95. package/types/apps/src/implementation/account-router.d.ts +4 -3
  96. package/types/apps/src/implementation/app.d.ts +41 -14
  97. package/types/apps/src/implementation/authoring.d.ts +25 -5
  98. package/types/apps/src/implementation/browser-scripts.gen.d.ts +6 -0
  99. package/types/apps/src/implementation/cache.d.ts +29 -2
  100. package/types/apps/src/implementation/catalog-cache.d.ts +35 -4
  101. package/types/apps/src/implementation/elicitation.d.ts +18 -15
  102. package/types/apps/src/implementation/events.d.ts +64 -0
  103. package/types/apps/src/implementation/failure-detail.d.ts +28 -5
  104. package/types/apps/src/implementation/graphql-catalog.d.ts +3 -3
  105. package/types/apps/src/implementation/graphql.d.ts +4 -3
  106. package/types/apps/src/implementation/input-problems.d.ts +6 -2
  107. package/types/apps/src/implementation/invocation-timing.d.ts +18 -0
  108. package/types/apps/src/implementation/live.d.ts +2 -2
  109. package/types/apps/src/implementation/mcp-call.d.ts +6 -5
  110. package/types/apps/src/implementation/mcp-catalog.d.ts +6 -4
  111. package/types/apps/src/implementation/mcp-client.d.ts +17 -9
  112. package/types/apps/src/implementation/mcp-tools.d.ts +2 -1
  113. package/types/apps/src/implementation/mcp.d.ts +20 -9
  114. package/types/apps/src/implementation/network.d.ts +16 -0
  115. package/types/apps/src/implementation/openapi-compile.d.ts +28 -7
  116. package/types/apps/src/implementation/openapi-document.d.ts +46 -19
  117. package/types/apps/src/implementation/openapi-names.d.ts +9 -4
  118. package/types/apps/src/implementation/openapi-request.d.ts +10 -2
  119. package/types/apps/src/implementation/openapi-source.d.ts +23 -1
  120. package/types/apps/src/implementation/openapi-upgrade.d.ts +4 -0
  121. package/types/apps/src/implementation/operations.d.ts +57 -7
  122. package/types/apps/src/implementation/optimistic.d.ts +1 -1
  123. package/types/apps/src/implementation/placement.d.ts +60 -0
  124. package/types/apps/src/implementation/protocol-operations.d.ts +3 -0
  125. package/types/apps/src/implementation/provider-error.d.ts +28 -1
  126. package/types/apps/src/implementation/provider.d.ts +19 -4
  127. package/types/apps/src/implementation/query-commit.d.ts +1 -1
  128. package/types/apps/src/implementation/router-catalog.d.ts +20 -18
  129. package/types/apps/src/implementation/router.d.ts +24 -5
  130. package/types/apps/src/implementation/runtime-yield.d.ts +7 -0
  131. package/types/apps/src/implementation/schedules.d.ts +39 -8
  132. package/types/apps/src/implementation/schema.d.ts +98 -11
  133. package/types/apps/src/implementation/skills.d.ts +18 -24
  134. package/types/apps/src/implementation/sql.d.ts +71 -0
  135. package/types/apps/src/implementation/ui-account-notice.d.ts +9 -0
  136. package/types/apps/src/implementation/ui-auth.d.ts +1 -1
  137. package/types/apps/src/implementation/ui-client.d.ts +2 -2
  138. package/types/apps/src/implementation/ui-document.d.ts +5 -0
  139. package/types/apps/src/implementation/ui-errors.d.ts +1 -1
  140. package/types/apps/src/implementation/ui-serving.d.ts +26 -9
  141. package/types/apps/src/implementation/ui-watch.d.ts +1 -1
  142. package/types/apps/src/implementation/upstream-error.d.ts +7 -0
  143. package/types/apps/src/implementation/webhooks.d.ts +15 -6
  144. package/types/apps/src/implementation/workflow-context.d.ts +6 -2
  145. package/types/apps/src/implementation/workflows.d.ts +11 -4
  146. package/types/apps/src/index.d.ts +68 -19
  147. package/types/apps/src/mcp.d.ts +20 -1
  148. package/types/apps/src/openapi.d.ts +6 -1
  149. package/types/apps/src/react.d.ts +1 -1
  150. package/types/apps/src/skills.d.ts +10 -8
  151. package/types/apps/src/ui-serving.d.ts +1 -1
  152. package/types/telemetry/src/app-records.d.ts +42 -0
  153. package/types/telemetry/src/browser-operations.d.ts +2 -2
  154. package/types/telemetry/src/browser.d.ts +8 -3
  155. package/types/telemetry/src/config.d.ts +2 -2
  156. package/types/telemetry/src/index.d.ts +2 -1
  157. package/types/telemetry/src/layer.d.ts +10 -4
  158. package/types/telemetry/src/measurements.d.ts +1 -1
  159. package/types/telemetry/src/ownership.d.ts +60 -0
  160. package/types/telemetry/src/recorded-failure.d.ts +29 -0
  161. package/types/telemetry/src/relay.d.ts +16 -6
  162. package/types/telemetry/src/span-attributes.d.ts +17 -1
  163. package/types/telemetry/src/transport.d.ts +8 -1
  164. package/types/utils/src/api-error.d.ts +55 -0
  165. package/types/utils/src/connection-failure.d.ts +33 -0
  166. package/types/utils/src/recorded-message.d.ts +18 -0
  167. package/types/utils/src/user-facing-error.d.ts +83 -0
  168. package/js/chunk-7EK2JDX4.js +0 -299
  169. package/js/chunk-IKS2C5MQ.js +0 -224
  170. package/js/chunk-MKWZPDR6.js +0 -63
  171. package/js/chunk-N7YDVXYJ.js +0 -186
  172. package/js/chunk-NKLWZJLE.js +0 -172
  173. package/js/chunk-PJJ24GU7.js +0 -877
  174. package/js/chunk-PZB6T6KU.js +0 -19
  175. package/js/chunk-R3EV5FTO.js +0 -97
  176. package/js/chunk-SJFZCGXG.js +0 -1243
  177. package/js/chunk-WLE7WX2U.js +0 -2645
  178. package/js/chunk-YXQHV65J.js +0 -242
  179. package/js/chunk-ZQINWV4W.js +0 -630
  180. package/js/mcp/stdio.js +0 -128
  181. package/types/app-data/src/implementation/cursor.d.ts +0 -10
  182. package/types/app-data/src/implementation/index-key.d.ts +0 -7
  183. package/types/app-data/src/implementation/promise.d.ts +0 -68
  184. package/types/app-data/src/implementation/range.d.ts +0 -8
  185. package/types/app-data/src/implementation/schema.d.ts +0 -18
  186. package/types/app-data/src/implementation/sqlite.d.ts +0 -11
  187. package/types/app-data/src/index.d.ts +0 -4
  188. package/types/apps/src/contracts/storage.d.ts +0 -68
  189. package/types/apps/src/implementation/mcp-stdio.d.ts +0 -4
  190. package/types/apps/src/implementation/storage.d.ts +0 -15
  191. package/types/apps/src/mcp-stdio.d.ts +0 -5
@@ -1,1243 +0,0 @@
1
- import {
2
- makeCache
3
- } from "./chunk-NKLWZJLE.js";
4
- import {
5
- accountSecrets,
6
- boundFailureMessage,
7
- describeFailure,
8
- failureDetail,
9
- readCatalog,
10
- routerSkills
11
- } from "./chunk-FL2QR3XW.js";
12
- import {
13
- folderSkillsEffect
14
- } from "./chunk-IPI4MFSN.js";
15
- import {
16
- ResponseStatusError,
17
- authorDatabase,
18
- isApp,
19
- toEffectApp,
20
- unavailableStorage
21
- } from "./chunk-YXQHV65J.js";
22
- import {
23
- parseDatabaseSchema
24
- } from "./chunk-ZQINWV4W.js";
25
- import {
26
- declaredOperations,
27
- fromPromise,
28
- locate,
29
- nativeOperation,
30
- toPromise
31
- } from "./chunk-Z5M2LQOZ.js";
32
- import {
33
- accountProviderError,
34
- httpProviderError,
35
- parseProviderError
36
- } from "./chunk-MKWZPDR6.js";
37
- import {
38
- AccountCheckResult,
39
- DeclaredProvider,
40
- DeclaredRequirements,
41
- ElicitationFailed,
42
- ElicitationResponse,
43
- FormElicitation,
44
- HostAccountsInvalid,
45
- HostDeclarationInvalid,
46
- HostError,
47
- HostEvaluationFailed,
48
- HostInputInvalid,
49
- HostKindMismatch,
50
- HostOperationFailed,
51
- HostOperationNotFound,
52
- HostOutputInvalid,
53
- HostRequest,
54
- HostRequestInvalid,
55
- HostToolApprovalRequired,
56
- HostToolBlocked,
57
- HostToolNotFound,
58
- HostToolPolicyFailed,
59
- HostedRouter,
60
- HostedTool,
61
- HostedToolSummary,
62
- HostedWebhook,
63
- HostedWorkflow,
64
- InvocationDeadline,
65
- ManualWebhookSetup,
66
- ManyAccounts,
67
- McpError,
68
- NonRetryableError,
69
- OpenapiResponseError,
70
- ResolvedAccounts,
71
- ToolResultObservation,
72
- TrustedToolApproval,
73
- WebhookResponseData,
74
- WorkflowDuration,
75
- WorkflowFailure,
76
- WorkflowName,
77
- WorkflowReplay,
78
- WorkflowStepOptions,
79
- WorkflowValue,
80
- approvalElicitation,
81
- defaultWebhookTransportLimits,
82
- maxInputProblems,
83
- workflowDurationMillis
84
- } from "./chunk-WLE7WX2U.js";
85
- import {
86
- CacheError
87
- } from "./chunk-R3EV5FTO.js";
88
- import {
89
- AppSkills,
90
- SkillFile,
91
- SkillLoadFailed
92
- } from "./chunk-JU7VHODU.js";
93
- import {
94
- captureTelemetry,
95
- invocationFetch
96
- } from "./chunk-ODEIDRGW.js";
97
- import {
98
- decoderOf,
99
- importedJsonSchema,
100
- jsonSchemaDecoder,
101
- jsonSchemaDocument
102
- } from "./chunk-5T57N25Q.js";
103
- import {
104
- JsonObject,
105
- JsonValue
106
- } from "./chunk-27F7W2LG.js";
107
- import {
108
- Cause_exports,
109
- Clock_exports,
110
- Effect_exports,
111
- Encoding_exports,
112
- Match_exports,
113
- Option_exports,
114
- Redacted_exports,
115
- SchemaIssue_exports,
116
- Schema_exports,
117
- Stream_exports
118
- } from "./chunk-CDL5PM2Q.js";
119
-
120
- // src/implementation/elicitation.ts
121
- var prepareElicitation = (input) => Effect_exports.gen(function* () {
122
- const request = yield* Schema_exports.decodeUnknownEffect(FormElicitation)(input, {
123
- onExcessProperty: "error"
124
- }).pipe(Effect_exports.mapError(() => new ElicitationFailed({ reason: "invalid-request" })));
125
- const content = yield* jsonSchemaDecoder(request.requestedSchema).pipe(
126
- Effect_exports.mapError(() => new ElicitationFailed({ reason: "invalid-request" }))
127
- );
128
- const respond = (input2) => Effect_exports.gen(function* () {
129
- const response = yield* Schema_exports.decodeUnknownEffect(ElicitationResponse)(input2).pipe(
130
- Effect_exports.catchTag(
131
- "SchemaError",
132
- () => Effect_exports.fail(new ElicitationFailed({ reason: "invalid-response" }))
133
- )
134
- );
135
- if (response.action === "accept") {
136
- const fields = response.content === void 0 ? {} : response.content;
137
- yield* Schema_exports.decodeUnknownEffect(content)(fields).pipe(
138
- Effect_exports.mapError(() => new ElicitationFailed({ reason: "invalid-response" }))
139
- );
140
- return { ...response, content: fields };
141
- }
142
- return response;
143
- });
144
- return { request, respond };
145
- });
146
- var makeElicit = (handler, signal) => toPromise(
147
- (input) => Effect_exports.gen(function* () {
148
- if (handler === void 0) return yield* new ElicitationFailed({ reason: "unavailable" });
149
- const form = yield* prepareElicitation(input);
150
- return yield* handler(form.request, signal).pipe(Effect_exports.flatMap(form.respond));
151
- }),
152
- signal
153
- );
154
-
155
- // src/contracts/approval.ts
156
- var ApprovalDecision = Schema_exports.Literals(["approved", "denied", "user-approval"]);
157
-
158
- // src/implementation/workflow-context.ts
159
- var workflowSafe = (work, secrets) => work.pipe(
160
- Effect_exports.catchCause((cause) => {
161
- if (Cause_exports.hasInterrupts(cause)) return Effect_exports.interrupt;
162
- const error = Cause_exports.squash(cause);
163
- if (Schema_exports.is(WorkflowFailure)(error)) return Effect_exports.fail(error);
164
- const { errorName, message } = failureDetail(error, secrets);
165
- return Effect_exports.fail(
166
- new WorkflowFailure({
167
- reason: "execution",
168
- retryable: !(error instanceof NonRetryableError),
169
- ...errorName === void 0 ? {} : { errorName },
170
- ...message === void 0 ? {} : { message }
171
- })
172
- );
173
- })
174
- );
175
- var inStep = (step) => (failure) => failure.step === void 0 ? new WorkflowFailure({
176
- reason: failure.reason,
177
- retryable: failure.retryable,
178
- step: step.slice(0, 200),
179
- ...failure.errorName === void 0 ? {} : { errorName: failure.errorName },
180
- ...failure.message.length === 0 ? {} : { message: failure.message }
181
- }) : failure;
182
- var makeWorkflowContext = (execution, definition, fresh, signal) => Effect_exports.gen(function* () {
183
- const services = yield* Effect_exports.context();
184
- const counts = /* @__PURE__ */ new Map();
185
- const identify = (kind, name) => Effect_exports.gen(function* () {
186
- yield* Schema_exports.decodeUnknownEffect(WorkflowName)(name).pipe(
187
- Effect_exports.mapError(() => new WorkflowFailure({ reason: "input", retryable: false }))
188
- );
189
- const key = JSON.stringify([kind, name]);
190
- const count = (counts.get(key) ?? 0) + 1;
191
- counts.set(key, count);
192
- const digest = yield* Effect_exports.tryPromise({
193
- try: () => crypto.subtle.digest(
194
- "SHA-256",
195
- new TextEncoder().encode(JSON.stringify([execution.runId, kind, name, count]))
196
- ),
197
- catch: () => new WorkflowFailure({ reason: "execution", retryable: false })
198
- });
199
- return Array.from(
200
- new Uint8Array(digest),
201
- (byte) => byte.toString(16).padStart(2, "0")
202
- ).join("");
203
- });
204
- const attempt = (options, work) => {
205
- const timeout = workflowDurationMillis(options.timeout ?? "10 minutes");
206
- if (timeout === void 0)
207
- return Effect_exports.fail(new WorkflowFailure({ reason: "input", retryable: false }));
208
- return work.pipe(
209
- Effect_exports.timeout(timeout),
210
- Effect_exports.catchTag(
211
- "TimeoutError",
212
- () => (
213
- // Both the capability deadline and the native engine deadline describe
214
- // the same cancellation, regardless of which timer fires first.
215
- Effect_exports.fail(new WorkflowFailure({ reason: "engine", retryable: true }))
216
- )
217
- )
218
- );
219
- };
220
- const runStep = (name, options, callback) => Effect_exports.gen(function* () {
221
- const stepId = yield* identify("do", name);
222
- const parsed = yield* Schema_exports.decodeUnknownEffect(WorkflowStepOptions)(options).pipe(
223
- Effect_exports.mapError(() => new WorkflowFailure({ reason: "input", retryable: false }))
224
- );
225
- return yield* execution.driver.do(
226
- `do:${name.slice(0, 100)}:${stepId}`,
227
- parsed,
228
- () => attempt(
229
- parsed,
230
- Effect_exports.scoped(
231
- Effect_exports.gen(function* () {
232
- const controller = yield* Effect_exports.acquireRelease(
233
- Effect_exports.sync(() => new AbortController()),
234
- (controller2) => Effect_exports.sync(() => controller2.abort())
235
- );
236
- const step2 = yield* fresh(stepId, AbortSignal.any([signal, controller.signal]));
237
- const result = yield* workflowSafe(
238
- Effect_exports.tryPromise({
239
- try: () => callback(step2.context),
240
- catch: (error) => error
241
- }),
242
- step2.secrets
243
- );
244
- return yield* Schema_exports.decodeUnknownEffect(WorkflowValue)(result).pipe(
245
- Effect_exports.mapError(
246
- () => new WorkflowFailure({
247
- reason: "output",
248
- retryable: false,
249
- message: "The step returned a value that is not JSON, such as undefined, or is larger than 1 MiB. Return null for no result."
250
- })
251
- )
252
- );
253
- })
254
- ).pipe(Effect_exports.provideContext(services))
255
- )
256
- ).pipe(Effect_exports.mapError(inStep(name)));
257
- });
258
- const operationStep = (kind, name, operation, input, options) => Effect_exports.gen(function* () {
259
- const target = nativeOperation(operation);
260
- const root = definition.tools?.kind === "router" ? definition.tools : void 0;
261
- const match = declaredOperations(root).find(
262
- (entry) => entry.operation === target && entry.operation.kind === kind
263
- );
264
- if (target === void 0 || match === void 0)
265
- return yield* new WorkflowFailure({ reason: "operation", retryable: false });
266
- const args = yield* Schema_exports.decodeUnknownEffect(JsonValue)(input).pipe(
267
- Effect_exports.mapError(() => new WorkflowFailure({ reason: "input", retryable: false }))
268
- );
269
- const parsed = yield* Schema_exports.decodeUnknownEffect(WorkflowStepOptions)(options).pipe(
270
- Effect_exports.mapError(() => new WorkflowFailure({ reason: "input", retryable: false }))
271
- );
272
- const stepId = yield* identify(kind, name);
273
- const timeout = workflowDurationMillis(parsed.timeout ?? "10 minutes");
274
- if (timeout === void 0)
275
- return yield* new WorkflowFailure({ reason: "input", retryable: false });
276
- return yield* execution.driver.do(
277
- `${kind}:${name.slice(0, 100)}:${stepId}`,
278
- parsed,
279
- () => attempt(
280
- parsed,
281
- execution.invoke({ kind, name: match.name, input: args, stepId, timeout }).pipe(Effect_exports.provideContext(services))
282
- )
283
- ).pipe(Effect_exports.mapError(inStep(name)));
284
- });
285
- const invoke = (effect) => toPromise(() => effect.pipe(Effect_exports.provideContext(services)), signal)();
286
- const step = {
287
- do: (name, options, run) => {
288
- const callback = typeof options === "function" ? options : run;
289
- if (callback === void 0)
290
- return Promise.reject(new WorkflowFailure({ reason: "input", retryable: false }));
291
- return invoke(runStep(name, typeof options === "function" ? {} : options, callback));
292
- },
293
- runQuery: (name, operation, input, options = {}) => invoke(operationStep("query", name, operation, input, options)),
294
- runMutation: (name, operation, input, options = {}) => invoke(operationStep("mutation", name, operation, input, options)),
295
- sleep: (name, duration) => invoke(
296
- Schema_exports.decodeUnknownEffect(WorkflowDuration)(duration).pipe(
297
- Effect_exports.mapError(() => new WorkflowFailure({ reason: "input", retryable: false })),
298
- Effect_exports.flatMap(
299
- (parsed) => identify("sleep", name).pipe(
300
- Effect_exports.flatMap(
301
- (id) => execution.driver.sleep(`sleep:${name.slice(0, 100)}:${id}`, parsed)
302
- )
303
- )
304
- )
305
- )
306
- ),
307
- sleepUntil: (name, timestamp) => invoke(
308
- identify("until", name).pipe(
309
- Effect_exports.flatMap(
310
- (id) => execution.driver.sleepUntil(
311
- `until:${name.slice(0, 100)}:${id}`,
312
- timestamp instanceof Date ? timestamp.getTime() : timestamp
313
- )
314
- )
315
- )
316
- )
317
- };
318
- return { runId: execution.runId, step };
319
- });
320
-
321
- // src/implementation/input-problems.ts
322
- var leafHook = (issue) => SchemaIssue_exports.hasInput(issue) ? "Invalid value" : SchemaIssue_exports.defaultLeafHook(issue);
323
- var checkHook = (issue) => SchemaIssue_exports.hasInput(issue) || SchemaIssue_exports.hasInput(issue.issue) ? SchemaIssue_exports.defaultCheckHook(issue) ?? "Invalid value" : SchemaIssue_exports.defaultCheckHook(issue);
324
- var format = SchemaIssue_exports.makeFormatterStandardSchemaV1({ leafHook, checkHook });
325
- var segment = (key) => typeof key === "number" ? `[${key}]` : typeof key === "string" && /^[A-Za-z_$][\w$-]{0,63}$/.test(key) ? `.${key}` : "[key]";
326
- var inputInvalid = (error) => {
327
- if (!Schema_exports.isSchemaError(error)) return new HostInputInvalid();
328
- const problems = format(error.issue).issues.slice(0, maxInputProblems).map(({ path, message }) => {
329
- const location = (path ?? []).map((key) => segment(typeof key === "object" ? key.key : key));
330
- return `${location.length === 0 ? "input" : `input${location.join("")}`}: ${message}`.slice(
331
- 0,
332
- 512
333
- );
334
- });
335
- return new HostInputInvalid({ problems });
336
- };
337
-
338
- // src/implementation/webhooks.ts
339
- var safe = (work, error) => Effect_exports.suspend(work).pipe(
340
- Effect_exports.catchCause(
341
- (cause) => Cause_exports.hasInterrupts(cause) ? Effect_exports.interrupt : Effect_exports.fail(error)
342
- )
343
- );
344
- var dispatchWebhook = (definition, command, context, accounts) => Effect_exports.gen(function* () {
345
- const hooks = definition.webhooks ?? {};
346
- if (command.operation === "webhooks") {
347
- return yield* Effect_exports.forEach(
348
- Object.entries(hooks),
349
- ([name, hook2]) => safe(
350
- () => Effect_exports.gen(function* () {
351
- if (!Object.hasOwn(accounts, hook2.account))
352
- return yield* new HostDeclarationInvalid();
353
- const describe = (schema) => {
354
- const imported = importedJsonSchema(schema);
355
- if (imported !== void 0) return Schema_exports.decodeUnknownEffect(JsonObject)(imported);
356
- const document = Schema_exports.toJsonSchemaDocument(schema);
357
- return Schema_exports.decodeUnknownEffect(JsonObject)({
358
- ...document.schema,
359
- $defs: document.definitions
360
- });
361
- };
362
- const configSchema = yield* describe(hook2.config);
363
- if (hook2.setup === void 0 ? hook2.register === void 0 || hook2.unregister === void 0 : hook2.register !== void 0 || hook2.unregister !== void 0)
364
- return yield* new HostDeclarationInvalid();
365
- const setup = hook2.setup === void 0 ? void 0 : {
366
- ...yield* Schema_exports.decodeUnknownEffect(ManualWebhookSetup)(hook2.setup),
367
- stateSchema: yield* describe(hook2.state)
368
- };
369
- return yield* Schema_exports.decodeUnknownEffect(HostedWebhook)({
370
- name,
371
- account: hook2.account,
372
- configSchema,
373
- ...setup === void 0 ? {} : { setup }
374
- });
375
- }),
376
- new HostDeclarationInvalid()
377
- )
378
- );
379
- }
380
- const hook = Object.hasOwn(hooks, command.name) ? hooks[command.name] : void 0;
381
- if (hook === void 0) return yield* new HostOperationNotFound();
382
- const selected = accounts[hook.account];
383
- const source = Array.isArray(selected) ? selected.find((account2) => account2.id === command.sourceAccount) : selected;
384
- if (source === void 0 || source.id !== command.sourceAccount)
385
- return yield* new HostInputInvalid();
386
- const bound = context.accounts[hook.account];
387
- const account = Array.isArray(bound) ? bound.find(
388
- (value) => typeof value === "object" && value !== null && "id" in value && value.id === source.id
389
- ) : bound;
390
- const config = yield* safe(
391
- () => Schema_exports.decodeUnknownEffect(hook.config)(command.config),
392
- new HostInputInvalid()
393
- );
394
- if (command.operation === "webhook-validate")
395
- return yield* safe(
396
- () => Schema_exports.decodeUnknownEffect(JsonValue)(config),
397
- new HostInputInvalid()
398
- );
399
- const input = {
400
- config,
401
- subscriptionId: command.subscriptionId,
402
- account,
403
- callbackUrl: command.callbackUrl,
404
- secret: command.secret
405
- };
406
- const invoke = (callback, value) => safe(() => callback(context, value), new HostOperationFailed());
407
- if (command.operation === "webhook-complete") {
408
- if (hook.setup === void 0) return yield* new HostInputInvalid();
409
- return yield* safe(
410
- () => Schema_exports.decodeUnknownEffect(hook.state)(command.state).pipe(
411
- Effect_exports.flatMap(Schema_exports.decodeUnknownEffect(JsonValue))
412
- ),
413
- new HostInputInvalid()
414
- );
415
- }
416
- if (command.operation === "webhook-register") {
417
- if (hook.register === void 0 || hook.setup !== void 0)
418
- return yield* new HostOperationFailed();
419
- const state2 = yield* invoke(hook.register, input);
420
- return yield* safe(
421
- () => Schema_exports.decodeUnknownEffect(hook.state)(state2).pipe(
422
- Effect_exports.flatMap(Schema_exports.decodeUnknownEffect(JsonValue))
423
- ),
424
- new HostOutputInvalid()
425
- );
426
- }
427
- const state = command.state === null ? null : yield* safe(
428
- () => Schema_exports.decodeUnknownEffect(hook.state)(command.state),
429
- new HostInputInvalid()
430
- );
431
- if (command.operation === "webhook-unregister") {
432
- if (hook.unregister === void 0 || hook.setup !== void 0)
433
- return yield* new HostOperationFailed();
434
- yield* invoke(hook.unregister, { ...input, state });
435
- return null;
436
- }
437
- const body = yield* Effect_exports.fromResult(Encoding_exports.decodeBase64(command.request.body)).pipe(
438
- Effect_exports.mapError(() => new HostInputInvalid())
439
- );
440
- if (body.byteLength > defaultWebhookTransportLimits.maxBodyBytes)
441
- return yield* new HostInputInvalid();
442
- const request = yield* safe(
443
- () => Effect_exports.sync(
444
- () => new Request(command.request.url, {
445
- method: command.request.method,
446
- headers: command.request.headers,
447
- ...context.signal === void 0 ? {} : { signal: context.signal },
448
- ...command.request.method === "GET" || command.request.method === "HEAD" ? {} : { body: Uint8Array.from(body) }
449
- })
450
- ),
451
- new HostInputInvalid()
452
- );
453
- const response = yield* invoke(hook.handle, { ...input, state, request });
454
- if (!(response instanceof Response)) return yield* new HostOutputInvalid();
455
- const chunks = [];
456
- let size = 0;
457
- const stream = response.body;
458
- if (stream !== null)
459
- yield* Stream_exports.fromReadableStream({
460
- evaluate: () => stream,
461
- onError: () => new HostOutputInvalid()
462
- }).pipe(
463
- Stream_exports.runForEach(
464
- (chunk) => Effect_exports.gen(function* () {
465
- size += chunk.byteLength;
466
- if (size > defaultWebhookTransportLimits.maxBodyBytes)
467
- return yield* new HostOutputInvalid();
468
- chunks.push(chunk);
469
- })
470
- )
471
- );
472
- const bytes = new Uint8Array(size);
473
- let offset = 0;
474
- for (const chunk of chunks) {
475
- bytes.set(chunk, offset);
476
- offset += chunk.byteLength;
477
- }
478
- const headers = {};
479
- response.headers.forEach((value, name) => {
480
- headers[name] = value;
481
- });
482
- return yield* safe(
483
- () => Schema_exports.decodeUnknownEffect(WebhookResponseData)({
484
- status: response.status,
485
- headers,
486
- body: Encoding_exports.encodeBase64(new Uint8Array(bytes))
487
- }),
488
- new HostOutputInvalid()
489
- );
490
- });
491
-
492
- // src/implementation/cache.ts
493
- var unavailableCache = {
494
- transport: () => Effect_exports.fail(new CacheError({ reason: "unavailable" })),
495
- background: () => Effect_exports.die(new Error("Cache background runner is unavailable"))
496
- };
497
- var authorCache = (host, accounts, signal, deadline) => {
498
- const scoped = (scope, callerSignal = signal) => {
499
- const cache = makeCache(host.transport, host.background, scope, deadline);
500
- const load = (method, options) => cache[method]({
501
- key: options.key,
502
- schema: decoderOf(options.schema),
503
- freshFor: options.freshFor,
504
- ...options.staleFor === void 0 ? {} : { staleFor: options.staleFor },
505
- load: Effect_exports.acquireUseRelease(
506
- Effect_exports.sync(() => new AbortController()),
507
- (controller) => invocationFetch(controller.signal).pipe(
508
- Effect_exports.flatMap(
509
- (fetch) => fromPromise(options.load)({
510
- fetch,
511
- signal: controller.signal,
512
- cache: scoped(scope, controller.signal)
513
- })
514
- )
515
- ),
516
- (controller) => Effect_exports.sync(() => controller.abort())
517
- )
518
- });
519
- return {
520
- get: toPromise((options) => load("get", options), callerSignal),
521
- revalidate: toPromise(
522
- (options) => load("revalidate", options),
523
- callerSignal
524
- ),
525
- read: toPromise(
526
- (key, schema) => cache.read([key]).pipe(
527
- Effect_exports.flatMap((entries) => {
528
- const entry = entries[0];
529
- return entry === void 0 || entry === null ? Effect_exports.succeed(void 0) : Schema_exports.decodeUnknownEffect(decoderOf(schema))(entry.value);
530
- })
531
- ),
532
- callerSignal
533
- ),
534
- readMany: toPromise(
535
- (keys, schema) => cache.read(keys).pipe(
536
- Effect_exports.flatMap(
537
- (entries) => Effect_exports.forEach(
538
- entries,
539
- (entry) => entry === null ? Effect_exports.succeed(void 0) : Schema_exports.decodeUnknownEffect(decoderOf(schema))(entry.value)
540
- )
541
- )
542
- ),
543
- callerSignal
544
- ),
545
- write: toPromise(cache.write, callerSignal),
546
- invalidate: toPromise(cache.invalidate, callerSignal),
547
- forAccount: (account) => {
548
- const bound = Object.values(accounts).flatMap((value) => Array.isArray(value) ? value : [value]).find((value) => value.id === account.id);
549
- if (bound === void 0) throw new CacheError({ reason: "invalid" });
550
- return scoped(
551
- { account: bound.id, method: bound.method, generation: bound.generation },
552
- callerSignal
553
- );
554
- }
555
- };
556
- };
557
- return scoped("shared");
558
- };
559
-
560
- // src/implementation/host.ts
561
- var WireCatalog = Schema_exports.Struct({
562
- tools: Schema_exports.Array(Schema_exports.Union([HostedTool, HostedToolSummary])),
563
- routers: Schema_exports.Array(HostedRouter)
564
- });
565
- function safe2(work, failure) {
566
- return Effect_exports.suspend(work).pipe(
567
- Effect_exports.catchCause(
568
- (cause) => Cause_exports.hasInterrupts(cause) ? Effect_exports.interrupt : Effect_exports.fail(failure)
569
- )
570
- );
571
- }
572
- var evaluationSafe = (work, secrets) => work.pipe(
573
- Effect_exports.catchCause((cause) => {
574
- if (Cause_exports.hasInterrupts(cause)) return Effect_exports.interrupt;
575
- const error = Cause_exports.squash(cause);
576
- const provider = parseProviderError(error);
577
- const skills = parseSkillLoadFailed(error);
578
- const mcp = parseMcpError(error);
579
- return Effect_exports.fail(
580
- Option_exports.isSome(provider) ? provider.value : Option_exports.isSome(skills) ? skills.value : Option_exports.isSome(mcp) ? mcp.value : new HostEvaluationFailed(failureDetail(error, secrets))
581
- );
582
- })
583
- );
584
- var declarationInvalid = (summary, cause, secrets = []) => new HostDeclarationInvalid({
585
- source: "app",
586
- errorName: "HostDeclarationInvalid",
587
- message: boundFailureMessage(
588
- cause === void 0 ? summary : `${summary}: ${describeFailure(cause)}`,
589
- secrets
590
- )
591
- });
592
- var declarationSafe = (work, summary) => Effect_exports.suspend(work).pipe(
593
- Effect_exports.catchCause(
594
- (cause) => Cause_exports.hasInterrupts(cause) ? Effect_exports.interrupt : Effect_exports.fail(declarationInvalid(summary, Cause_exports.squash(cause)))
595
- )
596
- );
597
- function providerDeclaration(provider) {
598
- return declarationSafe(
599
- () => Effect_exports.gen(function* () {
600
- const auth = /* @__PURE__ */ new Map();
601
- for (const [name, method] of Object.entries(provider.auth)) {
602
- switch (method._tag) {
603
- case "secrets":
604
- auth.set(name, {
605
- type: "secrets",
606
- label: method.label,
607
- fields: yield* jsonSchemaDocument(method.fields)
608
- });
609
- break;
610
- case "oauth2":
611
- auth.set(name, {
612
- type: "oauth2",
613
- ...method.config,
614
- response: yield* jsonSchemaDocument(method.response)
615
- });
616
- break;
617
- }
618
- }
619
- return yield* Schema_exports.decodeUnknownEffect(DeclaredProvider)({
620
- name: provider.name,
621
- auth: Object.fromEntries(auth)
622
- });
623
- }),
624
- `Account provider "${provider.name}" has an invalid declaration`
625
- );
626
- }
627
- function requirements(slots, database) {
628
- return Effect_exports.gen(function* () {
629
- const accounts = /* @__PURE__ */ new Map();
630
- for (const [slot, selection] of Object.entries(slots)) {
631
- const provider = selection instanceof ManyAccounts ? selection.provider : selection;
632
- accounts.set(slot, {
633
- cardinality: selection instanceof ManyAccounts ? "many" : "one",
634
- definition: yield* providerDeclaration(provider),
635
- ...provider.health === void 0 ? {} : { health: true }
636
- });
637
- }
638
- return yield* Schema_exports.decodeUnknownEffect(DeclaredRequirements)({
639
- accounts: Object.fromEntries(accounts),
640
- capabilities: { skills: true, toolIndex: true, skillSources: true, scheduledTools: true },
641
- ...database === void 0 ? {} : { database }
642
- }).pipe(
643
- Effect_exports.mapError(
644
- (cause) => declarationInvalid("The app's account or database declarations are invalid", cause)
645
- )
646
- );
647
- });
648
- }
649
- function canonical(value) {
650
- if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
651
- if (value !== null && typeof value === "object") {
652
- return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(",")}}`;
653
- }
654
- return JSON.stringify(value);
655
- }
656
- function bindAccounts(slots, declarations, context) {
657
- return safe2(
658
- () => Effect_exports.gen(function* () {
659
- const selected = yield* Schema_exports.decodeUnknownEffect(ResolvedAccounts)(
660
- Redacted_exports.value(context.accounts)
661
- );
662
- if (Object.keys(selected).some((slot) => !Object.hasOwn(slots, slot))) {
663
- return yield* Effect_exports.fail(new HostAccountsInvalid());
664
- }
665
- const bound = /* @__PURE__ */ new Map();
666
- for (const [slot, selection] of Object.entries(slots)) {
667
- const requirement = declarations.accounts[slot];
668
- const supplied = Object.hasOwn(selected, slot) ? selected[slot] : void 0;
669
- if (requirement === void 0 || supplied === void 0)
670
- return yield* Effect_exports.fail(new HostAccountsInvalid());
671
- const provider = selection instanceof ManyAccounts ? selection.provider : selection;
672
- const many = selection instanceof ManyAccounts;
673
- if (many !== Array.isArray(supplied))
674
- return yield* Effect_exports.fail(new HostAccountsInvalid());
675
- const accounts = Array.isArray(supplied) ? supplied : [supplied];
676
- const ids = /* @__PURE__ */ new Set();
677
- const values = [];
678
- for (const account of accounts) {
679
- if (ids.has(account.id)) return yield* Effect_exports.fail(new HostAccountsInvalid());
680
- ids.add(account.id);
681
- if (canonical(account.provider) !== canonical(requirement.definition) || !Object.hasOwn(provider.auth, account.method))
682
- return yield* Effect_exports.fail(new HostAccountsInvalid());
683
- const method = provider.auth[account.method];
684
- if (method === void 0) return yield* Effect_exports.fail(new HostAccountsInvalid());
685
- const fields = yield* Schema_exports.decodeUnknownEffect(
686
- method._tag === "secrets" ? method.fields : method.response
687
- )(account.fields);
688
- values.push({ id: account.id, method: account.method, fields });
689
- }
690
- if (many) bound.set(slot, values);
691
- else {
692
- const account = values[0];
693
- if (account === void 0) return yield* Effect_exports.fail(new HostAccountsInvalid());
694
- bound.set(slot, account);
695
- }
696
- }
697
- return { accounts: Object.fromEntries(bound) };
698
- }),
699
- new HostAccountsInvalid()
700
- );
701
- }
702
- function dispatch(app, request, context, signal) {
703
- return Effect_exports.scoped(
704
- Effect_exports.gen(function* () {
705
- if (!isApp(app))
706
- return yield* Effect_exports.fail(
707
- declarationInvalid("The app module's default export is not an app created by defineApp")
708
- );
709
- const native = toEffectApp(app);
710
- const secrets = accountSecrets(context.accounts);
711
- const storageFailure = (error) => Effect_exports.fail(new HostOperationFailed(failureDetail(error, secrets)));
712
- const declared = yield* requirements(native.accounts, native.database?.schema);
713
- if (request.operation === "requirements") {
714
- if (native.database !== void 0)
715
- yield* parseDatabaseSchema(native.database.schema).pipe(
716
- Effect_exports.catchTag(
717
- "AppDatabaseError",
718
- (cause) => Effect_exports.fail(
719
- declarationInvalid("The app's account or database declarations are invalid", cause)
720
- )
721
- )
722
- );
723
- return yield* safe2(
724
- () => Schema_exports.decodeUnknownEffect(JsonValue)(declared),
725
- new HostDeclarationInvalid()
726
- );
727
- }
728
- const lifetime = yield* Effect_exports.acquireRelease(
729
- Effect_exports.sync(() => new AbortController()),
730
- (controller) => Effect_exports.sync(() => controller.abort())
731
- );
732
- const invocationSignal = AbortSignal.any([signal, lifetime.signal]);
733
- const deadline = context.deadline === void 0 ? void 0 : yield* safe2(
734
- () => Schema_exports.decodeUnknownEffect(InvocationDeadline)(context.deadline),
735
- new HostInputInvalid()
736
- );
737
- const withinDeadline = (work) => Effect_exports.gen(function* () {
738
- if (deadline === void 0) return yield* work;
739
- const remaining = deadline - (yield* Clock_exports.currentTimeMillis);
740
- if (remaining <= 0)
741
- return yield* new WorkflowFailure({ reason: "engine", retryable: true });
742
- const result = yield* work.pipe(
743
- Effect_exports.timeout(remaining),
744
- Effect_exports.catchTag(
745
- "TimeoutError",
746
- () => Effect_exports.fail(new WorkflowFailure({ reason: "engine", retryable: true }))
747
- )
748
- );
749
- if ((yield* Clock_exports.currentTimeMillis) >= deadline)
750
- return yield* new WorkflowFailure({ reason: "engine", retryable: true });
751
- return result;
752
- });
753
- if (request.operation === "account-check")
754
- return yield* checkAccount(
755
- native.accounts,
756
- declared,
757
- request.requirement,
758
- context,
759
- invocationSignal
760
- ).pipe(withinDeadline);
761
- let running;
762
- let transactionOpen = false;
763
- const delivery = (request2, signal2) => Effect_exports.suspend(
764
- () => transactionOpen ? Effect_exports.fail(new ElicitationFailed({ reason: "transaction" })) : running !== void 0 && context.elicitation !== void 0 ? context.elicitation(request2, signal2).pipe(
765
- Effect_exports.withSpan("app.tool.elicitation"),
766
- Effect_exports.provideContext(running.context)
767
- ) : Effect_exports.fail(new ElicitationFailed({ reason: "unavailable" }))
768
- );
769
- const unavailableWorkflow = () => Effect_exports.fail(new WorkflowFailure({ reason: "unavailable", retryable: false }));
770
- const workflowControls = {
771
- start: toPromise(
772
- (input2) => context.workflowControls === void 0 ? unavailableWorkflow() : context.workflowControls.start(input2),
773
- invocationSignal
774
- ),
775
- get: toPromise(
776
- (input2) => context.workflowControls === void 0 ? unavailableWorkflow() : context.workflowControls.get(input2),
777
- invocationSignal
778
- ),
779
- list: toPromise(
780
- (input2) => context.workflowControls === void 0 ? unavailableWorkflow() : context.workflowControls.list(input2),
781
- invocationSignal
782
- ),
783
- terminate: toPromise(
784
- (input2) => context.workflowControls === void 0 ? unavailableWorkflow() : context.workflowControls.terminate(input2),
785
- invocationSignal
786
- )
787
- };
788
- const workflowReads = {
789
- get: workflowControls.get,
790
- list: workflowControls.list
791
- };
792
- const files = yield* Schema_exports.decodeUnknownEffect(Schema_exports.Array(SkillFile))(
793
- context.files ?? []
794
- ).pipe(Effect_exports.mapError(() => new HostDeclarationInvalid()));
795
- let cacheCommands = 0;
796
- const hostCache = context.cache ?? unavailableCache;
797
- const bound = {
798
- cache: authorCache(
799
- {
800
- ...hostCache,
801
- transport: (command) => {
802
- cacheCommands += 1;
803
- return hostCache.transport(command);
804
- }
805
- },
806
- Redacted_exports.value(context.accounts),
807
- invocationSignal,
808
- deadline
809
- ),
810
- files,
811
- ...yield* bindAccounts(native.accounts, declared, context).pipe(
812
- Effect_exports.withSpan("app.accounts.bind")
813
- ),
814
- workflows: workflowReads,
815
- signal: invocationSignal,
816
- fetch: yield* invocationFetch(invocationSignal),
817
- elicit: makeElicit(delivery, invocationSignal)
818
- };
819
- const definition = yield* evaluationSafe(native.evaluate(bound), secrets).pipe(
820
- Effect_exports.withSpan("app.evaluate")
821
- );
822
- if (request.operation === "skills") {
823
- const declared2 = definition.skills ?? (yield* folderSkillsEffect({ files }).pipe(
824
- Effect_exports.mapError(() => new HostDeclarationInvalid())
825
- ));
826
- const source = definition.dynamicSkills;
827
- const before = cacheCommands;
828
- const dynamic = source === void 0 ? [] : yield* evaluationSafe(Effect_exports.suspend(source.list), secrets).pipe(
829
- Effect_exports.withSpan("app.skills.load")
830
- );
831
- const cached = source !== void 0 && cacheCommands > before;
832
- const authored = new Set([...declared2, ...dynamic].map((skill) => skill.name));
833
- const routed = (yield* routerSkills(definition.tools).pipe(
834
- Effect_exports.withSpan("app.skills.routers")
835
- )).filter((skill) => !authored.has(skill.name));
836
- const skills = yield* Schema_exports.decodeUnknownEffect(AppSkills)([
837
- ...declared2,
838
- ...dynamic,
839
- ...routed
840
- ]).pipe(Effect_exports.mapError(() => new HostDeclarationInvalid()));
841
- return request.sources === true ? { skills, dynamic: source !== void 0, cached } : skills;
842
- }
843
- if (request.operation === "workflows") {
844
- return yield* Effect_exports.forEach(
845
- Object.entries(definition.workflows ?? {}),
846
- ([name, entry]) => safe2(
847
- () => Effect_exports.gen(function* () {
848
- return yield* Schema_exports.decodeUnknownEffect(HostedWorkflow)({
849
- name,
850
- ...entry.description === void 0 ? {} : { description: entry.description },
851
- inputSchema: yield* jsonSchemaDocument(entry.input),
852
- ...entry.output === void 0 ? {} : { outputSchema: yield* jsonSchemaDocument(entry.output) }
853
- });
854
- }),
855
- new HostDeclarationInvalid()
856
- )
857
- );
858
- }
859
- if (request.operation === "workflow-validate" || request.operation === "workflow-run") {
860
- const entry = definition.workflows !== void 0 && Object.hasOwn(definition.workflows, request.name) ? definition.workflows[request.name] : void 0;
861
- if (entry === void 0)
862
- return yield* new WorkflowFailure({ reason: "not_found", retryable: false });
863
- const input2 = yield* safe2(
864
- () => Schema_exports.decodeUnknownEffect(entry.input)(request.input),
865
- new WorkflowFailure({ reason: "input", retryable: false })
866
- );
867
- if (request.operation === "workflow-validate")
868
- return yield* safe2(
869
- () => Schema_exports.decodeUnknownEffect(WorkflowValue)(input2),
870
- new WorkflowFailure({ reason: "input", retryable: false })
871
- );
872
- const execution = context.workflow;
873
- if (execution === void 0)
874
- return yield* new WorkflowFailure({ reason: "unavailable", retryable: false });
875
- const workflowContext = yield* makeWorkflowContext(
876
- execution,
877
- definition,
878
- (stepId, signal2) => Effect_exports.gen(function* () {
879
- const current = yield* execution.resolve();
880
- const accounts = yield* safe2(
881
- () => bindAccounts(native.accounts, declared, current),
882
- new WorkflowFailure({ reason: "credentials", retryable: false })
883
- );
884
- return {
885
- context: {
886
- ...accounts,
887
- cache: authorCache(
888
- context.cache ?? unavailableCache,
889
- Redacted_exports.value(current.accounts),
890
- signal2
891
- ),
892
- files,
893
- fetch: yield* invocationFetch(signal2),
894
- signal: signal2,
895
- runId: execution.runId,
896
- stepId,
897
- idempotencyKey: stepId
898
- },
899
- // The resolved values, not the app's decoded fields, which may be `Redacted`.
900
- secrets: accountSecrets(current.accounts)
901
- };
902
- }),
903
- invocationSignal
904
- );
905
- const output = yield* workflowSafe(entry.run(workflowContext, input2), secrets);
906
- const outputSchema = entry.output;
907
- const decoded = outputSchema === void 0 ? output : yield* safe2(
908
- () => Schema_exports.decodeUnknownEffect(outputSchema)(output),
909
- new WorkflowFailure({
910
- reason: "output",
911
- retryable: false,
912
- message: "The workflow's result does not match its declared output schema."
913
- })
914
- );
915
- return yield* safe2(
916
- () => Schema_exports.decodeUnknownEffect(WorkflowValue)(decoded),
917
- new WorkflowFailure({
918
- reason: "output",
919
- retryable: false,
920
- message: "The workflow returned a value that is not JSON, such as undefined, or is larger than 1 MiB. Return null for no result."
921
- })
922
- );
923
- }
924
- if (request.operation === "inspect") {
925
- const summary = request.detail === "summary";
926
- const catalog = yield* readCatalog(definition.tools, {
927
- summary,
928
- secrets,
929
- ...request.tools === void 0 ? {} : { wanted: new Set(request.tools) },
930
- ...request.scheduled === true ? { scheduled: true } : {},
931
- schedules: (name) => Object.entries(definition.schedules ?? {}).filter(([, schedule]) => schedule.tool === name).map(([name2, { tool: _tool, ...schedule }]) => ({ name: name2, ...schedule }))
932
- }).pipe(Effect_exports.withSpan("app.catalog.read"));
933
- return yield* safe2(
934
- () => Schema_exports.encodeEffect(WireCatalog)(catalog).pipe(
935
- Effect_exports.flatMap(Schema_exports.decodeUnknownEffect(JsonValue))
936
- ),
937
- new HostDeclarationInvalid()
938
- );
939
- }
940
- if (request.operation === "webhook-complete" || request.operation === "webhook-validate" || request.operation === "webhooks" || request.operation === "webhook-register" || request.operation === "webhook-handle" || request.operation === "webhook-unregister") {
941
- const executeWebhook = (db) => dispatchWebhook(
942
- definition,
943
- request,
944
- {
945
- files,
946
- cache: bound.cache,
947
- accounts: bound.accounts,
948
- workflows: workflowControls,
949
- signal: bound.signal,
950
- fetch: bound.fetch,
951
- ...db === void 0 || native.database === void 0 ? {} : {
952
- db: authorDatabase(native.database.tables, db, invocationSignal, true)
953
- }
954
- },
955
- Redacted_exports.value(context.accounts)
956
- );
957
- if (native.database === void 0 || !["webhook-register", "webhook-handle", "webhook-unregister"].includes(request.operation))
958
- return yield* executeWebhook();
959
- const storage2 = context.storage ?? unavailableStorage;
960
- return yield* storage2.mutate(native.database.schema, executeWebhook).pipe(
961
- Effect_exports.catchTags({
962
- AppDatabaseError: storageFailure,
963
- DatabaseLimitExceeded: (error) => Effect_exports.fail(error),
964
- AppStorageUnavailable: storageFailure,
965
- AppStorageError: storageFailure
966
- })
967
- );
968
- }
969
- const toolName = request.operation === "call" ? request.tool : request.name;
970
- const location = locate(definition.tools, toolName);
971
- const tool = location === void 0 ? void 0 : location.kind === "operation" ? location.operation : yield* evaluationSafe(location.source.resolve(location.name), secrets);
972
- if (tool === void 0)
973
- return yield* request.operation === "call" ? new HostToolNotFound() : new HostOperationNotFound();
974
- const requested = request.operation === "call" ? request.kind : request.operation === "query" ? "query" : "mutation";
975
- if (requested !== void 0 && tool.kind !== requested)
976
- return yield* new HostKindMismatch({ tool: toolName, requested, actual: tool.kind });
977
- const kind = tool.kind === "query" ? "query" : "mutate";
978
- const input = yield* Effect_exports.suspend(
979
- () => Schema_exports.decodeUnknownEffect(tool.input)(request.input)
980
- ).pipe(
981
- Effect_exports.catchCause(
982
- (cause) => Cause_exports.hasInterrupts(cause) ? Effect_exports.interrupt : Effect_exports.fail(inputInvalid(Cause_exports.squash(cause)))
983
- )
984
- );
985
- if (context.approval !== void 0) {
986
- const approved = yield* safe2(
987
- () => Schema_exports.decodeUnknownEffect(TrustedToolApproval)(context.approval),
988
- new HostInputInvalid()
989
- );
990
- const decoded = yield* safe2(
991
- () => Schema_exports.decodeUnknownEffect(JsonValue)(input),
992
- new HostInputInvalid()
993
- );
994
- if (approved.tool !== toolName || !Schema_exports.toEquivalence(JsonValue)(approved.input, decoded)) {
995
- return yield* new HostInputInvalid();
996
- }
997
- } else if (tool.approval !== void 0) {
998
- const approval = tool.approval;
999
- const decision = yield* safe2(
1000
- () => approval({ toolName, toolInput: input, signal: invocationSignal }).pipe(
1001
- Effect_exports.withSpan("app.tool.approval", {
1002
- attributes: { "executor.tool.name": toolName }
1003
- }),
1004
- Effect_exports.flatMap(Schema_exports.decodeUnknownEffect(ApprovalDecision))
1005
- ),
1006
- new HostToolPolicyFailed()
1007
- );
1008
- yield* Match_exports.value(decision).pipe(
1009
- Match_exports.when("approved", () => Effect_exports.void),
1010
- Match_exports.when("denied", () => Effect_exports.fail(new HostToolBlocked())),
1011
- Match_exports.when(
1012
- "user-approval",
1013
- () => safe2(() => Schema_exports.decodeUnknownEffect(JsonValue)(input), new HostInputInvalid()).pipe(
1014
- Effect_exports.flatMap(
1015
- (input2) => Effect_exports.fail(
1016
- new HostToolApprovalRequired({
1017
- input: input2,
1018
- elicitation: approvalElicitation(toolName, input2)
1019
- })
1020
- )
1021
- )
1022
- )
1023
- ),
1024
- Match_exports.exhaustive
1025
- );
1026
- }
1027
- const execute = (db) => Effect_exports.gen(function* () {
1028
- transactionOpen = db !== void 0;
1029
- const output = yield* Effect_exports.gen(function* () {
1030
- running = yield* captureTelemetry;
1031
- const fetch = yield* invocationFetch(invocationSignal);
1032
- return yield* tool.run(
1033
- {
1034
- ...bound,
1035
- fetch,
1036
- workflows: kind === "mutate" ? workflowControls : workflowReads,
1037
- ...db === void 0 || native.database === void 0 ? {} : {
1038
- db: authorDatabase(
1039
- native.database.tables,
1040
- db,
1041
- invocationSignal,
1042
- kind === "mutate"
1043
- )
1044
- }
1045
- },
1046
- input
1047
- );
1048
- }).pipe(
1049
- Effect_exports.ensuring(
1050
- Effect_exports.sync(() => {
1051
- running = void 0;
1052
- })
1053
- ),
1054
- Effect_exports.catchCause((cause) => {
1055
- if (Cause_exports.hasInterrupts(cause)) return Effect_exports.interrupt;
1056
- const error = Cause_exports.squash(cause);
1057
- const provider = parseProviderError(error);
1058
- const response = Schema_exports.decodeUnknownOption(OpenapiResponseError)(error);
1059
- const failure = Schema_exports.decodeUnknownOption(ElicitationFailed)(error);
1060
- return Effect_exports.fail(
1061
- Option_exports.isSome(provider) ? provider.value : Option_exports.isSome(response) ? new OpenapiResponseError({
1062
- code: response.value.code,
1063
- status: response.value.status,
1064
- message: response.value.message,
1065
- ...response.value.recovery === void 0 ? {} : { recovery: response.value.recovery }
1066
- }) : Option_exports.isSome(failure) ? failure.value : new HostOperationFailed(failureDetail(error, secrets))
1067
- );
1068
- }),
1069
- Effect_exports.withSpan("app.operation.execute", {
1070
- attributes: { "executor.tool.name": toolName, "executor.operation": kind }
1071
- })
1072
- );
1073
- const outputSchema = tool.output;
1074
- const decoded = outputSchema === void 0 ? output : yield* safe2(
1075
- () => Schema_exports.decodeUnknownEffect(outputSchema)(output),
1076
- new HostOutputInvalid()
1077
- );
1078
- return yield* safe2(
1079
- () => Schema_exports.decodeUnknownEffect(JsonValue)(decoded),
1080
- new HostOutputInvalid()
1081
- );
1082
- });
1083
- const replay = context.replay === void 0 ? void 0 : yield* safe2(
1084
- () => Schema_exports.decodeUnknownEffect(WorkflowReplay)(context.replay),
1085
- new HostInputInvalid()
1086
- );
1087
- if (replay !== void 0 && kind !== "mutate") return yield* new HostInputInvalid();
1088
- if (native.database === void 0) return yield* withinDeadline(execute());
1089
- const storage = context.storage ?? unavailableStorage;
1090
- return yield* storage[kind === "query" ? "read" : "mutate"](
1091
- native.database.schema,
1092
- (db) => withinDeadline(
1093
- replay === void 0 ? execute(db) : db.once(replay.key, replay.fingerprint, () => execute(db))
1094
- )
1095
- ).pipe(
1096
- Effect_exports.catchTags({
1097
- AppDatabaseError: storageFailure,
1098
- DatabaseLimitExceeded: (error) => Effect_exports.fail(error),
1099
- AppStorageUnavailable: storageFailure,
1100
- AppStorageError: storageFailure
1101
- })
1102
- );
1103
- })
1104
- );
1105
- }
1106
- function checkAccount(slots, declared, requirement, context, signal) {
1107
- return Effect_exports.gen(function* () {
1108
- const selection = Object.hasOwn(slots, requirement) ? slots[requirement] : void 0;
1109
- const slot = Object.hasOwn(declared.accounts, requirement) ? declared.accounts[requirement] : void 0;
1110
- if (selection === void 0 || slot === void 0) return yield* new HostAccountsInvalid();
1111
- const provider = selection instanceof ManyAccounts ? selection.provider : selection;
1112
- const health = provider.health;
1113
- if (health === void 0) return yield* new HostOperationNotFound();
1114
- const { accounts } = yield* bindAccounts(
1115
- { [requirement]: provider },
1116
- { accounts: { [requirement]: { ...slot, cardinality: "one" } } },
1117
- context
1118
- ).pipe(Effect_exports.withSpan("app.accounts.bind"));
1119
- const account = accounts[requirement];
1120
- if (account === void 0 || !("id" in account)) return yield* new HostAccountsInvalid();
1121
- const result = yield* Effect_exports.suspend(
1122
- () => Effect_exports.gen(function* () {
1123
- return yield* health.run({ account, fetch: yield* invocationFetch(signal), signal });
1124
- })
1125
- ).pipe(
1126
- Effect_exports.catchCause((cause) => {
1127
- if (Cause_exports.hasInterrupts(cause)) return Effect_exports.interrupt;
1128
- const error = Cause_exports.squash(cause);
1129
- const status = Schema_exports.decodeUnknownOption(ResponseStatusError)(error);
1130
- const classified = Option_exports.isSome(status) ? Option_exports.fromNullishOr(httpProviderError(status.value.status)) : parseProviderError(error);
1131
- return Effect_exports.fail(
1132
- Option_exports.isSome(classified) ? accountProviderError(classified.value, account.id) : new HostOperationFailed()
1133
- );
1134
- }),
1135
- Effect_exports.withSpan("app.account.check")
1136
- );
1137
- return yield* safe2(
1138
- () => Schema_exports.decodeUnknownEffect(AccountCheckResult)(result ?? {}).pipe(
1139
- Effect_exports.flatMap(Schema_exports.encodeEffect(AccountCheckResult)),
1140
- Effect_exports.flatMap(Schema_exports.decodeUnknownEffect(JsonValue))
1141
- ),
1142
- new HostOutputInvalid()
1143
- );
1144
- });
1145
- }
1146
- var parseSkillLoadFailed = (error) => Schema_exports.decodeUnknownOption(SkillLoadFailed)(error).pipe(
1147
- Option_exports.map(
1148
- ({ reason, message, status }) => new SkillLoadFailed({
1149
- reason,
1150
- ...message ? { message } : {},
1151
- ...status === void 0 ? {} : { status }
1152
- })
1153
- )
1154
- );
1155
- var parseMcpError = (error) => Schema_exports.decodeUnknownOption(McpError)(error).pipe(
1156
- Option_exports.map(
1157
- ({ phase, reason, status }) => new McpError({ phase, reason, ...status === void 0 ? {} : { status } })
1158
- )
1159
- );
1160
- var errorStatus = Match_exports.type().pipe(
1161
- Match_exports.tagsExhaustive({
1162
- ProviderError: () => 502,
1163
- McpError: () => 502,
1164
- SkillLoadFailed: () => 502,
1165
- OpenapiResponseError: () => 502,
1166
- WorkflowFailure: () => 422,
1167
- HostRequestInvalid: () => 400,
1168
- HostAccountsInvalid: () => 422,
1169
- HostInputInvalid: () => 422,
1170
- HostOperationNotFound: () => 404,
1171
- HostKindMismatch: () => 409,
1172
- HostToolNotFound: () => 404,
1173
- HostToolBlocked: () => 403,
1174
- HostToolApprovalRequired: () => 409,
1175
- HostToolPolicyFailed: () => 500,
1176
- HostOperationFailed: () => 500,
1177
- DatabaseLimitExceeded: () => 422,
1178
- DatabaseFieldReserved: () => 422,
1179
- HostDeclarationInvalid: () => 500,
1180
- HostEvaluationFailed: () => 500,
1181
- HostOutputInvalid: () => 500,
1182
- ElicitationFailed: () => 422
1183
- })
1184
- );
1185
- var createAppHandler = (app) => (request, context) => Effect_exports.gen(function* () {
1186
- if (request.method !== "POST") return yield* Effect_exports.fail(new HostRequestInvalid());
1187
- const input = yield* Effect_exports.tryPromise({
1188
- try: () => request.json(),
1189
- catch: () => new HostRequestInvalid()
1190
- });
1191
- const command = yield* Schema_exports.decodeUnknownEffect(HostRequest)(input, {
1192
- onExcessProperty: "error"
1193
- }).pipe(Effect_exports.mapError(() => new HostRequestInvalid()));
1194
- yield* Effect_exports.annotateCurrentSpan({
1195
- "executor.operation": command.operation,
1196
- ...command.operation === "call" ? { "executor.tool.name": command.tool } : {}
1197
- });
1198
- let toolError = false;
1199
- const value = yield* dispatch(app, command, context, request.signal).pipe(
1200
- Effect_exports.provideService(ToolResultObservation, {
1201
- failed: () => {
1202
- toolError = true;
1203
- }
1204
- }),
1205
- Effect_exports.withSpan(`app.${command.operation}`)
1206
- );
1207
- if (toolError)
1208
- yield* Effect_exports.annotateCurrentSpan({
1209
- "executor.outcome": "failed",
1210
- "error.type": "McpToolError"
1211
- });
1212
- return Response.json({ ok: true, value, ...toolError ? { toolError: true } : {} });
1213
- }).pipe(
1214
- Effect_exports.catch(
1215
- (error) => Schema_exports.encodeEffect(HostError)(error).pipe(
1216
- Effect_exports.map(
1217
- (encoded) => Response.json({ ok: false, error: encoded }, { status: errorStatus(error) })
1218
- ),
1219
- Effect_exports.orDie
1220
- )
1221
- ),
1222
- Effect_exports.catchCause(
1223
- (cause) => Cause_exports.hasInterrupts(cause) ? Effect_exports.interrupt : Effect_exports.logError(cause).pipe(
1224
- Effect_exports.andThen(
1225
- Schema_exports.encodeEffect(HostError)(
1226
- declarationInvalid(
1227
- "The app failed while it was loaded",
1228
- Cause_exports.squash(cause),
1229
- accountSecrets(context.accounts)
1230
- )
1231
- )
1232
- ),
1233
- Effect_exports.map((error) => Response.json({ ok: false, error }, { status: 500 })),
1234
- Effect_exports.orDie
1235
- )
1236
- )
1237
- );
1238
-
1239
- export {
1240
- prepareElicitation,
1241
- ApprovalDecision,
1242
- createAppHandler
1243
- };