@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
@@ -16,6 +16,7 @@
16
16
  import type { IncomingMessage, ServerResponse } from "node:http";
17
17
  import type { WriteApprovalCandidate } from "../../agent/merchant/action-candidate.js";
18
18
  import type { MerchantAdminSessions } from "../../auth/merchant-sessions.js";
19
+ import { type createFileListingPublicationService } from "../../cloud/file-listing-publication.js";
19
20
  import { type CloudProductRecord, type CloudProductTable } from "../../cloud/product-source.js";
20
21
  import { MerchantImportDraftStore } from "./draft-store.js";
21
22
  import { type VerifiedActorContext } from "../../merchant/application/actor.js";
@@ -26,6 +27,8 @@ import { OnboardingStore } from "../../cloud/onboarding/store.js";
26
27
  import type { PlatformEvidenceResult } from "../../cloud/onboarding/types.js";
27
28
  import { type WorkbenchConfirmationStore } from "./webauthn-confirmation.js";
28
29
  import { type A2aNegotiationRow } from "../../merchant/workbench-service.js";
30
+ import { type NegotiationObserver } from "../../merchant/negotiation-observer.js";
31
+ import { type OperationsReportBuilder } from "../../merchant/operations-report.js";
29
32
  import type { ExactMerchantProduct } from "../../agent/merchant/types.js";
30
33
  import { type ExactMoney } from "../../merchant/application/money.js";
31
34
  import type { WorkbenchQuoteResult } from "../../merchant/quote-calculator.js";
@@ -39,6 +42,8 @@ import { type GrantAction, type GrantResourceType, type MerchantGrantStore } fro
39
42
  export interface MerchantManagementApiOptions {
40
43
  /** 本实例商家(服务端绑定;不来自请求)。 */
41
44
  merchantId: string;
45
+ merchantName?: string;
46
+ merchantNameNeedsUpdate?: boolean;
42
47
  /** 当前部署代次(单代次实例恒 1;代次切换后旧代次不得再产生业务写入)。 */
43
48
  generation: () => number;
44
49
  runtimeVersion: string;
@@ -82,10 +87,14 @@ export interface MerchantManagementApiOptions {
82
87
  digest: string;
83
88
  records: CloudProductRecord[];
84
89
  };
90
+ /** Attach local runtime ownership and the Catalog-confirmed merchant id. */
91
+ prepareTable?: (table: CloudProductTable) => CloudProductTable | Promise<CloudProductTable>;
85
92
  commit: (table: CloudProductTable) => {
86
93
  digest: string;
87
94
  };
88
95
  };
96
+ /** Explicit owner preview/confirmation for public Catalog product metadata. */
97
+ fileListingPublication?: ReturnType<typeof createFileListingPublicationService>;
89
98
  /** 策略草稿提交(MerchantPolicyRuntime.apply;缺省 → 503)。回执只含版本与摘要。 */
90
99
  policyApply?: (patch: Record<string, unknown>) => Promise<{
91
100
  version: number;
@@ -101,6 +110,7 @@ export interface MerchantManagementApiOptions {
101
110
  ready: boolean;
102
111
  checks: Record<string, {
103
112
  ok: boolean;
113
+ code?: string;
104
114
  }>;
105
115
  }>;
106
116
  /**
@@ -112,11 +122,30 @@ export interface MerchantManagementApiOptions {
112
122
  */
113
123
  onboarding?: {
114
124
  store: OnboardingStore;
125
+ /** 只读安全配对信息的目录;设备码和许可永不经此 API 返回。 */
126
+ enrollmentStateDir?: string;
115
127
  platformEvidence?: (input: {
116
128
  stepId: string;
117
129
  recordId: string;
118
130
  }) => Promise<PlatformEvidenceResult>;
119
131
  };
132
+ /** 已部署实例的目录连接;独立于需要平台回执的部署向导。 */
133
+ catalogConnection?: {
134
+ getSummary: () => Promise<{
135
+ status: string;
136
+ published: boolean;
137
+ agentId?: string;
138
+ bindingId?: string;
139
+ bindingExpiresAt?: string;
140
+ errorCode?: string;
141
+ }>;
142
+ getPairing: () => Promise<{
143
+ user_code: string;
144
+ verification_uri: string;
145
+ expires_at: string;
146
+ } | null>;
147
+ begin: () => Promise<unknown>;
148
+ };
120
149
  /** Workbench v1 trusted confirmation authority; absent means strong-confirmation routes fail closed. */
121
150
  workbenchConfirmations?: WorkbenchConfirmationStore;
122
151
  /** Workbench Feed authority. Writes remain candidate-only through the prepare callbacks. */
@@ -132,6 +161,14 @@ export interface MerchantManagementApiOptions {
132
161
  }>;
133
162
  get: (negotiationId: string) => Promise<A2aNegotiationRow>;
134
163
  };
