@sealant/sdk-next 0.40.0-next.973 → 0.40.0-next.975

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 (64) hide show
  1. package/README.md +34 -13
  2. package/dist/client.d.ts +12 -2
  3. package/dist/client.js +22 -2
  4. package/dist/effect/api-client.d.ts +37 -11
  5. package/dist/effect/api-client.js +71 -28
  6. package/dist/effect/config.d.ts +47 -0
  7. package/dist/effect/config.js +36 -0
  8. package/dist/effect/context.d.ts +27 -0
  9. package/dist/effect/context.js +29 -0
  10. package/dist/effect/endpoint.d.ts +10 -0
  11. package/dist/effect/endpoint.js +1 -0
  12. package/dist/effect/errors.d.ts +113 -0
  13. package/dist/effect/errors.js +104 -0
  14. package/dist/effect/events/layer.d.ts +14 -0
  15. package/dist/effect/events/layer.js +109 -0
  16. package/dist/effect/events/observe.d.ts +19 -0
  17. package/dist/effect/events/observe.js +15 -0
  18. package/dist/effect/events/service.d.ts +62 -0
  19. package/dist/effect/events/service.js +3 -0
  20. package/dist/effect/http.d.ts +42 -0
  21. package/dist/effect/http.js +76 -0
  22. package/dist/effect/index.d.ts +49 -16
  23. package/dist/effect/index.js +45 -17
  24. package/dist/effect/layer.d.ts +24 -0
  25. package/dist/effect/layer.js +21 -0
  26. package/dist/effect/operations.d.ts +107 -30
  27. package/dist/effect/operations.js +7 -0
  28. package/dist/effect/read-retry.d.ts +4 -2
  29. package/dist/effect/read-retry.js +9 -2
  30. package/dist/effect/runs/layer.d.ts +9 -0
  31. package/dist/effect/runs/layer.js +94 -0
  32. package/dist/effect/runs/service.d.ts +51 -0
  33. package/dist/effect/runs/service.js +3 -0
  34. package/dist/effect/runs/wait.d.ts +15 -0
  35. package/dist/effect/runs/wait.js +16 -0
  36. package/dist/effect/runtime.d.ts +33 -14
  37. package/dist/effect/runtime.js +42 -50
  38. package/dist/effect/sessions/attach.d.ts +12 -0
  39. package/dist/effect/sessions/attach.js +142 -0
  40. package/dist/effect/sessions/layer.d.ts +10 -0
  41. package/dist/effect/sessions/layer.js +149 -0
  42. package/dist/effect/sessions/service.d.ts +83 -0
  43. package/dist/effect/sessions/service.js +3 -0
  44. package/dist/effect/websocket.d.ts +11 -0
  45. package/dist/effect/websocket.js +16 -0
  46. package/dist/effect/workspaces/layer.d.ts +9 -0
  47. package/dist/effect/workspaces/layer.js +148 -0
  48. package/dist/effect/workspaces/service.d.ts +75 -0
  49. package/dist/effect/workspaces/service.js +3 -0
  50. package/dist/effect/workspaces/wait.d.ts +216 -0
  51. package/dist/effect/workspaces/wait.js +158 -0
  52. package/dist/facade/exec-sync.d.ts +4 -0
  53. package/dist/facade/exec-sync.js +38 -0
  54. package/dist/facade/run.js +19 -20
  55. package/dist/facade/session.js +75 -89
  56. package/dist/facade/workspace.d.ts +5 -20
  57. package/dist/facade/workspace.js +122 -277
  58. package/dist/index.d.ts +1 -0
  59. package/dist/index.js +2 -0
  60. package/dist/internal/map-error.js +20 -1
  61. package/dist/internal/workspace-phase.d.ts +41 -0
  62. package/dist/internal/workspace-phase.js +95 -0
  63. package/dist/types.d.ts +42 -6
  64. package/package.json +3 -3
