@harrylabsj/kiwi 0.11.0 → 0.12.1

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 (134) hide show
  1. package/README.md +16 -1
  2. package/contracts/kiwi-contracts.lock.json +1 -1
  3. package/contracts/manifest.json +2 -2
  4. package/contracts/runtime-binding/0.1.2/document.schema.json +3 -1
  5. package/dist/a2a/node.d.ts +2 -0
  6. package/dist/a2a/node.js +92 -13
  7. package/dist/a2a/node.js.map +1 -1
  8. package/dist/a2a/server/merchant-handler.js +31 -17
  9. package/dist/a2a/server/merchant-handler.js.map +1 -1
  10. package/dist/a2a/server/pipeline.js +1 -0
  11. package/dist/a2a/server/pipeline.js.map +1 -1
  12. package/dist/a2a/server/types.d.ts +1 -0
  13. package/dist/agent/buyer/buyer-tools.d.ts +2 -2
  14. package/dist/agent/buyer/buyer-tools.js.map +1 -1
  15. package/dist/agent/chat-tools.d.ts +2 -11
  16. package/dist/agent/chat-tools.js.map +1 -1
  17. package/dist/agent/fake-chat-model.d.ts +3 -3
  18. package/dist/agent/fake-chat-model.js +3 -5
  19. package/dist/agent/fake-chat-model.js.map +1 -1
  20. package/dist/agent/kernel-builder.js +4 -4
  21. package/dist/agent/kernel-builder.js.map +1 -1
  22. package/dist/agent/kernel.d.ts +15 -5
  23. package/dist/agent/kernel.js +143 -67
  24. package/dist/agent/kernel.js.map +1 -1
  25. package/dist/agent/kiwi-tool.d.ts +33 -0
  26. package/dist/agent/kiwi-tool.js +17 -0
  27. package/dist/agent/kiwi-tool.js.map +1 -0
  28. package/dist/agent/merchant/merchant-tools.d.ts +2 -17
  29. package/dist/agent/merchant/merchant-tools.js.map +1 -1
  30. package/dist/agent/negotiation-chat.d.ts +3 -2
  31. package/dist/agent/negotiation-chat.js.map +1 -1
  32. package/dist/agent/session.d.ts +15 -3
  33. package/dist/agent/session.js +114 -122
  34. package/dist/agent/session.js.map +1 -1
  35. package/dist/agent/skills/tools.d.ts +2 -2
  36. package/dist/agent/skills/tools.js.map +1 -1
  37. package/dist/cli.d.ts +5 -1
  38. package/dist/cli.js +239 -32
  39. package/dist/cli.js.map +1 -1
  40. package/dist/cloud/binding/enrollment-challenge.d.ts +37 -0
  41. package/dist/cloud/binding/enrollment-challenge.js +153 -0
  42. package/dist/cloud/binding/enrollment-challenge.js.map +1 -0
  43. package/dist/cloud/binding/enrollment-heartbeat.d.ts +26 -0
  44. package/dist/cloud/binding/enrollment-heartbeat.js +146 -0
  45. package/dist/cloud/binding/enrollment-heartbeat.js.map +1 -0
  46. package/dist/cloud/binding/enrollment-key-recovery.d.ts +27 -0
  47. package/dist/cloud/binding/enrollment-key-recovery.js +127 -0
  48. package/dist/cloud/binding/enrollment-key-recovery.js.map +1 -0
  49. package/dist/cloud/binding/runtime-challenge.d.ts +1 -1
  50. package/dist/cloud/binding/runtime-challenge.js +8 -1
  51. package/dist/cloud/binding/runtime-challenge.js.map +1 -1
  52. package/dist/cloud/bootstrap.d.ts +2 -0
  53. package/dist/cloud/bootstrap.js +324 -18
  54. package/dist/cloud/bootstrap.js.map +1 -1
  55. package/dist/cloud/catalog-client.d.ts +305 -0
  56. package/dist/cloud/catalog-client.js +962 -0
  57. package/dist/cloud/catalog-client.js.map +1 -0
  58. package/dist/cloud/config.d.ts +12 -0
  59. package/dist/cloud/config.js +45 -0
  60. package/dist/cloud/config.js.map +1 -1
  61. package/dist/cloud/connect-service.d.ts +144 -0
  62. package/dist/cloud/connect-service.js +776 -0
  63. package/dist/cloud/connect-service.js.map +1 -0
  64. package/dist/cloud/file-listing-publication.d.ts +105 -0
  65. package/dist/cloud/file-listing-publication.js +436 -0
  66. package/dist/cloud/file-listing-publication.js.map +1 -0
  67. package/dist/cloud/http-router.d.ts +2 -0
  68. package/dist/cloud/http-router.js +8 -0
  69. package/dist/cloud/http-router.js.map +1 -1
  70. package/dist/cloud/listing-publisher.d.ts +45 -0
  71. package/dist/cloud/listing-publisher.js +244 -0
  72. package/dist/cloud/listing-publisher.js.map +1 -0
  73. package/dist/cloud/merchant-connect.d.ts +53 -0
  74. package/dist/cloud/merchant-connect.js +90 -0
  75. package/dist/cloud/merchant-connect.js.map +1 -0
  76. package/dist/cloud/merchant-identity.d.ts +14 -0
  77. package/dist/cloud/merchant-identity.js +76 -0
  78. package/dist/cloud/merchant-identity.js.map +1 -0
  79. package/dist/cloud/onboarding/catalog-pipeline.d.ts +135 -0
  80. package/dist/cloud/onboarding/catalog-pipeline.js +454 -0
  81. package/dist/cloud/onboarding/catalog-pipeline.js.map +1 -0
  82. package/dist/cloud/onboarding/steps.js +2 -2
  83. package/dist/cloud/onboarding/steps.js.map +1 -1
  84. package/dist/cloud/product-import-tabular.d.ts +100 -0
  85. package/dist/cloud/product-import-tabular.js +1073 -0
  86. package/dist/cloud/product-import-tabular.js.map +1 -0
  87. package/dist/cloud/product-source.d.ts +8 -1
  88. package/dist/cloud/product-source.js +63 -13
  89. package/dist/cloud/product-source.js.map +1 -1
  90. package/dist/config/profile.d.ts +4 -0
  91. package/dist/config/profile.js +14 -0
  92. package/dist/config/profile.js.map +1 -1
  93. package/dist/discovery/catalog-source/cloud-card.d.ts +1 -1
  94. package/dist/discovery/catalog-source/cloud-card.js +7 -1
  95. package/dist/discovery/catalog-source/cloud-card.js.map +1 -1
  96. package/dist/http/merchant-management/api.d.ts +37 -0
  97. package/dist/http/merchant-management/api.js +379 -7
  98. package/dist/http/merchant-management/api.js.map +1 -1
  99. package/dist/http/merchant-management/page.d.ts +4 -1
  100. package/dist/http/merchant-management/page.js +426 -25
  101. package/dist/http/merchant-management/page.js.map +1 -1
  102. package/dist/mcp/merchant-runtime-assembly.js +4 -1
  103. package/dist/mcp/merchant-runtime-assembly.js.map +1 -1
  104. package/dist/mcp/merchant-server.d.ts +2 -0
  105. package/dist/mcp/merchant-server.js +15 -0
  106. package/dist/mcp/merchant-server.js.map +1 -1
  107. package/dist/merchant/negotiation-observer.d.ts +92 -0
  108. package/dist/merchant/negotiation-observer.js +278 -0
  109. package/dist/merchant/negotiation-observer.js.map +1 -0
  110. package/dist/merchant/operations-report.d.ts +85 -0
  111. package/dist/merchant/operations-report.js +227 -0
  112. package/dist/merchant/operations-report.js.map +1 -0
  113. package/dist/merchant/stats-store.d.ts +5 -0
  114. package/dist/merchant/stats-store.js +18 -0
  115. package/dist/merchant/stats-store.js.map +1 -1
  116. package/dist/merchant-gateway/catalog-publications.d.ts +28 -0
  117. package/dist/merchant-gateway/catalog-publications.js +69 -0
  118. package/dist/merchant-gateway/catalog-publications.js.map +1 -1
  119. package/dist/merchant-gateway/catalog-tools.js +20 -0
  120. package/dist/merchant-gateway/catalog-tools.js.map +1 -1
  121. package/dist/negotiation/lease/store.js +21 -2
  122. package/dist/negotiation/lease/store.js.map +1 -1
  123. package/dist/product-cli.d.ts +2 -2
  124. package/dist/product-cli.js +24 -9
  125. package/dist/product-cli.js.map +1 -1
  126. package/dist/product-init.d.ts +4 -1
  127. package/dist/product-init.js +39 -11
  128. package/dist/product-init.js.map +1 -1
  129. package/dist/product-publish.d.ts +8 -2
  130. package/dist/product-publish.js +222 -142
  131. package/dist/product-publish.js.map +1 -1
  132. package/dist/runtime/fake-model.js +9 -3
  133. package/dist/runtime/fake-model.js.map +1 -1
  134. package/package.json +10 -5
