{"version":3,"file":"exec-BPiDy-Fi.mjs","names":[],"sources":["../src/core/transport/ports.ts","../src/core/transport/agent.ts","../src/core/transport/exec.ts"],"sourcesContent":["/**\n * The ports a transport runs a plugin with, `handle`'s and `serve`'s alike:\n * the settings, the platform port, tracing, the logger and the signal, each\n * defaulting as it says. Any other port given is the plugin's own: `context.ports`,\n * and its own serve's `context.ports`. The settings are resolved once per run,\n * here: what the run is given, else each one's default. The tracer the\n * settings build is the transport's: it stops it once it is done with it.\n */\n\nimport { authorizedFetch, type Fetch } from \"../api\";\nimport { stderrLogger, type Logger } from \"../logger\";\nimport type { AnswerPorts } from \"../run/context\";\nimport { settingsOf, type Settings } from \"../settings\";\nimport { tracerOf, type TracingPort } from \"../tracing/sdk\";\n\n/** The ports every transport runs a plugin with; each defaults as it says. */\nexport interface Ports {\n  /** The run's settings (contract/settings.json): each the one given, else its default. `main` fills what the code leaves unset from the variables the agent sets. */\n  settings?: Partial<Settings>;\n  /** The platform port every call of `context.api` goes through: the one the settings authorize (`authorizedFetch`) unless given (a local run passes `recordingPlatform().fetch`). */\n  fetch?: Fetch;\n  /** Where every run is traced: a Tracer (`noopTracing`), or the tracing SDK's Tracer as it is; the settings' unless given. */\n  tracing?: TracingPort;\n  /** The run's logger: what the handler, the server and tracing say. `stderrLogger` unless given; never stdout, which is the answer's. */\n  log?: Logger;\n  /** Aborted when the worker must stop; never unless given. */\n  signal?: AbortSignal;\n}\n\n/**\n * The argument a run of a plugin whose own ports are `Own` is handed, its\n * ports or its options (`Given`): optional when each of its own ports is,\n * else required (as `Required`, its own ports in it), so no plugin runs\n * without a port it needs. `main`, `handle` and `serve` take their ports so,\n * and `run` its options.\n */\nexport type OwnPortsArgument<Own extends object, Given, Required = Given> = {} extends Own ? [Given?] : [Required];\n\n/** The core's ports, by name: every other port given is the plugin's own. */\nconst CORE_PORTS: Record<keyof Ports, true> = { settings: true, fetch: true, tracing: true, log: true, signal: true };\n\n/** A signal nothing aborts: the worker's when it is given none. */\nconst NEVER_ABORTED = new AbortController().signal;\n\n/** The ports given beside the core's: the plugin's own (a collector's ingest), never the settings, the platform port, tracing, the log or the signal. */\nexport function ownPorts<Own extends object>(given: Ports & Own): Own {\n  return Object.fromEntries(Object.entries(given).filter(([name]) => !Object.hasOwn(CORE_PORTS, name))) as Own;\n}\n\n/** The ports a transport answers with, and what it calls once it is done with them: the tracer the settings built then stops what it is still sending; one given as a port is the caller's, and goes on. */\nexport interface TransportPorts<Own extends object> {\n  ports: AnswerPorts<Own>;\n  done: () => void;\n}\n\n/**\n * The ports a plugin answers with, from those given: the run's settings,\n * resolved once; each core port given or its default, tracing told the log,\n * the settings and when the transport is done (`done`); and the plugin's own.\n * None given is the core's defaults: a run's types give none only to a plugin\n * that needs none of its own (`OwnPortsArgument`).\n */\nexport function transportPortsOf<Own extends object>(given: Ports & Own = {} as Ports & Own): TransportPorts<Own> {\n  const log = given.log ?? stderrLogger;\n  const settings = settingsOf(given.settings);\n  const finished = new AbortController();\n  const ports: AnswerPorts<Own> = {\n    settings,\n    fetch: given.fetch ?? authorizedFetch(settings),\n    log,\n    signal: given.signal ?? NEVER_ABORTED,\n    ports: ownPorts(given),\n    tracer: tracerOf(given.tracing, { log, settings, done: finished.signal }),\n  };\n  return { ports, done: () => finished.abort() };\n}\n","/**\n * Which of the agent's protocols a worker speaks, as its settings say, each\n * read as text (a blank one is none): the agent's gRPC protocol when the\n * agent's cookie names it (contract/platform.json) or a listen address is\n * set; else the document the agent exec'd it with. It is apart from the gRPC\n * server so that what answers a document (exec.ts, `main`, the root entry)\n * loads no gRPC module: `serve` imports the server only when it serves.\n */\n\nimport platform from \"../../../../contract/platform.json\" with { type: \"json\" };\nimport type { Settings } from \"../settings\";\nimport { textOf } from \"../text\";\n\n/** The protocol the agent speaks: a worker started without a listen address serves only when the agent's cookie names it. */\nexport const AGENT_PROTOCOL: string = platform.cookie.value;\n\n/** Whether a worker of `settings` serves the agent's gRPC protocol: the agent's cookie names it, or a listen address is set; each read as text. */\nexport function servesAgentProtocol(settings: Pick<Settings, \"agentPlugin\" | \"grpcListen\">): boolean {\n  return textOf(settings.agentPlugin) === AGENT_PROTOCOL || textOf(settings.grpcListen) !== undefined;\n}\n","/**\n * The agent's exec protocol: the document arrives as text (the run's\n * `actionContext`, `execDocument`, which `main` hands `handle`), the answer\n * leaves as what the worker prints and whether it succeeded, its exit\n * status. A handler's log goes to the run's logger, never to stdout, which is\n * the answer's.\n *\n * What every transport answers a delivery with lives here too: text that is\n * not a JSON object is refused with MISSING_CONTEXT; a plugin's answer that\n * rejects, or a return JSON cannot print, is an EXECUTION_ERROR. Each is\n * failed and logged as any failure is. A return is written as JSON once per\n * answer (`PrintableAnswer`): what exec prints and what gRPC sends share it.\n */\n\nimport { ActionError, messageOf } from \"../errors\";\nimport { documentOf } from \"../payload\";\nimport type { AnswerPorts } from \"../run/context\";\nimport { failedAnswer, type Answer, type Plugin } from \"../run/plugin\";\nimport type { Settings } from \"../settings\";\nimport { textOf } from \"../text\";\nimport { transportPortsOf, type OwnPortsArgument, type Ports } from \"./ports\";\nimport { servesAgentProtocol } from \"./agent\";\n\n/** What the worker prints, and whether it succeeded: exit 0 when it did, 1 when not. */\nexport interface Handled {\n  output: string;\n  success: boolean;\n}\n\n/** Why a delivery whose text is not a JSON object is refused. */\nconst NOT_A_DOCUMENT = \"the document is not a JSON object\";\n\n/** An answer as the transports print it: the plugin's answer, and its data as JSON text, written once (undefined when JSON writes nothing for it, or the answer failed). */\nexport interface PrintableAnswer extends Answer {\n  json: string | undefined;\n}\n\n/** `data` as JSON text; none when JSON prints nothing for it (undefined, a function). */\nfunction jsonOf(data: unknown): string | undefined {\n  return JSON.stringify(data);\n}\n\n/** `plugin`'s answer to `document`; a rejection, which a plugin never gives, answered as a failure. */\nasync function answered<Own extends object>(plugin: Plugin<Own>, document: Record<string, unknown>, ports: AnswerPorts<Own>): Promise<Answer> {\n  try {\n    return await plugin.answer(document, ports);\n  } catch (error) {\n    return failedAnswer(error, \"envelope\", ports);\n  }\n}\n\n/** `answer` as the transports print it, its data written as JSON once: a return JSON cannot print fails it. */\nfunction printable<Own extends object>(answer: Answer, ports: AnswerPorts<Own>): PrintableAnswer {\n  try {\n    return { ...answer, json: jsonOf(answer.data) };\n  } catch (error) {\n    const failed = failedAnswer(new Error(`the handler's return is not JSON: ${messageOf(error)}`, { cause: error }), answer.output, ports);\n    return { ...failed, json: undefined };\n  }\n}\n\n/** `plugin`'s answer to `document`, never a rejection, as every transport answers it: an answer that rejects, or a return JSON cannot print, is a failure. */\nexport async function answerDocument<Own extends object>(plugin: Plugin<Own>, document: Record<string, unknown>, ports: AnswerPorts<Own>): Promise<PrintableAnswer> {\n  return printable(await answered(plugin, document, ports), ports);\n}\n\n/** The answer to a delivery's text, never a rejection: its document answered by `plugin`, or refused with MISSING_CONTEXT when it carries none. */\nexport async function answerDelivery<Own extends object>(plugin: Plugin<Own>, text: string, ports: AnswerPorts<Own>): Promise<PrintableAnswer> {\n  const document = documentOf(text);\n  if (document === undefined) {\n    return printable(failedAnswer(new ActionError(\"MISSING_CONTEXT\", NOT_A_DOCUMENT), \"envelope\", ports), ports);\n  }\n  return answerDocument(plugin, document, ports);\n}\n\n/** A success's envelope around `json`, its data as JSON text: `{\"success\":true,\"data\":…}`, with no `data` when there is none. */\nfunction envelopeOf(json: string | undefined): string {\n  return json === undefined ? JSON.stringify({ success: true }) : `{\"success\":true,\"data\":${json}}`;\n}\n\n/**\n * What the worker prints for `answer`. A failure is the envelope, its message\n * and code, never whether it is retryable. A raw answer is its data: a string\n * as it is, nothing as `{}`, anything else as its JSON. An envelope is\n * `{\"success\":true,\"data\":…}`, with no `data` when the handler returned\n * nothing.\n */\nexport function printed(answer: PrintableAnswer): Handled {\n  if (answer.status === \"failed\") {\n    return { output: JSON.stringify({ success: false, error: answer.failure?.message, errorCode: answer.failure?.code }), success: false };\n  }\n  if (answer.output === \"raw\") {\n    return { output: typeof answer.data === \"string\" ? answer.data : (answer.json ?? \"{}\"), success: true };\n  }\n  return { output: envelopeOf(answer.json), success: true };\n}\n\n/**\n * Answers one document, as text: what the entry point prints and exits with.\n * Once answered, it stops the tracer it built, so nothing of tracing holds the\n * worker's exit. The ports beyond the core's are the plugin's own\n * (`context.ports`), required when the plugin needs them.\n */\nexport async function handle<Own extends object = {}>(plugin: Plugin<Own>, text: string, ...[ports]: OwnPortsArgument<Own, Ports & Own>): Promise<Handled> {\n  const { ports: answerPorts, done } = transportPortsOf(ports);\n  try {\n    return printed(await answerDelivery(plugin, text, answerPorts));\n  } finally {\n    done();\n  }\n}\n\n/**\n * The document the agent exec'd a worker of `settings` with: their\n * `actionContext`, when it is set and not blank and the worker does not serve\n * the agent's gRPC protocol (`servesAgentProtocol`); none otherwise, when the\n * worker is to serve.\n */\nexport function execDocument(settings: Pick<Settings, \"actionContext\" | \"agentPlugin\" | \"grpcListen\">): string | undefined {\n  const text = settings.actionContext;\n  return textOf(text) === undefined || servesAgentProtocol(settings) ? undefined : text;\n}\n"],"mappings":";;;;;;;;;;;;AAuCA,MAAM,aAAwC;CAAE,UAAU;CAAM,OAAO;CAAM,SAAS;CAAM,KAAK;CAAM,QAAQ;AAAK;;AAGpH,MAAM,gBAAgB,IAAI,gBAAgB,CAAC,CAAC;;AAG5C,SAAgB,SAA6B,OAAyB;CACpE,OAAO,OAAO,YAAY,OAAO,QAAQ,KAAK,CAAC,CAAC,QAAQ,CAAC,UAAU,CAAC,OAAO,OAAO,YAAY,IAAI,CAAC,CAAC;AACtG;;;;;;;;AAeA,SAAgB,iBAAqC,QAAqB,CAAC,GAAuC;CAChH,MAAM,MAAM,MAAM,OAAO;CACzB,MAAM,WAAW,WAAW,MAAM,QAAQ;CAC1C,MAAM,WAAW,IAAI,gBAAgB;CASrC,OAAO;EAAE,OAAA;GAPP;GACA,OAAO,MAAM,SAAS,gBAAgB,QAAQ;GAC9C;GACA,QAAQ,MAAM,UAAU;GACxB,OAAO,SAAS,KAAK;GACrB,QAAQ,SAAS,MAAM,SAAS;IAAE;IAAK;I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