@gjermundgaraba/effect-actions 0.22.0 → 0.24.0

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 (276) hide show
  1. package/README.md +9 -3
  2. package/dist/Action.d.mts +2 -2
  3. package/dist/Action.mjs +1 -0
  4. package/dist/ActionCli.d.mts +1 -1
  5. package/dist/ActionCli.mjs +1 -2
  6. package/dist/ActionHttp.d.mts +2 -2
  7. package/dist/ActionMcp.d.mts +20 -20
  8. package/dist/ActionMcp.mjs +9 -11
  9. package/dist/ActionRpc.d.mts +8 -15
  10. package/dist/ActionRpc.mjs +29 -54
  11. package/dist/ActionToolkit.d.mts +0 -2
  12. package/dist/ActionToolkit.mjs +0 -2
  13. package/dist/Event.d.mts +0 -23
  14. package/dist/Testing.mjs +3 -2
  15. package/dist/Webhook.mjs +2 -2
  16. package/dist/authentication/refusal.mjs +0 -1
  17. package/dist/cli/commands.mjs +0 -5
  18. package/dist/contract/authorizer.mjs +0 -5
  19. package/dist/contract/call.mjs +0 -23
  20. package/dist/contract/callback.mjs +0 -1
  21. package/dist/contract/caller.mjs +0 -11
  22. package/dist/contract/canonical.mjs +0 -5
  23. package/dist/contract/codec.d.mts +0 -1
  24. package/dist/contract/codec.mjs +0 -1
  25. package/dist/contract/codes.mjs +1 -15
  26. package/dist/contract/declared.mjs +0 -15
  27. package/dist/contract/digest.mjs +0 -1
  28. package/dist/contract/errors.d.mts +0 -4
  29. package/dist/contract/errors.mjs +0 -4
  30. package/dist/contract/feed.d.mts +0 -1
  31. package/dist/contract/feed.mjs +0 -20
  32. package/dist/contract/hints.mjs +0 -6
  33. package/dist/contract/hub.mjs +0 -3
  34. package/dist/contract/idempotency.mjs +0 -4
  35. package/dist/contract/implementation.d.mts +0 -1
  36. package/dist/contract/implementation.mjs +0 -27
  37. package/dist/contract/input-check.mjs +0 -1
  38. package/dist/contract/lease.mjs +0 -1
  39. package/dist/contract/listed.mjs +0 -6
  40. package/dist/contract/log.mjs +0 -8
  41. package/dist/contract/names.mjs +0 -1
  42. package/dist/contract/occurrence.mjs +0 -8
  43. package/dist/contract/pages.mjs +5 -12
  44. package/dist/contract/progress.mjs +2 -25
  45. package/dist/contract/push.d.mts +0 -5
  46. package/dist/contract/push.mjs +1 -24
  47. package/dist/contract/receiving.mjs +0 -7
  48. package/dist/contract/reported.mjs +0 -5
  49. package/dist/contract/serving.mjs +0 -18
  50. package/dist/contract/status.mjs +0 -3
  51. package/dist/contract/stream.mjs +0 -2
  52. package/dist/contract/subscribe.d.mts +0 -2
  53. package/dist/contract/subscribe.mjs +0 -8
  54. package/dist/contract/transient.mjs +0 -12
  55. package/dist/contract/watch.mjs +5 -17
  56. package/dist/contract/webhooks.mjs +0 -11
  57. package/dist/http/client.mjs +0 -1
  58. package/dist/http/events.d.mts +0 -10
  59. package/dist/http/events.mjs +2 -31
  60. package/dist/http/placed.d.mts +0 -2
  61. package/dist/http/streamed.d.mts +0 -1
  62. package/dist/http/streamed.mjs +4 -32
  63. package/dist/http/watch.mjs +0 -6
  64. package/dist/mcp/bridge.mjs +1 -26
  65. package/dist/mcp/client.d.mts +0 -1
  66. package/dist/mcp/client.mjs +0 -1
  67. package/dist/mcp/events.mjs +0 -6
  68. package/dist/mcp/progress.mjs +0 -7
  69. package/dist/mcp/protocol.mjs +0 -6
  70. package/dist/mcp/reply.mjs +0 -11
  71. package/dist/mcp/request.mjs +0 -1
  72. package/dist/mcp/watch.mjs +0 -6
  73. package/dist/rpc/watch.mjs +0 -6
  74. package/dist/stdio/console.mjs +2 -2
  75. package/dist/webhook/address.mjs +4 -9
  76. package/dist/webhook/attempt.mjs +2 -15
  77. package/dist/webhook/receiver.mjs +2 -8
  78. package/dist/webhook/signing.mjs +0 -3
  79. package/dist/webhook/stored.mjs +8 -17
  80. package/dist/webhook/subscriptions.mjs +19 -23
  81. package/docs/Action-streams.md +0 -12
  82. package/docs/Action.md +0 -10
  83. package/docs/ActionCli.md +2 -26
  84. package/docs/ActionHttp-failures.md +1 -1
  85. package/docs/ActionHttp.md +0 -28
  86. package/docs/ActionMcp-failures.md +2 -1
  87. package/docs/ActionMcp.md +2 -37
  88. package/docs/ActionRpc-events.md +0 -16
  89. package/docs/ActionRpc.md +0 -63
  90. package/docs/ActionToolkit.md +0 -11
  91. package/docs/Authentication-advanced.md +0 -31
  92. package/docs/Authentication.md +4 -13
  93. package/docs/Event.md +0 -37
  94. package/docs/README.md +1 -1
  95. package/docs/Testing-failures.md +1 -1
  96. package/docs/Testing.md +3 -13
  97. package/docs/Webhook.md +0 -46
  98. package/docs/setup-failures.md +1 -1
  99. package/docs/setup.md +5 -10
  100. package/examples/README.md +7 -1
  101. package/examples/assistant/src/agent.ts +8 -31
  102. package/examples/assistant/src/cli.ts +2 -9
  103. package/examples/assistant/src/commands.ts +0 -8
  104. package/examples/assistant/src/identity/Identity.ts +0 -10
  105. package/examples/assistant/src/identity/authorize.ts +0 -4
  106. package/examples/assistant/src/identity/members.ts +1 -3
  107. package/examples/assistant/src/identity/permissions.ts +0 -5
  108. package/examples/assistant/src/platform/tasks-file.ts +1 -6
  109. package/examples/assistant/src/scripted.ts +0 -4
  110. package/examples/assistant/src/tasks/Tasks.ts +0 -2
  111. package/examples/assistant/src/tasks/handlers.ts +0 -3
  112. package/examples/assistant/src/tasks/store.ts +0 -7
  113. package/examples/assistant/src/toolkit.ts +0 -11
  114. package/examples/assistant/test/commands.test.ts +0 -5
  115. package/examples/assistant/test/identity/identity.test.ts +6 -6
  116. package/examples/assistant/test/platform/tasks-file.test.ts +2 -6
  117. package/examples/assistant/test/tasks/tasks.test.ts +13 -14
  118. package/examples/assistant/test/toolkit.test.ts +7 -18
  119. package/examples/build-events/README.md +2 -0
  120. package/examples/build-events/src/Api.ts +0 -3
  121. package/examples/build-events/src/Rpc.ts +0 -2
  122. package/examples/build-events/src/builds/Builds.ts +0 -15
  123. package/examples/build-events/src/builds/events.ts +0 -10
  124. package/examples/build-events/src/builds/handlers.ts +0 -6
  125. package/examples/build-events/src/builds/log.ts +0 -6
  126. package/examples/build-events/src/builds/status.ts +0 -4
  127. package/examples/build-events/src/builds/store.ts +0 -21
  128. package/examples/build-events/src/cli.ts +0 -2
  129. package/examples/build-events/src/commands.ts +0 -9
  130. package/examples/build-events/src/deploys/approvers.ts +0 -3
  131. package/examples/build-events/src/deploys/events.ts +0 -8
  132. package/examples/build-events/src/deploys/handlers.ts +0 -2
  133. package/examples/build-events/src/identity/Identity.ts +0 -11
  134. package/examples/build-events/src/identity/members.ts +1 -2
  135. package/examples/build-events/src/identity/verifier.ts +8 -9
  136. package/examples/build-events/src/notifier/Notices.ts +0 -3
  137. package/examples/build-events/src/notifier/routes.ts +0 -10
  138. package/examples/build-events/src/notifier.ts +0 -8
  139. package/examples/build-events/src/routes.ts +0 -24
  140. package/examples/build-events/src/server.ts +0 -14
  141. package/examples/build-events/test/builds/events.test.ts +0 -6
  142. package/examples/build-events/test/builds/log.test.ts +0 -1
  143. package/examples/build-events/test/builds/progress.test.ts +0 -1
  144. package/examples/build-events/test/commands.test.ts +0 -5
  145. package/examples/build-events/test/deploys/events.test.ts +0 -1
  146. package/examples/build-events/test/http.test.ts +0 -4
  147. package/examples/build-events/test/notifier.test.ts +0 -9
  148. package/examples/build-events/test/routes.test.ts +0 -9
  149. package/examples/build-events/test/rpc.test.ts +0 -4
  150. package/examples/build-events/test/support/as.ts +3 -4
  151. package/examples/build-events/test/support/memory.ts +0 -5
  152. package/examples/build-events/test/webhooks.test.ts +0 -12
  153. package/examples/kitchen-sink/README.md +1 -1
  154. package/examples/kitchen-sink/src/Actions.ts +0 -10
  155. package/examples/kitchen-sink/src/Api.ts +0 -8
  156. package/examples/kitchen-sink/src/Rpc.ts +0 -4
  157. package/examples/kitchen-sink/src/admin/Admin.ts +0 -9
  158. package/examples/kitchen-sink/src/admin/authenticate.ts +2 -6
  159. package/examples/kitchen-sink/src/admin/authorize.ts +0 -5
  160. package/examples/kitchen-sink/src/admin/grants.ts +0 -5
  161. package/examples/kitchen-sink/src/admin/handlers.ts +0 -2
  162. package/examples/kitchen-sink/src/admin/keys.ts +1 -3
  163. package/examples/kitchen-sink/src/agent.ts +2 -13
  164. package/examples/kitchen-sink/src/assistant/Assistant.ts +7 -24
  165. package/examples/kitchen-sink/src/assistant/conversations.ts +3 -21
  166. package/examples/kitchen-sink/src/assistant/demo-model.ts +0 -5
  167. package/examples/kitchen-sink/src/assistant/handlers.ts +1 -30
  168. package/examples/kitchen-sink/src/attachments/Attachments.ts +0 -4
  169. package/examples/kitchen-sink/src/attachments/download.ts +0 -10
  170. package/examples/kitchen-sink/src/attachments/handlers.ts +0 -3
  171. package/examples/kitchen-sink/src/attachments/store.ts +0 -3
  172. package/examples/kitchen-sink/src/browser.ts +0 -9
  173. package/examples/kitchen-sink/src/cli.ts +0 -19
  174. package/examples/kitchen-sink/src/config.ts +3 -11
  175. package/examples/kitchen-sink/src/identity/Identity.ts +0 -18
  176. package/examples/kitchen-sink/src/identity/authenticate.ts +3 -14
  177. package/examples/kitchen-sink/src/identity/authorize.ts +0 -6
  178. package/examples/kitchen-sink/src/identity/directory.ts +8 -18
  179. package/examples/kitchen-sink/src/identity/handlers.ts +0 -3
  180. package/examples/kitchen-sink/src/identity/members.ts +1 -5
  181. package/examples/kitchen-sink/src/identity/quota.ts +0 -11
  182. package/examples/kitchen-sink/src/issues/Issues.ts +0 -24
  183. package/examples/kitchen-sink/src/issues/assistant.ts +0 -10
  184. package/examples/kitchen-sink/src/issues/events.ts +2 -16
  185. package/examples/kitchen-sink/src/issues/export.ts +0 -5
  186. package/examples/kitchen-sink/src/issues/guide.ts +0 -5
  187. package/examples/kitchen-sink/src/issues/handlers.ts +0 -5
  188. package/examples/kitchen-sink/src/issues/store.ts +19 -23
  189. package/examples/kitchen-sink/src/issues/write-limit.ts +0 -12
  190. package/examples/kitchen-sink/src/memory.ts +0 -9
  191. package/examples/kitchen-sink/src/ops.ts +0 -6
  192. package/examples/kitchen-sink/src/request-policy.ts +0 -17
  193. package/examples/kitchen-sink/src/routes.ts +0 -48
  194. package/examples/kitchen-sink/src/sdk.ts +0 -12
  195. package/examples/kitchen-sink/src/seed.ts +0 -10
  196. package/examples/kitchen-sink/src/server.ts +0 -22
  197. package/examples/kitchen-sink/src/stdio.ts +2 -12
  198. package/examples/kitchen-sink/src/workspaces/Workspaces.ts +0 -4
  199. package/examples/kitchen-sink/src/workspaces/handlers.ts +0 -4
  200. package/examples/kitchen-sink/src/workspaces/registry.ts +0 -5
  201. package/examples/kitchen-sink/src/workspaces/tenant.ts +0 -4
  202. package/examples/kitchen-sink/test/admin/admin.test.ts +0 -1
  203. package/examples/kitchen-sink/test/assistant/assistant.test.ts +0 -18
  204. package/examples/kitchen-sink/test/attachments/attachments.test.ts +0 -9
  205. package/examples/kitchen-sink/test/identity/identity.test.ts +0 -10
  206. package/examples/kitchen-sink/test/identity/session.test.ts +0 -10
  207. package/examples/kitchen-sink/test/issues/assistant.test.ts +3 -7
  208. package/examples/kitchen-sink/test/issues/events.test.ts +2 -9
  209. package/examples/kitchen-sink/test/issues/export.test.ts +0 -3
  210. package/examples/kitchen-sink/test/issues/issues.test.ts +6 -12
  211. package/examples/kitchen-sink/test/request-policy.test.ts +0 -6
  212. package/examples/kitchen-sink/test/routes.test.ts +0 -6
  213. package/examples/kitchen-sink/test/support/as.ts +3 -5
  214. package/examples/kitchen-sink/test/support/scripted.ts +0 -3
  215. package/examples/kitchen-sink/test/support/services.ts +0 -3
  216. package/examples/live-rpc/src/Rpc.ts +0 -4
  217. package/examples/live-rpc/src/browser.ts +0 -24
  218. package/examples/live-rpc/src/chat/Chat.ts +0 -22
  219. package/examples/live-rpc/src/chat/authorize.ts +0 -3
  220. package/examples/live-rpc/src/chat/events.ts +0 -14
  221. package/examples/live-rpc/src/chat/handlers.ts +0 -5
  222. package/examples/live-rpc/src/chat/room.ts +0 -6
  223. package/examples/live-rpc/src/chat/store.ts +0 -9
  224. package/examples/live-rpc/src/client.ts +0 -6
  225. package/examples/live-rpc/src/identity/Identity.ts +0 -6
  226. package/examples/live-rpc/src/identity/members.ts +1 -3
  227. package/examples/live-rpc/src/identity/verifier.ts +6 -12
  228. package/examples/live-rpc/src/page.ts +0 -10
  229. package/examples/live-rpc/src/routes.ts +0 -13
  230. package/examples/live-rpc/src/server.ts +0 -16
  231. package/examples/live-rpc/test/browser.test.ts +0 -9
  232. package/examples/live-rpc/test/chat/chat.test.ts +3 -11
  233. package/examples/live-rpc/test/routes.test.ts +0 -8
  234. package/examples/live-rpc/test/server.test.ts +0 -13
  235. package/examples/mcp-tools/src/instructions.ts +0 -4
  236. package/examples/mcp-tools/src/platform/fake-farm.ts +0 -6
  237. package/examples/mcp-tools/src/platform/print-farm.ts +0 -16
  238. package/examples/mcp-tools/src/printers/Printers.ts +0 -21
  239. package/examples/mcp-tools/src/printers/farm.ts +0 -5
  240. package/examples/mcp-tools/src/printers/handlers.ts +0 -6
  241. package/examples/mcp-tools/src/routes.ts +0 -11
  242. package/examples/mcp-tools/src/server.ts +0 -9
  243. package/examples/mcp-tools/src/stdio.ts +1 -13
  244. package/examples/mcp-tools/test/printers/printers.test.ts +0 -10
  245. package/examples/mcp-tools/test/routes.test.ts +0 -14
  246. package/examples/notes-service/src/Api.ts +0 -4
  247. package/examples/notes-service/src/browser.ts +0 -12
  248. package/examples/notes-service/src/cli.ts +0 -2
  249. package/examples/notes-service/src/commands.ts +0 -30
  250. package/examples/notes-service/src/identity/Identity.ts +0 -2
  251. package/examples/notes-service/src/identity/authorize.ts +0 -4
  252. package/examples/notes-service/src/identity/users.ts +1 -3
  253. package/examples/notes-service/src/identity/verifier.ts +4 -11
  254. package/examples/notes-service/src/notes/Notes.ts +0 -12
  255. package/examples/notes-service/src/notes/handlers.ts +0 -4
  256. package/examples/notes-service/src/notes/store.ts +62 -48
  257. package/examples/notes-service/src/routes.ts +0 -12
  258. package/examples/notes-service/src/server.ts +0 -6
  259. package/examples/notes-service/src/status/Status.ts +0 -1
  260. package/examples/notes-service/src/status/handlers.ts +0 -1
  261. package/examples/notes-service/src/stdio.ts +2 -12
  262. package/examples/notes-service/src/worker.ts +0 -7
  263. package/examples/notes-service/test/commands.test.ts +0 -20
  264. package/examples/notes-service/test/notes/as.ts +3 -4
  265. package/examples/notes-service/test/notes/in-process.test.ts +3 -6
  266. package/examples/notes-service/test/notes/notes.test.ts +0 -6
  267. package/examples/notes-service/test/routes.test.ts +0 -5
  268. package/examples/notes-service/test/worker.test.ts +0 -1
  269. package/examples/quickstart/src/Api.ts +0 -1
  270. package/examples/quickstart/src/client.ts +0 -3
  271. package/examples/quickstart/src/greeting/Greeting.ts +0 -2
  272. package/examples/quickstart/src/greeting/handlers.ts +0 -1
  273. package/examples/quickstart/src/routes.ts +0 -1
  274. package/examples/quickstart/src/server.ts +3 -6
  275. package/examples/quickstart/test/routes.test.ts +0 -1
  276. package/package.json +6 -6
