@okxweb3/a2a-node 0.0.2-beta-38940d220c-260609204302 → 0.0.4

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 +5 -4
  2. package/dist/cli.js +1194 -488
  3. package/dist/index.js +50753 -50267
  4. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -972,6 +972,16 @@ var init_session_store = __esm({
972
972
  }
973
973
  return null;
974
974
  }
975
+ setAiBypassEnabled(enabled) {
976
+ this.setSetting("isBypass", enabled ? "1" : "0");
977
+ }
978
+ getAiBypassEnabled() {
979
+ const value = this.getSetting("isBypass");
980
+ if (value === null) {
981
+ return true;
982
+ }
983
+ return value !== "0";
984
+ }
975
985
  getUserAttentionByIdempotencyKey(idempotencyKey) {
976
986
  const row = this.db.prepare("SELECT * FROM user_attention WHERE idempotency_key = ? AND deleted_at IS NULL").get(idempotencyKey);
977
987
  return row ? mapAttentionRow(row) : null;
@@ -1203,15 +1213,15 @@ async function ensureAiWorkspace(paths) {
1203
1213
  return aiWorkingDir;
1204
1214
  }
1205
1215
  async function waitForImmediateExit(child, timeoutMs) {
1206
- return await new Promise((resolve5) => {
1216
+ return await new Promise((resolve6) => {
1207
1217
  let timer;
1208
1218
  const onExit = () => {
1209
1219
  clearTimeout(timer);
1210
- resolve5(true);
1220
+ resolve6(true);
1211
1221
  };
1212
1222
  timer = setTimeout(() => {
1213
1223
  child.off("exit", onExit);
1214
- resolve5(false);
1224
+ resolve6(false);
1215
1225
  }, timeoutMs);
1216
1226
  child.once("exit", onExit);
1217
1227
  });
@@ -1330,7 +1340,7 @@ async function waitForExit(pid, timeoutMs) {
1330
1340
  if (!isProcessAlive(pid)) {
1331
1341
  return true;
1332
1342
  }
1333
- await new Promise((resolve5) => setTimeout(resolve5, 100));
1343
+ await new Promise((resolve6) => setTimeout(resolve6, 100));
1334
1344
  }
1335
1345
  return !isProcessAlive(pid);
1336
1346
  }
@@ -1601,7 +1611,7 @@ var init_command_store = __esm({
1601
1611
  if (result) {
1602
1612
  return result;
1603
1613
  }
1604
- await new Promise((resolve5) => setTimeout(resolve5, 500));
1614
+ await new Promise((resolve6) => setTimeout(resolve6, 500));
1605
1615
  }
1606
1616
  return null;
1607
1617
  }
@@ -2433,7 +2443,7 @@ async function promptForAiProviderWithArrows(options) {
2433
2443
  options.stdin.resume();
2434
2444
  options.stdout.write("\x1B[?25l");
2435
2445
  render();
2436
- return await new Promise((resolve5, reject) => {
2446
+ return await new Promise((resolve6, reject) => {
2437
2447
  const cleanup = () => {
2438
2448
  options.stdin.off("keypress", onKeypress);
2439
2449
  options.stdin.setRawMode(false);
@@ -2452,7 +2462,7 @@ async function promptForAiProviderWithArrows(options) {
2452
2462
  clearRendered();
2453
2463
  options.stdout.write(`Selected AI provider: ${provider}
2454
2464
  `);
2455
- resolve5(provider);
2465
+ resolve6(provider);
2456
2466
  };
2457
2467
  const onKeypress = (_str, key) => {
2458
2468
  if (key.ctrl && key.name === "c") {
@@ -4439,7 +4449,7 @@ var require_path = __commonJS({
4439
4449
  const parts = splitPathRe.exec(truncated);
4440
4450
  return parts ? parts.slice(1) : [];
4441
4451
  }
4442
- function resolve5(...args) {
4452
+ function resolve6(...args) {
4443
4453
  let resolvedPath = "";
4444
4454
  let resolvedAbsolute = false;
4445
4455
  for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
@@ -4475,8 +4485,8 @@ var require_path = __commonJS({
4475
4485
  return arr.slice(start, end - start + 1);
4476
4486
  }
4477
4487
  function relative(from3, to) {
4478
- from3 = resolve5(from3).slice(1);
4479
- to = resolve5(to).slice(1);
4488
+ from3 = resolve6(from3).slice(1);
4489
+ to = resolve6(to).slice(1);
4480
4490
  const fromParts = trim2(from3.split("/"));
4481
4491
  const toParts = trim2(to.split("/"));
4482
4492
  const length2 = Math.min(fromParts.length, toParts.length);
@@ -4527,20 +4537,20 @@ var require_path = __commonJS({
4527
4537
  }
4528
4538
  return root + dir;
4529
4539
  }
4530
- function basename3(path, ext) {
4540
+ function basename4(path, ext) {
4531
4541
  let f = splitPath(path)[2];
4532
4542
  if (ext && f.slice(ext.length * -1) === ext) {
4533
4543
  f = f.slice(0, f.length - ext.length);
4534
4544
  }
4535
4545
  return f;
4536
4546
  }
4537
- exports2.basename = basename3;
4547
+ exports2.basename = basename4;
4538
4548
  exports2.dirname = dirname5;
4539
4549
  exports2.isAbsolute = isAbsolute2;
4540
4550
  exports2.join = join17;
4541
4551
  exports2.normalizePath = normalizePath;
4542
4552
  exports2.relative = relative;
4543
- exports2.resolve = resolve5;
4553
+ exports2.resolve = resolve6;
4544
4554
  }
4545
4555
  });
4546
4556
 
@@ -4559,8 +4569,8 @@ var require_syncpromise = __commonJS({
4559
4569
  States2[States2["REJECTED"] = REJECTED] = "REJECTED";
4560
4570
  })(States || (States = {}));
4561
4571
  function resolvedSyncPromise(value) {
4562
- return new SyncPromise((resolve5) => {
4563
- resolve5(value);
4572
+ return new SyncPromise((resolve6) => {
4573
+ resolve6(value);
4564
4574
  });
4565
4575
  }
4566
4576
  function rejectedSyncPromise(reason) {
@@ -4584,15 +4594,15 @@ var require_syncpromise = __commonJS({
4584
4594
  }
4585
4595
  /** JSDoc */
4586
4596
  then(onfulfilled, onrejected) {
4587
- return new _SyncPromise((resolve5, reject) => {
4597
+ return new _SyncPromise((resolve6, reject) => {
4588
4598
  this._handlers.push([
4589
4599
  false,
4590
4600
  (result) => {
4591
4601
  if (!onfulfilled) {
4592
- resolve5(result);
4602
+ resolve6(result);
4593
4603
  } else {
4594
4604
  try {
4595
- resolve5(onfulfilled(result));
4605
+ resolve6(onfulfilled(result));
4596
4606
  } catch (e) {
4597
4607
  reject(e);
4598
4608
  }
@@ -4603,7 +4613,7 @@ var require_syncpromise = __commonJS({
4603
4613
  reject(reason);
4604
4614
  } else {
4605
4615
  try {
4606
- resolve5(onrejected(reason));
4616
+ resolve6(onrejected(reason));
4607
4617
  } catch (e) {
4608
4618
  reject(e);
4609
4619
  }
@@ -4619,7 +4629,7 @@ var require_syncpromise = __commonJS({
4619
4629
  }
4620
4630
  /** JSDoc */
4621
4631
  finally(onfinally) {
4622
- return new _SyncPromise((resolve5, reject) => {
4632
+ return new _SyncPromise((resolve6, reject) => {
4623
4633
  let val;
4624
4634
  let isRejected;
4625
4635
  return this.then(
@@ -4642,7 +4652,7 @@ var require_syncpromise = __commonJS({
4642
4652
  reject(val);
4643
4653
  return;
4644
4654
  }
4645
- resolve5(val);
4655
+ resolve6(val);
4646
4656
  });
4647
4657
  });
4648
4658
  }
@@ -4732,21 +4742,21 @@ var require_promisebuffer = __commonJS({
4732
4742
  return task;
4733
4743
  }
4734
4744
  function drain(timeout) {
4735
- return new syncpromise.SyncPromise((resolve5, reject) => {
4745
+ return new syncpromise.SyncPromise((resolve6, reject) => {
4736
4746
  let counter = buffer2.length;
4737
4747
  if (!counter) {
4738
- return resolve5(true);
4748
+ return resolve6(true);
4739
4749
  }
4740
4750
  const capturedSetTimeout = setTimeout(() => {
4741
4751
  if (timeout && timeout > 0) {
4742
- resolve5(false);
4752
+ resolve6(false);
4743
4753
  }
4744
4754
  }, timeout);
4745
4755
  buffer2.forEach((item) => {
4746
4756
  void syncpromise.resolvedSyncPromise(item).then(() => {
4747
4757
  if (!--counter) {
4748
4758
  clearTimeout(capturedSetTimeout);
4749
- resolve5(true);
4759
+ resolve6(true);
4750
4760
  }
4751
4761
  }, reject);
4752
4762
  });
@@ -5948,17 +5958,17 @@ var require_eventProcessors = __commonJS({
5948
5958
  getGlobalEventProcessors().push(callback);
5949
5959
  }
5950
5960
  function notifyEventProcessors(processors, event, hint, index2 = 0) {
5951
- return new utils.SyncPromise((resolve5, reject) => {
5961
+ return new utils.SyncPromise((resolve6, reject) => {
5952
5962
  const processor = processors[index2];
5953
5963
  if (event === null || typeof processor !== "function") {
5954
- resolve5(event);
5964
+ resolve6(event);
5955
5965
  } else {
5956
5966
  const result = processor({ ...event }, hint);
5957
5967
  (typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__) && processor.id && result === null && utils.logger.log(`Event processor "${processor.id}" dropped event`);
5958
5968
  if (utils.isThenable(result)) {
5959
- void result.then((final) => notifyEventProcessors(processors, final, hint, index2 + 1).then(resolve5)).then(null, reject);
5969
+ void result.then((final) => notifyEventProcessors(processors, final, hint, index2 + 1).then(resolve6)).then(null, reject);
5960
5970
  } else {
5961
- void notifyEventProcessors(processors, result, hint, index2 + 1).then(resolve5).then(null, reject);
5971
+ void notifyEventProcessors(processors, result, hint, index2 + 1).then(resolve6).then(null, reject);
5962
5972
  }
5963
5973
  }
5964
5974
  });
@@ -9112,18 +9122,18 @@ var require_baseclient = __commonJS({
9112
9122
  * `false` otherwise
9113
9123
  */
9114
9124
  _isClientDoneProcessing(timeout) {
9115
- return new utils.SyncPromise((resolve5) => {
9125
+ return new utils.SyncPromise((resolve6) => {
9116
9126
  let ticked = 0;
9117
9127
  const tick = 1;
9118
9128
  const interval = setInterval(() => {
9119
9129
  if (this._numProcessing == 0) {
9120
9130
  clearInterval(interval);
9121
- resolve5(true);
9131
+ resolve6(true);
9122
9132
  } else {
9123
9133
  ticked += tick;
9124
9134
  if (timeout && ticked >= timeout) {
9125
9135
  clearInterval(interval);
9126
- resolve5(false);
9136
+ resolve6(false);
9127
9137
  }
9128
9138
  }
9129
9139
  }, tick);
@@ -13773,12 +13783,12 @@ var require_promisify = __commonJS({
13773
13783
  Object.defineProperty(exports2, "__esModule", { value: true });
13774
13784
  function promisify2(fn) {
13775
13785
  return function(req, opts) {
13776
- return new Promise((resolve5, reject) => {
13786
+ return new Promise((resolve6, reject) => {
13777
13787
  fn.call(this, req, opts, (err2, rtn) => {
13778
13788
  if (err2) {
13779
13789
  reject(err2);
13780
13790
  } else {
13781
- resolve5(rtn);
13791
+ resolve6(rtn);
13782
13792
  }
13783
13793
  });
13784
13794
  });
@@ -13982,7 +13992,7 @@ var require_parse_proxy_response = __commonJS({
13982
13992
  var debug_1 = __importDefault(require_src());
13983
13993
  var debug = debug_1.default("https-proxy-agent:parse-proxy-response");
13984
13994
  function parseProxyResponse(socket) {
13985
- return new Promise((resolve5, reject) => {
13995
+ return new Promise((resolve6, reject) => {
13986
13996
  let buffersLength = 0;
13987
13997
  const buffers = [];
13988
13998
  function read2() {
@@ -14022,7 +14032,7 @@ var require_parse_proxy_response = __commonJS({
14022
14032
  const firstLine = buffered.toString("ascii", 0, buffered.indexOf("\r\n"));
14023
14033
  const statusCode = +firstLine.split(" ")[1];
14024
14034
  debug("got proxy server response: %o", firstLine);
14025
- resolve5({
14035
+ resolve6({
14026
14036
  statusCode,
14027
14037
  buffered
14028
14038
  });
@@ -14043,11 +14053,11 @@ var require_agent = __commonJS({
14043
14053
  "use strict";
14044
14054
  var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) {
14045
14055
  function adopt(value) {
14046
- return value instanceof P2 ? value : new P2(function(resolve5) {
14047
- resolve5(value);
14056
+ return value instanceof P2 ? value : new P2(function(resolve6) {
14057
+ resolve6(value);
14048
14058
  });
14049
14059
  }
14050
- return new (P2 || (P2 = Promise))(function(resolve5, reject) {
14060
+ return new (P2 || (P2 = Promise))(function(resolve6, reject) {
14051
14061
  function fulfilled(value) {
14052
14062
  try {
14053
14063
  step(generator.next(value));
@@ -14063,7 +14073,7 @@ var require_agent = __commonJS({
14063
14073
  }
14064
14074
  }
14065
14075
  function step(result) {
14066
- result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected);
14076
+ result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
14067
14077
  }
14068
14078
  step((generator = generator.apply(thisArg, _arguments || [])).next());
14069
14079
  });
@@ -14274,7 +14284,7 @@ var require_http = __commonJS({
14274
14284
  function createRequestExecutor(options, httpModule, agent) {
14275
14285
  const { hostname, pathname, port, protocol, search } = new url.URL(options.url);
14276
14286
  return function makeRequest(request) {
14277
- return new Promise((resolve5, reject) => {
14287
+ return new Promise((resolve6, reject) => {
14278
14288
  let body = streamFromBody(request.body);
14279
14289
  const headers = { ...options.headers };
14280
14290
  if (request.body.length > GZIP_THRESHOLD) {
@@ -14300,7 +14310,7 @@ var require_http = __commonJS({
14300
14310
  res.setEncoding("utf8");
14301
14311
  const retryAfterHeader = _nullishCoalesce(res.headers["retry-after"], () => null);
14302
14312
  const rateLimitsHeader = _nullishCoalesce(res.headers["x-sentry-rate-limits"], () => null);
14303
- resolve5({
14313
+ resolve6({
14304
14314
  statusCode: res.statusCode,
14305
14315
  headers: {
14306
14316
  "retry-after": retryAfterHeader,
@@ -14332,10 +14342,10 @@ var require_module = __commonJS({
14332
14342
  return;
14333
14343
  }
14334
14344
  const normalizedFilename = normalizeWindowsPathSeparator ? normalizeWindowsPath(filename) : filename;
14335
- let { root, dir, base: basename3, ext } = path.posix.parse(normalizedFilename);
14345
+ let { root, dir, base: basename4, ext } = path.posix.parse(normalizedFilename);
14336
14346
  const base3 = require && require.main && require.main.filename && dir || global.process.cwd();
14337
14347
  const normalizedBase = `${base3}/`;
14338
- let file = basename3;
14348
+ let file = basename4;
14339
14349
  if (ext === ".js" || ext === ".mjs" || ext === ".cjs") {
14340
14350
  file = file.slice(0, ext.length * -1);
14341
14351
  }
@@ -14568,7 +14578,7 @@ var require_websocket = __commonJS({
14568
14578
  };
14569
14579
  async function createWebSocketClient(rawUrl) {
14570
14580
  const parts = url.parse(rawUrl);
14571
- return new Promise((resolve5, reject) => {
14581
+ return new Promise((resolve6, reject) => {
14572
14582
  const key = crypto3.randomBytes(16).toString("base64");
14573
14583
  const digest2 = createKey(key);
14574
14584
  const req = http2.request({
@@ -14599,7 +14609,7 @@ var require_websocket = __commonJS({
14599
14609
  return;
14600
14610
  }
14601
14611
  const client = new WebSocketInterface(socket);
14602
- resolve5(client);
14612
+ resolve6(client);
14603
14613
  });
14604
14614
  req.on("error", (err2) => {
14605
14615
  reject(err2);
@@ -15928,10 +15938,10 @@ var require_contextlines = __commonJS({
15928
15938
  var FILE_CONTENT_CACHE = new lru_map.LRUMap(100);
15929
15939
  var DEFAULT_LINES_OF_CONTEXT = 7;
15930
15940
  function readTextFileAsync(path) {
15931
- return new Promise((resolve5, reject) => {
15941
+ return new Promise((resolve6, reject) => {
15932
15942
  fs.readFile(path, "utf8", (err2, data) => {
15933
15943
  if (err2) reject(err2);
15934
- else resolve5(data);
15944
+ else resolve6(data);
15935
15945
  });
15936
15946
  });
15937
15947
  }
@@ -16241,13 +16251,13 @@ var require_context = __commonJS({
16241
16251
  version: `10.${Number(os.release().split(".")[0]) - 4}`
16242
16252
  };
16243
16253
  try {
16244
- const output4 = await new Promise((resolve5, reject) => {
16254
+ const output4 = await new Promise((resolve6, reject) => {
16245
16255
  child_process.execFile("/usr/bin/sw_vers", (error, stdout) => {
16246
16256
  if (error) {
16247
16257
  reject(error);
16248
16258
  return;
16249
16259
  }
16250
- resolve5(stdout);
16260
+ resolve6(stdout);
16251
16261
  });
16252
16262
  });
16253
16263
  darwinInfo.name = matchFirst(/^ProductName:\s+(.*)$/m, output4);
@@ -17918,6 +17928,8 @@ var init_events = __esm({
17918
17928
  CONFIG_SENSITIVE_WORDS_REFRESHED: "Sensitive words config refreshed",
17919
17929
  CONFIG_SYSTEM_REFRESHED: "System config refreshed",
17920
17930
  GATEWAY_DISCONNECTED: "Gateway disconnected",
17931
+ GATEWAY_REQUEST: "Gateway request",
17932
+ PROMPT_USER_CHECKPOINT: "Prompt user checkpoint",
17921
17933
  INBOUND_DM_RAW: "Inbound DM raw",
17922
17934
  INBOUND_GROUP_RAW: "Inbound group raw",
17923
17935
  // ── error ─────────────────────────────────────────────────────
@@ -17949,6 +17961,17 @@ var init_events = __esm({
17949
17961
  OFFLINE_REPLAY_MESSAGE_FAILED: "Offline replay message failed",
17950
17962
  PENDING_NOTIFICATION_FAILED: "Pending notification failed",
17951
17963
  GATEWAY_CONNECT_FAILED: "Gateway connect failed",
17964
+ GATEWAY_REQUEST_FAILED: "Gateway request failed",
17965
+ PROMPT_USER_FAILED: "Prompt user failed",
17966
+ DAEMON_COMMAND_FAILED: "Daemon command failed",
17967
+ DAEMON_COMMAND_TIMEOUT: "Daemon command timeout",
17968
+ DAEMON_COMMAND_STALE: "Daemon command stale",
17969
+ DAEMON_TICK_FAILED: "Daemon tick failed",
17970
+ DIRECT_CLI_FAILED: "Direct CLI failed",
17971
+ AI_RUN_FAILED: "AI run failed",
17972
+ AI_RUN_TIMEOUT: "AI run timeout",
17973
+ AI_RUN_TOOL_FAILED: "AI run tool failed",
17974
+ IPC_FAILED: "IPC failed",
17952
17975
  NOTIFY_AGENTS_WAKEUP_FAILED: "Notify agents wakeup failed",
17953
17976
  OUTBOUND_AGENT_LOOKUP_FAILED: "Outbound agent lookup failed",
17954
17977
  OUTBOUND_ELIGIBILITY_CHECK_FAILED: "Outbound eligibility check failed",
@@ -17971,21 +17994,29 @@ function agentExtras(identity3) {
17971
17994
  onchainosAgentId: identity3.onchainosAgentId || UNKNOWN_FIELD
17972
17995
  };
17973
17996
  }
17974
- var Sentry, import_node_crypto3, FLOW_ID, SENTRY_EXTRA_BLOCKLIST, SentryLogger, logger, initLogger, UNKNOWN_FIELD;
17997
+ var Sentry, import_node_crypto3, FLOW_ID, SENTRY_EXTRA_BLOCKLIST, SENTRY_EXTRA_BLOCKED_KEY_PARTS, SENTRY_TAG_KEYS, SENTRY_FINGERPRINT_KEYS, SENTRY_INFO_ALLOWLIST, MAX_EXTRA_STRING_LENGTH, MAX_TAG_VALUE_LENGTH, SENTRY_SENSITIVE_VALUE_KEYS, SentryLogger, logger, initLogger, shutdown, UNKNOWN_FIELD;
17975
17998
  var init_sentry_logger = __esm({
17976
17999
  "../core/src/sentry-logger/index.ts"() {
17977
18000
  "use strict";
17978
18001
  Sentry = __toESM(require_cjs4());
17979
18002
  import_node_crypto3 = require("node:crypto");
17980
18003
  init_events();
18004
+ init_events();
17981
18005
  FLOW_ID = (0, import_node_crypto3.randomUUID)();
17982
18006
  SENTRY_EXTRA_BLOCKLIST = /* @__PURE__ */ new Set([
17983
18007
  "args",
18008
+ "apikey",
17984
18009
  "argv",
18010
+ "auth",
18011
+ "authorization",
18012
+ "authtoken",
18013
+ "bearer",
17985
18014
  "body",
17986
18015
  "cache",
17987
18016
  "command",
17988
18017
  "content",
18018
+ "credential",
18019
+ "credentials",
17989
18020
  "cwd",
17990
18021
  "data",
17991
18022
  "error",
@@ -17999,24 +18030,176 @@ var init_sentry_logger = __esm({
17999
18030
  "logpath",
18000
18031
  "message",
18001
18032
  "output",
18033
+ "password",
18002
18034
  "params",
18003
18035
  "path",
18004
18036
  "payload",
18037
+ "privatekey",
18005
18038
  "prompt",
18006
18039
  "raw",
18007
18040
  "rawevent",
18008
18041
  "rawtext",
18009
18042
  "request",
18010
18043
  "response",
18044
+ "accesstoken",
18045
+ "refreshtoken",
18011
18046
  "digest",
18012
18047
  "nonce",
18013
18048
  "salt",
18014
18049
  "secret",
18050
+ "token",
18015
18051
  "stderr",
18016
18052
  "stdout",
18017
18053
  "title",
18018
18054
  "tooloutput"
18019
18055
  ]);
18056
+ SENTRY_EXTRA_BLOCKED_KEY_PARTS = [
18057
+ "accesstoken",
18058
+ "apikey",
18059
+ "authorization",
18060
+ "authtoken",
18061
+ "content",
18062
+ "credential",
18063
+ "filepath",
18064
+ "logpath",
18065
+ "outputpath",
18066
+ "password",
18067
+ "payload",
18068
+ "privatekey",
18069
+ "prompt",
18070
+ "rawevent",
18071
+ "rawtext",
18072
+ "refreshtoken",
18073
+ "requestbody",
18074
+ "responsebody",
18075
+ "secret",
18076
+ "stderr",
18077
+ "stdout",
18078
+ "token",
18079
+ "tooloutput"
18080
+ ];
18081
+ SENTRY_TAG_KEYS = /* @__PURE__ */ new Set([
18082
+ "agentPlatform",
18083
+ "cacheName",
18084
+ "checkpoint",
18085
+ "code",
18086
+ "communicationClass",
18087
+ "component",
18088
+ "eventName",
18089
+ "exitCode",
18090
+ "kind",
18091
+ "method",
18092
+ "operation",
18093
+ "phase",
18094
+ "platform",
18095
+ "provider",
18096
+ "reason",
18097
+ "role",
18098
+ "source",
18099
+ "stage",
18100
+ "status",
18101
+ "subcommand",
18102
+ "taskId",
18103
+ "type"
18104
+ ]);
18105
+ SENTRY_FINGERPRINT_KEYS = [
18106
+ "eventName",
18107
+ "cacheName",
18108
+ "checkpoint",
18109
+ "component",
18110
+ "method",
18111
+ "operation",
18112
+ "phase",
18113
+ "reason",
18114
+ "code",
18115
+ "provider",
18116
+ "type",
18117
+ "kind",
18118
+ "status",
18119
+ "subcommand"
18120
+ ];
18121
+ SENTRY_INFO_ALLOWLIST = /* @__PURE__ */ new Set([
18122
+ LogEvent.GATEWAY_STARTED,
18123
+ LogEvent.GATEWAY_STOPPED,
18124
+ LogEvent.GATEWAY_DISCONNECTED,
18125
+ LogEvent.GATEWAY_REQUEST,
18126
+ LogEvent.PROMPT_USER_CHECKPOINT,
18127
+ LogEvent.CHANNEL_READY,
18128
+ LogEvent.CONVERSATION_STARTED,
18129
+ LogEvent.EVALUATE_CONVERSATION_STARTED,
18130
+ LogEvent.CONVERSATION_DELETED,
18131
+ LogEvent.USER_DISPATCHED,
18132
+ LogEvent.SESSION_DISPATCHED,
18133
+ LogEvent.SESSION_CREATED,
18134
+ LogEvent.SESSION_DELETED,
18135
+ LogEvent.SESSION_AUTO_RECOVERED,
18136
+ LogEvent.INBOUND_DELIVERED,
18137
+ LogEvent.INBOUND_DM_RAW,
18138
+ LogEvent.INBOUND_GROUP_RAW,
18139
+ LogEvent.INBOUND_BLOCKED_ADDRESS_MISMATCH,
18140
+ LogEvent.INBOUND_BLOCKED_INELIGIBLE,
18141
+ LogEvent.INBOUND_BLOCKED_SENSITIVE,
18142
+ LogEvent.INBOUND_DROP_DM_INVALID_PAYLOAD,
18143
+ LogEvent.INBOUND_DROP_DM_NON_SYSTEM,
18144
+ LogEvent.INBOUND_DROP_DM_UNKNOWN_AGENT,
18145
+ LogEvent.INBOUND_DROP_EMPTY_CONTENT,
18146
+ LogEvent.INBOUND_DROP_MISSING_JOBID,
18147
+ LogEvent.INBOUND_DROP_UNSUPPORTED_MSGTYPE,
18148
+ LogEvent.DM_DELIVERED,
18149
+ LogEvent.DM_FALLBACK_TO_BACKUP,
18150
+ LogEvent.DM_WHITELIST_FAIL_OPEN,
18151
+ LogEvent.INBOUND_BUYER_PENDING,
18152
+ LogEvent.INBOUND_BUYER_SESSION_AUTO_RECOVERED,
18153
+ LogEvent.MESSAGE_SENT,
18154
+ LogEvent.AGENT_CLIENT_CREATED,
18155
+ LogEvent.AGENT_CLIENT_REMOVED,
18156
+ LogEvent.ADDRESS_SYNC_COMPLETED,
18157
+ LogEvent.AGENTS_REFRESHED,
18158
+ LogEvent.AGENTS_WAKEUP_NOTIFIED,
18159
+ LogEvent.AGENT_LIST_QUERIED,
18160
+ LogEvent.BOOTSTRAP_APPLIED,
18161
+ LogEvent.CONFIG_SENSITIVE_WORDS_REFRESHED,
18162
+ LogEvent.CONFIG_SYSTEM_REFRESHED,
18163
+ LogEvent.CONVERSATION_HISTORY_QUERIED,
18164
+ LogEvent.FILE_DOWNLOADED,
18165
+ LogEvent.FILE_UPLOADED,
18166
+ LogEvent.GROUP_CONSENT_CHANGED,
18167
+ LogEvent.MESSAGE_RECEIVED,
18168
+ LogEvent.OFFLINE_REPLAY_MESSAGE_REPLAYED,
18169
+ LogEvent.AGENT_REFRESH_SESSION_EXPIRED,
18170
+ LogEvent.OUTBOUND_ELIGIBILITY_CHECKED,
18171
+ LogEvent.OUTBOUND_BLOCKED_INELIGIBLE,
18172
+ LogEvent.PENDING_CONVERSATION_DENIED,
18173
+ LogEvent.PENDING_LIST_QUERIED,
18174
+ LogEvent.SESSION_KEY_DERIVED,
18175
+ LogEvent.SESSIONS_QUERIED,
18176
+ LogEvent.SYNC_TICK_COMPLETED
18177
+ ]);
18178
+ MAX_EXTRA_STRING_LENGTH = 256;
18179
+ MAX_TAG_VALUE_LENGTH = 128;
18180
+ SENTRY_SENSITIVE_VALUE_KEYS = [
18181
+ "address",
18182
+ "agentid",
18183
+ "chatid",
18184
+ "channelid",
18185
+ "commandid",
18186
+ "conversationid",
18187
+ "groupid",
18188
+ "inboxid",
18189
+ "jobid",
18190
+ "keyuuid",
18191
+ "filekey",
18192
+ "logfile",
18193
+ "messageid",
18194
+ "runid",
18195
+ "scopekey",
18196
+ "sessionid",
18197
+ "sessionkey",
18198
+ "taskid",
18199
+ "uuid",
18200
+ "wallet",
18201
+ "xmtp"
18202
+ ];
18020
18203
  SentryLogger = class _SentryLogger {
18021
18204
  static instance;
18022
18205
  initialized = false;
@@ -18034,32 +18217,49 @@ var init_sentry_logger = __esm({
18034
18217
  console.warn("[logger] Already initialized, skipping.");
18035
18218
  return;
18036
18219
  }
18037
- Sentry.init({
18038
- dsn: config.dsn,
18039
- release: config.release,
18040
- environment: config.environment,
18041
- maxBreadcrumbs: 0,
18042
- beforeBreadcrumb: () => null,
18043
- isInner: false
18044
- });
18045
- Sentry.setTags({
18046
- projectName: config.projectName,
18047
- agentPlatform: config.agentPlatform
18048
- });
18220
+ try {
18221
+ Sentry.init({
18222
+ dsn: config.dsn,
18223
+ release: config.release,
18224
+ environment: config.environment,
18225
+ maxBreadcrumbs: 0,
18226
+ beforeBreadcrumb: () => null,
18227
+ isInner: false
18228
+ });
18229
+ Sentry.setTags({
18230
+ projectName: config.projectName,
18231
+ agentPlatform: config.agentPlatform
18232
+ });
18233
+ } catch {
18234
+ return;
18235
+ }
18049
18236
  this.initialized = true;
18050
18237
  this.flush();
18051
18238
  }
18052
18239
  info(message, extra) {
18053
18240
  const extraWithFlow = _SentryLogger.sanitizeExtra({ flowId: FLOW_ID, ...extra ?? {} });
18241
+ if (!SENTRY_INFO_ALLOWLIST.has(message)) {
18242
+ return;
18243
+ }
18054
18244
  if (!this.initialized) {
18055
18245
  this.buffer.push({ level: "info", message, extra: extraWithFlow });
18056
18246
  return;
18057
18247
  }
18058
- Sentry.captureEvent({
18059
- level: "info",
18060
- message,
18061
- contexts: { report: { info: JSON.stringify(extraWithFlow) } }
18062
- });
18248
+ try {
18249
+ Sentry.withScope((scope) => {
18250
+ _SentryLogger.applyDiagnostics(scope, message, extraWithFlow);
18251
+ Sentry.captureEvent({
18252
+ level: "info",
18253
+ message,
18254
+ contexts: { report: { info: JSON.stringify(extraWithFlow) } },
18255
+ extra: {
18256
+ ...extraWithFlow,
18257
+ eventName: message
18258
+ }
18259
+ });
18260
+ });
18261
+ } catch {
18262
+ }
18063
18263
  }
18064
18264
  error(message, error, extra) {
18065
18265
  const extraWithFlow = _SentryLogger.sanitizeExtra({ flowId: FLOW_ID, ...extra ?? {} });
@@ -18072,18 +18272,22 @@ var init_sentry_logger = __esm({
18072
18272
  });
18073
18273
  return;
18074
18274
  }
18075
- Sentry.withScope((scope) => {
18076
- scope.setLevel("error");
18077
- scope.setContext("report", { info: JSON.stringify(extraWithFlow) });
18078
- Sentry.captureException(_SentryLogger.createSentryEvent(message, error), {
18079
- extra: error ? {
18080
- ...extraWithFlow,
18081
- eventName: message,
18082
- errorName: error.name,
18083
- errorMessageLength: String(error.message.length)
18084
- } : extraWithFlow
18275
+ try {
18276
+ Sentry.withScope((scope) => {
18277
+ scope.setLevel("error");
18278
+ scope.setContext("report", { info: JSON.stringify(extraWithFlow) });
18279
+ _SentryLogger.applyDiagnostics(scope, message, extraWithFlow);
18280
+ Sentry.captureException(_SentryLogger.createSentryEvent(message), {
18281
+ extra: error ? {
18282
+ ...extraWithFlow,
18283
+ eventName: message,
18284
+ errorName: error.name,
18285
+ errorMessageLength: String(error.message.length)
18286
+ } : extraWithFlow
18287
+ });
18085
18288
  });
18086
- });
18289
+ } catch {
18290
+ }
18087
18291
  }
18088
18292
  async shutdown() {
18089
18293
  await Sentry.flush(5e3);
@@ -18100,21 +18304,101 @@ var init_sentry_logger = __esm({
18100
18304
  }
18101
18305
  static sanitizeExtra(extra) {
18102
18306
  return Object.fromEntries(
18103
- Object.entries(extra).filter(([key]) => !SENTRY_EXTRA_BLOCKLIST.has(key.toLowerCase()))
18307
+ Object.entries(extra).filter(([, value]) => value !== void 0).filter(([key]) => !_SentryLogger.isBlockedExtraKey(key)).map(([key, value]) => [key, _SentryLogger.safeValueForKey(key, value)])
18104
18308
  );
18105
18309
  }
18310
+ static isBlockedExtraKey(key) {
18311
+ const lower = key.toLowerCase();
18312
+ const normalized = _SentryLogger.normalizeSensitiveKey(key);
18313
+ if (SENTRY_EXTRA_BLOCKLIST.has(lower) || SENTRY_EXTRA_BLOCKLIST.has(normalized)) {
18314
+ return true;
18315
+ }
18316
+ if (_SentryLogger.isSafeMetricKey(normalized)) {
18317
+ return false;
18318
+ }
18319
+ return SENTRY_EXTRA_BLOCKED_KEY_PARTS.some((needle) => normalized.includes(needle));
18320
+ }
18321
+ static isSafeMetricKey(normalized) {
18322
+ return /(bytes|count|length|ms|size)$/.test(normalized);
18323
+ }
18324
+ static safeValueForKey(key, value) {
18325
+ const safe = _SentryLogger.safeValue(value);
18326
+ if (safe === "" || safe === null || safe === void 0 || !_SentryLogger.isSensitiveValueKey(key)) {
18327
+ return safe;
18328
+ }
18329
+ if (typeof safe === "string" && _SentryLogger.isHashedValue(safe)) {
18330
+ return safe;
18331
+ }
18332
+ return `sha256:${(0, import_node_crypto3.createHash)("sha256").update(String(safe)).digest("hex").slice(0, 24)}`;
18333
+ }
18334
+ static isHashedValue(value) {
18335
+ return /^sha256:[a-f0-9]{24}$/i.test(value);
18336
+ }
18337
+ static isSensitiveValueKey(key) {
18338
+ const normalized = _SentryLogger.normalizeSensitiveKey(key);
18339
+ return SENTRY_SENSITIVE_VALUE_KEYS.some((needle) => normalized.includes(needle));
18340
+ }
18341
+ static normalizeSensitiveKey(key) {
18342
+ return key.toLowerCase().replace(/[^a-z0-9]/g, "");
18343
+ }
18344
+ static safeValue(value) {
18345
+ if (typeof value === "string") {
18346
+ return value.length <= MAX_EXTRA_STRING_LENGTH ? value : `${value.slice(0, MAX_EXTRA_STRING_LENGTH)}...`;
18347
+ }
18348
+ if (value === null || value === void 0 || typeof value === "number" || typeof value === "boolean") {
18349
+ return value;
18350
+ }
18351
+ if (typeof value === "bigint") {
18352
+ return value.toString();
18353
+ }
18354
+ if (value instanceof Error) {
18355
+ return {
18356
+ name: value.name,
18357
+ messageLength: value.message.length
18358
+ };
18359
+ }
18360
+ if (Array.isArray(value)) {
18361
+ return value.slice(0, 20).map((item) => _SentryLogger.safeValue(item));
18362
+ }
18363
+ if (typeof value === "object") {
18364
+ return Object.fromEntries(
18365
+ Object.entries(value).slice(0, 50).filter(([, item]) => item !== void 0).filter(([key]) => !_SentryLogger.isBlockedExtraKey(key)).map(([key, item]) => [key, _SentryLogger.safeValueForKey(key, item)])
18366
+ );
18367
+ }
18368
+ const text = String(value);
18369
+ return text.length <= MAX_EXTRA_STRING_LENGTH ? text : `${text.slice(0, MAX_EXTRA_STRING_LENGTH)}...`;
18370
+ }
18371
+ static tagValue(value) {
18372
+ const text = String(value);
18373
+ return text.length <= MAX_TAG_VALUE_LENGTH ? text : `${text.slice(0, MAX_TAG_VALUE_LENGTH)}...`;
18374
+ }
18375
+ static normalizeTagKey(key) {
18376
+ return key.replace(/[^A-Za-z0-9_.:-]+/g, "_").slice(0, 32) || "unknown";
18377
+ }
18378
+ static applyDiagnostics(scope, eventName, extra) {
18379
+ const enriched = { eventName, ...extra };
18380
+ for (const [key, value] of Object.entries(enriched)) {
18381
+ if (!SENTRY_TAG_KEYS.has(key)) {
18382
+ continue;
18383
+ }
18384
+ scope.setTag(_SentryLogger.normalizeTagKey(key), _SentryLogger.tagValue(value));
18385
+ }
18386
+ const fingerprint = ["a2a", eventName];
18387
+ for (const key of SENTRY_FINGERPRINT_KEYS) {
18388
+ const value = enriched[key];
18389
+ if (value) {
18390
+ fingerprint.push(`${key}:${_SentryLogger.tagValue(value)}`);
18391
+ }
18392
+ }
18393
+ scope.setFingerprint(fingerprint);
18394
+ }
18106
18395
  static toPascalCase(str) {
18107
18396
  return str.split(/[\s:]+/).filter(Boolean).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
18108
18397
  }
18109
- static createSentryEvent(eventName, cause) {
18398
+ static createSentryEvent(eventName) {
18110
18399
  const err2 = new Error(eventName);
18111
18400
  err2.name = _SentryLogger.toPascalCase(eventName);
18112
- if (cause?.stack) {
18113
- err2.stack = [
18114
- `${err2.name}: ${eventName}`,
18115
- ...cause.stack.split("\n").slice(1)
18116
- ].join("\n");
18117
- }
18401
+ err2.stack = `${err2.name}: ${eventName}`;
18118
18402
  return err2;
18119
18403
  }
18120
18404
  };
@@ -18122,10 +18406,27 @@ var init_sentry_logger = __esm({
18122
18406
  initLogger = (config) => {
18123
18407
  return logger.init(config);
18124
18408
  };
18409
+ shutdown = () => {
18410
+ return logger.shutdown();
18411
+ };
18125
18412
  UNKNOWN_FIELD = "unknown";
18126
18413
  }
18127
18414
  });
18128
18415
 
18416
+ // ../core/src/sentry-config.ts
18417
+ var environment, SENTRY_CONFIG;
18418
+ var init_sentry_config = __esm({
18419
+ "../core/src/sentry-config.ts"() {
18420
+ "use strict";
18421
+ environment = process.env.SENTRY_ENV === "dev" ? "dev" : "prod";
18422
+ SENTRY_CONFIG = {
18423
+ projectName: "okx/openclaw-okx-a2a-extension",
18424
+ release: "0.0.4",
18425
+ environment
18426
+ };
18427
+ }
18428
+ });
18429
+
18129
18430
  // ../core/src/xmtp-sdk/onchainos/bin.ts
18130
18431
  async function resolve2() {
18131
18432
  if (resolvedBin) {
@@ -18218,7 +18519,12 @@ async function exec(args) {
18218
18519
  LogEvent.ONCHAINOS_CLI_ERROR,
18219
18520
  new Error("onchainos command failed"),
18220
18521
  {
18522
+ component: "onchainos_cli",
18523
+ source: "onchainos",
18524
+ stage: "exec",
18525
+ communicationClass: "onchainos_cli_or_api_issue",
18221
18526
  operation: redactArgsForLog(args).slice(0, 3).join(" "),
18527
+ reason: "exec_failed",
18222
18528
  argCount: String(args.length),
18223
18529
  exitCode: String(err2?.code ?? ""),
18224
18530
  signal: String(err2?.signal ?? ""),
@@ -20368,7 +20674,7 @@ var require_parseParams = __commonJS({
20368
20674
  var require_basename = __commonJS({
20369
20675
  "../../node_modules/@fastify/busboy/lib/utils/basename.js"(exports2, module2) {
20370
20676
  "use strict";
20371
- module2.exports = function basename3(path) {
20677
+ module2.exports = function basename4(path) {
20372
20678
  if (typeof path !== "string") {
20373
20679
  return "";
20374
20680
  }
@@ -20395,7 +20701,7 @@ var require_multipart = __commonJS({
20395
20701
  var Dicer = require_Dicer();
20396
20702
  var parseParams = require_parseParams();
20397
20703
  var decodeText = require_decodeText();
20398
- var basename3 = require_basename();
20704
+ var basename4 = require_basename();
20399
20705
  var getLimit = require_getLimit();
20400
20706
  var RE_BOUNDARY = /^boundary$/i;
20401
20707
  var RE_FIELD = /^form-data$/i;
@@ -20512,7 +20818,7 @@ var require_multipart = __commonJS({
20512
20818
  } else if (RE_FILENAME.test(parsed[i][0])) {
20513
20819
  filename = parsed[i][1];
20514
20820
  if (!preservePath) {
20515
- filename = basename3(filename);
20821
+ filename = basename4(filename);
20516
20822
  }
20517
20823
  }
20518
20824
  }
@@ -21774,8 +22080,8 @@ var require_util2 = __commonJS({
21774
22080
  function createDeferredPromise() {
21775
22081
  let res;
21776
22082
  let rej;
21777
- const promise = new Promise((resolve5, reject) => {
21778
- res = resolve5;
22083
+ const promise = new Promise((resolve6, reject) => {
22084
+ res = resolve6;
21779
22085
  rej = reject;
21780
22086
  });
21781
22087
  return { promise, resolve: res, reject: rej };
@@ -23279,8 +23585,8 @@ Content-Type: ${value.type || "application/octet-stream"}\r
23279
23585
  });
23280
23586
  }
23281
23587
  });
23282
- const busboyResolve = new Promise((resolve5, reject) => {
23283
- busboy.on("finish", resolve5);
23588
+ const busboyResolve = new Promise((resolve6, reject) => {
23589
+ busboy.on("finish", resolve6);
23284
23590
  busboy.on("error", (err2) => reject(new TypeError(err2)));
23285
23591
  });
23286
23592
  if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk);
@@ -23814,9 +24120,9 @@ var require_dispatcher_base = __commonJS({
23814
24120
  }
23815
24121
  close(callback) {
23816
24122
  if (callback === void 0) {
23817
- return new Promise((resolve5, reject) => {
24123
+ return new Promise((resolve6, reject) => {
23818
24124
  this.close((err2, data) => {
23819
- return err2 ? reject(err2) : resolve5(data);
24125
+ return err2 ? reject(err2) : resolve6(data);
23820
24126
  });
23821
24127
  });
23822
24128
  }
@@ -23854,12 +24160,12 @@ var require_dispatcher_base = __commonJS({
23854
24160
  err2 = null;
23855
24161
  }
23856
24162
  if (callback === void 0) {
23857
- return new Promise((resolve5, reject) => {
24163
+ return new Promise((resolve6, reject) => {
23858
24164
  this.destroy(err2, (err3, data) => {
23859
24165
  return err3 ? (
23860
24166
  /* istanbul ignore next: should never error */
23861
24167
  reject(err3)
23862
- ) : resolve5(data);
24168
+ ) : resolve6(data);
23863
24169
  });
23864
24170
  });
23865
24171
  }
@@ -24919,16 +25225,16 @@ var require_client2 = __commonJS({
24919
25225
  return this[kNeedDrain] < 2;
24920
25226
  }
24921
25227
  async [kClose]() {
24922
- return new Promise((resolve5) => {
25228
+ return new Promise((resolve6) => {
24923
25229
  if (!this[kSize]) {
24924
- resolve5(null);
25230
+ resolve6(null);
24925
25231
  } else {
24926
- this[kClosedResolve] = resolve5;
25232
+ this[kClosedResolve] = resolve6;
24927
25233
  }
24928
25234
  });
24929
25235
  }
24930
25236
  async [kDestroy](err2) {
24931
- return new Promise((resolve5) => {
25237
+ return new Promise((resolve6) => {
24932
25238
  const requests = this[kQueue].splice(this[kPendingIdx]);
24933
25239
  for (let i = 0; i < requests.length; i++) {
24934
25240
  const request = requests[i];
@@ -24939,7 +25245,7 @@ var require_client2 = __commonJS({
24939
25245
  this[kClosedResolve]();
24940
25246
  this[kClosedResolve] = null;
24941
25247
  }
24942
- resolve5();
25248
+ resolve6();
24943
25249
  };
24944
25250
  if (this[kHTTP2Session] != null) {
24945
25251
  util.destroy(this[kHTTP2Session], err2);
@@ -25519,7 +25825,7 @@ var require_client2 = __commonJS({
25519
25825
  });
25520
25826
  }
25521
25827
  try {
25522
- const socket = await new Promise((resolve5, reject) => {
25828
+ const socket = await new Promise((resolve6, reject) => {
25523
25829
  client[kConnector]({
25524
25830
  host,
25525
25831
  hostname,
@@ -25531,7 +25837,7 @@ var require_client2 = __commonJS({
25531
25837
  if (err2) {
25532
25838
  reject(err2);
25533
25839
  } else {
25534
- resolve5(socket2);
25840
+ resolve6(socket2);
25535
25841
  }
25536
25842
  });
25537
25843
  });
@@ -26155,12 +26461,12 @@ upgrade: ${upgrade}\r
26155
26461
  cb();
26156
26462
  }
26157
26463
  }
26158
- const waitForDrain = () => new Promise((resolve5, reject) => {
26464
+ const waitForDrain = () => new Promise((resolve6, reject) => {
26159
26465
  assert(callback === null);
26160
26466
  if (socket[kError]) {
26161
26467
  reject(socket[kError]);
26162
26468
  } else {
26163
- callback = resolve5;
26469
+ callback = resolve6;
26164
26470
  }
26165
26471
  });
26166
26472
  if (client[kHTTPConnVersion] === "h2") {
@@ -26505,8 +26811,8 @@ var require_pool_base = __commonJS({
26505
26811
  if (this[kQueue].isEmpty()) {
26506
26812
  return Promise.all(this[kClients].map((c) => c.close()));
26507
26813
  } else {
26508
- return new Promise((resolve5) => {
26509
- this[kClosedResolve] = resolve5;
26814
+ return new Promise((resolve6) => {
26815
+ this[kClosedResolve] = resolve6;
26510
26816
  });
26511
26817
  }
26512
26818
  }
@@ -27084,7 +27390,7 @@ var require_readable = __commonJS({
27084
27390
  if (this.closed) {
27085
27391
  return Promise.resolve(null);
27086
27392
  }
27087
- return new Promise((resolve5, reject) => {
27393
+ return new Promise((resolve6, reject) => {
27088
27394
  const signalListenerCleanup = signal ? util.addAbortListener(signal, () => {
27089
27395
  this.destroy();
27090
27396
  }) : noop;
@@ -27093,7 +27399,7 @@ var require_readable = __commonJS({
27093
27399
  if (signal && signal.aborted) {
27094
27400
  reject(signal.reason || Object.assign(new Error("The operation was aborted"), { name: "AbortError" }));
27095
27401
  } else {
27096
- resolve5(null);
27402
+ resolve6(null);
27097
27403
  }
27098
27404
  }).on("error", noop).on("data", function(chunk) {
27099
27405
  limit -= chunk.length;
@@ -27115,11 +27421,11 @@ var require_readable = __commonJS({
27115
27421
  throw new TypeError("unusable");
27116
27422
  }
27117
27423
  assert(!stream[kConsume]);
27118
- return new Promise((resolve5, reject) => {
27424
+ return new Promise((resolve6, reject) => {
27119
27425
  stream[kConsume] = {
27120
27426
  type,
27121
27427
  stream,
27122
- resolve: resolve5,
27428
+ resolve: resolve6,
27123
27429
  reject,
27124
27430
  length: 0,
27125
27431
  body: []
@@ -27154,12 +27460,12 @@ var require_readable = __commonJS({
27154
27460
  }
27155
27461
  }
27156
27462
  function consumeEnd(consume2) {
27157
- const { type, body, resolve: resolve5, stream, length: length2 } = consume2;
27463
+ const { type, body, resolve: resolve6, stream, length: length2 } = consume2;
27158
27464
  try {
27159
27465
  if (type === "text") {
27160
- resolve5(toUSVString(Buffer.concat(body)));
27466
+ resolve6(toUSVString(Buffer.concat(body)));
27161
27467
  } else if (type === "json") {
27162
- resolve5(JSON.parse(Buffer.concat(body)));
27468
+ resolve6(JSON.parse(Buffer.concat(body)));
27163
27469
  } else if (type === "arrayBuffer") {
27164
27470
  const dst = new Uint8Array(length2);
27165
27471
  let pos = 0;
@@ -27167,12 +27473,12 @@ var require_readable = __commonJS({
27167
27473
  dst.set(buf, pos);
27168
27474
  pos += buf.byteLength;
27169
27475
  }
27170
- resolve5(dst.buffer);
27476
+ resolve6(dst.buffer);
27171
27477
  } else if (type === "blob") {
27172
27478
  if (!Blob2) {
27173
27479
  Blob2 = require("buffer").Blob;
27174
27480
  }
27175
- resolve5(new Blob2(body, { type: stream[kContentType] }));
27481
+ resolve6(new Blob2(body, { type: stream[kContentType] }));
27176
27482
  }
27177
27483
  consumeFinish(consume2);
27178
27484
  } catch (err2) {
@@ -27427,9 +27733,9 @@ var require_api_request = __commonJS({
27427
27733
  };
27428
27734
  function request(opts, callback) {
27429
27735
  if (callback === void 0) {
27430
- return new Promise((resolve5, reject) => {
27736
+ return new Promise((resolve6, reject) => {
27431
27737
  request.call(this, opts, (err2, data) => {
27432
- return err2 ? reject(err2) : resolve5(data);
27738
+ return err2 ? reject(err2) : resolve6(data);
27433
27739
  });
27434
27740
  });
27435
27741
  }
@@ -27602,9 +27908,9 @@ var require_api_stream = __commonJS({
27602
27908
  };
27603
27909
  function stream(opts, factory, callback) {
27604
27910
  if (callback === void 0) {
27605
- return new Promise((resolve5, reject) => {
27911
+ return new Promise((resolve6, reject) => {
27606
27912
  stream.call(this, opts, factory, (err2, data) => {
27607
- return err2 ? reject(err2) : resolve5(data);
27913
+ return err2 ? reject(err2) : resolve6(data);
27608
27914
  });
27609
27915
  });
27610
27916
  }
@@ -27885,9 +28191,9 @@ var require_api_upgrade = __commonJS({
27885
28191
  };
27886
28192
  function upgrade(opts, callback) {
27887
28193
  if (callback === void 0) {
27888
- return new Promise((resolve5, reject) => {
28194
+ return new Promise((resolve6, reject) => {
27889
28195
  upgrade.call(this, opts, (err2, data) => {
27890
- return err2 ? reject(err2) : resolve5(data);
28196
+ return err2 ? reject(err2) : resolve6(data);
27891
28197
  });
27892
28198
  });
27893
28199
  }
@@ -27976,9 +28282,9 @@ var require_api_connect = __commonJS({
27976
28282
  };
27977
28283
  function connect(opts, callback) {
27978
28284
  if (callback === void 0) {
27979
- return new Promise((resolve5, reject) => {
28285
+ return new Promise((resolve6, reject) => {
27980
28286
  connect.call(this, opts, (err2, data) => {
27981
- return err2 ? reject(err2) : resolve5(data);
28287
+ return err2 ? reject(err2) : resolve6(data);
27982
28288
  });
27983
28289
  });
27984
28290
  }
@@ -31600,7 +31906,7 @@ var require_fetch = __commonJS({
31600
31906
  async function dispatch({ body }) {
31601
31907
  const url = requestCurrentURL(request);
31602
31908
  const agent = fetchParams.controller.dispatcher;
31603
- return new Promise((resolve5, reject) => agent.dispatch(
31909
+ return new Promise((resolve6, reject) => agent.dispatch(
31604
31910
  {
31605
31911
  path: url.pathname + url.search,
31606
31912
  origin: url.origin,
@@ -31676,7 +31982,7 @@ var require_fetch = __commonJS({
31676
31982
  }
31677
31983
  }
31678
31984
  }
31679
- resolve5({
31985
+ resolve6({
31680
31986
  status,
31681
31987
  statusText,
31682
31988
  headersList: headers[kHeadersList],
@@ -31719,7 +32025,7 @@ var require_fetch = __commonJS({
31719
32025
  const val = headersList[n + 1].toString("latin1");
31720
32026
  headers[kHeadersList].append(key, val);
31721
32027
  }
31722
- resolve5({
32028
+ resolve6({
31723
32029
  status,
31724
32030
  statusText: STATUS_CODES[status],
31725
32031
  headersList: headers[kHeadersList],
@@ -35046,11 +35352,11 @@ var require_fetch_pb = __commonJS({
35046
35352
  "use strict";
35047
35353
  var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) {
35048
35354
  function adopt(value) {
35049
- return value instanceof P2 ? value : new P2(function(resolve5) {
35050
- resolve5(value);
35355
+ return value instanceof P2 ? value : new P2(function(resolve6) {
35356
+ resolve6(value);
35051
35357
  });
35052
35358
  }
35053
- return new (P2 || (P2 = Promise))(function(resolve5, reject) {
35359
+ return new (P2 || (P2 = Promise))(function(resolve6, reject) {
35054
35360
  function fulfilled(value) {
35055
35361
  try {
35056
35362
  step(generator.next(value));
@@ -35066,7 +35372,7 @@ var require_fetch_pb = __commonJS({
35066
35372
  }
35067
35373
  }
35068
35374
  function step(result) {
35069
- result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected);
35375
+ result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
35070
35376
  }
35071
35377
  step((generator = generator.apply(thisArg, _arguments || [])).next());
35072
35378
  });
@@ -36336,7 +36642,7 @@ var require_aspromise = __commonJS({
36336
36642
  var params = new Array(arguments.length - 1), offset = 0, index2 = 2, pending = true;
36337
36643
  while (index2 < arguments.length)
36338
36644
  params[offset++] = arguments[index2++];
36339
- return new Promise(function executor(resolve5, reject) {
36645
+ return new Promise(function executor(resolve6, reject) {
36340
36646
  params[offset] = function callback(err2) {
36341
36647
  if (pending) {
36342
36648
  pending = false;
@@ -36346,7 +36652,7 @@ var require_aspromise = __commonJS({
36346
36652
  var params2 = new Array(arguments.length - 1), offset2 = 0;
36347
36653
  while (offset2 < params2.length)
36348
36654
  params2[offset2++] = arguments[offset2];
36349
- resolve5.apply(null, params2);
36655
+ resolve6.apply(null, params2);
36350
36656
  }
36351
36657
  }
36352
36658
  };
@@ -45802,7 +46108,7 @@ var require_Observable = __commonJS({
45802
46108
  Observable2.prototype.forEach = function(next, promiseCtor) {
45803
46109
  var _this = this;
45804
46110
  promiseCtor = getPromiseCtor(promiseCtor);
45805
- return new promiseCtor(function(resolve5, reject) {
46111
+ return new promiseCtor(function(resolve6, reject) {
45806
46112
  var subscriber = new Subscriber_1.SafeSubscriber({
45807
46113
  next: function(value) {
45808
46114
  try {
@@ -45813,7 +46119,7 @@ var require_Observable = __commonJS({
45813
46119
  }
45814
46120
  },
45815
46121
  error: reject,
45816
- complete: resolve5
46122
+ complete: resolve6
45817
46123
  });
45818
46124
  _this.subscribe(subscriber);
45819
46125
  });
@@ -45835,14 +46141,14 @@ var require_Observable = __commonJS({
45835
46141
  Observable2.prototype.toPromise = function(promiseCtor) {
45836
46142
  var _this = this;
45837
46143
  promiseCtor = getPromiseCtor(promiseCtor);
45838
- return new promiseCtor(function(resolve5, reject) {
46144
+ return new promiseCtor(function(resolve6, reject) {
45839
46145
  var value;
45840
46146
  _this.subscribe(function(x) {
45841
46147
  return value = x;
45842
46148
  }, function(err2) {
45843
46149
  return reject(err2);
45844
46150
  }, function() {
45845
- return resolve5(value);
46151
+ return resolve6(value);
45846
46152
  });
45847
46153
  });
45848
46154
  };
@@ -46103,11 +46409,11 @@ var require_innerFrom = __commonJS({
46103
46409
  "use strict";
46104
46410
  var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P2, generator) {
46105
46411
  function adopt(value) {
46106
- return value instanceof P2 ? value : new P2(function(resolve5) {
46107
- resolve5(value);
46412
+ return value instanceof P2 ? value : new P2(function(resolve6) {
46413
+ resolve6(value);
46108
46414
  });
46109
46415
  }
46110
- return new (P2 || (P2 = Promise))(function(resolve5, reject) {
46416
+ return new (P2 || (P2 = Promise))(function(resolve6, reject) {
46111
46417
  function fulfilled(value) {
46112
46418
  try {
46113
46419
  step(generator.next(value));
@@ -46123,7 +46429,7 @@ var require_innerFrom = __commonJS({
46123
46429
  }
46124
46430
  }
46125
46431
  function step(result) {
46126
- result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected);
46432
+ result.done ? resolve6(result.value) : adopt(result.value).then(fulfilled, rejected);
46127
46433
  }
46128
46434
  step((generator = generator.apply(thisArg, _arguments || [])).next());
46129
46435
  });
@@ -46205,14 +46511,14 @@ var require_innerFrom = __commonJS({
46205
46511
  }, i);
46206
46512
  function verb(n) {
46207
46513
  i[n] = o[n] && function(v) {
46208
- return new Promise(function(resolve5, reject) {
46209
- v = o[n](v), settle(resolve5, reject, v.done, v.value);
46514
+ return new Promise(function(resolve6, reject) {
46515
+ v = o[n](v), settle(resolve6, reject, v.done, v.value);
46210
46516
  });
46211
46517
  };
46212
46518
  }
46213
- function settle(resolve5, reject, d, v) {
46519
+ function settle(resolve6, reject, d, v) {
46214
46520
  Promise.resolve(v).then(function(v2) {
46215
- resolve5({ value: v2, done: d });
46521
+ resolve6({ value: v2, done: d });
46216
46522
  }, reject);
46217
46523
  }
46218
46524
  };
@@ -61115,8 +61421,8 @@ var init_dist4 = __esm({
61115
61421
  value: this.#queue.shift()
61116
61422
  });
61117
61423
  }
61118
- return new Promise((resolve5) => {
61119
- this.#pendingResolves.push(resolve5);
61424
+ return new Promise((resolve6) => {
61425
+ this.#pendingResolves.push(resolve6);
61120
61426
  });
61121
61427
  };
61122
61428
  return = () => {
@@ -61142,7 +61448,7 @@ var init_dist4 = __esm({
61142
61448
  isUsableProperty = (prop) => {
61143
61449
  return usableProperties.includes(prop);
61144
61450
  };
61145
- wait = (ms) => new Promise((resolve5) => setTimeout(resolve5, ms));
61451
+ wait = (ms) => new Promise((resolve6) => setTimeout(resolve6, ms));
61146
61452
  DEFAULT_RETRY_DELAY = 6e4;
61147
61453
  DEFAULT_RETRY_ATTEMPTS = 10;
61148
61454
  createStream = async (streamFunction, streamValueMutator, options) => {
@@ -70622,7 +70928,7 @@ var init_wait = __esm({
70622
70928
 
70623
70929
  // ../../node_modules/viem/_esm/utils/promise/withRetry.js
70624
70930
  function withRetry(fn, { delay: delay_ = 100, retryCount = 2, shouldRetry: shouldRetry2 = () => true } = {}) {
70625
- return new Promise((resolve5, reject) => {
70931
+ return new Promise((resolve6, reject) => {
70626
70932
  const attemptRetry = async ({ count = 0 } = {}) => {
70627
70933
  const retry = async ({ error }) => {
70628
70934
  const delay = typeof delay_ === "function" ? delay_({ count, error }) : delay_;
@@ -70632,7 +70938,7 @@ function withRetry(fn, { delay: delay_ = 100, retryCount = 2, shouldRetry: shoul
70632
70938
  };
70633
70939
  try {
70634
70940
  const data = await fn();
70635
- resolve5(data);
70941
+ resolve6(data);
70636
70942
  } catch (err2) {
70637
70943
  if (count < retryCount && await shouldRetry2({ count, error: err2 }))
70638
70944
  return retry({ error: err2 });
@@ -71206,13 +71512,13 @@ var init_transactionRequest = __esm({
71206
71512
 
71207
71513
  // ../../node_modules/viem/_esm/utils/promise/withResolvers.js
71208
71514
  function withResolvers() {
71209
- let resolve5 = () => void 0;
71515
+ let resolve6 = () => void 0;
71210
71516
  let reject = () => void 0;
71211
71517
  const promise = new Promise((resolve_, reject_) => {
71212
- resolve5 = resolve_;
71518
+ resolve6 = resolve_;
71213
71519
  reject = reject_;
71214
71520
  });
71215
- return { promise, resolve: resolve5, reject };
71521
+ return { promise, resolve: resolve6, reject };
71216
71522
  }
71217
71523
  var init_withResolvers = __esm({
71218
71524
  "../../node_modules/viem/_esm/utils/promise/withResolvers.js"() {
@@ -71231,8 +71537,8 @@ function createBatchScheduler({ fn, id, shouldSplitBatch, wait: wait3 = 0, sort
71231
71537
  if (sort && Array.isArray(data))
71232
71538
  data.sort(sort);
71233
71539
  for (let i = 0; i < scheduler.length; i++) {
71234
- const { resolve: resolve5 } = scheduler[i];
71235
- resolve5?.([data[i], data]);
71540
+ const { resolve: resolve6 } = scheduler[i];
71541
+ resolve6?.([data[i], data]);
71236
71542
  }
71237
71543
  }).catch((err2) => {
71238
71544
  for (let i = 0; i < scheduler.length; i++) {
@@ -71248,16 +71554,16 @@ function createBatchScheduler({ fn, id, shouldSplitBatch, wait: wait3 = 0, sort
71248
71554
  return {
71249
71555
  flush: flush2,
71250
71556
  async schedule(args) {
71251
- const { promise, resolve: resolve5, reject } = withResolvers();
71557
+ const { promise, resolve: resolve6, reject } = withResolvers();
71252
71558
  const split2 = shouldSplitBatch?.([...getBatchedArgs(), args]);
71253
71559
  if (split2)
71254
71560
  exec2();
71255
71561
  const hasActiveScheduler = getScheduler().length > 0;
71256
71562
  if (hasActiveScheduler) {
71257
- setScheduler({ args, resolve: resolve5, reject });
71563
+ setScheduler({ args, resolve: resolve6, reject });
71258
71564
  return promise;
71259
71565
  }
71260
- setScheduler({ args, resolve: resolve5, reject });
71566
+ setScheduler({ args, resolve: resolve6, reject });
71261
71567
  setTimeout(exec2, wait3);
71262
71568
  return promise;
71263
71569
  }
@@ -71694,7 +72000,7 @@ var init_getTransactionCount = __esm({
71694
72000
 
71695
72001
  // ../../node_modules/viem/_esm/utils/promise/withTimeout.js
71696
72002
  function withTimeout(fn, { errorInstance = new Error("timed out"), timeout, signal }) {
71697
- return new Promise((resolve5, reject) => {
72003
+ return new Promise((resolve6, reject) => {
71698
72004
  ;
71699
72005
  (async () => {
71700
72006
  let timeoutId;
@@ -71709,7 +72015,7 @@ function withTimeout(fn, { errorInstance = new Error("timed out"), timeout, sign
71709
72015
  }
71710
72016
  }, timeout);
71711
72017
  }
71712
- resolve5(await fn({ signal: controller?.signal || null }));
72018
+ resolve6(await fn({ signal: controller?.signal || null }));
71713
72019
  } catch (err2) {
71714
72020
  if (err2?.name === "AbortError")
71715
72021
  reject(errorInstance);
@@ -74786,7 +75092,7 @@ async function sendCalls(client, parameters) {
74786
75092
  });
74787
75093
  promises.push(promise);
74788
75094
  if (experimental_fallbackDelay > 0)
74789
- await new Promise((resolve5) => setTimeout(resolve5, experimental_fallbackDelay));
75095
+ await new Promise((resolve6) => setTimeout(resolve6, experimental_fallbackDelay));
74790
75096
  }
74791
75097
  const results = await Promise.allSettled(promises);
74792
75098
  if (results.every((r) => r.status === "rejected"))
@@ -74917,9 +75223,9 @@ async function waitForCallsStatus(client, parameters) {
74917
75223
  throwOnFailure = false
74918
75224
  } = parameters;
74919
75225
  const observerId = stringify(["waitForCallsStatus", client.uid, id]);
74920
- const { promise, resolve: resolve5, reject } = withResolvers();
75226
+ const { promise, resolve: resolve6, reject } = withResolvers();
74921
75227
  let timer;
74922
- const unobserve = observe(observerId, { resolve: resolve5, reject }, (emit) => {
75228
+ const unobserve = observe(observerId, { resolve: resolve6, reject }, (emit) => {
74923
75229
  const unpoll = poll(async () => {
74924
75230
  const done = (fn) => {
74925
75231
  clearTimeout(timer);
@@ -75257,13 +75563,13 @@ async function waitForTransactionReceipt(client, parameters) {
75257
75563
  let retrying = false;
75258
75564
  let _unobserve;
75259
75565
  let _unwatch;
75260
- const { promise, resolve: resolve5, reject } = withResolvers();
75566
+ const { promise, resolve: resolve6, reject } = withResolvers();
75261
75567
  const timer = timeout ? setTimeout(() => {
75262
75568
  _unwatch?.();
75263
75569
  _unobserve?.();
75264
75570
  reject(new WaitForTransactionReceiptTimeoutError({ hash: hash2 }));
75265
75571
  }, timeout) : void 0;
75266
- _unobserve = observe(observerId, { onReplaced, resolve: resolve5, reject }, async (emit) => {
75572
+ _unobserve = observe(observerId, { onReplaced, resolve: resolve6, reject }, async (emit) => {
75267
75573
  receipt = await getAction(client, getTransactionReceipt, "getTransactionReceipt")({ hash: hash2 }).catch(() => void 0);
75268
75574
  if (receipt && confirmations <= 1) {
75269
75575
  clearTimeout(timer);
@@ -76902,7 +77208,7 @@ function loadSensitiveWordsFromCache(dataDir) {
76902
77208
  return null;
76903
77209
  } catch (err2) {
76904
77210
  console.log("[xmtp-sdk] failed to read sensitive-words.json cache:", err2);
76905
- logger.error(LogEvent.CACHE_LOAD_FAILED, err2 instanceof Error ? err2 : new Error(String(err2)), { cache: "sensitive-words" });
77211
+ logger.error(LogEvent.CACHE_LOAD_FAILED, err2 instanceof Error ? err2 : new Error(String(err2)), { cacheName: "sensitive-words" });
76906
77212
  return null;
76907
77213
  }
76908
77214
  }
@@ -76912,7 +77218,7 @@ function saveSensitiveWordsToCache(dataDir, words) {
76912
77218
  (0, import_node_fs8.writeFileSync)(cachePath(dataDir, "sensitive-words.json"), JSON.stringify(words));
76913
77219
  } catch (err2) {
76914
77220
  console.log(`[xmtp-sdk] failed to write sensitive-words.json:`, err2);
76915
- logger.error(LogEvent.CACHE_WRITE_FAILED, err2 instanceof Error ? err2 : new Error(String(err2)), { cache: "sensitive-words" });
77221
+ logger.error(LogEvent.CACHE_WRITE_FAILED, err2 instanceof Error ? err2 : new Error(String(err2)), { cacheName: "sensitive-words" });
76916
77222
  }
76917
77223
  }
76918
77224
  async function loadSensitiveWordsWith(dataDir, fetcher) {
@@ -76961,7 +77267,7 @@ function loadSystemConfigFromCache(dataDir) {
76961
77267
  return null;
76962
77268
  } catch (err2) {
76963
77269
  console.log("[xmtp-sdk] failed to read system-config.json cache:", err2);
76964
- logger.error(LogEvent.CACHE_LOAD_FAILED, err2 instanceof Error ? err2 : new Error(String(err2)), { cache: "system-config" });
77270
+ logger.error(LogEvent.CACHE_LOAD_FAILED, err2 instanceof Error ? err2 : new Error(String(err2)), { cacheName: "system-config" });
76965
77271
  return null;
76966
77272
  }
76967
77273
  }
@@ -76971,7 +77277,7 @@ function saveSystemConfigToCache(dataDir, config) {
76971
77277
  (0, import_node_fs8.writeFileSync)(cachePath(dataDir, "system-config.json"), JSON.stringify(config));
76972
77278
  } catch (err2) {
76973
77279
  console.log(`[xmtp-sdk] failed to write system-config.json:`, err2);
76974
- logger.error(LogEvent.CACHE_WRITE_FAILED, err2 instanceof Error ? err2 : new Error(String(err2)), { cache: "system-config" });
77280
+ logger.error(LogEvent.CACHE_WRITE_FAILED, err2 instanceof Error ? err2 : new Error(String(err2)), { cacheName: "system-config" });
76975
77281
  }
76976
77282
  }
76977
77283
  async function loadSystemConfigWith(dataDir, fetcher) {
@@ -77029,7 +77335,7 @@ function loadSyncByAddress(dataDir) {
77029
77335
  }
77030
77336
  } catch (err2) {
77031
77337
  console.log("[xmtp-sdk] failed to read last-sync.json cache:", err2);
77032
- logger.error(LogEvent.CACHE_LOAD_FAILED, err2 instanceof Error ? err2 : new Error(String(err2)), { cache: "last-sync" });
77338
+ logger.error(LogEvent.CACHE_LOAD_FAILED, err2 instanceof Error ? err2 : new Error(String(err2)), { cacheName: "last-sync" });
77033
77339
  }
77034
77340
  return map;
77035
77341
  }
@@ -77057,7 +77363,7 @@ function saveSyncForAddress(dataDir, address, timestampMs) {
77057
77363
  err2
77058
77364
  );
77059
77365
  logger.error(LogEvent.CACHE_WRITE_FAILED, err2 instanceof Error ? err2 : new Error(String(err2)), {
77060
- cache: "last-sync",
77366
+ cacheName: "last-sync",
77061
77367
  walletAddress: address
77062
77368
  });
77063
77369
  }
@@ -78544,6 +78850,10 @@ function cliResponseExtras(stdout) {
78544
78850
  }
78545
78851
  function cliOkFalseExtras(stdout, command, extra) {
78546
78852
  return {
78853
+ component: "onchainos_cli",
78854
+ source: "onchainos",
78855
+ stage: "ok_false",
78856
+ communicationClass: "onchainos_cli_or_api_issue",
78547
78857
  operation: command,
78548
78858
  reason: CliErrorReason.OK_FALSE,
78549
78859
  ...cliResponseExtras(stdout),
@@ -78556,6 +78866,10 @@ function parseCliJson(stdout, command, extras = {}) {
78556
78866
  } catch (err2) {
78557
78867
  const parseErr = err2 instanceof Error ? err2 : new Error(String(err2));
78558
78868
  logger.error(LogEvent.ONCHAINOS_CLI_ERROR, parseErr, {
78869
+ component: "onchainos_cli",
78870
+ source: "onchainos",
78871
+ stage: "json_parse",
78872
+ communicationClass: "onchainos_cli_or_api_issue",
78559
78873
  operation: command,
78560
78874
  reason: CliErrorReason.JSON_PARSE_FAILED,
78561
78875
  ...cliResponseExtras(stdout),
@@ -78581,7 +78895,15 @@ function notifySessionExpired(command) {
78581
78895
  logger.error(
78582
78896
  LogEvent.ONCHAINOS_SESSION_EXPIRED,
78583
78897
  new Error("onchainos session expired"),
78584
- { command }
78898
+ {
78899
+ component: "onchainos_cli",
78900
+ source: "onchainos",
78901
+ stage: "session_expired",
78902
+ operation: command,
78903
+ command,
78904
+ communicationClass: "onchainos_auth_issue",
78905
+ reason: "session_expired"
78906
+ }
78585
78907
  );
78586
78908
  const hook = XmtpService.getInstance().tools.notifySessionExpired;
78587
78909
  if (!hook) {
@@ -79229,14 +79551,14 @@ async function startUserAttentionEventServer(options = {}) {
79229
79551
  }
79230
79552
  }
79231
79553
  }
79232
- await new Promise((resolve5, reject) => {
79554
+ await new Promise((resolve6, reject) => {
79233
79555
  const onError = (err2) => {
79234
79556
  server.off("listening", onListening);
79235
79557
  reject(err2);
79236
79558
  };
79237
79559
  const onListening = () => {
79238
79560
  server.off("error", onError);
79239
- resolve5();
79561
+ resolve6();
79240
79562
  };
79241
79563
  server.once("error", onError);
79242
79564
  server.once("listening", onListening);
@@ -79251,7 +79573,7 @@ async function startUserAttentionEventServer(options = {}) {
79251
79573
  for (const socket of sockets) {
79252
79574
  socket.destroy();
79253
79575
  }
79254
- return new Promise((resolve5, reject) => {
79576
+ return new Promise((resolve6, reject) => {
79255
79577
  server.close((err2) => {
79256
79578
  if (process.platform !== "win32") {
79257
79579
  try {
@@ -79262,7 +79584,7 @@ async function startUserAttentionEventServer(options = {}) {
79262
79584
  if (err2) {
79263
79585
  reject(err2);
79264
79586
  } else {
79265
- resolve5();
79587
+ resolve6();
79266
79588
  }
79267
79589
  });
79268
79590
  });
@@ -79271,7 +79593,7 @@ async function startUserAttentionEventServer(options = {}) {
79271
79593
  }
79272
79594
  async function subscribeUserAttentionEvents(options) {
79273
79595
  const path = resolveUserAttentionIpcPath(options.homeDir);
79274
- return new Promise((resolve5) => {
79596
+ return new Promise((resolve6) => {
79275
79597
  const socket = (0, import_node_net.createConnection)(path);
79276
79598
  let settled = false;
79277
79599
  let buffer2 = "";
@@ -79280,7 +79602,7 @@ async function subscribeUserAttentionEvents(options) {
79280
79602
  return;
79281
79603
  }
79282
79604
  settled = true;
79283
- resolve5({
79605
+ resolve6({
79284
79606
  path,
79285
79607
  connected,
79286
79608
  close() {
@@ -79312,7 +79634,7 @@ async function subscribeUserAttentionEvents(options) {
79312
79634
  }
79313
79635
  async function notifyUserAttentionChanged(homeDir) {
79314
79636
  const path = resolveUserAttentionIpcPath(homeDir);
79315
- return new Promise((resolve5) => {
79637
+ return new Promise((resolve6) => {
79316
79638
  const socket = (0, import_node_net.createConnection)(path);
79317
79639
  let done = false;
79318
79640
  const finish = (ok) => {
@@ -79321,7 +79643,7 @@ async function notifyUserAttentionChanged(homeDir) {
79321
79643
  }
79322
79644
  done = true;
79323
79645
  socket.destroy();
79324
- resolve5(ok);
79646
+ resolve6(ok);
79325
79647
  };
79326
79648
  socket.setTimeout(1e3, () => finish(false));
79327
79649
  socket.once("connect", () => {
@@ -79594,57 +79916,6 @@ function createEmptyTaskFile(jobId, sessionAgentId) {
79594
79916
  messages: []
79595
79917
  };
79596
79918
  }
79597
- function sameAddress(left, right) {
79598
- return !!left && !!right && left.toLowerCase() === right.toLowerCase();
79599
- }
79600
- function isNonEmptyString(value) {
79601
- return typeof value === "string" && value.length > 0;
79602
- }
79603
- function extractJsonObjects(raw) {
79604
- const objects = [];
79605
- let start = -1;
79606
- let depth = 0;
79607
- let inString = false;
79608
- let escaped = false;
79609
- for (let i = 0; i < raw.length; i++) {
79610
- const char = raw[i];
79611
- if (start === -1) {
79612
- if (char === "{") {
79613
- start = i;
79614
- depth = 1;
79615
- inString = false;
79616
- escaped = false;
79617
- }
79618
- continue;
79619
- }
79620
- if (inString) {
79621
- if (escaped) {
79622
- escaped = false;
79623
- } else if (char === "\\") {
79624
- escaped = true;
79625
- } else if (char === '"') {
79626
- inString = false;
79627
- }
79628
- continue;
79629
- }
79630
- if (char === '"') {
79631
- inString = true;
79632
- } else if (char === "{") {
79633
- depth++;
79634
- } else if (char === "}") {
79635
- depth--;
79636
- if (depth === 0) {
79637
- const candidate = raw.slice(start, i + 1);
79638
- const parsed = parseJson(candidate);
79639
- if (parsed) {
79640
- objects.push(parsed);
79641
- }
79642
- start = -1;
79643
- }
79644
- }
79645
- }
79646
- return objects;
79647
- }
79648
79919
  function selectReplyTarget(messages, replyToMessageId) {
79649
79920
  if (replyToMessageId) {
79650
79921
  const exact = messages.find((message) => message.id === replyToMessageId);
@@ -79819,176 +80090,100 @@ function inferMyXmtpAddress(params) {
79819
80090
  }
79820
80091
  throw new Error("Cannot infer local XMTP address; pass --my-agent-id <id>");
79821
80092
  }
79822
- function findDataObject(raw, predicate) {
79823
- const objects = extractJsonObjects(raw);
79824
- for (let i = objects.length - 1; i >= 0; i--) {
79825
- const object = objects[i];
79826
- if (!isPlainObject(object)) {
79827
- continue;
80093
+ async function resolveAgentByIdFromCacheOrNetwork(service, agentId) {
80094
+ const local = service.getAgentByAgentId(agentId);
80095
+ if (local) {
80096
+ resolvedAgentByIdCache.set(local.agentId, local);
80097
+ if (local.communicationAddress) {
80098
+ resolvedAgentByAddressCache.set(local.communicationAddress.toLowerCase(), local);
79828
80099
  }
79829
- const data = isPlainObject(object.data) ? object.data : object;
79830
- if (predicate(data)) {
79831
- return data;
80100
+ return local;
80101
+ }
80102
+ const cached = resolvedAgentByIdCache.get(agentId);
80103
+ if (cached) {
80104
+ return cached;
80105
+ }
80106
+ const [remote] = await fetchAgentsByIds([agentId]);
80107
+ if (remote?.agentId) {
80108
+ resolvedAgentByIdCache.set(remote.agentId, remote);
80109
+ if (remote.communicationAddress) {
80110
+ resolvedAgentByAddressCache.set(remote.communicationAddress.toLowerCase(), remote);
79832
80111
  }
79833
80112
  }
79834
- return null;
80113
+ return remote;
79835
80114
  }
79836
- async function fetchTaskStatus(jobId, myAgentId) {
79837
- const { stdout, stderr } = await exec([
79838
- "agent",
79839
- "status",
79840
- jobId,
79841
- "--agent-id",
79842
- myAgentId
79843
- ]);
79844
- const data = findDataObject(`${stdout}
79845
- ${stderr}`, (item) => {
79846
- return readString(item.jobId)?.toLowerCase() === jobId.toLowerCase();
79847
- });
79848
- if (!data) {
79849
- return null;
80115
+ async function resolveAgentByAddressFromCacheOrNetwork(service, communicationAddress) {
80116
+ const local = service.getAgentByAddress(communicationAddress);
80117
+ if (local) {
80118
+ resolvedAgentByIdCache.set(local.agentId, local);
80119
+ resolvedAgentByAddressCache.set(local.communicationAddress.toLowerCase(), local);
80120
+ return local;
79850
80121
  }
79851
- return {
79852
- jobId: readString(data.jobId) ?? void 0,
79853
- providerAgentId: readString(data.providerAgentId),
79854
- providerAgentAddress: readString(data.providerAgentAddress),
79855
- designatedProvider: readString(data.designatedProvider)
79856
- };
79857
- }
79858
- async function fetchTaskRecommendations(jobId, myAgentId) {
79859
- const { stdout, stderr } = await exec([
79860
- "agent",
79861
- "recommend",
79862
- jobId,
79863
- "--agent-id",
79864
- myAgentId
79865
- ]);
79866
- const data = findDataObject(`${stdout}
79867
- ${stderr}`, (item) => Array.isArray(item.recommendations));
79868
- const recommendations = Array.isArray(data?.recommendations) ? data.recommendations : [];
79869
- return recommendations.filter(isPlainObject).map((item) => ({
79870
- providerAgentId: readString(item.providerAgentId),
79871
- providerAddress: readString(item.providerAddress)
79872
- }));
79873
- }
79874
- async function searchAgents(query) {
79875
- const { stdout, stderr } = await exec([
79876
- "agent",
79877
- "search",
79878
- "--query",
79879
- query,
79880
- "--page",
79881
- "1",
79882
- "--page-size",
79883
- "10"
79884
- ]);
79885
- const data = findDataObject(`${stdout}
79886
- ${stderr}`, (item) => {
79887
- return Array.isArray(item.list);
79888
- });
79889
- const list = Array.isArray(data?.list) ? data.list : [];
79890
- return list.filter(isPlainObject).map((item) => ({
79891
- agentId: readString(item.agentId) ?? void 0,
79892
- communicationAddress: readString(item.communicationAddress) ?? void 0
79893
- }));
79894
- }
79895
- async function fetchAgentByWalletAddress(walletAddress) {
79896
- const candidates = await searchAgents(walletAddress);
79897
- const ids = candidates.map((item) => item.agentId).filter(isNonEmptyString);
79898
- if (ids.length === 0) {
79899
- return void 0;
80122
+ const cached = resolvedAgentByAddressCache.get(communicationAddress.toLowerCase());
80123
+ if (cached) {
80124
+ return cached;
80125
+ }
80126
+ const remote = await fetchAgentByAddress(communicationAddress);
80127
+ if (remote?.agentId) {
80128
+ resolvedAgentByIdCache.set(remote.agentId, remote);
80129
+ if (remote.communicationAddress) {
80130
+ resolvedAgentByAddressCache.set(remote.communicationAddress.toLowerCase(), remote);
80131
+ }
79900
80132
  }
79901
- const agents = await fetchAgentsByIds(ids);
79902
- return agents.find((agent) => {
79903
- return sameAddress(agent.agentWalletAddress, walletAddress) || sameAddress(agent.ownerAddress, walletAddress);
79904
- }) ?? agents[0];
80133
+ return remote;
79905
80134
  }
79906
- async function resolveRemoteAgentFromJob(jobId, myAgentId) {
80135
+ async function resolveRemoteByAgentId(params) {
80136
+ const { service, agentId, fallbackAddress, logContext } = params;
80137
+ let remoteAgent;
79907
80138
  try {
79908
- const status = await fetchTaskStatus(jobId, myAgentId);
79909
- if (status?.providerAgentId) {
79910
- const [agent] = await fetchAgentsByIds([status.providerAgentId]);
79911
- if (agent?.communicationAddress) {
79912
- return agent;
79913
- }
79914
- }
79915
- const providerWallet = status?.providerAgentAddress ?? status?.designatedProvider;
79916
- if (providerWallet) {
79917
- const agent = await fetchAgentByWalletAddress(providerWallet);
79918
- if (agent?.communicationAddress) {
79919
- return agent;
79920
- }
79921
- }
80139
+ remoteAgent = await resolveAgentByIdFromCacheOrNetwork(service, agentId);
79922
80140
  } catch (err2) {
79923
- console.log(
79924
- `[okx-agent-task] failed to infer provider from task status job=${jobId} myAgentId=${myAgentId}:`,
79925
- err2
79926
- );
80141
+ if (!fallbackAddress) {
80142
+ throw err2;
80143
+ }
80144
+ logRecipientStatusLookupFailed(logContext, err2);
79927
80145
  }
79928
- try {
79929
- const recommendations = await fetchTaskRecommendations(jobId, myAgentId);
79930
- for (const recommendation of recommendations) {
79931
- if (recommendation.providerAgentId) {
79932
- const [agent] = await fetchAgentsByIds([recommendation.providerAgentId]);
79933
- if (agent?.communicationAddress) {
79934
- return agent;
79935
- }
79936
- }
79937
- if (recommendation.providerAddress) {
79938
- const agent = await fetchAgentByWalletAddress(recommendation.providerAddress);
79939
- if (agent?.communicationAddress) {
79940
- return agent;
79941
- }
79942
- }
80146
+ if (!remoteAgent?.communicationAddress && fallbackAddress) {
80147
+ try {
80148
+ const fallbackAgent = await resolveAgentByAddressFromCacheOrNetwork(service, fallbackAddress);
80149
+ remoteAgent = fallbackAgent ?? remoteAgent;
80150
+ } catch (err2) {
80151
+ console.log(
80152
+ `[okx-agent-task] remote agent lookup failed for ${fallbackAddress}, continuing without receiverAgentId:`,
80153
+ err2
80154
+ );
79943
80155
  }
79944
- } catch (err2) {
79945
- console.log(
79946
- `[okx-agent-task] failed to infer provider from recommendations job=${jobId} myAgentId=${myAgentId}:`,
79947
- err2
79948
- );
79949
80156
  }
79950
- return void 0;
80157
+ if (!remoteAgent?.communicationAddress && !fallbackAddress) {
80158
+ throw new Error(`No communication address found for toAgentId=${agentId}`);
80159
+ }
80160
+ assertRecipientAvailable(remoteAgent);
80161
+ return {
80162
+ toXmtpAddress: remoteAgent?.communicationAddress ?? fallbackAddress,
80163
+ toAgentId: remoteAgent?.agentId ?? agentId,
80164
+ remoteAgent
80165
+ };
79951
80166
  }
79952
80167
  async function resolveRemote(params) {
79953
80168
  const { command, file, service } = params;
79954
80169
  if (command.toAgentId) {
79955
- let remoteAgent;
79956
- try {
79957
- [remoteAgent] = await fetchAgentsByIds([command.toAgentId]);
79958
- } catch (err2) {
79959
- const fallbackAddress = command.toXmtpAddress ?? file.toXmtpAddress;
79960
- if (!fallbackAddress) {
79961
- throw err2;
79962
- }
79963
- logRecipientStatusLookupFailed(`toAgentId=${command.toAgentId}`, err2);
79964
- return {
79965
- toXmtpAddress: fallbackAddress,
79966
- toAgentId: command.toAgentId,
79967
- remoteAgent: void 0
79968
- };
79969
- }
79970
- if (!remoteAgent?.communicationAddress) {
79971
- throw new Error(`No communication address found for toAgentId=${command.toAgentId}`);
79972
- }
79973
- assertRecipientAvailable(remoteAgent);
79974
- return {
79975
- toXmtpAddress: remoteAgent.communicationAddress,
79976
- toAgentId: remoteAgent.agentId,
79977
- remoteAgent
79978
- };
80170
+ return resolveRemoteByAgentId({
80171
+ service,
80172
+ agentId: command.toAgentId,
80173
+ fallbackAddress: command.toXmtpAddress ?? file.toXmtpAddress,
80174
+ logContext: `toAgentId=${command.toAgentId}`
80175
+ });
79979
80176
  }
79980
80177
  const toXmtpAddress = command.toXmtpAddress ?? file.toXmtpAddress;
79981
80178
  if (toXmtpAddress) {
79982
- let remoteAgent = service.getAgentByAddress(toXmtpAddress);
79983
- if (!remoteAgent) {
79984
- try {
79985
- remoteAgent = await fetchAgentByAddress(toXmtpAddress);
79986
- } catch (err2) {
79987
- console.log(
79988
- `[okx-agent-task] remote agent lookup failed for ${toXmtpAddress}, continuing without receiverAgentId:`,
79989
- err2
79990
- );
79991
- }
80179
+ let remoteAgent;
80180
+ try {
80181
+ remoteAgent = await resolveAgentByAddressFromCacheOrNetwork(service, toXmtpAddress);
80182
+ } catch (err2) {
80183
+ console.log(
80184
+ `[okx-agent-task] remote agent lookup failed for ${toXmtpAddress}, continuing without receiverAgentId:`,
80185
+ err2
80186
+ );
79992
80187
  }
79993
80188
  assertRecipientAvailable(remoteAgent);
79994
80189
  return {
@@ -79997,59 +80192,29 @@ async function resolveRemote(params) {
79997
80192
  remoteAgent
79998
80193
  };
79999
80194
  }
80000
- if (command.myAgentId) {
80001
- const remoteAgent = await resolveRemoteAgentFromJob(command.jobId, command.myAgentId);
80002
- if (remoteAgent?.communicationAddress) {
80003
- assertRecipientAvailable(remoteAgent);
80004
- return {
80005
- toXmtpAddress: remoteAgent.communicationAddress,
80006
- toAgentId: remoteAgent.agentId,
80007
- remoteAgent
80008
- };
80009
- }
80010
- }
80011
80195
  throw new Error(
80012
- "job JSON has no xmtpGroupId and provider could not be inferred; pass --my-agent-id <id> or optionally --to-agent-id/--to-address"
80196
+ "job JSON has no xmtpGroupId or remote address; pass --to-agent-id or --to-address"
80013
80197
  );
80014
80198
  }
80015
80199
  async function resolveRemoteWithoutFile(params) {
80016
80200
  const { command, service } = params;
80017
80201
  if (command.toAgentId) {
80202
+ return resolveRemoteByAgentId({
80203
+ service,
80204
+ agentId: command.toAgentId,
80205
+ fallbackAddress: command.toXmtpAddress,
80206
+ logContext: `toAgentId=${command.toAgentId}`
80207
+ });
80208
+ }
80209
+ if (command.toXmtpAddress) {
80018
80210
  let remoteAgent;
80019
80211
  try {
80020
- [remoteAgent] = await fetchAgentsByIds([command.toAgentId]);
80212
+ remoteAgent = await resolveAgentByAddressFromCacheOrNetwork(service, command.toXmtpAddress);
80021
80213
  } catch (err2) {
80022
- if (!command.toXmtpAddress) {
80023
- throw err2;
80024
- }
80025
- logRecipientStatusLookupFailed(`toAgentId=${command.toAgentId}`, err2);
80026
- return {
80027
- toXmtpAddress: command.toXmtpAddress,
80028
- toAgentId: command.toAgentId,
80029
- remoteAgent: void 0
80030
- };
80031
- }
80032
- if (!remoteAgent?.communicationAddress) {
80033
- throw new Error(`No communication address found for toAgentId=${command.toAgentId}`);
80034
- }
80035
- assertRecipientAvailable(remoteAgent);
80036
- return {
80037
- toXmtpAddress: remoteAgent.communicationAddress,
80038
- toAgentId: remoteAgent.agentId,
80039
- remoteAgent
80040
- };
80041
- }
80042
- if (command.toXmtpAddress) {
80043
- let remoteAgent = service.getAgentByAddress(command.toXmtpAddress);
80044
- if (!remoteAgent) {
80045
- try {
80046
- remoteAgent = await fetchAgentByAddress(command.toXmtpAddress);
80047
- } catch (err2) {
80048
- console.log(
80049
- `[okx-agent-task] remote agent lookup failed for ${command.toXmtpAddress}, continuing without receiverAgentId:`,
80050
- err2
80051
- );
80052
- }
80214
+ console.log(
80215
+ `[okx-agent-task] remote agent lookup failed for ${command.toXmtpAddress}, continuing without receiverAgentId:`,
80216
+ err2
80217
+ );
80053
80218
  }
80054
80219
  assertRecipientAvailable(remoteAgent);
80055
80220
  return {
@@ -80187,16 +80352,14 @@ async function ensureGroupSession(params) {
80187
80352
  let remoteAgent;
80188
80353
  if (stored.toAgentId) {
80189
80354
  try {
80190
- [remoteAgent] = await fetchAgentsByIds([stored.toAgentId]);
80355
+ remoteAgent = await resolveAgentByIdFromCacheOrNetwork(service, stored.toAgentId);
80191
80356
  } catch (err2) {
80192
80357
  logRecipientStatusLookupFailed(`stored.toAgentId=${stored.toAgentId}`, err2);
80193
80358
  }
80194
- } else {
80195
- remoteAgent = service.getAgentByAddress(stored.toXmtpAddress);
80196
80359
  }
80197
80360
  if (!remoteAgent) {
80198
80361
  try {
80199
- remoteAgent = await fetchAgentByAddress(stored.toXmtpAddress);
80362
+ remoteAgent = await resolveAgentByAddressFromCacheOrNetwork(service, stored.toXmtpAddress);
80200
80363
  } catch {
80201
80364
  remoteAgent = void 0;
80202
80365
  }
@@ -80494,7 +80657,7 @@ async function handleXmtpSendCommand(params) {
80494
80657
  });
80495
80658
  return { messageId };
80496
80659
  }
80497
- var import_node_crypto6, TASK_MIN_VERSION, sqliteGroupSessionPromises;
80660
+ var import_node_crypto6, TASK_MIN_VERSION, sqliteGroupSessionPromises, resolvedAgentByIdCache, resolvedAgentByAddressCache;
80498
80661
  var init_xmtp_send = __esm({
80499
80662
  "src/xmtp-send.ts"() {
80500
80663
  "use strict";
@@ -80503,12 +80666,13 @@ var init_xmtp_send = __esm({
80503
80666
  init_envelope();
80504
80667
  init_concurrency2();
80505
80668
  init_xmtp_sdk();
80506
- init_bin();
80507
80669
  init_onchainos();
80508
80670
  init_session_store();
80509
80671
  init_agent_message_notice();
80510
80672
  TASK_MIN_VERSION = 1;
80511
80673
  sqliteGroupSessionPromises = /* @__PURE__ */ new Map();
80674
+ resolvedAgentByIdCache = /* @__PURE__ */ new Map();
80675
+ resolvedAgentByAddressCache = /* @__PURE__ */ new Map();
80512
80676
  }
80513
80677
  });
80514
80678
 
@@ -80516,8 +80680,8 @@ var init_xmtp_send = __esm({
80516
80680
  function buildClaudeAllowedToolsArgs() {
80517
80681
  return ["--allowedTools", ...CLAUDE_ALLOWED_TOOLS];
80518
80682
  }
80519
- function buildCodexPermissionPrefix(homeDir, cwd, env = process.env) {
80520
- const preset = resolveAiPermissionPreset({ homeDir, env });
80683
+ function buildCodexPermissionPrefix(homeDir, cwd, env = process.env, permissionPreset) {
80684
+ const preset = permissionPreset ?? resolveAiPermissionPreset({ homeDir, env });
80521
80685
  const sandbox = readCodexSandboxMode(preset, env);
80522
80686
  const approvalPolicy = readCodexApprovalPolicy(preset, env);
80523
80687
  const addDirArgs = sandbox === "workspace-write" ? [homeDir, ...readCodexAddDirs(env)].flatMap((dir) => ["--add-dir", dir]) : [];
@@ -80550,7 +80714,7 @@ function buildAiAdapterCommand(options) {
80550
80714
  "--output-format",
80551
80715
  outputFormat,
80552
80716
  ...outputFormat === "stream-json" ? ["--verbose"] : [],
80553
- ...buildClaudePermissionModeArgs(homeDir, env),
80717
+ ...buildClaudePermissionModeArgs(homeDir, env, options.permissionPreset),
80554
80718
  ...buildClaudeAllowedToolsArgs(),
80555
80719
  ...buildClaudeAddDirArgs(homeDir, env)
80556
80720
  ];
@@ -80561,7 +80725,7 @@ function buildAiAdapterCommand(options) {
80561
80725
  };
80562
80726
  }
80563
80727
  if (options.provider === "codex") {
80564
- const prefix = [...buildCodexPermissionPrefix(homeDir, cwd, env), "exec"];
80728
+ const prefix = [...buildCodexPermissionPrefix(homeDir, cwd, env, options.permissionPreset), "exec"];
80565
80729
  return {
80566
80730
  provider: options.provider,
80567
80731
  command,
@@ -80611,7 +80775,9 @@ function expandHomePath(value) {
80611
80775
  return value;
80612
80776
  }
80613
80777
  async function runAiAdapter(options) {
80614
- const built = buildAiAdapterCommand(options);
80778
+ const homeDir = options.homeDir ?? resolveTaskPaths().homeDir;
80779
+ const permissionPreset = options.permissionPreset ?? (options.provider === "codex" || options.provider === "claude" ? resolveAiPermissionPresetForRun(homeDir, options.env ?? process.env) : void 0);
80780
+ const built = buildAiAdapterCommand({ ...options, homeDir, permissionPreset });
80615
80781
  const startedAt = Date.now();
80616
80782
  console.error(
80617
80783
  `[okx-agent-task] AI adapter start provider=${options.provider} command=${built.command} mode=${options.sessionId ? "resume" : "new"} cwd=${options.cwd ?? process.cwd()}`
@@ -80674,9 +80840,9 @@ async function runAiAdapter(options) {
80674
80840
  }, 5e3).unref();
80675
80841
  }, timeoutMs);
80676
80842
  timeout.unref();
80677
- const exitCode = await new Promise((resolve5, reject) => {
80843
+ const exitCode = await new Promise((resolve6, reject) => {
80678
80844
  child.once("error", reject);
80679
- child.once("close", (code2) => resolve5(code2));
80845
+ child.once("close", (code2) => resolve6(code2));
80680
80846
  });
80681
80847
  clearTimeout(timeout);
80682
80848
  const durationMs = Date.now() - startedAt;
@@ -80692,6 +80858,27 @@ async function runAiAdapter(options) {
80692
80858
  console.error(
80693
80859
  `[okx-agent-task] AI adapter done provider=${options.provider} exitCode=${exitCode ?? "null"} sessionId=${sessionId ?? "(none)"} duration=${durationMs}ms timeout=${timedOut ? "yes" : "no"} stdout=${stdout.length}B stderr=${stderr.length}B`
80694
80860
  );
80861
+ if (timedOut || exitCode !== 0 || !sessionId) {
80862
+ const reason = timedOut ? "timeout" : !sessionId ? "missing_ai_session_id" : "non_zero_exit";
80863
+ logger.error(
80864
+ timedOut ? LogEvent.AI_RUN_TIMEOUT : LogEvent.AI_RUN_FAILED,
80865
+ new Error(`${options.provider} AI adapter failed: ${reason}`),
80866
+ {
80867
+ component: "node_ai_adapter",
80868
+ source: "ai-cli",
80869
+ provider: options.provider,
80870
+ stage: "run_adapter",
80871
+ reason,
80872
+ sessionKey: options.sessionKey ?? "",
80873
+ timeoutMs: String(timeoutMs),
80874
+ exitCode: exitCode === null ? "null" : String(exitCode),
80875
+ timedOut: String(timedOut),
80876
+ durationMs: String(durationMs),
80877
+ stdoutBytes: String(Buffer.byteLength(stdout, "utf8")),
80878
+ stderrBytes: String(Buffer.byteLength(stderr, "utf8"))
80879
+ }
80880
+ );
80881
+ }
80695
80882
  return {
80696
80883
  ...built,
80697
80884
  ok: !timedOut && exitCode === 0 && !!sessionId,
@@ -80793,13 +80980,24 @@ function buildClaudeAddDirArgs(homeDir, env) {
80793
80980
  ];
80794
80981
  return ["--add-dir", ...[...new Set(dirs)]];
80795
80982
  }
80796
- function buildClaudePermissionModeArgs(homeDir, env) {
80797
- const mode = env.OKX_A2A_AI_CLAUDE_PERMISSION_MODE || env.OKX_AGENT_TASK_CLAUDE_PERMISSION_MODE || (resolveAiPermissionPreset({ homeDir, env }) === "bypass" ? "bypassPermissions" : "auto");
80983
+ function buildClaudePermissionModeArgs(homeDir, env, permissionPreset) {
80984
+ const mode = env.OKX_A2A_AI_CLAUDE_PERMISSION_MODE || env.OKX_AGENT_TASK_CLAUDE_PERMISSION_MODE || ((permissionPreset ?? resolveAiPermissionPreset({ homeDir, env })) === "bypass" ? "bypassPermissions" : "auto");
80798
80985
  if (!CLAUDE_PERMISSION_MODES.has(mode)) {
80799
80986
  throw new Error(`Unsupported Claude permission mode: ${mode}`);
80800
80987
  }
80801
80988
  return ["--permission-mode", mode];
80802
80989
  }
80990
+ function resolveAiPermissionPresetForRun(homeDir, env) {
80991
+ if (env.OKX_A2A_AI_PERMISSION_PRESET || env.OKX_AGENT_TASK_AI_PERMISSION_PRESET) {
80992
+ return resolveAiPermissionPreset({ homeDir, env });
80993
+ }
80994
+ const store = new SessionStore({ homeDir });
80995
+ try {
80996
+ return store.getAiBypassEnabled() ? "bypass" : "auto";
80997
+ } finally {
80998
+ store.close();
80999
+ }
81000
+ }
80803
81001
  function readCodexSandboxMode(preset, env) {
80804
81002
  const mode = env.OKX_A2A_AI_CODEX_SANDBOX || env.OKX_AGENT_TASK_CODEX_SANDBOX || (preset === "bypass" ? "danger-full-access" : "workspace-write");
80805
81003
  if (!CODEX_SANDBOX_MODES.has(mode)) {
@@ -80842,7 +81040,9 @@ var init_ai_adapter = __esm({
80842
81040
  import_node_path13 = require("node:path");
80843
81041
  init_ai_command();
80844
81042
  init_paths();
81043
+ init_session_store();
80845
81044
  init_task_config();
81045
+ init_sentry_logger();
80846
81046
  CLAUDE_ALLOWED_TOOLS = [
80847
81047
  "Read",
80848
81048
  "LS",
@@ -80867,6 +81067,60 @@ var init_ai_adapter = __esm({
80867
81067
  });
80868
81068
 
80869
81069
  // src/ai-runner.ts
81070
+ function aiRunSentryExtra(input) {
81071
+ const entries = Object.entries({
81072
+ component: "node_ai_runner",
81073
+ source: input.source,
81074
+ sessionKey: input.sessionKey,
81075
+ jobId: input.jobId ?? "",
81076
+ agentId: input.agentId ?? "",
81077
+ messageId: input.messageId ?? "",
81078
+ provider: input.provider ?? "",
81079
+ reason: input.reason ?? "",
81080
+ stage: input.stage ?? "",
81081
+ timeoutMs: input.timeoutMs ?? "",
81082
+ exitCode: input.exitCode ?? "",
81083
+ closeSignal: input.closeSignal ?? "",
81084
+ timedOut: input.timedOut === void 0 ? "" : String(input.timedOut),
81085
+ aiSessionId: input.aiSessionId ?? "",
81086
+ aiLogFileHash: input.logPath ? stableHash2((0, import_node_path14.basename)(input.logPath)) : "",
81087
+ queueWaitMs: input.queueWaitMs ?? "",
81088
+ cliMs: input.cliMs ?? "",
81089
+ totalMs: input.totalMs ?? "",
81090
+ timeToFirstStdoutMs: input.timeToFirstStdoutMs ?? "",
81091
+ timeToFirstStderrMs: input.timeToFirstStderrMs ?? ""
81092
+ }).filter(([, value]) => value !== "");
81093
+ return entries.reduce((out, [key, value]) => {
81094
+ out[key] = String(value);
81095
+ return out;
81096
+ }, {});
81097
+ }
81098
+ function aiRunToolFailureSentryExtra(failure, context) {
81099
+ const entries = Object.entries({
81100
+ component: "node_ai_runner",
81101
+ source: context.source,
81102
+ sessionKey: context.sessionKey,
81103
+ jobId: context.jobId ?? "",
81104
+ agentId: context.agentId ?? "",
81105
+ messageId: context.messageId ?? "",
81106
+ provider: failure.provider,
81107
+ tool: failure.tool,
81108
+ type: failure.errorType,
81109
+ kind: failure.permissionKind ?? "",
81110
+ permissionTargetHash: failure.permissionTarget ? stableHash2(failure.permissionTarget) : "",
81111
+ suggestedAddDirHash: failure.suggestedAddDir ? stableHash2(failure.suggestedAddDir) : "",
81112
+ status: failure.status ?? "",
81113
+ exitCode: failure.exitCode ?? context.exitCode ?? "",
81114
+ closeSignal: context.closeSignal ?? "",
81115
+ timedOut: String(context.timedOut),
81116
+ aiSessionId: context.aiSessionId ?? "",
81117
+ aiLogFileHash: stableHash2((0, import_node_path14.basename)(context.logPath))
81118
+ }).filter(([, value]) => value !== "");
81119
+ return entries.reduce((out, [key, value]) => {
81120
+ out[key] = String(value);
81121
+ return out;
81122
+ }, {});
81123
+ }
80870
81124
  function safeProcessCwd() {
80871
81125
  try {
80872
81126
  return process.cwd();
@@ -81995,8 +82249,10 @@ var init_ai_runner = __esm({
81995
82249
  init_file_store();
81996
82250
  init_ai_provider();
81997
82251
  init_ai_adapter();
82252
+ init_task_config();
81998
82253
  init_session_store();
81999
82254
  init_user_attention_ipc();
82255
+ init_sentry_logger();
82000
82256
  AiRunner = class {
82001
82257
  homeDir;
82002
82258
  logsDir;
@@ -82257,9 +82513,9 @@ var init_ai_runner = __esm({
82257
82513
  }, 5e3).unref();
82258
82514
  }, timeoutMs);
82259
82515
  timeout.unref();
82260
- const closeResult = await new Promise((resolve5, reject) => {
82516
+ const closeResult = await new Promise((resolve6, reject) => {
82261
82517
  child.once("error", reject);
82262
- child.once("close", (code2, signal) => resolve5({ code: code2, signal }));
82518
+ child.once("close", (code2, signal) => resolve6({ code: code2, signal }));
82263
82519
  });
82264
82520
  clearTimeout(timeout);
82265
82521
  const exitCode = closeResult.code;
@@ -82278,8 +82534,8 @@ var init_ai_runner = __esm({
82278
82534
  const sessionWriteEndedAt = Date.now();
82279
82535
  const sessionWriteMs = sessionWriteEndedAt - sessionWriteStartedAt;
82280
82536
  const logFileCloseStartedAt = Date.now();
82281
- await new Promise((resolve5) => {
82282
- log.end(resolve5);
82537
+ await new Promise((resolve6) => {
82538
+ log.end(resolve6);
82283
82539
  });
82284
82540
  const logFileCloseEndedAt = Date.now();
82285
82541
  const totalMs = logFileCloseEndedAt - triggeredAt;
@@ -82313,6 +82569,27 @@ var init_ai_runner = __esm({
82313
82569
  console.error(
82314
82570
  `[okx-agent-task] ${label} done ${target} provider=${provider} exitCode=${exitCode ?? "null"} signal=${closeResult.signal ?? "none"} timeout=${timedOut ? "yes" : "no"} aiSession=${shortenValue2(aiSessionId)} cli=${cliMs}ms sessionWrite=${sessionWriteMs}ms total=${totalMs}ms result=${summarizeAiOutput(stdoutText, stderrText)}`
82315
82571
  );
82572
+ const aiFailureExtra = (reason) => aiRunSentryExtra({
82573
+ source: request.source,
82574
+ sessionKey: request.sessionKey,
82575
+ jobId: request.jobId,
82576
+ agentId: request.agentId,
82577
+ messageId: request.messageId,
82578
+ provider,
82579
+ reason,
82580
+ stage: "run_ai",
82581
+ timeoutMs,
82582
+ exitCode,
82583
+ closeSignal: closeResult.signal,
82584
+ timedOut,
82585
+ aiSessionId,
82586
+ logPath,
82587
+ queueWaitMs,
82588
+ cliMs,
82589
+ totalMs,
82590
+ timeToFirstStdoutMs: firstStdoutAt === null ? null : firstStdoutAt - spawnedAt,
82591
+ timeToFirstStderrMs: firstStderrAt === null ? null : firstStderrAt - spawnedAt
82592
+ });
82316
82593
  await this.appendLlmLog({
82317
82594
  type: "ai-output",
82318
82595
  source: request.source,
@@ -82379,6 +82656,11 @@ var init_ai_runner = __esm({
82379
82656
  return this.runAi(request, enqueuedAt, triggeredAt, true);
82380
82657
  }
82381
82658
  if (timedOut) {
82659
+ logger.error(
82660
+ LogEvent.AI_RUN_TIMEOUT,
82661
+ new Error(`${provider} AI run timed out after ${timeoutMs}ms`),
82662
+ aiFailureExtra("timeout")
82663
+ );
82382
82664
  throw buildAiRunFailureError(formatAiCliFailure({
82383
82665
  provider,
82384
82666
  target: this.formatRunTarget(request),
@@ -82389,6 +82671,11 @@ var init_ai_runner = __esm({
82389
82671
  }), runFailureContext);
82390
82672
  }
82391
82673
  if (!aiSessionId) {
82674
+ logger.error(
82675
+ LogEvent.AI_RUN_FAILED,
82676
+ new Error(`${provider} AI run did not emit a session id`),
82677
+ aiFailureExtra("missing_ai_session_id")
82678
+ );
82392
82679
  throw buildAiRunFailureError(formatAiCliFailure({
82393
82680
  provider,
82394
82681
  target: this.formatRunTarget(request),
@@ -82399,6 +82686,11 @@ var init_ai_runner = __esm({
82399
82686
  }), runFailureContext);
82400
82687
  }
82401
82688
  if (exitCode !== 0) {
82689
+ logger.error(
82690
+ LogEvent.AI_RUN_FAILED,
82691
+ new Error(`${provider} AI CLI exited with code ${exitCode}`),
82692
+ aiFailureExtra("non_zero_exit")
82693
+ );
82402
82694
  throw buildAiRunFailureError(formatAiCliFailure({
82403
82695
  provider,
82404
82696
  target: this.formatRunTarget(request),
@@ -82540,6 +82832,7 @@ var init_ai_runner = __esm({
82540
82832
  }, aiSessionId, cwd);
82541
82833
  }
82542
82834
  buildRunArgs(provider, request, aiSessionId, cwd = this.resolveAiWorkingDir()) {
82835
+ const permissionPreset = this.resolveAiPermissionPresetForRun();
82543
82836
  const prompt = provider === "codex" ? buildCodexToolFailureContractPrompt(request.prompt) : request.prompt;
82544
82837
  if (provider === "claude") {
82545
82838
  return buildAiAdapterCommand({
@@ -82548,11 +82841,12 @@ var init_ai_runner = __esm({
82548
82841
  sessionId: aiSessionId,
82549
82842
  sessionKey: request.sessionKey,
82550
82843
  homeDir: this.homeDir,
82551
- cwd
82844
+ cwd,
82845
+ permissionPreset
82552
82846
  }).args;
82553
82847
  }
82554
82848
  if (provider === "codex") {
82555
- const commonPrefix = [...buildCodexPermissionPrefix(this.homeDir, cwd, process.env), "exec"];
82849
+ const commonPrefix = [...buildCodexPermissionPrefix(this.homeDir, cwd, process.env, permissionPreset), "exec"];
82556
82850
  const outputSchemaPath = ensureCodexToolFailureOutputSchema(this.homeDir);
82557
82851
  if (aiSessionId) {
82558
82852
  return [
@@ -82581,9 +82875,16 @@ var init_ai_runner = __esm({
82581
82875
  sessionId: aiSessionId,
82582
82876
  sessionKey: request.sessionKey,
82583
82877
  homeDir: this.homeDir,
82584
- cwd
82878
+ cwd,
82879
+ permissionPreset
82585
82880
  }).args;
82586
82881
  }
82882
+ resolveAiPermissionPresetForRun() {
82883
+ if (process.env.OKX_A2A_AI_PERMISSION_PRESET || process.env.OKX_AGENT_TASK_AI_PERMISSION_PRESET) {
82884
+ return resolveAiPermissionPreset({ homeDir: this.homeDir, env: process.env });
82885
+ }
82886
+ return this.sessionStore.getAiBypassEnabled() ? "bypass" : "auto";
82887
+ }
82587
82888
  resolveAiWorkingDir() {
82588
82889
  const candidates = [
82589
82890
  process.env.OKX_A2A_AI_CWD,
@@ -82662,11 +82963,36 @@ var init_ai_runner = __esm({
82662
82963
  });
82663
82964
  await notifyUserAttentionChanged(this.homeDir);
82664
82965
  } catch (attentionErr) {
82966
+ logger.error(
82967
+ LogEvent.AI_RUN_FAILED,
82968
+ attentionErr instanceof Error ? attentionErr : new Error(String(attentionErr)),
82969
+ aiRunSentryExtra({
82970
+ source: request.source,
82971
+ sessionKey: request.sessionKey,
82972
+ jobId: request.jobId,
82973
+ agentId: request.agentId,
82974
+ messageId: request.messageId,
82975
+ provider: runContext?.provider ?? safeResolveAiProviderForDispatch(this.sessionStore, request.sessionKey),
82976
+ reason: "user_attention_create_failed",
82977
+ stage: "record_run_failure",
82978
+ logPath: runContext?.logPath
82979
+ })
82980
+ );
82665
82981
  console.error("[okx-agent-task] failed to create user_attention for AI run failure:", attentionErr);
82666
82982
  }
82667
82983
  }
82668
82984
  async reportAiToolFailures(failures, context) {
82669
82985
  for (const failure of failures.filter(isReportableAiToolFailure)) {
82986
+ const toolExtra = aiRunToolFailureSentryExtra(failure, context);
82987
+ logger.error(
82988
+ LogEvent.AI_RUN_TOOL_FAILED,
82989
+ new Error(`${failure.provider} AI tool failure: ${failure.tool} ${failure.errorType}`),
82990
+ {
82991
+ ...toolExtra,
82992
+ stage: "tool_failure_detected",
82993
+ reason: "tool_failure"
82994
+ }
82995
+ );
82670
82996
  try {
82671
82997
  const decision = buildAiToolFailureDecision({
82672
82998
  failure,
@@ -82694,6 +83020,15 @@ var init_ai_runner = __esm({
82694
83020
  });
82695
83021
  await notifyUserAttentionChanged(this.homeDir);
82696
83022
  } catch (attentionErr) {
83023
+ logger.error(
83024
+ LogEvent.AI_RUN_TOOL_FAILED,
83025
+ attentionErr instanceof Error ? attentionErr : new Error(String(attentionErr)),
83026
+ {
83027
+ ...toolExtra,
83028
+ stage: "tool_failure_user_attention",
83029
+ reason: "user_attention_create_failed"
83030
+ }
83031
+ );
82697
83032
  console.error("[okx-agent-task] failed to create user_attention for AI tool failure:", attentionErr);
82698
83033
  }
82699
83034
  }
@@ -82762,6 +83097,37 @@ var init_ai_runner = __esm({
82762
83097
  });
82763
83098
 
82764
83099
  // src/command-processor.ts
83100
+ function commandSentryExtra(command, extra = {}) {
83101
+ const base3 = {
83102
+ component: "node_command_processor",
83103
+ commandId: command.id,
83104
+ type: command.type,
83105
+ createdAt: command.createdAt,
83106
+ ...extra
83107
+ };
83108
+ if (isAiDispatchCommand(command)) {
83109
+ base3.kind = command.kind;
83110
+ base3.jobId = command.jobId ?? "";
83111
+ base3.messageId = command.messageId ?? "";
83112
+ if (command.kind === "session-message") {
83113
+ base3.agentId = command.agentId ?? "";
83114
+ base3.sessionKey = command.sessionKey;
83115
+ } else {
83116
+ base3.agentId = command.sessionAgentId ?? "";
83117
+ }
83118
+ } else if (command.type === "xmtp-send") {
83119
+ base3.jobId = command.jobId;
83120
+ base3.myAgentId = command.myAgentId ?? "";
83121
+ base3.toAgentId = command.toAgentId ?? "";
83122
+ base3.toXmtpAddress = command.toXmtpAddress ?? "";
83123
+ } else if (command.type === "xmtp-deny-pending-conversation") {
83124
+ base3.groupId = command.groupId;
83125
+ base3.agentId = command.agentId ?? "";
83126
+ }
83127
+ return Object.fromEntries(
83128
+ Object.entries(base3).filter(([, value]) => value !== void 0 && value !== null).map(([key, value]) => [key, String(value)])
83129
+ );
83130
+ }
82765
83131
  function startCommandProcessor(params) {
82766
83132
  const commands = new CommandStore(params.homeDir);
82767
83133
  const aiRunner = params.aiRunner ?? new AiRunner(params.homeDir, params.store, params.sessionStore);
@@ -82794,6 +83160,12 @@ function startCommandProcessor(params) {
82794
83160
  ok: false,
82795
83161
  error: message
82796
83162
  });
83163
+ logger.error(LogEvent.DAEMON_COMMAND_STALE, new Error(message), commandSentryExtra(command, {
83164
+ stage: "pending",
83165
+ ageMs: Date.now() - command.createdAt,
83166
+ timeoutMs: staleTimeoutMs,
83167
+ reason: "pending_expired"
83168
+ }));
82797
83169
  console.log(
82798
83170
  `[okx-agent-task] ${command.type} command expired id=${command.id}: ${message}`
82799
83171
  );
@@ -82817,6 +83189,16 @@ function startCommandProcessor(params) {
82817
83189
  ok: false,
82818
83190
  error: message
82819
83191
  });
83192
+ const isTimeout = /timed out|timeout/i.test(message);
83193
+ logger.error(
83194
+ isTimeout ? LogEvent.DAEMON_COMMAND_TIMEOUT : LogEvent.DAEMON_COMMAND_FAILED,
83195
+ err2 instanceof Error ? err2 : new Error(message),
83196
+ commandSentryExtra(command, {
83197
+ stage: "execute",
83198
+ reason: isTimeout ? "execution_timeout" : "execution_error",
83199
+ timeoutMs: executionTimeoutMs
83200
+ })
83201
+ );
82820
83202
  if (command.type === "xmtp-send") {
82821
83203
  await notifyCommandFailure(params, command, message);
82822
83204
  }
@@ -82826,6 +83208,15 @@ function startCommandProcessor(params) {
82826
83208
  }
82827
83209
  }
82828
83210
  } catch (err2) {
83211
+ logger.error(
83212
+ LogEvent.DAEMON_TICK_FAILED,
83213
+ err2 instanceof Error ? err2 : new Error(String(err2)),
83214
+ {
83215
+ component: "node_command_processor",
83216
+ stage: "non_ai_tick",
83217
+ reason: "tick_exception"
83218
+ }
83219
+ );
82829
83220
  console.log("[okx-agent-task] command processor tick failed:", err2);
82830
83221
  } finally {
82831
83222
  inFlight = false;
@@ -82858,6 +83249,12 @@ function startCommandProcessor(params) {
82858
83249
  ok: false,
82859
83250
  error: message
82860
83251
  });
83252
+ logger.error(LogEvent.DAEMON_COMMAND_STALE, new Error(message), commandSentryExtra(command, {
83253
+ stage: "pending",
83254
+ ageMs: Date.now() - command.createdAt,
83255
+ timeoutMs: aiStaleTimeoutMs,
83256
+ reason: "pending_expired"
83257
+ }));
82861
83258
  console.log(
82862
83259
  `[okx-agent-task] ${command.type}/${command.kind} command expired id=${command.id}: ${message}`
82863
83260
  );
@@ -82872,6 +83269,15 @@ function startCommandProcessor(params) {
82872
83269
  void processAiDispatchCommand(command, queueKey);
82873
83270
  }
82874
83271
  } catch (err2) {
83272
+ logger.error(
83273
+ LogEvent.DAEMON_TICK_FAILED,
83274
+ err2 instanceof Error ? err2 : new Error(String(err2)),
83275
+ {
83276
+ component: "node_command_processor",
83277
+ stage: "ai_tick",
83278
+ reason: "tick_exception"
83279
+ }
83280
+ );
82875
83281
  console.log("[okx-agent-task] AI command processor tick failed:", err2);
82876
83282
  } finally {
82877
83283
  aiScanInFlight = false;
@@ -82888,6 +83294,15 @@ function startCommandProcessor(params) {
82888
83294
  ok: false,
82889
83295
  error: message
82890
83296
  });
83297
+ const isTimeout = /timed out|timeout/i.test(message);
83298
+ logger.error(
83299
+ isTimeout ? LogEvent.AI_RUN_TIMEOUT : LogEvent.AI_RUN_FAILED,
83300
+ err2 instanceof Error ? err2 : new Error(message),
83301
+ commandSentryExtra(command, {
83302
+ stage: "ai_execute",
83303
+ reason: isTimeout ? "ai_timeout" : "ai_error"
83304
+ })
83305
+ );
82891
83306
  console.log(
82892
83307
  `[okx-agent-task] ${command.type}/${command.kind} command failed id=${command.id}: ${message}`
82893
83308
  );
@@ -83051,6 +83466,12 @@ async function failStaleProcessing(commands, params, staleTimeoutMs, aiStaleTime
83051
83466
  ok: false,
83052
83467
  error: message
83053
83468
  });
83469
+ logger.error(LogEvent.DAEMON_COMMAND_STALE, new Error(message), commandSentryExtra(entry.command, {
83470
+ stage: "processing",
83471
+ ageMs,
83472
+ timeoutMs,
83473
+ reason: "processing_recovered_stale"
83474
+ }));
83054
83475
  if (entry.command.type === "xmtp-send") {
83055
83476
  await notifyCommandFailure(params, entry.command, message);
83056
83477
  }
@@ -83158,6 +83579,7 @@ var init_command_processor = __esm({
83158
83579
  init_ai_runner();
83159
83580
  init_session_store();
83160
83581
  init_user_attention_ipc();
83582
+ init_sentry_logger();
83161
83583
  DEFAULT_COMMAND_EXECUTION_TIMEOUT_MS = 5e4;
83162
83584
  DEFAULT_COMMAND_STALE_TIMEOUT_MS = 12e4;
83163
83585
  DEFAULT_AI_COMMAND_STALE_TIMEOUT_MS = 30 * 6e4;
@@ -83982,6 +84404,41 @@ var init_message_handler = __esm({
83982
84404
  });
83983
84405
 
83984
84406
  // src/user-attention-watchers.ts
84407
+ function createUserAttentionWatchParentMonitor(options = {}) {
84408
+ const parentPid = options.parentPid ?? process.ppid;
84409
+ const currentParentPid = options.currentParentPid ?? (() => process.ppid);
84410
+ const signalPid = options.signalPid ?? ((pid) => {
84411
+ process.kill(pid, 0);
84412
+ });
84413
+ return {
84414
+ parentPid,
84415
+ isAlive() {
84416
+ return isOriginalParentProcessAlive({
84417
+ parentPid,
84418
+ currentParentPid: currentParentPid(),
84419
+ signalPid
84420
+ });
84421
+ }
84422
+ };
84423
+ }
84424
+ function isOriginalParentProcessAlive(options) {
84425
+ if (!Number.isInteger(options.parentPid) || options.parentPid <= 1) {
84426
+ return false;
84427
+ }
84428
+ if (Number.isInteger(options.currentParentPid) && options.currentParentPid > 0 && options.currentParentPid !== options.parentPid) {
84429
+ return false;
84430
+ }
84431
+ try {
84432
+ options.signalPid(options.parentPid);
84433
+ return true;
84434
+ } catch (err2) {
84435
+ const code2 = err2.code;
84436
+ if (code2 === "ESRCH") {
84437
+ return false;
84438
+ }
84439
+ return true;
84440
+ }
84441
+ }
83985
84442
  function registerUserAttentionWatcher(options) {
83986
84443
  return options.store.registerUserAttentionWatcher({
83987
84444
  id: options.id ?? (0, import_node_crypto9.randomUUID)(),
@@ -84045,7 +84502,7 @@ function startUserAttentionWatcherCoordinator(options) {
84045
84502
  }
84046
84503
  };
84047
84504
  }
84048
- var import_node_crypto9, USER_ATTENTION_WATCH_REPLACED_MESSAGE, USER_ATTENTION_WATCHER_SCAN_MS, USER_ATTENTION_WATCHER_TTL_MS;
84505
+ var import_node_crypto9, USER_ATTENTION_WATCH_REPLACED_MESSAGE, USER_ATTENTION_WATCHER_SCAN_MS, USER_ATTENTION_WATCHER_TTL_MS, USER_ATTENTION_WATCH_PARENT_CHECK_MS;
84049
84506
  var init_user_attention_watchers = __esm({
84050
84507
  "src/user-attention-watchers.ts"() {
84051
84508
  "use strict";
@@ -84053,20 +84510,7 @@ var init_user_attention_watchers = __esm({
84053
84510
  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.";
84054
84511
  USER_ATTENTION_WATCHER_SCAN_MS = 500;
84055
84512
  USER_ATTENTION_WATCHER_TTL_MS = 15e3;
84056
- }
84057
- });
84058
-
84059
- // ../core/src/sentry-config.ts
84060
- var environment, SENTRY_CONFIG;
84061
- var init_sentry_config = __esm({
84062
- "../core/src/sentry-config.ts"() {
84063
- "use strict";
84064
- environment = process.env.SENTRY_ENV === "dev" ? "dev" : "prod";
84065
- SENTRY_CONFIG = {
84066
- projectName: "okx/openclaw-okx-a2a-extension",
84067
- release: "0.0.2-beta-38940d220c-260609204302",
84068
- environment
84069
- };
84513
+ USER_ATTENTION_WATCH_PARENT_CHECK_MS = 1e3;
84070
84514
  }
84071
84515
  });
84072
84516
 
@@ -84125,16 +84569,31 @@ async function runListenerWithLock(options, paths) {
84125
84569
  userAttentionEvents = await startUserAttentionEventServer({
84126
84570
  homeDir: options.homeDir,
84127
84571
  onError: (err2) => {
84572
+ logger.error(LogEvent.IPC_FAILED, err2 instanceof Error ? err2 : new Error(String(err2)), {
84573
+ component: "node_listener",
84574
+ stage: "user_attention_ipc_wake",
84575
+ reason: "server_error"
84576
+ });
84128
84577
  console.log("[okx-agent-task] user_attention IPC wake error:", err2);
84129
84578
  }
84130
84579
  });
84131
84580
  console.log(`[okx-agent-task] user_attention IPC wake listening at ${userAttentionEvents.path}`);
84132
84581
  } catch (err2) {
84582
+ logger.error(LogEvent.IPC_FAILED, err2 instanceof Error ? err2 : new Error(String(err2)), {
84583
+ component: "node_listener",
84584
+ stage: "user_attention_ipc_start",
84585
+ reason: "start_failed"
84586
+ });
84133
84587
  console.log("[okx-agent-task] failed to start user_attention IPC wake; watchers will use polling fallback:", err2);
84134
84588
  }
84135
84589
  const watcherCoordinator = startUserAttentionWatcherCoordinator({
84136
84590
  store: sessionStore,
84137
84591
  onError: (err2) => {
84592
+ logger.error(LogEvent.IPC_FAILED, err2 instanceof Error ? err2 : new Error(String(err2)), {
84593
+ component: "node_listener",
84594
+ stage: "user_attention_watcher",
84595
+ reason: "watcher_error"
84596
+ });
84138
84597
  console.log("[okx-agent-task] user_attention watcher coordinator error:", err2);
84139
84598
  }
84140
84599
  });
@@ -84175,12 +84634,12 @@ async function runListenerWithLock(options, paths) {
84175
84634
  }));
84176
84635
  }
84177
84636
  });
84178
- service.setPluginVersion("0.0.2-beta-38940d220c-260609204302");
84637
+ service.setPluginVersion("0.0.4");
84179
84638
  await service.init();
84180
84639
  const pluginVersionStatus = service.pluginVersionStatus;
84181
84640
  if (pluginVersionStatus.unavailable) {
84182
84641
  throw new Error(
84183
- `@okxweb3/a2a-node v${"0.0.2-beta-38940d220c-260609204302"} is below the required minimum v${pluginVersionStatus.minVersion}`
84642
+ `@okxweb3/a2a-node v${"0.0.4"} is below the required minimum v${pluginVersionStatus.minVersion}`
84184
84643
  );
84185
84644
  }
84186
84645
  const systemConfig = service.getSystemConfig();
@@ -84198,7 +84657,7 @@ async function runListenerWithLock(options, paths) {
84198
84657
  onchainosAgentId: "*",
84199
84658
  reason: "system-config missing sentryDsn",
84200
84659
  pluginId: "@okxweb3/a2a-node",
84201
- pluginVersion: "0.0.2-beta-38940d220c-260609204302"
84660
+ pluginVersion: "0.0.4"
84202
84661
  });
84203
84662
  }
84204
84663
  console.log(
@@ -84228,9 +84687,22 @@ async function runListenerWithLock(options, paths) {
84228
84687
  const heartbeatMs = heartbeatResult.durationMs;
84229
84688
  const replayMs = replayResult.durationMs;
84230
84689
  if (shouldHeartbeat && heartbeatResult.error) {
84690
+ logger.error(LogEvent.HEARTBEAT_FAILED, heartbeatResult.error instanceof Error ? heartbeatResult.error : new Error(String(heartbeatResult.error)), {
84691
+ component: "node_listener",
84692
+ stage: "sync_tick",
84693
+ durationMs: String(heartbeatMs),
84694
+ chainIndex: ONCHAINOS_CHAIN_INDEX,
84695
+ communicationClass: "onchainos_or_network"
84696
+ });
84231
84697
  console.log(`[okx-agent-task] heartbeat failed duration=${heartbeatMs}ms:`, heartbeatResult.error);
84232
84698
  }
84233
84699
  if (shouldReplay && replayResult.error) {
84700
+ logger.error(LogEvent.OFFLINE_REPLAY_FAILED, replayResult.error instanceof Error ? replayResult.error : new Error(String(replayResult.error)), {
84701
+ component: "node_listener",
84702
+ stage: "sync_tick",
84703
+ durationMs: String(replayMs),
84704
+ communicationClass: "xmtp_replay_or_storage"
84705
+ });
84234
84706
  console.log(`[okx-agent-task] offline replay failed duration=${replayMs}ms:`, replayResult.error);
84235
84707
  }
84236
84708
  const replaySummary = shouldReplay ? replayResult.value : void 0;
@@ -84238,6 +84710,12 @@ async function runListenerWithLock(options, paths) {
84238
84710
  `[okx-agent-task] sync tick agents=${refresh.agentCount} changed=${refresh.changed ? "yes" : "no"} added=${refresh.added.length} removed=${refresh.removed.length} replayed=${replaySummary?.replayed ?? 0}`
84239
84711
  );
84240
84712
  } catch (err2) {
84713
+ logger.error(LogEvent.DAEMON_TICK_FAILED, err2 instanceof Error ? err2 : new Error(String(err2)), {
84714
+ component: "node_listener",
84715
+ stage: "sync_tick",
84716
+ durationMs: String(Date.now() - tickStartedAt),
84717
+ reason: "sync_tick_exception"
84718
+ });
84241
84719
  console.log(`[okx-agent-task] sync tick failed total=${Date.now() - tickStartedAt}ms:`, err2);
84242
84720
  } finally {
84243
84721
  syncInFlight = false;
@@ -84277,6 +84755,11 @@ async function runListenerWithLock(options, paths) {
84277
84755
  scheduleSyncTimer(nextIntervalSec);
84278
84756
  }
84279
84757
  } catch (err2) {
84758
+ logger.error(LogEvent.CONFIG_LOAD_FAILED, err2 instanceof Error ? err2 : new Error(String(err2)), {
84759
+ component: "node_listener",
84760
+ stage: "system_config_refresh",
84761
+ reason: "refresh_failed"
84762
+ });
84280
84763
  console.log("[okx-agent-task] system-config refresh failed:", err2);
84281
84764
  }
84282
84765
  };
@@ -84291,8 +84774,8 @@ async function runListenerWithLock(options, paths) {
84291
84774
  sessionStore,
84292
84775
  homeDir: options.homeDir
84293
84776
  });
84294
- await new Promise((resolve5) => {
84295
- const shutdown = (signal) => {
84777
+ await new Promise((resolve6) => {
84778
+ const shutdown2 = (signal) => {
84296
84779
  if (stopping) {
84297
84780
  return;
84298
84781
  }
@@ -84300,7 +84783,7 @@ async function runListenerWithLock(options, paths) {
84300
84783
  console.log(`[okx-agent-task] received ${signal}, stopping listener`);
84301
84784
  const forceResolve = setTimeout(() => {
84302
84785
  console.log("[okx-agent-task] listener shutdown timed out; forcing process exit");
84303
- resolve5();
84786
+ resolve6();
84304
84787
  }, SHUTDOWN_FORCE_RESOLVE_MS);
84305
84788
  void (async () => {
84306
84789
  if (timer) {
@@ -84312,16 +84795,21 @@ async function runListenerWithLock(options, paths) {
84312
84795
  try {
84313
84796
  await userAttentionEvents?.close();
84314
84797
  } catch (err2) {
84798
+ logger.error(LogEvent.IPC_FAILED, err2 instanceof Error ? err2 : new Error(String(err2)), {
84799
+ component: "node_listener",
84800
+ stage: "user_attention_ipc_close",
84801
+ reason: "close_failed"
84802
+ });
84315
84803
  console.log("[okx-agent-task] failed to close user_attention IPC wake:", err2);
84316
84804
  }
84317
84805
  stopClients(service);
84318
84806
  sessionStore.close();
84319
84807
  clearTimeout(forceResolve);
84320
- resolve5();
84808
+ resolve6();
84321
84809
  })();
84322
84810
  };
84323
- process.once("SIGTERM", shutdown);
84324
- process.once("SIGINT", shutdown);
84811
+ process.once("SIGTERM", shutdown2);
84812
+ process.once("SIGINT", shutdown2);
84325
84813
  });
84326
84814
  }
84327
84815
  async function timeSettled(fn) {
@@ -84517,9 +85005,17 @@ async function uploadFile(params) {
84517
85005
  params.agentId,
84518
85006
  "--job-id",
84519
85007
  params.jobId
84520
- ]);
85008
+ ], "file-upload", {
85009
+ agentId: params.agentId,
85010
+ jobId: params.jobId
85011
+ });
84521
85012
  const res = parseCliJson2(stdout, "file-upload");
84522
85013
  if (!res.ok || !res.data?.fileKey) {
85014
+ logger.error(LogEvent.FILE_UPLOAD_FAILED, new Error("onchainos file-upload ok=false"), fileCliSentryExtra("file-upload", "ok_false", {
85015
+ agentId: params.agentId,
85016
+ jobId: params.jobId,
85017
+ responseBytes: String(Buffer.byteLength(stdout, "utf8"))
85018
+ }));
84523
85019
  throw new Error(`file upload failed: ${stdout}`);
84524
85020
  }
84525
85021
  console.log(JSON.stringify({
@@ -84552,9 +85048,17 @@ async function downloadFile(params) {
84552
85048
  params.agentId,
84553
85049
  "--output",
84554
85050
  encryptedPath
84555
- ]);
85051
+ ], "file-download", {
85052
+ agentId: params.agentId,
85053
+ fileKey: params.fileKey
85054
+ });
84556
85055
  const res = parseCliJson2(stdout, "file-download");
84557
85056
  if (!res.ok) {
85057
+ logger.error(LogEvent.FILE_DOWNLOAD_FAILED, new Error("onchainos file-download ok=false"), fileCliSentryExtra("file-download", "ok_false", {
85058
+ agentId: params.agentId,
85059
+ fileKey: params.fileKey,
85060
+ responseBytes: String(Buffer.byteLength(stdout, "utf8"))
85061
+ }));
84558
85062
  throw new Error(`file download failed: ${stdout}`);
84559
85063
  }
84560
85064
  const payload = new Uint8Array((0, import_node_fs12.readFileSync)(encryptedPath));
@@ -84596,7 +85100,7 @@ async function decryptAttachmentPayload(payload, params) {
84596
85100
  function toArrayBuffer(bytes) {
84597
85101
  return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
84598
85102
  }
84599
- function runOnchainos(args) {
85103
+ function runOnchainos(args, operation, extra = {}) {
84600
85104
  const command = readCommand("ONCHAINOS_BIN", "onchainos");
84601
85105
  const [bin, ...prefix] = command;
84602
85106
  const result = (0, import_node_child_process5.spawnSync)(bin, [...prefix, ...args], {
@@ -84604,9 +85108,21 @@ function runOnchainos(args) {
84604
85108
  env: process.env
84605
85109
  });
84606
85110
  if (result.error) {
85111
+ logger.error(LogEvent.ONCHAINOS_CLI_ERROR, result.error, fileCliSentryExtra(operation, "exec_error", {
85112
+ ...extra,
85113
+ cliErrorName: result.error.name,
85114
+ cliErrorMessageLength: String(result.error.message.length)
85115
+ }));
84607
85116
  throw result.error;
84608
85117
  }
84609
85118
  if (result.status !== 0) {
85119
+ logger.error(LogEvent.ONCHAINOS_CLI_ERROR, new Error("onchainos command failed"), fileCliSentryExtra(operation, "non_zero_exit", {
85120
+ ...extra,
85121
+ exitCode: String(result.status ?? ""),
85122
+ signal: String(result.signal ?? ""),
85123
+ stdoutBytes: String(Buffer.byteLength(result.stdout ?? "", "utf8")),
85124
+ stderrBytes: String(Buffer.byteLength(result.stderr ?? "", "utf8"))
85125
+ }));
84610
85126
  throw new Error([
84611
85127
  `${[bin, ...prefix, ...args].join(" ")} exited with code ${result.status}`,
84612
85128
  result.stdout ? `stdout:
@@ -84630,6 +85146,9 @@ function parseCliJson2(stdout, label) {
84630
85146
  } catch {
84631
85147
  }
84632
85148
  }
85149
+ logger.error(LogEvent.ONCHAINOS_CLI_ERROR, new Error(`${label} returned non-JSON output`), fileCliSentryExtra(label, "json_parse_failed", {
85150
+ responseBytes: String(Buffer.byteLength(stdout, "utf8"))
85151
+ }));
84633
85152
  throw new Error(`${label} returned non-JSON output:
84634
85153
  ${trimmed}`);
84635
85154
  }
@@ -84651,7 +85170,7 @@ function readUploadSystemConfig() {
84651
85170
  return parseUploadSystemConfig(cached);
84652
85171
  }
84653
85172
  try {
84654
- const stdout = runOnchainos(["agent", "system-config"]);
85173
+ const stdout = runOnchainos(["agent", "system-config"], "system-config");
84655
85174
  const res = parseCliJson2(stdout, "system-config");
84656
85175
  if (res.data && typeof res.data === "object") {
84657
85176
  ensureA2aTaskDir(OKX_A2A_PATHS.xmtpDir);
@@ -84665,6 +85184,17 @@ function readUploadSystemConfig() {
84665
85184
  };
84666
85185
  }
84667
85186
  }
85187
+ function fileCliSentryExtra(operation, reason, extra = {}) {
85188
+ return {
85189
+ component: "node_file_cli",
85190
+ source: "direct_cli",
85191
+ stage: reason,
85192
+ operation,
85193
+ reason,
85194
+ communicationClass: "onchainos_cli_or_api_issue",
85195
+ ...extra
85196
+ };
85197
+ }
84668
85198
  function readSystemConfigFromCache() {
84669
85199
  try {
84670
85200
  if (!(0, import_node_fs12.existsSync)(SYSTEM_CONFIG_PATH)) {
@@ -84854,6 +85384,7 @@ async function watchUserAttentionLoop(store, parsed, json, options = {}) {
84854
85384
  const pollMs = readNumberOption(parsed, "poll-ms") ?? 500;
84855
85385
  const deadline = timeoutMs > 0 ? Date.now() + timeoutMs : null;
84856
85386
  const wake = createWakeSignal();
85387
+ const parentMonitor = createUserAttentionWatchParentMonitor();
84857
85388
  const subscription = await subscribeUserAttentionEvents({
84858
85389
  homeDir: store.homeDir,
84859
85390
  onChange: wake.trigger,
@@ -84873,6 +85404,9 @@ async function watchUserAttentionLoop(store, parsed, json, options = {}) {
84873
85404
  }
84874
85405
  try {
84875
85406
  while (true) {
85407
+ if (!parentMonitor.isAlive()) {
85408
+ return;
85409
+ }
84876
85410
  const batch = store.consumeUnseenUserAttentionForWatch(
84877
85411
  options.jobId ? { jobId: options.jobId } : void 0
84878
85412
  );
@@ -84889,7 +85423,7 @@ async function watchUserAttentionLoop(store, parsed, json, options = {}) {
84889
85423
  process.exitCode = 4;
84890
85424
  return;
84891
85425
  }
84892
- const waitMs = deadline ? Math.max(0, Math.min(pollMs, deadline - Date.now())) : pollMs;
85426
+ const waitMs = deadline ? Math.max(0, Math.min(pollMs, USER_ATTENTION_WATCH_PARENT_CHECK_MS, deadline - Date.now())) : Math.min(pollMs, USER_ATTENTION_WATCH_PARENT_CHECK_MS);
84893
85427
  await wake.wait(waitMs);
84894
85428
  }
84895
85429
  } finally {
@@ -84906,6 +85440,7 @@ async function watchUserAttentionViaDaemon(store, parsed, json, options) {
84906
85440
  });
84907
85441
  let watcher = registration.watcher;
84908
85442
  let nextHeartbeatAt = 0;
85443
+ const parentMonitor = createUserAttentionWatchParentMonitor();
84909
85444
  if (!json) {
84910
85445
  process.stderr.write(
84911
85446
  `Watching user_attention table at ${store.dbPath}; daemon coordinator job=${options.jobId ?? "(global)"}.
@@ -84915,6 +85450,9 @@ async function watchUserAttentionViaDaemon(store, parsed, json, options) {
84915
85450
  const watcherCleanup = installWatcherProcessCleanup(store, () => watcher);
84916
85451
  try {
84917
85452
  while (true) {
85453
+ if (!parentMonitor.isAlive()) {
85454
+ return;
85455
+ }
84918
85456
  const event = readUserAttentionWatcherEvent(store, watcher.id);
84919
85457
  if (event) {
84920
85458
  outputWatcherEvent(json, event);
@@ -84933,7 +85471,7 @@ async function watchUserAttentionViaDaemon(store, parsed, json, options) {
84933
85471
  watcher = heartbeatUserAttentionWatcher(store, watcher);
84934
85472
  nextHeartbeatAt = Date.now() + Math.min(1e3, Math.max(100, pollMs));
84935
85473
  }
84936
- const waitMs = deadline ? Math.max(0, Math.min(pollMs, deadline - Date.now())) : pollMs;
85474
+ const waitMs = deadline ? Math.max(0, Math.min(pollMs, USER_ATTENTION_WATCH_PARENT_CHECK_MS, deadline - Date.now())) : Math.min(pollMs, USER_ATTENTION_WATCH_PARENT_CHECK_MS);
84937
85475
  await sleep(waitMs);
84938
85476
  }
84939
85477
  } finally {
@@ -85027,16 +85565,16 @@ function createWakeSignal() {
85027
85565
  wake = null;
85028
85566
  },
85029
85567
  wait(ms) {
85030
- return new Promise((resolve5) => {
85568
+ return new Promise((resolve6) => {
85031
85569
  const timer = setTimeout(() => {
85032
85570
  if (wake === finish) {
85033
85571
  wake = null;
85034
85572
  }
85035
- resolve5();
85573
+ resolve6();
85036
85574
  }, ms);
85037
85575
  const finish = () => {
85038
85576
  clearTimeout(timer);
85039
- resolve5();
85577
+ resolve6();
85040
85578
  };
85041
85579
  wake = finish;
85042
85580
  });
@@ -85044,7 +85582,7 @@ function createWakeSignal() {
85044
85582
  };
85045
85583
  }
85046
85584
  function sleep(ms) {
85047
- return new Promise((resolve5) => setTimeout(resolve5, ms));
85585
+ return new Promise((resolve6) => setTimeout(resolve6, ms));
85048
85586
  }
85049
85587
  function output(json, payload, human) {
85050
85588
  if (json) {
@@ -85172,6 +85710,13 @@ async function handleSessionCommand(args) {
85172
85710
  if (subcommand === "create") {
85173
85711
  const input = readSessionInput(parsed);
85174
85712
  const session = store.upsertSession(input);
85713
+ logger.info(LogEvent.SESSION_CREATED, sessionCliSentryExtra("session_create", {
85714
+ sessionKey: session.sessionKey,
85715
+ jobId: session.jobId ?? "",
85716
+ myAgentId: session.myAgentId ?? "",
85717
+ toAgentId: session.toAgentId ?? "",
85718
+ groupId: session.groupId ?? ""
85719
+ }));
85175
85720
  output2(json, { ok: true, session }, `session ${session.sessionKey} saved`);
85176
85721
  return;
85177
85722
  }
@@ -85206,6 +85751,10 @@ ${file ? `messages=${file.messages.length}` : "messages unavailable"}`);
85206
85751
  if (subcommand === "delete") {
85207
85752
  const sessionKey = readRequiredOption3(parsed, "session-key");
85208
85753
  const deleted = store.deleteSession(sessionKey);
85754
+ logger.info(LogEvent.SESSION_DELETED, sessionCliSentryExtra("session_delete", {
85755
+ sessionKey,
85756
+ status: deleted ? "deleted" : "not_found"
85757
+ }));
85209
85758
  output2(json, { ok: deleted, deleted, sessionKey }, deleted ? `deleted ${sessionKey}` : `session not found: ${sessionKey}`);
85210
85759
  if (!deleted) {
85211
85760
  process.exitCode = 2;
@@ -85333,17 +85882,39 @@ async function assertDaemonRunningForAiDispatch(commandName) {
85333
85882
  if (status.capabilities.includes(DAEMON_CAPABILITY_AI_DISPATCH)) {
85334
85883
  return;
85335
85884
  }
85885
+ logger.error(LogEvent.DAEMON_COMMAND_FAILED, new Error(`${commandName} daemon missing AI dispatch support`), sessionCliSentryExtra(commandName, {
85886
+ stage: "daemon_precondition",
85887
+ reason: "daemon_missing_ai_dispatch_capability"
85888
+ }));
85336
85889
  throw new Error(
85337
85890
  `${commandName} requires a daemon with ${DAEMON_CAPABILITY_AI_DISPATCH} support. Run \`okx-a2a daemon restart\` first.`
85338
85891
  );
85339
85892
  }
85340
85893
  if (status.stale) {
85894
+ logger.error(LogEvent.DAEMON_COMMAND_STALE, new Error(`${commandName} daemon pid file stale`), sessionCliSentryExtra(commandName, {
85895
+ stage: "daemon_precondition",
85896
+ reason: "daemon_pid_stale",
85897
+ pid: String(status.pid ?? "")
85898
+ }));
85341
85899
  throw new Error(
85342
85900
  `${commandName} requires the daemon, but the pid file is stale (pid=${status.pid}). Run \`okx-a2a daemon restart\` first.`
85343
85901
  );
85344
85902
  }
85903
+ logger.error(LogEvent.DAEMON_COMMAND_FAILED, new Error(`${commandName} daemon not running`), sessionCliSentryExtra(commandName, {
85904
+ stage: "daemon_precondition",
85905
+ reason: "daemon_not_running"
85906
+ }));
85345
85907
  throw new Error(`${commandName} requires the daemon. Run \`okx-a2a daemon start\` first.`);
85346
85908
  }
85909
+ function sessionCliSentryExtra(operation, extra = {}) {
85910
+ return {
85911
+ component: "node_session_cli",
85912
+ source: "direct_cli",
85913
+ operation,
85914
+ communicationClass: "node_cli_or_daemon_issue",
85915
+ ...extra
85916
+ };
85917
+ }
85347
85918
  function readSessionInput(parsed) {
85348
85919
  const jobId = readRequiredOption3(parsed, "job-id");
85349
85920
  const myAgentId = readRequiredOption3(parsed, "my-agent-id");
@@ -85481,6 +86052,7 @@ var init_session_cli = __esm({
85481
86052
  init_daemon();
85482
86053
  init_daemon_lock();
85483
86054
  init_ai_dispatch_queue();
86055
+ init_sentry_logger();
85484
86056
  }
85485
86057
  });
85486
86058
 
@@ -85622,6 +86194,8 @@ var init_ai_cli = __esm({
85622
86194
 
85623
86195
  // src/cli.ts
85624
86196
  var import_node_child_process6 = require("node:child_process");
86197
+ var import_node_fs13 = require("node:fs");
86198
+ var import_node_os6 = require("node:os");
85625
86199
  var import_node_path17 = require("node:path");
85626
86200
  init_daemon();
85627
86201
  init_command_store();
@@ -85630,6 +86204,8 @@ init_ai_provider();
85630
86204
  init_session_store();
85631
86205
  init_paths();
85632
86206
  init_task_config();
86207
+ init_sentry_logger();
86208
+ init_sentry_config();
85633
86209
  function printUsage2() {
85634
86210
  console.log(`Usage: okx-a2a <daemon|start|restart|stop|status|run|logs|user|session|task|agent|file|ai|config|ai-provider|xmtp-send>
85635
86211
 
@@ -85657,6 +86233,8 @@ Commands:
85657
86233
  Manage pending XMTP task requests.
85658
86234
  agent refresh
85659
86235
  Refresh the listener agent list.
86236
+ agent bypass <on|off> [--json]
86237
+ Configure AI subsession bypass permissions.
85660
86238
  file <upload|download>
85661
86239
  Upload or download encrypted XMTP attachments.
85662
86240
  ai <status|exec|resume>
@@ -85709,12 +86287,12 @@ async function printDaemonStatus() {
85709
86287
  }
85710
86288
  }
85711
86289
  async function tailLogFile(logPath) {
85712
- await new Promise((resolve5, reject) => {
86290
+ await new Promise((resolve6, reject) => {
85713
86291
  const child = (0, import_node_child_process6.spawn)("tail", ["-600", "-f", logPath], { stdio: "inherit" });
85714
86292
  child.on("error", reject);
85715
86293
  child.on("close", (code2, signal) => {
85716
86294
  if (signal || code2 === 0) {
85717
- resolve5();
86295
+ resolve6();
85718
86296
  return;
85719
86297
  }
85720
86298
  reject(new Error(`tail exited with code=${code2}`));
@@ -85819,7 +86397,44 @@ async function handleAgentCommand(args) {
85819
86397
  await queueXmtpDaemonCommand(args.slice(1), "xmtp-refresh-agents");
85820
86398
  return;
85821
86399
  }
85822
- throw new Error("agent requires <refresh>");
86400
+ if (subcommand === "bypass") {
86401
+ handleAgentBypassCommand(args.slice(1));
86402
+ return;
86403
+ }
86404
+ throw new Error("agent requires <refresh|bypass>");
86405
+ }
86406
+ function handleAgentBypassCommand(args) {
86407
+ const json = hasFlag(args, "--json");
86408
+ const rawMode = readOption2(args, "--mode") ?? args.find((arg) => !arg.startsWith("--"));
86409
+ const store = new SessionStore();
86410
+ try {
86411
+ if (rawMode) {
86412
+ const enabled = parseBypassMode(rawMode);
86413
+ store.setAiBypassEnabled(enabled);
86414
+ outputAgentBypass(json, enabled);
86415
+ return;
86416
+ }
86417
+ outputAgentBypass(json, store.getAiBypassEnabled());
86418
+ } finally {
86419
+ store.close();
86420
+ }
86421
+ }
86422
+ function parseBypassMode(value) {
86423
+ const normalized = value.trim().toLowerCase();
86424
+ if (normalized === "on" || normalized === "1" || normalized === "true" || normalized === "yes") {
86425
+ return true;
86426
+ }
86427
+ if (normalized === "off" || normalized === "0" || normalized === "false" || normalized === "no") {
86428
+ return false;
86429
+ }
86430
+ throw new Error("agent bypass requires <on|off>");
86431
+ }
86432
+ function outputAgentBypass(json, enabled) {
86433
+ if (json) {
86434
+ console.log(JSON.stringify({ ok: true, isBypass: enabled ? 1 : 0, bypass: enabled }));
86435
+ return;
86436
+ }
86437
+ console.log(`AI bypass permissions: ${enabled ? "on" : "off"}`);
85823
86438
  }
85824
86439
  function readRequiredOption4(args, name2) {
85825
86440
  const value = readOption2(args, name2);
@@ -85852,10 +86467,19 @@ async function assertDaemonRunningForQueuedCommand(commandName) {
85852
86467
  return;
85853
86468
  }
85854
86469
  if (status.stale) {
86470
+ logger.error(LogEvent.DAEMON_COMMAND_STALE, new Error(`${commandName} daemon pid file stale`), directCliSentryExtra(commandName, {
86471
+ stage: "daemon_precondition",
86472
+ reason: "daemon_pid_stale",
86473
+ pid: String(status.pid ?? "")
86474
+ }));
85855
86475
  throw new Error(
85856
86476
  `${commandName} requires the daemon, but the pid file is stale (pid=${status.pid}). Run \`okx-a2a daemon restart\` first.`
85857
86477
  );
85858
86478
  }
86479
+ logger.error(LogEvent.DAEMON_COMMAND_FAILED, new Error(`${commandName} daemon not running`), directCliSentryExtra(commandName, {
86480
+ stage: "daemon_precondition",
86481
+ reason: "daemon_not_running"
86482
+ }));
85859
86483
  throw new Error(`${commandName} requires the daemon. Run \`okx-a2a daemon start\` first.`);
85860
86484
  }
85861
86485
  async function configureDefaultAiProviderForLifecycle(args) {
@@ -86019,6 +86643,62 @@ function assertSupportedNodeVersion() {
86019
86643
  throw new Error(`okx-a2a requires Node.js >= 22.13.0, current=${process.version}`);
86020
86644
  }
86021
86645
  }
86646
+ var cliSentryInitAttempted = false;
86647
+ var cliSentryInitialized = false;
86648
+ function initDirectCliSentry() {
86649
+ if (cliSentryInitAttempted) {
86650
+ return;
86651
+ }
86652
+ cliSentryInitAttempted = true;
86653
+ try {
86654
+ const configPath = (0, import_node_path17.join)(resolveTaskHomeForSentryConfig(), "xmtp", "system-config.json");
86655
+ if (!(0, import_node_fs13.existsSync)(configPath)) {
86656
+ return;
86657
+ }
86658
+ const config = JSON.parse((0, import_node_fs13.readFileSync)(configPath, "utf8"));
86659
+ if (typeof config.sentryDsn !== "string" || !config.sentryDsn) {
86660
+ return;
86661
+ }
86662
+ initLogger({
86663
+ dsn: config.sentryDsn,
86664
+ ...SENTRY_CONFIG,
86665
+ agentPlatform: "node"
86666
+ });
86667
+ cliSentryInitialized = true;
86668
+ } catch {
86669
+ }
86670
+ }
86671
+ function resolveTaskHomeForSentryConfig() {
86672
+ if (process.env.OKX_AGENT_TASK_HOME) {
86673
+ return process.env.OKX_AGENT_TASK_HOME;
86674
+ }
86675
+ try {
86676
+ const home = (0, import_node_os6.homedir)();
86677
+ if (home) {
86678
+ return (0, import_node_path17.join)(home, ".okx-agent-task");
86679
+ }
86680
+ } catch {
86681
+ }
86682
+ return (0, import_node_path17.resolve)(process.cwd(), ".okx-agent-task");
86683
+ }
86684
+ function directCliSentryExtra(operation, extra = {}) {
86685
+ return {
86686
+ component: "node_direct_cli",
86687
+ source: "direct_cli",
86688
+ operation,
86689
+ communicationClass: "node_cli_or_daemon_issue",
86690
+ ...extra
86691
+ };
86692
+ }
86693
+ async function flushDirectCliSentry() {
86694
+ if (!cliSentryInitialized) {
86695
+ return;
86696
+ }
86697
+ try {
86698
+ await shutdown();
86699
+ } catch {
86700
+ }
86701
+ }
86022
86702
  async function main() {
86023
86703
  assertSupportedNodeVersion();
86024
86704
  const command = process.argv[2] ?? "status";
@@ -86073,20 +86753,28 @@ async function main() {
86073
86753
  return;
86074
86754
  }
86075
86755
  if (command === "xmtp-send") {
86756
+ initDirectCliSentry();
86076
86757
  await queueXmtpSend(process.argv.slice(3));
86758
+ await flushDirectCliSentry();
86077
86759
  return;
86078
86760
  }
86079
86761
  if (command === "task") {
86762
+ initDirectCliSentry();
86080
86763
  await handleTaskCommand(process.argv.slice(3));
86764
+ await flushDirectCliSentry();
86081
86765
  return;
86082
86766
  }
86083
86767
  if (command === "agent") {
86768
+ initDirectCliSentry();
86084
86769
  await handleAgentCommand(process.argv.slice(3));
86770
+ await flushDirectCliSentry();
86085
86771
  return;
86086
86772
  }
86087
86773
  if (command === "file") {
86774
+ initDirectCliSentry();
86088
86775
  const { handleFileCommand: handleFileCommand2 } = await Promise.resolve().then(() => (init_file_cli(), file_cli_exports));
86089
86776
  await handleFileCommand2(process.argv.slice(3));
86777
+ await flushDirectCliSentry();
86090
86778
  return;
86091
86779
  }
86092
86780
  if (command === "xmtp-get-pending-list") {
@@ -86107,13 +86795,17 @@ async function main() {
86107
86795
  return;
86108
86796
  }
86109
86797
  if (command === "session") {
86798
+ initDirectCliSentry();
86110
86799
  const { handleSessionCommand: handleSessionCommand2 } = await Promise.resolve().then(() => (init_session_cli(), session_cli_exports));
86111
86800
  await handleSessionCommand2(process.argv.slice(3));
86801
+ await flushDirectCliSentry();
86112
86802
  return;
86113
86803
  }
86114
86804
  if (command === "ai") {
86805
+ initDirectCliSentry();
86115
86806
  const { handleAiCommand: handleAiCommand2 } = await Promise.resolve().then(() => (init_ai_cli(), ai_cli_exports));
86116
86807
  await handleAiCommand2(process.argv.slice(3));
86808
+ await flushDirectCliSentry();
86117
86809
  return;
86118
86810
  }
86119
86811
  if (command === "config") {
@@ -86127,12 +86819,26 @@ async function main() {
86127
86819
  printUsage2();
86128
86820
  process.exitCode = 1;
86129
86821
  }
86130
- main().catch((err2) => {
86822
+ main().catch(async (err2) => {
86131
86823
  if (err2 instanceof UserCancelledAiProviderSelectionError) {
86132
86824
  process.exitCode = 1;
86133
86825
  return;
86134
86826
  }
86135
86827
  console.error(err2 instanceof Error ? err2.stack ?? err2.message : String(err2));
86828
+ try {
86829
+ initDirectCliSentry();
86830
+ const command = process.argv[2] ?? "status";
86831
+ const subcommand = process.argv[3] ?? "";
86832
+ logger.error(LogEvent.DIRECT_CLI_FAILED, err2 instanceof Error ? err2 : new Error(String(err2)), directCliSentryExtra(command, {
86833
+ stage: "cli_error",
86834
+ reason: err2 instanceof UserCancelledAiProviderSelectionError ? "user_cancelled" : "cli_exception",
86835
+ subcommand,
86836
+ cliErrorName: err2 instanceof Error ? err2.name : "",
86837
+ cliErrorMessageLength: String(err2 instanceof Error ? err2.message.length : String(err2).length)
86838
+ }));
86839
+ } catch {
86840
+ }
86841
+ await flushDirectCliSentry();
86136
86842
  process.exitCode = 1;
86137
86843
  });
86138
86844
  /*! Bundled license information: