@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
@@ -0,0 +1,962 @@
1
+ /**
2
+ * Copyright 2026 harrylabsj
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /**
17
+ * Runtime 侧 Catalog 控制面客户端(设计 §4.6;写路径)。
18
+ *
19
+ * `src/cloud/` 此前只有绑定的**声明与证明材料**(binding/proofs.ts 等),没有任何
20
+ * 对 Catalog 的 HTTP 调用;本模块补上商家侧发布闭环的四个方法:
21
+ *
22
+ * - `requestBinding()` POST /v1/agents/{cagt}/runtime-bindings
23
+ * - `awaitBindingConfirmation()` GET /v1/agents/{cagt}/runtime-binding(匿名轮询)
24
+ * - `publishCard()` POST /v1/agents/{cagt}/card-publications
25
+ * - `activateCard()` POST /v1/agents/{cagt}/publish(CAS)
26
+ *
27
+ * 纪律(§4.6 实现约束与失败语义,逐条落实):
28
+ *
29
+ * 1. **身份 = 绑定签名**:Runtime 不持有 owner token;所有写请求以
30
+ * `x-kiwi-binding-jws`(EdDSA compact JWS)背书,签名覆盖该端点的全部安全相关
31
+ * 字段 + `issued_at`(服务端 300s 时钟偏差窗,kiwi-catalog
32
+ * `request_signature.py` 强制,缺了即 400)+ 每次请求**新生成的唯一 nonce**
33
+ * (重放由服务端 `control_plane_nonces` 判 409/400,客户端绝不复用 nonce)。
34
+ * 2. **runtime_origin 只来自平台配置**:由调用方从 `KIWI_CLOUD_PUBLIC_ORIGIN`
35
+ * (loadCloudConfig().publicOrigin)传入;本模块不从别处推导、不猜默认值。
36
+ * 3. **确认前不发布**:`awaitBindingConfirmation()` 走**匿名公开读**(绝不带任何
37
+ * 凭据),逐次比对 `binding_id` / `runtime_origin` / `key_thumbprint`,三者
38
+ * 不全符就继续等——服务端同样会拒(签名校验要求活动绑定),客户端先挡住。
39
+ * 注意 catalog 现状:确认后、首张名片激活前,公开读返回 **403**
40
+ * ("agent is not publishable",SIG-02 不签发),本模块把它与 404 区分成
41
+ * `BINDING_UNREADABLE`——此时绑定已存在但文档不可读,binding_id 拿不到,
42
+ * 首发布需要 catalog 提供确认后的 binding_id 通道(见仓库汇报记录)。
43
+ * 4. **失败语义**:目录不可达(网络/超时/5xx/429)→ `CATALOG_UNREACHABLE`,
44
+ * 调用方标 `pending_publication` 按退避重试,**不谎报已发布**;CAS 冲突(409)
45
+ * → 重新匿名读公开绑定取最新 revision 后**重试一次**,仍冲突抛 `CONFLICT`
46
+ * 停下来报人工;重复提交同一 card_digest 前先读当前 expected_revision
47
+ * (`fetchPublicBinding()` 信封顶层的 `card_revision`——契约
48
+ * `runtime-binding/0.1.2/document.schema.json` 的公开元数据,不是 claims 字段)。
49
+ * 5. **fail-closed**:本地产物发出前用 `contracts/{runtime-binding,card-publication}/
50
+ * 0.1.2/*.schema.json` 做结构自检;名片接口全部在自身 origin 内、至少一项等于
51
+ * 绑定的 a2a_endpoint——**发出前**自查,不把坏卡交给服务端。
52
+ *
53
+ * 零新运行时依赖(裸 fetch);出站加固与 `discovery/catalog-source/cloud-card.ts`
54
+ * 同口径(redirect: manual、超时覆盖 body 读取、响应体上限)。
55
+ */
56
+ import { createHash, createPublicKey, randomBytes } from "node:crypto";
57
+ import { validateCloudContract } from "../contracts/cloud-contracts.js";
58
+ import { validateAgentCard } from "../discovery/agent-card/validate.js";
59
+ import { isRedirectResponse, readJsonBody, SafeHttpError } from "../net/safe-http.js";
60
+ import { canonicalize } from "../negotiation/jcs.js";
61
+ import { PRODUCT_VERSION } from "../product-cli.js";
62
+ import { validateBindingClaims } from "../trust/binding/claims.js";
63
+ import { jwkThumbprint } from "../trust/binding/thumbprint.js";
64
+ import { signCompactJws } from "../trust/identity/jws.js";
65
+ import { verifyCompactJws } from "../trust/identity/jws.js";
66
+ const DEFAULT_TIMEOUT_MS = 15_000;
67
+ const DEFAULT_CONFIRM_TIMEOUT_MS = 15 * 60 * 1000;
68
+ const DEFAULT_CONFIRM_POLL_MS = 5_000;
69
+ export class CatalogClientError extends Error {
70
+ code;
71
+ status;
72
+ remoteCode;
73
+ constructor(code, message, status, remoteCode) {
74
+ super(message);
75
+ this.name = "CatalogClientError";
76
+ this.code = code;
77
+ if (status !== undefined)
78
+ this.status = status;
79
+ if (remoteCode !== undefined)
80
+ this.remoteCode = remoteCode;
81
+ }
82
+ }
83
+ function isRecord(value) {
84
+ return value !== null && typeof value === "object" && !Array.isArray(value);
85
+ }
86
+ function recordOrEmpty(value) {
87
+ if (!isRecord(value))
88
+ throw new CatalogClientError("RESPONSE_INVALID", "catalog 响应必须是 JSON 对象");
89
+ return value;
90
+ }
91
+ function requiredString(value, field) {
92
+ if (typeof value !== "string" || value.trim() === "") {
93
+ throw new CatalogClientError("RESPONSE_INVALID", `catalog 响应缺少 ${field}`);
94
+ }
95
+ return value;
96
+ }
97
+ function positiveInteger(value, fallback) {
98
+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : fallback;
99
+ }
100
+ function sha256Json(value) {
101
+ return `sha256:${createHash("sha256").update(canonicalize(value), "utf8").digest("hex")}`;
102
+ }
103
+ function requireCatalogVerificationUri(baseUrl, raw) {
104
+ let parsed;
105
+ try {
106
+ parsed = new URL(raw, baseUrl);
107
+ }
108
+ catch {
109
+ throw new CatalogClientError("RESPONSE_INVALID", "verification_uri 不是合法 URL");
110
+ }
111
+ const base = new URL(baseUrl);
112
+ if (parsed.origin !== base.origin || parsed.protocol !== base.protocol || parsed.username !== "" || parsed.password !== "") {
113
+ throw new CatalogClientError("RESPONSE_INVALID", "verification_uri 必须属于配置的 Catalog origin");
114
+ }
115
+ return parsed.toString();
116
+ }
117
+ function defaultNonce() {
118
+ return randomBytes(24).toString("base64url");
119
+ }
120
+ function requireHttpsUrl(value, field) {
121
+ const trimmed = String(value ?? "").trim();
122
+ if (!trimmed.startsWith("https://")) {
123
+ throw new CatalogClientError("INVALID_INPUT", `${field} 必须是 https URL:${trimmed}`);
124
+ }
125
+ try {
126
+ new URL(trimmed);
127
+ }
128
+ catch {
129
+ throw new CatalogClientError("INVALID_INPUT", `${field} 不是合法 URL:${trimmed}`);
130
+ }
131
+ return trimmed;
132
+ }
133
+ function originOf(url) {
134
+ return new URL(url).origin;
135
+ }
136
+ /** 规范化 origin(去掉末尾斜杠,逐字比对前的统一口径)。 */
137
+ export function normalizeOrigin(value) {
138
+ return value.replace(/\/+$/, "");
139
+ }
140
+ export class CatalogClient {
141
+ baseUrl;
142
+ fetchImpl;
143
+ timeoutMs;
144
+ nonceFactory;
145
+ now;
146
+ constructor(options) {
147
+ const trimmed = String(options.baseUrl ?? "").trim().replace(/\/+$/, "");
148
+ if (!trimmed.startsWith("https://") && !trimmed.startsWith("http://127.0.0.1") && !trimmed.startsWith("http://localhost")) {
149
+ throw new CatalogClientError("INVALID_INPUT", `catalog baseUrl 必须是 https(本地联调仅放行 loopback):${trimmed}`);
150
+ }
151
+ this.baseUrl = trimmed;
152
+ this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
153
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
154
+ this.nonceFactory = options.nonceFactory ?? defaultNonce;
155
+ this.now = options.now ?? (() => new Date());
156
+ }
157
+ /** Catalog origin is pinned by constructor configuration and remains the only control-plane trust anchor. */
158
+ get catalogOrigin() {
159
+ return new URL(this.baseUrl).origin;
160
+ }
161
+ /** 创建独立 Runtime 设备授权会话;仅绑定本机持久密钥和锁定的公开预览。 */
162
+ async createDeviceEnrollment(input, identity) {
163
+ const origin = normalizeOrigin(requireHttpsUrl(input.runtimeOrigin, "runtime_origin"));
164
+ const endpoint = requireHttpsUrl(input.a2aEndpoint, "a2a_endpoint");
165
+ if (originOf(origin) !== originOf(endpoint)) {
166
+ throw new CatalogClientError("INVALID_INPUT", "a2a_endpoint 必须与 runtime_origin 同源");
167
+ }
168
+ const { keyJwk, keyThumbprint } = runtimePublicKey(identity);
169
+ const body = {
170
+ binding: {
171
+ runtime_origin: origin,
172
+ a2a_endpoint: endpoint,
173
+ key_jwk: { kty: keyJwk.kty, crv: keyJwk.crv, x: keyJwk.x },
174
+ key_id: identity.keyId,
175
+ generation: input.generation,
176
+ service_epoch: input.serviceEpoch,
177
+ },
178
+ public_preview: input.publicPreview,
179
+ public_profile_revision: input.publicProfileRevision,
180
+ };
181
+ const nonce = this.nonceFactory();
182
+ const issuedAt = this.now();
183
+ const signed = {
184
+ method: "POST",
185
+ path: "/v1/enrollments/device",
186
+ audience: "kiwi-catalog",
187
+ body_digest: sha256Json(body),
188
+ key_id: identity.keyId,
189
+ key_thumbprint: keyThumbprint,
190
+ generation: input.generation,
191
+ service_epoch: input.serviceEpoch,
192
+ issued_at: issuedAt.toISOString(),
193
+ exp: new Date(issuedAt.getTime() + 30_000).toISOString(),
194
+ nonce,
195
+ };
196
+ const { json } = await this.request("POST", "/v1/enrollments/device", {
197
+ body,
198
+ jws: signCompactJws(signed, identity.signingIdentity, { extraHeader: { typ: "kiwi-runtime-request" } }),
199
+ });
200
+ const result = recordOrEmpty(json);
201
+ const session = {
202
+ enrollmentId: requiredString(result["enrollment_id"], "enrollment_id"),
203
+ deviceCode: requiredString(result["device_code"], "device_code"),
204
+ userCode: requiredString(result["user_code"], "user_code"),
205
+ verificationUri: requireCatalogVerificationUri(this.baseUrl, requiredString(result["verification_uri"], "verification_uri")),
206
+ expiresAt: requiredString(result["expires_at"], "expires_at"),
207
+ intervalSeconds: positiveInteger(result["interval"], 5),
208
+ keyThumbprint,
209
+ };
210
+ return session;
211
+ }
212
+ /** 以匹配设备私钥轮询;user_code 不是取回 grant 的凭据。 */
213
+ async pollDeviceEnrollment(deviceCode, identity) {
214
+ if (deviceCode.length < 32)
215
+ throw new CatalogClientError("INVALID_INPUT", "device_code 形状非法");
216
+ const { keyThumbprint } = runtimePublicKey(identity);
217
+ const nonce = this.nonceFactory();
218
+ const issuedAt = this.now();
219
+ const signed = {
220
+ method: "POST",
221
+ path: "/v1/enrollments/device/token",
222
+ audience: "kiwi-catalog",
223
+ device_code_hash: createHash("sha256").update(deviceCode).digest("hex"),
224
+ key_id: identity.keyId,
225
+ key_thumbprint: keyThumbprint,
226
+ issued_at: issuedAt.toISOString(),
227
+ exp: new Date(issuedAt.getTime() + 30_000).toISOString(),
228
+ nonce,
229
+ };
230
+ const { json } = await this.request("POST", "/v1/enrollments/device/token", {
231
+ body: { device_code: deviceCode },
232
+ jws: signCompactJws(signed, identity.signingIdentity, { extraHeader: { typ: "kiwi-runtime-request" } }),
233
+ });
234
+ const result = recordOrEmpty(json);
235
+ const state = result["status"] ?? result["error"];
236
+ if (state === "authorization_pending" || state === "pending") {
237
+ return { status: "authorization_pending", intervalSeconds: positiveInteger(result["interval"], 5) };
238
+ }
239
+ if (state === "slow_down") {
240
+ return { status: "slow_down", intervalSeconds: positiveInteger(result["interval"], 10) };
241
+ }
242
+ if (state !== "authorized" && typeof result["grant"] !== "string") {
243
+ throw new CatalogClientError("RESPONSE_INVALID", "设备轮询响应既非等待状态也非授权结果");
244
+ }
245
+ return {
246
+ status: "authorized",
247
+ enrollmentId: requiredString(result["enrollment_id"], "enrollment_id"),
248
+ grant: requiredString(result["grant"], "grant"),
249
+ catalogAgentId: requiredString(result["catalog_agent_id"], "catalog_agent_id"),
250
+ merchantId: requiredString(result["merchant_id"], "merchant_id"),
251
+ runtimeOrigin: normalizeOrigin(requireHttpsUrl(requiredString(result["runtime_origin"], "runtime_origin"), "runtime_origin")),
252
+ a2aEndpoint: requireHttpsUrl(requiredString(result["a2a_endpoint"], "a2a_endpoint"), "a2a_endpoint"),
253
+ expiresAt: requiredString(result["expires_at"], "expires_at"),
254
+ authorizationEpoch: positiveInteger(result["authorization_epoch"], 0),
255
+ approvedCardDigest: requiredString(result["approved_card_digest"], "approved_card_digest"),
256
+ scopes: Array.isArray(result["scopes"]) ? result["scopes"].filter((v) => typeof v === "string") : [],
257
+ };
258
+ }
259
+ /** 一次性许可换取活动绑定;Catalog 的挑战和签发结果是绑定权威。 */
260
+ async bindEnrollment(input, identity) {
261
+ const origin = normalizeOrigin(requireHttpsUrl(input.runtimeOrigin, "runtime_origin"));
262
+ const endpoint = requireHttpsUrl(input.a2aEndpoint, "a2a_endpoint");
263
+ const { keyJwk, keyThumbprint } = runtimePublicKey(identity);
264
+ const body = {
265
+ enrollment_id: input.enrollmentId,
266
+ grant: input.grant,
267
+ binding: {
268
+ runtime_origin: origin,
269
+ a2a_endpoint: endpoint,
270
+ key_jwk: { kty: keyJwk.kty, crv: keyJwk.crv, x: keyJwk.x },
271
+ key_id: identity.keyId,
272
+ generation: input.generation,
273
+ service_epoch: input.serviceEpoch,
274
+ },
275
+ };
276
+ const nonce = this.nonceFactory();
277
+ const issuedAt = this.now();
278
+ const signed = {
279
+ method: "POST",
280
+ path: `/v1/agents/${encodeURIComponent(input.catalogAgentId)}/runtime-bindings`,
281
+ audience: "kiwi-catalog",
282
+ body_digest: sha256Json(body),
283
+ enrollment_id: input.enrollmentId,
284
+ grant_hash: createHash("sha256").update(input.grant).digest("hex"),
285
+ catalog_agent_id: input.catalogAgentId,
286
+ key_id: identity.keyId,
287
+ key_thumbprint: keyThumbprint,
288
+ runtime_origin: origin,
289
+ a2a_endpoint: endpoint,
290
+ generation: input.generation,
291
+ service_epoch: input.serviceEpoch,
292
+ authorization_epoch: input.authorizationEpoch,
293
+ issued_at: issuedAt.toISOString(),
294
+ exp: new Date(issuedAt.getTime() + 30_000).toISOString(),
295
+ nonce,
296
+ };
297
+ const { json } = await this.request("POST", `/v1/agents/${encodeURIComponent(input.catalogAgentId)}/runtime-bindings`, {
298
+ body,
299
+ jws: signCompactJws(signed, identity.signingIdentity, { extraHeader: { typ: "kiwi-runtime-request" } }),
300
+ });
301
+ const result = recordOrEmpty(json);
302
+ const claim = result["binding_claim"];
303
+ if (claim === null || typeof claim !== "object" || Array.isArray(claim)) {
304
+ throw new CatalogClientError("RESPONSE_INVALID", "绑定回执缺少 Catalog 签发的 binding_claim");
305
+ }
306
+ const checkedClaim = await this.verifyCatalogBindingClaim(claim, {
307
+ bindingId: requiredString(result["binding_id"], "binding_id"),
308
+ bindingVersion: positiveInteger(result["binding_version"], 0),
309
+ keyThumbprint,
310
+ runtimeOrigin: origin,
311
+ a2aEndpoint: endpoint,
312
+ catalogAgentId: input.catalogAgentId,
313
+ merchantId: input.merchantId,
314
+ keyId: identity.keyId,
315
+ serviceEpoch: input.serviceEpoch,
316
+ });
317
+ return {
318
+ bindingId: checkedClaim.binding_id,
319
+ bindingVersion: checkedClaim.binding_version,
320
+ keyThumbprint: requiredString(result["key_thumbprint"], "key_thumbprint"),
321
+ activeCardRevision: typeof claim["card_revision"] === "number"
322
+ && Number.isInteger(claim["card_revision"])
323
+ ? claim["card_revision"]
324
+ : null,
325
+ bindingClaim: claim,
326
+ };
327
+ }
328
+ /** Catalog origin 固定来自部署配置;JWKS仅经其标准HTTPS/TLS读取后用于验声明。 */
329
+ /** Publish one already-approved public listing with the active Runtime binding key. */
330
+ async publishSignedListing(input, identity) {
331
+ const agentId = this.requireAgentId(input.catalogAgentId);
332
+ if (input.listing["owner_agent_id"] !== agentId || input.listing["merchant_id"] !== input.merchantId) {
333
+ throw new CatalogClientError("INVALID_INPUT", "signed listing body identity does not match its route/claims");
334
+ }
335
+ if (typeof input.bindingId !== "string" || input.bindingId.trim() === "") {
336
+ throw new CatalogClientError("INVALID_INPUT", "binding_id must be non-empty");
337
+ }
338
+ if (!/^sha256:[a-f0-9]{64}$/.test(input.listingDigest)) {
339
+ throw new CatalogClientError("INVALID_INPUT", "listing_digest must be sha256:<64 lowercase hex>");
340
+ }
341
+ if (input.idempotencyKey.trim() === "" || input.idempotencyKey.length > 160) {
342
+ throw new CatalogClientError("INVALID_INPUT", "Idempotency-Key must contain 1 to 160 characters");
343
+ }
344
+ const issuedAt = this.now();
345
+ const jws = signCompactJws({
346
+ method: "POST",
347
+ path: "/v1/listings/publish",
348
+ audience: "kiwi-catalog",
349
+ agent_id: agentId,
350
+ merchant_id: input.merchantId,
351
+ binding_id: input.bindingId,
352
+ key_id: identity.keyId,
353
+ listing_digest: input.listingDigest,
354
+ idempotency_key: input.idempotencyKey,
355
+ issued_at: issuedAt.toISOString(),
356
+ exp: new Date(issuedAt.getTime() + 90_000).toISOString(),
357
+ nonce: this.nonceFactory(),
358
+ }, identity.signingIdentity, { extraHeader: { typ: "kiwi-runtime-request" } });
359
+ const { json } = await this.request("POST", "/v1/listings/publish", {
360
+ body: input.listing,
361
+ jws,
362
+ headers: { "Idempotency-Key": input.idempotencyKey },
363
+ });
364
+ const receipt = recordOrEmpty(json);
365
+ const listing = recordOrEmpty(receipt["listing"]);
366
+ if (receipt["ok"] !== true || typeof listing["listing_id"] !== "string" || listing["listing_id"] === "") {
367
+ throw new CatalogClientError("RESPONSE_INVALID", "Catalog signed listing publish response lacks a listing receipt");
368
+ }
369
+ return { listingId: listing["listing_id"], idempotent: receipt["idempotent"] === true };
370
+ }
371
+ /** Owner-token-free self-list, authenticated by the current binding JWS. */
372
+ async listSignedListings(context, identity, input) {
373
+ const agentId = this.requireAgentId(context.catalogAgentId);
374
+ const limit = Number.isInteger(input.limit) && input.limit > 0 ? Math.min(input.limit, 100) : 20;
375
+ const cursor = input.cursor?.trim() ?? "";
376
+ const freshnessState = input.freshnessState?.trim() ?? "";
377
+ const queryDigest = sha256Json({ limit, cursor, freshness_state: freshnessState });
378
+ const path = `/v1/agents/${encodeURIComponent(agentId)}/listings`;
379
+ const query = new URLSearchParams({ limit: String(limit) });
380
+ if (cursor !== "")
381
+ query.set("cursor", cursor);
382
+ if (freshnessState !== "")
383
+ query.set("freshness_state", freshnessState);
384
+ const issuedAt = this.now();
385
+ const jws = signCompactJws({
386
+ method: "GET",
387
+ path,
388
+ audience: "kiwi-catalog",
389
+ agent_id: agentId,
390
+ merchant_id: context.merchantId,
391
+ binding_id: context.bindingId,
392
+ key_id: context.keyId,
393
+ query_digest: queryDigest,
394
+ issued_at: issuedAt.toISOString(),
395
+ exp: new Date(issuedAt.getTime() + 90_000).toISOString(),
396
+ nonce: this.nonceFactory(),
397
+ }, identity.signingIdentity, { extraHeader: { typ: "kiwi-runtime-request" } });
398
+ const { json } = await this.request("GET", `${path}?${query.toString()}`, { jws });
399
+ const response = recordOrEmpty(json);
400
+ if (response["ok"] !== true || !Array.isArray(response["results"])) {
401
+ throw new CatalogClientError("RESPONSE_INVALID", "Catalog signed self-list response lacks results");
402
+ }
403
+ const results = response["results"].filter(isRecord);
404
+ if (results.some((item) => item["owner_agent_id"] !== agentId || item["merchant_id"] !== context.merchantId)) {
405
+ throw new CatalogClientError("RESPONSE_INVALID", "Catalog signed self-list returned a listing outside the current enrollment identity");
406
+ }
407
+ return {
408
+ results,
409
+ ...(typeof response["next_cursor"] === "string" && response["next_cursor"] !== "" ? { nextCursor: response["next_cursor"] } : {}),
410
+ };
411
+ }
412
+ /** Withdraw one disappeared product projection with the current binding. */
413
+ async withdrawSignedListing(context, identity, input) {
414
+ const listingId = String(input.listingId ?? "").trim();
415
+ if (listingId === "" || listingId.includes("/") || listingId.includes("..")) {
416
+ throw new CatalogClientError("INVALID_INPUT", "listing_id is invalid");
417
+ }
418
+ if (input.idempotencyKey.trim() === "" || input.idempotencyKey.length > 160) {
419
+ throw new CatalogClientError("INVALID_INPUT", "Idempotency-Key must contain 1 to 160 characters");
420
+ }
421
+ const path = `/v1/listings/${encodeURIComponent(listingId)}/withdraw`;
422
+ const body = {};
423
+ const issuedAt = this.now();
424
+ const jws = signCompactJws({
425
+ method: "POST",
426
+ path,
427
+ audience: "kiwi-catalog",
428
+ agent_id: context.catalogAgentId,
429
+ merchant_id: context.merchantId,
430
+ binding_id: context.bindingId,
431
+ key_id: context.keyId,
432
+ listing_id: listingId,
433
+ idempotency_key: input.idempotencyKey,
434
+ body_digest: sha256Json(body),
435
+ issued_at: issuedAt.toISOString(),
436
+ exp: new Date(issuedAt.getTime() + 90_000).toISOString(),
437
+ nonce: this.nonceFactory(),
438
+ }, identity.signingIdentity, { extraHeader: { typ: "kiwi-runtime-request" } });
439
+ const { json } = await this.request("POST", path, {
440
+ body,
441
+ jws,
442
+ headers: { "Idempotency-Key": input.idempotencyKey },
443
+ });
444
+ const response = recordOrEmpty(json);
445
+ if (response["ok"] !== true)
446
+ throw new CatalogClientError("RESPONSE_INVALID", "Catalog signed withdraw response is not ok");
447
+ }
448
+ async verifyCatalogBindingClaim(envelope, expected) {
449
+ const claimsJws = requiredString(envelope["claims_jws"], "binding_claim.claims_jws");
450
+ const issuerKid = requiredString(envelope["issuer_kid"], "binding_claim.issuer_kid");
451
+ const issuerThumbprint = requiredString(envelope["issuer_thumbprint"], "binding_claim.issuer_thumbprint");
452
+ const keysResponse = recordOrEmpty((await this.request("GET", "/v1/issuer-keys", {})).json);
453
+ if (!Array.isArray(keysResponse["keys"]))
454
+ throw new CatalogClientError("RESPONSE_INVALID", "Catalog issuer-keys 响应缺 keys 数组");
455
+ const key = keysResponse["keys"].find((candidate) => isRecord(candidate) && candidate["kid"] === issuerKid);
456
+ if (!isRecord(key) || (key["state"] !== "ACTIVE" && key["state"] !== "VERIFY_ONLY") || !isRecord(key["jwk"])) {
457
+ throw new CatalogClientError("RESPONSE_INVALID", `Catalog issuer-keys 未提供可信的活动发行密钥 ${issuerKid}`);
458
+ }
459
+ if (typeof key["thumbprint"] !== "string" || key["thumbprint"] !== issuerThumbprint || jwkThumbprint(key["jwk"]) !== key["thumbprint"]) {
460
+ throw new CatalogClientError("RESPONSE_INVALID", "Catalog issuer JWK thumbprint 不匹配");
461
+ }
462
+ let verified;
463
+ try {
464
+ verified = verifyCompactJws(claimsJws, key["jwk"]);
465
+ }
466
+ catch (err) {
467
+ throw new CatalogClientError("RESPONSE_INVALID", `Catalog binding 声明验签失败:${err instanceof Error ? err.message : String(err)}`);
468
+ }
469
+ if (verified.keyid !== issuerKid)
470
+ throw new CatalogClientError("RESPONSE_INVALID", "Catalog binding JWS protected kid 与 issuer-keys 不一致");
471
+ let parsed;
472
+ try {
473
+ parsed = JSON.parse(verified.payload.toString("utf8"));
474
+ }
475
+ catch {
476
+ throw new CatalogClientError("RESPONSE_INVALID", "Catalog binding claims 不是合法 JSON");
477
+ }
478
+ const validated = validateBindingClaims(parsed);
479
+ if (!validated.ok)
480
+ throw new CatalogClientError("RESPONSE_INVALID", `Catalog binding claims 非法:${validated.errors.join(";")}`);
481
+ const claims = validated.claims;
482
+ const currentTime = this.now().getTime();
483
+ const mismatches = [];
484
+ if (keysResponse["issuer"] !== claims.issuer)
485
+ mismatches.push("issuer");
486
+ if (claims.merchant_id !== expected.merchantId)
487
+ mismatches.push("merchant_id");
488
+ if (claims.binding_id !== expected.bindingId)
489
+ mismatches.push("binding_id");
490
+ if (claims.binding_version !== expected.bindingVersion)
491
+ mismatches.push("binding_version");
492
+ if (claims.key_thumbprint !== expected.keyThumbprint)
493
+ mismatches.push("key_thumbprint");
494
+ if (normalizeOrigin(claims.runtime_origin) !== expected.runtimeOrigin)
495
+ mismatches.push("runtime_origin");
496
+ if (claims.a2a_endpoint !== expected.a2aEndpoint)
497
+ mismatches.push("a2a_endpoint");
498
+ if (claims.agent_id !== expected.catalogAgentId)
499
+ mismatches.push("agent_id");
500
+ if (claims.key_id !== expected.keyId)
501
+ mismatches.push("key_id");
502
+ if (claims.service_epoch !== expected.serviceEpoch)
503
+ mismatches.push("service_epoch");
504
+ if (claims.status !== "active")
505
+ mismatches.push("status");
506
+ if (claims.card_url !== `${this.baseUrl}/v1/agents/${encodeURIComponent(expected.catalogAgentId)}/agent-card.json`)
507
+ mismatches.push("card_url");
508
+ if (!Number.isFinite(Date.parse(claims.issued_at)) || Date.parse(claims.issued_at) > currentTime + 60_000)
509
+ mismatches.push("issued_at");
510
+ if (!Number.isFinite(Date.parse(claims.expires_at)) || Date.parse(claims.expires_at) <= currentTime)
511
+ mismatches.push("expires_at");
512
+ if (mismatches.length > 0) {
513
+ throw new CatalogClientError("RESPONSE_INVALID", `Catalog 已签名绑定声明与本次 Runtime 请求不一致(${mismatches.join(", ")})`);
514
+ }
515
+ return claims;
516
+ }
517
+ // ── 公开读(匿名,绝不带任何凭据)────────────────────────────────────
518
+ /**
519
+ * 匿名读公开绑定文档。404(未确认/不存在)返回 null;其它失败抛类型化错误。
520
+ *
521
+ * 这是**公开读**:名片与绑定是"任何人都能核验"的公开事实,一旦需要凭据,
522
+ * 验证就退化成"相信持有凭据的那个人"(与 cloud-card.ts 同一纪律)。
523
+ *
524
+ * catalog 现状(kiwi-catalog `binding_claims.py::read_runtime_binding`):
525
+ * 绑定已确认但**没有活动名片**时(首绑确认后 → 首发布之间的窗口),公开读
526
+ * 返回 403 而不是文档——此时抛 `BINDING_UNREADABLE`,调用方据此区分
527
+ * "还没确认"(404 → null)与"已确认但文档暂不可读"(403)。
528
+ */
529
+ async fetchPublicBinding(agentId) {
530
+ const id = this.requireAgentId(agentId);
531
+ try {
532
+ const { status, json } = await this.request("GET", `/v1/agents/${encodeURIComponent(id)}/runtime-binding`, {});
533
+ if (status === 404)
534
+ return null;
535
+ return parsePublicBinding(json);
536
+ }
537
+ catch (err) {
538
+ if (err instanceof CatalogClientError && err.code === "REQUEST_REJECTED" && err.status === 403) {
539
+ throw new CatalogClientError("BINDING_UNREADABLE", `绑定文档暂不可读(403):Catalog 可能处于未发布、暂停、过期或撤回状态(agent=${id})`, 403);
540
+ }
541
+ throw err;
542
+ }
543
+ }
544
+ // ── S3:发起绑定请求(签名头覆盖七个字段 + 唯一 nonce)────────────────
545
+ async requestBinding(input, identity) {
546
+ const agentId = this.requireAgentId(input.agentId);
547
+ const runtimeOrigin = normalizeOrigin(requireHttpsUrl(input.runtimeOrigin, "runtime_origin"));
548
+ const a2aEndpoint = requireHttpsUrl(input.a2aEndpoint, "a2a_endpoint");
549
+ if (originOf(a2aEndpoint) !== originOf(runtimeOrigin)) {
550
+ throw new CatalogClientError("INVALID_INPUT", `a2a_endpoint(${a2aEndpoint})必须在 runtime_origin(${runtimeOrigin})域内`);
551
+ }
552
+ if (!Number.isInteger(input.generation) || input.generation < 0) {
553
+ throw new CatalogClientError("INVALID_INPUT", `generation 必须是非负整数:${input.generation}`);
554
+ }
555
+ if (!Number.isInteger(input.serviceEpoch) || input.serviceEpoch < 1) {
556
+ throw new CatalogClientError("INVALID_INPUT", `service_epoch 必须是正整数:${input.serviceEpoch}`);
557
+ }
558
+ const { keyJwk, keyThumbprint } = runtimePublicKey(identity);
559
+ const nonce = this.nonceFactory();
560
+ // 签名头覆盖设计钉死的七个字段 + issued_at(服务端 300s 时钟窗强制)+ 唯一 nonce。
561
+ const jws = signCompactJws({
562
+ agent_id: agentId,
563
+ key_id: identity.keyId,
564
+ key_thumbprint: keyThumbprint,
565
+ runtime_origin: runtimeOrigin,
566
+ a2a_endpoint: a2aEndpoint,
567
+ generation: input.generation,
568
+ service_epoch: input.serviceEpoch,
569
+ issued_at: this.now().toISOString(),
570
+ nonce,
571
+ }, identity.signingIdentity, { extraHeader: { typ: "kiwi-runtime-request" } });
572
+ const binding = {
573
+ runtime_origin: runtimeOrigin,
574
+ a2a_endpoint: a2aEndpoint,
575
+ key_jwk: { kty: keyJwk.kty, crv: keyJwk.crv, x: keyJwk.x },
576
+ key_id: identity.keyId,
577
+ generation: input.generation,
578
+ service_epoch: input.serviceEpoch,
579
+ };
580
+ if (input.expiresAt !== undefined)
581
+ binding["expires_at"] = input.expiresAt;
582
+ const body = { binding };
583
+ if (input.adminToken !== undefined && input.adminToken !== "") {
584
+ body["admin_token"] = input.adminToken;
585
+ }
586
+ assertContract("runtime-binding-request", body);
587
+ const { json } = await this.request("POST", `/v1/agents/${encodeURIComponent(agentId)}/runtime-bindings`, { body, jws });
588
+ const receipt = isRecord(json) ? json : {};
589
+ const requestId = receipt["binding_request_id"] ?? receipt["request_id"] ?? receipt["binding_id"];
590
+ return {
591
+ bindingRequestId: typeof requestId === "string" && requestId !== "" ? requestId : null,
592
+ keyThumbprint,
593
+ nonce,
594
+ };
595
+ }
596
+ // ── S3:等待商家在门户确认(匿名轮询;未确认绝不放行发布)─────────────
597
+ /**
598
+ * 轮询公开读地址,直到出现与本实例**逐字匹配**的绑定(runtime_origin +
599
+ * key_thumbprint,给了 binding_id 还要逐字匹配 binding_id)。
600
+ *
601
+ * 超时不是失败:商家可能还没看到门户上的待确认卡片。抛 `CONFIRMATION_TIMEOUT`,
602
+ * 由调用方提示商家到门户「我的名片」页确认后再继续(断点续办)。
603
+ */
604
+ async awaitBindingConfirmation(input) {
605
+ const agentId = this.requireAgentId(input.agentId);
606
+ const runtimeOrigin = normalizeOrigin(requireHttpsUrl(input.runtimeOrigin, "runtime_origin"));
607
+ const timeoutMs = input.timeoutMs ?? DEFAULT_CONFIRM_TIMEOUT_MS;
608
+ const pollMs = input.pollIntervalMs ?? DEFAULT_CONFIRM_POLL_MS;
609
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
610
+ throw new CatalogClientError("INVALID_INPUT", `timeoutMs 必须是正数:${timeoutMs}`);
611
+ }
612
+ if (!Number.isFinite(pollMs) || pollMs <= 0) {
613
+ throw new CatalogClientError("INVALID_INPUT", `pollIntervalMs 必须是正数:${pollMs}`);
614
+ }
615
+ const now = input.now ?? (() => new Date());
616
+ const sleep = input.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
617
+ const deadline = now().getTime() + timeoutMs;
618
+ let observed = null;
619
+ for (;;) {
620
+ let binding;
621
+ try {
622
+ binding = await this.fetchPublicBinding(agentId);
623
+ }
624
+ catch (err) {
625
+ // 403(BINDING_UNREADABLE):绑定可能已确认但首张名片未激活——继续等,
626
+ // 但记入观测信息(超时时如实带上)。其它错误(不可达/拒绝)原样抛出。
627
+ if (err instanceof CatalogClientError && err.code === "BINDING_UNREADABLE") {
628
+ observed = "公开读 403:绑定已存在但文档暂不可读(首绑确认后、首发布前的窗口)";
629
+ binding = null;
630
+ }
631
+ else {
632
+ throw err;
633
+ }
634
+ }
635
+ if (binding !== null) {
636
+ if (normalizeOrigin(binding.runtimeOrigin) === runtimeOrigin &&
637
+ binding.keyThumbprint === input.keyThumbprint &&
638
+ (input.bindingId === undefined || binding.bindingId === input.bindingId)) {
639
+ return binding;
640
+ }
641
+ observed = `binding_id=${binding.bindingId} origin=${binding.runtimeOrigin} thumbprint=${binding.keyThumbprint}`;
642
+ }
643
+ if (now().getTime() >= deadline) {
644
+ throw new CatalogClientError("CONFIRMATION_TIMEOUT", observed === null
645
+ ? `等待门户确认超时(${timeoutMs}ms):公开读地址上还没有本实例的绑定`
646
+ : `等待门户确认超时(${timeoutMs}ms):${observed}`);
647
+ }
648
+ await sleep(pollMs);
649
+ }
650
+ }
651
+ // ── S4:构造并发布名片(不可变 revision;发出前自查 origin 与端点)─────
652
+ async publishCard(input, identity) {
653
+ const agentId = this.requireAgentId(input.agentId);
654
+ const runtimeOrigin = normalizeOrigin(requireHttpsUrl(input.runtimeOrigin, "runtime_origin"));
655
+ const a2aEndpoint = requireHttpsUrl(input.a2aEndpoint, "a2a_endpoint");
656
+ if (typeof input.bindingId !== "string" || input.bindingId.trim() === "") {
657
+ throw new CatalogClientError("INVALID_INPUT", "binding_id 必须是非空字符串(发布由活动绑定背书)");
658
+ }
659
+ if (!Number.isInteger(input.expectedRevision) || input.expectedRevision < 0) {
660
+ throw new CatalogClientError("INVALID_INPUT", `expected_revision 必须是非负整数:${input.expectedRevision}`);
661
+ }
662
+ // 提前自查(服务端也会拦,但坏卡不该出门):结构 + secret 扫描。
663
+ let card;
664
+ try {
665
+ card = validateAgentCard(input.agentCard);
666
+ }
667
+ catch (err) {
668
+ throw new CatalogClientError("SCHEMA_VIOLATION", `agent_card 未通过结构校验:${err instanceof Error ? err.message : String(err)}`);
669
+ }
670
+ assertCardWithinOrigin(card, runtimeOrigin, a2aEndpoint);
671
+ // card_digest 由发布方计算(JCS 规范化后 sha256);Catalog 只存不算。
672
+ const cardDigest = `sha256:${createHash("sha256").update(canonicalize(card), "utf8").digest("hex")}`;
673
+ const attempt = async (expectedRevision) => {
674
+ const nonce = this.nonceFactory();
675
+ const jws = signCompactJws({
676
+ agent_id: agentId,
677
+ binding_id: input.bindingId,
678
+ generation: input.generation,
679
+ expected_revision: expectedRevision,
680
+ card_digest: cardDigest,
681
+ issued_at: this.now().toISOString(),
682
+ nonce,
683
+ }, identity.signingIdentity, { extraHeader: { typ: "kiwi-runtime-request" } });
684
+ const body = {
685
+ publication: {
686
+ schema_version: "0.1.2",
687
+ agent_id: agentId,
688
+ binding_id: input.bindingId,
689
+ generation: input.generation,
690
+ expected_revision: expectedRevision,
691
+ wire_profile: "a2a-1.0",
692
+ card_digest: cardDigest,
693
+ agent_card: card,
694
+ },
695
+ };
696
+ assertContract("card-publication-request", body);
697
+ const { json } = await this.request("POST", `/v1/agents/${encodeURIComponent(agentId)}/card-publications`, { body, jws });
698
+ return { json, nonce };
699
+ };
700
+ const outcome = await this.withCasRetry(agentId, input.expectedRevision, attempt, input.casRetry);
701
+ const receipt = isRecord(outcome.json) ? outcome.json : {};
702
+ const revision = receipt["revision"] ?? receipt["card_revision"];
703
+ return {
704
+ revision: typeof revision === "number" && Number.isInteger(revision) ? revision : null,
705
+ cardDigest,
706
+ nonce: outcome.nonce,
707
+ };
708
+ }
709
+ // ── S4:CAS 激活(body 平铺:card_revision + expected_revision + binding_id)──
710
+ /**
711
+ * 激活指定名片 revision(kiwi-catalog `activate_card_publication` 的实际契约):
712
+ * body 是**平铺**的 `{agent_id, binding_id, card_revision, expected_revision}`
713
+ * (`card_revision`/`expected_revision` 都是顶层必填整数,缺 card_revision 直接 400);
714
+ * JWS 覆盖 `agent_id/binding_id/card_revision/expected_revision` + `issued_at` + nonce。
715
+ */
716
+ async activateCard(input, identity) {
717
+ const agentId = this.requireAgentId(input.agentId);
718
+ if (typeof input.bindingId !== "string" || input.bindingId.trim() === "") {
719
+ throw new CatalogClientError("INVALID_INPUT", "binding_id 必须是非空字符串(激活由活动绑定背书)");
720
+ }
721
+ if (!Number.isInteger(input.cardRevision) || input.cardRevision < 1) {
722
+ throw new CatalogClientError("INVALID_INPUT", `card_revision 必须是正整数(要激活的版本号):${input.cardRevision}`);
723
+ }
724
+ if (!Number.isInteger(input.expectedRevision) || input.expectedRevision < 0) {
725
+ throw new CatalogClientError("INVALID_INPUT", `expected_revision 必须是非负整数:${input.expectedRevision}`);
726
+ }
727
+ const attempt = async (expectedRevision) => {
728
+ const nonce = this.nonceFactory();
729
+ const jws = signCompactJws({
730
+ agent_id: agentId,
731
+ binding_id: input.bindingId,
732
+ card_revision: input.cardRevision,
733
+ expected_revision: expectedRevision,
734
+ issued_at: this.now().toISOString(),
735
+ nonce,
736
+ }, identity.signingIdentity, { extraHeader: { typ: "kiwi-runtime-request" } });
737
+ const { json } = await this.request("POST", `/v1/agents/${encodeURIComponent(agentId)}/publish`, {
738
+ body: {
739
+ agent_id: agentId,
740
+ binding_id: input.bindingId,
741
+ card_revision: input.cardRevision,
742
+ expected_revision: expectedRevision,
743
+ },
744
+ jws,
745
+ });
746
+ return { json, nonce };
747
+ };
748
+ const outcome = await this.withCasRetry(agentId, input.expectedRevision, attempt, input.casRetry);
749
+ const receipt = isRecord(outcome.json) ? outcome.json : {};
750
+ // catalog `activate_card` 回执是 {active_revision, etag};兼容 revision/card_revision 命名。
751
+ const revision = receipt["active_revision"] ?? receipt["revision"] ?? receipt["card_revision"];
752
+ return {
753
+ revision: typeof revision === "number" && Number.isInteger(revision) ? revision : null,
754
+ nonce: outcome.nonce,
755
+ };
756
+ }
757
+ // ── 内部 ─────────────────────────────────────────────────────────────
758
+ /**
759
+ * CAS 冲突处理(§4.6):409 → 匿名重读公开绑定文档信封的 `card_revision`
760
+ * (契约 `document.schema.json` 的公开元数据,= catalog `card_publications.
761
+ * active_revision`;不在 claims 里)→ 用**新 nonce** 重试一次;仍冲突抛
762
+ * CONFLICT 停下来报人工。重读到的 revision 与手头相同说明冲突不是"版本旧了",
763
+ * 重试无意义,直接报人工。文档不可读(BINDING_UNREADABLE,首发布前窗口)时
764
+ * 无从取新版本,同样直接报人工。
765
+ */
766
+ async withCasRetry(agentId, expectedRevision, attempt, casRetry) {
767
+ try {
768
+ return await attempt(expectedRevision);
769
+ }
770
+ catch (err) {
771
+ if (!(err instanceof CatalogClientError) || err.code !== "CONFLICT" || casRetry === false) {
772
+ throw err;
773
+ }
774
+ }
775
+ let current;
776
+ try {
777
+ current = await this.fetchPublicBinding(agentId);
778
+ }
779
+ catch (err) {
780
+ if (err instanceof CatalogClientError && err.code === "BINDING_UNREADABLE") {
781
+ throw new CatalogClientError("CONFLICT", "CAS 冲突且公开绑定文档暂不可读(403 窗口),无法重读最新 revision——停下来报人工核对", 409);
782
+ }
783
+ throw err;
784
+ }
785
+ const fresh = current?.cardRevision ?? 0;
786
+ if (fresh === expectedRevision) {
787
+ throw new CatalogClientError("CONFLICT", `CAS 冲突:expected_revision=${expectedRevision} 与目录当前活动版本一致但仍被拒,停下来报人工核对`, 409);
788
+ }
789
+ try {
790
+ return await attempt(fresh);
791
+ }
792
+ catch (err) {
793
+ if (err instanceof CatalogClientError && err.code === "CONFLICT") {
794
+ throw new CatalogClientError("CONFLICT", `CAS 冲突:重读(revision=${fresh})后重试一次仍 409,停下来报人工核对`, 409);
795
+ }
796
+ throw err;
797
+ }
798
+ }
799
+ requireAgentId(agentId) {
800
+ const trimmed = String(agentId ?? "").trim();
801
+ if (trimmed === "") {
802
+ throw new CatalogClientError("INVALID_INPUT", "agentId 必须是非空字符串");
803
+ }
804
+ if (trimmed.includes("/") || trimmed.includes("..")) {
805
+ throw new CatalogClientError("INVALID_INPUT", `agentId 含非法字符:${trimmed}`);
806
+ }
807
+ return trimmed;
808
+ }
809
+ /**
810
+ * 统一出站:redirect: manual、超时覆盖 body 读取、响应体上限(与
811
+ * cloud-card.ts 同口径)。错误映射:网络/超时/5xx/429 → CATALOG_UNREACHABLE;
812
+ * 409 → CONFLICT;404 原样上报(匿名读用);其余 4xx → REQUEST_REJECTED。
813
+ */
814
+ async request(method, requestPath, options) {
815
+ const url = `${this.baseUrl}${requestPath}`;
816
+ const headers = {
817
+ accept: "application/json",
818
+ "user-agent": `kiwi-runtime/${PRODUCT_VERSION}`,
819
+ };
820
+ if (options.body !== undefined)
821
+ headers["content-type"] = "application/json";
822
+ if (options.jws !== undefined)
823
+ headers["x-kiwi-binding-jws"] = options.jws;
824
+ Object.assign(headers, options.headers ?? {});
825
+ const controller = new AbortController();
826
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
827
+ try {
828
+ let response;
829
+ try {
830
+ response = await this.fetchImpl(url, {
831
+ method,
832
+ redirect: "manual",
833
+ signal: controller.signal,
834
+ headers,
835
+ ...(options.body !== undefined ? { body: JSON.stringify(options.body) } : {}),
836
+ });
837
+ }
838
+ catch (err) {
839
+ const name = err?.name;
840
+ const detail = err instanceof Error ? err.message : String(err);
841
+ throw new CatalogClientError("CATALOG_UNREACHABLE", name === "AbortError"
842
+ ? `catalog 请求超时(${this.timeoutMs}ms):${url}`
843
+ : `catalog 不可达:${url}(${detail})`);
844
+ }
845
+ if (isRedirectResponse(response)) {
846
+ throw new CatalogClientError("RESPONSE_INVALID", `catalog 控制面不得重定向(HTTP ${response.status} from ${url})`, response.status);
847
+ }
848
+ if (response.status === 404) {
849
+ return { status: 404, json: undefined };
850
+ }
851
+ if (response.status === 409) {
852
+ throw new CatalogClientError("CONFLICT", `catalog 拒绝(409 冲突):${method} ${url}`, 409);
853
+ }
854
+ if (response.status === 429 || response.status >= 500) {
855
+ throw new CatalogClientError("CATALOG_UNREACHABLE", `catalog 暂不可用(HTTP ${response.status}):${method} ${url}`, response.status);
856
+ }
857
+ if (!response.ok) {
858
+ let remoteCode;
859
+ try {
860
+ const errorPayload = await readJsonBody(response, { signal: controller.signal, maxBytes: 16 * 1024 });
861
+ if (isRecord(errorPayload)) {
862
+ const rawCode = errorPayload["error"] ?? errorPayload["code"];
863
+ if (typeof rawCode === "string") {
864
+ const match = /^([A-Z][A-Z0-9_]{1,79})(?::|$)/.exec(rawCode);
865
+ if (match)
866
+ remoteCode = match[1];
867
+ }
868
+ }
869
+ }
870
+ catch {
871
+ // Error bodies are advisory; the HTTP status remains authoritative.
872
+ }
873
+ throw new CatalogClientError("REQUEST_REJECTED", `catalog 拒绝(HTTP ${response.status}${remoteCode ? ` ${remoteCode}` : ""}):${method} ${url}`, response.status, remoteCode);
874
+ }
875
+ let json;
876
+ try {
877
+ json = await readJsonBody(response, { signal: controller.signal });
878
+ }
879
+ catch (err) {
880
+ if (controller.signal.aborted) {
881
+ throw new CatalogClientError("CATALOG_UNREACHABLE", `catalog 响应读取超时(${this.timeoutMs}ms):${url}`);
882
+ }
883
+ throw new CatalogClientError("RESPONSE_INVALID", err instanceof SafeHttpError && err.code === "response_too_large"
884
+ ? `catalog 响应超限(${url}):${err.message}`
885
+ : `catalog 响应不是合法 JSON:${url}`);
886
+ }
887
+ return { status: response.status, json };
888
+ }
889
+ finally {
890
+ clearTimeout(timer);
891
+ }
892
+ }
893
+ }
894
+ /** 由自持私钥导出公钥 JWK 与指纹(私钥不出进程;公钥随绑定请求公开)。 */
895
+ export function runtimePublicKey(identity) {
896
+ const keyJwk = createPublicKey(identity.signingIdentity.privateKey).export({
897
+ format: "jwk",
898
+ });
899
+ return { keyJwk, keyThumbprint: jwkThumbprint(keyJwk) };
900
+ }
901
+ /** 名片域内自查(§4.6:发出前客户端先拦,服务端也会拦)。 */
902
+ export function assertCardWithinOrigin(card, runtimeOrigin, a2aEndpoint) {
903
+ const origin = originOf(normalizeOrigin(runtimeOrigin));
904
+ if (typeof card.url !== "string" || card.url === "") {
905
+ throw new CatalogClientError("CARD_ORIGIN_VIOLATION", "agent_card.url 缺失(必须等于运行时 origin)");
906
+ }
907
+ if (originOf(card.url) !== origin) {
908
+ throw new CatalogClientError("CARD_ORIGIN_VIOLATION", `agent_card.url(${card.url})不在运行时 origin(${origin})内`);
909
+ }
910
+ if (!Array.isArray(card.supportedInterfaces) || card.supportedInterfaces.length === 0) {
911
+ throw new CatalogClientError("CARD_ENDPOINT_NOT_BOUND", "agent_card.supportedInterfaces 为空");
912
+ }
913
+ let bound = false;
914
+ for (const [index, entry] of card.supportedInterfaces.entries()) {
915
+ if (typeof entry.url !== "string" || !entry.url.startsWith("https://")) {
916
+ throw new CatalogClientError("CARD_ORIGIN_VIOLATION", `supportedInterfaces[${index}].url 必须是 https URL:${String(entry.url)}`);
917
+ }
918
+ if (originOf(entry.url) !== origin) {
919
+ throw new CatalogClientError("CARD_ORIGIN_VIOLATION", `supportedInterfaces[${index}].url(${entry.url})不在运行时 origin(${origin})内`);
920
+ }
921
+ if (entry.url === a2aEndpoint)
922
+ bound = true;
923
+ }
924
+ if (!bound) {
925
+ throw new CatalogClientError("CARD_ENDPOINT_NOT_BOUND", `名片没有任何接口等于绑定的 a2a_endpoint(${a2aEndpoint})——不得指向 Catalog 或他域`);
926
+ }
927
+ }
928
+ /** 本地产物结构自检:发出前用仓内 0.1.2 契约 schema 校验。 */
929
+ function assertContract(name, body) {
930
+ const errors = validateCloudContract(name, body);
931
+ if (errors.length > 0) {
932
+ throw new CatalogClientError("SCHEMA_VIOLATION", `本地产物不符合 ${name} 契约:${errors.join(";")}`);
933
+ }
934
+ }
935
+ /** 解析公开绑定文档(只取与自身核对所需字段;claims 过完整校验,fail-closed)。 */
936
+ function parsePublicBinding(raw) {
937
+ if (!isRecord(raw)) {
938
+ throw new CatalogClientError("RESPONSE_INVALID", "runtime-binding 响应必须是 JSON 对象");
939
+ }
940
+ const check = validateBindingClaims(raw["claims"]);
941
+ if (!check.ok) {
942
+ throw new CatalogClientError("RESPONSE_INVALID", `runtime-binding 的 claims 不符合 schema:${check.errors.join(";")}`);
943
+ }
944
+ const claims = check.claims;
945
+ const revision = raw["card_revision"];
946
+ const etag = raw["card_etag"];
947
+ const governance = raw["governance"];
948
+ return {
949
+ bindingId: claims.binding_id,
950
+ bindingVersion: claims.binding_version,
951
+ merchantId: claims.merchant_id,
952
+ runtimeOrigin: claims.runtime_origin,
953
+ a2aEndpoint: claims.a2a_endpoint,
954
+ keyId: claims.key_id,
955
+ keyThumbprint: claims.key_thumbprint,
956
+ expiresAt: claims.expires_at,
957
+ cardRevision: typeof revision === "number" && Number.isInteger(revision) ? revision : null,
958
+ cardEtag: typeof etag === "string" && etag !== "" ? etag : null,
959
+ publicationState: isRecord(governance) ? String(governance["publication_state"] ?? "") : "",
960
+ };
961
+ }
962
+ //# sourceMappingURL=catalog-client.js.map