@@ -5,13 +5,7 @@ import { answeredStatus, failingWhenUnanswered, isTransient, receivedFrom } from
5
5
  import { Effect, Predicate, Stream } from "effect";
6
6
  import { HttpClientError } from "effect/http";
7
7
  // src/http/watch.ts
8
- /** Whether `error` is an HTTP client's failure on a 404 answer. */
9
8
  const isNotFound = Predicate.compose(HttpClientError.isHttpClientError, (error) => answeredStatus(error) === 404);
10
- /**
11
- * The transport of one subscription to `event` over its route, `input` its decoded input: each
12
- * page from `poll`, the stream from `stream`, and a webhook subscription from `webhook`'s routes
13
- * where the binding has them, a 404 failing as `NotServed`.
14
- */
15
9
  const transportOf = (event, poll, stream, webhook, input) => {
16
10
  const notServed = Effect.fail(SubscriptionError.of(event.name, new NotServed()));
17
11
  const answered = (request) => request.pipe(failingWhenUnanswered, Effect.catchIf(isNotFound, () => notServed));
@@ -18,13 +18,9 @@ import { McpSchema } from "effect/ai";
18
18
  const isGroup = (u) => Predicate.isObjectKeyword(u) && "merge" in u && Predicate.isFunction(u.merge) && "requests" in u && u.requests instanceof Map;
19
19
  const groupOf = (adapter, key) => {
20
20
  const group = Predicate.hasProperty(adapter, key) ? adapter[key] : void 0;
21
- if (!isGroup(group)) throw new Error(`Effect's MCP ${adapter.protocolVersion} adapter holds no ${key} group: effect-actions supports MCP events on effect 4.0.x (install the effect version its peer range names)`);
21
+ if (!isGroup(group)) throw new Error(`Effect's MCP ${adapter.protocolVersion} adapter holds no ${key} group: effect-actions supports MCP events on effect 4.1.x (install the effect version its peer range names)`);
22
22
  return group;
23
23
  };
24
- /**
25
- * The JSON Schemas `events/list` lists for `event`, refusing an input or a payload that is no
26
- * object.
27
- */
28
24
  const eventSchemasOf = (event) => {
29
25
  const inputSchema = toolJsonSchema(Schema.toCodecJson(event.input), true);
30
26
  if (!isObjectSchema(inputSchema)) throw new Error(`MCP event input must be one object with keys, such as a struct: ${event.name} (wrap a union, an array or a scalar in a field, or omit input for no arguments)`);
@@ -70,27 +66,11 @@ const servedOf = (feed, delivery) => {
70
66
  }
71
67
  };
72
68
  };
73
- /**
74
- * Dies with the reason the endpoint of `serving` cannot serve one of its events, run where the
75
- * endpoint's layer is built: a protected one with a `subscription` hook, under an authentication
76
- * without a principal to key its polls by.
77
- */
78
69
  const refuseUnservable = ({ events, authentication }) => authentication === void 0 ? Effect.void : Effect.flatMap(acquireFeeds(events), (feeds) => {
79
70
  const refusal = unkeyedHook("MCP", feeds, authentication.principal !== void 0);
80
71
  return refusal === void 0 ? Effect.void : Effect.die(new Error(refusal));
81
72
  });
82
- /**
83
- * Serves the feeds the endpoint of `serving` offers by webhook to `Webhooks`, where it is
84
- * provided, run where the endpoint's layer is built: it restores their kept subscriptions, and
85
- * dies where they cannot be kept.
86
- */
87
73
  const serveWebhooks = (serving) => Effect.asVoid(Effect.flatMap(acquireFeeds(serving.events), (feeds) => servedWebhooks(feeds, serving.authentication)));
88
- /**
89
- * One push subscription, as `events/stream` holds it: what the feed's `pushed` sends, as
90
- * SEP-3415's notifications. Its confirmation is `active`, a later gap a fresh `active`, a
91
- * position a heartbeat, and a failure it reads on through `error`. A failure before `active` is
92
- * the request's error; a refusal after it ends the subscription with `terminated`.
93
- */
94
74
  const delivered = ({ send, clientId, requestId, wire, _meta: resultMeta }, run) => {
95
75
  const notify = (rpc, payload) => send("2026-07-28", clientId, {
96
76
  tag: rpc._tag,
@@ -149,11 +129,6 @@ const delivered = ({ send, clientId, requestId, wire, _meta: resultMeta }, run)
149
129
  };
150
130
  });
151
131
  };