@@ -0,0 +1,104 @@
1
+ import { sessionEndedSchema, workspaceErrorSchema, workspaceStatusSchema, } from "@sealant/api-contracts";
2
+ /**
3
+ * The errors the Effect SDK's own services fail with, beside the contract's (`WorkspaceNotFoundError`,
4
+ * `SessionConflictError`, …), which reach callers unchanged. Every one is a `Schema.TaggedError`, so
5
+ * `Effect.catchTag` reaches it and nothing needs a status code or a message to tell them apart.
6
+ *
7
+ * - `SealantTransportError`: a request that never got an answer the contract describes: the
8
+ * connection failed, or the answer did not decode.
9
+ * - `SealantStreamRefusedError`: a streaming endpoint (events, session output) refused the request
10
+ * with a status a retry cannot change (401, 403, 404, …).
11
+ * - `SealantWaitTimeoutError`: a wait the caller bounded ran out.
12
+ * - `WorkspaceSettledError`: a workspace being waited on settled where the wait cannot end.
13
+ * - `SessionAttachError`: the attach socket could not be opened, or kept being cut.
14
+ * - `SessionEndedError`: input for a session that has ended.
15
+ */
16
+ import { Effect, Schema } from "effect";
17
+ import { HttpClientError } from "effect/http";
18
+ /** A request that got no answer the contract describes: the transport failed or the body did not decode. */
19
+ export class SealantTransportError extends Schema.TaggedError()("SealantTransportError", {
20
+ /** The SDK operation, e.g. `Workspaces.get`. */
21
+ operation: Schema.String,
22
+ message: Schema.String,
23
+ /** The response's status, when there was a response. */
24
+ status: Schema.optional(Schema.Number),
25
+ cause: Schema.Defect(),
26
+ }) {
27
+ /** A transport failure or a 5xx may succeed when asked again; a body that did not decode will not. */
28
+ get isRetryable() {
29
+ return this.status === undefined || this.status >= 500;
30
+ }
31
+ }
32
+ /** A streaming endpoint refused the request with a status asking again would not change. */
33
+ export class SealantStreamRefusedError extends Schema.TaggedError()("SealantStreamRefusedError", {
34
+ /** The stream, e.g. `GET /v1/events`. */
35
+ stream: Schema.String,
36
+ status: Schema.Number,
37
+ message: Schema.String,
38
+ }) {
39
+ }
40
+ /** A wait the caller bounded ran out before what it waited for happened. */
41
+ export class SealantWaitTimeoutError extends Schema.TaggedError()("SealantWaitTimeoutError", {
42
+ /** The wait, e.g. `Runs.wait`. */
43
+ operation: Schema.String,
44
+ /** Stable: `workspace_ready_timeout`, `workspace_image_build_stalled`, `run_wait_timeout`, … */
45
+ code: Schema.String,
46
+ message: Schema.String,
47
+ /** The bound the caller set, when the wait ran out of one the caller set. */
48
+ timeoutMs: Schema.optional(Schema.Number),
49
+ }) {
50
+ }
51
+ /**
52
+ * A workspace being waited on settled where the wait cannot end: `waitReady` saw it fail, stop or
53
+ * be cancelled before it was ready. `error` is the control plane's own account, when it gave one.
54
+ */
55
+ export class WorkspaceSettledError extends Schema.TaggedError()("WorkspaceSettledError", {
56
+ workspaceId: Schema.String,
57
+ status: workspaceStatusSchema,
58
+ message: Schema.String,
59
+ /** The control plane's account of the failure (its `code`, and Boat's own, when Boat refused). */
60
+ error: Schema.optional(workspaceErrorSchema),
61
+ }) {
62
+ }
63
+ /** The attach socket could not be opened, or was cut more times in a row than the backoff allows. */
64
+ export class SessionAttachError extends Schema.TaggedError()("SessionAttachError", {
65
+ sessionId: Schema.String,
66
+ message: Schema.String,
67
+ /** The last close code, when the socket closed rather than failed to open. */
68
+ closeCode: Schema.optional(Schema.Number),
69
+ cause: Schema.optional(Schema.Defect()),
70
+ }) {
71
+ }
72
+ /** Input, a resize or a signal for a session that has already ended. */
73
+ export class SessionEndedError extends Schema.TaggedError()("SessionEndedError", {
74
+ sessionId: Schema.String,
75
+ ended: sessionEndedSchema,
76
+ }) {
77
+ get message() {
78
+ return `Session ${this.sessionId} has ${this.ended.status}.`;
79
+ }
80
+ }
81
+ const isTransportFailure = (error) => HttpClientError.isHttpClientError(error) || Schema.isSchemaError(error);
82
+ const isContractFailure = (error) => !isTransportFailure(error);
83
+ /** `error`, a transport or decode failure, as the `SealantTransportError` of `operation`. */
84
+ const toTransportError = (operation, error) => {
85
+ if (HttpClientError.isHttpClientError(error)) {
86
+ const status = "response" in error.reason ? error.reason.response.status : undefined;
87
+ return new SealantTransportError({
88
+ operation,
89
+ message: `${operation} failed: ${error.message}`,
90
+ ...(status === undefined ? {} : { status }),
91
+ cause: error,
92
+ });
93
+ }
94
+ return new SealantTransportError({
95
+ operation,
96
+ message: `${operation} got an answer that did not decode: ${error instanceof Error ? error.message : String(error)}`,
97
+ cause: error,
98
+ });
99
+ };
100
+ /**
101
+ * Names `effect`'s transport and decode failures as `operation`'s `SealantTransportError`, leaving
102
+ * every contract error as it is, so a caller matches either with `Effect.catchTag`.
103
+ */
104
+ export const transported = (operation) => (effect) => Effect.mapError(effect, (error) => isContractFailure(error) ? error : toTransportError(operation, error));
@@ -0,0 +1,14 @@
1
+ import { Effect, Layer } from "effect";
2
+ import type { HttpClient } from "effect/http";
3
+ import { SealantConfig } from "../config.js";
4
+ import { SseClient } from "../http.js";
5
+ import { SealantEvents } from "./service.js";
6
+ export declare const make: Effect.Effect<SealantEvents["Service"], never, SseClient | SealantConfig>;
7
+ /** Events over the root's `SealantConfig` and `HttpClient`. */
8
+ export declare const layerNoDeps: Layer.Layer<SealantEvents, never, SseClient | SealantConfig>;
9
+ export declare const layer: Layer.Layer<SealantEvents, never, SealantConfig | HttpClient.HttpClient>;
10
+ /**
11
+ * No push channel: `stream` is empty and every wait reads on its `poll`. For a control plane known
12
+ * to predate `GET /v1/events`, and for tests of a wait's polling.
13
+ */
14
+ export declare const layerPolling: Layer.Layer<SealantEvents>;
@@ -0,0 +1,109 @@
1
+ import { controlPlaneEventSchema } from "@sealant/api-contracts";
2
+ import { Deferred, Duration, Effect, Layer, Queue, Random, Ref, Schema, Stream } from "effect";
3
+ import { SealantConfig } from "../config.js";
4
+ import { currentOwner } from "../context.js";
5
+ import { SseClient } from "../http.js";
6
+ import { SealantEvents } from "./service.js";
7
+ /** The first reconnect waits this long; each cut in a row doubles it, up to the cap. */
8
+ const RECONNECT_FIRST = Duration.millis(250);
9
+ const RECONNECT_MAX = Duration.seconds(30);
10
+ /** How long `watch` waits for its subscription before the caller's first read. */
11
+ const SUBSCRIBE_WAIT = Duration.seconds(2);
12
+ /**
13
+ * While changes are pushed, a waiter still reads this often: a wait never hangs on one event that
14
+ * did not arrive.
15
+ */
16
+ const SAFETY_INTERVAL = Duration.seconds(30);
17
+ /** The delay before reconnect number `attempt` (from 0): doubling, capped, scaled by 0.8–1.2. */
18
+ const reconnectDelay = (attempt) => Effect.map(Random.nextBetween(0.8, 1.2), (factor) => Duration.times(Duration.min(Duration.times(RECONNECT_FIRST, 2 ** Math.min(attempt, 16)), RECONNECT_MAX), factor));
19
+ const decodeEvent = Schema.decodeUnknownResult(Schema.fromJsonString(controlPlaneEventSchema));
20
+ const ROUTE = { method: "GET", path: "/v1/events" };
21
+ export const make = Effect.gen(function* () {
22
+ const sse = yield* SseClient;
23
+ const config = yield* SealantConfig;
24
+ /** One connection's events, ending with its body. */
25
+ const connection = (ownerUserId, filter) => sse
26
+ .connect({
27
+ route: ROUTE,
28
+ span: "sealant.sdk.events.stream",
29
+ path: ROUTE.path,
30
+ query: {
31
+ ownerUserId,
32
+ workspaceId: filter.workspaceId,
33
+ runId: filter.runId,
34
+ sessionId: filter.sessionId,
35
+ },
36
+ })
37
+ .pipe(
38
+ // A newer control plane may send event types this SDK does not know: skip them.
39
+ Stream.filterMap((event) => decodeEvent(event.data)));
40
+ const follow = (filter, hooks) => Stream.unwrap(Effect.gen(function* () {
41
+ const ownerUserId = filter.ownerUserId ?? (yield* currentOwner);
42
+ const cuts = yield* Ref.make(0);
43
+ const reconnect = Stream.unwrap(Effect.gen(function* () {
44
+ yield* hooks.onCut;
45
+ const attempt = yield* Ref.getAndUpdate(cuts, (n) => n + 1);
46
+ yield* Effect.sleep(yield* reconnectDelay(attempt));
47
+ return connected;
48
+ }));
49
+ // A body that ends, or a connection that fails in a way asking again could change, is a
50
+ // cut: reconnect. Only a refusal ends the stream.
51
+ const connected = connection(ownerUserId, filter).pipe(Stream.tap(() => Ref.set(cuts, 0)), Stream.catchTag("SealantTransportError", () => Stream.empty), Stream.concat(Stream.suspend(() => reconnect)));
52
+ return connected;
53
+ }).pipe(Effect.provideService(SealantConfig, config)));
54
+ const stream = (filter = {}) => follow(filter, { onCut: Effect.void });
55
+ const watch = Effect.fn("sealant.sdk.watch_events")(function* (filter = {}) {
56
+ // Coalesced: a waiter needs to know that something changed since it last read, not what.
57
+ const wakes = yield* Queue.sliding(1);
58
+ const pushed = yield* Ref.make(false);
59
+ const settled = yield* Deferred.make();
60
+ const onEvent = (event) => Effect.gen(function* () {
61
+ // Woken first: the first `subscribed` settles the wait below, which then drops this
62
+ // wake, since the caller reads after it anyway.
63
+ yield* Queue.offer(wakes, undefined);
64
+ if (event.type === "resync") {
65
+ // `listen-lost`: the control plane delivers nothing until `listen-resumed`.
66
+ yield* Ref.set(pushed, event.reason !== "listen-lost");
67
+ if (event.reason === "subscribed")
68
+ yield* Deferred.succeed(settled, undefined);
69
+ }
70
+ });
71
+ // A cut before the first subscription settles the wait for it too: the caller reads on its
72
+ // poll until a reconnect subscribes, and that `subscribed` wakes it.
73
+ const onCut = Effect.andThen(Ref.set(pushed, false), Deferred.succeed(settled, undefined));
74
+ yield* follow(filter, { onCut }).pipe(Stream.runForEach(onEvent),
75
+ // Refused (an older control plane, a key that may not read events): no push channel, so
76
+ // every wait reads on its `poll`. Nothing to report: the wait still works.
77
+ Effect.catchTag("SealantStreamRefusedError", () => Effect.andThen(Ref.set(pushed, false), Deferred.succeed(settled, undefined))), Effect.forkScoped);
78
+ yield* Deferred.await(settled).pipe(Effect.timeoutOption(SUBSCRIBE_WAIT));
79
+ // The caller reads next: whatever woke us before that read is already in it.
80
+ yield* Queue.clear(wakes);
81
+ const next = (options) => Effect.gen(function* () {
82
+ const live = yield* Ref.get(pushed);
83
+ const poll = Duration.fromInputUnsafe(options.poll);
84
+ const longest = live ? SAFETY_INTERVAL : poll;
85
+ const wait = options.atMost === undefined
86
+ ? longest
87
+ : Duration.min(longest, Duration.fromInputUnsafe(options.atMost));
88
+ yield* Queue.take(wakes).pipe(Effect.timeoutOption(wait));
89
+ });
90
+ return { next, pushed: Ref.get(pushed) };
91
+ });
92
+ return SealantEvents.of({ stream, watch });
93
+ });
94
+ /** Events over the root's `SealantConfig` and `HttpClient`. */
95
+ export const layerNoDeps = Layer.effect(SealantEvents, make);
96
+ export const layer = layerNoDeps.pipe(Layer.provide(SseClient.layer));
97
+ /**
98
+ * No push channel: `stream` is empty and every wait reads on its `poll`. For a control plane known
99
+ * to predate `GET /v1/events`, and for tests of a wait's polling.
100
+ */
101
+ export const layerPolling = Layer.succeed(SealantEvents, SealantEvents.of({
102
+ stream: () => Stream.empty,
103
+ watch: () => Effect.succeed({
104
+ next: (options) => Effect.sleep(options.atMost === undefined
105
+ ? options.poll
106
+ : Duration.min(Duration.fromInputUnsafe(options.poll), Duration.fromInputUnsafe(options.atMost))),
107
+ pushed: Effect.succeed(false),
108
+ }),
109
+ }));
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The shape of every SDK wait: read the state, decide, and when it is not settled yet, wait for
3
+ * the next wake-up (`Wakeups.next`: a pushed change, a `resync`, or the decision's own `poll` or
4
+ * deadline) and read again. No wait sleeps on a fixed interval while changes are pushed.
5
+ */
6
+ import { Effect } from "effect";
7
+ import type { WakeOptions, Wakeups } from "./service.js";
8
+ /** What a wait decided after one read: settled with a value, or read again on the next wake-up. */
9
+ export type Step<B> = {
10
+ readonly kind: "done";
11
+ readonly value: B;
12
+ } | {
13
+ readonly kind: "wait";
14
+ readonly wake: WakeOptions;
15
+ };
16
+ export declare const done: <B>(value: B) => Step<B>;
17
+ export declare const waitFor: (wake: WakeOptions) => Step<never>;
18
+ /** Reads with `read` and decides with `step` until `step` is done. */
19
+ export declare const observe: <A, B, E, R, E2, R2>(wakeups: Wakeups, read: Effect.Effect<A, E, R>, step: (value: A) => Effect.Effect<Step<B>, E2, R2>) => Effect.Effect<B, E | E2, R | R2>;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The shape of every SDK wait: read the state, decide, and when it is not settled yet, wait for
3
+ * the next wake-up (`Wakeups.next`: a pushed change, a `resync`, or the decision's own `poll` or
4
+ * deadline) and read again. No wait sleeps on a fixed interval while changes are pushed.
5
+ */
6
+ import { Effect } from "effect";
7
+ export const done = (value) => ({ kind: "done", value });
8
+ export const waitFor = (wake) => ({ kind: "wait", wake });
9
+ /** Reads with `read` and decides with `step` until `step` is done. */
10
+ export const observe = (wakeups, read, step) => {
11
+ const loop = Effect.flatMap(read, (value) => Effect.flatMap(step(value), (decided) => decided.kind === "done"
12
+ ? Effect.succeed(decided.value)
13
+ : Effect.andThen(wakeups.next(decided.wake), Effect.suspend(() => loop))));
14
+ return loop;
15
+ };
@@ -0,0 +1,62 @@
1
+ /**
2
+ * `SealantEvents`: the control plane's push channel, `GET /v1/events`, as a `Stream`, and the
3
+ * wake-up every SDK wait is built on.
4
+ *
5
+ * An event is a pointer, never the state: it says which record changed, and the caller reads the
6
+ * record. `resync` says events may have been missed (the stream (re)subscribed, or the control
7
+ * plane lost its database listen): re-read whatever you wait on.
8
+ */
9
+ import type { ControlPlaneEvent } from "@sealant/api-contracts";
10
+ import { Context, type Duration, type Effect, type Scope, type Stream } from "effect";
11
+ import type { SealantStreamRefusedError } from "../errors.js";
12
+ /** Which events a stream carries. Each id given narrows it; `resync` is always sent. */
13
+ export interface EventFilter {
14
+ /** Whose events. Default: `ActingOwner`, else the configured owner. */
15
+ readonly ownerUserId?: string | undefined;
16
+ /** The workspace's events and those of its runs and sessions. */
17
+ readonly workspaceId?: string | undefined;
18
+ /** The run's events and those of its sessions. */
19
+ readonly runId?: string | undefined;
20
+ /** The session's events. */
21
+ readonly sessionId?: string | undefined;
22
+ }
23
+ /** How long {@link Wakeups.next} waits before the caller reads again. */
24
+ export interface WakeOptions {
25
+ /** While changes are not pushed (no push channel, a cut, a lost listen): read again after this. */
26
+ readonly poll: Duration.Input;
27
+ /** Read again after this whatever happens: a deadline the caller keeps. */
28
+ readonly atMost?: Duration.Input | undefined;
29
+ }
30
+ /**
31
+ * When to read again. A wait reads the state it waits on, then calls `next` and reads again when
32
+ * it returns, until the state is what it waited for.
33
+ */
34
+ export interface Wakeups {
35
+ /**
36
+ * Returns on the next matching change or `resync`, after `poll` while changes are not being
37
+ * pushed, after `atMost` regardless, and otherwise after a long safety interval, so a wait never
38
+ * depends on one event arriving.
39
+ */
40
+ readonly next: (options: WakeOptions) => Effect.Effect<void>;
41
+ /** Whether changes are being pushed right now. */
42
+ readonly pushed: Effect.Effect<boolean>;
43
+ }
44
+ export interface SealantEventsShape {
45
+ /**
46
+ * Every matching event, for as long as the stream is consumed. A cut connection reconnects with
47
+ * jittered exponential backoff (reset once an event arrives), and each new connection starts
48
+ * with `resync` (`subscribed`). Fails only when the control plane refuses the stream outright:
49
+ * `404` from one older than it, `401`/`403` for a key that may not read events.
50
+ */
51
+ readonly stream: (filter?: EventFilter) => Stream.Stream<ControlPlaneEvent, SealantStreamRefusedError>;
52
+ /**
53
+ * Subscribes for the scope's lifetime and returns once the subscription is live (or has not
54
+ * come up within two seconds), so no change made after it returns is missed. With no push
55
+ * channel at all, `next` falls back to `poll`.
56
+ */
57
+ readonly watch: (filter?: EventFilter) => Effect.Effect<Wakeups, never, Scope.Scope>;
58
+ }
59
+ declare const SealantEvents_base: Context.ServiceClass<SealantEvents, "@sealant/sdk/SealantEvents", SealantEventsShape>;
60
+ export declare class SealantEvents extends SealantEvents_base {
61
+ }
62
+ export {};
@@ -0,0 +1,3 @@
1
+ import { Context } from "effect";
2
+ export class SealantEvents extends Context.Service()("@sealant/sdk/SealantEvents") {
3
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Server-Sent Events from the control plane's raw streaming routes (`GET /v1/events`, a session's
3
+ * output stream), which the schema-derived `HttpApi` cannot describe. One connection is one
4
+ * `Stream` of SSE events that ends when the body ends: reconnecting, and deciding what a reconnect
5
+ * resumes from, belong to the caller, which knows its cursor.
6
+ *
7
+ * A request carries the same headers as every contract call (priority, trace, API key) and goes
8
+ * through the same `HttpClient`, but not the retry middleware: a stream reconnects itself.
9
+ */
10
+ import { Context, Layer, Stream } from "effect";
11
+ import { Sse } from "effect/encoding";
12
+ import { HttpClient } from "effect/http";
13
+ import { SealantConfig } from "./config.js";
14
+ import { SealantStreamRefusedError, SealantTransportError } from "./errors.js";
15
+ /** What one stream connection fails with. */
16
+ export type SseConnectionError = SealantTransportError | SealantStreamRefusedError;
17
+ export interface SseConnectOptions {
18
+ /** The route, for errors and spans: `GET /v1/events`. */
19
+ readonly route: {
20
+ readonly method: "GET";
21
+ readonly path: string;
22
+ };
23
+ /** The span that opening the connection makes, e.g. `sealant.sdk.events.stream`. */
24
+ readonly span: string;
25
+ readonly path: string;
26
+ readonly query: Readonly<Record<string, string | undefined>>;
27
+ readonly headers?: Readonly<Record<string, string>>;
28
+ }
29
+ export interface SseClientShape {
30
+ /**
31
+ * One connection's events, ending when the body ends. A refusal a retry cannot change (4xx other
32
+ * than 408 and 429) fails with `SealantStreamRefusedError`; anything else with
33
+ * `SealantTransportError`, which a caller may reconnect after.
34
+ */
35
+ readonly connect: (options: SseConnectOptions) => Stream.Stream<Sse.Event, SseConnectionError>;
36
+ }
37
+ declare const SseClient_base: Context.ServiceClass<SseClient, "@sealant/sdk/SseClient", SseClientShape>;
38
+ /** The SSE client the streaming services share, over the root's `HttpClient`. */
39
+ export declare class SseClient extends SseClient_base {
40
+ static readonly layer: Layer.Layer<SseClient, never, SealantConfig | HttpClient.HttpClient>;
41
+ }
42
+ export {};
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Server-Sent Events from the control plane's raw streaming routes (`GET /v1/events`, a session's
3
+ * output stream), which the schema-derived `HttpApi` cannot describe. One connection is one
4
+ * `Stream` of SSE events that ends when the body ends: reconnecting, and deciding what a reconnect
5
+ * resumes from, belong to the caller, which knows its cursor.
6
+ *
7
+ * A request carries the same headers as every contract call (priority, trace, API key) and goes
8
+ * through the same `HttpClient`, but not the retry middleware: a stream reconnects itself.
9
+ */
10
+ import { Context, Effect, Layer, Stream } from "effect";
11
+ import { Sse } from "effect/encoding";
12
+ import { HttpClient, HttpClientRequest } from "effect/http";
13
+ import { authorize, HostRequestPriority } from "./api-client.js";
14
+ import { SealantConfig } from "./config.js";
15
+ import { SealantStreamRefusedError, SealantTransportError } from "./errors.js";
16
+ import { traceCall } from "./trace.js";
17
+ /** Statuses after which asking again could get another answer. */
18
+ const mayChange = (status) => status === 408 || status === 429 || status >= 500;
19
+ const refusal = (options, response) => Effect.flatMap(response.text.pipe(Effect.orElseSucceed(() => "")), (body) => {
20
+ const stream = `${options.route.method} ${options.route.path}`;
21
+ const message = `${stream} answered ${response.status}${body.length > 0 ? `: ${body.slice(0, 200)}` : ""}`;
22
+ return mayChange(response.status)
23
+ ? Effect.fail(new SealantTransportError({
24
+ operation: stream,
25
+ message,
26
+ status: response.status,
27
+ cause: undefined,
28
+ }))
29
+ : Effect.fail(new SealantStreamRefusedError({ stream, status: response.status, message }));
30
+ });
31
+ const make = Effect.gen(function* () {
32
+ const config = yield* SealantConfig;
33
+ const host = yield* HostRequestPriority;
34
+ const client = (yield* HttpClient.HttpClient).pipe(HttpClient.mapRequestEffect(authorize(config, host)));
35
+ const connect = (options) => {
36
+ const stream = `${options.route.method} ${options.route.path}`;
37
+ const url = new URL(options.path, config.baseUrl);
38
+ for (const [key, value] of Object.entries(options.query)) {
39
+ if (value !== undefined)
40
+ url.searchParams.set(key, value);
41
+ }
42
+ const request = HttpClientRequest.get(url).pipe(HttpClientRequest.setHeaders({ accept: "text/event-stream", ...options.headers }));
43
+ const open = traceCall(options.span, {}, client.execute(request), options.route).pipe(Effect.mapError((cause) => new SealantTransportError({
44
+ operation: stream,
45
+ message: `${stream} could not be opened: ${cause.message}`,
46
+ cause,
47
+ })), Effect.flatMap((response) => {
48
+ if (response.status < 200 || response.status >= 300)
49
+ return refusal(options, response);
50
+ // A server that answers this route with anything but an event stream does not serve it.
51
+ const type = response.headers["content-type"] ?? "";
52
+ if (!type.startsWith("text/event-stream")) {
53
+ return Effect.fail(new SealantStreamRefusedError({
54
+ stream,
55
+ status: response.status,
56
+ message: `${stream} answered ${response.status} with ${type.length > 0 ? type : "no content type"}, not an event stream`,
57
+ }));
58
+ }
59
+ return Effect.succeed(response);
60
+ }));
61
+ return Stream.unwrap(Effect.map(open, (response) => response.stream)).pipe(Stream.decodeText(), Stream.pipeThroughChannel(Sse.decode()), Stream.mapError((cause) => {
62
+ if (cause instanceof SealantTransportError || cause instanceof SealantStreamRefusedError)
63
+ return cause;
64
+ return new SealantTransportError({
65
+ operation: stream,
66
+ message: `${stream} was cut: ${Sse.Retry.is(cause) ? "the server asked for a reconnect" : cause.message}`,
67
+ cause,
68
+ });
69
+ }));
70
+ };
71
+ return { connect };
72
+ });
73
+ /** The SSE client the streaming services share, over the root's `HttpClient`. */
74
+ export class SseClient extends Context.Service()("@sealant/sdk/SseClient") {
75
+ static layer = Layer.effect(SseClient, make);
76
+ }
@@ -1,31 +1,64 @@
1
1
  /**
2
- * @sealant/sdk/effect — the Effect-native core of the SDK, for consumers that are Effect end-to-end.
2
+ * @sealant/sdk/effect — the SDK for Effect programs: services, layers and typed errors, with no
3
+ * Promise in the way.
3
4
  *
4
- * The Promise facade (`@sealant/sdk`) is a thin wrapper over what this subpath exports directly:
5
+ * import { Effect, Layer } from "effect"
6
+ * import { ActingOwner, SealantConfig, SealantLayer, Workspaces } from "@sealant/sdk/effect"
5
7
  *
6
- * - `SealantApiClient` + `sealantApiClientLayer` — the contract-derived control-plane client as an
7
- * Effect service. The client is generated from the `@sealant/api-contracts` `HttpApi`, so its
8
- * request/response types and tagged error channel are the contract's, by construction.
9
- * - The operation effects (`createWorkspaceOp`, `createRunOp`, `getRunTimelineOp`, …) — one per
10
- * contract endpoint, returning WIRE types on a typed error channel.
11
- * - `makeSdkRuntime` — the managed runtime the facade itself runs on, for consumers who want the
12
- * memoized layer build + `SealantError` mapping without hand-rolling a scope.
13
- * - The tagged contract errors (`WorkspaceNotFoundError`, `RunNotFoundError`, …) so failures can be
14
- * matched with `Effect.catchTag` instead of string-matching a squashed `SealantError`.
8
+ * const ready = Effect.gen(function* () {
9
+ * const workspaces = yield* Workspaces
10
+ * return yield* workspaces.waitReady("ws_123")
11
+ * }).pipe(Effect.provideService(ActingOwner, "usr_alice"))
15
12
  *
16
- * Errors: effects composed from this subpath fail with the TYPED contract errors (plus Effect HTTP
17
- * client/schema errors) — nothing is squashed. The plain `SealantError` classes only enter play via
18
- * `makeSdkRuntime`, which maps the typed channel at the Promise boundary exactly like the facade.
13
+ * ready.pipe(Effect.provide(SealantLayer.pipe(Layer.provide(SealantConfig.layerFromEnv))))
14
+ *
15
+ * - Services: `Workspaces`, `Runs`, `Sessions` (with `attach`, a scoped duplex socket that
16
+ * resumes across cuts) and `SealantEvents` (the control plane's push channel). Every wait is
17
+ * woken by events, not a timer.
18
+ * - Context: `SealantConfig` (where the control plane is, the API key as `Redacted`),
19
+ * `ActingOwner` (who a call acts for, per fiber: one layer serves every user) and
20
+ * `RequestPriority`.
21
+ * - Layers: `SealantLayer` (fetch and the global `WebSocket` provided; needs `SealantConfig`)
22
+ * and `SealantLayerNoInfra` (bring your own `HttpClient` and `WebSocketConstructor`), and each
23
+ * service's own `layer` and `layerNoDeps`.
24
+ * - Errors: every failure is a `Schema.TaggedError` — the contract's (`WorkspaceNotFoundError`,
25
+ * …) and the SDK's (`SealantTransportError`, `SealantWaitTimeoutError`, …) — for
26
+ * `Effect.catchTag`.
27
+ *
28
+ * Below the services: `SealantApiClient`, the client derived from `@sealant/api-contracts`, and
29
+ * one operation effect per contract endpoint (`createWorkspaceOp`, …), in wire types.
19
30
  */
