@okxweb3/a2a-node 0.2.10 → 0.2.11-beta-8fef2ef558-260901171734

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/cli.js +1296 -215
  2. package/dist/index.js +16 -10
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -108,6 +108,7 @@ function resolveTaskPaths(homeDir = resolveTaskHome()) {
108
108
  workspaceDir: (0, import_node_path2.join)(homeDir, "workspace"),
109
109
  xmtpDir: (0, import_node_path2.join)(homeDir, "xmtp"),
110
110
  sqliteDir: (0, import_node_path2.join)(homeDir, "sqlite"),
111
+ bzRecordsDir: (0, import_node_path2.join)(homeDir, "bz-records"),
111
112
  pendingCommandsDir: (0, import_node_path2.join)(homeDir, "commands", "pending"),
112
113
  processingCommandsDir: (0, import_node_path2.join)(homeDir, "commands", "processing"),
113
114
  completedCommandsDir: (0, import_node_path2.join)(homeDir, "commands", "completed"),
@@ -6524,7 +6525,7 @@ var require_path = __commonJS({
6524
6525
  function isAbsolute4(path2) {
6525
6526
  return path2.charAt(0) === "/";
6526
6527
  }
6527
- function join33(...args) {
6528
+ function join34(...args) {
6528
6529
  return normalizePath(args.join("/"));
6529
6530
  }
6530
6531
  function dirname11(path2) {
@@ -6549,7 +6550,7 @@ var require_path = __commonJS({
6549
6550
  exports2.basename = basename11;
6550
6551
  exports2.dirname = dirname11;
6551
6552
  exports2.isAbsolute = isAbsolute4;
6552
- exports2.join = join33;
6553
+ exports2.join = join34;
6553
6554
  exports2.normalizePath = normalizePath;
6554
6555
  exports2.relative = relative;
6555
6556
  exports2.resolve = resolve14;
@@ -26934,7 +26935,7 @@ function buildConnectParams(config, instanceId, protocolVersion) {
26934
26935
  client: {
26935
26936
  id: "gateway-client",
26936
26937
  displayName: "okx-a2a-node",
26937
- version: "0.2.10",
26938
+ version: "0.2.11-beta-8fef2ef558-260901171734",
26938
26939
  platform: "node",
26939
26940
  mode: "backend",
26940
26941
  instanceId
@@ -26945,7 +26946,7 @@ function buildConnectParams(config, instanceId, protocolVersion) {
26945
26946
  commands: [],
26946
26947
  permissions: {},
26947
26948
  locale: Intl.DateTimeFormat().resolvedOptions().locale || "en-US",
26948
- userAgent: `okx-a2a-node/${"0.2.10"}`,
26949
+ userAgent: `okx-a2a-node/${"0.2.11-beta-8fef2ef558-260901171734"}`,
26949
26950
  auth: {
26950
26951
  ...config.token ? { token: config.token } : {},
26951
26952
  ...config.password ? { password: config.password } : {}
@@ -29004,7 +29005,7 @@ var init_sentry_config = __esm({
29004
29005
  environment = process.env.SENTRY_ENV === "dev" ? "dev" : "prod";
29005
29006
  SENTRY_CONFIG = {
29006
29007
  projectName: "okx/openclaw-okx-a2a-extension",
29007
- release: "0.2.10",
29008
+ release: "0.2.11-beta-8fef2ef558-260901171734",
29008
29009
  environment,
29009
29010
  runtimeContainer: normalizeRuntimeContainer(process.env.OKX_A2A_RUNTIME_CONTAINER)
29010
29011
  };
@@ -29293,7 +29294,7 @@ var require_BufferList = __commonJS({
29293
29294
  this.head = this.tail = null;
29294
29295
  this.length = 0;
29295
29296
  };
29296
- BufferList.prototype.join = function join33(s) {
29297
+ BufferList.prototype.join = function join34(s) {
29297
29298
  if (this.length === 0) return "";
29298
29299
  var p = this.head;
29299
29300
  var ret = "" + p.data;
@@ -39574,8 +39575,8 @@ function readSqliteRows(dbPath, sql, params = []) {
39574
39575
  if (!(0, import_node_fs17.existsSync)(dbPath)) {
39575
39576
  throw unavailable(`SQLite database not found: ${dbPath}`);
39576
39577
  }
39577
- const { DatabaseSync: DatabaseSync4 } = loadSqlite3();
39578
- const db = new DatabaseSync4(dbPath, { readOnly: true });
39578
+ const { DatabaseSync: DatabaseSync5 } = loadSqlite3();
39579
+ const db = new DatabaseSync5(dbPath, { readOnly: true });
39579
39580
  try {
39580
39581
  return db.prepare(sql).all(...params);
39581
39582
  } finally {
@@ -40174,7 +40175,7 @@ async function exportDiagnosticLogs(options) {
40174
40175
  node: process.version,
40175
40176
  platform: process.platform,
40176
40177
  arch: process.arch,
40177
- packageVersion: true ? "0.2.10" : "unknown",
40178
+ packageVersion: true ? "0.2.11-beta-8fef2ef558-260901171734" : "unknown",
40178
40179
  sensitiveContentIncluded: options.includeSensitiveContent,
40179
40180
  listenerAndLlmContentIncluded: true,
40180
40181
  credentialsAlwaysRedacted: true,
@@ -41068,6 +41069,11 @@ function getA2ACapabilities() {
41068
41069
  ok: true,
41069
41070
  fixCommands: [],
41070
41071
  message: ""
41072
+ },
41073
+ tradeRecordsV1: {
41074
+ ok: true,
41075
+ fixCommands: [],
41076
+ message: ""
41071
41077
  }
41072
41078
  };
41073
41079
  }
@@ -41097,6 +41103,1057 @@ var init_capabilities_cli = __esm({
41097
41103
  }
41098
41104
  });
41099
41105
 
41106
+ // src/trade-records-store.ts
41107
+ function resolveTradeRecordsDbPath(homeDir) {
41108
+ return (0, import_node_path24.join)(resolveTaskPaths(homeDir).bzRecordsDir, TRADE_RECORDS_DB_NAME);
41109
+ }
41110
+ function tradeRecordsDbExists(homeDir) {
41111
+ return (0, import_node_fs20.existsSync)(resolveTradeRecordsDbPath(homeDir));
41112
+ }
41113
+ function encodeTradeRecordCursor(cursor) {
41114
+ return Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url");
41115
+ }
41116
+ function decodeTradeRecordCursor(value) {
41117
+ try {
41118
+ const parsed = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
41119
+ if (parsed.version !== 1 || parsed.sortBy !== "createdAt" && parsed.sortBy !== "updatedAt" || parsed.order !== "asc" && parsed.order !== "desc" || typeof parsed.timestamp !== "number" || !Number.isSafeInteger(parsed.timestamp) || parsed.timestamp < 0 || typeof parsed.deliveryId !== "string" || parsed.deliveryId.length === 0) {
41120
+ throw new Error("invalid cursor payload");
41121
+ }
41122
+ return parsed;
41123
+ } catch {
41124
+ throw new TradeRecordsStoreError("INVALID_ARGUMENT", "--cursor is invalid");
41125
+ }
41126
+ }
41127
+ function applyMigrationV1(db) {
41128
+ db.exec(`
41129
+ CREATE TABLE ${TABLE_NAME} (
41130
+ delivery_id TEXT PRIMARY KEY,
41131
+ job_id TEXT NOT NULL,
41132
+ status TEXT NOT NULL,
41133
+ reason TEXT NOT NULL DEFAULT '',
41134
+ extra TEXT NOT NULL DEFAULT '{}',
41135
+ created_at INTEGER NOT NULL,
41136
+ updated_at INTEGER NOT NULL,
41137
+ deleted_at INTEGER,
41138
+ CHECK (length(job_id) > 0),
41139
+ CHECK (length(delivery_id) > 0),
41140
+ CHECK (length(status) > 0),
41141
+ CHECK (json_valid(extra)),
41142
+ CHECK (json_type(extra) = 'object')
41143
+ )
41144
+ `);
41145
+ db.exec(`CREATE INDEX idx_trade_records_job_updated ON ${TABLE_NAME}(job_id, updated_at DESC, delivery_id DESC)`);
41146
+ db.exec(`CREATE INDEX idx_trade_records_status_updated ON ${TABLE_NAME}(status, updated_at DESC, delivery_id DESC)`);
41147
+ db.exec(`CREATE INDEX idx_trade_records_created ON ${TABLE_NAME}(created_at DESC, delivery_id DESC)`);
41148
+ db.exec(`CREATE INDEX idx_trade_records_deleted ON ${TABLE_NAME}(deleted_at, updated_at DESC)`);
41149
+ }
41150
+ function buildWhere(filter2, includeCursor) {
41151
+ const clauses = [];
41152
+ const params = [];
41153
+ const add = (clause, ...values) => {
41154
+ clauses.push(clause);
41155
+ params.push(...values);
41156
+ };
41157
+ if (!filter2.includeDeleted) {
41158
+ add(filter2.onlyDeleted ? "deleted_at IS NOT NULL" : "deleted_at IS NULL");
41159
+ } else if (filter2.onlyDeleted) {
41160
+ add("deleted_at IS NOT NULL");
41161
+ }
41162
+ if (filter2.jobId) add("job_id = ?", filter2.jobId);
41163
+ if (filter2.deliveryId) add("delivery_id = ?", filter2.deliveryId);
41164
+ if (filter2.statuses && filter2.statuses.length > 0) {
41165
+ add(`status IN (${filter2.statuses.map(() => "?").join(", ")})`, ...filter2.statuses);
41166
+ }
41167
+ if (filter2.reason !== void 0) add("reason = ?", filter2.reason);
41168
+ if (filter2.reasonContains !== void 0) {
41169
+ add("reason LIKE ? ESCAPE '\\'", `%${escapeLike(filter2.reasonContains)}%`);
41170
+ }
41171
+ if (filter2.createdFrom !== void 0) add("created_at >= ?", filter2.createdFrom);
41172
+ if (filter2.createdTo !== void 0) add("created_at <= ?", filter2.createdTo);
41173
+ if (filter2.updatedFrom !== void 0) add("updated_at >= ?", filter2.updatedFrom);
41174
+ if (filter2.updatedTo !== void 0) add("updated_at <= ?", filter2.updatedTo);
41175
+ for (const extra of filter2.extraEquals ?? []) {
41176
+ if (extra.value === null) {
41177
+ add("json_type(extra, ?) = 'null'", extra.path);
41178
+ } else {
41179
+ add(
41180
+ "json_extract(extra, ?) = ?",
41181
+ extra.path,
41182
+ typeof extra.value === "boolean" ? extra.value ? 1 : 0 : extra.value
41183
+ );
41184
+ }
41185
+ }
41186
+ if (includeCursor && filter2.cursor) {
41187
+ const column = filter2.sortBy === "createdAt" ? "created_at" : "updated_at";
41188
+ const operator = filter2.order === "asc" ? ">" : "<";
41189
+ add(
41190
+ `(${column} ${operator} ? OR (${column} = ? AND delivery_id ${operator} ?))`,
41191
+ filter2.cursor.timestamp,
41192
+ filter2.cursor.timestamp,
41193
+ filter2.cursor.deliveryId
41194
+ );
41195
+ }
41196
+ return { clauses, params };
41197
+ }
41198
+ function mapRow(row) {
41199
+ const extra = JSON.parse(row.extra);
41200
+ if (!isJsonObject(extra)) {
41201
+ throw new TradeRecordsStoreError("DATABASE_READ_FAILED", "stored trade record extra is not a JSON object");
41202
+ }
41203
+ return {
41204
+ jobId: row.job_id,
41205
+ deliveryId: row.delivery_id,
41206
+ status: row.status,
41207
+ reason: row.reason,
41208
+ extra,
41209
+ createdAt: row.created_at,
41210
+ updatedAt: row.updated_at,
41211
+ deletedAt: row.deleted_at
41212
+ };
41213
+ }
41214
+ function isJsonObject(value) {
41215
+ return typeof value === "object" && value !== null && !Array.isArray(value);
41216
+ }
41217
+ function escapeLike(value) {
41218
+ return value.replace(/[\\%_]/g, (character) => `\\${character}`);
41219
+ }
41220
+ function readPragmaNumber(db, name) {
41221
+ const row = db.prepare(`PRAGMA ${name}`).get();
41222
+ return Number(row[name] ?? 0);
41223
+ }
41224
+ function assertNotSymlink(path2, label) {
41225
+ if (!(0, import_node_fs20.existsSync)(path2)) {
41226
+ return;
41227
+ }
41228
+ if ((0, import_node_fs20.lstatSync)(path2).isSymbolicLink()) {
41229
+ throw new TradeRecordsStoreError("DATABASE_PATH_UNSAFE", `${label} must not be a symbolic link`);
41230
+ }
41231
+ }
41232
+ function assertSafeDatabasePath(dbPath) {
41233
+ assertSafeDatabaseFile(dbPath);
41234
+ for (const suffix of ["-journal", "-wal", "-shm"]) {
41235
+ assertNotSymlink(`${dbPath}${suffix}`, `trade records database sidecar ${suffix}`);
41236
+ }
41237
+ }
41238
+ function assertSafeDatabaseFile(dbPath) {
41239
+ if (!(0, import_node_fs20.existsSync)(dbPath)) {
41240
+ return;
41241
+ }
41242
+ const stat4 = (0, import_node_fs20.lstatSync)(dbPath);
41243
+ if (stat4.isSymbolicLink()) {
41244
+ throw new TradeRecordsStoreError(
41245
+ "DATABASE_PATH_UNSAFE",
41246
+ "trade records database must not be a symbolic link"
41247
+ );
41248
+ }
41249
+ if (!stat4.isFile() || stat4.nlink !== 1) {
41250
+ throw new TradeRecordsStoreError(
41251
+ "DATABASE_PATH_UNSAFE",
41252
+ "trade records database must be a regular file with one hard link"
41253
+ );
41254
+ }
41255
+ }
41256
+ function rollbackQuietly(db) {
41257
+ try {
41258
+ db.exec("ROLLBACK");
41259
+ } catch {
41260
+ }
41261
+ }
41262
+ function withBusyRetry(operation) {
41263
+ for (let attempt = 1; ; attempt += 1) {
41264
+ try {
41265
+ return operation();
41266
+ } catch (error) {
41267
+ if (!isSqliteBusyError(error) || attempt >= WRITE_RETRY_ATTEMPTS) {
41268
+ throw error;
41269
+ }
41270
+ sleepSyncMs2(Math.min(100 * 2 ** (attempt - 1), 1600));
41271
+ }
41272
+ }
41273
+ }
41274
+ function sleepSyncMs2(ms) {
41275
+ const buffer2 = new Int32Array(new SharedArrayBuffer(4));
41276
+ Atomics.wait(buffer2, 0, 0, ms);
41277
+ }
41278
+ function loadSqlite4() {
41279
+ const originalEmitWarning = process.emitWarning;
41280
+ process.emitWarning = ((warning, ...args) => {
41281
+ const message = typeof warning === "string" ? warning : warning.message;
41282
+ if (message.includes("SQLite is an experimental feature") && args.some((arg) => arg === "ExperimentalWarning")) {
41283
+ return;
41284
+ }
41285
+ return originalEmitWarning.call(process, warning, ...args);
41286
+ });
41287
+ try {
41288
+ return require("node:sqlite");
41289
+ } finally {
41290
+ process.emitWarning = originalEmitWarning;
41291
+ }
41292
+ }
41293
+ var import_node_fs20, import_node_path24, DatabaseSync3, TRADE_RECORDS_APPLICATION_ID, TRADE_RECORDS_SCHEMA_VERSION, TRADE_RECORDS_DB_NAME, TABLE_NAME, WRITE_RETRY_ATTEMPTS, TradeRecordsStoreError, TradeRecordsStore;
41294
+ var init_trade_records_store = __esm({
41295
+ "src/trade-records-store.ts"() {
41296
+ "use strict";
41297
+ import_node_fs20 = require("node:fs");
41298
+ import_node_path24 = require("node:path");
41299
+ init_paths();
41300
+ init_session_store();
41301
+ ({ DatabaseSync: DatabaseSync3 } = loadSqlite4());
41302
+ TRADE_RECORDS_APPLICATION_ID = 1329681490;
41303
+ TRADE_RECORDS_SCHEMA_VERSION = 1;
41304
+ TRADE_RECORDS_DB_NAME = "trade-records.sqlite";
41305
+ TABLE_NAME = `"trade-records"`;
41306
+ WRITE_RETRY_ATTEMPTS = 6;
41307
+ TradeRecordsStoreError = class extends Error {
41308
+ code;
41309
+ constructor(code, message) {
41310
+ super(message);
41311
+ this.name = "TradeRecordsStoreError";
41312
+ this.code = code;
41313
+ }
41314
+ };
41315
+ TradeRecordsStore = class _TradeRecordsStore {
41316
+ dbPath;
41317
+ db;
41318
+ constructor(dbPath, db) {
41319
+ this.dbPath = dbPath;
41320
+ this.db = db;
41321
+ }
41322
+ static openForWrite(homeDir) {
41323
+ const paths = resolveTaskPaths(homeDir);
41324
+ assertNotSymlink(paths.bzRecordsDir, "trade records directory");
41325
+ ensureTaskDir(paths.bzRecordsDir);
41326
+ assertNotSymlink(paths.bzRecordsDir, "trade records directory");
41327
+ const dbPath = (0, import_node_path24.join)(paths.bzRecordsDir, TRADE_RECORDS_DB_NAME);
41328
+ assertSafeDatabasePath(dbPath);
41329
+ const db = new DatabaseSync3(dbPath);
41330
+ const store = new _TradeRecordsStore(dbPath, db);
41331
+ try {
41332
+ store.configureConnectionForWrite();
41333
+ store.ensureSchemaForWrite();
41334
+ return store;
41335
+ } catch (error) {
41336
+ db.close();
41337
+ throw error;
41338
+ }
41339
+ }
41340
+ static openForRead(homeDir) {
41341
+ const dbPath = resolveTradeRecordsDbPath(homeDir);
41342
+ if (!(0, import_node_fs20.existsSync)(dbPath)) {
41343
+ return null;
41344
+ }
41345
+ assertSafeDatabaseFile(dbPath);
41346
+ const db = new DatabaseSync3(dbPath, { readOnly: true });
41347
+ const store = new _TradeRecordsStore(dbPath, db);
41348
+ try {
41349
+ db.exec("PRAGMA query_only=ON");
41350
+ store.assertReadableSchema();
41351
+ return store;
41352
+ } catch (error) {
41353
+ db.close();
41354
+ throw error;
41355
+ }
41356
+ }
41357
+ close() {
41358
+ this.db.close();
41359
+ }
41360
+ insert(records) {
41361
+ return this.withWriteTransaction(() => {
41362
+ const existingStatement = this.db.prepare(
41363
+ `SELECT deleted_at FROM ${TABLE_NAME} WHERE delivery_id = ?`
41364
+ );
41365
+ const upsertStatement = this.db.prepare(`
41366
+ INSERT INTO ${TABLE_NAME} (
41367
+ delivery_id, job_id, status, reason, extra, created_at, updated_at, deleted_at
41368
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, NULL)
41369
+ ON CONFLICT(delivery_id) DO UPDATE SET
41370
+ job_id = excluded.job_id,
41371
+ status = excluded.status,
41372
+ reason = excluded.reason,
41373
+ extra = excluded.extra,
41374
+ updated_at = excluded.updated_at,
41375
+ deleted_at = NULL
41376
+ `);
41377
+ const now = Date.now();
41378
+ let insertedCount = 0;
41379
+ let updatedCount = 0;
41380
+ let restoredCount = 0;
41381
+ for (const record of records) {
41382
+ const existing = existingStatement.get(record.deliveryId);
41383
+ if (!existing) {
41384
+ insertedCount += 1;
41385
+ } else if (existing.deleted_at === null) {
41386
+ updatedCount += 1;
41387
+ } else {
41388
+ restoredCount += 1;
41389
+ }
41390
+ upsertStatement.run(
41391
+ record.deliveryId,
41392
+ record.jobId,
41393
+ record.status,
41394
+ record.reason,
41395
+ JSON.stringify(record.extra),
41396
+ now,
41397
+ now
41398
+ );
41399
+ }
41400
+ return { insertedCount, updatedCount, restoredCount };
41401
+ });
41402
+ }
41403
+ delete(deliveryId, jobId) {
41404
+ return this.withWriteTransaction(() => {
41405
+ const existing = this.db.prepare(`
41406
+ SELECT deleted_at FROM ${TABLE_NAME}
41407
+ WHERE delivery_id = ?${jobId ? " AND job_id = ?" : ""}
41408
+ `).get(...jobId ? [deliveryId, jobId] : [deliveryId]);
41409
+ if (!existing) {
41410
+ return { deliveryId, deleted: false, alreadyDeleted: false, notFound: true };
41411
+ }
41412
+ if (existing.deleted_at !== null) {
41413
+ return { deliveryId, deleted: false, alreadyDeleted: true, notFound: false };
41414
+ }
41415
+ const now = Date.now();
41416
+ this.db.prepare(`
41417
+ UPDATE ${TABLE_NAME}
41418
+ SET deleted_at = ?, updated_at = ?
41419
+ WHERE delivery_id = ?${jobId ? " AND job_id = ?" : ""} AND deleted_at IS NULL
41420
+ `).run(...jobId ? [now, now, deliveryId, jobId] : [now, now, deliveryId]);
41421
+ return { deliveryId, deleted: true, alreadyDeleted: false, notFound: false };
41422
+ });
41423
+ }
41424
+ query(filter2) {
41425
+ const base = buildWhere(filter2, false);
41426
+ const page = buildWhere(filter2, true);
41427
+ const sortColumn = filter2.sortBy === "createdAt" ? "created_at" : "updated_at";
41428
+ const direction = filter2.order.toUpperCase();
41429
+ const rows = this.db.prepare(`
41430
+ SELECT delivery_id, job_id, status, reason, extra, created_at, updated_at, deleted_at
41431
+ FROM ${TABLE_NAME}
41432
+ ${page.clauses.length > 0 ? `WHERE ${page.clauses.join(" AND ")}` : ""}
41433
+ ORDER BY ${sortColumn} ${direction}, delivery_id ${direction}
41434
+ LIMIT ?
41435
+ `).all(...page.params, filter2.limit + 1);
41436
+ const hasMore = rows.length > filter2.limit;
41437
+ const visibleRows = hasMore ? rows.slice(0, filter2.limit) : rows;
41438
+ const records = visibleRows.map(mapRow);
41439
+ const last = visibleRows.at(-1);
41440
+ const nextCursor = hasMore && last ? encodeTradeRecordCursor({
41441
+ version: 1,
41442
+ sortBy: filter2.sortBy,
41443
+ order: filter2.order,
41444
+ timestamp: filter2.sortBy === "createdAt" ? last.created_at : last.updated_at,
41445
+ deliveryId: last.delivery_id
41446
+ }) : null;
41447
+ let count;
41448
+ if (filter2.includeCount) {
41449
+ const row = this.db.prepare(`
41450
+ SELECT COUNT(*) AS count
41451
+ FROM ${TABLE_NAME}
41452
+ ${base.clauses.length > 0 ? `WHERE ${base.clauses.join(" AND ")}` : ""}
41453
+ `).get(...base.params);
41454
+ count = Number(row.count);
41455
+ }
41456
+ return { records, nextCursor, ...count === void 0 ? {} : { count } };
41457
+ }
41458
+ configureConnectionForWrite() {
41459
+ this.db.exec("PRAGMA busy_timeout=5000");
41460
+ }
41461
+ ensureSchemaForWrite() {
41462
+ withBusyRetry(() => {
41463
+ this.db.exec("BEGIN IMMEDIATE");
41464
+ try {
41465
+ const applicationId = readPragmaNumber(this.db, "application_id");
41466
+ const userVersion = readPragmaNumber(this.db, "user_version");
41467
+ const hasTables = Boolean(this.db.prepare(
41468
+ "SELECT 1 AS present FROM sqlite_master WHERE type = 'table' LIMIT 1"
41469
+ ).get());
41470
+ if (applicationId === 0 && !hasTables && userVersion === 0) {
41471
+ this.db.exec(`PRAGMA application_id=${TRADE_RECORDS_APPLICATION_ID}`);
41472
+ } else if (applicationId !== TRADE_RECORDS_APPLICATION_ID) {
41473
+ throw new TradeRecordsStoreError(
41474
+ "DATABASE_IDENTITY_MISMATCH",
41475
+ "trade records database identity does not match"
41476
+ );
41477
+ }
41478
+ if (userVersion > TRADE_RECORDS_SCHEMA_VERSION) {
41479
+ throw new TradeRecordsStoreError(
41480
+ "DATABASE_SCHEMA_TOO_NEW",
41481
+ `trade records schema version ${userVersion} is newer than supported ${TRADE_RECORDS_SCHEMA_VERSION}`
41482
+ );
41483
+ }
41484
+ if (userVersion < 1) {
41485
+ applyMigrationV1(this.db);
41486
+ this.db.exec("PRAGMA user_version=1");
41487
+ }
41488
+ this.db.exec("COMMIT");
41489
+ } catch (error) {
41490
+ rollbackQuietly(this.db);
41491
+ throw error;
41492
+ }
41493
+ });
41494
+ withBusyRetry(() => {
41495
+ this.db.exec("PRAGMA journal_mode=WAL");
41496
+ this.db.exec("PRAGMA synchronous=FULL");
41497
+ });
41498
+ }
41499
+ assertReadableSchema() {
41500
+ const applicationId = readPragmaNumber(this.db, "application_id");
41501
+ if (applicationId !== TRADE_RECORDS_APPLICATION_ID) {
41502
+ throw new TradeRecordsStoreError(
41503
+ "DATABASE_IDENTITY_MISMATCH",
41504
+ "trade records database identity does not match"
41505
+ );
41506
+ }
41507
+ const userVersion = readPragmaNumber(this.db, "user_version");
41508
+ if (userVersion > TRADE_RECORDS_SCHEMA_VERSION) {
41509
+ throw new TradeRecordsStoreError(
41510
+ "DATABASE_SCHEMA_TOO_NEW",
41511
+ `trade records schema version ${userVersion} is newer than supported ${TRADE_RECORDS_SCHEMA_VERSION}`
41512
+ );
41513
+ }
41514
+ if (userVersion < TRADE_RECORDS_SCHEMA_VERSION) {
41515
+ throw new TradeRecordsStoreError(
41516
+ "DATABASE_MIGRATION_REQUIRED",
41517
+ "trade records database requires a write command to finish migration"
41518
+ );
41519
+ }
41520
+ }
41521
+ withWriteTransaction(operation) {
41522
+ return withBusyRetry(() => {
41523
+ this.db.exec("BEGIN IMMEDIATE");
41524
+ try {
41525
+ const result = operation();
41526
+ this.db.exec("COMMIT");
41527
+ return result;
41528
+ } catch (error) {
41529
+ rollbackQuietly(this.db);
41530
+ throw error;
41531
+ }
41532
+ });
41533
+ }
41534
+ };
41535
+ }
41536
+ });
41537
+
41538
+ // src/trade-records-cli.ts
41539
+ var trade_records_cli_exports = {};
41540
+ __export(trade_records_cli_exports, {
41541
+ handleTradeRecordsCommand: () => handleTradeRecordsCommand,
41542
+ printTradeRecordsUsage: () => printTradeRecordsUsage
41543
+ });
41544
+ async function handleTradeRecordsCommand(args) {
41545
+ const wantsJson = args.includes("--json");
41546
+ try {
41547
+ const subcommand = args[0];
41548
+ if (!subcommand || isHelpArg(subcommand)) {
41549
+ printTradeRecordsUsage();
41550
+ return;
41551
+ }
41552
+ if (args.slice(1).some(isHelpArg)) {
41553
+ printSubcommandUsage(subcommand);
41554
+ return;
41555
+ }
41556
+ if (subcommand === "insert") {
41557
+ handleInsert(args.slice(1));
41558
+ return;
41559
+ }
41560
+ if (subcommand === "query") {
41561
+ handleQuery(args.slice(1));
41562
+ return;
41563
+ }
41564
+ if (subcommand === "delete") {
41565
+ handleDelete(args.slice(1));
41566
+ return;
41567
+ }
41568
+ throw new TradeRecordsCliError("INVALID_ARGUMENT", `Unknown trade-records command: ${subcommand}`);
41569
+ } catch (error) {
41570
+ outputError(wantsJson, normalizeError(error));
41571
+ process.exitCode = 1;
41572
+ }
41573
+ }
41574
+ function printTradeRecordsUsage() {
41575
+ console.log(`Usage: okx-a2a trade-records <insert|query|delete> [options]
41576
+
41577
+ Commands:
41578
+ insert Insert or replace trade records by deliveryId.
41579
+ query Query active or soft-deleted trade records.
41580
+ delete Soft-delete one trade record by deliveryId.
41581
+
41582
+ Run \`okx-a2a trade-records <command> --help\` for command-specific help.`);
41583
+ }
41584
+ function printSubcommandUsage(subcommand) {
41585
+ if (subcommand === "insert") {
41586
+ console.log(`Usage: okx-a2a trade-records insert [options]
41587
+
41588
+ Input modes (choose exactly one):
41589
+ --job-id <id> --delivery-id <id> --status <status> [--reason <text>] [--extra <json-object>]
41590
+ --input-json <json-array>
41591
+ --input-file <path-to-json-array>
41592
+
41593
+ Options:
41594
+ --reason <text> Default: empty string.
41595
+ --extra <json> Complete JSON object. Default: {}.
41596
+ --json Print machine-readable summary.`);
41597
+ return;
41598
+ }
41599
+ if (subcommand === "query") {
41600
+ console.log(`Usage: okx-a2a trade-records query [options]
41601
+
41602
+ Options:
41603
+ --job-id <id> Filter by job id.
41604
+ --delivery-id <id> Filter by delivery id.
41605
+ --status <status> Filter by status; repeatable.
41606
+ --reason <text> Exact reason match.
41607
+ --reason-contains <text> Reason substring match.
41608
+ --created-from <epoch-ms> Inclusive createdAt lower bound.
41609
+ --created-to <epoch-ms> Inclusive createdAt upper bound.
41610
+ --updated-from <epoch-ms> Inclusive updatedAt lower bound.
41611
+ --updated-to <epoch-ms> Inclusive updatedAt upper bound.
41612
+ --extra-eq <path=json> Exact extra field match; repeatable.
41613
+ --include-deleted Include active and deleted records.
41614
+ --only-deleted Return only deleted records.
41615
+ --sort-by <createdAt|updatedAt> Default: updatedAt.
41616
+ --order <asc|desc> Default: desc.
41617
+ --limit <n> Default: 100; maximum: 1000.
41618
+ --cursor <cursor> Continue keyset pagination.
41619
+ --count Include total matching count.
41620
+ --json Print machine-readable output.`);
41621
+ return;
41622
+ }
41623
+ if (subcommand === "delete") {
41624
+ console.log(`Usage: okx-a2a trade-records delete --delivery-id <id> [--job-id <id>] [--json]
41625
+
41626
+ Soft-delete one trade record. Repeated deletes and missing records are idempotent.`);
41627
+ return;
41628
+ }
41629
+ throw new TradeRecordsCliError("INVALID_ARGUMENT", `Unknown trade-records command: ${subcommand}`);
41630
+ }
41631
+ function handleInsert(args) {
41632
+ const parsed = parseArgs(args, {
41633
+ command: "trade-records insert",
41634
+ options: /* @__PURE__ */ new Set([...INPUT_FIELD_OPTIONS, "input-json", "input-file"]),
41635
+ flags: /* @__PURE__ */ new Set(["json"])
41636
+ });
41637
+ const json = parsed.flags.has("json");
41638
+ const loaded = loadInsertRecords(parsed);
41639
+ const coalesced = coalesceByLastDeliveryId(loaded.records);
41640
+ const store = TradeRecordsStore.openForWrite();
41641
+ try {
41642
+ const result = store.insert(coalesced.records);
41643
+ const payload = {
41644
+ ok: true,
41645
+ operation: "insert",
41646
+ inputCount: loaded.records.length,
41647
+ finalRecordCount: coalesced.records.length,
41648
+ insertedCount: result.insertedCount,
41649
+ updatedCount: result.updatedCount,
41650
+ restoredCount: result.restoredCount,
41651
+ duplicateInputCount: coalesced.duplicateInputCount
41652
+ };
41653
+ if (json) {
41654
+ console.log(JSON.stringify(payload));
41655
+ return;
41656
+ }
41657
+ if (loaded.records.length === 1) {
41658
+ const operation = result.insertedCount === 1 ? "inserted" : result.restoredCount === 1 ? "restored" : "updated";
41659
+ console.log(`Trade record saved: deliveryId=${coalesced.records[0].deliveryId}, result=${operation}`);
41660
+ return;
41661
+ }
41662
+ console.log(`Trade records saved: ${loaded.records.length} inputs, ${coalesced.records.length} final records`);
41663
+ console.log(
41664
+ `Inserted: ${result.insertedCount}, updated: ${result.updatedCount}, restored: ${result.restoredCount}, duplicate inputs overwritten: ${coalesced.duplicateInputCount}`
41665
+ );
41666
+ } finally {
41667
+ store.close();
41668
+ }
41669
+ }
41670
+ function handleQuery(args) {
41671
+ const parsed = parseArgs(args, {
41672
+ command: "trade-records query",
41673
+ options: /* @__PURE__ */ new Set([
41674
+ "job-id",
41675
+ "delivery-id",
41676
+ "status",
41677
+ "reason",
41678
+ "reason-contains",
41679
+ "created-from",
41680
+ "created-to",
41681
+ "updated-from",
41682
+ "updated-to",
41683
+ "extra-eq",
41684
+ "sort-by",
41685
+ "order",
41686
+ "limit",
41687
+ "cursor"
41688
+ ]),
41689
+ flags: /* @__PURE__ */ new Set(["include-deleted", "only-deleted", "count", "json"]),
41690
+ repeatable: /* @__PURE__ */ new Set(["status", "extra-eq"])
41691
+ });
41692
+ const json = parsed.flags.has("json");
41693
+ if (parsed.flags.has("include-deleted") && parsed.flags.has("only-deleted")) {
41694
+ throw new TradeRecordsCliError(
41695
+ "INVALID_ARGUMENT",
41696
+ "--include-deleted and --only-deleted cannot be used together"
41697
+ );
41698
+ }
41699
+ const sortBy = readChoice(parsed, "sort-by", ["createdAt", "updatedAt"]) ?? "updatedAt";
41700
+ const order = readChoice(parsed, "order", ["asc", "desc"]) ?? "desc";
41701
+ const cursorRaw = readSingle(parsed, "cursor");
41702
+ const cursor = cursorRaw ? decodeTradeRecordCursor(cursorRaw) : void 0;
41703
+ if (cursor && (cursor.sortBy !== sortBy || cursor.order !== order)) {
41704
+ throw new TradeRecordsCliError(
41705
+ "INVALID_ARGUMENT",
41706
+ "--cursor does not match the requested --sort-by and --order"
41707
+ );
41708
+ }
41709
+ const createdFrom = readTimestamp(parsed, "created-from");
41710
+ const createdTo = readTimestamp(parsed, "created-to");
41711
+ const updatedFrom = readTimestamp(parsed, "updated-from");
41712
+ const updatedTo = readTimestamp(parsed, "updated-to");
41713
+ assertRange("created", createdFrom, createdTo);
41714
+ assertRange("updated", updatedFrom, updatedTo);
41715
+ const filter2 = {
41716
+ sortBy,
41717
+ order,
41718
+ limit: readLimit(parsed),
41719
+ statuses: parsed.options.get("status")?.map((value) => requireText(value, "--status", MAX_STATUS_LENGTH)),
41720
+ extraEquals: (parsed.options.get("extra-eq") ?? []).map(parseExtraFilter),
41721
+ includeDeleted: parsed.flags.has("include-deleted"),
41722
+ onlyDeleted: parsed.flags.has("only-deleted"),
41723
+ includeCount: parsed.flags.has("count"),
41724
+ ...readOptionalText(parsed, "job-id", MAX_ID_LENGTH) ? { jobId: readOptionalText(parsed, "job-id", MAX_ID_LENGTH) } : {},
41725
+ ...readOptionalText(parsed, "delivery-id", MAX_ID_LENGTH) ? { deliveryId: readOptionalText(parsed, "delivery-id", MAX_ID_LENGTH) } : {},
41726
+ ...readSingle(parsed, "reason") !== void 0 ? { reason: readSingle(parsed, "reason") } : {},
41727
+ ...readSingle(parsed, "reason-contains") !== void 0 ? { reasonContains: readSingle(parsed, "reason-contains") } : {},
41728
+ ...createdFrom === void 0 ? {} : { createdFrom },
41729
+ ...createdTo === void 0 ? {} : { createdTo },
41730
+ ...updatedFrom === void 0 ? {} : { updatedFrom },
41731
+ ...updatedTo === void 0 ? {} : { updatedTo },
41732
+ ...cursor ? { cursor } : {}
41733
+ };
41734
+ const store = TradeRecordsStore.openForRead();
41735
+ if (!store) {
41736
+ outputQuery(json, [], filter2.limit, null, filter2.includeCount ? 0 : void 0);
41737
+ return;
41738
+ }
41739
+ try {
41740
+ const result = store.query(filter2);
41741
+ outputQuery(json, result.records, filter2.limit, result.nextCursor, result.count);
41742
+ } finally {
41743
+ store.close();
41744
+ }
41745
+ }
41746
+ function handleDelete(args) {
41747
+ const parsed = parseArgs(args, {
41748
+ command: "trade-records delete",
41749
+ options: /* @__PURE__ */ new Set(["delivery-id", "job-id"]),
41750
+ flags: /* @__PURE__ */ new Set(["json"])
41751
+ });
41752
+ const json = parsed.flags.has("json");
41753
+ const deliveryId = requireText(readSingle(parsed, "delivery-id"), "--delivery-id", MAX_ID_LENGTH);
41754
+ const jobId = readOptionalText(parsed, "job-id", MAX_ID_LENGTH);
41755
+ if (!tradeRecordsDbExists()) {
41756
+ outputDelete(json, {
41757
+ deliveryId,
41758
+ deleted: false,
41759
+ alreadyDeleted: false,
41760
+ notFound: true
41761
+ });
41762
+ return;
41763
+ }
41764
+ const store = TradeRecordsStore.openForWrite();
41765
+ try {
41766
+ outputDelete(json, store.delete(deliveryId, jobId));
41767
+ } finally {
41768
+ store.close();
41769
+ }
41770
+ }
41771
+ function loadInsertRecords(parsed) {
41772
+ const inputJson = readSingle(parsed, "input-json");
41773
+ const inputFile = readSingle(parsed, "input-file");
41774
+ const providedFieldOptions = [...INPUT_FIELD_OPTIONS].filter((name) => parsed.options.has(name));
41775
+ const modeCount = Number(inputJson !== void 0) + Number(inputFile !== void 0) + Number(providedFieldOptions.length > 0);
41776
+ if (modeCount !== 1) {
41777
+ throw new TradeRecordsCliError(
41778
+ "INVALID_ARGUMENT",
41779
+ "trade-records insert requires exactly one input mode: field options, --input-json, or --input-file"
41780
+ );
41781
+ }
41782
+ if (inputJson !== void 0) {
41783
+ assertInputSize(inputJson, "--input-json");
41784
+ return { records: parseRecordArray(inputJson, "--input-json") };
41785
+ }
41786
+ if (inputFile !== void 0) {
41787
+ let content2;
41788
+ try {
41789
+ const stat4 = (0, import_node_fs21.statSync)(inputFile);
41790
+ if (!stat4.isFile()) {
41791
+ throw new Error("not a regular file");
41792
+ }
41793
+ if (stat4.size > MAX_INPUT_BYTES) {
41794
+ throw new TradeRecordsCliError("INPUT_TOO_LARGE", `--input-file exceeds ${MAX_INPUT_BYTES} bytes`);
41795
+ }
41796
+ content2 = (0, import_node_fs21.readFileSync)(inputFile, "utf8");
41797
+ } catch (error) {
41798
+ if (error instanceof TradeRecordsCliError) throw error;
41799
+ throw new TradeRecordsCliError("INVALID_INPUT_FILE", `could not read --input-file: ${String(error)}`);
41800
+ }
41801
+ return { records: parseRecordArray(content2, "--input-file") };
41802
+ }
41803
+ const extraRaw = readSingle(parsed, "extra");
41804
+ let extra = {};
41805
+ if (extraRaw !== void 0) {
41806
+ extra = parseJsonObject(extraRaw, "--extra");
41807
+ }
41808
+ return {
41809
+ records: [normalizeRecord({
41810
+ jobId: readSingle(parsed, "job-id"),
41811
+ deliveryId: readSingle(parsed, "delivery-id"),
41812
+ status: readSingle(parsed, "status"),
41813
+ reason: readSingle(parsed, "reason") ?? "",
41814
+ extra
41815
+ }, 0)]
41816
+ };
41817
+ }
41818
+ function parseRecordArray(raw, label) {
41819
+ let parsed;
41820
+ try {
41821
+ parsed = JSON.parse(raw);
41822
+ } catch {
41823
+ throw new TradeRecordsCliError("INVALID_INPUT_JSON", `${label} must contain valid JSON`);
41824
+ }
41825
+ if (!Array.isArray(parsed) || parsed.length === 0) {
41826
+ throw new TradeRecordsCliError("INVALID_INPUT_JSON", `${label} must contain a non-empty JSON array`);
41827
+ }
41828
+ if (parsed.length > MAX_BATCH_RECORDS) {
41829
+ throw new TradeRecordsCliError(
41830
+ "TOO_MANY_RECORDS",
41831
+ `${label} contains ${parsed.length} records; maximum is ${MAX_BATCH_RECORDS}`
41832
+ );
41833
+ }
41834
+ const records = [];
41835
+ const details = [];
41836
+ for (let index2 = 0; index2 < parsed.length; index2 += 1) {
41837
+ try {
41838
+ records.push(normalizeRecord(parsed[index2], index2));
41839
+ } catch (error) {
41840
+ const normalized = normalizeError(error);
41841
+ details.push(...normalized.details ?? [{ index: index2, reason: normalized.message }]);
41842
+ }
41843
+ }
41844
+ if (details.length > 0) {
41845
+ throw new TradeRecordsCliError("INVALID_ARGUMENT", "one or more trade records are invalid", details);
41846
+ }
41847
+ return records;
41848
+ }
41849
+ function normalizeRecord(value, index2) {
41850
+ if (!isJsonObject2(value)) {
41851
+ throw invalidField(index2, void 0, "must be a JSON object");
41852
+ }
41853
+ for (const field of Object.keys(value)) {
41854
+ if (FORBIDDEN_RECORD_FIELDS.has(field)) {
41855
+ throw invalidField(index2, field, "business callers must not provide timestamp fields");
41856
+ }
41857
+ if (!ALLOWED_RECORD_FIELDS.has(field)) {
41858
+ throw invalidField(index2, field, "unknown field; put extensible fields inside extra");
41859
+ }
41860
+ }
41861
+ const jobId = requireRecordText(value.jobId, index2, "jobId", MAX_ID_LENGTH);
41862
+ const deliveryId = requireRecordText(value.deliveryId, index2, "deliveryId", MAX_ID_LENGTH);
41863
+ const status = requireRecordText(value.status, index2, "status", MAX_STATUS_LENGTH);
41864
+ const reason = value.reason === void 0 ? "" : requireRecordString(value.reason, index2, "reason", MAX_REASON_LENGTH, true);
41865
+ const extra = value.extra === void 0 ? {} : value.extra;
41866
+ if (!isJsonObject2(extra)) {
41867
+ throw invalidField(index2, "extra", "must be a JSON object");
41868
+ }
41869
+ const serializedExtra = JSON.stringify(extra);
41870
+ if (Buffer.byteLength(serializedExtra, "utf8") > MAX_EXTRA_BYTES) {
41871
+ throw invalidField(index2, "extra", `serialized JSON exceeds ${MAX_EXTRA_BYTES} bytes`);
41872
+ }
41873
+ return { jobId, deliveryId, status, reason, extra };
41874
+ }
41875
+ function coalesceByLastDeliveryId(records) {
41876
+ const lastIndexes = /* @__PURE__ */ new Map();
41877
+ records.forEach((record, index2) => lastIndexes.set(record.deliveryId, index2));
41878
+ const coalesced = records.filter((record, index2) => lastIndexes.get(record.deliveryId) === index2);
41879
+ return { records: coalesced, duplicateInputCount: records.length - coalesced.length };
41880
+ }
41881
+ function parseArgs(args, spec) {
41882
+ const options = /* @__PURE__ */ new Map();
41883
+ const flags = /* @__PURE__ */ new Set();
41884
+ for (let index2 = 0; index2 < args.length; index2 += 1) {
41885
+ const token = args[index2];
41886
+ if (!token.startsWith("--")) {
41887
+ throw new TradeRecordsCliError("INVALID_ARGUMENT", `${spec.command} unexpected positional argument: ${token}`);
41888
+ }
41889
+ const name = token.slice(2);
41890
+ if (spec.flags.has(name)) {
41891
+ if (flags.has(name)) {
41892
+ throw new TradeRecordsCliError("INVALID_ARGUMENT", `${token} must not be repeated`);
41893
+ }
41894
+ flags.add(name);
41895
+ continue;
41896
+ }
41897
+ if (!spec.options.has(name)) {
41898
+ throw new TradeRecordsCliError("INVALID_ARGUMENT", `${spec.command} unknown option ${token}`);
41899
+ }
41900
+ if (index2 + 1 >= args.length) {
41901
+ throw new TradeRecordsCliError("INVALID_ARGUMENT", `${token} requires a value`);
41902
+ }
41903
+ const value = args[++index2];
41904
+ if (value.startsWith("--")) {
41905
+ throw new TradeRecordsCliError("INVALID_ARGUMENT", `${token} requires a value`);
41906
+ }
41907
+ const values = options.get(name) ?? [];
41908
+ if (values.length > 0 && !spec.repeatable?.has(name)) {
41909
+ throw new TradeRecordsCliError("INVALID_ARGUMENT", `${token} must not be repeated`);
41910
+ }
41911
+ values.push(value);
41912
+ options.set(name, values);
41913
+ }
41914
+ return { options, flags };
41915
+ }
41916
+ function readSingle(parsed, name) {
41917
+ return parsed.options.get(name)?.[0];
41918
+ }
41919
+ function readOptionalText(parsed, name, maxLength) {
41920
+ const value = readSingle(parsed, name);
41921
+ return value === void 0 ? void 0 : requireText(value, `--${name}`, maxLength);
41922
+ }
41923
+ function requireText(value, label, maxLength) {
41924
+ if (typeof value !== "string" || value.trim().length === 0) {
41925
+ throw new TradeRecordsCliError("INVALID_ARGUMENT", `${label} is required and must be a non-empty string`);
41926
+ }
41927
+ const normalized = value.trim();
41928
+ if (normalized.length > maxLength) {
41929
+ throw new TradeRecordsCliError("INVALID_ARGUMENT", `${label} exceeds ${maxLength} characters`);
41930
+ }
41931
+ return normalized;
41932
+ }
41933
+ function requireRecordText(value, index2, field, maxLength) {
41934
+ if (typeof value !== "string" || value.trim().length === 0) {
41935
+ throw invalidField(index2, field, "must be a non-empty string");
41936
+ }
41937
+ const normalized = value.trim();
41938
+ if (normalized.length > maxLength) {
41939
+ throw invalidField(index2, field, `exceeds ${maxLength} characters`);
41940
+ }
41941
+ return normalized;
41942
+ }
41943
+ function requireRecordString(value, index2, field, maxLength, allowEmpty) {
41944
+ if (typeof value !== "string" || !allowEmpty && value.length === 0) {
41945
+ throw invalidField(index2, field, allowEmpty ? "must be a string" : "must be a non-empty string");
41946
+ }
41947
+ if (value.length > maxLength) {
41948
+ throw invalidField(index2, field, `exceeds ${maxLength} characters`);
41949
+ }
41950
+ return value;
41951
+ }
41952
+ function invalidField(index2, field, reason) {
41953
+ return new TradeRecordsCliError("INVALID_ARGUMENT", `invalid trade record at index ${index2}`, [
41954
+ { index: index2, ...field ? { field } : {}, reason }
41955
+ ]);
41956
+ }
41957
+ function parseJsonObject(raw, label) {
41958
+ let value;
41959
+ try {
41960
+ value = JSON.parse(raw);
41961
+ } catch {
41962
+ throw new TradeRecordsCliError("INVALID_ARGUMENT", `${label} must be valid JSON`);
41963
+ }
41964
+ if (!isJsonObject2(value)) {
41965
+ throw new TradeRecordsCliError("INVALID_ARGUMENT", `${label} must be a JSON object`);
41966
+ }
41967
+ if (Buffer.byteLength(JSON.stringify(value), "utf8") > MAX_EXTRA_BYTES) {
41968
+ throw new TradeRecordsCliError("INPUT_TOO_LARGE", `${label} exceeds ${MAX_EXTRA_BYTES} bytes`);
41969
+ }
41970
+ return value;
41971
+ }
41972
+ function parseExtraFilter(raw) {
41973
+ const separator = raw.indexOf("=");
41974
+ if (separator <= 0 || separator === raw.length - 1) {
41975
+ throw new TradeRecordsCliError("INVALID_ARGUMENT", "--extra-eq must use path=jsonValue syntax");
41976
+ }
41977
+ const path2 = raw.slice(0, separator).trim();
41978
+ const segments = path2.split(".");
41979
+ if (segments.some((segment) => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(segment))) {
41980
+ throw new TradeRecordsCliError("INVALID_ARGUMENT", `--extra-eq has invalid JSON path: ${path2}`);
41981
+ }
41982
+ let value;
41983
+ try {
41984
+ value = JSON.parse(raw.slice(separator + 1));
41985
+ } catch {
41986
+ throw new TradeRecordsCliError("INVALID_ARGUMENT", "--extra-eq value must be a JSON primitive");
41987
+ }
41988
+ if (typeof value === "object" && value !== null) {
41989
+ throw new TradeRecordsCliError("INVALID_ARGUMENT", "--extra-eq value must be a JSON primitive");
41990
+ }
41991
+ if (!["string", "number", "boolean"].includes(typeof value) && value !== null) {
41992
+ throw new TradeRecordsCliError("INVALID_ARGUMENT", "--extra-eq value must be a JSON primitive");
41993
+ }
41994
+ if (typeof value === "number" && !Number.isFinite(value)) {
41995
+ throw new TradeRecordsCliError("INVALID_ARGUMENT", "--extra-eq number must be finite");
41996
+ }
41997
+ return { path: `$.${segments.join(".")}`, value };
41998
+ }
41999
+ function readTimestamp(parsed, name) {
42000
+ const raw = readSingle(parsed, name);
42001
+ if (raw === void 0) return void 0;
42002
+ const value = Number(raw);
42003
+ if (!Number.isSafeInteger(value) || value < 0) {
42004
+ throw new TradeRecordsCliError("INVALID_ARGUMENT", `--${name} must be a non-negative integer`);
42005
+ }
42006
+ return value;
42007
+ }
42008
+ function assertRange(label, from, to) {
42009
+ if (from !== void 0 && to !== void 0 && from > to) {
42010
+ throw new TradeRecordsCliError("INVALID_ARGUMENT", `--${label}-from must not exceed --${label}-to`);
42011
+ }
42012
+ }
42013
+ function readLimit(parsed) {
42014
+ const raw = readSingle(parsed, "limit");
42015
+ if (raw === void 0) return 100;
42016
+ const limit = Number(raw);
42017
+ if (!Number.isInteger(limit) || limit < 1 || limit > 1e3) {
42018
+ throw new TradeRecordsCliError("INVALID_ARGUMENT", "--limit must be an integer between 1 and 1000");
42019
+ }
42020
+ return limit;
42021
+ }
42022
+ function readChoice(parsed, name, choices) {
42023
+ const value = readSingle(parsed, name);
42024
+ if (value === void 0) return void 0;
42025
+ if (!choices.includes(value)) {
42026
+ throw new TradeRecordsCliError(
42027
+ "INVALID_ARGUMENT",
42028
+ `--${name} must be one of: ${choices.join(", ")}`
42029
+ );
42030
+ }
42031
+ return value;
42032
+ }
42033
+ function assertInputSize(value, label) {
42034
+ if (Buffer.byteLength(value, "utf8") > MAX_INPUT_BYTES) {
42035
+ throw new TradeRecordsCliError("INPUT_TOO_LARGE", `${label} exceeds ${MAX_INPUT_BYTES} bytes`);
42036
+ }
42037
+ }
42038
+ function outputQuery(json, records, limit, nextCursor, count) {
42039
+ if (json) {
42040
+ console.log(JSON.stringify({
42041
+ ok: true,
42042
+ records,
42043
+ page: { limit, nextCursor },
42044
+ ...count === void 0 ? {} : { count }
42045
+ }));
42046
+ return;
42047
+ }
42048
+ if (records.length === 0) {
42049
+ console.log("No trade records found.");
42050
+ return;
42051
+ }
42052
+ for (const record of records) {
42053
+ console.log(
42054
+ `${record.deliveryId} job=${record.jobId} status=${record.status} reason=${JSON.stringify(record.reason)} extra=${JSON.stringify(record.extra)} createdAt=${record.createdAt} updatedAt=${record.updatedAt} deletedAt=${record.deletedAt ?? ""}`
42055
+ );
42056
+ }
42057
+ if (nextCursor) {
42058
+ console.log(`Next cursor: ${nextCursor}`);
42059
+ }
42060
+ if (count !== void 0) {
42061
+ console.log(`Count: ${count}`);
42062
+ }
42063
+ }
42064
+ function outputDelete(json, result) {
42065
+ if (json) {
42066
+ console.log(JSON.stringify({ ok: true, operation: "delete", ...result }));
42067
+ return;
42068
+ }
42069
+ if (result.deleted) {
42070
+ console.log(`Trade record deleted: deliveryId=${result.deliveryId}`);
42071
+ } else if (result.alreadyDeleted) {
42072
+ console.log(`Trade record already deleted: deliveryId=${result.deliveryId}`);
42073
+ } else {
42074
+ console.log(`Trade record not found: deliveryId=${result.deliveryId}`);
42075
+ }
42076
+ }
42077
+ function outputError(json, error) {
42078
+ if (json) {
42079
+ console.log(JSON.stringify({
42080
+ ok: false,
42081
+ code: error.code,
42082
+ message: error.message,
42083
+ ...error.details ? { details: error.details } : {}
42084
+ }));
42085
+ return;
42086
+ }
42087
+ console.error(`Trade records error [${error.code}]: ${error.message}`);
42088
+ for (const detail of error.details ?? []) {
42089
+ console.error(
42090
+ ` index=${detail.index ?? ""} field=${detail.field ?? ""} reason=${detail.reason}`
42091
+ );
42092
+ }
42093
+ }
42094
+ function normalizeError(error) {
42095
+ if (error instanceof TradeRecordsCliError) return error;
42096
+ if (error instanceof TradeRecordsStoreError) {
42097
+ return new TradeRecordsCliError(error.code, error.message);
42098
+ }
42099
+ if (isBusyError(error)) {
42100
+ return new TradeRecordsCliError("DATABASE_BUSY", "trade records database is busy; retry later");
42101
+ }
42102
+ return new TradeRecordsCliError(
42103
+ "TRADE_RECORDS_FAILED",
42104
+ error instanceof Error ? error.message : String(error)
42105
+ );
42106
+ }
42107
+ function isBusyError(error) {
42108
+ if (!(error instanceof Error)) return false;
42109
+ const code = error.errcode;
42110
+ return typeof code === "number" && ((code & 255) === 5 || (code & 255) === 6) || /database is locked|database table is locked/i.test(error.message);
42111
+ }
42112
+ function isJsonObject2(value) {
42113
+ return typeof value === "object" && value !== null && !Array.isArray(value);
42114
+ }
42115
+ function isHelpArg(value) {
42116
+ return value === "help" || value === "-h" || value === "--help";
42117
+ }
42118
+ var import_node_fs21, MAX_BATCH_RECORDS, MAX_INPUT_BYTES, MAX_EXTRA_BYTES, MAX_ID_LENGTH, MAX_STATUS_LENGTH, MAX_REASON_LENGTH, INPUT_FIELD_OPTIONS, FORBIDDEN_RECORD_FIELDS, ALLOWED_RECORD_FIELDS, TradeRecordsCliError;
42119
+ var init_trade_records_cli = __esm({
42120
+ "src/trade-records-cli.ts"() {
42121
+ "use strict";
42122
+ import_node_fs21 = require("node:fs");
42123
+ init_trade_records_store();
42124
+ MAX_BATCH_RECORDS = 1e3;
42125
+ MAX_INPUT_BYTES = 10 * 1024 * 1024;
42126
+ MAX_EXTRA_BYTES = 256 * 1024;
42127
+ MAX_ID_LENGTH = 512;
42128
+ MAX_STATUS_LENGTH = 128;
42129
+ MAX_REASON_LENGTH = 4096;
42130
+ INPUT_FIELD_OPTIONS = /* @__PURE__ */ new Set(["job-id", "delivery-id", "status", "reason", "extra"]);
42131
+ FORBIDDEN_RECORD_FIELDS = /* @__PURE__ */ new Set([
42132
+ "createdAt",
42133
+ "createAt",
42134
+ "updatedAt",
42135
+ "updateAt",
42136
+ "deletedAt",
42137
+ "created_at",
42138
+ "create_at",
42139
+ "updated_at",
42140
+ "update_at",
42141
+ "deleted_at"
42142
+ ]);
42143
+ ALLOWED_RECORD_FIELDS = /* @__PURE__ */ new Set(["jobId", "deliveryId", "status", "reason", "extra"]);
42144
+ TradeRecordsCliError = class extends Error {
42145
+ code;
42146
+ details;
42147
+ constructor(code, message, details) {
42148
+ super(message);
42149
+ this.name = "TradeRecordsCliError";
42150
+ this.code = code;
42151
+ this.details = details;
42152
+ }
42153
+ };
42154
+ }
42155
+ });
42156
+
41100
42157
  // ../core/src/xmtp-sdk/onchainos/bin.ts
41101
42158
  async function refreshOnchainosVersionMetadata(options = {}) {
41102
42159
  const now = options.now ?? Date.now;
@@ -41216,11 +42273,11 @@ function isResolvedBinUsable(bin) {
41216
42273
  if (!isPathLikeCommand(bin)) {
41217
42274
  return true;
41218
42275
  }
41219
- return process.platform === "win32" ? (0, import_node_fs20.existsSync)(bin) : isExecutable2(bin);
42276
+ return process.platform === "win32" ? (0, import_node_fs22.existsSync)(bin) : isExecutable2(bin);
41220
42277
  }
41221
42278
  function resolvePosixBareCommand(command, pathValue) {
41222
42279
  for (const dir of pathValue.split(":")) {
41223
- const candidate = (0, import_node_path24.join)(dir || ".", command);
42280
+ const candidate = (0, import_node_path25.join)(dir || ".", command);
41224
42281
  if (isExecutable2(candidate)) {
41225
42282
  return candidate;
41226
42283
  }
@@ -41503,12 +42560,12 @@ function buildWin32CandidatePaths(names, pathValue, userProfile) {
41503
42560
  addDir(dir);
41504
42561
  }
41505
42562
  if (userProfile?.trim()) {
41506
- addDir((0, import_node_path24.join)(userProfile, ".local", "bin"));
42563
+ addDir((0, import_node_path25.join)(userProfile, ".local", "bin"));
41507
42564
  }
41508
42565
  const candidates = [];
41509
42566
  for (const dir of dirs) {
41510
42567
  for (const name of names) {
41511
- candidates.push((0, import_node_path24.join)(dir, name));
42568
+ candidates.push((0, import_node_path25.join)(dir, name));
41512
42569
  }
41513
42570
  }
41514
42571
  return candidates;
@@ -41521,7 +42578,7 @@ function buildWin32OnchainosCandidates(pathValue, userProfile) {
41521
42578
  );
41522
42579
  }
41523
42580
  function resolveWin32BareCommandCandidate(command, pathValue, pathExtValue, userProfile) {
41524
- const names = (0, import_node_path24.extname)(command) ? [command] : [
42581
+ const names = (0, import_node_path25.extname)(command) ? [command] : [
41525
42582
  ...new Set(
41526
42583
  pathExtValue.split(";").map((extension) => extension.trim().toLowerCase()).filter(Boolean).map(
41527
42584
  (extension) => `${command}${extension.startsWith(".") ? extension : `.${extension}`}`
@@ -41537,7 +42594,7 @@ function resolveWin32BareCommandCandidate(command, pathValue, pathExtValue, user
41537
42594
  return null;
41538
42595
  }
41539
42596
  function win32CandidatePriority(candidate) {
41540
- const extension = (0, import_node_path24.extname)(candidate).toLowerCase();
42597
+ const extension = (0, import_node_path25.extname)(candidate).toLowerCase();
41541
42598
  if (extension === ".exe") {
41542
42599
  return 0;
41543
42600
  }
@@ -41553,7 +42610,7 @@ function isWindowsAppsAlias(candidate) {
41553
42610
  return candidate.toLowerCase().includes(WINDOWS_APPS_ALIAS_MARKER);
41554
42611
  }
41555
42612
  function win32FileExists(path2) {
41556
- return (0, import_node_fs20.existsSync)(path2);
42613
+ return (0, import_node_fs22.existsSync)(path2);
41557
42614
  }
41558
42615
  function pickOnchainosWin32Candidate(lines, fileExists2 = win32FileExists) {
41559
42616
  const candidates = lines.map((line) => {
@@ -41609,7 +42666,7 @@ function extractExecutablePath(stdout) {
41609
42666
  }
41610
42667
  function isExecutable2(path2) {
41611
42668
  try {
41612
- (0, import_node_fs20.accessSync)(path2, import_node_fs20.constants.X_OK);
42669
+ (0, import_node_fs22.accessSync)(path2, import_node_fs22.constants.X_OK);
41613
42670
  return true;
41614
42671
  } catch {
41615
42672
  return false;
@@ -41714,14 +42771,14 @@ async function exec(args, options = {}) {
41714
42771
  }
41715
42772
  throw new Error("OnchainOS command retry exhausted");
41716
42773
  }
41717
- var import_node_fs20, import_node_child_process8, import_node_path24, import_node_util2, execFileAsync2, resolvedBin, resolvedForEnvBin, resolverRevision, versionProbeInFlight, posixDiscoveryFlights, REDACTED_VALUE_FLAGS, COMMAND_UNAVAILABLE_CODES, ONCHAINOS_VERSION_PROBE_TIMEOUT_MS, ONCHAINOS_BIN_RESOLVE_TIMEOUT_MS, WINDOWS_APPS_ALIAS_MARKER;
42774
+ var import_node_fs22, import_node_child_process8, import_node_path25, import_node_util2, execFileAsync2, resolvedBin, resolvedForEnvBin, resolverRevision, versionProbeInFlight, posixDiscoveryFlights, REDACTED_VALUE_FLAGS, COMMAND_UNAVAILABLE_CODES, ONCHAINOS_VERSION_PROBE_TIMEOUT_MS, ONCHAINOS_BIN_RESOLVE_TIMEOUT_MS, WINDOWS_APPS_ALIAS_MARKER;
41718
42775
  var init_bin = __esm({
41719
42776
  "../core/src/xmtp-sdk/onchainos/bin.ts"() {
41720
42777
  "use strict";
41721
42778
  init_log();
41722
- import_node_fs20 = require("node:fs");
42779
+ import_node_fs22 = require("node:fs");
41723
42780
  import_node_child_process8 = require("node:child_process");
41724
- import_node_path24 = require("node:path");
42781
+ import_node_path25 = require("node:path");
41725
42782
  import_node_util2 = require("node:util");
41726
42783
  init_sentry_logger();
41727
42784
  init_runtime_metadata();
@@ -41783,7 +42840,7 @@ function createAsyncStreamProxy(stream) {
41783
42840
  }
41784
42841
  });
41785
42842
  }
41786
- var import_node_bindings, import_node_bindings2, import_node_crypto9, import_types, import_node_path25, import_node_process, HistorySyncUrls, envMap, reverseEnvMap, envToString, createBackend, InboxReassignError, AccountAlreadyAssociatedError, MissingContentTypeError, SignerUnavailableError, ClientNotInitializedError, StreamFailedError, StreamInvalidRetryAttemptsError, generateInboxId, getInboxIdForIdentifier, isReaction, isReply, isText, isRemoteAttachment, isAttachment, isMultiRemoteAttachment, isTransactionReference, isGroupUpdated, isReadReceipt, isLeaveRequest, isWalletSendCalls, isIntent, isActions, isMarkdown, CodecRegistry, getContentFromDecodedMessageContent, getContentTypeFromDecodedMessageContent, DecodedMessage, AsyncStream, usableProperties, isUsableProperty, wait, DEFAULT_RETRY_DELAY, DEFAULT_RETRY_ATTEMPTS, createStream, Conversation, Dm, Group, Conversations, DebugInformation, Preferences, networkOptionKeys, hasBackend, resolveBackend$1, createClient, resolveBackend, createEphemeralIdentifier, toInboxUpdatesCountMap, Client;
42843
+ var import_node_bindings, import_node_bindings2, import_node_crypto9, import_types, import_node_path26, import_node_process, HistorySyncUrls, envMap, reverseEnvMap, envToString, createBackend, InboxReassignError, AccountAlreadyAssociatedError, MissingContentTypeError, SignerUnavailableError, ClientNotInitializedError, StreamFailedError, StreamInvalidRetryAttemptsError, generateInboxId, getInboxIdForIdentifier, isReaction, isReply, isText, isRemoteAttachment, isAttachment, isMultiRemoteAttachment, isTransactionReference, isGroupUpdated, isReadReceipt, isLeaveRequest, isWalletSendCalls, isIntent, isActions, isMarkdown, CodecRegistry, getContentFromDecodedMessageContent, getContentTypeFromDecodedMessageContent, DecodedMessage, AsyncStream, usableProperties, isUsableProperty, wait, DEFAULT_RETRY_DELAY, DEFAULT_RETRY_ATTEMPTS, createStream, Conversation, Dm, Group, Conversations, DebugInformation, Preferences, networkOptionKeys, hasBackend, resolveBackend$1, createClient, resolveBackend, createEphemeralIdentifier, toInboxUpdatesCountMap, Client;
41787
42844
  var init_dist2 = __esm({
41788
42845
  "../../node_modules/@xmtp/node-sdk/dist/index.js"() {
41789
42846
  import_node_bindings = require("@xmtp/node-bindings");
@@ -41791,7 +42848,7 @@ var init_dist2 = __esm({
41791
42848
  import_node_crypto9 = require("node:crypto");
41792
42849
  init_dist();
41793
42850
  import_types = require("node:util/types");
41794
- import_node_path25 = require("node:path");
42851
+ import_node_path26 = require("node:path");
41795
42852
  import_node_process = __toESM(require("node:process"), 1);
41796
42853
  HistorySyncUrls = {
41797
42854
  local: "http://localhost:5558",
@@ -43430,7 +44487,7 @@ var init_dist2 = __esm({
43430
44487
  const env = envToString(backend.env);
43431
44488
  let dbPath;
43432
44489
  if (options?.dbPath === void 0) {
43433
- dbPath = (0, import_node_path25.join)(import_node_process.default.cwd(), `xmtp-${env}-${inboxId}.db3`);
44490
+ dbPath = (0, import_node_path26.join)(import_node_process.default.cwd(), `xmtp-${env}-${inboxId}.db3`);
43434
44491
  } else if (typeof options.dbPath === "function") {
43435
44492
  dbPath = options.dbPath(inboxId);
43436
44493
  } else {
@@ -55721,14 +56778,14 @@ async function createRemoteAttachmentFromFile(unencryptedFile, uploadCallback) {
55721
56778
  const fileUrl = await uploadCallback(encryptedAttachment);
55722
56779
  return createRemoteAttachment(encryptedAttachment, fileUrl);
55723
56780
  }
55724
- var import_node_events, import_node_fs21, import_node_path26, import_ts_retry_promise, import_node_crypto10, version2, fromSelf, hasContent, isDM, isGroup, isGroupAdmin, isGroupSuperAdmin, usesCodec, filter, validLogLevels, isLogLevel, getValidLogLevels, parseLogLevel, logDetails, getInstallationInfo, createUser, createIdentifier, createSigner, AgentError, AgentStreamingError, ClientContext, ConversationContext, MessageContext, Agent, CANCEL_ACTION_ID, LimitedMap, cache;
56781
+ var import_node_events, import_node_fs23, import_node_path27, import_ts_retry_promise, import_node_crypto10, version2, fromSelf, hasContent, isDM, isGroup, isGroupAdmin, isGroupSuperAdmin, usesCodec, filter, validLogLevels, isLogLevel, getValidLogLevels, parseLogLevel, logDetails, getInstallationInfo, createUser, createIdentifier, createSigner, AgentError, AgentStreamingError, ClientContext, ConversationContext, MessageContext, Agent, CANCEL_ACTION_ID, LimitedMap, cache;
55725
56782
  var init_dist4 = __esm({
55726
56783
  "../../node_modules/@xmtp/agent-sdk/dist/index.js"() {
55727
56784
  init_dist2();
55728
56785
  init_dist2();
55729
56786
  import_node_events = __toESM(require("node:events"), 1);
55730
- import_node_fs21 = __toESM(require("node:fs"), 1);
55731
- import_node_path26 = __toESM(require("node:path"), 1);
56787
+ import_node_fs23 = __toESM(require("node:fs"), 1);
56788
+ import_node_path27 = __toESM(require("node:path"), 1);
55732
56789
  import_ts_retry_promise = __toESM(require_retry_promise(), 1);
55733
56790
  init_dist3();
55734
56791
  init_esm();
@@ -56094,9 +57151,9 @@ var init_dist4 = __esm({
56094
57151
  initializedOptions.gatewayHost = XMTP_GATEWAY_HOST;
56095
57152
  }
56096
57153
  if (typeof XMTP_DB_DIRECTORY === "string") {
56097
- import_node_fs21.default.mkdirSync(XMTP_DB_DIRECTORY, { recursive: true, mode: 448 });
57154
+ import_node_fs23.default.mkdirSync(XMTP_DB_DIRECTORY, { recursive: true, mode: 448 });
56098
57155
  initializedOptions.dbPath = (inboxId) => {
56099
- const dbPath = import_node_path26.default.join(XMTP_DB_DIRECTORY, `xmtp-${inboxId}.db3`);
57156
+ const dbPath = import_node_path27.default.join(XMTP_DB_DIRECTORY, `xmtp-${inboxId}.db3`);
56100
57157
  console.info(`Saving local database to "${dbPath}"`);
56101
57158
  return dbPath;
56102
57159
  };
@@ -57139,7 +58196,7 @@ var init_session_expired = __esm({
57139
58196
 
57140
58197
  // ../core/src/xmtp-sdk/index.ts
57141
58198
  function cachePath(dataDir, fileName) {
57142
- return (0, import_node_path27.join)(dataDir, fileName);
58199
+ return (0, import_node_path28.join)(dataDir, fileName);
57143
58200
  }
57144
58201
  function formatLogTimestamp2(timestampMs) {
57145
58202
  return timestampMs && timestampMs > 0 ? new Date(timestampMs).toISOString() : "(none)";
@@ -57167,10 +58224,10 @@ function ensureCacheDir(dataDir) {
57167
58224
  function loadSensitiveWordsFromCache(dataDir) {
57168
58225
  try {
57169
58226
  const path2 = cachePath(dataDir, "sensitive-words.json");
57170
- if (!(0, import_node_fs22.existsSync)(path2)) {
58227
+ if (!(0, import_node_fs24.existsSync)(path2)) {
57171
58228
  return null;
57172
58229
  }
57173
- const data = JSON.parse((0, import_node_fs22.readFileSync)(path2, "utf-8"));
58230
+ const data = JSON.parse((0, import_node_fs24.readFileSync)(path2, "utf-8"));
57174
58231
  if (Array.isArray(data)) {
57175
58232
  return data;
57176
58233
  }
@@ -57184,7 +58241,7 @@ function loadSensitiveWordsFromCache(dataDir) {
57184
58241
  function saveSensitiveWordsToCache(dataDir, words) {
57185
58242
  try {
57186
58243
  ensureCacheDir(dataDir);
57187
- (0, import_node_fs22.writeFileSync)(cachePath(dataDir, "sensitive-words.json"), JSON.stringify(words));
58244
+ (0, import_node_fs24.writeFileSync)(cachePath(dataDir, "sensitive-words.json"), JSON.stringify(words));
57188
58245
  } catch (err2) {
57189
58246
  logWithTimestamp(`[xmtp-sdk] failed to write sensitive-words.json:`, err2);
57190
58247
  logger.error(LogEvent.CACHE_WRITE_FAILED, err2 instanceof Error ? err2 : new Error(String(err2)), { cacheName: "sensitive-words" });
@@ -57226,10 +58283,10 @@ async function loadSensitiveWordsWith(dataDir, fetcher) {
57226
58283
  function loadSystemConfigFromCache(dataDir) {
57227
58284
  try {
57228
58285
  const path2 = cachePath(dataDir, "system-config.json");
57229
- if (!(0, import_node_fs22.existsSync)(path2)) {
58286
+ if (!(0, import_node_fs24.existsSync)(path2)) {
57230
58287
  return null;
57231
58288
  }
57232
- const data = JSON.parse((0, import_node_fs22.readFileSync)(path2, "utf-8"));
58289
+ const data = JSON.parse((0, import_node_fs24.readFileSync)(path2, "utf-8"));
57233
58290
  if (data && typeof data === "object" && !Array.isArray(data)) {
57234
58291
  return data;
57235
58292
  }
@@ -57243,7 +58300,7 @@ function loadSystemConfigFromCache(dataDir) {
57243
58300
  function saveSystemConfigToCache(dataDir, config) {
57244
58301
  try {
57245
58302
  ensureCacheDir(dataDir);
57246
- (0, import_node_fs22.writeFileSync)(cachePath(dataDir, "system-config.json"), JSON.stringify(config));
58303
+ (0, import_node_fs24.writeFileSync)(cachePath(dataDir, "system-config.json"), JSON.stringify(config));
57247
58304
  } catch (err2) {
57248
58305
  logWithTimestamp(`[xmtp-sdk] failed to write system-config.json:`, err2);
57249
58306
  logger.error(LogEvent.CACHE_WRITE_FAILED, err2 instanceof Error ? err2 : new Error(String(err2)), { cacheName: "system-config" });
@@ -57293,10 +58350,10 @@ function loadSyncByAddress(dataDir) {
57293
58350
  const map = /* @__PURE__ */ new Map();
57294
58351
  try {
57295
58352
  const path2 = cachePath(dataDir, "last-sync.json");
57296
- if (!(0, import_node_fs22.existsSync)(path2)) {
58353
+ if (!(0, import_node_fs24.existsSync)(path2)) {
57297
58354
  return map;
57298
58355
  }
57299
- const data = JSON.parse((0, import_node_fs22.readFileSync)(path2, "utf-8"));
58356
+ const data = JSON.parse((0, import_node_fs24.readFileSync)(path2, "utf-8"));
57300
58357
  const obj = data?.syncByAddress;
57301
58358
  if (obj && typeof obj === "object" && !Array.isArray(obj)) {
57302
58359
  for (const [addr, ts] of Object.entries(obj)) {
@@ -57315,9 +58372,9 @@ function saveSyncForAddress(dataDir, address, timestampMs) {
57315
58372
  try {
57316
58373
  let data = {};
57317
58374
  const path2 = cachePath(dataDir, "last-sync.json");
57318
- if ((0, import_node_fs22.existsSync)(path2)) {
58375
+ if ((0, import_node_fs24.existsSync)(path2)) {
57319
58376
  try {
57320
- const raw = JSON.parse((0, import_node_fs22.readFileSync)(path2, "utf-8"));
58377
+ const raw = JSON.parse((0, import_node_fs24.readFileSync)(path2, "utf-8"));
57321
58378
  if (raw && typeof raw === "object" && !Array.isArray(raw)) {
57322
58379
  data = raw;
57323
58380
  }
@@ -57328,7 +58385,7 @@ function saveSyncForAddress(dataDir, address, timestampMs) {
57328
58385
  data.syncByAddress = {};
57329
58386
  }
57330
58387
  data.syncByAddress[address] = timestampMs;
57331
- (0, import_node_fs22.writeFileSync)(path2, JSON.stringify(data, null, 2));
58388
+ (0, import_node_fs24.writeFileSync)(path2, JSON.stringify(data, null, 2));
57332
58389
  } catch (err2) {
57333
58390
  logWithTimestamp(
57334
58391
  `[xmtp-sdk] failed to write last-sync.json (address=${address}):`,
@@ -57547,13 +58604,13 @@ function createOfflineReplayAddressSummary(address) {
57547
58604
  durationMs: 0
57548
58605
  };
57549
58606
  }
57550
- var import_node_fs22, import_node_path27, DEFAULT_DATA_DIR, XMTP_INSTALLATION_WARNING_THRESHOLD, XMTP_INSTALLATION_NEAR_LIMIT_THRESHOLD, REPLAY_SCAN_INITIAL_BACKOFF_MS, REPLAY_SCAN_MAX_BACKOFF_MS, SENSITIVE_WORDS_LAZY_RETRY_COOLDOWN_MS, InboundReplayGate, SYSTEM_CONFIG_DEFAULTS, STREAM_RECOVERY_ALERT_THRESHOLD_MS, STREAM_RECOVERY_STABILITY_WINDOW_MS, REPLAY_GATE_DRAIN_MAX_ATTEMPTS, REPLAY_GATE_DRAIN_RETRY_DELAY_MS, SEMVER_RE, isRecord5, isPositiveNumber, SYSTEM_CONFIG_VALIDATORS, XmtpService;
58607
+ var import_node_fs24, import_node_path28, DEFAULT_DATA_DIR, XMTP_INSTALLATION_WARNING_THRESHOLD, XMTP_INSTALLATION_NEAR_LIMIT_THRESHOLD, REPLAY_SCAN_INITIAL_BACKOFF_MS, REPLAY_SCAN_MAX_BACKOFF_MS, SENSITIVE_WORDS_LAZY_RETRY_COOLDOWN_MS, InboundReplayGate, SYSTEM_CONFIG_DEFAULTS, STREAM_RECOVERY_ALERT_THRESHOLD_MS, STREAM_RECOVERY_STABILITY_WINDOW_MS, REPLAY_GATE_DRAIN_MAX_ATTEMPTS, REPLAY_GATE_DRAIN_RETRY_DELAY_MS, SEMVER_RE, isRecord5, isPositiveNumber, SYSTEM_CONFIG_VALIDATORS, XmtpService;
57551
58608
  var init_xmtp_sdk = __esm({
57552
58609
  "../core/src/xmtp-sdk/index.ts"() {
57553
58610
  "use strict";
57554
58611
  init_log();
57555
- import_node_fs22 = require("node:fs");
57556
- import_node_path27 = require("node:path");
58612
+ import_node_fs24 = require("node:fs");
58613
+ import_node_path28 = require("node:path");
57557
58614
  init_dist4();
57558
58615
  init_dist2();
57559
58616
  init_sentry_logger();
@@ -60789,7 +61846,7 @@ var init_envelope = __esm({
60789
61846
  });
60790
61847
 
60791
61848
  // src/invalid-message-store.ts
60792
- function loadSqlite4() {
61849
+ function loadSqlite5() {
60793
61850
  const originalEmitWarning = process.emitWarning;
60794
61851
  process.emitWarning = ((warning, ...args) => {
60795
61852
  const message = typeof warning === "string" ? warning : warning.message;
@@ -60804,22 +61861,22 @@ function loadSqlite4() {
60804
61861
  process.emitWarning = originalEmitWarning;
60805
61862
  }
60806
61863
  }
60807
- var import_node_fs23, import_node_path28, DatabaseSync3, InvalidXmtpMessageStore;
61864
+ var import_node_fs25, import_node_path29, DatabaseSync4, InvalidXmtpMessageStore;
60808
61865
  var init_invalid_message_store = __esm({
60809
61866
  "src/invalid-message-store.ts"() {
60810
61867
  "use strict";
60811
- import_node_fs23 = require("node:fs");
60812
- import_node_path28 = require("node:path");
61868
+ import_node_fs25 = require("node:fs");
61869
+ import_node_path29 = require("node:path");
60813
61870
  init_paths();
60814
- ({ DatabaseSync: DatabaseSync3 } = loadSqlite4());
61871
+ ({ DatabaseSync: DatabaseSync4 } = loadSqlite5());
60815
61872
  InvalidXmtpMessageStore = class {
60816
61873
  dbPath;
60817
61874
  db;
60818
61875
  constructor(homeDir) {
60819
61876
  const paths = resolveTaskPaths(homeDir);
60820
- this.dbPath = (0, import_node_path28.join)(paths.sqliteDir, "invalid-xmtp-messages.sqlite");
60821
- (0, import_node_fs23.mkdirSync)((0, import_node_path28.dirname)(this.dbPath), { recursive: true });
60822
- this.db = new DatabaseSync3(this.dbPath);
61877
+ this.dbPath = (0, import_node_path29.join)(paths.sqliteDir, "invalid-xmtp-messages.sqlite");
61878
+ (0, import_node_fs25.mkdirSync)((0, import_node_path29.dirname)(this.dbPath), { recursive: true });
61879
+ this.db = new DatabaseSync4(this.dbPath);
60823
61880
  this.ensureReady();
60824
61881
  }
60825
61882
  close() {
@@ -62264,7 +63321,7 @@ function buildAiAdapterCommand(options) {
62264
63321
  function readCodexAddDirs(env = process.env) {
62265
63322
  const raw = env.OKX_A2A_AI_CODEX_ADD_DIRS ?? env.OKX_AGENT_TASK_CODEX_ADD_DIRS ?? "";
62266
63323
  const seen = /* @__PURE__ */ new Set();
62267
- return raw.split(import_node_path29.delimiter).map((value) => expandHomePath(value.trim())).filter(Boolean).filter((dir) => {
63324
+ return raw.split(import_node_path30.delimiter).map((value) => expandHomePath(value.trim())).filter(Boolean).filter((dir) => {
62268
63325
  if (seen.has(dir)) {
62269
63326
  return false;
62270
63327
  }
@@ -62277,7 +63334,7 @@ function expandHomePath(value) {
62277
63334
  return (0, import_node_os9.homedir)();
62278
63335
  }
62279
63336
  if (value.startsWith("~/")) {
62280
- return (0, import_node_path29.join)((0, import_node_os9.homedir)(), value.slice(2));
63337
+ return (0, import_node_path30.join)((0, import_node_os9.homedir)(), value.slice(2));
62281
63338
  }
62282
63339
  return value;
62283
63340
  }
@@ -62494,9 +63551,9 @@ function formatOpenClawSessionKey(sessionKey, agentId) {
62494
63551
  function buildClaudeAddDirArgs(homeDir, env) {
62495
63552
  const dirs = [
62496
63553
  homeDir,
62497
- (0, import_node_path29.join)((0, import_node_os9.homedir)(), ".agents"),
62498
- (0, import_node_path29.join)(__dirname, ".."),
62499
- ...env.OKX_A2A_AI_CLAUDE_ADD_DIRS ? env.OKX_A2A_AI_CLAUDE_ADD_DIRS.split(import_node_path29.delimiter).filter(Boolean) : []
63554
+ (0, import_node_path30.join)((0, import_node_os9.homedir)(), ".agents"),
63555
+ (0, import_node_path30.join)(__dirname, ".."),
63556
+ ...env.OKX_A2A_AI_CLAUDE_ADD_DIRS ? env.OKX_A2A_AI_CLAUDE_ADD_DIRS.split(import_node_path30.delimiter).filter(Boolean) : []
62500
63557
  ];
62501
63558
  return ["--add-dir", ...[...new Set(dirs)]];
62502
63559
  }
@@ -62548,16 +63605,16 @@ function applyArgTemplate(template, options) {
62548
63605
  const homeDir = options.homeDir ?? resolveTaskPaths().homeDir;
62549
63606
  const cwd = options.cwd ?? process.cwd();
62550
63607
  return template.map((arg) => {
62551
- return arg.replaceAll("{prompt}", options.prompt).replaceAll("{sessionId}", options.sessionId ?? "").replaceAll("{homeDir}", homeDir).replaceAll("{cwd}", cwd).replaceAll("{repoCli}", (0, import_node_path29.join)(__dirname, "cli.js"));
63608
+ return arg.replaceAll("{prompt}", options.prompt).replaceAll("{sessionId}", options.sessionId ?? "").replaceAll("{homeDir}", homeDir).replaceAll("{cwd}", cwd).replaceAll("{repoCli}", (0, import_node_path30.join)(__dirname, "cli.js"));
62552
63609
  });
62553
63610
  }
62554
- var import_node_os9, import_node_path29, CLAUDE_ALLOWED_TOOLS, CLAUDE_PERMISSION_MODES, CODEX_SANDBOX_MODES, CODEX_APPROVAL_POLICIES;
63611
+ var import_node_os9, import_node_path30, CLAUDE_ALLOWED_TOOLS, CLAUDE_PERMISSION_MODES, CODEX_SANDBOX_MODES, CODEX_APPROVAL_POLICIES;
62555
63612
  var init_ai_adapter = __esm({
62556
63613
  "src/ai-adapter.ts"() {
62557
63614
  "use strict";
62558
63615
  init_log();
62559
63616
  import_node_os9 = require("node:os");
62560
- import_node_path29 = require("node:path");
63617
+ import_node_path30 = require("node:path");
62561
63618
  init_ai_command();
62562
63619
  init_paths();
62563
63620
  init_session_store();
@@ -62617,7 +63674,7 @@ function aiRunSentryExtra(input) {
62617
63674
  closeSignal: input.closeSignal ?? "",
62618
63675
  timedOut: input.timedOut === void 0 ? "" : String(input.timedOut),
62619
63676
  aiSessionId: input.aiSessionId ?? "",
62620
- aiLogFile: input.logPath ? (0, import_node_path30.basename)(input.logPath) : "",
63677
+ aiLogFile: input.logPath ? (0, import_node_path31.basename)(input.logPath) : "",
62621
63678
  commandPendingMs: input.commandPendingMs ?? "",
62622
63679
  queueWaitMs: input.queueWaitMs ?? "",
62623
63680
  storeReadMs: input.storeReadMs ?? "",
@@ -62645,7 +63702,7 @@ function resolveProviderCommandWithSelfHeal(options) {
62645
63702
  const env = options.env ?? process.env;
62646
63703
  const storedCommand = options.provider === "codex" ? options.store.getAiProviderCommand(options.provider) : null;
62647
63704
  const resolved = resolveAiProviderCommandWithSource(options.provider, env, storedCommand, options.platform);
62648
- if (options.provider === "codex" && resolved.source !== "explicit_override" && resolved.command !== storedCommand && (0, import_node_path30.isAbsolute)(resolved.command)) {
63705
+ if (options.provider === "codex" && resolved.source !== "explicit_override" && resolved.command !== storedCommand && (0, import_node_path31.isAbsolute)(resolved.command)) {
62649
63706
  options.store.setAiProviderCommand(options.provider, resolved.command);
62650
63707
  }
62651
63708
  return { command: resolved.command, commandSource: resolved.source };
@@ -62677,7 +63734,7 @@ function aiRunToolFailureSentryExtra(failure, context) {
62677
63734
  closeSignal: context.closeSignal ?? "",
62678
63735
  timedOut: String(context.timedOut),
62679
63736
  aiSessionId: context.aiSessionId ?? "",
62680
- aiLogFile: (0, import_node_path30.basename)(context.logPath)
63737
+ aiLogFile: (0, import_node_path31.basename)(context.logPath)
62681
63738
  }).filter(([, value]) => value !== "");
62682
63739
  return entries.reduce((out, [key, value]) => {
62683
63740
  out[key] = String(value);
@@ -62700,7 +63757,7 @@ function safeProcessCwd() {
62700
63757
  }
62701
63758
  function isDirectory(path2) {
62702
63759
  try {
62703
- return (0, import_node_fs24.statSync)(path2).isDirectory();
63760
+ return (0, import_node_fs26.statSync)(path2).isDirectory();
62704
63761
  } catch {
62705
63762
  return false;
62706
63763
  }
@@ -63039,9 +64096,9 @@ function getPreferredCodexWritableRoot(target) {
63039
64096
  const expanded = expandHomePath2(target);
63040
64097
  const home = (0, import_node_os10.homedir)();
63041
64098
  const appRoots = [
63042
- (0, import_node_path30.join)(home, ".onchainos", "task"),
63043
- (0, import_node_path30.join)(home, ".onchainos", "deliverables"),
63044
- (0, import_node_path30.join)(home, ".okx-agent-task")
64099
+ (0, import_node_path31.join)(home, ".onchainos", "task"),
64100
+ (0, import_node_path31.join)(home, ".onchainos", "deliverables"),
64101
+ (0, import_node_path31.join)(home, ".okx-agent-task")
63045
64102
  ];
63046
64103
  for (const root of appRoots) {
63047
64104
  if (expanded === root || expanded.startsWith(`${root}/`)) {
@@ -63056,7 +64113,7 @@ function inferAppOwnedCodexWritableRoot(failure) {
63056
64113
  return void 0;
63057
64114
  }
63058
64115
  if (containsOnchainosCommand(command) && /\b0x[0-9a-fA-F]{16,}\b/.test(command)) {
63059
- return (0, import_node_path30.join)((0, import_node_os10.homedir)(), ".onchainos", "task");
64116
+ return (0, import_node_path31.join)((0, import_node_os10.homedir)(), ".onchainos", "task");
63060
64117
  }
63061
64118
  return void 0;
63062
64119
  }
@@ -63065,7 +64122,7 @@ function expandHomePath2(value) {
63065
64122
  return (0, import_node_os10.homedir)();
63066
64123
  }
63067
64124
  if (value.startsWith("~/")) {
63068
- return (0, import_node_path30.join)((0, import_node_os10.homedir)(), value.slice(2));
64125
+ return (0, import_node_path31.join)((0, import_node_os10.homedir)(), value.slice(2));
63069
64126
  }
63070
64127
  return value;
63071
64128
  }
@@ -64046,16 +65103,16 @@ function shortenJobId2(jobId) {
64046
65103
  }
64047
65104
  return `${jobId.slice(0, 6)}\u2026${jobId.slice(-4)}`;
64048
65105
  }
64049
- var import_node_crypto13, import_node_fs24, import_promises12, import_node_os10, import_node_path30, AiRunner, CODEX_TOOL_FAILURE_MARKER;
65106
+ var import_node_crypto13, import_node_fs26, import_promises12, import_node_os10, import_node_path31, AiRunner, CODEX_TOOL_FAILURE_MARKER;
64050
65107
  var init_ai_runner = __esm({
64051
65108
  "src/ai-runner.ts"() {
64052
65109
  "use strict";
64053
65110
  init_log();
64054
65111
  import_node_crypto13 = require("node:crypto");
64055
- import_node_fs24 = require("node:fs");
65112
+ import_node_fs26 = require("node:fs");
64056
65113
  import_promises12 = require("node:fs/promises");
64057
65114
  import_node_os10 = require("node:os");
64058
- import_node_path30 = require("node:path");
65115
+ import_node_path31 = require("node:path");
64059
65116
  init_ai_command();
64060
65117
  init_paths();
64061
65118
  init_file_store();
@@ -64200,7 +65257,7 @@ var init_ai_runner = __esm({
64200
65257
  ensureTaskDir(this.logsDir);
64201
65258
  const lifecycleLogsEnabled = isAiLifecycleLoggingEnabled();
64202
65259
  const logPath = lifecycleLogsEnabled ? this.buildRunLogPath(request) : "";
64203
- const log = lifecycleLogsEnabled ? (0, import_node_fs24.createWriteStream)(logPath, { flags: "a" }) : null;
65260
+ const log = lifecycleLogsEnabled ? (0, import_node_fs26.createWriteStream)(logPath, { flags: "a" }) : null;
64204
65261
  let existing = null;
64205
65262
  let storeReadStartedAt;
64206
65263
  let storeReadEndedAt;
@@ -64686,10 +65743,10 @@ var init_ai_runner = __esm({
64686
65743
  const safeMessageId = encodeURIComponent(request.messageId);
64687
65744
  if (request.source === "job-dispatch") {
64688
65745
  const safeJobId = encodeURIComponent(request.jobId ?? "unknown");
64689
- return (0, import_node_path30.join)(this.logsDir, `ai-${safeJobId}-${safeMessageId}.log`);
65746
+ return (0, import_node_path31.join)(this.logsDir, `ai-${safeJobId}-${safeMessageId}.log`);
64690
65747
  }
64691
65748
  const safeSessionKey = encodeURIComponent(request.sessionKey);
64692
- return (0, import_node_path30.join)(this.logsDir, `ai-session-${safeSessionKey}-${safeMessageId}.log`);
65749
+ return (0, import_node_path31.join)(this.logsDir, `ai-session-${safeSessionKey}-${safeMessageId}.log`);
64693
65750
  }
64694
65751
  readRunAiSessionId(provider, request, file, sessionMeta) {
64695
65752
  if (request.source === "job-dispatch" && request.jobId) {
@@ -65028,7 +66085,7 @@ var init_ai_runner = __esm({
65028
66085
  async appendLlmLog(entry) {
65029
66086
  try {
65030
66087
  ensureTaskDir(this.logsDir);
65031
- await (0, import_promises12.appendFile)((0, import_node_path30.join)(this.logsDir, "llm.log"), formatLlmLogEntry(entry), "utf8");
66088
+ await (0, import_promises12.appendFile)((0, import_node_path31.join)(this.logsDir, "llm.log"), formatLlmLogEntry(entry), "utf8");
65032
66089
  } catch (err2) {
65033
66090
  errorWithTimestamp("[okx-agent-task] failed to append llm.log:", err2);
65034
66091
  }
@@ -68456,12 +69513,12 @@ async function isGatewayAvailableForHeartbeat(options) {
68456
69513
  }
68457
69514
  async function getHermesGatewayPluginStatus(options = {}) {
68458
69515
  const env = options.env ?? process.env;
68459
- const hermesHome = env.HERMES_HOME?.trim() || (0, import_node_path31.join)((0, import_node_os11.homedir)(), ".hermes");
68460
- const pluginYamlPath = (0, import_node_path31.join)(hermesHome, "plugins", "platforms", "okx-a2a", "plugin.yaml");
68461
- if (!(0, import_node_fs25.existsSync)(pluginYamlPath)) {
69516
+ const hermesHome = env.HERMES_HOME?.trim() || (0, import_node_path32.join)((0, import_node_os11.homedir)(), ".hermes");
69517
+ const pluginYamlPath = (0, import_node_path32.join)(hermesHome, "plugins", "platforms", "okx-a2a", "plugin.yaml");
69518
+ if (!(0, import_node_fs27.existsSync)(pluginYamlPath)) {
68462
69519
  return { enabled: false, reason: "plugin_yaml_missing", hermesHome, checkedPath: pluginYamlPath };
68463
69520
  }
68464
- const configPath = (0, import_node_path31.join)(hermesHome, "config.yaml");
69521
+ const configPath = (0, import_node_path32.join)(hermesHome, "config.yaml");
68465
69522
  let content2;
68466
69523
  try {
68467
69524
  content2 = await (0, import_promises13.readFile)(configPath, "utf8");
@@ -68693,12 +69750,12 @@ async function runListenerWithLock(options, paths) {
68693
69750
  });
68694
69751
  }
68695
69752
  });
68696
- service.setPluginVersion("0.2.10");
69753
+ service.setPluginVersion("0.2.11-beta-8fef2ef558-260901171734");
68697
69754
  await service.init();
68698
69755
  const pluginVersionStatus = service.pluginVersionStatus;
68699
69756
  if (pluginVersionStatus.unavailable) {
68700
69757
  throw new Error(
68701
- `@okxweb3/a2a-node v${"0.2.10"} is below the required minimum v${pluginVersionStatus.minVersion}`
69758
+ `@okxweb3/a2a-node v${"0.2.11-beta-8fef2ef558-260901171734"} is below the required minimum v${pluginVersionStatus.minVersion}`
68702
69759
  );
68703
69760
  }
68704
69761
  const systemConfig = service.getSystemConfig();
@@ -68726,7 +69783,7 @@ async function runListenerWithLock(options, paths) {
68726
69783
  onchainosAgentId: "*",
68727
69784
  reason: "system-config missing sentryDsn",
68728
69785
  pluginId: "@okxweb3/a2a-node",
68729
- pluginVersion: "0.2.10"
69786
+ pluginVersion: "0.2.11-beta-8fef2ef558-260901171734"
68730
69787
  });
68731
69788
  }
68732
69789
  logWithTimestamp(
@@ -69076,15 +70133,15 @@ async function timeSettled(fn) {
69076
70133
  return { durationMs: Date.now() - startedAt, error };
69077
70134
  }
69078
70135
  }
69079
- var import_node_fs25, import_promises13, import_node_os11, import_node_path31, DEFAULT_OFFLINE_REPLAY_INTERVAL_SEC, DEFAULT_XMTP_CLIENT_RECYCLE_INTERVAL_SEC, XMTP_CLIENT_RECYCLE_INTERVAL_ENV, HEARTBEAT_GATEWAY_CHECK_TIMEOUT_MS, AUTH_RECOVERY_PROBE_INTERVAL_MS, AUTH_RECOVERY_REFRESH_BACKOFF_MS, AgentRefreshAuthGate, AgentRefreshCoordinator, ListenerDeferredTaskScheduler, ListenerMaintenanceGate, UPGRADE_RECOMMENDATION_IDEMPOTENCY_KEY, SHUTDOWN_FORCE_RESOLVE_MS;
70136
+ var import_node_fs27, import_promises13, import_node_os11, import_node_path32, DEFAULT_OFFLINE_REPLAY_INTERVAL_SEC, DEFAULT_XMTP_CLIENT_RECYCLE_INTERVAL_SEC, XMTP_CLIENT_RECYCLE_INTERVAL_ENV, HEARTBEAT_GATEWAY_CHECK_TIMEOUT_MS, AUTH_RECOVERY_PROBE_INTERVAL_MS, AUTH_RECOVERY_REFRESH_BACKOFF_MS, AgentRefreshAuthGate, AgentRefreshCoordinator, ListenerDeferredTaskScheduler, ListenerMaintenanceGate, UPGRADE_RECOMMENDATION_IDEMPOTENCY_KEY, SHUTDOWN_FORCE_RESOLVE_MS;
69080
70137
  var init_listener = __esm({
69081
70138
  "src/listener.ts"() {
69082
70139
  "use strict";
69083
70140
  init_log();
69084
- import_node_fs25 = require("node:fs");
70141
+ import_node_fs27 = require("node:fs");
69085
70142
  import_promises13 = require("node:fs/promises");
69086
70143
  import_node_os11 = require("node:os");
69087
- import_node_path31 = require("node:path");
70144
+ import_node_path32 = require("node:path");
69088
70145
  init_onchainos();
69089
70146
  init_system_config();
69090
70147
  init_offline_replay_capability();
@@ -69329,9 +70386,9 @@ async function handleXmtpTestCommand(args, releaseInfo) {
69329
70386
  async function startXmtpTest(args, releaseInfo) {
69330
70387
  assertKnownOptions(args, /* @__PURE__ */ new Set(["--name", "--run-id", "--json"]));
69331
70388
  const paths = resolveTaskPaths();
69332
- const testsDir = (0, import_node_path32.join)(paths.homeDir, "xmtp-tests");
70389
+ const testsDir = (0, import_node_path33.join)(paths.homeDir, "xmtp-tests");
69333
70390
  await ensurePrivateDir(testsDir);
69334
- const active = await readJsonIfExists((0, import_node_path32.join)(testsDir, ACTIVE_FILE));
70391
+ const active = await readJsonIfExists((0, import_node_path33.join)(testsDir, ACTIVE_FILE));
69335
70392
  if (active?.runId) {
69336
70393
  throw new Error(
69337
70394
  `XMTP test ${active.runId} is already active. Run \`okx-a2a xmtp-test stop\` first.`
@@ -69370,7 +70427,7 @@ async function startXmtpTest(args, releaseInfo) {
69370
70427
  ...releaseInfo
69371
70428
  };
69372
70429
  await writeJson(files.manifestPath, manifest);
69373
- await writeJson((0, import_node_path32.join)(testsDir, ACTIVE_FILE), {
70430
+ await writeJson((0, import_node_path33.join)(testsDir, ACTIVE_FILE), {
69374
70431
  runId,
69375
70432
  startedAt: manifest.startedAt
69376
70433
  });
@@ -69393,7 +70450,7 @@ Run \`okx-a2a xmtp-test watch\` to open the realtime dashboard.`);
69393
70450
  async function stopXmtpTest(args) {
69394
70451
  assertKnownOptions(args, /* @__PURE__ */ new Set(["--json"]));
69395
70452
  const testsDir = resolveTestsDir();
69396
- const activePath = (0, import_node_path32.join)(testsDir, ACTIVE_FILE);
70453
+ const activePath = (0, import_node_path33.join)(testsDir, ACTIVE_FILE);
69397
70454
  const active = await readJsonIfExists(activePath);
69398
70455
  if (!active?.runId) {
69399
70456
  throw new Error("No active XMTP test.");
@@ -69687,17 +70744,17 @@ function formatJobEvent(event) {
69687
70744
  return `${timestamp} ${businessEvent.padEnd(34)} ${role}#${agent} ${source}${timings.length > 0 ? ` ${timings.join(" ")}` : ""}`;
69688
70745
  }
69689
70746
  function resolveTestsDir() {
69690
- return (0, import_node_path32.join)(resolveTaskPaths().homeDir, "xmtp-tests");
70747
+ return (0, import_node_path33.join)(resolveTaskPaths().homeDir, "xmtp-tests");
69691
70748
  }
69692
70749
  function resolveRunFiles(testsDir, runId) {
69693
70750
  validateRunId(runId);
69694
- const runDir = (0, import_node_path32.join)(testsDir, runId);
70751
+ const runDir = (0, import_node_path33.join)(testsDir, runId);
69695
70752
  return {
69696
70753
  testsDir,
69697
70754
  runDir,
69698
- manifestPath: (0, import_node_path32.join)(runDir, "manifest.json"),
69699
- eventsPath: (0, import_node_path32.join)(runDir, "events.jsonl"),
69700
- summaryPath: (0, import_node_path32.join)(runDir, "summary.json")
70755
+ manifestPath: (0, import_node_path33.join)(runDir, "manifest.json"),
70756
+ eventsPath: (0, import_node_path33.join)(runDir, "events.jsonl"),
70757
+ summaryPath: (0, import_node_path33.join)(runDir, "summary.json")
69701
70758
  };
69702
70759
  }
69703
70760
  async function resolveRequestedRunId(testsDir, args, preferActive = false) {
@@ -69705,7 +70762,7 @@ async function resolveRequestedRunId(testsDir, args, preferActive = false) {
69705
70762
  if (requested) {
69706
70763
  return validateRunId(requested);
69707
70764
  }
69708
- const active = await readJsonIfExists((0, import_node_path32.join)(testsDir, ACTIVE_FILE));
70765
+ const active = await readJsonIfExists((0, import_node_path33.join)(testsDir, ACTIVE_FILE));
69709
70766
  if (active?.runId && (preferActive || !args.includes("--latest"))) {
69710
70767
  return validateRunId(active.runId);
69711
70768
  }
@@ -69731,7 +70788,7 @@ async function findLatestRunId(testsDir) {
69731
70788
  continue;
69732
70789
  }
69733
70790
  const manifest = await readJsonIfExists(
69734
- (0, import_node_path32.join)(testsDir, entry.name, "manifest.json")
70791
+ (0, import_node_path33.join)(testsDir, entry.name, "manifest.json")
69735
70792
  );
69736
70793
  if (manifest?.runId && manifest.startedAt) {
69737
70794
  manifests.push(manifest);
@@ -69966,12 +71023,12 @@ function formatPercent(value) {
69966
71023
  function validTimestamp(value) {
69967
71024
  return typeof value === "string" && Number.isFinite(Date.parse(value));
69968
71025
  }
69969
- var import_promises14, import_node_path32, RUN_ID_PATTERN2, ACTIVE_FILE;
71026
+ var import_promises14, import_node_path33, RUN_ID_PATTERN2, ACTIVE_FILE;
69970
71027
  var init_xmtp_test_cli = __esm({
69971
71028
  "src/xmtp-test-cli.ts"() {
69972
71029
  "use strict";
69973
71030
  import_promises14 = require("node:fs/promises");
69974
- import_node_path32 = require("node:path");
71031
+ import_node_path33 = require("node:path");
69975
71032
  init_daemon();
69976
71033
  init_log_tail();
69977
71034
  init_paths();
@@ -113160,9 +114217,9 @@ var init_dist6 = __esm({
113160
114217
 
113161
114218
  // ../core/src/file-upload-safety.ts
113162
114219
  function getUnsafeFileUploadReason(filePath, sensitiveUploadReg = []) {
113163
- const expanded = (0, import_node_path33.resolve)(expandHome(filePath));
113164
- const target = (0, import_node_fs26.realpathSync)(expanded);
113165
- const targetName = (0, import_node_path33.basename)(target);
114220
+ const expanded = (0, import_node_path34.resolve)(expandHome(filePath));
114221
+ const target = (0, import_node_fs28.realpathSync)(expanded);
114222
+ const targetName = (0, import_node_path34.basename)(target);
113166
114223
  if (targetName === ".env" || targetName.startsWith(".env.")) {
113167
114224
  return ".env";
113168
114225
  }
@@ -113175,13 +114232,13 @@ function getUnsafeFileUploadReason(filePath, sensitiveUploadReg = []) {
113175
114232
  return null;
113176
114233
  }
113177
114234
  for (const dir of SENSITIVE_HOME_DIRS) {
113178
- const sensitiveDir = safeRealpath((0, import_node_path33.join)(home, dir));
114235
+ const sensitiveDir = safeRealpath((0, import_node_path34.join)(home, dir));
113179
114236
  if (sensitiveDir && isPathInside(target, sensitiveDir)) {
113180
114237
  return `~/${dir}`;
113181
114238
  }
113182
114239
  }
113183
114240
  for (const file of SENSITIVE_HOME_FILES) {
113184
- const sensitiveFile = safeRealpath((0, import_node_path33.join)(home, file));
114241
+ const sensitiveFile = safeRealpath((0, import_node_path34.join)(home, file));
113185
114242
  if (sensitiveFile && target === sensitiveFile) {
113186
114243
  return `~/${file}`;
113187
114244
  }
@@ -113209,27 +114266,27 @@ function expandHome(filePath) {
113209
114266
  if (filePath === "~") {
113210
114267
  return (0, import_node_os12.homedir)();
113211
114268
  }
113212
- if (filePath.startsWith(`~${import_node_path33.sep}`)) {
113213
- return (0, import_node_path33.join)((0, import_node_os12.homedir)(), filePath.slice(2));
114269
+ if (filePath.startsWith(`~${import_node_path34.sep}`)) {
114270
+ return (0, import_node_path34.join)((0, import_node_os12.homedir)(), filePath.slice(2));
113214
114271
  }
113215
114272
  return filePath;
113216
114273
  }
113217
114274
  function safeRealpath(path2) {
113218
- if (!(0, import_node_fs26.existsSync)(path2)) {
114275
+ if (!(0, import_node_fs28.existsSync)(path2)) {
113219
114276
  return null;
113220
114277
  }
113221
- return (0, import_node_fs26.realpathSync)(path2);
114278
+ return (0, import_node_fs28.realpathSync)(path2);
113222
114279
  }
113223
114280
  function isPathInside(target, dir) {
113224
- return target === dir || target.startsWith(`${dir}${import_node_path33.sep}`);
114281
+ return target === dir || target.startsWith(`${dir}${import_node_path34.sep}`);
113225
114282
  }
113226
- var import_node_fs26, import_node_os12, import_node_path33, SENSITIVE_HOME_DIRS, SENSITIVE_HOME_FILES, UNSAFE_FILE_UPLOAD_MESSAGE;
114283
+ var import_node_fs28, import_node_os12, import_node_path34, SENSITIVE_HOME_DIRS, SENSITIVE_HOME_FILES, UNSAFE_FILE_UPLOAD_MESSAGE;
113227
114284
  var init_file_upload_safety = __esm({
113228
114285
  "../core/src/file-upload-safety.ts"() {
113229
114286
  "use strict";
113230
- import_node_fs26 = require("node:fs");
114287
+ import_node_fs28 = require("node:fs");
113231
114288
  import_node_os12 = require("node:os");
113232
- import_node_path33 = require("node:path");
114289
+ import_node_path34 = require("node:path");
113233
114290
  SENSITIVE_HOME_DIRS = [
113234
114291
  ".ssh",
113235
114292
  ".gnupg",
@@ -113237,7 +114294,7 @@ var init_file_upload_safety = __esm({
113237
114294
  ".azure",
113238
114295
  ".kube",
113239
114296
  ".docker",
113240
- (0, import_node_path33.join)(".config", "gcloud")
114297
+ (0, import_node_path34.join)(".config", "gcloud")
113241
114298
  ];
113242
114299
  SENSITIVE_HOME_FILES = [
113243
114300
  ".npmrc",
@@ -113299,7 +114356,7 @@ function hasHelpFlag(args) {
113299
114356
  return args.some((arg) => arg === "-h" || arg === "--help" || arg === "help");
113300
114357
  }
113301
114358
  async function uploadFile(params) {
113302
- const filename = params.filename || (0, import_node_path34.basename)(params.filePath);
114359
+ const filename = params.filename || (0, import_node_path35.basename)(params.filePath);
113303
114360
  const mimeType = params.mimeType || "application/octet-stream";
113304
114361
  const uploadConfig = readUploadSystemConfig();
113305
114362
  const unsafeReason = getUnsafeFileUploadReason(params.filePath, uploadConfig.sensitiveUploadReg);
@@ -113315,16 +114372,16 @@ async function uploadFile(params) {
113315
114372
  return;
113316
114373
  }
113317
114374
  const maxFileSizeBytes = uploadConfig.maxFileSizeBytes;
113318
- const fileSize = (0, import_node_fs27.statSync)(params.filePath).size;
114375
+ const fileSize = (0, import_node_fs29.statSync)(params.filePath).size;
113319
114376
  if (fileSize > maxFileSizeBytes) {
113320
114377
  throw new Error(formatFileTooLargeMessage(maxFileSizeBytes));
113321
114378
  }
113322
- const data = (0, import_node_fs27.readFileSync)(params.filePath);
114379
+ const data = (0, import_node_fs29.readFileSync)(params.filePath);
113323
114380
  const attachment = { filename, mimeType, data: new Uint8Array(data) };
113324
114381
  const encrypted = await RemoteAttachmentCodec.encodeEncrypted(attachment, new AttachmentCodec());
113325
114382
  ensureFileDirs();
113326
- const encryptedPath = (0, import_node_path34.resolve)(FILE_WORK_DIR, `${(0, import_node_crypto17.randomUUID)()}.enc`);
113327
- (0, import_node_fs27.writeFileSync)(encryptedPath, encrypted.payload);
114383
+ const encryptedPath = (0, import_node_path35.resolve)(FILE_WORK_DIR, `${(0, import_node_crypto17.randomUUID)()}.enc`);
114384
+ (0, import_node_fs29.writeFileSync)(encryptedPath, encrypted.payload);
113328
114385
  try {
113329
114386
  const stdout = runOnchainos([
113330
114387
  "agent",
@@ -113360,14 +114417,14 @@ async function uploadFile(params) {
113360
114417
  }, null, 2));
113361
114418
  } finally {
113362
114419
  try {
113363
- (0, import_node_fs27.unlinkSync)(encryptedPath);
114420
+ (0, import_node_fs29.unlinkSync)(encryptedPath);
113364
114421
  } catch {
113365
114422
  }
113366
114423
  }
113367
114424
  }
113368
114425
  async function downloadFile(params) {
113369
114426
  ensureFileDirs();
113370
- const encryptedPath = (0, import_node_path34.resolve)(FILE_WORK_DIR, `${(0, import_node_crypto17.randomUUID)()}.enc`);
114427
+ const encryptedPath = (0, import_node_path35.resolve)(FILE_WORK_DIR, `${(0, import_node_crypto17.randomUUID)()}.enc`);
113371
114428
  try {
113372
114429
  const stdout = runOnchainos([
113373
114430
  "agent",
@@ -113391,7 +114448,7 @@ async function downloadFile(params) {
113391
114448
  }));
113392
114449
  throw new Error(`file download failed: ${stdout}`);
113393
114450
  }
113394
- const payload = new Uint8Array((0, import_node_fs27.readFileSync)(encryptedPath));
114451
+ const payload = new Uint8Array((0, import_node_fs29.readFileSync)(encryptedPath));
113395
114452
  const digestBytes = new Uint8Array(await import_node_crypto17.webcrypto.subtle.digest("SHA-256", payload));
113396
114453
  const actualDigest = Array.from(digestBytes).map((byte) => byte.toString(16).padStart(2, "0")).join("");
113397
114454
  if (actualDigest !== params.digest) {
@@ -113403,12 +114460,12 @@ async function downloadFile(params) {
113403
114460
  const outputFilename = params.filename || attachment.filename || `${(0, import_node_crypto17.randomUUID)()}.bin`;
113404
114461
  const outputDir = DOWNLOADS_DIR;
113405
114462
  ensureA2aTaskDir(outputDir);
113406
- const outputPath = (0, import_node_path34.resolve)(outputDir, (0, import_node_path34.basename)(outputFilename));
113407
- (0, import_node_fs27.writeFileSync)(outputPath, attachment.data);
114463
+ const outputPath = (0, import_node_path35.resolve)(outputDir, (0, import_node_path35.basename)(outputFilename));
114464
+ (0, import_node_fs29.writeFileSync)(outputPath, attachment.data);
113408
114465
  console.log(outputPath);
113409
114466
  } finally {
113410
114467
  try {
113411
- (0, import_node_fs27.unlinkSync)(encryptedPath);
114468
+ (0, import_node_fs29.unlinkSync)(encryptedPath);
113412
114469
  } catch {
113413
114470
  }
113414
114471
  }
@@ -113505,7 +114562,7 @@ function readUploadSystemConfig() {
113505
114562
  const res = parseCliJson2(stdout, "system-config");
113506
114563
  if (res.data && typeof res.data === "object") {
113507
114564
  ensureA2aTaskDir(OKX_A2A_PATHS.xmtpDir);
113508
- (0, import_node_fs27.writeFileSync)(SYSTEM_CONFIG_PATH, JSON.stringify(res.data));
114565
+ (0, import_node_fs29.writeFileSync)(SYSTEM_CONFIG_PATH, JSON.stringify(res.data));
113509
114566
  }
113510
114567
  return parseUploadSystemConfig(res.data ?? {});
113511
114568
  } catch {
@@ -113528,10 +114585,10 @@ function fileCliSentryExtra(operation, reason, extra = {}) {
113528
114585
  }
113529
114586
  function readSystemConfigFromCache() {
113530
114587
  try {
113531
- if (!(0, import_node_fs27.existsSync)(SYSTEM_CONFIG_PATH)) {
114588
+ if (!(0, import_node_fs29.existsSync)(SYSTEM_CONFIG_PATH)) {
113532
114589
  return null;
113533
114590
  }
113534
- return JSON.parse((0, import_node_fs27.readFileSync)(SYSTEM_CONFIG_PATH, "utf8"));
114591
+ return JSON.parse((0, import_node_fs29.readFileSync)(SYSTEM_CONFIG_PATH, "utf8"));
113535
114592
  } catch {
113536
114593
  return null;
113537
114594
  }
@@ -113565,14 +114622,14 @@ function readRequiredOption(args, name) {
113565
114622
  }
113566
114623
  return value;
113567
114624
  }
113568
- var import_node_crypto17, import_node_fs27, import_node_path34, import_proto2, OKX_A2A_PATHS, OKX_A2A_HOME_DIR, FILE_WORK_DIR, DOWNLOADS_DIR, SYSTEM_CONFIG_PATH;
114625
+ var import_node_crypto17, import_node_fs29, import_node_path35, import_proto2, OKX_A2A_PATHS, OKX_A2A_HOME_DIR, FILE_WORK_DIR, DOWNLOADS_DIR, SYSTEM_CONFIG_PATH;
113569
114626
  var init_file_cli = __esm({
113570
114627
  "src/file-cli.ts"() {
113571
114628
  "use strict";
113572
114629
  init_win_spawn();
113573
114630
  import_node_crypto17 = require("node:crypto");
113574
- import_node_fs27 = require("node:fs");
113575
- import_node_path34 = require("node:path");
114631
+ import_node_fs29 = require("node:fs");
114632
+ import_node_path35 = require("node:path");
113576
114633
  init_dist6();
113577
114634
  import_proto2 = __toESM(require_node4());
113578
114635
  init_a2a_paths();
@@ -113583,7 +114640,7 @@ var init_file_cli = __esm({
113583
114640
  OKX_A2A_HOME_DIR = OKX_A2A_PATHS.homeDir;
113584
114641
  FILE_WORK_DIR = process.env.OKX_A2A_FILE_WORK_DIR || OKX_A2A_PATHS.filesDir;
113585
114642
  DOWNLOADS_DIR = process.env.OKX_A2A_DOWNLOADS_DIR || OKX_A2A_PATHS.downloadsDir;
113586
- SYSTEM_CONFIG_PATH = (0, import_node_path34.resolve)(OKX_A2A_PATHS.xmtpDir, "system-config.json");
114643
+ SYSTEM_CONFIG_PATH = (0, import_node_path35.resolve)(OKX_A2A_PATHS.xmtpDir, "system-config.json");
113587
114644
  }
113588
114645
  });
113589
114646
 
@@ -113594,12 +114651,12 @@ __export(user_attention_cli_exports, {
113594
114651
  });
113595
114652
  async function handleUserCommand(args) {
113596
114653
  const subcommand = args[0];
113597
- if (!subcommand || args.every(isHelpArg)) {
114654
+ if (!subcommand || args.every(isHelpArg2)) {
113598
114655
  printUserUsage();
113599
114656
  return;
113600
114657
  }
113601
114658
  if (subcommand === "help") {
113602
- const helpTarget = args.slice(1).find((arg) => !isHelpArg(arg));
114659
+ const helpTarget = args.slice(1).find((arg) => !isHelpArg2(arg));
113603
114660
  if (!helpTarget) {
113604
114661
  printUserUsage();
113605
114662
  return;
@@ -113616,7 +114673,7 @@ async function handleUserCommand(args) {
113616
114673
  return;
113617
114674
  }
113618
114675
  const commandStartedAt = Date.now();
113619
- const parsed = parseArgs(args.slice(1));
114676
+ const parsed = parseArgs2(args.slice(1));
113620
114677
  const json = parsed.flags.has("json");
113621
114678
  const storeInitStartedAt = Date.now();
113622
114679
  const store = new SessionStore();
@@ -113733,7 +114790,7 @@ async function handleUserCommand(args) {
113733
114790
  function hasHelpFlag2(args) {
113734
114791
  return args.some((arg) => arg === "-h" || arg === "--help");
113735
114792
  }
113736
- function isHelpArg(arg) {
114793
+ function isHelpArg2(arg) {
113737
114794
  return arg === "-h" || arg === "--help" || arg === "help";
113738
114795
  }
113739
114796
  function printUserUsage() {
@@ -114252,7 +115309,7 @@ function runSyncWithoutConsoleOutput(fn) {
114252
115309
  console.error = originalError;
114253
115310
  }
114254
115311
  }
114255
- function parseArgs(args) {
115312
+ function parseArgs2(args) {
114256
115313
  const positional = [];
114257
115314
  const options = /* @__PURE__ */ new Map();
114258
115315
  const flags = /* @__PURE__ */ new Set();
@@ -114706,12 +115763,12 @@ __export(session_cli_exports, {
114706
115763
  });
114707
115764
  async function handleSessionCommand(args) {
114708
115765
  const subcommand = args[0];
114709
- if (!subcommand || args.every(isHelpArg2)) {
115766
+ if (!subcommand || args.every(isHelpArg3)) {
114710
115767
  printSessionUsage();
114711
115768
  return;
114712
115769
  }
114713
115770
  if (subcommand === "help") {
114714
- const helpTarget = args.slice(1).find((arg) => !isHelpArg2(arg));
115771
+ const helpTarget = args.slice(1).find((arg) => !isHelpArg3(arg));
114715
115772
  if (!helpTarget) {
114716
115773
  printSessionUsage();
114717
115774
  return;
@@ -114727,7 +115784,7 @@ async function handleSessionCommand(args) {
114727
115784
  }
114728
115785
  return;
114729
115786
  }
114730
- const parsed = parseArgs2(args.slice(1));
115787
+ const parsed = parseArgs3(args.slice(1));
114731
115788
  const json = parsed.flags.has("json");
114732
115789
  const store = new SessionStore();
114733
115790
  let usedOpenClawGateway = false;
@@ -114893,9 +115950,9 @@ async function handleSessionCommand(args) {
114893
115950
  }
114894
115951
  }
114895
115952
  function hasHelpFlag3(args) {
114896
- return args.some(isHelpArg2);
115953
+ return args.some(isHelpArg3);
114897
115954
  }
114898
- function isHelpArg2(arg) {
115955
+ function isHelpArg3(arg) {
114899
115956
  return arg === "-h" || arg === "--help" || arg === "help";
114900
115957
  }
114901
115958
  function printSessionUsage() {
@@ -115701,7 +116758,7 @@ function normalizeOptionalText4(value) {
115701
116758
  const normalized = value?.trim();
115702
116759
  return normalized ? normalized : null;
115703
116760
  }
115704
- function parseArgs2(args) {
116761
+ function parseArgs3(args) {
115705
116762
  const positional = [];
115706
116763
  const options = /* @__PURE__ */ new Map();
115707
116764
  const flags = /* @__PURE__ */ new Set();
@@ -115784,7 +116841,7 @@ async function handleXmtpDebugCli(args) {
115784
116841
  throw new Error(`Unknown xmtp-debug command: ${subcommand}`);
115785
116842
  }
115786
116843
  const action = subcommand;
115787
- const parsed = parseArgs3(args.slice(1));
116844
+ const parsed = parseArgs4(args.slice(1));
115788
116845
  rejectAccountOverride(parsed);
115789
116846
  const groupId = parsed.options.get("group-id");
115790
116847
  const jobId = parsed.options.get("job-id");
@@ -115878,7 +116935,7 @@ Options:
115878
116935
  --json Print machine-readable JSON.
115879
116936
  `);
115880
116937
  }
115881
- function parseArgs3(args) {
116938
+ function parseArgs4(args) {
115882
116939
  const options = /* @__PURE__ */ new Map();
115883
116940
  const flags = /* @__PURE__ */ new Set();
115884
116941
  for (let index2 = 0; index2 < args.length; index2 += 1) {
@@ -115966,7 +117023,7 @@ async function handleAiCommand(args) {
115966
117023
  return;
115967
117024
  }
115968
117025
  const subcommand = args[0] ?? "status";
115969
- const parsed = parseArgs4(args.slice(1));
117026
+ const parsed = parseArgs5(args.slice(1));
115970
117027
  const json = parsed.flags.has("json");
115971
117028
  const store = new SessionStore();
115972
117029
  try {
@@ -116090,7 +117147,7 @@ function output4(json, payload, human) {
116090
117147
  }
116091
117148
  console.log(human);
116092
117149
  }
116093
- function parseArgs4(args) {
117150
+ function parseArgs5(args) {
116094
117151
  const positional = [];
116095
117152
  const options = /* @__PURE__ */ new Map();
116096
117153
  const flags = /* @__PURE__ */ new Set();
@@ -116146,7 +117203,7 @@ function isPostjectRunnable() {
116146
117203
  function resolvePostjectCommand() {
116147
117204
  try {
116148
117205
  const cliPath = (0, import_node_module.createRequire)(__filename).resolve("postject/dist/cli.js");
116149
- if ((0, import_node_fs28.existsSync)(cliPath)) {
117206
+ if ((0, import_node_fs30.existsSync)(cliPath)) {
116150
117207
  return { command: process.execPath, prefixArgs: [cliPath] };
116151
117208
  }
116152
117209
  } catch {
@@ -116217,26 +117274,26 @@ function buildSeaConfig(entryPath, blobPath) {
116217
117274
  }
116218
117275
  async function installWindowsNativeLauncher(options) {
116219
117276
  const nodeExe = options.nodeExe ?? process.execPath;
116220
- if (!(0, import_node_fs28.existsSync)(options.cliPath)) {
117277
+ if (!(0, import_node_fs30.existsSync)(options.cliPath)) {
116221
117278
  throw new Error(`cannot build okx-a2a.exe: CLI entry not found at ${options.cliPath}`);
116222
117279
  }
116223
- if (!(0, import_node_fs28.existsSync)(nodeExe)) {
117280
+ if (!(0, import_node_fs30.existsSync)(nodeExe)) {
116224
117281
  throw new Error(`cannot build okx-a2a.exe: node executable not found at ${nodeExe}`);
116225
117282
  }
116226
- const exePath = (0, import_node_path35.join)(options.targetDir, NATIVE_LAUNCHER_EXE_NAME);
116227
- (0, import_node_fs28.mkdirSync)(options.targetDir, { recursive: true });
116228
- const work = (0, import_node_fs28.mkdtempSync)((0, import_node_path35.join)((0, import_node_os13.tmpdir)(), "okx-a2a-sea-"));
117283
+ const exePath = (0, import_node_path36.join)(options.targetDir, NATIVE_LAUNCHER_EXE_NAME);
117284
+ (0, import_node_fs30.mkdirSync)(options.targetDir, { recursive: true });
117285
+ const work = (0, import_node_fs30.mkdtempSync)((0, import_node_path36.join)((0, import_node_os13.tmpdir)(), "okx-a2a-sea-"));
116229
117286
  try {
116230
- const entryPath = (0, import_node_path35.join)(work, "launcher-entry.js");
116231
- const blobPath = (0, import_node_path35.join)(work, "okx-a2a.blob");
116232
- const configPath = (0, import_node_path35.join)(work, "sea-config.json");
116233
- (0, import_node_fs28.writeFileSync)(entryPath, buildLauncherEntryJs(options.cliPath), "utf8");
116234
- (0, import_node_fs28.writeFileSync)(configPath, buildSeaConfig(entryPath, blobPath), "utf8");
117287
+ const entryPath = (0, import_node_path36.join)(work, "launcher-entry.js");
117288
+ const blobPath = (0, import_node_path36.join)(work, "okx-a2a.blob");
117289
+ const configPath = (0, import_node_path36.join)(work, "sea-config.json");
117290
+ (0, import_node_fs30.writeFileSync)(entryPath, buildLauncherEntryJs(options.cliPath), "utf8");
117291
+ (0, import_node_fs30.writeFileSync)(configPath, buildSeaConfig(entryPath, blobPath), "utf8");
116235
117292
  (0, import_node_child_process9.execFileSync)(nodeExe, ["--experimental-sea-config", configPath], {
116236
117293
  stdio: "ignore",
116237
117294
  windowsHide: true
116238
117295
  });
116239
- (0, import_node_fs28.copyFileSync)(nodeExe, exePath);
117296
+ (0, import_node_fs30.copyFileSync)(nodeExe, exePath);
116240
117297
  const isMac = process.platform === "darwin";
116241
117298
  if (isMac) {
116242
117299
  try {
@@ -116256,19 +117313,19 @@ async function installWindowsNativeLauncher(options) {
116256
117313
  );
116257
117314
  return { exePath, cliPath: options.cliPath, nodeExe };
116258
117315
  } finally {
116259
- (0, import_node_fs28.rmSync)(work, { recursive: true, force: true });
117316
+ (0, import_node_fs30.rmSync)(work, { recursive: true, force: true });
116260
117317
  }
116261
117318
  }
116262
- function findWindowsNativeOkxA2aExe(pathValue, appData, userProfile, fileExists2 = import_node_fs28.existsSync) {
117319
+ function findWindowsNativeOkxA2aExe(pathValue, appData, userProfile, fileExists2 = import_node_fs30.existsSync) {
116263
117320
  const dirs = pathValue.split(";").map((d) => d.trim()).filter(Boolean);
116264
117321
  if (appData) {
116265
- dirs.push((0, import_node_path35.join)(appData, "npm"));
117322
+ dirs.push((0, import_node_path36.join)(appData, "npm"));
116266
117323
  }
116267
117324
  if (userProfile) {
116268
- dirs.push((0, import_node_path35.join)(userProfile, ".local", "bin"));
117325
+ dirs.push((0, import_node_path36.join)(userProfile, ".local", "bin"));
116269
117326
  }
116270
117327
  for (const dir of dirs) {
116271
- const candidate = (0, import_node_path35.join)(dir, NATIVE_LAUNCHER_EXE_NAME);
117328
+ const candidate = (0, import_node_path36.join)(dir, NATIVE_LAUNCHER_EXE_NAME);
116272
117329
  if (fileExists2(candidate)) {
116273
117330
  return candidate;
116274
117331
  }
@@ -116277,11 +117334,11 @@ function findWindowsNativeOkxA2aExe(pathValue, appData, userProfile, fileExists2
116277
117334
  }
116278
117335
  function resolveRunningCliPath() {
116279
117336
  const fromArgv = process.argv[1];
116280
- if (fromArgv && /(?:^|[\\/])cli\.js$/.test(fromArgv) && (0, import_node_fs28.existsSync)(fromArgv)) {
117337
+ if (fromArgv && /(?:^|[\\/])cli\.js$/.test(fromArgv) && (0, import_node_fs30.existsSync)(fromArgv)) {
116281
117338
  return fromArgv;
116282
117339
  }
116283
- const beside = (0, import_node_path35.join)(__dirname, "cli.js");
116284
- if ((0, import_node_fs28.existsSync)(beside)) {
117340
+ const beside = (0, import_node_path36.join)(__dirname, "cli.js");
117341
+ if ((0, import_node_fs30.existsSync)(beside)) {
116285
117342
  return beside;
116286
117343
  }
116287
117344
  if (fromArgv) {
@@ -116299,19 +117356,19 @@ async function ensureWindowsNativeLauncher(options = {}) {
116299
117356
  if (existing) {
116300
117357
  return { exePath: existing, installed: false };
116301
117358
  }
116302
- const targetDir = env.APPDATA ? (0, import_node_path35.join)(env.APPDATA, "npm") : (0, import_node_path35.join)(env.USERPROFILE ?? (0, import_node_os13.homedir)(), ".local", "bin");
117359
+ const targetDir = env.APPDATA ? (0, import_node_path36.join)(env.APPDATA, "npm") : (0, import_node_path36.join)(env.USERPROFILE ?? (0, import_node_os13.homedir)(), ".local", "bin");
116303
117360
  const result = await installWindowsNativeLauncher({ cliPath: resolveRunningCliPath(), targetDir });
116304
117361
  return { exePath: result.exePath, installed: true };
116305
117362
  }
116306
- var import_node_child_process9, import_node_fs28, import_node_module, import_node_os13, import_node_path35, SEA_SENTINEL_FUSE, NATIVE_LAUNCHER_EXE_NAME, POSTJECT_SPEC, POSTJECT_BIN;
117363
+ var import_node_child_process9, import_node_fs30, import_node_module, import_node_os13, import_node_path36, SEA_SENTINEL_FUSE, NATIVE_LAUNCHER_EXE_NAME, POSTJECT_SPEC, POSTJECT_BIN;
116307
117364
  var init_win_native_launcher = __esm({
116308
117365
  "src/win-native-launcher.ts"() {
116309
117366
  "use strict";
116310
117367
  import_node_child_process9 = require("node:child_process");
116311
- import_node_fs28 = require("node:fs");
117368
+ import_node_fs30 = require("node:fs");
116312
117369
  import_node_module = require("node:module");
116313
117370
  import_node_os13 = require("node:os");
116314
- import_node_path35 = require("node:path");
117371
+ import_node_path36 = require("node:path");
116315
117372
  init_win_compat();
116316
117373
  init_win_spawn();
116317
117374
  SEA_SENTINEL_FUSE = "NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2";
@@ -116450,7 +117507,7 @@ function buildProviderMismatchWarning(target, provider) {
116450
117507
  ].join("\n");
116451
117508
  }
116452
117509
  async function handleUpdateCommand(args) {
116453
- if (args.some(isHelpArg3)) {
117510
+ if (args.some(isHelpArg4)) {
116454
117511
  printUpdateUsage();
116455
117512
  return;
116456
117513
  }
@@ -116491,7 +117548,7 @@ function resolveUpdateTarget(target) {
116491
117548
  return detectGatewayInvocation() ?? "node";
116492
117549
  }
116493
117550
  async function handleSetupCommand(args) {
116494
- if (args.some(isHelpArg3)) {
117551
+ if (args.some(isHelpArg4)) {
116495
117552
  printSetupUsage();
116496
117553
  return;
116497
117554
  }
@@ -117053,7 +118110,7 @@ async function getCurrentNodeCliVersion() {
117053
118110
  return await getGlobalNpmPackageVersion(UPDATE_PACKAGES.node) ?? getBundledNodeCliVersion();
117054
118111
  }
117055
118112
  function getBundledNodeCliVersion() {
117056
- return true ? "0.2.10" : null;
118113
+ return true ? "0.2.11-beta-8fef2ef558-260901171734" : null;
117057
118114
  }
117058
118115
  function readConfiguredAiProvider() {
117059
118116
  const explicit = process.env.OKX_A2A_AI_PROVIDER || process.env.OKX_AGENT_TASK_AI_CLI;
@@ -117238,17 +118295,17 @@ async function updateHermes(release, options) {
117238
118295
  assertNotRunningInsideGateway("hermes");
117239
118296
  }
117240
118297
  const spec = buildNpmPackageSpec("hermes", release);
117241
- const workDir = await (0, import_promises15.mkdtemp)((0, import_node_path36.join)((0, import_node_os14.tmpdir)(), `okx-a2a-${label}-hermes-`));
118298
+ const workDir = await (0, import_promises15.mkdtemp)((0, import_node_path37.join)((0, import_node_os14.tmpdir)(), `okx-a2a-${label}-hermes-`));
117242
118299
  try {
117243
118300
  console.log(`[${label}] downloading ${spec}`);
117244
118301
  const npmTarball = await npmPack(spec, workDir);
117245
- const npmPackageDir = (0, import_node_path36.join)(workDir, "npm-package");
118302
+ const npmPackageDir = (0, import_node_path37.join)(workDir, "npm-package");
117246
118303
  await runCommand("tar", ["-xzf", npmTarball, "-C", npmPackageDir], { ensureDir: npmPackageDir });
117247
- const pluginTarball = await findHermesPluginTarball((0, import_node_path36.join)(npmPackageDir, "package", "dist"));
117248
- const pluginDir = (0, import_node_path36.join)(workDir, "plugin");
118304
+ const pluginTarball = await findHermesPluginTarball((0, import_node_path37.join)(npmPackageDir, "package", "dist"));
118305
+ const pluginDir = (0, import_node_path37.join)(workDir, "plugin");
117249
118306
  await runCommand("tar", ["-xzf", pluginTarball, "-C", pluginDir], { ensureDir: pluginDir });
117250
118307
  const unpackedPluginDir = await findFirstDirectory(pluginDir);
117251
- const installer = (0, import_node_path36.join)(unpackedPluginDir, "scripts", "install-or-upgrade.sh");
118308
+ const installer = (0, import_node_path37.join)(unpackedPluginDir, "scripts", "install-or-upgrade.sh");
117252
118309
  console.log(`[${label}] running ${installer}`);
117253
118310
  await runCommand("bash", [installer, ...options.restart ? ["--restart"] : []], { cwd: unpackedPluginDir });
117254
118311
  await normalizeHermesOkxA2aPluginConfig();
@@ -117263,7 +118320,7 @@ async function updateHermes(release, options) {
117263
118320
  }
117264
118321
  }
117265
118322
  async function installGatewayPluginForDoctor(target) {
117266
- const release = isPrereleaseVersion("0.2.10") ? "beta" : "latest";
118323
+ const release = isPrereleaseVersion("0.2.11-beta-8fef2ef558-260901171734") ? "beta" : "latest";
117267
118324
  const insideTargetGateway = detectGatewayInvocation() === target;
117268
118325
  const options = {
117269
118326
  restart: !insideTargetGateway,
@@ -117314,7 +118371,7 @@ async function ensureHermesOkxA2aPluginConfig(configFile = resolveHermesConfigPa
117314
118371
  if (options.dryRun) {
117315
118372
  return true;
117316
118373
  }
117317
- await (0, import_promises15.mkdir)((0, import_node_path36.resolve)(configFile, ".."), { recursive: true });
118374
+ await (0, import_promises15.mkdir)((0, import_node_path37.resolve)(configFile, ".."), { recursive: true });
117318
118375
  await (0, import_promises15.writeFile)(configFile, "plugins:\n enabled:\n - okx-a2a\n");
117319
118376
  console.log(`[update] added Hermes plugins.enabled okx-a2a entry in ${configFile}`);
117320
118377
  return true;
@@ -117554,7 +118611,7 @@ function findFirstEnabledListItem(lines, startIndex, enabledIndent) {
117554
118611
  return null;
117555
118612
  }
117556
118613
  function resolveHermesConfigPath() {
117557
- return (0, import_node_path36.join)(process.env.HERMES_HOME ?? (0, import_node_path36.join)((0, import_node_os14.homedir)(), ".hermes"), "config.yaml");
118614
+ return (0, import_node_path37.join)(process.env.HERMES_HOME ?? (0, import_node_path37.join)((0, import_node_os14.homedir)(), ".hermes"), "config.yaml");
117558
118615
  }
117559
118616
  function lineIndent(line) {
117560
118617
  const match = line.match(/^\s*/);
@@ -117632,13 +118689,13 @@ async function assertGatewayPluginInstalled(target) {
117632
118689
  );
117633
118690
  }
117634
118691
  function resolveHermesPluginYamlPath() {
117635
- return (0, import_node_path36.join)(process.env.HERMES_HOME ?? (0, import_node_path36.join)((0, import_node_os14.homedir)(), ".hermes"), "plugins", "platforms", "okx-a2a", "plugin.yaml");
118692
+ return (0, import_node_path37.join)(process.env.HERMES_HOME ?? (0, import_node_path37.join)((0, import_node_os14.homedir)(), ".hermes"), "plugins", "platforms", "okx-a2a", "plugin.yaml");
117636
118693
  }
117637
118694
  async function isGatewayPluginInstalled(target) {
117638
118695
  if (target === "openclaw") {
117639
118696
  return (await getInstalledOpenClawPluginInfo()).installed;
117640
118697
  }
117641
- return (0, import_node_fs29.existsSync)(resolveHermesPluginYamlPath());
118698
+ return (0, import_node_fs31.existsSync)(resolveHermesPluginYamlPath());
117642
118699
  }
117643
118700
  async function getInstalledGatewayPluginVersion(target) {
117644
118701
  if (target === "hermes") {
@@ -117725,7 +118782,7 @@ function parsePackageVersionFromText(output5) {
117725
118782
  return output5.match(/@okxweb3\/a2a-openclaw@([0-9A-Za-z.+-]+)/)?.[1] ?? null;
117726
118783
  }
117727
118784
  async function getInstalledHermesPluginVersion() {
117728
- const pluginYaml = (0, import_node_path36.join)(process.env.HERMES_HOME ?? (0, import_node_path36.join)((0, import_node_os14.homedir)(), ".hermes"), "plugins", "platforms", "okx-a2a", "plugin.yaml");
118785
+ const pluginYaml = (0, import_node_path37.join)(process.env.HERMES_HOME ?? (0, import_node_path37.join)((0, import_node_os14.homedir)(), ".hermes"), "plugins", "platforms", "okx-a2a", "plugin.yaml");
117729
118786
  try {
117730
118787
  const content2 = await (0, import_promises15.readFile)(pluginYaml, "utf8");
117731
118788
  return parsePluginYamlVersion(content2);
@@ -117783,7 +118840,7 @@ async function npmPack(spec, destination) {
117783
118840
  if (!tarballName) {
117784
118841
  throw new Error(`Unable to detect npm pack tarball from output: ${output5.trim()}`);
117785
118842
  }
117786
- return (0, import_node_path36.resolve)(destination, (0, import_node_path36.basename)(tarballName));
118843
+ return (0, import_node_path37.resolve)(destination, (0, import_node_path37.basename)(tarballName));
117787
118844
  }
117788
118845
  async function findHermesPluginTarball(distDir) {
117789
118846
  const entries = await (0, import_promises15.readdir)(distDir);
@@ -117791,7 +118848,7 @@ async function findHermesPluginTarball(distDir) {
117791
118848
  if (!tarball) {
117792
118849
  throw new Error(`Hermes npm package did not contain dist/okx-a2a-hermes-plugin-*.tar.gz`);
117793
118850
  }
117794
- return (0, import_node_path36.join)(distDir, tarball);
118851
+ return (0, import_node_path37.join)(distDir, tarball);
117795
118852
  }
117796
118853
  async function findFirstDirectory(parent) {
117797
118854
  const entries = await (0, import_promises15.readdir)(parent, { withFileTypes: true });
@@ -117799,7 +118856,7 @@ async function findFirstDirectory(parent) {
117799
118856
  if (!dir) {
117800
118857
  throw new Error(`No unpacked plugin directory found under ${parent}`);
117801
118858
  }
117802
- return (0, import_node_path36.join)(parent, dir.name);
118859
+ return (0, import_node_path37.join)(parent, dir.name);
117803
118860
  }
117804
118861
  function readOption4(args, name) {
117805
118862
  const index2 = args.indexOf(name);
@@ -117811,7 +118868,7 @@ function readOption4(args, name) {
117811
118868
  function hasFlag(args, name) {
117812
118869
  return args.includes(name);
117813
118870
  }
117814
- function isHelpArg3(value) {
118871
+ function isHelpArg4(value) {
117815
118872
  return value === "-h" || value === "--help" || value === "help";
117816
118873
  }
117817
118874
  function isSupportedRelease(value) {
@@ -118020,15 +119077,15 @@ function buildExternalCommandInvocation(command, args, platform = process.platfo
118020
119077
  function formatExternalCommand(command, args) {
118021
119078
  return [command, ...args].join(" ");
118022
119079
  }
118023
- var import_node_child_process10, import_node_fs29, import_promises15, import_node_os14, import_node_path36, UPDATE_PACKAGES, CODEX_NPM_PACKAGE, OPENCLAW_FORCE_INSTALL_FLAG, OPENCLAW_UNSAFE_INSTALL_FLAG, OKX_A2A_PLUGIN_ID, OPENCLAW_SESSION_DM_SCOPE_CONFIG_PATH, OPENCLAW_SESSION_DM_SCOPE_CONFIG_VALUE, OPENCLAW_PLUGIN_ALLOW_CONFIG_PATH, OPENCLAW_OKX_A2A_CONVERSATION_HOOK_ACCESS_CONFIG_PATH, DEFAULT_AI_PROVIDER_LOGIN_TIMEOUT_MS, PROVIDER_CLI_AUTH_PROBE_TIMEOUT_MS, SetupBlockedError, redirectCommandStdoutToStderr;
119080
+ var import_node_child_process10, import_node_fs31, import_promises15, import_node_os14, import_node_path37, UPDATE_PACKAGES, CODEX_NPM_PACKAGE, OPENCLAW_FORCE_INSTALL_FLAG, OPENCLAW_UNSAFE_INSTALL_FLAG, OKX_A2A_PLUGIN_ID, OPENCLAW_SESSION_DM_SCOPE_CONFIG_PATH, OPENCLAW_SESSION_DM_SCOPE_CONFIG_VALUE, OPENCLAW_PLUGIN_ALLOW_CONFIG_PATH, OPENCLAW_OKX_A2A_CONVERSATION_HOOK_ACCESS_CONFIG_PATH, DEFAULT_AI_PROVIDER_LOGIN_TIMEOUT_MS, PROVIDER_CLI_AUTH_PROBE_TIMEOUT_MS, SetupBlockedError, redirectCommandStdoutToStderr;
118024
119081
  var init_update_cli = __esm({
118025
119082
  "src/update-cli.ts"() {
118026
119083
  "use strict";
118027
119084
  import_node_child_process10 = require("node:child_process");
118028
- import_node_fs29 = require("node:fs");
119085
+ import_node_fs31 = require("node:fs");
118029
119086
  import_promises15 = require("node:fs/promises");
118030
119087
  import_node_os14 = require("node:os");
118031
- import_node_path36 = require("node:path");
119088
+ import_node_path37 = require("node:path");
118032
119089
  init_ai_command();
118033
119090
  init_win_spawn();
118034
119091
  init_ai_provider();
@@ -118316,7 +119373,7 @@ async function runDoctor(options = {}) {
118316
119373
  platform: options.platform ?? process.platform,
118317
119374
  env: options.env ?? process.env,
118318
119375
  target: options.target ?? resolveDoctorTarget(options.env ?? process.env),
118319
- cliVersion: options.cliVersion ?? (true ? "0.2.10" : "0.0.0"),
119376
+ cliVersion: options.cliVersion ?? (true ? "0.2.11-beta-8fef2ef558-260901171734" : "0.0.0"),
118320
119377
  fixMode: options.fix === true,
118321
119378
  nonInteractive: options.nonInteractive === true,
118322
119379
  packageChanged: false,
@@ -118524,11 +119581,11 @@ async function writeStdoutAndExit(output5, code) {
118524
119581
  });
118525
119582
  process.exit(code);
118526
119583
  }
118527
- var import_node_path37, DOCTOR_MIN_NODE_VERSION, DOCTOR_DAEMON_READY_TIMEOUT_MS, DOCTOR_DAEMON_WAIT_HEARTBEAT_MS, NODE_PACKAGE_SPEC, CODEX_INSTALL_SPEC, CLAUDE_INSTALL_SPEC, nodeVersionChecker, npmChecker, cliVersionChecker, windowsNativeLauncherChecker, providerBindingChecker, providerCliChecker, gatewayPluginChecker, gatewayConfigChecker, daemonChecker, agentRefreshChecker, gatewayReachableChecker, autostartChecker, CHECKERS, STATUS_MARK;
119584
+ var import_node_path38, DOCTOR_MIN_NODE_VERSION, DOCTOR_DAEMON_READY_TIMEOUT_MS, DOCTOR_DAEMON_WAIT_HEARTBEAT_MS, NODE_PACKAGE_SPEC, CODEX_INSTALL_SPEC, CLAUDE_INSTALL_SPEC, nodeVersionChecker, npmChecker, cliVersionChecker, windowsNativeLauncherChecker, providerBindingChecker, providerCliChecker, gatewayPluginChecker, gatewayConfigChecker, daemonChecker, agentRefreshChecker, gatewayReachableChecker, autostartChecker, CHECKERS, STATUS_MARK;
118528
119585
  var init_doctor_cli = __esm({
118529
119586
  "src/doctor-cli.ts"() {
118530
119587
  "use strict";
118531
- import_node_path37 = require("node:path");
119588
+ import_node_path38 = require("node:path");
118532
119589
  init_log();
118533
119590
  init_win_compat();
118534
119591
  init_ai_command();
@@ -118715,7 +119772,7 @@ var init_doctor_cli = __esm({
118715
119772
  command: "okx-a2a doctor --fix"
118716
119773
  },
118717
119774
  data: {
118718
- appDataNpm: ctx.env.APPDATA ? (0, import_node_path37.join)(ctx.env.APPDATA, "npm") : null
119775
+ appDataNpm: ctx.env.APPDATA ? (0, import_node_path38.join)(ctx.env.APPDATA, "npm") : null
118719
119776
  }
118720
119777
  };
118721
119778
  },
@@ -119323,9 +120380,9 @@ var init_doctor_cli = __esm({
119323
120380
  });
119324
120381
 
119325
120382
  // src/cli.ts
119326
- var import_node_fs30 = require("node:fs");
120383
+ var import_node_fs32 = require("node:fs");
119327
120384
  var import_node_os15 = require("node:os");
119328
- var import_node_path38 = require("node:path");
120385
+ var import_node_path39 = require("node:path");
119329
120386
  init_daemon();
119330
120387
  init_command_store();
119331
120388
  init_file_store();
@@ -119393,7 +120450,7 @@ init_sentry_config();
119393
120450
  init_runtime_metadata();
119394
120451
  var CURRENT_GATEWAY_SESSION_KEYS_ENV4 = "OKX_A2A_CURRENT_GATEWAY_SESSION_KEYS";
119395
120452
  function printUsage3() {
119396
- console.log(`okx-a2a ${"0.2.10"}
120453
+ console.log(`okx-a2a ${"0.2.11-beta-8fef2ef558-260901171734"}
119397
120454
 
119398
120455
  Usage:
119399
120456
  okx-a2a <command> [options]
@@ -119423,6 +120480,8 @@ Commands:
119423
120480
  Alias for runtime switch-current
119424
120481
  job-provider Manage job-to-provider bindings
119425
120482
  xmtp-send Queue an XMTP message through the running daemon
120483
+ trade-records
120484
+ Insert, query, and soft-delete local business trade records
119426
120485
  capabilities Print machine-readable A2A capability negotiation status (used by OnchainOS)
119427
120486
 
119428
120487
  Global options:
@@ -119433,7 +120492,7 @@ Run \`okx-a2a <command> -h\` for command-specific help.
119433
120492
  `);
119434
120493
  }
119435
120494
  function printVersion() {
119436
- console.log("0.2.10");
120495
+ console.log("0.2.11-beta-8fef2ef558-260901171734");
119437
120496
  }
119438
120497
  function printDaemonUsage() {
119439
120498
  console.log(`Usage: okx-a2a daemon <start|restart|stop|status|autostart> [options]
@@ -119595,8 +120654,22 @@ function printCommandUsage(command) {
119595
120654
  printXmtpSendUsage();
119596
120655
  return true;
119597
120656
  }
120657
+ if (command === "trade-records") {
120658
+ printTradeRecordsUsageProxy();
120659
+ return true;
120660
+ }
119598
120661
  return false;
119599
120662
  }
120663
+ function printTradeRecordsUsageProxy() {
120664
+ console.log(`Usage: okx-a2a trade-records <insert|query|delete> [options]
120665
+
120666
+ Commands:
120667
+ insert Insert or replace trade records by deliveryId.
120668
+ query Query active or soft-deleted trade records.
120669
+ delete Soft-delete one trade record by deliveryId.
120670
+
120671
+ Run \`okx-a2a trade-records <command> --help\` for command-specific help.`);
120672
+ }
119600
120673
  function printUserUsageProxy() {
119601
120674
  console.log(`Usage: okx-a2a user <notify|decision-request|list|outdated-list|consume|check|watch>
119602
120675
 
@@ -119683,11 +120756,11 @@ Commands:
119683
120756
  Print setup status JSON to stdout. Installer logs are written to stderr.
119684
120757
  `);
119685
120758
  }
119686
- function isHelpArg4(value) {
120759
+ function isHelpArg5(value) {
119687
120760
  return value === "-h" || value === "--help" || value === "help";
119688
120761
  }
119689
120762
  function hasHelpFlag5(args) {
119690
- return args.some(isHelpArg4);
120763
+ return args.some(isHelpArg5);
119691
120764
  }
119692
120765
  function isVersionArg(value) {
119693
120766
  return value === "-v" || value === "--version" || value === "version";
@@ -119714,14 +120787,14 @@ function maybeRedirectDaemonSelfLog() {
119714
120787
  }
119715
120788
  try {
119716
120789
  const logPath = resolveTaskPaths().listenerLogPath;
119717
- (0, import_node_fs30.mkdirSync)((0, import_node_path38.join)(logPath, ".."), { recursive: true });
119718
- const fd = (0, import_node_fs30.openSync)(logPath, "a");
120790
+ (0, import_node_fs32.mkdirSync)((0, import_node_path39.join)(logPath, ".."), { recursive: true });
120791
+ const fd = (0, import_node_fs32.openSync)(logPath, "a");
119719
120792
  const writeToLog = ((chunk, encoding, cb) => {
119720
120793
  try {
119721
120794
  if (typeof chunk === "string") {
119722
- (0, import_node_fs30.writeSync)(fd, chunk);
120795
+ (0, import_node_fs32.writeSync)(fd, chunk);
119723
120796
  } else {
119724
- (0, import_node_fs30.writeSync)(fd, chunk);
120797
+ (0, import_node_fs32.writeSync)(fd, chunk);
119725
120798
  }
119726
120799
  } catch {
119727
120800
  }
@@ -119811,7 +120884,7 @@ async function handleLogs(args) {
119811
120884
  return;
119812
120885
  }
119813
120886
  if (subcommand === "llm") {
119814
- await tailLogFile((0, import_node_path38.join)(paths.logsDir, "llm.log"), parseLogsTailArgs(args.slice(1), subcommand));
120887
+ await tailLogFile((0, import_node_path39.join)(paths.logsDir, "llm.log"), parseLogsTailArgs(args.slice(1), subcommand));
119815
120888
  return;
119816
120889
  }
119817
120890
  throw new Error("logs requires <server|llm|export>");
@@ -120077,12 +121150,12 @@ async function queueXmtpDaemonCommand(args, type) {
120077
121150
  }
120078
121151
  async function handleTaskCommand(args) {
120079
121152
  const subcommand = args[0];
120080
- if (!subcommand || args.every(isHelpArg4)) {
121153
+ if (!subcommand || args.every(isHelpArg5)) {
120081
121154
  printTaskUsage();
120082
121155
  return;
120083
121156
  }
120084
121157
  if (subcommand === "help") {
120085
- const helpTarget = args.slice(1).find((arg) => !isHelpArg4(arg));
121158
+ const helpTarget = args.slice(1).find((arg) => !isHelpArg5(arg));
120086
121159
  if (!helpTarget) {
120087
121160
  printTaskUsage();
120088
121161
  return;
@@ -120770,11 +121843,11 @@ async function initDirectCliSentry() {
120770
121843
  }
120771
121844
  cliSentryInitAttempted = true;
120772
121845
  try {
120773
- const configPath = (0, import_node_path38.join)(resolveTaskHomeForSentryConfig(), "xmtp", "system-config.json");
120774
- if (!(0, import_node_fs30.existsSync)(configPath)) {
121846
+ const configPath = (0, import_node_path39.join)(resolveTaskHomeForSentryConfig(), "xmtp", "system-config.json");
121847
+ if (!(0, import_node_fs32.existsSync)(configPath)) {
120775
121848
  return;
120776
121849
  }
120777
- const config = JSON.parse((0, import_node_fs30.readFileSync)(configPath, "utf8"));
121850
+ const config = JSON.parse((0, import_node_fs32.readFileSync)(configPath, "utf8"));
120778
121851
  if (typeof config.sentryDsn !== "string" || !config.sentryDsn) {
120779
121852
  return;
120780
121853
  }
@@ -120799,11 +121872,11 @@ function resolveTaskHomeForSentryConfig() {
120799
121872
  try {
120800
121873
  const home = (0, import_node_os15.homedir)();
120801
121874
  if (home) {
120802
- return (0, import_node_path38.join)(home, ".okx-agent-task");
121875
+ return (0, import_node_path39.join)(home, ".okx-agent-task");
120803
121876
  }
120804
121877
  } catch {
120805
121878
  }
120806
- return (0, import_node_path38.resolve)(process.cwd(), ".okx-agent-task");
121879
+ return (0, import_node_path39.resolve)(process.cwd(), ".okx-agent-task");
120807
121880
  }
120808
121881
  function directCliSentryExtra(operation, extra = {}) {
120809
121882
  return {
@@ -120836,7 +121909,7 @@ async function main() {
120836
121909
  assertSupportedNodeVersion();
120837
121910
  }
120838
121911
  const args = process.argv.slice(3);
120839
- if (isHelpArg4(command)) {
121912
+ if (isHelpArg5(command)) {
120840
121913
  printUsage3();
120841
121914
  return;
120842
121915
  }
@@ -120852,6 +121925,11 @@ async function main() {
120852
121925
  handleCapabilitiesCommand2(process.argv.slice(3));
120853
121926
  return;
120854
121927
  }
121928
+ if (command === "trade-records") {
121929
+ const { handleTradeRecordsCommand: handleTradeRecordsCommand2 } = await Promise.resolve().then(() => (init_trade_records_cli(), trade_records_cli_exports));
121930
+ await handleTradeRecordsCommand2(args);
121931
+ return;
121932
+ }
120855
121933
  if (command === "daemon") {
120856
121934
  if (hasHelpFlag5(args)) {
120857
121935
  printDaemonUsage();
@@ -120911,7 +121989,7 @@ async function main() {
120911
121989
  if (command === "xmtp-test") {
120912
121990
  const { handleXmtpTestCommand: handleXmtpTestCommand2 } = await Promise.resolve().then(() => (init_xmtp_test_cli(), xmtp_test_cli_exports));
120913
121991
  await handleXmtpTestCommand2(process.argv.slice(3), {
120914
- packageVersion: "0.2.10",
121992
+ packageVersion: "0.2.11-beta-8fef2ef558-260901171734",
120915
121993
  agentSdkVersion: "2.3.0",
120916
121994
  nodeSdkVersion: "6.1.0",
120917
121995
  nodeBindingsVersion: "1.11.0"
@@ -121016,10 +122094,13 @@ function shouldDeferHelpToNestedHandler(command, args) {
121016
122094
  if (command === "xmtp-test") {
121017
122095
  return true;
121018
122096
  }
122097
+ if (command === "trade-records") {
122098
+ return args.some((arg) => !isHelpArg5(arg));
122099
+ }
121019
122100
  if (command !== "session" && command !== "user" && command !== "task") {
121020
122101
  return false;
121021
122102
  }
121022
- return args.some((arg) => !isHelpArg4(arg));
122103
+ return args.some((arg) => !isHelpArg5(arg));
121023
122104
  }
121024
122105
  main().then(() => {
121025
122106
  if (cliSentryFlushTimedOut) {