@gjermundgaraba/effect-actions 0.30.0 → 0.31.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 (40) hide show
  1. package/README.md +2 -2
  2. package/dist/Action.mjs +10 -11
  3. package/dist/ActionHttp.d.mts +1 -0
  4. package/dist/ActionHttp.mjs +14 -18
  5. package/dist/ActionMcp.mjs +7 -10
  6. package/dist/ActionRpc.d.mts +2 -1
  7. package/dist/ActionRpc.mjs +54 -68
  8. package/dist/ActionToolkit.mjs +4 -3
  9. package/dist/Authentication.mjs +43 -45
  10. package/dist/authentication/refusal.mjs +11 -4
  11. package/dist/cli/commands.mjs +8 -8
  12. package/dist/contract/call.mjs +1 -1
  13. package/dist/contract/callback.mjs +6 -1
  14. package/dist/contract/digest.mjs +3 -2
  15. package/dist/contract/feed.mjs +7 -5
  16. package/dist/contract/implementation.mjs +7 -17
  17. package/dist/contract/push.mjs +3 -5
  18. package/dist/contract/recent.mjs +3 -2
  19. package/dist/contract/serving.mjs +17 -17
  20. package/dist/contract/stream.d.mts +1 -1
  21. package/dist/contract/stream.mjs +14 -2
  22. package/dist/contract/subscribe.mjs +7 -2
  23. package/dist/contract/watch.mjs +4 -7
  24. package/dist/contract/webhooks.mjs +17 -6
  25. package/dist/http/client.mjs +6 -4
  26. package/dist/http/events.mjs +3 -1
  27. package/dist/http/streamed.d.mts +1 -0
  28. package/dist/http/streamed.mjs +10 -5
  29. package/dist/mcp/bridge.mjs +11 -20
  30. package/dist/mcp/client.mjs +1 -10
  31. package/dist/mcp/events.mjs +1 -1
  32. package/dist/mcp/progress.mjs +11 -1
  33. package/dist/rpc/watch.mjs +3 -5
  34. package/dist/webhook/health.mjs +25 -28
  35. package/dist/webhook/receiver.mjs +4 -7
  36. package/dist/webhook/subscriptions.mjs +11 -12
  37. package/docs/Action.md +1 -1
  38. package/docs/setup-failures.md +1 -1
  39. package/docs/setup.md +4 -4
  40. package/package.json +8 -8
@@ -177,7 +177,6 @@ const positionalOrder = (params, positional) => {
177
177
  return ordered;
178
178
  };
179
179
  const wholeInputFlag = (encoded) => Flag.String("input").pipe(Flag.withSchema(jsonOfAcceptedKindOrText(encoded)), Flag.withDescription("Whole action input as JSON; omitted, {}"), Flag.optional);
