@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
package/README.md CHANGED
@@ -76,10 +76,10 @@ Effect.gen(function* () {
76
76
  ## Install
77
77
 
78
78
  ```sh
79
- pnpm add @gjermundgaraba/effect-actions effect@~4.1.1
79
+ pnpm add @gjermundgaraba/effect-actions effect@~4.1.3
80
80
  ```
81
81
 
82
- It needs TypeScript 7 or newer and is ESM only ([docs/setup.md](docs/setup.md#install)). Add `@effect/platform-node@~4.1.1` to serve or run a CLI from Node, and `@types/node` for its `node:` imports. Every module is a subpath import (`.../Action`, `.../ActionHttp`, ...); there is no package root, so a contracts-only bundle never loads a server.
82
+ It needs TypeScript 7 or newer and is ESM only ([docs/setup.md](docs/setup.md#install)). Add `@effect/platform-node@~4.1.3` to serve or run a CLI from Node, and `@types/node` for its `node:` imports. Every module is a subpath import (`.../Action`, `.../ActionHttp`, ...); there is no package root, so a contracts-only bundle never loads a server.
83
83
 
84
84
  ## Examples
85
85
 
package/dist/Action.mjs CHANGED
@@ -1,19 +1,19 @@
1
1
  import { authorizerOf } from "./contract/authorizer.mjs";
2
- import { inputOf, jsonRoundTrip, onProgressOf, watchInput } from "./contract/call.mjs";
2
+ import { checked, checkedStream, jsonRoundTrip, watchInput } from "./contract/call.mjs";
3
3
  import { Anyone, assertCaller } from "./contract/caller.mjs";
4
4
  import { codecOf } from "./contract/codec.mjs";
5
5
  import { assertDistinctTags, errorList, projectedErrors } from "./contract/declared.mjs";
6
- import { BuiltIn, Forbidden, InvalidInput, Refusal, Unauthenticated } from "./contract/errors.mjs";
7
6
  import { NotServed, SubscriptionError } from "./Event.mjs";
8
- import { acquireFeeds, eventsOf, feedBuilders } from "./contract/feed.mjs";
7
+ import { acquireFeeds, eventsOf } from "./contract/feed.mjs";
9
8
  import { Idempotency, keyed, layerIdempotency } from "./contract/idempotency.mjs";
10
- import { Implementation, acquire, builtWith, elementsOf, memoized, provideBuilders, toList, uniqueKey } from "./contract/implementation.mjs";
9
+ import { Implementation, acquire, builtWith, elementsOf, memoized, toList, uniqueKey } from "./contract/implementation.mjs";
11
10
  import { assertKnown, assertName, assertOnce, heldOnce } from "./contract/names.mjs";
12
11
  import { progressSink } from "./contract/progress.mjs";
13
12
  import { polledOn, queuedPush, readOn } from "./contract/push.mjs";
14
- import { selectFrom } from "./contract/serving.mjs";
13
+ import { buildersOf, provideServed, selectFrom } from "./contract/serving.mjs";
15
14
  import { Stream, elementOf } from "./contract/stream.mjs";
16
15
  import { watching } from "./contract/watch.mjs";
16
+ import { BuiltIn, Forbidden, InvalidInput, Refusal, Unauthenticated } from "./contract/errors.mjs";
17
17
  import { Image } from "./contract/media.mjs";
18
18
  import { InputCheck } from "./contract/input-check.mjs";
19
19
  import { Array as Array$1, Cause, Effect, Function, Layer, Predicate, Schema, Stream as Stream$1 } from "effect";
@@ -91,7 +91,7 @@ function implement(actions, handlers, options) {
91
91
  return new Implementation(listed, memoized(recorded), authorizer);
92
92
  }
93
93
  function layer(implementations) {
94
- return Layer.empty.pipe(provideBuilders([...toList(implementations).map((app) => Implementation.layerOf(app)), ...feedBuilders(eventsOf(implementations))]));
94
+ return Layer.empty.pipe(provideServed(toList(implementations), eventsOf(implementations)));
95
95
  }
96
96
  const received = (schema) => {
97
97
  const sent = jsonRoundTrip(schema);
@@ -101,15 +101,14 @@ const mapFailuresInPlace = (cause, failure) => Effect.map(Effect.forEach(cause.r
101
101
  onFailure: (refused) => Cause.combine(Cause.die(refused), Cause.die(reason.error)),
102
102
  onSuccess: (decoded) => Cause.fail(Predicate.isError(reason.error) && Predicate.isError(decoded) ? Object.assign(decoded, { stack: reason.error.stack }) : decoded)
103
103
  }).pipe(Effect.map((mapped) => Cause.annotate(mapped, Cause.reasonAnnotations(reason)))) : Effect.succeed(Cause.fromReasons([reason]))), (causes) => Cause.fromReasons(causes.flatMap(({ reasons }) => reasons)));
104
+ const receivedInput = (action) => received(action.input);
104
105
  const methodOf = (action, run) => {
105
- const input = received(action.input);
106
106
  const element = elementOf(action.success);
107
107
  const success = received(element ?? action.success);
108
108
  const failure = received(Schema.Union(projectedErrors(action)));
109
109
  const declared = (cause) => Effect.flatMap(mapFailuresInPlace(cause, failure), Effect.failCause);
110
- const called = (args) => inputOf(action, args).pipe(Effect.flatMap(input), Effect.mapError(InvalidInput.fromSchemaError), Effect.map((value) => run(value, progressSink(onProgressOf(args)))));
111
- if (element !== void 0) return (...args) => Stream$1.unwrap(Effect.map(called(args), elementsOf)).pipe(Stream$1.catchCause((cause) => Stream$1.fromEffect(declared(cause))), Stream$1.mapEffect((value) => Effect.orDie(success(value))));
112
- return (...args) => called(args).pipe(Effect.flatMap((answer) => Effect.catchCause(answer, declared)), Effect.flatMap((value) => Effect.orDie(success(value))));
110
+ if (element !== void 0) return checkedStream(action, receivedInput, (input, onProgress) => elementsOf(run(input, progressSink(onProgress))).pipe(Stream$1.catchCause((cause) => Stream$1.fromEffect(declared(cause))), Stream$1.mapEffect((value) => Effect.orDie(success(value)))));
111
+ return checked(action, receivedInput, (input, onProgress) => Effect.catchCause(run(input, progressSink(onProgress)), declared).pipe(Effect.flatMap((value) => Effect.orDie(success(value)))));
113
112
  };
114
113
  const watcherOf = (feeds) => (event, input, options) => {
115
114
  const feed = feeds.find((held) => held.event === event);
@@ -131,7 +130,7 @@ function client(served, options) {
131
130
  const { apps, events } = selectFrom(served, options?.actions);
132
131
  assertOnce("action", apps.flatMap((app) => app.actions), heldOnce);
133
132
  assertOnce("event", events.flatMap((app) => app.events), heldOnce);
134
- return Effect.map(builtWith([...apps.map((app) => Implementation.layerOf(app)), ...feedBuilders(events)], Effect.all([acquire(apps, void 0), acquireFeeds(events)])), ([bound, feeds]) => ({
133
+ return Effect.map(builtWith(buildersOf(apps, events), Effect.all([acquire(apps, void 0), acquireFeeds(events)])), ([bound, feeds]) => ({
135
134
  ...Object.fromEntries(bound.map(([action, run]) => [action.name, methodOf(action, run)])),
136
135
  ...feeds.length === 0 ? {} : { watch: watcherOf(feeds) }
137
136
  }));
@@ -162,6 +162,7 @@ export declare function make<const Contracts extends ReadonlyArray<Any$1 | Any$2
162
162
  * - An action declaring `progress` answers a request whose `Accept` names `text/event-stream`, whatever else it names, with an SSE stream, listed in OpenAPI: a `progress` event for each value, its data the value's JSON, then one `final` event holding the answer's JSON, `null` for none; without that `Accept` it answers as any action, its progress dropped.
163
163
  * - An action answering a stream, `Action.Stream`, answers an SSE stream alone, whatever `Accept` says: an `element` event for each element, its data the element's JSON, and a `progress` event for each value where it declares `progress`; a stream of none answers a 200 with no event. A failure before the first event answers its status; one after ends the stream as Effect's stream failure event, a defect as `Internal server error`.
164
164
  * - The stream starts with the call's first event, so a failure before it, a refusal included, answers as it would without the stream; a declared failure after it ends the stream with Effect's `effect/http-api/stream/failure` event, reported as `Info` as without the stream, and a defect or an answer that does not encode with one saying `Internal server error`, its cause logged and reported.
165
+ * - An action's SSE stream writes a `: keepalive` comment every 15 seconds from its first event until it ends, events or not, which SSE clients skip, so a proxy closing a silent response keeps it open through a slow step; before the first event no response has started, so a proxy timing out a response's start still ends a call silent that long.
165
166
  * - A body that is not JSON is a 400 `InvalidInput`; a request with no `Content-Type` a 415 `Unsupported content-type: none`, one with another type Effect's own 415; each after authentication on a protected route.
166
167
  * - A defect, an undeclared failure, or a success or an error that does not encode answers an empty 500: the cause goes to the log and to the call's `ErrorReporter`s, never to the body.
167
168
  * - A path no layer serves, or a method other than `POST` on a route, is a 404.
@@ -2,13 +2,12 @@ import { providerOf } from "./authentication/provider.mjs";
2
2
  import { inputParseOptions } from "./contract/call.mjs";
3
3
  import { Anyone } from "./contract/caller.mjs";
4
4
  import { bindingErrors, bindingOf, eventErrors, projectedErrors } from "./contract/declared.mjs";
5
- import { acquireFeeds, unkeyedHook } from "./contract/feed.mjs";
6
5
  import { acquire } from "./contract/implementation.mjs";
7
6
  import { listed } from "./contract/listed.mjs";
8
7
  import { provideServed, servingOf } from "./contract/serving.mjs";
9
8
  import { declared } from "./contract/status.mjs";
10
- import { elementOf } from "./contract/stream.mjs";
11
- import { offersWebhook, servedWebhooks } from "./contract/webhooks.mjs";
9
+ import { Answering, answeringOf } from "./contract/stream.mjs";
10
+ import { offersWebhook, servingFeeds } from "./contract/webhooks.mjs";
12
11
  import { methods } from "./http/client.mjs";
13
12
  import { answering, eventEndpointOf, servedSent, webhookAnswers, webhookEndpointsOf } from "./http/events.mjs";
14
13
  import { SchemaErrors, schemaErrors } from "./http/schema-errors.mjs";
@@ -26,21 +25,21 @@ const apiOf = (group, endpoints) => {
26
25
  const [first, ...rest] = endpoints;
27
26
  return HttpApi.make("actions").annotate(HttpApi.ParseOptions, { errors: "all" }).add(first === void 0 ? empty : empty.add(first, ...rest));
28
27
  };
29
- const successOf = (action, errors) => {
30
- const element = elementOf(action.success);
31
- if (element !== void 0) return elementStreamOf(element, action.progress, errors);
32
- return action.progress === void 0 ? action.success : [answeredWithProgress(action.success), progressStreamOf(action.progress, action.success, errors)];
33
- };
28
+ const successOf = (action, errors) => Answering.$match(answeringOf(action), {
29
+ Value: ({ success }) => success,
30
+ Progressed: ({ success, progress }) => [answeredWithProgress(success), progressStreamOf(progress, success, errors)],
31
+ Elements: ({ element, progress }) => elementStreamOf(element, progress, errors)
32
+ });
34
33
  const endpointOf = (action, path, errors) => HttpApiEndpoint.post(action.name, path, {
35
34
  payload: action.input.pipe(HttpApiSchema.asJson()),
36
35
  success: successOf(action, errors),
37
36
  error: errors.map(declared)
38
37
  });
39
- const answerOf = (action, run) => {
40
- const element = elementOf(action.success);
41
- if (element !== void 0) return answeringElements(element, run);
42
- return action.progress === void 0 ? run : answeringWithProgress(action.success, run);
43
- };
38
+ const answerOf = (action, run) => Answering.$match(answeringOf(action), {
39
+ Value: () => run,
40
+ Progressed: ({ success }) => answeringWithProgress(success, run),
41
+ Elements: ({ element }) => answeringElements(element, run)
42
+ });
44
43
  const withinLayerMiddleware = (endpoint, middleware = []) => {
45
44
  let within = endpoint;
46
45
  for (const key of middleware) within = within.middleware(key);
@@ -98,10 +97,7 @@ function layer(binding, served, options = {}) {
98
97
  })]).annotate(HttpApi.PayloadParseOptions, inputParseOptions);
99
98
  const handlers = Layer.unwrap(Effect.gen(function* () {
100
99
  const bound = yield* acquire(apps, authentication);
101
- const feeds = yield* acquireFeeds(events);
102
- const refusal = unkeyedHook("ActionHttp", feeds, authentication?.principal !== void 0);
103
- if (refusal !== void 0) return yield* Effect.die(new Error(refusal));
104
- const { webhooks, offered } = yield* servedWebhooks(feeds, authentication);
100
+ const { feeds, webhooks, offered } = yield* servingFeeds("ActionHttp", events, authentication);
105
101
  const security = authentication === void 0 ? Layer.empty : yield* Effect.map(providerOf(authentication), (provider) => Layer.mergeAll(Layer.succeed(authentication["~middleware"], provider.middleware), Layer.succeed(StepUp, provider.stepUp)));
106
102
  const hostProvidedMiddleware = yield* Effect.forEach(options.middleware ?? [], (key) => Effect.map(Effect.service(key), (service) => Layer.succeed(key, service)));
107
103
  const webhookAnswered = offered.map((feed) => [feed.event.name, webhookAnswers(feed, authentication, webhooks)]);
@@ -120,7 +116,7 @@ function layer(binding, served, options = {}) {
120
116
  security,
121
117
  ...hostProvidedMiddleware
122
118
  ]), buildInEmptyContext);
123
- })).pipe(provideServed(selected));
119
+ })).pipe(provideServed(selected.apps, selected.events));
124
120
  return HttpApiBuilder.layer(api).pipe(Layer.provide(handlers), Layer.provide(startupBeneathRequest()));
125
121
  }
126
122
  function client(binding, options) {
@@ -1,5 +1,5 @@
1
- import { promote, providerOf } from "./authentication/provider.mjs";
2
- import { recordStepUp } from "./authentication/refusal.mjs";
1
+ import { providerOf } from "./authentication/provider.mjs";
2
+ import { asCaller } from "./authentication/refusal.mjs";
3
3
  import { inputParseOptions } from "./contract/call.mjs";
4
4
  import { Anyone, assertAuthentication } from "./contract/caller.mjs";
5
5
  import { projectedErrors } from "./contract/declared.mjs";
@@ -9,8 +9,9 @@ import { liftOf, liftedFrom } from "./contract/lift.mjs";
9
9
  import { assertOnce, heldOnce } from "./contract/names.mjs";
10
10
  import { provideServed, selectFrom } from "./contract/serving.mjs";
11
11
  import { toolSuccessOf } from "./contract/stream.mjs";
12
+ import { servingFeeds } from "./contract/webhooks.mjs";
12
13
  import { withStderrConsole } from "./stdio/console.mjs";
13
- import { eventSchemasOf, refuseUnservable, serveWebhooks, withEvents } from "./mcp/bridge.mjs";
14
+ import { eventSchemasOf, withEvents } from "./mcp/bridge.mjs";
14
15
  import { progressNotifier } from "./mcp/progress.mjs";
15
16
  import { defaultPath, fieldKey, httpProtocol, isMisplaced, isObjectSchema, protocols, toolJsonSchema } from "./mcp/protocol.mjs";
16
17
  import { client } from "./mcp/client.mjs";
@@ -78,7 +79,7 @@ const registerTools = Effect.fnUntraced(function* (apps, authentication) {
78
79
  const encodeSuccess = encoder(toolSuccess);
79
80
  const encodeFailure = encoder(Schema.Union(projectedErrors(action)));
80
81
  const reported = (input) => action.progress === void 0 ? run(input) : Effect.flatMap(progressNotifier(registry.notifications, action.progress), (sink) => run(input, sink));
81
- const call = authentication === void 0 || action.caller === Anyone ? reported : (input) => recordStepUp(promote(authentication, reported(input)));
82
+ const call = (input) => asCaller(authentication, action, reported(input));
82
83
  const liftedFieldNames = new Set(media?.fields.map(({ name }) => name));
83
84
  const resultOf = (encoded, success) => {
84
85
  if (media === void 0) return new McpSchema.CallToolResult({
@@ -131,14 +132,10 @@ const server = (apps, serving, transport, features = Layer.empty) => {
131
132
  const register = Effect.gen(function* () {
132
133
  const namesClaimedByFeatures = (yield* McpServer.McpServer).tools.flatMap(({ tool }) => names.has(tool.name) ? [tool.name] : []);
133
134
  if (namesClaimedByFeatures.length > 0) return yield* Effect.die(/* @__PURE__ */ new Error(`Duplicate MCP tool: ${namesClaimedByFeatures.join(", ")}, claimed by an action and a native feature (rename the native tool, or leave the action out of actions)`));
134
- yield* refuseUnservable(serving);
135
- yield* serveWebhooks(serving);
135
+ yield* servingFeeds("MCP", serving.events, serving.authentication);
136
136
  yield* registerTools(apps, authentication);
137
137
  });
138
- return Layer.empty.pipe(Layer.provide(transport(Layer.effectDiscard(register).pipe(Layer.provide(features)))), Layer.fresh, provideServed({
139
- apps,
140
- events
141
- }));
138
+ return Layer.empty.pipe(Layer.provide(transport(Layer.effectDiscard(register).pipe(Layer.provide(features)))), Layer.fresh, provideServed(apps, events));
142
139
  };
143
140
  const anonymousMethods = /* @__PURE__ */ new Set([
144
141
  "server/discover",
@@ -196,7 +196,8 @@ export interface KeptSubscription {
196
196
  readonly headers: ReadonlyArray<readonly [string, string]>;
197
197
  /**
198
198
  * The payload that resumes the subscription after `values`, a chunk sent for it, or
199
- * `undefined` where they reach no position.
199
+ * `undefined` where they reach no position. It never throws, being called as the protocol
200
+ * sends: an input that does not encode fails its subscription as it is admitted instead.
200
201
  */
201
202
  readonly resumeFrom: (values: RpcMessage.ResponseChunkEncoded["values"]) => Schema.Json | undefined;
202
203
  }
@@ -1,17 +1,17 @@
1
1
  import { providerOf } from "./authentication/provider.mjs";
2
- import { checked, checkedStream, decodeInput, inputParseOptions, sendingJson, watchInput } from "./contract/call.mjs";
2
+ import { checked, checkedStream, decodeInput, sendingJson, watchInput } from "./contract/call.mjs";
3
3
  import { Anyone } from "./contract/caller.mjs";
4
4
  import { bindingErrors, bindingOf, eventErrors } from "./contract/declared.mjs";
5
- import { InvalidInput, Unauthenticated } from "./contract/errors.mjs";
5
+ import { Unauthenticated } from "./contract/errors.mjs";
6
6
  import { acquireFeeds } from "./contract/feed.mjs";
7
7
  import { acquire, elementsOf } from "./contract/implementation.mjs";
8
8
  import { listed } from "./contract/listed.mjs";
9
9
  import { reservedList, reservedNames } from "./contract/names.mjs";
10
10
  import { answerFrom, elementsFrom } from "./contract/progress.mjs";
11
- import { PushedOf, Subscription, SubscriptionOf, queuedPush } from "./contract/push.mjs";
11
+ import { PushedOf, SubscriptionOf, queuedPush } from "./contract/push.mjs";
12
12
  import { concealed } from "./contract/reported.mjs";
13
13
  import { provideServed, servingOf } from "./contract/serving.mjs";
14
- import { elementOf } from "./contract/stream.mjs";
14
+ import { Answering, answeringOf, elementOf } from "./contract/stream.mjs";
15
15
  import { watching } from "./contract/watch.mjs";
16
16
  import { transportOf } from "./rpc/watch.mjs";
17
17
  import { Cause, Effect, ErrorReporter, Layer, Match, Option, Predicate, Queue, Result, Schedule, Schema, SchemaTransformation, Stream } from "effect";
@@ -21,13 +21,12 @@ import { Rpc, RpcClient, RpcGroup, RpcMiddleware, RpcSchema, RpcServer } from "e
21
21
  // src/rpc/ActionRpc.ts
22
22
  const ProgressedOf = (progress, success) => Schema.Union([Schema.TaggedStruct("Progress", { value: progress }), Schema.TaggedStruct("Final", { value: success })]);
23
23
  const elementedOf = (element, progress) => Schema.Union([Schema.TaggedStruct("Element", { value: element }), ...progress === void 0 ? [] : [Schema.TaggedStruct("Progress", { value: progress })]]);
24
- const streams = (action) => action.progress !== void 0 || elementOf(action.success) !== void 0;
25
- const streamedOf = (action) => {
26
- const element = elementOf(action.success);
27
- if (element !== void 0) return elementedOf(element, action.progress);
28
- return action.progress === void 0 ? void 0 : ProgressedOf(action.progress, action.success);
29
- };
30
- const sentOf = (action) => streamedOf(action) ?? action.success;
24
+ const streams = (action) => !Answering.$is("Value")(answeringOf(action));
25
+ const streamedOf = (action) => Answering.$match(answeringOf(action), {
26
+ Value: () => void 0,
27
+ Progressed: ({ success, progress }) => ProgressedOf(progress, success),
28
+ Elements: ({ element, progress }) => elementedOf(element, progress)
29
+ });
31
30
  const authenticatedKey = "effect-actions/ActionRpc/Authenticated";
32
31
  const nativeOf = (group) => group;
33
32
  const authenticatedOf = (authentication) => RpcMiddleware.Service()(authenticatedKey, { error: Schema.Union([Unauthenticated, ...authentication.error]) });
@@ -35,12 +34,15 @@ const authenticatedIn = (rpc) => [...rpc.middlewares].find(({ key }) => key ===
35
34
  function make(contracts, options = {}) {
36
35
  const { actions, events } = listed(contracts);
37
36
  const bound = bindingOf("ActionRpc binding", actions, events, options);
38
- const rpcOf = (action) => Rpc.make(action.name, {
39
- payload: action.input,
40
- success: sentOf(action),
41
- error: Schema.Union(bindingErrors(action, bound)),
42
- stream: streams(action)
43
- });
37
+ const rpcOf = (action) => {
38
+ const streamed = streamedOf(action);
39
+ return Rpc.make(action.name, {
40
+ payload: action.input,
41
+ success: streamed ?? action.success,
42
+ error: Schema.Union(bindingErrors(action, bound)),
43
+ stream: streamed !== void 0
44
+ });
45
+ };
44
46
  const given = options.rpcs === void 0 ? RpcGroup.make() : nativeOf(options.rpcs);
45
47
  for (const tag of given.requests.keys()) if (reservedNames.includes(tag) || contracts.some((contract) => contract.name === tag)) throw new Error(`ActionRpc binding: the rpc "${tag}" of rpcs is named after an action, an event type or a name the client keeps, ${reservedList} (rename it)`);
46
48
  const rpcs = bound.authentication === void 0 ? given : given.middleware(authenticatedOf(bound.authentication));
@@ -111,40 +113,29 @@ const callBoundaryOf = (error) => {
111
113
  })) : Effect.failCause(failure.failure);
112
114
  });
113
115
  };
116
+ const servedCall = (steps, boundary, call) => (payload, options) => boundary(throughSteps(steps, call(payload, options), {
117
+ ...options,
118
+ payload
119
+ }));
114
120
  const handlerOf = (action, run, steps, error) => {
115
121
  const decode = decodeInput(action);
116
122
  const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(action.success));
117
- const boundary = callBoundaryOf(error);
118
- return (payload, options) => {
119
- const call = Effect.suspend(() => decode(payload)).pipe(Effect.flatMap(run), Effect.flatMap(encode));
120
- const wrapped = throughSteps(steps, call, {
121
- ...options,
122
- payload
123
- });
124
- return boundary(wrapped);
125
- };
123
+ return servedCall(steps, callBoundaryOf(error), (payload) => Effect.suspend(() => decode(payload)).pipe(Effect.flatMap(run), Effect.flatMap(encode)));
126
124
  };
127
125
  const streamingHandlerOf = (action, sending, steps, error) => {
128
126
  const decode = decodeInput(action);
129
127
  const boundary = callBoundaryOf(error);
130
128
  const encodeProgress = Schema.encodeUnknownEffect(Schema.toCodecJson(action.progress ?? Schema.Never));
131
- return (payload, options) => {
132
- const call = Effect.gen(function* () {
133
- const input = yield* decode(payload);
134
- const sent = yield* Queue.bounded(1);
135
- const send = (each) => Effect.asVoid(Queue.offer(sent, each));
136
- yield* sending(input, { progress: (value) => Effect.flatMap(Effect.orDie(encodeProgress(value)), (json) => send({
137
- _tag: "Progress",
138
- value: json
139
- })) }, send).pipe(boundary, Queue.into(sent), Effect.forkScoped({ startImmediately: true }));
140
- return sent;
141
- });
142
- const wrapped = throughSteps(steps, call, {
143
- ...options,
144
- payload
145
- });
146
- return boundary(wrapped);
147
- };
129
+ return servedCall(steps, boundary, (payload) => Effect.gen(function* () {
130
+ const input = yield* decode(payload);
131
+ const sent = yield* Queue.bounded(1);
132
+ const send = (each) => Effect.asVoid(Queue.offer(sent, each));
133
+ yield* sending(input, { progress: (value) => Effect.flatMap(Effect.orDie(encodeProgress(value)), (json) => send({
134
+ _tag: "Progress",
135
+ value: json
136
+ })) }, send).pipe(boundary, Queue.into(sent), Effect.forkScoped({ startImmediately: true }));
137
+ return sent;
138
+ }));
148
139
  };
149
140
  const sendingAnswer = (success, run) => {
150
141
  const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(success));
@@ -168,20 +159,17 @@ const keeperOf = (protocol) => {
168
159
  return isSubscriptionKeeper(kept) ? kept : void 0;
169
160
  };
170
161
  const subscriptionHandlerOf = (feed, steps, error, keeper) => {
171
- const decode = Schema.decodeUnknownEffect(Subscription, inputParseOptions);
172
- const decodeEventInput = decodeInput(feed.event);
162
+ const decode = decodeInput({ input: SubscriptionOf(feed.event) });
163
+ const encodeInput = Schema.encodeEffect(Schema.toCodecJson(feed.event.input));
173
164
  const sent = Schema.toCodecJson(PushedOf(feed.event));
174
165
  const encode = Schema.encodeEffect(sent);
175
166
  const decodeSent = Schema.decodeUnknownOption(sent);
176
167
  const boundary = callBoundaryOf(error);
177
- return (payload, options) => {
178
- const call = Effect.gen(function* () {
179
- const { input, cursor } = yield* Effect.mapError(decode(payload), InvalidInput.fromSchemaError);
180
- const open = yield* feed.stream(yield* decodeEventInput(input));
181
- if (keeper === void 0) return yield* queuedPush(open, cursor, encode, {
182
- ending: boundary,
183
- positions: "heartbeat"
184
- });
168
+ return servedCall(steps, boundary, (payload, options) => Effect.gen(function* () {
169
+ const { input, cursor } = yield* decode(payload);
170
+ const open = yield* feed.stream(input);
171
+ if (keeper !== void 0) {
172
+ const resumed = yield* Effect.orDie(encodeInput(input));
185
173
  yield* keeper.keep({
186
174
  clientId: options.client.id,
187
175
  requestId: options.requestId,
@@ -191,22 +179,17 @@ const subscriptionHandlerOf = (feed, steps, error, keeper) => {
191
179
  resumeFrom: (values) => {
192
180
  const reached = values.flatMap((value) => Option.toArray(decodeSent(value))).map((pushed) => Match.value(pushed).pipe(Match.tag("Failed", () => null), Match.orElse((positioned) => positioned.cursor))).findLast(Predicate.isNotNull);
193
181
  return reached === void 0 ? void 0 : {
194
- input,
182
+ input: resumed,
195
183
  cursor: reached
196
184
  };
197
185
  }
198
186
  });
199
- return yield* queuedPush(open, cursor, encode, {
200
- ending: boundary,
201
- positions: "watermark"
202
- });
203
- });
204
- const wrapped = throughSteps(steps, call, {
205
- ...options,
206
- payload
187
+ }
188
+ return yield* queuedPush(open, cursor, encode, {
189
+ ending: boundary,
190
+ positions: keeper === void 0 ? "heartbeat" : "watermark"
207
191
  });
208
- return boundary(wrapped);
209
- };
192
+ }));
210
193
  };
211
194
  /**
212
195
  * The key a protocol answering each call once sets to `true` on its `RpcServer.Protocol`
@@ -246,9 +229,12 @@ function layer(binding, served, options = {}) {
246
229
  requested
247
230
  ];
248
231
  const handlerFor = (action, run, steps, error) => {
249
- const element = elementOf(action.success);
250
- if (element !== void 0) return streamingHandlerOf(action, sendingElements(element, run), steps, error);
251
- return action.progress === void 0 ? handlerOf(action, run, steps, error) : streamingHandlerOf(action, sendingAnswer(action.success, run), steps, error);
232
+ const streaming = (sending) => streamingHandlerOf(action, sending, steps, error);
233
+ return Answering.$match(answeringOf(action), {
234
+ Value: () => handlerOf(action, run, steps, error),
235
+ Progressed: ({ success }) => streaming(sendingAnswer(success, run)),
236
+ Elements: ({ element }) => streaming(sendingElements(element, run))
237
+ });
252
238
  };
253
239
  const byName = {
254
240
  ...Object.fromEntries(bound.map(([action, run]) => [action.name, handlerFor(action, run, stepsOf(action.caller), Schema.Union(bindingErrors(action, binding)))])),
@@ -259,7 +245,7 @@ function layer(binding, served, options = {}) {
259
245
  if (authenticated === void 0 || authenticating === void 0) return servedActions;
260
246
  const authenticate = authenticating(verifyingNative);
261
247
  return Layer.merge(servedActions, Layer.succeed(authenticated)(authenticate));
262
- })).pipe(provideServed(selected));
248
+ })).pipe(provideServed(selected.apps, selected.events));
263
249
  return RpcServer.layer(jsonGroup.merge(binding.rpcs), { disableFatalDefects: true }).pipe(Layer.provide(handlers));
264
250
  }
265
251
  const isDeclared = (failure) => failure instanceof DeclaredFailure;
@@ -1,9 +1,10 @@
1
1
  import { projectedErrors } from "./contract/declared.mjs";
2
2
  import { hintsOf } from "./contract/hints.mjs";
3
- import { Implementation, acquire, answeringWhole, provideHandlers, select, toList } from "./contract/implementation.mjs";
3
+ import { Implementation, acquire, actionKind, answeringWhole, select, toList } from "./contract/implementation.mjs";
4
4
  import { liftOf, liftedFrom } from "./contract/lift.mjs";
5
5
  import { assertOnce, heldOnce } from "./contract/names.mjs";
6
6
  import { progressSink } from "./contract/progress.mjs";
7
+ import { provideServed } from "./contract/serving.mjs";
7
8
  import { toolSuccessOf } from "./contract/stream.mjs";
8
9
  import { Effect, Schema, SchemaGetter } from "effect";
9
10
  import { Prompt, Tool, Toolkit } from "effect/ai";
@@ -50,7 +51,7 @@ const jsonToolOf = (action) => {
50
51
  });
51
52
  };
52
53
  function make(apps, options) {
53
- const served = select(toList(apps), options?.actions);
54
+ const served = select(actionKind, toList(apps), options?.actions);
54
55
  const needsApproval = options?.needsApproval;
55
56
  assertOnce("tool", served.flatMap((app) => app.actions), heldOnce);
56
57
  const toolOf = (action, app) => Object.assign(needsApproval === void 0 ? jsonToolOf(action) : jsonToolOf(action).setNeedsApproval((input, context) => {
@@ -67,7 +68,7 @@ function make(apps, options) {
67
68
  layer: toolkit.toLayer(Effect.map(acquire(served, void 0), (bound) => Object.fromEntries(bound.map(([action, handler]) => {
68
69
  const run = answeringWhole(action, handler);
69
70
  return [action.name, (input, { preliminary }) => run(input, progressSink((value) => preliminary(new Reported(value))))];
70
- })))).pipe(provideHandlers(served))
71
+ })))).pipe(provideServed(served))
71
72
  };
72
73
  }
73
74
  /**
@@ -25,12 +25,6 @@ const namedOf = (options) => ({
25
25
  scope: options?.scopesRequired?.join(" "),
26
26
  metadataUrl: options === void 0 ? void 0 : metadataUrlOf(options).href
27
27
  });
28
- const presentsBearerToken = (authorization) => Option.isSome(bearerTokenOf(authorization));
29
- const bearerChallengeOf = (named, presented) => bearer([
30
- ["error", presented ? "invalid_token" : void 0],
31
- ["scope", named.scope],
32
- ["resource_metadata", named.metadataUrl]
33
- ]);
34
28
  const assertPublishableResource = (oauth, options) => {
35
29
  if (options === void 0) return;
36
30
  if (!oauth) throw new Error("A protected resource is published only for a Bearer scheme: drop `protectedResource`, or authenticate with a Bearer descriptor");
@@ -50,6 +44,32 @@ const withNoStoreAndChallenge = (response, wwwAuthenticate) => HttpServerRespons
50
44
  const isBearer = (security) => Predicate.isTagged(security, "Http") && security.scheme.toLowerCase() === "bearer";
51
45
  const openApiComponentKey = /^[\w.-]+$/u;
52
46
  const nonBearerChallengeOf = (security, name) => Match.value(security).pipe(Match.tag("Http", ({ scheme }) => challenge(scheme, [])), Match.tag("Basic", () => challenge("Basic", [["realm", name]])), Match.tag("ApiKey", Function.constUndefined), Match.exhaustive);
47
+ const refusingOf = (authentication, resource) => {
48
+ const oauth = authentication === void 0 || isBearer(authentication.security);
49
+ assertPublishableResource(oauth, resource);
50
+ const { scope, metadataUrl } = namedOf(resource);
51
+ const bearerChallenge = (presented) => bearer([
52
+ ["error", presented ? "invalid_token" : void 0],
53
+ ["scope", scope],
54
+ ["resource_metadata", metadataUrl]
55
+ ]);
56
+ const invalid = bearerChallenge(true);
57
+ const anonymous = bearerChallenge(false);
58
+ const other = authentication === void 0 || oauth ? void 0 : nonBearerChallengeOf(authentication.security, authentication.name);
59
+ return {
60
+ missing: new Unauthenticated({ message: oauth ? "A bearer token is required." : "A credential is required." }),
61
+ challenge: (presented) => {
62
+ if (!oauth) return other;
63
+ return presented ? invalid : anonymous;
64
+ },
65
+ response: (error) => {
66
+ if (!isRefusal(error)) return declaredResponse(authentication?.error ?? [], error);
67
+ return oauth ? answer(error, metadataUrl) : plain(error);
68
+ },
69
+ stepUp: (route) => oauth ? Effect.catchIf(route, isStepUp, (error) => Effect.succeed(answer(error, metadataUrl))) : route,
70
+ answeringStepUp: (route) => oauth ? answerStepUp(route, metadataUrl) : route
71
+ };
72
+ };
53
73
  /**
54
74
  * The response `layer` answers a refusal with, for a caller the router never routes, such as a
55
75
  * Node `upgrade` handler admitting a socket, which holds a header and no request: read its token
@@ -59,17 +79,10 @@ const nonBearerChallengeOf = (security, name) => Match.value(security).pipe(Matc
59
79
  * naming scopes. `HttpServerResponse.toWeb` gives it as a web `Response`.
60
80
  */
61
81
  const refusalResponse = (error, options) => {
62
- const authentication = options?.authentication;
63
- const oauth = authentication === void 0 || isBearer(authentication.security);
64
- assertPublishableResource(oauth, options?.protectedResource);
65
- const named = namedOf(options?.protectedResource);
66
- const wwwAuthenticate = authentication !== void 0 && !oauth ? nonBearerChallengeOf(authentication.security, authentication.name) : bearerChallengeOf(named, presentsBearerToken(options?.authorization));
67
- if (!isRefusal(error)) {
68
- const response = declaredResponse(authentication?.error ?? [], error);
69
- if (response === void 0) throw new Error("Not a refusal, nor an error the authentication declares: pass the descriptor declaring it as `authentication`, or answer the error yourself");
70
- return withNoStoreAndChallenge(response, wwwAuthenticate);
71
- }
72
- return withNoStoreAndChallenge(oauth ? answer(error, named.metadataUrl) : plain(error), wwwAuthenticate);
82
+ const refusing = refusingOf(options?.authentication, options?.protectedResource);
83
+ const response = refusing.response(error);
84
+ if (response === void 0) throw new Error("Not a refusal, nor an error the authentication declares: pass the descriptor declaring it as `authentication`, or answer the error yourself");
85
+ return withNoStoreAndChallenge(response, refusing.challenge(Option.isSome(bearerTokenOf(options?.authorization))));
73
86
  };
74
87
  const mayResolveToDiscoveryPath = /\.well-known|[\t\n\r]/u;
75
88
  const corsPreflight = (request) => {
@@ -103,15 +116,6 @@ const discoveryMiddleware = (options) => {
103
116
  return next;
104
117
  });
105
118
  };
106
- const resourceAnswersOf = (options) => {
107
- const named = namedOf(options);
108
- return {
109
- metadataUrl: named.metadataUrl,
110
- invalid: bearerChallengeOf(named, true),
111
- anonymous: bearerChallengeOf(named, false),
112
- published: options === void 0 ? void 0 : discoveryMiddleware(options)
113
- };
114
- };
115
119
  /**
116
120
  * Browser-safe declaration shared by clients and remote surfaces: the `identity` it
117
121
  * authenticates, and the scheme a caller proves it by, `Options.security`. The literal name
@@ -142,31 +146,25 @@ const make = (name, identity, ...options) => {
142
146
  const presented = (credential) => Redacted.isRedacted(credential) ? Redacted.value(credential) !== "" : credential.username !== "" || Redacted.value(credential.password) !== "";
143
147
  function layer(authentication, verify, options = {}) {
144
148
  const { security } = authentication;
145
- const oauth = isBearer(security);
146
149
  const { protectedResource } = options;
147
- assertPublishableResource(oauth, protectedResource);
148
- const resource = Effect.isEffect(protectedResource) ? Effect.map(protectedResource, (built) => {
149
- assertPublishableResource(oauth, built);
150
- return resourceAnswersOf(built);
151
- }) : Effect.succeed(resourceAnswersOf(protectedResource));
152
- const missing = new Unauthenticated({ message: oauth ? "A bearer token is required." : "A credential is required." });
150
+ const published = (built) => ({
151
+ refusing: refusingOf(authentication, built),
152
+ discovery: built === void 0 ? void 0 : discoveryMiddleware(built)
153
+ });
154
+ const resource = Effect.isEffect(protectedResource) ? Effect.map(protectedResource, published) : Effect.succeed(published(protectedResource));
153
155
  return Layer.effect(authentication["~provider"], Effect.gen(function* () {
154
- const { metadataUrl, invalid, anonymous, published } = yield* resource;
155
- if (published !== void 0) yield* (yield* HttpRouter.HttpRouter).addGlobalMiddleware(published);
156
+ const { refusing, discovery } = yield* resource;
157
+ if (discovery !== void 0) yield* (yield* HttpRouter.HttpRouter).addGlobalMiddleware(discovery);
156
158
  const verifier = Effect.isEffect(verify) ? yield* verify : verify;
157
159
  if (!Predicate.isFunction(verifier)) return yield* Effect.die(/* @__PURE__ */ new Error("Missing verify: pass a verify function, or an Effect building one"));
158
- const authenticate = (credential) => presented(credential) ? verifier(credential) : Effect.fail(missing);
160
+ const authenticate = (credential) => presented(credential) ? verifier(credential) : Effect.fail(refusing.missing);
159
161
  const noStoreOnFailure = HttpEffect.appendPreResponseHandler((_request, response) => Effect.succeed(HttpServerResponse.setHeader(response, "cache-control", "no-store")));
160
- const challengeOf = (credential) => {
161
- if (!oauth) return nonBearerChallengeOf(security, authentication.name);
162
- return presented(credential) ? invalid : anonymous;
163
- };
164
- const refuse = (error) => isRefusal(error) ? Effect.succeed(oauth ? answer(error, metadataUrl) : plain(error)) : Effect.suspend(() => {
165
- const response = declaredResponse(authentication.error, error);
162
+ const refuse = (error) => Effect.suspend(() => {
163
+ const response = refusing.response(error);
166
164
  return response === void 0 ? Effect.die(error) : Effect.succeed(response);
167
165
  });
168
166
  const verified = (credential, route, slot) => {
169
- const wwwAuthenticate = challengeOf(credential);
167
+ const wwwAuthenticate = refusing.challenge(presented(credential));
170
168
  return Effect.matchEffect(authenticate(credential), {
171
169
  onFailure: refuse,
172
170
  onSuccess: (actor) => Effect.provideService(route, slot, actor)
@@ -176,8 +174,8 @@ function layer(authentication, verify, options = {}) {
176
174
  descriptor: authentication,
177
175
  authenticate,
178
176
  middleware: { [authentication.name]: (route, { credential }) => verified(credential, route, authentication.identity) },
179
- stepUp: (route) => oauth ? Effect.catchIf(route, isStepUp, (error) => Effect.succeed(answer(error, metadataUrl))) : route,
180
- http: ((route, optional) => Effect.flatMap(HttpApiBuilder.securityDecode(security), (credential) => optional && !presented(credential) ? route : verified(credential, oauth ? answerStepUp(route, metadataUrl) : route, authentication["~verified"]))),
177
+ stepUp: refusing.stepUp,
178
+ http: ((route, optional) => Effect.flatMap(HttpApiBuilder.securityDecode(security), (credential) => optional && !presented(credential) ? route : verified(credential, refusing.answeringStepUp(route), authentication["~verified"]))),
181
179
  route: ((route) => Effect.flatMap(HttpApiBuilder.securityDecode(security), (credential) => verified(credential, Effect.catchIf(route, isRefusal, refuse), authentication.identity)))
182
180
  };
183
181
  }));
@@ -1,12 +1,14 @@
1
+ import { Anyone } from "../contract/caller.mjs";
1
2
  import { errorSchemas } from "../contract/declared.mjs";
2
3
  import { Forbidden, Refusal, Unauthenticated } from "../contract/errors.mjs";
3
- import { declared, httpApiStatusOf } from "../contract/status.mjs";
4
+ import { declaredStatus } from "../contract/status.mjs";
5
+ import { promote } from "./provider.mjs";
4
6
  import { Cause, Context, Effect, Exit, Option, Predicate, Ref, Schema } from "effect";
5
7
  import { HttpServerResponse } from "effect/http";
6
8
  // src/authentication/refusal.ts
7
- const responseOf = (schema, error) => HttpServerResponse.jsonUnsafe(Schema.encodeUnknownSync(Schema.toCodecJson(schema))(error), { status: httpApiStatusOf(schema.ast) ?? 422 });
9
+ const responseOf = (schema, error) => HttpServerResponse.jsonUnsafe(Schema.encodeUnknownSync(Schema.toCodecJson(schema))(error), { status: declaredStatus(schema) });
8
10
  const declaredResponse = (errors, error) => {
9
- const schema = errorSchemas(errors).map(declared).find((each) => Schema.is(each)(error));
11
+ const schema = errorSchemas(errors).find((each) => Schema.is(each)(error));
10
12
  return schema === void 0 ? void 0 : responseOf(schema, error);
11
13
  };
12
14
  const rfc6750ErrorDescriptionCharacters = /^[\u0020\u0021\u0023-\u005B\u005D-\u007E]+$/u;
@@ -35,6 +37,11 @@ const answer = (error, metadataUrl) => {
35
37
  var SteppedUpRefusal = class extends Context.Service()("effect-actions/SteppedUp") {};
36
38
  const isStepUp = (error) => isRefusal(error) && (!Predicate.isTagged(error, "Forbidden") || error.scopes !== void 0);
37
39
  const recordStepUp = (call) => Effect.tapError(call, (error) => isStepUp(error) ? Effect.flatMap(Effect.serviceOption(SteppedUpRefusal), (slot) => Option.isSome(slot) ? Ref.set(slot.value, Option.some(error)) : Effect.void) : Effect.void);
40
+ /**
41
+ * `run` as the caller of `called`: unchanged where it is public or nothing authenticates, and
42
+ * otherwise with the identity its request verified, a step-up it fails with recorded.
43
+ */
44
+ const asCaller = (authentication, called, run) => authentication === void 0 || called.caller === Anyone ? run : recordStepUp(promote(authentication, run));
38
45
  const answerStepUp = (route, metadataUrl) => Effect.gen(function* () {
39
46
  const slot = yield* Ref.make(Option.none());
40
47
  const exit = yield* Effect.exit(Effect.provideService(route, SteppedUpRefusal, slot));
@@ -42,4 +49,4 @@ const answerStepUp = (route, metadataUrl) => Effect.gen(function* () {
42
49
  const diedOrInterruptedAfterRefusal = Exit.isFailure(exit) && (Cause.hasDies(exit.cause) || Cause.hasInterrupts(exit.cause));
43
50
  return Option.isSome(refused) && !diedOrInterruptedAfterRefusal ? answer(refused.value, metadataUrl) : yield* exit;
44
51
  });
45
- export { answer, answerStepUp, bearer, challenge, declaredResponse, isRefusal, isStepUp, plain, recordStepUp };
52
+ export { answer, answerStepUp, asCaller, bearer, challenge, declaredResponse, isRefusal, isStepUp, plain, recordStepUp };