@okxweb3/a2a-node 0.2.9 → 0.2.10-beta-98689bff7a-260826152645

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 (4) hide show
  1. package/README.md +26 -0
  2. package/dist/cli.js +1644 -262
  3. package/dist/index.js +1440 -211
  4. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -3992,7 +3992,7 @@ var require_is = __commonJS({
3992
3992
  function isPrimitive(wat) {
3993
3993
  return wat === null || typeof wat !== "object" && typeof wat !== "function";
3994
3994
  }
3995
- function isPlainObject4(wat) {
3995
+ function isPlainObject6(wat) {
3996
3996
  return isBuiltin(wat, "Object");
3997
3997
  }
3998
3998
  function isEvent(wat) {
@@ -4008,7 +4008,7 @@ var require_is = __commonJS({
4008
4008
  return Boolean(wat && wat.then && typeof wat.then === "function");
4009
4009
  }
4010
4010
  function isSyntheticEvent(wat) {
4011
- return isPlainObject4(wat) && "nativeEvent" in wat && "preventDefault" in wat && "stopPropagation" in wat;
4011
+ return isPlainObject6(wat) && "nativeEvent" in wat && "preventDefault" in wat && "stopPropagation" in wat;
4012
4012
  }
4013
4013
  function isNaN2(wat) {
4014
4014
  return typeof wat === "number" && wat !== wat;
@@ -4031,7 +4031,7 @@ var require_is = __commonJS({
4031
4031
  exports2.isEvent = isEvent;
4032
4032
  exports2.isInstanceOf = isInstanceOf;
4033
4033
  exports2.isNaN = isNaN2;
4034
- exports2.isPlainObject = isPlainObject4;
4034
+ exports2.isPlainObject = isPlainObject6;
4035
4035
  exports2.isPrimitive = isPrimitive;
4036
4036
  exports2.isRegExp = isRegExp;
4037
4037
  exports2.isString = isString;
@@ -5839,7 +5839,7 @@ var require_path = __commonJS({
5839
5839
  function isAbsolute4(path2) {
5840
5840
  return path2.charAt(0) === "/";
5841
5841
  }
5842
- function join31(...args) {
5842
+ function join33(...args) {
5843
5843
  return normalizePath(args.join("/"));
5844
5844
  }
5845
5845
  function dirname10(path2) {
@@ -5864,7 +5864,7 @@ var require_path = __commonJS({
5864
5864
  exports2.basename = basename8;
5865
5865
  exports2.dirname = dirname10;
5866
5866
  exports2.isAbsolute = isAbsolute4;
5867
- exports2.join = join31;
5867
+ exports2.join = join33;
5868
5868
  exports2.normalizePath = normalizePath;
5869
5869
  exports2.relative = relative;
5870
5870
  exports2.resolve = resolve11;
@@ -15098,7 +15098,7 @@ var require_promisify = __commonJS({
15098
15098
  "../../node_modules/agent-base/dist/src/promisify.js"(exports2) {
15099
15099
  "use strict";
15100
15100
  Object.defineProperty(exports2, "__esModule", { value: true });
15101
- function promisify3(fn) {
15101
+ function promisify4(fn) {
15102
15102
  return function(req, opts) {
15103
15103
  return new Promise((resolve11, reject) => {
15104
15104
  fn.call(this, req, opts, (err, rtn) => {
@@ -15111,7 +15111,7 @@ var require_promisify = __commonJS({
15111
15111
  });
15112
15112
  };
15113
15113
  }
15114
- exports2.default = promisify3;
15114
+ exports2.default = promisify4;
15115
15115
  }
15116
15116
  });
15117
15117
 
@@ -30987,7 +30987,7 @@ var require_websocket2 = __commonJS({
30987
30987
  var http2 = require("http");
30988
30988
  var net = require("net");
30989
30989
  var tls = require("tls");
30990
- var { randomBytes: randomBytes3, createHash: createHash6 } = require("crypto");
30990
+ var { randomBytes: randomBytes3, createHash: createHash7 } = require("crypto");
30991
30991
  var { Duplex, Readable } = require("stream");
30992
30992
  var { URL: URL2 } = require("url");
30993
30993
  var PerMessageDeflate = require_permessage_deflate();
@@ -31647,7 +31647,7 @@ var require_websocket2 = __commonJS({
31647
31647
  abortHandshake(websocket, socket, "Invalid Upgrade header");
31648
31648
  return;
31649
31649
  }
31650
- const digest = createHash6("sha1").update(key + GUID).digest("base64");
31650
+ const digest = createHash7("sha1").update(key + GUID).digest("base64");
31651
31651
  if (res.headers["sec-websocket-accept"] !== digest) {
31652
31652
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
31653
31653
  return;
@@ -32014,7 +32014,7 @@ var require_websocket_server = __commonJS({
32014
32014
  var EventEmitter2 = require("events");
32015
32015
  var http2 = require("http");
32016
32016
  var { Duplex } = require("stream");
32017
- var { createHash: createHash6 } = require("crypto");
32017
+ var { createHash: createHash7 } = require("crypto");
32018
32018
  var extension = require_extension();
32019
32019
  var PerMessageDeflate = require_permessage_deflate();
32020
32020
  var subprotocol = require_subprotocol();
@@ -32315,7 +32315,7 @@ var require_websocket_server = __commonJS({
32315
32315
  );
32316
32316
  }
32317
32317
  if (this._state > RUNNING) return abortHandshake(socket, 503);
32318
- const digest = createHash6("sha1").update(key + GUID).digest("base64");
32318
+ const digest = createHash7("sha1").update(key + GUID).digest("base64");
32319
32319
  const headers = [
32320
32320
  "HTTP/1.1 101 Switching Protocols",
32321
32321
  "Upgrade: websocket",
@@ -32437,7 +32437,7 @@ var init_sentry_config = __esm({
32437
32437
  environment = process.env.SENTRY_ENV === "dev" ? "dev" : "prod";
32438
32438
  SENTRY_CONFIG = {
32439
32439
  projectName: "okx/openclaw-okx-a2a-extension",
32440
- release: "0.2.9",
32440
+ release: "0.2.10-beta-98689bff7a-260826152645",
32441
32441
  environment,
32442
32442
  runtimeContainer: normalizeRuntimeContainer(process.env.OKX_A2A_RUNTIME_CONTAINER)
32443
32443
  };
@@ -32471,7 +32471,7 @@ function isPostjectRunnable() {
32471
32471
  function resolvePostjectCommand() {
32472
32472
  try {
32473
32473
  const cliPath = (0, import_node_module.createRequire)(__filename).resolve("postject/dist/cli.js");
32474
- if ((0, import_node_fs21.existsSync)(cliPath)) {
32474
+ if ((0, import_node_fs23.existsSync)(cliPath)) {
32475
32475
  return { command: process.execPath, prefixArgs: [cliPath] };
32476
32476
  }
32477
32477
  } catch {
@@ -32542,37 +32542,37 @@ function buildSeaConfig(entryPath, blobPath) {
32542
32542
  }
32543
32543
  async function installWindowsNativeLauncher(options) {
32544
32544
  const nodeExe = options.nodeExe ?? process.execPath;
32545
- if (!(0, import_node_fs21.existsSync)(options.cliPath)) {
32545
+ if (!(0, import_node_fs23.existsSync)(options.cliPath)) {
32546
32546
  throw new Error(`cannot build okx-a2a.exe: CLI entry not found at ${options.cliPath}`);
32547
32547
  }
32548
- if (!(0, import_node_fs21.existsSync)(nodeExe)) {
32548
+ if (!(0, import_node_fs23.existsSync)(nodeExe)) {
32549
32549
  throw new Error(`cannot build okx-a2a.exe: node executable not found at ${nodeExe}`);
32550
32550
  }
32551
- const exePath = (0, import_node_path27.join)(options.targetDir, NATIVE_LAUNCHER_EXE_NAME);
32552
- (0, import_node_fs21.mkdirSync)(options.targetDir, { recursive: true });
32553
- const work = (0, import_node_fs21.mkdtempSync)((0, import_node_path27.join)((0, import_node_os10.tmpdir)(), "okx-a2a-sea-"));
32551
+ const exePath = (0, import_node_path29.join)(options.targetDir, NATIVE_LAUNCHER_EXE_NAME);
32552
+ (0, import_node_fs23.mkdirSync)(options.targetDir, { recursive: true });
32553
+ const work = (0, import_node_fs23.mkdtempSync)((0, import_node_path29.join)((0, import_node_os10.tmpdir)(), "okx-a2a-sea-"));
32554
32554
  try {
32555
- const entryPath = (0, import_node_path27.join)(work, "launcher-entry.js");
32556
- const blobPath = (0, import_node_path27.join)(work, "okx-a2a.blob");
32557
- const configPath = (0, import_node_path27.join)(work, "sea-config.json");
32558
- (0, import_node_fs21.writeFileSync)(entryPath, buildLauncherEntryJs(options.cliPath), "utf8");
32559
- (0, import_node_fs21.writeFileSync)(configPath, buildSeaConfig(entryPath, blobPath), "utf8");
32560
- (0, import_node_child_process7.execFileSync)(nodeExe, ["--experimental-sea-config", configPath], {
32555
+ const entryPath = (0, import_node_path29.join)(work, "launcher-entry.js");
32556
+ const blobPath = (0, import_node_path29.join)(work, "okx-a2a.blob");
32557
+ const configPath = (0, import_node_path29.join)(work, "sea-config.json");
32558
+ (0, import_node_fs23.writeFileSync)(entryPath, buildLauncherEntryJs(options.cliPath), "utf8");
32559
+ (0, import_node_fs23.writeFileSync)(configPath, buildSeaConfig(entryPath, blobPath), "utf8");
32560
+ (0, import_node_child_process8.execFileSync)(nodeExe, ["--experimental-sea-config", configPath], {
32561
32561
  stdio: "ignore",
32562
32562
  windowsHide: true
32563
32563
  });
32564
- (0, import_node_fs21.copyFileSync)(nodeExe, exePath);
32564
+ (0, import_node_fs23.copyFileSync)(nodeExe, exePath);
32565
32565
  const isMac = process.platform === "darwin";
32566
32566
  if (isMac) {
32567
32567
  try {
32568
- (0, import_node_child_process7.execFileSync)("codesign", ["--remove-signature", exePath], { stdio: "ignore" });
32568
+ (0, import_node_child_process8.execFileSync)("codesign", ["--remove-signature", exePath], { stdio: "ignore" });
32569
32569
  } catch {
32570
32570
  }
32571
32571
  }
32572
32572
  injectSeaBlob(exePath, blobPath, isMac);
32573
32573
  if (isMac) {
32574
32574
  try {
32575
- (0, import_node_child_process7.execFileSync)("codesign", ["--sign", "-", exePath], { stdio: "ignore" });
32575
+ (0, import_node_child_process8.execFileSync)("codesign", ["--sign", "-", exePath], { stdio: "ignore" });
32576
32576
  } catch {
32577
32577
  }
32578
32578
  }
@@ -32581,19 +32581,19 @@ async function installWindowsNativeLauncher(options) {
32581
32581
  );
32582
32582
  return { exePath, cliPath: options.cliPath, nodeExe };
32583
32583
  } finally {
32584
- (0, import_node_fs21.rmSync)(work, { recursive: true, force: true });
32584
+ (0, import_node_fs23.rmSync)(work, { recursive: true, force: true });
32585
32585
  }
32586
32586
  }
32587
- function findWindowsNativeOkxA2aExe(pathValue, appData, userProfile, fileExists2 = import_node_fs21.existsSync) {
32587
+ function findWindowsNativeOkxA2aExe(pathValue, appData, userProfile, fileExists2 = import_node_fs23.existsSync) {
32588
32588
  const dirs = pathValue.split(";").map((d) => d.trim()).filter(Boolean);
32589
32589
  if (appData) {
32590
- dirs.push((0, import_node_path27.join)(appData, "npm"));
32590
+ dirs.push((0, import_node_path29.join)(appData, "npm"));
32591
32591
  }
32592
32592
  if (userProfile) {
32593
- dirs.push((0, import_node_path27.join)(userProfile, ".local", "bin"));
32593
+ dirs.push((0, import_node_path29.join)(userProfile, ".local", "bin"));
32594
32594
  }
32595
32595
  for (const dir of dirs) {
32596
- const candidate = (0, import_node_path27.join)(dir, NATIVE_LAUNCHER_EXE_NAME);
32596
+ const candidate = (0, import_node_path29.join)(dir, NATIVE_LAUNCHER_EXE_NAME);
32597
32597
  if (fileExists2(candidate)) {
32598
32598
  return candidate;
32599
32599
  }
@@ -32602,11 +32602,11 @@ function findWindowsNativeOkxA2aExe(pathValue, appData, userProfile, fileExists2
32602
32602
  }
32603
32603
  function resolveRunningCliPath() {
32604
32604
  const fromArgv = process.argv[1];
32605
- if (fromArgv && /(?:^|[\\/])cli\.js$/.test(fromArgv) && (0, import_node_fs21.existsSync)(fromArgv)) {
32605
+ if (fromArgv && /(?:^|[\\/])cli\.js$/.test(fromArgv) && (0, import_node_fs23.existsSync)(fromArgv)) {
32606
32606
  return fromArgv;
32607
32607
  }
32608
- const beside = (0, import_node_path27.join)(__dirname, "cli.js");
32609
- if ((0, import_node_fs21.existsSync)(beside)) {
32608
+ const beside = (0, import_node_path29.join)(__dirname, "cli.js");
32609
+ if ((0, import_node_fs23.existsSync)(beside)) {
32610
32610
  return beside;
32611
32611
  }
32612
32612
  if (fromArgv) {
@@ -32624,19 +32624,19 @@ async function ensureWindowsNativeLauncher(options = {}) {
32624
32624
  if (existing) {
32625
32625
  return { exePath: existing, installed: false };
32626
32626
  }
32627
- const targetDir = env.APPDATA ? (0, import_node_path27.join)(env.APPDATA, "npm") : (0, import_node_path27.join)(env.USERPROFILE ?? (0, import_node_os10.homedir)(), ".local", "bin");
32627
+ const targetDir = env.APPDATA ? (0, import_node_path29.join)(env.APPDATA, "npm") : (0, import_node_path29.join)(env.USERPROFILE ?? (0, import_node_os10.homedir)(), ".local", "bin");
32628
32628
  const result = await installWindowsNativeLauncher({ cliPath: resolveRunningCliPath(), targetDir });
32629
32629
  return { exePath: result.exePath, installed: true };
32630
32630
  }
32631
- var import_node_child_process7, import_node_fs21, import_node_module, import_node_os10, import_node_path27, SEA_SENTINEL_FUSE, NATIVE_LAUNCHER_EXE_NAME, POSTJECT_SPEC, POSTJECT_BIN;
32631
+ var import_node_child_process8, import_node_fs23, import_node_module, import_node_os10, import_node_path29, SEA_SENTINEL_FUSE, NATIVE_LAUNCHER_EXE_NAME, POSTJECT_SPEC, POSTJECT_BIN;
32632
32632
  var init_win_native_launcher = __esm({
32633
32633
  "src/win-native-launcher.ts"() {
32634
32634
  "use strict";
32635
- import_node_child_process7 = require("node:child_process");
32636
- import_node_fs21 = require("node:fs");
32635
+ import_node_child_process8 = require("node:child_process");
32636
+ import_node_fs23 = require("node:fs");
32637
32637
  import_node_module = require("node:module");
32638
32638
  import_node_os10 = require("node:os");
32639
- import_node_path27 = require("node:path");
32639
+ import_node_path29 = require("node:path");
32640
32640
  init_win_compat();
32641
32641
  init_win_spawn();
32642
32642
  SEA_SENTINEL_FUSE = "NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2";
@@ -33378,7 +33378,7 @@ async function getCurrentNodeCliVersion() {
33378
33378
  return await getGlobalNpmPackageVersion(UPDATE_PACKAGES.node) ?? getBundledNodeCliVersion();
33379
33379
  }
33380
33380
  function getBundledNodeCliVersion() {
33381
- return true ? "0.2.9" : null;
33381
+ return true ? "0.2.10-beta-98689bff7a-260826152645" : null;
33382
33382
  }
33383
33383
  function readConfiguredAiProvider() {
33384
33384
  const explicit = process.env.OKX_A2A_AI_PROVIDER || process.env.OKX_AGENT_TASK_AI_CLI;
@@ -33563,17 +33563,17 @@ async function updateHermes(release, options) {
33563
33563
  assertNotRunningInsideGateway("hermes");
33564
33564
  }
33565
33565
  const spec = buildNpmPackageSpec("hermes", release);
33566
- const workDir = await (0, import_promises11.mkdtemp)((0, import_node_path28.join)((0, import_node_os11.tmpdir)(), `okx-a2a-${label}-hermes-`));
33566
+ const workDir = await (0, import_promises11.mkdtemp)((0, import_node_path30.join)((0, import_node_os11.tmpdir)(), `okx-a2a-${label}-hermes-`));
33567
33567
  try {
33568
33568
  console.log(`[${label}] downloading ${spec}`);
33569
33569
  const npmTarball = await npmPack(spec, workDir);
33570
- const npmPackageDir = (0, import_node_path28.join)(workDir, "npm-package");
33570
+ const npmPackageDir = (0, import_node_path30.join)(workDir, "npm-package");
33571
33571
  await runCommand("tar", ["-xzf", npmTarball, "-C", npmPackageDir], { ensureDir: npmPackageDir });
33572
- const pluginTarball = await findHermesPluginTarball((0, import_node_path28.join)(npmPackageDir, "package", "dist"));
33573
- const pluginDir = (0, import_node_path28.join)(workDir, "plugin");
33572
+ const pluginTarball = await findHermesPluginTarball((0, import_node_path30.join)(npmPackageDir, "package", "dist"));
33573
+ const pluginDir = (0, import_node_path30.join)(workDir, "plugin");
33574
33574
  await runCommand("tar", ["-xzf", pluginTarball, "-C", pluginDir], { ensureDir: pluginDir });
33575
33575
  const unpackedPluginDir = await findFirstDirectory(pluginDir);
33576
- const installer = (0, import_node_path28.join)(unpackedPluginDir, "scripts", "install-or-upgrade.sh");
33576
+ const installer = (0, import_node_path30.join)(unpackedPluginDir, "scripts", "install-or-upgrade.sh");
33577
33577
  console.log(`[${label}] running ${installer}`);
33578
33578
  await runCommand("bash", [installer, ...options.restart ? ["--restart"] : []], { cwd: unpackedPluginDir });
33579
33579
  await normalizeHermesOkxA2aPluginConfig();
@@ -33588,7 +33588,7 @@ async function updateHermes(release, options) {
33588
33588
  }
33589
33589
  }
33590
33590
  async function installGatewayPluginForDoctor(target) {
33591
- const release = isPrereleaseVersion("0.2.9") ? "beta" : "latest";
33591
+ const release = isPrereleaseVersion("0.2.10-beta-98689bff7a-260826152645") ? "beta" : "latest";
33592
33592
  const insideTargetGateway = detectGatewayInvocation() === target;
33593
33593
  const options = {
33594
33594
  restart: !insideTargetGateway,
@@ -33639,7 +33639,7 @@ async function ensureHermesOkxA2aPluginConfig(configFile = resolveHermesConfigPa
33639
33639
  if (options.dryRun) {
33640
33640
  return true;
33641
33641
  }
33642
- await (0, import_promises11.mkdir)((0, import_node_path28.resolve)(configFile, ".."), { recursive: true });
33642
+ await (0, import_promises11.mkdir)((0, import_node_path30.resolve)(configFile, ".."), { recursive: true });
33643
33643
  await (0, import_promises11.writeFile)(configFile, "plugins:\n enabled:\n - okx-a2a\n");
33644
33644
  console.log(`[update] added Hermes plugins.enabled okx-a2a entry in ${configFile}`);
33645
33645
  return true;
@@ -33879,7 +33879,7 @@ function findFirstEnabledListItem(lines, startIndex, enabledIndent) {
33879
33879
  return null;
33880
33880
  }
33881
33881
  function resolveHermesConfigPath() {
33882
- return (0, import_node_path28.join)(process.env.HERMES_HOME ?? (0, import_node_path28.join)((0, import_node_os11.homedir)(), ".hermes"), "config.yaml");
33882
+ return (0, import_node_path30.join)(process.env.HERMES_HOME ?? (0, import_node_path30.join)((0, import_node_os11.homedir)(), ".hermes"), "config.yaml");
33883
33883
  }
33884
33884
  function lineIndent(line) {
33885
33885
  const match = line.match(/^\s*/);
@@ -33957,13 +33957,13 @@ async function assertGatewayPluginInstalled(target) {
33957
33957
  );
33958
33958
  }
33959
33959
  function resolveHermesPluginYamlPath() {
33960
- return (0, import_node_path28.join)(process.env.HERMES_HOME ?? (0, import_node_path28.join)((0, import_node_os11.homedir)(), ".hermes"), "plugins", "platforms", "okx-a2a", "plugin.yaml");
33960
+ return (0, import_node_path30.join)(process.env.HERMES_HOME ?? (0, import_node_path30.join)((0, import_node_os11.homedir)(), ".hermes"), "plugins", "platforms", "okx-a2a", "plugin.yaml");
33961
33961
  }
33962
33962
  async function isGatewayPluginInstalled(target) {
33963
33963
  if (target === "openclaw") {
33964
33964
  return (await getInstalledOpenClawPluginInfo()).installed;
33965
33965
  }
33966
- return (0, import_node_fs22.existsSync)(resolveHermesPluginYamlPath());
33966
+ return (0, import_node_fs24.existsSync)(resolveHermesPluginYamlPath());
33967
33967
  }
33968
33968
  async function getInstalledGatewayPluginVersion(target) {
33969
33969
  if (target === "hermes") {
@@ -34050,7 +34050,7 @@ function parsePackageVersionFromText(output) {
34050
34050
  return output.match(/@okxweb3\/a2a-openclaw@([0-9A-Za-z.+-]+)/)?.[1] ?? null;
34051
34051
  }
34052
34052
  async function getInstalledHermesPluginVersion() {
34053
- const pluginYaml = (0, import_node_path28.join)(process.env.HERMES_HOME ?? (0, import_node_path28.join)((0, import_node_os11.homedir)(), ".hermes"), "plugins", "platforms", "okx-a2a", "plugin.yaml");
34053
+ const pluginYaml = (0, import_node_path30.join)(process.env.HERMES_HOME ?? (0, import_node_path30.join)((0, import_node_os11.homedir)(), ".hermes"), "plugins", "platforms", "okx-a2a", "plugin.yaml");
34054
34054
  try {
34055
34055
  const content = await (0, import_promises11.readFile)(pluginYaml, "utf8");
34056
34056
  return parsePluginYamlVersion(content);
@@ -34108,7 +34108,7 @@ async function npmPack(spec, destination) {
34108
34108
  if (!tarballName) {
34109
34109
  throw new Error(`Unable to detect npm pack tarball from output: ${output.trim()}`);
34110
34110
  }
34111
- return (0, import_node_path28.resolve)(destination, (0, import_node_path28.basename)(tarballName));
34111
+ return (0, import_node_path30.resolve)(destination, (0, import_node_path30.basename)(tarballName));
34112
34112
  }
34113
34113
  async function findHermesPluginTarball(distDir) {
34114
34114
  const entries = await (0, import_promises11.readdir)(distDir);
@@ -34116,7 +34116,7 @@ async function findHermesPluginTarball(distDir) {
34116
34116
  if (!tarball) {
34117
34117
  throw new Error(`Hermes npm package did not contain dist/okx-a2a-hermes-plugin-*.tar.gz`);
34118
34118
  }
34119
- return (0, import_node_path28.join)(distDir, tarball);
34119
+ return (0, import_node_path30.join)(distDir, tarball);
34120
34120
  }
34121
34121
  async function findFirstDirectory(parent) {
34122
34122
  const entries = await (0, import_promises11.readdir)(parent, { withFileTypes: true });
@@ -34124,7 +34124,7 @@ async function findFirstDirectory(parent) {
34124
34124
  if (!dir) {
34125
34125
  throw new Error(`No unpacked plugin directory found under ${parent}`);
34126
34126
  }
34127
- return (0, import_node_path28.join)(parent, dir.name);
34127
+ return (0, import_node_path30.join)(parent, dir.name);
34128
34128
  }
34129
34129
  function readOption2(args, name) {
34130
34130
  const index2 = args.indexOf(name);
@@ -34175,7 +34175,7 @@ async function runCommand(command, args, options = {}) {
34175
34175
  await new Promise((resolvePromise, reject) => {
34176
34176
  const invocation = buildExternalCommandInvocation(command, args);
34177
34177
  const redirect = redirectCommandStdoutToStderr || options.redirectStdoutToStderr === true;
34178
- const child = (0, import_node_child_process8.spawn)(invocation.command, invocation.args, {
34178
+ const child = (0, import_node_child_process9.spawn)(invocation.command, invocation.args, {
34179
34179
  cwd: options.cwd,
34180
34180
  stdio: redirect ? [options.inheritStdin ? "inherit" : "ignore", "pipe", "pipe"] : "inherit",
34181
34181
  windowsVerbatimArguments: invocation.windowsVerbatimArguments
@@ -34219,7 +34219,7 @@ async function runCommand(command, args, options = {}) {
34219
34219
  async function runCommandCapture(command, args) {
34220
34220
  return await new Promise((resolvePromise, reject) => {
34221
34221
  const invocation = buildExternalCommandInvocation(command, args);
34222
- const child = (0, import_node_child_process8.spawn)(invocation.command, invocation.args, {
34222
+ const child = (0, import_node_child_process9.spawn)(invocation.command, invocation.args, {
34223
34223
  stdio: ["ignore", "pipe", "pipe"],
34224
34224
  windowsVerbatimArguments: invocation.windowsVerbatimArguments
34225
34225
  });
@@ -34252,7 +34252,7 @@ ${stderr}`));
34252
34252
  async function runCommandCaptureOptional(command, args) {
34253
34253
  return await new Promise((resolvePromise) => {
34254
34254
  const invocation = buildExternalCommandInvocation(command, args);
34255
- const child = (0, import_node_child_process8.spawn)(invocation.command, invocation.args, {
34255
+ const child = (0, import_node_child_process9.spawn)(invocation.command, invocation.args, {
34256
34256
  stdio: ["ignore", "pipe", "ignore"],
34257
34257
  windowsVerbatimArguments: invocation.windowsVerbatimArguments
34258
34258
  });
@@ -34272,7 +34272,7 @@ async function runCommandCaptureOptional(command, args) {
34272
34272
  async function runCommandCaptureStatus(command, args, options = {}) {
34273
34273
  return await new Promise((resolvePromise) => {
34274
34274
  const invocation = buildExternalCommandInvocation(command, args);
34275
- const child = (0, import_node_child_process8.spawn)(invocation.command, invocation.args, {
34275
+ const child = (0, import_node_child_process9.spawn)(invocation.command, invocation.args, {
34276
34276
  stdio: ["ignore", "pipe", "pipe"],
34277
34277
  windowsVerbatimArguments: invocation.windowsVerbatimArguments
34278
34278
  });
@@ -34345,15 +34345,15 @@ function buildExternalCommandInvocation(command, args, platform = process.platfo
34345
34345
  function formatExternalCommand(command, args) {
34346
34346
  return [command, ...args].join(" ");
34347
34347
  }
34348
- var import_node_child_process8, import_node_fs22, import_promises11, import_node_os11, import_node_path28, 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;
34348
+ var import_node_child_process9, import_node_fs24, import_promises11, import_node_os11, import_node_path30, 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;
34349
34349
  var init_update_cli = __esm({
34350
34350
  "src/update-cli.ts"() {
34351
34351
  "use strict";
34352
- import_node_child_process8 = require("node:child_process");
34353
- import_node_fs22 = require("node:fs");
34352
+ import_node_child_process9 = require("node:child_process");
34353
+ import_node_fs24 = require("node:fs");
34354
34354
  import_promises11 = require("node:fs/promises");
34355
34355
  import_node_os11 = require("node:os");
34356
- import_node_path28 = require("node:path");
34356
+ import_node_path30 = require("node:path");
34357
34357
  init_ai_command();
34358
34358
  init_win_spawn();
34359
34359
  init_ai_provider();
@@ -34666,7 +34666,7 @@ var require_BufferList = __commonJS({
34666
34666
  this.head = this.tail = null;
34667
34667
  this.length = 0;
34668
34668
  };
34669
- BufferList.prototype.join = function join31(s) {
34669
+ BufferList.prototype.join = function join33(s) {
34670
34670
  if (this.length === 0) return "";
34671
34671
  var p = this.head;
34672
34672
  var ret = "" + p.data;
@@ -44317,9 +44317,12 @@ __export(index_exports, {
44317
44317
  NATIVE_LAUNCHER_EXE_NAME: () => NATIVE_LAUNCHER_EXE_NAME,
44318
44318
  OPENCLAW_GATEWAY_ROUTE_GROUP_ID: () => OPENCLAW_GATEWAY_ROUTE_GROUP_ID,
44319
44319
  ProviderNotReadyError: () => ProviderNotReadyError,
44320
+ SIGNAL_PAYLOAD_TYPE: () => SIGNAL_PAYLOAD_TYPE,
44321
+ SIGNAL_SPEC_VERSION: () => SIGNAL_SPEC_VERSION,
44320
44322
  SYSTEM_NOTIFICATION_SESSION_KEY: () => SYSTEM_NOTIFICATION_SESSION_KEY,
44321
44323
  SessionBusyTracker: () => SessionBusyTracker,
44322
44324
  SessionStore: () => SessionStore,
44325
+ SignalTradingBuyerRuntime: () => SignalTradingBuyerRuntime,
44323
44326
  SqliteOutboundBehavior: () => SqliteOutboundBehavior,
44324
44327
  TASK_NAME: () => TASK_NAME,
44325
44328
  TaskMessageStore: () => TaskMessageStore,
@@ -44360,6 +44363,7 @@ __export(index_exports, {
44360
44363
  buildLaunchdPlist: () => buildLaunchdPlist,
44361
44364
  buildLauncherEntryJs: () => buildLauncherEntryJs,
44362
44365
  buildMessageEligibleArgs: () => buildMessageEligibleArgs,
44366
+ buildPolymarketExecutionPlan: () => buildPolymarketExecutionPlan,
44363
44367
  buildSchtasksCreateArgs: () => buildSchtasksCreateArgs,
44364
44368
  buildSchtasksDeleteArgs: () => buildSchtasksDeleteArgs,
44365
44369
  buildSchtasksEndArgs: () => buildSchtasksEndArgs,
@@ -44368,6 +44372,7 @@ __export(index_exports, {
44368
44372
  buildSeaConfig: () => buildSeaConfig,
44369
44373
  buildServicePath: () => buildServicePath,
44370
44374
  buildSessionKey: () => buildSessionKey,
44375
+ buildSignalEnvelopePayload: () => buildSignalEnvelopePayload,
44371
44376
  buildSystemMessageNotice: () => buildSystemMessageNotice,
44372
44377
  buildSystemStoredMessage: () => buildSystemStoredMessage,
44373
44378
  buildSystemdUserService: () => buildSystemdUserService,
@@ -44391,6 +44396,7 @@ __export(index_exports, {
44391
44396
  collectCodexAppBundledCandidates: () => collectCodexAppBundledCandidates,
44392
44397
  collectCodexCommandCandidates: () => collectCodexCommandCandidates,
44393
44398
  commandExists: () => commandExists,
44399
+ comparePositiveDecimals: () => comparePositiveDecimals,
44394
44400
  createAiToolFailureTracker: () => createAiToolFailureTracker,
44395
44401
  createFileMessageHandler: () => createFileMessageHandler,
44396
44402
  createOutboundBehavior: () => createOutboundBehavior,
@@ -44411,6 +44417,7 @@ __export(index_exports, {
44411
44417
  exportDiagnosticLogs: () => exportDiagnosticLogs,
44412
44418
  extractAiSessionId: () => extractAiSessionId,
44413
44419
  extractDirectToUserNotification: () => extractDirectToUserNotification,
44420
+ extractSignalEnvelopePayload: () => extractSignalEnvelopePayload,
44414
44421
  extractXmtpSentAtMs: () => extractXmtpSentAtMs2,
44415
44422
  findWindowsNativeOkxA2aExe: () => findWindowsNativeOkxA2aExe,
44416
44423
  followFile: () => followFile,
@@ -44422,10 +44429,12 @@ __export(index_exports, {
44422
44429
  getSessionBusyTracker: () => getSessionBusyTracker,
44423
44430
  handleCapabilitiesCommand: () => handleCapabilitiesCommand,
44424
44431
  handleDoctorCommand: () => handleDoctorCommand,
44432
+ handleSignalPublishCommand: () => handleSignalPublishCommand,
44425
44433
  handleXmtpDebugCommand: () => handleXmtpDebugCommand,
44426
44434
  handleXmtpSendCommand: () => handleXmtpSendCommand,
44427
44435
  handleXmtpTestCommand: () => handleXmtpTestCommand,
44428
44436
  hasAiRuntimeMarker: () => hasAiRuntimeMarker,
44437
+ hasSignalEnvelopePayload: () => hasSignalEnvelopePayload,
44429
44438
  hashDiagnosticFileContent: () => hashDiagnosticFileContent,
44430
44439
  heartbeatUserAttentionWatcher: () => heartbeatUserAttentionWatcher,
44431
44440
  hermesConfigEnablesOkxA2a: () => hermesConfigEnablesOkxA2a,
@@ -44451,6 +44460,7 @@ __export(index_exports, {
44451
44460
  killProcessTree: () => killProcessTree,
44452
44461
  launchdPlistHasCurrentRestartPolicy: () => launchdPlistHasCurrentRestartPolicy,
44453
44462
  listAllAgentsWithMetadata: () => listAllAgentsWithMetadata,
44463
+ loadSignalTradingConfig: () => loadSignalTradingConfig,
44454
44464
  logWinCompat: () => logWinCompat,
44455
44465
  logXmtpMessageSent: () => logXmtpMessageSent,
44456
44466
  maybeRecommendOnchainosUpgrade: () => maybeRecommendOnchainosUpgrade,
@@ -44467,6 +44477,8 @@ __export(index_exports, {
44467
44477
  parseLogsExportArgs: () => parseLogsExportArgs,
44468
44478
  parseOnchainosVersionOutput: () => parseOnchainosVersionOutput,
44469
44479
  parsePluginYamlVersion: () => parsePluginYamlVersion,
44480
+ parseSignalTradingConfig: () => parseSignalTradingConfig,
44481
+ parseTradingSignalV1: () => parseTradingSignalV1,
44470
44482
  parseWalletLoginStatus: () => parseWalletLoginStatus,
44471
44483
  parseWindowsParentProcessJson: () => parseWindowsParentProcessJson,
44472
44484
  performRuntimeSwitch: () => performRuntimeSwitch,
@@ -44516,6 +44528,8 @@ __export(index_exports, {
44516
44528
  resolveOpenClawGatewayRoute: () => resolveOpenClawGatewayRoute,
44517
44529
  resolveOpenClawGatewayRoutes: () => resolveOpenClawGatewayRoutes,
44518
44530
  resolveProviderCommandWithSelfHeal: () => resolveProviderCommandWithSelfHeal,
44531
+ resolveSignalTradingConfigPath: () => resolveSignalTradingConfigPath,
44532
+ resolveSignalTradingDir: () => resolveSignalTradingDir,
44519
44533
  resolveSystemNotificationTargets: () => resolveSystemNotificationTargets,
44520
44534
  resolveSystemdAutostartPaths: () => resolveSystemdAutostartPaths,
44521
44535
  resolveTaskConfigPath: () => resolveTaskConfigPath,
@@ -48062,6 +48076,15 @@ var CommandStore = class {
48062
48076
  createdAt: Date.now()
48063
48077
  };
48064
48078
  }
48079
+ createSignalPublishCommand(params) {
48080
+ return {
48081
+ id: (0, import_node_crypto5.randomUUID)(),
48082
+ type: "signal-publish",
48083
+ serviceId: params.serviceId,
48084
+ signal: params.signal,
48085
+ createdAt: Date.now()
48086
+ };
48087
+ }
48065
48088
  createXmtpGetConversationHistoryCommand(params) {
48066
48089
  return {
48067
48090
  id: (0, import_node_crypto5.randomUUID)(),
@@ -48370,6 +48393,10 @@ function isDaemonCommand(value) {
48370
48393
  if (parsed.type === "xmtp-send") {
48371
48394
  return typeof parsed.jobId === "string" && typeof parsed.message === "string";
48372
48395
  }
48396
+ if (parsed.type === "signal-publish") {
48397
+ const command = parsed;
48398
+ return typeof command.serviceId === "string" && !!command.signal && typeof command.signal === "object";
48399
+ }
48373
48400
  if (parsed.type === "xmtp-get-pending-list") {
48374
48401
  return true;
48375
48402
  }
@@ -61023,7 +61050,7 @@ function buildConnectParams(config, instanceId, protocolVersion) {
61023
61050
  client: {
61024
61051
  id: "gateway-client",
61025
61052
  displayName: "okx-a2a-node",
61026
- version: "0.2.9",
61053
+ version: "0.2.10-beta-98689bff7a-260826152645",
61027
61054
  platform: "node",
61028
61055
  mode: "backend",
61029
61056
  instanceId
@@ -61034,7 +61061,7 @@ function buildConnectParams(config, instanceId, protocolVersion) {
61034
61061
  commands: [],
61035
61062
  permissions: {},
61036
61063
  locale: Intl.DateTimeFormat().resolvedOptions().locale || "en-US",
61037
- userAgent: `okx-a2a-node/${"0.2.9"}`,
61064
+ userAgent: `okx-a2a-node/${"0.2.10-beta-98689bff7a-260826152645"}`,
61038
61065
  auth: {
61039
61066
  ...config.token ? { token: config.token } : {},
61040
61067
  ...config.password ? { password: config.password } : {}
@@ -64122,6 +64149,511 @@ function isRecord5(value) {
64122
64149
  return !!value && typeof value === "object" && !Array.isArray(value);
64123
64150
  }
64124
64151
 
64152
+ // src/signal-trading/publisher.ts
64153
+ var import_node_crypto12 = require("node:crypto");
64154
+
64155
+ // src/signal-trading/config.ts
64156
+ var import_node_fs19 = require("node:fs");
64157
+ var import_node_path25 = require("node:path");
64158
+ init_paths();
64159
+ var SIGNAL_TRADING_CONFIG_VERSION = 1;
64160
+ function isPlainObject2(value) {
64161
+ return !!value && typeof value === "object" && !Array.isArray(value);
64162
+ }
64163
+ function requireObject(value, path2) {
64164
+ if (!isPlainObject2(value)) {
64165
+ throw new Error(`${path2} must be an object`);
64166
+ }
64167
+ return value;
64168
+ }
64169
+ function requireString(value, path2) {
64170
+ if (typeof value !== "string" || value.trim().length === 0) {
64171
+ throw new Error(`${path2} must be a non-empty string`);
64172
+ }
64173
+ return value.trim();
64174
+ }
64175
+ function optionalString(value, path2) {
64176
+ return value === void 0 ? void 0 : requireString(value, path2);
64177
+ }
64178
+ function requireBoolean(value, path2) {
64179
+ if (typeof value !== "boolean") {
64180
+ throw new Error(`${path2} must be a boolean`);
64181
+ }
64182
+ return value;
64183
+ }
64184
+ function requireInteger(value, path2, minimum) {
64185
+ if (typeof value !== "number" || !Number.isInteger(value) || value < minimum) {
64186
+ throw new Error(`${path2} must be an integer >= ${minimum}`);
64187
+ }
64188
+ return value;
64189
+ }
64190
+ function requireArray(value, path2) {
64191
+ if (!Array.isArray(value)) {
64192
+ throw new Error(`${path2} must be an array`);
64193
+ }
64194
+ return value;
64195
+ }
64196
+ function parseStringArray2(value, path2) {
64197
+ return requireArray(value, path2).map((item, index2) => requireString(item, `${path2}[${index2}]`));
64198
+ }
64199
+ function parseProviderRoute(value, index2) {
64200
+ const path2 = `config.provider.routes[${index2}]`;
64201
+ const input = requireObject(value, path2);
64202
+ const myAgentId = optionalString(input.myAgentId, `${path2}.myAgentId`);
64203
+ const toXmtpAddress = optionalString(input.toXmtpAddress, `${path2}.toXmtpAddress`);
64204
+ return {
64205
+ serviceId: requireString(input.serviceId, `${path2}.serviceId`),
64206
+ subscriptionId: requireString(input.subscriptionId, `${path2}.subscriptionId`),
64207
+ jobId: requireString(input.jobId, `${path2}.jobId`),
64208
+ ...myAgentId ? { myAgentId } : {},
64209
+ toAgentId: requireString(input.toAgentId, `${path2}.toAgentId`),
64210
+ ...toXmtpAddress ? { toXmtpAddress } : {}
64211
+ };
64212
+ }
64213
+ function parseBuyerSubscription(value, index2) {
64214
+ const path2 = `config.buyer.subscriptions[${index2}]`;
64215
+ const input = requireObject(value, path2);
64216
+ return {
64217
+ serviceId: requireString(input.serviceId, `${path2}.serviceId`),
64218
+ subscriptionId: requireString(input.subscriptionId, `${path2}.subscriptionId`),
64219
+ jobId: requireString(input.jobId, `${path2}.jobId`),
64220
+ providerAgentId: requireString(input.providerAgentId, `${path2}.providerAgentId`)
64221
+ };
64222
+ }
64223
+ function parseRiskPolicy(value) {
64224
+ const input = requireObject(value, "config.buyer.riskPolicy");
64225
+ const allowedSides = parseStringArray2(input.allowedSides, "config.buyer.riskPolicy.allowedSides");
64226
+ for (const side of allowedSides) {
64227
+ if (side !== "BUY" && side !== "SELL") {
64228
+ throw new Error("config.buyer.riskPolicy.allowedSides supports only BUY and SELL");
64229
+ }
64230
+ }
64231
+ const allowedTokenIds = parseStringArray2(
64232
+ input.allowedTokenIds,
64233
+ "config.buyer.riskPolicy.allowedTokenIds"
64234
+ );
64235
+ let allowedMarketSeries;
64236
+ if (input.allowedMarketSeries !== void 0) {
64237
+ allowedMarketSeries = requireArray(
64238
+ input.allowedMarketSeries,
64239
+ "config.buyer.riskPolicy.allowedMarketSeries"
64240
+ ).map((value2, index2) => {
64241
+ const path2 = `config.buyer.riskPolicy.allowedMarketSeries[${index2}]`;
64242
+ const series = requireObject(value2, path2);
64243
+ const outcomes = parseStringArray2(series.outcomes, `${path2}.outcomes`);
64244
+ if (outcomes.length === 0) {
64245
+ throw new Error(`${path2}.outcomes must not be empty`);
64246
+ }
64247
+ return {
64248
+ slugPrefix: requireString(series.slugPrefix, `${path2}.slugPrefix`),
64249
+ outcomes,
64250
+ ...series.seriesSlug === void 0 ? {} : { seriesSlug: requireString(series.seriesSlug, `${path2}.seriesSlug`) },
64251
+ ...series.cryptoMarketConfigId === void 0 ? {} : {
64252
+ cryptoMarketConfigId: requireString(
64253
+ series.cryptoMarketConfigId,
64254
+ `${path2}.cryptoMarketConfigId`
64255
+ )
64256
+ }
64257
+ };
64258
+ });
64259
+ }
64260
+ if (allowedTokenIds.length === 0 && !allowedMarketSeries?.length) {
64261
+ throw new Error(
64262
+ "config.buyer.riskPolicy requires allowedTokenIds or allowedMarketSeries"
64263
+ );
64264
+ }
64265
+ return {
64266
+ allowedTokenIds,
64267
+ ...allowedMarketSeries?.length ? { allowedMarketSeries } : {},
64268
+ allowedSides,
64269
+ ...input.minBuyUsdc === void 0 ? {} : { minBuyUsdc: requireString(input.minBuyUsdc, "config.buyer.riskPolicy.minBuyUsdc") },
64270
+ ...input.maxBuyUsdc === void 0 ? {} : { maxBuyUsdc: requireString(input.maxBuyUsdc, "config.buyer.riskPolicy.maxBuyUsdc") },
64271
+ ...input.minSellShares === void 0 ? {} : {
64272
+ minSellShares: requireString(
64273
+ input.minSellShares,
64274
+ "config.buyer.riskPolicy.minSellShares"
64275
+ )
64276
+ },
64277
+ ...input.maxSellShares === void 0 ? {} : {
64278
+ maxSellShares: requireString(
64279
+ input.maxSellShares,
64280
+ "config.buyer.riskPolicy.maxSellShares"
64281
+ )
64282
+ },
64283
+ ...input.minOrderShares === void 0 ? {} : {
64284
+ minOrderShares: requireString(
64285
+ input.minOrderShares,
64286
+ "config.buyer.riskPolicy.minOrderShares"
64287
+ )
64288
+ },
64289
+ ...input.maxBuyPrice === void 0 ? {} : { maxBuyPrice: requireString(input.maxBuyPrice, "config.buyer.riskPolicy.maxBuyPrice") },
64290
+ ...input.minSellPrice === void 0 ? {} : {
64291
+ minSellPrice: requireString(
64292
+ input.minSellPrice,
64293
+ "config.buyer.riskPolicy.minSellPrice"
64294
+ )
64295
+ },
64296
+ ...input.minOrderAmount === void 0 ? {} : {
64297
+ minOrderAmount: requireString(
64298
+ input.minOrderAmount,
64299
+ "config.buyer.riskPolicy.minOrderAmount"
64300
+ )
64301
+ },
64302
+ ...input.maxOrderAmount === void 0 ? {} : {
64303
+ maxOrderAmount: requireString(
64304
+ input.maxOrderAmount,
64305
+ "config.buyer.riskPolicy.maxOrderAmount"
64306
+ )
64307
+ },
64308
+ maxSlippageBps: requireInteger(
64309
+ input.maxSlippageBps,
64310
+ "config.buyer.riskPolicy.maxSlippageBps",
64311
+ 0
64312
+ ),
64313
+ maxSignalAgeMs: requireInteger(
64314
+ input.maxSignalAgeMs,
64315
+ "config.buyer.riskPolicy.maxSignalAgeMs",
64316
+ 1
64317
+ ),
64318
+ ...input.minTimeToExpiryMs === void 0 ? {} : {
64319
+ minTimeToExpiryMs: requireInteger(
64320
+ input.minTimeToExpiryMs,
64321
+ "config.buyer.riskPolicy.minTimeToExpiryMs",
64322
+ 0
64323
+ )
64324
+ },
64325
+ ...input.minEventTimeToCloseMs === void 0 ? {} : {
64326
+ minEventTimeToCloseMs: requireInteger(
64327
+ input.minEventTimeToCloseMs,
64328
+ "config.buyer.riskPolicy.minEventTimeToCloseMs",
64329
+ 0
64330
+ )
64331
+ }
64332
+ };
64333
+ }
64334
+ function parseBuyer(value) {
64335
+ const input = requireObject(value, "config.buyer");
64336
+ const executionMode = requireString(input.executionMode, "config.buyer.executionMode");
64337
+ if (executionMode !== "DRY_RUN" && executionMode !== "LIVE") {
64338
+ throw new Error("config.buyer.executionMode must be DRY_RUN or LIVE");
64339
+ }
64340
+ let polymarket;
64341
+ if (input.polymarket !== void 0) {
64342
+ const polymarketInput = requireObject(input.polymarket, "config.buyer.polymarket");
64343
+ const bin = optionalString(polymarketInput.bin, "config.buyer.polymarket.bin");
64344
+ const timeoutMs = polymarketInput.timeoutMs === void 0 ? void 0 : requireInteger(polymarketInput.timeoutMs, "config.buyer.polymarket.timeoutMs", 1);
64345
+ polymarket = {
64346
+ ...bin ? { bin } : {},
64347
+ ...timeoutMs ? { timeoutMs } : {}
64348
+ };
64349
+ }
64350
+ return {
64351
+ enabled: requireBoolean(input.enabled, "config.buyer.enabled"),
64352
+ executionMode,
64353
+ subscriptions: requireArray(input.subscriptions, "config.buyer.subscriptions").map(parseBuyerSubscription),
64354
+ riskPolicy: parseRiskPolicy(input.riskPolicy),
64355
+ ...polymarket ? { polymarket } : {}
64356
+ };
64357
+ }
64358
+ function parseSignalTradingConfig(value) {
64359
+ const input = requireObject(value, "config");
64360
+ if (input.version !== SIGNAL_TRADING_CONFIG_VERSION) {
64361
+ throw new Error(`config.version must be ${SIGNAL_TRADING_CONFIG_VERSION}`);
64362
+ }
64363
+ let provider;
64364
+ if (input.provider !== void 0) {
64365
+ const providerInput = requireObject(input.provider, "config.provider");
64366
+ provider = {
64367
+ routes: requireArray(providerInput.routes, "config.provider.routes").map(parseProviderRoute)
64368
+ };
64369
+ }
64370
+ const buyer = input.buyer === void 0 ? void 0 : parseBuyer(input.buyer);
64371
+ return {
64372
+ version: SIGNAL_TRADING_CONFIG_VERSION,
64373
+ ...provider ? { provider } : {},
64374
+ ...buyer ? { buyer } : {}
64375
+ };
64376
+ }
64377
+ function resolveSignalTradingDir(homeDir) {
64378
+ return (0, import_node_path25.join)(resolveTaskPaths(homeDir).homeDir, "signal-trading");
64379
+ }
64380
+ function resolveSignalTradingConfigPath(homeDir) {
64381
+ return (0, import_node_path25.join)(resolveSignalTradingDir(homeDir), "config.json");
64382
+ }
64383
+ function loadSignalTradingConfig(homeDir) {
64384
+ const path2 = resolveSignalTradingConfigPath(homeDir);
64385
+ if (!(0, import_node_fs19.existsSync)(path2)) {
64386
+ throw new Error(`signal trading config not found: ${path2}`);
64387
+ }
64388
+ let parsed;
64389
+ try {
64390
+ parsed = JSON.parse((0, import_node_fs19.readFileSync)(path2, "utf8"));
64391
+ } catch (error) {
64392
+ throw new Error(
64393
+ `signal trading config is not valid JSON: ${path2}: ${error instanceof Error ? error.message : String(error)}`
64394
+ );
64395
+ }
64396
+ return parseSignalTradingConfig(parsed);
64397
+ }
64398
+
64399
+ // src/signal-trading/protocol.ts
64400
+ var SIGNAL_PAYLOAD_TYPE = "signal";
64401
+ var SIGNAL_SPEC_VERSION = "1.0";
64402
+ function isPlainObject3(value) {
64403
+ return !!value && typeof value === "object" && !Array.isArray(value);
64404
+ }
64405
+ function requireObject2(value, path2) {
64406
+ if (!isPlainObject3(value)) {
64407
+ throw new Error(`${path2} must be an object`);
64408
+ }
64409
+ return value;
64410
+ }
64411
+ function requireString2(value, path2) {
64412
+ if (typeof value !== "string" || value.trim().length === 0) {
64413
+ throw new Error(`${path2} must be a non-empty string`);
64414
+ }
64415
+ return value.trim();
64416
+ }
64417
+ function optionalString2(value, path2) {
64418
+ if (value === void 0) {
64419
+ return void 0;
64420
+ }
64421
+ return requireString2(value, path2);
64422
+ }
64423
+ function requireEnum(value, path2, values) {
64424
+ if (typeof value !== "string" || !values.includes(value)) {
64425
+ throw new Error(`${path2} must be one of ${values.join(", ")}`);
64426
+ }
64427
+ return value;
64428
+ }
64429
+ function requireFiniteNumber(value, path2) {
64430
+ if (typeof value !== "number" || !Number.isFinite(value)) {
64431
+ throw new Error(`${path2} must be a finite number`);
64432
+ }
64433
+ return value;
64434
+ }
64435
+ function requireInteger2(value, path2, minimum = 0) {
64436
+ const parsed = requireFiniteNumber(value, path2);
64437
+ if (!Number.isInteger(parsed) || parsed < minimum) {
64438
+ throw new Error(`${path2} must be an integer >= ${minimum}`);
64439
+ }
64440
+ return parsed;
64441
+ }
64442
+ function requireIsoTimestamp(value, path2) {
64443
+ const timestamp = requireString2(value, path2);
64444
+ if (!Number.isFinite(Date.parse(timestamp))) {
64445
+ throw new Error(`${path2} must be an ISO-8601 timestamp`);
64446
+ }
64447
+ return timestamp;
64448
+ }
64449
+ function readStringRecord2(value, path2) {
64450
+ if (value === void 0) {
64451
+ return void 0;
64452
+ }
64453
+ const input = requireObject2(value, path2);
64454
+ const result = {};
64455
+ for (const [key, item] of Object.entries(input)) {
64456
+ result[key] = requireString2(item, `${path2}.${key}`);
64457
+ }
64458
+ return result;
64459
+ }
64460
+ function parseTradingSignalV1(value) {
64461
+ const input = requireObject2(value, "signal");
64462
+ const specVersion = requireEnum(input.specVersion, "signal.specVersion", [SIGNAL_SPEC_VERSION]);
64463
+ const emittedAt = requireIsoTimestamp(input.emittedAt, "signal.emittedAt");
64464
+ const expiresAt = requireIsoTimestamp(input.expiresAt, "signal.expiresAt");
64465
+ if (Date.parse(expiresAt) <= Date.parse(emittedAt)) {
64466
+ throw new Error("signal.expiresAt must be later than signal.emittedAt");
64467
+ }
64468
+ const instrumentInput = requireObject2(input.instrument, "signal.instrument");
64469
+ const instrument = {
64470
+ symbol: requireString2(instrumentInput.symbol, "signal.instrument.symbol"),
64471
+ marketType: requireEnum(
64472
+ instrumentInput.marketType,
64473
+ "signal.instrument.marketType",
64474
+ ["SPOT", "PERP", "ONCHAIN"]
64475
+ )
64476
+ };
64477
+ const chainId = optionalString2(instrumentInput.chainId, "signal.instrument.chainId");
64478
+ const tokenIn = optionalString2(instrumentInput.tokenIn, "signal.instrument.tokenIn");
64479
+ const tokenOut = optionalString2(instrumentInput.tokenOut, "signal.instrument.tokenOut");
64480
+ if (chainId) {
64481
+ instrument.chainId = chainId;
64482
+ }
64483
+ if (tokenIn) {
64484
+ instrument.tokenIn = tokenIn;
64485
+ }
64486
+ if (tokenOut) {
64487
+ instrument.tokenOut = tokenOut;
64488
+ }
64489
+ const intentInput = requireObject2(input.intent, "signal.intent");
64490
+ const action = requireEnum(
64491
+ intentInput.action,
64492
+ "signal.intent.action",
64493
+ ["ENTER", "EXIT", "REBALANCE", "CANCEL", "NO_TRADE"]
64494
+ );
64495
+ let intent;
64496
+ if (action === "ENTER" || action === "EXIT") {
64497
+ intent = {
64498
+ action,
64499
+ side: requireEnum(intentInput.side, "signal.intent.side", ["BUY", "SELL"]),
64500
+ orderType: requireEnum(
64501
+ intentInput.orderType,
64502
+ "signal.intent.orderType",
64503
+ ["MARKET", "LIMIT"]
64504
+ )
64505
+ };
64506
+ } else if (action === "REBALANCE") {
64507
+ const targetWeightBps = requireInteger2(
64508
+ intentInput.targetWeightBps,
64509
+ "signal.intent.targetWeightBps"
64510
+ );
64511
+ if (targetWeightBps > 1e4) {
64512
+ throw new Error("signal.intent.targetWeightBps must be <= 10000");
64513
+ }
64514
+ intent = { action, targetWeightBps };
64515
+ } else if (action === "CANCEL") {
64516
+ intent = {
64517
+ action,
64518
+ targetSignalId: optionalString2(intentInput.targetSignalId, "signal.intent.targetSignalId"),
64519
+ targetExecutionId: optionalString2(
64520
+ intentInput.targetExecutionId,
64521
+ "signal.intent.targetExecutionId"
64522
+ )
64523
+ };
64524
+ } else {
64525
+ intent = {
64526
+ action,
64527
+ reason: requireString2(intentInput.reason, "signal.intent.reason")
64528
+ };
64529
+ }
64530
+ let sizing;
64531
+ if (input.sizing !== void 0) {
64532
+ const sizingInput = requireObject2(input.sizing, "signal.sizing");
64533
+ sizing = {
64534
+ type: requireEnum(
64535
+ sizingInput.type,
64536
+ "signal.sizing.type",
64537
+ ["FIXED_BASE", "FIXED_QUOTE", "PORTFOLIO_BPS"]
64538
+ ),
64539
+ value: requireString2(sizingInput.value, "signal.sizing.value")
64540
+ };
64541
+ } else if (action === "ENTER" || action === "EXIT") {
64542
+ throw new Error(`signal.sizing is required for ${action} signals`);
64543
+ }
64544
+ let constraints;
64545
+ if (input.constraints !== void 0) {
64546
+ const constraintsInput = requireObject2(input.constraints, "signal.constraints");
64547
+ constraints = {};
64548
+ const limitPrice = optionalString2(constraintsInput.limitPrice, "signal.constraints.limitPrice");
64549
+ if (limitPrice) {
64550
+ constraints.limitPrice = limitPrice;
64551
+ }
64552
+ if (constraintsInput.maxSlippageBps !== void 0) {
64553
+ constraints.maxSlippageBps = requireInteger2(
64554
+ constraintsInput.maxSlippageBps,
64555
+ "signal.constraints.maxSlippageBps"
64556
+ );
64557
+ }
64558
+ if (constraintsInput.timeInForce !== void 0) {
64559
+ constraints.timeInForce = requireEnum(
64560
+ constraintsInput.timeInForce,
64561
+ "signal.constraints.timeInForce",
64562
+ ["GTC", "IOC", "FOK"]
64563
+ );
64564
+ }
64565
+ }
64566
+ return {
64567
+ specVersion,
64568
+ signalId: requireString2(input.signalId, "signal.signalId"),
64569
+ serviceId: requireString2(input.serviceId, "signal.serviceId"),
64570
+ subscriptionId: requireString2(input.subscriptionId, "signal.subscriptionId"),
64571
+ providerAgentId: requireString2(input.providerAgentId, "signal.providerAgentId"),
64572
+ sequence: requireInteger2(input.sequence, "signal.sequence", 1),
64573
+ emittedAt,
64574
+ expiresAt,
64575
+ instrument,
64576
+ intent,
64577
+ ...sizing ? { sizing } : {},
64578
+ ...constraints ? { constraints } : {},
64579
+ ...input.metadata !== void 0 ? { metadata: readStringRecord2(input.metadata, "signal.metadata") } : {}
64580
+ };
64581
+ }
64582
+ function buildSignalEnvelopePayload(signal) {
64583
+ return { type: SIGNAL_PAYLOAD_TYPE, signal };
64584
+ }
64585
+ function extractSignalEnvelopePayload(envelope) {
64586
+ if (!isPlainObject3(envelope) || !isPlainObject3(envelope.payload)) {
64587
+ return null;
64588
+ }
64589
+ if (envelope.payload.type !== SIGNAL_PAYLOAD_TYPE) {
64590
+ return null;
64591
+ }
64592
+ return {
64593
+ type: SIGNAL_PAYLOAD_TYPE,
64594
+ signal: parseTradingSignalV1(envelope.payload.signal)
64595
+ };
64596
+ }
64597
+ function hasSignalEnvelopePayload(envelope) {
64598
+ return isPlainObject3(envelope) && isPlainObject3(envelope.payload) && envelope.payload.type === SIGNAL_PAYLOAD_TYPE;
64599
+ }
64600
+
64601
+ // src/signal-trading/publisher.ts
64602
+ async function handleSignalPublishCommand(params) {
64603
+ const signal = parseTradingSignalV1(params.command.signal);
64604
+ if (params.command.serviceId !== signal.serviceId) {
64605
+ throw new Error(
64606
+ `signal publish --service-id ${params.command.serviceId} does not match signal.serviceId ${signal.serviceId}`
64607
+ );
64608
+ }
64609
+ const config = loadSignalTradingConfig(params.homeDir);
64610
+ const routes = config.provider?.routes.filter((route) => {
64611
+ return route.serviceId === signal.serviceId && route.subscriptionId === signal.subscriptionId;
64612
+ }) ?? [];
64613
+ if (routes.length === 0) {
64614
+ throw new Error(
64615
+ `no provider route configured for serviceId=${signal.serviceId} subscriptionId=${signal.subscriptionId}`
64616
+ );
64617
+ }
64618
+ const deliveries = [];
64619
+ for (const route of routes) {
64620
+ if (route.myAgentId && route.myAgentId !== signal.providerAgentId) {
64621
+ throw new Error(
64622
+ `provider route myAgentId=${route.myAgentId} does not match signal.providerAgentId=${signal.providerAgentId}`
64623
+ );
64624
+ }
64625
+ const childCommand = {
64626
+ id: (0, import_node_crypto12.randomUUID)(),
64627
+ type: "xmtp-send",
64628
+ jobId: route.jobId,
64629
+ message: `Trading signal ${signal.signalId} from service ${signal.serviceId}`,
64630
+ sessionAgentId: route.toAgentId,
64631
+ myAgentId: route.myAgentId ?? signal.providerAgentId,
64632
+ toAgentId: route.toAgentId,
64633
+ toXmtpAddress: route.toXmtpAddress,
64634
+ payload: buildSignalEnvelopePayload(signal),
64635
+ createdAt: params.command.createdAt
64636
+ };
64637
+ const result = await handleXmtpSendCommand({
64638
+ command: childCommand,
64639
+ service: params.service,
64640
+ store: params.store,
64641
+ sessionStore: params.sessionStore
64642
+ });
64643
+ deliveries.push({
64644
+ subscriptionId: route.subscriptionId,
64645
+ jobId: route.jobId,
64646
+ toAgentId: route.toAgentId,
64647
+ messageId: result.messageId
64648
+ });
64649
+ }
64650
+ return {
64651
+ signalId: signal.signalId,
64652
+ serviceId: signal.serviceId,
64653
+ deliveries
64654
+ };
64655
+ }
64656
+
64125
64657
  // src/command-processor.ts
64126
64658
  var DEFAULT_COMMAND_EXECUTION_TIMEOUT_MS = 5e4;
64127
64659
  var DEFAULT_COMMAND_STALE_TIMEOUT_MS = 12e4;
@@ -64150,6 +64682,11 @@ function commandSentryExtra(command, extra = {}) {
64150
64682
  base.myAgentId = command.myAgentId ?? "";
64151
64683
  base.toAgentId = command.toAgentId ?? "";
64152
64684
  base.toXmtpAddress = command.toXmtpAddress ?? "";
64685
+ } else if (command.type === "signal-publish") {
64686
+ base.serviceId = command.serviceId;
64687
+ base.signalId = command.signal.signalId;
64688
+ base.subscriptionId = command.signal.subscriptionId;
64689
+ base.agentId = command.signal.providerAgentId;
64153
64690
  } else if (command.type === "xmtp-deny-pending-conversation") {
64154
64691
  base.groupId = command.groupId;
64155
64692
  base.jobId = command.jobId ?? "";
@@ -64402,6 +64939,16 @@ async function handleDaemonCommand(command, params) {
64402
64939
  });
64403
64940
  return { ok: true, messageId: result.messageId };
64404
64941
  }
64942
+ if (command.type === "signal-publish") {
64943
+ const payload = await handleSignalPublishCommand({
64944
+ command,
64945
+ service: params.service,
64946
+ store: params.store,
64947
+ sessionStore: params.sessionStore,
64948
+ homeDir: params.homeDir
64949
+ });
64950
+ return { ok: true, payload };
64951
+ }
64405
64952
  if (command.type === "xmtp-get-pending-list") {
64406
64953
  return { ok: true, payload: await listPendingTaskRequests(params) };
64407
64954
  }
@@ -64484,12 +65031,12 @@ async function listPendingTaskRequests(params) {
64484
65031
  }
64485
65032
  async function denyPendingConversationsByJobId(jobId, params, content) {
64486
65033
  const pending = await listPendingTaskRequests(params);
64487
- const matched = pending.filter((item) => isPlainObject2(item) && readString2(item.jobId) === jobId);
65034
+ const matched = pending.filter((item) => isPlainObject4(item) && readString2(item.jobId) === jobId);
64488
65035
  const clientAddresses = [...params.service.getClients().keys()];
64489
65036
  const targetsByKey = collectDenyTargetsFromPending(matched, clientAddresses);
64490
65037
  const groupIds = /* @__PURE__ */ new Set();
64491
65038
  for (const item of matched) {
64492
- if (!isPlainObject2(item)) {
65039
+ if (!isPlainObject4(item)) {
64493
65040
  continue;
64494
65041
  }
64495
65042
  const groupId = readString2(item.groupId);
@@ -64516,7 +65063,7 @@ async function denyPendingConversationsByJobId(jobId, params, content) {
64516
65063
  function collectDenyTargetsFromPending(pending, fallbackAddresses) {
64517
65064
  const targetsByKey = /* @__PURE__ */ new Map();
64518
65065
  for (const item of pending) {
64519
- if (!isPlainObject2(item)) {
65066
+ if (!isPlainObject4(item)) {
64520
65067
  continue;
64521
65068
  }
64522
65069
  const groupId = readString2(item.groupId);
@@ -64541,7 +65088,7 @@ ${groupId}`, {
64541
65088
  async function resolvePendingTargetsByGroupId(groupId, addresses, params) {
64542
65089
  const addressSet = addresses ? new Set(addresses) : null;
64543
65090
  const pending = (await listPendingTaskRequests(params)).filter((item) => {
64544
- if (!isPlainObject2(item) || readString2(item.groupId) !== groupId) {
65091
+ if (!isPlainObject4(item) || readString2(item.groupId) !== groupId) {
64545
65092
  return false;
64546
65093
  }
64547
65094
  const address = readString2(item.myXmtpAddress);
@@ -64661,7 +65208,7 @@ function filterKnownPendingGroups(items, sessionStore) {
64661
65208
  return items;
64662
65209
  }
64663
65210
  return items.filter((item) => {
64664
- if (!isPlainObject2(item)) {
65211
+ if (!isPlainObject4(item)) {
64665
65212
  return true;
64666
65213
  }
64667
65214
  const jobId = readString2(item.jobId);
@@ -64672,7 +65219,7 @@ function filterKnownPendingGroups(items, sessionStore) {
64672
65219
  return sessionStore.querySessions({ jobId, toAgentId, limit: 1 }).length === 0;
64673
65220
  });
64674
65221
  }
64675
- function isPlainObject2(value) {
65222
+ function isPlainObject4(value) {
64676
65223
  return !!value && typeof value === "object" && !Array.isArray(value);
64677
65224
  }
64678
65225
  function readString2(value) {
@@ -64806,6 +65353,11 @@ function formatCommandCompleted(command, result) {
64806
65353
  if (command.type === "xmtp-send") {
64807
65354
  return `[okx-agent-task] xmtp-send command completed id=${command.id} job=${command.jobId} messageId=${result.messageId}`;
64808
65355
  }
65356
+ if (command.type === "signal-publish") {
65357
+ const payload = isPlainObject4(result.payload) ? result.payload : {};
65358
+ const deliveries = Array.isArray(payload.deliveries) ? payload.deliveries.length : 0;
65359
+ return `[signal-trading] signal-publish command completed id=${command.id} service=${command.serviceId} signal=${command.signal.signalId} deliveries=${deliveries}`;
65360
+ }
64809
65361
  if (command.type === "xmtp-get-pending-list") {
64810
65362
  return `[okx-agent-task] xmtp-get-pending-list command completed id=${command.id}`;
64811
65363
  }
@@ -64826,8 +65378,8 @@ function formatCommandCompleted(command, result) {
64826
65378
  return `[okx-agent-task] xmtp-refresh-agents command completed id=${command.id}`;
64827
65379
  }
64828
65380
  function formatXmtpDebugCompleted(command, payload) {
64829
- const record = isPlainObject2(payload) ? payload : {};
64830
- const summary = isPlainObject2(record.summary) ? record.summary : {};
65381
+ const record = isPlainObject4(payload) ? payload : {};
65382
+ const summary = isPlainObject4(record.summary) ? record.summary : {};
64831
65383
  const count = command.action === "group-list" ? record.groupCount ?? 0 : command.action === "group-inspect" ? record.conversationFound ? 1 : 0 : summary.matchedCount ?? 0;
64832
65384
  return `[okx-agent-task] xmtp-debug command completed id=${command.id} action=${command.action} rows=${String(count)}`;
64833
65385
  }
@@ -64968,7 +65520,7 @@ function trimForUser2(value) {
64968
65520
 
64969
65521
  // src/message-handler.ts
64970
65522
  init_log();
64971
- var import_node_crypto12 = require("node:crypto");
65523
+ var import_node_crypto13 = require("node:crypto");
64972
65524
  init_sentry_logger();
64973
65525
  init_log_fields();
64974
65526
  init_paths();
@@ -64990,7 +65542,7 @@ function tryMarkProcessed(messageId) {
64990
65542
  }
64991
65543
  return true;
64992
65544
  }
64993
- function isPlainObject3(value) {
65545
+ function isPlainObject5(value) {
64994
65546
  return !!value && typeof value === "object" && !Array.isArray(value);
64995
65547
  }
64996
65548
  function safeStringify(value) {
@@ -65047,9 +65599,9 @@ function readNumber(value) {
65047
65599
  }
65048
65600
  function resolveSessionAgentId(params) {
65049
65601
  const { chatType, payload, myXmtpAddress } = params;
65050
- const payloadObject = isPlainObject3(payload) ? payload : null;
65051
- const sender = isPlainObject3(payloadObject?.sender) ? payloadObject.sender : null;
65052
- const message = isPlainObject3(payloadObject?.message) ? payloadObject.message : null;
65602
+ const payloadObject = isPlainObject5(payload) ? payload : null;
65603
+ const sender = isPlainObject5(payloadObject?.sender) ? payloadObject.sender : null;
65604
+ const message = isPlainObject5(payloadObject?.message) ? payloadObject.message : null;
65053
65605
  const localAgentId = XmtpService.getInstance().getAgentByAddress(myXmtpAddress)?.agentId ?? null;
65054
65606
  if (chatType === "group") {
65055
65607
  return readString3(sender?.agentId) ?? readString3(payloadObject?.receiverAgentId) ?? localAgentId;
@@ -65060,7 +65612,7 @@ function resolveSessionAgentId(params) {
65060
65612
  return localAgentId;
65061
65613
  }
65062
65614
  function routeMessage(chatType, parsed, payload) {
65063
- if (!parsed || !isPlainObject3(payload)) {
65615
+ if (!parsed || !isPlainObject5(payload)) {
65064
65616
  return {
65065
65617
  jobId: BACKUP_JOB_ID,
65066
65618
  route: "backup",
@@ -65072,7 +65624,7 @@ function routeMessage(chatType, parsed, payload) {
65072
65624
  return jobId ? { jobId, route: "job", routeReason: "group-job-id" } : { jobId: BACKUP_JOB_ID, route: "backup", routeReason: "group-missing-job-id" };
65073
65625
  }
65074
65626
  if (chatType === "dm") {
65075
- const message = isPlainObject3(payload.message) ? payload.message : null;
65627
+ const message = isPlainObject5(payload.message) ? payload.message : null;
65076
65628
  const nestedJobId = readString3(message?.jobId);
65077
65629
  const directJobId = readString3(payload.jobId);
65078
65630
  const jobId = nestedJobId ?? directJobId;
@@ -65085,10 +65637,10 @@ function routeMessage(chatType, parsed, payload) {
65085
65637
  return { jobId: BACKUP_JOB_ID, route: "backup", routeReason: "unknown-conversation" };
65086
65638
  }
65087
65639
  function extractDirectToUserNotification(payload) {
65088
- if (!isPlainObject3(payload)) {
65640
+ if (!isPlainObject5(payload)) {
65089
65641
  return { kind: "none" };
65090
65642
  }
65091
- const message = isPlainObject3(payload.message) ? payload.message : null;
65643
+ const message = isPlainObject5(payload.message) ? payload.message : null;
65092
65644
  if (message?.isDirectToUser !== true) {
65093
65645
  return { kind: "none" };
65094
65646
  }
@@ -65112,10 +65664,10 @@ function extractDirectToUserNotification(payload) {
65112
65664
  };
65113
65665
  }
65114
65666
  function extractSystemNotification(payload) {
65115
- if (!isPlainObject3(payload)) {
65667
+ if (!isPlainObject5(payload)) {
65116
65668
  return null;
65117
65669
  }
65118
- const message = isPlainObject3(payload.message) ? payload.message : null;
65670
+ const message = isPlainObject5(payload.message) ? payload.message : null;
65119
65671
  const isDirectCommunication = message?.isDirectCommunication === true;
65120
65672
  if (message?.source !== "system" && !isDirectCommunication) {
65121
65673
  return null;
@@ -65416,7 +65968,7 @@ function maybeNotifyInboundAgentMessage(params) {
65416
65968
  return;
65417
65969
  }
65418
65970
  const content = payloadObject.content;
65419
- const sender = isPlainObject3(payloadObject.sender) ? payloadObject.sender : null;
65971
+ const sender = isPlainObject5(payloadObject.sender) ? payloadObject.sender : null;
65420
65972
  const localAgent = XmtpService.getInstance().getAgentByAddress(params.deps.myXmtpAddress);
65421
65973
  void notifyAgentMessageToUserAttention({
65422
65974
  direction: "inbound" /* INBOUND */,
@@ -65447,11 +65999,11 @@ function stringifySystemPayload(payload) {
65447
65999
  }
65448
66000
  }
65449
66001
  function summarizePayloadForLog(payload) {
65450
- if (!isPlainObject3(payload)) {
66002
+ if (!isPlainObject5(payload)) {
65451
66003
  return "payload=non-object";
65452
66004
  }
65453
- const message = isPlainObject3(payload.message) ? payload.message : null;
65454
- const sender = isPlainObject3(payload.sender) ? payload.sender : null;
66005
+ const message = isPlainObject5(payload.message) ? payload.message : null;
66006
+ const sender = isPlainObject5(payload.sender) ? payload.sender : null;
65455
66007
  const jobId = readString3(payload.jobId) ?? readString3(message?.jobId);
65456
66008
  const parts = [
65457
66009
  readString3(payload.msgType) ? `type=${readString3(payload.msgType)}` : null,
@@ -65720,7 +66272,7 @@ async function verifyInboundA2AGroupMessage(params) {
65720
66272
  messageId,
65721
66273
  groupId,
65722
66274
  jobId,
65723
- agentId: readString3(isPlainObject3(payload.sender) ? payload.sender.agentId : null),
66275
+ agentId: readString3(isPlainObject5(payload.sender) ? payload.sender.agentId : null),
65724
66276
  localAgentId: myAgent?.agentId ?? null,
65725
66277
  senderAddress,
65726
66278
  senderInboxId,
@@ -65746,7 +66298,7 @@ async function verifyInboundA2AGroupMessage(params) {
65746
66298
  });
65747
66299
  return false;
65748
66300
  }
65749
- const sender = isPlainObject3(payload.sender) ? payload.sender : null;
66301
+ const sender = isPlainObject5(payload.sender) ? payload.sender : null;
65750
66302
  const senderAgentId = readString3(sender?.agentId);
65751
66303
  const senderRole = readNumber(sender?.role);
65752
66304
  if (!senderAgentId || !myAgent) {
@@ -65970,7 +66522,7 @@ async function processFileMessage(ctx, deps, options = {}) {
65970
66522
  timing.mark("payloadParse", parseStartedAt);
65971
66523
  const directToUser = chatType === "dm" && parseResult.ok ? extractDirectToUserNotification(parseResult.data) : { kind: "none" };
65972
66524
  if (directToUser.kind === "invalid") {
65973
- const droppedMessageId = messageId || `direct-to-user-${(0, import_node_crypto12.randomUUID)()}`;
66525
+ const droppedMessageId = messageId || `direct-to-user-${(0, import_node_crypto13.randomUUID)()}`;
65974
66526
  logger.error(
65975
66527
  LogEvent.INBOUND_DROP_DM_INVALID_PAYLOAD,
65976
66528
  new Error("Invalid direct-to-user system DM"),
@@ -65994,7 +66546,7 @@ async function processFileMessage(ctx, deps, options = {}) {
65994
66546
  await dispatchDirectToUserNotification({
65995
66547
  deps,
65996
66548
  notification: directToUser.notification,
65997
- messageId: messageId || `direct-to-user-${(0, import_node_crypto12.randomUUID)()}`,
66549
+ messageId: messageId || `direct-to-user-${(0, import_node_crypto13.randomUUID)()}`,
65998
66550
  timing,
65999
66551
  source: options.source ?? "live"
66000
66552
  });
@@ -66002,7 +66554,7 @@ async function processFileMessage(ctx, deps, options = {}) {
66002
66554
  }
66003
66555
  const systemNotification = chatType === "dm" && parseResult.ok ? extractSystemNotification(parseResult.data) : null;
66004
66556
  if (systemNotification) {
66005
- const systemMessageId = messageId || `system-${(0, import_node_crypto12.randomUUID)()}`;
66557
+ const systemMessageId = messageId || `system-${(0, import_node_crypto13.randomUUID)()}`;
66006
66558
  logWithTimestamp(
66007
66559
  `[okx-agent-task:${deps.myXmtpAddress}] xmtp_system_message_received agentId=${systemNotification.agentId ?? ""} msg=${shortenLogValue(systemMessageId)} event=${systemNotification.event ?? ""} job=${shortenLogValue(systemNotification.jobId)} conv=${conversationId} source=${options.source ?? "live"} rawBytes=${Buffer.byteLength(rawText, "utf8")} rawPreview=${previewRawEnvelope(rawText)}`
66008
66560
  );
@@ -66201,7 +66753,7 @@ async function processFileMessage(ctx, deps, options = {}) {
66201
66753
  );
66202
66754
  }
66203
66755
  if (route.route === "job" && chatType === "group") {
66204
- const payloadObject = isPlainObject3(parseResult.ok ? parseResult.data : null) ? parseResult.data : null;
66756
+ const payloadObject = isPlainObject5(parseResult.ok ? parseResult.data : null) ? parseResult.data : null;
66205
66757
  const service = XmtpService.getInstance();
66206
66758
  const trustedSystemSender = service.isTrustedSystemAccountSender({
66207
66759
  senderAddress,
@@ -66227,7 +66779,7 @@ async function processFileMessage(ctx, deps, options = {}) {
66227
66779
  });
66228
66780
  return true;
66229
66781
  }
66230
- const sender = isPlainObject3(payloadObject?.sender) ? payloadObject.sender : null;
66782
+ const sender = isPlainObject5(payloadObject?.sender) ? payloadObject.sender : null;
66231
66783
  const localAgent = service.getAgentByAddress(deps.myXmtpAddress);
66232
66784
  const myAgentId = localAgent?.agentId ?? readString3(payloadObject?.receiverAgentId) ?? sessionAgentId ?? null;
66233
66785
  const toAgentId = readString3(sender?.agentId);
@@ -66247,7 +66799,7 @@ async function processFileMessage(ctx, deps, options = {}) {
66247
66799
  if (!accepted) {
66248
66800
  return true;
66249
66801
  }
66250
- const routedMessageId = messageId || `group-${(0, import_node_crypto12.randomUUID)()}`;
66802
+ const routedMessageId = messageId || `group-${(0, import_node_crypto13.randomUUID)()}`;
66251
66803
  const sessionKey = ensureInboundGroupSession(deps, {
66252
66804
  jobId: route.jobId,
66253
66805
  myAgentId,
@@ -66255,6 +66807,35 @@ async function processFileMessage(ctx, deps, options = {}) {
66255
66807
  groupId: conversationId,
66256
66808
  toAgentXmtpAddress: senderAddress || readString3(payloadObject?.fromXmtpAddress)
66257
66809
  });
66810
+ if (hasSignalEnvelopePayload(parseResult.data)) {
66811
+ try {
66812
+ const signalPayload = extractSignalEnvelopePayload(parseResult.data);
66813
+ if (!signalPayload) {
66814
+ throw new Error("signal envelope payload is missing");
66815
+ }
66816
+ if (!toAgentId) {
66817
+ throw new Error("signal envelope sender.agentId is missing");
66818
+ }
66819
+ if (!deps.onSignalTradingSignal) {
66820
+ throw new Error("signal buyer runtime is unavailable");
66821
+ }
66822
+ await deps.onSignalTradingSignal({
66823
+ signal: signalPayload.signal,
66824
+ jobId: route.jobId,
66825
+ senderAgentId: toAgentId,
66826
+ messageId: routedMessageId
66827
+ });
66828
+ logWithTimestamp(
66829
+ `[signal-trading] inbound signal handled signal=${signalPayload.signal.signalId} service=${signalPayload.signal.serviceId} job=${shortenLogValue(route.jobId)} message=${shortenLogValue(routedMessageId)}`
66830
+ );
66831
+ } catch (error) {
66832
+ logWithTimestamp(
66833
+ `[signal-trading] inbound signal rejected job=${shortenLogValue(route.jobId)} message=${shortenLogValue(routedMessageId)}:`,
66834
+ error
66835
+ );
66836
+ }
66837
+ return true;
66838
+ }
66258
66839
  const dispatchStartedAt = Date.now();
66259
66840
  void Promise.resolve(deps.onSessionMessage?.({
66260
66841
  sessionKey,
@@ -66313,7 +66894,7 @@ async function processFileMessage(ctx, deps, options = {}) {
66313
66894
  return true;
66314
66895
  }
66315
66896
  const stored = {
66316
- id: messageId || `local-${(0, import_node_crypto12.randomUUID)()}`,
66897
+ id: messageId || `local-${(0, import_node_crypto13.randomUUID)()}`,
66317
66898
  direction: "inbound",
66318
66899
  route: route.route,
66319
66900
  routeReason: route.routeReason,
@@ -66331,8 +66912,8 @@ async function processFileMessage(ctx, deps, options = {}) {
66331
66912
  await deps.store.append(route.jobId, stored, sessionAgentId);
66332
66913
  timing.mark("storeAppend", storeAppendStartedAt);
66333
66914
  if ((route.route === "job" || parseResult.ok && !isA2AEnvelope(stored.payload)) && !options.skipNotify) {
66334
- const payloadObject = isPlainObject3(stored.payload) ? stored.payload : null;
66335
- const sender = isPlainObject3(payloadObject?.sender) ? payloadObject.sender : null;
66915
+ const payloadObject = isPlainObject5(stored.payload) ? stored.payload : null;
66916
+ const sender = isPlainObject5(payloadObject?.sender) ? payloadObject.sender : null;
66336
66917
  const localAgent = XmtpService.getInstance().getAgentByAddress(deps.myXmtpAddress);
66337
66918
  const sessionKey = route.route === "job" ? buildSessionKey({
66338
66919
  jobId: route.jobId,
@@ -66350,8 +66931,8 @@ async function processFileMessage(ctx, deps, options = {}) {
66350
66931
  });
66351
66932
  }
66352
66933
  if (route.route === "job" && chatType === "group" && conversationId && senderAddress) {
66353
- const payloadObject = isPlainObject3(stored.payload) ? stored.payload : null;
66354
- const sender = isPlainObject3(payloadObject?.sender) ? payloadObject.sender : null;
66934
+ const payloadObject = isPlainObject5(stored.payload) ? stored.payload : null;
66935
+ const sender = isPlainObject5(payloadObject?.sender) ? payloadObject.sender : null;
66355
66936
  await deps.store.updateXmtpSession(route.jobId, {
66356
66937
  xmtpGroupId: conversationId,
66357
66938
  myXmtpAddress: deps.myXmtpAddress,
@@ -66478,7 +67059,8 @@ function createMiddlewareFromCoreDeps(store, deps, extra) {
66478
67059
  allowGroup: deps.allowGroup,
66479
67060
  onMessageProcessed: deps.onMessageProcessed,
66480
67061
  onJobMessageStored: extra?.onJobMessageStored,
66481
- onSessionMessage: extra?.onSessionMessage
67062
+ onSessionMessage: extra?.onSessionMessage,
67063
+ onSignalTradingSignal: extra?.onSignalTradingSignal
66482
67064
  });
66483
67065
  }
66484
67066
  function processOfflineFromCoreDeps(store, ctx, deps, options) {
@@ -66488,13 +67070,14 @@ function processOfflineFromCoreDeps(store, ctx, deps, options) {
66488
67070
  sessionStore: options.sessionStore,
66489
67071
  allowGroup: deps.allowGroup,
66490
67072
  onJobMessageStored: options.onJobMessageStored,
66491
- onSessionMessage: options.onSessionMessage
67073
+ onSessionMessage: options.onSessionMessage,
67074
+ onSignalTradingSignal: options.onSignalTradingSignal
66492
67075
  }, { ...options, source: "replay" });
66493
67076
  }
66494
67077
  function buildSystemStoredMessage(params) {
66495
67078
  const now = Date.now();
66496
67079
  return {
66497
- id: params.id ?? `system-${now}-${(0, import_node_crypto12.randomUUID)()}`,
67080
+ id: params.id ?? `system-${now}-${(0, import_node_crypto13.randomUUID)()}`,
66498
67081
  direction: "system",
66499
67082
  route: "backup",
66500
67083
  routeReason: params.reason,
@@ -66510,15 +67093,640 @@ function buildSystemStoredMessage(params) {
66510
67093
  };
66511
67094
  }
66512
67095
  function isA2AEnvelope(payload) {
66513
- return isPlainObject3(payload) && payload.msgType === A2A_MESSAGE_TYPE;
67096
+ return isPlainObject5(payload) && payload.msgType === A2A_MESSAGE_TYPE;
66514
67097
  }
66515
67098
 
67099
+ // src/signal-trading/execution.ts
67100
+ var import_node_child_process7 = require("node:child_process");
67101
+ var import_node_crypto14 = require("node:crypto");
67102
+ var import_node_fs20 = require("node:fs");
67103
+ var import_node_path26 = require("node:path");
67104
+ var import_node_util3 = require("node:util");
67105
+ init_log();
67106
+ var execFileAsync3 = (0, import_node_util3.promisify)(import_node_child_process7.execFile);
67107
+ var DEFAULT_POLYMARKET_TIMEOUT_MS = 3e4;
67108
+ var MAX_POLYMARKET_OUTPUT_BYTES = 1048576;
67109
+ var MAX_RECEIPT_OUTPUT_CHARS = 16384;
67110
+ var MAX_FUTURE_CLOCK_SKEW_MS = 3e4;
67111
+ function defaultPolymarketCommandRunner(bin, args, options) {
67112
+ return execFileAsync3(bin, args, {
67113
+ windowsHide: true,
67114
+ timeout: options.timeoutMs,
67115
+ maxBuffer: MAX_POLYMARKET_OUTPUT_BYTES
67116
+ });
67117
+ }
67118
+ async function defaultPolymarketEventFetcher(slug, options) {
67119
+ const response = await fetch(
67120
+ `https://gamma-api.polymarket.com/events/slug/${encodeURIComponent(slug)}`,
67121
+ { signal: AbortSignal.timeout(options.timeoutMs) }
67122
+ );
67123
+ if (!response.ok) {
67124
+ throw new Error(`Gamma API returned HTTP ${response.status}`);
67125
+ }
67126
+ return response.json();
67127
+ }
67128
+ function normalizeDecimal(value, path2) {
67129
+ const trimmed = value.trim();
67130
+ const match = /^(?:0|[1-9]\d*)(?:\.(\d+))?$/.exec(trimmed);
67131
+ if (!match || /^0(?:\.0+)?$/.test(trimmed)) {
67132
+ throw new Error(`${path2} must be a positive decimal string`);
67133
+ }
67134
+ const fraction = match[1] ?? "";
67135
+ return {
67136
+ digits: BigInt(trimmed.replace(".", "")),
67137
+ scale: fraction.length
67138
+ };
67139
+ }
67140
+ function comparePositiveDecimals(left, right) {
67141
+ const a = normalizeDecimal(left, "left decimal");
67142
+ const b = normalizeDecimal(right, "right decimal");
67143
+ const scale = Math.max(a.scale, b.scale);
67144
+ const aScaled = a.digits * 10n ** BigInt(scale - a.scale);
67145
+ const bScaled = b.digits * 10n ** BigInt(scale - b.scale);
67146
+ return aScaled < bScaled ? -1 : aScaled > bScaled ? 1 : 0;
67147
+ }
67148
+ function formatDecimal(digits, scale) {
67149
+ const raw = digits.toString().padStart(scale + 1, "0");
67150
+ if (scale === 0) {
67151
+ return raw;
67152
+ }
67153
+ const integer = raw.slice(0, -scale);
67154
+ const fraction = raw.slice(-scale).replace(/0+$/, "");
67155
+ return fraction ? `${integer}.${fraction}` : integer;
67156
+ }
67157
+ function adjustPriceByBps(value, bps, side) {
67158
+ const parsed = normalizeDecimal(value, "Polymarket reference price");
67159
+ const scale = Math.max(parsed.scale, 6);
67160
+ const scaled = parsed.digits * 10n ** BigInt(scale - parsed.scale);
67161
+ const factor = BigInt(side === "buy" ? 1e4 + bps : 1e4 - bps);
67162
+ const product = scaled * factor;
67163
+ const quotient = product / 10000n;
67164
+ const adjusted = side === "buy" && product % 10000n !== 0n ? quotient + 1n : quotient;
67165
+ if (adjusted <= 0n) {
67166
+ throw new Error("calculated Polymarket limit price must be positive");
67167
+ }
67168
+ return formatDecimal(adjusted, scale);
67169
+ }
67170
+ function divideDecimal(left, right, outputScale = 6) {
67171
+ const numerator = normalizeDecimal(left, "Polymarket BUY amount");
67172
+ const denominator = normalizeDecimal(right, "Polymarket BUY limit price");
67173
+ const scaledNumerator = numerator.digits * 10n ** BigInt(denominator.scale + outputScale);
67174
+ const scaledDenominator = denominator.digits * 10n ** BigInt(numerator.scale);
67175
+ const quotient = scaledNumerator / scaledDenominator;
67176
+ if (quotient <= 0n) {
67177
+ throw new Error("calculated Polymarket order size must be positive");
67178
+ }
67179
+ return formatDecimal(quotient, outputScale);
67180
+ }
67181
+ function minDecimal(left, right) {
67182
+ return comparePositiveDecimals(left, right) <= 0 ? left : right;
67183
+ }
67184
+ function maxDecimal(left, right) {
67185
+ return comparePositiveDecimals(left, right) >= 0 ? left : right;
67186
+ }
67187
+ function alignPriceToTick(value, tickSize, side) {
67188
+ const price = normalizeDecimal(value, "Polymarket limit price");
67189
+ const tick = normalizeDecimal(tickSize, "Polymarket tick size");
67190
+ const scale = Math.max(price.scale, tick.scale);
67191
+ const scaledPrice = price.digits * 10n ** BigInt(scale - price.scale);
67192
+ const scaledTick = tick.digits * 10n ** BigInt(scale - tick.scale);
67193
+ const quotient = scaledPrice / scaledTick;
67194
+ const alignedTicks = side === "sell" && scaledPrice % scaledTick !== 0n ? quotient + 1n : quotient;
67195
+ const aligned = alignedTicks * scaledTick;
67196
+ if (aligned <= 0n) {
67197
+ throw new Error("calculated Polymarket tick-aligned limit price must be positive");
67198
+ }
67199
+ return formatDecimal(aligned, scale);
67200
+ }
67201
+ function requireBuyerSubscription(buyer, signal, context) {
67202
+ const subscription = buyer.subscriptions.find((candidate) => {
67203
+ return candidate.serviceId === signal.serviceId && candidate.subscriptionId === signal.subscriptionId && candidate.jobId === context.jobId && candidate.providerAgentId === signal.providerAgentId;
67204
+ });
67205
+ if (!subscription) {
67206
+ throw new Error(
67207
+ `signal subscription is not configured for serviceId=${signal.serviceId} subscriptionId=${signal.subscriptionId} jobId=${context.jobId}`
67208
+ );
67209
+ }
67210
+ if (context.senderAgentId !== signal.providerAgentId) {
67211
+ throw new Error(
67212
+ `signal providerAgentId=${signal.providerAgentId} does not match verified senderAgentId=${context.senderAgentId}`
67213
+ );
67214
+ }
67215
+ }
67216
+ function buildPolymarketExecutionPlan(signalValue, buyer, context, market, nowMs = Date.now()) {
67217
+ const signal = parseTradingSignalV1(signalValue);
67218
+ validateSignalPreconditions(signal, buyer, context, nowMs);
67219
+ if (signal.intent.action !== "ENTER" && signal.intent.action !== "EXIT") {
67220
+ throw new Error(`Polymarket demo does not execute ${signal.intent.action} signals`);
67221
+ }
67222
+ if (!signal.sizing) {
67223
+ throw new Error(`signal.sizing is required for ${signal.intent.action} signals`);
67224
+ }
67225
+ if (signal.intent.orderType !== "MARKET") {
67226
+ throw new Error("Polymarket demo accepts MARKET intents only");
67227
+ }
67228
+ if (!buyer.riskPolicy.allowedSides.includes(signal.intent.side)) {
67229
+ throw new Error(`signal side ${signal.intent.side} is not allowed by risk policy`);
67230
+ }
67231
+ const expectedSizing = signal.intent.side === "BUY" ? "FIXED_QUOTE" : "FIXED_BASE";
67232
+ if (signal.sizing.type !== expectedSizing) {
67233
+ throw new Error(`${signal.intent.side} market orders require sizing.type=${expectedSizing}`);
67234
+ }
67235
+ normalizeDecimal(signal.sizing.value, "signal.sizing.value");
67236
+ const side = signal.intent.side.toLowerCase();
67237
+ const minimumAmount = side === "buy" ? buyer.riskPolicy.minBuyUsdc ?? buyer.riskPolicy.minOrderAmount : buyer.riskPolicy.minSellShares ?? buyer.riskPolicy.minOrderAmount;
67238
+ const maximumAmount = side === "buy" ? buyer.riskPolicy.maxBuyUsdc ?? buyer.riskPolicy.maxOrderAmount : buyer.riskPolicy.maxSellShares ?? buyer.riskPolicy.maxOrderAmount;
67239
+ if (!maximumAmount) {
67240
+ throw new Error(
67241
+ side === "buy" ? "config.buyer.riskPolicy.maxBuyUsdc is required for BUY" : "config.buyer.riskPolicy.maxSellShares is required for SELL"
67242
+ );
67243
+ }
67244
+ if (minimumAmount && comparePositiveDecimals(signal.sizing.value, minimumAmount) < 0) {
67245
+ throw new Error(
67246
+ `signal amount ${signal.sizing.value} is below ${side} risk minimum ${minimumAmount}`
67247
+ );
67248
+ }
67249
+ if (comparePositiveDecimals(signal.sizing.value, maximumAmount) > 0) {
67250
+ throw new Error(
67251
+ `signal amount ${signal.sizing.value} exceeds ${side} risk maximum ${maximumAmount}`
67252
+ );
67253
+ }
67254
+ if (signal.constraints?.maxSlippageBps !== void 0 && signal.constraints.maxSlippageBps > buyer.riskPolicy.maxSlippageBps) {
67255
+ throw new Error(
67256
+ `signal maxSlippageBps ${signal.constraints.maxSlippageBps} exceeds risk policy ${buyer.riskPolicy.maxSlippageBps}`
67257
+ );
67258
+ }
67259
+ if (buyer.riskPolicy.maxSlippageBps > 1e4) {
67260
+ throw new Error("config.buyer.riskPolicy.maxSlippageBps must be <= 10000");
67261
+ }
67262
+ const tokenId = signal.metadata?.polymarketTokenId ?? signal.instrument.symbol;
67263
+ if (!buyer.riskPolicy.allowedTokenIds.includes(tokenId)) {
67264
+ throw new Error(`Polymarket token ${tokenId} is not allowlisted`);
67265
+ }
67266
+ normalizeDecimal(market.referencePrice, "Polymarket reference price");
67267
+ if (comparePositiveDecimals(market.referencePrice, "1") > 0) {
67268
+ throw new Error("Polymarket reference price must be <= 1");
67269
+ }
67270
+ const slippageBps = signal.constraints?.maxSlippageBps ?? buyer.riskPolicy.maxSlippageBps;
67271
+ const slippageLimit = adjustPriceByBps(market.referencePrice, slippageBps, side);
67272
+ let limitPrice;
67273
+ if (side === "buy") {
67274
+ const maxBuyPrice = buyer.riskPolicy.maxBuyPrice;
67275
+ if (!maxBuyPrice) {
67276
+ throw new Error("config.buyer.riskPolicy.maxBuyPrice is required for BUY");
67277
+ }
67278
+ if (comparePositiveDecimals(market.referencePrice, maxBuyPrice) > 0) {
67279
+ throw new Error(
67280
+ `Polymarket BUY reference price ${market.referencePrice} exceeds maxBuyPrice ${maxBuyPrice}`
67281
+ );
67282
+ }
67283
+ limitPrice = alignPriceToTick(minDecimal(slippageLimit, maxBuyPrice), market.tickSize, side);
67284
+ } else {
67285
+ const minSellPrice = buyer.riskPolicy.minSellPrice;
67286
+ if (!minSellPrice) {
67287
+ throw new Error("config.buyer.riskPolicy.minSellPrice is required for SELL");
67288
+ }
67289
+ if (comparePositiveDecimals(market.referencePrice, minSellPrice) < 0) {
67290
+ throw new Error(
67291
+ `Polymarket SELL reference price ${market.referencePrice} is below minSellPrice ${minSellPrice}`
67292
+ );
67293
+ }
67294
+ limitPrice = alignPriceToTick(maxDecimal(slippageLimit, minSellPrice), market.tickSize, side);
67295
+ }
67296
+ const size3 = side === "buy" ? divideDecimal(signal.sizing.value, limitPrice) : signal.sizing.value;
67297
+ if (comparePositiveDecimals(limitPrice, "1") > 0) {
67298
+ throw new Error("calculated Polymarket limit price must be <= 1");
67299
+ }
67300
+ const minOrderSize = market.minOrderSize ?? buyer.riskPolicy.minOrderShares;
67301
+ if (minOrderSize && comparePositiveDecimals(size3, minOrderSize) < 0) {
67302
+ throw new Error(
67303
+ `calculated Polymarket order size ${size3} is below market minimum ${minOrderSize}`
67304
+ );
67305
+ }
67306
+ return {
67307
+ bin: buyer.polymarket?.bin ?? process.env.POLYMARKET_BIN ?? "polymarket",
67308
+ args: [
67309
+ "-o",
67310
+ "json",
67311
+ "clob",
67312
+ "create-order",
67313
+ "--token",
67314
+ tokenId,
67315
+ "--side",
67316
+ side,
67317
+ "--price",
67318
+ limitPrice,
67319
+ "--size",
67320
+ size3,
67321
+ "--order-type",
67322
+ "FOK"
67323
+ ],
67324
+ tokenId,
67325
+ side,
67326
+ amount: signal.sizing.value,
67327
+ referencePrice: market.referencePrice,
67328
+ limitPrice,
67329
+ size: size3
67330
+ };
67331
+ }
67332
+ function validateSignalPreconditions(signal, buyer, context, nowMs) {
67333
+ if (!buyer.enabled) {
67334
+ throw new Error("signal buyer runtime is disabled");
67335
+ }
67336
+ requireBuyerSubscription(buyer, signal, context);
67337
+ const emittedAtMs = Date.parse(signal.emittedAt);
67338
+ const expiresAtMs = Date.parse(signal.expiresAt);
67339
+ if (expiresAtMs <= nowMs) {
67340
+ throw new Error(`signal ${signal.signalId} is expired`);
67341
+ }
67342
+ if (buyer.riskPolicy.minTimeToExpiryMs !== void 0 && expiresAtMs - nowMs < buyer.riskPolicy.minTimeToExpiryMs) {
67343
+ throw new Error(
67344
+ `signal ${signal.signalId} expires too soon for minTimeToExpiryMs=${buyer.riskPolicy.minTimeToExpiryMs}`
67345
+ );
67346
+ }
67347
+ if (emittedAtMs > nowMs + MAX_FUTURE_CLOCK_SKEW_MS) {
67348
+ throw new Error(`signal ${signal.signalId} emittedAt is too far in the future`);
67349
+ }
67350
+ if (nowMs - emittedAtMs > buyer.riskPolicy.maxSignalAgeMs) {
67351
+ throw new Error(`signal ${signal.signalId} exceeds maxSignalAgeMs`);
67352
+ }
67353
+ if (signal.instrument.marketType !== "ONCHAIN") {
67354
+ throw new Error("Polymarket execution requires instrument.marketType=ONCHAIN");
67355
+ }
67356
+ if (signal.metadata?.venue?.toLowerCase() !== "polymarket") {
67357
+ throw new Error("signal.metadata.venue must be polymarket");
67358
+ }
67359
+ }
67360
+ function receiptPath(homeDir, idempotencyKey) {
67361
+ const digest = (0, import_node_crypto14.createHash)("sha256").update(idempotencyKey).digest("hex");
67362
+ return (0, import_node_path26.join)(resolveSignalTradingDir(homeDir), "executions", `${digest}.json`);
67363
+ }
67364
+ function readReceipt(path2) {
67365
+ if (!(0, import_node_fs20.existsSync)(path2)) {
67366
+ return null;
67367
+ }
67368
+ try {
67369
+ return JSON.parse((0, import_node_fs20.readFileSync)(path2, "utf8"));
67370
+ } catch {
67371
+ return null;
67372
+ }
67373
+ }
67374
+ function claimReceipt(path2, receipt) {
67375
+ (0, import_node_fs20.mkdirSync)((0, import_node_path26.join)(path2, ".."), { recursive: true });
67376
+ let fd;
67377
+ try {
67378
+ fd = (0, import_node_fs20.openSync)(path2, "wx", 384);
67379
+ } catch (error) {
67380
+ if (error.code === "EEXIST") {
67381
+ return false;
67382
+ }
67383
+ throw error;
67384
+ }
67385
+ try {
67386
+ (0, import_node_fs20.writeSync)(fd, JSON.stringify(receipt, null, 2));
67387
+ } finally {
67388
+ (0, import_node_fs20.closeSync)(fd);
67389
+ }
67390
+ return true;
67391
+ }
67392
+ function updateReceipt(path2, receipt) {
67393
+ const temporaryPath = `${path2}.${process.pid}.${(0, import_node_crypto14.randomUUID)()}.tmp`;
67394
+ (0, import_node_fs20.writeFileSync)(temporaryPath, JSON.stringify(receipt, null, 2), { mode: 384 });
67395
+ (0, import_node_fs20.renameSync)(temporaryPath, path2);
67396
+ }
67397
+ function boundedOutput(value) {
67398
+ if (typeof value !== "string" || value.length === 0) {
67399
+ return void 0;
67400
+ }
67401
+ return value.slice(0, MAX_RECEIPT_OUTPUT_CHARS);
67402
+ }
67403
+ function parsePolymarketStringArray(value, path2) {
67404
+ let parsed = value;
67405
+ if (typeof parsed === "string") {
67406
+ try {
67407
+ parsed = JSON.parse(parsed);
67408
+ } catch (error) {
67409
+ throw new Error(
67410
+ `${path2} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`
67411
+ );
67412
+ }
67413
+ }
67414
+ if (!Array.isArray(parsed) || parsed.some((item) => typeof item !== "string")) {
67415
+ throw new Error(`${path2} must be an array of strings`);
67416
+ }
67417
+ return parsed;
67418
+ }
67419
+ function asRecord(value) {
67420
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
67421
+ }
67422
+ async function authorizeRotatingPolymarketToken(signal, buyer, runner, eventFetcher) {
67423
+ const tokenId = signal.metadata?.polymarketTokenId ?? signal.instrument.symbol;
67424
+ if (buyer.riskPolicy.allowedTokenIds.includes(tokenId)) {
67425
+ return { buyer };
67426
+ }
67427
+ const marketSlug = signal.metadata?.market;
67428
+ const outcome = signal.metadata?.outcome;
67429
+ if (!marketSlug || !outcome) {
67430
+ throw new Error(`Polymarket token ${tokenId} is not allowlisted`);
67431
+ }
67432
+ const allowedSeries = buyer.riskPolicy.allowedMarketSeries?.find((series) => {
67433
+ return marketSlug.startsWith(series.slugPrefix) && series.outcomes.some((allowed) => allowed.toLowerCase() === outcome.toLowerCase());
67434
+ });
67435
+ if (!allowedSeries) {
67436
+ throw new Error(`Polymarket token ${tokenId} is not allowlisted`);
67437
+ }
67438
+ const bin = buyer.polymarket?.bin ?? process.env.POLYMARKET_BIN ?? "polymarket";
67439
+ const timeoutMs = buyer.polymarket?.timeoutMs ?? DEFAULT_POLYMARKET_TIMEOUT_MS;
67440
+ let eventValue;
67441
+ let cliError;
67442
+ try {
67443
+ const result = await runner(bin, ["-o", "json", "events", "get", marketSlug], { timeoutMs });
67444
+ eventValue = JSON.parse(result.stdout);
67445
+ const record = asRecord(eventValue);
67446
+ if (record?.error) {
67447
+ throw new Error(String(record.error));
67448
+ }
67449
+ } catch (error) {
67450
+ eventValue = void 0;
67451
+ cliError = error instanceof Error ? error.message : String(error);
67452
+ }
67453
+ if (eventValue === void 0) {
67454
+ try {
67455
+ eventValue = await eventFetcher(marketSlug, { timeoutMs });
67456
+ } catch (error) {
67457
+ throw new Error(
67458
+ `failed to verify rotating Polymarket event ${marketSlug}: CLI=${cliError}; Gamma=${error instanceof Error ? error.message : String(error)}`
67459
+ );
67460
+ }
67461
+ }
67462
+ const event = asRecord(eventValue);
67463
+ if (!event || event.error || event.slug !== marketSlug || event.active !== true || event.closed === true) {
67464
+ throw new Error(`Polymarket event ${marketSlug} is not active`);
67465
+ }
67466
+ if (allowedSeries.seriesSlug && event.seriesSlug !== allowedSeries.seriesSlug) {
67467
+ throw new Error(
67468
+ `Polymarket event ${marketSlug} does not belong to series ${allowedSeries.seriesSlug}`
67469
+ );
67470
+ }
67471
+ const markets = Array.isArray(event.markets) ? event.markets : [];
67472
+ let verifiedMinOrderSize;
67473
+ let verifiedTickSize;
67474
+ let verificationFailure;
67475
+ const tokenVerified = markets.some((marketValue) => {
67476
+ const market = asRecord(marketValue);
67477
+ if (market?.active !== true || market.closed === true) {
67478
+ return false;
67479
+ }
67480
+ if ((market.acceptingOrders ?? market.accepting_orders) !== true) {
67481
+ return false;
67482
+ }
67483
+ if (allowedSeries.cryptoMarketConfigId && market.cryptoMarketConfigId !== allowedSeries.cryptoMarketConfigId) {
67484
+ return false;
67485
+ }
67486
+ const outcomes = parsePolymarketStringArray(market.outcomes, "market.outcomes");
67487
+ const tokenIds = parsePolymarketStringArray(
67488
+ market.clobTokenIds ?? market.clob_token_ids,
67489
+ "market.clobTokenIds"
67490
+ );
67491
+ if (outcomes.length !== tokenIds.length) {
67492
+ throw new Error("market outcomes and CLOB token IDs have different lengths");
67493
+ }
67494
+ const outcomeIndex = outcomes.findIndex((candidateOutcome, index2) => {
67495
+ return candidateOutcome.toLowerCase() === outcome.toLowerCase() && tokenIds[index2] === tokenId;
67496
+ });
67497
+ if (outcomeIndex < 0) {
67498
+ return false;
67499
+ }
67500
+ const endValue = market.endDate ?? market.end_date ?? event.endDate ?? event.end_date;
67501
+ const endMs = typeof endValue === "string" ? Date.parse(endValue) : Number.NaN;
67502
+ const closeSafetyMs = buyer.riskPolicy.minEventTimeToCloseMs ?? buyer.riskPolicy.minTimeToExpiryMs ?? 0;
67503
+ if (!Number.isFinite(endMs) || endMs - Date.now() < closeSafetyMs) {
67504
+ verificationFailure = `event closes within minEventTimeToCloseMs=${closeSafetyMs}`;
67505
+ return false;
67506
+ }
67507
+ if (Date.parse(signal.expiresAt) > endMs - closeSafetyMs) {
67508
+ verificationFailure = "signal expiresAt exceeds the independently verified event close margin";
67509
+ return false;
67510
+ }
67511
+ const minOrderSize = market.orderMinSize ?? market.order_min_size;
67512
+ if (typeof minOrderSize === "number" || typeof minOrderSize === "string") {
67513
+ verifiedMinOrderSize = String(minOrderSize);
67514
+ }
67515
+ const tickSize = market.orderPriceMinTickSize ?? market.order_price_min_tick_size;
67516
+ if (typeof tickSize === "number" || typeof tickSize === "string") {
67517
+ verifiedTickSize = String(tickSize);
67518
+ }
67519
+ return true;
67520
+ });
67521
+ if (!tokenVerified) {
67522
+ if (verificationFailure) {
67523
+ throw new Error(`Polymarket event ${marketSlug} is unsafe: ${verificationFailure}`);
67524
+ }
67525
+ throw new Error(
67526
+ `Polymarket token ${tokenId} does not match outcome ${outcome} in active event ${marketSlug}`
67527
+ );
67528
+ }
67529
+ return {
67530
+ buyer: {
67531
+ ...buyer,
67532
+ riskPolicy: {
67533
+ ...buyer.riskPolicy,
67534
+ allowedTokenIds: [...buyer.riskPolicy.allowedTokenIds, tokenId]
67535
+ }
67536
+ },
67537
+ ...verifiedMinOrderSize ? { minOrderSize: verifiedMinOrderSize } : {},
67538
+ ...verifiedTickSize ? { tickSize: verifiedTickSize } : {}
67539
+ };
67540
+ }
67541
+ async function queryPolymarketMarketSnapshot(signal, buyer, runner, knownTickSize) {
67542
+ if (signal.intent.action !== "ENTER" && signal.intent.action !== "EXIT") {
67543
+ throw new Error(`cannot query a price for ${signal.intent.action}`);
67544
+ }
67545
+ const tokenId = signal.metadata?.polymarketTokenId ?? signal.instrument.symbol;
67546
+ const side = signal.intent.side.toLowerCase();
67547
+ const bin = buyer.polymarket?.bin ?? process.env.POLYMARKET_BIN ?? "polymarket";
67548
+ const result = await runner(bin, ["-o", "json", "clob", "price", "--side", side, tokenId], {
67549
+ timeoutMs: buyer.polymarket?.timeoutMs ?? DEFAULT_POLYMARKET_TIMEOUT_MS
67550
+ });
67551
+ let value;
67552
+ try {
67553
+ value = JSON.parse(result.stdout);
67554
+ } catch (error) {
67555
+ throw new Error(
67556
+ `Polymarket price query returned invalid JSON: ${error instanceof Error ? error.message : String(error)}`
67557
+ );
67558
+ }
67559
+ const record = asRecord(value);
67560
+ const price = typeof record?.price === "string" || typeof record?.price === "number" ? String(record.price) : typeof value === "string" || typeof value === "number" ? String(value) : void 0;
67561
+ if (!price) {
67562
+ throw new Error("Polymarket price query did not return a price");
67563
+ }
67564
+ normalizeDecimal(price, "Polymarket reference price");
67565
+ let tickSize = knownTickSize;
67566
+ if (!tickSize) {
67567
+ const tickResult = await runner(bin, ["-o", "json", "clob", "tick-size", tokenId], {
67568
+ timeoutMs: buyer.polymarket?.timeoutMs ?? DEFAULT_POLYMARKET_TIMEOUT_MS
67569
+ });
67570
+ let tickValue;
67571
+ try {
67572
+ tickValue = JSON.parse(tickResult.stdout);
67573
+ } catch (error) {
67574
+ throw new Error(
67575
+ `Polymarket tick-size query returned invalid JSON: ${error instanceof Error ? error.message : String(error)}`
67576
+ );
67577
+ }
67578
+ const tickRecord = asRecord(tickValue);
67579
+ const candidate = tickRecord?.tickSize ?? tickRecord?.tick_size ?? tickRecord?.minimumTickSize ?? tickRecord?.minimum_tick_size;
67580
+ tickSize = typeof candidate === "string" || typeof candidate === "number" ? String(candidate) : typeof tickValue === "string" || typeof tickValue === "number" ? String(tickValue) : void 0;
67581
+ }
67582
+ if (!tickSize) {
67583
+ throw new Error("Polymarket tick-size query did not return a tick size");
67584
+ }
67585
+ normalizeDecimal(tickSize, "Polymarket tick size");
67586
+ return { referencePrice: price, tickSize };
67587
+ }
67588
+ var SignalTradingBuyerRuntime = class {
67589
+ constructor(homeDir, runner = defaultPolymarketCommandRunner, eventFetcher = defaultPolymarketEventFetcher) {
67590
+ this.homeDir = homeDir;
67591
+ this.runner = runner;
67592
+ this.eventFetcher = eventFetcher;
67593
+ }
67594
+ homeDir;
67595
+ runner;
67596
+ eventFetcher;
67597
+ async process(signalValue, context) {
67598
+ const config = loadSignalTradingConfig(this.homeDir);
67599
+ if (!config.buyer) {
67600
+ throw new Error("signal buyer config is missing");
67601
+ }
67602
+ const signal = parseTradingSignalV1(signalValue);
67603
+ const idempotencyKey = `${signal.providerAgentId}:${signal.subscriptionId}:${signal.signalId}`;
67604
+ const path2 = receiptPath(this.homeDir, idempotencyKey);
67605
+ const now = (/* @__PURE__ */ new Date()).toISOString();
67606
+ if (signal.intent.action === "NO_TRADE") {
67607
+ validateSignalPreconditions(signal, config.buyer, context, Date.now());
67608
+ const receipt = {
67609
+ idempotencyKey,
67610
+ signalId: signal.signalId,
67611
+ serviceId: signal.serviceId,
67612
+ subscriptionId: signal.subscriptionId,
67613
+ providerAgentId: signal.providerAgentId,
67614
+ jobId: context.jobId,
67615
+ messageId: context.messageId,
67616
+ status: "SKIPPED",
67617
+ executionMode: config.buyer.executionMode,
67618
+ skipReason: signal.intent.reason,
67619
+ createdAt: now,
67620
+ updatedAt: now
67621
+ };
67622
+ if (!claimReceipt(path2, receipt)) {
67623
+ const existing = readReceipt(path2);
67624
+ if (!existing) {
67625
+ throw new Error(`signal execution receipt exists but cannot be read: ${path2}`);
67626
+ }
67627
+ return { handled: true, duplicate: true, receipt: existing };
67628
+ }
67629
+ logWithTimestamp(
67630
+ `[signal-trading] skipped NO_TRADE signal=${signal.signalId} service=${signal.serviceId} job=${context.jobId} reason=${signal.intent.reason}`
67631
+ );
67632
+ return { handled: true, duplicate: false, receipt };
67633
+ }
67634
+ const existingReceipt = readReceipt(path2);
67635
+ if (existingReceipt) {
67636
+ return { handled: true, duplicate: true, receipt: existingReceipt };
67637
+ }
67638
+ validateSignalPreconditions(signal, config.buyer, context, Date.now());
67639
+ const authorization = await authorizeRotatingPolymarketToken(
67640
+ signal,
67641
+ config.buyer,
67642
+ this.runner,
67643
+ this.eventFetcher
67644
+ );
67645
+ const marketSnapshot = await queryPolymarketMarketSnapshot(
67646
+ signal,
67647
+ authorization.buyer,
67648
+ this.runner,
67649
+ authorization.tickSize
67650
+ );
67651
+ const plan = buildPolymarketExecutionPlan(
67652
+ signal,
67653
+ authorization.buyer,
67654
+ context,
67655
+ {
67656
+ ...marketSnapshot,
67657
+ ...authorization.minOrderSize ? { minOrderSize: authorization.minOrderSize } : {}
67658
+ }
67659
+ );
67660
+ const initialReceipt = {
67661
+ idempotencyKey,
67662
+ signalId: signal.signalId,
67663
+ serviceId: signal.serviceId,
67664
+ subscriptionId: signal.subscriptionId,
67665
+ providerAgentId: signal.providerAgentId,
67666
+ jobId: context.jobId,
67667
+ messageId: context.messageId,
67668
+ status: "PROCESSING",
67669
+ executionMode: config.buyer.executionMode,
67670
+ command: { bin: plan.bin, args: plan.args },
67671
+ createdAt: now,
67672
+ updatedAt: now
67673
+ };
67674
+ if (!claimReceipt(path2, initialReceipt)) {
67675
+ const existing = readReceipt(path2);
67676
+ if (!existing) {
67677
+ throw new Error(`signal execution receipt exists but cannot be read: ${path2}`);
67678
+ }
67679
+ return { handled: true, duplicate: true, receipt: existing };
67680
+ }
67681
+ if (config.buyer.executionMode === "DRY_RUN") {
67682
+ const receipt = {
67683
+ ...initialReceipt,
67684
+ status: "DRY_RUN",
67685
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
67686
+ };
67687
+ updateReceipt(path2, receipt);
67688
+ logWithTimestamp(
67689
+ `[signal-trading] dry-run signal=${signal.signalId} service=${signal.serviceId} job=${context.jobId}`
67690
+ );
67691
+ return { handled: true, duplicate: false, receipt };
67692
+ }
67693
+ try {
67694
+ const result = await this.runner(plan.bin, plan.args, {
67695
+ timeoutMs: config.buyer.polymarket?.timeoutMs ?? DEFAULT_POLYMARKET_TIMEOUT_MS
67696
+ });
67697
+ const receipt = {
67698
+ ...initialReceipt,
67699
+ status: "SUBMITTED",
67700
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
67701
+ ...boundedOutput(result.stdout) ? { stdout: boundedOutput(result.stdout) } : {},
67702
+ ...boundedOutput(result.stderr) ? { stderr: boundedOutput(result.stderr) } : {}
67703
+ };
67704
+ updateReceipt(path2, receipt);
67705
+ logWithTimestamp(
67706
+ `[signal-trading] Polymarket order submitted signal=${signal.signalId} service=${signal.serviceId} job=${context.jobId}`
67707
+ );
67708
+ return { handled: true, duplicate: false, receipt };
67709
+ } catch (error) {
67710
+ const receipt = {
67711
+ ...initialReceipt,
67712
+ status: "UNKNOWN",
67713
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
67714
+ error: error instanceof Error ? error.message : String(error)
67715
+ };
67716
+ updateReceipt(path2, receipt);
67717
+ throw new Error(
67718
+ `Polymarket CLI execution became UNKNOWN for signal=${signal.signalId}; automatic retry is disabled: ${receipt.error}`
67719
+ );
67720
+ }
67721
+ }
67722
+ };
67723
+
66516
67724
  // src/listener.ts
66517
67725
  init_log();
66518
- var import_node_fs19 = require("node:fs");
67726
+ var import_node_fs21 = require("node:fs");
66519
67727
  var import_promises8 = require("node:fs/promises");
66520
67728
  var import_node_os9 = require("node:os");
66521
- var import_node_path25 = require("node:path");
67729
+ var import_node_path27 = require("node:path");
66522
67730
 
66523
67731
  // ../core/src/xmtp-sdk/onchainos/signer.ts
66524
67732
  init_log();
@@ -66656,7 +67864,7 @@ async function enqueueAiSessionMessageDispatch(params) {
66656
67864
  init_paths();
66657
67865
 
66658
67866
  // src/user-attention-watchers.ts
66659
- var import_node_crypto13 = require("node:crypto");
67867
+ var import_node_crypto15 = require("node:crypto");
66660
67868
  init_sentry_logger();
66661
67869
  var USER_ATTENTION_WATCH_REPLACED_MESSAGE = "Another okx-a2a user watch with the same job scope was started, so this watcher has been closed. Do not run this watch command again automatically, because starting another watcher may interrupt a different session that is already monitoring task progress.";
66662
67870
  var USER_ATTENTION_WATCHER_SCAN_MS = 500;
@@ -66699,7 +67907,7 @@ function isOriginalParentProcessAlive(options) {
66699
67907
  }
66700
67908
  function registerUserAttentionWatcher(options) {
66701
67909
  return options.store.registerUserAttentionWatcher({
66702
- id: options.id ?? (0, import_node_crypto13.randomUUID)(),
67910
+ id: options.id ?? (0, import_node_crypto15.randomUUID)(),
66703
67911
  provider: options.provider,
66704
67912
  jobId: options.jobId,
66705
67913
  nowMs: options.nowMs ?? Date.now(),
@@ -67024,12 +68232,12 @@ async function isGatewayAvailableForHeartbeat(options) {
67024
68232
  }
67025
68233
  async function getHermesGatewayPluginStatus(options = {}) {
67026
68234
  const env = options.env ?? process.env;
67027
- const hermesHome = env.HERMES_HOME?.trim() || (0, import_node_path25.join)((0, import_node_os9.homedir)(), ".hermes");
67028
- const pluginYamlPath = (0, import_node_path25.join)(hermesHome, "plugins", "platforms", "okx-a2a", "plugin.yaml");
67029
- if (!(0, import_node_fs19.existsSync)(pluginYamlPath)) {
68235
+ const hermesHome = env.HERMES_HOME?.trim() || (0, import_node_path27.join)((0, import_node_os9.homedir)(), ".hermes");
68236
+ const pluginYamlPath = (0, import_node_path27.join)(hermesHome, "plugins", "platforms", "okx-a2a", "plugin.yaml");
68237
+ if (!(0, import_node_fs21.existsSync)(pluginYamlPath)) {
67030
68238
  return { enabled: false, reason: "plugin_yaml_missing", hermesHome, checkedPath: pluginYamlPath };
67031
68239
  }
67032
- const configPath = (0, import_node_path25.join)(hermesHome, "config.yaml");
68240
+ const configPath = (0, import_node_path27.join)(hermesHome, "config.yaml");
67033
68241
  let content;
67034
68242
  try {
67035
68243
  content = await (0, import_promises8.readFile)(configPath, "utf8");
@@ -67191,6 +68399,7 @@ async function runListenerWithLock(options, paths) {
67191
68399
  logWithTimestamp("[okx-agent-task] user_attention watcher coordinator scanning SQLite watcher state");
67192
68400
  let stopping = false;
67193
68401
  const service = XmtpService.getInstance();
68402
+ const signalBuyerRuntime = new SignalTradingBuyerRuntime(options.homeDir);
67194
68403
  const agentRefreshCoordinator = new AgentRefreshCoordinator({
67195
68404
  lookup: (previousFingerprint) => listAllAgentsWithMetadata(previousFingerprint),
67196
68405
  refresh: () => service.refreshAgents(),
@@ -67221,6 +68430,9 @@ async function runListenerWithLock(options, paths) {
67221
68430
  },
67222
68431
  onSessionMessage: async (event) => {
67223
68432
  await enqueueAiSessionMessageDispatch({ commands, event });
68433
+ },
68434
+ onSignalTradingSignal: async (event) => {
68435
+ await signalBuyerRuntime.process(event.signal, event);
67224
68436
  }
67225
68437
  }),
67226
68438
  processOfflineMessage: (ctx, deps, replayOptions) => processOfflineFromCoreDeps(store, ctx, deps, {
@@ -67231,6 +68443,9 @@ async function runListenerWithLock(options, paths) {
67231
68443
  },
67232
68444
  onSessionMessage: async (event) => {
67233
68445
  await enqueueAiSessionMessageDispatch({ commands, event });
68446
+ },
68447
+ onSignalTradingSignal: async (event) => {
68448
+ await signalBuyerRuntime.process(event.signal, event);
67234
68449
  }
67235
68450
  }),
67236
68451
  notifySessionExpired: (command) => {
@@ -67262,12 +68477,12 @@ async function runListenerWithLock(options, paths) {
67262
68477
  });
67263
68478
  }
67264
68479
  });
67265
- service.setPluginVersion("0.2.9");
68480
+ service.setPluginVersion("0.2.10-beta-98689bff7a-260826152645");
67266
68481
  await service.init();
67267
68482
  const pluginVersionStatus = service.pluginVersionStatus;
67268
68483
  if (pluginVersionStatus.unavailable) {
67269
68484
  throw new Error(
67270
- `@okxweb3/a2a-node v${"0.2.9"} is below the required minimum v${pluginVersionStatus.minVersion}`
68485
+ `@okxweb3/a2a-node v${"0.2.10-beta-98689bff7a-260826152645"} is below the required minimum v${pluginVersionStatus.minVersion}`
67271
68486
  );
67272
68487
  }
67273
68488
  const systemConfig = service.getSystemConfig();
@@ -67295,7 +68510,7 @@ async function runListenerWithLock(options, paths) {
67295
68510
  onchainosAgentId: "*",
67296
68511
  reason: "system-config missing sentryDsn",
67297
68512
  pluginId: "@okxweb3/a2a-node",
67298
- pluginVersion: "0.2.9"
68513
+ pluginVersion: "0.2.10-beta-98689bff7a-260826152645"
67299
68514
  });
67300
68515
  }
67301
68516
  logWithTimestamp(
@@ -67731,11 +68946,11 @@ init_paths();
67731
68946
 
67732
68947
  // src/xmtp-test-cli.ts
67733
68948
  var import_promises10 = require("node:fs/promises");
67734
- var import_node_path26 = require("node:path");
68949
+ var import_node_path28 = require("node:path");
67735
68950
  init_daemon();
67736
68951
 
67737
68952
  // src/log-tail.ts
67738
- var import_node_fs20 = require("node:fs");
68953
+ var import_node_fs22 = require("node:fs");
67739
68954
  var import_promises9 = require("node:fs/promises");
67740
68955
  var import_node_string_decoder = require("node:string_decoder");
67741
68956
  init_win_spawn();
@@ -67859,7 +69074,7 @@ async function followFile(filePath, onData, options = {}) {
67859
69074
  void check();
67860
69075
  }, pollIntervalMs);
67861
69076
  try {
67862
- watcher = (0, import_node_fs20.watch)(filePath, () => {
69077
+ watcher = (0, import_node_fs22.watch)(filePath, () => {
67863
69078
  void check();
67864
69079
  });
67865
69080
  watcher.on("error", (error) => {
@@ -67974,9 +69189,9 @@ async function handleXmtpTestCommand(args, releaseInfo) {
67974
69189
  async function startXmtpTest(args, releaseInfo) {
67975
69190
  assertKnownOptions(args, /* @__PURE__ */ new Set(["--name", "--run-id", "--json"]));
67976
69191
  const paths = resolveTaskPaths();
67977
- const testsDir = (0, import_node_path26.join)(paths.homeDir, "xmtp-tests");
69192
+ const testsDir = (0, import_node_path28.join)(paths.homeDir, "xmtp-tests");
67978
69193
  await ensurePrivateDir(testsDir);
67979
- const active = await readJsonIfExists((0, import_node_path26.join)(testsDir, ACTIVE_FILE));
69194
+ const active = await readJsonIfExists((0, import_node_path28.join)(testsDir, ACTIVE_FILE));
67980
69195
  if (active?.runId) {
67981
69196
  throw new Error(
67982
69197
  `XMTP test ${active.runId} is already active. Run \`okx-a2a xmtp-test stop\` first.`
@@ -68015,7 +69230,7 @@ async function startXmtpTest(args, releaseInfo) {
68015
69230
  ...releaseInfo
68016
69231
  };
68017
69232
  await writeJson(files.manifestPath, manifest);
68018
- await writeJson((0, import_node_path26.join)(testsDir, ACTIVE_FILE), {
69233
+ await writeJson((0, import_node_path28.join)(testsDir, ACTIVE_FILE), {
68019
69234
  runId,
68020
69235
  startedAt: manifest.startedAt
68021
69236
  });
@@ -68038,7 +69253,7 @@ Run \`okx-a2a xmtp-test watch\` to open the realtime dashboard.`);
68038
69253
  async function stopXmtpTest(args) {
68039
69254
  assertKnownOptions(args, /* @__PURE__ */ new Set(["--json"]));
68040
69255
  const testsDir = resolveTestsDir();
68041
- const activePath = (0, import_node_path26.join)(testsDir, ACTIVE_FILE);
69256
+ const activePath = (0, import_node_path28.join)(testsDir, ACTIVE_FILE);
68042
69257
  const active = await readJsonIfExists(activePath);
68043
69258
  if (!active?.runId) {
68044
69259
  throw new Error("No active XMTP test.");
@@ -68332,17 +69547,17 @@ function formatJobEvent(event) {
68332
69547
  return `${timestamp} ${businessEvent.padEnd(34)} ${role}#${agent} ${source}${timings.length > 0 ? ` ${timings.join(" ")}` : ""}`;
68333
69548
  }
68334
69549
  function resolveTestsDir() {
68335
- return (0, import_node_path26.join)(resolveTaskPaths().homeDir, "xmtp-tests");
69550
+ return (0, import_node_path28.join)(resolveTaskPaths().homeDir, "xmtp-tests");
68336
69551
  }
68337
69552
  function resolveRunFiles(testsDir, runId) {
68338
69553
  validateRunId(runId);
68339
- const runDir = (0, import_node_path26.join)(testsDir, runId);
69554
+ const runDir = (0, import_node_path28.join)(testsDir, runId);
68340
69555
  return {
68341
69556
  testsDir,
68342
69557
  runDir,
68343
- manifestPath: (0, import_node_path26.join)(runDir, "manifest.json"),
68344
- eventsPath: (0, import_node_path26.join)(runDir, "events.jsonl"),
68345
- summaryPath: (0, import_node_path26.join)(runDir, "summary.json")
69558
+ manifestPath: (0, import_node_path28.join)(runDir, "manifest.json"),
69559
+ eventsPath: (0, import_node_path28.join)(runDir, "events.jsonl"),
69560
+ summaryPath: (0, import_node_path28.join)(runDir, "summary.json")
68346
69561
  };
68347
69562
  }
68348
69563
  async function resolveRequestedRunId(testsDir, args, preferActive = false) {
@@ -68350,7 +69565,7 @@ async function resolveRequestedRunId(testsDir, args, preferActive = false) {
68350
69565
  if (requested) {
68351
69566
  return validateRunId(requested);
68352
69567
  }
68353
- const active = await readJsonIfExists((0, import_node_path26.join)(testsDir, ACTIVE_FILE));
69568
+ const active = await readJsonIfExists((0, import_node_path28.join)(testsDir, ACTIVE_FILE));
68354
69569
  if (active?.runId && (preferActive || !args.includes("--latest"))) {
68355
69570
  return validateRunId(active.runId);
68356
69571
  }
@@ -68376,7 +69591,7 @@ async function findLatestRunId(testsDir) {
68376
69591
  continue;
68377
69592
  }
68378
69593
  const manifest = await readJsonIfExists(
68379
- (0, import_node_path26.join)(testsDir, entry.name, "manifest.json")
69594
+ (0, import_node_path28.join)(testsDir, entry.name, "manifest.json")
68380
69595
  );
68381
69596
  if (manifest?.runId && manifest.startedAt) {
68382
69597
  manifests.push(manifest);
@@ -68677,23 +69892,23 @@ function handleCapabilitiesCommand(args) {
68677
69892
  }
68678
69893
 
68679
69894
  // src/logs-export.ts
68680
- var import_node_child_process10 = require("node:child_process");
68681
- var import_node_fs27 = require("node:fs");
69895
+ var import_node_child_process11 = require("node:child_process");
69896
+ var import_node_fs29 = require("node:fs");
68682
69897
  var import_promises15 = require("node:fs/promises");
68683
69898
  var import_node_os13 = require("node:os");
68684
- var import_node_path33 = require("node:path");
69899
+ var import_node_path35 = require("node:path");
68685
69900
  var import_jszip = __toESM(require_lib3());
68686
69901
 
68687
69902
  // src/logs-export-archive.ts
68688
- var import_node_crypto14 = require("node:crypto");
68689
- var import_node_fs24 = require("node:fs");
69903
+ var import_node_crypto16 = require("node:crypto");
69904
+ var import_node_fs26 = require("node:fs");
68690
69905
  var import_promises13 = require("node:fs/promises");
68691
- var import_node_path30 = require("node:path");
69906
+ var import_node_path32 = require("node:path");
68692
69907
 
68693
69908
  // src/logs-export-filter.ts
68694
- var import_node_fs23 = require("node:fs");
69909
+ var import_node_fs25 = require("node:fs");
68695
69910
  var import_promises12 = require("node:fs/promises");
68696
- var import_node_path29 = require("node:path");
69911
+ var import_node_path31 = require("node:path");
68697
69912
  var import_node_readline2 = require("node:readline");
68698
69913
  var MAX_SINGLE_RECORD_BYTES = 2 * 1024 * 1024;
68699
69914
  var CONTENT_KEYS = /* @__PURE__ */ new Set([
@@ -68758,7 +69973,7 @@ async function readFilteredLog(path2, options, correlationIds, requireCorrelatio
68758
69973
  let excludedOutsideWindow = 0;
68759
69974
  let excludedNoCorrelation = 0;
68760
69975
  let truncated = false;
68761
- const mode = (0, import_node_path29.basename)(path2) === "llm.log" ? "llm" : recordMode;
69976
+ const mode = (0, import_node_path31.basename)(path2) === "llm.log" ? "llm" : recordMode;
68762
69977
  const filterByTime = options.fromMs !== void 0 && options.toMs !== void 0;
68763
69978
  for await (const record of streamLogRecords(path2, mode)) {
68764
69979
  if (options.jobId && recordExplicitlyNamesForeignJob(record.lines, options.jobId)) {
@@ -68802,7 +70017,7 @@ async function readFilteredLog(path2, options, correlationIds, requireCorrelatio
68802
70017
  };
68803
70018
  }
68804
70019
  async function* streamLogRecords(path2, mode) {
68805
- const input = (0, import_node_fs23.createReadStream)(path2, { encoding: "utf8" });
70020
+ const input = (0, import_node_fs25.createReadStream)(path2, { encoding: "utf8" });
68806
70021
  const lines = (0, import_node_readline2.createInterface)({ input, crlfDelay: Infinity });
68807
70022
  let current = null;
68808
70023
  try {
@@ -69222,7 +70437,7 @@ async function assertRegularFile(path2) {
69222
70437
  const file = await (0, import_promises12.lstat)(path2);
69223
70438
  if (file.isSymbolicLink() || !file.isFile()) {
69224
70439
  throw Object.assign(
69225
- new Error(`Refusing non-regular diagnostic source: ${(0, import_node_path29.basename)(path2)}`),
70440
+ new Error(`Refusing non-regular diagnostic source: ${(0, import_node_path31.basename)(path2)}`),
69226
70441
  { diagnosticUnavailable: true }
69227
70442
  );
69228
70443
  }
@@ -69303,30 +70518,30 @@ function recordCollector(state, result) {
69303
70518
  }
69304
70519
  async function resolveOutputPath(requested, input) {
69305
70520
  if (requested) {
69306
- const output2 = (0, import_node_path30.isAbsolute)(requested) ? requested : (0, import_node_path30.resolve)(input.cwd, requested);
69307
- if ((0, import_node_fs24.existsSync)(output2) && !input.overwrite) {
70521
+ const output2 = (0, import_node_path32.isAbsolute)(requested) ? requested : (0, import_node_path32.resolve)(input.cwd, requested);
70522
+ if ((0, import_node_fs26.existsSync)(output2) && !input.overwrite) {
69308
70523
  throw new Error(`Output already exists: ${output2}. Pass --overwrite to replace it.`);
69309
70524
  }
69310
70525
  return output2;
69311
70526
  }
69312
70527
  const stamp = input.now.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
69313
70528
  const base = `okx-a2a-diagnostics-${stamp}.zip`;
69314
- let output = (0, import_node_path30.join)(input.cwd, base);
69315
- for (let suffix = 2; (0, import_node_fs24.existsSync)(output); suffix += 1) {
69316
- output = (0, import_node_path30.join)(input.cwd, `okx-a2a-diagnostics-${stamp}-${suffix}.zip`);
70529
+ let output = (0, import_node_path32.join)(input.cwd, base);
70530
+ for (let suffix = 2; (0, import_node_fs26.existsSync)(output); suffix += 1) {
70531
+ output = (0, import_node_path32.join)(input.cwd, `okx-a2a-diagnostics-${stamp}-${suffix}.zip`);
69317
70532
  }
69318
70533
  return output;
69319
70534
  }
69320
70535
  async function writeArchiveAtomically(outputPath, archive, overwrite) {
69321
- await (0, import_promises13.mkdir)((0, import_node_path30.dirname)(outputPath), { recursive: true });
69322
- const temporaryPath = (0, import_node_path30.join)(
69323
- (0, import_node_path30.dirname)(outputPath),
69324
- `.${(0, import_node_path30.basename)(outputPath)}.${(0, import_node_crypto14.randomUUID)()}.tmp`
70536
+ await (0, import_promises13.mkdir)((0, import_node_path32.dirname)(outputPath), { recursive: true });
70537
+ const temporaryPath = (0, import_node_path32.join)(
70538
+ (0, import_node_path32.dirname)(outputPath),
70539
+ `.${(0, import_node_path32.basename)(outputPath)}.${(0, import_node_crypto16.randomUUID)()}.tmp`
69325
70540
  );
69326
70541
  try {
69327
70542
  await (0, import_promises13.writeFile)(temporaryPath, archive, { flag: "wx", mode: 384 });
69328
70543
  if (overwrite) {
69329
- if ((0, import_node_fs24.existsSync)(outputPath)) {
70544
+ if ((0, import_node_fs26.existsSync)(outputPath)) {
69330
70545
  await (0, import_promises13.rm)(outputPath, { force: true });
69331
70546
  }
69332
70547
  await (0, import_promises13.rename)(temporaryPath, outputPath);
@@ -69340,14 +70555,14 @@ async function writeArchiveAtomically(outputPath, archive, overwrite) {
69340
70555
  }
69341
70556
  }
69342
70557
  function hashDiagnosticFileContent(content) {
69343
- return (0, import_node_crypto14.createHash)("sha256").update(content).digest("hex");
70558
+ return (0, import_node_crypto16.createHash)("sha256").update(content).digest("hex");
69344
70559
  }
69345
70560
  function isUnavailableError(err) {
69346
70561
  return !!err && typeof err === "object" && "diagnosticUnavailable" in err;
69347
70562
  }
69348
70563
 
69349
70564
  // src/logs-export-database.ts
69350
- var import_node_fs25 = require("node:fs");
70565
+ var import_node_fs27 = require("node:fs");
69351
70566
  var PROVIDERS = ["codex", "claude", "openclaw", "hermes"];
69352
70567
  function readSessionSqliteSnapshot(dbPath, options, selectedJobIds) {
69353
70568
  const hasTimeWindow2 = options.fromMs !== void 0 && options.toMs !== void 0;
@@ -69445,7 +70660,7 @@ function readSessionSqliteSnapshot(dbPath, options, selectedJobIds) {
69445
70660
  };
69446
70661
  }
69447
70662
  function readSqliteRows(dbPath, sql, params = []) {
69448
- if (!(0, import_node_fs25.existsSync)(dbPath)) {
70663
+ if (!(0, import_node_fs27.existsSync)(dbPath)) {
69449
70664
  throw unavailable(`SQLite database not found: ${dbPath}`);
69450
70665
  }
69451
70666
  const { DatabaseSync: DatabaseSync4 } = loadSqlite4();
@@ -69503,15 +70718,15 @@ function unavailable(message) {
69503
70718
  }
69504
70719
 
69505
70720
  // src/logs-export-provider.ts
69506
- var import_node_child_process9 = require("node:child_process");
70721
+ var import_node_child_process10 = require("node:child_process");
69507
70722
  var import_node_os12 = require("node:os");
69508
- var import_node_path31 = require("node:path");
70723
+ var import_node_path33 = require("node:path");
69509
70724
  var PROVIDERS2 = ["codex", "claude", "openclaw", "hermes"];
69510
70725
  function providerConfigCandidates(provider, taskHome2) {
69511
70726
  if (provider === "codex") {
69512
70727
  return [
69513
70728
  {
69514
- path: (0, import_node_path31.join)(process.env.CODEX_HOME ?? (0, import_node_path31.join)((0, import_node_os12.homedir)(), ".codex"), "config.toml"),
70729
+ path: (0, import_node_path33.join)(process.env.CODEX_HOME ?? (0, import_node_path33.join)((0, import_node_os12.homedir)(), ".codex"), "config.toml"),
69515
70730
  archiveName: "config.redacted.toml"
69516
70731
  }
69517
70732
  ];
@@ -69519,11 +70734,11 @@ function providerConfigCandidates(provider, taskHome2) {
69519
70734
  if (provider === "claude") {
69520
70735
  return [
69521
70736
  {
69522
- path: (0, import_node_path31.join)((0, import_node_os12.homedir)(), ".claude", "settings.json"),
70737
+ path: (0, import_node_path33.join)((0, import_node_os12.homedir)(), ".claude", "settings.json"),
69523
70738
  archiveName: "settings.redacted.json"
69524
70739
  },
69525
70740
  {
69526
- path: (0, import_node_path31.join)(process.cwd(), ".claude", "settings.json"),
70741
+ path: (0, import_node_path33.join)(process.cwd(), ".claude", "settings.json"),
69527
70742
  archiveName: "project-settings.redacted.json"
69528
70743
  }
69529
70744
  ];
@@ -69532,28 +70747,28 @@ function providerConfigCandidates(provider, taskHome2) {
69532
70747
  const openClawStateDir = resolveOpenClawStateDir();
69533
70748
  return [
69534
70749
  {
69535
- path: (0, import_node_path31.join)(openClawStateDir, "openclaw.json"),
70750
+ path: (0, import_node_path33.join)(openClawStateDir, "openclaw.json"),
69536
70751
  archiveName: "config.redacted.json"
69537
70752
  },
69538
70753
  {
69539
- path: (0, import_node_path31.join)(taskHome2, "xmtp", "openclaw-gateway.json"),
70754
+ path: (0, import_node_path33.join)(taskHome2, "xmtp", "openclaw-gateway.json"),
69540
70755
  archiveName: "gateway-config.redacted.json"
69541
70756
  }
69542
70757
  ];
69543
70758
  }
69544
70759
  return [
69545
70760
  {
69546
- path: (0, import_node_path31.join)(resolveHermesHome(), "config.yaml"),
70761
+ path: (0, import_node_path33.join)(resolveHermesHome(), "config.yaml"),
69547
70762
  archiveName: "config.redacted.yaml"
69548
70763
  }
69549
70764
  ];
69550
70765
  }
69551
70766
  function resolveOpenClawStateDir() {
69552
70767
  const configured = process.env.OPENCLAW_STATE_DIR?.trim() || process.env.OPENCLAW_HOME?.trim();
69553
- return (0, import_node_path31.resolve)(configured || (0, import_node_path31.join)((0, import_node_os12.homedir)(), ".openclaw"));
70768
+ return (0, import_node_path33.resolve)(configured || (0, import_node_path33.join)((0, import_node_os12.homedir)(), ".openclaw"));
69554
70769
  }
69555
70770
  function resolveHermesHome() {
69556
- return (0, import_node_path31.resolve)(process.env.HERMES_HOME?.trim() || (0, import_node_path31.join)((0, import_node_os12.homedir)(), ".hermes"));
70771
+ return (0, import_node_path33.resolve)(process.env.HERMES_HOME?.trim() || (0, import_node_path33.join)((0, import_node_os12.homedir)(), ".hermes"));
69557
70772
  }
69558
70773
  function providerEnvironment(provider) {
69559
70774
  const prefixes = provider === "codex" ? ["OKX_A2A_AI_CODEX_", "CODEX_"] : provider === "claude" ? ["OKX_A2A_AI_CLAUDE_", "ANTHROPIC_MODEL", "CLAUDE_"] : provider === "openclaw" ? ["OPENCLAW_", "OKX_A2A_OPENCLAW_"] : ["HERMES_", "OKX_A2A_HERMES_"];
@@ -69570,7 +70785,7 @@ function safeCommandLabel(command) {
69570
70785
  return "";
69571
70786
  }
69572
70787
  const executable = trimmed.match(/^"([^"]+)"/)?.[1] ?? trimmed.split(/\s+/, 1)[0];
69573
- return (0, import_node_path31.basename)(executable);
70788
+ return (0, import_node_path33.basename)(executable);
69574
70789
  }
69575
70790
  function resolveProvider(requested, binding, fallback = null) {
69576
70791
  if (requested !== "auto") {
@@ -69583,7 +70798,7 @@ function resolveProviderCommand(provider, storedCommand) {
69583
70798
  return override || storedCommand || provider;
69584
70799
  }
69585
70800
  function probeVersion(command) {
69586
- const result = (0, import_node_child_process9.spawnSync)(command, ["--version"], {
70801
+ const result = (0, import_node_child_process10.spawnSync)(command, ["--version"], {
69587
70802
  encoding: "utf8",
69588
70803
  timeout: 1e4,
69589
70804
  shell: process.platform === "win32"
@@ -69600,10 +70815,10 @@ function isProvider2(value) {
69600
70815
  }
69601
70816
 
69602
70817
  // src/logs-export-utils.ts
69603
- var import_node_crypto15 = require("node:crypto");
69604
- var import_node_fs26 = require("node:fs");
70818
+ var import_node_crypto17 = require("node:crypto");
70819
+ var import_node_fs28 = require("node:fs");
69605
70820
  var import_promises14 = require("node:fs/promises");
69606
- var import_node_path32 = require("node:path");
70821
+ var import_node_path34 = require("node:path");
69607
70822
  var MAX_JSON_FILE_BYTES = 20 * 1024 * 1024;
69608
70823
  var STRONG_CORRELATION_KEYS = /* @__PURE__ */ new Set([
69609
70824
  "approvalid",
@@ -69737,14 +70952,14 @@ async function readJsonObject(path2) {
69737
70952
  async function assertRegularFile2(path2) {
69738
70953
  const file = await (0, import_promises14.lstat)(path2);
69739
70954
  if (file.isSymbolicLink() || !file.isFile()) {
69740
- throw unavailable2(`Refusing non-regular diagnostic source: ${(0, import_node_path32.basename)(path2)}`);
70955
+ throw unavailable2(`Refusing non-regular diagnostic source: ${(0, import_node_path34.basename)(path2)}`);
69741
70956
  }
69742
70957
  return file;
69743
70958
  }
69744
70959
  async function inspectRegularFile(path2) {
69745
70960
  const file = await assertRegularFile2(path2);
69746
- const hash2 = (0, import_node_crypto15.createHash)("sha256");
69747
- for await (const chunk of (0, import_node_fs26.createReadStream)(path2)) {
70961
+ const hash2 = (0, import_node_crypto17.createHash)("sha256");
70962
+ for await (const chunk of (0, import_node_fs28.createReadStream)(path2)) {
69748
70963
  hash2.update(chunk);
69749
70964
  }
69750
70965
  return {
@@ -69895,7 +71110,7 @@ function parseLogsExportArgs(args, input = {}) {
69895
71110
  async function exportDiagnosticLogs(options) {
69896
71111
  validateOptions(options);
69897
71112
  const paths = diagnosticPaths(options.taskHome);
69898
- const cwd = (0, import_node_path33.resolve)(options.cwd ?? process.cwd());
71113
+ const cwd = (0, import_node_path35.resolve)(options.cwd ?? process.cwd());
69899
71114
  const now = options.now ?? /* @__PURE__ */ new Date();
69900
71115
  const outputPath = await resolveOutputPath(options.outputPath, {
69901
71116
  cwd,
@@ -69989,14 +71204,14 @@ async function exportDiagnosticLogs(options) {
69989
71204
  scope,
69990
71205
  jobId: options.jobId,
69991
71206
  taskHome: {
69992
- basename: (0, import_node_path33.basename)(paths.taskHome),
71207
+ basename: (0, import_node_path35.basename)(paths.taskHome),
69993
71208
  explicitlyConfigured: !!options.taskHome,
69994
71209
  absolutePathCollected: false
69995
71210
  },
69996
71211
  node: process.version,
69997
71212
  platform: process.platform,
69998
71213
  arch: process.arch,
69999
- packageVersion: true ? "0.2.9" : "unknown",
71214
+ packageVersion: true ? "0.2.10-beta-98689bff7a-260826152645" : "unknown",
70000
71215
  sensitiveContentIncluded: options.includeSensitiveContent,
70001
71216
  listenerAndLlmContentIncluded: true,
70002
71217
  credentialsAlwaysRedacted: true,
@@ -70079,7 +71294,7 @@ async function collectJobMetadata(state, paths, options) {
70079
71294
  correlationIds.strong.add(options.jobId);
70080
71295
  }
70081
71296
  for (const name of names.filter((item) => item.endsWith(".json")).sort()) {
70082
- const path2 = (0, import_node_path33.join)(paths.jobsDir, name);
71297
+ const path2 = (0, import_node_path35.join)(paths.jobsDir, name);
70083
71298
  let parsed;
70084
71299
  try {
70085
71300
  parsed = await readJsonObject(path2);
@@ -70150,7 +71365,7 @@ async function collectJobMetadata(state, paths, options) {
70150
71365
  }
70151
71366
  async function collectSessionSnapshot(state, paths, options, selectedJobIds) {
70152
71367
  return runCollector(state, "a2a-session-store", async () => {
70153
- const dbPath = (0, import_node_path33.join)(paths.sqliteDir, "session-store.sqlite");
71368
+ const dbPath = (0, import_node_path35.join)(paths.sqliteDir, "session-store.sqlite");
70154
71369
  const snapshot = readSessionSqliteSnapshot(dbPath, options, selectedJobIds);
70155
71370
  addJsonEntry(state, "a2a/sessions.json", {
70156
71371
  sessions: snapshot.sessions,
@@ -70182,7 +71397,7 @@ async function collectA2aLogs(state, paths, options, sessionKeys, correlationIds
70182
71397
  const filterNotes = [];
70183
71398
  for (const [sourcePath, archivePath] of [
70184
71399
  [paths.listenerLogPath, "a2a/listener.log"],
70185
- [(0, import_node_path33.join)(paths.logsDir, "llm.log"), "a2a/llm.log"]
71400
+ [(0, import_node_path35.join)(paths.logsDir, "llm.log"), "a2a/llm.log"]
70186
71401
  ]) {
70187
71402
  const output = await readFilteredLog(
70188
71403
  sourcePath,
@@ -70195,7 +71410,7 @@ async function collectA2aLogs(state, paths, options, sessionKeys, correlationIds
70195
71410
  if (!output?.text) {
70196
71411
  if (output?.excludedNoTimestamp) {
70197
71412
  filterNotes.push(
70198
- `${(0, import_node_path33.basename)(sourcePath)} excluded ${output.excludedNoTimestamp} timestamp-less records`
71413
+ `${(0, import_node_path35.basename)(sourcePath)} excluded ${output.excludedNoTimestamp} timestamp-less records`
70199
71414
  );
70200
71415
  }
70201
71416
  continue;
@@ -70204,11 +71419,11 @@ async function collectA2aLogs(state, paths, options, sessionKeys, correlationIds
70204
71419
  collected.push(archivePath);
70205
71420
  if (output.excludedNoTimestamp) {
70206
71421
  filterNotes.push(
70207
- `${(0, import_node_path33.basename)(sourcePath)} excluded ${output.excludedNoTimestamp} timestamp-less records`
71422
+ `${(0, import_node_path35.basename)(sourcePath)} excluded ${output.excludedNoTimestamp} timestamp-less records`
70208
71423
  );
70209
71424
  }
70210
71425
  if (output.truncated) {
70211
- filterNotes.push(`${(0, import_node_path33.basename)(sourcePath)} reached the configured size limit`);
71426
+ filterNotes.push(`${(0, import_node_path35.basename)(sourcePath)} reached the configured size limit`);
70212
71427
  }
70213
71428
  }
70214
71429
  for (const name of await safeReadDir(paths.logsDir)) {
@@ -70223,7 +71438,7 @@ async function collectA2aLogs(state, paths, options, sessionKeys, correlationIds
70223
71438
  if (!matchesDirectJob && !matchesPersistedSession && !matchesJobSessionFilename) {
70224
71439
  continue;
70225
71440
  }
70226
- const sourcePath = (0, import_node_path33.join)(paths.logsDir, name);
71441
+ const sourcePath = (0, import_node_path35.join)(paths.logsDir, name);
70227
71442
  let info;
70228
71443
  let filtered;
70229
71444
  try {
@@ -70296,7 +71511,7 @@ async function collectA2aLogs(state, paths, options, sessionKeys, correlationIds
70296
71511
  }
70297
71512
  async function collectCommands(state, paths, options) {
70298
71513
  return runCollector(state, "a2a-command-store", async () => {
70299
- const dbPath = (0, import_node_path33.join)(paths.sqliteDir, "command-store.sqlite");
71514
+ const dbPath = (0, import_node_path35.join)(paths.sqliteDir, "command-store.sqlite");
70300
71515
  const hasWindow = hasTimeWindow(options);
70301
71516
  const rows = readSqliteRows(dbPath, `
70302
71517
  SELECT id, type, status, command_json, result_json,
@@ -70337,8 +71552,8 @@ async function collectCommands(state, paths, options) {
70337
71552
  }
70338
71553
  async function collectOnchainAudit(state, options, correlationIds) {
70339
71554
  await runCollector(state, "onchainos-audit", async () => {
70340
- const onchainHome = process.env.ONCHAINOS_HOME?.trim() ? (0, import_node_path33.resolve)(process.env.ONCHAINOS_HOME) : (0, import_node_path33.join)((0, import_node_os13.homedir)(), ".onchainos");
70341
- const auditPath = (0, import_node_path33.join)(onchainHome, "audit.jsonl");
71555
+ const onchainHome = process.env.ONCHAINOS_HOME?.trim() ? (0, import_node_path35.resolve)(process.env.ONCHAINOS_HOME) : (0, import_node_path35.join)((0, import_node_os13.homedir)(), ".onchainos");
71556
+ const auditPath = (0, import_node_path35.join)(onchainHome, "audit.jsonl");
70342
71557
  const output = await readFilteredLog(
70343
71558
  auditPath,
70344
71559
  options,
@@ -70413,7 +71628,7 @@ async function collectProviderDiagnostics(state, provider, storedCommand, option
70413
71628
  const configCandidates = providerConfigCandidates(provider, paths.taskHome);
70414
71629
  const configNotes = [];
70415
71630
  for (const candidate of configCandidates) {
70416
- if (!(0, import_node_fs27.existsSync)(candidate.path)) {
71631
+ if (!(0, import_node_fs29.existsSync)(candidate.path)) {
70417
71632
  continue;
70418
71633
  }
70419
71634
  let info;
@@ -70453,7 +71668,7 @@ async function collectOpenClawSessionStore(state, options) {
70453
71668
  const jobId = options.jobId;
70454
71669
  const filterLabel = jobId ? "exact-job" : "time-window";
70455
71670
  await runCollector(state, "openclaw-session-store", async () => {
70456
- const agentsDir = (0, import_node_path33.join)(resolveOpenClawStateDir(), "agents");
71671
+ const agentsDir = (0, import_node_path35.join)(resolveOpenClawStateDir(), "agents");
70457
71672
  const allAgentNames = (await safeReadDir(agentsDir)).sort();
70458
71673
  if (allAgentNames.length === 0) {
70459
71674
  throw unavailable2("No OpenClaw agent session stores were found");
@@ -70462,7 +71677,7 @@ async function collectOpenClawSessionStore(state, options) {
70462
71677
  let skippedSources = 0;
70463
71678
  let discoveryLimited = allAgentNames.length > MAX_OPENCLAW_AGENTS;
70464
71679
  for (const agentId of allAgentNames.slice(0, MAX_OPENCLAW_AGENTS)) {
70465
- const sessionsDir = (0, import_node_path33.join)(agentsDir, agentId, "sessions");
71680
+ const sessionsDir = (0, import_node_path35.join)(agentsDir, agentId, "sessions");
70466
71681
  try {
70467
71682
  const info = await (0, import_promises15.lstat)(sessionsDir);
70468
71683
  if (info.isSymbolicLink() || !info.isDirectory()) {
@@ -70478,7 +71693,7 @@ async function collectOpenClawSessionStore(state, options) {
70478
71693
  try {
70479
71694
  for (const name of await safeReadDir(sessionsDir)) {
70480
71695
  if (isOpenClawSessionLogName(name)) {
70481
- candidates.push({ agentId, path: (0, import_node_path33.join)(sessionsDir, name) });
71696
+ candidates.push({ agentId, path: (0, import_node_path35.join)(sessionsDir, name) });
70482
71697
  }
70483
71698
  }
70484
71699
  } catch {
@@ -70516,7 +71731,7 @@ async function collectOpenClawSessionStore(state, options) {
70516
71731
  if (!output?.text || output.matchedRecords === 0) {
70517
71732
  continue;
70518
71733
  }
70519
- const archivePath = `providers/openclaw/sessions/${safeArchiveName(candidate.agentId)}/${safeArchiveName((0, import_node_path33.basename)(candidate.path))}`;
71734
+ const archivePath = `providers/openclaw/sessions/${safeArchiveName(candidate.agentId)}/${safeArchiveName((0, import_node_path35.basename)(candidate.path))}`;
70520
71735
  addTextEntry(state, archivePath, output.text);
70521
71736
  files.push(archivePath);
70522
71737
  matchedRecords += output.matchedRecords;
@@ -70565,11 +71780,11 @@ async function collectGatewayLogs(state, provider, paths, options, correlationId
70565
71780
  let candidates;
70566
71781
  if (provider === "openclaw") {
70567
71782
  candidates = [
70568
- (0, import_node_path33.join)(paths.logsDir, "gateway-openclaw.jsonl"),
70569
- (0, import_node_path33.join)(resolveOpenClawStateDir(), "logs", "gateway.log")
71783
+ (0, import_node_path35.join)(paths.logsDir, "gateway-openclaw.jsonl"),
71784
+ (0, import_node_path35.join)(resolveOpenClawStateDir(), "logs", "gateway.log")
70570
71785
  ];
70571
71786
  } else {
70572
- const hermesLogsDir = (0, import_node_path33.join)(resolveHermesHome(), "logs");
71787
+ const hermesLogsDir = (0, import_node_path35.join)(resolveHermesHome(), "logs");
70573
71788
  let rotatedNames = [];
70574
71789
  try {
70575
71790
  rotatedNames = (await safeReadDir(hermesLogsDir)).filter(isHermesRotatedLogName).sort();
@@ -70583,12 +71798,12 @@ async function collectGatewayLogs(state, provider, paths, options, correlationId
70583
71798
  rotatedNames.length = MAX_HERMES_ROTATED_LOG_FILES;
70584
71799
  }
70585
71800
  candidates = [
70586
- (0, import_node_path33.join)(paths.logsDir, "gateway-hermes.jsonl"),
70587
- (0, import_node_path33.join)(hermesLogsDir, "agent.log"),
70588
- (0, import_node_path33.join)(hermesLogsDir, "gateway.log"),
70589
- (0, import_node_path33.join)(hermesLogsDir, "error.log"),
70590
- (0, import_node_path33.join)(hermesLogsDir, "errors.log"),
70591
- ...rotatedNames.map((name) => (0, import_node_path33.join)(hermesLogsDir, name)),
71801
+ (0, import_node_path35.join)(paths.logsDir, "gateway-hermes.jsonl"),
71802
+ (0, import_node_path35.join)(hermesLogsDir, "agent.log"),
71803
+ (0, import_node_path35.join)(hermesLogsDir, "gateway.log"),
71804
+ (0, import_node_path35.join)(hermesLogsDir, "error.log"),
71805
+ (0, import_node_path35.join)(hermesLogsDir, "errors.log"),
71806
+ ...rotatedNames.map((name) => (0, import_node_path35.join)(hermesLogsDir, name)),
70592
71807
  "/tmp/hermes-gateway.log"
70593
71808
  ];
70594
71809
  }
@@ -70610,7 +71825,7 @@ async function collectGatewayLogs(state, provider, paths, options, correlationId
70610
71825
  if (!output?.text) {
70611
71826
  continue;
70612
71827
  }
70613
- const archivePath = `providers/${provider}/gateway/${safeArchiveName((0, import_node_path33.basename)(candidate))}`;
71828
+ const archivePath = `providers/${provider}/gateway/${safeArchiveName((0, import_node_path35.basename)(candidate))}`;
70614
71829
  addTextEntry(state, archivePath, output.text);
70615
71830
  files.push(archivePath);
70616
71831
  }
@@ -70641,10 +71856,10 @@ async function collectGatewayLogs(state, provider, paths, options, correlationId
70641
71856
  async function collectDoctorSnapshot(state, options) {
70642
71857
  await runCollector(state, "doctor", async () => {
70643
71858
  const cliPath = process.argv[1];
70644
- if (!cliPath || !(0, import_node_fs27.existsSync)(cliPath)) {
71859
+ if (!cliPath || !(0, import_node_fs29.existsSync)(cliPath)) {
70645
71860
  throw unavailable2("Unable to resolve the running okx-a2a CLI path");
70646
71861
  }
70647
- const result = (0, import_node_child_process10.spawnSync)(process.execPath, [
71862
+ const result = (0, import_node_child_process11.spawnSync)(process.execPath, [
70648
71863
  cliPath,
70649
71864
  "doctor",
70650
71865
  "--json",
@@ -70783,13 +71998,13 @@ function formatEvidence(value, unavailableReason) {
70783
71998
  return unavailableReason ? `unknown (${unavailableReason})` : "unknown";
70784
71999
  }
70785
72000
  function diagnosticPaths(taskHome2) {
70786
- const home = (0, import_node_path33.resolve)(taskHome2 ?? resolveTaskHome());
72001
+ const home = (0, import_node_path35.resolve)(taskHome2 ?? resolveTaskHome());
70787
72002
  return {
70788
72003
  taskHome: home,
70789
- jobsDir: (0, import_node_path33.join)(home, "jobs"),
70790
- logsDir: (0, import_node_path33.join)(home, "logs"),
70791
- sqliteDir: (0, import_node_path33.join)(home, "sqlite"),
70792
- listenerLogPath: (0, import_node_path33.join)(home, "logs", "listener.log")
72004
+ jobsDir: (0, import_node_path35.join)(home, "jobs"),
72005
+ logsDir: (0, import_node_path35.join)(home, "logs"),
72006
+ sqliteDir: (0, import_node_path35.join)(home, "sqlite"),
72007
+ listenerLogPath: (0, import_node_path35.join)(home, "logs", "listener.log")
70793
72008
  };
70794
72009
  }
70795
72010
  function validateOptions(options) {
@@ -70860,7 +72075,7 @@ init_ai_provider();
70860
72075
  init_update_cli();
70861
72076
 
70862
72077
  // src/doctor-cli.ts
70863
- var import_node_path34 = require("node:path");
72078
+ var import_node_path36 = require("node:path");
70864
72079
  init_log();
70865
72080
  init_win_compat();
70866
72081
  init_ai_command();
@@ -71249,7 +72464,7 @@ var windowsNativeLauncherChecker = {
71249
72464
  command: "okx-a2a doctor --fix"
71250
72465
  },
71251
72466
  data: {
71252
- appDataNpm: ctx.env.APPDATA ? (0, import_node_path34.join)(ctx.env.APPDATA, "npm") : null
72467
+ appDataNpm: ctx.env.APPDATA ? (0, import_node_path36.join)(ctx.env.APPDATA, "npm") : null
71253
72468
  }
71254
72469
  };
71255
72470
  },
@@ -71878,7 +73093,7 @@ async function runDoctor(options = {}) {
71878
73093
  platform: options.platform ?? process.platform,
71879
73094
  env: options.env ?? process.env,
71880
73095
  target: options.target ?? resolveDoctorTarget(options.env ?? process.env),
71881
- cliVersion: options.cliVersion ?? (true ? "0.2.9" : "0.0.0"),
73096
+ cliVersion: options.cliVersion ?? (true ? "0.2.10-beta-98689bff7a-260826152645" : "0.0.0"),
71882
73097
  fixMode: options.fix === true,
71883
73098
  nonInteractive: options.nonInteractive === true,
71884
73099
  packageChanged: false,
@@ -72132,9 +73347,12 @@ init_autostart_windows();
72132
73347
  NATIVE_LAUNCHER_EXE_NAME,
72133
73348
  OPENCLAW_GATEWAY_ROUTE_GROUP_ID,
72134
73349
  ProviderNotReadyError,
73350
+ SIGNAL_PAYLOAD_TYPE,
73351
+ SIGNAL_SPEC_VERSION,
72135
73352
  SYSTEM_NOTIFICATION_SESSION_KEY,
72136
73353
  SessionBusyTracker,
72137
73354
  SessionStore,
73355
+ SignalTradingBuyerRuntime,
72138
73356
  SqliteOutboundBehavior,
72139
73357
  TASK_NAME,
72140
73358
  TaskMessageStore,
@@ -72175,6 +73393,7 @@ init_autostart_windows();
72175
73393
  buildLaunchdPlist,
72176
73394
  buildLauncherEntryJs,
72177
73395
  buildMessageEligibleArgs,
73396
+ buildPolymarketExecutionPlan,
72178
73397
  buildSchtasksCreateArgs,
72179
73398
  buildSchtasksDeleteArgs,
72180
73399
  buildSchtasksEndArgs,
@@ -72183,6 +73402,7 @@ init_autostart_windows();
72183
73402
  buildSeaConfig,
72184
73403
  buildServicePath,
72185
73404
  buildSessionKey,
73405
+ buildSignalEnvelopePayload,
72186
73406
  buildSystemMessageNotice,
72187
73407
  buildSystemStoredMessage,
72188
73408
  buildSystemdUserService,
@@ -72206,6 +73426,7 @@ init_autostart_windows();
72206
73426
  collectCodexAppBundledCandidates,
72207
73427
  collectCodexCommandCandidates,
72208
73428
  commandExists,
73429
+ comparePositiveDecimals,
72209
73430
  createAiToolFailureTracker,
72210
73431
  createFileMessageHandler,
72211
73432
  createOutboundBehavior,
@@ -72226,6 +73447,7 @@ init_autostart_windows();
72226
73447
  exportDiagnosticLogs,
72227
73448
  extractAiSessionId,
72228
73449
  extractDirectToUserNotification,
73450
+ extractSignalEnvelopePayload,
72229
73451
  extractXmtpSentAtMs,
72230
73452
  findWindowsNativeOkxA2aExe,
72231
73453
  followFile,
@@ -72237,10 +73459,12 @@ init_autostart_windows();
72237
73459
  getSessionBusyTracker,
72238
73460
  handleCapabilitiesCommand,
72239
73461
  handleDoctorCommand,
73462
+ handleSignalPublishCommand,
72240
73463
  handleXmtpDebugCommand,
72241
73464
  handleXmtpSendCommand,
72242
73465
  handleXmtpTestCommand,
72243
73466
  hasAiRuntimeMarker,
73467
+ hasSignalEnvelopePayload,
72244
73468
  hashDiagnosticFileContent,
72245
73469
  heartbeatUserAttentionWatcher,
72246
73470
  hermesConfigEnablesOkxA2a,
@@ -72266,6 +73490,7 @@ init_autostart_windows();
72266
73490
  killProcessTree,
72267
73491
  launchdPlistHasCurrentRestartPolicy,
72268
73492
  listAllAgentsWithMetadata,
73493
+ loadSignalTradingConfig,
72269
73494
  logWinCompat,
72270
73495
  logXmtpMessageSent,
72271
73496
  maybeRecommendOnchainosUpgrade,
@@ -72282,6 +73507,8 @@ init_autostart_windows();
72282
73507
  parseLogsExportArgs,
72283
73508
  parseOnchainosVersionOutput,
72284
73509
  parsePluginYamlVersion,
73510
+ parseSignalTradingConfig,
73511
+ parseTradingSignalV1,
72285
73512
  parseWalletLoginStatus,
72286
73513
  parseWindowsParentProcessJson,
72287
73514
  performRuntimeSwitch,
@@ -72331,6 +73558,8 @@ init_autostart_windows();
72331
73558
  resolveOpenClawGatewayRoute,
72332
73559
  resolveOpenClawGatewayRoutes,
72333
73560
  resolveProviderCommandWithSelfHeal,
73561
+ resolveSignalTradingConfigPath,
73562
+ resolveSignalTradingDir,
72334
73563
  resolveSystemNotificationTargets,
72335
73564
  resolveSystemdAutostartPaths,
72336
73565
  resolveTaskConfigPath,