{"version":3,"file":"sdk-BHJkQs10.mjs","names":[],"sources":["../src/core/tracing/port.ts","../src/core/tracing/sdk.ts"],"sourcesContent":["/**\n * The tracing port: what a run's trace is told, in the tracing SDK's\n * vocabulary. It knows no payload: whoever reads the payload (a kind, in a\n * route's `describe`) describes the run as a `RunSpec`, and the core runs it,\n * hands its traced step and its narrative to the route's middleware and its\n * handler, and ends it with the answer. The SDK\n * adapter is one tracer; `noopTracing`, what tracing is when off, another.\n *\n * Tracing never fails a run: nothing a span is told throws, and `end` never\n * rejects.\n */\n\nimport type { Failure } from \"../errors\";\nimport { silentNarrative, type Narrative } from \"./narrative\";\nimport type { Plan } from \"./plan\";\nimport type { Step } from \"./step\";\n\n/** What a run is on the trace. */\nexport interface RunSpec {\n  /** Who reports the run: the package's slug. */\n  producer: string;\n  /** The entity the run is scoped to; the tracing API refuses a run without one, so such a run is not traced. */\n  nrn?: string;\n  /** The run's id in its trace. */\n  runId: string;\n  /** The trace the run belongs to; the run starts one of its own when absent. */\n  traceId?: string;\n  /** The run this one is a stage of, in the same trace. */\n  parentRunId?: string;\n  /** The run's name on screen. */\n  title: string;\n  /** What the run does: its narrative until the handler says more. */\n  description?: string;\n  /** The steps the run is expected to run; `context.trace.step` names them by key. */\n  plan?: Plan;\n  /** The job every run like this one is an instance of: it carries the plan. */\n  job?: { namespace: string; name: string; version: string };\n  /** The run's labels; one whose value is undefined is left out. */\n  labels: Record<string, string | undefined>;\n  /** Who asked for the run. */\n  actor?: { kind: \"user\" | \"service\"; id: string };\n  /** What the run consumed, by name. */\n  input?: Record<string, unknown>;\n}\n\n/** What a route says of the run that answers a payload: the run, and what the run traces of a successful answer's data (a copy, its secrets redacted, say). */\nexport interface RunDescription {\n  run: RunSpec;\n  result(data: unknown): unknown;\n}\n\n/** How a run ended: what it answered, or how it failed. */\nexport type SpanOutcome = { status: \"success\"; result?: unknown } | { status: \"failed\"; failure: Failure };\n\n/** A run on the trace, from its start to its end. */\nexport interface Span {\n  /** `step`, each of its calls a step of the run, its work handed the step's narrative. */\n  traced(step: Step): Step;\n  /** The run's own narrative: what `context.trace` tells. */\n  narrative: Narrative;\n  /** Ends the run with its outcome, once the trace has been told. */\n  end(outcome: SpanOutcome): Promise<void>;\n}\n\nexport interface Tracer {\n  /** Starts the run `spec` describes. */\n  run(spec: RunSpec): Span;\n}\n\n/** A run that records nothing: its steps as they are, its narrative silent; what a run that is not traced is. */\nexport const untracedSpan: Span = {\n  traced: (step) => step,\n  narrative: silentNarrative,\n  end: async () => {},\n};\n\n/** Tracing that records nothing: what tracing is when off, and what a local run passes. */\nexport const noopTracing: Tracer = {\n  run: () => untracedSpan,\n};\n","/**\n * The tracing port over the tracing SDK (`@nullplatform/tracing`), in the\n * SDK's own vocabulary (its guide's first rule: never rename or invent its\n * concepts): a run is the SDK's run, scoped to the run's NRN; a run with a plan\n * and a job is an `instance_of` that job, declared once per job and tenant,\n * which carries the plan; each `context.trace.step` is a step of the run, keyed by its\n * name; a narrative is the node's `explain`, `external_links` and `output`. It\n * reads no payload: what a run is, the kind's middleware says in its `RunSpec`.\n *\n * Optional: off without the run's platform API key (a blank one is none),\n * whatever its tracing URL says, and off with a blank tracing URL.\n * Tracing never fails a run: what the SDK throws is ignored, and an event it\n * drops, or a parent edge the API refuses, is a warning on the log it is given.\n * Nor does it hold an answer, or the worker, for long. The end of a run's\n * tracing waits END_BUDGET_MS at most, then stops waiting and aborts the\n * run's parent edge; what the run's client is still sending goes on, for the\n * runs beside it share that client. The settings' tracer owns the producer\n * clients it builds, and the transport that built it stops it once it is done\n * with it (`TracerOptions.done`: exec once it has answered, serve once it has\n * ended): a backoff they are sleeping ends, what they are still sending is\n * aborted, and all of it is dropped; they send nothing more, so nothing of\n * tracing holds the worker's exit. A tracer or a client given as the port is\n * the caller's, never stopped.\n */\n\nimport * as sdk from \"@nullplatform/tracing\";\nimport { bearerFetch, credentialsOf, TIMEOUT_MS } from \"../api/auth\";\nimport { send } from \"../api/transport\";\nimport { failureOf, messageOf, type Failure } from \"../errors\";\nimport { stderrLogger, written, type Logger } from \"../logger\";\nimport { isJsonObject } from \"../payload\";\nimport { describeSetting, settingsOf, type Settings } from \"../settings\";\nimport { textOf, withoutTrailingSlashes } from \"../text\";\nimport { within } from \"../within\";\nimport type { Explanation, ExternalLink, Narrative } from \"./narrative\";\nimport type { Plan } from \"./plan\";\nimport { noopTracing, type RunSpec, type Span, type SpanOutcome, type Tracer } from \"./port\";\nimport { callOf, type Step, type StepOptions, type StepWork } from \"./step\";\n\n// The SDK as this module tells it: structural, so a test hands in a fake. Each\n// member is a function-typed property, never a method, so TypeScript checks\n// what it takes as strictly as a function's parameters (a method's it would\n// check both ways): the SDK's own Tracer is a TracingClientLike as it is, and\n// `sdkClient`, which hands one as the other, fails to typecheck the day the SDK\n// takes less than this module hands it.\n\n/** What a run and a step are both told: their narrative, and how they ended. */\nexport interface NodeHandleLike {\n  /** `tracing.explain`: the words the console leads with; `title` is the node's name. */\n  explain: (body: Explanation & { title: string }) => unknown;\n  /** `tracing.external_links`: the node's whole list, each call replacing the last. */\n  externalLinks: (links: ExternalLink[]) => unknown;\n  /** Inline `tracing.output`: what the node produced. */\n  output: (name: string, value: unknown) => unknown;\n  /** `tracing.error`: how the node failed, its code and whether it may be retried, over what `fail` derives. */\n  error: (body: Failure) => unknown;\n  complete: () => unknown;\n  fail: (thrown: unknown) => unknown;\n}\n\n/** A job's handle: the definition every run like one is an instance of, carrying its plan. */\nexport interface JobHandleLike {\n  plan: (body: Plan) => JobHandleLike;\n  toRef: () => sdk.JobRef;\n}\n\n/** A run's handle. */\nexport interface RunHandleLike extends NodeHandleLike {\n  labels: (values: Record<string, string | undefined>) => unknown;\n  /** `tracing.actor`: who asked for the run. */\n  actor: (body: { kind: \"user\" | \"service\"; id: string }) => unknown;\n  /** Inline `tracing.input`: what the run consumed. */\n  input: (name: string, value: unknown) => unknown;\n  /** `tracing.plan` on the run itself, the SDK's run-level plan: a run with a plan and no job. */\n  plan: (body: Plan) => unknown;\n  /** The `instance_of` edge to the run's job. */\n  instanceOf: (job: JobHandleLike) => unknown;\n  step: (spec: { key: string }) => NodeHandleLike;\n}\n\n/** A run's identity, as the SDK's run spec takes it: identity only, everything else told to its handle. */\nexport interface RunIdentity {\n  trace_id: string;\n  run_id: string;\n  nrn: string;\n}\n\n/** A job's identity in a tenant: the job the kind names, at its run's NRN. */\nexport type JobIdentity = NonNullable<RunSpec[\"job\"]> & { nrn: string };\n\n/** A producer client: the SDK's own Tracer as it is, or a fake of it. */\nexport interface TracingClientLike {\n  run: (spec: RunIdentity) => RunHandleLike;\n  /** A job definition, lazy: emitted once, the first time a run is an instance of it. */\n  job: (spec: JobIdentity) => JobHandleLike;\n  flush: () => Promise<unknown>;\n  /** Told each event the client drops: one the API refused, or its queue had no room for. */\n  on: (event: \"drop\", listener: (envelope: { type?: string } | undefined, reason: unknown) => void) => unknown;\n}\n\n/** What the tracing port takes: a Tracer (`noopTracing`, a test's), or the SDK's own Tracer as it is. */\nexport type TracingPort = Tracer | TracingClientLike;\n\n/** How long the end of a run's tracing (its flush and its parent edge) may hold the answer: past it, the end stops waiting, with a warning, and aborts the run's parent edge; what its client is still sending goes on until the transport that built the tracer stops it. */\nexport const END_BUDGET_MS = 5_000;\n\n/** How many jobs a producer client remembers it declared, by identity and tenant: one used less recently is forgotten past them, and declared again when a run is an instance of it. */\nexport const JOBS_REMEMBERED = 1_000;\n\n/** What a producer client is built with, in the SDK's own words. */\nexport interface ClientOptions {\n  /** Where it sends its events: the tracing URL. */\n  baseURL: string;\n  /** Where it exchanges `apiKey` for its token: the platform API the run is traced for, never the SDK's default. */\n  authBaseURL: string;\n  apiKey: string;\n  producer: string;\n  /** What it sends every request through: the global fetch, stopped once the transport that built the tracer is done with it (`stoppableFetch`). */\n  fetchImpl: typeof fetch;\n  /** What stops its retries: aborted once the transport that built the tracer is done with it, a backoff it is sleeping then ends and nothing it fails to send is tried again. */\n  signal: AbortSignal;\n}\n\n/** How a producer client is built: `sdkClient` unless a test gives another. */\nexport type ClientFactory = (options: ClientOptions) => TracingClientLike;\n\n/** What the tracing adapter reads of a run's settings: its platform API key and URL, and its tracing URL. */\nexport type TracingSettings = Pick<Settings, \"apiUrl\" | \"apiKey\" | \"tracingUrl\">;\n\n/** What `tracerOf` tells, reaches outside the process through, and reaches with. */\nexport interface TracerOptions {\n  /** Where dropped events and refused edges are explained, as warnings; stderr unless given. */\n  log?: Logger;\n  /** What posts a parent edge and exchanges the key for its token; the global fetch unless given. */\n  fetch?: typeof fetch;\n  /** How the producer client is built when no port is given; `sdkClient` unless given. */\n  client?: ClientFactory;\n  /** What it reads of the run's settings: the platform API key and URL, and the tracing URL; their defaults (`settingsOf()`) unless given. */\n  settings?: TracingSettings;\n  /** Aborted once the transport that built the tracer is done with it: the settings' tracer then stops every producer client it built, a backoff each is sleeping ended and what each is still sending aborted, all of it dropped, and it sends nothing more. A port given is the caller's, never stopped. Never unless given. */\n  done?: AbortSignal;\n}\n\n/** What a tracer explains on, posts through, and reaches with; what stops a run's parent edge (`signal`, its run's); and, on the settings' tracer, what stops all it sends (`done`). */\ninterface TracerPorts {\n  log: Logger;\n  fetch?: typeof fetch;\n  settings: TracingSettings;\n  signal?: AbortSignal;\n  done?: AbortSignal;\n}\n\n/**\n * The tracer a port names: a Tracer as it is; a producer client wrapped,\n * which `done` never stops; none, the settings': off (`noopTracing`) without\n * the platform API key or with an empty tracing URL, else one producer client\n * per producer at the tracing URL, built by `client` and owned by the tracer,\n * all stopped once `done` aborts.\n */\nexport function tracerOf(port: TracingPort | undefined, options: TracerOptions = {}): Tracer {\n  const ports: TracerPorts = { log: options.log ?? stderrLogger, fetch: options.fetch, settings: options.settings ?? settingsOf() };\n  if (port === undefined) {\n    return settingsTracer(options.client ?? sdkClient, { ...ports, done: options.done });\n  }\n  return isClient(port) ? clientTracer(port, ports) : port;\n}\n\n/**\n * The tracing SDK's own Tracer, built handling no signal: a worker's signals\n * are its entry point's, and each run is flushed when it ends.\n */\nexport const sdkClient: ClientFactory = (options) => new sdk.Tracer({ ...options, shutdownHooks: false });\n\n/**\n * The trace a carrier continues (the tracing SDK's `np-trace` value,\n * `<version>|<trace_id>|<run_id>`), as the SDK reads it: a carrier naming no\n * run anchors on its trace; a version the SDK does not know, or no trace, is\n * none.\n */\nexport function parseCarrier(text: string): { traceId: string; parentRunId?: string } | undefined {\n  const upstream = sdk.extractTraceContext({ [sdk.TRACE_CARRIER_KEY]: text });\n  return upstream === null ? undefined : { traceId: upstream.trace_id, parentRunId: upstream.run_id };\n}\n\n/** Whether `port` is a producer client rather than a Tracer: a client flushes what it buffers, a Tracer has nothing to flush. */\nfunction isClient(port: TracingPort): port is TracingClientLike {\n  return typeof (port as Partial<TracingClientLike>).flush === \"function\";\n}\n\n// ─── The settings' producer clients ───\n\n/**\n * The settings' tracer: off without the platform API key or with a blank\n * tracing URL, each read as text; else each run through its producer's\n * client, which the tracer builds once and owns, all stopped by `ports.done`:\n * their retries by the SDK's own signal, what they send by one fetch\n * (`stoppableFetch`).\n */\nfunction settingsTracer(build: ClientFactory, ports: TracerPorts): Tracer {\n  const { apiKey, apiUrl } = credentialsOf(ports.settings);\n  const baseURL = tracingUrlOf(ports.settings);\n  if (apiKey === \"\" || baseURL === \"\") {\n    return noopTracing;\n  }\n  const authBaseURL = withoutTrailingSlashes(apiUrl);\n  const clients = new Map<string, TracingClientLike | undefined>();\n  const signal = ports.done ?? new AbortController().signal;\n  const fetchImpl = stoppableFetch(signal);\n  return {\n    run(spec) {\n      const client = producerClient(build, { baseURL, authBaseURL, apiKey, producer: spec.producer, fetchImpl, signal }, clients, ports.log);\n      return client === undefined ? noopTracing.run(spec) : clientTracer(client, ports).run(spec);\n    },\n  };\n}\n\n/** The client `build` makes with `options`; none, with a warning on `log`, when it cannot be built. */\nfunction builtClient(build: ClientFactory, options: ClientOptions, log: Logger): TracingClientLike | undefined {\n  try {\n    return build(options);\n  } catch (error) {\n    log.warn(`tracing: the tracing client for ${options.producer} could not be built: ${messageOf(error)}`);\n    return undefined;\n  }\n}\n\n/**\n * The client of `options`' producer among a tracer's `clients`, built by\n * `build` once, whether it could be or not: a client exchanges a token of its\n * own and keeps a queue, so a tracer builds one per producer; one that could\n * not be built is none, its warning told once.\n */\nfunction producerClient(build: ClientFactory, options: ClientOptions, clients: Map<string, TracingClientLike | undefined>, log: Logger): TracingClientLike | undefined {\n  if (!clients.has(options.producer)) {\n    clients.set(options.producer, builtClient(build, options, log));\n  }\n  return clients.get(options.producer);\n}\n\n/** Why what a stopped tracer's clients were still sending is dropped. */\nconst TRACER_STOPPED = \"its tracer was stopped\";\n\n/**\n * A fetch over the global one, stopped once `stopped` aborts: a request in\n * flight is aborted then, and every later one is refused before it is sent.\n * The SDK's signal is `stopped` too, so what either throws is final: its event\n * is dropped at once, a token exchange's with it, and no backoff follows.\n */\nfunction stoppableFetch(stopped: AbortSignal): typeof fetch {\n  const sent = async (input: string | URL | Request, init: RequestInit = {}): Promise<Response> => {\n    stopped.throwIfAborted();\n    return await fetch(input, { ...init, signal: init.signal ? AbortSignal.any([init.signal, stopped]) : stopped });\n  };\n  // The SDK calls its fetch as fetch is called, a URL and its init, and reads nothing else of it.\n  return sent as typeof fetch;\n}\n\n/** Where `settings` send traces: their tracing URL (the platform API's own tracing endpoint unless given), with no trailing slash; empty when it is blank. */\nfunction tracingUrlOf(settings: TracingSettings): string {\n  return withoutTrailingSlashes(textOf(settings.tracingUrl) ?? \"\");\n}\n\n// ─── What every tracer over one client shares ───\n\n/** What every tracer over one producer client shares: its jobs, one per identity (the JOBS_REMEMBERED used last), and the log its drops are explained on. */\ninterface Shared {\n  jobs: Map<string, JobHandleLike>;\n  /** The log of whoever asked for a tracer over the client last. */\n  log: Logger;\n  /** What stops the client, on the settings' tracer: once it has, what the client drops is dropped for that. */\n  stopped?: AbortSignal;\n}\n\n/** Each producer client's shared state: a client given to every answer gets one drop listener, and declares each job once. */\nconst sharedState = new WeakMap<TracingClientLike, Shared>();\n\n/** What tracers over `client` share, its drops explained on `log` from now on, those after `stopped` aborts as its stop. */\nfunction sharedOf(client: TracingClientLike, log: Logger, stopped: AbortSignal | undefined): Shared {\n  const known = sharedState.get(client);\n  if (known !== undefined) {\n    known.log = log;\n    return known;\n  }\n  const shared: Shared = { jobs: new Map(), log, stopped };\n  sharedState.set(client, shared);\n  observeDrops(client, shared);\n  return shared;\n}\n\n/** How many dropped events are explained per client: enough to say why a trace is missing, never a flood. */\nconst DROPS_EXPLAINED = 3;\n\n/** Explains the client's first dropped events on the shared log: the SDK drops what the API refuses, and a missing trace says why; once the client is stopped, why is its stop. */\nfunction observeDrops(client: TracingClientLike, shared: Shared): void {\n  let explained = 0;\n  written(() =>\n    client.on(\"drop\", (envelope, reason) => {\n      if (explained >= DROPS_EXPLAINED) {\n        return;\n      }\n      explained += 1;\n      const why = shared.stopped?.aborted === true ? TRACER_STOPPED : messageOf(reason);\n      shared.log.warn(`tracing: ${envelope?.type ?? \"event\"} dropped: ${why}`);\n    }),\n  );\n}\n\n// ─── A run ───\n\n/** A tracer over a producer client: each run the SDK's, told what its spec says. */\nfunction clientTracer(client: TracingClientLike, ports: TracerPorts): Tracer {\n  const shared = sharedOf(client, ports.log, ports.done);\n  return { run: (spec) => tracedRun(client, shared, ports, spec) };\n}\n\n/**\n * The run `spec` describes, on the trace, scoped to its NRN as text\n * (`textOf`). A run that names no NRN, or one of blanks, is not traced: the\n * tracing API refuses it. Everything the spec says is told before\n * anything is awaited, so it lands on the run's started event: an in-flight run\n * is already readable and findable. Once its end outlasts END_BUDGET_MS, its\n * parent edge is aborted; its client is the tracer's, and goes on.\n */\nfunction tracedRun(client: TracingClientLike, shared: Shared, ports: TracerPorts, spec: RunSpec): Span {\n  const nrn = textOf(spec.nrn);\n  if (nrn === undefined) {\n    return noopTracing.run(spec);\n  }\n  const identity: RunIdentity = { trace_id: spec.traceId ?? spec.runId, run_id: spec.runId, nrn };\n  const run = attempted(() => client.run(identity));\n  if (run === undefined) {\n    return noopTracing.run(spec);\n  }\n  const narrative = narrate(run, spec.title);\n  introduce(run, narrative, spec);\n  declarePlan(run, jobOf(client, shared.jobs, spec, nrn), spec.plan);\n  const edge = new AbortController();\n  const nested = nestUnder(client, identity, spec, { ...ports, signal: edge.signal });\n  const stopWaiting = (): void => edge.abort(new Error(`the run's end stopped waiting for it after ${END_BUDGET_MS} ms`));\n  return {\n    narrative,\n    traced: (step) => tracedStep(step, run, titlesOf(spec.plan)),\n    end: async (outcome) => {\n      endRun(run, narrative, outcome);\n      await waitedAtMost(delivered(client, nested), ports.log, stopWaiting);\n    },\n  };\n}\n\n/** Tells a run what its spec says of it: its title and intent, its labels, its actor and its input. */\nfunction introduce(run: RunHandleLike, narrative: Narrative, spec: RunSpec): void {\n  narrative.explain(spec.description === undefined ? {} : { what: spec.description });\n  written(() => run.labels(spec.labels));\n  const actor = spec.actor;\n  if (actor !== undefined) {\n    written(() => run.actor(actor));\n  }\n  for (const [name, value] of Object.entries(spec.input ?? {})) {\n    written(() => run.input(name, value));\n  }\n}\n\n/**\n * The job a run with a plan and a job is an instance of, declared with the plan\n * once per identity while it is remembered. The identity holds the run's\n * tenant: the SDK emits a job's node once, on the first run that is an instance\n * of it, and bakes that run's tenant into the handle, so another tenant's runs\n * are instances of a job of their own.\n */\nfunction jobOf(client: TracingClientLike, jobs: Map<string, JobHandleLike>, spec: RunSpec, nrn: string): JobHandleLike | undefined {\n  const { plan, job } = spec;\n  if (plan === undefined || job === undefined) {\n    return undefined;\n  }\n  const identity: JobIdentity = { ...job, nrn };\n  const key = JSON.stringify(identity);\n  const declared = jobs.get(key) ?? attempted(() => client.job(identity).plan(plan));\n  if (declared !== undefined) {\n    remember(jobs, key, declared);\n  }\n  return declared;\n}\n\n/** Keeps `job` as the one used last, under `key`; past JOBS_REMEMBERED, the one used least recently is forgotten. */\nfunction remember(jobs: Map<string, JobHandleLike>, key: string, job: JobHandleLike): void {\n  jobs.delete(key);\n  jobs.set(key, job);\n  if (jobs.size > JOBS_REMEMBERED) {\n    jobs.delete(jobs.keys().next().value as string);\n  }\n}\n\n/** The run is an instance of its job, which carries the plan; a plan with no job is the run's own, the SDK's run-level plan. */\nfunction declarePlan(run: RunHandleLike, job: JobHandleLike | undefined, plan: Plan | undefined): void {\n  if (job !== undefined) {\n    written(() => run.instanceOf(job));\n    return;\n  }\n  if (plan !== undefined) {\n    written(() => run.plan(plan));\n  }\n}\n\n/** Ends the run with its outcome: completed with what it answered, or failed. */\nfunction endRun(run: RunHandleLike, narrative: Narrator, outcome: SpanOutcome): void {\n  if (outcome.status === \"success\") {\n    completeRun(run, outcome.result);\n  } else {\n    failRun(run, narrative, outcome.failure);\n  }\n}\n\n/** What the client buffered, sent, then the edge to the run's parent, posted: once it resolves, the run is on the trace. */\nasync function delivered(client: TracingClientLike, nested: Promise<void>): Promise<void> {\n  await flushed(client);\n  await nested;\n}\n\n/** Waits for `delivery` END_BUDGET_MS at most: past it, a warning on `log`, and what the wait alone held is let go (`stopWaiting`). */\nasync function waitedAtMost(delivery: Promise<void>, log: Logger, stopWaiting: () => void): Promise<void> {\n  const late = () => new Error(`the run's events are still being sent after ${END_BUDGET_MS} ms: the answer does not wait for them`);\n  try {\n    await within(delivery, END_BUDGET_MS, late);\n  } catch (error) {\n    written(() => log.warn(`tracing: ${messageOf(error)}`));\n    stopWaiting();\n  }\n}\n\n/** A run that succeeded: what it answered as its `results` when that is an object, then completed. */\nfunction completeRun(run: RunHandleLike, result: unknown): void {\n  if (isJsonObject(result)) {\n    written(() => run.output(\"results\", result));\n  }\n  written(() => run.complete());\n}\n\n/** A run that failed: its narrative turned red, saying what failed, unless the handler told the failure itself; then failed with the failure's code. */\nfunction failRun(run: RunHandleLike, narrative: Narrator, failure: Failure): void {\n  if (narrative.told?.severity !== \"error\") {\n    narrative.explain({ ...narrative.told, severity: \"error\", what: failure.message });\n  }\n  failNode(run, failure, failure.message);\n}\n\n/** Fails a node with `failure` as its `tracing.error` (its code, whether it may be retried), over what `thrown` says. */\nfunction failNode(handle: NodeHandleLike | undefined, failure: Failure, thrown: unknown): void {\n  written(() => handle?.error(failure));\n  written(() => handle?.fail(thrown));\n}\n\n/** Sends what the client buffered; a flush it refuses is ignored, since the run's outcome stands whatever its delivery does. */\nasync function flushed(client: TracingClientLike): Promise<void> {\n  try {\n    await client.flush();\n  } catch {\n    // Tracing never fails a run.\n  }\n}\n\n// ─── The parent edge ───\n\n/** Where the tracing API ingests an event, under its URL: where the SDK's own transport posts. */\nconst EVENTS_PATH = \"/events\";\n\n/**\n * Nests the run under the run it is a stage of, when it names one: the\n * console's timeline folds a run with its descendants through `parent` edges.\n * The SDK opens no child of a run another process owns, so the `edge.parent`\n * event is posted to the tracing API directly, once the run's own events are\n * sent (the API refuses an edge to a node it has not seen). What keeps it back,\n * its run's end or its tracer stopping it among them (`ports.signal`,\n * `ports.done`), is a warning: it never rejects.\n */\nasync function nestUnder(client: TracingClientLike, run: RunIdentity, spec: RunSpec, ports: TracerPorts): Promise<void> {\n  const parentRunId = spec.parentRunId;\n  if (parentRunId === undefined || parentRunId === run.run_id) {\n    return;\n  }\n  try {\n    await client.flush();\n    await postEvent(parentEdgeEvent(spec.producer, run, parentRunId), ports);\n  } catch (error) {\n    ports.log.warn(`tracing: edge.parent from ${parentRunId} not posted: ${messageOf(error)}`);\n  }\n}\n\n/** The `edge.parent` event from the run `parentRunId` names, in the same trace, to `run`: the SDK's own envelope. */\nfunction parentEdgeEvent(producer: string, run: RunIdentity, parentRunId: string): Record<string, unknown> {\n  return {\n    id: sdk.occurrence(),\n    time: new Date().toISOString(),\n    type: sdk.EventType.EDGE_PARENT,\n    nrn: run.nrn,\n    producer,\n    data: { from: sdk.runRef(run.trace_id, parentRunId), to: sdk.runRef(run.trace_id, run.run_id) },\n  };\n}\n\n/**\n * Posts `event` to the tracing API through the ports' fetch (the global one\n * unless given), with the token of the settings' platform API key as its\n * bearer, sent once more with a fresh one on a 401 as every platform call is\n * (`bearerFetch`), bounded by TIMEOUT_MS and stopped by the ports' signal and\n * their `done`. A refusal throws, naming its status and what the API\n * answered, and so does an empty tracing URL, naming the setting.\n */\nasync function postEvent(event: Record<string, unknown>, ports: TracerPorts): Promise<void> {\n  const baseUrl = tracingUrlOf(ports.settings);\n  if (baseUrl === \"\") {\n    throw new Error(`the tracing API needs a URL: set ${describeSetting(\"tracingUrl\")}`);\n  }\n  const bounds = [AbortSignal.timeout(TIMEOUT_MS), ports.signal, ports.done].filter((bound) => bound !== undefined);\n  const endpoint = { fetch: bearerFetch(ports.settings, ports.fetch), baseUrl, setting: \"tracingUrl\" as const, signal: AbortSignal.any(bounds) };\n  await send(endpoint, { method: \"POST\", path: EVENTS_PATH, body: event });\n}\n\n// ─── A step ───\n\n/** `step`, each of its calls a step of the run, keyed by its name and titled from the plan (else from its key). */\nfunction tracedStep(step: Step, run: RunHandleLike, titles: Map<string, string>): Step {\n  const traced = async <Result>(name: string, optionsOrWork: StepOptions | StepWork<Result>, work?: StepWork<Result>): Promise<Result> => {\n    const call = callOf(optionsOrWork, work);\n    const node = stepNode(run, name, titles.get(name) ?? humanize(name));\n    try {\n      const result = await step(name, call.options, () => call.run(node.narrative()));\n      node.complete();\n      return result;\n    } catch (error) {\n      node.fail(error);\n      throw error;\n    }\n  };\n  return traced as Step;\n}\n\n/** One step of the run on the trace. */\ninterface StepNode {\n  /** The step's narrative, opening its node the first time it is asked. */\n  narrative(): Narrative;\n  complete(): void;\n  fail(error: unknown): void;\n}\n\n/**\n * The node of the step `key` names, opened when its first attempt starts (so a\n * name the step refuses opens none) and the same for every later attempt.\n */\nfunction stepNode(run: RunHandleLike, key: string, title: string): StepNode {\n  let opened: { handle: NodeHandleLike | undefined; narrative: Narrative } | undefined;\n  const open = () => {\n    const handle = attempted(() => run.step({ key }));\n    return { handle, narrative: narrate(handle, title) };\n  };\n  return {\n    narrative: () => {\n      opened ??= open();\n      return opened.narrative;\n    },\n    complete: () => written(() => opened?.handle?.complete()),\n    fail: (error) => failNode(opened?.handle, failureOf(error), error),\n  };\n}\n\n/** Each planned step's title, by its key: what names a step on screen when its narrative names none. */\nfunction titlesOf(plan: Plan | undefined): Map<string, string> {\n  return new Map((plan?.steps ?? []).flatMap((step) => (step.title === undefined ? [] : [[step.key, step.title] as const])));\n}\n\n/** `attach-listener-rule` → `Attach listener rule`: a readable name for a step, or a run, its declaration did not title. */\nexport function humanize(key: string): string {\n  const words = key.replace(/[-_.]+/g, \" \").trim().toLowerCase();\n  return words === \"\" ? key : `${words.charAt(0).toUpperCase()}${words.slice(1)}`;\n}\n\n// ─── The narrative ───\n\n/** A narrative that remembers what it explained last. */\ninterface Narrator extends Narrative {\n  told?: Explanation;\n}\n\n/**\n * A node's narrative, never throwing: each explanation titled as it says, else\n * as the last one was, else `title`; each link sent with every one before it,\n * since the SDK's links are the node's whole list; each output kept. Over no\n * handle (a node the SDK could not open), it tells nothing.\n */\nfunction narrate(handle: NodeHandleLike | undefined, title: string): Narrator {\n  const links: ExternalLink[] = [];\n  const narrator: Narrator = {\n    explain(body) {\n      const told = { ...body, title: body.title ?? narrator.told?.title ?? title };\n      narrator.told = told;\n      written(() => handle?.explain(told));\n    },\n    link(link) {\n      links.push(link);\n      written(() => handle?.externalLinks([...links]));\n    },\n    output(name, value) {\n      written(() => handle?.output(name, value));\n    },\n  };\n  return narrator;\n}\n\n// ─── Never failing a run ───\n\n/** What `call` answers; undefined when it throws, since tracing never fails a run. */\nfunction attempted<Result>(call: () => Result): Result | undefined {\n  try {\n    return call();\n  } catch {\n    return undefined;\n  }\n}\n\n"],"mappings":";;;;AAsEA,MAAa,eAAqB;CAChC,SAAS,SAAS;CAClB,WAAW;CACX,KAAK,YAAY,CAAC;AACpB;;AAGA,MAAa,cAAsB,EACjC,WAAW,aACb;;;;;;;;;;;;;;;;;;;;;;;;;;;ACyBA,MAAa,gBAAgB;;;;;;;;AAuD7B,SAAgB,SAAS,MAA+B,UAAyB,CAAC,GAAW;CAC3F,MAAM,QAAqB;EAAE,KAAK,QAAQ,OAAO;EAAc,OAAO,QAAQ;EAAO,UAAU,QAAQ,YAAY,WAAW;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