180
- const printedOutput = (action, value, render) => Effect.map(Effect.orDie(Schema.encodeEffect(Schema.toCodecJson(action.success))(value)), (encoded) => render === void 0 && SchemaAST.isVoid(action.success.ast) ? Option.none() : Option.some(render === void 0 ? JSON.stringify(encoded, null, 2) : render(value)));
181
180
  /**
182
181
  * What a command fails with when its action fails: Effect CLI's `UserError`, typed with the
183
182
  * action's failure as its `cause` and `reason`, and whose `userMessage` is its JSON, or for a
@@ -292,12 +291,13 @@ const progressLinesOf = (progress) => {
292
291
  };
293
292
  const printedOf = (action) => {
294
293
  const element = elementOf(action.success);
295
- if (element === void 0) return (value, render, print) => Effect.flatMap(printedOutput(action, value, render), Option.match({
296
- onNone: () => Effect.void,
297
- onSome: (line) => Effect.sync(() => {
298
- print(line);
299
- })
300
- }));
294
+ if (element === void 0) {
295
+ const encode = Schema.encodeEffect(Schema.toCodecJson(action.success));
296
+ const silent = SchemaAST.isVoid(action.success.ast);
297
+ return (value, render, print) => Effect.flatMap(Effect.orDie(encode(value)), (encoded) => render === void 0 && silent ? Effect.void : Effect.sync(() => {
298
+ print(render === void 0 ? JSON.stringify(encoded, null, 2) : render(value));
299
+ }));
300
+ }
301
301
  const encode = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.toCodecJson(element)));
302
302
  return (value, render, print) => Stream.runForEach(elementsOf(Effect.succeed(value)), (each) => Effect.map(Effect.orDie(encode(each)), (json) => {
303
303
  print(render === void 0 ? json : render(each));
@@ -370,4 +370,4 @@ const watchCommand = (event, watch, errors) => {
370
370
  stdout.log(line);
371
371
  })))), failing, withStderrConsole))).pipe(Command.withDescription(event.description));
372
372
  };
373
- export { UserError, command, failingAsDerived, kebab, watchCommand };
373
+ export { UserError, command, failingAsDerived, watchCommand };
@@ -38,4 +38,4 @@ const checkedStream = (action, check, send) => {
38
38
  const method = checked(action, check, (input, onProgress) => Effect.succeed(send(input, onProgress)));
39
39
  return (...args) => Stream.unwrap(method(...args));
40
40
  };
41
- export { checked, checkedStream, decodeInput, inputOf, inputParseOptions, jsonRoundTrip, onProgressOf, sendingJson, sendingValue, watchInput };
41
+ export { checked, checkedStream, decodeInput, inputParseOptions, jsonRoundTrip, sendingJson, sendingValue, watchInput };
@@ -7,6 +7,11 @@ const SigningSecret = Schema.Struct({
7
7
  key: Schema.Uint8Array
8
8
  });
9
9
  const secretPrefix = "whsec_";
10
+ const encodeBase64 = Schema.encodeSync(Schema.Uint8ArrayFromBase64);
11
+ const signingSecretOf = (key) => ({
12
+ text: `${secretPrefix}${encodeBase64(key)}`,
13
+ key
14
+ });
10
15
  const decodeBase64 = Schema.decodeUnknownOption(Schema.Uint8ArrayFromBase64);
11
16
  const keyOf = (text) => text.startsWith(secretPrefix) ? Option.filter(decodeBase64(text.slice(6)), (key) => key.length >= 24 && key.length <= 64) : Option.none();
12
17
  const WebhookSecret = Schema.String.annotate({ description: "whsec_ and the base64 of 24 to 64 random bytes, which signs each delivery." }).pipe(Schema.decodeTo(SigningSecret, SchemaTransformation.transformEffect({
@@ -19,4 +24,4 @@ const WebhookSecret = Schema.String.annotate({ description: "whsec_ and the base
19
24
  }),
20
25
  encode: ({ text }) => Effect.succeed(text)
21
26
  })));
22
- export { CallbackUrl, SigningSecret, WebhookSecret };
27
+ export { CallbackUrl, SigningSecret, WebhookSecret, signingSecretOf };
@@ -1,5 +1,6 @@
1
- import { Effect } from "effect";
1
+ import { Effect, Schema } from "effect";
2
2
  // src/contract/digest.ts
3
3
  const encoder = new TextEncoder();
4
- const sha256Hex = (text) => Effect.promise(async () => Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", encoder.encode(text))), (byte) => byte.toString(16).padStart(2, "0")).join(""));
4
+ const encodeHex = Schema.encodeSync(Schema.Uint8ArrayFromHex);
5
+ const sha256Hex = (text) => Effect.promise(async () => encodeHex(new Uint8Array(await crypto.subtle.digest("SHA-256", encoder.encode(text)))));
5
6
  export { sha256Hex };
@@ -3,7 +3,7 @@ import { Anyone } from "./caller.mjs";
3
3
  import { canonicalInput } from "./canonical.mjs";
4
4
  import { Unauthenticated } from "./errors.mjs";
5
5
  import { Events, attachmentsOf, reaches } from "./hub.mjs";
6
- import { builderLayer, memoized, notMadeHere, selectHeld } from "./implementation.mjs";
6
+ import { builderLayer, memoized, notMadeHere } from "./implementation.mjs";
7
7
  import { checkInput } from "./input-check.mjs";
8
8
  import { makeLeases } from "./lease.mjs";
9
9
  import { assertKnown } from "./names.mjs";
@@ -221,9 +221,11 @@ var EventImplementation = class EventImplementation {
221
221
  return app;
222
222
  }
223
223
  };
224
- const unkeyedHook = (surface, feeds, keyed) => keyed ? void 0 : Array.findFirst(feeds, ({ event, release }) => release !== void 0 && event.caller !== Anyone).pipe(Option.map(({ event }) => `${surface} event "${event.name}" is protected and has a subscription hook, so its authentication needs principal to tell poll subscribers apart (give Authentication.make a principal, such as (user) => user.id)`), Option.getOrUndefined);
225
224
  const eventsOf = (served) => Array.ensure(served).filter((app) => Predicate.isTagged(app, "EventImplementation"));
226
- const selectEvents = (apps, listed) => selectHeld(apps, listed, (app) => app.events, (own, app) => EventImplementation.share(own, app));
227
- const feedBuilders = (events) => events.map((app) => EventImplementation.layerOf(app));
225
+ const eventKind = {
226
+ noun: "event",
227
+ holds: (app) => app.events,
228
+ share: (own, app) => EventImplementation.share(own, app)
229
+ };
228
230
  const acquireFeeds = (events) => Effect.map(Effect.forEach(events, (app) => EventImplementation.feedsOf(app)), (feeds) => feeds.flat());
229
- export { EventImplementation, acquireFeeds, defaultNextPoll, eventsOf, feedBuilders, selectEvents, sourcesOf, unkeyedHook };
231
+ export { EventImplementation, acquireFeeds, defaultNextPoll, eventKind, eventsOf, sourcesOf };
@@ -2,7 +2,6 @@ import { Anyone, CallerKeyed } from "./caller.mjs";
2
2
  import { projectedErrors } from "./declared.mjs";
3
3
  import { Unauthenticated } from "./errors.mjs";
4
4
  import { checkInput } from "./input-check.mjs";
5
- import { assertOnce, heldOnce } from "./names.mjs";
6
5
  import { reportedTo, streamReportedTo } from "./progress.mjs";
7
6
  import { elementOf } from "./stream.mjs";
8
7
  import { Array, Cause, Context, Effect, Exit, Layer, Option, Predicate, References, Schema, Stream } from "effect";
@@ -136,7 +135,12 @@ const assertHeld = ({ why, fix, holder }, listed, held) => {
136
135
  throw new Error(`Listed in actions, but ${why}: ${markingOthers(missing, names)} (${fix}${sameName ? `; one marked (another contract) is a contract of that name ${holder}` : ""})`);
137
136
  }
138
137
  };
139
- const selectHeld = (apps, listed, holds, share) => {
138
+ const actionKind = {
139
+ noun: "action",
140
+ holds: (app) => app.actions,
141
+ share: (own, app) => Implementation.share(own, app)
142
+ };
143
+ const select = ({ holds, share }, apps, listed) => {
140
144
  if (listed === void 0) return apps;
141
145
  assertHeld(notHeld.byImplementation, listed, apps.flatMap(holds));
142
146
  return apps.flatMap((app) => {
@@ -146,24 +150,10 @@ const selectHeld = (apps, listed, holds, share) => {
146
150
  return own.length === held.length ? [app] : [share(own, app)];
147
151
  });
148
152
  };
149
- const select = (apps, listed) => selectHeld(apps, listed, (app) => app.actions, (own, app) => Implementation.share(own, app));
150
- const servedBy = (what, bound, apps, listed) => {
151
- if (listed !== void 0) assertHeld(notHeld.byBinding, listed, bound);
152
- const held = apps.flatMap((app) => app.actions);
153
- const served = select(apps, listed ?? bound.filter((action) => held.includes(action)));
154
- const actions = served.flatMap((app) => app.actions);
155
- if (actions.length === 0 && listed === void 0 && apps.length > 0) {
156
- const names = new Set(bound.map(({ name }) => name));
157
- throw new Error(`No action of these implementations is in this ${what}: ${markingOthers(held, names) || "none"} (pass an implementation of a bound action, or bind one of these)`);
158
- }
159
- assertOnce("served action", actions, heldOnce);
160
- return served;
161
- };
162
153
  const provideBuilders = (builders) => (layer) => {
163
154
  const [first, ...rest] = builders;
164
155
  return first === void 0 ? layer : Layer.provide(layer, Layer.mergeAll(first, ...rest));
165
156
  };
166
- const provideHandlers = (apps) => provideBuilders(apps.map((app) => Implementation.layerOf(app)));
167
157
  const acquire = (apps, keyed) => Effect.map(Effect.forEach(apps, (app) => Implementation.boundOf(app, keyed)), (bound) => bound.flat());
168
158
  const builtWith = (builders, acquisition) => {
169
159
  const [first, ...rest] = builders;
@@ -176,4 +166,4 @@ const builtWith = (builders, acquisition) => {
176
166
  return yield* Effect.provideContext(acquisition, context);
177
167
  });
178
168
  };
179
- export { Implementation, acquire, answered, answeringWhole, assertHeld, builderLayer, builtWith, elementsOf, markingOthers, memoized, notHeld, notMadeHere, provideBuilders, provideHandlers, select, selectHeld, servedBy, toList, uniqueKey };
169
+ export { Implementation, acquire, actionKind, answered, answeringWhole, assertHeld, builderLayer, builtWith, elementsOf, markingOthers, memoized, notHeld, notMadeHere, provideBuilders, select, toList, uniqueKey };
@@ -11,12 +11,10 @@ const PushedOf = (event) => Schema.Union([
11
11
  Checked,
12
12
  Failed
13
13
  ]);
14
- const subscriptionWith = (input) => Schema.Struct({
15
- input,
14
+ const SubscriptionOf = (event) => Schema.Struct({
15
+ input: event.input,
16
16
  cursor: Schema.NullOr(Schema.String).annotate({ description: "Where to resume: a cursor an occurrence or a page carried; null or omitted, from now." }).pipe(Schema.withDecodingDefaultKey(Effect.succeed(null)))
17
17
  });
18
- const SubscriptionOf = (event) => subscriptionWith(event.input);
19
- const Subscription = subscriptionWith(Schema.Json);
20
18
  const defaultCapacity = 16;
21
19
  const heartbeatEvery = Duration.seconds(30);
22
20
  const isFailed = Schema.is(Failed);
@@ -66,4 +64,4 @@ const queuedPush = (open, cursor, encode, { ending, positions, capacity = defaul
66
64
  }).pipe(ending, Queue.into(queue), Effect.forkScoped({ startImmediately: true }));
67
65
  return queue;
68
66
  });
69
- export { Failed, PushedOf, Subscription, SubscriptionOf, polledOn, pushed, queuedPush, readOn, refusalIn };
67
+ export { Failed, PushedOf, SubscriptionOf, polledOn, pushed, queuedPush, readOn, refusalIn };
@@ -1,11 +1,12 @@
1
1
  // src/contract/recent.ts
2
- const makeRecent = (size) => {
2
+ const keptIds = 1e3;
3
+ const makeRecent = () => {
3
4
  const ids = /* @__PURE__ */ new Set();