31
+ export { DEFAULT_OWNER_USER_ID, DEFAULT_REGISTRY_ID, SealantConfig } from "./config.js";
32
+ export type { SealantConfigOptions, SealantConfigShape } from "./config.js";
33
+ export { ActingOwner, currentOwner, RequestPriority } from "./context.js";
34
+ export type { RequestPriorityLevel } from "./context.js";
35
+ export { SealantStreamRefusedError, SealantTransportError, SealantWaitTimeoutError, SessionAttachError, SessionEndedError, WorkspaceSettledError, } from "./errors.js";
36
+ export type { SealantSdkError, Transported } from "./errors.js";
37
+ export type { EndpointError } from "./endpoint.js";
38
+ export { SealantEvents } from "./events/service.js";
39
+ export type { EventFilter, SealantEventsShape, WakeOptions, Wakeups } from "./events/service.js";
40
+ export * as SealantEventsLayer from "./events/layer.js";
41
+ export { Workspaces } from "./workspaces/service.js";
42
+ export type { ExecAsUserOptions, ExecOptions, WaitReadyOptions, WaitStoppedOptions, WorkspaceReadError, WorkspacesShape, } from "./workspaces/service.js";
43
+ export * as WorkspacesLayer from "./workspaces/layer.js";
44
+ export { Runs } from "./runs/service.js";
45
+ export type { RunReadError, RunsShape, StreamOptions as RunStreamOptions, TimelineOptions, TimelineReadError, WaitOptions as RunWaitOptions, } from "./runs/service.js";
46
+ export * as RunsLayer from "./runs/layer.js";
47
+ export { Sessions } from "./sessions/service.js";
48
+ export type { AttachedSession, AttachOptions, OutputOptions as SessionOutputOptions, SessionOutputChunk, SessionReadError, SessionSignal, SessionsShape, } from "./sessions/service.js";
49
+ export * as SessionsLayer from "./sessions/layer.js";
50
+ export { SealantLayer, SealantLayerNoInfra } from "./layer.js";
51
+ export type { SealantServices } from "./layer.js";
52
+ export { WebSocketConstructorLayer } from "./websocket.js";
20
53
  export { SealantApiClient, sealantApiClientLayer } from "./api-client.js";
