{"version":3,"file":"plugin-DB6jdSCd.mjs","names":["table.settings","refusalOf","platform.token","token","platform.channel"],"sources":["../src/core/text.ts","../src/core/component.ts","../src/core/errors.ts","../src/core/logger.ts","../src/core/payload.ts","../src/core/where.ts","../../contract/platform.json","../../contract/settings.json","../src/core/settings.ts","../src/core/api/transport.ts","../src/core/api/auth.ts","../src/core/api/resource.ts","../src/core/tracing/narrative.ts","../src/core/package.ts","../src/core/within.ts","../src/core/tracing/plan.ts","../src/core/tracing/step.ts","../src/core/tracing/trace.ts","../src/core/run/context.ts","../src/core/run/manifest.ts","../src/core/run/route.ts","../src/core/run/traced.ts","../src/core/run/plugin.ts"],"sourcesContent":["/**\n * What counts as text: a string with something besides blanks, read trimmed.\n * The one rule every name, id, source and token is read by: a blank value says\n * nothing, so it is never taken for one. And text as JSON: what a text says,\n * whether a value is what JSON carries as it is, and a value as JSON carries it.\n */\n\n/** `value` trimmed, when it is a string with something besides blanks; nothing otherwise. */\nexport function textOf(value: unknown): string | undefined {\n  if (typeof value !== \"string\") {\n    return undefined;\n  }\n  const trimmed = value.trim();\n  return trimmed === \"\" ? undefined : trimmed;\n}\n\n/** `names` given more than once, each named once. */\nexport function repeatedOf(names: string[]): string[] {\n  return [...new Set(names.filter((name, index) => names.indexOf(name) !== index))];\n}\n\n/** `text` without the slashes it ends with: a URL or a path whose segments another is joined to. */\nexport function withoutTrailingSlashes(text: string): string {\n  return text.replace(/\\/+$/, \"\");\n}\n\n/** An id as the platform sends it, as text: text as `textOf` reads it, or a number as its digits; nothing otherwise. */\nexport function idOf(value: unknown): string | undefined {\n  return textOf(typeof value === \"number\" ? String(value) : value);\n}\n\n/** What `text` says as JSON; `fallback` when it is not JSON. */\nexport function jsonOr(text: string, fallback: unknown): unknown {\n  try {\n    return JSON.parse(text);\n  } catch {\n    return fallback;\n  }\n}\n\n/** Whether `value` is an array, or an object of no class: what JSON writes as its items or its fields. */\nfunction isPlainContainer(value: object): boolean {\n  const prototype: unknown = Object.getPrototypeOf(value);\n  return Array.isArray(value) || prototype === Object.prototype || prototype === null;\n}\n\n/** Whether `value`, reached through `ancestors`, is what JSON carries as it is. */\nfunction isJsonWithin(value: unknown, ancestors: readonly object[]): boolean {\n  if (value === null || typeof value === \"string\" || typeof value === \"boolean\") {\n    return true;\n  }\n  if (typeof value === \"number\") {\n    return Number.isFinite(value);\n  }\n  if (typeof value !== \"object\" || ancestors.includes(value) || !isPlainContainer(value)) {\n    return false;\n  }\n  const within = [...ancestors, value];\n  return Object.values(value).every((item) => isJsonWithin(item, within));\n}\n\n/**\n * Whether `value` is what JSON carries as it is: null, true or false, a finite\n * number, text, or an array or a plain object of them, however deep. Anything\n * else JSON writes otherwise or not at all (a Date as text, a Map as `{}`, an\n * instance of a class as its fields; undefined, a function, NaN, a cycle), and\n * so is a value a field of which cannot be read.\n */\nexport function isJson(value: unknown): boolean {\n  try {\n    return isJsonWithin(value, []);\n  } catch {\n    return false;\n  }\n}\n\n/** `value` as JSON carries it, written and read back: a copy sharing nothing with it; undefined when JSON writes nothing for it. One JSON cannot write (a BigInt, a cycle) throws. */\nexport function asJson(value: unknown): unknown {\n  const written = JSON.stringify(value);\n  return written === undefined ? undefined : JSON.parse(written);\n}\n","/**\n * A component is what a plugin publishes: an entity of some kind, the API's\n * own resource type, named uniquely in the package, with the body that kind's\n * API takes exactly as its author wrote it. The core knows no kind: a kind's\n * sugar builds its components with `component`.\n */\n\nimport { textOf } from \"./text\";\n\n/** The API's entity name: snake_case, a letter first. */\nconst KIND = /^[a-z][a-z0-9_]*$/;\n\n/** Where a component lives on the API, when the convention does not hold, and who owns it. */\nexport interface ComponentOptions {\n  /** The component this one belongs to, created under it. */\n  parent?: Component;\n  /** The collection it is created in. */\n  path?: string;\n  /** Where it is found before it is created. */\n  list?: string;\n  /** The field that identifies it in that listing. */\n  identity?: string;\n  /** `platform`: the platform creates it; publish looks it up and pins it, never writes it. */\n  owner?: \"platform\";\n}\n\n/** What publish registers: one manifest entry, the API's body as written. */\nexport interface Component {\n  readonly kind: string;\n  readonly name: string;\n  readonly body: Record<string, unknown>;\n  readonly parent?: Component;\n  readonly children: Component[];\n  readonly path?: string;\n  readonly list?: string;\n  readonly identity?: string;\n  readonly owner?: \"platform\";\n}\n\n/** Every component `component` built: what tells a component from a value shaped like one. */\nconst built = new WeakSet<object>();\n\n/** A component of `kind` named `name`, its `body` as written; it goes under its parent's children. Its options set only where it lives and who owns it, whatever else an object wider than their type carries. */\nexport function component(kind: string, name: string, body: Record<string, unknown>, options: ComponentOptions = {}): Component {\n  if (typeof kind !== \"string\" || !KIND.test(kind)) {\n    throw new Error(`component kind \"${kind}\" is not the API's snake_case entity name, as \"approval_policy\"`);\n  }\n  if (textOf(name) === undefined) {\n    throw new Error(`a component of kind \"${kind}\" needs a name`);\n  }\n  const { parent, path, list, identity, owner } = options;\n  const declared: Component = { kind, name, body, children: [], parent, path, list, identity, owner };\n  parent?.children.push(declared);\n  built.add(declared);\n  return declared;\n}\n\n/** Whether `value` is a component `component` built. */\nexport function isComponent(value: unknown): value is Component {\n  return typeof value === \"object\" && value !== null && built.has(value);\n}\n\n/** What a body embeds to name another component, which the CLI resolves to its id at publish: `{ ref: \"<kind>/<name>\" }`. */\nexport function ref(declared: Component): { ref: string } {\n  return { ref: `${declared.kind}/${declared.name}` };\n}\n\n/** The component `declared` is under, at the top. */\nfunction topmostOf(declared: Component): Component {\n  let topmost = declared;\n  while (topmost.parent !== undefined) {\n    topmost = topmost.parent;\n  }\n  return topmost;\n}\n\n/** Every component and the ones under it, each once, in declaration order, each after its parent. */\nexport function collect(roots: Component[]): Component[] {\n  const collected = new Set<Component>();\n  const visit = (declared: Component): void => {\n    if (collected.has(declared)) {\n      return;\n    }\n    collected.add(declared);\n    declared.children.forEach(visit);\n  };\n  roots.map(topmostOf).forEach(visit);\n  return [...collected];\n}\n","/** How a handler fails, what any error says, and how a definition is refused. */\n\n/** The code of a failure no ActionError names. */\nconst EXECUTION_ERROR = \"EXECUTION_ERROR\";\n\n/** What a thrown value says when it cannot be made text. */\nconst UNDESCRIBED = \"a value that cannot be described\";\n\n/**\n * What an ActionError says beside its code and message. `retryable` and\n * `details` are the failure's: the trace's error carries them (the tracing\n * SDK's `tracing.error`), and so does `RunResult.failure`; neither the answer\n * the worker prints, nor its gRPC result, nor what the lifecycle reports to the\n * platform carries them, and nothing runs the action again.\n */\nexport interface ActionErrorOptions {\n  /** Whether running the action again may succeed, as the trace tells it. Default false. */\n  retryable?: boolean;\n  /** What the trace tells of the failure beside its message. */\n  details?: Record<string, unknown>;\n  /** What made it fail, as `Error`'s own `cause`. */\n  cause?: unknown;\n}\n\n/**\n * Fails the action with a named code. Any other throw is an EXECUTION_ERROR;\n * this one keeps the code the author chose, so tests, logs and traces all read\n * the same name.\n */\nexport class ActionError extends Error {\n  readonly code: string;\n  readonly retryable: boolean;\n  readonly details?: Record<string, unknown>;\n\n  constructor(code: string, message: string, options: ActionErrorOptions = {}) {\n    // `Error` reads only `cause`, and sets it only when the options carry one.\n    super(message, options);\n    this.name = \"ActionError\";\n    this.code = code;\n    this.retryable = options.retryable ?? false;\n    this.details = options.details;\n  }\n}\n\n/** How an answer failed: its code, its message, whether the platform may retry it, and its details. */\nexport interface Failure {\n  code: string;\n  message: string;\n  retryable: boolean;\n  details?: Record<string, unknown>;\n}\n\n/** The first ActionError in `error`'s cause chain, each error in it visited once; none when the chain cannot be read. */\nfunction actionErrorIn(error: unknown): ActionError | undefined {\n  const visited = new Set<Error>();\n  try {\n    for (let current: unknown = error; current instanceof Error && !visited.has(current); current = current.cause) {\n      if (current instanceof ActionError) {\n        return current;\n      }\n      visited.add(current);\n    }\n  } catch {\n    // An error whose cause cannot be read ends the chain.\n  }\n  return undefined;\n}\n\n/** The failure the ActionError `named` says: its code and its message as text, whether it is retryable, its details when it has them; none when a field cannot be read or made text. */\nfunction namedFailureOf(named: ActionError): Failure | undefined {\n  try {\n    const failure: Failure = { code: String(named.code), message: String(named.message), retryable: named.retryable };\n    const details = named.details;\n    if (details !== undefined) {\n      failure.details = details;\n    }\n    return failure;\n  } catch {\n    return undefined;\n  }\n}\n\n/**\n * The failure `error` names, never a throw, whatever was thrown: the first\n * ActionError in its cause chain, else (or when that one cannot be read) an\n * EXECUTION_ERROR with its message (`messageOf`: a fixed text when it has none\n * that can be read).\n */\nexport function failureOf(error: unknown): Failure {\n  const named = actionErrorIn(error);\n  const failure = named === undefined ? undefined : namedFailureOf(named);\n  return failure ?? { code: EXECUTION_ERROR, message: messageOf(error), retryable: false };\n}\n\n/** What a refusal of `problems` says: each one, joined by `; `, after `<where>: ` when `where` names what they are of. */\nexport function refusalText(problems: string[], where?: string): string {\n  const joined = problems.join(\"; \");\n  return where === undefined ? joined : `${where}: ${joined}`;\n}\n\n/** Refuses with every problem at once, when there is any: one Error saying them as `refusalText` does. */\nexport function refuseProblems(problems: string[], where?: string): void {\n  if (problems.length > 0) {\n    throw new Error(refusalText(problems, where));\n  }\n}\n\n/** A failure as it is said, wherever it is: in the log, and to the platform: `<code>: <message>`. */\nexport function failureText(failure: Failure): string {\n  return `${failure.code}: ${failure.message}`;\n}\n\n/** The message of anything thrown: an Error's own, else the value as text; a value that cannot be made text says so. */\nexport function messageOf(error: unknown): string {\n  try {\n    return error instanceof Error ? String(error.message) : String(error);\n  } catch {\n    return UNDESCRIBED;\n  }\n}\n","/**\n * The one logger every run takes (`log`) and every handler gets (`context.log`),\n * whatever the plugin's kind. It is a logger, not a trace: a handler's steps,\n * their outcomes and durations go to the tracing port.\n */\n\nimport { Console } from \"console\";\n\n/**\n * Where a run says what it does, by level: pino, winston or a `Console` fit.\n * It writes to stderr: a worker's stdout is its answer (or the gRPC\n * handshake), and the global `console` writes `info` and `debug` there.\n */\nexport interface Logger {\n  debug(message: string): void;\n  info(message: string): void;\n  warn(message: string): void;\n  error(message: string): void;\n}\n\n/** The default `log`: a `Console` on stderr for every level, since stdout is the answer. */\nexport const stderrLogger: Logger = new Console({ stdout: process.stderr, stderr: process.stderr });\n\n/** Drops what it is given. */\nfunction ignore(): void {}\n\n/**\n * Runs `write`, one sink's call (a logger's, a stream's, an observer's, a\n * callback's), ignoring what it throws and, when it answers a promise, what\n * that rejects with: a sink that cannot take what it is told loses it, never\n * its caller, and nothing it does is left unhandled.\n */\nexport function written(write: () => unknown): void {\n  try {\n    void Promise.resolve(write()).catch(ignore);\n  } catch {\n    // What its caller does stands whatever a sink does with what it is told.\n  }\n}\n\n/** Says nothing: the log of a port whose calls its caller records itself. */\nexport const silentLogger: Logger = {\n  debug() {},\n  info() {},\n  warn() {},\n  error() {},\n};\n\n/** A message a run logged, at its level. */\nexport interface RunLog {\n  level: keyof Logger;\n  message: string;\n}\n\n/** A logger that records each message at its level, as it was logged, and writes nothing: what a run's `logs` are. */\nexport function recordingLog(): { log: Logger; logs: RunLog[] } {\n  const logs: RunLog[] = [];\n  const recorded = (level: keyof Logger) => (message: string): void => {\n    logs.push({ level, message });\n  };\n  return { log: { debug: recorded(\"debug\"), info: recorded(\"info\"), warn: recorded(\"warn\"), error: recorded(\"error\") }, logs };\n}\n","/**\n * What the agent delivers: a document, a JSON object, and the payload in it.\n * The core reads nothing a payload says; this is the one place that knows\n * where a delivery puts it.\n */\n\nimport { jsonOr } from \"./text\";\n\n/** What the agent delivered for a plugin to answer: a JSON object. */\nexport type Payload = Record<string, unknown>;\n\n/** Whether `value` is a JSON object: an object, never null or an array. */\nexport function isJsonObject(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** `value` when it is a JSON object, else an empty one. */\nexport function objectOf(value: unknown): Record<string, unknown> {\n  return isJsonObject(value) ? value : {};\n}\n\n/** `text` without one pair of single quotes around it, which a shell may leave on a value. */\nfunction unquoted(text: string): string {\n  return text.startsWith(\"'\") && text.endsWith(\"'\") ? text.slice(1, -1) : text;\n}\n\n/** The document `text` carries, trimmed and unquoted first; undefined unless it is a JSON object. */\nexport function documentOf(text: string): Record<string, unknown> | undefined {\n  const document = jsonOr(unquoted(text.trim()), undefined);\n  return isJsonObject(document) ? document : undefined;\n}\n\n/** The payload a document carries: its `notification` when that is an object, else the document itself. */\nexport function payloadOf(document: Record<string, unknown>): Payload {\n  const delivered = document.notification;\n  return isJsonObject(delivered) ? delivered : document;\n}\n\n/** The document the agent delivers `payload` in: `{ notification: <payload> }`, which `payloadOf` unwraps to the payload whatever it holds. */\nexport function deliveryOf(payload: Payload): Record<string, unknown> {\n  return { notification: payload };\n}\n","/**\n * A route's match by its payload's fields: `where({ \"action\": \"create\",\n * \"link\": null })`. The core reads no payload's field itself: what a field\n * holds is the caller's, written as a dotted path, each segment a field JSON\n * gives (an object's own field, an array's item by its index, never its\n * length). Values are JSON, copied when the match is built, and compare as\n * JSON (`equal`), as describe compares a channel's filters too.\n */\n\nimport { refuseProblems } from \"./errors\";\nimport { isJsonObject, type Payload } from \"./payload\";\nimport { asJson, isJson } from \"./text\";\n\n/** An array's item by its index: the one kind of segment an array has a field for. */\nconst INDEX = /^\\d+$/;\n\n/** Whether `reached` has the field `segment` as JSON gives it: an object's own field, an array's item by its index. */\nfunction hasField(reached: object, segment: string): boolean {\n  return (!Array.isArray(reached) || INDEX.test(segment)) && Object.hasOwn(reached, segment);\n}\n\n/** What the dotted `path` reaches in `payload`: the fields JSON gives only, undefined once it reaches nothing. */\nfunction valueAt(payload: Payload, path: string): unknown {\n  let reached: unknown = payload;\n  for (const segment of path.split(\".\")) {\n    if (typeof reached !== \"object\" || reached === null || !hasField(reached, segment)) {\n      return undefined;\n    }\n    reached = (reached as Record<string, unknown>)[segment];\n  }\n  return reached;\n}\n\n/** Whether two JSON values are equal: an array or an object by its values, however deep, its fields in any order, anything else by `===`. */\nexport function equal(expected: unknown, actual: unknown): boolean {\n  if (Array.isArray(expected)) {\n    return Array.isArray(actual) && expected.length === actual.length && expected.every((item, index) => equal(item, actual[index]));\n  }\n  if (isJsonObject(expected)) {\n    return isJsonObject(actual) && sameFields(expected, actual);\n  }\n  return expected === actual;\n}\n\n/** Whether two objects have the same own fields, each with an equal value. */\nfunction sameFields(expected: Record<string, unknown>, actual: Record<string, unknown>): boolean {\n  const fields = Object.keys(expected);\n  return fields.length === Object.keys(actual).length && fields.every((field) => Object.hasOwn(actual, field) && equal(expected[field], actual[field]));\n}\n\n/** Whether a field's `actual` value matches the `expected` one: null matches null or absent. */\nfunction matches(expected: unknown, actual: unknown): boolean {\n  if (expected === null) {\n    return actual === null || actual === undefined;\n  }\n  return equal(expected, actual);\n}\n\n/** Each path of `fields` whose value JSON cannot carry: it would match what JSON writes for it, or nothing. */\nfunction strayPathsOf(fields: Record<string, unknown>): string[] {\n  return Object.entries(fields)\n    .filter(([, value]) => !isJson(value))\n    .map(([path]) => `\"${path}\"`);\n}\n\n/**\n * A match that accepts a payload whose every dotted path's value equals its\n * field's, `null` matching null or absent. The fields are copied, however\n * deep: changing them after changes nothing it matches. A value JSON cannot\n * carry (a Date, a Map, undefined, …) is refused, naming each path.\n */\nexport function where(fields: Record<string, unknown>): (payload: Payload) => boolean {\n  const strays = strayPathsOf(fields);\n  if (strays.length > 0) {\n    refuseProblems([`${strays.join(\", \")} must each be a JSON value: null, true or false, a finite number, text, or an array or a plain object of them`], \"where\");\n  }\n  const expected = Object.entries(asJson(fields) as Record<string, unknown>);\n  return (payload) => expected.every(([path, value]) => matches(value, valueAt(payload, path)));\n}\n","","","/**\n * The settings: what the library runs with, one parameter per row of\n * contract/settings.json, each a string with the default the table gives it.\n * A run resolves them once, from what its caller gives (`settingsOf`): a value\n * given in code wins, then what the caller fills in for the rest, then the\n * default. The library reads no file and no environment variable for them:\n * the agent's command line (`main`) reads the variables the agent sets on a\n * worker, the table's `agent` column, through `agentSettingsOf`, and hands\n * them over. A message about a setting names it with `describeSetting`. Where\n * a setting is used, a blank value is absent (`textOf`); the platform API URL\n * absent is its default (`textOrDefaultOf`).\n */\n\nimport table from \"../../../contract/settings.json\" with { type: \"json\" };\nimport { textOf, withoutTrailingSlashes } from \"./text\";\n\n/** A setting the agent sets on a worker, in the variable contract/settings.json's `agent` column names. */\nexport type AgentSettingName =\n  | \"apiUrl\"\n  | \"apiKey\"\n  | \"actionContext\"\n  | \"grpcListen\"\n  | \"agentPlugin\"\n  | \"workerTlsCa\"\n  | \"workerTlsCaFile\"\n  | \"workerTlsCert\"\n  | \"workerTlsCertFile\"\n  | \"workerTlsKey\"\n  | \"workerTlsKeyFile\";\n\n/** The name of a setting: one per row of contract/settings.json. */\nexport type SettingName = AgentSettingName | \"tracingUrl\";\n\n/** A run's settings, resolved: one string per setting, empty when nothing gives it and the table gives it no default. */\nexport type Settings = Readonly<Record<SettingName, string>>;\n\n/** A row of contract/settings.json: the agent sets only the settings that name its variable. */\ninterface Setting {\n  name: SettingName;\n  default?: string;\n  agent?: string;\n  about: string;\n}\n\nconst ROWS = table.settings as Setting[];\n\nconst SETTINGS = Object.fromEntries(ROWS.map((setting) => [setting.name, setting])) as Record<SettingName, Setting>;\n\n/** The variable the agent sets each of its settings in, in the table's order. */\nconst AGENT_VARIABLES = Object.fromEntries(ROWS.filter((setting) => setting.agent !== undefined).map((setting) => [setting.name, setting.agent])) as Record<AgentSettingName, string>;\n\n/** A placeholder in a default: the name of a setting before it in the table, `${apiUrl}`. */\nconst PLACEHOLDER = /\\$\\{(?<name>[^}]*)\\}/g;\n\n/** `text` with each placeholder filled with the setting it names as it is used (`textOrDefaultOf`), from what `resolved` holds, without the slashes it ends with. */\nfunction filled(text: string, resolved: Partial<Settings>): string {\n  return text.replace(PLACEHOLDER, (placeholder, name: SettingName) => withoutTrailingSlashes(textOrDefaultOf(name, resolved[name], resolved)));\n}\n\n/**\n * The setting `name` where a blank value is absent and an absent one is its\n * default: `value` read as text (`textOf`), else the table's default, a\n * placeholder in it filled from `resolved`; else empty. What the platform API\n * URL is wherever it is used, and what a placeholder is filled with.\n */\nexport function textOrDefaultOf(name: SettingName, value: string | undefined, resolved: Partial<Settings> = {}): string {\n  return textOf(value) ?? filled(SETTINGS[name].default ?? \"\", resolved);\n}\n\n/**\n * A run's settings, frozen: each the value `given` holds, even empty; else the\n * one `fallback` holds; else its default, a placeholder in it filled with the\n * setting it names; else empty. A setting given undefined is unset.\n */\nexport function settingsOf(given: Partial<Settings> = {}, fallback: Partial<Settings> = {}): Settings {\n  const resolved: Partial<Record<SettingName, string>> = {};\n  for (const setting of ROWS) {\n    resolved[setting.name] = given[setting.name] ?? fallback[setting.name] ?? filled(setting.default ?? \"\", resolved);\n  }\n  return Object.freeze(resolved) as Settings;\n}\n\n/** The settings the agent sets, each read from its variable in `environment` when that holds it, even empty; no other variable is read. */\nexport function agentSettingsOf(environment: Record<string, string | undefined>): Partial<Settings> {\n  const held = Object.entries(AGENT_VARIABLES).filter(([, variable]) => environment[variable] !== undefined);\n  return Object.fromEntries(held.map(([name, variable]) => [name, environment[variable]]));\n}\n\n/** A setting as a message names it: `the platform API key (settings.apiKey; the agent sets NP_API_KEY)`; by its parameter alone when the agent does not set it. */\nexport function describeSetting(name: SettingName): string {\n  const { about, agent } = SETTINGS[name];\n  return agent === undefined ? `${about} (settings.${name})` : `${about} (settings.${name}; the agent sets ${agent})`;\n}\n\n/** The variable the agent sets `name` in, for what starts a worker as the agent does. */\nexport function agentVariableOf(name: AgentSettingName): string {\n  return AGENT_VARIABLES[name];\n}\n\n/** Every variable the agent sets on a worker, one per setting it sets, in the table's order. */\nexport function agentVariables(): string[] {\n  return Object.values(AGENT_VARIABLES);\n}\n","/**\n * How a call reaches the platform API: its URL under the API's base URL, JSON\n * in and out, a refusal named, and so a call that gets no whole answer and a\n * base URL that is none. And the port a test or a local run gives in place of\n * the platform: it sends nothing, records each request and answers it.\n */\n\nimport { messageOf } from \"../errors\";\nimport { silentLogger, type Logger } from \"../logger\";\nimport { describeSetting, textOrDefaultOf, type SettingName } from \"../settings\";\nimport { jsonOr, textOf, withoutTrailingSlashes } from \"../text\";\n\n/** The platform port: what sends a request to the platform and answers its response. */\nexport type Fetch = (request: Request) => Promise<Response>;\n\n/** A query string's values; an undefined or empty one is left out. */\nexport type Query = Record<string, string | number | boolean | undefined>;\n\n/** Where calls go: the port that sends them, the API's base URL and the setting that gives it, and what cancels them. */\nexport interface Endpoint {\n  fetch: Fetch;\n  baseUrl: string;\n  /** The setting `baseUrl` is: what a base URL that is not one is refused naming. */\n  setting: SettingName;\n  signal?: AbortSignal;\n}\n\n/** A call: its method, its path as the API spells it, its query and its body. */\nexport interface Call {\n  method: string;\n  path: string;\n  query?: Query;\n  body?: unknown;\n}\n\nconst JSON_TYPE = \"application/json\";\n\n/** The protocols a setting's URL may have: the APIs it reaches speak HTTP. */\nconst WEB_PROTOCOLS = [\"http:\", \"https:\"];\n\n/** `text` as a URL; none when it is not one. */\nfunction urlIn(text: string): URL | undefined {\n  try {\n    return new URL(text);\n  } catch {\n    return undefined;\n  }\n}\n\n/** `text`, the URL the setting `setting` gives; one that is not an http or https URL (`localhost:8080` is one of the scheme `localhost:`) is refused, naming the setting. */\nexport function settingUrlOf(text: string, setting: SettingName): URL {\n  const url = urlIn(text);\n  if (url === undefined || !WEB_PROTOCOLS.includes(url.protocol)) {\n    throw new Error(`${describeSetting(setting)} is not an http or https URL: ${JSON.stringify(text)}`);\n  }\n  return url;\n}\n\n/** The URL of `path` under the endpoint's base URL, the base's own path kept, with the query's values but an undefined or empty one; a base that is not an http or https URL is refused, naming its setting. */\nfunction urlOf(endpoint: Endpoint, path: string, query: Query = {}): URL {\n  settingUrlOf(endpoint.baseUrl, endpoint.setting);\n  const url = new URL(`${withoutTrailingSlashes(endpoint.baseUrl)}${path}`);\n  for (const [name, value] of Object.entries(query)) {\n    if (value !== undefined && value !== \"\") {\n      url.searchParams.set(name, String(value));\n    }\n  }\n  return url;\n}\n\n/** The path of `url` under the API root at `baseUrl` (the base's own path left out), with its query. */\nfunction pathUnder(baseUrl: string, url: URL): string {\n  const root = withoutTrailingSlashes(new URL(baseUrl).pathname);\n  const path = url.pathname.startsWith(`${root}/`) ? url.pathname.slice(root.length) : url.pathname;\n  return `${path}${url.search}`;\n}\n\n/** The request `call` makes at `url`: asking for JSON, and sending its body as JSON when it has one. */\nfunction requestOf(url: URL, call: Call, signal: AbortSignal | undefined): Request {\n  if (call.body === undefined) {\n    return new Request(url, { method: call.method, headers: { Accept: JSON_TYPE }, signal });\n  }\n  const headers = { Accept: JSON_TYPE, \"Content-Type\": JSON_TYPE };\n  return new Request(url, { method: call.method, headers, body: JSON.stringify(call.body), signal });\n}\n\n/**\n * What a call `called` names (`<METHOD> <path>`) throws when it gets no whole\n * answer (the network fails, the attempt times out, it is cancelled, before\n * its answer or while its body is read): `API: <METHOD> <path> — <why>`, what\n * kept the answer back its cause.\n */\nfunction unanswered(called: string, error: unknown): Error {\n  return new Error(`API: ${called} — ${messageOf(error)}`, { cause: error });\n}\n\n/** What `endpoint` answers `request`, the call `called` names; one it gets no answer to throws as `unanswered` says. */\nasync function answerTo(endpoint: Endpoint, request: Request, called: string): Promise<Response> {\n  try {\n    return await endpoint.fetch(request);\n  } catch (error) {\n    throw unanswered(called, error);\n  }\n}\n\n/** What every message about an answer starts with: `API <status> <statusText>: <METHOD> <path>`. */\nfunction answeredOf(response: Response, called: string): string {\n  const status = `${response.status} ${response.statusText}`.trimEnd();\n  return `API ${status}: ${called}`;\n}\n\n/** A refusal: what the platform answered after `answered`, when it said anything that can be read. */\nasync function refusalOf(response: Response, answered: string): Promise<Error> {\n  const text = await response.text().catch(() => \"\");\n  return new Error(text === \"\" ? answered : `${answered} — ${text}`);\n}\n\n/** The text of a success's body, the call `called` names; a body that cannot be read wholly is a call that gets no answer (`unanswered`). */\nasync function bodyTextOf(response: Response, called: string): Promise<string> {\n  try {\n    return await response.text();\n  } catch (error) {\n    throw unanswered(called, error);\n  }\n}\n\n/** What a success's body `text` says as JSON: undefined when it is empty or blank; text that is not JSON throws after `answered`. */\nfunction answerIn(text: string, answered: string): unknown {\n  if (textOf(text) === undefined) {\n    return undefined;\n  }\n  try {\n    return JSON.parse(text);\n  } catch {\n    throw new Error(`${answered}, its body not JSON: ${text}`);\n  }\n}\n\n/**\n * Sends `call` to `endpoint` and answers the platform's JSON, undefined when\n * the answer has no body (an empty or a blank one). A refusal throws, naming\n * the status, the method, the path and what the platform answered; so does a\n * success whose body is not JSON. A call that gets no whole answer throws,\n * naming the method and the path and why (`unanswered`), and so does a base\n * URL that is none, naming its setting.\n */\nexport async function send<Result = unknown>(endpoint: Endpoint, call: Call): Promise<Result> {\n  const url = urlOf(endpoint, call.path, call.query);\n  const called = `${call.method} ${pathUnder(endpoint.baseUrl, url)}`;\n  const response = await answerTo(endpoint, requestOf(url, call, endpoint.signal), called);\n  const answered = answeredOf(response, called);\n  if (!response.ok) {\n    throw await refusalOf(response, answered);\n  }\n  return answerIn(await bodyTextOf(response, called), answered) as Result;\n}\n\n/** A request as the recording platform saw it: its method, its path and query under the API root, and its body. */\nexport interface RecordedRequest {\n  method: string;\n  path: string;\n  body?: unknown;\n}\n\n/** What a recording platform tells, how it answers, and where the API it stands for is. */\nexport interface RecordingOptions {\n  /** Told each request at debug; silent unless given. */\n  log?: Logger;\n  /** What answers each request; `200 {}` unless given. */\n  respond?: (request: Request) => Response | Promise<Response>;\n  /** The platform API URL each path is recorded under; the `apiUrl` setting's default unless given, or given blank. */\n  apiUrl?: string;\n}\n\n/** `request` as recorded: its path under the platform API URL `apiUrl`'s own path, its body as JSON, or as its text when it is not JSON. */\nasync function recordedOf(request: Request, apiUrl: string): Promise<RecordedRequest> {\n  const recorded: RecordedRequest = { method: request.method, path: pathUnder(apiUrl, new URL(request.url)) };\n  const text = await request.clone().text();\n  if (text !== \"\") {\n    recorded.body = jsonOr(text, text);\n  }\n  return recorded;\n}\n\n/** A recorded request as the log tells it: `<METHOD> <path>`, and its body as JSON when it has one. */\nfunction toldOf(recorded: RecordedRequest): string {\n  const line = `${recorded.method} ${recorded.path}`;\n  return recorded.body === undefined ? line : `${line} ${JSON.stringify(recorded.body)}`;\n}\n\n/**\n * A platform port that sends nothing: it records each request (`requests`),\n * its path under `apiUrl`, tells `log` of it at debug, and answers what\n * `respond` answers, `200 {}` unless given. A local run's port, and a test's.\n */\nexport function recordingPlatform(options: RecordingOptions = {}): { fetch: Fetch; requests: RecordedRequest[] } {\n  const { log = silentLogger, respond = () => Response.json({}) } = options;\n  const apiUrl = textOrDefaultOf(\"apiUrl\", options.apiUrl);\n  const requests: RecordedRequest[] = [];\n  const record: Fetch = async (request) => {\n    const recorded = await recordedOf(request, apiUrl);\n    requests.push(recorded);\n    log.debug(toldOf(recorded));\n    return respond(request);\n  };\n  return { fetch: record, requests };\n}\n","/**\n * The platform's credentials: a run's API key exchanged at its platform API\n * for the token every call sends (contract/platform.json's `token`), the port\n * that sends a request with it (`bearerFetch`), and the authorized port, the\n * default platform port, which sends it only to the platform API's own origin.\n * Each is read as text where it is used: a blank key is none, a blank URL the\n * table's default.\n */\n\nimport platform from \"../../../../contract/platform.json\" with { type: \"json\" };\nimport { describeSetting, textOrDefaultOf, type Settings } from \"../settings\";\nimport { textOf } from \"../text\";\nimport { send, settingUrlOf, type Fetch } from \"./transport\";\n\n/** How long one attempt to reach the platform may take. */\nexport const TIMEOUT_MS = 30_000;\n\n/** The platform's credentials, as a run's settings give them: the platform API's URL, where the key is exchanged, and the key. */\nexport type Credentials = Pick<Settings, \"apiUrl\" | \"apiKey\">;\n\n/**\n * The credentials `given` holds, read as text, copied and frozen: a blank URL\n * is the table's default (`textOrDefaultOf`), a blank key is none (empty).\n * What is written to `given` after, or tried on the copy, changes nothing.\n */\nexport function credentialsOf(given: Credentials): Credentials {\n  return Object.freeze({ apiUrl: textOrDefaultOf(\"apiUrl\", given.apiUrl), apiKey: textOf(given.apiKey) ?? \"\" });\n}\n\n/** A key's exchange at a platform API: what answers its token, and the token once it has. */\ninterface Exchange {\n  answered: Promise<string>;\n  token?: string;\n}\n\n/** Each key's exchange at each platform API, from the moment it starts: every call shares it until a call refused its token replaces it. */\nconst exchanges = new Map<string, Exchange>();\n\n/** How `accessToken` gets the token. */\nexport interface AccessTokenOptions {\n  /** The token a call was answered 401 with: the key is exchanged again, unless the exchange cached is already another one, so the calls refused at once share one. */\n  refused?: string;\n  /** What sends the exchange; the global fetch unless given. */\n  fetch?: typeof fetch;\n  /** What stops the caller's wait for the token, with its reason; the exchange goes on for every other call. */\n  signal?: AbortSignal;\n}\n\n/** The token the exchange of `credentials`' key at their platform API answers, bounded by TIMEOUT_MS. */\nasync function exchange(credentials: Credentials, port: Fetch): Promise<string> {\n  const { method, path, answer } = platform.token;\n  const endpoint = { fetch: port, baseUrl: credentials.apiUrl, setting: \"apiUrl\" as const, signal: AbortSignal.timeout(TIMEOUT_MS) };\n  const answered = await send<Record<string, unknown> | undefined>(endpoint, { method, path, body: { api_key: credentials.apiKey } });\n  const token = textOf(answered?.[answer]);\n  if (token === undefined) {\n    throw new Error(`${method} ${path} answered no ${answer}`);\n  }\n  return token;\n}\n\n/** A new exchange of `credentials`' key, cached as `key` names it: its token kept once it answers, and forgotten when it fails, so the next call exchanges again. */\nfunction started(key: string, credentials: Credentials, port: Fetch): Exchange {\n  const begun: Exchange = { answered: exchange(credentials, port) };\n  exchanges.set(key, begun);\n  begun.answered.then(\n    (token) => {\n      begun.token = token;\n    },\n    () => {\n      if (exchanges.get(key) === begun) {\n        exchanges.delete(key);\n      }\n    },\n  );\n  return begun;\n}\n\n/** Whether `known` gives a token a caller may use: it is cached, and it answers a token other than the one `refused` (one in flight answers a newer one). */\nfunction isUsable(known: Exchange | undefined, refused: string | undefined): known is Exchange {\n  return known !== undefined && (refused === undefined || known.token !== refused);\n}\n\n/** What `answered` gives, unless `signal` aborts first: the wait then rejects with the signal's reason, and the exchange goes on. */\nfunction waited(answered: Promise<string>, signal: AbortSignal | undefined): Promise<string> {\n  if (signal === undefined) {\n    return answered;\n  }\n  return new Promise((resolve, reject) => {\n    const stop = (): void => reject(signal.reason);\n    signal.addEventListener(\"abort\", stop, { once: true });\n    answered.then(resolve, reject).finally(() => signal.removeEventListener(\"abort\", stop));\n  });\n}\n\n/**\n * The token of `given`'s key, read as text (`credentialsOf`): exchanged once\n * per key and platform API (`POST <apiUrl>/token` with `{ \"api_key\": <key> }`,\n * the answer's `access_token`) and cached; a token `refused` is exchanged\n * again once, however many calls it was refused for. Without a key it throws,\n * naming the setting; a `signal` aborted stops the wait, never the exchange.\n */\nexport async function accessToken(given: Credentials, options: AccessTokenOptions = {}): Promise<string> {\n  const credentials = credentialsOf(given);\n  if (credentials.apiKey === \"\") {\n    throw new Error(`the platform API needs credentials: set ${describeSetting(\"apiKey\")}`);\n  }\n  options.signal?.throwIfAborted();\n  const key = JSON.stringify([credentials.apiUrl, credentials.apiKey]);\n  const known = exchanges.get(key);\n  const current = isUsable(known, options.refused) ? known : started(key, credentials, options.fetch ?? fetch);\n  return waited(current.answered, options.signal);\n}\n\n/** One attempt at `request` through `port` with `token` as its bearer, bounded by TIMEOUT_MS and the request's own signal. */\nfunction attempt(port: typeof fetch, request: Request, token: string): Promise<Response> {\n  const sent = new Request(request.clone(), { signal: AbortSignal.any([request.signal, AbortSignal.timeout(TIMEOUT_MS)]) });\n  sent.headers.set(\"Authorization\", `Bearer ${token}`);\n  return port(sent);\n}\n\n/** Lets `response`'s body go unread, so what holds it is freed before the request is sent again; a body that cannot be let go is left as it is. */\nasync function discarded(response: Response): Promise<void> {\n  try {\n    await response.body?.cancel();\n  } catch {\n    // The request is sent again whatever its refused answer holds.\n  }\n}\n\n/**\n * A port that sends each request through `port` (the global fetch unless\n * given) with the token of `credentials`' key as its bearer (`accessToken`,\n * the exchange sent through `port` too), and once more with a fresh token when\n * it is answered 401, the refused answer's body let go first. Each attempt is\n * bounded by TIMEOUT_MS and the request's own signal, which stops the wait for\n * the token too.\n */\nexport function bearerFetch(credentials: Credentials, port?: typeof fetch): Fetch {\n  return async (request) => {\n    const through = { fetch: port, signal: request.signal };\n    const token = await accessToken(credentials, through);\n    const answered = await attempt(port ?? fetch, request, token);\n    if (answered.status !== 401) {\n      return answered;\n    }\n    await discarded(answered);\n    return attempt(port ?? fetch, request, await accessToken(credentials, { ...through, refused: token }));\n  };\n}\n\n/** Whether `request` goes to the origin of the platform API `credentials` reach; a platform API URL that is not an http or https URL is refused, naming the setting. */\nfunction isPlatformRequest(request: Request, credentials: Credentials): boolean {\n  return new URL(request.url).origin === settingUrlOf(credentials.apiUrl, \"apiUrl\").origin;\n}\n\n/**\n * The default platform port of `given`, read once (`credentialsOf`), over the\n * global fetch: each request to their platform API's own origin sent as\n * `bearerFetch` sends it, with their key's token. A request to any other\n * origin goes as it is: the token never leaves the platform API.\n */\nexport function authorizedFetch(given: Credentials): Fetch {\n  const credentials = credentialsOf(given);\n  const authorized = bearerFetch(credentials);\n  return async (request) => (isPlatformRequest(request, credentials) ? authorized(request) : fetch(request));\n}\n","/**\n * The platform API read as its URL: `api.scope(id).get()` is `GET /scope/<id>`.\n * A property adds a path segment as the API spells it, a call adds an id\n * URL-encoded, and six verbs send; nothing is sent without one. Read as text\n * (`String(resource)`, a template literal), a resource is its path. No\n * endpoint is fixed here: a path the API does not have is its refusal, naming\n * the path.\n */\n\nimport { settingsOf } from \"../settings\";\nimport { authorizedFetch, credentialsOf, type Credentials } from \"./auth\";\nimport { send, type Endpoint, type Fetch, type Query } from \"./transport\";\n\n/** What sends a request to a resource: JSON in, JSON out, the result typed by the caller. */\nexport interface Verbs {\n  /** `GET` the resource, with `query`. */\n  get<Result = unknown>(query?: Query): Promise<Result>;\n  /** Every item of the resource's listing (`{ paging, results }`), page after page, with `query`. */\n  list<Item = unknown>(query?: Query): AsyncIterable<Item>;\n  /** `POST` `body` to the resource. */\n  post<Result = unknown>(body?: unknown): Promise<Result>;\n  /** `PUT` `body` to the resource. */\n  put<Result = unknown>(body?: unknown): Promise<Result>;\n  /** `PATCH` the resource with `body`. */\n  patch<Result = unknown>(body?: unknown): Promise<Result>;\n  /** `DELETE` the resource. */\n  delete<Result = unknown>(): Promise<Result>;\n}\n\n/** A path on the platform API: a property adds a segment, a call adds an id, a verb sends; read as text, it is its path. */\nexport type Resource = Verbs & ((id: string | number) => Resource) & { readonly [segment: string]: Resource } & { [Symbol.toPrimitive](): string };\n\n/** The platform API: each property its first path segment, and `fetch` the port every call goes through. */\nexport type Api = { readonly [segment: string]: Resource } & { fetch: Fetch };\n\n/** What `createApi` builds the API over. */\nexport interface ApiOptions {\n  /** The platform port every call goes through; the port `credentials` authorize (`authorizedFetch`) unless given. */\n  fetch?: Fetch;\n  /** The platform's credentials, each its setting's default unless given: the API's URL (`apiUrl`), and the key its default port exchanges for a token (`apiKey`). */\n  credentials?: Partial<Credentials>;\n  /** What cancels every call. */\n  signal?: AbortSignal;\n}\n\n/** The API's largest page: a listing asks for this many at a time. */\nconst PAGE_SIZE = 200;\n\n/** A page of a listing, as the platform answers it. */\ninterface Page {\n  paging?: { total?: unknown };\n  results?: unknown;\n}\n\n/** Whether `page`, of `count` results, ends its listing once `offset` items came: it came short, or they reach `paging.total`. */\nfunction endsListing(page: Page | undefined, count: number, offset: number): boolean {\n  const total = page?.paging?.total;\n  return count < PAGE_SIZE || (typeof total === \"number\" && offset >= total);\n}\n\n/**\n * Every item of the listing at `path`: each page asked with `limit` the API's\n * largest and `offset` past what came before, until a page ends the listing.\n */\nasync function* pages(endpoint: Endpoint, path: string, query: Query = {}): AsyncGenerator<unknown> {\n  let offset = 0;\n  let ended = false;\n  while (!ended) {\n    const page = await send<Page | undefined>(endpoint, { method: \"GET\", path, query: { ...query, limit: PAGE_SIZE, offset } });\n    const results = Array.isArray(page?.results) ? page.results : [];\n    yield* results;\n    offset += results.length;\n    ended = endsListing(page, results.length, offset);\n  }\n}\n\n/** A verb at a resource's path: the function that sends its request. */\ntype Sender = (endpoint: Endpoint, path: string) => unknown;\n\n/** A verb that sends a body. */\nfunction withBody(method: string): Sender {\n  return (endpoint, path) => (body?: unknown) => send(endpoint, { method, path, body });\n}\n\n/** What each of the six verbs sends to a resource. */\nconst VERBS: Record<keyof Verbs, Sender> = {\n  get: (endpoint, path) => (query?: Query) => send(endpoint, { method: \"GET\", path, query }),\n  list: (endpoint, path) => (query?: Query) => pages(endpoint, path, query),\n  post: withBody(\"POST\"),\n  put: withBody(\"PUT\"),\n  patch: withBody(\"PATCH\"),\n  delete: (endpoint, path) => () => send(endpoint, { method: \"DELETE\", path }),\n};\n\n/** Whether `name` reads as a path segment: a string, never `then`, so awaiting a resource sends nothing. */\nfunction isSegment(name: string | symbol): name is string {\n  return typeof name === \"string\" && name !== \"then\";\n}\n\n/** Whether `name` is one of the six verbs. */\nfunction isVerb(name: string): name is keyof Verbs {\n  return Object.hasOwn(VERBS, name);\n}\n\n/** The ids that name no resource: as a path segment, the URL drops `.`, `..` climbs to the parent, and `\"\"` is no segment at all. */\nconst NO_RESOURCE = new Set([\"\", \".\", \"..\"]);\n\n/** The path of the resource `id` names under `path`; an id that names none is refused, naming the path so far. */\nfunction idPath(path: string, id: string | number): string {\n  const segment = String(id);\n  if (NO_RESOURCE.has(segment)) {\n    throw new Error(`the id ${JSON.stringify(segment)} after ${path} names no resource: an id is never \"\", \".\" or \"..\"`);\n  }\n  return `${path}/${encodeURIComponent(segment)}`;\n}\n\n/** The resource at `path`: a call adds an id, a verb sends, any other name adds a segment; read as text, it is `path`. */\nfunction resourceAt(endpoint: Endpoint, path: string): Resource {\n  const withId = (id: string | number): Resource => resourceAt(endpoint, idPath(path, id));\n  const member = (target: typeof withId, name: string | symbol): unknown => {\n    if (name === Symbol.toPrimitive) {\n      return () => path;\n    }\n    if (!isSegment(name)) {\n      return undefined;\n    }\n    return isVerb(name) ? VERBS[name](endpoint, path) : resourceAt(endpoint, `${path}/${name}`);\n  };\n  return new Proxy(withId, { get: member }) as unknown as Resource;\n}\n\n/**\n * The platform API at the `apiUrl` its credentials give, over `fetch` (the\n * port they authorize unless given), each call cancelled by `signal`. Every\n * property but `fetch`, the port itself, is the first segment of a path.\n */\nexport function createApi(options: ApiOptions = {}): Api {\n  const credentials = credentialsOf(settingsOf(options.credentials));\n  const endpoint: Endpoint = { fetch: options.fetch ?? authorizedFetch(credentials), baseUrl: credentials.apiUrl, setting: \"apiUrl\", signal: options.signal };\n  const member = (target: object, name: string | symbol): unknown => {\n    if (name === \"fetch\") {\n      return endpoint.fetch;\n    }\n    return isSegment(name) ? resourceAt(endpoint, `/${name}`) : undefined;\n  };\n  return new Proxy({}, { get: member }) as Api;\n}\n","/**\n * The narrative: what a handler says about its work on the trace, in the words\n * the console leads with. A step's narrative reaches the handler as the\n * argument of its `context.trace.step` work; the run's own is `context.trace`.\n *\n * Everything here is best effort: with no tracing it is silent, and nothing a\n * narrative is told can fail a run. The console names a node from\n * `explain.title` first (the plan's title stands in when a handler leaves it\n * out), leads with `what`, and keeps `why`, `impact` and `next` under it: say\n * what happened with the facts in it, and why.\n */\n\nexport interface Explanation {\n  /** The node's display name: the plan's title for this step (or run) unless given. */\n  title?: string;\n  /** What happened, in one sentence with the facts in it. */\n  what?: string;\n  /** Why it was done, or why it went the way it did. */\n  why?: string;\n  /** What it means for the reader. */\n  impact?: string;\n  /** What to do now, when there is something to do. */\n  next?: string;\n  severity?: \"ok\" | \"warn\" | \"error\";\n}\n\n/** Somewhere to go from the node: the job run, the bundle folder, the commit. */\nexport interface ExternalLink {\n  rel: string;\n  uri: string;\n  label?: string;\n}\n\nexport interface Narrative {\n  /** `tracing.explain`: the plain words the console leads with. A later call replaces an earlier one. */\n  explain(body: Explanation): void;\n  /** `tracing.external_links`: a link out of the node. */\n  link(link: ExternalLink): void;\n  /** `tracing.output`: a fact worth keeping as data (ids, hosts, versions). */\n  output(name: string, value: unknown): void;\n}\n\n/** Says nothing: the narrative with no tracing behind it. */\nexport const silentNarrative: Narrative = {\n  explain() {},\n  link() {},\n  output() {},\n};\n","/**\n * A plugin's package: what every plugin belongs to, declared by the project\n * (its name, version and description, which the project loads from its own\n * package.json). The library reads no package.json.\n */\n\nimport { textOf } from \"./text\";\n\n/** What every plugin belongs to: the project, as publish registers it. */\nexport interface Package {\n  readonly name: string;\n  readonly slug: string;\n  readonly version: string;\n  readonly description?: string;\n}\n\n/** A package as a define takes it: the slug is the name, slugified, unless given. */\nexport interface PackageDeclaration {\n  name: string;\n  version: string;\n  description?: string;\n  slug?: string;\n}\n\n/** Lowercase letters and digits, each run of anything else one dash, none at either end. */\nexport function slugify(text: string): string {\n  return text\n    .toLowerCase()\n    .replace(/[^a-z0-9]+/g, \"-\")\n    .replace(/^-+|-+$/g, \"\");\n}\n\n/** Whether `value` is a slug: text that `slugify` leaves as it is. */\nexport function isSlug(value: unknown): value is string {\n  return typeof value === \"string\" && textOf(value) !== undefined && slugify(value) === value;\n}\n\n/** The slug a declaration gives, which must already be one, or its name's. */\nfunction slugOf(definer: string, declaration: PackageDeclaration): string {\n  if (declaration.slug !== undefined) {\n    if (!isSlug(declaration.slug)) {\n      throw new Error(`${definer}: package.slug \"${declaration.slug}\" is not a slug`);\n    }\n    return declaration.slug;\n  }\n  const slug = slugify(declaration.name);\n  if (slug === \"\") {\n    throw new Error(`${definer}: package.name \"${declaration.name}\" makes no slug: give package.slug`);\n  }\n  return slug;\n}\n\n/** The package a define (`definer`) declares, its slug resolved; what is missing or malformed is refused, naming the field. */\nexport function packageOf(definer: string, declaration: PackageDeclaration): Package {\n  if (!declaration || typeof declaration !== \"object\") {\n    throw new Error(`${definer}: package is required: { name, version, description? }`);\n  }\n  if (textOf(declaration.name) === undefined) {\n    throw new Error(`${definer}: package.name is required`);\n  }\n  if (textOf(declaration.version) === undefined) {\n    throw new Error(`${definer}: package.version is required`);\n  }\n  const declared: Package = { name: declaration.name, slug: slugOf(definer, declaration), version: declaration.version };\n  return declaration.description === undefined ? declared : { ...declared, description: declaration.description };\n}\n","/**\n * Work bounded in time: what it gives, unless its time passes first. The one\n * timeout race of the library: a step's attempt, the testing client's wait\n * for a handshake, the end budget of a run's tracing and a stopping gRPC\n * server's close all run it. A time of Infinity bounds nothing; one past what\n * a timer holds (2^31 - 1 ms, about 24.8 days) bounds the work at that, as a\n * timer would otherwise fire at once.\n */\n\n/** The longest a timer waits: a longer delay overflows it, and it fires at once. */\nconst LONGEST_TIMER_MS = 2 ** 31 - 1;\n\n/** What `work` gives, unless `timeoutMs` passes first: then it rejects with `refusal()`. The timer is cleared either way; Infinity sets none. */\nexport async function within<Value>(work: Promise<Value>, timeoutMs: number, refusal: () => Error): Promise<Value> {\n  if (timeoutMs === Infinity) {\n    return work;\n  }\n  let timer: ReturnType<typeof setTimeout> | undefined;\n  const expired = new Promise<never>((resolve, reject) => {\n    timer = setTimeout(() => reject(refusal()), Math.min(timeoutMs, LONGEST_TIMER_MS));\n  });\n  try {\n    return await Promise.race([work, expired]);\n  } finally {\n    clearTimeout(timer);\n  }\n}\n","/**\n * The plan of a run: the steps it is expected to run, in the tracing SDK's own\n * words (`@nullplatform/tracing`: a plan is `{ groups?, steps }`, a step\n * `{ key, title?, description?, after?, sla?, optional?, group? }`, a group\n * `{ key, title?, group? }`). On the trace it is the plan of the job every run\n * is an instance of, so the console knows the stations before the first one\n * reports. It is checked where it is declared, so a typo is a definition error\n * and never a plan slot that stays missing forever.\n */\n\nimport { keyViolation, type PlanFacetInput, type PlanGroupInput, type PlanStepInput } from \"@nullplatform/tracing\";\n\nexport type Plan = PlanFacetInput;\nexport type PlanStep = PlanStepInput;\nexport type PlanGroup = PlanGroupInput;\n\n/** Why a `context.trace.step` name cannot be a step key, in the tracing SDK's words; undefined when it can. */\nexport function stepKeyProblem(name: string): string | undefined {\n  return keyViolation(name) ?? undefined;\n}\n\n/**\n * Why a plan cannot be declared, as the tracing SDK would refuse it, every\n * problem at once; empty when it can. A plan with no step is refused too,\n * though the SDK takes one: it says nothing.\n */\nexport function planProblems(plan: Plan): string[] {\n  if (!Array.isArray(plan.steps) || plan.steps.length === 0) {\n    return [\"a plan declares at least one step\"];\n  }\n  const groups = plan.groups ?? [];\n  return [\n    ...keyProblems(\"step\", plan.steps),\n    ...afterProblems(plan.steps),\n    ...keyProblems(\"group\", groups),\n    ...nestingProblems(groups),\n    ...membershipProblems(plan.steps, groups),\n  ];\n}\n\n/** Each key outside the SDK's charset, and each key declared twice. */\nfunction keyProblems(kind: \"step\" | \"group\", declarations: { key: string }[]): string[] {\n  const problems: string[] = [];\n  const declared = new Set<string>();\n  for (const { key } of declarations) {\n    const violation = keyViolation(key);\n    if (violation !== null) {\n      problems.push(`${kind} key \"${key}\" ${violation}`);\n    }\n    if (declared.has(key)) {\n      problems.push(`${kind} \"${key}\" is declared twice`);\n    }\n    declared.add(key);\n  }\n  return problems;\n}\n\n/** Each step a step comes after that the plan does not declare. */\nfunction afterProblems(steps: PlanStep[]): string[] {\n  const declared = new Set(steps.map((step) => step.key));\n  return steps.flatMap((step) =>\n    listOf(step.after)\n      .filter((previous) => !declared.has(previous))\n      .map((previous) => `step \"${step.key}\" comes after an undeclared step \"${previous}\"`),\n  );\n}\n\n/** Each group nested under a group the plan does not declare. */\nfunction nestingProblems(groups: PlanGroup[]): string[] {\n  const declared = new Set(groups.map((group) => group.key));\n  return groups\n    .filter((group) => group.group !== undefined && !declared.has(group.group))\n    .map((group) => `group \"${group.key}\" nests under an undeclared group \"${group.group}\"`);\n}\n\n/**\n * Where a plan declares groups, a step names one of them by its key, and the\n * group's nesting has no cycle; where it declares none, a step names a path\n * of keys, each in the SDK's charset.\n */\nfunction membershipProblems(steps: PlanStep[], groups: PlanGroup[]): string[] {\n  if (groups.length === 0) {\n    return steps.flatMap(groupPathProblems);\n  }\n  const parents = new Map(groups.map((group) => [group.key, group.group]));\n  return [...steps.flatMap((step) => declaredGroupProblems(step, parents)), ...cycleProblems(steps, parents)];\n}\n\n/** Why a step cannot be in the group it names, among the declared ones (each group's key to its parent's). */\nfunction declaredGroupProblems(step: PlanStep, parents: Map<string, string | undefined>): string[] {\n  if (step.group === undefined) {\n    return [];\n  }\n  if (typeof step.group !== \"string\") {\n    return [`step \"${step.key}\" names its group by a path: where a plan declares groups, a step names its group by its key`];\n  }\n  if (!parents.has(step.group)) {\n    return [`step \"${step.key}\" is in an undeclared group \"${step.group}\"`];\n  }\n  return [];\n}\n\n/** Each declared group a step is in whose nesting comes back to a group it has passed, once per group. */\nfunction cycleProblems(steps: PlanStep[], parents: Map<string, string | undefined>): string[] {\n  const joined = new Set(steps.map((step) => step.group).filter((group): group is string => typeof group === \"string\" && parents.has(group)));\n  return [...joined].flatMap((group) => cycleProblem(group, parents));\n}\n\n/** Where `group`'s nesting comes back to a group it has passed, when it does. */\nfunction cycleProblem(group: string, parents: Map<string, string | undefined>): string[] {\n  const passed = new Set<string>();\n  for (let current: string | undefined = group; current !== undefined; current = parents.get(current)) {\n    if (passed.has(current)) {\n      return [`group \"${group}\" nests in a cycle at \"${current}\"`];\n    }\n    passed.add(current);\n  }\n  return [];\n}\n\n/** Why a step's group path, where the plan declares no group, cannot be one. */\nfunction groupPathProblems(step: PlanStep): string[] {\n  if (step.group === undefined) {\n    return [];\n  }\n  const path = listOf(step.group);\n  if (path.length === 0) {\n    return [`step \"${step.key}\" has an empty group path`];\n  }\n  return path.flatMap((key) => {\n    const violation = keyViolation(key);\n    return violation === null ? [] : [`step \"${step.key}\" group key \"${key}\" ${violation}`];\n  });\n}\n\n/** One value or a list of them, as a list; none when absent. */\nfunction listOf(value: string | string[] | undefined): string[] {\n  if (value === undefined) {\n    return [];\n  }\n  return Array.isArray(value) ? value : [value];\n}\n","/**\n * A step: the unit of work inside a handler (`context.trace.step`), the boundary of its\n * retries and its timeout. Its name is its key on the trace.\n *\n * It logs nothing of its own but a retried attempt, a warning: how it ended\n * and how long it took are told to its observer, once per step, and to the\n * trace by the span that traces it. An observer never fails the step: what it\n * throws or rejects with is ignored. When it fails, the error names the step,\n * so the operator reads `step \"attach-listener-rule\" failed`, not a stack\n * frame; an ActionError passes through as it was thrown, since its code is\n * what the platform, the trace and the tests read.\n */\n\nimport { ActionError, messageOf } from \"../errors\";\nimport { written, type Logger } from \"../logger\";\nimport { within } from \"../within\";\nimport { silentNarrative, type Narrative } from \"./narrative\";\nimport { stepKeyProblem } from \"./plan\";\n\nexport interface StepOptions {\n  /** Additional attempts after the first failure; none unless given (fail fast). */\n  retries?: number;\n  /** Each attempt's time budget in milliseconds, none when absent, 0 or Infinity (`within`); an attempt over it fails. */\n  timeoutMs?: number;\n}\n\n/** The work of a step. Its argument narrates the step on the trace (what happened, why, links, outputs). */\nexport type StepWork<Result> = (step: Narrative) => Promise<Result> | Result;\n\nexport interface Step {\n  <Result>(name: string, run: StepWork<Result>): Promise<Result>;\n  <Result>(name: string, options: StepOptions, run: StepWork<Result>): Promise<Result>;\n}\n\n/** Told how a step ended and how long it took, from its first attempt to its last: once per step that runs. */\nexport type StepObserver = (name: string, outcome: { status: \"completed\" | \"failed\"; durationMs: number }) => void;\n\n/** A step that warns on `log` of each retried attempt and tells `observe` how each step ended. */\nexport function createStep(log: Logger, observe?: StepObserver): Step {\n  const step = async <Result>(name: string, optionsOrWork: StepOptions | StepWork<Result>, work?: StepWork<Result>): Promise<Result> => {\n    // A name the trace could never match as a key is a handler bug, said before the work runs.\n    const problem = stepKeyProblem(name);\n    if (problem !== undefined) {\n      throw new Error(`context.trace.step(\"${name}\"): the name ${problem}`);\n    }\n    const { options, run } = callOf(optionsOrWork, work);\n    return observed(name, observe, () => attempts(name, options, run, log));\n  };\n  return step as Step;\n}\n\n/** The options and the work of a call, in either of a step's two forms: what a step that wraps another (a traced one) parses too. */\nexport function callOf<Result>(optionsOrWork: StepOptions | StepWork<Result>, work?: StepWork<Result>): { options: StepOptions; run: StepWork<Result> } {\n  if (typeof optionsOrWork === \"function\") {\n    return { options: {}, run: optionsOrWork };\n  }\n  return { options: optionsOrWork, run: work as StepWork<Result> };\n}\n\n/** Runs `work`, telling `observe` how it ended and how long it took; what it throws passes through. */\nasync function observed<Result>(name: string, observe: StepObserver | undefined, work: () => Promise<Result>): Promise<Result> {\n  const started = performance.now();\n  let result: Result;\n  try {\n    result = await work();\n  } catch (error) {\n    tell(observe, name, { status: \"failed\", durationMs: performance.now() - started });\n    throw error;\n  }\n  tell(observe, name, { status: \"completed\", durationMs: performance.now() - started });\n  return result;\n}\n\n/** Tells `observe`, when there is one, how a step ended: what it throws, or its promise rejects with (an async observer is a StepObserver too), is ignored (`written`). */\nfunction tell(observe: StepObserver | undefined, name: string, outcome: Parameters<StepObserver>[1]): void {\n  if (observe !== undefined) {\n    written(() => observe(name, outcome));\n  }\n}\n\n/** The attempts the options allow, until one answers: a warning for each failed one before the last, whose failure is the step's. */\nasync function attempts<Result>(name: string, options: StepOptions, run: StepWork<Result>, log: Logger): Promise<Result> {\n  const total = 1 + Math.max(0, options.retries ?? 0);\n  let failure: unknown;\n  for (let attempt = 1; attempt <= total; attempt++) {\n    try {\n      return await attempted(run, options.timeoutMs);\n    } catch (error) {\n      failure = error;\n      if (attempt < total) {\n        log.warn(`step \"${name}\": attempt ${attempt}/${total} failed: ${messageOf(error)}; retrying`);\n      }\n    }\n  }\n  throw stepFailure(name, failure);\n}\n\n/** One attempt of `run`, failed when it takes longer than `timeoutMs`. */\nasync function attempted<Result>(run: StepWork<Result>, timeoutMs: number | undefined): Promise<Result> {\n  if (!timeoutMs) {\n    return run(silentNarrative);\n  }\n  return within(Promise.resolve().then(() => run(silentNarrative)), timeoutMs, () => new Error(`timed out after ${timeoutMs} ms`));\n}\n\n/** What a failed step throws: an ActionError as it is, anything else named by the step, with what was thrown as its cause. */\nfunction stepFailure(name: string, error: unknown): unknown {\n  if (error instanceof ActionError) {\n    return error;\n  }\n  return new Error(`step \"${name}\" failed: ${messageOf(error)}`, { cause: error });\n}\n","/**\n * The trace a handler is handed (`context.trace`): the run's step and its\n * narrative together, in the tracing SDK's own vocabulary, where the step is\n * the run's (`RunHandle.step`). With tracing off its step still runs its work\n * with its retries and its timeout, and only what it reports is silent.\n */\n\nimport type { Narrative } from \"./narrative\";\nimport type { Step } from \"./step\";\n\n/** The run's step and its narrative. */\nexport interface Trace extends Narrative {\n  /** A unit of work, with retries and a timeout: a step of the run, keyed by its name. */\n  step: Step;\n}\n\n/** The trace of `step` and `narrative`: each call of the narrative told to it. */\nexport function traceOf(step: Step, narrative: Narrative): Trace {\n  return {\n    step,\n    explain: (body) => narrative.explain(body),\n    link: (link) => narrative.link(link),\n    output: (name, value) => narrative.output(name, value),\n  };\n}\n","/**\n * What every handler gets beside its input, whatever the plugin's kind: the\n * SDK's tools, never a field of the payload. A handler is called\n * `(input, context)`: its input is the payload's data (the payload itself,\n * or what a kind's middleware builds of it), its context the logger, the\n * trace (the run's step and its narrative), the cancel signal, the platform\n * API, the run's platform credentials and the project's own ports. Every\n * middleware, a kind's or an author's, is handed the same context: a kind's\n * builds its input from the input it is handed (the payload, first), and the\n * core opens the run's trace before any of them. The core builds it from the\n * ports a transport answers with. The rest of the run's settings (where it\n * listens, its TLS material, the agent's document) are the transport's,\n * never a handler's.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { createApi, credentialsOf, type Api, type Credentials, type Fetch } from \"../api\";\nimport { messageOf } from \"../errors\";\nimport { written, type Logger } from \"../logger\";\nimport type { Settings } from \"../settings\";\nimport { silentNarrative } from \"../tracing/narrative\";\nimport type { Tracer } from \"../tracing/port\";\nimport { createStep, type StepObserver } from \"../tracing/step\";\nimport { traceOf, type Trace } from \"../tracing/trace\";\n\n/** How a route prints its answer: the envelope (`{\"success\":…}`) unless it says `raw`, the handler's return as it is. */\nexport type Output = \"envelope\" | \"raw\";\n\n/** What every handler gets beside its input: the SDK's tools. */\nexport interface Context<Ports extends object = {}> {\n  /** The run's logger, and the agent's stream when the transport has one. */\n  log: Logger;\n  /** The run's step, a unit of work with retries and a timeout, and what the handler says on the trace; the step still runs and the rest is silent when tracing is off. */\n  trace: Trace;\n  /** Aborted when the worker stops or the agent cancels. */\n  signal: AbortSignal;\n  /** The platform API, at the run's `apiUrl`. */\n  api: Api;\n  /** The run's platform credentials (`apiUrl`, `apiKey`), frozen: what the platform API and a kind's own client reach the platform with. */\n  credentials: Credentials;\n  /** The project's own ports. */\n  ports: Ports;\n}\n\n/** A piece of the agent's stream: text on its stdout or its stderr. */\nexport interface StreamChunk {\n  stdout?: string;\n  stderr?: string;\n}\n\n/** What a transport answers a payload with: the ports the handler's context is built from. */\nexport interface AnswerPorts<Ports extends object = {}> {\n  /** The run's settings, resolved once and frozen: the transport's; a handler gets only their platform credentials (`context.credentials`). */\n  settings: Settings;\n  /** The platform port every call of `context.api` goes through. */\n  fetch: Fetch;\n  /** The run's logger: every level the handler logs. */\n  log: Logger;\n  /** Aborted when the worker stops or the agent cancels. */\n  signal: AbortSignal;\n  /** The project's own ports: `context.ports`. */\n  ports: Ports;\n  /** The tracing port: where the core opens the run a route describes. */\n  tracer: Tracer;\n  /** The agent's stream, when the transport has one (gRPC): the log, line by line. */\n  stream?: (chunk: StreamChunk) => void;\n  /** Told how each step ended and how long it took. */\n  observeStep?: StepObserver;\n}\n\n/** The levels a log streams: debug is never streamed, it stays on the run's logger. */\ntype StreamedLevel = \"info\" | \"warn\" | \"error\";\n\n/** Where each streamed level goes, by how the answer prints: an envelope's info is stdout, everything else stderr, since a raw answer's stdout is its answer. */\nconst STREAMS: Record<Output, Record<StreamedLevel, keyof StreamChunk>> = {\n  envelope: { info: \"stdout\", warn: \"stderr\", error: \"stderr\" },\n  raw: { info: \"stderr\", warn: \"stderr\", error: \"stderr\" },\n};\n\n/** Whether `value` is how a route prints its answer: envelope or raw. */\nexport function isOutput(value: unknown): value is Output {\n  return typeof value === \"string\" && Object.hasOwn(STREAMS, value);\n}\n\n/** `message` as a streamed line: its text, newline-terminated, a text that already ends in one kept as it is. */\nexport function lineOf(message: unknown): string {\n  const text = typeof message === \"string\" ? message : messageOf(message);\n  return text.endsWith(\"\\n\") ? text : `${text}\\n`;\n}\n\n/**\n * A log that writes every level to `log` and streams each info, warning and\n * error line, newline-terminated, through `stream` where `output` says;\n * debug stays on `log`. A logger or a stream that throws is ignored.\n */\nexport function streamingLog(log: Logger, output: Output, stream?: AnswerPorts[\"stream\"]): Logger {\n  const streamed = (level: StreamedLevel) => (message: string): void => {\n    const chunk: StreamChunk = { [STREAMS[output][level]]: lineOf(message) };\n    written(() => log[level](message));\n    written(() => stream?.(chunk));\n  };\n  return { debug: (message) => written(() => log.debug(message)), info: streamed(\"info\"), warn: streamed(\"warn\"), error: streamed(\"error\") };\n}\n\n/**\n * The log of the context the code running now was handed, for the run's step.\n * A run's step is built once, so a middleware that wraps it (a kind's tracing)\n * wraps the one the handler calls; it logs each line to the log of the context\n * its caller was handed (`compose` hands each middleware and the handler the\n * context it is passed), so a log a middleware passes on (a kind's, posting\n * each line to the platform) hears a retried attempt's warning too. It follows\n * the code that runs, not the last context passed: a middleware's own step\n * after its `next` has returned, and each of concurrent `next` calls, log to\n * their own context's log.\n */\nconst handedLog = new AsyncLocalStorage<Logger>();\n\n/** Runs `work` as code handed `context`: a run's step it calls logs to `context.log`, whatever runs beside it. */\nexport function handedTo<Result>(context: Context, work: () => Result): Result {\n  return handedLog.run(context.log, work);\n}\n\n/** A log that writes each line to the log of the context its caller was handed, `fallback` when called outside any; a log that throws loses the line. */\nfunction forwardingLog(fallback: Logger): Logger {\n  const forwarded = (level: keyof Logger) => (message: string): void => {\n    written(() => (handedLog.getStore() ?? fallback)[level](message));\n  };\n  return { debug: forwarded(\"debug\"), info: forwarded(\"info\"), warn: forwarded(\"warn\"), error: forwarded(\"error\") };\n}\n\n/**\n * The context a route's middleware and handler get, printed `output`: its log\n * the streaming log over the ports' logger; its trace a step telling\n * `observeStep` and warning on the log of the context its caller was handed\n * (`handedTo`; the streaming log outside any), with a silent narrative (the\n * run a route describes replaces both, `runOf`); the run's platform\n * credentials; and the platform API over the ports' fetch at their `apiUrl`.\n */\nexport function contextOf<Ports extends object>(ports: AnswerPorts<Ports>, output: Output): Context<Ports> {\n  const log = streamingLog(ports.log, output, ports.stream);\n  const credentials = credentialsOf(ports.settings);\n  return {\n    log,\n    trace: traceOf(createStep(forwardingLog(log), ports.observeStep), silentNarrative),\n    signal: ports.signal,\n    api: createApi({ fetch: ports.fetch, credentials, signal: ports.signal }),\n    credentials,\n    ports: ports.ports,\n  };\n}\n\n/** The handler's context of `context`: its tools only, whatever else a middleware passed on beside them. */\nexport function handlerContextOf<Ports extends object>(context: Context<Ports>): Context<Ports> {\n  const { log, trace, signal, api, credentials, ports } = context;\n  return { log, trace, signal, api, credentials, ports };\n}\n","/**\n * Describe (`plugin.manifest()`): everything publish registers, said by the\n * plugin itself, as contract/manifest.schema.json has it. The package's name,\n * slug, version and description; its components in declaration order, each\n * parent before its children, each body exactly as its author wrote it; then\n * the package's agent channel (contract/platform.json `channel`), letting\n * through what the routes' channels name; then the runs tooling offers, one\n * per route with a sample; then any tooling block the definition adds. It is\n * a copy each time, as JSON carries it: what a caller changes in one reaches\n * no later describe, no body and no route's sample.\n *\n * The core fills only `${slug}`. Every other placeholder (`${nrn}`,\n * `${version}`, `${api_key}`, `${parent}`, `${NOTIFICATION_CONTEXT}`, a\n * `{ ref }`) reaches describe as written, for the CLI at publish and the agent\n * at delivery.\n */\n\nimport platform from \"../../../../contract/platform.json\" with { type: \"json\" };\nimport { collect, ref, type Component } from \"../component\";\nimport type { Package } from \"../package\";\nimport { deliveryOf } from \"../payload\";\nimport { asJson } from \"../text\";\nimport { equal } from \"../where\";\nimport type { Route } from \"./route\";\n\n/** How the package's agent channel reaches the worker; each defaults from the package's slug and the routes. */\nexport interface AgentOptions {\n  /** The tags an agent carries to answer the package; `{ package: <slug> }` unless given. */\n  selector?: Record<string, string>;\n  /** What the agent execs in the worker image; contract/platform.json's `entrypoint` for the slug unless given. */\n  entrypoint?: string;\n  /** The notification sources the channel subscribes to; the routes' channel sources unless given. */\n  sources?: string[];\n  /** Pins the channel's command to the version published (`${version}`). */\n  pinVersion?: boolean;\n  /** Whether publish manages the channel; true unless false. */\n  manageChannel?: boolean;\n}\n\n/** One entry of what publish registers: the API's body as written, and where it lives when the convention does not hold. */\nexport interface ManifestComponent {\n  /** Unique in the package; a ref names it as `<resource_type>/<name>`. */\n  name: string;\n  /** The API's entity name. */\n  resource_type: string;\n  /** The body the kind's API takes, as its author wrote it. */\n  resource?: Record<string, unknown>;\n  /** The component this one is created under, as `<resource_type>/<name>`. */\n  parent?: string;\n  /** Where it is created, when not `/<resource_type>`. */\n  path?: string;\n  /** Where publish lists it to find an existing one. */\n  list?: string;\n  /** The body's field that identifies an existing one, when not `name`. */\n  identity?: string;\n  /** `platform`: the platform creates it; publish looks it up and pins it, never writes it. */\n  owner?: \"platform\";\n}\n\n/** What tooling offers to run: a route's name, and the document the agent would deliver for it. */\nexport interface ManifestRun {\n  name: string;\n  document: unknown;\n}\n\n/** What describe prints. */\nexport interface Manifest {\n  name: string;\n  slug: string;\n  version: string;\n  description?: string;\n  components: ManifestComponent[];\n  runs: ManifestRun[];\n  /** A tooling block a definition adds (a collector's `collector`); publish ignores it. */\n  [tooling: string]: unknown;\n}\n\n/** What describe is built from: the plugin's package, its agent options, its components, its routes and its tooling. */\nexport interface ManifestParts {\n  package: Package;\n  agent?: AgentOptions;\n  components: Component[];\n  routes: readonly Route[];\n  tooling?: Record<string, unknown>;\n}\n\n/** The placeholder the core fills with the package's slug. */\nconst SLUG = \"${slug}\";\n\n/** The placeholders publish fills: the target NRN, the version published, the key the channel authenticates with. */\nconst NRN = \"${nrn}\";\nconst VERSION = \"${version}\";\nconst API_KEY = \"${api_key}\";\n\n/** The package's agent channel's name in the package. */\nconst CHANNEL = \"channel\";\n\n/** What the routes' channels let through: each source once and each filter once, in route order. */\ninterface ChannelRoutes {\n  sources: string[];\n  filters: Record<string, unknown>[];\n}\n\n/** `fields` without the ones that are undefined. */\nfunction definedOf<Fields extends Record<string, unknown>>(fields: Fields): Fields {\n  return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined)) as Fields;\n}\n\n/** A component as describe prints it: its name, its kind, its body as written, and what the convention cannot tell. */\nfunction componentOf(declared: Component): ManifestComponent {\n  return definedOf({\n    name: declared.name,\n    resource_type: declared.kind,\n    resource: declared.body,\n    parent: declared.parent === undefined ? undefined : ref(declared.parent).ref,\n    path: declared.path,\n    list: declared.list,\n    identity: declared.identity,\n    owner: declared.owner,\n  });\n}\n\n/** `text` with the package's slug in place of `${slug}`. */\nfunction withSlug(text: string, slug: string): string {\n  return text.replaceAll(SLUG, slug);\n}\n\n/** `items` each once, the first of each kept in order, by `same`. */\nfunction distinct<Item>(items: Item[], same: (first: Item, second: Item) => boolean): Item[] {\n  return items.filter((item, index) => items.findIndex((other) => same(other, item)) === index);\n}\n\n/** What the routes' channels let through, each source and each filter once, in route order. */\nfunction channelRoutesOf(routes: readonly Route[]): ChannelRoutes {\n  const channels = routes.flatMap((route) => (route.channel === undefined ? [] : [route.channel]));\n  return {\n    sources: distinct(channels.map((channel) => channel.source), Object.is),\n    filters: distinct(channels.map((channel) => channel.filter), equal),\n  };\n}\n\n/** What the agent execs for the package, with the environment it hands the worker; pinned to the version published when `agent` says. */\nfunction commandDataOf(slug: string, agent: AgentOptions): Record<string, unknown> {\n  const environment = Object.fromEntries(Object.entries(platform.channel.environment).map(([name, value]) => [name, withSlug(value, slug)]));\n  return definedOf({\n    package: slug,\n    cmdline: agent.entrypoint || withSlug(platform.channel.entrypoint, slug),\n    environment,\n    version: agent.pinVersion ? VERSION : undefined,\n  });\n}\n\n/** The tags an agent carries to answer the package: a copy of the agent's own, `{ package: <slug> }` when it gives none. */\nfunction selectorOf(slug: string, agent: AgentOptions): Record<string, string> {\n  return agent.selector && Object.keys(agent.selector).length > 0 ? { ...agent.selector } : { package: slug };\n}\n\n/** The package's agent channel: from the agent's sources or the routes', letting through what the routes' filters name. */\nfunction channelOf(slug: string, agent: AgentOptions, routes: ChannelRoutes): ManifestComponent {\n  const { resource_type: resourceType, path, list, identity, type, description, command } = platform.channel;\n  return {\n    name: CHANNEL,\n    resource_type: resourceType,\n    resource: {\n      nrn: NRN,\n      source: agent.sources?.length ? [...agent.sources] : routes.sources,\n      type,\n      description: withSlug(description, slug),\n      configuration: {\n        api_key: API_KEY,\n        selector: selectorOf(slug, agent),\n        command: { type: command, data: commandDataOf(slug, agent) },\n      },\n      filters: { $or: routes.filters },\n    },\n    path,\n    list,\n    identity,\n  };\n}\n\n/** The package's agent channel, when it has one: some route has a channel and the agent does not leave it out. */\nfunction channelsOf(slug: string, agent: AgentOptions, routes: readonly Route[]): ManifestComponent[] {\n  const channelRoutes = channelRoutesOf(routes);\n  if (agent.manageChannel === false || channelRoutes.filters.length === 0) {\n    return [];\n  }\n  return [channelOf(slug, agent, channelRoutes)];\n}\n\n/** The runs tooling offers: one per route with a sample, its document the sample as the agent delivers it (`deliveryOf`). */\nfunction runsOf(routes: readonly Route[]): ManifestRun[] {\n  return routes.flatMap((route) => (route.sample === undefined ? [] : [{ name: route.name, document: deliveryOf(route.sample) }]));\n}\n\n/** What describe prints for a plugin of these parts, a copy each time, as JSON carries it (`asJson`). */\nexport function manifestOf(parts: ManifestParts): Manifest {\n  const { name, slug, version, description } = parts.package;\n  const agent = parts.agent ?? {};\n  return asJson({\n    ...definedOf({ name, slug, version, description }),\n    components: [...collect(parts.components).map(componentOf), ...channelsOf(slug, agent, parts.routes)],\n    runs: runsOf(parts.routes),\n    ...parts.tooling,\n  }) as Manifest;\n}\n","/**\n * A route is one thing a plugin answers: it matches a payload, runs its\n * middleware around its handler, says how its answer prints, what the\n * package's agent channel lets through for it, and what tooling offers to run\n * it with. A plugin answers a payload with the first route whose match\n * accepts it; the core reads nothing a payload says, the match does.\n */\n\nimport type { Payload } from \"../payload\";\nimport type { RunDescription } from \"../tracing/port\";\nimport { handedTo, handlerContextOf, type Context, type Output } from \"./context\";\n\n/**\n * What a middleware calls to run the inner ones, the handler last, with the\n * input and the context it passes on; each call runs them again. One it\n * leaves out, or undefined, passes on as it was handed: `next()` passes both\n * on unchanged, `next(input)` replaces the input only.\n */\nexport type Next<Input = Payload> = (input?: Input, context?: Context) => Promise<unknown>;\n\n/**\n * Runs around the next one, `(input, context, next)` as a handler is\n * `(input, context)`, whoever wrote it: typed by the input it is handed, the\n * payload unless a kind's (a service's action's, a scope's), and by the input\n * it passes on, the same unless it builds another (a kind's own, which builds\n * its input from the payload it is handed). It may change the input and the\n * context it passes on, and sees what the inner ones returned or threw.\n */\nexport type Middleware<Input = Payload, Passed = Input> = (input: Input, context: Context, next: Next<Passed>) => Promise<unknown>;\n\n/** What answers a payload: its input the payload, or what a route's middleware passes on, and its context the run's tools. */\nexport type Handler = (input: Payload, context: Context) => unknown;\n\n/**\n * A route's last word before its handler: handed what its middleware passed\n * on and the payload as delivered, it returns what the handler gets, or throws\n * to fail the answer. A kind's own: the core calls it, and reads neither.\n */\nexport type Guard = (input: Payload, payload: Payload) => Payload;\n\n/** The chain a route runs for one payload: its middleware around its handler, handed the payload and the run's context. */\nexport type Chain = (input: Payload, context: Context) => Promise<unknown>;\n\n/** One thing the plugin answers. */\nexport interface Route {\n  /** Unique in the plugin: what a refusal lists and tooling offers. */\n  name: string;\n  /** Whether the route answers `payload`; routes are tried in order. */\n  match(payload: Payload): boolean;\n  /** Around the handler, outermost first, after the plugin's own. */\n  use?: readonly Middleware[];\n  /** What answers the payload: its return is the answer's data, what it throws the failure. */\n  handler: Handler;\n  /** What the run that answers `payload` is on the trace, a kind's own description of it: opened before the middleware, ended with the answer; none, no run. */\n  describe?(payload: Payload): RunDescription | undefined;\n  /** What the handler gets of what the middleware passed on, checked right before it (`Guard`); what the middleware passed on unless given. */\n  guard?: Guard;\n  /** How the answer prints for `payload`; envelope unless it says. */\n  output?(payload: Payload): Output;\n  /** What the package's agent channel lets through for it: a source and the filter on it. */\n  channel?: { source: string; filter: Record<string, unknown> };\n  /** What tooling offers to run it with, and tests start from. */\n  sample?: Payload;\n}\n\n/** What a `use` that is not middleware is refused with. */\nexport const NOT_MIDDLEWARE = \"use must be an array of middleware functions\";\n\n/** Whether `use` is middleware: an array of functions, each run around the next. */\nexport function isMiddleware(use: unknown): use is readonly Middleware[] {\n  return Array.isArray(use) && use.every((around) => typeof around === \"function\");\n}\n\n/** What is wrong with a `use` a definition gives: none when it gives none or middleware, else that it is not middleware. */\nexport function useProblemsOf(use: unknown): string[] {\n  return use === undefined || isMiddleware(use) ? [] : [NOT_MIDDLEWARE];\n}\n\n/** A part of a route that is a method, bound to the route when it is a function, so a route of a class answers as its instance; anything else as it is, for definePlugin to refuse. */\nfunction boundTo<Part>(route: Route, part: Part): Part {\n  return typeof part === \"function\" ? (part.bind(route) as Part) : part;\n}\n\n/**\n * A fresh route of `route`'s declared parts, whether they are its own or its\n * class's, with `use` as its middleware: its methods bound to `route` itself,\n * so a route of a class keeps its private state, and `route` never written\n * to, so a frozen one may be given.\n */\nexport function routeUsing(route: Route, use: readonly Middleware[] | undefined): Route {\n  const { name, channel, sample } = route;\n  return {\n    name,\n    match: boundTo(route, route.match),\n    handler: boundTo(route, route.handler),\n    ...(route.output !== undefined && { output: boundTo(route, route.output) }),\n    ...(route.describe !== undefined && { describe: boundTo(route, route.describe) }),\n    ...(route.guard !== undefined && { guard: boundTo(route, route.guard) }),\n    ...(use !== undefined && { use }),\n    ...(channel !== undefined && { channel }),\n    ...(sample !== undefined && { sample }),\n  };\n}\n\n/** The route that answers anything, its handler handed the payload as its input: it goes last. Tooling offers it with an empty payload. */\nexport function execute(handler: Handler): Route {\n  return { name: \"execute\", match: () => true, handler, sample: {} };\n}\n\n/**\n * The handler with the middleware around it, outermost first: each runs around\n * the next, the last around the handler, each as code handed the context it is\n * passed (`handedTo`), so a step it calls logs to that context's log. The\n * handler gets the tools only (`handlerContextOf`).\n */\nexport function compose(middleware: readonly Middleware[], handler: Handler): Chain {\n  const innermost: Chain = async (input, context) => handedTo(context, () => handler(input, handlerContextOf(context)));\n  return middleware.reduceRight<Chain>(\n    (inner, around) => async (input, context) =>\n      handedTo(context, () => around(input, context, (passedInput = input, passedContext = context) => inner(passedInput, passedContext))),\n    innermost,\n  );\n}\n","/**\n * The run a route's answer is traced as. A route that describes its run\n * (`Route.describe`, a kind's own function of the payload, which the core\n * never reads) has it opened on the tracer before any of its middleware, and\n * every middleware and its handler get the run's trace: its step traced, its\n * narrative the run's. The run ends with the answer: what the route makes of\n * its data on success, its failure otherwise.\n *\n * Tracing never fails an answer: a run that cannot be described, a tracer that\n * throws, or a run that cannot trace its steps, is not traced, with a warning\n * on the context's log; a run that fails to end leaves the answer as it was.\n */\n\nimport { failureOf, messageOf } from \"../errors\";\nimport { written } from \"../logger\";\nimport type { Payload } from \"../payload\";\nimport type { RunDescription, Span, Tracer } from \"../tracing/port\";\nimport { traceOf, type Trace } from \"../tracing/trace\";\nimport type { Context } from \"./context\";\n\n/** A run on the trace, as an answer uses it: the trace its middleware and handler get, and how it ends. */\nexport interface TracedRun {\n  trace: Trace;\n  /** Ends the run: a success with its data, as the route traces it, or the failure `error` names. */\n  end(outcome: { data: unknown } | { error: unknown }): Promise<void>;\n}\n\n/** The run of a route that describes none: the context's own trace, ending with nothing to tell. */\nfunction untracedRun(context: Context): TracedRun {\n  return { trace: context.trace, end: async () => {} };\n}\n\n/** The run `describe` says of `payload`, opened on `tracer`; none, with a warning, when it cannot be described or the tracer throws. */\nfunction openedOf(describe: (payload: Payload) => RunDescription | undefined, payload: Payload, tracer: Tracer, context: Context): { span: Span; description: RunDescription } | undefined {\n  try {\n    const description = describe(payload);\n    return description === undefined ? undefined : { span: tracer.run(description.run), description };\n  } catch (error) {\n    written(() => context.log.warn(`tracing: the action's run is not traced: ${messageOf(error)}`));\n    return undefined;\n  }\n}\n\n/** The trace of `span`: its step over the context's, and its narrative; the context's own, with a warning, when the span cannot give them. */\nfunction spanTraceOf(span: Span, context: Context): Trace {\n  try {\n    return traceOf(span.traced(context.trace.step), span.narrative);\n  } catch (error) {\n    written(() => context.log.warn(`tracing: the action's steps are not traced: ${messageOf(error)}`));\n    return context.trace;\n  }\n}\n\n/** The run an answer to `payload` is traced as, on `tracer`: the one `describe` says, opened now; untraced when the route describes none. */\nexport function runOf(describe: ((payload: Payload) => RunDescription | undefined) | undefined, payload: Payload, tracer: Tracer, context: Context): TracedRun {\n  const opened = describe === undefined ? undefined : openedOf(describe, payload, tracer, context);\n  if (opened === undefined) {\n    return untracedRun(context);\n  }\n  const { span, description } = opened;\n  return {\n    trace: spanTraceOf(span, context),\n    end: async (outcome) => {\n      try {\n        await span.end(\"error\" in outcome ? { status: \"failed\", failure: failureOf(outcome.error) } : { status: \"success\", result: description.result(outcome.data) });\n      } catch {\n        // Tracing never fails an answer.\n      }\n    },\n  };\n}\n\n","/**\n * definePlugin: a plugin is its package, its components and an ordered list\n * of routes. It answers a payload with the first route whose match accepts it,\n * running the plugin's middleware, then the route's, around the route's\n * handler, each `(input, context, next)` and the handler `(input, context)`,\n * the first handed the payload; the run the route describes, opened before\n * them all (`runOf`), and its guard, right before the handler, are the\n * route's own functions, which the core calls and never reads. A payload no\n * route accepts is refused with UNKNOWN_ACTION, naming\n * every route. It describes itself (`manifest()`) for publish and tooling.\n * Nothing runs on import: a transport answers with it, and the project's entry\n * point picks the transport.\n */\n\nimport { collect, isComponent, ref, type Component } from \"../component\";\nimport { ActionError, failureOf, failureText, messageOf, refusalText, refuseProblems, type Failure } from \"../errors\";\nimport { packageOf, type Package, type PackageDeclaration } from \"../package\";\nimport { isJsonObject, payloadOf, type Payload } from \"../payload\";\nimport { isJson, repeatedOf, textOf } from \"../text\";\nimport { contextOf, isOutput, streamingLog, type AnswerPorts, type Context, type Output } from \"./context\";\nimport { manifestOf, type AgentOptions, type Manifest } from \"./manifest\";\nimport { compose, isMiddleware, NOT_MIDDLEWARE, routeUsing, useProblemsOf, type Handler, type Middleware, type Route } from \"./route\";\nimport { runOf } from \"./traced\";\nimport type { Tracer } from \"../tracing/port\";\n\n/** What a plugin's own serve is handed: the run's logger, its signal, its platform credentials (frozen) and the project's own ports. */\nexport interface ServeContext<Ports extends object = {}> extends Pick<Context<Ports>, \"log\" | \"signal\" | \"credentials\" | \"ports\"> {}\n\n/** What a plugin is defined by. */\nexport interface PluginDefinition<Ports extends object = {}> {\n  /** The package it belongs to: its name, version and description (the slug is the name's unless given), the project's own. */\n  package: PackageDeclaration;\n  /** How the package's agent channel reaches the worker. */\n  agent?: AgentOptions;\n  /** What it publishes: values from `component()`, children reached through their parents. */\n  components?: Component[];\n  /** Around every route's middleware and handler, outermost first. */\n  use?: Middleware[];\n  /** What it answers, tried in order. */\n  routes: Route[];\n  /** How it serves itself, when it does (a collector's schedule and watch), in place of the agent's protocol. */\n  serve?: (context: ServeContext<Ports>) => Promise<void>;\n  /** Blocks describe carries for tooling beside the manifest's own fields (a collector's `collector`); publish ignores them. */\n  tooling?: Record<string, unknown>;\n}\n\n/** How a plugin answered a payload: the handler's return, or the failure, and how the answer prints. */\nexport interface Answer {\n  status: \"success\" | \"failed\";\n  data?: unknown;\n  failure?: Failure;\n  output: Output;\n}\n\n/** A plugin: what describe prints and what the transports answer with. */\nexport interface Plugin<Ports extends object = {}> {\n  readonly package: Package;\n  readonly routes: readonly Route[];\n  /** What publish registers and tooling offers. */\n  manifest(): Manifest;\n  /** The answer to the document a transport delivered. */\n  answer(document: Record<string, unknown>, ports: AnswerPorts<Ports>): Promise<Answer>;\n  /** How it serves itself, when it does. */\n  readonly serve?: (context: ServeContext<Ports>) => Promise<void>;\n}\n\n/** Who refuses a definition, as its problems are named. */\nconst DEFINER = \"definePlugin\";\n\n/** The manifest's own fields: tooling rides beside them, never in their place. */\nconst MANIFEST_FIELDS = [\"name\", \"slug\", \"version\", \"description\", \"components\", \"runs\"];\n\n/** A part of a definition that is optional: its name, what it must be when it is given, and the problem it names when it is not. */\ninterface Part {\n  name: string;\n  valid: (value: unknown) => boolean;\n  problem: string;\n}\n\n/** Whether `value` is a function. */\nfunction isFunction(value: unknown): boolean {\n  return typeof value === \"function\";\n}\n\n/** Whether `value` is true or false. */\nfunction isBoolean(value: unknown): boolean {\n  return typeof value === \"boolean\";\n}\n\n/** Whether `value` is a payload a route offers: a JSON object, as the agent delivers one (`isJson`: a Date or a Map, which JSON writes as text or `{}`, is not). */\nfunction isSample(value: unknown): boolean {\n  return isJsonObject(value) && isJson(value);\n}\n\n/** Whether `value` is a channel: a source's name and a filter, a JSON object. */\nfunction isChannel(value: unknown): boolean {\n  return isJsonObject(value) && textOf(value.source) !== undefined && isSample(value.filter);\n}\n\n/** Whether `value` is an agent's tags: an object of text. */\nfunction isTags(value: unknown): boolean {\n  return isJsonObject(value) && Object.values(value).every((tag) => typeof tag === \"string\");\n}\n\n/** Whether `value` is an array of source names. */\nfunction isSourceNames(value: unknown): boolean {\n  return Array.isArray(value) && value.every((name) => textOf(name) !== undefined);\n}\n\n/** What a route's optional parts must be. */\nconst ROUTE_PARTS: Part[] = [\n  { name: \"use\", valid: isMiddleware, problem: NOT_MIDDLEWARE },\n  { name: \"output\", valid: isFunction, problem: \"output must be a function\" },\n  { name: \"describe\", valid: isFunction, problem: \"describe must be a function\" },\n  { name: \"guard\", valid: isFunction, problem: \"guard must be a function\" },\n  { name: \"channel\", valid: isChannel, problem: \"channel must be { source, filter }: a source's name and a JSON filter object\" },\n  { name: \"sample\", valid: isSample, problem: \"sample must be a JSON object: a payload\" },\n];\n\n/** What the agent's options must be. */\nconst AGENT_PARTS: Part[] = [\n  { name: \"selector\", valid: isTags, problem: 'agent.selector must be an object of tags: { <tag>: \"<value>\" }' },\n  { name: \"entrypoint\", valid: (value) => textOf(value) !== undefined, problem: \"agent.entrypoint must be a path\" },\n  { name: \"sources\", valid: isSourceNames, problem: \"agent.sources must be an array of source names\" },\n  { name: \"pinVersion\", valid: isBoolean, problem: \"agent.pinVersion must be true or false\" },\n  { name: \"manageChannel\", valid: isBoolean, problem: \"agent.manageChannel must be true or false\" },\n];\n\n/** The problem of each of `parts` that `given` gives and is not what it must be. */\nfunction partsProblemsOf(given: object, parts: Part[]): string[] {\n  return parts.filter((part) => Reflect.get(given, part.name) !== undefined && !part.valid(Reflect.get(given, part.name))).map((part) => part.problem);\n}\n\n/** Whether `value` is a route: a name, a match function and a handler function. */\nfunction isRoute(value: unknown): value is Route {\n  return isJsonObject(value) && textOf(value.name) !== undefined && typeof value.match === \"function\" && typeof value.handler === \"function\";\n}\n\n/** What is wrong with the route at `index`: what it lacks, and an optional part that is not what it must be. */\nfunction routeProblemsOf(route: unknown, index: number): string[] {\n  if (!isRoute(route)) {\n    return [`routes[${index}] needs a name, a match function and a handler function`];\n  }\n  return partsProblemsOf(route, ROUTE_PARTS).map((problem) => `route \"${route.name}\": ${problem}`);\n}\n\n/** What is wrong with the routes: not an array, a route that is not one, a name given twice. */\nfunction routesProblemsOf(routes: unknown): string[] {\n  if (!Array.isArray(routes)) {\n    return [\"routes must be an array of routes: { name, match, handler }\"];\n  }\n  const names = routes.filter(isRoute).map((route) => route.name);\n  return [...routes.flatMap(routeProblemsOf), ...repeatedOf(names).map((name) => `route \"${name}\" is given twice`)];\n}\n\n/** What is wrong with the components: not an array, a value that is not one, two of the same kind and name. */\nfunction componentsProblemsOf(components: unknown): string[] {\n  if (!Array.isArray(components)) {\n    return [\"components must be an array of values from component()\"];\n  }\n  const refs = collect(components.filter(isComponent)).map((declared) => ref(declared).ref);\n  const strays = components.some((value) => !isComponent(value)) ? [\"components must be values from component()\"] : [];\n  return [...strays, ...repeatedOf(refs).map((named) => `${named} is given twice`)];\n}\n\n/** What is wrong with the agent's options: not an object, or an option that is not what it must be. */\nfunction agentProblemsOf(agent: unknown): string[] {\n  if (agent === undefined) {\n    return [];\n  }\n  if (!isJsonObject(agent)) {\n    return [\"agent must be an object: { selector?, entrypoint?, sources?, pinVersion?, manageChannel? }\"];\n  }\n  return partsProblemsOf(agent, AGENT_PARTS);\n}\n\n/** What is wrong with the tooling: not an object of blocks, or a block named as one of the manifest's own fields. */\nfunction toolingProblemsOf(tooling: unknown): string[] {\n  if (tooling === undefined) {\n    return [];\n  }\n  if (!isJsonObject(tooling)) {\n    return [\"tooling must be an object of blocks: { <block>: … }\"];\n  }\n  const reserved = Object.keys(tooling).filter((field) => MANIFEST_FIELDS.includes(field));\n  return reserved.length === 0 ? [] : [`tooling may not name ${reserved.join(\", \")}: they are the manifest's own`];\n}\n\n/** Every problem of a definition but its package's, in the order it is written: what definePlugin refuses, and what a kind that builds one names in its own refusal, beside its own problems. */\nexport function pluginProblemsOf<Ports extends object>(definition: Partial<PluginDefinition<Ports>>): string[] {\n  return [\n    ...useProblemsOf(definition.use),\n    ...routesProblemsOf(definition.routes),\n    ...componentsProblemsOf(definition.components ?? []),\n    ...agentProblemsOf(definition.agent),\n    ...toolingProblemsOf(definition.tooling),\n    ...(definition.serve === undefined || isFunction(definition.serve) ? [] : [\"serve must be a function\"]),\n  ];\n}\n\n/** The package a definition declares, or the problem that refuses it, named as packageOf names it. */\nfunction declaredPackageOf(declaration: PackageDeclaration | undefined): { declared: Package } | { problem: string } {\n  try {\n    return { declared: packageOf(DEFINER, declaration as PackageDeclaration) };\n  } catch (error) {\n    return { problem: messageOf(error) };\n  }\n}\n\n/** The package of a definition, every problem of it refused at once: its package's first, the rest after it, named by the package when it has one. */\nfunction validated<Ports extends object>(definition: Partial<PluginDefinition<Ports>>): Package {\n  const declaration = declaredPackageOf(definition.package);\n  const problems = pluginProblemsOf(definition);\n  if (\"problem\" in declaration) {\n    throw new Error(refusalText([declaration.problem, ...problems]));\n  }\n  refuseProblems(problems, `${DEFINER}(${declaration.declared.name})`);\n  return declaration.declared;\n}\n\n/** The refusal of a payload no route accepts: every route's name, in order. */\nfunction refusalOf(routes: readonly Route[]): ActionError {\n  const names = routes.map((route) => route.name).join(\", \");\n  return new ActionError(\"UNKNOWN_ACTION\", `nothing in this plugin answers this payload (it answers: ${names})`);\n}\n\n/** How `route` prints its answer to `payload`: as its output says, envelope unless it says; anything but envelope or raw is refused. */\nfunction outputOf(route: Route, payload: Payload): Output {\n  const output = route.output?.(payload) ?? \"envelope\";\n  if (!isOutput(output)) {\n    throw new Error(`route \"${route.name}\" prints its answer as \"${messageOf(output)}\": a route prints envelope or raw`);\n  }\n  return output;\n}\n\n/** What answers `document`: its payload, the first route whose match accepts it and how it prints; or what refuses it. */\nfunction chosenFor(routes: readonly Route[], document: Record<string, unknown>): { payload: Payload; route: Route; output: Output } | { refusal: unknown } {\n  try {\n    const payload = payloadOf(document);\n    const route = routes.find((candidate) => candidate.match(payload));\n    if (route === undefined) {\n      return { refusal: refusalOf(routes) };\n    }\n    return { payload, route, output: outputOf(route, payload) };\n  } catch (error) {\n    return { refusal: error };\n  }\n}\n\n/** A failed answer printed `output`: the failure `error` names, logged once at error, as `failureText` says it, on the ports' log and stream. */\nexport function failedAnswer<Ports extends object>(error: unknown, output: Output, ports: AnswerPorts<Ports>): Answer {\n  const failure = failureOf(error);\n  streamingLog(ports.log, output, ports.stream).error(failureText(failure));\n  return { status: \"failed\", failure, output };\n}\n\n/** The answer to `document`, never a rejection: its payload answered by the route chosen for it, inside the plugin's middleware and the route's. */\nasync function answerOf<Ports extends object>(routes: readonly Route[], use: readonly Middleware[], document: Record<string, unknown>, ports: AnswerPorts<Ports>): Promise<Answer> {\n  const chosen = chosenFor(routes, document);\n  if (\"refusal\" in chosen) {\n    return failedAnswer(chosen.refusal, \"envelope\", ports);\n  }\n  const { payload, route, output } = chosen;\n  try {\n    const context = contextOf(ports, output);\n    return { status: \"success\", data: await tracedData(route, use, payload, context, ports.tracer), output };\n  } catch (error) {\n    return failedAnswer(error, output, ports);\n  }\n}\n\n/** What `route` answers `payload` with, inside the plugin's middleware `use` and its own, traced as the run it describes: opened on `tracer` first, ended with the data, or with what was thrown, which passes on. */\nasync function tracedData(route: Route, use: readonly Middleware[], payload: Payload, context: Context, tracer: Tracer): Promise<unknown> {\n  const run = runOf(route.describe, payload, tracer, context);\n  try {\n    const data = await compose([...use, ...(route.use ?? [])], guardedHandler(route, payload))(payload, { ...context, trace: run.trace });\n    await run.end({ data });\n    return data;\n  } catch (error) {\n    await run.end({ error });\n    throw error;\n  }\n}\n\n/** The handler of `route` for `payload`: handed what the route's guard makes of its input and the payload, when it has one. */\nfunction guardedHandler(route: Route, payload: Payload): Handler {\n  const { guard, handler } = route;\n  return guard === undefined ? handler : (input, context) => handler(guard(input, payload), context);\n}\n\n/** `value` frozen at every depth: a copy the plugin keeps, which no reader can change. */\nfunction deeplyFrozen<Value>(value: Value): Value {\n  if (typeof value === \"object\" && value !== null) {\n    Object.values(value).forEach(deeplyFrozen);\n    Object.freeze(value);\n  }\n  return value;\n}\n\n/**\n * `route` as the plugin keeps it, built from its declared parts (`routeUsing`):\n * its methods bound to it, copies of its middleware, its channel and its\n * sample, each frozen at every depth, and the whole frozen.\n */\nfunction fixedRouteOf(route: Route): Route {\n  const { use, channel, sample } = route;\n  return Object.freeze({\n    ...routeUsing(route, use && Object.freeze([...use])),\n    ...(channel && { channel: deeplyFrozen({ source: channel.source, filter: structuredClone(channel.filter) }) }),\n    ...(sample && { sample: deeplyFrozen(structuredClone(sample)) }),\n  });\n}\n\n/** The agent's options as the plugin keeps them: a copy, its selector and its sources copied too. */\nfunction fixedAgentOf(agent: AgentOptions = {}): AgentOptions {\n  const { selector, sources } = agent;\n  return Object.freeze({ ...agent, selector: selector && { ...selector }, sources: sources && [...sources] });\n}\n\n/**\n * A plugin of its package, its components and its routes; a definition with a\n * problem is refused, naming every problem at once. What it is given is copied\n * when it is defined: a later change to the definition reaches neither its\n * answers nor its describe.\n */\nexport function definePlugin<Ports extends object = {}>(definition: PluginDefinition<Ports>): Plugin<Ports> {\n  const declared = validated<Ports>(definition ?? {});\n  const routes = Object.freeze(definition.routes.map(fixedRouteOf));\n  const use = Object.freeze([...(definition.use ?? [])]);\n  const components = Object.freeze([...(definition.components ?? [])]);\n  const agent = fixedAgentOf(definition.agent);\n  const tooling = Object.freeze({ ...definition.tooling });\n  const plugin: Plugin<Ports> = {\n    package: declared,\n    routes,\n    manifest: () => manifestOf({ package: declared, agent, components: [...components], routes, tooling }),\n    answer: (document, ports) => answerOf(routes, use, document, ports),\n  };\n  return definition.serve === undefined ? plugin : { ...plugin, serve: definition.serve };\n}\n"],"mappings":";;;;;;;;;;;AAQA,SAAgB,OAAO,OAAoC;CACzD,IAAI,OAAO,UAAU,UACnB;CAEF,MAAM,UAAU,MAAM,KAAK;CAC3B,OAAO,YAAY,KAAK,KAAA,IAAY;AACtC;;AAGA,SAAgB,WAAW,OAA2B;CACpD,OAAO,CAAC,GAAG,IAAI,IAAI,MAAM,QAAQ,MAAM,UAAU,MAAM,Q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