@kb-labs/core-state-daemon 2.89.0 → 2.93.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.cjs CHANGED
@@ -78,21 +78,23 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
78
78
  mod
79
79
  ));
80
80
  function getOrCreatePlatformContext() {
81
- const existing = process[PLATFORM_CONTEXT_KEY];
81
+ const proc = process;
82
+ const existing = proc[PLATFORM_CONTEXT_KEY];
82
83
  if (existing instanceof async_hooks.AsyncLocalStorage) {
83
84
  return existing;
84
85
  }
85
86
  const ctx = new async_hooks.AsyncLocalStorage();
86
- process[PLATFORM_CONTEXT_KEY] = ctx;
87
+ proc[PLATFORM_CONTEXT_KEY] = ctx;
87
88
  return ctx;
88
89
  }
89
90
  function getOrCreateRuntimeContext() {
90
- const existing = process[RUNTIME_CONTEXT_KEY];
91
+ const proc = process;
92
+ const existing = proc[RUNTIME_CONTEXT_KEY];
91
93
  if (existing instanceof async_hooks.AsyncLocalStorage) {
92
94
  return existing;
93
95
  }
94
96
  const ctx = new async_hooks.AsyncLocalStorage();
95
- process[RUNTIME_CONTEXT_KEY] = ctx;
97
+ proc[RUNTIME_CONTEXT_KEY] = ctx;
96
98
  return ctx;
97
99
  }
98
100
  var noopColor, noopColors, noopSymbols, noopUI, PLATFORM_CONTEXT_KEY, RUNTIME_CONTEXT_KEY;
@@ -184,20 +186,26 @@ var init_dist = __esm({
184
186
  });
185
187
 
186
188
  // ../../../core/platform/dist/serializable/index.js
189
+ function isRecord(v) {
190
+ return typeof v === "object" && v !== null;
191
+ }
187
192
  function isAdapterCall(msg) {
188
- if (typeof msg !== "object" || msg === null || msg.type !== "adapter:call" || typeof msg.requestId !== "string" || typeof msg.adapter !== "string" || typeof msg.method !== "string" || !Array.isArray(msg.args)) {
193
+ if (!isRecord(msg)) {
194
+ return false;
195
+ }
196
+ if (msg["type"] !== "adapter:call" || typeof msg["requestId"] !== "string" || typeof msg["adapter"] !== "string" || typeof msg["method"] !== "string" || !Array.isArray(msg["args"])) {
189
197
  return false;
190
198
  }
191
- if ("version" in msg && typeof msg.version !== "number") {
199
+ if ("version" in msg && typeof msg["version"] !== "number") {
192
200
  return false;
193
201
  }
194
202
  if (!("version" in msg)) {
195
- msg.version = 1;
203
+ msg["version"] = 1;
196
204
  }
197
205
  return true;
198
206
  }
199
207
  function isAdapterResponse(msg) {
200
- return typeof msg === "object" && msg !== null && msg.type === "adapter:response" && typeof msg.requestId === "string";
208
+ return isRecord(msg) && msg["type"] === "adapter:response" && typeof msg["requestId"] === "string";
201
209
  }
202
210
  function serialize(value) {
203
211
  const seen = /* @__PURE__ */ new WeakSet();
@@ -297,7 +305,7 @@ function deserialize(value) {
297
305
  error.stack = obj.stack;
298
306
  }
299
307
  if (obj.code !== void 0) {
300
- error.code = obj.code;
308
+ Object.assign(error, { code: obj.code });
301
309
  }
302
310
  return error;
303
311
  }
@@ -16068,6 +16076,9 @@ function createIPCServer(platform2) {
16068
16076
  server.start();
16069
16077
  return server;
16070
16078
  }
16079
+ function serializeError(error) {
16080
+ return serialize(error);
16081
+ }
16071
16082
  function isRetryableError2(error) {
16072
16083
  if (error instanceof TimeoutError) {
16073
16084
  return true;
@@ -16091,7 +16102,8 @@ function isRetryableError2(error) {
16091
16102
  ];
16092
16103
  return retryableCodes.includes(code);
16093
16104
  }
16094
- const status = error.status || error.statusCode;
16105
+ const e = error;
16106
+ const status = e.status ?? e.statusCode;
16095
16107
  if (status) {
16096
16108
  return status === 503 || status === 429;
16097
16109
  }
@@ -16373,7 +16385,7 @@ var init_dist3 = __esm({
16373
16385
  const call = JSON.parse(line);
16374
16386
  this.handleCall(socket, call);
16375
16387
  } catch (error) {
16376
- console.error("[UnixSocketServer] Failed to parse message:", error);
16388
+ this.platform.logger.warn("UnixSocketServer: failed to parse message", { error });
16377
16389
  }
16378
16390
  }
16379
16391
  });
@@ -16381,7 +16393,7 @@ var init_dist3 = __esm({
16381
16393
  this.clients.delete(socket);
16382
16394
  });
16383
16395
  socket.on("error", (error) => {
16384
- console.error("[UnixSocketServer] Client socket error:", error);
16396
+ this.platform.logger.warn("UnixSocketServer: client socket error", { error });
16385
16397
  this.clients.delete(socket);
16386
16398
  });
16387
16399
  }