152
- /**
153
- * `base`, the 2026-07-28 adapter, also serving SEP-3415's `events/list`, `events/poll` and
154
- * `events/stream` for the event implementations of `serving`, and advertising the extension in
155
- * its discovery.
156
- */
157
132
  const withEvents = (base, serving) => {
158
133
  const { authentication } = serving;
159
134
  const asSubscriber = (event, run) => authentication === void 0 || event.caller === Anyone ? run : recordStepUp(promote(authentication, run));
@@ -33,7 +33,6 @@ export interface ClientOptions<D extends Any$2 | undefined = Any$2 | undefined,
33
33
  readonly authentication?: D;
34
34
  }
35
35
  type CallError<A extends Any$1, D> = A["error"][number]["Type"] | VerifierError<A, D>["Type"] | BuiltIn | Schema.SchemaError | HttpClientError.HttpClientError | McpCallError;
36
- /** What a watch of `W` may fail with, under the endpoint's descriptor `D`. */
37
36
  type WatchError<W extends Any, D> = SubscriptionError | BuiltIn | VerifierError<W, D>["Type"] | Schema.SchemaError | HttpClientError.HttpClientError | McpCallError;
38
37
  /**
39
38
  * Every action of `Contracts` as `client.<action>(input)`, calling its tool; one answering a
@@ -21,7 +21,6 @@ const ToolCallReply = Schema.Union([Schema.Struct({ result: McpSchema.CallToolRe
21
21
  message: Schema.String
22
22
  }) })]);
23
23
  const decodeReply = Schema.decodeUnknownOption(Schema.fromJsonString(ToolCallReply));
24
- /** `onProgress` given each `notifications/progress` value decoded, one that does not logged and dropped. */
25
24
  const decodedSink = (progress, onProgress) => {
26
25
  const sink = progressSink(onProgress);
27
26
  if (progress === void 0 || sink === void 0) return;
@@ -4,9 +4,7 @@ import { ErrorReporter, Schema, Struct } from "effect";
4
4
  import { McpSchema } from "effect/ai";
5
5
  import { Rpc, RpcGroup } from "effect/rpc";
6
6
  // src/mcp/events.ts
7
- /** The extension's identifier, its key in `capabilities.extensions`. */
8
7
  const extension = "io.modelcontextprotocol/events";
9
- /** The `_meta` key a push stream's notifications carry its request id under. */
10
8
  const subscriptionIdKey = "io.modelcontextprotocol/subscriptionId";
11
9
  const codes = {
12
10
  headerMismatch: -32020,
@@ -17,17 +15,14 @@ const codes = {
17
15
  const Meta = Schema.optional(Schema.Record(Schema.String, Schema.Json));
18
16
  const Arguments = Schema.optional(Schema.Record(Schema.String, Schema.Json));
19
17
  const Cursor = Schema.optional(Schema.NullOr(Schema.String));
20
- /** A JSON-RPC error as an `events/*` request fails with, and a termination carries. */
21
18
  const WireError = Schema.Struct({
22
19
  code: Schema.Int,
23
20
  message: Schema.String,
24
21
  data: Schema.optional(Schema.Json)
25
22
  });
26
- /** What an `events/*` handler fails with: the JSON-RPC error it answers. */
27
23
  var EventsError = class extends Schema.Error("effect-actions/McpEventsError")(WireError.fields) {
28
24
  [ErrorReporter.ignore] = true;
29
25
  };
30
- /** One event type as `events/list` lists it. */
31
26
  const EventDescriptor = Schema.Struct({
32
27
  name: Schema.String,
33
28
  description: Schema.String,
@@ -39,7 +34,6 @@ const EventDescriptor = Schema.Struct({
39
34
  inputSchema: McpSchema.ToolJson,
40
35
  payloadSchema: McpSchema.ToolOutputJson
41
36
  });
42
- /** An occurrence on the wire: in a poll's `events`, and the params of an event notification. */
43
37
  const WireOccurrence = Schema.Struct({
44
38
  eventId: Schema.String,
45
39
  name: Schema.String,
@@ -1,14 +1,8 @@
1
1
  import { Effect, Option, Schema } from "effect";
2
2
  import { McpSchema } from "effect/ai";
3
3
  // src/mcp/progress.ts
4
- /** The `_meta` key a `notifications/progress` carries its value under, as JSON. */
5
4
  const progressKey = "effect-actions/progress";
6
5
  const tokenOf = Schema.decodeUnknownOption(McpSchema.ProgressToken);
7
- /**
8
- * Where a tool call's progress goes: a `notifications/progress` for each value, on the
9
- * `progressToken` its request carried, `progress` counting from 1, `message` the value's JSON and
10
- * `_meta` the value; none for a request without a token, so the values are checked and dropped.
11
- */
12
6
  const progressNotifier = (notifications, progress) => Effect.map(Effect.service(McpSchema.McpRequestContext), ({ requestMetadata }) => {
13
7
  const token = tokenOf(requestMetadata?.progressToken);
14
8
  if (Option.isNone(token)) return;
@@ -29,6 +23,5 @@ const Notified = Schema.fromJsonString(Schema.Struct({
29
23
  params: Schema.Struct({ _meta: Schema.Struct({ [progressKey]: Schema.Json }) })
30
24
  }));
31
25
  const notifiedOf = Schema.decodeUnknownOption(Notified);
32
- /** The value a frame's `notifications/progress` carries, or none for another frame. */
33
26
  const progressOf = (data) => Option.map(notifiedOf(data), (notified) => notified.params._meta[progressKey]);
34
27
  export { progressKey, progressNotifier, progressOf };
@@ -34,7 +34,6 @@ const toolJsonSchema = (schema, strict) => {
34
34
  $defs: definitions
35
35
  };
36
36
  };
37
- /** The forms an MCP routing header may carry `name` in: as sent, or base64-encoded in its sentinel. */
38
37
  const routingFormsOf = (name) => [name, `=?base64?${Base64.encode(name)}?=`];
39
38
  const fieldKey = "effect-actions/field";
40
39
  const isMedia = Schema.is(Media);
@@ -143,11 +142,6 @@ const mediaOf = ({ name, kind, many }, result) => {
143
142
  }] : []);
144
143
  return many || values.length > 1 ? values : values[0];
145
144
  };
146
- /**
147
- * The encoded success a tool result carries, `liftedFrom` undone: its structured content, each
148
- * lifted field from the blocks whose `_meta` names it, and a success that is media from its
149
- * blocks alone.
150
- */
151
145
  const unliftedFrom = (lift, result) => {
152
146
  const [whole] = lift.fields;
153
147
  if (whole !== void 0 && whole.name === void 0) return mediaOf(whole, result);
@@ -70,10 +70,6 @@ const callError = (method, target, reason) => new McpCallError({
70
70
  message: `MCP ${method} "${target}" ${sentenceOf(reason)}`
71
71
  });
72
72
  const isEventStream = (response) => (response.headers["content-type"] ?? "").startsWith("text/event-stream");
73
- /**
74
- * The data of each frame of the event stream `response` is, as it arrives: more than the parser
75
- * holds with no frame ending fails `method` on `name` with `FrameTooLarge`.
76
- */
77
73
  const framesOf = (method, name, response) => Stream.suspend(() => {
78
74
  const data = [];
79
75
  const parser = Sse.makeParser((event) => {
@@ -84,16 +80,9 @@ const framesOf = (method, name, response) => Stream.suspend(() => {
84
80
  return error === void 0 ? Effect.succeed(data.splice(0)) : Effect.fail(callError(method, name, new FrameTooLarge({ maxEventSize: error.reason.maxEventSize })));
85
81
  }), Stream.flattenIterable);
86
82
  });
87
- /**
88
- * The messages of `response`, read as it arrives: the data of each frame of an event stream, or
89
- * the body itself as one. Each `notifications/progress` frame hands its value to `sink` and is
90
- * left out, so a long call holds the frames its reply is read from, not every value it reported.
91
- * A stateless request's notifications are its own.
92
- */
93
83
  const bodyOf = (method, name, response, sink) => isEventStream(response) ? Stream.runCollect(Stream.filterEffect(framesOf(method, name, response), (data) => Option.match(progressOf(data), {
94
84
  onNone: () => Effect.succeed(true),
95
85
  onSome: (value) => sink === void 0 ? Effect.succeed(false) : Effect.as(sink.progress(value), false)
96
86
  }))) : Effect.map(response.text, (text) => [text]);
97
- /** Fails with the error of `errors` that `text` decodes as, or with `otherwise`. */
98
87
  const failWith = (errors, text, otherwise) => Schema.decodeEffect(Schema.fromJsonString(Schema.toCodecJson(Schema.Union(errors))))(text).pipe(Effect.mapError(() => otherwise), Effect.flatMap(Effect.fail));
99
88
  export { FrameTooLarge, McpCallError, NoReply, NoStructuredContent, ProtocolError, StatusError, UndeclaredError, bodyOf, callError, failWith, framesOf, isEventStream };
@@ -2,7 +2,6 @@ import { defaultPath, httpProtocol } from "./protocol.mjs";
2
2
  import { Predicate } from "effect";
3
3
  import { HttpClientRequest } from "effect/http";
4
4
  // src/mcp/request.ts
5
- /** The routing headers and JSON-RPC body of the request `request` builds. */
6
5
  const statelessRequest = (method, params) => {
7
6
  const { protocolVersion } = httpProtocol;
8
7
  const name = method === "resources/read" ? params["uri"] : params["name"];
@@ -12,7 +12,6 @@ import { McpCallError, NoReply, ProtocolError, StatusError, bodyOf, callError, f
12
12
  import { request } from "./request.mjs";
13
13
  import { Duration, Effect, Match, Option, Predicate, Schema, Stream } from "effect";
14
14
  // src/mcp/watch.ts
15
- /** Reads one message as a request's reply: its result, by `success`, or its error. */
16
15
  const replyOf = (success) => Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Union([Schema.Struct({ result: success }), Schema.Struct({ error: WireError })])));
17
16
  const pollReplyOf = replyOf(PollEvents.successSchema);
18
17
  const Frame = Schema.Union([
@@ -35,10 +34,6 @@ const encodeTarget = Schema.encodeSync(WebhookTarget);
35
34
  const transientReason = (reason) => Match.value(reason).pipe(Match.tag("StatusError", ({ status }) => isTransientStatus(status)), Match.tag("ProtocolError", ({ code }) => code === codes.internal), Match.orElse(() => false));
36
35
  const isMcpCallError = Schema.is(McpCallError);
37
36
  const transient = Predicate.or(isTransient, Predicate.compose(isMcpCallError, ({ reason }) => transientReason(reason)));
38
- /**
39
- * The transport of one subscription over an MCP endpoint served by `layerHttp`: `events/poll`
40
- * for each page, and `events/stream` read as it arrives, each failing as the endpoint answered.
41
- */
42
37
  const transportOf = ({ http, url, event, refusedWith }, input) => {
43
38
  const { name } = event;
44
39
  const untagged = untaggedOccurrenceOf(event);
@@ -55,7 +50,6 @@ const transportOf = ({ http, url, event, refusedWith }, input) => {
55
50
  status: response.status,
56
51
  body
57
52
  })))));
58
- /** The result of one `method` request, or what its error reply fails with. */
59
53
  const answered = (method, params, decodeReply) => Effect.gen(function* () {
60
54
  const messages = yield* bodyOf(method, name, yield* sent(method, params));
61
55
  const reply = messages.flatMap((message) => Option.toArray(decodeReply(message))).at(-1);
@@ -12,17 +12,11 @@ const isAnsweredReason = Schema.is(Schema.Union([
12
12
  Schema.instanceOf(HttpClientError.DecodeError)
13
13
  ]));
14
14
  const cutResponses = ["HTTP response ended before RPC request completed", "Received empty HTTP response"];
15
- /** Whether a watch's failure over an rpc protocol is one a reconnect may outlast. */
16
15
  const isRpcTransient = Predicate.or(Cause.isTimeoutError, (error) => isRpcClientError(error) && Match.value(error.reason).pipe(Match.tag("SocketReadError", "SocketWriteError", "SocketOpenError", () => true), Match.tag("SocketCloseError", ({ code }) => code < 4e3 || code > 4999), Match.tag("HttpError", ({ cause }) => isAnsweredReason(cause) && isTransientReason(cause)), Match.tag("RpcClientDefect", ({ message }) => cutResponses.some((fragment) => message.includes(fragment))), Match.orElse(() => false)));
17
16
  const isUnknownTag = (tag) => {
18
17
  const message = `Unknown request tag: ${tag}`;
19
18
  return (cause) => cause.reasons.some((reason) => Cause.isDieReason(reason) && (Predicate.hasProperty(reason.defect, "message") ? reason.defect.message === message : reason.defect === message));
20
19
  };
21
- /**
22
- * The transport of one subscription to `event` over its stream rpc: the stream alone, since an
23
- * rpc serves no poll, failing as `NotServed` where the server serves no such rpc, and once it goes
24
- * silent where `silenceEnds`.
25
- */
26
20
  const transportOf = (event, stream, silenceEnds) => {
27
21
  const notServed = Stream.fail(SubscriptionError.of(event.name, new NotServed()));
28
22
  const unknownTag = isUnknownTag(event.name);
@@ -1,6 +1,6 @@
1
1
  import { Clock, Console, Effect, Function, Predicate } from "effect";
2
2
  // src/stdio/console.ts
3
- const stderrConsole = (console, clock) => {
3
+ const stderrOnlyConsole = (console, clock) => {
4
4
  const counts = /* @__PURE__ */ new Map();
5
5
  const timers = /* @__PURE__ */ new Map();
6
6
  const write = (...args) => {
@@ -67,5 +67,5 @@ const stderrConsole = (console, clock) => {
67
67
  warn: write
68
68
  };
69
69
  };
70
- const withStderrConsole = (effect) => Effect.provideServiceEffect(effect, Console.Console, Effect.zipWith(Effect.service(Console.Console), Effect.service(Clock.Clock), stderrConsole));
70
+ const withStderrConsole = (effect) => Effect.provideServiceEffect(effect, Console.Console, Effect.zipWith(Effect.service(Console.Console), Effect.service(Clock.Clock), stderrOnlyConsole));
71
71
  export { withStderrConsole };
@@ -31,17 +31,12 @@ const notGlobal = [
31
31
  "fe80::/10",
32
32
  "ff00::/8"
33
33
  ].map(IpNetwork.fromStringUnsafe);
34
- /** Whether `address` is globally reachable, in no special-purpose range. */
35
34
  const isGlobal = (address) => !notGlobal.some((network) => IpNetwork.contains(network, address));
36
- /**
37
- * Checks the host of `url`, failing unless every address it names is globally reachable: a
38
- * literal address is checked as it is, a name through `dns`, or passed where there is none, and a
39
- * scoped IPv6 literal refused.
40
- */
41
35
  const checkedHost = (url, dns) => {
42
36
  const host = Result.getOrUndefined(Host.hostFromString(url.hostname.replace(/^\[(?<address>.*)\]$/u, "$<address>")));
43
- if (!NetAddress.isIpAddress(host) && !Host.isDomainName(host)) return Effect.fail(void 0);
44
- const addresses = NetAddress.isIpAddress(host) ? Effect.succeed([host]) : dns?.lookup(host) ?? Effect.succeed([]);
45
- return Effect.flatMap(Effect.mapError(addresses, Function.constUndefined), (resolved) => resolved.every(isGlobal) ? Effect.void : Effect.fail(void 0));
37
+ if (NetAddress.isIpAddress(host)) return isGlobal(host) ? Effect.void : Effect.fail(void 0);
38
+ if (!Host.isDomainName(host)) return Effect.fail(void 0);
39
+ if (dns === void 0) return Effect.void;
40
+ return Effect.flatMap(Effect.mapError(dns.lookup(host), Function.constUndefined), (resolved) => resolved.every(isGlobal) ? Effect.void : Effect.fail(void 0));
46
41
  };
47
42
  export { checkedHost };
@@ -2,10 +2,6 @@ import { signature } from "./signing.mjs";
2
2
  import { Clock, Data, Duration, Effect, Option, Schema, Stream } from "effect";
3
3
  import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
4
4
  // src/webhook/attempt.ts
5
- /**
6
- * One attempt of a delivery that failed: `category` is SEP-3415's for it, and `final` says a
7
- * retry would not help, as for a `410 Gone` or a `413 Payload Too Large`.
8
- */
9
5
  var AttemptFailed = class extends Data.TaggedError("AttemptFailed") {};
10
6
  const timeout = Duration.seconds(5);
11
7
  const statusCategory = (status) => status >= 500 ? "http_5xx" : "http_4xx";
@@ -39,14 +35,9 @@ const sent = ({ url, subscriptionId, webhookId, body, keys }, checked, answer) =
39
35
  }))
40
36
  }), Effect.scoped);
41
37
  });
42
- /**
43
- * POSTs `body` to the callback, signed with a fresh timestamp, once `checked`, its address check,
44
- * passes, and succeeds at a 2xx without reading its body. The timeout bounds the check and the
45
- * POST together.
46
- */
47
38
  const attempt = (posting, checked) => sent(posting, checked, () => Effect.void);
48
39
  const Challenged = Schema.fromJsonString(Schema.Struct({ challenge: Schema.String }));
49
- const answerLimit = 4096;
40
+ const challengeAnswerByteLimit = 4096;
50
41
  const textOf = (response) => Effect.suspend(() => {
51
42
  const decoder = new TextDecoder();
52
43
  return response.stream.pipe(Stream.scan(() => ({
@@ -55,11 +46,7 @@ const textOf = (response) => Effect.suspend(() => {
55
46
  }), ({ bytes, text }, chunk) => ({
56
47
  bytes: bytes + chunk.length,
57
48
  text: text + decoder.decode(chunk, { stream: true })
58
- })), Stream.takeUntil(({ bytes }) => bytes > answerLimit), Stream.runLast, Effect.map((last) => Option.map(Option.filter(last, ({ bytes }) => bytes <= answerLimit), ({ text }) => text + decoder.decode())), Effect.orElseSucceed(() => Option.none()));
49
+ })), Stream.takeUntil(({ bytes }) => bytes > challengeAnswerByteLimit), Stream.runLast, Effect.map((last) => Option.map(Option.filter(last, ({ bytes }) => bytes <= challengeAnswerByteLimit), ({ text }) => text + decoder.decode())), Effect.orElseSucceed(() => Option.none()));
59
50
  });