164
+ /**
165
+ * 会话旁观投影(WP11):分页(offset cursor)+ 状态过滤 + 单条时间线。
166
+ * 配置后 `/negotiations` 走本通道(limit-only 查询语义不变);未配置时
167
+ * 维持上面的 legacy 通道(仅 limit)。
168
+ */
169
+ negotiationObserver?: NegotiationObserver;
170
+ /** 运营报告聚合(WP11):stats-store + 磋商账本 → day/week/month 报告。 */
171
+ operationsReports?: OperationsReportBuilder;
135
172
  workbenchReconciliation?: WorkbenchReconciliationStore;
136
173
  exactProducts?: {
137
174
  list: () => Promise<ExactMerchantProduct[]>;
@@ -40,17 +40,22 @@
40
40
  import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
41
41
  import { contentHash } from "../../agent/merchant/action-candidate.js";
42
42
  import { ADMIN_SESSION_COOKIE } from "../../auth/merchant-sessions.js";
43
+ import { FileListingPublicationError, } from "../../cloud/file-listing-publication.js";
43
44
  import { parseProductTable, ProductTableError, productTableDigest, } from "../../cloud/product-source.js";
45
+ import { convertTabularImport, renderImportTemplateCsv, renderImportTemplateXlsx, TABULAR_IMPORT_MAX_BYTES, } from "../../cloud/product-import-tabular.js";
44
46
  import { MerchantImportDraftStore } from "./draft-store.js";
45
47
  import { ActorContextError, assertVerifiedActor, createVerifiedActorContext, hasPermission, } from "../../merchant/application/actor.js";
46
48
  import { MANAGEMENT_API_MAJOR, MANAGEMENT_ERROR_STATUS, ManagementError, MerchantApplicationService, } from "../../merchant/application/service.js";
47
49
  import { managementRequestDigest, MerchantManagementOperationStore } from "./operation-store.js";
48
50
  import { OnboardingStore } from "../../cloud/onboarding/store.js";
51
+ import { readEnrollmentStore } from "../../cloud/binding/enrollment-challenge.js";
49
52
  import { requestsDisabledLocalImplementation } from "../../cloud/onboarding/local-fallback.js";
50
53
  import { checkStepSubmission, planWizard, WIZARD_STEPS } from "../../cloud/onboarding/steps.js";
51
54
  import { createWorkbenchProblem } from "./problem.js";
52
55
  import { WorkbenchConfirmationError, } from "./webauthn-confirmation.js";
53
56
  import { MerchantWorkbenchError, } from "../../merchant/workbench-service.js";
57
+ import { NEGOTIATION_STATUS_FILTERS, } from "../../merchant/negotiation-observer.js";
58
+ import { parseReportPeriod, } from "../../merchant/operations-report.js";
54
59
  import { parseExactMoney, WorkbenchMoneyError, WORKBENCH_CURRENCY_TABLE_VERSION, } from "../../merchant/application/money.js";
55
60
  import { EXACT_PRODUCT_TOOLS } from "../../merchant/exact-product-executors.js";
56
61
  import { SERVICE_CONTROL_TOOLS } from "../../merchant/service-control-executors.js";
@@ -63,6 +68,11 @@ import { WorkbenchEventProjectionError, } from "./event-projection.js";
63
68
  import { GRANT_ACTIONS, MerchantGrantError, } from "../../merchant/grant-store.js";
64
69
  const API_PREFIX = "/merchant/api";
65
70
  const WORKBENCH_API_PREFIX = "/merchant/api/v1";
71
+ const CATALOG_CONNECTION_SAFE_CODES = new Set([
72
+ "PUBLICATION_NOT_ACTIVE", "PUBLICATION_NOT_VERIFIED", "CATALOG_UNREACHABLE",
73
+ "CATALOG_MISMATCH", "BINDING_MERCHANT_MISMATCH", "BINDING_CLAIM_EXPIRED",
74
+ "BINDING_EXPIRED", "AUTHORIZATION_PENDING", "PREVIEW_CHANGED", "RUNTIME_CARD_CHANGED",
75
+ ]);
66
76
  const MAX_BODY_BYTES = 1_048_576;
67
77
  /** 非候选写命令确认引用的有效期(BD §7.3:短时、单次)。 */
68
78
  const CONFIRMATION_TTL_MS = 5 * 60 * 1000;
@@ -144,7 +154,7 @@ export function createMerchantManagementApiHandler(options) {
144
154
  return;
145
155
  }
146
156
  if (method === "POST") {
147
- await routeWorkbenchV1Post(req, res, rest, requestId);
157
+ await routeWorkbenchV1Post(req, res, rest, requestId, url);
148
158
  return;
149
159
  }
150
160
  {
@@ -185,6 +195,50 @@ export function createMerchantManagementApiHandler(options) {
185
195
  // ── 只读路由(认证即鉴权入口;业务授权在服务层逐次复核)────────────────
186
196
  /** Workbench v1 读取面复用同一应用服务;未实现路由明确失败,不返回假数据。 */
187
197
  async function routeWorkbenchV1Get(req, res, url, rest, requestId) {
198
+ const listingDraftMatch = /^\/products\/publication-drafts\/(flp_[a-z0-9]+_[0-9a-f]{12})$/.exec(rest);
199
+ if (listingDraftMatch !== null) {
200
+ const auth = requireActor(req);
201
+ authorizeOrThrow(auth.ctx, "products:import");
202
+ if (auth.ctx.role !== "owner")
203
+ throw new ManagementError("forbidden", "only owner can publish products");
204
+ const channel = options.fileListingPublication;
205
+ if (channel === undefined)
206
+ throw new ManagementError("unavailable", "product publication is unavailable");
207
+ const result = await channel.getDraft(listingDraftMatch[1]);
208
+ if (!result.found)
209
+ throw new ManagementError("not_found", "publication draft does not exist");
210
+ writeJson(res, 200, result, { "x-request-id": requestId });
211
+ return;
212
+ }
213
+ if (rest === "/catalog/connect" || rest === "/catalog/connect/pairing") {
214
+ const auth = requireActor(req);
215
+ authorizeOrThrow(auth.ctx, "onboarding:manage");
216
+ if (auth.ctx.role !== "owner")
217
+ throw new ManagementError("forbidden", "only owner can manage Catalog connection");
218
+ const channel = options.catalogConnection;
219
+ if (channel === undefined)
220
+ throw new ManagementError("unavailable", "Catalog connection is not configured");
221
+ if (rest.endsWith("/pairing")) {
222
+ const pairing = await channel.getPairing();
223
+ writeJson(res, 200, { pairing: pairing === null ? null : {
224
+ user_code: pairing.user_code,
225
+ verification_uri: pairing.verification_uri,
226
+ expires_at: pairing.expires_at,
227
+ } }, { "x-request-id": requestId });
228
+ }
229
+ else {
230
+ const summary = await channel.getSummary();
231
+ // 默认状态响应白名单:配对码与设备凭据不能混入助手可读取的摘要。
232
+ writeJson(res, 200, {
233
+ status: summary.status, published: summary.published,
234
+ agentId: summary.agentId ?? null, bindingId: summary.bindingId ?? null,
235
+ bindingExpiresAt: summary.bindingExpiresAt ?? null,
236
+ errorCode: summary.errorCode == null ? null : CATALOG_CONNECTION_SAFE_CODES.has(summary.errorCode)
237
+ ? summary.errorCode : "CATALOG_CONNECTION_UNAVAILABLE",
238
+ }, { "x-request-id": requestId });
239
+ }
240
+ return;
241
+ }
188
242
  if (rest === "/overview") {
189
243
  const auth = requireActor(req);
190
244
  const runtime = await readService.getStatus(auth.ctx);
@@ -244,7 +298,11 @@ export function createMerchantManagementApiHandler(options) {
244
298
  }
245
299
  if (rest === "/runtime/status") {
246
300
  const auth = requireActor(req);
247
- writeJson(res, 200, await readService.getStatus(auth.ctx), { "x-request-id": requestId });
301
+ writeJson(res, 200, {
302
+ ...await readService.getStatus(auth.ctx),
303
+ merchant_name: options.merchantName ?? null,
304
+ merchant_name_needs_update: options.merchantNameNeedsUpdate === true,
305
+ }, { "x-request-id": requestId });
248
306
  return;
249
307
  }
250
308
  if (rest === "/products") {
@@ -268,6 +326,38 @@ export function createMerchantManagementApiHandler(options) {
268
326
  }, { "x-request-id": requestId });
269
327
  return;
270
328
  }
329
+ if (rest === "/products/import-template") {
330
+ const auth = requireActor(req);
331
+ authorizeOrThrow(auth.ctx, "products:read");
332
+ const format = url.searchParams.get("format");
333
+ if (format !== "csv" && format !== "xlsx") {
334
+ throw new ManagementError("invalid_input", "format must be csv or xlsx");
335
+ }
336
+ if (res.headersSent) {
337
+ res.end();
338
+ return;
339
+ }
340
+ if (format === "csv") {
341
+ const body = renderImportTemplateCsv();
342
+ res.writeHead(200, {
343
+ "content-type": "text/csv; charset=utf-8",
344
+ "content-disposition": 'attachment; filename="kiwi-product-import-template.csv"',
345
+ "cache-control": "no-store",
346
+ "x-request-id": requestId,
347
+ });
348
+ res.end(body);
349
+ return;
350
+ }
351
+ const bytes = renderImportTemplateXlsx();
352
+ res.writeHead(200, {
353
+ "content-type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
354
+ "content-disposition": 'attachment; filename="kiwi-product-import-template.xlsx"',
355
+ "cache-control": "no-store",
356
+ "x-request-id": requestId,
357
+ });
358
+ res.end(Buffer.from(bytes));
359
+ return;
360
+ }
271
361
  const productMatch = /^\/products\/([^/]+)$/.exec(rest);
272
362
  if (productMatch !== null) {
273
363
  const auth = requireActor(req);
@@ -289,11 +379,29 @@ export function createMerchantManagementApiHandler(options) {
289
379
  if (rest === "/negotiations") {
290
380
  const auth = requireActor(req);
291
381
  authorizeOrThrow(auth.ctx, "approvals:read");
382
+ const query = pageQuery(url);
383
+ const statusRaw = url.searchParams.get("status");
384
+ if (statusRaw !== null && statusRaw !== "" && !NEGOTIATION_STATUS_FILTERS.includes(statusRaw)) {
385
+ throw new ManagementError("invalid_input", "status must be active, agreement or all");
386
+ }
387
+ const observer = options.negotiationObserver;
388
+ if (observer !== undefined) {
389
+ writeJson(res, 200, observer.list({
390
+ ...(query.cursor !== undefined ? { cursor: query.cursor } : {}),
391
+ ...(query.limit !== undefined ? { limit: query.limit } : {}),
392
+ ...(statusRaw !== null && statusRaw !== ""
393
+ ? { status: statusRaw }
394
+ : {}),
395
+ }), { "x-request-id": requestId });
396
+ return;
397
+ }
398
+ if (statusRaw !== null && statusRaw !== "") {
399
+ throw new ManagementError("unavailable", "status filtering requires the negotiation observer projection");
400
+ }
292
401
  const channel = options.negotiations;
293
402
  if (channel === undefined) {
294
403
  throw new ManagementError("unavailable", "negotiation authority is not configured");
295
404
  }
296
- const query = pageQuery(url);
297
405
  writeJson(res, 200, await channel.list(query.limit), { "x-request-id": requestId });
298
406
  return;
299
407
  }
@@ -301,6 +409,13 @@ export function createMerchantManagementApiHandler(options) {
301
409
  if (negotiationMatch !== null) {
302
410
  const auth = requireActor(req);
303
411
  authorizeOrThrow(auth.ctx, "approvals:read");
412
+ const observer = options.negotiationObserver;
413
+ if (observer !== undefined) {
414
+ writeJson(res, 200, observer.timeline(pathSegment(negotiationMatch[1] ?? "")), {
415
+ "x-request-id": requestId,
416
+ });
417
+ return;
418
+ }
304
419
  const channel = options.negotiations;
305
420
  if (channel === undefined) {
306
421
  throw new ManagementError("unavailable", "negotiation authority is not configured");
@@ -310,6 +425,19 @@ export function createMerchantManagementApiHandler(options) {
310
425
  });
311
426
  return;
312
427
  }
428
+ if (rest === "/reports") {
429
+ const auth = requireActor(req);
430
+ authorizeOrThrow(auth.ctx, "operations:read");
431
+ const builder = options.operationsReports;
432
+ if (builder === undefined) {
433
+ throw new ManagementError("unavailable", "operations report authority is not configured");
434
+ }
435
+ const periodRaw = url.searchParams.get("period");
436
+ writeJson(res, 200, builder.build(parseReportPeriod(periodRaw)), {
437
+ "x-request-id": requestId,
438
+ });
439
+ return;
440
+ }
313
441
  if (rest === "/broadcasts") {
314
442
  const auth = requireActor(req);
315
443
  authorizeOrThrow(auth.ctx, "approvals:read");
@@ -445,7 +573,88 @@ export function createMerchantManagementApiHandler(options) {
445
573
  }
446
574
  writeWorkbenchProblem(res, "RESOURCE_NOT_FOUND", requestId, "资源不存在", "Workbench API 路由不存在或尚未实现。");
447
575
  }
448
- async function routeWorkbenchV1Post(req, res, rest, requestId) {
576
+ async function routeWorkbenchV1Post(req, res, rest, requestId, url) {
577
+ const publicationCommitMatch = /^\/products\/publication-drafts\/(flp_[a-z0-9]+_[0-9a-f]{12})\/commit$/.exec(rest);
578
+ if (rest === "/products/publication-drafts" || publicationCommitMatch !== null) {
579
+ const auth = requireActor(req);
580
+ assertWriteGuards(req, auth.sessionId);
581
+ authorizeOrThrow(auth.ctx, "products:import");
582
+ if (auth.ctx.role !== "owner")
583
+ throw new ManagementError("forbidden", "only owner can publish products");
584
+ const channel = options.fileListingPublication;
585
+ if (channel === undefined)
586
+ throw new ManagementError("unavailable", "product publication is unavailable");
587
+ try {
588
+ if (publicationCommitMatch !== null) {
589
+ const fields = objectFields(await readJsonBody(req), ["expected_digest", "confirm_publication"]);
590
+ if (fields["confirm_publication"] !== true)
591
+ throw new ManagementError("invalid_input", "explicit publication confirmation is required");
592
+ const result = await channel.commit(publicationCommitMatch[1], requireString(fields["expected_digest"], "expected_digest"));
593
+ writeJson(res, result.status === "pending" ? 202 : 200, result, { "x-request-id": requestId });
594
+ }
595
+ else {
596
+ const fields = objectFields(await readJsonBody(req), ["selections"]);
597
+ const selections = fields["selections"];
598
+ if (!Array.isArray(selections) || selections.length === 0 || selections.length > 100) {
599
+ throw new ManagementError("invalid_input", "select between 1 and 100 products");
600
+ }
601
+ const selected = selections.map((item) => {
602
+ const entry = objectFields(item, ["sku", "category"]);
603
+ return { sku: requireString(entry["sku"], "sku"), category: requireString(entry["category"], "category") };
604
+ });
605
+ writeJson(res, 200, await channel.preview(selected), { "x-request-id": requestId });
606
+ }
607
+ }
608
+ catch (err) {
609
+ if (err instanceof FileListingPublicationError) {
610
+ // Never reflect remote errors or credential-bearing URLs to the page.
611
+ throw new ManagementError("precondition_changed", "商品发布条件已变化或目录暂不可用,请检查连接状态并重新预览。");
612
+ }
613
+ if (err instanceof ManagementError)
614
+ throw err;
615
+ throw new ManagementError("unavailable", "商品发布结果暂无法确认,请查看原草稿回执后决定是否续办。");
616
+ }
617
+ return;
618
+ }
619
+ if (rest === "/catalog/connect/begin") {
620
+ const auth = requireActor(req);
621
+ assertWriteGuards(req, auth.sessionId);
622
+ authorizeOrThrow(auth.ctx, "onboarding:manage");
623
+ if (auth.ctx.role !== "owner")
624
+ throw new ManagementError("forbidden", "only owner can begin Catalog connection");
625
+ const channel = options.catalogConnection;
626
+ if (channel === undefined)
627
+ throw new ManagementError("unavailable", "Catalog connection is not configured");
628
+ const fields = objectFields(await readJsonBody(req), ["idempotency_key"]);
629
+ const begun = operations.begin({
630
+ merchantId: auth.ctx.merchantId, actorId: auth.ctx.actorId,
631
+ commandType: "catalog.connection.begin",
632
+ idempotencyKey: requireString(fields["idempotency_key"], "idempotency_key"),
633
+ requestDigest: managementRequestDigest({ generation: options.generation() }),
634
+ });
635
+ if (begun.kind === "conflict")
636
+ throw new ManagementError("conflict", "idempotency key was reused with another request");
637
+ if (begun.kind === "replay") {
638
+ writeJson(res, 200, begun.receipt, { "x-request-id": requestId });
639
+ return;
640
+ }
641
+ let status = "succeeded";
642
+ try {
643
+ await channel.begin();
644
+ }
645
+ catch {
646
+ // 远端创建可能已发生:保留幂等回执,先查连接状态,不盲目重复创建。
647
+ status = "unknown";
648
+ console.warn("[merchant-management] catalog.connection.begin result unknown; query connection status before retry");
649
+ }
650
+ const receipt = {
651
+ ...staticReceipt(begun.operationId, "catalog.connection.begin", status),
652
+ resource_ref: "catalog:connection", completed_at: now().toISOString(),
653
+ };
654
+ operations.complete(begun.operationId, status, receipt);
655
+ writeJson(res, status === "unknown" ? 202 : 200, receipt, { "x-request-id": requestId });
656
+ return;
657
+ }
449
658
  if (rest === "/runtime/safety-stops") {
450
659
  const auth = requireActor(req);
451
660
  assertWriteGuards(req, auth.sessionId);
@@ -718,10 +927,18 @@ export function createMerchantManagementApiHandler(options) {
718
927
  await postProductsImportCommit(req, res, pathSegment(importCommitMatch[1] ?? ""));
719
928
  return;
720
929
  }
930
+ if (rest === "/products/import-parse") {
931
+ await postProductsImportParse(req, res, url);
932
+ return;
933
+ }
721
934
  if (rest === "/policy/drafts") {
722
935
  await postPolicyDraft(req, res);
723
936
  return;
724
937
  }
938
+ if (rest === "/policy/form-drafts") {
939
+ await postPolicyFormDraft(req, res);
940
+ return;
941
+ }
725
942
  const policyCommitMatch = /^\/policy\/drafts\/([^/]+)\/commit$/.exec(rest);
726
943
  if (policyCommitMatch !== null) {
727
944
  await postPolicyCommit(req, res, pathSegment(policyCommitMatch[1] ?? ""));
@@ -1362,7 +1579,34 @@ export function createMerchantManagementApiHandler(options) {
1362
1579
  authorizeOrThrow(auth.ctx, "onboarding:manage");
1363
1580
  const channel = onboardingChannel();
1364
1581
  const record = channel.store.activeRecord(auth.ctx.merchantId) ?? null;
1365
- writeJson(res, 200, { record, plan: record === null ? null : planWizard(record) });
1582
+ const readiness = await options.readiness();
1583
+ const setupNotices = [
1584
+ ...(readiness.checks.products?.code === "PRODUCTS_NOT_CONFIGURED"
1585
+ ? [{ code: "products_required", message: "请先导入商品;导入后系统会自动继续服务检查,当前不会报价或发布名片。" }]
1586
+ : []),
1587
+ ...(options.merchantNameNeedsUpdate === true
1588
+ ? [{ code: "merchant_name_required", message: "请设置商家显示名后再确认公开资料。" }]
1589
+ : []),
1590
+ ];
1591
+ const enrollment = record === null || channel.enrollmentStateDir === undefined
1592
+ ? undefined
1593
+ : readEnrollmentStore(channel.enrollmentStateDir).sessions
1594
+ .map((session) => session)
1595
+ .find((session) => session.owner_ref === record.recordId);
1596
+ writeJson(res, 200, {
1597
+ record,
1598
+ plan: record === null ? null : planWizard(record),
1599
+ setup_notices: setupNotices,
1600
+ ...(enrollment !== undefined ? {
1601
+ connect: {
1602
+ enrollment_id: enrollment.enrollment_id,
1603
+ status: enrollment.status,
1604
+ user_code: enrollment.user_code,
1605
+ verification_uri: enrollment.verification_uri,
1606
+ expires_at: enrollment.expires_at,
1607
+ },
1608
+ } : {}),
1609
+ });
1366
1610
  return;
1367
1611
  }
1368
1612
  if (rest === "/policy") {
@@ -1481,6 +1725,10 @@ export function createMerchantManagementApiHandler(options) {
1481
1725
  async function postOnboardingIntent(req, res) {
1482
1726
  const auth = requireActor(req);
1483
1727
  assertWriteGuards(req, auth.sessionId);
1728
+ authorizeOrThrow(auth.ctx, "onboarding:manage");
1729
+ if (options.catalogConnection !== undefined) {
1730
+ throw new ManagementError("conflict", "本实例已启用目录直连,请在连接 Kiwi 目录入口继续,不能同时启动旧部署向导。");
1731
+ }
1484
1732
  const body = await readJsonBody(req);
1485
1733
  const fields = objectFields(body, [
1486
1734
  "intent_id",
@@ -2058,6 +2306,7 @@ export function createMerchantManagementApiHandler(options) {
2058
2306
  let table;
2059
2307
  try {
2060
2308
  table = parseProductTable(fields["table"], "request body");
2309
+ table = await importChannel.prepareTable?.(table) ?? table;
2061
2310
  }
2062
2311
  catch (err) {
2063
2312
  if (err instanceof ProductTableError) {
@@ -2065,8 +2314,8 @@ export function createMerchantManagementApiHandler(options) {
2065
2314
  }
2066
2315
  throw err;
2067
2316
  }
2068
- if (table.merchant_id !== options.merchantId) {
2069
- throw new ManagementError("forbidden", "product table merchant_id does not match this instance");
2317
+ if ((table.runtime_owner_id ?? table.merchant_id) !== options.merchantId) {
2318
+ throw new ManagementError("forbidden", "product table runtime owner does not match this instance");
2070
2319
  }
2071
2320
  let base;
2072
2321
  try {
@@ -2118,6 +2367,43 @@ export function createMerchantManagementApiHandler(options) {
2118
2367
  },
2119
2368
  });
2120
2369
  }
2370
+ /**
2371
+ * POST /products/import-parse?format=csv|xlsx —— 把商家上传的 CSV/xlsx 原文
2372
+ * (WP12)转换为商品表草稿:表头映射报告 + 逐行问题清单。无状态(不落盘),
2373
+ * 商家确认后仍走 import-drafts 严格校验与整表替换预览;服务端解析保证工作
2374
+ * 台、脚本与技能共用同一实现(`product-import-tabular.ts`)。
2375
+ */
2376
+ async function postProductsImportParse(req, res, url) {
2377
+ const auth = requireActor(req);
2378
+ assertWriteGuards(req, auth.sessionId);
2379
+ authorizeOrThrow(auth.ctx, "products:import");
2380
+ const format = url.searchParams.get("format");
2381
+ if (format !== "csv" && format !== "xlsx") {
2382
+ throw new ManagementError("invalid_input", "format must be csv or xlsx");
2383
+ }
2384
+ const chunks = [];
2385
+ let size = 0;
2386
+ for await (const chunk of req) {
2387
+ size += chunk.length;
2388
+ if (size > TABULAR_IMPORT_MAX_BYTES) {
2389
+ throw new ManagementError("invalid_input", `文件超过上限 ${TABULAR_IMPORT_MAX_BYTES} 字节,请分批导入或精简表格`);
2390
+ }
2391
+ chunks.push(chunk);
2392
+ }
2393
+ if (chunks.length === 0) {
2394
+ throw new ManagementError("invalid_input", "request body required");
2395
+ }
2396
+ const buffer = Buffer.concat(chunks);
2397
+ const result = convertTabularImport(format === "csv"
2398
+ ? { kind: "csv", text: buffer.toString("utf8") }
2399
+ : { kind: "xlsx", bytes: new Uint8Array(buffer) }, { merchantId: options.merchantId, now: () => now() });
2400
+ writeJson(res, 200, {
2401
+ ok: result.ok,
2402
+ ...(result.table !== undefined ? { table: result.table } : {}),
2403
+ report: result.report,
2404
+ errors: result.errors,
2405
+ });
2406
+ }
2121
2407
  /** POST /products/import-drafts/{id}/commit —— 原子落盘;结果不可分辨时记 unknown。 */
2122
2408
  async function postProductsImportCommit(req, res, draftId) {
2123
2409
  const auth = requireActor(req);
@@ -2254,6 +2540,75 @@ export function createMerchantManagementApiHandler(options) {
2254
2540
  base_digest: current?.digest ?? null,
2255
2541
  });
2256
2542
  }
2543
+ /**
2544
+ * POST /policy/form-drafts —— 常用规则表单(WP11):表单友好字段 → 服务端映射
2545
+ * 为 policy schema 字段,走与 JSON patch 完全相同的草稿→确认提交流程。
2546
+ * schema 字段名只出现在服务端(页面壳不含策略内部字段名,隐私守卫不变)。
2547
+ */
2548
+ async function postPolicyFormDraft(req, res) {
2549
+ const auth = requireActor(req);
2550
+ assertWriteGuards(req, auth.sessionId);
2551
+ authorizeOrThrow(auth.ctx, "policy:draft");
2552
+ const fields = objectFields(await readJsonBody(req), [
2553
+ "auto",
2554
+ "floor",
2555
+ "discount",
2556
+ "lead_days",
2557
+ "ttl_seconds",
2558
+ "human_review",
2559
+ ]);
2560
+ const patch = {};
2561
+ if (fields["auto"] !== undefined) {
2562
+ if (fields["auto"] !== "on" && fields["auto"] !== "off") {
2563
+ throw new ManagementError("invalid_input", "auto must be on or off");
2564
+ }
2565
+ patch["auto_negotiate"] = fields["auto"] === "on";
2566
+ }
2567
+ if (fields["floor"] !== undefined) {
2568
+ patch["min_unit_price_private"] = requireNonNegativeNumber(fields["floor"], "floor");
2569
+ }
2570
+ if (fields["discount"] !== undefined) {
2571
+ const discount = requireNonNegativeNumber(fields["discount"], "discount");
2572
+ if (discount > 100) {
2573
+ throw new ManagementError("invalid_input", "discount must be between 0 and 100");
2574
+ }
2575
+ patch["max_auto_discount_percent"] = discount;
2576
+ }
2577
+ if (fields["lead_days"] !== undefined) {
2578
+ patch["delivery_lead_days"] = requirePositiveNumber(fields["lead_days"], "lead_days");
2579
+ }
2580
+ if (fields["ttl_seconds"] !== undefined) {
2581
+ patch["quote_ttl_seconds"] = requirePositiveInteger(fields["ttl_seconds"], "ttl_seconds");
2582
+ }
2583
+ if (fields["human_review"] !== undefined) {
2584
+ const triggers = requireStringArray(fields["human_review"], "human_review");
2585
+ for (const trigger of triggers) {
2586
+ if (!HUMAN_REVIEW_TRIGGERS.includes(trigger)) {
2587
+ throw new ManagementError("invalid_input", `human_review trigger must be one of ${HUMAN_REVIEW_TRIGGERS.join(", ")}`);
2588
+ }
2589
+ }
2590
+ patch["human_review_on"] = triggers;
2591
+ }
2592
+ if (Object.keys(patch).length === 0) {
2593
+ throw new ManagementError("invalid_input", "form submitted no changes");
2594
+ }
2595
+ const current = options.policy?.();
2596
+ const digest = managementRequestDigest(patch);
2597
+ const created = options.drafts.create({
2598
+ merchantId: auth.ctx.merchantId,
2599
+ kind: "policy_override",
2600
+ payloadJson: JSON.stringify(patch),
2601
+ payloadDigest: digest,
2602
+ ...(current !== undefined ? { baseDigest: current.digest } : {}),
2603
+ });
2604
+ writeJson(res, 200, {
2605
+ draft_id: created.draftId,
2606
+ digest,
2607
+ reused: created.reused,
2608
+ base_digest: current?.digest ?? null,
2609
+ applied_keys: Object.keys(patch),
2610
+ });
2611
+ }
2257
2612
  /** POST /policy/drafts/{id}/commit —— 应用策略补丁;回执只含版本与摘要(红线 6)。 */
2258
2613
  async function postPolicyCommit(req, res, draftId) {
2259
2614
  const auth = requireActor(req);
@@ -2447,6 +2802,8 @@ function isKnownPath(rest) {
2447
2802
  rest === "/service/pause" ||
2448
2803
  rest === "/service/resume" ||
2449
2804
  rest === "/products/import-drafts" ||
2805
+ rest === "/products/import-parse" ||
2806
+ rest === "/products/import-template" ||
2450
2807
  rest === "/policy/drafts" ||
2451
2808
  rest === "/onboarding") {
2452
2809
  return true;
@@ -2535,6 +2892,21 @@ function requirePositiveInteger(value, field) {
2535
2892
  throw new ManagementError("invalid_input", `${field} must be positive`);
2536
2893
  return integer;
2537
2894
  }
2895
+ /** 表单数值允许小数(元/百分比),但必须有限且非负(或正数,见下)。 */
2896
+ function requireNonNegativeNumber(value, field) {
2897
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
2898
+ throw new ManagementError("invalid_input", `${field} must be a non-negative number`);
2899
+ }
2900
+ return value;
2901
+ }
2902
+ function requirePositiveNumber(value, field) {
2903
+ const number = requireNonNegativeNumber(value, field);
2904
+ if (number === 0)
2905
+ throw new ManagementError("invalid_input", `${field} must be positive`);
2906
+ return number;
2907
+ }
2908
+ /** human_review_on 已知触发词(product-init/supervisor 初始化口径)。 */
2909
+ const HUMAN_REVIEW_TRIGGERS = ["below_floor", "exceptional_warranty", "suspicious_content"];
2538
2910
  function requireDecision(value) {
2539
2911
  if (value !== "approve" && value !== "reject") {
2540
2912
  throw new ManagementError("invalid_input", "decision must be approve or reject");