4
5
  return {
5
6
  has: (id) => ids.has(id),
6
7
  add: (id) => {
7
8
  ids.add(id);
8
- if (ids.size > size) ids.delete(ids.values().next().value ?? id);
9
+ if (ids.size > keptIds) ids.delete(ids.values().next().value ?? id);
9
10
  }
10
11
  };
11
12
  };
@@ -1,34 +1,33 @@
1
1
  import { Anyone, assertAuthentication } from "./caller.mjs";
2
- import { eventsOf, feedBuilders, selectEvents } from "./feed.mjs";
3
- import { Implementation, assertHeld, markingOthers, notHeld, provideBuilders, select, servedBy, toList } from "./implementation.mjs";
2
+ import { EventImplementation, eventKind, eventsOf } from "./feed.mjs";
3
+ import { Implementation, actionKind, assertHeld, markingOthers, notHeld, provideBuilders, select, toList } from "./implementation.mjs";
4
4
  import { selection } from "./listed.mjs";
5
5
  import { assertDistinct, assertOnce, heldOnce } from "./names.mjs";
6
6
  // src/contract/serving.ts
7
7
  const selectFrom = (served, actions) => {
8
8
  const listed = selection(actions);
9
9
  return {
10
- apps: select(toList(served), listed.actions),
11
- events: selectEvents(eventsOf(served), listed.events)
10
+ apps: select(actionKind, toList(served), listed.actions),
11
+ events: select(eventKind, eventsOf(served), listed.events)
12
12
  };
13
13
  };
