{"version":3,"file":"grpc-Dq1DLPUK.mjs","names":["platform.capabilities"],"sources":["../src/core/transport/runtime.ts","../src/core/transport/grpc.ts"],"sourcesContent":["/** What the worker runs on, as the agent's Version and Health report it. */\n\n/** The runtime's name and version. */\nexport interface Runtime {\n  name: \"bun\" | \"node\";\n  version: string;\n}\n\n/** What tells the runtime apart: bun defines `Bun`, with its version. */\ninterface Host {\n  Bun?: { version: string };\n}\n\n/** The runtime `host` is: bun, with its version, when it defines `Bun`; else node, with its own. */\nexport function runtimeOf(host: Host = globalThis): Runtime {\n  return host.Bun === undefined ? { name: \"node\", version: process.version } : { name: \"bun\", version: host.Bun.version };\n}\n\n/** The memory the worker holds, in bytes. */\nexport function memoryInUse(): number {\n  return process.memoryUsage().rss;\n}\n","/**\n * The agent's gRPC protocol over a plugin: what each call of np-agent-v1's\n * ExecutorPlugin answers.\n *\n * Execute's payload is the document. It streams `started`, then the answer's\n * log as output events (the plugin's context splits stdout from stderr and\n * ends each line), then one `result`. A raw answer also streams itself as the\n * last stdout once the handler returns: a raw route's stdout is its answer, so\n * its log streams on stderr only. Each Execute answers with a signal of its\n * own, aborted when the agent cancels the call or the server stops. A call\n * whose stream cannot be written (one the agent closed) is that call's: it is\n * logged at error and the call ended, never the process's.\n *\n * Once the server is stopping, every call that arrives, an Execute as a\n * Health, is refused UNAVAILABLE, naming why, so the agent sends it to another\n * worker; the Executes in flight (`ServiceState.inFlight`) answer, each told\n * the stop by its signal, and their answers are delivered: an Execute is in\n * flight until its call has finished, every frame of its answer flushed, or\n * closed.\n */\n\nimport type * as grpc from \"@grpc/grpc-js\";\nimport platform from \"../../../../contract/platform.json\" with { type: \"json\" };\nimport { messageOf } from \"../errors\";\nimport { written, type Logger } from \"../logger\";\nimport type { Package } from \"../package\";\nimport { lineOf, type AnswerPorts, type StreamChunk } from \"../run/context\";\nimport type { Plugin } from \"../run/plugin\";\nimport type { Settings } from \"../settings\";\nimport { answerDelivery, printed, type PrintableAnswer } from \"./exec\";\nimport { memoryInUse, runtimeOf } from \"./runtime\";\n\n/** What the server serves, replaced in place on a hot reload: the plugin's package, the log the server speaks on, the run's settings (where it listens and how), and the plugin's answer to a delivery. */\nexport interface Served {\n  package: Package;\n  log: Logger;\n  settings: Settings;\n  /** The answer to a delivery's text, with the call's signal and its stream; never a rejection. */\n  answer(text: string, signal: AbortSignal, stream: (chunk: StreamChunk) => void): Promise<PrintableAnswer>;\n}\n\n/** `plugin` served with `ports`: each Execute answered with them, its signal and its stream the call's. */\nexport function servedOf<Own extends object>(plugin: Plugin<Own>, ports: AnswerPorts<Own>): Served {\n  return {\n    package: plugin.package,\n    log: ports.log,\n    settings: ports.settings,\n    answer: (text, signal, stream) => answerDelivery(plugin, text, { ...ports, signal, stream }),\n  };\n}\n\n/** What every call reads: what is served, a signal aborted when the server stops, when it started, and the Executes in flight, each until its answer is delivered. */\nexport interface ServiceState {\n  served: Served;\n  stopping: AbortSignal;\n  startedAt: number;\n  inFlight: Set<Promise<void>>;\n}\n\n/** gRPC's status for a server that takes no call now, typed as grpc-js's `status.UNAVAILABLE` (whose value this module never loads): the client may send the call elsewhere. */\nconst UNAVAILABLE: grpc.status.UNAVAILABLE = 14;\n\n/** Why a stopping server refuses a call, as gRPC carries it: UNAVAILABLE, and what is stopping. */\nfunction stoppingRefusalOf(state: ServiceState): { code: number; details: string } {\n  return { code: UNAVAILABLE, details: `${state.served.package.slug}: worker stopping: it answers no new call` };\n}\n\n// The wire's messages, their fields as the contract spells them.\n\ninterface ExecuteRequestMessage {\n  payload: Buffer;\n}\n\ninterface ExecuteResultMessage {\n  success: boolean;\n  data: Buffer;\n  error: string;\n  exit_code: number;\n  error_code: string;\n}\n\ninterface ExecuteEventMessage {\n  started?: Record<string, never>;\n  output?: { stdout: string; stderr: string };\n  result?: ExecuteResultMessage;\n}\n\n/** The log of what `state` serves when a line is logged, whatever it served when this was asked: a hot reload's swap reaches what logs on it after. */\nexport function servedLogOf(state: ServiceState): Logger {\n  const current = (level: keyof Logger) => (message: string): void => state.served.log[level](message);\n  return { debug: current(\"debug\"), info: current(\"info\"), warn: current(\"warn\"), error: current(\"error\") };\n}\n\n/** Runs `run` once `signal` aborts, now if it already has; what it answers stops listening to `signal`. */\nexport function onAbort(signal: AbortSignal, run: () => void): () => void {\n  signal.addEventListener(\"abort\", run, { once: true });\n  if (signal.aborted) {\n    run();\n  }\n  return () => signal.removeEventListener(\"abort\", run);\n}\n\n/**\n * The Execute result for `answer`, as exec exits: on a success, `data` the\n * handler's return as JSON bytes, whatever the route's output (empty when it\n * returned nothing), exit 0; on a failure, its message and code, no data,\n * exit 1. Never whether the failure is retryable.\n */\nexport function resultOf(answer: PrintableAnswer): ExecuteResultMessage {\n  if (answer.status === \"failed\") {\n    return { success: false, data: Buffer.alloc(0), error: answer.failure?.message ?? \"\", exit_code: 1, error_code: answer.failure?.code ?? \"\" };\n  }\n  return { success: true, data: Buffer.from(answer.json ?? \"\"), error: \"\", exit_code: 0, error_code: \"\" };\n}\n\n/** Answers one Execute on `call`: its output events as the answer streams them, a raw answer as the last stdout, then the result. */\nasync function answered(call: grpc.ServerWritableStream<ExecuteRequestMessage, ExecuteEventMessage>, served: Served, signal: AbortSignal): Promise<void> {\n  const stream = (chunk: StreamChunk): void => {\n    call.write({ output: { stdout: chunk.stdout ?? \"\", stderr: chunk.stderr ?? \"\" } });\n  };\n  const answer = await served.answer(call.request.payload.toString(\"utf-8\"), signal, stream);\n  if (answer.status === \"success\" && answer.output === \"raw\") {\n    stream({ stdout: lineOf(printed(answer).output) });\n  }\n  call.write({ result: resultOf(answer) });\n}\n\n/** `started`, then the answer, on `call`; what keeps them from reaching the agent is logged at error on the served log, never thrown. */\nasync function executed(call: grpc.ServerWritableStream<ExecuteRequestMessage, ExecuteEventMessage>, state: ServiceState, signal: AbortSignal): Promise<void> {\n  try {\n    call.write({ started: {} });\n    await answered(call, state.served, signal);\n  } catch (error) {\n    written(() => state.served.log.error(`${state.served.package.slug}: an Execute could not be answered: ${messageOf(error)}`));\n  }\n}\n\n/** Ends `call`; resolves once it has finished, every frame written to it flushed, or closed, whatever ended it: at once when it already has. */\nfunction ended(call: grpc.ServerWritableStream<ExecuteRequestMessage, ExecuteEventMessage>): Promise<void> {\n  return new Promise((resolve) => {\n    call.once(\"finish\", resolve);\n    call.once(\"close\", resolve);\n    written(() => call.end());\n    if (call.writableFinished || call.destroyed) {\n      resolve();\n    }\n  });\n}\n\n/** Execute: `started`, the answer, the call ended; its signal its own, aborted when the agent cancels the call or the server stops. In flight until its answer is delivered, the call finished or closed; refused once the server is stopping. */\nfunction executeOf(state: ServiceState): grpc.handleServerStreamingCall<ExecuteRequestMessage, ExecuteEventMessage> {\n  return (call) => {\n    if (state.stopping.aborted) {\n      call.emit(\"error\", stoppingRefusalOf(state));\n      return;\n    }\n    const answering = new AbortController();\n    const abort = (): void => answering.abort();\n    call.on(\"cancelled\", abort);\n    const stopListening = onAbort(state.stopping, abort);\n    const delivered: Promise<void> = executed(call, state, answering.signal)\n      .then(() => ended(call))\n      .finally(() => {\n        state.inFlight.delete(delivered);\n        stopListening();\n      });\n    state.inFlight.add(delivered);\n  };\n}\n\n/** `answer` as a unary call: what it answers, or UNAVAILABLE once the server is stopping. */\nfunction unaryOf<Reply>(state: ServiceState, answer: () => Reply): grpc.handleUnaryCall<object, Reply> {\n  return (call, callback) => {\n    if (state.stopping.aborted) {\n      callback(stoppingRefusalOf(state), null);\n      return;\n    }\n    callback(null, answer());\n  };\n}\n\n/** What Health answers: healthy, how long the server has served, the Executes in flight and the memory in use. */\nfunction healthOf(state: ServiceState): object {\n  return { healthy: true, uptime_ms: String(Date.now() - state.startedAt), active_commands: state.inFlight.size, memory_bytes: String(memoryInUse()), message: \"ok\" };\n}\n\n/** What Version answers: the package's name and version, and the runtime it runs on. */\nfunction versionOf(state: ServiceState): object {\n  const runtime = runtimeOf();\n  const { name, version } = state.served.package;\n  return { name, version, metadata: { runtime: runtime.name, runtime_version: runtime.version } };\n}\n\n/** The service's calls, each reading `state` as it is when the call arrives: a hot reload's swap takes effect on the next call. Every one is refused once the server is stopping. */\nexport function serviceOf(state: ServiceState): grpc.UntypedServiceImplementation {\n  return {\n    Execute: executeOf(state),\n    Capabilities: unaryOf(state, () => platform.capabilities),\n    Health: unaryOf(state, () => healthOf(state)),\n    Version: unaryOf(state, () => versionOf(state)),\n  };\n}\n"],"mappings":";;;;AAcA,SAAgB,UAAU,OAAa,YAAqB;CAC1D,OAAO,KAAK,QAAQ,KAAA,IAAY;EAAE,MAAM;EAAQ,SAAS,QAAQ;CAAQ,IAAI;EAAE,MAAM;EAAO,SAAS,KAAK,IAAI;CAAQ;AACxH;;AAGA,SAAgB,cAAsB;CACpC,OAAO,QAAQ,YAAY,CAAC,CAAC;AAC/B;;;ACqBA,SAAgB,SAA6B,QAAqB,OAAiC;CACjG,OAAO;EACL,SAAS,OAAO;EAChB,KAAK,MAAM;EACX,UAAU,MAAM;EAChB,SAAS,MAAM,QAAQ,WAAW,eAAe,QAAQ,MAAM;GAAE,GAAG;GAAO;GAAQ;EAAO,CAAC;CAC7F;AACF;;AAWA,MAAM,cAAuC;;AAG7C,SAAS,kBAAkB,OAAwD;CACjF,OAAO;EAAE,MAAM;EAAa,SAAS,GAAG,MAAM,OAAO,QAAQ,KAAK;CAA2C;AAC/G;;AAuBA,SAAgB,YAAY,OAA6B;CACvD,MAAM,WAAW,WAAyB,YAA0B,MAAM,OAAO,IAAI,MAAM,CAAC,OAAO;CACnG,OAAO;EAAE,OAAO,QAAQ,OAAO;EAAG,MAAM,QAAQ,MAAM;EAAG,MAAM,QAAQ,MAAM;EAAG,OAAO,QAAQ,OAAO;CAAE;AAC1G;;AAGA,SAAgB,QAAQ,QAAqB,KAA6B;CACxE,OAAO,iBAAiB,SAAS,KAAK,EAAE,MAAM,KAAK,CAAC;CACpD,IAAI,OAAO,SACT,IAAI;CAEN,aAAa,OAAO,oBAAoB,SAAS,GAAG;AACtD;;;;;;;AAQA,SAAgB,SAAS,QAA+C;CACtE,IAAI,OAAO,W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