21
54
  export type { ControlPlaneClient } from "./api-client.js";
22
55
  export { CurrentRetryPolicy, DEFAULT_HTTP_RETRY_POLICY, NO_HTTP_RETRY_POLICY, isTransientSdkError, retryTransientEffect, withHttpRetryMiddleware, } from "./retry-middleware.js";
23
56
  export type { HttpRetryPolicy, RetryTransientEffectOptions } from "./retry-middleware.js";
24
57
  export * from "./operations.js";
25
- export { makeSdkRuntime } from "./runtime.js";
58
+ export { makeSdkRuntime, sdkLayer } from "./runtime.js";
26
59
  export type { SdkRuntime, SdkServices } from "./runtime.js";
27
60
  export { captureCallerTrace } from "./trace.js";
28
61
  export type { CallerTrace } from "./trace.js";
29
62
  export { resolveInternalConfig } from "../internal/config.js";
30
63
  export type { SealantHostLocalConfig, SealantInternalConfig } from "../internal/config.js";
31
- export { isRateLimitedContractError, isRetryableContractError, isTransientContractError, ConnectedAccountBadRequestError, ConnectedAccountConflictError, ConnectedAccountInternalServerError, ConnectedAccountNotFoundError, ConnectedAccountServiceUnavailableError, InferenceBadRequestError, InferenceConflictError, InferenceInternalServerError, InferenceNotFoundError, InferenceUnavailableError, RunBadRequestError, RunInternalServerError, RunNotFoundError, UserBadRequestError, UserInternalServerError, UserNotFoundError, WorkspaceBadGatewayError, WorkspaceBadRequestError, WorkspaceConflictError, WorkspaceForbiddenError, WorkspaceInternalServerError, WorkspaceNotFoundError, WorkspaceRuntimeRequirementUnsupportedError, WorkspaceServiceUnavailableError, WorkspaceUnauthorizedError, } from "@sealant/api-contracts";
64
+ export { BudgetExceededError, RequestRefusedError, SessionBadGatewayError, SessionBadRequestError, SessionConflictError, SessionForbiddenError, SessionInternalServerError, SessionNotFoundError, SessionUnauthorizedError, isRateLimitedContractError, isRetryableContractError, isTransientContractError, ConnectedAccountBadRequestError, ConnectedAccountConflictError, ConnectedAccountInternalServerError, ConnectedAccountNotFoundError, ConnectedAccountServiceUnavailableError, InferenceBadRequestError, InferenceConflictError, InferenceInternalServerError, InferenceNotFoundError, InferenceUnavailableError, RunBadRequestError, RunInternalServerError, RunNotFoundError, UserBadRequestError, UserInternalServerError, UserNotFoundError, WorkspaceBadGatewayError, WorkspaceBadRequestError, WorkspaceConflictError, WorkspaceForbiddenError, WorkspaceInternalServerError, WorkspaceNotFoundError, WorkspaceRuntimeRequirementUnsupportedError, WorkspaceServiceUnavailableError, WorkspaceUnauthorizedError, } from "@sealant/api-contracts";
@@ -1,22 +1,50 @@
1
1
  /**
2
- * @sealant/sdk/effect — the Effect-native core of the SDK, for consumers that are Effect end-to-end.
2
+ * @sealant/sdk/effect — the SDK for Effect programs: services, layers and typed errors, with no
3
+ * Promise in the way.
3
4
  *
4
- * The Promise facade (`@sealant/sdk`) is a thin wrapper over what this subpath exports directly:
5
+ * import { Effect, Layer } from "effect"
6
+ * import { ActingOwner, SealantConfig, SealantLayer, Workspaces } from "@sealant/sdk/effect"
5
7
  *
6
- * - `SealantApiClient` + `sealantApiClientLayer` — the contract-derived control-plane client as an
7
- * Effect service. The client is generated from the `@sealant/api-contracts` `HttpApi`, so its
8
- * request/response types and tagged error channel are the contract's, by construction.
9
- * - The operation effects (`createWorkspaceOp`, `createRunOp`, `getRunTimelineOp`, …) — one per
10
- * contract endpoint, returning WIRE types on a typed error channel.
11
- * - `makeSdkRuntime` — the managed runtime the facade itself runs on, for consumers who want the
12
- * memoized layer build + `SealantError` mapping without hand-rolling a scope.
13
- * - The tagged contract errors (`WorkspaceNotFoundError`, `RunNotFoundError`, …) so failures can be
14
- * matched with `Effect.catchTag` instead of string-matching a squashed `SealantError`.
8
+ * const ready = Effect.gen(function* () {
9
+ * const workspaces = yield* Workspaces
10
+ * return yield* workspaces.waitReady("ws_123")
11
+ * }).pipe(Effect.provideService(ActingOwner, "usr_alice"))
15
12
  *
16
- * Errors: effects composed from this subpath fail with the TYPED contract errors (plus Effect HTTP
17
- * client/schema errors) — nothing is squashed. The plain `SealantError` classes only enter play via
18
- * `makeSdkRuntime`, which maps the typed channel at the Promise boundary exactly like the facade.
13
+ * ready.pipe(Effect.provide(SealantLayer.pipe(Layer.provide(SealantConfig.layerFromEnv))))
14
+ *
15
+ * - Services: `Workspaces`, `Runs`, `Sessions` (with `attach`, a scoped duplex socket that
16
+ * resumes across cuts) and `SealantEvents` (the control plane's push channel). Every wait is
17
+ * woken by events, not a timer.
18
+ * - Context: `SealantConfig` (where the control plane is, the API key as `Redacted`),
19
+ * `ActingOwner` (who a call acts for, per fiber: one layer serves every user) and
20
+ * `RequestPriority`.
21
+ * - Layers: `SealantLayer` (fetch and the global `WebSocket` provided; needs `SealantConfig`)
22
+ * and `SealantLayerNoInfra` (bring your own `HttpClient` and `WebSocketConstructor`), and each
23
+ * service's own `layer` and `layerNoDeps`.
24
+ * - Errors: every failure is a `Schema.TaggedError` — the contract's (`WorkspaceNotFoundError`,
25
+ * …) and the SDK's (`SealantTransportError`, `SealantWaitTimeoutError`, …) — for
26
+ * `Effect.catchTag`.
27
+ *
28
+ * Below the services: `SealantApiClient`, the client derived from `@sealant/api-contracts`, and
29
+ * one operation effect per contract endpoint (`createWorkspaceOp`, …), in wire types.
19
30
  */