package/dist/cli.js CHANGED
@@ -29,10 +29,12 @@
29
29
  */
30
30
  import { spawn, spawnSync } from "node:child_process";
31
31
  import { DatabaseSync } from "node:sqlite";
32
+ import { isIP } from "node:net";
32
33
  import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync, } from "node:fs";
33
34
  import { homedir, userInfo } from "node:os";
34
35
  import path from "node:path";
35
36
  import { fileURLToPath } from "node:url";
37
+ import { Writable } from "node:stream";
36
38
  import { startA2aNode } from "./a2a/node.js";
37
39
  import { runChatTui } from "./agent/chat-tui.js";
38
40
  import { buildChatKernel, buildClient, defaultChatProfile } from "./agent/kernel-builder.js";
@@ -65,6 +67,8 @@ import { buildRuntimeServiceSpecs } from "./merchant-runtime/services.js";
65
67
  import { collectMerchantHealth } from "./merchant-runtime/health.js";
66
68
  import { MerchantJobs, standardMerchantJobs } from "./merchant-runtime/jobs.js";
67
69
  import { runBackup } from "./merchant-runtime/backup.js";
70
+ import { connectMerchant } from "./cloud/merchant-connect.js";
71
+ import { rotateEnrollmentSigningKey } from "./cloud/binding/enrollment-key-recovery.js";
68
72
  function readRegistrationStatus(dataDir) {
69
73
  try {
70
74
  const value = JSON.parse(readFileSync(path.join(dataDir, "registration.json"), "utf8"));
@@ -110,7 +114,7 @@ import { supplierList, supplierMetrics, supplierPause, supplierPrefer, supplierR
110
114
  import { merchantStats } from "./product-merchant.js";
111
115
  import { merchantPublish } from "./product-publish.js";
112
116
  import { catalogServe } from "./product-catalog.js";
113
- import { extractPublicDomain, runMerchantSetupPublic, SetupPublicError, validatePublicDomain, } from "./product-setup-public.js";
117
+ import { detectPublicIp, extractPublicDomain, runMerchantSetupPublic, SetupPublicError, validatePublicDomain, } from "./product-setup-public.js";
114
118
  const USAGE = `kiwi ${PRODUCT_VERSION} — commerce negotiation agent runtime
115
119
 
116
120
  Usage:
@@ -183,6 +187,8 @@ export function parseArgs(argv) {
183
187
  let shoppingCliMerchant;
184
188
  let merchantId;
185
189
  let merchantName;
190
+ let merchantToken;
191
+ let publicUrl;
186
192
  let output;
187
193
  let force = false;
188
194
  let noInstall = false;
@@ -244,6 +250,12 @@ export function parseArgs(argv) {
244
250
  else if (arg === "--merchant-id") {
245
251
  merchantId = argv[++i];
246
252
  }
253
+ else if (arg === "--merchant-token") {
254
+ merchantToken = argv[++i];
255
+ }
256
+ else if (arg === "--public-url") {
257
+ publicUrl = argv[++i];
258
+ }
247
259
  else if (arg === "--name") {
248
260
  merchantName = argv[++i];
249
261
  }
@@ -376,6 +388,12 @@ export function parseArgs(argv) {
376
388
  else if (arg !== undefined && arg.startsWith("--merchant-id=")) {
377
389
  merchantId = arg.slice("--merchant-id=".length);
378
390
  }
391
+ else if (arg !== undefined && arg.startsWith("--merchant-token=")) {
392
+ merchantToken = arg.slice("--merchant-token=".length);
393
+ }
394
+ else if (arg !== undefined && arg.startsWith("--public-url=")) {
395
+ publicUrl = arg.slice("--public-url=".length);
396
+ }
379
397
  else if (arg !== undefined && arg.startsWith("--name=")) {
380
398
  merchantName = arg.slice("--name=".length);
381
399
  }
@@ -451,6 +469,10 @@ export function parseArgs(argv) {
451
469
  out.merchantId = merchantId;
452
470
  if (merchantName !== undefined)
453
471
  out.merchantName = merchantName;
472
+ if (merchantToken !== undefined)
473
+ out.merchantToken = merchantToken;
474
+ if (publicUrl !== undefined)
475
+ out.publicUrl = publicUrl;
454
476
  if (output !== undefined)
455
477
  out.output = output;
456
478
  if (agentId !== undefined)
@@ -702,8 +724,19 @@ async function cmdTui(args) {
702
724
  * policy-overrides / agent-db)同一消毒口径(审查 P2:此前读端用原始
703
725
  * agent_id、写端消毒,非 ASCII agent_id 下策略热更新对 A2A 静默不生效);
704
726
  * 重启后 Ledger/幂等/终态可恢复;显式 --data-dir 覆盖。绝不回退到临时目录。 */
705
- export function resolveServeDataDir(dataDir, agentId) {
706
- return dataDir ?? path.resolve(DEFAULT_AGENTS_ROOT, agentDirName(agentId));
727
+ export function resolveServeDataDir(dataDir, agentId, profileDataDir) {
728
+ return dataDir ?? profileDataDir ?? path.resolve(DEFAULT_AGENTS_ROOT, agentDirName(agentId));
729
+ }
730
+ function configuredDataDir(args, profile) {
731
+ return args.dataDir ?? profile.merchant_runtime?.data_dir;
732
+ }
733
+ /** Accept a domain or bare IP as shorthand for its HTTPS origin. */
734
+ export function normalizeMerchantRuntimeOriginInput(input) {
735
+ const value = input.trim();
736
+ if (value === "" || /^https?:\/\//i.test(value))
737
+ return value;
738
+ const unwrapped = value.startsWith("[") && value.endsWith("]") ? value.slice(1, -1) : value;
739
+ return isIP(unwrapped) === 6 ? `https://[${unwrapped}]` : `https://${value}`;
707
740
  }
708
741
  async function cmdAgentServe(args) {
709
742
  const profile = requireProfileOrDefault(args);
@@ -718,7 +751,7 @@ async function cmdAgentServe(args) {
718
751
  // mkdtemp 临时目录且 stop 时删除,重启后 Ledger/幂等/终态全丢:已终态
719
752
  // negotiation 可重开、已发 conditional offer 返回 offer_unknown。稳定目录
720
753
  // 让重启可恢复状态(resolveServeDataDir 见上)。
721
- const serveDataDir = resolveServeDataDir(args.dataDir, profile.agent_id);
754
+ const serveDataDir = resolveServeDataDir(args.dataDir, profile.agent_id, profile.merchant_runtime?.data_dir);
722
755
  // BUG-07:A2A 进程的策略读端——与 MCP 写端共享 <dataDir>/policy-overrides.json,
723
756
  // 每次报价 stat 文件 mtime,变化才重载(策略热更新跨进程立即生效)。
724
757
  const policyRuntime = new MerchantPolicyRuntime({
@@ -909,7 +942,7 @@ async function cmdChat(args, requiredRole) {
909
942
  preferredPort: args.port,
910
943
  // 审查:chat 起的 A2A 节点同样要持久 dataDir——否则 Ledger/幂等/签名密钥
911
944
  // 全落临时目录,重启后磋商状态与签名身份丢失(Issue 16 B)。
912
- dataDir: resolveServeDataDir(args.dataDir, p.agent_id),
945
+ dataDir: resolveServeDataDir(args.dataDir, p.agent_id, p.merchant_runtime?.data_dir),
913
946
  ...(merchantToken ? { ownerToken: merchantToken } : {}),
914
947
  ownerTokenSecret: process.env.KIWI_CATALOG_OWNER_TOKEN_SECRET,
915
948
  });
@@ -1174,6 +1207,8 @@ async function routeMerchant(sub, args) {
1174
1207
  return await cmdMerchantMcp(args);
1175
1208
  if (sub === "runtime")
1176
1209
  return await cmdMerchantRuntime(args);
1210
+ if (sub === "connect")
1211
+ return await cmdMerchantConnect(args);
1177
1212
  if (sub === "init")
1178
1213
  return await cmdMerchantInit(args);
1179
1214
  if (sub === "publish")
@@ -1193,6 +1228,37 @@ async function routeMerchant(sub, args) {
1193
1228
  process.stderr.write(`unknown merchant command: ${sub}\n`);
1194
1229
  return EXIT.CONFIG;
1195
1230
  }
1231
+ /** 本机执行设备授权;实际 Runtime 持钥留在本机文件,远端控制器不伪造其身份。 */
1232
+ async function cmdMerchantConnect(args) {
1233
+ try {
1234
+ const profile = requireProfileOrDefault(args);
1235
+ const dataDir = resolveServeDataDir(args.dataDir, profile.agent_id, profile.merchant_runtime?.data_dir);
1236
+ const catalog = args.catalog ?? process.env.KIWI_CATALOG_URL ?? profile.merchant_public?.catalog_url ?? DEFAULT_CATALOG_URL;
1237
+ const publicOrigin = process.env.KIWI_CLOUD_PUBLIC_ORIGIN ?? process.env.KIWI_A2A_PUBLIC_URL ?? profile.merchant_public?.public_url;
1238
+ const result = await connectMerchant({
1239
+ profile,
1240
+ dataDir,
1241
+ catalogUrl: catalog,
1242
+ ...(publicOrigin !== undefined ? { publicOrigin } : {}),
1243
+ ...(process.platform !== "win32" ? { openBrowser: (url) => {
1244
+ const command = process.platform === "darwin" ? "open" : "xdg-open";
1245
+ const commandArgs = [url];
1246
+ const child = spawn(command, commandArgs, { detached: true, stdio: "ignore" });
1247
+ child.once("error", () => {
1248
+ process.stderr.write("无法自动打开浏览器;请使用上方授权链接在手机或其他设备打开。\n");
1249
+ });
1250
+ child.unref();
1251
+ } } : {}),
1252
+ });
1253
+ process.stdout.write(`已上线:Catalog Agent ${result.agentId},绑定 ${result.bindingId},名片 revision ${result.cardRevision}。\n` +
1254
+ "商品发布使用当前 Runtime 绑定签名,并受 Catalog 商家方案额度限制;可在商家后台查看已用名额。\n");
1255
+ return EXIT.OK;
1256
+ }
1257
+ catch (err) {
1258
+ process.stderr.write(`${err instanceof Error ? err.message : String(err)}\n`);
1259
+ return EXIT.CONFIG;
1260
+ }
1261
+ }
1196
1262
  /**
1197
1263
  * `kiwi merchant runtime start|stop|status|health`:Merchant 实例运行时管理
1198
1264
  * (V2 阶段一 src/merchant-runtime/)。A2A 接待服务与 MCP 管理服务作为受管
@@ -1205,8 +1271,8 @@ async function routeMerchant(sub, args) {
1205
1271
  */
1206
1272
  async function cmdMerchantRuntime(args) {
1207
1273
  const action = args.command[2];
1208
- if (action === undefined || !["start", "stop", "status", "health"].includes(action)) {
1209
- process.stderr.write("usage: kiwi merchant runtime <start|stop|status|health> [--profile <file>] [--data-dir <dir>]\n");
1274
+ if (action === undefined || !["start", "stop", "status", "health", "rotate-key"].includes(action)) {
1275
+ process.stderr.write("usage: kiwi merchant runtime <start|stop|status|health|rotate-key> [--profile <file>] [--data-dir <dir>]\n");
1210
1276
  return EXIT.CONFIG;
1211
1277
  }
1212
1278
  const profile = requireProfileOrDefault(args);
@@ -1215,9 +1281,37 @@ async function cmdMerchantRuntime(args) {
1215
1281
  return EXIT.CONFIG;
1216
1282
  }
1217
1283
  const dirs = resolveMerchantMcpDirs({
1218
- ...(args.dataDir !== undefined ? { dataDir: args.dataDir } : {}),
1284
+ ...(configuredDataDir(args, profile) !== undefined ? { dataDir: configuredDataDir(args, profile) } : {}),
1219
1285
  agentId: profile.agent_id,
1220
1286
  });
1287
+ if (action === "rotate-key") {
1288
+ const publicOrigin = process.env.KIWI_A2A_PUBLIC_URL ?? profile.merchant_public?.public_url;
1289
+ let keyId = `merchant:${profile.agent_id}`;
1290
+ if (publicOrigin !== undefined && publicOrigin.trim() !== "") {
1291
+ try {
1292
+ const parsed = new URL(publicOrigin);
1293
+ if (parsed.protocol !== "https:" || parsed.username !== "" || parsed.password !== "" ||
1294
+ parsed.pathname !== "/" && parsed.pathname !== "" || parsed.search !== "" || parsed.hash !== "") {
1295
+ throw new Error("public origin must be a bare HTTPS origin");
1296
+ }
1297
+ keyId = parsed.origin;
1298
+ }
1299
+ catch (err) {
1300
+ process.stderr.write(`Runtime key rotation refused: ${err instanceof Error ? err.message : String(err)}\n`);
1301
+ return EXIT.CONFIG;
1302
+ }
1303
+ }
1304
+ try {
1305
+ rotateEnrollmentSigningKey(dirs.merchantDataDir, keyId);
1306
+ }
1307
+ catch (err) {
1308
+ process.stderr.write(`${err instanceof Error ? err.message : String(err)}\n`);
1309
+ return EXIT.CONFIG;
1310
+ }
1311
+ process.stdout.write("Runtime持久签名密钥已轮换。旧Catalog绑定可能仍有效,直到新Runtime使用新密钥完成Catalog登录确认、绑定和名片发布;本地不会假报撤销。若旧密钥确认泄漏,请先在Catalog暂停/撤回旧服务。\n" +
1312
+ "下一步:启动Runtime,然后运行 kiwi merchant connect 重新登录并批准新的公开预览。地址或公开卡片发生变化时,Catalog会展示新预览并要求确认。\n");
1313
+ return EXIT.OK;
1314
+ }
1221
1315
  const cliEntry = fileURLToPath(import.meta.url);
1222
1316
  const profileArgs = args.profile !== undefined ? ["--profile", args.profile] : [];
1223
1317
  const manager = new MerchantRuntimeManager({
@@ -1336,7 +1430,7 @@ async function cmdMerchantMcp(args) {
1336
1430
  return EXIT.CONFIG;
1337
1431
  }
1338
1432
  const dirs = resolveMerchantMcpDirs({
1339
- ...(args.dataDir !== undefined ? { dataDir: args.dataDir } : {}),
1433
+ ...(configuredDataDir(args, profile) !== undefined ? { dataDir: configuredDataDir(args, profile) } : {}),
1340
1434
  agentId: profile.agent_id,
1341
1435
  });
1342
1436
  try {
@@ -1363,7 +1457,7 @@ async function cmdMerchantMcp(args) {
1363
1457
  return EXIT.CONFIG;
1364
1458
  }
1365
1459
  const dirs = resolveMerchantMcpDirs({
1366
- ...(args.dataDir !== undefined ? { dataDir: args.dataDir } : {}),
1460
+ ...(configuredDataDir(args, profile) !== undefined ? { dataDir: configuredDataDir(args, profile) } : {}),
1367
1461
  agentId: profile.agent_id,
1368
1462
  });
1369
1463
  const { code, expiresAt } = createPairingCode(dirs.merchantDataDir);
@@ -1394,7 +1488,7 @@ async function cmdMerchantMcp(args) {
1394
1488
  return EXIT.CONFIG;
1395
1489
  }
1396
1490
  const dirs = resolveMerchantMcpDirs({
1397
- ...(args.dataDir !== undefined ? { dataDir: args.dataDir } : {}),
1491
+ ...(configuredDataDir(args, profile) !== undefined ? { dataDir: configuredDataDir(args, profile) } : {}),
1398
1492
  agentId: profile.agent_id,
1399
1493
  });
1400
1494
  const revoked = revokePairedCredential(dirs.merchantDataDir);
@@ -1435,7 +1529,7 @@ async function cmdMerchantMcp(args) {
1435
1529
  // 数据目录接线(V2 §5.1):merchant/principal/transportSessionId 显式注入,
1436
1530
  // 路径是 (dataDir, agentId) 的纯函数——重启稳定,传输会话不影响目录。
1437
1531
  const dirs = resolveMerchantMcpDirs({
1438
- ...(args.dataDir !== undefined ? { dataDir: args.dataDir } : {}),
1532
+ ...(configuredDataDir(args, profile) !== undefined ? { dataDir: configuredDataDir(args, profile) } : {}),
1439
1533
  agentId: profile.agent_id,
1440
1534
  });
1441
1535
  let assembly;
@@ -1493,7 +1587,7 @@ async function cmdMerchantStats(args) {
1493
1587
  try {
1494
1588
  const report = merchantStats({
1495
1589
  agentId: profile.agent_id,
1496
- dataDir: resolveServeDataDir(args.dataDir, profile.agent_id),
1590
+ dataDir: resolveServeDataDir(args.dataDir, profile.agent_id, profile.merchant_runtime?.data_dir),
1497
1591
  ...(days !== undefined ? { days } : {}),
1498
1592
  });
1499
1593
  printJson(report);
@@ -1522,19 +1616,72 @@ function promptLine(text, fallback) {
1522
1616
  });
1523
1617
  });
1524
1618
  }
1619
+ /** Read a secret in a TTY without echoing it. */
1620
+ function promptSecret(text) {
1621
+ if (!process.stdin.isTTY)
1622
+ return Promise.resolve("");
1623
+ process.stdout.write(text);
1624
+ const hiddenOutput = new Writable({ write(_chunk, _encoding, callback) { callback(); } });
1625
+ return new Promise((resolve) => {
1626
+ const rl = readline.createInterface({ input: process.stdin, output: hiddenOutput, terminal: true });
1627
+ rl.question("", (answer) => {
1628
+ rl.close();
1629
+ process.stdout.write("\n");
1630
+ resolve(answer.trim());
1631
+ });
1632
+ });
1633
+ }
1525
1634
  async function cmdMerchantInit(args) {
1526
- // --merchant-id / --name flag 优先,env 回退;TTY 下交互提示,缺省自动派生。
1635
+ // 无参数时续用默认 profile;首次运行仅询问商家名称,其余使用默认值。
1527
1636
  let merchantId = args.merchantId ?? process.env.KIWI_MERCHANT_ID ?? "";
1528
1637
  let name = args.merchantName ?? process.env.KIWI_MERCHANT_NAME ?? "";
1529
- let publicUrl = "";
1530
- let merchantToken = "";
1638
+ const outputPath = args.output ?? args.profile ?? process.env.KIWI_DEFAULT_PROFILE ?? DEFAULT_PROFILE_PATH;
1639
+ if (existsSync(outputPath) && !args.force && merchantId === "" && name === "") {
1640
+ try {
1641
+ const existing = loadProfile(outputPath);
1642
+ if (existing.role === "merchant") {
1643
+ merchantId = existing.agent_id;
1644
+ name = existing.name ?? existing.owner_id;
1645
+ }
1646
+ }
1647
+ catch {
1648
+ // merchantInit reports safely and preserves unknown/corrupt files.
1649
+ }
1650
+ }
1651
+ let publicUrl = args.publicUrl ?? process.env.KIWI_A2A_PUBLIC_URL ?? "";
1652
+ if (publicUrl === "" && existsSync(outputPath)) {
1653
+ try {
1654
+ publicUrl = loadProfile(outputPath).merchant_public?.public_url ?? "";
1655
+ }
1656
+ catch { /* validated by init */ }
1657
+ }
1658
+ // 商品服务令牌仅连接 shopping-cli;TTY 隐藏输入并写入本机 credentials 文件。
1659
+ let merchantToken = args.merchantToken ?? "";
1531
1660
  if (process.stdin.isTTY) {
1532
1661
  merchantId = await promptLine(`merchant_id(回车自动生成${name !== "" ? `,建议 ${slugifyMerchantId(name)}` : ""}): `, merchantId);
1533
1662
  name = await promptLine(`商家名称(回车用缺省): `, name);
1534
- publicUrl = await promptLine("公网域名(可选,回车跳过;如 merchant.example.com): ", "");
1535
- if (publicUrl !== "")
1536
- publicUrl = publicUrl.trim().toLowerCase();
1537
- merchantToken = await promptLine("商家令牌(从商家后台获取,可稍后设置;直接回车跳过): ", "");
1663
+ let addressPrompt = "公网 Runtime 地址(域名或 HTTPS 地址;回车稍后配置): ";
1664
+ if (publicUrl === "") {
1665
+ const detectedIp = await detectPublicIp();
1666
+ if (detectedIp !== null) {
1667
+ process.stdout.write(`检测到服务器出口公网 IPv4:${detectedIp}\n` +
1668
+ "它只是候选地址;是否可用还要验证公网 HTTPS 证书、端口和 Agent Card。已有域名建议优先使用。\n");
1669
+ addressPrompt = `公网 Runtime 地址(域名或 https://${detectedIp};回车稍后配置): `;
1670
+ }
1671
+ else {
1672
+ process.stdout.write("暂时无法自动检测服务器公网 IP;你仍可输入公网域名或 HTTPS 地址。\n");
1673
+ }
1674
+ }
1675
+ publicUrl = await promptLine(addressPrompt, publicUrl);
1676
+ if (publicUrl !== "") {
1677
+ publicUrl = normalizeMerchantRuntimeOriginInput(publicUrl);
1678
+ }
1679
+ if (merchantToken === "") {
1680
+ loadMerchantCredentials();
1681
+ merchantToken = process.env.KIWI_MERCHANT_TOKEN ?? "";
1682
+ if (merchantToken === "")
1683
+ merchantToken = await promptSecret("shopping-cli 商品服务令牌(回车稍后配置;输入不回显): ");
1684
+ }
1538
1685
  // TTY 下可全回车:merchant_id 自动生成(避免固定名碰撞)。
1539
1686
  if (merchantId === "")
1540
1687
  merchantId = `merchant-${Math.random().toString(36).slice(2, 8)}`;
@@ -1542,9 +1689,8 @@ async function cmdMerchantInit(args) {
1542
1689
  name = merchantId;
1543
1690
  }
1544
1691
  else if (merchantId === "" && name === "") {
1545
- // 非交互且无任何身份 → fail-closed(不自动生成碰撞身份)。
1546
- process.stderr.write("--merchant-id <id> 或 --name <商家名称> 至少填一个(TTY 下可交互回车自动生成)。\n");
1547
- return EXIT.CONFIG;
1692
+ merchantId = `merchant-${Math.random().toString(36).slice(2, 8)}`;
1693
+ name = merchantId;
1548
1694
  }
1549
1695
  else {
1550
1696
  // 系统补全:merchant_id 缺省从名称派生;名称缺省用 merchant_id。
@@ -1559,18 +1705,76 @@ async function cmdMerchantInit(args) {
1559
1705
  ...(publicUrl !== "" ? { publicUrl } : {}),
1560
1706
  ...(merchantToken !== "" ? { merchantToken } : {}),
1561
1707
  shoppingCliUrl: process.env.SHOPPING_CLI_URL ?? "http://127.0.0.1:8765",
1562
- shoppingCliDb: process.env.SHOPPING_DB_PATH,
1708
+ shoppingCliDb: args.shoppingCliDb ?? process.env.SHOPPING_DB_PATH,
1563
1709
  catalogUrl: args.catalog ?? process.env.KIWI_CATALOG_URL ?? DEFAULT_CATALOG_URL,
1710
+ ...(args.dataDir !== undefined ? { dataDir: args.dataDir } : {}),
1564
1711
  floorPriceMinor: 0,
1565
- ...(args.output !== undefined ? { outputPath: args.output } : {}),
1712
+ outputPath,
1566
1713
  ...(args.force ? { force: true } : {}),
1567
1714
  // 数据引擎默认自动安装(合一体验);--no-install 显式禁用(受限/CI)
1568
1715
  autoInstallShoppingCli: !args.noInstall,
1569
1716
  });
1570
- printJson(report);
1717
+ if (merchantToken !== "")
1718
+ process.env.KIWI_MERCHANT_TOKEN = merchantToken;
1719
+ else
1720
+ loadMerchantCredentials();
1721
+ let sourceCapabilities = report.steps.product_source_capabilities;
1722
+ if (report.steps.shopping_cli_reachable.ok) {
1723
+ try {
1724
+ const profile = loadProfile(report.profile_path);
1725
+ const probe = await new HttpMerchantClient(profile.commerce.base_url, new ProfileCredentialBroker(profile)).probeCapabilities();
1726
+ sourceCapabilities = {
1727
+ ok: probe.ok,
1728
+ detail: [probe.verdict, probe.version ? `shopping-cli ${probe.version}` : undefined,
1729
+ probe.protocol_versions ? `protocols ${probe.protocol_versions.join(", ")}` : undefined,
1730
+ probe.error].filter(Boolean).join(";"),
1731
+ };
1732
+ }
1733
+ catch (err) {
1734
+ sourceCapabilities = { ok: false, detail: err instanceof Error ? err.message : String(err) };
1735
+ }
1736
+ }
1737
+ let enrollment;
1738
+ const configuredOrigin = args.publicUrl ?? publicUrl;
1739
+ if (configuredOrigin !== "") {
1740
+ try {
1741
+ const profile = loadProfile(report.profile_path);
1742
+ const result = await connectMerchant({
1743
+ profile,
1744
+ dataDir: resolveServeDataDir(args.dataDir, profile.agent_id, profile.merchant_runtime?.data_dir),
1745
+ catalogUrl: args.catalog ?? process.env.KIWI_CATALOG_URL ?? profile.merchant_public?.catalog_url ?? DEFAULT_CATALOG_URL,
1746
+ publicOrigin: configuredOrigin,
1747
+ output: (line) => process.stdout.write(`${line}\n`),
1748
+ ...(process.platform !== "win32" ? { openBrowser: (url) => {
1749
+ const command = process.platform === "darwin" ? "open" : "xdg-open";
1750
+ const child = spawn(command, [url], { detached: true, stdio: "ignore" });
1751
+ child.once("error", () => process.stderr.write("无法自动打开浏览器;请使用上方授权链接打开。\n"));
1752
+ child.unref();
1753
+ } } : {}),
1754
+ });
1755
+ enrollment = { ok: true, detail: `绑定 ${result.bindingId},Agent ${result.agentId},名片 revision ${result.cardRevision}` };
1756
+ }
1757
+ catch (err) {
1758
+ enrollment = { ok: false, detail: err instanceof Error ? err.message : String(err) };
1759
+ }
1760
+ }
1761
+ printJson({ ...report, steps: { ...report.steps, product_source_capabilities: sourceCapabilities,
1762
+ ...(enrollment !== undefined ? { runtime_enrollment: enrollment } : {}) } });
1571
1763
  for (const warning of report.warnings) {
1572
1764
  process.stderr.write(`warning: ${warning}\n`);
1573
1765
  }
1766
+ if (!sourceCapabilities.ok)
1767
+ process.stderr.write(`商品源能力尚未通过:${sourceCapabilities.detail ?? "未验证"}\n`);
1768
+ if (enrollment !== undefined && !enrollment.ok) {
1769
+ process.stderr.write(`Runtime enrollment 未完成:${enrollment.detail}\n`);
1770
+ return EXIT.TRANSIENT;
1771
+ }
1772
+ if (configuredOrigin === "") {
1773
+ process.stderr.write("尚未提供公网 Runtime 地址;Catalog 账号授权和绑定未完成。先让 Agent Card 可经 HTTPS 公网访问,再设置 --public-url 重跑 init 继续。\n");
1774
+ }
1775
+ if (args.merchantToken !== undefined && report.ok) {
1776
+ process.stderr.write("shopping-cli 商品服务令牌已写入 ~/.kiwi/credentials.env(0600);它不用于 Kiwi Catalog Runtime 绑定。\n");
1777
+ }
1574
1778
  return report.ok ? EXIT.OK : EXIT.CONFIG;
1575
1779
  }
1576
1780
  /**
@@ -1585,7 +1789,10 @@ async function cmdMerchantPublish(args) {
1585
1789
  }
1586
1790
  loadMerchantCredentials(); // 加载 init 写入的 credentials.env(KIWI_MERCHANT_TOKEN)
1587
1791
  // 缺省路径与 shopping-cli 的 DEFAULT_DB_PATH 一致——商家无需设置 SHOPPING_DB_PATH。
1588
- const shoppingCliDb = args.shoppingCliDb ?? process.env.SHOPPING_DB_PATH ?? DEFAULT_SHOPPING_DB_PATH;
1792
+ const shoppingCliDb = args.shoppingCliDb ??
1793
+ profile.merchant_public?.shopping_db_path ??
1794
+ process.env.SHOPPING_DB_PATH ??
1795
+ DEFAULT_SHOPPING_DB_PATH;
1589
1796
  // `--file <csv>`:先导入商品(shopping-cli import-csv-excel)再发布。
1590
1797
  if (args.file !== undefined && args.file !== "") {
1591
1798
  const imp = spawnSync("shopping-cli", ["import-csv-excel", "--file", args.file, "--merchant", profile.agent_id, "--format", "json"], { env: { ...process.env, SHOPPING_DB_PATH: shoppingCliDb }, stdio: "inherit" });
@@ -1604,10 +1811,6 @@ async function cmdMerchantPublish(args) {
1604
1811
  const merchantToken = (merchantTokenEnv ? process.env[merchantTokenEnv] : undefined) ||
1605
1812
  process.env.KIWI_MERCHANT_TOKEN ||
1606
1813
  "";
1607
- if (!merchantToken && !ownerTokenSecret) {
1608
- process.stderr.write("需要 KIWI_MERCHANT_TOKEN(随机 token,推荐)或 KIWI_CATALOG_OWNER_TOKEN_SECRET(legacy HMAC)\n");
1609
- return EXIT.CONFIG;
1610
- }
1611
1814
  const catalog = args.catalog ??
1612
1815
  profile.merchant_public?.catalog_url ??
1613
1816
  process.env.KIWI_CATALOG_URL ??
@@ -1618,6 +1821,10 @@ async function cmdMerchantPublish(args) {
1618
1821
  ...(merchantToken ? { ownerToken: merchantToken } : {}),
1619
1822
  ...(ownerTokenSecret ? { ownerTokenSecret } : {}),
1620
1823
  shoppingCliDb,
1824
+ dataDir: resolveServeDataDir(args.dataDir, profile.agent_id, profile.merchant_runtime?.data_dir),
1825
+ ...(process.env.KIWI_A2A_PUBLIC_URL ?? profile.merchant_public?.public_url
1826
+ ? { runtimeOrigin: process.env.KIWI_A2A_PUBLIC_URL ?? profile.merchant_public?.public_url }
1827
+ : {}),
1621
1828
  ...(args.shoppingCliPath !== undefined ? { shoppingCliPath: args.shoppingCliPath } : {}),
1622
1829
  ...(args.shoppingCliMerchant !== undefined
1623
1830
  ? { shoppingCliMerchant: args.shoppingCliMerchant }
@@ -1774,7 +1981,7 @@ async function cmdMerchantUp(args) {
1774
1981
  process.env.KIWI_CATALOG_URL ??
1775
1982
  DEFAULT_CATALOG_URL;
1776
1983
  const merchantToken = process.env.KIWI_MERCHANT_TOKEN || "";
1777
- const serveDataDir = resolveServeDataDir(args.dataDir, profile.agent_id);
1984
+ const serveDataDir = resolveServeDataDir(args.dataDir, profile.agent_id, profile.merchant_runtime?.data_dir);
1778
1985
  let node = await startA2aNode({
1779
1986
  profile,
1780
1987
  catalog,