60
- /**
61
- * `attempt` of a verification: the challenge its 2xx answer echoes, where its first 4 KiB hold
62
- * one.
63
- */
64
51
  const challenged = (posting, checked) => sent(posting, checked, (response) => Effect.map(textOf(response), (text) => Option.getOrUndefined(Option.map(Option.flatMap(text, Schema.decodeUnknownOption(Challenged)), ({ challenge }) => challenge))));
65
52
  export { AttemptFailed, attempt, challenged };
@@ -5,18 +5,12 @@ import { Clock, Effect, Option, Predicate, Schema } from "effect";
5
5
  import { HttpServerRequest, HttpServerResponse } from "effect/http";
6
6
  import { Base64, Base64Url } from "effect/encoding";
7
7
  // src/webhook/receiver.ts
8
- /** How old a delivery's `webhook-timestamp` may be, or how far ahead, before it is refused. */
9
- const tolerance = 300;
8
+ const timestampToleranceSeconds = 300;
10
9
  const dedupeWindow = 1e3;
11
10
  const Body = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Json));
12
11
  const decodeBody = Schema.decodeUnknownOption(Body);
13
12
  const gone = HttpServerResponse.empty({ status: 410 });
14
13
  const unauthorized = HttpServerResponse.empty({ status: 401 });