31
+ // Configuration and per-fiber context.
32
+ export { DEFAULT_OWNER_USER_ID, DEFAULT_REGISTRY_ID, SealantConfig } from "./config.js";
33
+ export { ActingOwner, currentOwner, RequestPriority } from "./context.js";
34
+ // The SDK's own errors (the contract's are re-exported below).
35
+ export { SealantStreamRefusedError, SealantTransportError, SealantWaitTimeoutError, SessionAttachError, SessionEndedError, WorkspaceSettledError, } from "./errors.js";
36
+ // The services, each with its layers as a namespace (`WorkspacesLayer.layer`, `.layerNoDeps`).
37
+ export { SealantEvents } from "./events/service.js";
38
+ export * as SealantEventsLayer from "./events/layer.js";
39
+ export { Workspaces } from "./workspaces/service.js";
40
+ export * as WorkspacesLayer from "./workspaces/layer.js";
41
+ export { Runs } from "./runs/service.js";
42
+ export * as RunsLayer from "./runs/layer.js";
43
+ export { Sessions } from "./sessions/service.js";
44
+ export * as SessionsLayer from "./sessions/layer.js";
45
+ // The composed layers.
46
+ export { SealantLayer, SealantLayerNoInfra } from "./layer.js";
47
+ export { WebSocketConstructorLayer } from "./websocket.js";
20
48
  // The contract-derived client service + layer.
