@sealant/sdk-next 0.40.0-next.941 → 0.40.0-next.944

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.
package/dist/client.js CHANGED
@@ -1,7 +1,9 @@
1
1
  import { archiveConnectedAccountOp, archiveSshKeyOp, cancelWorkspaceCreateOp, createAccessTokenOp, checkBoatAccountOp, checkBoatInstallKeyOp, getBoatInstallKeyOp, proveBoatAccountOp, createBoatAccountOp, createConnectedAccountOp, createSshKeyOp, createWorkspaceOp, ensureUserOp, getRunOp, getSetupStateOp, getUserOp, bindUserPersonOp, getWorkspaceCreateOp, getWorkspaceOp, inferenceRespondOp, inspectWorkspaceImageOp, listWorkspaceRuntimesOp, listBoatAccountsOp, listConnectedAccountsOp, listSshKeysOp, listWorkspacesOp, markConnectedAccountInvalidOp, removeBoatAccountOp, rotateBoatAccountKeyOp, setBoatAccountOrganizationOp, setConnectedAccountDefaultOp, } from "./effect/operations.js";
2
2
  import { runHarness, startHarness } from "./effect/run-harness.js";
3
3
  import { makeSdkRuntime } from "./effect/runtime.js";
4
+ import { withCallerTrace } from "./effect/trace.js";
4
5
  import { SealantBudgetExceededError, SealantError } from "./errors.js";
6
+ import { captureTrace } from "./facade/context.js";
5
7
  import { makeRun } from "./facade/run.js";
6
8
  import { makeWorkspace, registerHarnessExecutors, toRuntimeInfo, toWorkspaceImage, } from "./facade/workspace.js";
7
9
  import { buildCreateWorkspaceRequest } from "./internal/blueprint.js";