15
- /**
16
- * The receiver of one `Webhook.layerReceiver` at `path`: `receiving`, where each watch keeps its
17
- * place under an id and a secret of its own, and `handler`, which verifies a POST against the
18
- * secret of the watch its URL names and hands its body to that watch.
19
- */
20
14
  const makeReceiver = (path) => Effect.sync(() => {
21
15
  const places = /* @__PURE__ */ new Map();
22
16
  const register = (deliver) => Effect.acquireRelease(Effect.sync(() => {
@@ -44,7 +38,7 @@ const makeReceiver = (path) => Effect.sync(() => {
44
38
  const timestamp = Number(request.headers["webhook-timestamp"]);
45
39
  const signatures = (request.headers["webhook-signature"] ?? "").split(" ");
46
40
  const now = Math.floor((yield* Clock.currentTimeMillis) / 1e3);
47
- if (id === void 0 || !Number.isInteger(timestamp) || Math.abs(now - timestamp) > tolerance) return unauthorized;
41
+ if (id === void 0 || !Number.isInteger(timestamp) || Math.abs(now - timestamp) > timestampToleranceSeconds) return unauthorized;
48
42
  const text = yield* Effect.orElseSucceed(request.text, () => "");
49
43
  const expected = yield* signature([place.key], id, timestamp, text);
50
44
  if (!signatures.some((each) => constantTimeEqual(each, expected))) return unauthorized;
@@ -15,11 +15,8 @@ const hmac = (key, content) => Effect.promise(async () => {
15
15
  * under each key, space apart, so a receiver mid-rotation verifies under either.
16
16
  */
17
17
  const signature = (keys, id, timestamp, body) => Effect.map(Effect.forEach(keys, (key) => hmac(key, `${id}.${timestamp}.${body}`)), (signed) => signed.map((bytes) => `v1,${Base64.encode(bytes)}`).join(" "));
18
- /** `sub_` and the first 16 bytes of the SHA-256 of `key`, in hex: a subscription's id. */
19
18
  const subscriptionId = (key) => Effect.map(sha256Hex(key), (hex) => `sub_${hex.slice(0, 32)}`);
20
- /** 16 random bytes in hex, for a challenge or an envelope's `webhook-id`. */
21
19
  const randomToken = Effect.sync(() => Hex.encode(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))));
22
- /** Whether `a` and `b` are equal, in a time that does not depend on where they differ. */
23
20
  const constantTimeEqual = (a, b) => {
24
21
  const left = encoder.encode(a);
25
22
  const right = encoder.encode(b);
@@ -4,12 +4,6 @@ import { DeliveryStatus } from "../contract/subscribe.mjs";
4
4
  import { Duration, Effect, Option, Queue, Schema, Semaphore } from "effect";
5
5
  import { KeyValueStore } from "effect/persistence";
6
6
  // src/webhook/stored.ts
7
- /**
8
- * A webhook subscription as `persist` keeps it, enough to start delivering again after a
9
- * restart: its callback, event, encoded input and identity, secret, expiry, watermark and
10
- * status. Its callback and secret are decoded again as it is read, as a request's are, and its
11
- * subscriber's principal is derived again from the identity.
12
- */
13
7
  const Stored = Schema.Struct({
14
8
  url: CallbackUrl,
15
9
  event: Schema.String,
@@ -23,13 +17,7 @@ const Stored = Schema.Struct({
23
17
  const prefix = "effect-actions/webhook";
24
18
  const Index = Schema.Array(Schema.String);
25
19
  const flushTimeout = Duration.seconds(5);
26
- /**
27
- * A storage over `store`. Its writes run on a fiber of their own, never in the request or the
28
- * delivery that marked them, so a slow or failing store holds up neither: a failure is reported,
29
- * and written again with the next mark or as the layer closes.
30
- * A store whose index cannot be read fails the layer as it builds.
31
- */
32
- const makeStorage = (store) => Effect.gen(function* () {
20
+ const makeWriteBehindStorage = (store) => Effect.gen(function* () {
33
21
  const records = KeyValueStore.toSchemaStore(KeyValueStore.prefix(store, `${prefix}/`), Stored);
34
22
  const index = KeyValueStore.toSchemaStore(store, Index);
35
23
  let indexed = new Set(yield* Effect.orDie(Effect.map(index.get(prefix), Option.getOrElse(() => []))));
@@ -39,10 +27,13 @@ const makeStorage = (store) => Effect.gen(function* () {
39
27
  const listed = (next) => Effect.andThen(index.set(prefix, [...next]), Effect.sync(() => {
40
28
  indexed = next;
41
29
  }));
42
- const written = (id, record) => record === void 0 ? Effect.andThen(records.remove(id), Effect.suspend(() => indexed.has(id) ? listed(new Set([...indexed].filter((each) => each !== id))) : Effect.void)) : Effect.andThen(Effect.suspend(() => indexed.has(id) ? Effect.void : listed(/* @__PURE__ */ new Set([...indexed, id]))), records.set(id, record));
43
- const flushed = writing.withPermits(1)(Effect.suspend(() => Effect.forEach([...pending], ([id, record]) => written(id, record).pipe(Effect.andThen(Effect.sync(() => {
30
+ const removedThenUnlisted = (id) => Effect.andThen(records.remove(id), Effect.suspend(() => indexed.has(id) ? listed(new Set([...indexed].filter((each) => each !== id))) : Effect.void));
31
+ const listedThenKept = (id, record) => Effect.andThen(Effect.suspend(() => indexed.has(id) ? Effect.void : listed(/* @__PURE__ */ new Set([...indexed, id]))), records.set(id, record));
32
+ const written = (id, record) => record === void 0 ? removedThenUnlisted(id) : listedThenKept(id, record);
33
+ const clearedUnlessRemarked = (id, record) => Effect.sync(() => {
44
34
  if (pending.get(id) === record) pending.delete(id);
45
- })), Effect.catchCause(reported)), { discard: true })));
35
+ });
36
+ const flushed = writing.withPermits(1)(Effect.suspend(() => Effect.forEach([...pending], ([id, record]) => written(id, record).pipe(Effect.andThen(clearedUnlessRemarked(id, record)), Effect.catchCause(reported)), { discard: true })));
46
37
  yield* Effect.forkScoped(Effect.forever(Effect.andThen(Queue.take(marked), flushed)));
47
38
  yield* Effect.addFinalizer(() => flushed.pipe(Effect.timeout(flushTimeout), Effect.ignore));
48
39
  return {
@@ -54,4 +45,4 @@ const makeStorage = (store) => Effect.gen(function* () {
54
45
  get: (id) => pending.has(id) ? Effect.succeed(Option.fromUndefinedOr(pending.get(id))) : records.get(id)
55
46
  };
56
47
  });
57
- export { Stored, makeStorage };
48
+ export { Stored, makeWriteBehindStorage };
@@ -14,9 +14,9 @@ const minTtl = Duration.minutes(1);
14
14
  const rotationGrace = Duration.minutes(5);
15
15
  const maxBody = 262144;
16
16
  const encoder = new TextEncoder();
17
- const lastAttempts = Schedule.exponential(Duration.seconds(1)).pipe(Schedule.upTo({ times: 3 }));
17
+ const terminatedEnvelopeRetries = Schedule.exponential(Duration.seconds(1)).pipe(Schedule.upTo({ times: 3 }));
18
18
  const iso = (millis) => DateTime.formatIso(DateTime.makeUnsafe(millis));
19
- const active = (status) => status.active ? status : {
19
+ const resumedWithFreshBudget = (status) => status.active ? status : {
20
20
  ...Struct.omit(status, ["failedSince"]),
21
21
  active: true
22
22
  };
@@ -27,11 +27,6 @@ const grantOf = (ttlMs, policy) => Duration.clamp(ttlMs === null || ttlMs === vo
27
27
  const trusted = (url, prefixes) => prefixes.some(({ origin, pathname }) => url.origin === origin && (url.pathname === pathname || url.pathname.startsWith(pathname.endsWith("/") ? pathname : `${pathname}/`)));
28
28
  const snapshotOf = Context.omit(Scope.Scope, HttpServerRequest.HttpServerRequest, HttpServerRequest.ParsedSearchParams, HttpRouter.RouteContext);
29
29
  const unencoded = Effect.die(/* @__PURE__ */ new Error("A webhook subscriber's identity did not encode by its authentication's schema (give Authentication.make a schema that encodes every identity its verifier provides)"));
30
- /**
31
- * The webhook subscriptions of one `Webhook.layer`: each a worker reading its feed as the
32
- * subscriber and POSTing what it reads to the callback, until it expires, is unsubscribed, or
33
- * is refused.
34
- */
35
30
  const confirmedAt = (cursor) => Effect.tap(Deferred.make(), (confirmation) => Deferred.succeed(confirmation, {
36
31
  cursor,
37
32
  truncated: false
@@ -62,11 +57,12 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
62
57
  const locks = yield* RcMap.make({ lookup: (_id) => Semaphore.make(1) });
63
58
  const retryForMillis = Duration.toMillis(policy.retryFor);
64
59
  const failingFor = ({ status }) => Effect.map(Clock.currentTimeMillis, (now) => status.failedSince === void 0 ? 0 : now - Date.parse(status.failedSince));
60
+ const waitingAsLongAsFailing = (subscription) => Schedule.modifyDelay(Schedule.forever, () => Effect.map(failingFor(subscription), (failing) => Duration.clamp(Duration.millis(failing), {
61
+ minimum: Duration.seconds(1),
62
+ maximum: Duration.minutes(5)
63
+ })));
65
64
  const retrying = (subscription) => ({
66
- schedule: Schedule.modifyDelay(Schedule.forever, () => Effect.map(failingFor(subscription), (failing) => Duration.clamp(Duration.millis(failing), {
67
- minimum: Duration.seconds(1),
68
- maximum: Duration.minutes(5)
69
- }))),
65
+ schedule: waitingAsLongAsFailing(subscription),
70
66
  while: (failure) => failure.final ? Effect.succeed(false) : Effect.map(failingFor(subscription), (failing) => failing < retryForMillis)
71
67
  });
72
68
  const locked = (id) => (effect) => Effect.scoped(Effect.flatMap(RcMap.get(locks, id), (lock) => lock.withPermits(1)(effect)));
@@ -97,12 +93,12 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
97
93
  active: false
98
94
  };
99
95
  }), kept(subscription)), Effect.never);
100
- const abandoned = (subscription) => Effect.andThen(Effect.sync(() => {
96
+ const abandonedResettingBudget = (subscription) => Effect.andThen(Effect.sync(() => {
101
97
  subscription.status = Struct.omit(subscription.status, ["failedSince"]);
102
98
  }), kept(subscription));
103
99
  const delivered = (subscription, webhookId, body) => post(subscription, webhookId, body).pipe(Effect.tapError((failure) => recorded(subscription, failure)), Effect.retry(retrying(subscription)), Effect.matchEffect({
104
100
  onSuccess: () => Effect.as(recorded(subscription, void 0), true),
105
- onFailure: (failure) => failure.final ? Effect.as(abandoned(subscription), false) : suspended(subscription)
101
+ onFailure: (failure) => failure.final ? Effect.as(abandonedResettingBudget(subscription), false) : suspended(subscription)
106
102
  }));
107
103
  const gapped = (subscription, cursor) => Effect.flatMap(randomToken, (token) => delivered(subscription, `msg_gap_${token}`, JSON.stringify({
108
104
  type: "gap",
@@ -141,7 +137,7 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
141
137
  type: "terminated",
142
138
  error: sentError(refusal)
143
139
  })).pipe(Effect.retry({
144
- schedule: lastAttempts,
140
+ schedule: terminatedEnvelopeRetries,
145
141
  while: (failure) => !failure.final
146
142
  }), Effect.ignore));
147
143
  };
@@ -179,7 +175,7 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
179
175
  }, checkedHost(url, policy.dns)), built).pipe(Effect.mapError(({ category }) => failedCallback(feed, category)))) !== challenge) return yield* failedCallback(feed, "challenge_failed");
180
176
  });
181
177
  };
182
- const handover = (id, next, worker) => Effect.uninterruptible(Effect.gen(function* () {
178
+ const swapHeldWorker = (id, next, worker) => Effect.uninterruptible(Effect.gen(function* () {
183
179
  const previous = yield* FiberMap.get(workers, id);
184
180
  if (next === void 0) held.delete(id);
185
181
  else held.set(id, next);
@@ -197,10 +193,10 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
197
193
  key: subscription.secret.key,
198
194
  until: now + Duration.toMillis(rotationGrace)
199
195
  } },
200
- status: active(status)
196
+ status: resumedWithFreshBudget(status)
201
197
  };
202
198
  const confirmation = yield* confirmedAt(watermark);
203
- yield* handover(renewed.id, renewed, workerOf(renewed, input, watermark, confirmation));
199
+ yield* swapHeldWorker(renewed.id, renewed, workerOf(renewed, input, watermark, confirmation));
204
200
  yield* remembered(renewed, now);
205
201
  yield* kept(renewed);
206
202
  return {
@@ -262,7 +258,7 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
262
258
  watermark: record.watermark
263
259
  });
264
260
  const confirmation = yield* confirmedAt(record.watermark);
265
- yield* handover(current, subscription, record.status.active ? workerOf(subscription, input, record.watermark, confirmation) : Effect.andThen(expired(subscription), finished(subscription)));
261
+ yield* swapHeldWorker(current, subscription, record.status.active ? workerOf(subscription, input, record.watermark, confirmation) : Effect.andThen(expired(subscription), finished(subscription)));
266
262
  if (current !== id) yield* kept(subscription);
267
263
  }).pipe(Effect.catchCause(reported));
268
264
  const serve = (feeds, keyed) => Effect.gen(function* () {
@@ -279,10 +275,10 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
279
275
  if (storage === void 0 || schema === void 0) return;
280
276
  for (const id of storage.ids()) yield* locked(id)(Effect.suspend(() => held.has(id) ? Effect.void : restoredFrom(storage, feeds, keyed, schema, id)));
281
277
  });
282
- const refused = (id, cause) => Effect.gen(function* () {
278
+ const terminatedOnRefusal = (id, cause) => Effect.gen(function* () {
283
279
  const existing = held.get(id);
284
280
  if (existing !== void 0 && refusalIn(cause) !== void 0 && (yield* Clock.currentTimeMillis) < existing.expiresAt) {
285
- yield* handover(id, void 0, terminated(existing, cause));
281
+ yield* swapHeldWorker(id, void 0, terminated(existing, cause));
286
282
  yield* dropped(id);
287
283
  }
288
284
  return yield* Effect.failCause(cause);
@@ -291,7 +287,7 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
291
287
  const { feed, principal, input, delivery: { url, secret }, cursor, ttlMs } = subscribing;
292
288
  const id = yield* idOf(subscribing);
293
289
  return yield* locked(id)(Effect.gen(function* () {
294
- yield* Effect.catchCause(feed.admit(input), (cause) => refused(id, cause));
290
+ yield* Effect.catchCause(feed.admit(input), (cause) => terminatedOnRefusal(id, cause));
295
291
  const now = yield* Clock.currentTimeMillis;
296
292
  const granted = {
297
293
  secret,
@@ -317,7 +313,7 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
317
313
  yield* verify(subscription, now);
318
314
  yield* remembered(subscription, now);
319
315
  const confirmation = yield* Deferred.make();
320
- yield* handover(id, subscription, workerOf(subscription, input, cursor, confirmation));
316
+ yield* swapHeldWorker(id, subscription, workerOf(subscription, input, cursor, confirmation));
321
317
  const started = yield* Deferred.await(confirmation);
322
318
  yield* kept(subscription);
323
319
  return {
@@ -329,7 +325,7 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
329
325
  }));
330
326
  });
331
327
  const unsubscribe = (subscription) => Effect.flatMap(idOf(subscription), (id) => locked(id)(Effect.gen(function* () {
332
- if ((yield* Clock.currentTimeMillis) < (held.get(id)?.expiresAt ?? 0)) return yield* Effect.andThen(handover(id, void 0, Effect.void), dropped(id));
328
+ if ((yield* Clock.currentTimeMillis) < (held.get(id)?.expiresAt ?? 0)) return yield* Effect.andThen(swapHeldWorker(id, void 0, Effect.void), dropped(id));
333
329
  if (storage?.ids().includes(id) === true) return yield* dropped(id);
334
330
  return yield* SubscriptionError.of(subscription.feed.event.name, new NotSubscribed());
335
331
  })));
@@ -22,8 +22,6 @@ import {
22
22
  import type { Build } from "./Builds.js";
23
23
  import { BuildStore } from "./store.js";
24
24
 
25
- // DEMO ONLY: each step passes at once. A runner's steps take their time, which is why a caller
26
- // wants to see them.
27
25
  const steps = ["install", "build", "test"];
28
26
 
29
27
  export const builds = Action.implement(
@@ -32,9 +30,6 @@ export const builds = Action.implement(
32
30
  const store = yield* BuildStore;
33
31
  const events = yield* Event.Events;
34
32
 
35
- // `build.finished` is a check source over the store: write the build there first, then wake
36
- // its subscribers, who read it now rather than at their next poll. `pipeline.status` is a
37
- // current source: the notify moves its pipeline's revision, so its subscribers alone read it.
38
33
  const finished = (build: Effect.Effect<Build>) =>
39
34
  Effect.tap(build, ({ pipeline }) =>
40
35
  Effect.andThen(
@@ -46,7 +41,6 @@ export const builds = Action.implement(
46
41
  return {
47
42
  finishBuild: ({ pipeline, status }) =>
48
43
  finished(store.finish(pipeline, status, [status])),
49
- // `progress` never waits for the caller: the build runs at its own pace.
50
44
  startBuild: ({ pipeline }, { progress }) =>
51
45
  Effect.andThen(
52
46
  Effect.forEach(
@@ -90,22 +84,16 @@ export const logs = Action.implement(
90
84
  Effect.gen(function* () {
91
85
  const store = yield* BuildStore;
92
86
 
93
- // The handler returns a `Stream`, run in a scope of its own that closes when the caller
94
- // stops reading, so what it acquires is released then.
95
87
  return ({ buildId }) =>
96
88
  Stream.unwrap(
97
89
  Effect.gen(function* () {
98
90
  const member = yield* CurrentMember;
99
- // A failure before the first line, `BuildNotFound` here, fails the call as an action
100
- // answering one value fails, a 404 over HTTP; one after a line ends the stream, the
101
- // lines before it already read.
102
91
  const log = yield* store.logOf(member.pipelines, buildId);
103
92
 
104
93
  return Stream.fromIterable(log.map((line) => ({ line })));
105
94
  })
106
95
  );
107
96
  }),
108
- // Which builds a member may read is the store's check, by pipeline.
109
97
  { authorize: Action.allowAll }
110
98
  );
111
99
  ```