21
49
  export { SealantApiClient, sealantApiClientLayer } from "./api-client.js";
22
50
  // HTTP retry/timeout middleware policy and Effect-level transient retry combinator.
@@ -24,12 +52,12 @@ export { CurrentRetryPolicy, DEFAULT_HTTP_RETRY_POLICY, NO_HTTP_RETRY_POLICY, is
24
52
  // One operation effect per contract endpoint (wire types in, wire types out).
25
53
  export * from "./operations.js";
26
54
  // The managed runtime the Promise facade runs on.
27
- export { makeSdkRuntime } from "./runtime.js";
55
+ export { makeSdkRuntime, sdkLayer } from "./runtime.js";
28
56
  // Trace continuation: the caller's trace an SDK call continues (see `captureCallerTrace`).
29
57
  export { captureCallerTrace } from "./trace.js";
30
58
  // The config the layer/runtime constructors take, and the resolver from the public `SealantConfig`.
31
59
  export { resolveInternalConfig } from "../internal/config.js";
32
- // The typed contract errors carried on the client's failure channel (workspaces + runs +
60
+ // The typed contract errors carried on the client's failure channel (workspaces, runs, sessions,
33
61
  // inference — the groups the operations above call). Re-exported so Effect consumers don't need to
34
62
  // depend on the contracts package directly to `Effect.catchTag` a failure.
35
- export { isRateLimitedContractError, isRetryableContractError, isTransientContractError, ConnectedAccountBadRequestError, ConnectedAccountConflictError, ConnectedAccountInternalServerError, ConnectedAccountNotFoundError, ConnectedAccountServiceUnavailableError, InferenceBadRequestError, InferenceConflictError, InferenceInternalServerError, InferenceNotFoundError, InferenceUnavailableError, RunBadRequestError, RunInternalServerError, RunNotFoundError, UserBadRequestError, UserInternalServerError, UserNotFoundError, WorkspaceBadGatewayError, WorkspaceBadRequestError, WorkspaceConflictError, WorkspaceForbiddenError, WorkspaceInternalServerError, WorkspaceNotFoundError, WorkspaceRuntimeRequirementUnsupportedError, WorkspaceServiceUnavailableError, WorkspaceUnauthorizedError, } from "@sealant/api-contracts";
63
+ export { BudgetExceededError, RequestRefusedError, SessionBadGatewayError, SessionBadRequestError, SessionConflictError, SessionForbiddenError, SessionInternalServerError, SessionNotFoundError, SessionUnauthorizedError, isRateLimitedContractError, isRetryableContractError, isTransientContractError, ConnectedAccountBadRequestError, ConnectedAccountConflictError, ConnectedAccountInternalServerError, ConnectedAccountNotFoundError, ConnectedAccountServiceUnavailableError, InferenceBadRequestError, InferenceConflictError, InferenceInternalServerError, InferenceNotFoundError, InferenceUnavailableError, RunBadRequestError, RunInternalServerError, RunNotFoundError, UserBadRequestError, UserInternalServerError, UserNotFoundError, WorkspaceBadGatewayError, WorkspaceBadRequestError, WorkspaceConflictError, WorkspaceForbiddenError, WorkspaceInternalServerError, WorkspaceNotFoundError, WorkspaceRuntimeRequirementUnsupportedError, WorkspaceServiceUnavailableError, WorkspaceUnauthorizedError, } from "@sealant/api-contracts";