@@ -86,11 +88,13 @@ export class Sealant {
86
88
  /** Workspace lifecycle: create, fetch, and list live environments. */
87
89
  workspaces = {
88
90
  create: async (options) => {
91
+ // Every request create makes, readiness polls included, continues the caller's trace.
92
+ const trace = captureTrace(this.#ctx);
89
93
  if (options.sshAsOwner === true) {
90
- await requireSshUser(this.#ctx);
94
+ await withCallerTrace(trace, () => requireSshUser(this.#ctx));
91
95
  }
92
96
  const { payload } = buildCreateWorkspaceRequest(options, this.#ctx.config);
93
- const created = await this.#runtime.run(createWorkspaceOp(payload));
97
+ const created = await this.#runtime.run(createWorkspaceOp(payload), trace);
94
98
  const workspace = makeWorkspace(this.#ctx, {
95
99
  id: created.workspaceId,
96
100
  name: created.name,
@@ -120,7 +124,7 @@ export class Sealant {
120
124
  const onEvent = options.onEvent;
121
125
  void (async () => {
122
126
  try {
123
- for await (const event of workspace.events()) {
127
+ for await (const event of withCallerTrace(trace, () => workspace.events())) {
124
128
  onEvent(event);
125
129
  }
126
130
  }
@@ -129,7 +133,7 @@ export class Sealant {
129
133
  }
130
134
  })();
131
135
  }
132
- return workspace.ready().catch((error) => {
136
+ return withCallerTrace(trace, () => workspace.ready()).catch((error) => {
133
137
  if (error instanceof SealantBudgetExceededError) {
134
138
  throw new SealantError(`Workspace ${created.workspaceId} was created, but a readiness request reached its budget. Resume this workspace instead of creating it again.`, { code: "workspace_readiness_refused", cause: error });
135
139
  }
@@ -9872,6 +9872,9 @@ declare const SealantApiClient_base: Context.ServiceClass<SealantApiClient, "@se
9872
9872
  }>;
9873
9873
  export declare class SealantApiClient extends SealantApiClient_base {
9874
9874
  }
9875
- /** Live layer: derives the client over the global-fetch `HttpClient`, with an optional bearer token. */
9875
+ /**
9876
+ * Live layer: derives the client over a fetch `HttpClient` (the configured `fetch`, else the
9877
+ * global one), with an optional bearer token.
9878
+ */
9876
9879
  export declare const sealantApiClientLayer: (config: SealantInternalConfig) => Layer.Layer<SealantApiClient>;
9877
9880
  export {};
@@ -13,21 +13,36 @@ import { Context, Effect, Layer } from "effect";
13
13
  import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
14
14
  import { HttpApiClient } from "effect/http-api";
15
15
  import { resolveRequestPriority } from "../internal/config.js";
16
+ import { CallerTraceState, DirectTraceparent, instrumentClient } from "./trace.js";
16
17
  /** A per-operation priority; providing it never changes concurrent requests. */
17
18
  export const CurrentRequestPriority = Context.Reference("@sealant/sdk/CurrentRequestPriority", { defaultValue: () => undefined });
18
19
  /** Builds the contract-derived client. Requires an `HttpClient` in context (provided by the layer). */
19
20
  const buildControlPlaneClient = (config) => {
20
- return HttpApiClient.make(ControlPlaneAPI, {
21
+ return Effect.map(HttpApiClient.make(ControlPlaneAPI, {
21
22
  baseUrl: config.baseUrl,
22
- transformClient: (client) => HttpClient.mapRequestEffect(client, (request) => Effect.map(CurrentRequestPriority, (priority) => {
23
- const prioritized = HttpClientRequest.setHeader(request, "x-sealant-request-priority", resolveRequestPriority(config.requestPriority, priority));
23
+ transformClient: (client) => HttpClient.mapRequestEffect(client, (request) => Effect.gen(function* () {
24
+ const priority = yield* CurrentRequestPriority;
25
+ const traceparent = yield* DirectTraceparent;
26
+ const tracestate = yield* CallerTraceState;
27
+ const prioritized = HttpClientRequest.setHeaders(request, {
28
+ "x-sealant-request-priority": resolveRequestPriority(config.requestPriority, priority),
29
+ // Effect's own propagation is off whenever `DirectTraceparent` is set, so this
30
+ // header is the one that reaches the server.
31
+ ...(traceparent === undefined ? {} : { traceparent }),
32
+ ...(tracestate === undefined ? {} : { tracestate }),
33
+ });
24
34
  return config.apiKey === undefined
25
35
  ? prioritized
26
36
  : HttpClientRequest.bearerToken(prioritized, config.apiKey);
27
37
  })),
28
- });
38
+ }), instrumentClient);
29
39
  };
30
40
  export class SealantApiClient extends Context.Service()("@sealant/sdk/SealantApiClient") {
31
41
  }
32
- /** Live layer: derives the client over the global-fetch `HttpClient`, with an optional bearer token. */
33
- export const sealantApiClientLayer = (config) => Layer.effect(SealantApiClient, buildControlPlaneClient(config)).pipe(Layer.provide(FetchHttpClient.layer));
42
+ /**
43
+ * Live layer: derives the client over a fetch `HttpClient` (the configured `fetch`, else the
44
+ * global one), with an optional bearer token.
45
+ */
46
+ export const sealantApiClientLayer = (config) => Layer.effect(SealantApiClient, buildControlPlaneClient(config)).pipe(Layer.provide(config.fetch === undefined
47
+ ? FetchHttpClient.layer
48
+ : FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, config.fetch)))));
@@ -22,6 +22,8 @@ export type { ControlPlaneClient } from "./api-client.js";
22
22
  export * from "./operations.js";
23
23
  export { makeSdkRuntime } from "./runtime.js";
24
24
  export type { SdkRuntime, SdkServices } from "./runtime.js";
25
+ export { captureCallerTrace } from "./trace.js";
26
+ export type { CallerTrace } from "./trace.js";
25
27
  export { resolveInternalConfig } from "../internal/config.js";
26
28
  export type { SealantHostLocalConfig, SealantInternalConfig } from "../internal/config.js";
27
29
  export { 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";
@@ -23,6 +23,8 @@ export { SealantApiClient, sealantApiClientLayer } from "./api-client.js";
23
23
  export * from "./operations.js";
24
24
  // The managed runtime the Promise facade runs on.
25
25
  export { makeSdkRuntime } from "./runtime.js";
26
+ // Trace continuation: the caller's trace an SDK call continues (see `captureCallerTrace`).
27
+ export { captureCallerTrace } from "./trace.js";
26
28
  // The config the layer/runtime constructors take, and the resolver from the public `SealantConfig`.
27
29
  export { resolveInternalConfig } from "../internal/config.js";
28
30
  // The typed contract errors carried on the client's failure channel (workspaces + runs +
@@ -550,71 +550,71 @@ export declare const listWorkspaceRuntimesOp: () => Effect.Effect<{
550
550
  readonly runtime: "boat" | "cloudflare" | "docker" | "host-vm" | "k3s" | "k8s" | "microvm";
551
551
  readonly os: {
552
552
  readonly ubuntu: {
553
+ readonly supported: true;
554
+ } | {
553
555
  readonly supported: false;
554
556
  readonly message: string;
555
- } | {
556
- readonly supported: true;
557
557
  };
558
558
  readonly nix: {
559
+ readonly supported: true;
560
+ } | {
559
561
  readonly supported: false;
560
562
  readonly message: string;
561
- } | {
562
- readonly supported: true;
563
563
  };
564
564
  readonly arch: {
565
+ readonly supported: true;
566
+ } | {
565
567
  readonly supported: false;
566
568
  readonly message: string;
567
- } | {
568
- readonly supported: true;
569
569
  };
570
570
  readonly fedora: {
571
+ readonly supported: true;
572
+ } | {
571
573
  readonly supported: false;
572
574
  readonly message: string;
573
- } | {
574
- readonly supported: true;
575
575
  };
576
576
  };
577
577
  readonly customImage: {
578
+ readonly supported: true;
579
+ } | {
578
580
  readonly supported: false;
579
581
  readonly message: string;
580
- } | {
581
- readonly supported: true;
582
582
  };
583
583
  readonly hostDirectories: {
584
+ readonly supported: true;
585
+ } | {
584
586
  readonly supported: false;
585
587
  readonly message: string;
586
- } | {
587
- readonly supported: true;
588
588
  };
589
589
  readonly docker: {
590
+ readonly supported: true;
591
+ } | {
590
592
  readonly supported: false;
591
593
  readonly message: string;
592
- } | {
593
- readonly supported: true;
594
594
  };
595
595
  readonly gvisor: {
596
+ readonly supported: true;
597
+ } | {
596
598
  readonly supported: false;
597
599
  readonly message: string;
598
- } | {
599
- readonly supported: true;
600
600
  };
601
601
  readonly clusterEnv: {
602
+ readonly supported: true;
603
+ } | {
602
604
  readonly supported: false;
603
605
  readonly message: string;
604
- } | {
605
- readonly supported: true;
606
606
  };
607
607
  readonly gitSource: {
608
+ readonly supported: true;
609
+ } | {
608
610
  readonly supported: false;
609
611
  readonly message: string;
610
- } | {
611
- readonly supported: true;
612
612
  };
613
613
  readonly dotfilesArchives: {
614
+ readonly supported: true;
615
+ } | {
614
616
  readonly supported: false;
615
617
  readonly message: string;
616
- } | {
617
- readonly supported: true;
618
618
  };
619
619
  readonly screen: {
620
620
  readonly supported: false;
@@ -637,28 +637,28 @@ export declare const listWorkspaceRuntimesOp: () => Effect.Effect<{
637
637
  };
638
638
  readonly networkPolicy?: {
639
639
  readonly vmIsolation: {
640
+ readonly supported: true;
641
+ } | {
640
642
  readonly supported: false;
641
643
  readonly message: string;
642
- } | {
643
- readonly supported: true;
644
644
  };
645
645
  readonly restricted: {
646
+ readonly supported: true;
647
+ } | {
646
648
  readonly supported: false;
647
649
  readonly message: string;
648
- } | {
649
- readonly supported: true;
650
650
  };
651
651
  readonly restrictedWithDocker: {
652
+ readonly supported: true;
653
+ } | {
652
654
  readonly supported: false;
653
655
  readonly message: string;
654
- } | {
655
- readonly supported: true;
656
656
  };
657
657
  readonly brokeredSecrets: {
658
+ readonly supported: true;
659
+ } | {
658
660
  readonly supported: false;
659
661
  readonly message: string;
660
- } | {
661
- readonly supported: true;
662
662
  };
663
663
  } | undefined;
664
664
  }[];
@@ -11,11 +11,16 @@
11
11
  import { Effect } from "effect";
12
12
  import type { SealantInternalConfig } from "../internal/config.js";
13
13
  import { SealantApiClient } from "./api-client.js";
14
+ import { type CallerTrace } from "./trace.js";
14
15
  /** Services the SDK runtime provides to operation effects. */
15
16
  export type SdkServices = SealantApiClient;
16
17
  export interface SdkRuntime {
17
- /** Provide the app context and run an operation effect, surfacing plain `SealantError`s. */
18
- readonly run: <A, E>(effect: Effect.Effect<A, E, SdkServices>) => Promise<A>;
18
+ /**
19
+ * Provide the app context and run an operation effect, surfacing plain `SealantError`s. The
20
+ * effect continues `trace` when given, else the caller's trace captured when `run` is called
21
+ * (see `captureCallerTrace`).
22
+ */
23
+ readonly run: <A, E>(effect: Effect.Effect<A, E, SdkServices>, trace?: CallerTrace) => Promise<A>;
19
24
  /** Dispose the runtime scope (the HTTP client). Idempotent. */
20
25
  readonly dispose: () => Promise<void>;
21
26
  }
@@ -11,6 +11,7 @@
11
11
  import { Cause, Context, Effect, Exit, Layer, Scope } from "effect";
12
12
  import { toSealantError } from "../internal/map-error.js";
13
13
  import { SealantApiClient, sealantApiClientLayer } from "./api-client.js";
14
+ import { captureCallerTrace, continueCallerTrace } from "./trace.js";
14
15
  // A single service: the contract-derived HTTP client. No DB pool, no docker-exec, no telemetry sink.
15
16
  const makeAppLayer = (config) => sealantApiClientLayer(config);
16
17
  export const makeSdkRuntime = (config) => {
@@ -37,17 +38,19 @@ export const makeSdkRuntime = (config) => {
37
38
  }
38
39
  return built;
39
40
  };
41
+ const runTraced = async (effect, trace) => {
42
+ const { context } = await build();
43
+ const provided = Effect.provide(effect, context).pipe(continueCallerTrace(trace));
44
+ const exit = await Effect.runPromiseExit(provided);
45
+ if (Exit.isSuccess(exit)) {
46
+ return exit.value;
47
+ }
48
+ // Squash the Cause to its underlying failure/defect value, then map to a plain error.
49
+ throw toSealantError(Cause.squash(exit.cause));
50
+ };
40
51
  return {
41
- run: async (effect) => {
42
- const { context } = await build();
43
- const provided = Effect.provide(effect, context);
44
- const exit = await Effect.runPromiseExit(provided);
45
- if (Exit.isSuccess(exit)) {
46
- return exit.value;
47
- }
48
- // Squash the Cause to its underlying failure/defect value, then map to a plain error.
49
- throw toSealantError(Cause.squash(exit.cause));
50
- },
52
+ // Captured before the first `await`, while a calling Effect fiber is still current.
53
+ run: (effect, trace) => runTraced(effect, trace ?? captureCallerTrace(config.traceContext)),
51
54
  dispose: async () => {
52
55
  if (built === undefined) {
53
56
  return;
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Trace continuation: every SDK call continues its caller's trace instead of starting its own.
3
+ *
4
+ * A call's parent is captured synchronously when the call starts, in this order:
5
+ *
6
+ * 1. the calling Effect fiber's current span (a Promise call made inside `Effect.promise` or
7
+ * `Effect.tryPromise` runs its first step while that fiber is current);
8
+ * 2. the client's `traceContext` provider;
9
+ * 3. the active OpenTelemetry context, read through `@opentelemetry/api`'s global registration,
10
+ * so the SDK imports and depends on no tracing package.
11
+ *
12
+ * Each contract call runs in a client span `sealant.sdk.<group>.<endpoint>` carrying only the IDs
13
+ * from its path. When the caller's Effect tracer exports spans, the SDK's spans are made on that
14
+ * tracer and the request carries the SDK's HTTP span. When nothing exports them, the request carries
15
+ * the parent's own `traceparent`, so the server's span hangs off a span that exists. With no parent
16
+ * and no exporting tracer the request carries no trace header at all.
17
+ */
18
+ import { Context, Effect, Tracer } from "effect";
19
+ import type { SealantTraceContext } from "../types.js";
20
+ /** The caller's trace, captured when a call starts and continued by everything that call does. */
21
+ export interface CallerTrace {
22
+ /** The span the call's spans hang off, when the caller has one. */
23
+ readonly parent: Tracer.AnySpan | undefined;
24
+ /** The calling fiber's tracer when it exports spans (anything but Effect's native tracer). */
25
+ readonly tracer: Tracer.Tracer | undefined;
26
+ /** The W3C `tracestate` that travels with an explicit or OpenTelemetry parent. */
27
+ readonly tracestate: string | undefined;
28
+ }
29
+ /** The `tracestate` a call forwards; set from the captured caller trace. */
30
+ export declare const CallerTraceState: Context.Reference<string | undefined>;
31
+ /** A `traceparent` the request carries as is, set when no exporting tracer makes the SDK's spans. */
32
+ export declare const DirectTraceparent: Context.Reference<string | undefined>;
33
+ /** A parsed W3C `traceparent`, or `undefined` for a malformed or invalid one. */
34
+ export declare function parseTraceparent(value: string): {
35
+ readonly traceId: string;
36
+ readonly spanId: string;
37
+ readonly sampled: boolean;
38
+ } | undefined;
39
+ /** The `traceparent` a span is continued by. */
40
+ export declare function formatTraceparent(span: Tracer.AnySpan): string;
41
+ /** The active OpenTelemetry span's context, when `@opentelemetry/api` is registered and has one. */
42
+ export declare function activeOpenTelemetryContext(): SealantTraceContext | undefined;
43
+ /**
44
+ * Call `f` so that every SDK call it starts synchronously captures `trace`: how a call that has
45
+ * already awaited hands its trace to another facade call (`create()` to `ready()`).
46
+ */
47
+ export declare function withCallerTrace<A>(trace: CallerTrace | undefined, f: () => A): A;
48
+ /**
49
+ * The caller's trace right now, or `undefined` when there is none. Synchronous: call it before the
50
+ * first `await` of a call, while a calling Effect fiber is still current.
51
+ */
52
+ export declare function captureCallerTrace(provider: (() => SealantTraceContext | undefined) | undefined): CallerTrace | undefined;
53
+ /** Run an effect as part of a captured caller trace. */
54
+ export declare const continueCallerTrace: (trace: CallerTrace | undefined) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
55
+ /** The trace headers a raw `fetch` made for a captured caller trace carries. */
56
+ export declare function traceHeaders(trace: CallerTrace | undefined): Readonly<Record<string, string>>;
57
+ /**
58
+ * Run one contract call in its client span, and choose what trace header its request carries (see
59
+ * the module comment).
60
+ */
61
+ export declare const traceCall: <A, E, R>(name: string, attributes: Readonly<Record<string, string>>, effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
62
+ /**
63
+ * The derived control-plane client with every endpoint run through {@link traceCall}, named
64
+ * `sealant.sdk.<group>.<endpoint>` from the contract's own identifiers.
65
+ */
66
+ export declare function instrumentClient<Client extends object>(client: Client): Client;
@@ -0,0 +1,252 @@
1
+ /**
2
+ * Trace continuation: every SDK call continues its caller's trace instead of starting its own.
3
+ *
4
+ * A call's parent is captured synchronously when the call starts, in this order:
5
+ *
6
+ * 1. the calling Effect fiber's current span (a Promise call made inside `Effect.promise` or
7
+ * `Effect.tryPromise` runs its first step while that fiber is current);
8
+ * 2. the client's `traceContext` provider;
9
+ * 3. the active OpenTelemetry context, read through `@opentelemetry/api`'s global registration,
10
+ * so the SDK imports and depends on no tracing package.
11
+ *
12
+ * Each contract call runs in a client span `sealant.sdk.<group>.<endpoint>` carrying only the IDs
13
+ * from its path. When the caller's Effect tracer exports spans, the SDK's spans are made on that
14
+ * tracer and the request carries the SDK's HTTP span. When nothing exports them, the request carries
15
+ * the parent's own `traceparent`, so the server's span hangs off a span that exists. With no parent
16
+ * and no exporting tracer the request carries no trace header at all.
17
+ */
18
+ import { Context, Effect, Fiber, Option, Tracer } from "effect";
19
+ import { HttpClient } from "effect/http";
20
+ /** The `tracestate` a call forwards; set from the captured caller trace. */
21
+ export const CallerTraceState = Context.Reference("@sealant/sdk/CallerTraceState", { defaultValue: () => undefined });
22
+ /** A `traceparent` the request carries as is, set when no exporting tracer makes the SDK's spans. */
23
+ export const DirectTraceparent = Context.Reference("@sealant/sdk/DirectTraceparent", { defaultValue: () => undefined });
24
+ const TRACEPARENT = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;
25
+ const ALL_ZERO = /^0+$/;
26
+ const TRACESTATE_MAX_LENGTH = 512;
27
+ const PRINTABLE_ASCII = /^[\x20-\x7e]*$/;
28
+ /** A parsed W3C `traceparent`, or `undefined` for a malformed or invalid one. */
29
+ export function parseTraceparent(value) {
30
+ const match = TRACEPARENT.exec(value.trim());
31
+ if (match === null)
32
+ return undefined;
33
+ const [, version, traceId, spanId, flags, rest] = match;
34
+ if (version === undefined || traceId === undefined || spanId === undefined)
35
+ return undefined;
36
+ if (flags === undefined || version === "ff")
37
+ return undefined;
38
+ // Version 00 has exactly four fields; a later version may append more.
39
+ if (version === "00" && rest !== undefined)
40
+ return undefined;
41
+ if (ALL_ZERO.test(traceId) || ALL_ZERO.test(spanId))
42
+ return undefined;
43
+ return { traceId, spanId, sampled: (Number.parseInt(flags, 16) & 1) === 1 };
44
+ }
45
+ /** The `traceparent` a span is continued by. */
46
+ export function formatTraceparent(span) {
47
+ return `00-${span.traceId.padStart(32, "0")}-${span.spanId}-${span.sampled ? "01" : "00"}`;
48
+ }
49
+ const safeTracestate = (value) => value !== undefined &&
50
+ value.length > 0 &&
51
+ value.length <= TRACESTATE_MAX_LENGTH &&
52
+ PRINTABLE_ASCII.test(value)
53
+ ? value
54
+ : undefined;
55
+ const isRecord = (value) => typeof value === "object" && value !== null;
56
+ /** Call `holder[name]()` when it is a method; anything else answers `undefined`. */
57
+ const callMethod = (holder, name, args = []) => {
58
+ if (!isRecord(holder))
59
+ return undefined;
60
+ const method = holder[name];
61
+ return typeof method === "function" ? Reflect.apply(method, holder, args) : undefined;
62
+ };
63
+ // `@opentelemetry/api` 1.x keeps its registered globals under this symbol, and keys the active span
64
+ // in a context with the second one. Reading them directly keeps the SDK free of the dependency.
65
+ const OPENTELEMETRY_API = Symbol.for("opentelemetry.js.api.1");
66
+ const OPENTELEMETRY_SPAN_KEY = Symbol.for("OpenTelemetry Context Key SPAN");
67
+ /** The active OpenTelemetry span's context, when `@opentelemetry/api` is registered and has one. */
68
+ export function activeOpenTelemetryContext() {
69
+ try {
70
+ const api = Reflect.get(globalThis, OPENTELEMETRY_API);
71
+ if (!isRecord(api))
72
+ return undefined;
73
+ const active = callMethod(api["context"], "active");
74
+ const span = callMethod(active, "getValue", [OPENTELEMETRY_SPAN_KEY]);
75
+ const spanContext = callMethod(span, "spanContext");
76
+ if (!isRecord(spanContext))
77
+ return undefined;
78
+ const { traceId, spanId, traceFlags, traceState } = spanContext;
79
+ if (typeof traceId !== "string" || typeof spanId !== "string")
80
+ return undefined;
81
+ const flags = typeof traceFlags === "number" && (traceFlags & 1) === 1 ? "01" : "00";
82
+ const traceparent = `00-${traceId}-${spanId}-${flags}`;
83
+ if (parseTraceparent(traceparent) === undefined)
84
+ return undefined;
85
+ const serialized = callMethod(traceState, "serialize");
86
+ const tracestate = safeTracestate(typeof serialized === "string" ? serialized : undefined);
87
+ return tracestate === undefined ? { traceparent } : { traceparent, tracestate };
88
+ }
89
+ catch {
90
+ return undefined;
91
+ }
92
+ }
93
+ /** The calling Effect fiber's span and exporting tracer, when a fiber is running this call. */
94
+ const fromCallingFiber = () => {
95
+ try {
96
+ const fiber = Fiber.getCurrent();
97
+ if (fiber === undefined)
98
+ return undefined;
99
+ const tracer = fiber.getRef(Tracer.Tracer);
100
+ return {
101
+ parent: Option.getOrUndefined(Context.getOption(fiber.context, Tracer.ParentSpan)),
102
+ tracer: tracer === Tracer.nativeTracer ? undefined : tracer,
103
+ };
104
+ }
105
+ catch {
106
+ return undefined;
107
+ }
108
+ };
109
+ const fromTraceContext = (context) => {
110
+ if (context === undefined || typeof context.traceparent !== "string")
111
+ return undefined;
112
+ const parsed = parseTraceparent(context.traceparent);
113
+ if (parsed === undefined)
114
+ return undefined;
115
+ return {
116
+ parent: Tracer.externalSpan(parsed),
117
+ tracestate: safeTracestate(context.tracestate),
118
+ };
119
+ };
120
+ const callProvider = (provider) => {
121
+ if (provider === undefined)
122
+ return undefined;
123
+ try {
124
+ return provider();
125
+ }
126
+ catch {
127
+ // A provider that throws must not fail the call it was asked about.
128
+ return undefined;
129
+ }
130
+ };
131
+ // Set only for the synchronous extent of `withCallerTrace`, so it never outlives the call that set it.
132
+ let handedTrace;
133
+ /**
134
+ * Call `f` so that every SDK call it starts synchronously captures `trace`: how a call that has
135
+ * already awaited hands its trace to another facade call (`create()` to `ready()`).
136
+ */
137
+ export function withCallerTrace(trace, f) {
138
+ const previous = handedTrace;
139
+ handedTrace = { trace };
140
+ try {
141
+ return f();
142
+ }
143
+ finally {
144
+ handedTrace = previous;
145
+ }
146
+ }
147
+ /**
148
+ * The caller's trace right now, or `undefined` when there is none. Synchronous: call it before the
149
+ * first `await` of a call, while a calling Effect fiber is still current.
150
+ */
151
+ export function captureCallerTrace(provider) {
152
+ if (handedTrace !== undefined)
153
+ return handedTrace.trace;
154
+ const fiber = fromCallingFiber();
155
+ if (fiber?.parent !== undefined) {
156
+ return { parent: fiber.parent, tracer: fiber.tracer, tracestate: undefined };
157
+ }
158
+ const explicit = fromTraceContext(callProvider(provider)) ?? fromTraceContext(activeOpenTelemetryContext());
159
+ if (explicit === undefined && fiber?.tracer === undefined)
160
+ return undefined;
161
+ return { parent: explicit?.parent, tracer: fiber?.tracer, tracestate: explicit?.tracestate };
162
+ }
163
+ /** Run an effect as part of a captured caller trace. */
164
+ export const continueCallerTrace = (trace) => (effect) => {
165
+ if (trace === undefined)
166
+ return effect;
167
+ const withState = trace.tracestate === undefined
168
+ ? effect
169
+ : Effect.provideService(effect, CallerTraceState, trace.tracestate);
170
+ const withTracer = trace.tracer === undefined
171
+ ? withState
172
+ : Effect.provideService(withState, Tracer.Tracer, trace.tracer);
173
+ return trace.parent === undefined
174
+ ? withTracer
175
+ : Effect.withParentSpan(withTracer, trace.parent, { captureStackTrace: false });
176
+ };
177
+ /** The trace headers a raw `fetch` made for a captured caller trace carries. */
178
+ export function traceHeaders(trace) {
179
+ if (trace?.parent === undefined)
180
+ return {};
181
+ const traceparent = formatTraceparent(trace.parent);
182
+ return trace.tracestate === undefined
183
+ ? { traceparent }
184
+ : { traceparent, tracestate: trace.tracestate };
185
+ }
186
+ /**
187
+ * Run one contract call in its client span, and choose what trace header its request carries (see
188
+ * the module comment).
189
+ */
190
+ export const traceCall = (name, attributes, effect) => Effect.gen(function* () {
191
+ const parent = yield* Effect.serviceOption(Tracer.ParentSpan);
192
+ const tracer = yield* Effect.tracer;
193
+ const spanned = Effect.withSpan(effect, name, {
194
+ kind: "client",
195
+ attributes,
196
+ captureStackTrace: false,
197
+ });
198
+ if (tracer !== Tracer.nativeTracer)
199
+ return yield* spanned;
200
+ const unpropagated = Effect.provideService(spanned, HttpClient.TracerPropagationEnabled, false);
201
+ if (Option.isNone(parent))
202
+ return yield* unpropagated;
203
+ return yield* Effect.provideService(unpropagated, DirectTraceparent, formatTraceparent(parent.value));
204
+ });
205
+ const snakeCase = (identifier) => identifier.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
206
+ /** The span attributes of a call: the IDs in its path (`workspaceId` -> `sealant.workspace_id`). */
207
+ const idAttributes = (request) => {
208
+ if (!isRecord(request) || !isRecord(request["params"]))
209
+ return {};
210
+ const attributes = {};
211
+ for (const [key, value] of Object.entries(request["params"])) {
212
+ if (key.length > 2 && key.endsWith("Id") && typeof value === "string") {
213
+ attributes[`sealant.${snakeCase(key)}`] = value;
214
+ }
215
+ }
216
+ return attributes;
217
+ };
218
+ /** An endpoint function wrapped in {@link traceCall}; any other value is kept as it is. */
219
+ const instrumentValue = (name, value, holder) => {
220
+ if (typeof value !== "function")
221
+ return value;
222
+ return (...args) => {
223
+ const result = Reflect.apply(value, holder, args);
224
+ return Effect.isEffect(result) ? traceCall(name, idAttributes(args[0]), result) : result;
225
+ };
226
+ };
227
+ const instrumentGroup = (prefix, group) => {
228
+ const instrumented = {};
229
+ for (const [key, value] of Object.entries(group)) {
230
+ instrumented[key] = instrumentValue(`${prefix}.${snakeCase(key)}`, value, group);
231
+ }
232
+ return instrumented;
233
+ };
234
+ /**
235
+ * The derived control-plane client with every endpoint run through {@link traceCall}, named
236
+ * `sealant.sdk.<group>.<endpoint>` from the contract's own identifiers.
237
+ */
238
+ export function instrumentClient(client) {
239
+ const instrumented = {};
240
+ for (const [key, value] of Object.entries(client)) {
241
+ const name = `sealant.sdk.${snakeCase(key)}`;
242
+ instrumented[key] =
243
+ typeof value !== "function" && isRecord(value)
244
+ ? instrumentGroup(name, value)
245
+ : instrumentValue(name, value, client);
246
+ }
247
+ // SAFETY: the copy has the client's keys, and each endpoint function is replaced by one taking the
248
+ // same arguments and returning the same effect type (`traceCall` preserves A, E and R). TypeScript
249
+ // cannot express that mapping over the derived client's type.
250
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the mapping above keeps the client's type; see SAFETY.
251
+ return instrumented;
252
+ }
@@ -1,9 +1,18 @@
1
- import type { SdkRuntime } from "../effect/runtime.js";
1
+ import type { Effect } from "effect";
2
+ import type { SdkRuntime, SdkServices } from "../effect/runtime.js";
3
+ import { type CallerTrace } from "../effect/trace.js";
2
4
  import type { SealantInternalConfig } from "../internal/config.js";
3
5
  /** What every facade object needs: the execution boundary and the resolved (host-local) config. */
4
6
  export interface SdkContext {
5
7
  readonly runtime: SdkRuntime;
6
8
  readonly config: SealantInternalConfig;
7
9
  }
10
+ /** The caller's trace right now (see `captureCallerTrace`); call it before a call's first `await`. */
11
+ export declare const captureTrace: (ctx: SdkContext) => CallerTrace | undefined;
12
+ /**
13
+ * A `run` bound to the caller's trace captured now, for a call that makes several requests across
14
+ * `await`s (a polling loop), so each continues the trace the call started in.
15
+ */
16
+ export declare const bindRun: (ctx: SdkContext) => (<A, E>(effect: Effect.Effect<A, E, SdkServices>) => Promise<A>);
8
17
  /** An AsyncIterable whose iteration rejects — for surface that is typed now but not yet implemented. */
9
18
  export declare const notImplementedAsyncIterable: <A>(operation: string, error: Error) => AsyncIterable<A>;
@@ -1,3 +1,14 @@
1
+ import { captureCallerTrace } from "../effect/trace.js";
2
+ /** The caller's trace right now (see `captureCallerTrace`); call it before a call's first `await`. */
3
+ export const captureTrace = (ctx) => captureCallerTrace(ctx.config.traceContext);
4
+ /**
5
+ * A `run` bound to the caller's trace captured now, for a call that makes several requests across
6
+ * `await`s (a polling loop), so each continues the trace the call started in.
7
+ */
8
+ export const bindRun = (ctx) => {
9
+ const trace = captureTrace(ctx);
10
+ return (effect) => ctx.runtime.run(effect, trace);
11
+ };
1
12
  /** An AsyncIterable whose iteration rejects — for surface that is typed now but not yet implemented. */
2
13
  export const notImplementedAsyncIterable = (operation, error) => ({
3
14
  [Symbol.asyncIterator]() {
@@ -7,7 +7,7 @@
7
7
  */
8
8
  import { type TimelineEntry as WireTimelineEntry } from "@sealant/api-contracts";
9
9
  import type { RunCommand, RunRecord, TimelineEntry } from "../types.js";
10
- import type { SdkContext } from "./context.js";
10
+ import { type SdkContext } from "./context.js";
11
11
  /**
12
12
  * Maps a wire entry to the public DISCRIMINATED entry: the contract's payload schemas fold
13
13
  * `(kind, ref)` into typed `data`, degrading to the `unknown` case (raw kind + payload preserved)
@@ -9,6 +9,7 @@ import { decodeRecordEventPayload, } from "@sealant/api-contracts";
9
9
  import { getRunLossOp, getRunOp, getRunScrollbackOp, getRunTimelineOp, } from "../effect/operations.js";
10
10
  import { SealantNotImplementedError } from "../errors.js";
11
11
  import { elapsed } from "../internal/clock.js";
12
+ import { bindRun } from "./context.js";
12
13
  // Live `stream()` is poll-backed for now: it tails the timeline endpoint until the run is terminal.
13
14
  // The transport swaps to SSE over Postgres LISTEN/NOTIFY in Stage 5 behind this same signature.
14
15
  const TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "cancelled"]);
@@ -184,12 +185,13 @@ export const makeRunRecord = (ctx, runId) => {
184
185
  commands: async () => reconstructCommands(await fetchTimeline()),
185
186
  transcript: async () => renderTranscript(reconstructCommands(await fetchTimeline())),
186
187
  stream: (options) => {
187
- const ctxRun = ctx.runtime;
188
+ // Captured when stream() is called: the generator's body first runs on the first next().
189
+ const traced = bindRun(ctx);
188
190
  async function* iterate() {
189
191
  let from = options?.from;
190
192
  const deadline = elapsed() + STREAM_TIMEOUT_MS;
191
193
  for (;;) {
192
- const wire = await ctxRun.run(getRunTimelineOp(runId, {
194
+ const wire = await traced(getRunTimelineOp(runId, {
193
195
  ownerUserId: ctx.config.hostLocal.ownerUserId,
194
196
  ...(from === undefined ? {} : { fromSequence: from.toString() }),
195
197
  }));
@@ -200,9 +202,9 @@ export const makeRunRecord = (ctx, runId) => {
200
202
  }
201
203
  // Stop once the run is terminal — with one final drain to catch entries written between the
202
204
  // last timeline fetch and the status check.
203
- const run = await ctxRun.run(getRunOp(runId, ctx.config.hostLocal.ownerUserId));
205
+ const run = await traced(getRunOp(runId, ctx.config.hostLocal.ownerUserId));
204
206
  if (TERMINAL_RUN_STATUSES.has(run.status)) {
205
- const tail = await ctxRun.run(getRunTimelineOp(runId, {
207
+ const tail = await traced(getRunTimelineOp(runId, {
206
208
  ownerUserId: ctx.config.hostLocal.ownerUserId,
207
209
  ...(from === undefined ? {} : { fromSequence: from.toString() }),
208
210
  }));
@@ -9,7 +9,7 @@
9
9
  */
10
10
  import type { Run as WireRun, RunChangesResponse } from "@sealant/api-contracts";
11
11
  import type { Run, RunFileChange } from "../types.js";
12
- import type { SdkContext } from "./context.js";
12
+ import { type SdkContext } from "./context.js";
13
13
  export interface RunChangesData {
14
14
  readonly files: readonly RunFileChange[];
15
15
  readonly diff: string;
@@ -1,6 +1,7 @@
1
1
  import { getRunChangesOp, getRunOp } from "../effect/operations.js";
2
2
  import { SealantError, SealantNotImplementedError } from "../errors.js";
3
3
  import { elapsed } from "../internal/clock.js";
4
+ import { bindRun } from "./context.js";
4
5
  import { makeRunRecord } from "./record.js";
5
6
  /** Maps the wire changes shape to the facade data (shared with the run-harness execution path). */
6
7
  export const toRunChangesData = (wire) => ({
@@ -46,6 +47,8 @@ export const makeRun = (ctx, init) => {
46
47
  artifacts: emptyArtifacts,
47
48
  record: makeRunRecord(ctx, runId),
48
49
  wait: async () => {
50
+ // Each poll continues the trace wait() was called in.
51
+ const run = bindRun(ctx);
49
52
  let current = init.wire;
50
53
  const deadline = elapsed() + WAIT_TIMEOUT_MS;
51
54
  while (!TERMINAL_STATUSES.has(current.status)) {
@@ -55,12 +58,12 @@ export const makeRun = (ctx, init) => {
55
58
  });
56
59
  }
57
60
  await delay(WAIT_POLL_INTERVAL_MS);
58
- current = await ctx.runtime.run(getRunOp(runId, ctx.config.hostLocal.ownerUserId));
61
+ current = await run(getRunOp(runId, ctx.config.hostLocal.ownerUserId));
59
62
  }
60
63
  // Settle the changes: a handle from `harness.start()` or `runs.get()` has none captured yet,
61
64
  // so read the server-side capture now that the run is terminal.
62
65
  const settledChanges = changesData ??
63
- toRunChangesData(await ctx.runtime.run(getRunChangesOp(runId, ctx.config.hostLocal.ownerUserId)));
66
+ toRunChangesData(await run(getRunChangesOp(runId, ctx.config.hostLocal.ownerUserId)));
64
67
  return makeRun(ctx, { wire: current, changes: settledChanges });
65
68
  },
66
69
  };
@@ -10,5 +10,5 @@
10
10
  */
11
11
  import type { SessionWire } from "@sealant/api-contracts";
12
12
  import type { InteractiveSession } from "../types.js";
13
- import type { SdkContext } from "./context.js";
13
+ import { type SdkContext } from "./context.js";
14
14
  export declare const makeInteractiveSession: (ctx: SdkContext, wire: SessionWire) => InteractiveSession;
@@ -1,8 +1,10 @@
1
1
  import { Predicate } from "effect";
2
2
  import { closeSessionOp, getSessionOp, getSessionOutputOp, resizeSessionOp, sendSessionInputOp, signalSessionOp, } from "../effect/operations.js";
3
+ import { traceHeaders } from "../effect/trace.js";
3
4
  import { SealantBudgetExceededError } from "../errors.js";
4
5
  import { resolveRequestPriority } from "../internal/config.js";
5
6
  import { toSealantError } from "../internal/map-error.js";
7
+ import { captureTrace } from "./context.js";
6
8
  /**
7
9
  * Open the held-WebSocket terminal attachment (the data plane). One socket:
8
10
  * binary frames are PTY bytes in both directions, text frames are control
@@ -128,7 +130,7 @@ const parseSseFrame = (block) => {
128
130
  return { event, id, data: dataLines.join("\n") };
129
131
  };
130
132
  /** Stream the session's output over SSE. Throws on transport failure (caller falls back). */
131
- async function* streamOverSse(ctx, sessionId, from, signal, priority) {
133
+ async function* streamOverSse(ctx, sessionId, from, signal, priority, trace) {
132
134
  const config = ctx.config;
133
135
  const fetchImpl = config.fetch ?? fetch;
134
136
  const url = new URL(`/v1/sessions/${sessionId}/output/stream`, config.baseUrl);
@@ -138,6 +140,7 @@ async function* streamOverSse(ctx, sessionId, from, signal, priority) {
138
140
  headers: {
139
141
  accept: "text/event-stream",
140
142
  "x-sealant-request-priority": priority,
143
+ ...traceHeaders(trace),
141
144
  ...(config.apiKey === undefined ? {} : { authorization: `Bearer ${config.apiKey}` }),
142
145
  },
143
146
  ...(signal === undefined ? {} : { signal }),
@@ -186,7 +189,7 @@ async function* streamOverSse(ctx, sessionId, from, signal, priority) {
186
189
  }
187
190
  }
188
191
  /** Poll-backed fallback: page the range endpoint until the session settles. */
189
- async function* streamByPolling(ctx, sessionId, from, signal) {
192
+ async function* streamByPolling(ctx, sessionId, from, signal, trace) {
190
193
  let cursor = from;
191
194
  for (;;) {
192
195
  if (signal?.aborted === true) {
@@ -195,7 +198,7 @@ async function* streamByPolling(ctx, sessionId, from, signal) {
195
198
  const page = await ctx.runtime.run(getSessionOutputOp(sessionId, {
196
199
  ownerUserId: ctx.config.hostLocal.ownerUserId,
197
200
  from: cursor.toString(),
198
- }));
201
+ }), trace);
199
202
  for (const chunk of page.chunks) {
200
203
  yield { sequence: BigInt(chunk.sequence), data: decodeBase64(chunk.dataBase64) };
201
204
  }
@@ -225,11 +228,13 @@ export const makeInteractiveSession = (ctx, wire) => {
225
228
  output: (options) => {
226
229
  const from = options?.from ?? 0n;
227
230
  const signal = options?.signal;
231
+ // Captured when output() is called: the generator's body first runs on the first next().
232
+ const trace = captureTrace(ctx);
228
233
  async function* iterate() {
229
234
  let cursor = from;
230
235
  const priority = resolveRequestPriority(ctx.config.requestPriority);
231
236
  try {
232
- for await (const chunk of streamOverSse(ctx, sessionId, cursor, signal, priority)) {
237
+ for await (const chunk of streamOverSse(ctx, sessionId, cursor, signal, priority, trace)) {
233
238
  yield chunk;
234
239
  cursor = chunk.sequence + 1n;
235
240
  }
@@ -245,7 +250,7 @@ export const makeInteractiveSession = (ctx, wire) => {
245
250
  // from the cursor; the sequence keying makes the switch seamless.
246
251
  void error;
247
252
  }
248
- yield* streamByPolling(ctx, sessionId, cursor, signal);
253
+ yield* streamByPolling(ctx, sessionId, cursor, signal, trace);
249
254
  }
250
255
  return iterate();
251
256
  },
@@ -6,7 +6,7 @@
6
6
  */
7
7
  import type { WorkspaceRuntime as WireWorkspaceRuntime, WorkspaceDetails as WireWorkspaceDetails } from "@sealant/api-contracts";
8
8
  import type { Harness, Workspace, WorkspaceLaunch, WorkspaceRuntimeInfo, WorkspaceImage, WorkspacePhase, WorkspaceStatus } from "../types.js";
9
- import type { SdkContext } from "./context.js";
9
+ import { type SdkContext } from "./context.js";
10
10
  export interface WorkspaceInit {
11
11
  readonly id: string;
12
12
  readonly name: string;
@@ -2,6 +2,7 @@ import { sessionArgvIssue, WORKSPACE_GATEWAY_UNAVAILABLE_CODE } from "@sealant/a
2
2
  import { applyDotfiles } from "../effect/apply-dotfiles.js";
3
3
  import { execWorkspace } from "../effect/exec-workspace.js";
4
4
  import { applyWorkspaceNetworkPolicyOp, bindWorkspaceOp, getWorkspaceNetworkPolicyOp, revokeWorkspaceAccessOp, flushWorkspaceCaptureOp, getWorkspaceCaptureStatusOp, createSessionAsUserOp, createSessionOp, expireWorkspaceOp, clearWorkspaceSshUserOp, getSessionOp, getWorkspaceOp, listSessionsOp, replanWorkspaceCaptureOp, recoverWorkspaceOp, restartWorkspaceOp, listWorkspaceCredentialsOp, putWorkspaceCredentialsOp, pruneWorkspaceCredentialsOp, releaseWorkspaceCredentialsOp, stopWorkspaceOp, } from "../effect/operations.js";
5
+ import { withCallerTrace } from "../effect/trace.js";
5
6
  import { SealantApiError, SealantBoatError, SealantBudgetExceededError, SealantError, SealantNotImplementedError, } from "../errors.js";
6
7
  import { specHarnessId } from "../internal/blueprint.js";
7
8
  import { elapsed } from "../internal/clock.js";
@@ -10,6 +11,7 @@ import { parseTtlSeconds } from "../internal/duration.js";
10
11
  import { requireCredentialPlacements } from "../internal/features.js";
11
12
  import { requireValidNetworkPolicy } from "../internal/network-policy.js";
12
13
  import { requireProcessUser } from "../internal/process-user.js";
14
+ import { bindRun, captureTrace } from "./context.js";
13
15
  import { openForward, openForwardV2 } from "./forward.js";
14
16
  import { makeInteractiveSession } from "./session.js";
15
17
  /** The wire runtime as the SDK reports it. */
@@ -475,6 +477,8 @@ export const makeWorkspace = (ctx, init) => {
475
477
  return details.phase === undefined ? null : toWorkspacePhase(details.phase);
476
478
  },
477
479
  ready: async (options) => {
480
+ // Every poll, and a give-up stop, continues the trace ready() was called in.
481
+ const trace = captureTrace(ctx);
478
482
  // Bounded by phase: the readiness bound is spent only outside an image build (queued,
479
483
  // booting), so a first launch on a new image is not failed by a slow package mirror. The
480
484
  // build has its own bound (none by default) and fails when it stops making progress. A
@@ -506,7 +510,7 @@ export const makeWorkspace = (ctx, init) => {
506
510
  // runtime does not keep running (and billing) to the platform's lifetime cap.
507
511
  // Best-effort: the bound is what the caller must see, whatever the request answers.
508
512
  // The request being accepted is all that is known — not that anything has stopped.
509
- const accepted = init.created === true ? await requestStop() : undefined;
513
+ const accepted = init.created === true ? await withCallerTrace(trace, requestStop) : undefined;
510
514
  throw new SealantError(`${message}${accepted === undefined
511
515
  ? ""
512
516
  : accepted
@@ -514,7 +518,7 @@ export const makeWorkspace = (ctx, init) => {
514
518
  : " Requesting a stop failed; stop it yourself."}`, { code });
515
519
  };
516
520
  for (;;) {
517
- const details = await ctx.runtime.run(getWorkspaceOp(init.id, ctx.config.hostLocal.ownerUserId));
521
+ const details = await ctx.runtime.run(getWorkspaceOp(init.id, ctx.config.hostLocal.ownerUserId), trace);
518
522
  const now = elapsed();
519
523
  // The time since the last look was spent building when the last look saw a build.
520
524
  if (building)
@@ -648,7 +652,8 @@ export const makeWorkspace = (ctx, init) => {
648
652
  // Poll-backed lifecycle stream: emit a coarse event on each status transition until the workspace
649
653
  // reaches a terminal/ready state. Swaps to SSE over Postgres LISTEN/NOTIFY in Stage 5 (same shape).
650
654
  events: () => {
651
- const ctxRun = ctx.runtime;
655
+ // Captured when events() is called: the generator's body first runs on the first next().
656
+ const run = bindRun(ctx);
652
657
  async function* iterate() {
653
658
  let lastStatus;
654
659
  let lastPhase;
@@ -656,7 +661,7 @@ export const makeWorkspace = (ctx, init) => {
656
661
  // follows a build as long as the build is moving, like ready().
657
662
  let deadline = elapsed() + READY_TIMEOUT_MS;
658
663
  for (;;) {
659
- const details = await ctxRun.run(getWorkspaceOp(init.id, ctx.config.hostLocal.ownerUserId));
664
+ const details = await run(getWorkspaceOp(init.id, ctx.config.hostLocal.ownerUserId));
660
665
  if (details.status !== lastStatus) {
661
666
  lastStatus = details.status;
662
667
  yield {
@@ -698,6 +703,7 @@ export const makeWorkspace = (ctx, init) => {
698
703
  // a drain (a refused or abandoned drain answers too), so it never decides the state.
699
704
  stop: async (options) => {
700
705
  const ownerUserId = ctx.config.hostLocal.ownerUserId;
706
+ const trace = captureTrace(ctx);
701
707
  const accepted = await ctx.runtime.run(stopWorkspaceOp(init.id, {
702
708
  ownerUserId,
703
709
  ...(options?.discardUnsaved === true ? { discardUnsaved: true } : {}),
@@ -733,7 +739,7 @@ export const makeWorkspace = (ctx, init) => {
733
739
  const deadline = elapsed() + STOP_TIMEOUT_MS;
734
740
  for (;;) {
735
741
  const details = await ctx.runtime
736
- .run(getWorkspaceOp(init.id, ctx.config.hostLocal.ownerUserId))
742
+ .run(getWorkspaceOp(init.id, ctx.config.hostLocal.ownerUserId), trace)
737
743
  .catch((error) => {
738
744
  if (error instanceof SealantBudgetExceededError) {
739
745
  throw new SealantError(`A stop for workspace ${init.id} was accepted, but a follow-up request reached its budget. Read the workspace again to observe its status.`, { code: "workspace_stop_observation_refused", cause: error });
@@ -753,7 +759,7 @@ export const makeWorkspace = (ctx, init) => {
753
759
  details.captureDrain !== undefined) {
754
760
  // Observed: the executor ended and is kept for recovery; this stop does not remove it
755
761
  // (only a discard or an accepted completion would), so there is nothing to wait for.
756
- const capture = await readCaptureStatus().catch(() => undefined);
762
+ const capture = await withCallerTrace(trace, readCaptureStatus).catch(() => undefined);
757
763
  return {
758
764
  state: "kept",
759
765
  drain: toCaptureDrain(details.captureDrain),
@@ -763,7 +769,7 @@ export const makeWorkspace = (ctx, init) => {
763
769
  }
764
770
  if (elapsed() > deadline) {
765
771
  const drain = details.captureDrain === undefined ? undefined : toCaptureDrain(details.captureDrain);
766
- const capture = await readCaptureStatus().catch(() => undefined);
772
+ const capture = await withCallerTrace(trace, readCaptureStatus).catch(() => undefined);
767
773
  const extras = { ...(capture === undefined ? {} : { capture }), ...completion };
768
774
  if (drain !== undefined && (drain.state === "draining" || drain.state === "kept")) {
769
775
  return { state: drain.state, drain, ...extras };
@@ -19,6 +19,7 @@ export interface SealantInternalConfig {
19
19
  readonly baseUrl: string;
20
20
  readonly apiKey: string | undefined;
21
21
  readonly fetch: typeof fetch | undefined;
22
+ readonly traceContext?: SealantConfig["traceContext"];
22
23
  readonly hostLocal: SealantHostLocalConfig;
23
24
  }
24
25
  /** Resolve the caller's priority at dispatch, before falling back to the operation default. */
@@ -13,6 +13,7 @@ export const resolveInternalConfig = (config) => ({
13
13
  ...(config.requestPriority === undefined ? {} : { requestPriority: config.requestPriority }),
14
14
  apiKey: config.apiKey,
15
15
  fetch: config.fetch,
16
+ ...(config.traceContext === undefined ? {} : { traceContext: config.traceContext }),
16
17
  hostLocal: {
17
18
  ownerUserId: config.ownerUserId ?? env("SEALANT_OWNER_USER_ID") ?? DEFAULT_OWNER_USER_ID,
18
19
  registryId: env("SEALANT_REGISTRY_ID") ?? DEFAULT_REGISTRY_ID,
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { RESOURCE_INSTANCE_EXEC, RESOURCE_INSTANCE_BACKUP, } from "@sealant/api-contracts";
7
7
  import { archiveResourceDomainOp, archiveResourceInstanceOp, purgeResourceInstanceOp, getResourceInstanceOp, linkResourceWorkspaceOp, listResourceInstancesOp, stopResourceInstanceOp, upResourceInstanceOp, } from "./effect/operations.js";
8
+ import { captureCallerTrace, traceHeaders } from "./effect/trace.js";
8
9
  import { SealantApiError, SealantBudgetExceededError, SealantError } from "./errors.js";
9
10
  import { resolveRequestPriority } from "./internal/config.js";
10
11
  import { toSealantError } from "./internal/map-error.js";
@@ -109,6 +110,7 @@ const exec = async (config, scopeId, key, options) => {
109
110
  headers: {
110
111
  "content-type": "application/octet-stream",
111
112
  "x-sealant-request-priority": resolveRequestPriority(config.requestPriority),
113
+ ...traceHeaders(captureCallerTrace(config.traceContext)),
112
114
  ...(config.apiKey === undefined ? {} : { authorization: `Bearer ${config.apiKey}` }),
113
115
  },
114
116
  body: execBody(frame, options.stdin),
@@ -152,6 +154,7 @@ export const makeScopeInstances = (runtime, config, scopeId) => ({
152
154
  const response = await (config.fetch ?? fetch)(new URL(path, config.baseUrl), {
153
155
  headers: {
154
156
  "x-sealant-request-priority": resolveRequestPriority(config.requestPriority),
157
+ ...traceHeaders(captureCallerTrace(config.traceContext)),
155
158
  ...(config.apiKey === undefined ? {} : { authorization: `Bearer ${config.apiKey}` }),
156
159
  },
157
160
  });
package/dist/types.d.ts CHANGED
@@ -45,8 +45,26 @@ export interface SealantConfig {
45
45
  * then `usr_local`.
46
46
  */
47
47
  readonly ownerUserId?: string;
48
- /** Override the `fetch` implementation (tests, custom agents, proxies). */
48
+ /**
49
+ * Override the `fetch` implementation (tests, custom agents, proxies). Every request the client
50
+ * makes goes through it: contract calls, session output streams and resource calls.
51
+ */
49
52
  readonly fetch?: typeof fetch;
53
+ /**
54
+ * The trace a call continues, read when each call starts. A call made inside an Effect span
55
+ * continues that span without this; otherwise the SDK calls this and, when it answers nothing,
56
+ * uses the active OpenTelemetry context if `@opentelemetry/api` is registered. With no parent
57
+ * from any of them, requests carry no trace header. Read per call, so one client can serve
58
+ * concurrent requests that belong to different traces.
59
+ */
60
+ readonly traceContext?: () => SealantTraceContext | undefined;
61
+ }
62
+ /** A W3C trace context the SDK's requests continue. */
63
+ export interface SealantTraceContext {
64
+ /** A W3C `traceparent` header value, such as `00-<32 hex trace id>-<16 hex span id>-01`. */
65
+ readonly traceparent: string;
66
+ /** The W3C `tracestate` header value that travels with it, when there is one. */
67
+ readonly tracestate?: string;
50
68
  }
51
69
  /** The harnesses with first-class integrations baked into the platform today. */
52
70
  export type HarnessId = "opencode" | "codex" | "claude-code" | "pi" | "antigravity";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sealant/sdk-next",
3
- "version": "0.40.0-next.941",
3
+ "version": "0.40.0-next.944",
4
4
  "description": "The fluent public SDK for Sealant — create a workspace, run a harness, replay the record.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -26,12 +26,12 @@
26
26
  "node": ">=20"
27
27
  },
28
28
  "dependencies": {
29
- "@sealant/api-contracts": "npm:@sealant/api-contracts-next@0.40.0-next.941"
29
+ "@sealant/api-contracts": "npm:@sealant/api-contracts-next@0.40.0-next.944"
30
30
  },
31
31
  "peerDependencies": {
32
32
  "effect": "^4.0.5"
33
33
  },
34
- "gitHead": "51ae61e6a1ed462b9c3e703726d9983675001ead",
34
+ "gitHead": "ea37a52a8fd95d205e408143f9a59f42e9afa707",
35
35
  "publishConfig": {
36
36
  "access": "public"
37
37
  }