@@ -16400,7 +16412,7 @@ var init_dist3 = __esm({
16400
16412
  return;
16401
16413
  }
16402
16414
  if (call.version !== IPC_PROTOCOL_VERSION) {
16403
- console.error("[UnixSocketServer] Protocol version mismatch:", {
16415
+ this.platform.logger.warn("UnixSocketServer: protocol version mismatch", {
16404
16416
  received: call.version,
16405
16417
  expected: IPC_PROTOCOL_VERSION,
16406
16418
  adapter: call.adapter,
@@ -16409,7 +16421,7 @@ var init_dist3 = __esm({
16409
16421
  });
16410
16422
  }
16411
16423
  if (call.context) {
16412
- console.error("[UnixSocketServer] Adapter call context:", {
16424
+ this.platform.logger.debug("UnixSocketServer: adapter call", {
16413
16425
  version: call.version,
16414
16426
  traceId: call.context.traceId,
16415
16427
  pluginId: call.context.pluginId,
@@ -16470,9 +16482,10 @@ var init_dist3 = __esm({
16470
16482
  };
16471
16483
  const message = JSON.stringify(response) + "\n";
16472
16484
  socket.write(message, "utf8");
16473
- console.error(
16474
- `[UnixSocketServer] Error handling adapter call: ${call.adapter}.${call.method}`,
16475
- error
16485
+ this.platform.logger.error(
16486
+ "UnixSocketServer: error handling adapter call",
16487
+ error instanceof Error ? error : new Error(String(error)),
16488
+ { adapter: call.adapter, method: call.method }
16476
16489
  );
16477
16490
  }
16478
16491
  }
@@ -16534,7 +16547,7 @@ var init_dist3 = __esm({
16534
16547
  fs4__namespace.unlinkSync(this.socketPath);
16535
16548
  }
16536
16549
  this.started = false;
16537
- console.error("[UnixSocketServer] Stopped listening for adapter calls");
16550
+ this.platform.logger.debug("UnixSocketServer stopped listening for adapter calls");
16538
16551
  }
16539
16552
  /**
16540
16553
  * Check if server is started.
@@ -16574,7 +16587,7 @@ var init_dist3 = __esm({
16574
16587
  }
16575
16588
  process.on("message", this.messageHandler);
16576
16589
  this.started = true;
16577
- console.error("[IPCServer] Started listening for adapter calls");
16590
+ this.platform.logger.debug("IPCServer started listening for adapter calls");
16578
16591
  }
16579
16592
  /**
16580
16593
  * Stop listening for IPC messages.
@@ -16587,7 +16600,7 @@ var init_dist3 = __esm({
16587
16600
  }
16588
16601
  process.off("message", this.messageHandler);
16589
16602
  this.started = false;
16590
- console.error("[IPCServer] Stopped listening for adapter calls");
16603
+ this.platform.logger.debug("IPCServer stopped listening for adapter calls");
16591
16604
  }
16592
16605
  /**
16593
16606
  * Handle incoming IPC message.
@@ -16599,7 +16612,7 @@ var init_dist3 = __esm({
16599
16612
  return;
16600
16613
  }
16601
16614
  if (msg.version !== IPC_PROTOCOL_VERSION) {
16602
- console.error("[IPCServer] Protocol version mismatch:", {
16615
+ this.platform.logger.warn("IPCServer: protocol version mismatch", {
16603
16616
  received: msg.version,
16604
16617
  expected: IPC_PROTOCOL_VERSION,
16605
16618
  adapter: msg.adapter,
@@ -16608,7 +16621,7 @@ var init_dist3 = __esm({
16608
16621
  });
16609
16622
  }
16610
16623
  if (msg.context) {
16611
- console.error("[IPCServer] Adapter call context:", {
16624
+ this.platform.logger.debug("IPCServer: adapter call", {
16612
16625
  version: msg.version,
16613
16626
  traceId: msg.context.traceId,
16614
16627
  pluginId: msg.context.pluginId,
@@ -16645,9 +16658,10 @@ var init_dist3 = __esm({
16645
16658
  if (process.send) {
16646
16659
  process.send(response);
16647
16660
  }
16648
- console.error(
16649
- `[IPCServer] Error handling adapter call: ${msg.adapter}.${msg.method}`,
16650
- error
16661
+ this.platform.logger.error(
16662
+ "IPCServer: error handling adapter call",
16663
+ error instanceof Error ? error : new Error(String(error)),
16664
+ { adapter: msg.adapter, method: msg.method }
16651
16665
  );
16652
16666
  }
16653
16667
  }
@@ -16738,7 +16752,7 @@ var init_dist3 = __esm({
16738
16752
  this.sendResponse({
16739
16753
  type: "adapter:response",
16740
16754
  requestId: msg.requestId,
16741
- error: serialize(permissionError)
16755
+ error: serializeError(permissionError)
16742
16756
  });
16743
16757
  return;
16744
16758
  }
@@ -16761,7 +16775,7 @@ var init_dist3 = __esm({
16761
16775
  this.sendResponse({
16762
16776
  type: "adapter:response",
16763
16777
  requestId: msg.requestId,
16764
- error: serialize(error)
16778
+ error: serializeError(error)
16765
16779
  });
16766
16780
  }
16767
16781
  }
@@ -17856,8 +17870,9 @@ Caused by: ${cause.stack}`;
17856
17870
  * }
17857
17871
  * ```
17858
17872
  */
17873
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
17859
17874
  async getConfig(productId, profileId) {
17860
- return await this.callRemote("getConfig", [productId, profileId]);
17875
+ return this.callRemote("getConfig", [productId, profileId]);
17861
17876
  }
17862
17877
  /**
17863
17878
  * Get raw kb.config.json data.
@@ -17872,8 +17887,9 @@ Caused by: ${cause.stack}`;
17872
17887
  * }
17873
17888
  * ```
17874
17889
  */
17890
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
17875
17891
  async getRawConfig() {
17876
- return await this.callRemote("getRawConfig", []);
17892
+ return this.callRemote("getRawConfig", []);
17877
17893
  }
17878
17894
  };
17879
17895
  }
@@ -17930,21 +17946,23 @@ function getLoggerMetadataFromHost(hostContext) {
17930
17946
  }
17931
17947
  }
17932
17948
  function getOrCreatePlatformContext2() {
17933
- const existing = process[PLATFORM_CONTEXT_KEY2];
17949
+ const proc = process;
17950
+ const existing = proc[PLATFORM_CONTEXT_KEY2];
17934
17951
  if (existing instanceof async_hooks.AsyncLocalStorage) {
17935
17952
  return existing;
17936
17953
  }
17937
17954
  const ctx = new async_hooks.AsyncLocalStorage();
17938
- process[PLATFORM_CONTEXT_KEY2] = ctx;
17955
+ proc[PLATFORM_CONTEXT_KEY2] = ctx;
17939
17956
  return ctx;
17940
17957
  }
17941
17958
  function getOrCreateRuntimeContext2() {
17942
- const existing = process[RUNTIME_CONTEXT_KEY2];
17959
+ const proc = process;
17960
+ const existing = proc[RUNTIME_CONTEXT_KEY2];
17943
17961
  if (existing instanceof async_hooks.AsyncLocalStorage) {
17944
17962
  return existing;
17945
17963
  }
17946
17964
  const ctx = new async_hooks.AsyncLocalStorage();
17947
- process[RUNTIME_CONTEXT_KEY2] = ctx;
17965
+ proc[RUNTIME_CONTEXT_KEY2] = ctx;
17948
17966
  return ctx;
17949
17967
  }
17950
17968
  function createExecutionMeta(options) {
@@ -19614,6 +19632,7 @@ function createPluginContextV3(options) {
19614
19632
  logger: finalLogger
19615
19633
  };
19616
19634
  const finalOutdir = `${cwd}/.kb/output`;
19635
+ const extendedPlatform = platform2;
19617
19636
  const api = createPluginAPI({
19618
19637
  pluginId: descriptor.pluginId,
19619
19638
  handlerId: descriptor.handlerId,
@@ -19626,15 +19645,14 @@ function createPluginContextV3(options) {
19626
19645
  eventEmitter,
19627
19646
  pluginInvoker,
19628
19647
  // Access workflows from platform container (if available)
19629
- // Cast to any to access workflows (exists on PlatformContainer but not in PlatformServices interface)
19630
- workflowEngine: platform2.workflows,
19648
+ workflowEngine: extendedPlatform.workflows,
19631
19649
  // Jobs/Cron use HTTP client to Workflow Service (microservices architecture)
19632
19650
  workflowServiceUrl: process.env.KB_WORKFLOW_SERVICE_URL,
19633
19651
  // Environment lifecycle goes through runtime EnvironmentManager when available.
19634
19652
  // Returns undefined on proxy/minimal platforms where these services are absent.
19635
- environmentManager: platform2.environmentManager,
19636
- workspaceManager: platform2.workspaceManager,
19637
- snapshotManager: platform2.snapshotManager,
19653
+ environmentManager: extendedPlatform.environmentManager,
19654
+ workspaceManager: extendedPlatform.workspaceManager,
19655
+ snapshotManager: extendedPlatform.snapshotManager,
19638
19656
  analytics: enrichedPlatform.analytics,
19639
19657
  eventBus: enrichedPlatform.eventBus,
19640
19658
  logger: enrichedPlatform.logger,
@@ -20167,20 +20185,20 @@ function createDefaultIPCServerFactory() {
20167
20185
  return async (platform2, executionId) => {
20168
20186
  const platformContainer = ensurePlatformContainer(platform2);
20169
20187
  if (process.platform === "win32") {
20170
- const { UnixSocketServer: UnixSocketServer3, createSocketPath: createSocketPath2 } = await Promise.resolve().then(() => (init_dist3(), dist_exports2));
20188
+ const { UnixSocketServer: UnixSocketServer22, createSocketPath: createSocketPath2 } = await Promise.resolve().then(() => (init_dist3(), dist_exports2));
20171
20189
  const socketPath = createSocketPath2(`subprocess-${executionId}`);
20172
20190
  const authToken = crypto.randomBytes(32).toString("hex");
20173
20191
  const serverConfig = { socketPath };
20174
20192
  serverConfig.authToken = authToken;
20175
- const server = new UnixSocketServer3(platformContainer, serverConfig);
20193
+ const server = new UnixSocketServer22(platformContainer, serverConfig);
20176
20194
  return new UnixSocketIPCServer(server, socketPath, authToken);
20177
20195
  } else {
20178
- const { UnixSocketServer: UnixSocketServer3, createSocketPath: createSocketPath2 } = await Promise.resolve().then(() => (init_dist3(), dist_exports2));
20196
+ const { UnixSocketServer: UnixSocketServer22, createSocketPath: createSocketPath2 } = await Promise.resolve().then(() => (init_dist3(), dist_exports2));
20179
20197
  const socketPath = createSocketPath2(`subprocess-${executionId}`);
20180
20198
  const authToken = crypto.randomBytes(32).toString("hex");
20181
20199
  const serverConfig = { socketPath };
20182
20200
  serverConfig.authToken = authToken;
20183
- const server = new UnixSocketServer3(platformContainer, serverConfig);
20201
+ const server = new UnixSocketServer22(platformContainer, serverConfig);
20184
20202
  return new UnixSocketIPCServer(server, socketPath, authToken);
20185
20203
  }
20186
20204
  };
@@ -20364,7 +20382,7 @@ function buildRoutingBackend(localBackend, remoteFactory, provisionEnvironment,
20364
20382
  shutdown: async () => localBackend.shutdown()
20365
20383
  };
20366
20384
  }
20367
- var LocalWorkspaceManager, localWorkspaceManager, KNOWN_ERROR_CODES, ExecutionLayerError, TimeoutError3, AbortError2, HandlerContractError, HandlerNotFoundError, WorkspaceError, PermissionDeniedError, ValidationError, QueueFullError, AcquireTimeoutError, WorkerCrashedError, WorkerUnhealthyError, InProcessBackend, UnixSocketIPCServer, SubprocessBackend, IPCPlatformTransportFactory, PoolStatsTracker, DEFAULT_STARTUP_TIMEOUT, DEFAULT_HEALTH_CHECK_TIMEOUT, Worker, PoolLifecycleManager, PoolQueueManager, PoolExecutor, WorkerPool, __dirname$1, WorkerPoolBackend, RemoteBackend, SubprocessRunnerAdapter, PROTOCOL_VERSION, DEFAULT_WORKER_POOL_CONFIG;
20385
+ var LocalWorkspaceManager, localWorkspaceManager, KNOWN_ERROR_CODES, ExecutionLayerError, TimeoutError3, AbortError2, HandlerContractError, HandlerNotFoundError, WorkspaceError, PermissionDeniedError, ValidationError, QueueFullError, AcquireTimeoutError, WorkerCrashedError, WorkerUnhealthyError, InProcessBackend, UnixSocketIPCServer, SubprocessBackend, UnixSocketPlatformTransportFactory, PoolStatsTracker, DEFAULT_STARTUP_TIMEOUT, DEFAULT_HEALTH_CHECK_TIMEOUT, Worker, PoolLifecycleManager, PoolQueueManager, PoolExecutor, WorkerPool, __dirname$1, WorkerPoolBackend, RemoteBackend, SubprocessRunnerAdapter, PROTOCOL_VERSION, DEFAULT_WORKER_POOL_CONFIG, IPCPlatformTransportFactory;
20368
20386
  var init_dist5 = __esm({
20369
20387
  "../../../core/plugin-execution-factory/dist/index.js"() {
20370
20388
  init_dist();
@@ -20927,13 +20945,55 @@ var init_dist5 = __esm({
20927
20945
  this.activeServers.clear();
20928
20946
  }
20929
20947
  };
20930
- IPCPlatformTransportFactory = class {
20931
- type = "ipc";
20932
- createServer(platform2, child) {
20933
- const server = new ChildIPCServer(platform2, child);
20948
+ UnixSocketPlatformTransportFactory = class {
20949
+ type = "unix-socket";
20950
+ server = null;
20951
+ socketPath;
20952
+ constructor() {
20953
+ const id = `pool-${process.pid}-${crypto.randomBytes(4).toString("hex")}`;
20954
+ this.socketPath = createSocketPath(id);
20955
+ }
20956
+ /**
20957
+ * Start the shared Unix socket server.
20958
+ * Must be called once before the first worker is spawned.
20959
+ */
20960
+ async init(platform2) {
20961
+ if (this.server) {
20962
+ return;
20963
+ }
20964
+ this.server = new UnixSocketServer(platform2, { socketPath: this.socketPath });
20965
+ await this.server.start();
20966
+ }
20967
+ /**
20968
+ * Stop the shared server and remove the socket file.
20969
+ * Should be called when the backend shuts down.
20970
+ */
20971
+ async dispose() {
20972
+ if (this.server) {
20973
+ await this.server.close();
20974
+ this.server = null;
20975
+ }
20976
+ }
20977
+ /**
20978
+ * Pass the socket path to each worker process via env.
20979
+ * worker-script.ts reads KB_PLATFORM_SOCKET_PATH when
20980
+ * KB_PLATFORM_TRANSPORT === 'unix-socket'.
20981
+ */
20982
+ getChildEnv() {
20934
20983
  return {
20935
- start: () => server.start(),
20936
- stop: () => server.stop()
20984
+ KB_PLATFORM_SOCKET_PATH: this.socketPath
20985
+ };
20986
+ }
20987
+ /**
20988
+ * No per-worker server needed — all workers share the single socket server
20989
+ * started in init(). Returns a noop PlatformTransportServer.
20990
+ */
20991
+ createServer(_platform, _child) {
20992
+ return {
20993
+ start: () => {
20994
+ },
20995
+ stop: () => {
20996
+ }
20937
20997
  };
20938
20998
  }
20939
20999
  };
@@ -21302,7 +21362,7 @@ var init_dist5 = __esm({
21302
21362
  const pending = this.pendingRequests.get(msg.requestId);
21303
21363
  if (pending) {
21304
21364
  const error = new Error(msg.error.message);
21305
- error.code = msg.error.code;
21365
+ Object.assign(error, { code: msg.error.code });
21306
21366
  error.stack = msg.error.stack;
21307
21367
  pending.reject(error);
21308
21368
  }
@@ -21873,7 +21933,7 @@ var init_dist5 = __esm({
21873
21933
  executionTimes = [];
21874
21934
  constructor(options) {
21875
21935
  this.platform = options.platform;
21876
- this.platformTransport = options.platformTransport ?? new IPCPlatformTransportFactory();
21936
+ this.platformTransport = options.platformTransport ?? new UnixSocketPlatformTransportFactory();
21877
21937
  this.uiProvider = options.uiProvider ?? (() => noopUI);
21878
21938
  this.workerScript = options.workerScript ?? path5__namespace.join(__dirname$1, "backends", "worker-pool", "worker-script.js");
21879
21939
  this.config = {
@@ -21899,6 +21959,11 @@ var init_dist5 = __esm({
21899
21959
  if (this.pool) {
21900
21960
  return;
21901
21961
  }
21962
+ if ("init" in this.platformTransport) {
21963
+ const transport = this.platformTransport;
21964
+ await transport.init(this.platform);
21965
+ this.platform.logger.debug("Platform transport initialized", { type: this.platformTransport.type });
21966
+ }
21902
21967
  this.pool = new WorkerPool(this.workerScript, this.config, this.platform, this.platformTransport);
21903
21968
  this.pool.on("workerSpawned", (worker) => {
21904
21969
  this.platform.logger.debug("Worker spawned", { workerId: worker.id });
@@ -22033,6 +22098,11 @@ var init_dist5 = __esm({
22033
22098
  await this.pool.shutdown();
22034
22099
  this.pool = null;
22035
22100
  }
22101
+ if ("dispose" in this.platformTransport) {
22102
+ const transport = this.platformTransport;
22103
+ await transport.dispose();
22104
+ this.platform.logger.debug("Platform transport disposed", { type: this.platformTransport.type });
22105
+ }
22036
22106
  }
22037
22107
  /**
22038
22108
  * Track execution time for statistics.
@@ -22168,6 +22238,16 @@ var init_dist5 = __esm({
22168
22238
  maxHandlers: 20
22169
22239
  }
22170
22240
  };
22241
+ IPCPlatformTransportFactory = class {
22242
+ type = "ipc";
22243
+ createServer(platform2, child) {
22244
+ const server = new ChildIPCServer(platform2, child);
22245
+ return {
22246
+ start: () => server.start(),
22247
+ stop: () => server.stop()
22248
+ };
22249
+ }
22250
+ };
22171
22251
  }
22172
22252
  });
22173
22253
 
@@ -31612,7 +31692,7 @@ var require_error_handler = __commonJS({
31612
31692
  FST_ERR_FAILED_ERROR_SERIALIZATION
31613
31693
  } = require_errors4();
31614
31694
  var { getSchemaSerializer } = require_schemas();
31615
- var serializeError = require_error_serializer();
31695
+ var serializeError2 = require_error_serializer();
31616
31696
  var rootErrorHandler = {
31617
31697
  func: defaultErrorHandler,
31618
31698
  toJSON() {
@@ -31690,7 +31770,7 @@ var require_error_handler = __commonJS({
31690
31770
  try {
31691
31771
  const serializerFn = getSchemaSerializer(reply[kRouteContext], statusCode, reply[kReplyHeaders]["content-type"]);
31692
31772
  if (serializerFn === false) {
31693
- payload = serializeError({
31773
+ payload = serializeError2({
31694
31774
  error: statusCodes[statusCode + ""],
31695
31775
  code: error.code,
31696
31776
  message: error.message,
@@ -31708,10 +31788,10 @@ var require_error_handler = __commonJS({
31708
31788
  reply.log.error({ err, statusCode: res.statusCode }, "The serializer for the given status code failed");
31709
31789
  }
31710
31790
  reply.code(500);
31711
- payload = serializeError(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error.message));
31791
+ payload = serializeError2(new FST_ERR_FAILED_ERROR_SERIALIZATION(err.message, error.message));
31712
31792
  }
31713
31793
  if (typeof payload !== "string" && !Buffer.isBuffer(payload)) {
31714
- payload = serializeError(new FST_ERR_REP_INVALID_PAYLOAD_TYPE(typeof payload));
31794
+ payload = serializeError2(new FST_ERR_REP_INVALID_PAYLOAD_TYPE(typeof payload));
31715
31795
  }
31716
31796
  reply[kReplyHeaders]["content-length"] = "" + Buffer.byteLength(payload);
31717
31797
  cb(reply, payload);
@@ -70764,15 +70844,16 @@ function mergeDefined(base, over) {
70764
70844
  return [...base, ...over.filter((v) => v !== void 0)];
70765
70845
  }
70766
70846
  if (isPlainObject(base) && isPlainObject(over)) {
70767
- const out = { ...base };
70847
+ const baseObj = base;
70848
+ const out = { ...baseObj };
70768
70849
  for (const [k, v] of Object.entries(over)) {
70769
70850
  if (v === void 0) {
70770
70851
  continue;
70771
70852
  }
70772
- if (isPlainObject(base[k]) && isPlainObject(v)) {
70773
- out[k] = mergeDefined(base[k], v);
70774
- } else if (Array.isArray(base[k]) && Array.isArray(v)) {
70775
- out[k] = mergeDefined(base[k], v);
70853
+ if (isPlainObject(baseObj[k]) && isPlainObject(v)) {
70854
+ out[k] = mergeDefined(baseObj[k], v);
70855
+ } else if (Array.isArray(baseObj[k]) && Array.isArray(v)) {
70856
+ out[k] = mergeDefined(baseObj[k], v);
70776
70857
  } else {
70777
70858
  out[k] = v;
70778
70859
  }
@@ -72717,7 +72798,7 @@ var init_config_proxy = __esm3({
72717
72798
  * ```
72718
72799
  */
72719
72800
  async getConfig(productId, profileId) {
72720
- return await this.callRemote("getConfig", [productId, profileId]);
72801
+ return this.callRemote("getConfig", [productId, profileId]);
72721
72802
  }
72722
72803
  /**
72723
72804
  * Get raw kb.config.json data.
@@ -72733,7 +72814,7 @@ var init_config_proxy = __esm3({
72733
72814
  * ```
72734
72815
  */
72735
72816
  async getRawConfig() {
72736
- return await this.callRemote("getRawConfig", []);
72817
+ return this.callRemote("getRawConfig", []);
72737
72818
  }
72738
72819
  };
72739
72820
  }
@@ -73038,7 +73119,8 @@ var init_config_adapter = __esm3({
73038
73119
  }
73039
73120
  const effectiveProfileId = profileId ?? process.env.KB_PROFILE ?? "default";
73040
73121
  if (rawConfig.profiles && Array.isArray(rawConfig.profiles)) {
73041
- const profile = rawConfig.profiles.find((p) => p.id === effectiveProfileId) ?? rawConfig.profiles[0];
73122
+ const profiles = rawConfig.profiles;
73123
+ const profile = profiles.find((p) => p.id === effectiveProfileId) ?? profiles[0];
73042
73124
  if (profile?.products?.[productId]) {
73043
73125
  return profile.products[productId];
73044
73126
  }
@@ -73603,10 +73685,12 @@ var AdapterLoader = class {
73603
73685
  if (!target) {
73604
73686
  return `target adapter "${targetName}" not found`;
73605
73687
  }
73606
- if (typeof target[hook] !== "function") {
73688
+ const targetObj = target;
73689
+ const instanceObj = instance;
73690
+ if (typeof targetObj[hook] !== "function") {
73607
73691
  return `target "${targetName}" has no method "${hook}"`;
73608
73692
  }
73609
- if (typeof instance[method] !== "function") {
73693
+ if (typeof instanceObj[method] !== "function") {
73610
73694
  return `extension has no method "${method}"`;
73611
73695
  }
73612
73696
  return null;
@@ -73651,8 +73735,10 @@ var AdapterLoader = class {
73651
73735
  continue;
73652
73736
  }
73653
73737
  try {
73654
- const extensionMethod = ext.instance[method].bind(ext.instance);
73655
- target[hook](extensionMethod);
73738
+ const instanceObj = ext.instance;
73739
+ const targetObj = target;
73740
+ const extensionMethod = instanceObj[method].bind(ext.instance);
73741
+ targetObj[hook](extensionMethod);
73656
73742
  if (process.env.DEBUG || process.env.KB_LOG_LEVEL === "debug") {
73657
73743
  process.stderr.write(
73658
73744
  `[AdapterLoader] Connected extension "${ext.name}" to "${targetName}.${hook}" (priority: ${ext.priority})
@@ -75659,7 +75745,7 @@ function initializeResourceBroker(container, config = {}) {
75659
75745
  }
75660
75746
  return broker;
75661
75747
  }
75662
- async function initPlatform(config = {}, cwd = process.cwd(), uiProvider) {
75748
+ async function initPlatform(config = {}, cwd = process.cwd(), uiProvider, platformRoot) {
75663
75749
  platform.logger.debug(`initPlatform isInitialized=${platform.isInitialized} pid=${process.pid}`);
75664
75750
  if (platform.isInitialized) {
75665
75751
  platform.logger.debug(`initPlatform returning existing platform pid=${process.pid}`);
@@ -75740,7 +75826,7 @@ async function initPlatform(config = {}, cwd = process.cwd(), uiProvider) {
75740
75826
  const loadModule = async (modulePath) => {
75741
75827
  try {
75742
75828
  const { discoverAdapters: discoverAdapters2 } = await Promise.resolve().then(() => (init_discover_adapters(), discover_adapters_exports));
75743
- const discovered = await discoverAdapters2(cwd);
75829
+ const discovered = await discoverAdapters2(platformRoot ?? cwd);
75744
75830
  const basePkgName = modulePath.split("/").slice(0, 2).join("/");
75745
75831
  const subpath = modulePath.includes("/") && modulePath.split("/").length > 2 ? modulePath.split("/").slice(2).join("/") : null;
75746
75832
  const adapter = discovered.get(basePkgName);
@@ -75890,7 +75976,7 @@ async function initPlatform(config = {}, cwd = process.cwd(), uiProvider) {
75890
75976
  const wrapperName = wrappedInstance.constructor?.name ?? "Unknown";
75891
75977
  const isWrapped = wrapperName.startsWith("Analytics");
75892
75978
  platform.logger.debug(
75893
- `initPlatform loaded adapter: ${name} \u2192 ${instance.constructor.name}${isWrapped ? ` (wrapped with ${wrapperName})` : ""}`
75979
+ `initPlatform loaded adapter: ${name} \u2192 ${Object.getPrototypeOf(instance)?.constructor?.name ?? "Unknown"}${isWrapped ? ` (wrapped with ${wrapperName})` : ""}`
75894
75980
  );
75895
75981
  }
75896
75982
  const graph = await loader.buildDependencyGraph(adapterConfigs, loadModule);
@@ -76533,7 +76619,12 @@ async function createServiceBootstrap(options) {
76533
76619
  }
76534
76620
  _platformRoot = platformRoot;
76535
76621
  _projectRoot = projectRoot;
76536
- await initPlatform(platformConfig, projectRoot);
76622
+ await initPlatform(
76623
+ platformConfig,
76624
+ projectRoot,
76625
+ void 0,
76626
+ platformRoot !== projectRoot ? platformRoot : void 0
76627
+ );
76537
76628
  _initialized = true;
76538
76629
  const hasConfig = !!sources.platformDefaults || !!sources.projectConfig;
76539
76630
  if (!hasConfig) {