@okxweb3/a2a-node 0.2.18 → 0.2.19-beta-fe6942ad54-261125201445

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.
Files changed (3) hide show
  1. package/dist/cli.js +1607 -225
  2. package/dist/index.js +1478 -120
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -114,7 +114,8 @@ function resolveTaskPaths(homeDir = resolveTaskHome()) {
114
114
  completedCommandsDir: (0, import_node_path2.join)(homeDir, "commands", "completed"),
115
115
  pidPath: (0, import_node_path2.join)(homeDir, "run", "listener.pid"),
116
116
  daemonLockPath: (0, import_node_path2.join)(homeDir, "run", "daemon.lock"),
117
- listenerLogPath: (0, import_node_path2.join)(homeDir, "logs", "listener.log")
117
+ listenerLogPath: (0, import_node_path2.join)(homeDir, "logs", "listener.log"),
118
+ devkitServerDbPath: (0, import_node_path2.join)(homeDir, "sqlite", DEVKIT_SERVER_DB_NAME)
118
119
  };
119
120
  }
120
121
  function ensureTaskHome(homeDir) {
@@ -126,13 +127,14 @@ function encodeJobIdForFile(jobId) {
126
127
  function ensureTaskDir(dir) {
127
128
  return ensureA2aTaskDir(dir);
128
129
  }
129
- var import_node_path2, BACKUP_JOB_ID;
130
+ var import_node_path2, BACKUP_JOB_ID, DEVKIT_SERVER_DB_NAME;
130
131
  var init_paths = __esm({
131
132
  "src/paths.ts"() {
132
133
  "use strict";
133
134
  import_node_path2 = require("node:path");
134
135
  init_a2a_paths();
135
136
  BACKUP_JOB_ID = "backup";
137
+ DEVKIT_SERVER_DB_NAME = "devkit-server.sqlite";
136
138
  }
137
139
  });
138
140
 
@@ -495,7 +497,7 @@ function normalizeGatewayRouteChatType(explicit, parsed, threadId) {
495
497
  }
496
498
  function matchingGatewayRouteFromSessionKey(sessionKey, expected, provider) {
497
499
  const parsed = parseGatewayRouteSessionKey(sessionKey, provider);
498
- if (!parsed || parsed.platform !== expected.platform || parsed.chatId !== expected.chatId) {
500
+ if (parsed?.platform !== expected.platform || parsed.chatId !== expected.chatId) {
499
501
  return null;
500
502
  }
501
503
  return {
@@ -1765,7 +1767,7 @@ async function readDaemonLock(lockPath) {
1765
1767
  async function markDaemonReady(lockPath) {
1766
1768
  const current = await readDaemonLock(lockPath);
1767
1769
  const metadata = current.metadata;
1768
- if (!metadata || metadata.pid !== process.pid) {
1770
+ if (metadata?.pid !== process.pid) {
1769
1771
  return;
1770
1772
  }
1771
1773
  await (0, import_promises.writeFile)(ownerPath(lockPath), `${JSON.stringify({
@@ -2219,7 +2221,7 @@ async function installWindowsAutostart() {
2219
2221
  taskHome: taskPaths.homeDir,
2220
2222
  ...pathValue ? { pathValue } : {}
2221
2223
  });
2222
- await (0, import_promises2.writeFile)(paths.vbsPath, "\uFEFF" + vbsContent, "utf16le");
2224
+ await (0, import_promises2.writeFile)(paths.vbsPath, `\uFEFF${vbsContent}`, "utf16le");
2223
2225
  logWinCompat(
2224
2226
  `${WIN_COMPAT_LOG_PREFIX} autostart install: wrote vbs=${paths.vbsPath} node=${execPath} cli=${cliPath} taskHome=${taskPaths.homeDir}`
2225
2227
  );
@@ -3378,12 +3380,11 @@ async function ensureAiWorkspace(paths) {
3378
3380
  }
3379
3381
  async function waitForImmediateExit(child, timeoutMs) {
3380
3382
  return await new Promise((resolve11) => {
3381
- let timer;
3382
3383
  const onExit = () => {
3383
3384
  clearTimeout(timer);
3384
3385
  resolve11(true);
3385
3386
  };
3386
- timer = setTimeout(() => {
3387
+ const timer = setTimeout(() => {
3387
3388
  child.off("exit", onExit);
3388
3389
  resolve11(false);
3389
3390
  }, timeoutMs);
@@ -19378,7 +19379,25 @@ var init_events = __esm({
19378
19379
  XMTP_DEBUG_SYNC_FAILED: "XMTP debug sync failed",
19379
19380
  // Underlying XMTP SDK client close failed during recycle/removal/shutdown
19380
19381
  // (DEXMARKET-9116). Error-level → NOT added to SENTRY_INFO_ALLOWLIST.
19381
- XMTP_CLIENT_CLOSE_FAILED: "XMTP client close failed"
19382
+ XMTP_CLIENT_CLOSE_FAILED: "XMTP client close failed",
19383
+ // ── devkit custom-server registry + delivery (DEXMARKET-9165) ──────────────
19384
+ // info-level (registered in SENTRY_INFO_ALLOWLIST below):
19385
+ DEVKIT_REGISTER_REQUESTED: "Devkit register requested",
19386
+ DEVKIT_REGISTER_COMPLETED: "Devkit register completed",
19387
+ DEVKIT_UNREGISTER_REQUESTED: "Devkit unregister requested",
19388
+ DEVKIT_UNREGISTER_COMPLETED: "Devkit unregister completed",
19389
+ DEVKIT_DAEMON_STATUS_UNKNOWN: "Devkit daemon status unknown",
19390
+ DEVKIT_ROUTE_DEFAULT_AI: "Devkit route default AI",
19391
+ DEVKIT_ROUTE_CUSTOM_SERVER: "Devkit route custom server",
19392
+ DEVKIT_DELIVERY_ACCEPTED: "Devkit delivery accepted",
19393
+ DEVKIT_DELIVERY_HTTP_ACCEPTED: "Devkit delivery http accepted",
19394
+ DEVKIT_DELIVERY_DROPPED: "Devkit delivery dropped",
19395
+ DEVKIT_DELIVERY_CANCELLED: "Devkit delivery cancelled",
19396
+ // error-level (NOT allowlisted — logger.error):
19397
+ DEVKIT_REGISTER_REJECTED: "Devkit register rejected",
19398
+ DEVKIT_CONFIG_PERSIST_FAILED: "Devkit config persist failed",
19399
+ DEVKIT_ROUTE_CONFIG_READ_FAILED: "Devkit route config read failed",
19400
+ DEVKIT_DELIVERY_HTTP_FAILED: "Devkit delivery http failed"
19382
19401
  };
19383
19402
  }
19384
19403
  });
@@ -20229,7 +20248,20 @@ var init_sentry_logger = __esm({
20229
20248
  LogEvent.XMTP_RATE_LIMIT_COOLDOWN_STARTED,
20230
20249
  LogEvent.XMTP_RATE_LIMIT_CREATE_SUPPRESSED,
20231
20250
  LogEvent.XMTP_RATE_LIMIT_PROBE,
20232
- LogEvent.XMTP_RATE_LIMIT_RECOVERED
20251
+ LogEvent.XMTP_RATE_LIMIT_RECOVERED,
20252
+ // devkit custom-server registry + delivery info checkpoints (DEXMARKET-9165).
20253
+ // info() drops any event not listed here, so these must stay registered.
20254
+ LogEvent.DEVKIT_REGISTER_REQUESTED,
20255
+ LogEvent.DEVKIT_REGISTER_COMPLETED,
20256
+ LogEvent.DEVKIT_UNREGISTER_REQUESTED,
20257
+ LogEvent.DEVKIT_UNREGISTER_COMPLETED,
20258
+ LogEvent.DEVKIT_DAEMON_STATUS_UNKNOWN,
20259
+ LogEvent.DEVKIT_ROUTE_DEFAULT_AI,
20260
+ LogEvent.DEVKIT_ROUTE_CUSTOM_SERVER,
20261
+ LogEvent.DEVKIT_DELIVERY_ACCEPTED,
20262
+ LogEvent.DEVKIT_DELIVERY_HTTP_ACCEPTED,
20263
+ LogEvent.DEVKIT_DELIVERY_DROPPED,
20264
+ LogEvent.DEVKIT_DELIVERY_CANCELLED
20233
20265
  ]);
20234
20266
  MAX_EXTRA_STRING_LENGTH = 256;
20235
20267
  MAX_TAG_VALUE_LENGTH = 128;
@@ -32465,7 +32497,7 @@ var init_sentry_config = __esm({
32465
32497
  environment = process.env.SENTRY_ENV === "dev" ? "dev" : "prod";
32466
32498
  SENTRY_CONFIG = {
32467
32499
  projectName: "okx/openclaw-okx-a2a-extension",
32468
- release: "0.2.18",
32500
+ release: "0.2.19-beta-fe6942ad54-261125201445",
32469
32501
  environment,
32470
32502
  runtimeContainer: normalizeRuntimeContainer(process.env.OKX_A2A_RUNTIME_CONTAINER)
32471
32503
  };
@@ -32499,7 +32531,7 @@ function isPostjectRunnable() {
32499
32531
  function resolvePostjectCommand() {
32500
32532
  try {
32501
32533
  const cliPath = (0, import_node_module.createRequire)(__filename).resolve("postject/dist/cli.js");
32502
- if ((0, import_node_fs21.existsSync)(cliPath)) {
32534
+ if ((0, import_node_fs22.existsSync)(cliPath)) {
32503
32535
  return { command: process.execPath, prefixArgs: [cliPath] };
32504
32536
  }
32505
32537
  } catch {
@@ -32570,26 +32602,26 @@ function buildSeaConfig(entryPath, blobPath) {
32570
32602
  }
32571
32603
  async function installWindowsNativeLauncher(options) {
32572
32604
  const nodeExe = options.nodeExe ?? process.execPath;
32573
- if (!(0, import_node_fs21.existsSync)(options.cliPath)) {
32605
+ if (!(0, import_node_fs22.existsSync)(options.cliPath)) {
32574
32606
  throw new Error(`cannot build okx-a2a.exe: CLI entry not found at ${options.cliPath}`);
32575
32607
  }
32576
- if (!(0, import_node_fs21.existsSync)(nodeExe)) {
32608
+ if (!(0, import_node_fs22.existsSync)(nodeExe)) {
32577
32609
  throw new Error(`cannot build okx-a2a.exe: node executable not found at ${nodeExe}`);
32578
32610
  }
32579
32611
  const exePath = (0, import_node_path28.join)(options.targetDir, NATIVE_LAUNCHER_EXE_NAME);
32580
- (0, import_node_fs21.mkdirSync)(options.targetDir, { recursive: true });
32581
- const work = (0, import_node_fs21.mkdtempSync)((0, import_node_path28.join)((0, import_node_os9.tmpdir)(), "okx-a2a-sea-"));
32612
+ (0, import_node_fs22.mkdirSync)(options.targetDir, { recursive: true });
32613
+ const work = (0, import_node_fs22.mkdtempSync)((0, import_node_path28.join)((0, import_node_os9.tmpdir)(), "okx-a2a-sea-"));
32582
32614
  try {
32583
32615
  const entryPath = (0, import_node_path28.join)(work, "launcher-entry.js");
32584
32616
  const blobPath = (0, import_node_path28.join)(work, "okx-a2a.blob");
32585
32617
  const configPath = (0, import_node_path28.join)(work, "sea-config.json");
32586
- (0, import_node_fs21.writeFileSync)(entryPath, buildLauncherEntryJs(options.cliPath), "utf8");
32587
- (0, import_node_fs21.writeFileSync)(configPath, buildSeaConfig(entryPath, blobPath), "utf8");
32618
+ (0, import_node_fs22.writeFileSync)(entryPath, buildLauncherEntryJs(options.cliPath), "utf8");
32619
+ (0, import_node_fs22.writeFileSync)(configPath, buildSeaConfig(entryPath, blobPath), "utf8");
32588
32620
  (0, import_node_child_process7.execFileSync)(nodeExe, ["--experimental-sea-config", configPath], {
32589
32621
  stdio: "ignore",
32590
32622
  windowsHide: true
32591
32623
  });
32592
- (0, import_node_fs21.copyFileSync)(nodeExe, exePath);
32624
+ (0, import_node_fs22.copyFileSync)(nodeExe, exePath);
32593
32625
  const isMac = process.platform === "darwin";
32594
32626
  if (isMac) {
32595
32627
  try {
@@ -32609,10 +32641,10 @@ async function installWindowsNativeLauncher(options) {
32609
32641
  );
32610
32642
  return { exePath, cliPath: options.cliPath, nodeExe };
32611
32643
  } finally {
32612
- (0, import_node_fs21.rmSync)(work, { recursive: true, force: true });
32644
+ (0, import_node_fs22.rmSync)(work, { recursive: true, force: true });
32613
32645
  }
32614
32646
  }
32615
- function findWindowsNativeOkxA2aExe(pathValue, appData, userProfile, fileExists2 = import_node_fs21.existsSync) {
32647
+ function findWindowsNativeOkxA2aExe(pathValue, appData, userProfile, fileExists2 = import_node_fs22.existsSync) {
32616
32648
  const dirs = pathValue.split(";").map((d) => d.trim()).filter(Boolean);
32617
32649
  if (appData) {
32618
32650
  dirs.push((0, import_node_path28.join)(appData, "npm"));
@@ -32630,11 +32662,11 @@ function findWindowsNativeOkxA2aExe(pathValue, appData, userProfile, fileExists2
32630
32662
  }
32631
32663
  function resolveRunningCliPath() {
32632
32664
  const fromArgv = process.argv[1];
32633
- if (fromArgv && /(?:^|[\\/])cli\.js$/.test(fromArgv) && (0, import_node_fs21.existsSync)(fromArgv)) {
32665
+ if (fromArgv && /(?:^|[\\/])cli\.js$/.test(fromArgv) && (0, import_node_fs22.existsSync)(fromArgv)) {
32634
32666
  return fromArgv;
32635
32667
  }
32636
32668
  const beside = (0, import_node_path28.join)(__dirname, "cli.js");
32637
- if ((0, import_node_fs21.existsSync)(beside)) {
32669
+ if ((0, import_node_fs22.existsSync)(beside)) {
32638
32670
  return beside;
32639
32671
  }
32640
32672
  if (fromArgv) {
@@ -32656,12 +32688,12 @@ async function ensureWindowsNativeLauncher(options = {}) {
32656
32688
  const result = await installWindowsNativeLauncher({ cliPath: resolveRunningCliPath(), targetDir });
32657
32689
  return { exePath: result.exePath, installed: true };
32658
32690
  }
32659
- var import_node_child_process7, import_node_fs21, import_node_module, import_node_os9, import_node_path28, SEA_SENTINEL_FUSE, NATIVE_LAUNCHER_EXE_NAME, POSTJECT_SPEC, POSTJECT_BIN;
32691
+ var import_node_child_process7, import_node_fs22, import_node_module, import_node_os9, import_node_path28, SEA_SENTINEL_FUSE, NATIVE_LAUNCHER_EXE_NAME, POSTJECT_SPEC, POSTJECT_BIN;
32660
32692
  var init_win_native_launcher = __esm({
32661
32693
  "src/win-native-launcher.ts"() {
32662
32694
  "use strict";
32663
32695
  import_node_child_process7 = require("node:child_process");
32664
- import_node_fs21 = require("node:fs");
32696
+ import_node_fs22 = require("node:fs");
32665
32697
  import_node_module = require("node:module");
32666
32698
  import_node_os9 = require("node:os");
32667
32699
  import_node_path28 = require("node:path");
@@ -32803,7 +32835,7 @@ function buildProviderMismatchWarning(target, provider) {
32803
32835
  ].join("\n");
32804
32836
  }
32805
32837
  async function handleUpdateCommand(args) {
32806
- if (args.some(isHelpArg)) {
32838
+ if (args.some(isHelpArg2)) {
32807
32839
  printUpdateUsage();
32808
32840
  return;
32809
32841
  }
@@ -32844,7 +32876,7 @@ function resolveUpdateTarget(target) {
32844
32876
  return detectGatewayInvocation() ?? "node";
32845
32877
  }
32846
32878
  async function handleSetupCommand(args) {
32847
- if (args.some(isHelpArg)) {
32879
+ if (args.some(isHelpArg2)) {
32848
32880
  printSetupUsage();
32849
32881
  return;
32850
32882
  }
@@ -33421,7 +33453,7 @@ async function getCurrentNodeCliVersion() {
33421
33453
  return await getGlobalNpmPackageVersion(UPDATE_PACKAGES.node) ?? getBundledNodeCliVersion();
33422
33454
  }
33423
33455
  function getBundledNodeCliVersion() {
33424
- return true ? "0.2.18" : null;
33456
+ return true ? "0.2.19-beta-fe6942ad54-261125201445" : null;
33425
33457
  }
33426
33458
  function readConfiguredAiProvider() {
33427
33459
  const explicit = process.env.OKX_A2A_AI_PROVIDER || process.env.OKX_AGENT_TASK_AI_CLI;
@@ -33606,7 +33638,7 @@ async function updateHermes(release, options) {
33606
33638
  assertNotRunningInsideGateway("hermes");
33607
33639
  }
33608
33640
  const spec = buildNpmPackageSpec("hermes", release);
33609
- const workDir = await (0, import_promises11.mkdtemp)((0, import_node_path29.join)((0, import_node_os10.tmpdir)(), `okx-a2a-${label}-hermes-`));
33641
+ const workDir = await (0, import_promises12.mkdtemp)((0, import_node_path29.join)((0, import_node_os10.tmpdir)(), `okx-a2a-${label}-hermes-`));
33610
33642
  try {
33611
33643
  console.log(`[${label}] downloading ${spec}`);
33612
33644
  const npmTarball = await npmPack(spec, workDir);
@@ -33627,11 +33659,11 @@ async function updateHermes(release, options) {
33627
33659
  }
33628
33660
  console.log(`[${label}] hermes ${label} done`);
33629
33661
  } finally {
33630
- await (0, import_promises11.rm)(workDir, { recursive: true, force: true });
33662
+ await (0, import_promises12.rm)(workDir, { recursive: true, force: true });
33631
33663
  }
33632
33664
  }
33633
33665
  async function installGatewayPluginForDoctor(target) {
33634
- const release = isPrereleaseVersion("0.2.18") ? "beta" : "latest";
33666
+ const release = isPrereleaseVersion("0.2.19-beta-fe6942ad54-261125201445") ? "beta" : "latest";
33635
33667
  const insideTargetGateway = detectGatewayInvocation() === target;
33636
33668
  const options = {
33637
33669
  restart: !insideTargetGateway,
@@ -33658,7 +33690,7 @@ function setupReadyMessage(target) {
33658
33690
  async function normalizeHermesOkxA2aPluginConfig(configFile = resolveHermesConfigPath()) {
33659
33691
  let content;
33660
33692
  try {
33661
- content = await (0, import_promises11.readFile)(configFile, "utf8");
33693
+ content = await (0, import_promises12.readFile)(configFile, "utf8");
33662
33694
  } catch (error) {
33663
33695
  if (isNodeError(error) && error.code === "ENOENT") {
33664
33696
  return false;
@@ -33669,21 +33701,21 @@ async function normalizeHermesOkxA2aPluginConfig(configFile = resolveHermesConfi
33669
33701
  if (!normalized.changed) {
33670
33702
  return false;
33671
33703
  }
33672
- await (0, import_promises11.writeFile)(configFile, normalized.content);
33704
+ await (0, import_promises12.writeFile)(configFile, normalized.content);
33673
33705
  console.log(`[update] normalized Hermes plugins.enabled okx-a2a entry in ${configFile}`);
33674
33706
  return true;
33675
33707
  }
33676
33708
  async function ensureHermesOkxA2aPluginConfig(configFile = resolveHermesConfigPath(), options = {}) {
33677
33709
  let content;
33678
33710
  try {
33679
- content = await (0, import_promises11.readFile)(configFile, "utf8");
33711
+ content = await (0, import_promises12.readFile)(configFile, "utf8");
33680
33712
  } catch (error) {
33681
33713
  if (isNodeError(error) && error.code === "ENOENT") {
33682
33714
  if (options.dryRun) {
33683
33715
  return true;
33684
33716
  }
33685
- await (0, import_promises11.mkdir)((0, import_node_path29.resolve)(configFile, ".."), { recursive: true });
33686
- await (0, import_promises11.writeFile)(configFile, "plugins:\n enabled:\n - okx-a2a\n");
33717
+ await (0, import_promises12.mkdir)((0, import_node_path29.resolve)(configFile, ".."), { recursive: true });
33718
+ await (0, import_promises12.writeFile)(configFile, "plugins:\n enabled:\n - okx-a2a\n");
33687
33719
  console.log(`[update] added Hermes plugins.enabled okx-a2a entry in ${configFile}`);
33688
33720
  return true;
33689
33721
  }
@@ -33694,7 +33726,7 @@ async function ensureHermesOkxA2aPluginConfig(configFile = resolveHermesConfigPa
33694
33726
  if (options.dryRun) {
33695
33727
  return true;
33696
33728
  }
33697
- await (0, import_promises11.writeFile)(configFile, normalized.content);
33729
+ await (0, import_promises12.writeFile)(configFile, normalized.content);
33698
33730
  console.log(`[update] normalized Hermes plugins.enabled okx-a2a entry in ${configFile}`);
33699
33731
  return true;
33700
33732
  }
@@ -33705,7 +33737,7 @@ async function ensureHermesOkxA2aPluginConfig(configFile = resolveHermesConfigPa
33705
33737
  return true;
33706
33738
  }
33707
33739
  const updated = addHermesOkxA2aEnabled(content);
33708
- await (0, import_promises11.writeFile)(configFile, updated);
33740
+ await (0, import_promises12.writeFile)(configFile, updated);
33709
33741
  console.log(`[update] added Hermes plugins.enabled okx-a2a entry in ${configFile}`);
33710
33742
  return true;
33711
33743
  }
@@ -34006,7 +34038,7 @@ async function isGatewayPluginInstalled(target) {
34006
34038
  if (target === "openclaw") {
34007
34039
  return (await getInstalledOpenClawPluginInfo()).installed;
34008
34040
  }
34009
- return (0, import_node_fs22.existsSync)(resolveHermesPluginYamlPath());
34041
+ return (0, import_node_fs23.existsSync)(resolveHermesPluginYamlPath());
34010
34042
  }
34011
34043
  async function getInstalledGatewayPluginVersion(target) {
34012
34044
  if (target === "hermes") {
@@ -34095,7 +34127,7 @@ function parsePackageVersionFromText(output) {
34095
34127
  async function getInstalledHermesPluginVersion() {
34096
34128
  const pluginYaml = (0, import_node_path29.join)(process.env.HERMES_HOME ?? (0, import_node_path29.join)((0, import_node_os10.homedir)(), ".hermes"), "plugins", "platforms", "okx-a2a", "plugin.yaml");
34097
34129
  try {
34098
- const content = await (0, import_promises11.readFile)(pluginYaml, "utf8");
34130
+ const content = await (0, import_promises12.readFile)(pluginYaml, "utf8");
34099
34131
  return parsePluginYamlVersion(content);
34100
34132
  } catch (error) {
34101
34133
  if (isNodeError(error) && error.code === "ENOENT") {
@@ -34154,7 +34186,7 @@ async function npmPack(spec, destination) {
34154
34186
  return (0, import_node_path29.resolve)(destination, (0, import_node_path29.basename)(tarballName));
34155
34187
  }
34156
34188
  async function findHermesPluginTarball(distDir) {
34157
- const entries = await (0, import_promises11.readdir)(distDir);
34189
+ const entries = await (0, import_promises12.readdir)(distDir);
34158
34190
  const tarball = entries.find((entry) => /^okx-a2a-hermes-plugin-.+\.tar\.gz$/.test(entry));
34159
34191
  if (!tarball) {
34160
34192
  throw new Error(`Hermes npm package did not contain dist/okx-a2a-hermes-plugin-*.tar.gz`);
@@ -34162,7 +34194,7 @@ async function findHermesPluginTarball(distDir) {
34162
34194
  return (0, import_node_path29.join)(distDir, tarball);
34163
34195
  }
34164
34196
  async function findFirstDirectory(parent) {
34165
- const entries = await (0, import_promises11.readdir)(parent, { withFileTypes: true });
34197
+ const entries = await (0, import_promises12.readdir)(parent, { withFileTypes: true });
34166
34198
  const dir = entries.find((entry) => entry.isDirectory());
34167
34199
  if (!dir) {
34168
34200
  throw new Error(`No unpacked plugin directory found under ${parent}`);
@@ -34179,7 +34211,7 @@ function readOption2(args, name) {
34179
34211
  function hasFlag(args, name) {
34180
34212
  return args.includes(name);
34181
34213
  }
34182
- function isHelpArg(value) {
34214
+ function isHelpArg2(value) {
34183
34215
  return value === "-h" || value === "--help" || value === "help";
34184
34216
  }
34185
34217
  function isSupportedRelease(value) {
@@ -34388,13 +34420,13 @@ function buildExternalCommandInvocation(command, args, platform = process.platfo
34388
34420
  function formatExternalCommand(command, args) {
34389
34421
  return [command, ...args].join(" ");
34390
34422
  }
34391
- var import_node_child_process8, import_node_fs22, import_promises11, import_node_os10, import_node_path29, UPDATE_PACKAGES, CODEX_NPM_PACKAGE, OPENCLAW_FORCE_INSTALL_FLAG, OPENCLAW_UNSAFE_INSTALL_FLAG, OKX_A2A_PLUGIN_ID, OPENCLAW_SESSION_DM_SCOPE_CONFIG_PATH, OPENCLAW_SESSION_DM_SCOPE_CONFIG_VALUE, OPENCLAW_PLUGIN_ALLOW_CONFIG_PATH, OPENCLAW_OKX_A2A_CONVERSATION_HOOK_ACCESS_CONFIG_PATH, DEFAULT_AI_PROVIDER_LOGIN_TIMEOUT_MS, PROVIDER_CLI_AUTH_PROBE_TIMEOUT_MS, SetupBlockedError, redirectCommandStdoutToStderr;
34423
+ var import_node_child_process8, import_node_fs23, import_promises12, import_node_os10, import_node_path29, UPDATE_PACKAGES, CODEX_NPM_PACKAGE, OPENCLAW_FORCE_INSTALL_FLAG, OPENCLAW_UNSAFE_INSTALL_FLAG, OKX_A2A_PLUGIN_ID, OPENCLAW_SESSION_DM_SCOPE_CONFIG_PATH, OPENCLAW_SESSION_DM_SCOPE_CONFIG_VALUE, OPENCLAW_PLUGIN_ALLOW_CONFIG_PATH, OPENCLAW_OKX_A2A_CONVERSATION_HOOK_ACCESS_CONFIG_PATH, DEFAULT_AI_PROVIDER_LOGIN_TIMEOUT_MS, PROVIDER_CLI_AUTH_PROBE_TIMEOUT_MS, SetupBlockedError, redirectCommandStdoutToStderr;
34392
34424
  var init_update_cli = __esm({
34393
34425
  "src/update-cli.ts"() {
34394
34426
  "use strict";
34395
34427
  import_node_child_process8 = require("node:child_process");
34396
- import_node_fs22 = require("node:fs");
34397
- import_promises11 = require("node:fs/promises");
34428
+ import_node_fs23 = require("node:fs");
34429
+ import_promises12 = require("node:fs/promises");
34398
34430
  import_node_os10 = require("node:os");
34399
34431
  import_node_path29 = require("node:path");
34400
34432
  init_ai_command();
@@ -44347,7 +44379,23 @@ __export(index_exports, {
44347
44379
  DEFAULT_LOG_TAIL_LIMIT: () => DEFAULT_LOG_TAIL_LIMIT,
44348
44380
  DEFAULT_OFFLINE_REPLAY_INTERVAL_SEC: () => DEFAULT_OFFLINE_REPLAY_INTERVAL_SEC,
44349
44381
  DEFAULT_XMTP_CLIENT_RECYCLE_INTERVAL_SEC: () => DEFAULT_XMTP_CLIENT_RECYCLE_INTERVAL_SEC,
44382
+ DEVKIT_DROP_REASON: () => DEVKIT_DROP_REASON,
44383
+ DEVKIT_MAX_CONCURRENCY: () => DEVKIT_MAX_CONCURRENCY,
44384
+ DEVKIT_MAX_MESSAGE_BYTES: () => DEVKIT_MAX_MESSAGE_BYTES,
44385
+ DEVKIT_MAX_PENDING: () => DEVKIT_MAX_PENDING,
44386
+ DEVKIT_MAX_PENDING_BYTES: () => DEVKIT_MAX_PENDING_BYTES,
44387
+ DEVKIT_OUTCOME: () => DEVKIT_OUTCOME,
44388
+ DEVKIT_REQUEST_BUDGET_MS: () => DEVKIT_REQUEST_BUDGET_MS,
44389
+ DEVKIT_RESPONSE_DIAGNOSTIC_MAX_BYTES: () => DEVKIT_RESPONSE_DIAGNOSTIC_MAX_BYTES,
44390
+ DEVKIT_RESPONSE_SUMMARY_MAX_CHARS: () => DEVKIT_RESPONSE_SUMMARY_MAX_CHARS,
44391
+ DEVKIT_SERVER_APPLICATION_ID: () => DEVKIT_SERVER_APPLICATION_ID,
44392
+ DEVKIT_SERVER_DB_NAME: () => DEVKIT_SERVER_DB_NAME,
44393
+ DEVKIT_SERVER_SCHEMA_VERSION: () => DEVKIT_SERVER_SCHEMA_VERSION,
44350
44394
  DOCTOR_MIN_NODE_VERSION: () => DOCTOR_MIN_NODE_VERSION,
44395
+ DevkitDeliveryDispatcher: () => DevkitDeliveryDispatcher,
44396
+ DevkitServerStore: () => DevkitServerStore,
44397
+ DevkitServerStoreError: () => DevkitServerStoreError,
44398
+ DevkitTargetError: () => DevkitTargetError,
44351
44399
  GatewayOutboundBehavior: () => GatewayOutboundBehavior,
44352
44400
  HEARTBEAT_GATEWAY_CHECK_TIMEOUT_MS: () => HEARTBEAT_GATEWAY_CHECK_TIMEOUT_MS,
44353
44401
  InboundReplayGate: () => InboundReplayGate,
@@ -44405,6 +44453,7 @@ __export(index_exports, {
44405
44453
  buildExternalCommandInvocation: () => buildExternalCommandInvocation,
44406
44454
  buildGatewayOutboundExtra: () => buildGatewayOutboundExtra,
44407
44455
  buildInboundTerminalExtras: () => buildInboundTerminalExtras,
44456
+ buildJobEnvelope: () => buildJobEnvelope,
44408
44457
  buildLaunchdPlist: () => buildLaunchdPlist,
44409
44458
  buildLauncherEntryJs: () => buildLauncherEntryJs,
44410
44459
  buildMessageEligibleArgs: () => buildMessageEligibleArgs,
@@ -44415,6 +44464,7 @@ __export(index_exports, {
44415
44464
  buildSchtasksRunArgs: () => buildSchtasksRunArgs,
44416
44465
  buildSeaConfig: () => buildSeaConfig,
44417
44466
  buildServicePath: () => buildServicePath,
44467
+ buildSessionEnvelope: () => buildSessionEnvelope,
44418
44468
  buildSessionKey: () => buildSessionKey,
44419
44469
  buildSystemMessageNotice: () => buildSystemMessageNotice,
44420
44470
  buildSystemStoredMessage: () => buildSystemStoredMessage,
@@ -44432,6 +44482,8 @@ __export(index_exports, {
44432
44482
  checkCodexCliAuthStatus: () => checkCodexCliAuthStatus,
44433
44483
  checkCodexReadiness: () => checkCodexReadiness,
44434
44484
  claimActiveDaemon: () => claimActiveDaemon,
44485
+ classifyFetchFailure: () => classifyFetchFailure,
44486
+ classifyHttpOutcome: () => classifyHttpOutcome,
44435
44487
  classifyJobBindingSource: () => classifyJobBindingSource,
44436
44488
  clearCodexReadinessCache: () => clearCodexReadinessCache,
44437
44489
  codexCommandResolvesWithoutOverride: () => codexCommandResolvesWithoutOverride,
@@ -44440,6 +44492,7 @@ __export(index_exports, {
44440
44492
  collectCodexCommandCandidates: () => collectCodexCommandCandidates,
44441
44493
  commandExists: () => commandExists,
44442
44494
  createAiToolFailureTracker: () => createAiToolFailureTracker,
44495
+ createDevkitAutoRouter: () => createDevkitAutoRouter,
44443
44496
  createFileMessageHandler: () => createFileMessageHandler,
44444
44497
  createOutboundBehavior: () => createOutboundBehavior,
44445
44498
  createUserAttentionWatchParentMonitor: () => createUserAttentionWatchParentMonitor,
@@ -44450,6 +44503,7 @@ __export(index_exports, {
44450
44503
  detectGatewayInvocation: () => detectGatewayInvocation,
44451
44504
  detectMessageEligibleOfflineReplaySupport: () => detectMessageEligibleOfflineReplaySupport,
44452
44505
  detectRuntime: () => detectRuntime,
44506
+ devkitServerDbExists: () => devkitServerDbExists,
44453
44507
  ensureDaemonReady: () => ensureDaemonReady,
44454
44508
  ensureDefaultAiProvider: () => ensureDefaultAiProvider,
44455
44509
  ensureOpenClawOkxA2aPluginConfig: () => ensureOpenClawOkxA2aPluginConfig,
@@ -44472,6 +44526,7 @@ __export(index_exports, {
44472
44526
  getSessionBusyTracker: () => getSessionBusyTracker,
44473
44527
  getXmtpCreationCooldown: () => getXmtpCreationCooldown,
44474
44528
  handleCapabilitiesCommand: () => handleCapabilitiesCommand,
44529
+ handleDevkitCommand: () => handleDevkitCommand,
44475
44530
  handleDoctorCommand: () => handleDoctorCommand,
44476
44531
  handleXmtpDebugCommand: () => handleXmtpDebugCommand,
44477
44532
  handleXmtpSendCommand: () => handleXmtpSendCommand,
@@ -44513,6 +44568,7 @@ __export(index_exports, {
44513
44568
  nodeVersionSatisfies: () => nodeVersionSatisfies,
44514
44569
  normalizeAiProvider: () => normalizeAiProvider,
44515
44570
  normalizeAiRuntimeProvider: () => normalizeAiRuntimeProvider,
44571
+ normalizeDevkitTarget: () => normalizeDevkitTarget,
44516
44572
  normalizeHermesOkxA2aPluginConfig: () => normalizeHermesOkxA2aPluginConfig,
44517
44573
  notifyAgentMessageToUserAttention: () => notifyAgentMessageToUserAttention,
44518
44574
  notifyDirectToUserAttention: () => notifyDirectToUserAttention,
@@ -44529,6 +44585,7 @@ __export(index_exports, {
44529
44585
  persistCurrentRuntimeSelectionForNewJob: () => persistCurrentRuntimeSelectionForNewJob,
44530
44586
  pickOnchainosWin32Candidate: () => pickOnchainosWin32Candidate,
44531
44587
  prepareAndBindCurrentRuntimeForNewJob: () => prepareAndBindCurrentRuntimeForNewJob,
44588
+ printDevkitUsage: () => printDevkitUsage,
44532
44589
  printLogsExportUsage: () => printLogsExportUsage,
44533
44590
  printXmtpTestUsage: () => printXmtpTestUsage,
44534
44591
  probeCodexAuthStatus: () => probeCodexAuthStatus,
@@ -44540,6 +44597,7 @@ __export(index_exports, {
44540
44597
  readLastLines: () => readLastLines,
44541
44598
  readParentProcessCommandForPlatform: () => readParentProcessCommandForPlatform,
44542
44599
  readUserAttentionWatcherEvent: () => readUserAttentionWatcherEvent,
44600
+ redactSummary: () => redactSummary,
44543
44601
  refreshAgentsAndWait: () => refreshAgentsAndWait,
44544
44602
  refreshOnchainosVersionMetadata: () => refreshOnchainosVersionMetadata,
44545
44603
  registerUserAttentionWatcher: () => registerUserAttentionWatcher,
@@ -44562,6 +44620,7 @@ __export(index_exports, {
44562
44620
  resolveCodexCommandSource: () => resolveCodexCommandSource,
44563
44621
  resolveConfiguredAiProvider: () => resolveConfiguredAiProvider,
44564
44622
  resolveConfiguredAiProviderForJob: () => resolveConfiguredAiProviderForJob,
44623
+ resolveDevkitServerDbPath: () => resolveDevkitServerDbPath,
44565
44624
  resolveDirectCommunicationSessionTarget: () => resolveDirectCommunicationSessionTarget,
44566
44625
  resolveDoctorTarget: () => resolveDoctorTarget,
44567
44626
  resolveEnvelopePayload: () => resolveEnvelopePayload,
@@ -44839,13 +44898,12 @@ var TaskMessageStore = class {
44839
44898
  withFileLock(path2, operation) {
44840
44899
  const previous = this.writeLocks.get(path2) ?? Promise.resolve();
44841
44900
  const next = previous.then(operation, operation);
44842
- let tracked;
44843
44901
  const release = () => {
44844
44902
  if (this.writeLocks.get(path2) === tracked) {
44845
44903
  this.writeLocks.delete(path2);
44846
44904
  }
44847
44905
  };
44848
- tracked = next.then(release, release);
44906
+ const tracked = next.then(release, release);
44849
44907
  this.writeLocks.set(path2, tracked);
44850
44908
  return next;
44851
44909
  }
@@ -62133,7 +62191,7 @@ function buildConnectParams(config, instanceId, protocolVersion) {
62133
62191
  client: {
62134
62192
  id: "gateway-client",
62135
62193
  displayName: "okx-a2a-node",
62136
- version: "0.2.18",
62194
+ version: "0.2.19-beta-fe6942ad54-261125201445",
62137
62195
  platform: "node",
62138
62196
  mode: "backend",
62139
62197
  instanceId
@@ -62144,7 +62202,7 @@ function buildConnectParams(config, instanceId, protocolVersion) {
62144
62202
  commands: [],
62145
62203
  permissions: {},
62146
62204
  locale: Intl.DateTimeFormat().resolvedOptions().locale || "en-US",
62147
- userAgent: `okx-a2a-node/${"0.2.18"}`,
62205
+ userAgent: `okx-a2a-node/${"0.2.19-beta-fe6942ad54-261125201445"}`,
62148
62206
  auth: {
62149
62207
  ...config.token ? { token: config.token } : {},
62150
62208
  ...config.password ? { password: config.password } : {}
@@ -66742,7 +66800,7 @@ async function isTrustedDmSender(params) {
66742
66800
  }
66743
66801
  if (trustedInboxIds.length === 0) {
66744
66802
  logger.info(LogEvent.DM_WHITELIST_FAIL_OPEN, { ...dmExtras(), reason: "trusted_inbox_list_empty" });
66745
- return true;
66803
+ return false;
66746
66804
  }
66747
66805
  if (!matches(trustedInboxIds)) {
66748
66806
  logger.info(LogEvent.INBOUND_DROP_DM_NON_SYSTEM, {
@@ -67737,8 +67795,8 @@ function isA2AEnvelope(payload) {
67737
67795
 
67738
67796
  // src/listener.ts
67739
67797
  init_log();
67740
- var import_node_fs19 = require("node:fs");
67741
- var import_promises8 = require("node:fs/promises");
67798
+ var import_node_fs20 = require("node:fs");
67799
+ var import_promises9 = require("node:fs/promises");
67742
67800
  var import_node_os8 = require("node:os");
67743
67801
  var import_node_path25 = require("node:path");
67744
67802
 
@@ -67849,6 +67907,472 @@ function createOnchainosSigner(agent) {
67849
67907
  // src/listener.ts
67850
67908
  init_session_store();
67851
67909
 
67910
+ // src/devkit-delivery.ts
67911
+ var import_promises8 = require("node:dns/promises");
67912
+
67913
+ // src/devkit-target.ts
67914
+ var import_node_net2 = require("node:net");
67915
+ var DevkitTargetError = class extends Error {
67916
+ constructor(field, message) {
67917
+ super(message);
67918
+ this.field = field;
67919
+ this.name = "DevkitTargetError";
67920
+ }
67921
+ field;
67922
+ };
67923
+ function normalizeDevkitTarget(origin, port) {
67924
+ if (typeof origin !== "string" || origin.includes("\\")) {
67925
+ throw new DevkitTargetError("url", "URL must be an HTTP or HTTPS loopback origin");
67926
+ }
67927
+ const originParts = /^(https?):\/\/([^/?#]*)(.*)$/i.exec(origin);
67928
+ if (!originParts) {
67929
+ throw new DevkitTargetError("url", "URL must be an HTTP or HTTPS loopback origin");
67930
+ }
67931
+ let parsedUrl;
67932
+ try {
67933
+ parsedUrl = new URL(origin);
67934
+ } catch {
67935
+ throw new DevkitTargetError("url", "URL must be a valid HTTP or HTTPS loopback origin");
67936
+ }
67937
+ if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") {
67938
+ throw new DevkitTargetError("url", "URL protocol must be HTTP or HTTPS");
67939
+ }
67940
+ const rawAuthority = originParts[2];
67941
+ const rawHost = rawAuthority.slice(rawAuthority.lastIndexOf("@") + 1);
67942
+ const hasEmbeddedPort = rawHost.startsWith("[") ? /^\[[^\]]+\]:/.test(rawHost) : rawHost.includes(":");
67943
+ if (rawAuthority.includes("@") || hasEmbeddedPort || originParts[3] !== "" && originParts[3] !== "/") {
67944
+ throw new DevkitTargetError("url", "URL must not include credentials, a port, or a path, query, or fragment");
67945
+ }
67946
+ const hostname = parsedUrl.hostname.toLowerCase();
67947
+ if (!isDevkitLoopbackHostname(hostname)) {
67948
+ throw new DevkitTargetError("url", "URL hostname must be localhost or a loopback address");
67949
+ }
67950
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
67951
+ throw new DevkitTargetError("port", "Port must be an integer from 1 to 65535");
67952
+ }
67953
+ const normalizedHostname = hostname === "localhost" ? "127.0.0.1" : hostname;
67954
+ return {
67955
+ origin: `${parsedUrl.protocol}//${normalizedHostname}`,
67956
+ port
67957
+ };
67958
+ }
67959
+ function isDevkitLoopbackHostname(hostname) {
67960
+ const address = hostname.startsWith("[") && hostname.endsWith("]") ? hostname.slice(1, -1) : hostname;
67961
+ if (address.toLowerCase() === "localhost") {
67962
+ return true;
67963
+ }
67964
+ return (0, import_node_net2.isIP)(address) === 4 ? address.startsWith("127.") : (0, import_node_net2.isIP)(address) === 6 && address === "::1";
67965
+ }
67966
+
67967
+ // src/devkit-delivery.ts
67968
+ init_sentry_logger();
67969
+ init_error_diagnostics();
67970
+
67971
+ // src/devkit-types.ts
67972
+ var DEVKIT_MAX_CONCURRENCY = 16;
67973
+ var DEVKIT_MAX_PENDING = 256;
67974
+ var DEVKIT_MAX_PENDING_BYTES = 16 * 1024 * 1024;
67975
+ var DEVKIT_MAX_MESSAGE_BYTES = 1 * 1024 * 1024;
67976
+ var DEVKIT_REQUEST_BUDGET_MS = 5e3;
67977
+ var DEVKIT_RESPONSE_DIAGNOSTIC_MAX_BYTES = 4 * 1024;
67978
+ var DEVKIT_RESPONSE_SUMMARY_MAX_CHARS = 256;
67979
+ var DEVKIT_OUTCOME = {
67980
+ HTTP_ACCEPTED: "http_accepted",
67981
+ DROPPED: "dropped"
67982
+ };
67983
+ var DEVKIT_DROP_REASON = {
67984
+ REQUEST_TOO_LARGE: "request_too_large",
67985
+ // serialized > 1 MiB (FR-3-AC-6)
67986
+ PENDING_OVERFLOW: "pending_overflow",
67987
+ // > 256 items or > 16 MiB total pending (NFR-2-AC-1)
67988
+ CONFIG_CHANGED: "config_changed",
67989
+ // snapshot version changed/removed before send (FR-2-AC-6)
67990
+ CONFIG_READ_FAILED: "config_read_failed",
67991
+ // snapshot unreadable/corrupt (FR-2-AC-5)
67992
+ HTTP_STATUS: "http_status",
67993
+ // non-2xx response (FR-3-AC-3)
67994
+ REDIRECT_BLOCKED: "redirect_blocked",
67995
+ // 3xx response, not followed (NFR-3-AC-2)
67996
+ CONNECTION_FAILED: "connection_failed",
67997
+ // ECONNREFUSED / reset / unreachable (FR-3-AC-4)
67998
+ TIMEOUT: "timeout",
67999
+ // exceeded the 5 s budget (FR-3-AC-4)
68000
+ REQUEST_BUILD_ERROR: "request_build_error",
68001
+ // serialization / target build failure
68002
+ RESPONSE_READ_ERROR: "response_read_error",
68003
+ // diagnostic read failure
68004
+ SHUTDOWN_CANCELLED: "shutdown_cancelled"
68005
+ // daemon stopped before send (NFR-2-AC-3)
68006
+ };
68007
+
68008
+ // src/devkit-delivery.ts
68009
+ var COMPONENT = "node_devkit";
68010
+ var SECRET_KEYS = "authorization|bearer|basic|jwt|password|api[_-]?key|secret|token";
68011
+ var SECRET_SCHEME_PATTERN = new RegExp(`\\b(?:${SECRET_KEYS})\\s+\\S+`, "gi");
68012
+ var SECRET_KV_PATTERN = new RegExp(
68013
+ `("?)(${SECRET_KEYS})("?)\\s*([:=])\\s*"?[^"\\s,}]+`,
68014
+ "gi"
68015
+ );
68016
+ function fallbackDeliveryId(parts) {
68017
+ return `devkit-${parts.jobId ?? "none"}-${parts.sessionKey ?? "none"}-${parts.receivedAt}`;
68018
+ }
68019
+ function buildSessionEnvelope(ev, ctx = {}) {
68020
+ const now = ctx.now ?? Date.now;
68021
+ const receivedAt = Math.floor(now() / 1e3);
68022
+ const jobId = ev.jobId ?? null;
68023
+ const agentId = ev.agentId ?? null;
68024
+ const deliveryId = ev.messageId ?? fallbackDeliveryId({ jobId, sessionKey: ev.sessionKey, receivedAt });
68025
+ const messageId = ev.messageId ?? deliveryId;
68026
+ return {
68027
+ deliveryId,
68028
+ receivedAt,
68029
+ kind: "session",
68030
+ agentId,
68031
+ event: {
68032
+ sessionKey: ev.sessionKey,
68033
+ content: ev.content,
68034
+ messageId,
68035
+ jobId,
68036
+ agentId
68037
+ }
68038
+ };
68039
+ }
68040
+ function buildJobEnvelope(ev, _ctx = {}) {
68041
+ const sessionAgentId = ev.sessionAgentId ?? null;
68042
+ const receivedAt = Math.floor(ev.message.receivedAtMs / 1e3);
68043
+ return {
68044
+ deliveryId: ev.message.id,
68045
+ receivedAt,
68046
+ kind: "job",
68047
+ agentId: sessionAgentId,
68048
+ event: {
68049
+ jobId: ev.jobId,
68050
+ sessionAgentId,
68051
+ message: {
68052
+ ...ev.message,
68053
+ content: ev.message.rawText
68054
+ }
68055
+ }
68056
+ };
68057
+ }
68058
+ function classifyHttpOutcome(status) {
68059
+ if (status >= 200 && status < 300) {
68060
+ return { outcome: DEVKIT_OUTCOME.HTTP_ACCEPTED };
68061
+ }
68062
+ if (status >= 300 && status < 400) {
68063
+ return { outcome: DEVKIT_OUTCOME.DROPPED, reason: DEVKIT_DROP_REASON.REDIRECT_BLOCKED };
68064
+ }
68065
+ return { outcome: DEVKIT_OUTCOME.DROPPED, reason: DEVKIT_DROP_REASON.HTTP_STATUS };
68066
+ }
68067
+ function classifyFetchFailure(params) {
68068
+ if (params.cancelledByShutdown) {
68069
+ return DEVKIT_DROP_REASON.SHUTDOWN_CANCELLED;
68070
+ }
68071
+ if (params.timedOut || params.errorCategory === "timeout") {
68072
+ return DEVKIT_DROP_REASON.TIMEOUT;
68073
+ }
68074
+ return DEVKIT_DROP_REASON.CONNECTION_FAILED;
68075
+ }
68076
+ function redactSummary(raw) {
68077
+ const collapsed = raw.replace(/\s+/g, " ").trim();
68078
+ const redacted = collapsed.replace(SECRET_SCHEME_PATTERN, "[REDACTED]").replace(
68079
+ SECRET_KV_PATTERN,
68080
+ (_match, keyQuote, key, keyQuoteClose, sep3) => `${keyQuote}${key}${keyQuoteClose}${sep3}[REDACTED]`
68081
+ );
68082
+ const truncated = redacted.length > DEVKIT_RESPONSE_SUMMARY_MAX_CHARS;
68083
+ return { text: redacted.slice(0, DEVKIT_RESPONSE_SUMMARY_MAX_CHARS), truncated };
68084
+ }
68085
+ async function readRedactedResponse(response) {
68086
+ let bodyText;
68087
+ try {
68088
+ bodyText = await response.text();
68089
+ } catch {
68090
+ return { responseBytesRead: 0, responseTruncated: false, responseSummary: "" };
68091
+ }
68092
+ const bytes = Buffer.from(bodyText, "utf8");
68093
+ const diagnosticSlice = bytes.subarray(0, DEVKIT_RESPONSE_DIAGNOSTIC_MAX_BYTES);
68094
+ const sliceTruncated = bytes.byteLength > DEVKIT_RESPONSE_DIAGNOSTIC_MAX_BYTES;
68095
+ const summary = redactSummary(diagnosticSlice.toString("utf8"));
68096
+ return {
68097
+ responseBytesRead: diagnosticSlice.byteLength,
68098
+ responseTruncated: sliceTruncated || summary.truncated,
68099
+ responseSummary: summary.text
68100
+ };
68101
+ }
68102
+ async function isLoopbackTarget(origin) {
68103
+ let hostname;
68104
+ try {
68105
+ hostname = new URL(origin).hostname;
68106
+ } catch {
68107
+ return false;
68108
+ }
68109
+ if (!isDevkitLoopbackHostname(hostname)) {
68110
+ return false;
68111
+ }
68112
+ if (hostname.toLowerCase() !== "localhost") {
68113
+ return true;
68114
+ }
68115
+ try {
68116
+ const resolved = await (0, import_promises8.lookup)(hostname);
68117
+ return isDevkitLoopbackHostname(resolved.address);
68118
+ } catch {
68119
+ return false;
68120
+ }
68121
+ }
68122
+ function orderingKeyFor(envelope, config) {
68123
+ const routeKey = envelope.kind === "session" ? envelope.event.sessionKey : envelope.event.jobId;
68124
+ return JSON.stringify([config.origin, config.port, envelope.kind, routeKey]);
68125
+ }
68126
+ function targetFields(config) {
68127
+ return {
68128
+ targetOrigin: config.origin,
68129
+ targetPort: config.port,
68130
+ targetId: JSON.stringify([config.origin, config.port])
68131
+ };
68132
+ }
68133
+ function copyConfig(config) {
68134
+ return { ...config };
68135
+ }
68136
+ function sleep4(ms) {
68137
+ return new Promise((resolve11) => setTimeout(resolve11, Math.max(0, ms)));
68138
+ }
68139
+ var DevkitDeliveryDispatcher = class {
68140
+ now;
68141
+ fetchImpl;
68142
+ diagnosticLogger;
68143
+ pendingQueue = [];
68144
+ pendingBytes = 0;
68145
+ activeKeys = /* @__PURE__ */ new Set();
68146
+ inFlight = /* @__PURE__ */ new Set();
68147
+ activeControllers = /* @__PURE__ */ new Map();
68148
+ shuttingDown = false;
68149
+ constructor(options) {
68150
+ this.now = options.now ?? Date.now;
68151
+ this.fetchImpl = options.fetchImpl ?? fetch;
68152
+ this.diagnosticLogger = options.diagnosticLogger ?? logger;
68153
+ }
68154
+ enqueue(input) {
68155
+ const config = copyConfig(input.config);
68156
+ const serialized = JSON.stringify(input.envelope);
68157
+ const envelope = JSON.parse(serialized);
68158
+ const bytes = Buffer.byteLength(serialized, "utf8");
68159
+ const kind = envelope.kind;
68160
+ const deliveryId = envelope.deliveryId;
68161
+ const item = {
68162
+ envelope,
68163
+ config,
68164
+ serialized,
68165
+ bytes,
68166
+ cancelledByShutdown: false,
68167
+ timedOut: false
68168
+ };
68169
+ if (this.shuttingDown) {
68170
+ this.emitCancelled(item, 0);
68171
+ return false;
68172
+ }
68173
+ if (bytes > DEVKIT_MAX_MESSAGE_BYTES) {
68174
+ this.emitDropped({
68175
+ ...targetFields(config),
68176
+ deliveryId,
68177
+ kind,
68178
+ reason: DEVKIT_DROP_REASON.REQUEST_TOO_LARGE,
68179
+ durationMs: 0
68180
+ });
68181
+ return true;
68182
+ }
68183
+ if (this.pendingQueue.length >= DEVKIT_MAX_PENDING || this.pendingBytes + bytes > DEVKIT_MAX_PENDING_BYTES) {
68184
+ this.emitDropped({
68185
+ ...targetFields(config),
68186
+ deliveryId,
68187
+ kind,
68188
+ reason: DEVKIT_DROP_REASON.PENDING_OVERFLOW,
68189
+ durationMs: 0
68190
+ });
68191
+ return false;
68192
+ }
68193
+ this.pendingQueue.push(item);
68194
+ this.pendingBytes += bytes;
68195
+ this.diagnosticLogger.info(LogEvent.DEVKIT_DELIVERY_ACCEPTED, {
68196
+ component: COMPONENT,
68197
+ deliveryId,
68198
+ kind,
68199
+ ...targetFields(config),
68200
+ agentId: envelope.agentId ?? void 0
68201
+ });
68202
+ this.pump();
68203
+ return true;
68204
+ }
68205
+ pump() {
68206
+ if (this.shuttingDown) {
68207
+ return;
68208
+ }
68209
+ while (this.activeKeys.size < DEVKIT_MAX_CONCURRENCY) {
68210
+ const index2 = this.pendingQueue.findIndex(
68211
+ (item2) => !this.activeKeys.has(orderingKeyFor(item2.envelope, item2.config))
68212
+ );
68213
+ if (index2 === -1) {
68214
+ break;
68215
+ }
68216
+ const [item] = this.pendingQueue.splice(index2, 1);
68217
+ this.pendingBytes -= item.bytes;
68218
+ const key = orderingKeyFor(item.envelope, item.config);
68219
+ this.activeKeys.add(key);
68220
+ const promise = this.send(item).finally(() => {
68221
+ this.activeKeys.delete(key);
68222
+ this.inFlight.delete(promise);
68223
+ this.pump();
68224
+ });
68225
+ this.inFlight.add(promise);
68226
+ }
68227
+ }
68228
+ async send(item) {
68229
+ const startedAt = this.now();
68230
+ const { envelope } = item;
68231
+ const { config } = item;
68232
+ const controller = new AbortController();
68233
+ this.activeControllers.set(item, controller);
68234
+ const loopbackOk = await isLoopbackTarget(config.origin);
68235
+ if (item.cancelledByShutdown) {
68236
+ this.activeControllers.delete(item);
68237
+ this.emitCancelled(item, this.now() - startedAt);
68238
+ return;
68239
+ }
68240
+ if (!loopbackOk) {
68241
+ this.activeControllers.delete(item);
68242
+ this.emitHttpFailed(
68243
+ item,
68244
+ DEVKIT_DROP_REASON.CONNECTION_FAILED,
68245
+ { errorCategory: "network_unavailable" },
68246
+ this.now() - startedAt
68247
+ );
68248
+ return;
68249
+ }
68250
+ const url = `${config.origin}:${config.port}${config.eventPath}`;
68251
+ const timeoutTimer = setTimeout(() => {
68252
+ item.timedOut = true;
68253
+ controller.abort();
68254
+ }, DEVKIT_REQUEST_BUDGET_MS);
68255
+ let response;
68256
+ try {
68257
+ response = await this.fetchImpl(url, {
68258
+ method: "POST",
68259
+ headers: { "content-type": "application/json" },
68260
+ body: item.serialized,
68261
+ redirect: "manual",
68262
+ signal: controller.signal
68263
+ });
68264
+ } catch (err) {
68265
+ clearTimeout(timeoutTimer);
68266
+ this.activeControllers.delete(item);
68267
+ const durationMs2 = this.now() - startedAt;
68268
+ if (item.cancelledByShutdown) {
68269
+ this.emitCancelled(item, durationMs2);
68270
+ return;
68271
+ }
68272
+ const diagnostics = buildErrorDiagnostics(
68273
+ LogEvent.DEVKIT_DELIVERY_HTTP_FAILED,
68274
+ err instanceof Error ? err : void 0,
68275
+ {}
68276
+ );
68277
+ const reason = classifyFetchFailure({
68278
+ cancelledByShutdown: item.cancelledByShutdown,
68279
+ timedOut: item.timedOut,
68280
+ errorCategory: diagnostics.errorCategory
68281
+ });
68282
+ this.emitHttpFailed(item, reason, diagnostics, durationMs2, err instanceof Error ? err : void 0);
68283
+ return;
68284
+ }
68285
+ clearTimeout(timeoutTimer);
68286
+ this.activeControllers.delete(item);
68287
+ const durationMs = this.now() - startedAt;
68288
+ if (item.cancelledByShutdown) {
68289
+ this.emitCancelled(item, durationMs);
68290
+ return;
68291
+ }
68292
+ const status = response.status;
68293
+ const classified = classifyHttpOutcome(status);
68294
+ if (classified.outcome === DEVKIT_OUTCOME.HTTP_ACCEPTED) {
68295
+ this.diagnosticLogger.info(LogEvent.DEVKIT_DELIVERY_HTTP_ACCEPTED, {
68296
+ component: COMPONENT,
68297
+ deliveryId: envelope.deliveryId,
68298
+ kind: envelope.kind,
68299
+ ...targetFields(config),
68300
+ statusCode: status,
68301
+ durationMs
68302
+ });
68303
+ return;
68304
+ }
68305
+ const redaction = await readRedactedResponse(response);
68306
+ this.emitDropped({
68307
+ ...targetFields(config),
68308
+ deliveryId: envelope.deliveryId,
68309
+ kind: envelope.kind,
68310
+ reason: classified.reason,
68311
+ statusCode: status,
68312
+ durationMs,
68313
+ ...redaction
68314
+ });
68315
+ }
68316
+ async shutdown(deadlineMs) {
68317
+ this.shuttingDown = true;
68318
+ const deadline = this.now() + Math.max(0, deadlineMs);
68319
+ if (this.inFlight.size > 0) {
68320
+ const remaining = Math.max(0, deadline - this.now());
68321
+ await Promise.race([Promise.allSettled(Array.from(this.inFlight)), sleep4(remaining)]);
68322
+ }
68323
+ for (const [item, controller] of this.activeControllers) {
68324
+ item.cancelledByShutdown = true;
68325
+ controller.abort();
68326
+ }
68327
+ const stillPending = this.pendingQueue.splice(0, this.pendingQueue.length);
68328
+ this.pendingBytes = 0;
68329
+ for (const item of stillPending) {
68330
+ this.emitCancelled(item, 0);
68331
+ }
68332
+ }
68333
+ emitDropped(params) {
68334
+ this.diagnosticLogger.info(LogEvent.DEVKIT_DELIVERY_DROPPED, {
68335
+ component: COMPONENT,
68336
+ outcome: DEVKIT_OUTCOME.DROPPED,
68337
+ deliveryId: params.deliveryId,
68338
+ kind: params.kind,
68339
+ targetOrigin: params.targetOrigin,
68340
+ targetPort: params.targetPort,
68341
+ targetId: params.targetId,
68342
+ reason: params.reason,
68343
+ durationMs: params.durationMs,
68344
+ ...params.statusCode !== void 0 ? { statusCode: params.statusCode } : {},
68345
+ ...params.responseBytesRead !== void 0 ? { responseBytesRead: params.responseBytesRead } : {},
68346
+ ...params.responseTruncated !== void 0 ? { responseTruncated: params.responseTruncated } : {},
68347
+ ...params.responseSummary !== void 0 ? { responseSummary: params.responseSummary } : {}
68348
+ });
68349
+ }
68350
+ emitHttpFailed(item, reason, diagnostics, durationMs, err) {
68351
+ this.diagnosticLogger.error(LogEvent.DEVKIT_DELIVERY_HTTP_FAILED, err, {
68352
+ component: COMPONENT,
68353
+ outcome: DEVKIT_OUTCOME.DROPPED,
68354
+ deliveryId: item.envelope.deliveryId,
68355
+ kind: item.envelope.kind,
68356
+ ...targetFields(item.config),
68357
+ reason,
68358
+ durationMs,
68359
+ ...diagnostics.errorCategory ? { errorCategory: diagnostics.errorCategory } : {},
68360
+ ...diagnostics.errorCode ? { errorCode: diagnostics.errorCode } : {}
68361
+ });
68362
+ }
68363
+ emitCancelled(item, durationMs) {
68364
+ this.diagnosticLogger.info(LogEvent.DEVKIT_DELIVERY_CANCELLED, {
68365
+ component: COMPONENT,
68366
+ outcome: DEVKIT_OUTCOME.DROPPED,
68367
+ deliveryId: item.envelope.deliveryId,
68368
+ kind: item.envelope.kind,
68369
+ ...targetFields(item.config),
68370
+ reason: DEVKIT_DROP_REASON.SHUTDOWN_CANCELLED,
68371
+ durationMs
68372
+ });
68373
+ }
68374
+ };
68375
+
67852
68376
  // src/ai-dispatch-queue.ts
67853
68377
  async function enqueueAiJobMessageDispatch(params) {
67854
68378
  const commands = params.commands ?? new CommandStore(params.homeDir);
@@ -67874,6 +68398,475 @@ async function enqueueAiSessionMessageDispatch(params) {
67874
68398
  return command;
67875
68399
  }
67876
68400
 
68401
+ // src/devkit-router.ts
68402
+ init_sentry_logger();
68403
+ function createDevkitAutoRouter(deps) {
68404
+ const { commands, dispatcher, readSnapshots } = deps;
68405
+ const diagnosticLogger = deps.diagnosticLogger ?? logger;
68406
+ function readConfigSnapshots(phase) {
68407
+ try {
68408
+ const configs = readSnapshots();
68409
+ return {
68410
+ ok: true,
68411
+ // Capture detached, shallow immutable copies before any enqueue can trigger a registry
68412
+ // update. Delivery then owns the exact target/path selected for this inbound message.
68413
+ configs: configs.map((config) => Object.freeze({ ...config }))
68414
+ };
68415
+ } catch (err) {
68416
+ diagnosticLogger.error(
68417
+ LogEvent.DEVKIT_ROUTE_CONFIG_READ_FAILED,
68418
+ err instanceof Error ? err : new Error(String(err)),
68419
+ {
68420
+ component: "node_devkit",
68421
+ phase,
68422
+ outcome: "dropped",
68423
+ reason: "config_read_failed"
68424
+ }
68425
+ );
68426
+ return { ok: false };
68427
+ }
68428
+ }
68429
+ function enqueueForTargets(phase, envelope, configs, eventFields) {
68430
+ for (const config of configs) {
68431
+ const targetId = JSON.stringify([config.origin, config.port]);
68432
+ const targetFields2 = {
68433
+ targetOrigin: config.origin,
68434
+ targetPort: config.port,
68435
+ targetId
68436
+ };
68437
+ try {
68438
+ const accepted = dispatcher.enqueue({ envelope, config });
68439
+ diagnosticLogger.info(LogEvent.DEVKIT_ROUTE_CUSTOM_SERVER, {
68440
+ component: "node_devkit",
68441
+ phase,
68442
+ kind: envelope.kind,
68443
+ deliveryId: envelope.deliveryId,
68444
+ ...targetFields2,
68445
+ outcome: accepted ? "accepted" : "dropped",
68446
+ ...eventFields
68447
+ });
68448
+ } catch (err) {
68449
+ diagnosticLogger.error(
68450
+ LogEvent.DEVKIT_ROUTE_CUSTOM_SERVER,
68451
+ err instanceof Error ? err : new Error(String(err)),
68452
+ {
68453
+ component: "node_devkit",
68454
+ phase,
68455
+ kind: envelope.kind,
68456
+ deliveryId: envelope.deliveryId,
68457
+ ...targetFields2,
68458
+ outcome: "dropped",
68459
+ reason: "enqueue_failed"
68460
+ }
68461
+ );
68462
+ }
68463
+ }
68464
+ }
68465
+ async function routeSession(event) {
68466
+ const read = readConfigSnapshots("session");
68467
+ if (!read.ok) {
68468
+ return;
68469
+ }
68470
+ if (read.configs.length === 0) {
68471
+ await enqueueAiSessionMessageDispatch({ commands, event });
68472
+ diagnosticLogger.info(LogEvent.DEVKIT_ROUTE_DEFAULT_AI, {
68473
+ component: "node_devkit",
68474
+ phase: "session",
68475
+ kind: "session",
68476
+ messageId: event.messageId ?? "",
68477
+ jobId: event.jobId ?? "",
68478
+ agentId: event.agentId ?? ""
68479
+ });
68480
+ return;
68481
+ }
68482
+ const envelope = buildSessionEnvelope(event);
68483
+ enqueueForTargets("session", envelope, read.configs, {
68484
+ messageId: event.messageId ?? "",
68485
+ jobId: event.jobId ?? "",
68486
+ agentId: event.agentId ?? ""
68487
+ });
68488
+ }
68489
+ async function routeJob(event) {
68490
+ const read = readConfigSnapshots("job");
68491
+ if (!read.ok) {
68492
+ return;
68493
+ }
68494
+ if (read.configs.length === 0) {
68495
+ await enqueueAiJobMessageDispatch({ commands, event });
68496
+ diagnosticLogger.info(LogEvent.DEVKIT_ROUTE_DEFAULT_AI, {
68497
+ component: "node_devkit",
68498
+ phase: "job",
68499
+ kind: "job",
68500
+ jobId: event.jobId,
68501
+ agentId: event.sessionAgentId ?? ""
68502
+ });
68503
+ return;
68504
+ }
68505
+ const envelope = buildJobEnvelope(event);
68506
+ enqueueForTargets("job", envelope, read.configs, {
68507
+ messageId: event.message.id,
68508
+ jobId: event.jobId,
68509
+ agentId: event.sessionAgentId ?? ""
68510
+ });
68511
+ }
68512
+ return { routeJob, routeSession };
68513
+ }
68514
+
68515
+ // src/devkit-server-store.ts
68516
+ var import_node_fs19 = require("node:fs");
68517
+ init_paths();
68518
+ init_session_store();
68519
+ var { DatabaseSync: DatabaseSync4 } = loadSqlite4();
68520
+ var DEVKIT_SERVER_APPLICATION_ID = 1329677395;
68521
+ var DEVKIT_SERVER_SCHEMA_VERSION = 2;
68522
+ var TABLE_NAME = `"devkit-server"`;
68523
+ var WRITE_RETRY_ATTEMPTS = 6;
68524
+ var DevkitServerStoreError = class extends Error {
68525
+ code;
68526
+ constructor(code, message) {
68527
+ super(message);
68528
+ this.name = "DevkitServerStoreError";
68529
+ this.code = code;
68530
+ }
68531
+ };
68532
+ function resolveDevkitServerDbPath(homeDir) {
68533
+ return resolveTaskPaths(homeDir).devkitServerDbPath;
68534
+ }
68535
+ function devkitServerDbExists(homeDir) {
68536
+ return (0, import_node_fs19.existsSync)(resolveDevkitServerDbPath(homeDir));
68537
+ }
68538
+ var DevkitServerStore = class _DevkitServerStore {
68539
+ dbPath;
68540
+ db;
68541
+ constructor(dbPath, db) {
68542
+ this.dbPath = dbPath;
68543
+ this.db = db;
68544
+ }
68545
+ static openForWrite(homeDir) {
68546
+ const paths = resolveTaskPaths(homeDir);
68547
+ const dbPath = paths.devkitServerDbPath;
68548
+ assertNotSymlink(paths.sqliteDir, "devkit server directory");
68549
+ ensureTaskDir(paths.sqliteDir);
68550
+ assertNotSymlink(paths.sqliteDir, "devkit server directory");
68551
+ assertSafeDatabasePath(dbPath);
68552
+ const db = new DatabaseSync4(dbPath);
68553
+ const store = new _DevkitServerStore(dbPath, db);
68554
+ try {
68555
+ store.configureConnectionForWrite();
68556
+ store.ensureSchemaForWrite();
68557
+ return store;
68558
+ } catch (error) {
68559
+ db.close();
68560
+ throw error;
68561
+ }
68562
+ }
68563
+ static openForRead(homeDir) {
68564
+ const dbPath = resolveDevkitServerDbPath(homeDir);
68565
+ if (!(0, import_node_fs19.existsSync)(dbPath)) {
68566
+ return null;
68567
+ }
68568
+ assertSafeDatabaseFile(dbPath);
68569
+ const db = new DatabaseSync4(dbPath, { readOnly: true });
68570
+ const store = new _DevkitServerStore(dbPath, db);
68571
+ try {
68572
+ db.exec("PRAGMA query_only=ON");
68573
+ store.assertReadableSchema();
68574
+ return store;
68575
+ } catch (error) {
68576
+ db.close();
68577
+ throw error;
68578
+ }
68579
+ }
68580
+ close() {
68581
+ this.db.close();
68582
+ }
68583
+ register(input) {
68584
+ const target = normalizeDevkitTarget(input.origin, input.port);
68585
+ assertValidPath(input.eventPath, "event path");
68586
+ assertValidPath(input.healthPath, "health path");
68587
+ return this.withWriteTransaction(() => {
68588
+ const existing = this.db.prepare(`SELECT config_version FROM ${TABLE_NAME} WHERE origin = ? AND port = ?`).get(target.origin, target.port);
68589
+ const configVersion = (existing?.config_version ?? 0) + 1;
68590
+ const updatedAt = Date.now();
68591
+ this.db.prepare(`
68592
+ INSERT INTO ${TABLE_NAME} (
68593
+ origin, port, event_path, health_path, config_version, updated_at
68594
+ ) VALUES (?, ?, ?, ?, ?, ?)
68595
+ ON CONFLICT(origin, port) DO UPDATE SET
68596
+ event_path = excluded.event_path,
68597
+ health_path = excluded.health_path,
68598
+ config_version = excluded.config_version,
68599
+ updated_at = excluded.updated_at
68600
+ `).run(target.origin, target.port, input.eventPath, input.healthPath, configVersion, updatedAt);
68601
+ return {
68602
+ origin: target.origin,
68603
+ port: target.port,
68604
+ eventPath: input.eventPath,
68605
+ healthPath: input.healthPath,
68606
+ configVersion,
68607
+ updatedAt
68608
+ };
68609
+ });
68610
+ }
68611
+ unregister(targetInput) {
68612
+ const target = targetInput ? normalizeDevkitTarget(targetInput.origin, targetInput.port) : void 0;
68613
+ return this.withWriteTransaction(() => {
68614
+ const result = target ? this.db.prepare(`DELETE FROM ${TABLE_NAME} WHERE origin = ? AND port = ?`).run(target.origin, target.port) : this.db.prepare(`DELETE FROM ${TABLE_NAME}`).run();
68615
+ const removedCount = Number(result.changes);
68616
+ return { removed: removedCount > 0, removedCount };
68617
+ });
68618
+ }
68619
+ readSnapshot() {
68620
+ return this.readSnapshots()[0] ?? null;
68621
+ }
68622
+ readSnapshots() {
68623
+ let rows;
68624
+ try {
68625
+ rows = this.db.prepare(`
68626
+ SELECT origin, port, event_path, health_path, config_version, updated_at
68627
+ FROM ${TABLE_NAME} ORDER BY origin ASC, port ASC, id ASC
68628
+ `).all().map(parseDevkitServerRow);
68629
+ } catch (error) {
68630
+ throw new DevkitServerStoreError(
68631
+ "DATABASE_READ_FAILED",
68632
+ `failed to read devkit server configs: ${error instanceof Error ? error.message : String(error)}`
68633
+ );
68634
+ }
68635
+ return rows.map((snapshot) => ({
68636
+ origin: snapshot.origin,
68637
+ port: snapshot.port,
68638
+ eventPath: snapshot.event_path,
68639
+ healthPath: snapshot.health_path,
68640
+ configVersion: snapshot.config_version,
68641
+ updatedAt: snapshot.updated_at
68642
+ }));
68643
+ }
68644
+ configureConnectionForWrite() {
68645
+ this.db.exec("PRAGMA busy_timeout=5000");
68646
+ }
68647
+ ensureSchemaForWrite() {
68648
+ withBusyRetry(() => {
68649
+ this.db.exec("BEGIN IMMEDIATE");
68650
+ try {
68651
+ const applicationId = readPragmaNumber(this.db, "application_id");
68652
+ const userVersion = readPragmaNumber(this.db, "user_version");
68653
+ const hasTables = Boolean(
68654
+ this.db.prepare("SELECT 1 AS present FROM sqlite_master WHERE type = 'table' LIMIT 1").get()
68655
+ );
68656
+ if (applicationId === 0 && !hasTables && userVersion === 0) {
68657
+ this.db.exec(`PRAGMA application_id=${DEVKIT_SERVER_APPLICATION_ID}`);
68658
+ } else if (applicationId !== DEVKIT_SERVER_APPLICATION_ID) {
68659
+ throw new DevkitServerStoreError(
68660
+ "DATABASE_IDENTITY_MISMATCH",
68661
+ "devkit server database identity does not match"
68662
+ );
68663
+ }
68664
+ if (userVersion > DEVKIT_SERVER_SCHEMA_VERSION) {
68665
+ throw new DevkitServerStoreError(
68666
+ "DATABASE_SCHEMA_TOO_NEW",
68667
+ `devkit server schema version ${userVersion} is newer than supported ${DEVKIT_SERVER_SCHEMA_VERSION}`
68668
+ );
68669
+ }
68670
+ if (userVersion === 0) {
68671
+ applyMigrationV2(this.db);
68672
+ this.db.exec("PRAGMA user_version=2");
68673
+ } else if (userVersion === 1) {
68674
+ migrateV1ToV2(this.db);
68675
+ this.db.exec("PRAGMA user_version=2");
68676
+ }
68677
+ this.db.exec("COMMIT");
68678
+ } catch (error) {
68679
+ rollbackQuietly(this.db);
68680
+ throw error;
68681
+ }
68682
+ });
68683
+ withBusyRetry(() => {
68684
+ this.db.exec("PRAGMA journal_mode=WAL");
68685
+ this.db.exec("PRAGMA synchronous=FULL");
68686
+ });
68687
+ }
68688
+ assertReadableSchema() {
68689
+ const applicationId = readPragmaNumber(this.db, "application_id");
68690
+ if (applicationId !== DEVKIT_SERVER_APPLICATION_ID) {
68691
+ throw new DevkitServerStoreError(
68692
+ "DATABASE_IDENTITY_MISMATCH",
68693
+ "devkit server database identity does not match"
68694
+ );
68695
+ }
68696
+ const userVersion = readPragmaNumber(this.db, "user_version");
68697
+ if (userVersion > DEVKIT_SERVER_SCHEMA_VERSION) {
68698
+ throw new DevkitServerStoreError(
68699
+ "DATABASE_SCHEMA_TOO_NEW",
68700
+ `devkit server schema version ${userVersion} is newer than supported ${DEVKIT_SERVER_SCHEMA_VERSION}`
68701
+ );
68702
+ }
68703
+ if (userVersion < DEVKIT_SERVER_SCHEMA_VERSION) {
68704
+ throw new DevkitServerStoreError(
68705
+ "DATABASE_MIGRATION_REQUIRED",
68706
+ "devkit server database requires a write command to finish migration"
68707
+ );
68708
+ }
68709
+ }
68710
+ withWriteTransaction(operation) {
68711
+ return withBusyRetry(() => {
68712
+ this.db.exec("BEGIN IMMEDIATE");
68713
+ try {
68714
+ const result = operation();
68715
+ this.db.exec("COMMIT");
68716
+ return result;
68717
+ } catch (error) {
68718
+ rollbackQuietly(this.db);
68719
+ throw error;
68720
+ }
68721
+ });
68722
+ }
68723
+ };
68724
+ function applyMigrationV2(db) {
68725
+ db.exec(`
68726
+ CREATE TABLE ${TABLE_NAME} (
68727
+ id INTEGER PRIMARY KEY,
68728
+ origin TEXT NOT NULL,
68729
+ port INTEGER NOT NULL CHECK (port >= 1 AND port <= 65535),
68730
+ event_path TEXT NOT NULL,
68731
+ health_path TEXT NOT NULL,
68732
+ config_version INTEGER NOT NULL,
68733
+ updated_at INTEGER NOT NULL,
68734
+ CHECK (length(origin) > 0),
68735
+ CHECK (substr(event_path,1,1) = '/'),
68736
+ CHECK (substr(health_path,1,1) = '/'),
68737
+ UNIQUE (origin, port)
68738
+ )
68739
+ `);
68740
+ }
68741
+ function migrateV1ToV2(db) {
68742
+ const legacyRows = db.prepare(`
68743
+ SELECT id, origin, port, event_path, health_path, config_version, updated_at
68744
+ FROM ${TABLE_NAME} ORDER BY id ASC
68745
+ `).all().map((row) => ({ ...parseDevkitServerRow(row), id: readRowNumber(row, "id") }));
68746
+ db.exec(`ALTER TABLE ${TABLE_NAME} RENAME TO "devkit-server-v1"`);
68747
+ applyMigrationV2(db);
68748
+ const insert = db.prepare(`
68749
+ INSERT INTO ${TABLE_NAME} (
68750
+ id, origin, port, event_path, health_path, config_version, updated_at
68751
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
68752
+ `);
68753
+ for (const row of legacyRows) {
68754
+ const target = normalizeDevkitTarget(row.origin, row.port);
68755
+ insert.run(
68756
+ row.id,
68757
+ target.origin,
68758
+ target.port,
68759
+ row.event_path,
68760
+ row.health_path,
68761
+ row.config_version,
68762
+ row.updated_at
68763
+ );
68764
+ }
68765
+ db.exec('DROP TABLE "devkit-server-v1"');
68766
+ }
68767
+ function readRowNumber(row, field) {
68768
+ const value = row[field];
68769
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) {
68770
+ throw new DevkitServerStoreError("DATABASE_READ_FAILED", `invalid devkit server field: ${field}`);
68771
+ }
68772
+ return value;
68773
+ }
68774
+ function readRowString(row, field) {
68775
+ const value = row[field];
68776
+ if (typeof value !== "string") {
68777
+ throw new DevkitServerStoreError("DATABASE_READ_FAILED", `invalid devkit server field: ${field}`);
68778
+ }
68779
+ return value;
68780
+ }
68781
+ function parseDevkitServerRow(row) {
68782
+ return {
68783
+ origin: readRowString(row, "origin"),
68784
+ port: readRowNumber(row, "port"),
68785
+ event_path: readRowString(row, "event_path"),
68786
+ health_path: readRowString(row, "health_path"),
68787
+ config_version: readRowNumber(row, "config_version"),
68788
+ updated_at: readRowNumber(row, "updated_at")
68789
+ };
68790
+ }
68791
+ function assertValidPath(path2, label) {
68792
+ if (typeof path2 !== "string" || !path2.startsWith("/") || path2.length === 0) {
68793
+ throw new DevkitServerStoreError("INVALID_CONFIG_PATH", `${label} must start with /`);
68794
+ }
68795
+ }
68796
+ function readPragmaNumber(db, name) {
68797
+ const row = db.prepare(`PRAGMA ${name}`).get();
68798
+ return Number(row[name] ?? 0);
68799
+ }
68800
+ function assertNotSymlink(path2, label) {
68801
+ if (!(0, import_node_fs19.existsSync)(path2)) {
68802
+ return;
68803
+ }
68804
+ if ((0, import_node_fs19.lstatSync)(path2).isSymbolicLink()) {
68805
+ throw new DevkitServerStoreError("DATABASE_PATH_UNSAFE", `${label} must not be a symbolic link`);
68806
+ }
68807
+ }
68808
+ function assertSafeDatabasePath(dbPath) {
68809
+ assertSafeDatabaseFile(dbPath);
68810
+ for (const suffix of ["-journal", "-wal", "-shm"]) {
68811
+ assertNotSymlink(`${dbPath}${suffix}`, `devkit server database sidecar ${suffix}`);
68812
+ }
68813
+ }
68814
+ function assertSafeDatabaseFile(dbPath) {
68815
+ if (!(0, import_node_fs19.existsSync)(dbPath)) {
68816
+ return;
68817
+ }
68818
+ const stat4 = (0, import_node_fs19.lstatSync)(dbPath);
68819
+ if (stat4.isSymbolicLink()) {
68820
+ throw new DevkitServerStoreError(
68821
+ "DATABASE_PATH_UNSAFE",
68822
+ "devkit server database must not be a symbolic link"
68823
+ );
68824
+ }
68825
+ if (!stat4.isFile() || stat4.nlink !== 1) {
68826
+ throw new DevkitServerStoreError(
68827
+ "DATABASE_PATH_UNSAFE",
68828
+ "devkit server database must be a regular file with one hard link"
68829
+ );
68830
+ }
68831
+ }
68832
+ function rollbackQuietly(db) {
68833
+ try {
68834
+ db.exec("ROLLBACK");
68835
+ } catch {
68836
+ }
68837
+ }
68838
+ function withBusyRetry(operation) {
68839
+ for (let attempt = 1; ; attempt += 1) {
68840
+ try {
68841
+ return operation();
68842
+ } catch (error) {
68843
+ if (!isSqliteBusyError(error) || attempt >= WRITE_RETRY_ATTEMPTS) {
68844
+ throw error;
68845
+ }
68846
+ sleepSyncMs2(Math.min(100 * 2 ** (attempt - 1), 1600));
68847
+ }
68848
+ }
68849
+ }
68850
+ function sleepSyncMs2(ms) {
68851
+ const buffer2 = new Int32Array(new SharedArrayBuffer(4));
68852
+ Atomics.wait(buffer2, 0, 0, ms);
68853
+ }
68854
+ function loadSqlite4() {
68855
+ const originalEmitWarning = process.emitWarning;
68856
+ process.emitWarning = ((warning, ...args) => {
68857
+ const message = typeof warning === "string" ? warning : warning.message;
68858
+ if (message.includes("SQLite is an experimental feature") && args.some((arg) => arg === "ExperimentalWarning")) {
68859
+ return;
68860
+ }
68861
+ return originalEmitWarning.call(process, warning, ...args);
68862
+ });
68863
+ try {
68864
+ return require("node:sqlite");
68865
+ } finally {
68866
+ process.emitWarning = originalEmitWarning;
68867
+ }
68868
+ }
68869
+
67877
68870
  // src/listener.ts
67878
68871
  init_paths();
67879
68872
 
@@ -68248,13 +69241,13 @@ async function getHermesGatewayPluginStatus(options = {}) {
68248
69241
  const env = options.env ?? process.env;
68249
69242
  const hermesHome = env.HERMES_HOME?.trim() || (0, import_node_path25.join)((0, import_node_os8.homedir)(), ".hermes");
68250
69243
  const pluginYamlPath = (0, import_node_path25.join)(hermesHome, "plugins", "platforms", "okx-a2a", "plugin.yaml");
68251
- if (!(0, import_node_fs19.existsSync)(pluginYamlPath)) {
69244
+ if (!(0, import_node_fs20.existsSync)(pluginYamlPath)) {
68252
69245
  return { enabled: false, reason: "plugin_yaml_missing", hermesHome, checkedPath: pluginYamlPath };
68253
69246
  }
68254
69247
  const configPath = (0, import_node_path25.join)(hermesHome, "config.yaml");
68255
69248
  let content;
68256
69249
  try {
68257
- content = await (0, import_promises8.readFile)(configPath, "utf8");
69250
+ content = await (0, import_promises9.readFile)(configPath, "utf8");
68258
69251
  } catch {
68259
69252
  return { enabled: false, reason: "config_read_error", hermesHome, checkedPath: configPath };
68260
69253
  }
@@ -68376,6 +69369,27 @@ async function runListenerWithLock(options, paths) {
68376
69369
  const store = new TaskMessageStore(options.homeDir);
68377
69370
  const sessionStore = new SessionStore({ homeDir: options.homeDir });
68378
69371
  const commands = new CommandStore(options.homeDir);
69372
+ const devkitInitializer = DevkitServerStore.openForWrite(options.homeDir);
69373
+ devkitInitializer.close();
69374
+ const devkitReadSnapshots = () => {
69375
+ const snapshotStore = DevkitServerStore.openForRead(options.homeDir);
69376
+ if (!snapshotStore) {
69377
+ return [];
69378
+ }
69379
+ try {
69380
+ return snapshotStore.readSnapshots();
69381
+ } finally {
69382
+ snapshotStore.close();
69383
+ }
69384
+ };
69385
+ const devkitDispatcher = new DevkitDeliveryDispatcher({
69386
+ homeDir: options.homeDir
69387
+ });
69388
+ const devkitRouter = createDevkitAutoRouter({
69389
+ commands,
69390
+ dispatcher: devkitDispatcher,
69391
+ readSnapshots: devkitReadSnapshots
69392
+ });
68379
69393
  await store.ensureReady();
68380
69394
  let userAttentionEvents = null;
68381
69395
  try {
@@ -68439,20 +69453,20 @@ async function runListenerWithLock(options, paths) {
68439
69453
  createInboundMiddleware: (deps) => createMiddlewareFromCoreDeps(store, deps, {
68440
69454
  sessionStore,
68441
69455
  onJobMessageStored: async (event) => {
68442
- await enqueueAiJobMessageDispatch({ commands, event });
69456
+ await devkitRouter.routeJob(event);
68443
69457
  },
68444
69458
  onSessionMessage: async (event) => {
68445
- await enqueueAiSessionMessageDispatch({ commands, event });
69459
+ await devkitRouter.routeSession(event);
68446
69460
  }
68447
69461
  }),
68448
69462
  processOfflineMessage: (ctx, deps, replayOptions) => processOfflineFromCoreDeps(store, ctx, deps, {
68449
69463
  ...replayOptions,
68450
69464
  sessionStore,
68451
69465
  onJobMessageStored: async (event) => {
68452
- await enqueueAiJobMessageDispatch({ commands, event });
69466
+ await devkitRouter.routeJob(event);
68453
69467
  },
68454
69468
  onSessionMessage: async (event) => {
68455
- await enqueueAiSessionMessageDispatch({ commands, event });
69469
+ await devkitRouter.routeSession(event);
68456
69470
  }
68457
69471
  }),
68458
69472
  notifySessionExpired: (command) => {
@@ -68484,12 +69498,12 @@ async function runListenerWithLock(options, paths) {
68484
69498
  });
68485
69499
  }
68486
69500
  });
68487
- service.setPluginVersion("0.2.18");
69501
+ service.setPluginVersion("0.2.19-beta-fe6942ad54-261125201445");
68488
69502
  await service.init();
68489
69503
  const pluginVersionStatus = service.pluginVersionStatus;
68490
69504
  if (pluginVersionStatus.unavailable) {
68491
69505
  throw new Error(
68492
- `@okxweb3/a2a-node v${"0.2.18"} is below the required minimum v${pluginVersionStatus.minVersion}`
69506
+ `@okxweb3/a2a-node v${"0.2.19-beta-fe6942ad54-261125201445"} is below the required minimum v${pluginVersionStatus.minVersion}`
68493
69507
  );
68494
69508
  }
68495
69509
  const systemConfig = service.getSystemConfig();
@@ -68517,7 +69531,7 @@ async function runListenerWithLock(options, paths) {
68517
69531
  onchainosAgentId: "*",
68518
69532
  reason: "system-config missing sentryDsn",
68519
69533
  pluginId: "@okxweb3/a2a-node",
68520
- pluginVersion: "0.2.18"
69534
+ pluginVersion: "0.2.19-beta-fe6942ad54-261125201445"
68521
69535
  });
68522
69536
  }
68523
69537
  logWithTimestamp(
@@ -68849,6 +69863,7 @@ async function runListenerWithLock(options, paths) {
68849
69863
  logWithTimestamp("[okx-agent-task] failed to close user_attention IPC wake:", err);
68850
69864
  }
68851
69865
  stopClients(service);
69866
+ await devkitDispatcher.shutdown(SHUTDOWN_FORCE_RESOLVE_MS);
68852
69867
  sessionStore.close();
68853
69868
  clearTimeout(forceResolve);
68854
69869
  resolve11();
@@ -68871,14 +69886,331 @@ async function timeSettled(fn) {
68871
69886
  // src/index.ts
68872
69887
  init_paths();
68873
69888
 
69889
+ // src/devkit-cli.ts
69890
+ var import_node_crypto14 = require("node:crypto");
69891
+ init_daemon();
69892
+ init_sentry_logger();
69893
+ var DAEMON_NOT_RUNNING_MESSAGE = "\u5F53\u524D daemon \u672A\u8FD0\u884C,\u8BF7\u4F7F\u7528 okx-a2a start \u542F\u52A8 daemon";
69894
+ var DAEMON_STATUS_UNKNOWN_MESSAGE = "\u914D\u7F6E\u5DF2\u5199\u5165,\u4F46\u65E0\u6CD5\u786E\u8BA4 daemon \u8FD0\u884C\u72B6\u6001";
69895
+ var DevkitCliError = class extends Error {
69896
+ field;
69897
+ constructor(field, reason) {
69898
+ super(reason);
69899
+ this.name = "DevkitCliError";
69900
+ this.field = field;
69901
+ }
69902
+ toValidationError() {
69903
+ return { field: this.field, reason: this.message };
69904
+ }
69905
+ };
69906
+ async function handleDevkitCommand(args) {
69907
+ const wantsJson = args.includes("--json");
69908
+ const subcommand = args[0];
69909
+ if (!subcommand || isHelpArg(subcommand)) {
69910
+ printDevkitUsage();
69911
+ return;
69912
+ }
69913
+ if (args.slice(1).some(isHelpArg)) {
69914
+ printDevkitUsage();
69915
+ return;
69916
+ }
69917
+ if (subcommand === "register") {
69918
+ await handleRegister(args.slice(1), wantsJson);
69919
+ return;
69920
+ }
69921
+ if (subcommand === "unregister") {
69922
+ await handleUnregister(args.slice(1), wantsJson);
69923
+ return;
69924
+ }
69925
+ outputError(wantsJson, { field: "command", reason: `unknown devkit command: ${subcommand}` });
69926
+ process.exitCode = 1;
69927
+ }
69928
+ function printDevkitUsage() {
69929
+ console.log(`Usage: okx-a2a devkit <register|unregister> [options]
69930
+
69931
+ Commands:
69932
+ register Register a local custom server for daemon auto-message delivery.
69933
+ --url <origin> --port <n> --paths '{"event":"/path","health":"/path"}'
69934
+ Multiple loopback targets are allowed; localhost is stored as IPv4 127.0.0.1.
69935
+ unregister Remove one target with paired --url and --port, or omit both to unregister all.
69936
+ Already queued deliveries keep their captured target snapshot and are not retracted.
69937
+
69938
+ Options:
69939
+ --json Print machine-readable output.`);
69940
+ }
69941
+ async function handleRegister(args, wantsJson) {
69942
+ const operationId = (0, import_node_crypto14.randomUUID)();
69943
+ const startedAt = Date.now();
69944
+ logger.info(LogEvent.DEVKIT_REGISTER_REQUESTED, devkitSentryExtra({ operationId, phase: "requested" }));
69945
+ try {
69946
+ const parsed = parseArgs(args, { options: /* @__PURE__ */ new Set(["url", "port", "paths"]), flags: /* @__PURE__ */ new Set(["json"]) });
69947
+ const rawOrigin = requireOption(parsed, "url");
69948
+ const rawPort = requireOption(parsed, "port");
69949
+ const target = normalizeDevkitTarget(rawOrigin, parsePortValue(rawPort));
69950
+ const { eventPath, healthPath } = validatePaths(requireOption(parsed, "paths"));
69951
+ let config;
69952
+ try {
69953
+ const store = DevkitServerStore.openForWrite();
69954
+ try {
69955
+ config = store.register({ ...target, eventPath, healthPath });
69956
+ } finally {
69957
+ store.close();
69958
+ }
69959
+ } catch (error) {
69960
+ logger.error(
69961
+ LogEvent.DEVKIT_CONFIG_PERSIST_FAILED,
69962
+ error instanceof Error ? error : new Error(String(error)),
69963
+ devkitSentryExtra({ operationId, phase: "persist_failed", durationMs: Date.now() - startedAt })
69964
+ );
69965
+ outputError(wantsJson, {
69966
+ field: "config",
69967
+ reason: error instanceof DevkitServerStoreError ? error.message : "failed to persist devkit configuration"
69968
+ });
69969
+ process.exitCode = 1;
69970
+ return;
69971
+ }
69972
+ const outcome = config.configVersion === 1 ? "created" : "updated";
69973
+ const { daemonRunning, warning } = await resolveDaemonStatus(operationId);
69974
+ logger.info(
69975
+ LogEvent.DEVKIT_REGISTER_COMPLETED,
69976
+ devkitSentryExtra({
69977
+ operationId,
69978
+ phase: "completed",
69979
+ outcome,
69980
+ registrationId: String(config.configVersion),
69981
+ daemonRunning: String(daemonRunning),
69982
+ durationMs: Date.now() - startedAt
69983
+ })
69984
+ );
69985
+ outputSuccess(wantsJson, { daemonRunning, warning, configVersion: config.configVersion });
69986
+ } catch (error) {
69987
+ const detail = normalizeError(error);
69988
+ logger.error(
69989
+ LogEvent.DEVKIT_REGISTER_REJECTED,
69990
+ error instanceof Error ? error : new Error(String(error)),
69991
+ devkitSentryExtra({ operationId, phase: "rejected", reason: detail.field, durationMs: Date.now() - startedAt })
69992
+ );
69993
+ outputError(wantsJson, detail);
69994
+ process.exitCode = 1;
69995
+ }
69996
+ }
69997
+ async function handleUnregister(args, wantsJson) {
69998
+ const operationId = (0, import_node_crypto14.randomUUID)();
69999
+ const startedAt = Date.now();
70000
+ logger.info(LogEvent.DEVKIT_UNREGISTER_REQUESTED, devkitSentryExtra({ operationId, phase: "requested" }));
70001
+ try {
70002
+ const parsed = parseArgs(args, { options: /* @__PURE__ */ new Set(["url", "port"]), flags: /* @__PURE__ */ new Set(["json"]) });
70003
+ const rawOrigin = parsed.options.get("url")?.[0];
70004
+ const rawPort = parsed.options.get("port")?.[0];
70005
+ if (rawOrigin === void 0 !== (rawPort === void 0)) {
70006
+ throw new DevkitCliError("command", "--url and --port must be provided together");
70007
+ }
70008
+ const target = rawOrigin === void 0 || rawPort === void 0 ? void 0 : normalizeDevkitTarget(rawOrigin, parsePortValue(rawPort));
70009
+ let result;
70010
+ try {
70011
+ const store = DevkitServerStore.openForWrite();
70012
+ try {
70013
+ result = store.unregister(target);
70014
+ } finally {
70015
+ store.close();
70016
+ }
70017
+ } catch (error) {
70018
+ logger.error(
70019
+ LogEvent.DEVKIT_CONFIG_PERSIST_FAILED,
70020
+ error instanceof Error ? error : new Error(String(error)),
70021
+ devkitSentryExtra({ operationId, phase: "persist_failed", durationMs: Date.now() - startedAt })
70022
+ );
70023
+ outputError(wantsJson, {
70024
+ field: "config",
70025
+ reason: error instanceof DevkitServerStoreError ? error.message : "failed to persist devkit configuration"
70026
+ });
70027
+ process.exitCode = 1;
70028
+ return;
70029
+ }
70030
+ const outcome = result.removed ? "removed" : "noop";
70031
+ const { daemonRunning, warning } = await resolveDaemonStatus(operationId);
70032
+ logger.info(
70033
+ LogEvent.DEVKIT_UNREGISTER_COMPLETED,
70034
+ devkitSentryExtra({
70035
+ operationId,
70036
+ phase: "completed",
70037
+ outcome,
70038
+ removedCount: result.removedCount,
70039
+ ...target ? { targetOrigin: target.origin, targetPort: target.port } : {},
70040
+ daemonRunning: String(daemonRunning),
70041
+ durationMs: Date.now() - startedAt
70042
+ })
70043
+ );
70044
+ outputSuccess(wantsJson, { daemonRunning, warning, removedCount: result.removedCount });
70045
+ } catch (error) {
70046
+ const detail = normalizeError(error);
70047
+ logger.error(
70048
+ LogEvent.DEVKIT_REGISTER_REJECTED,
70049
+ error instanceof Error ? error : new Error(String(error)),
70050
+ devkitSentryExtra({ operationId, phase: "rejected", reason: detail.field, durationMs: Date.now() - startedAt })
70051
+ );
70052
+ outputError(wantsJson, detail);
70053
+ process.exitCode = 1;
70054
+ }
70055
+ }
70056
+ async function resolveDaemonStatus(operationId) {
70057
+ try {
70058
+ const status = await getDaemonStatus();
70059
+ if (status.running) {
70060
+ return { daemonRunning: true };
70061
+ }
70062
+ return {
70063
+ daemonRunning: false,
70064
+ warning: { code: "DAEMON_NOT_RUNNING", message: DAEMON_NOT_RUNNING_MESSAGE }
70065
+ };
70066
+ } catch {
70067
+ logger.info(LogEvent.DEVKIT_DAEMON_STATUS_UNKNOWN, devkitSentryExtra({ operationId, phase: "status_unknown" }));
70068
+ return {
70069
+ daemonRunning: null,
70070
+ warning: { code: "DAEMON_STATUS_UNKNOWN", message: DAEMON_STATUS_UNKNOWN_MESSAGE }
70071
+ };
70072
+ }
70073
+ }
70074
+ function parsePortValue(raw) {
70075
+ if (!/^(0|[1-9][0-9]*)$/.test(raw)) {
70076
+ throw new DevkitCliError("port", "--port must be an integer between 1 and 65535");
70077
+ }
70078
+ return Number(raw);
70079
+ }
70080
+ function validatePaths(raw) {
70081
+ let parsed;
70082
+ try {
70083
+ parsed = JSON.parse(raw);
70084
+ } catch {
70085
+ throw new DevkitCliError("paths", "--paths must be valid JSON");
70086
+ }
70087
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
70088
+ throw new DevkitCliError("paths", "--paths must be a JSON object");
70089
+ }
70090
+ const record = parsed;
70091
+ const keys = Object.keys(record);
70092
+ if (keys.length !== 2 || !keys.includes("event") || !keys.includes("health")) {
70093
+ throw new DevkitCliError("paths", '--paths must contain exactly the keys "event" and "health"');
70094
+ }
70095
+ const eventPath = validatePathValue(record.event, "event");
70096
+ const healthPath = validatePathValue(record.health, "health");
70097
+ return { eventPath, healthPath };
70098
+ }
70099
+ function validatePathValue(value, key) {
70100
+ if (typeof value !== "string" || value.length === 0) {
70101
+ throw new DevkitCliError("paths", `--paths.${key} must be a non-empty string`);
70102
+ }
70103
+ if (!value.startsWith("/") || value.startsWith("//")) {
70104
+ throw new DevkitCliError("paths", `--paths.${key} must start with a single "/"`);
70105
+ }
70106
+ if (value.includes("\\") || value.includes("?") || value.includes("#") || value.includes("..")) {
70107
+ throw new DevkitCliError(
70108
+ "paths",
70109
+ `--paths.${key} must not contain a query, fragment, backslash, "..", or an absolute URL`
70110
+ );
70111
+ }
70112
+ if (/^\/[a-zA-Z][a-zA-Z0-9+.-]*:/.test(value)) {
70113
+ throw new DevkitCliError("paths", `--paths.${key} must not be an absolute URL`);
70114
+ }
70115
+ return value;
70116
+ }
70117
+ function parseArgs(args, spec) {
70118
+ const options = /* @__PURE__ */ new Map();
70119
+ const flags = /* @__PURE__ */ new Set();
70120
+ for (let index2 = 0; index2 < args.length; index2 += 1) {
70121
+ const token = args[index2];
70122
+ if (!token.startsWith("--")) {
70123
+ throw new DevkitCliError("command", `unexpected positional argument: ${token}`);
70124
+ }
70125
+ const name = token.slice(2);
70126
+ if (spec.flags.has(name)) {
70127
+ if (flags.has(name)) {
70128
+ throw new DevkitCliError("command", `${token} must not be repeated`);
70129
+ }
70130
+ flags.add(name);
70131
+ continue;
70132
+ }
70133
+ if (!spec.options.has(name)) {
70134
+ throw new DevkitCliError("command", `unknown option ${token}`);
70135
+ }
70136
+ if (index2 + 1 >= args.length) {
70137
+ throw new DevkitCliError("command", `${token} requires a value`);
70138
+ }
70139
+ const value = args[++index2];
70140
+ if (value.startsWith("--")) {
70141
+ throw new DevkitCliError("command", `${token} requires a value`);
70142
+ }
70143
+ if (options.has(name)) {
70144
+ throw new DevkitCliError("command", `${token} must not be repeated`);
70145
+ }
70146
+ options.set(name, [value]);
70147
+ }
70148
+ return { options, flags };
70149
+ }
70150
+ function requireOption(parsed, name) {
70151
+ const value = parsed.options.get(name)?.[0];
70152
+ if (value === void 0 || value.length === 0) {
70153
+ throw new DevkitCliError(name, `--${name} is required`);
70154
+ }
70155
+ return value;
70156
+ }
70157
+ function outputSuccess(json, result) {
70158
+ if (json) {
70159
+ console.log(JSON.stringify({
70160
+ ok: true,
70161
+ daemonRunning: result.daemonRunning,
70162
+ ...result.warning ? { warning: result.warning } : {},
70163
+ ...result.configVersion === void 0 ? {} : { configVersion: result.configVersion },
70164
+ ...result.removedCount === void 0 ? {} : { removedCount: result.removedCount }
70165
+ }));
70166
+ return;
70167
+ }
70168
+ const daemonText = result.daemonRunning === null ? "unknown" : String(result.daemonRunning);
70169
+ console.log(`ok=true daemonRunning=${daemonText}${result.warning ? ` warning=${result.warning.code}` : ""}${result.removedCount === void 0 ? "" : ` removedCount=${result.removedCount}`}`);
70170
+ if (result.warning) {
70171
+ console.log(result.warning.message);
70172
+ }
70173
+ }
70174
+ function outputError(json, detail) {
70175
+ if (json) {
70176
+ console.log(JSON.stringify({ ok: false, error: detail.reason }));
70177
+ return;
70178
+ }
70179
+ console.error(`ok=false field=${detail.field} error=${detail.reason}`);
70180
+ }
70181
+ function normalizeError(error) {
70182
+ if (error instanceof DevkitCliError) {
70183
+ return error.toValidationError();
70184
+ }
70185
+ if (error instanceof DevkitTargetError) {
70186
+ return { field: error.field, reason: error.message };
70187
+ }
70188
+ if (error instanceof DevkitServerStoreError) {
70189
+ return { field: "config", reason: error.message };
70190
+ }
70191
+ return { field: "unknown", reason: error instanceof Error ? error.message : String(error) };
70192
+ }
70193
+ function devkitSentryExtra(extra) {
70194
+ const normalized = { component: "node_devkit" };
70195
+ for (const [key, value] of Object.entries(extra)) {
70196
+ if (value !== void 0) {
70197
+ normalized[key] = String(value);
70198
+ }
70199
+ }
70200
+ return normalized;
70201
+ }
70202
+ function isHelpArg(value) {
70203
+ return value === "help" || value === "-h" || value === "--help";
70204
+ }
70205
+
68874
70206
  // src/xmtp-test-cli.ts
68875
- var import_promises10 = require("node:fs/promises");
70207
+ var import_promises11 = require("node:fs/promises");
68876
70208
  var import_node_path27 = require("node:path");
68877
70209
  init_daemon();
68878
70210
 
68879
70211
  // src/log-tail.ts
68880
- var import_node_fs20 = require("node:fs");
68881
- var import_promises9 = require("node:fs/promises");
70212
+ var import_node_fs21 = require("node:fs");
70213
+ var import_promises10 = require("node:fs/promises");
68882
70214
  var import_node_path26 = require("node:path");
68883
70215
  var import_node_string_decoder = require("node:string_decoder");
68884
70216
  init_win_spawn();
@@ -68936,7 +70268,6 @@ async function followFile(filePath, onData, options = {}) {
68936
70268
  let done = false;
68937
70269
  await new Promise((resolvePromise, rejectPromise) => {
68938
70270
  let watcher;
68939
- let timer;
68940
70271
  const finish = (error) => {
68941
70272
  if (done) {
68942
70273
  return;
@@ -68973,7 +70304,7 @@ async function followFile(filePath, onData, options = {}) {
68973
70304
  let handle;
68974
70305
  try {
68975
70306
  try {
68976
- handle = await (0, import_promises9.open)(filePath, "r");
70307
+ handle = await (0, import_promises10.open)(filePath, "r");
68977
70308
  } catch (error) {
68978
70309
  if (error.code === "ENOENT") {
68979
70310
  markMissing();
@@ -69033,12 +70364,12 @@ async function followFile(filePath, onData, options = {}) {
69033
70364
  checking = false;
69034
70365
  }
69035
70366
  };
69036
- timer = setInterval(() => {
70367
+ const timer = setInterval(() => {
69037
70368
  void check();
69038
70369
  }, pollIntervalMs);
69039
70370
  const targetName = (0, import_node_path26.basename)(filePath);
69040
70371
  try {
69041
- watcher = (0, import_node_fs20.watch)((0, import_node_path26.dirname)(filePath), (_eventType, filename) => {
70372
+ watcher = (0, import_node_fs21.watch)((0, import_node_path26.dirname)(filePath), (_eventType, filename) => {
69042
70373
  if (filename === null || filename.toString() === targetName) {
69043
70374
  void check();
69044
70375
  }
@@ -69079,7 +70410,7 @@ async function readTailSnapshot(filePath, maxLines) {
69079
70410
  async function readTailSnapshotOnce(filePath, maxLines) {
69080
70411
  let handle;
69081
70412
  try {
69082
- handle = await (0, import_promises9.open)(filePath, "r");
70413
+ handle = await (0, import_promises10.open)(filePath, "r");
69083
70414
  } catch (error) {
69084
70415
  if (error.code === "ENOENT") {
69085
70416
  return { text: "", offset: 0, fileIdentity: null };
@@ -69136,7 +70467,7 @@ async function readTailSnapshotOnce(filePath, maxLines) {
69136
70467
  }
69137
70468
  async function currentPositionOrMissing(filePath) {
69138
70469
  try {
69139
- const stats = await (0, import_promises9.stat)(filePath);
70470
+ const stats = await (0, import_promises10.stat)(filePath);
69140
70471
  return { offset: stats.size, fileIdentity: identityForStats(stats) };
69141
70472
  } catch (error) {
69142
70473
  if (error.code === "ENOENT") {
@@ -69233,7 +70564,7 @@ async function startXmtpTest(args, releaseInfo) {
69233
70564
  const runId = requestedRunId ? validateRunId(requestedRunId) : createRunId(requestedName);
69234
70565
  const files = resolveRunFiles(testsDir, runId);
69235
70566
  try {
69236
- await (0, import_promises10.stat)(files.runDir);
70567
+ await (0, import_promises11.stat)(files.runDir);
69237
70568
  throw new Error(`XMTP test run already exists: ${runId}`);
69238
70569
  } catch (error) {
69239
70570
  if (error.code !== "ENOENT") {
@@ -69241,7 +70572,7 @@ async function startXmtpTest(args, releaseInfo) {
69241
70572
  }
69242
70573
  }
69243
70574
  await ensurePrivateDir(files.runDir);
69244
- await (0, import_promises10.writeFile)(files.eventsPath, "", { encoding: "utf8", mode: 384 });
70575
+ await (0, import_promises11.writeFile)(files.eventsPath, "", { encoding: "utf8", mode: 384 });
69245
70576
  const manifest = {
69246
70577
  runId,
69247
70578
  name: requestedName,
@@ -69285,7 +70616,7 @@ async function stopXmtpTest(args) {
69285
70616
  }
69286
70617
  const runId = validateRunId(active.runId);
69287
70618
  const files = resolveRunFiles(testsDir, runId);
69288
- await (0, import_promises10.unlink)(activePath);
70619
+ await (0, import_promises11.unlink)(activePath);
69289
70620
  const manifest = await readRequiredJson(files.manifestPath);
69290
70621
  const completed = {
69291
70622
  ...manifest,
@@ -69603,7 +70934,7 @@ async function resolveRequestedRunId(testsDir, args, preferActive = false) {
69603
70934
  async function findLatestRunId(testsDir) {
69604
70935
  let entries;
69605
70936
  try {
69606
- entries = await (0, import_promises10.readdir)(testsDir, { withFileTypes: true });
70937
+ entries = await (0, import_promises11.readdir)(testsDir, { withFileTypes: true });
69607
70938
  } catch (error) {
69608
70939
  if (error.code === "ENOENT") {
69609
70940
  return null;
@@ -69628,7 +70959,7 @@ async function findLatestRunId(testsDir) {
69628
70959
  async function readMetricEvents(path2) {
69629
70960
  let text;
69630
70961
  try {
69631
- text = await (0, import_promises10.readFile)(path2, "utf8");
70962
+ text = await (0, import_promises11.readFile)(path2, "utf8");
69632
70963
  } catch (error) {
69633
70964
  if (error.code === "ENOENT") {
69634
70965
  return [];
@@ -69652,9 +70983,9 @@ function parseMetricEvent(line) {
69652
70983
  }
69653
70984
  }
69654
70985
  async function ensurePrivateDir(path2) {
69655
- await (0, import_promises10.mkdir)(path2, { recursive: true, mode: 448 });
70986
+ await (0, import_promises11.mkdir)(path2, { recursive: true, mode: 448 });
69656
70987
  try {
69657
- await (0, import_promises10.chmod)(path2, 448);
70988
+ await (0, import_promises11.chmod)(path2, 448);
69658
70989
  } catch (error) {
69659
70990
  const code = error.code;
69660
70991
  if (code !== "EPERM" && code !== "EACCES") {
@@ -69664,12 +70995,12 @@ async function ensurePrivateDir(path2) {
69664
70995
  }
69665
70996
  async function writeJson(path2, value) {
69666
70997
  const temporary = `${path2}.${process.pid}.tmp`;
69667
- await (0, import_promises10.writeFile)(temporary, `${JSON.stringify(value, null, 2)}
70998
+ await (0, import_promises11.writeFile)(temporary, `${JSON.stringify(value, null, 2)}
69668
70999
  `, {
69669
71000
  encoding: "utf8",
69670
71001
  mode: 384
69671
71002
  });
69672
- await (0, import_promises10.rename)(temporary, path2);
71003
+ await (0, import_promises11.rename)(temporary, path2);
69673
71004
  }
69674
71005
  async function readRequiredJson(path2) {
69675
71006
  const value = await readJsonIfExists(path2);
@@ -69680,7 +71011,7 @@ async function readRequiredJson(path2) {
69680
71011
  }
69681
71012
  async function readJsonIfExists(path2) {
69682
71013
  try {
69683
- return JSON.parse(await (0, import_promises10.readFile)(path2, "utf8"));
71014
+ return JSON.parse(await (0, import_promises11.readFile)(path2, "utf8"));
69684
71015
  } catch (error) {
69685
71016
  if (error.code === "ENOENT") {
69686
71017
  return null;
@@ -69972,21 +71303,21 @@ function parseLogsTailArgs(args, subcommand) {
69972
71303
 
69973
71304
  // src/logs-export.ts
69974
71305
  var import_node_child_process10 = require("node:child_process");
69975
- var import_node_fs27 = require("node:fs");
69976
- var import_promises15 = require("node:fs/promises");
71306
+ var import_node_fs28 = require("node:fs");
71307
+ var import_promises16 = require("node:fs/promises");
69977
71308
  var import_node_os12 = require("node:os");
69978
71309
  var import_node_path34 = require("node:path");
69979
71310
  var import_jszip = __toESM(require_lib3());
69980
71311
 
69981
71312
  // src/logs-export-archive.ts
69982
- var import_node_crypto14 = require("node:crypto");
69983
- var import_node_fs24 = require("node:fs");
69984
- var import_promises13 = require("node:fs/promises");
71313
+ var import_node_crypto15 = require("node:crypto");
71314
+ var import_node_fs25 = require("node:fs");
71315
+ var import_promises14 = require("node:fs/promises");
69985
71316
  var import_node_path31 = require("node:path");
69986
71317
 
69987
71318
  // src/logs-export-filter.ts
69988
- var import_node_fs23 = require("node:fs");
69989
- var import_promises12 = require("node:fs/promises");
71319
+ var import_node_fs24 = require("node:fs");
71320
+ var import_promises13 = require("node:fs/promises");
69990
71321
  var import_node_path30 = require("node:path");
69991
71322
  var import_node_readline2 = require("node:readline");
69992
71323
  var MAX_SINGLE_RECORD_BYTES = 2 * 1024 * 1024;
@@ -70096,7 +71427,7 @@ async function readFilteredLog(path2, options, correlationIds, requireCorrelatio
70096
71427
  };
70097
71428
  }
70098
71429
  async function* streamLogRecords(path2, mode) {
70099
- const input = (0, import_node_fs23.createReadStream)(path2, { encoding: "utf8" });
71430
+ const input = (0, import_node_fs24.createReadStream)(path2, { encoding: "utf8" });
70100
71431
  const lines = (0, import_node_readline2.createInterface)({ input, crlfDelay: Infinity });
70101
71432
  let current = null;
70102
71433
  try {
@@ -70513,7 +71844,7 @@ function escapeRegExp2(value) {
70513
71844
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
70514
71845
  }
70515
71846
  async function assertRegularFile(path2) {
70516
- const file = await (0, import_promises12.lstat)(path2);
71847
+ const file = await (0, import_promises13.lstat)(path2);
70517
71848
  if (file.isSymbolicLink() || !file.isFile()) {
70518
71849
  throw Object.assign(
70519
71850
  new Error(`Refusing non-regular diagnostic source: ${(0, import_node_path30.basename)(path2)}`),
@@ -70598,7 +71929,7 @@ function recordCollector(state, result) {
70598
71929
  async function resolveOutputPath(requested, input) {
70599
71930
  if (requested) {
70600
71931
  const output2 = (0, import_node_path31.isAbsolute)(requested) ? requested : (0, import_node_path31.resolve)(input.cwd, requested);
70601
- if ((0, import_node_fs24.existsSync)(output2) && !input.overwrite) {
71932
+ if ((0, import_node_fs25.existsSync)(output2) && !input.overwrite) {
70602
71933
  throw new Error(`Output already exists: ${output2}. Pass --overwrite to replace it.`);
70603
71934
  }
70604
71935
  return output2;
@@ -70606,42 +71937,42 @@ async function resolveOutputPath(requested, input) {
70606
71937
  const stamp = input.now.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
70607
71938
  const base = `okx-a2a-diagnostics-${stamp}.zip`;
70608
71939
  let output = (0, import_node_path31.join)(input.cwd, base);
70609
- for (let suffix = 2; (0, import_node_fs24.existsSync)(output); suffix += 1) {
71940
+ for (let suffix = 2; (0, import_node_fs25.existsSync)(output); suffix += 1) {
70610
71941
  output = (0, import_node_path31.join)(input.cwd, `okx-a2a-diagnostics-${stamp}-${suffix}.zip`);
70611
71942
  }
70612
71943
  return output;
70613
71944
  }
70614
71945
  async function writeArchiveAtomically(outputPath, archive, overwrite) {
70615
- await (0, import_promises13.mkdir)((0, import_node_path31.dirname)(outputPath), { recursive: true });
71946
+ await (0, import_promises14.mkdir)((0, import_node_path31.dirname)(outputPath), { recursive: true });
70616
71947
  const temporaryPath = (0, import_node_path31.join)(
70617
71948
  (0, import_node_path31.dirname)(outputPath),
70618
- `.${(0, import_node_path31.basename)(outputPath)}.${(0, import_node_crypto14.randomUUID)()}.tmp`
71949
+ `.${(0, import_node_path31.basename)(outputPath)}.${(0, import_node_crypto15.randomUUID)()}.tmp`
70619
71950
  );
70620
71951
  try {
70621
- await (0, import_promises13.writeFile)(temporaryPath, archive, { flag: "wx", mode: 384 });
71952
+ await (0, import_promises14.writeFile)(temporaryPath, archive, { flag: "wx", mode: 384 });
70622
71953
  if (overwrite) {
70623
- if ((0, import_node_fs24.existsSync)(outputPath)) {
70624
- await (0, import_promises13.rm)(outputPath, { force: true });
71954
+ if ((0, import_node_fs25.existsSync)(outputPath)) {
71955
+ await (0, import_promises14.rm)(outputPath, { force: true });
70625
71956
  }
70626
- await (0, import_promises13.rename)(temporaryPath, outputPath);
71957
+ await (0, import_promises14.rename)(temporaryPath, outputPath);
70627
71958
  } else {
70628
- await (0, import_promises13.link)(temporaryPath, outputPath);
70629
- await (0, import_promises13.rm)(temporaryPath, { force: true });
71959
+ await (0, import_promises14.link)(temporaryPath, outputPath);
71960
+ await (0, import_promises14.rm)(temporaryPath, { force: true });
70630
71961
  }
70631
71962
  } catch (err) {
70632
- await (0, import_promises13.rm)(temporaryPath, { force: true }).catch(() => void 0);
71963
+ await (0, import_promises14.rm)(temporaryPath, { force: true }).catch(() => void 0);
70633
71964
  throw err;
70634
71965
  }
70635
71966
  }
70636
71967
  function hashDiagnosticFileContent(content) {
70637
- return (0, import_node_crypto14.createHash)("sha256").update(content).digest("hex");
71968
+ return (0, import_node_crypto15.createHash)("sha256").update(content).digest("hex");
70638
71969
  }
70639
71970
  function isUnavailableError(err) {
70640
71971
  return !!err && typeof err === "object" && "diagnosticUnavailable" in err;
70641
71972
  }
70642
71973
 
70643
71974
  // src/logs-export-database.ts
70644
- var import_node_fs25 = require("node:fs");
71975
+ var import_node_fs26 = require("node:fs");
70645
71976
  var PROVIDERS = ["codex", "claude", "openclaw", "hermes"];
70646
71977
  function readSessionSqliteSnapshot(dbPath, options, selectedJobIds) {
70647
71978
  const hasTimeWindow2 = options.fromMs !== void 0 && options.toMs !== void 0;
@@ -70739,11 +72070,11 @@ function readSessionSqliteSnapshot(dbPath, options, selectedJobIds) {
70739
72070
  };
70740
72071
  }
70741
72072
  function readSqliteRows(dbPath, sql, params = []) {
70742
- if (!(0, import_node_fs25.existsSync)(dbPath)) {
72073
+ if (!(0, import_node_fs26.existsSync)(dbPath)) {
70743
72074
  throw unavailable(`SQLite database not found: ${dbPath}`);
70744
72075
  }
70745
- const { DatabaseSync: DatabaseSync4 } = loadSqlite4();
70746
- const db = new DatabaseSync4(dbPath, { readOnly: true });
72076
+ const { DatabaseSync: DatabaseSync5 } = loadSqlite5();
72077
+ const db = new DatabaseSync5(dbPath, { readOnly: true });
70747
72078
  try {
70748
72079
  return db.prepare(sql).all(...params);
70749
72080
  } finally {
@@ -70761,7 +72092,7 @@ function emptySqliteSnapshot() {
70761
72092
  storedProviderCommands: {}
70762
72093
  };
70763
72094
  }
70764
- function loadSqlite4() {
72095
+ function loadSqlite5() {
70765
72096
  const originalEmitWarning = process.emitWarning;
70766
72097
  process.emitWarning = ((warning, ...args) => {
70767
72098
  const message = typeof warning === "string" ? warning : warning.message;
@@ -70894,9 +72225,9 @@ function isProvider2(value) {
70894
72225
  }
70895
72226
 
70896
72227
  // src/logs-export-utils.ts
70897
- var import_node_crypto15 = require("node:crypto");
70898
- var import_node_fs26 = require("node:fs");
70899
- var import_promises14 = require("node:fs/promises");
72228
+ var import_node_crypto16 = require("node:crypto");
72229
+ var import_node_fs27 = require("node:fs");
72230
+ var import_promises15 = require("node:fs/promises");
70900
72231
  var import_node_path33 = require("node:path");
70901
72232
  var MAX_JSON_FILE_BYTES = 20 * 1024 * 1024;
70902
72233
  var STRONG_CORRELATION_KEYS = /* @__PURE__ */ new Set([
@@ -71012,7 +72343,7 @@ function collectCorrelationIds(value, output, key = "", depth = 0) {
71012
72343
  }
71013
72344
  async function safeReadDir(path2) {
71014
72345
  try {
71015
- return await (0, import_promises14.readdir)(path2);
72346
+ return await (0, import_promises15.readdir)(path2);
71016
72347
  } catch (err) {
71017
72348
  if (err.code === "ENOENT") {
71018
72349
  return [];
@@ -71025,11 +72356,11 @@ async function readJsonObject(path2) {
71025
72356
  if (file.size > MAX_JSON_FILE_BYTES) {
71026
72357
  throw unavailable2(`JSON source exceeds ${MAX_JSON_FILE_BYTES} bytes`);
71027
72358
  }
71028
- const value = parseJsonValue3(await (0, import_promises14.readFile)(path2, "utf8"));
72359
+ const value = parseJsonValue3(await (0, import_promises15.readFile)(path2, "utf8"));
71029
72360
  return isRecord7(value) ? value : null;
71030
72361
  }
71031
72362
  async function assertRegularFile2(path2) {
71032
- const file = await (0, import_promises14.lstat)(path2);
72363
+ const file = await (0, import_promises15.lstat)(path2);
71033
72364
  if (file.isSymbolicLink() || !file.isFile()) {
71034
72365
  throw unavailable2(`Refusing non-regular diagnostic source: ${(0, import_node_path33.basename)(path2)}`);
71035
72366
  }
@@ -71037,8 +72368,8 @@ async function assertRegularFile2(path2) {
71037
72368
  }
71038
72369
  async function inspectRegularFile(path2) {
71039
72370
  const file = await assertRegularFile2(path2);
71040
- const hash2 = (0, import_node_crypto15.createHash)("sha256");
71041
- for await (const chunk of (0, import_node_fs26.createReadStream)(path2)) {
72371
+ const hash2 = (0, import_node_crypto16.createHash)("sha256");
72372
+ for await (const chunk of (0, import_node_fs27.createReadStream)(path2)) {
71042
72373
  hash2.update(chunk);
71043
72374
  }
71044
72375
  return {
@@ -71290,7 +72621,7 @@ async function exportDiagnosticLogs(options) {
71290
72621
  node: process.version,
71291
72622
  platform: process.platform,
71292
72623
  arch: process.arch,
71293
- packageVersion: true ? "0.2.18" : "unknown",
72624
+ packageVersion: true ? "0.2.19-beta-fe6942ad54-261125201445" : "unknown",
71294
72625
  sensitiveContentIncluded: options.includeSensitiveContent,
71295
72626
  listenerAndLlmContentIncluded: true,
71296
72627
  credentialsAlwaysRedacted: true,
@@ -71707,7 +73038,7 @@ async function collectProviderDiagnostics(state, provider, storedCommand, option
71707
73038
  const configCandidates = providerConfigCandidates(provider, paths.taskHome);
71708
73039
  const configNotes = [];
71709
73040
  for (const candidate of configCandidates) {
71710
- if (!(0, import_node_fs27.existsSync)(candidate.path)) {
73041
+ if (!(0, import_node_fs28.existsSync)(candidate.path)) {
71711
73042
  continue;
71712
73043
  }
71713
73044
  let info;
@@ -71758,7 +73089,7 @@ async function collectOpenClawSessionStore(state, options) {
71758
73089
  for (const agentId of allAgentNames.slice(0, MAX_OPENCLAW_AGENTS)) {
71759
73090
  const sessionsDir = (0, import_node_path34.join)(agentsDir, agentId, "sessions");
71760
73091
  try {
71761
- const info = await (0, import_promises15.lstat)(sessionsDir);
73092
+ const info = await (0, import_promises16.lstat)(sessionsDir);
71762
73093
  if (info.isSymbolicLink() || !info.isDirectory()) {
71763
73094
  skippedSources += 1;
71764
73095
  continue;
@@ -71935,7 +73266,7 @@ async function collectGatewayLogs(state, provider, paths, options, correlationId
71935
73266
  async function collectDoctorSnapshot(state, options) {
71936
73267
  await runCollector(state, "doctor", async () => {
71937
73268
  const cliPath = process.argv[1];
71938
- if (!cliPath || !(0, import_node_fs27.existsSync)(cliPath)) {
73269
+ if (!cliPath || !(0, import_node_fs28.existsSync)(cliPath)) {
71939
73270
  throw unavailable2("Unable to resolve the running okx-a2a CLI path");
71940
73271
  }
71941
73272
  const result = (0, import_node_child_process10.spawnSync)(process.execPath, [
@@ -73148,7 +74479,7 @@ var autostartChecker = {
73148
74479
  title: "Daemon autostart",
73149
74480
  status: "fail",
73150
74481
  severity: "recommended",
73151
- detail: "OS autostart is not installed. This is OPTIONAL and NOT blocking \u2014 the daemon runs fine for this session; autostart only makes the A2A service start automatically on every boot/logon so you don't have to start it manually." + (needsAdmin ? " On Windows this needs an Administrator terminal." : ""),
74482
+ detail: `OS autostart is not installed. This is OPTIONAL and NOT blocking \u2014 the daemon runs fine for this session; autostart only makes the A2A service start automatically on every boot/logon so you don't have to start it manually.${needsAdmin ? " On Windows this needs an Administrator terminal." : ""}`,
73152
74483
  fix: needsAdmin ? {
73153
74484
  kind: "manual",
73154
74485
  description: "Optional: to start the A2A daemon automatically at every logon, run this once from an Administrator PowerShell. Skipping it is fine \u2014 just run `okx-a2a daemon start` when you need the daemon.",
@@ -73202,7 +74533,7 @@ async function runDoctor(options = {}) {
73202
74533
  platform: options.platform ?? process.platform,
73203
74534
  env: options.env ?? process.env,
73204
74535
  target: options.target ?? resolveDoctorTarget(options.env ?? process.env),
73205
- cliVersion: options.cliVersion ?? (true ? "0.2.18" : "0.0.0"),
74536
+ cliVersion: options.cliVersion ?? (true ? "0.2.19-beta-fe6942ad54-261125201445" : "0.0.0"),
73206
74537
  fixMode: options.fix === true,
73207
74538
  nonInteractive: options.nonInteractive === true,
73208
74539
  packageChanged: false,
@@ -73443,7 +74774,23 @@ init_autostart_windows();
73443
74774
  DEFAULT_LOG_TAIL_LIMIT,
73444
74775
  DEFAULT_OFFLINE_REPLAY_INTERVAL_SEC,
73445
74776
  DEFAULT_XMTP_CLIENT_RECYCLE_INTERVAL_SEC,
74777
+ DEVKIT_DROP_REASON,
74778
+ DEVKIT_MAX_CONCURRENCY,
74779
+ DEVKIT_MAX_MESSAGE_BYTES,
74780
+ DEVKIT_MAX_PENDING,
74781
+ DEVKIT_MAX_PENDING_BYTES,
74782
+ DEVKIT_OUTCOME,
74783
+ DEVKIT_REQUEST_BUDGET_MS,
74784
+ DEVKIT_RESPONSE_DIAGNOSTIC_MAX_BYTES,
74785
+ DEVKIT_RESPONSE_SUMMARY_MAX_CHARS,
74786
+ DEVKIT_SERVER_APPLICATION_ID,
74787
+ DEVKIT_SERVER_DB_NAME,
74788
+ DEVKIT_SERVER_SCHEMA_VERSION,
73446
74789
  DOCTOR_MIN_NODE_VERSION,
74790
+ DevkitDeliveryDispatcher,
74791
+ DevkitServerStore,
74792
+ DevkitServerStoreError,
74793
+ DevkitTargetError,
73447
74794
  GatewayOutboundBehavior,
73448
74795
  HEARTBEAT_GATEWAY_CHECK_TIMEOUT_MS,
73449
74796
  InboundReplayGate,
@@ -73501,6 +74848,7 @@ init_autostart_windows();
73501
74848
  buildExternalCommandInvocation,
73502
74849
  buildGatewayOutboundExtra,
73503
74850
  buildInboundTerminalExtras,
74851
+ buildJobEnvelope,
73504
74852
  buildLaunchdPlist,
73505
74853
  buildLauncherEntryJs,
73506
74854
  buildMessageEligibleArgs,
@@ -73511,6 +74859,7 @@ init_autostart_windows();
73511
74859
  buildSchtasksRunArgs,
73512
74860
  buildSeaConfig,
73513
74861
  buildServicePath,
74862
+ buildSessionEnvelope,
73514
74863
  buildSessionKey,
73515
74864
  buildSystemMessageNotice,
73516
74865
  buildSystemStoredMessage,
@@ -73528,6 +74877,8 @@ init_autostart_windows();
73528
74877
  checkCodexCliAuthStatus,
73529
74878
  checkCodexReadiness,
73530
74879
  claimActiveDaemon,
74880
+ classifyFetchFailure,
74881
+ classifyHttpOutcome,
73531
74882
  classifyJobBindingSource,
73532
74883
  clearCodexReadinessCache,
73533
74884
  codexCommandResolvesWithoutOverride,
@@ -73536,6 +74887,7 @@ init_autostart_windows();
73536
74887
  collectCodexCommandCandidates,
73537
74888
  commandExists,
73538
74889
  createAiToolFailureTracker,
74890
+ createDevkitAutoRouter,
73539
74891
  createFileMessageHandler,
73540
74892
  createOutboundBehavior,
73541
74893
  createUserAttentionWatchParentMonitor,
@@ -73546,6 +74898,7 @@ init_autostart_windows();
73546
74898
  detectGatewayInvocation,
73547
74899
  detectMessageEligibleOfflineReplaySupport,
73548
74900
  detectRuntime,
74901
+ devkitServerDbExists,
73549
74902
  ensureDaemonReady,
73550
74903
  ensureDefaultAiProvider,
73551
74904
  ensureOpenClawOkxA2aPluginConfig,
@@ -73568,6 +74921,7 @@ init_autostart_windows();
73568
74921
  getSessionBusyTracker,
73569
74922
  getXmtpCreationCooldown,
73570
74923
  handleCapabilitiesCommand,
74924
+ handleDevkitCommand,
73571
74925
  handleDoctorCommand,
73572
74926
  handleXmtpDebugCommand,
73573
74927
  handleXmtpSendCommand,
@@ -73609,6 +74963,7 @@ init_autostart_windows();
73609
74963
  nodeVersionSatisfies,
73610
74964
  normalizeAiProvider,
73611
74965
  normalizeAiRuntimeProvider,
74966
+ normalizeDevkitTarget,
73612
74967
  normalizeHermesOkxA2aPluginConfig,
73613
74968
  notifyAgentMessageToUserAttention,
73614
74969
  notifyDirectToUserAttention,
@@ -73625,6 +74980,7 @@ init_autostart_windows();
73625
74980
  persistCurrentRuntimeSelectionForNewJob,
73626
74981
  pickOnchainosWin32Candidate,
73627
74982
  prepareAndBindCurrentRuntimeForNewJob,
74983
+ printDevkitUsage,
73628
74984
  printLogsExportUsage,
73629
74985
  printXmtpTestUsage,
73630
74986
  probeCodexAuthStatus,
@@ -73636,6 +74992,7 @@ init_autostart_windows();
73636
74992
  readLastLines,
73637
74993
  readParentProcessCommandForPlatform,
73638
74994
  readUserAttentionWatcherEvent,
74995
+ redactSummary,
73639
74996
  refreshAgentsAndWait,
73640
74997
  refreshOnchainosVersionMetadata,
73641
74998
  registerUserAttentionWatcher,
@@ -73658,6 +75015,7 @@ init_autostart_windows();
73658
75015
  resolveCodexCommandSource,
73659
75016
  resolveConfiguredAiProvider,
73660
75017
  resolveConfiguredAiProviderForJob,
75018
+ resolveDevkitServerDbPath,
73661
75019
  resolveDirectCommunicationSessionTarget,
73662
75020
  resolveDoctorTarget,
73663
75021
  resolveEnvelopePayload,