14
- const eventsServedBy = (what, bound, served, listed) => {
15
- const apps = eventsOf(served);
14
+ const servedBy = (kind, what, bound, apps, listed) => {
15
+ const { noun, holds } = kind;
16
16
  if (listed !== void 0) assertHeld(notHeld.byBinding, listed, bound);
17
- const unbound = apps.filter((app) => !app.events.some((event) => bound.includes(event)));
18
- if (listed === void 0 && unbound.length > 0 && unbound.length === apps.length) {
17
+ const held = apps.flatMap(holds);
18
+ if (listed === void 0 && apps.length > 0 && !held.some((contract) => bound.includes(contract))) {
19
19
  const names = new Set(bound.map(({ name }) => name));
20
- throw new Error(`No event of these implementations is in this ${what}: ${markingOthers(unbound.flatMap((app) => app.events), names)} (pass an implementation of a bound event, or bind one of these)`);
20
+ throw new Error(`No ${noun} of these implementations is in this ${what}: ${markingOthers(held, names) || "none"} (pass an implementation of a bound ${noun}, or bind one of these)`);
21
21
  }
22
- const held = new Set(apps.flatMap((app) => app.events));
23
- const selected = selectEvents(apps, listed ?? bound.filter((event) => held.has(event)));
24
- assertOnce("served event", selected.flatMap((app) => app.events), heldOnce);
25
- return selected;
22
+ const served = select(kind, apps, listed ?? bound.filter((contract) => held.includes(contract)));
23
+ assertOnce(`served ${noun}`, served.flatMap(holds), heldOnce);
24
+ return served;
26
25
  };
27
26
  const servingOf = (what, binding, served, options) => {
28
27
  const listed = selection(options.actions);
29
- const apps = servedBy(what, binding.actions, toList(served), listed.actions);
28
+ const apps = servedBy(actionKind, what, binding.actions, toList(served), listed.actions);
30
29
  const actions = apps.flatMap((app) => app.actions);
31
- const events = eventsServedBy(what, binding.events, served, listed.events);
30
+ const events = servedBy(eventKind, what, binding.events, eventsOf(served), listed.events);
32
31
  const eventTypes = events.flatMap((app) => app.events);
33
32
  assertAuthentication(actions, binding.authentication);
34
33
  assertAuthentication(eventTypes, binding.authentication, "event");
@@ -41,5 +40,6 @@ const servingOf = (what, binding, served, options) => {
41
40
  authentication: [...actions, ...eventTypes].some((contract) => contract.caller !== Anyone) ? binding.authentication : void 0
42
41
  };
43
42
  };
44
- const provideServed = (served) => provideBuilders([...served.apps.map((app) => Implementation.layerOf(app)), ...feedBuilders(served.events)]);
45
- export { provideServed, selectFrom, servingOf };
43
+ const buildersOf = (apps, events = []) => [...apps.map((app) => Implementation.layerOf(app)), ...events.map((app) => EventImplementation.layerOf(app))];
44
+ const provideServed = (apps, events = []) => provideBuilders(buildersOf(apps, events));
45
+ export { buildersOf, provideServed, selectFrom, servingOf };
@@ -1,5 +1,5 @@
1
1
  import { Codec, CodecOf, Fields } from "./codec.mjs";
2
- import { Effect, Schema, Stream } from "effect";
2
+ import { Data, Effect, Schema, Stream } from "effect";
3
3
  declare const TypeId = "~effect-actions/Stream";
4
4
  /** The success of an action answering a stream: a schema of `Stream`s, holding its element's. */
5
5
  export interface StreamOf<Element extends Codec> extends Schema.declare<Stream.Stream<Element["Type"]>> {
@@ -1,5 +1,5 @@
1
1
  import { codecOf } from "./codec.mjs";
2
- import { Predicate, Schema, Stream } from "effect";
2
+ import { Data, Predicate, Schema, Stream } from "effect";
3
3
  // src/contract/stream.ts
4
4
  const TypeId = "~effect-actions/Stream";
5
5
  const streams = Schema.declare(Stream.isStream);
@@ -22,8 +22,20 @@ const Stream$1 = (element) => Schema.make(streams.ast, {
22
22
  });
23
23
  const isStreamOf = (success) => Predicate.hasProperty(success, TypeId);
24
24
  const elementOf = (success) => isStreamOf(success) ? success.element : void 0;
25
+ const Answering = Data.taggedEnum();
26
+ const answeringOf = ({ success, progress }) => {
27
+ const element = elementOf(success);
28
+ if (element !== void 0) return Answering.Elements({
29
+ element,
30
+ progress
31
+ });
32
+ return progress === void 0 ? Answering.Value({ success }) : Answering.Progressed({
33
+ success,
34
+ progress
35
+ });
36
+ };
25
37
  const toolSuccessOf = (success) => {
26
38
  const element = elementOf(success);
27
39
  return element === void 0 ? success : Schema.Array(element);
28
40
  };
29
- export { Stream$1 as Stream, elementOf, toolSuccessOf };
41
+ export { Answering, Stream$1 as Stream, answeringOf, elementOf, toolSuccessOf };
@@ -1,8 +1,13 @@
1
1
  import { CallbackUrl, WebhookSecret } from "./callback.mjs";
2
- import { CallbackCategory } from "../Event.mjs";
2
+ import { CallbackCategory, SubscriptionError, Unsupported } from "../Event.mjs";
3
3
  import { SubscriptionOf } from "./push.mjs";
4
4
  import { Schema, Struct } from "effect";
5
5
  // src/contract/subscribe.ts
6
+ /** The error for `event` that is not delivered by `mode` where it is asked for. */
7
+ const deliveryUnsupported = (event, mode) => SubscriptionError.of(event, new Unsupported({
8
+ feature: "deliveryMode",
9
+ value: mode
10
+ }));
6
11
  const WebhookCallback = Schema.Struct({
7
12
  url: CallbackUrl,
8
13
  secret: WebhookSecret
@@ -35,4 +40,4 @@ const Subscribed = Schema.Struct({
35
40
  truncated: Schema.Boolean,
36
41
  deliveryStatus: Schema.optional(DeliveryStatus)
37
42
  });
38
- export { DeliveryStatus, Subscribed, WebhookCallback, WebhookCancellationOf, WebhookSubscriptionOf, WebhookTarget, webhookFields };
43
+ export { DeliveryStatus, Subscribed, WebhookCallback, WebhookCancellationOf, WebhookSubscriptionOf, WebhookTarget, deliveryUnsupported, webhookFields };
@@ -1,9 +1,10 @@
1
1
  import { CallbackUrl } from "./callback.mjs";
2
- import { SubscriptionError, Unsupported } from "../Event.mjs";
2
+ import { SubscriptionError } from "../Event.mjs";
3
3
  import { Checked, Gap } from "./occurrence.mjs";
4
4
  import { paged } from "./pages.mjs";
5
5
  import { watchParameter } from "./receiving.mjs";
6
6
  import { makeRecent } from "./recent.mjs";
7
+ import { deliveryUnsupported } from "./subscribe.mjs";
7
8
  import { Cause, Clock, Duration, Effect, Predicate, Queue, Schedule, Schema, Stream } from "effect";
8
9
  // src/contract/watch.ts
9
10
  const reconnectDelay = Duration.seconds(1);
@@ -11,7 +12,6 @@ const maxReconnectDelay = Duration.seconds(30);
11
12
  const afterFailures = (transient) => Schedule.min([Schedule.exponential(reconnectDelay), Schedule.spaced(maxReconnectDelay)]).pipe(Schedule.setInputType(), Schedule.while(({ input }) => transient(input)), Schedule.tap(({ input, duration }) => Effect.logWarning(`A watch reconnects in ${Duration.format(duration)} after a failure`, input)));
12
13
  const isSubscriptionError = Schema.is(SubscriptionError);
13
14
  const pushRefused = Predicate.compose(isSubscriptionError, ({ reason }) => Predicate.isTagged(reason, "Unsupported") && reason.feature === "deliveryMode" && reason.value === "push");
14
- const dedupeWindow = 1e3;
15
15
  const capacity = 16;
16
16
  const unsubscribeTimeout = Duration.seconds(5);
17
17
  const delivered = (webhook, request, received, cursor) => {
@@ -42,10 +42,7 @@ const watching = (transport, { cursor: given, mode, resume } = {}) => {
42
42
  const polled = (cursor) => reconnecting((at) => paged(transport.poll, at), cursor);
43
43
  const webhooked = ({ baseUrl, ttl }, cursor) => Stream.unwrap(Effect.gen(function* () {
44
44
  const { webhook } = transport;
45
- if (webhook === void 0) return yield* SubscriptionError.of(transport.name, new Unsupported({
46
- feature: "deliveryMode",
47
- value: "webhook"
48
- }));
45
+ if (webhook === void 0) return yield* deliveryUnsupported(transport.name, "webhook");
49
46
  const base = yield* Schema.decodeEffect(CallbackUrl)(baseUrl);
50
47
  const receiving = yield* webhook.receiver;
51
48
  const received = yield* Queue.unbounded();
@@ -63,7 +60,7 @@ const watching = (transport, { cursor: given, mode, resume } = {}) => {
63
60
  return reconnecting((at) => delivered(webhook, request, received, at), cursor);
64
61
  }));
65
62
  return Stream.suspend(() => {
66
- const seen = makeRecent(dedupeWindow);
63
+ const seen = makeRecent();
67
64
  let keptOnNextPull = null;
68
65
  const keep = (cursor) => cursor === null || resume === void 0 ? Effect.void : resume.store.set(resume.key, cursor);
69
66
  const fresh = (eventId) => {
@@ -1,5 +1,6 @@
1
1
  import { Anyone, isNamed } from "./caller.mjs";
2
- import { SubscriptionError, Unsupported } from "../Event.mjs";
2
+ import { acquireFeeds } from "./feed.mjs";
3
+ import { deliveryUnsupported } from "./subscribe.mjs";
3
4
  import { Context, Effect, Option } from "effect";
4
5
  // src/contract/webhooks.ts
5
6
  /**
@@ -24,10 +25,7 @@ const servedWebhooks = (feeds, keyed) => Effect.gen(function* () {
24
25
  });
25
26
  const webhookSubscriber = (feed, keyed, webhooks) => {
26
27
  const { event } = feed;
27
- if (Option.isNone(webhooks) || !isNamed(keyed) || !isProtected(event)) return Effect.fail(SubscriptionError.of(event.name, new Unsupported({
28
- feature: "deliveryMode",
29
- value: "webhook"
30
- })));
28
+ if (Option.isNone(webhooks) || !isNamed(keyed) || !isProtected(event)) return Effect.fail(deliveryUnsupported(event.name, "webhook"));
31
29
  const service = webhooks.value;
32
30
  return Effect.map(Effect.service(event.caller), (identity) => ({
33
31
  webhooks: service,
@@ -39,4 +37,17 @@ const webhookSubscriber = (feed, keyed, webhooks) => {
39
37
  principal: keyed.principal(identity)
40
38
  }));
41
39
  };
42
- export { Webhooks, offersWebhook, servedWebhooks, webhookSubscriber };
40
+ /**
41
+ * The feeds of `events` a surface's layer serves, and the webhooks it offers, served: run as the
42
+ * layer builds, dying where a protected event's subscription hook has no principal to key it by.
43
+ */
44
+ const servingFeeds = Effect.fnUntraced(function* (surface, events, keyed) {
45
+ const feeds = yield* acquireFeeds(events);
46
+ const unkeyed = keyed?.principal === void 0 ? feeds.find(({ event, release }) => release !== void 0 && event.caller !== Anyone) : void 0;
47
+ if (unkeyed !== void 0) return yield* Effect.die(/* @__PURE__ */ new Error(`${surface} event "${unkeyed.event.name}" is protected and has a subscription hook, so its authentication needs principal to tell poll subscribers apart (give Authentication.make a principal, such as (user) => user.id)`));
48
+ return {
49
+ feeds,
50
+ ...yield* servedWebhooks(feeds, keyed)
51
+ };
52
+ });
53
+ export { Webhooks, offersWebhook, servedWebhooks, servingFeeds, webhookSubscriber };
@@ -1,5 +1,5 @@
1
1
  import { checked, checkedStream, sendingValue, watchInput } from "../contract/call.mjs";
2
- import { elementOf } from "../contract/stream.mjs";
2
+ import { Answering, answeringOf } from "../contract/stream.mjs";
3
3
  import { watching } from "../contract/watch.mjs";
4
4
  import { readElements, readWithProgress } from "./streamed.mjs";
5
5
  import { transportOf } from "./watch.mjs";
@@ -19,9 +19,11 @@ const nativeOf = (http, httpClient, baseUrl) => HttpApiClient.makeWith(http.api,
19
19
  });
20
20
  const actionMethodOf = (action, native) => {
21
21
  const method = methodOf(native, action.name, "action");
22
- if (elementOf(action.success) !== void 0) return checkedStream(action, sendingValue, (payload, onProgress) => Stream.unwrap(Effect.map(method({ payload }), (answer) => readElements(answer, onProgress))));
23
- if (action.progress === void 0) return checked(action, sendingValue, (payload) => method({ payload }));
24
- return checked(action, sendingValue, (payload, onProgress) => Effect.flatMap(method({ payload }), (answer) => readWithProgress(answer, onProgress)));
22
+ return Answering.$match(answeringOf(action), {
23
+ Value: () => checked(action, sendingValue, (payload) => method({ payload })),
24
+ Progressed: () => checked(action, sendingValue, (payload, onProgress) => Effect.flatMap(method({ payload }), (answer) => readWithProgress(answer, onProgress))),
25
+ Elements: () => checkedStream(action, sendingValue, (payload, onProgress) => Stream.unwrap(Effect.map(method({ payload }), (answer) => readElements(answer, onProgress))))
26
+ });
25
27
  };
26
28
  const sendersWith = (http, httpClient, baseUrl) => Effect.gen(function* () {
27
29
  const native = yield* nativeOf(http, acceptingStreams(httpClient), baseUrl);
@@ -7,6 +7,7 @@ import { PushedOf, SubscriptionOf, queuedPush } from "../contract/push.mjs";
7
7
  import { declared } from "../contract/status.mjs";
8
8
  import { Subscribed, WebhookCancellationOf, WebhookSubscriptionOf } from "../contract/subscribe.mjs";
9
9
  import { webhookSubscriber } from "../contract/webhooks.mjs";
10
+ import { acceptsEventStream } from "./streamed.mjs";
10
11
  import { Effect, Function, Schema, Stream } from "effect";
11
12
  import { HttpServerRequest } from "effect/http";
12
13
  import { HttpApiEndpoint, HttpApiSchema, OpenApi } from "effect/http-api";
@@ -62,7 +63,8 @@ const webhookAnswers = (feed, authentication, webhooks) => {
62
63
  const answering = (feed, authentication) => {
63
64
  const encode = Schema.encodeEffect(Schema.toCodecJson(PushedOf(feed.event)));
64
65
  return ({ payload: { input, cursor } }) => Effect.gen(function* () {
65
- if (((yield* HttpServerRequest.HttpServerRequest).headers["accept"] ?? "").includes("text/event-stream")) {
66
+ const request = yield* HttpServerRequest.HttpServerRequest;
67
+ if (acceptsEventStream(request)) {
66
68
  const open = yield* feed.stream(input);
67
69
  return Stream.fromQueue(yield* queuedPush(open, cursor, encode, {
68
70
  ending: Function.identity,
@@ -4,6 +4,7 @@ import { ErasedValue } from "../contract/implementation.mjs";
4
4
  import "../contract/progress.mjs";
5
5
  import { StreamOf } from "../contract/stream.mjs";
6
6
  import { Effect, Schema, Stream } from "effect";
7
+ import { HttpServerRequest } from "effect/http";
7
8
  import { HttpApiSchema } from "effect/http-api";
8
9
  interface Sent {
9
10
  readonly event: "progress" | "element" | "final";
@@ -1,7 +1,7 @@
1
1
  import { elementsOf } from "../contract/implementation.mjs";
2
2
  import { Progressed, answerFrom, elementsFrom } from "../contract/progress.mjs";
3
3
  import { concealed } from "../contract/reported.mjs";
4
- import { Cause, Effect, ErrorReporter, Queue, Schema, Stream } from "effect";
4
+ import { Cause, Duration, Effect, ErrorReporter, Queue, Schema, Stream } from "effect";
5
5
  import { HttpServerRequest } from "effect/http";
6
6
  import { HttpApiSchema } from "effect/http-api";
7
7
  // src/http/streamed.ts
@@ -10,14 +10,17 @@ const eventOf = (event, data) => Schema.Struct({
10
10
  event: Schema.Literal(event),
11
11
  data: Schema.fromJsonString(Schema.toCodecJson(data))
12
12
  });
13
+ const keepAliveEvery = Duration.seconds(15);
13
14
  const answeredWithProgress = (success) => HttpApiSchema.isNoContent(success.ast) ? HttpApiSchema.NoContent : success;
14
15
  const progressStreamOf = (progress, success, errors) => HttpApiSchema.StreamSse({
15
16
  events: Schema.Union([eventOf("progress", progress), eventOf("final", success)]),
16
- error: Schema.Union(errors)
17
+ error: Schema.Union(errors),
18
+ keepAlive: keepAliveEvery
17
19
  });
18
20
  const elementStreamOf = (element, progress, errors) => HttpApiSchema.StreamSse({
19
21
  events: Schema.Union(progress === void 0 ? [eventOf("element", element)] : [eventOf("element", element), eventOf("progress", progress)]),
20
- error: Schema.Union(errors)
22
+ error: Schema.Union(errors),
23
+ keepAlive: keepAliveEvery
21
24
  });
22
25
  const gatedOnFirst = (sent) => Effect.map(Effect.catchIf(Queue.take(sent), Cause.isDone, () => Effect.undefined), (first) => first === void 0 ? Stream.empty : Stream.concat(Stream.make(first), Stream.fromQueue(sent)));
23
26
  const streamed = (answer) => Effect.gen(function* () {
@@ -41,9 +44,11 @@ const checkedBy = (schema) => {
41
44
  const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(schema));
42
45
  return (data) => Effect.orDie(encode(data));
43
46
  };
47
+ /** Whether `request` asks for an SSE stream, `text/event-stream` among whatever else it accepts. */
48
+ const acceptsEventStream = (request) => (request.headers["accept"] ?? "").includes("text/event-stream");
44
49
  const answeringWithProgress = (success, run) => {
45
50
  const check = checkedBy(success);
46
- return (payload) => Effect.flatMap(HttpServerRequest.HttpServerRequest, (request) => (request.headers["accept"] ?? "").includes("text/event-stream") ? streamed((reporting, send) => run(payload, reporting).pipe(Effect.tap(check), Effect.flatMap((data) => send({
51
+ return (payload) => Effect.flatMap(HttpServerRequest.HttpServerRequest, (request) => acceptsEventStream(request) ? streamed((reporting, send) => run(payload, reporting).pipe(Effect.tap(check), Effect.flatMap((data) => send({
47
52
  event: "final",
48
53
  data
49
54
  })))) : run(payload));
@@ -63,4 +68,4 @@ const answeredWithout = /* @__PURE__ */ new Error("A route of an action declarin
63
68
  const sentFrom = (answer) => Stream.isStream(answer) ? Stream.map(answer, progressedOf) : Stream.die(answeredWithout);
64
69
  const readWithProgress = (answer, onProgress) => answerFrom(sentFrom(answer), onProgress);
65
70
  const readElements = (answer, onProgress) => elementsFrom(sentFrom(answer), onProgress);
66
- export { answeredWithProgress, answeringElements, answeringWithProgress, elementStreamOf, progressStreamOf, readElements, readWithProgress };
71
+ export { acceptsEventStream, answeredWithProgress, answeringElements, answeringWithProgress, elementStreamOf, progressStreamOf, readElements, readWithProgress };
@@ -1,14 +1,14 @@
1
- import { promote } from "../authentication/provider.mjs";
2
- import { recordStepUp } from "../authentication/refusal.mjs";
1
+ import { asCaller } from "../authentication/refusal.mjs";
3
2
  import { inputParseOptions } from "../contract/call.mjs";
4
- import { Anyone, principalOf } from "../contract/caller.mjs";
3
+ import { principalOf } from "../contract/caller.mjs";
5
4
  import { sentError } from "../contract/codes.mjs";
6
- import { NotServed, SubscriptionError, Unsupported } from "../Event.mjs";
7
- import { acquireFeeds, unkeyedHook } from "../contract/feed.mjs";
5
+ import { NotServed, SubscriptionError } from "../Event.mjs";
6
+ import { acquireFeeds } from "../contract/feed.mjs";
8
7
  import { encodeUntaggedOf } from "../contract/occurrence.mjs";
9
8
  import { pushed, refusalIn } from "../contract/push.mjs";
10
9
  import { reported } from "../contract/reported.mjs";
11
- import { Webhooks, offersWebhook, servedWebhooks, webhookSubscriber } from "../contract/webhooks.mjs";
10
+ import { deliveryUnsupported } from "../contract/subscribe.mjs";
11
+ import { Webhooks, offersWebhook, webhookSubscriber } from "../contract/webhooks.mjs";
12
12
  import { Active, EventsError, Failed, Heartbeat, Notifications, Occurred, Requests, Terminated, codes, extension, subscriptionIdKey } from "./events.mjs";
13
13
  import { isObjectSchema, toolJsonSchema } from "./protocol.mjs";
14
14
  import { Cause, Context, Duration, Effect, Exit, Match, Option, Predicate, Result, Schema } from "effect";
@@ -70,11 +70,6 @@ const servedOf = (feed, delivery) => {
70
70
  }
71
71
  };
72
72
  };
73
- const refuseUnservable = ({ events, authentication }) => authentication === void 0 ? Effect.void : Effect.flatMap(acquireFeeds(events), (feeds) => {
74
- const refusal = unkeyedHook("MCP", feeds, authentication.principal !== void 0);
75
- return refusal === void 0 ? Effect.void : Effect.die(new Error(refusal));
76
- });
77
- const serveWebhooks = (serving) => Effect.asVoid(Effect.flatMap(acquireFeeds(serving.events), (feeds) => servedWebhooks(feeds, serving.authentication)));
78
73
  const delivered = ({ send, clientId, requestId, wire, _meta: resultMeta }, run) => {
79
74
  const notify = (rpc, payload) => send("2026-07-28", clientId, {
80
75
  tag: rpc._tag,
@@ -135,7 +130,6 @@ const delivered = ({ send, clientId, requestId, wire, _meta: resultMeta }, run)
135
130
  };
136
131
  const withEvents = (base, serving) => {
137
132
  const { authentication } = serving;
138
- const asSubscriber = (event, run) => authentication === void 0 || event.caller === Anyone ? run : recordStepUp(promote(authentication, run));
139
133
  const installHandlers = (core, lifecycle, target) => Effect.gen(function* () {
140
134
  const feeds = yield* acquireFeeds(serving.events);
141
135
  const built = yield* Effect.context();
@@ -153,7 +147,7 @@ const withEvents = (base, serving) => {
153
147
  const found = served.get(name);
154
148
  return found === void 0 ? Effect.fail(new EventsError(sentError(SubscriptionError.of(name, new NotServed())))) : Effect.succeed(found);
155
149
  };
156
- const asWebhook = (feed, run) => Effect.catchCause(asSubscriber(feed.event, Effect.flatMap(webhookSubscriber(feed, authentication, webhooks), run)), (cause) => Effect.flatMap(wireErrorOf(cause), Effect.fail));
150
+ const asWebhook = (feed, run) => Effect.catchCause(asCaller(authentication, feed.event, Effect.flatMap(webhookSubscriber(feed, authentication, webhooks), run)), (cause) => Effect.flatMap(wireErrorOf(cause), Effect.fail));
157
151
  const fromBuilt = (handled) => Effect.updateContext(handled, (request) => Context.merge(built, request));
158
152
  const handlers = Requests.of({
159
153
  "events/list": () => Effect.map(meta, (_meta) => ({
@@ -166,7 +160,7 @@ const withEvents = (base, serving) => {
166
160
  const { feed, decode, wire } = yield* servedNamed(name);
167
161
  const input = yield* decode(args);
168
162
  const { page, events } = yield* Effect.gen(function* () {
169
- const polled = yield* asSubscriber(feed.event, Effect.flatMap(principalOf(feed.event, authentication), (subscriber) => feed.poll(input, cursor ?? null, {
163
+ const polled = yield* asCaller(authentication, feed.event, Effect.flatMap(principalOf(feed.event, authentication), (subscriber) => feed.poll(input, cursor ?? null, {
170
164
  subscriber,
171
165
  maxEvents
172
166
  })));
@@ -189,17 +183,14 @@ const withEvents = (base, serving) => {
189
183
  yield* routedTo(name);
190
184
  const { feed, decode, wire } = yield* servedNamed(name);
191
185
  const input = yield* decode(args);
192
- if (send === void 0) return yield* new EventsError(sentError(SubscriptionError.of(name, new Unsupported({
193
- feature: "deliveryMode",
194
- value: "push"
195
- }))));
186
+ if (send === void 0) return yield* new EventsError(sentError(deliveryUnsupported(name, "push")));
196
187
  return yield* delivered({
197
188
  send,
198
189
  clientId: client.id,
199
190
  requestId,
200
191
  wire,
201
192
  _meta: yield* meta
202
- }, (deliver) => asSubscriber(feed.event, Effect.flatMap(feed.stream(input), (open) => pushed(open, cursor ?? null, deliver, { positions: "heartbeat" }))));
193
+ }, (deliver) => asCaller(authentication, feed.event, Effect.flatMap(feed.stream(input), (open) => pushed(open, cursor ?? null, deliver, { positions: "heartbeat" }))));
203
194
  }).pipe(fromBuilt),
204
195
  "events/subscribe": ({ name, arguments: args, delivery: { url, secret }, cursor, ttlMs }) => Effect.gen(function* () {
205
196
  yield* routedTo(name);
@@ -259,4 +250,4 @@ const withEvents = (base, serving) => {
259
250
  installHandlers
260
251
  };
261
252
  };
262
- export { eventSchemasOf, refuseUnservable, serveWebhooks, withEvents };
253
+ export { eventSchemasOf, withEvents };
@@ -5,9 +5,9 @@ import { Refusal } from "../contract/errors.mjs";
5
5
  import { liftOf } from "../contract/lift.mjs";
6
6
  import { split } from "../contract/listed.mjs";
7
7
  import { assertOnce } from "../contract/names.mjs";
8
- import { progressSink } from "../contract/progress.mjs";
9
8
  import { elementOf } from "../contract/stream.mjs";
10
9
  import { watching } from "../contract/watch.mjs";
10
+ import { decodedSink } from "./progress.mjs";
11
11
  import { defaultPath, unliftedFrom } from "./protocol.mjs";
12
12
  import { NoReply, NoStructuredContent, ProtocolError, StatusError, UndeclaredError, bodyOf, callError, failWith } from "./reply.mjs";
13
13
  import { request } from "./request.mjs";
@@ -22,15 +22,6 @@ const ToolCallReply = Schema.Union([Schema.Struct({ result: McpSchema.CallToolRe
22
22
  message: Schema.String
23
23
  }) })]);
24
24
  const decodeReply = Schema.decodeUnknownOption(Schema.fromJsonString(ToolCallReply));
25
- const decodedSink = (progress, onProgress) => {
26
- const sink = progressSink(onProgress);
27
- if (progress === void 0 || sink === void 0) return;
28
- const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(progress));
29
- return { progress: (json) => Effect.matchEffect(decode(json), {
30
- onFailure: (error) => Effect.logWarning("A progress value did not decode", error),
31
- onSuccess: sink.progress
32
- }) };
33
- };
34
25
  const callTool = (client, url, action, success, refusedWith, input, sink) => {
35
26
  const { name } = action;
36
27
  const lift = liftOf(success);
@@ -133,4 +133,4 @@ const Terminated = Rpc.make("notifications/events/terminated", { payload: {
133
133
  } });
134
134
  const Requests = RpcGroup.make(ListEvents, PollEvents, StreamEvents, SubscribeEvents, UnsubscribeEvents);
135
135
  const Notifications = RpcGroup.make(Active, Occurred, Heartbeat, Failed, Terminated);
136
- export { Active, EventDescriptor, EventsError, Failed, Heartbeat, ListEvents, Notifications, Occurred, PollEvents, Requests, StreamEvents, SubscribeEvents, Terminated, UnsubscribeEvents, WireError, WireOccurrence, codes, extension, subscriptionIdKey };
136
+ export { Active, EventDescriptor, EventsError, Failed, Heartbeat, Notifications, Occurred, PollEvents, Requests, SubscribeEvents, Terminated, UnsubscribeEvents, WireError, WireOccurrence, codes, extension, subscriptionIdKey };
@@ -1,3 +1,4 @@
1
+ import { progressSink } from "../contract/progress.mjs";
1
2
  import { Effect, Option, Schema } from "effect";
2
3
  import { McpSchema } from "effect/ai";
3
4
  // src/mcp/progress.ts
@@ -24,4 +25,13 @@ const Notified = Schema.fromJsonString(Schema.Struct({
24
25
  }));
25
26
  const notifiedOf = Schema.decodeUnknownOption(Notified);
26
27
  const progressOf = (data) => Option.map(notifiedOf(data), (notified) => notified.params._meta[progressKey]);
27
- export { progressKey, progressNotifier, progressOf };
28
+ const decodedSink = (progress, onProgress) => {
29
+ const sink = progressSink(onProgress);
30
+ if (progress === void 0 || sink === void 0) return;
31
+ const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(progress));
32
+ return { progress: (json) => Effect.matchEffect(decode(json), {
33
+ onFailure: (error) => Effect.logWarning("A progress value did not decode", error),
34
+ onSuccess: sink.progress
35
+ }) };
36
+ };
37
+ export { decodedSink, progressNotifier, progressOf };