@tool-bridge/server 0.24.0 → 0.25.0

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 (112) hide show
  1. package/dist/admin.js +164 -5
  2. package/dist/{airtable-Z6KEL3MA.js → airtable-4HFPBKO2.js} +6 -6
  3. package/dist/{alt_text_generator_ai-RM2GHSNM.js → alt_text_generator_ai-TBGJCAWO.js} +5 -5
  4. package/dist/{amap-YEJLGIKY.js → amap-V2WZ4GP4.js} +5 -5
  5. package/dist/{anthropic-62M4MUVQ.js → anthropic-HVNDGFRH.js} +6 -6
  6. package/dist/{apify-AHRNDBCB.js → apify-TI5DOAUG.js} +6 -6
  7. package/dist/{brave_search-JAHWOMQC.js → brave_search-7GFBVUIH.js} +6 -6
  8. package/dist/{chunk-TH3H5YAG.js → chunk-3VF7MQJX.js} +40 -3
  9. package/dist/{chunk-FZV7CF7L.js → chunk-CXRQCZBS.js} +3 -3
  10. package/dist/{chunk-NG4C7YB3.js → chunk-G6GI7EMV.js} +3 -3
  11. package/dist/{chunk-U2UGFSOX.js → chunk-KVLI7ZFI.js} +2 -2
  12. package/dist/{chunk-GQ4O7NK5.js → chunk-N7ZFZWGA.js} +1 -1
  13. package/dist/{chunk-7MUNQNXG.js → chunk-TF2N67HN.js} +1731 -1358
  14. package/dist/{chunk-LD7KQRQ3.js → chunk-UKITQ6LN.js} +3773 -2879
  15. package/dist/{chunk-SU6Q4RAY.js → chunk-UVG4PNWV.js} +2 -2
  16. package/dist/{circleci-UJUYBIAO.js → circleci-75NMIPKV.js} +6 -6
  17. package/dist/{clerk-FCFM3WJK.js → clerk-PB2SJAMC.js} +6 -6
  18. package/dist/{cohere-OTSYSMPC.js → cohere-UBIMGBOU.js} +6 -6
  19. package/dist/{confluence-LPANSCGT.js → confluence-5436ZQBW.js} +6 -6
  20. package/dist/{convertapi-AJZOVUHT.js → convertapi-CZILNAZL.js} +4 -4
  21. package/dist/{currencyapi-HGK5FSGO.js → currencyapi-IPUUA4ZC.js} +6 -6
  22. package/dist/{deepseek-7HMTFJRV.js → deepseek-F2JV4HEE.js} +6 -6
  23. package/dist/{docker_hub-FCNVKJZW.js → docker_hub-TRH7EULS.js} +5 -5
  24. package/dist/{dropbox-2XVKCQZE.js → dropbox-4DCC6FQ7.js} +6 -6
  25. package/dist/{dub-CTUKPX2A.js → dub-RSI5NDXK.js} +6 -6
  26. package/dist/{e2b-ULEWTRKI.js → e2b-KM4FJOXS.js} +6 -6
  27. package/dist/{exa-QENFV3AU.js → exa-MF26RJSD.js} +6 -6
  28. package/dist/{fal_ai-TQYUBBAF.js → fal_ai-4I4QJKBZ.js} +6 -6
  29. package/dist/{feishu-OYCWDSHD.js → feishu-KEBTN5OD.js} +3 -3
  30. package/dist/{feishu_custom_bot-VYQ7A3PU.js → feishu_custom_bot-KJTIB3PG.js} +4 -4
  31. package/dist/{figma-5DLOKAQQ.js → figma-OFW54Q54.js} +6 -6
  32. package/dist/{firehydrant-X4MGP2OI.js → firehydrant-RU3B7DXC.js} +6 -6
  33. package/dist/{fixer-LMIWM3ZX.js → fixer-QZ4WCQN3.js} +5 -5
  34. package/dist/{fly-J5HN5L2I.js → fly-ZPUXZ5Y7.js} +6 -6
  35. package/dist/{front-E3SMBQW3.js → front-SCMVKIEA.js} +6 -6
  36. package/dist/{geocodio-AOINRPLA.js → geocodio-N3QYPBRC.js} +5 -5
  37. package/dist/{ghost-E4CBGZWJ.js → ghost-VMSBR3TP.js} +5 -5
  38. package/dist/{github-PGR6U3FC.js → github-XOML5UVH.js} +6 -6
  39. package/dist/github_events-5FCIB5E3.js +78 -0
  40. package/dist/{gmail-XNQHMQ6F.js → gmail-FX3TTLAE.js} +6 -6
  41. package/dist/{googlecalendar-RE6DGG7L.js → googlecalendar-LWMUNEF5.js} +6 -6
  42. package/dist/{googledocs-CX2BZDQH.js → googledocs-ZGVN66MU.js} +4 -4
  43. package/dist/{grafana-GX75ZA5X.js → grafana-NKZPJG5L.js} +6 -6
  44. package/dist/{graphhopper-XMUYLWHS.js → graphhopper-XCRPVZNX.js} +5 -5
  45. package/dist/index.d.ts +315 -5
  46. package/dist/index.js +7 -5
  47. package/dist/{ip2proxy-ZGIRBAG5.js → ip2proxy-RDDJFPLQ.js} +5 -5
  48. package/dist/{ipgeolocation_io-MAP27QMO.js → ipgeolocation_io-RTUJKI3Z.js} +5 -5
  49. package/dist/{ipqualityscore-6IIUUAQ2.js → ipqualityscore-5NG5KR33.js} +5 -5
  50. package/dist/{jina_ai-GGH77RQH.js → jina_ai-VG5X5JBE.js} +6 -6
  51. package/dist/{jira-7GPZW6HZ.js → jira-LS6ITOSL.js} +6 -6
  52. package/dist/{langsmith-CJXYE7WM.js → langsmith-TT26W3A4.js} +6 -6
  53. package/dist/{lemlist-OYPOX6GN.js → lemlist-25WLR36L.js} +6 -6
  54. package/dist/{linear-TPQ6X4XZ.js → linear-JLE2CHI3.js} +4 -4
  55. package/dist/{logsnag-HT2PRLIV.js → logsnag-OI67GLMG.js} +6 -6
  56. package/dist/main.js +6 -5
  57. package/dist/{mattermost-6IYTWTM5.js → mattermost-AYJAUGNG.js} +6 -6
  58. package/dist/{mem0-7AVGBGOX.js → mem0-ZGEAZPCF.js} +6 -6
  59. package/dist/{memos-CTOXWZ6X.js → memos-PS2QHWZX.js} +6 -6
  60. package/dist/{metabase-AFJXQ5SQ.js → metabase-6F5P4YNZ.js} +6 -6
  61. package/dist/{mistral_ai-QDKM4N3R.js → mistral_ai-GKF6H3PY.js} +6 -6
  62. package/dist/{mother_duck-XSKR4GVL.js → mother_duck-C7KWG5OB.js} +6 -6
  63. package/dist/{ngrok-NQMLM24P.js → ngrok-UZQYPMSO.js} +6 -6
  64. package/dist/{notes-ZWMVZQWJ.js → notes-DO7GGFTP.js} +2 -2
  65. package/dist/{notion-6544KSMM.js → notion-JSLD5P5J.js} +6 -6
  66. package/dist/{open_exchange_rates-4CLN7O2N.js → open_exchange_rates-NZYN73GB.js} +5 -5
  67. package/dist/{openai-HLFGPVI5.js → openai-KOXCZZVV.js} +6 -6
  68. package/dist/{opengraph_io-57JDHT3M.js → opengraph_io-DVAV6AK6.js} +5 -5
  69. package/dist/{openrouter-WDAVB2OP.js → openrouter-MPMSFAEY.js} +6 -6
  70. package/dist/{outline-A6MDLZVH.js → outline-E2SNFTFE.js} +6 -6
  71. package/dist/{paddle-WX5ULOPP.js → paddle-QOZOMZ6T.js} +6 -6
  72. package/dist/{perplexity-LYTWWWCZ.js → perplexity-VRWYDYRW.js} +6 -6
  73. package/dist/{pinecone-7KAF3S7U.js → pinecone-LDU3YSBJ.js} +6 -6
  74. package/dist/{pipedrive-YQY243G7.js → pipedrive-ZN6NDUPL.js} +6 -6
  75. package/dist/{polar-A5HKXSQY.js → polar-H5GK75YP.js} +6 -6
  76. package/dist/{posthog-CF2LHLS4.js → posthog-XVJMSCPA.js} +6 -6
  77. package/dist/{postmark-W756TMJM.js → postmark-IVXNOXFI.js} +6 -6
  78. package/dist/{prerender-ZYM4UQ5R.js → prerender-FH4SBVJY.js} +5 -5
  79. package/dist/{pubmed-QXTUQCTQ.js → pubmed-TM7LBALS.js} +4 -4
  80. package/dist/{railway-F4MOZ3LQ.js → railway-FJ4XQ2NF.js} +4 -4
  81. package/dist/{readwise-S7MF5SR5.js → readwise-4VQNTOLQ.js} +6 -6
  82. package/dist/{render-D7EIVDUA.js → render-CX7AWO6F.js} +6 -6
  83. package/dist/{replicate-ABNKPZR7.js → replicate-U6T7GYMR.js} +6 -6
  84. package/dist/{resend-7VJEY4KC.js → resend-RDQXZGY6.js} +6 -6
  85. package/dist/{rootly-UMFJOKXC.js → rootly-AWTSRSIZ.js} +6 -6
  86. package/dist/{scrapfly-UDT4KNFL.js → scrapfly-UWX6TBH7.js} +5 -5
  87. package/dist/{scrapingbee-XTFD54NB.js → scrapingbee-BKCOLELF.js} +5 -5
  88. package/dist/{screenshot_fyi-5GTW3SFY.js → screenshot_fyi-3OYHV6ZZ.js} +5 -5
  89. package/dist/{semantic_scholar-Y6WK2MST.js → semantic_scholar-EV2HDKRA.js} +6 -6
  90. package/dist/{sentry-ZFPGDA6C.js → sentry-BPEKPIFX.js} +6 -6
  91. package/dist/{shodan-3SCDBOQ3.js → shodan-RYTNBHVJ.js} +5 -5
  92. package/dist/{shopify-LMTBS2I2.js → shopify-JGWZFCNO.js} +6 -6
  93. package/dist/{stripe-4JQJ2CUG.js → stripe-RBWCW52X.js} +4 -4
  94. package/dist/{supabase-7HA3BEFK.js → supabase-TX5J2UBD.js} +6 -6
  95. package/dist/{tavily-H34ZBPGC.js → tavily-33ZRT2RT.js} +6 -6
  96. package/dist/{telegram-CRX4YWQ3.js → telegram-HX3UKW3Y.js} +5 -5
  97. package/dist/{telnyx-TIKGEU34.js → telnyx-5J74OO5R.js} +6 -6
  98. package/dist/{todoist-LU563DGZ.js → todoist-6CUCDWTH.js} +6 -6
  99. package/dist/{trello-NTRGEROX.js → trello-FTFDRPZ7.js} +5 -5
  100. package/dist/{turso-EY3CNVPZ.js → turso-33T4OAJR.js} +6 -6
  101. package/dist/{twilio-ICX3WRQH.js → twilio-ZBX6EHFG.js} +4 -4
  102. package/dist/{umami-NPMRVI3M.js → umami-QCVTF7WS.js} +6 -6
  103. package/dist/{unsplash-TIHBZFIM.js → unsplash-M6XCQKQE.js} +6 -6
  104. package/dist/{upstash_redis-2DO6EHCN.js → upstash_redis-57JQ3XMB.js} +6 -6
  105. package/dist/{uptimerobot-BGYOCKGI.js → uptimerobot-KDS5YBKZ.js} +4 -4
  106. package/dist/{v2ex-GOWDPGGA.js → v2ex-5YPZ6BIT.js} +6 -6
  107. package/dist/{vercel-G33RXVBI.js → vercel-6VWZHALZ.js} +6 -6
  108. package/dist/{wolfram_alpha_api-IRZSMD3P.js → wolfram_alpha_api-4YNRTVTQ.js} +5 -5
  109. package/dist/{wordpress-ATWGGUC3.js → wordpress-LKN2EV4B.js} +6 -6
  110. package/dist/{workos-LHJDETBX.js → workos-DTPEULYR.js} +6 -6
  111. package/dist/{zhihu-IAH53YPP.js → zhihu-LFQRTQS7.js} +6 -6
  112. package/package.json +5 -5
@@ -241,10 +241,10 @@ var AnnotationStore = class {
241
241
  async list(prefix) {
242
242
  const normPrefix = prefix === void 0 ? "" : normalizeAnnotationPath(prefix);
243
243
  const out = [];
244
- let cursor;
244
+ let cursor2;
245
245
  do {
246
246
  const page = await this.store.list(KEY_ANNOTATION, {
247
- ...cursor !== void 0 ? { cursor } : {}
247
+ ...cursor2 !== void 0 ? { cursor: cursor2 } : {}
248
248
  });
249
249
  for (const { key, value } of page.items) {
250
250
  const path = key.slice(KEY_ANNOTATION.length);
@@ -259,8 +259,8 @@ var AnnotationStore = class {
259
259
  updatedBy: typeof a.updatedBy === "string" ? a.updatedBy : ""
260
260
  });
261
261
  }
262
- cursor = page.cursor;
263
- } while (cursor);
262
+ cursor2 = page.cursor;
263
+ } while (cursor2);
264
264
  return out.sort((a, b) => a.path.localeCompare(b.path));
265
265
  }
266
266
  };
@@ -318,6 +318,7 @@ var LIST_LIMIT_DEFAULT = 50;
318
318
  var LIST_LIMIT_MAX = 200;
319
319
  var ACTIONS = ["read", "write", "call", "register", "admin"];
320
320
  var NODE_KINDS = [
321
+ "topic",
321
322
  "directory",
322
323
  "mcp",
323
324
  "http",
@@ -838,7 +839,8 @@ function cmdPath(nodePath) {
838
839
  var DESCRIPTION = "Built-in integration catalog (read-only; mount one via system/registry)";
839
840
  var NODE_KIND_BY_PROFILE = {
840
841
  "tools/v1": "tool",
841
- "context/v1": "context"
842
+ "context/v1": "context",
843
+ "events/v1": "topic"
842
844
  };
843
845
  function projectExportAuth(exported) {
844
846
  if (exported.oauth !== void 0) return { kind: "oauth" };
@@ -871,6 +873,7 @@ function projectListItem(entry) {
871
873
  id: e.id,
872
874
  kind,
873
875
  auth: projectExportAuth(e),
876
+ ...e.eventSource ? { eventSource: e.eventSource } : {},
874
877
  ...e.description !== void 0 ? { description: e.description } : {},
875
878
  ...e.mountConfigFields !== void 0 ? { mountConfigFields: e.mountConfigFields } : {}
876
879
  };
@@ -946,22 +949,45 @@ function createCatalogModule(deps) {
946
949
  }
947
950
 
948
951
  // ../core/src/builtin/plugin.ts
949
- import { z as z9 } from "zod/v4";
952
+ import { z as z12 } from "zod/v4";
953
+
954
+ // ../core/src/builtin/pluginDistribution.ts
955
+ import { z as z11 } from "zod/v4";
956
+
957
+ // ../core/src/plugin/release.ts
958
+ import { z as z10 } from "zod/v4";
950
959
 
951
960
  // ../core/src/plugin/contract.ts
952
- import { z as z7 } from "zod";
961
+ import { z as z8 } from "zod";
962
+
963
+ // ../core/src/plugin/eventSource.ts
964
+ import { z as z5 } from "zod/v4";
965
+ var eventBindingSchema = z5.strictObject({
966
+ kind: z5.literal("topic"),
967
+ provider: z5.string().min(1).max(128),
968
+ export: z5.string().min(1).max(128),
969
+ authRef: z5.string().min(1).max(128)
970
+ });
971
+ var eventSourceSchema = z5.strictObject({
972
+ headers: z5.array(z5.string().max(80).regex(/^x-(?!tb-|forwarded-)[a-z0-9-]+$/)).max(12),
973
+ types: z5.array(z5.strictObject({
974
+ type: z5.string().min(1).max(128),
975
+ version: z5.number().int().positive(),
976
+ dataSchema: z5.record(z5.string(), z5.unknown())
977
+ })).min(1).max(64)
978
+ });
953
979
 
954
980
  // ../core/src/plugin/oauth.ts
955
- import { z as z5 } from "zod";
981
+ import { z as z6 } from "zod";
956
982
  var OAUTH_CLIENT_AUTH_METHODS = ["client_secret_basic", "client_secret_post", "none"];
957
- var httpsUrl = z5.string().url().refine(
983
+ var httpsUrl = z6.string().url().refine(
958
984
  (value) => {
959
985
  const url = new URL2(value);
960
986
  return url.protocol === "https:" && !url.hash && !url.username && !url.password;
961
987
  },
962
988
  "OAuth \u7AEF\u70B9\u5FC5\u987B\u662F HTTPS\uFF0C\u4E14\u4E0D\u80FD\u542B fragment \u6216 URL \u51ED\u8BC1"
963
989
  );
964
- var pluginOAuthSchema = z5.object({
990
+ var pluginOAuthSchema = z6.object({
965
991
  /** 浏览器跳转的授权端点。 */
966
992
  authorizationUrl: httpsUrl,
967
993
  /** 兑换 code / 刷新令牌的端点。 */
@@ -969,23 +995,23 @@ var pluginOAuthSchema = z5.object({
969
995
  /** 刷新端点(缺省同 tokenUrl;个别 provider 分开)。 */
970
996
  refreshUrl: httpsUrl.optional(),
971
997
  /** 申请的 scope 列表。 */
972
- scopes: z5.array(z5.string().min(1)).optional(),
998
+ scopes: z6.array(z6.string().min(1)).optional(),
973
999
  /** scope 分隔符(缺省空格;个别 provider 用逗号)。 */
974
- scopeSeparator: z5.enum([" ", ","]).optional(),
1000
+ scopeSeparator: z6.enum([" ", ","]).optional(),
975
1001
  /** 客户端认证方式(缺省 client_secret_post)。 */
976
- clientAuth: z5.enum(OAUTH_CLIENT_AUTH_METHODS).optional(),
1002
+ clientAuth: z6.enum(OAUTH_CLIENT_AUTH_METHODS).optional(),
977
1003
  /**
978
1004
  * 授权 URL 的额外静态参数(如 Google 的 `access_type=offline`、
979
1005
  * 飞书的 `state` 之外的自定义项)。不得覆盖协议参数。
980
1006
  */
981
- authorizationParams: z5.record(z5.string(), z5.string()).optional(),
1007
+ authorizationParams: z6.record(z6.string(), z6.string()).optional(),
982
1008
  /**
983
1009
  * 令牌响应被包了一层信封时的取值路径(如飞书 v2 的 `{code,msg,data:{...}}` → `'data'`)。
984
1010
  * 缺省表示响应根就是令牌对象。
985
1011
  */
986
- responseEnvelope: z5.string().min(1).optional(),
1012
+ responseEnvelope: z6.string().min(1).optional(),
987
1013
  /** PKCE:缺省启用(S256)。个别老 provider 不支持,置 false。 */
988
- pkce: z5.boolean().optional()
1014
+ pkce: z6.boolean().optional()
989
1015
  });
990
1016
  var OAUTH_CLIENT_FIELDS = [
991
1017
  {
@@ -1077,16 +1103,16 @@ function buildTokenRequest(opts) {
1077
1103
  return { body: encodeForm(form), headers };
1078
1104
  }
1079
1105
  function parseTokenResponse(payload, config, now) {
1080
- let source = payload;
1106
+ let source2 = payload;
1081
1107
  if (config.responseEnvelope !== void 0) {
1082
1108
  const outer = asRecord(payload);
1083
1109
  const inner = outer?.[config.responseEnvelope];
1084
1110
  if (inner === void 0) {
1085
1111
  throw new TBError("invalid_argument", tokenErrorMessage(outer) ?? "\u4EE4\u724C\u54CD\u5E94\u7F3A\u5C11\u4EE4\u724C\u6570\u636E");
1086
1112
  }
1087
- source = inner;
1113
+ source2 = inner;
1088
1114
  }
1089
- const record = asRecord(source);
1115
+ const record = asRecord(source2);
1090
1116
  const accessToken = typeof record?.access_token === "string" ? record.access_token : void 0;
1091
1117
  if (accessToken === void 0 || accessToken === "") {
1092
1118
  throw new TBError("invalid_argument", tokenErrorMessage(asRecord(payload)) ?? "\u4EE4\u724C\u54CD\u5E94\u7F3A\u5C11 access_token");
@@ -1104,34 +1130,34 @@ function parseTokenResponse(payload, config, now) {
1104
1130
  }
1105
1131
 
1106
1132
  // ../core/src/context/commands.ts
1107
- import { z as z6 } from "zod/v4";
1108
- var metadataSchema = z6.record(z6.string(), z6.string()).optional().describe(
1133
+ import { z as z7 } from "zod/v4";
1134
+ var metadataSchema = z7.record(z7.string(), z7.string()).optional().describe(
1109
1135
  "string-to-string metadata map"
1110
1136
  );
1111
- var entrySchema = z6.strictObject({
1112
- contentType: z6.string().optional().describe(
1137
+ var entrySchema = z7.strictObject({
1138
+ contentType: z7.string().optional().describe(
1113
1139
  "required when content is a string; defaults to application/json for non-string content"
1114
1140
  ),
1115
- content: z6.unknown().describe("entry body: string, or any JSON value"),
1141
+ content: z7.unknown().describe("entry body: string, or any JSON value"),
1116
1142
  metadata: metadataSchema,
1117
- ifVersion: z6.string().optional().describe("optimistic concurrency: expected current version")
1143
+ ifVersion: z7.string().optional().describe("optimistic concurrency: expected current version")
1118
1144
  });
1119
- var patchSchema = z6.strictObject({
1120
- content: z6.unknown().optional().describe("replacement content"),
1145
+ var patchSchema = z7.strictObject({
1146
+ content: z7.unknown().optional().describe("replacement content"),
1121
1147
  metadata: metadataSchema,
1122
- ifVersion: z6.string().optional().describe("optimistic concurrency: expected current version")
1148
+ ifVersion: z7.string().optional().describe("optimistic concurrency: expected current version")
1123
1149
  }).describe("partial update; omitted fields keep their current value");
1124
- var searchOptionsSchema = z6.strictObject({
1125
- cursor: z6.string().optional().describe("opaque cursor returned by the previous page"),
1126
- limit: z6.number().optional().describe("page size (default 50, max 200)"),
1127
- mode: z6.enum(["keyword", "semantic"]).optional().describe('default "keyword"')
1150
+ var searchOptionsSchema = z7.strictObject({
1151
+ cursor: z7.string().optional().describe("opaque cursor returned by the previous page"),
1152
+ limit: z7.number().optional().describe("page size (default 50, max 200)"),
1153
+ mode: z7.enum(["keyword", "semantic"]).optional().describe('default "keyword"')
1128
1154
  }).describe("pagination + search mode");
1129
1155
  var contextCommands = new HtbpCommandRegistry().register(
1130
1156
  "list",
1131
1157
  {
1132
1158
  h: "list entries directly under a path (shallow, paginated)",
1133
- inputSchema: z6.strictObject({
1134
- path: z6.string().optional().describe("entry path prefix inside the namespace"),
1159
+ inputSchema: z7.strictObject({
1160
+ path: z7.string().optional().describe("entry path prefix inside the namespace"),
1135
1161
  opts: HTBP_LIST_OPTIONS_SCHEMA.optional()
1136
1162
  }),
1137
1163
  returns: "Page<ContextEntryMeta>",
@@ -1143,8 +1169,8 @@ var contextCommands = new HtbpCommandRegistry().register(
1143
1169
  "get",
1144
1170
  {
1145
1171
  h: "read one entry with content (oversized content comes back as { $ref: <download URL> })",
1146
- inputSchema: z6.strictObject({
1147
- path: z6.string().describe("entry path inside the namespace")
1172
+ inputSchema: z7.strictObject({
1173
+ path: z7.string().describe("entry path inside the namespace")
1148
1174
  }),
1149
1175
  returns: "ContextEntry",
1150
1176
  scope: "read",
@@ -1155,8 +1181,8 @@ var contextCommands = new HtbpCommandRegistry().register(
1155
1181
  "write",
1156
1182
  {
1157
1183
  h: "create or fully replace an entry (idempotent upsert)",
1158
- inputSchema: z6.strictObject({
1159
- path: z6.string().describe("entry path inside the namespace"),
1184
+ inputSchema: z7.strictObject({
1185
+ path: z7.string().describe("entry path inside the namespace"),
1160
1186
  entry: entrySchema
1161
1187
  }),
1162
1188
  returns: "ContextEntryMeta",
@@ -1168,8 +1194,8 @@ var contextCommands = new HtbpCommandRegistry().register(
1168
1194
  "update",
1169
1195
  {
1170
1196
  h: "partially update content and/or metadata (shallow merge); not_found if the entry does not exist",
1171
- inputSchema: z6.strictObject({
1172
- path: z6.string().describe("entry path inside the namespace"),
1197
+ inputSchema: z7.strictObject({
1198
+ path: z7.string().describe("entry path inside the namespace"),
1173
1199
  patch: patchSchema
1174
1200
  }),
1175
1201
  returns: "ContextEntryMeta",
@@ -1181,8 +1207,8 @@ var contextCommands = new HtbpCommandRegistry().register(
1181
1207
  "delete",
1182
1208
  {
1183
1209
  h: "delete an entry (idempotent)",
1184
- inputSchema: z6.strictObject({
1185
- path: z6.string().describe("entry path inside the namespace")
1210
+ inputSchema: z7.strictObject({
1211
+ path: z7.string().describe("entry path inside the namespace")
1186
1212
  }),
1187
1213
  scope: "write",
1188
1214
  effect: "destructive"
@@ -1192,8 +1218,8 @@ var contextCommands = new HtbpCommandRegistry().register(
1192
1218
  "search",
1193
1219
  {
1194
1220
  h: "keyword search: substring match on entry paths and metadata values",
1195
- inputSchema: z6.strictObject({
1196
- query: z6.string().describe("substring to match"),
1221
+ inputSchema: z7.strictObject({
1222
+ query: z7.string().describe("substring to match"),
1197
1223
  opts: searchOptionsSchema.optional()
1198
1224
  }),
1199
1225
  returns: "Page<ContextEntryMeta>",
@@ -1207,10 +1233,10 @@ var contextCommands = new HtbpCommandRegistry().register(
1207
1233
  h: "create a short-lived, path-scoped direct-upload grant; persist the returned uri, not url",
1208
1234
  // 宿主专属扩展:仅在底层具备直传签名能力时由宿主装配,不进基础动词表。
1209
1235
  hostOnly: true,
1210
- inputSchema: z6.strictObject({
1211
- path: z6.string().describe("target entry path inside the namespace"),
1212
- contentType: z6.string().describe("media type signed into the PUT request"),
1213
- overwrite: z6.boolean().optional().describe(
1236
+ inputSchema: z7.strictObject({
1237
+ path: z7.string().describe("target entry path inside the namespace"),
1238
+ contentType: z7.string().describe("media type signed into the PUT request"),
1239
+ overwrite: z7.boolean().optional().describe(
1214
1240
  "allow replacing an existing object; default false"
1215
1241
  )
1216
1242
  }),
@@ -1279,10 +1305,11 @@ function contextCapabilitiesOf(provider) {
1279
1305
  }
1280
1306
 
1281
1307
  // ../core/src/plugin/contract.ts
1282
- var PLUGIN_PROFILES = ["tools/v1", "context/v1"];
1308
+ var PLUGIN_PROFILES = ["tools/v1", "context/v1", "events/v1"];
1283
1309
  var NODE_KIND_BY_PROFILE2 = {
1284
1310
  "tools/v1": "tool",
1285
- "context/v1": "context"
1311
+ "context/v1": "context",
1312
+ "events/v1": "topic"
1286
1313
  };
1287
1314
  var OPTIONAL_METHOD_BY_CAPABILITY = {
1288
1315
  search: "search",
@@ -1298,29 +1325,30 @@ function optionalMethodsForCapabilities(capabilities) {
1298
1325
  return methods;
1299
1326
  }
1300
1327
  var EXPORT_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
1301
- var exportAuthSchema = z7.discriminatedUnion("kind", [
1302
- z7.object({ kind: z7.literal("none") }),
1303
- z7.object({
1304
- kind: z7.literal("single"),
1305
- description: z7.string().optional(),
1306
- label: z7.string().optional(),
1307
- required: z7.boolean().optional()
1328
+ var exportAuthSchema = z8.discriminatedUnion("kind", [
1329
+ z8.object({ kind: z8.literal("none") }),
1330
+ z8.object({
1331
+ kind: z8.literal("single"),
1332
+ description: z8.string().optional(),
1333
+ label: z8.string().optional(),
1334
+ required: z8.boolean().optional()
1308
1335
  })
1309
1336
  ]);
1310
- var exportSchema = z7.object({
1311
- id: z7.string().regex(EXPORT_ID_RE, "export id \u987B\u4E3A [A-Za-z0-9._-] \u4E14\u4E0D\u4EE5\u6807\u70B9\u5F00\u5934"),
1312
- profile: z7.enum(PLUGIN_PROFILES),
1313
- description: z7.string().optional(),
1337
+ var exportSchema = z8.object({
1338
+ id: z8.string().regex(EXPORT_ID_RE, "export id \u987B\u4E3A [A-Za-z0-9._-] \u4E14\u4E0D\u4EE5\u6807\u70B9\u5F00\u5934"),
1339
+ profile: z8.enum(PLUGIN_PROFILES),
1340
+ eventSource: eventSourceSchema.optional(),
1341
+ description: z8.string().optional(),
1314
1342
  /** context/v1:实际提供的动词;tools/v1 由运行时 List 发现,可省。 */
1315
- methods: z7.array(z7.string()).optional(),
1316
- capabilities: z7.array(z7.string()).optional(),
1343
+ methods: z8.array(z8.string()).optional(),
1344
+ capabilities: z8.array(z8.string()).optional(),
1317
1345
  /** export 的单值/无凭证声明;多字段与 OAuth 继续由各自字段表达。 */
1318
1346
  auth: exportAuthSchema.optional(),
1319
1347
  /**
1320
1348
  * tools/v1 可选:一个**只读、零副作用、无必填入参**的工具名,平台在挂载时拿它做一次
1321
1349
  * 真实调用来验证 `authRef` 指向的凭证可用(见 `credentialProbe` 的类型注释)。
1322
1350
  */
1323
- credentialProbe: z7.string().optional(),
1351
+ credentialProbe: z8.string().optional(),
1324
1352
  /**
1325
1353
  * 多字段凭证的字段声明(tools/v1)。声明了它,平台就知道该 secret 存的是一个 JSON
1326
1354
  * 对象而非单值,并在挂载时校验字段齐全 —— 见 `credentialFields` 的类型注释。
@@ -1330,29 +1358,29 @@ var exportSchema = z7.object({
1330
1358
  * `POST /<path>/~authorize` 发起、回调兑换、调用时自动刷新,插件只拿到 access token。
1331
1359
  */
1332
1360
  oauth: pluginOAuthSchema.optional(),
1333
- credentialFields: z7.array(z7.object({
1334
- key: z7.string().regex(/^[A-Za-z_][\w]*$/, "\u5B57\u6BB5\u540D\u987B\u4E3A\u5408\u6CD5\u6807\u8BC6\u7B26"),
1335
- label: z7.string().optional(),
1336
- description: z7.string().optional(),
1337
- required: z7.boolean().optional(),
1361
+ credentialFields: z8.array(z8.object({
1362
+ key: z8.string().regex(/^[A-Za-z_][\w]*$/, "\u5B57\u6BB5\u540D\u987B\u4E3A\u5408\u6CD5\u6807\u8BC6\u7B26"),
1363
+ label: z8.string().optional(),
1364
+ description: z8.string().optional(),
1365
+ required: z8.boolean().optional(),
1338
1366
  /** 敏感字段:管理面不回显、日志不打印。缺省按敏感处理(fail safe)。 */
1339
- secret: z7.boolean().optional()
1367
+ secret: z8.boolean().optional()
1340
1368
  })).min(1).optional(),
1341
1369
  /**
1342
1370
  * 非凭证的挂载配置字段(如 baseUrl / instanceUrl / region)。声明了它,平台就知道
1343
1371
  * 该 export 挂载时还需要哪些 `providerConfig`,管理面据此渲染带标签的输入框而不是让
1344
1372
  * 用户对着一个自由 k=v 框猜 —— 见 `mountConfigFields` 的类型注释。
1345
1373
  */
1346
- mountConfigFields: z7.array(z7.object({
1347
- key: z7.string().regex(/^[A-Za-z_][\w]*$/, "\u5B57\u6BB5\u540D\u987B\u4E3A\u5408\u6CD5\u6807\u8BC6\u7B26"),
1348
- label: z7.string().optional(),
1349
- description: z7.string().optional(),
1350
- required: z7.boolean().optional()
1374
+ mountConfigFields: z8.array(z8.object({
1375
+ key: z8.string().regex(/^[A-Za-z_][\w]*$/, "\u5B57\u6BB5\u540D\u987B\u4E3A\u5408\u6CD5\u6807\u8BC6\u7B26"),
1376
+ label: z8.string().optional(),
1377
+ description: z8.string().optional(),
1378
+ required: z8.boolean().optional()
1351
1379
  })).min(1).optional()
1352
1380
  });
1353
- var describeSchema = z7.object({
1354
- protocolVersion: z7.string().min(1),
1355
- exports: z7.array(exportSchema).min(1, "\u81F3\u5C11\u58F0\u660E\u4E00\u4E2A export")
1381
+ var describeSchema = z8.object({
1382
+ protocolVersion: z8.string().min(1),
1383
+ exports: z8.array(exportSchema).min(1, "\u81F3\u5C11\u58F0\u660E\u4E00\u4E2A export")
1356
1384
  });
1357
1385
  function validatePluginContract(input) {
1358
1386
  const { manifest } = input;
@@ -1453,6 +1481,15 @@ function validatePluginContract(input) {
1453
1481
  keys.add(field.key);
1454
1482
  }
1455
1483
  }
1484
+ if (exported.profile === "events/v1") {
1485
+ if (!exported.eventSource || exported.auth?.kind !== "single" || !exported.auth.required) {
1486
+ throw new TBError("invalid_argument", "event sources require a verifier credential and declared event types");
1487
+ }
1488
+ const names = exported.eventSource.types.map((item) => item.type);
1489
+ if (new Set(names).size !== names.length) throw new TBError("invalid_argument", "duplicate event type");
1490
+ } else if (exported.eventSource) {
1491
+ throw new TBError("invalid_argument", "eventSource requires events/v1");
1492
+ }
1456
1493
  if (exported.profile === "context/v1") {
1457
1494
  const known = new Set(CONTEXT_METHODS);
1458
1495
  const unknown = (exported.methods ?? []).filter((m) => !known.has(m));
@@ -1511,7 +1548,7 @@ function resolvePluginExport(describe, opts) {
1511
1548
  }
1512
1549
 
1513
1550
  // ../core/src/plugin/manifest.ts
1514
- import { z as z8 } from "zod";
1551
+ import { z as z9 } from "zod";
1515
1552
 
1516
1553
  // ../core/src/tool/upstreamError.ts
1517
1554
  function normalizeUpstreamError(e) {
@@ -1546,19 +1583,19 @@ function assertSecureUrl(url, allowInsecure) {
1546
1583
  var PLUGIN_PROTOCOL_VERSION = "plugin/v2";
1547
1584
  var ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
1548
1585
  var BINDING_RE = /^binding:[A-Za-z0-9_-]+$/;
1549
- var authSchema = z8.discriminatedUnion("kind", [
1550
- z8.object({ kind: z8.literal("platform-token") }),
1551
- z8.object({ kind: z8.literal("bearer"), secretRef: z8.string().min(1) })
1586
+ var authSchema = z9.discriminatedUnion("kind", [
1587
+ z9.object({ kind: z9.literal("platform-token") }),
1588
+ z9.object({ kind: z9.literal("bearer"), secretRef: z9.string().min(1) })
1552
1589
  ]);
1553
- var manifestSchema = z8.object({
1554
- id: z8.string().regex(ID_RE, "id \u987B\u4E3A path-segment \u5B89\u5168\u5B57\u7B26([A-Za-z0-9._-],\u4E0D\u4EE5\u6807\u70B9\u5F00\u5934)"),
1555
- protocolVersion: z8.string().refine((v) => v === PLUGIN_PROTOCOL_VERSION, {
1590
+ var manifestSchema = z9.object({
1591
+ id: z9.string().regex(ID_RE, "id \u987B\u4E3A path-segment \u5B89\u5168\u5B57\u7B26([A-Za-z0-9._-],\u4E0D\u4EE5\u6807\u70B9\u5F00\u5934)"),
1592
+ protocolVersion: z9.string().refine((v) => v === PLUGIN_PROTOCOL_VERSION, {
1556
1593
  error: `protocolVersion \u987B\u4E3A '${PLUGIN_PROTOCOL_VERSION}'`
1557
1594
  }),
1558
- endpoint: z8.string().min(1),
1595
+ endpoint: z9.string().min(1),
1559
1596
  auth: authSchema,
1560
- healthPath: z8.string().regex(/^\//, "healthPath \u987B\u4EE5 '/' \u5F00\u5934"),
1561
- enabled: z8.boolean()
1597
+ healthPath: z9.string().regex(/^\//, "healthPath \u987B\u4EE5 '/' \u5F00\u5934"),
1598
+ enabled: z9.boolean()
1562
1599
  }).strict();
1563
1600
  function parsePluginManifest(value, opts = {}) {
1564
1601
  const parsed = manifestSchema.safeParse(value);
@@ -1580,169 +1617,798 @@ function parsePluginManifest(value, opts = {}) {
1580
1617
  return manifest;
1581
1618
  }
1582
1619
 
1583
- // ../core/src/builtin/plugin.ts
1584
- var DESCRIPTION2 = "Plugin registry: register / probe external tool & context providers, then mount them via system/registry (admin only)";
1585
- function pluginTokenSecretName(id) {
1586
- return `plugin-token:${id}`;
1620
+ // ../core/src/plugin/catalog.ts
1621
+ function canonicalCatalogJson(value) {
1622
+ const normalize = (input) => {
1623
+ if (Array.isArray(input)) return input.map(normalize);
1624
+ if (input === null || typeof input !== "object") return input;
1625
+ const source2 = input;
1626
+ const out = {};
1627
+ for (const key of Object.keys(source2).sort()) {
1628
+ if (source2[key] !== void 0) out[key] = normalize(source2[key]);
1629
+ }
1630
+ return out;
1631
+ };
1632
+ return JSON.stringify(normalize(value));
1587
1633
  }
1588
- function projectManifest(record) {
1589
- return omit(record, "tokenSkId");
1634
+ async function catalogDigest(value) {
1635
+ const bytes2 = new TextEncoder().encode(canonicalCatalogJson(value));
1636
+ const hash = await crypto.subtle.digest("SHA-256", bytes2);
1637
+ return [...new Uint8Array(hash)].map((b) => b.toString(16).padStart(2, "0")).join("");
1590
1638
  }
1591
- var pluginAuthSchema = z9.discriminatedUnion("kind", [
1592
- z9.strictObject({ kind: z9.literal("platform-token") }),
1593
- z9.strictObject({ kind: z9.literal("bearer"), secretRef: z9.string().min(1) })
1594
- ]).describe(
1595
- '{ kind: "platform-token" } \u2014 gateway mints the token (shown once in the response); or { kind: "bearer", secretRef }'
1639
+ async function catalogSetDigest(catalog) {
1640
+ const pairs = Object.keys(catalog).sort().map((id) => ({ id, digest: catalog[id].digest }));
1641
+ return await catalogDigest(pairs);
1642
+ }
1643
+ function builtinManifestOf(id) {
1644
+ return {
1645
+ id,
1646
+ protocolVersion: "plugin/v2",
1647
+ endpoint: `binding:${id}`,
1648
+ auth: { kind: "platform-token" },
1649
+ healthPath: "/healthz",
1650
+ enabled: true
1651
+ };
1652
+ }
1653
+ function resolveBuiltinExport(catalog, id, nodeKind, what, exportId) {
1654
+ const entry = catalog[id];
1655
+ if (entry === void 0) {
1656
+ throw new TBError("invalid_argument", `\u672A\u77E5 ${what} provider:'${id}'`);
1657
+ }
1658
+ const chosen = resolvePluginExport(entry.describe, {
1659
+ nodeKind,
1660
+ pluginId: id,
1661
+ ...exportId !== void 0 ? { exportId } : {}
1662
+ });
1663
+ return { manifest: builtinManifestOf(id), export: chosen, source: "builtin" };
1664
+ }
1665
+ async function resolveExternalExport(store, id, nodeKind, what, exportId) {
1666
+ const manifest = await store.get(KEY_PLUGIN + id);
1667
+ if (manifest === null) {
1668
+ throw new TBError("invalid_argument", `\u672A\u77E5 ${what} provider:'${id}'`);
1669
+ }
1670
+ if (manifest.enabled !== true) {
1671
+ throw new TBError("invalid_argument", `plugin '${id}' \u5DF2\u7981\u7528`);
1672
+ }
1673
+ const describe = manifest.describe ?? await store.get(KEY_PLUGIN_META + id);
1674
+ if (describe === null) {
1675
+ throw new TBError("invalid_argument", `plugin '${id}' \u7F3A\u5C11 ~describe \u7F13\u5B58,\u8BF7\u91CD\u65B0\u6CE8\u518C`);
1676
+ }
1677
+ const chosen = resolvePluginExport(describe, {
1678
+ nodeKind,
1679
+ pluginId: id,
1680
+ ...exportId !== void 0 ? { exportId } : {}
1681
+ });
1682
+ return { manifest, export: chosen, source: "external" };
1683
+ }
1684
+ async function resolveIntegration(store, catalog, id, nodeKind, what, exportId) {
1685
+ const manifest = await store.get(KEY_PLUGIN + id);
1686
+ if (manifest !== null) {
1687
+ return await resolveExternalExport(store, id, nodeKind, what, exportId);
1688
+ }
1689
+ return resolveBuiltinExport(catalog, id, nodeKind, what, exportId);
1690
+ }
1691
+
1692
+ // ../core/src/plugin/release.ts
1693
+ var pluginImageSchema = z10.string().max(512).regex(
1694
+ /^[a-z0-9]+(?:[.-][a-z0-9]+)*(?::[0-9]+)?\/(?:[a-z0-9]+(?:[._-][a-z0-9]+)*\/)*[a-z0-9]+(?:[._-][a-z0-9]+)*@sha256:[a-f0-9]{64}$/,
1695
+ "expected registry/repository@sha256:<digest>"
1596
1696
  );
1597
- var pluginIdSchema = z9.string().min(1).describe("plugin id");
1598
- var manifestFields = {
1599
- id: z9.string().min(1).describe("unique plugin id"),
1600
- protocolVersion: z9.literal("plugin/v2").describe(
1601
- "transport protocol version; what the plugin provides is declared by its /~describe exports"
1602
- ),
1603
- endpoint: z9.string().min(1).describe("https base URL of the plugin service"),
1604
- auth: pluginAuthSchema,
1605
- healthPath: z9.string().min(1).describe('GET probe path, e.g. "/healthz"'),
1606
- enabled: z9.boolean()
1697
+ var pluginVersionPattern = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|[\da-zA-Z-]*[a-zA-Z-][\da-zA-Z-]*)(?:\.(?:0|[1-9]\d*|[\da-zA-Z-]*[a-zA-Z-][\da-zA-Z-]*))*)?(?:\+[\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*)?$/;
1698
+ var fields = {
1699
+ schemaVersion: z10.literal("tb-plugin-release/v1"),
1700
+ id: z10.string().max(128).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),
1701
+ version: z10.string().max(128).regex(pluginVersionPattern),
1702
+ healthPath: z10.string().max(256).regex(/^\/[a-zA-Z0-9_./~-]*$/).default("/healthz")
1607
1703
  };
1608
- var pluginWriteSchema = z9.strictObject(manifestFields);
1609
- var pluginPatchSchema = z9.strictObject({
1610
- id: manifestFields.id.optional(),
1611
- protocolVersion: manifestFields.protocolVersion.optional(),
1612
- endpoint: manifestFields.endpoint.optional(),
1613
- auth: manifestFields.auth.optional(),
1614
- healthPath: manifestFields.healthPath.optional(),
1615
- enabled: manifestFields.enabled.optional()
1616
- }).describe("fields to change; same shape as write, all optional");
1617
- var COMMANDS2 = new BuiltinCommandRegistry("plugin", DESCRIPTION2).register(
1618
- "list",
1619
- {
1620
- h: "list registered plugins (pluginToken never returned)",
1621
- inputSchema: z9.strictObject({ opts: HTBP_LIST_OPTIONS_SCHEMA.optional() }),
1622
- returns: "Page<PluginView> \u2014 manifest + the exports declared by its /~describe",
1623
- scope: "admin"
1624
- },
1625
- ({ opts }, { deps }) => deps.list(opts)
1626
- ).register(
1627
- "get",
1628
- {
1629
- h: "fetch one plugin manifest by id",
1630
- inputSchema: z9.strictObject({ id: pluginIdSchema }),
1631
- returns: "PluginView \u2014 manifest + the exports declared by its /~describe",
1632
- scope: "admin"
1633
- },
1634
- ({ id }, { deps }) => deps.get(id)
1635
- ).register(
1636
- "write",
1637
- {
1638
- h: "register a plugin: probes health and validates its /~describe exports before accepting; then mount an export via system/registry (config.provider = plugin id, config.export = export id)",
1639
- inputSchema: pluginWriteSchema,
1640
- returns: "PluginView + pluginToken shown once (platform-token only)",
1641
- scope: "admin"
1642
- },
1643
- (input, { deps }) => deps.write(input)
1644
- ).register(
1645
- "update",
1646
- {
1647
- h: "patch a registration; endpoint changes re-probe and re-validate the exports before applying",
1648
- inputSchema: z9.strictObject({
1649
- id: pluginIdSchema,
1650
- patch: pluginPatchSchema
1651
- }),
1652
- returns: "PluginView \u2014 pluginToken shown once if auth switched to platform-token",
1653
- scope: "admin"
1654
- },
1655
- ({ id, patch }, { deps }) => deps.update(id, patch)
1656
- ).register(
1657
- "delete",
1658
- {
1659
- h: "unregister a plugin and revoke its platform token; mounted nodes referencing it stop working",
1660
- inputSchema: z9.strictObject({ id: pluginIdSchema }),
1661
- returns: "void",
1662
- scope: "admin"
1663
- },
1664
- async ({ id }, { deps }) => {
1665
- await deps.remove(id);
1666
- return VOID_ACK;
1704
+ var releaseSchema = z10.union([
1705
+ z10.strictObject({ ...fields, endpoint: z10.string().max(2048) }),
1706
+ z10.strictObject({ ...fields, image: pluginImageSchema })
1707
+ ]);
1708
+ function httpsReleaseUrl(value) {
1709
+ try {
1710
+ const url = new URL2(value);
1711
+ if (value.startsWith("https://") && url.protocol === "https:" && !url.username && !url.password && !/[?#\\\s]/.test(value))
1712
+ return url.toString();
1713
+ } catch {
1667
1714
  }
1668
- ).register(
1669
- "health",
1670
- {
1671
- h: "probe the plugin health endpoint now",
1672
- inputSchema: z9.strictObject({ id: pluginIdSchema }),
1673
- returns: "{ id, healthy, checkedAt }",
1674
- scope: "admin"
1675
- },
1676
- ({ id }, { deps }) => deps.health(id)
1677
- );
1715
+ throw new TBError("invalid_argument", "expected a credential-free HTTPS URL without query or fragment");
1716
+ }
1717
+ function parsePluginRelease(input) {
1718
+ const result = releaseSchema.safeParse(input);
1719
+ if (!result.success) throw new TBError("invalid_argument", "invalid tb-plugin-release/v1 manifest");
1720
+ if ("endpoint" in result.data) result.data.endpoint = httpsReleaseUrl(result.data.endpoint).replace(/\/+$/, "");
1721
+ return result.data;
1722
+ }
1723
+ async function releaseReceipt(source2, { release, resolvedSource }, approvedBy) {
1724
+ return {
1725
+ source: source2,
1726
+ resolvedSource,
1727
+ approvedBy,
1728
+ version: release.version,
1729
+ digest: "sha256:" + await sha256Hex(canonicalCatalogJson(release)),
1730
+ ..."image" in release ? { image: release.image } : {}
1731
+ };
1732
+ }
1733
+
1734
+ // ../core/src/tree/registry.ts
1678
1735
  function clampLimit2(limit) {
1679
1736
  if (limit === void 0 || limit < 1) return LIST_LIMIT_DEFAULT;
1680
1737
  return limit > LIST_LIMIT_MAX ? LIST_LIMIT_MAX : limit;
1681
1738
  }
1682
- function createPluginModule(deps) {
1683
- const { store, sk, secrets, now } = deps;
1684
- async function read(id) {
1685
- return await store.get(KEY_PLUGIN + id);
1739
+ function assertKindConfig(node) {
1740
+ if (node.config === void 0) return;
1741
+ if (node.config.kind !== node.kind) {
1742
+ throw new TBError(
1743
+ "invalid_argument",
1744
+ `kind='${node.kind}' \u4E0E config.kind='${node.config.kind}' \u4E0D\u4E00\u81F4`
1745
+ );
1686
1746
  }
1687
- async function require2(id) {
1688
- const record = await read(id);
1689
- if (!record) throw new TBError("not_found", `plugin '${id}' not found`);
1690
- return record;
1747
+ }
1748
+ function byPath(a, b) {
1749
+ return a.path < b.path ? -1 : a.path > b.path ? 1 : 0;
1750
+ }
1751
+ var NodeRegistryStore = class {
1752
+ store;
1753
+ constructor(store) {
1754
+ this.store = store;
1691
1755
  }
1692
- async function view(record) {
1693
- const describe = await store.get(KEY_PLUGIN_META + record.id);
1694
- if (describe === null) {
1695
- throw new TBError(
1696
- "unavailable",
1697
- `plugin '${record.id}' \u7F3A\u5C11 ~describe \u7F13\u5B58,\u8BF7\u91CD\u65B0\u6CE8\u518C`,
1698
- { retryable: false }
1699
- );
1700
- }
1701
- return { ...projectManifest(record), exports: describe.exports };
1756
+ keyOf(path) {
1757
+ return KEY_NODE + path;
1702
1758
  }
1703
- async function revokeToken(record) {
1704
- if (record.tokenSkId !== void 0) await sk.delete(record.tokenSkId);
1705
- try {
1706
- await secrets.delete(pluginTokenSecretName(record.id));
1707
- } catch {
1708
- }
1759
+ async read(path) {
1760
+ return await this.store.get(this.keyOf(path));
1709
1761
  }
1710
- async function probeAndRecord(manifest) {
1711
- const result = await deps.probe(manifest);
1712
- const prev = await store.get(KEY_PLUGIN_HEALTH + manifest.id);
1713
- const record = {
1714
- healthy: result.healthy,
1715
- checkedAt: now(),
1716
- consecutiveFailures: result.healthy ? 0 : (prev?.consecutiveFailures ?? 0) + 1
1717
- };
1718
- await store.put(KEY_PLUGIN_HEALTH + manifest.id, record);
1719
- return record;
1762
+ /** 翻页取尽 node:* 全量。 */
1763
+ async scanAll() {
1764
+ return this.scanPrefix(KEY_NODE);
1720
1765
  }
1721
- async function write(args) {
1722
- const manifest = parsePluginManifest(args, {
1723
- allowInsecureHttp: deps.allowInsecureHttp ?? false
1724
- });
1725
- const probed = await deps.probe(manifest);
1726
- if (!probed.healthy) {
1727
- throw new TBError(
1728
- "unavailable",
1729
- `plugin '${manifest.id}' \u63A2\u6D3B\u5931\u8D25,\u62D2\u7EDD\u6CE8\u518C${probed.detail !== void 0 ? `:${probed.detail}` : ""}`,
1730
- { retryable: true }
1766
+ /**
1767
+ * 翻页扫描给定 KV 键前缀下的所有 TreeNode。
1768
+ *
1769
+ * 只扫子树(前缀限定),不再对全树做内存过滤——避免 children/hasChildren/subtree 的
1770
+ * O(N²)(每层各扫全树)。`opts.limit` 传给底层 `store.list` 以小步取(hasChildren 短路用)。
1771
+ *
1772
+ * **Workers 查询预算约束**:D1StateStore.list 是单条 SQL 直接带值返回(ADR-001 迁 D1 后
1773
+ * 不再逐键 get),每页只花一次 D1 查询;但 Workers 单请求仍有查询/子请求预算,深翻页的
1774
+ * 页数应远小于预算——当前树规模小(节点数十级)可接受。
1775
+ */
1776
+ async scanPrefix(keyPrefix, opts) {
1777
+ const out = [];
1778
+ let cursor2;
1779
+ do {
1780
+ const limit = opts?.maxNodes === void 0 ? opts?.limit ?? LIST_LIMIT_MAX : Math.min(
1781
+ opts.limit ?? LIST_LIMIT_MAX,
1782
+ opts.maxNodes - out.length + (opts.truncate === true ? 0 : 1)
1731
1783
  );
1732
- }
1733
- const contract = await deps.fetchContract(manifest);
1734
- const describe = validatePluginContract({ manifest, describe: contract.describe });
1735
- const existing = await read(manifest.id);
1736
- if (existing) await revokeToken(existing);
1737
- let pluginToken;
1738
- let tokenSkId;
1739
- if (manifest.auth.kind === "platform-token") {
1740
- const minted = await sk.write({ owner: `plugin:${manifest.id}`, scopes: [] }, now());
1741
- await secrets.set(pluginTokenSecretName(manifest.id), minted.secret, now());
1742
- pluginToken = minted.secret;
1743
- tokenSkId = minted.key.id;
1744
- }
1745
- await store.put(KEY_PLUGIN_META + manifest.id, describe);
1784
+ if (limit < 1) return out;
1785
+ const page = await this.store.list(keyPrefix, {
1786
+ limit,
1787
+ ...cursor2 !== void 0 ? { cursor: cursor2 } : {}
1788
+ });
1789
+ for (const { value } of page.items) out.push(value);
1790
+ if (opts?.truncate === true && out.length >= (opts.maxNodes ?? Number.POSITIVE_INFINITY)) {
1791
+ return out;
1792
+ }
1793
+ if (opts?.maxNodes !== void 0 && out.length > opts.maxNodes) {
1794
+ throw new TBError(
1795
+ "rate_limited",
1796
+ `registry scan \u6700\u591A\u8BFB\u53D6 ${opts.maxNodes} \u4E2A\u8282\u70B9`
1797
+ );
1798
+ }
1799
+ cursor2 = page.cursor;
1800
+ } while (cursor2);
1801
+ return out;
1802
+ }
1803
+ /** KV 前缀:某路径的子树(含中间 directory)= `node:<path>/`;根('')= `node:`。 */
1804
+ subtreePrefix(norm) {
1805
+ return norm === "" ? KEY_NODE : `${KEY_NODE}${norm}/`;
1806
+ }
1807
+ async hasChildren(path) {
1808
+ const norm = normalizePath(path);
1809
+ const page = await this.store.list(this.subtreePrefix(norm), { limit: 1 });
1810
+ return page.items.length > 0;
1811
+ }
1812
+ /** 取单个;不存在 → not_found。路径大小写不敏感(规范化为小写后查)。 */
1813
+ async get(path) {
1814
+ const norm = canonicalizePath(path);
1815
+ const node = await this.read(norm);
1816
+ if (!node) throw new TBError("not_found", `\u8282\u70B9\u4E0D\u5B58\u5728:'${norm}'`);
1817
+ return node;
1818
+ }
1819
+ /** 批量取节点;路径先规范化(小写)去重,不存在的节点不进入返回 Map。 */
1820
+ async getMany(paths) {
1821
+ const canonical = [...new Set(paths.map((path) => canonicalizePath(path)))];
1822
+ const values = await this.store.getMany(canonical.map((path) => this.keyOf(path)));
1823
+ const out = /* @__PURE__ */ new Map();
1824
+ for (const path of canonical) {
1825
+ const value = values.get(this.keyOf(path));
1826
+ if (value !== void 0) out.set(path, value);
1827
+ }
1828
+ return out;
1829
+ }
1830
+ /**
1831
+ * 枚举 `prefix` 之下(含 prefix 自身,按段前缀匹配)的节点,分页。
1832
+ * 无 prefix = 全树。cursor 为上一页末节点的 path。
1833
+ */
1834
+ async list(prefix, opts) {
1835
+ const normPrefix = prefix === void 0 ? "" : canonicalizePath(prefix);
1836
+ const limit = clampLimit2(opts?.limit);
1837
+ const all = (await this.scanAll()).filter((n) => isPrefixOf(normPrefix, n.path)).sort(byPath);
1838
+ const cursor2 = opts?.cursor;
1839
+ const start = cursor2 ? all.findIndex((n) => n.path === cursor2) + 1 : 0;
1840
+ const items = all.slice(start, start + limit);
1841
+ const hasMore = start + limit < all.length;
1842
+ return {
1843
+ items,
1844
+ cursor: hasMore ? items[items.length - 1]?.path : void 0
1845
+ };
1846
+ }
1847
+ /** 直接子节点(段深恰好 +1);~help 列子节点用。只扫子树前缀,不扫全树。 */
1848
+ async children(path) {
1849
+ const norm = canonicalizePath(path);
1850
+ const depth = segments(norm).length;
1851
+ const sub = await this.scanPrefix(this.subtreePrefix(norm));
1852
+ return sub.filter((n) => segments(n.path).length === depth + 1).sort(byPath);
1853
+ }
1854
+ /**
1855
+ * 一次性取整棵子树的节点数组(含 `path` 自身 + 全部后代),按 path 排序。
1856
+ * 供 `~tree` 建树一次读入内存(而非每层递归各扫一遍)。根('')= 全树。
1857
+ * 不存在的根返回空数组(调用方自行判 not_found)。
1858
+ */
1859
+ async subtree(path, opts) {
1860
+ const norm = canonicalizePath(path);
1861
+ if (opts?.maxNodes !== void 0 && (!Number.isInteger(opts.maxNodes) || opts.maxNodes < 1)) {
1862
+ throw new TBError("invalid_argument", "maxNodes \u5FC5\u987B\u662F\u6B63\u6574\u6570");
1863
+ }
1864
+ const descendants = await this.scanPrefix(this.subtreePrefix(norm), opts);
1865
+ if (norm === "") return descendants.sort(byPath);
1866
+ const self = await this.read(norm);
1867
+ const all = self ? [self, ...descendants] : descendants;
1868
+ if (opts?.maxNodes !== void 0 && all.length > opts.maxNodes) {
1869
+ throw new TBError(
1870
+ "rate_limited",
1871
+ `registry scan \u6700\u591A\u8BFB\u53D6 ${opts.maxNodes} \u4E2A\u8282\u70B9`
1872
+ );
1873
+ }
1874
+ return all.sort(byPath);
1875
+ }
1876
+ /**
1877
+ * 取按 key 确定排序的有界根快照,并显式报告是否截断。派生索引用 truncated
1878
+ * 选择保留 last-known-good,不把 canonical registry 的规模限制反向施加到主数据面。
1879
+ */
1880
+ async rootSnapshot(maxNodes) {
1881
+ if (!Number.isInteger(maxNodes) || maxNodes < 1) {
1882
+ throw new TBError("invalid_argument", "maxNodes \u5FC5\u987B\u662F\u6B63\u6574\u6570");
1883
+ }
1884
+ const items = await this.scanPrefix(KEY_NODE, { maxNodes: maxNodes + 1, truncate: true });
1885
+ return {
1886
+ items: items.slice(0, maxNodes).sort(byPath),
1887
+ truncated: items.length > maxNodes
1888
+ };
1889
+ }
1890
+ /**
1891
+ * 幂等 upsert:
1892
+ * - 校验路径(空/空段/保留段)与 kind↔config 一致性;
1893
+ * - 自动物化 parentPaths 中缺失的中间 directory(registeredBy=system:auto,description='');
1894
+ * 已存在的祖先(无论显式或自动)一律不动;
1895
+ * - createdAt 保留原值(存在时)否则取 now;updatedAt 始终刷新为 now;
1896
+ * - registeredBy 由调用方注入(device 节点由 Gateway 代写)。
1897
+ *
1898
+ * conflict(覆盖他人节点)判定在网关注册路径层,不在此——本层是幂等 upsert。
1899
+ */
1900
+ async write(node, registeredBy, now, opts = {}) {
1901
+ const invalid2 = validatePath(node.path);
1902
+ if (invalid2) throw invalid2;
1903
+ const path = canonicalizePath(node.path);
1904
+ assertKindConfig(node);
1905
+ for (const parent of parentPaths(path)) {
1906
+ if (!await this.read(parent)) {
1907
+ const dir = {
1908
+ path: parent,
1909
+ kind: "directory",
1910
+ description: "",
1911
+ registeredBy: SYSTEM_AUTO,
1912
+ createdAt: now,
1913
+ updatedAt: now
1914
+ };
1915
+ if (this.store.putIfAbsent) await this.store.putIfAbsent(this.keyOf(parent), dir);
1916
+ else await this.store.put(this.keyOf(parent), dir);
1917
+ }
1918
+ }
1919
+ const existing = await this.read(path);
1920
+ const full = {
1921
+ path,
1922
+ kind: node.kind,
1923
+ description: node.description,
1924
+ ...node.config !== void 0 ? { config: node.config } : {},
1925
+ ...node.virtualize !== void 0 ? { virtualize: node.virtualize } : {},
1926
+ ...opts.deviceId !== void 0 ? { deviceId: opts.deviceId } : {},
1927
+ ...opts.deviceEnvironment !== void 0 ? { deviceEnvironment: opts.deviceEnvironment } : {},
1928
+ ...opts.deviceReportedAt !== void 0 ? { deviceReportedAt: opts.deviceReportedAt } : {},
1929
+ ...opts.online !== void 0 ? { online: opts.online } : {},
1930
+ ...opts.lastSeenAt !== void 0 ? { lastSeenAt: opts.lastSeenAt } : {},
1931
+ registeredBy,
1932
+ createdAt: existing?.createdAt ?? now,
1933
+ updatedAt: now
1934
+ };
1935
+ await this.store.put(this.keyOf(path), full);
1936
+ return full;
1937
+ }
1938
+ async editExisting(path, edit) {
1939
+ const key = this.keyOf(path);
1940
+ if (this.store.updateNode) return this.store.updateNode(key, edit);
1941
+ const node = await this.read(path);
1942
+ if (!node) return null;
1943
+ const next = edit(node);
1944
+ await this.store.put(key, next);
1945
+ return next;
1946
+ }
1947
+ /** Apply partial configuration edits to the same row that carries device presence. */
1948
+ async update(path, patch, now) {
1949
+ const norm = canonicalizePath(path);
1950
+ if (patch.path !== void 0 && canonicalizePath(patch.path) !== norm) {
1951
+ throw new TBError("invalid_argument", "path \u4E0D\u53EF\u901A\u8FC7 Update \u53D8\u66F4");
1952
+ }
1953
+ const updated = await this.editExisting(norm, (current) => {
1954
+ const next = {
1955
+ ...current,
1956
+ ...patch.kind !== void 0 ? { kind: patch.kind } : {},
1957
+ ...patch.description !== void 0 ? { description: patch.description } : {},
1958
+ ...patch.config !== void 0 ? { config: patch.config } : {},
1959
+ ...patch.virtualize !== void 0 ? { virtualize: patch.virtualize } : {},
1960
+ updatedAt: now
1961
+ };
1962
+ assertKindConfig(next);
1963
+ return next;
1964
+ });
1965
+ if (!updated) throw new TBError("not_found", `\u8282\u70B9\u4E0D\u5B58\u5728:'${norm}'`);
1966
+ return updated;
1967
+ }
1968
+ async setOnline(path, online, now) {
1969
+ const norm = canonicalizePath(path);
1970
+ const updated = await this.editExisting(norm, (current) => ({
1971
+ ...current,
1972
+ online,
1973
+ updatedAt: now,
1974
+ ...online ? { lastSeenAt: now } : {}
1975
+ }));
1976
+ if (!updated) throw new TBError("not_found", `\u8282\u70B9\u4E0D\u5B58\u5728:'${norm}'`);
1977
+ return updated;
1978
+ }
1979
+ async touchSeen(path, now) {
1980
+ await this.editExisting(canonicalizePath(path), (current) => ({
1981
+ ...current,
1982
+ lastSeenAt: current.lastSeenAt && current.lastSeenAt > now ? current.lastSeenAt : now
1983
+ }));
1984
+ }
1985
+ /**
1986
+ * 卸载;不存在 → not_found。删除后自底向上级联回收:
1987
+ * 仅回收 registeredBy=system:auto 且再无子节点的 directory,遇显式节点/仍有子节点即停。
1988
+ *
1989
+ * 实现决策(待回写 docs):被删节点若仍有后代 → conflict
1990
+ * (不允许删除非空子树;显式 directory 同理)。
1991
+ */
1992
+ async delete(path) {
1993
+ const norm = canonicalizePath(path);
1994
+ const existing = await this.read(norm);
1995
+ if (!existing) throw new TBError("not_found", `\u8282\u70B9\u4E0D\u5B58\u5728:'${norm}'`);
1996
+ if (await this.hasChildren(norm)) {
1997
+ throw new TBError("conflict", `\u8282\u70B9 '${norm}' \u4ECD\u6709\u5B50\u8282\u70B9,\u4E0D\u5141\u8BB8\u5220\u9664\u975E\u7A7A\u5B50\u6811`);
1998
+ }
1999
+ await this.store.delete(this.keyOf(norm));
2000
+ for (const parent of [...parentPaths(norm)].reverse()) {
2001
+ const p = await this.read(parent);
2002
+ if (!p || p.registeredBy !== SYSTEM_AUTO || p.kind !== "directory") break;
2003
+ if (await this.hasChildren(parent)) break;
2004
+ await this.store.delete(this.keyOf(parent));
2005
+ }
2006
+ }
2007
+ /**
2008
+ * 设备回收专用:删除一个已知子树(含根与全部后代),再按普通 delete 规则回收自动目录。
2009
+ * 普通管理面仍使用 delete(),不允许误删非空子树。
2010
+ */
2011
+ async deleteSubtree(path) {
2012
+ const norm = canonicalizePath(path);
2013
+ const existing = await this.read(norm);
2014
+ if (!existing) throw new TBError("not_found", `\u8282\u70B9\u4E0D\u5B58\u5728:'${norm}'`);
2015
+ const descendants = await this.scanPrefix(this.subtreePrefix(norm));
2016
+ descendants.sort((a, b) => segments(b.path).length - segments(a.path).length || byPath(b, a));
2017
+ for (const n of descendants) await this.store.delete(this.keyOf(n.path));
2018
+ await this.store.delete(this.keyOf(norm));
2019
+ for (const parent of [...parentPaths(norm)].reverse()) {
2020
+ const p = await this.read(parent);
2021
+ if (!p || p.registeredBy !== SYSTEM_AUTO || p.kind !== "directory") break;
2022
+ if (await this.hasChildren(parent)) break;
2023
+ await this.store.delete(this.keyOf(parent));
2024
+ }
2025
+ }
2026
+ /**
2027
+ * 最长前缀匹配:返回命中节点与剩余段('/' 连接)。
2028
+ * 完全匹配 → rest=''。无任何匹配 → not_found。
2029
+ */
2030
+ async resolve(path) {
2031
+ const norm = canonicalizePath(path);
2032
+ const candidates = [norm, ...parentPaths(norm).reverse()];
2033
+ for (const cand of candidates) {
2034
+ const node = await this.read(cand);
2035
+ if (node) {
2036
+ const rest = segments(norm).slice(segments(cand).length).join("/");
2037
+ return { node, rest };
2038
+ }
2039
+ }
2040
+ throw new TBError("not_found", `\u65E0\u5339\u914D\u8282\u70B9:'${norm}'`);
2041
+ }
2042
+ };
2043
+
2044
+ // ../core/src/builtin/pluginDistribution.ts
2045
+ var source = z11.string().min(1).max(2048);
2046
+ var installInput = z11.strictObject({
2047
+ source,
2048
+ secretRef: z11.string().min(1).max(128).regex(/^[^:\s]+$/),
2049
+ origin: z11.string().max(2048).optional()
2050
+ });
2051
+ var previewInput = z11.strictObject({ id: z11.string().min(1), source: source.optional() });
2052
+ var upgradeInput = previewInput.extend({ candidateDigest: z11.string().regex(/^sha256:[0-9a-f]{64}$/).optional() });
2053
+ function approvedOrigin(url) {
2054
+ return new URL2(httpsReleaseUrl(url)).origin;
2055
+ }
2056
+ function manifestOf(record) {
2057
+ const { id, protocolVersion, enabled, endpoint, healthPath, auth } = record;
2058
+ return { id, protocolVersion, enabled, endpoint, healthPath, auth };
2059
+ }
2060
+ function createDistribution(deps) {
2061
+ async function load(source2) {
2062
+ if (!deps.resolveRelease || !deps.store.compareAndSwap)
2063
+ throw new TBError("unavailable", "this host does not support plugin distribution");
2064
+ return deps.resolveRelease(source2);
2065
+ }
2066
+ async function resolveCandidate(receipt, release, origin) {
2067
+ let endpoint;
2068
+ if ("image" in release) {
2069
+ if (!deps.prepareImage) throw new TBError("unavailable", "an administrator must configure the isolated plugin runner");
2070
+ endpoint = httpsReleaseUrl(await deps.prepareImage(release.id, release.image)).replace(/\/+$/, "");
2071
+ } else {
2072
+ endpoint = release.endpoint;
2073
+ const trusted = origin ?? (receipt.resolvedSource.startsWith("https://") ? receipt.resolvedSource : void 0);
2074
+ if (!trusted || approvedOrigin(trusted) !== approvedOrigin(endpoint))
2075
+ throw new TBError("invalid_argument", "hosted endpoint must match the approved HTTPS origin");
2076
+ }
2077
+ return { ...receipt, endpoint, healthPath: release.healthPath };
2078
+ }
2079
+ async function inspect(manifest, distribution) {
2080
+ if (!distribution.active.image && approvedOrigin(distribution.active.endpoint) !== distribution.origin)
2081
+ throw new TBError("conflict", "candidate endpoint does not match the installation origin");
2082
+ const candidate = { ...manifest, distribution, endpoint: distribution.active.endpoint, healthPath: distribution.active.healthPath };
2083
+ const probed = await deps.probe(candidate);
2084
+ if (!probed.healthy) throw new TBError("unavailable", "candidate plugin failed its health check", { retryable: true });
2085
+ const { describe: raw } = await deps.fetchContract(candidate);
2086
+ const describe = validatePluginContract({ manifest: candidate, describe: raw });
2087
+ return { ...candidate, describe };
2088
+ }
2089
+ async function verifyAuth(candidate) {
2090
+ if (!deps.verifyReleaseAuth) throw new TBError("unavailable", "plugin bearer verifier unavailable");
2091
+ await deps.verifyReleaseAuth(candidate);
2092
+ }
2093
+ async function activate(candidate, prior) {
2094
+ await verifyAuth(candidate);
2095
+ const revision2 = prior ? prior.revision + 1 : Number.parseInt(crypto.randomUUID().replace(/-/g, "").slice(0, 12), 16);
2096
+ const record = { ...candidate, revision: revision2 };
2097
+ if (!await deps.store.compareAndSwap?.(KEY_PLUGIN + candidate.id, prior?.revision ?? null, record))
2098
+ throw new TBError("conflict", "plugin registration changed; reload before retrying");
2099
+ return { ...manifestOf(candidate), distribution: candidate.distribution, exports: candidate.describe.exports };
2100
+ }
2101
+ async function managed(id, scopes) {
2102
+ const record = await deps.store.get(KEY_PLUGIN + id);
2103
+ if (!record) throw new TBError("not_found", "plugin not installed");
2104
+ if (!record.distribution) throw new TBError("conflict", "plugin was registered manually; use plugin update");
2105
+ if (record.auth.kind !== "bearer") throw new TBError("conflict", "missing installation bearer reference");
2106
+ assertSecretRefUse(scopes, { authRef: record.auth.secretRef });
2107
+ return record;
2108
+ }
2109
+ async function prepareUpgrade(record, input, actor) {
2110
+ const { active } = record.distribution;
2111
+ const source2 = input.source ?? active.source;
2112
+ const resolved = await load(source2);
2113
+ const { release } = resolved;
2114
+ if (release.id !== input.id || "image" in release !== (active.image !== void 0))
2115
+ throw new TBError("invalid_argument", "plugin identity or hosting mode changed");
2116
+ const receipt = await releaseReceipt(source2, resolved, actor);
2117
+ for (const known of [active, record.distribution.previous, record.distribution.rolledBackFrom]) {
2118
+ if (known?.version === receipt.version && known.digest !== receipt.digest)
2119
+ throw new TBError("conflict", "a known version cannot be replaced with a different manifest");
2120
+ }
2121
+ const next = await resolveCandidate(receipt, release, record.distribution.origin);
2122
+ if (active.digest === next.digest && active.endpoint !== next.endpoint)
2123
+ throw new TBError("conflict", "an existing release cannot change endpoints");
2124
+ if (active.digest !== next.digest && active.endpoint === next.endpoint)
2125
+ throw new TBError("conflict", "a new release needs its own endpoint so rollback remains possible");
2126
+ const distribution = active.digest === next.digest ? { ...record.distribution, active: next } : { origin: record.distribution.origin, active: next, previous: active };
2127
+ return inspect(manifestOf(record), distribution);
2128
+ }
2129
+ async function confirmationDigest(record, candidate) {
2130
+ const { digest, resolvedSource } = candidate.distribution.active;
2131
+ return "sha256:" + await catalogDigest({
2132
+ id: record.id,
2133
+ revision: record.revision,
2134
+ resolvedSource,
2135
+ digest,
2136
+ endpoint: candidate.endpoint,
2137
+ describe: candidate.describe
2138
+ });
2139
+ }
2140
+ return {
2141
+ async install(input, actor) {
2142
+ const resolved = await load(input.source);
2143
+ const { release } = resolved;
2144
+ if (await deps.store.get(KEY_PLUGIN + release.id)) throw new TBError("conflict", "plugin is already registered");
2145
+ if (!await deps.secrets.resolve(input.secretRef)) throw new TBError("invalid_argument", "plugin bearer secret is unavailable");
2146
+ const receipt = await releaseReceipt(input.source, resolved, actor);
2147
+ const active = await resolveCandidate(receipt, release, input.origin);
2148
+ return activate(await inspect({
2149
+ id: release.id,
2150
+ protocolVersion: "plugin/v2",
2151
+ enabled: true,
2152
+ auth: { kind: "bearer", secretRef: input.secretRef },
2153
+ endpoint: active.endpoint,
2154
+ healthPath: active.healthPath
2155
+ }, { active, ...!active.image ? { origin: approvedOrigin(active.endpoint) } : {} }));
2156
+ },
2157
+ async preview(input, scopes, actor) {
2158
+ const record = await managed(input.id, scopes);
2159
+ const candidate = await prepareUpgrade(record, input, actor);
2160
+ await verifyAuth(candidate);
2161
+ const before = new Map(record.describe.exports.map((e) => [e.id, e]));
2162
+ const after = new Map(candidate.describe.exports.map((e) => [e.id, e]));
2163
+ const addedExports = [...after.keys()].filter((id) => !before.has(id)).sort();
2164
+ const removedExports = [...before.keys()].filter((id) => !after.has(id)).sort();
2165
+ const changedExports = [...after.keys()].filter(
2166
+ (id) => before.has(id) && canonicalCatalogJson(before.get(id)) !== canonicalCatalogJson(after.get(id))
2167
+ ).sort();
2168
+ const affectedMounts = [];
2169
+ const incompatibleMounts = [];
2170
+ const kinds = Object.values(NODE_KIND_BY_PROFILE2);
2171
+ for (const node of await new NodeRegistryStore(deps.store).subtree("")) {
2172
+ const cfg = node.config;
2173
+ if (!cfg || !("provider" in cfg) || cfg.provider !== record.id || cfg.kind !== node.kind) continue;
2174
+ const nodeKind = kinds.find((kind) => kind === cfg.kind);
2175
+ if (!nodeKind || !checkScopes(scopes, node.path, "read")) continue;
2176
+ if (nodeKind === "context" && ["storage", "s3", "device-fs"].includes(cfg.provider)) continue;
2177
+ const pc = "providerConfig" in cfg ? cfg.providerConfig : void 0;
2178
+ if (typeof pc?.deviceId === "string" && typeof pc.mountPath === "string") continue;
2179
+ affectedMounts.push(node.path);
2180
+ try {
2181
+ resolvePluginExport(candidate.describe, {
2182
+ pluginId: record.id,
2183
+ nodeKind,
2184
+ exportId: "export" in cfg ? cfg.export : void 0
2185
+ });
2186
+ } catch (err) {
2187
+ if (!isTBError(err) || err.code !== "invalid_argument") throw err;
2188
+ incompatibleMounts.push(node.path);
2189
+ }
2190
+ }
2191
+ return {
2192
+ id: record.id,
2193
+ currentVersion: record.distribution.active.version,
2194
+ candidateVersion: candidate.distribution.active.version,
2195
+ candidateDigest: await confirmationDigest(record, candidate),
2196
+ addedExports,
2197
+ removedExports,
2198
+ changedExports,
2199
+ affectedMounts,
2200
+ incompatibleMounts,
2201
+ requiresRunner: candidate.distribution.active.image !== void 0
2202
+ };
2203
+ },
2204
+ async upgrade(input, scopes, actor) {
2205
+ const record = await managed(input.id, scopes);
2206
+ const candidate = await prepareUpgrade(record, input, actor);
2207
+ if (input.candidateDigest && input.candidateDigest !== await confirmationDigest(record, candidate))
2208
+ throw new TBError("conflict", "candidate or active registration changed; preview again");
2209
+ return activate(candidate, record);
2210
+ },
2211
+ async rollback(id, scopes, digest) {
2212
+ const record = await managed(id, scopes);
2213
+ const { active, previous } = record.distribution;
2214
+ if (digest === active.digest || !digest && !previous && record.distribution.rolledBackFrom)
2215
+ return { ...manifestOf(record), distribution: record.distribution, exports: record.describe.exports };
2216
+ if (!previous || digest && digest !== previous.digest)
2217
+ throw new TBError("conflict", "requested rollback target is unavailable");
2218
+ if (previous.image) {
2219
+ if (!deps.prepareImage) throw new TBError("unavailable", "isolated plugin runner unavailable");
2220
+ const endpoint = httpsReleaseUrl(await deps.prepareImage(id, previous.image)).replace(/\/+$/, "");
2221
+ if (endpoint !== previous.endpoint) throw new TBError("conflict", "previous runner endpoint changed");
2222
+ }
2223
+ return activate(await inspect(manifestOf(record), { origin: record.distribution.origin, active: previous, rolledBackFrom: active }), record);
2224
+ }
2225
+ };
2226
+ }
2227
+
2228
+ // ../core/src/builtin/plugin.ts
2229
+ var DESCRIPTION2 = "Plugin registry: register / probe external tool & context providers, then mount them via system/registry (admin only)";
2230
+ function pluginTokenSecretName(id) {
2231
+ return `plugin-token:${id}`;
2232
+ }
2233
+ var pluginAuthSchema = z12.discriminatedUnion("kind", [
2234
+ z12.strictObject({ kind: z12.literal("platform-token") }),
2235
+ z12.strictObject({ kind: z12.literal("bearer"), secretRef: z12.string().min(1) })
2236
+ ]).describe(
2237
+ '{ kind: "platform-token" } \u2014 gateway mints the token (shown once in the response); or { kind: "bearer", secretRef }'
2238
+ );
2239
+ var pluginIdSchema = z12.string().min(1).describe("plugin id");
2240
+ var manifestFields = {
2241
+ id: z12.string().min(1).describe("unique plugin id"),
2242
+ protocolVersion: z12.literal("plugin/v2").describe(
2243
+ "transport protocol version; what the plugin provides is declared by its /~describe exports"
2244
+ ),
2245
+ endpoint: z12.string().min(1).describe("https base URL of the plugin service"),
2246
+ auth: pluginAuthSchema,
2247
+ healthPath: z12.string().min(1).describe('GET probe path, e.g. "/healthz"'),
2248
+ enabled: z12.boolean()
2249
+ };
2250
+ var pluginWriteSchema = z12.strictObject(manifestFields);
2251
+ var pluginPatchSchema = z12.strictObject({
2252
+ id: manifestFields.id.optional(),
2253
+ protocolVersion: manifestFields.protocolVersion.optional(),
2254
+ endpoint: manifestFields.endpoint.optional(),
2255
+ auth: manifestFields.auth.optional(),
2256
+ healthPath: manifestFields.healthPath.optional(),
2257
+ enabled: manifestFields.enabled.optional()
2258
+ }).describe("fields to change; same shape as write, all optional");
2259
+ var COMMANDS2 = new BuiltinCommandRegistry("plugin", DESCRIPTION2).register("install", {
2260
+ h: "Install a hosted or digest-pinned release after validating its candidate",
2261
+ scope: "admin",
2262
+ inputSchema: installInput,
2263
+ returns: "PluginView"
2264
+ }, (input, { deps, call }) => {
2265
+ assertSecretRefUse(call.scopes, { authRef: input.secretRef });
2266
+ return deps.install(input, call.keyId);
2267
+ }).register("preview", {
2268
+ h: "Preview export changes and readable mounts without switching traffic; a pinned OCI candidate is started or reused",
2269
+ scope: "admin",
2270
+ inputSchema: previewInput,
2271
+ returns: "PluginUpgradePreview"
2272
+ }, (input, { deps, call }) => deps.preview(input, call.scopes, call.keyId)).register("upgrade", {
2273
+ h: "Validate and switch to a new release, or refresh the current release",
2274
+ scope: "admin",
2275
+ inputSchema: upgradeInput,
2276
+ returns: "PluginView"
2277
+ }, (input, { deps, call }) => deps.upgrade(input, call.scopes, call.keyId)).register("rollback", {
2278
+ h: "Check and restore the previous installed release",
2279
+ scope: "admin",
2280
+ inputSchema: z12.strictObject({ id: pluginIdSchema, digest: z12.string().regex(/^sha256:[0-9a-f]{64}$/).optional() }),
2281
+ returns: "PluginView"
2282
+ }, ({ id, digest }, { deps, call }) => deps.rollback(id, call.scopes, digest)).register(
2283
+ "list",
2284
+ {
2285
+ h: "list registered plugins (pluginToken never returned)",
2286
+ inputSchema: z12.strictObject({ opts: HTBP_LIST_OPTIONS_SCHEMA.optional() }),
2287
+ returns: "Page<PluginView> \u2014 manifest + the exports declared by its /~describe",
2288
+ scope: "admin"
2289
+ },
2290
+ ({ opts }, { deps }) => deps.list(opts)
2291
+ ).register(
2292
+ "get",
2293
+ {
2294
+ h: "fetch one plugin manifest by id",
2295
+ inputSchema: z12.strictObject({ id: pluginIdSchema }),
2296
+ returns: "PluginView \u2014 manifest + the exports declared by its /~describe",
2297
+ scope: "admin"
2298
+ },
2299
+ ({ id }, { deps }) => deps.get(id)
2300
+ ).register(
2301
+ "write",
2302
+ {
2303
+ h: "register a plugin: probes health and validates its /~describe exports before accepting; then mount an export via system/registry (config.provider = plugin id, config.export = export id)",
2304
+ inputSchema: pluginWriteSchema,
2305
+ returns: "PluginView + pluginToken shown once (platform-token only)",
2306
+ scope: "admin"
2307
+ },
2308
+ (input, { deps }) => deps.write(input)
2309
+ ).register(
2310
+ "update",
2311
+ {
2312
+ h: "patch a registration; endpoint changes re-probe and re-validate the exports before applying",
2313
+ inputSchema: z12.strictObject({
2314
+ id: pluginIdSchema,
2315
+ patch: pluginPatchSchema
2316
+ }),
2317
+ returns: "PluginView \u2014 pluginToken shown once if auth switched to platform-token",
2318
+ scope: "admin"
2319
+ },
2320
+ ({ id, patch }, { deps }) => deps.update(id, patch)
2321
+ ).register(
2322
+ "delete",
2323
+ {
2324
+ h: "unregister a plugin and revoke its platform token; mounted nodes referencing it stop working",
2325
+ inputSchema: z12.strictObject({ id: pluginIdSchema }),
2326
+ returns: "void",
2327
+ scope: "admin"
2328
+ },
2329
+ async ({ id }, { deps }) => {
2330
+ await deps.remove(id);
2331
+ return VOID_ACK;
2332
+ }
2333
+ ).register(
2334
+ "health",
2335
+ {
2336
+ h: "probe the plugin health endpoint now",
2337
+ inputSchema: z12.strictObject({ id: pluginIdSchema }),
2338
+ returns: "{ id, healthy, checkedAt }",
2339
+ scope: "admin"
2340
+ },
2341
+ ({ id }, { deps }) => deps.health(id)
2342
+ );
2343
+ function clampLimit3(limit) {
2344
+ if (limit === void 0 || limit < 1) return LIST_LIMIT_DEFAULT;
2345
+ return limit > LIST_LIMIT_MAX ? LIST_LIMIT_MAX : limit;
2346
+ }
2347
+ function createPluginModule(deps) {
2348
+ const { store, sk, secrets, now } = deps;
2349
+ async function read(id) {
2350
+ return await store.get(KEY_PLUGIN + id);
2351
+ }
2352
+ async function require2(id) {
2353
+ const record = await read(id);
2354
+ if (!record) throw new TBError("not_found", `plugin '${id}' not found`);
2355
+ return record;
2356
+ }
2357
+ async function view(record) {
2358
+ const describe = record.describe ?? await store.get(KEY_PLUGIN_META + record.id);
2359
+ if (describe === null) {
2360
+ throw new TBError(
2361
+ "unavailable",
2362
+ `plugin '${record.id}' \u7F3A\u5C11 ~describe \u7F13\u5B58,\u8BF7\u91CD\u65B0\u6CE8\u518C`,
2363
+ { retryable: false }
2364
+ );
2365
+ }
2366
+ return { ...manifestOf(record), exports: describe.exports, ...record.distribution ? { distribution: record.distribution } : {} };
2367
+ }
2368
+ async function revokeToken(record) {
2369
+ if (record.tokenSkId !== void 0) await sk.delete(record.tokenSkId);
2370
+ try {
2371
+ await secrets.delete(pluginTokenSecretName(record.id));
2372
+ } catch {
2373
+ }
2374
+ }
2375
+ async function probeAndRecord(manifest) {
2376
+ const result = await deps.probe(manifest);
2377
+ const prev = await store.get(KEY_PLUGIN_HEALTH + manifest.id);
2378
+ const record = {
2379
+ healthy: result.healthy,
2380
+ checkedAt: now(),
2381
+ consecutiveFailures: result.healthy ? 0 : (prev?.consecutiveFailures ?? 0) + 1
2382
+ };
2383
+ await store.put(KEY_PLUGIN_HEALTH + manifest.id, record);
2384
+ return record;
2385
+ }
2386
+ async function write(args) {
2387
+ const manifest = parsePluginManifest(args, {
2388
+ allowInsecureHttp: deps.allowInsecureHttp ?? false
2389
+ });
2390
+ const probed = await deps.probe(manifest);
2391
+ if (!probed.healthy) {
2392
+ throw new TBError(
2393
+ "unavailable",
2394
+ `plugin '${manifest.id}' \u63A2\u6D3B\u5931\u8D25,\u62D2\u7EDD\u6CE8\u518C${probed.detail !== void 0 ? `:${probed.detail}` : ""}`,
2395
+ { retryable: true }
2396
+ );
2397
+ }
2398
+ const contract = await deps.fetchContract(manifest);
2399
+ const describe = validatePluginContract({ manifest, describe: contract.describe });
2400
+ const existing = await read(manifest.id);
2401
+ if (existing?.distribution) throw new TBError("conflict", "use plugin upgrade for an installed release");
2402
+ if (existing) await revokeToken(existing);
2403
+ let pluginToken;
2404
+ let tokenSkId;
2405
+ if (manifest.auth.kind === "platform-token") {
2406
+ const minted = await sk.write({ owner: `plugin:${manifest.id}`, scopes: [] }, now());
2407
+ await secrets.set(pluginTokenSecretName(manifest.id), minted.secret, now());
2408
+ pluginToken = minted.secret;
2409
+ tokenSkId = minted.key.id;
2410
+ }
2411
+ await store.put(KEY_PLUGIN_META + manifest.id, describe);
1746
2412
  await store.put(KEY_PLUGIN_HEALTH + manifest.id, {
1747
2413
  healthy: true,
1748
2414
  checkedAt: now(),
@@ -1752,7 +2418,11 @@ function createPluginModule(deps) {
1752
2418
  ...manifest,
1753
2419
  ...tokenSkId !== void 0 ? { tokenSkId } : {}
1754
2420
  };
1755
- await store.put(KEY_PLUGIN + manifest.id, record);
2421
+ if (!existing && store.putIfAbsent) {
2422
+ if (!await store.putIfAbsent(KEY_PLUGIN + manifest.id, record)) throw new TBError("conflict", "plugin registered concurrently");
2423
+ } else {
2424
+ await store.put(KEY_PLUGIN + manifest.id, record);
2425
+ }
1756
2426
  return {
1757
2427
  ...manifest,
1758
2428
  exports: describe.exports,
@@ -1764,7 +2434,14 @@ function createPluginModule(deps) {
1764
2434
  if (patch.id !== void 0 && patch.id !== id) {
1765
2435
  throw new TBError("invalid_argument", "id \u4E0D\u53EF\u901A\u8FC7 update \u53D8\u66F4");
1766
2436
  }
1767
- const prev = projectManifest(existing);
2437
+ if (existing.distribution) {
2438
+ if (Object.keys(patch).some((k) => k !== "enabled"))
2439
+ throw new TBError("invalid_argument", "use plugin upgrade to change an installed release");
2440
+ const record2 = { ...existing, enabled: typeof patch.enabled === "boolean" ? patch.enabled : existing.enabled, revision: existing.revision + 1 };
2441
+ if (!await store.compareAndSwap?.(KEY_PLUGIN + id, existing.revision, record2)) throw new TBError("conflict", "plugin changed");
2442
+ return view(record2);
2443
+ }
2444
+ const prev = manifestOf(existing);
1768
2445
  const merged = parsePluginManifest(
1769
2446
  { ...prev, ...patch },
1770
2447
  { allowInsecureHttp: deps.allowInsecureHttp ?? false }
@@ -1815,14 +2492,19 @@ function createPluginModule(deps) {
1815
2492
  async function remove(id) {
1816
2493
  const existing = await read(id);
1817
2494
  if (!existing) return;
2495
+ if (existing.distribution) {
2496
+ if (!await store.compareAndSwap?.(KEY_PLUGIN + id, existing.revision, null)) throw new TBError("conflict", "plugin changed");
2497
+ return;
2498
+ }
1818
2499
  await revokeToken(existing);
1819
2500
  await store.delete(KEY_PLUGIN + id);
1820
2501
  await store.delete(KEY_PLUGIN_HEALTH + id);
1821
2502
  await store.delete(KEY_PLUGIN_META + id);
1822
2503
  }
1823
2504
  return COMMANDS2.module({
2505
+ ...createDistribution(deps),
1824
2506
  async list(opts) {
1825
- const listOpts = { limit: clampLimit2(opts?.limit) };
2507
+ const listOpts = { limit: clampLimit3(opts?.limit) };
1826
2508
  if (opts?.cursor !== void 0) listOpts.cursor = opts.cursor;
1827
2509
  const page = await store.list(KEY_PLUGIN, listOpts);
1828
2510
  const items = await Promise.all(
@@ -1837,7 +2519,12 @@ function createPluginModule(deps) {
1837
2519
  update,
1838
2520
  remove,
1839
2521
  async health(id) {
1840
- const manifest = projectManifest(await require2(id));
2522
+ const installed = await require2(id);
2523
+ if (installed.distribution) {
2524
+ const { healthy } = await deps.probe(installed);
2525
+ return { id, healthy, checkedAt: now() };
2526
+ }
2527
+ const manifest = manifestOf(installed);
1841
2528
  const record = await probeAndRecord(manifest);
1842
2529
  return { id, healthy: record.healthy, checkedAt: record.checkedAt };
1843
2530
  }
@@ -1845,27 +2532,27 @@ function createPluginModule(deps) {
1845
2532
  }
1846
2533
 
1847
2534
  // ../core/src/builtin/store.ts
1848
- import { z as z10 } from "zod/v4";
2535
+ import { z as z13 } from "zod/v4";
1849
2536
  var DESCRIPTION3 = "Deployment-level private object Store for uploads, reads and short-lived sharing";
1850
- var contentTypeSchema = z10.string().min(1).describe("object MIME type");
1851
- var filenameSchema = z10.string().optional().describe(
2537
+ var contentTypeSchema = z13.string().min(1).describe("object MIME type");
2538
+ var filenameSchema = z13.string().optional().describe(
1852
2539
  "display-only filename; never used as a storage key"
1853
2540
  );
1854
- var checksumSchema = z10.strictObject({
1855
- algorithm: z10.literal("sha256"),
1856
- value: z10.string()
2541
+ var checksumSchema = z13.strictObject({
2542
+ algorithm: z13.literal("sha256"),
2543
+ value: z13.string()
1857
2544
  }).optional().describe("optional sha256 checksum declaration");
1858
- var uriSchema = z10.string().describe("store://default/<objectId>");
2545
+ var uriSchema = z13.string().describe("store://default/<objectId>");
1859
2546
  var COMMANDS3 = new BuiltinCommandRegistry("store", DESCRIPTION3).register(
1860
2547
  "create_upload",
1861
2548
  {
1862
2549
  h: "create a new opaque Store object and bounded upload session",
1863
- inputSchema: z10.strictObject({
2550
+ inputSchema: z13.strictObject({
1864
2551
  contentType: contentTypeSchema,
1865
2552
  filename: filenameSchema,
1866
- size: z10.number().optional().describe("expected byte size"),
2553
+ size: z13.number().optional().describe("expected byte size"),
1867
2554
  checksum: checksumSchema,
1868
- idempotencyKey: z10.string().optional().describe("owner-scoped create retry key")
2555
+ idempotencyKey: z13.string().optional().describe("owner-scoped create retry key")
1869
2556
  }),
1870
2557
  returns: "StoreUploadGrant",
1871
2558
  scope: "write"
@@ -1888,7 +2575,7 @@ var COMMANDS3 = new BuiltinCommandRegistry("store", DESCRIPTION3).register(
1888
2575
  "complete_upload",
1889
2576
  {
1890
2577
  h: "verify a direct upload and atomically mark its object ready; idempotent",
1891
- inputSchema: z10.strictObject({ uploadId: z10.string().min(1) }),
2578
+ inputSchema: z13.strictObject({ uploadId: z13.string().min(1) }),
1892
2579
  returns: "StoreObject",
1893
2580
  scope: "write"
1894
2581
  },
@@ -1897,7 +2584,7 @@ var COMMANDS3 = new BuiltinCommandRegistry("store", DESCRIPTION3).register(
1897
2584
  "abort_upload",
1898
2585
  {
1899
2586
  h: "abandon an unfinished upload; idempotent until the object is ready",
1900
- inputSchema: z10.strictObject({ uploadId: z10.string().min(1) }),
2587
+ inputSchema: z13.strictObject({ uploadId: z13.string().min(1) }),
1901
2588
  returns: "void",
1902
2589
  scope: "write"
1903
2590
  },
@@ -1906,7 +2593,7 @@ var COMMANDS3 = new BuiltinCommandRegistry("store", DESCRIPTION3).register(
1906
2593
  "stat",
1907
2594
  {
1908
2595
  h: "return metadata for a ready object owned by the current principal",
1909
- inputSchema: z10.strictObject({ uri: uriSchema }),
2596
+ inputSchema: z13.strictObject({ uri: uriSchema }),
1910
2597
  returns: "StoreObject",
1911
2598
  scope: "read"
1912
2599
  },
@@ -1915,7 +2602,7 @@ var COMMANDS3 = new BuiltinCommandRegistry("store", DESCRIPTION3).register(
1915
2602
  "read",
1916
2603
  {
1917
2604
  h: "authorize an object read and return a short-lived $ref",
1918
- inputSchema: z10.strictObject({ uri: uriSchema }),
2605
+ inputSchema: z13.strictObject({ uri: uriSchema }),
1919
2606
  returns: "{ $ref, contentType, size, expiresAt }",
1920
2607
  scope: "read"
1921
2608
  },
@@ -1927,9 +2614,9 @@ var COMMANDS3 = new BuiltinCommandRegistry("store", DESCRIPTION3).register(
1927
2614
  "share",
1928
2615
  {
1929
2616
  h: "create a short-lived, revocable read share for an owned object",
1930
- inputSchema: z10.strictObject({
2617
+ inputSchema: z13.strictObject({
1931
2618
  uri: uriSchema,
1932
- ttlSec: z10.number().int().positive().optional()
2619
+ ttlSec: z13.number().int().positive().optional()
1933
2620
  }),
1934
2621
  returns: "StoreShare",
1935
2622
  scope: "write"
@@ -1942,7 +2629,7 @@ var COMMANDS3 = new BuiltinCommandRegistry("store", DESCRIPTION3).register(
1942
2629
  "revoke_share",
1943
2630
  {
1944
2631
  h: "revoke a Store share grant",
1945
- inputSchema: z10.strictObject({ shareId: z10.string().min(1) }),
2632
+ inputSchema: z13.strictObject({ shareId: z13.string().min(1) }),
1946
2633
  returns: "void",
1947
2634
  scope: "write"
1948
2635
  },
@@ -1951,7 +2638,7 @@ var COMMANDS3 = new BuiltinCommandRegistry("store", DESCRIPTION3).register(
1951
2638
  "delete",
1952
2639
  {
1953
2640
  h: "make an owned Store object immediately unreadable and delete its bytes",
1954
- inputSchema: z10.strictObject({ uri: uriSchema }),
2641
+ inputSchema: z13.strictObject({ uri: uriSchema }),
1955
2642
  returns: "void",
1956
2643
  scope: "write"
1957
2644
  },
@@ -1960,7 +2647,7 @@ var COMMANDS3 = new BuiltinCommandRegistry("store", DESCRIPTION3).register(
1960
2647
  "list",
1961
2648
  {
1962
2649
  h: "list ready Store objects owned by the current principal",
1963
- inputSchema: z10.strictObject({ opts: HTBP_LIST_OPTIONS_SCHEMA.optional() }),
2650
+ inputSchema: z13.strictObject({ opts: HTBP_LIST_OPTIONS_SCHEMA.optional() }),
1964
2651
  returns: "Page<StoreObject>",
1965
2652
  scope: "read"
1966
2653
  },
@@ -1971,18 +2658,18 @@ function createStoreModule(deps) {
1971
2658
  }
1972
2659
 
1973
2660
  // ../core/src/builtin/annotation.ts
1974
- import { z as z11 } from "zod/v4";
2661
+ import { z as z14 } from "zod/v4";
1975
2662
  var DESCRIPTION4 = "Path annotations: admin-curated notes shown in ~help of the annotated path (set / get / remove / list)";
1976
- var rootablePathSchema = z11.string().describe('tree path; "" = tree-wide notice');
2663
+ var rootablePathSchema = z14.string().describe('tree path; "" = tree-wide notice');
1977
2664
  var COMMANDS4 = new BuiltinCommandRegistry("annotation", DESCRIPTION4).register(
1978
2665
  "set",
1979
2666
  {
1980
2667
  h: "upsert the note shown in ~help of <path>; empty path = tree-wide notice",
1981
- inputSchema: z11.strictObject({
1982
- path: z11.string().describe(
2668
+ inputSchema: z14.strictObject({
2669
+ path: z14.string().describe(
1983
2670
  'tree path (tool sub-paths like "feishu/create-doc" work); "" = tree-wide'
1984
2671
  ),
1985
- text: z11.string().min(1).max(ANNOTATION_TEXT_MAX).describe("the note (max 2000 chars)")
2672
+ text: z14.string().min(1).max(ANNOTATION_TEXT_MAX).describe("the note (max 2000 chars)")
1986
2673
  }),
1987
2674
  returns: "{ path, text, updatedAt, updatedBy }",
1988
2675
  scope: "admin"
@@ -1995,7 +2682,7 @@ var COMMANDS4 = new BuiltinCommandRegistry("annotation", DESCRIPTION4).register(
1995
2682
  "get",
1996
2683
  {
1997
2684
  h: "read the note of one path (not_found if none)",
1998
- inputSchema: z11.strictObject({ path: rootablePathSchema }),
2685
+ inputSchema: z14.strictObject({ path: rootablePathSchema }),
1999
2686
  returns: "{ path, text, updatedAt, updatedBy }",
2000
2687
  scope: "read"
2001
2688
  },
@@ -2010,7 +2697,7 @@ var COMMANDS4 = new BuiltinCommandRegistry("annotation", DESCRIPTION4).register(
2010
2697
  "remove",
2011
2698
  {
2012
2699
  h: "remove the note of a path (idempotent)",
2013
- inputSchema: z11.strictObject({ path: rootablePathSchema }),
2700
+ inputSchema: z14.strictObject({ path: rootablePathSchema }),
2014
2701
  returns: "void",
2015
2702
  scope: "admin"
2016
2703
  },
@@ -2022,8 +2709,8 @@ var COMMANDS4 = new BuiltinCommandRegistry("annotation", DESCRIPTION4).register(
2022
2709
  "list",
2023
2710
  {
2024
2711
  h: "all annotated paths (optionally under a prefix)",
2025
- inputSchema: z11.strictObject({
2026
- prefix: z11.string().optional().describe("only paths under this prefix")
2712
+ inputSchema: z14.strictObject({
2713
+ prefix: z14.string().optional().describe("only paths under this prefix")
2027
2714
  }),
2028
2715
  returns: "{ items: Array<{ path, text, updatedAt, updatedBy }> }",
2029
2716
  scope: "read"
@@ -2035,7 +2722,7 @@ function createAnnotationModule(deps) {
2035
2722
  }
2036
2723
 
2037
2724
  // ../core/src/builtin/federation.ts
2038
- import { z as z12 } from "zod/v4";
2725
+ import { z as z15 } from "zod/v4";
2039
2726
 
2040
2727
  // ../core/src/tool/allowlist.ts
2041
2728
  function normalizeAllowHost(raw) {
@@ -2119,7 +2806,7 @@ var COMMANDS5 = new BuiltinCommandRegistry("federation", DESCRIPTION5).register(
2119
2806
  "list",
2120
2807
  {
2121
2808
  h: "merged allowlist view: env baseline entries (removable=false) plus runtime entries",
2122
- inputSchema: z12.strictObject({}),
2809
+ inputSchema: z15.strictObject({}),
2123
2810
  returns: 'Page<{ host, source: "env"|"store", removable, updatedAt? }>',
2124
2811
  scope: "admin"
2125
2812
  },
@@ -2128,8 +2815,8 @@ var COMMANDS5 = new BuiltinCommandRegistry("federation", DESCRIPTION5).register(
2128
2815
  "add",
2129
2816
  {
2130
2817
  h: "allow a host (suffix match covers subdomains); takes effect immediately",
2131
- inputSchema: z12.strictObject({
2132
- host: z12.string().min(1).describe(
2818
+ inputSchema: z15.strictObject({
2819
+ host: z15.string().min(1).describe(
2133
2820
  'bare host suffix, e.g. "example.com" \u2014 no scheme/port/path'
2134
2821
  )
2135
2822
  }),
@@ -2147,8 +2834,8 @@ var COMMANDS5 = new BuiltinCommandRegistry("federation", DESCRIPTION5).register(
2147
2834
  "remove",
2148
2835
  {
2149
2836
  h: "remove a runtime-added host; env baseline entries cannot be removed here",
2150
- inputSchema: z12.strictObject({
2151
- host: z12.string().min(1).describe("bare host suffix as listed")
2837
+ inputSchema: z15.strictObject({
2838
+ host: z15.string().min(1).describe("bare host suffix as listed")
2152
2839
  }),
2153
2840
  returns: "void \u2014 env baseline entries are not removable",
2154
2841
  scope: "admin"
@@ -2170,10 +2857,10 @@ function createFederationModule(deps) {
2170
2857
  }
2171
2858
 
2172
2859
  // ../core/src/builtin/registry.ts
2173
- import { z as z16 } from "zod/v4";
2860
+ import { z as z19 } from "zod/v4";
2174
2861
 
2175
2862
  // ../core/src/protocol/wire.ts
2176
- import { z as z15 } from "zod";
2863
+ import { z as z18 } from "zod";
2177
2864
 
2178
2865
  // ../core/src/secret/keyring.ts
2179
2866
  function validateEncryptionKeyring(input) {
@@ -2240,7 +2927,7 @@ function positiveInteger(value, fallback, field) {
2240
2927
  }
2241
2928
  return actual;
2242
2929
  }
2243
- function clampLimit3(value) {
2930
+ function clampLimit4(value) {
2244
2931
  if (value === void 0) return LIST_LIMIT_DEFAULT2;
2245
2932
  if (!Number.isSafeInteger(value) || value < 1) {
2246
2933
  throw new TBError("invalid_argument", "limit must be a positive integer");
@@ -2587,7 +3274,7 @@ var DeviceMailboxService = class {
2587
3274
  return await this.detail(await this.expireRecord(key, record));
2588
3275
  }
2589
3276
  async list(input) {
2590
- const limit = clampLimit3(input.limit);
3277
+ const limit = clampLimit4(input.limit);
2591
3278
  const states = input.states === void 0 ? void 0 : new Set(input.states);
2592
3279
  if (states !== void 0 && [...states].some((state) => !isState(state))) {
2593
3280
  throw new TBError("invalid_argument", "states contains an invalid operation state");
@@ -2613,7 +3300,7 @@ var DeviceMailboxService = class {
2613
3300
  deviceId: input.deviceId,
2614
3301
  claimableBy: input.deviceKeyId,
2615
3302
  now: serverNow,
2616
- limit: clampLimit3(input.limit),
3303
+ limit: clampLimit4(input.limit),
2617
3304
  ...input.cursor === void 0 ? {} : { cursor: input.cursor }
2618
3305
  });
2619
3306
  for (const item of page.items) {
@@ -2785,7 +3472,7 @@ var DeviceMailboxService = class {
2785
3472
  }
2786
3473
  /** Re-encrypt only unchanged ledger revisions; concurrent lease/terminal transitions retain authority. */
2787
3474
  async reencryptPage(opts = {}) {
2788
- const page = await this.repository.list({ ...opts, limit: clampLimit3(opts.limit) });
3475
+ const page = await this.repository.list({ ...opts, limit: clampLimit4(opts.limit) });
2789
3476
  let changed = 0;
2790
3477
  for (const item of page.items) {
2791
3478
  const record = parseRecord(item.value);
@@ -2805,7 +3492,7 @@ var DeviceMailboxService = class {
2805
3492
  }
2806
3493
  async cleanup(opts = {}) {
2807
3494
  const page = await this.repository.list({
2808
- limit: clampLimit3(opts.limit),
3495
+ limit: clampLimit4(opts.limit),
2809
3496
  ...opts.cursor === void 0 ? {} : { cursor: opts.cursor }
2810
3497
  });
2811
3498
  let deleted = 0;
@@ -2834,337 +3521,338 @@ var DeviceMailboxService = class {
2834
3521
  };
2835
3522
 
2836
3523
  // ../core/src/device/environment.ts
2837
- import { z as z13 } from "zod";
2838
- var deviceEnvironmentSchema = z13.strictObject({
2839
- platform: z13.enum(["darwin", "linux", "win32", "android", "ios", "other"]),
2840
- arch: z13.string().min(1).max(32).regex(/^[a-zA-Z0-9._-]+$/).optional(),
2841
- runtime: z13.enum(["node", "bun", "react-native", "other"]).optional(),
2842
- runtimeVersion: z13.string().min(1).max(64).regex(/^[a-zA-Z0-9.+_-]+$/).optional(),
2843
- runtimeId: z13.string().min(1).max(128).regex(/^[a-zA-Z0-9._-]+$/).optional()
3524
+ import { z as z16 } from "zod";
3525
+ var deviceEnvironmentSchema = z16.strictObject({
3526
+ platform: z16.enum(["darwin", "linux", "win32", "android", "ios", "other"]),
3527
+ arch: z16.string().min(1).max(32).regex(/^[a-zA-Z0-9._-]+$/).optional(),
3528
+ runtime: z16.enum(["node", "bun", "react-native", "other"]).optional(),
3529
+ runtimeVersion: z16.string().min(1).max(64).regex(/^[a-zA-Z0-9.+_-]+$/).optional(),
3530
+ runtimeId: z16.string().min(1).max(128).regex(/^[a-zA-Z0-9._-]+$/).optional()
2844
3531
  });
2845
3532
 
2846
3533
  // ../core/src/protocol/errorWire.ts
2847
- import { z as z14 } from "zod";
2848
- var tbErrorCodeSchema = z14.enum(TB_ERROR_CODES);
2849
- var tbErrorBodySchema = z14.object({
3534
+ import { z as z17 } from "zod";
3535
+ var tbErrorCodeSchema = z17.enum(TB_ERROR_CODES);
3536
+ var tbErrorBodySchema = z17.object({
2850
3537
  code: tbErrorCodeSchema,
2851
- message: z14.string(),
2852
- retryable: z14.boolean()
3538
+ message: z17.string(),
3539
+ retryable: z17.boolean()
2853
3540
  });
2854
3541
 
2855
3542
  // ../core/src/protocol/wire.ts
2856
- var actionSchema = z15.enum(ACTIONS);
2857
- var nodeKindSchema = z15.enum(NODE_KINDS);
2858
- var nodeInputConfigSchema = z15.record(z15.string(), z15.unknown()).optional().describe(
3543
+ var actionSchema = z18.enum(ACTIONS);
3544
+ var nodeKindSchema = z18.enum(NODE_KINDS);
3545
+ var nodeInputConfigSchema = z18.record(z18.string(), z18.unknown()).optional().describe(
2859
3546
  "kind-specific config, e.g. mcp: { url, auth?, authRef?, oauthClient?: { clientId, clientSecretRef? } } / http: { endpoint, tools } / context: { provider, bucket, \u2026 } / remote: { baseUrl, skRef }; credentials go by SecretStore reference name, never inline"
2860
3547
  );
2861
- var nodeInputVirtualizeSchema = z15.strictObject({
2862
- prefix: z15.string().optional(),
2863
- rename: z15.record(z15.string(), z15.string()).optional(),
2864
- hide: z15.array(z15.string()).optional(),
2865
- describe: z15.record(z15.string(), z15.string()).optional()
3548
+ var nodeInputVirtualizeSchema = z18.strictObject({
3549
+ prefix: z18.string().optional(),
3550
+ rename: z18.record(z18.string(), z18.string()).optional(),
3551
+ hide: z18.array(z18.string()).optional(),
3552
+ describe: z18.record(z18.string(), z18.string()).optional()
2866
3553
  }).optional().describe(
2867
3554
  "optional tool virtualization: { prefix?, rename?: {from:to}, hide?: [name], describe?: {name:text} }"
2868
3555
  );
2869
- var nodeInputSchema = z15.strictObject({
2870
- path: z15.string().min(1).describe('tree path to mount at, e.g. "docs/context7"'),
3556
+ var nodeInputSchema = z18.strictObject({
3557
+ path: z18.string().min(1).describe('tree path to mount at, e.g. "docs/context7"'),
2871
3558
  kind: nodeKindSchema.describe("node kind; determines the config shape"),
2872
- description: z15.string().min(1).describe("one-line description shown in parent ~help"),
3559
+ description: z18.string().min(1).describe("one-line description shown in parent ~help"),
2873
3560
  config: nodeInputConfigSchema,
2874
3561
  virtualize: nodeInputVirtualizeSchema
2875
3562
  });
2876
- var presenceStateSchema = z15.enum(["online", "stale", "offline"]);
2877
- var presenceSchema = z15.object({
2878
- lastSeenAt: z15.string().optional(),
3563
+ var presenceStateSchema = z18.enum(["online", "stale", "offline"]);
3564
+ var presenceSchema = z18.object({
3565
+ lastSeenAt: z18.string().optional(),
2879
3566
  state: presenceStateSchema
2880
3567
  });
2881
- var helpFeedbackItemSchema = z15.object({
2882
- id: z15.string(),
2883
- score: z15.number(),
2884
- title: z15.string()
3568
+ var helpFeedbackItemSchema = z18.object({
3569
+ id: z18.string(),
3570
+ score: z18.number(),
3571
+ title: z18.string()
2885
3572
  });
2886
- var helpChildSchema = z15.object({
2887
- description: z15.string(),
3573
+ var helpChildSchema = z18.object({
3574
+ description: z18.string(),
2888
3575
  kind: nodeKindSchema,
2889
- path: z15.string()
3576
+ path: z18.string()
2890
3577
  });
2891
- var helpCommandSchema = z15.object({
2892
- confirm: z15.boolean().optional(),
2893
- delivery: z15.enum(["realtime", "mailbox", "both"]).optional(),
2894
- effect: z15.string().optional(),
2895
- h: z15.string().optional(),
2896
- inputSchema: z15.unknown().optional(),
2897
- method: z15.literal("POST"),
2898
- name: z15.string(),
2899
- outputSchema: z15.unknown().optional(),
2900
- path: z15.string(),
2901
- returns: z15.string().optional(),
3578
+ var helpCommandSchema = z18.object({
3579
+ confirm: z18.boolean().optional(),
3580
+ delivery: z18.enum(["realtime", "mailbox", "both"]).optional(),
3581
+ effect: z18.string().optional(),
3582
+ h: z18.string().optional(),
3583
+ inputSchema: z18.unknown().optional(),
3584
+ method: z18.literal("POST"),
3585
+ name: z18.string(),
3586
+ outputSchema: z18.unknown().optional(),
3587
+ path: z18.string(),
3588
+ returns: z18.string().optional(),
2902
3589
  scope: actionSchema
2903
3590
  });
2904
- var deviceContextSchema = z15.strictObject({
3591
+ var deviceContextSchema = z18.strictObject({
2905
3592
  environment: deviceEnvironmentSchema,
2906
- reportedAt: z15.iso.datetime({ offset: true }),
3593
+ reportedAt: z18.iso.datetime({ offset: true }),
2907
3594
  presence: presenceSchema.optional()
2908
3595
  });
2909
- var helpJsonSchema = z15.object({
2910
- children: z15.array(helpChildSchema).optional(),
2911
- cmds: z15.array(helpCommandSchema),
3596
+ var helpJsonSchema = z18.object({
3597
+ children: z18.array(helpChildSchema).optional(),
3598
+ cmds: z18.array(helpCommandSchema),
2912
3599
  deviceContext: deviceContextSchema.optional(),
2913
- feedback: z15.array(helpFeedbackItemSchema).optional(),
2914
- hint: z15.string().optional(),
2915
- htbp: z15.string(),
2916
- node: z15.object({
2917
- description: z15.string(),
3600
+ feedback: z18.array(helpFeedbackItemSchema).optional(),
3601
+ hint: z18.string().optional(),
3602
+ htbp: z18.string(),
3603
+ node: z18.object({
3604
+ description: z18.string(),
2918
3605
  kind: nodeKindSchema,
2919
- path: z15.string()
3606
+ path: z18.string()
2920
3607
  }),
2921
- note: z15.string().optional()
3608
+ note: z18.string().optional()
2922
3609
  });
2923
- var treeJsonSchema = z15.lazy(() => z15.object({
2924
- children: z15.array(treeJsonSchema).optional(),
2925
- description: z15.string(),
3610
+ var treeJsonSchema = z18.lazy(() => z18.object({
3611
+ children: z18.array(treeJsonSchema).optional(),
3612
+ description: z18.string(),
2926
3613
  kind: nodeKindSchema,
2927
- path: z15.string(),
3614
+ path: z18.string(),
2928
3615
  presence: presenceSchema.optional(),
2929
- truncated: z15.boolean().optional()
3616
+ truncated: z18.boolean().optional()
2930
3617
  }));
2931
- var toolSpecSchema = z15.object({
2932
- confirm: z15.boolean().optional(),
2933
- delivery: z15.enum(["realtime", "mailbox", "both"]).optional(),
2934
- description: z15.string().optional(),
2935
- effect: z15.string().optional(),
2936
- inputSchema: z15.unknown().optional(),
2937
- name: z15.string(),
2938
- outputSchema: z15.unknown().optional()
3618
+ var toolSpecSchema = z18.object({
3619
+ confirm: z18.boolean().optional(),
3620
+ delivery: z18.enum(["realtime", "mailbox", "both"]).optional(),
3621
+ description: z18.string().optional(),
3622
+ effect: z18.string().optional(),
3623
+ inputSchema: z18.unknown().optional(),
3624
+ name: z18.string(),
3625
+ outputSchema: z18.unknown().optional()
2939
3626
  });
2940
- var toolSearchRelevanceSchema = z15.strictObject({
2941
- coverage: z15.number().min(0).max(1),
2942
- matchedTermCount: z15.number().int().nonnegative(),
2943
- rankingVersion: z15.literal("keyword-v2"),
2944
- totalTermCount: z15.number().int().positive()
3627
+ var toolSearchRelevanceSchema = z18.strictObject({
3628
+ coverage: z18.number().min(0).max(1),
3629
+ matchedTermCount: z18.number().int().nonnegative(),
3630
+ rankingVersion: z18.literal("keyword-v2"),
3631
+ totalTermCount: z18.number().int().positive()
2945
3632
  }).refine(
2946
3633
  (value) => value.matchedTermCount <= value.totalTermCount && value.coverage === value.matchedTermCount / value.totalTermCount,
2947
3634
  { message: "coverage must equal matchedTermCount / totalTermCount" }
2948
3635
  );
2949
- var toolSearchSourceSchema = z15.strictObject({
2950
- path: z15.string()
3636
+ var toolSearchSourceSchema = z18.strictObject({
3637
+ path: z18.string()
2951
3638
  });
2952
- var toolSearchSourceResultSchema = z15.strictObject({
2953
- path: z15.string(),
2954
- status: z15.enum([
3639
+ var toolSearchSourceResultSchema = z18.strictObject({
3640
+ path: z18.string(),
3641
+ status: z18.enum([
2955
3642
  "ok",
2956
3643
  "unsupported",
2957
3644
  "timed_out",
2958
3645
  "unavailable",
2959
3646
  "cycle",
2960
3647
  "hop_limit",
3648
+ "index_capacity",
2961
3649
  "budget_exhausted",
2962
3650
  "invalid_response"
2963
3651
  ])
2964
3652
  });
2965
- var toolSearchItemSchema = z15.strictObject({
2966
- path: z15.string(),
3653
+ var toolSearchItemSchema = z18.strictObject({
3654
+ path: z18.string(),
2967
3655
  relevance: toolSearchRelevanceSchema,
2968
3656
  source: toolSearchSourceSchema.optional(),
2969
3657
  tool: toolSpecSchema
2970
3658
  });
2971
3659
  function pageSchema(itemSchema) {
2972
- return z15.object({
2973
- cursor: z15.string().optional(),
2974
- items: z15.array(itemSchema)
3660
+ return z18.object({
3661
+ cursor: z18.string().optional(),
3662
+ items: z18.array(itemSchema)
2975
3663
  });
2976
3664
  }
2977
- var toolSearchPageSchema = z15.strictObject({
2978
- cursor: z15.string().optional(),
2979
- items: z15.array(toolSearchItemSchema),
2980
- partial: z15.boolean().optional(),
2981
- snapshot: z15.string().optional(),
2982
- sources: z15.array(toolSearchSourceResultSchema).optional()
3665
+ var toolSearchPageSchema = z18.strictObject({
3666
+ cursor: z18.string().optional(),
3667
+ items: z18.array(toolSearchItemSchema),
3668
+ partial: z18.boolean().optional(),
3669
+ snapshot: z18.string().optional(),
3670
+ sources: z18.array(toolSearchSourceResultSchema).optional()
2983
3671
  });
2984
- var toolSearchOptionsSchema = z15.strictObject({
2985
- cursor: z15.string().optional(),
2986
- detail: z15.enum(["compact", "full"]).optional(),
2987
- effects: z15.array(z15.enum(["read", "write", "destructive", "unknown"])).min(1).optional(),
2988
- federation: z15.enum(["local", "recursive"]).optional(),
2989
- limit: z15.number().int().optional(),
2990
- matching: z15.enum(["best", "all"]).optional(),
2991
- minCoverage: z15.number().gt(0).max(1).optional(),
2992
- mode: z15.enum(["keyword"]).optional(),
2993
- pathPrefix: z15.string().optional()
3672
+ var toolSearchOptionsSchema = z18.strictObject({
3673
+ cursor: z18.string().optional(),
3674
+ detail: z18.enum(["compact", "full"]).optional(),
3675
+ effects: z18.array(z18.enum(["read", "write", "destructive", "unknown"])).min(1).optional(),
3676
+ federation: z18.enum(["local", "recursive"]).optional(),
3677
+ limit: z18.number().int().optional(),
3678
+ matching: z18.enum(["best", "all"]).optional(),
3679
+ minCoverage: z18.number().gt(0).max(1).optional(),
3680
+ mode: z18.enum(["keyword"]).optional(),
3681
+ pathPrefix: z18.string().optional()
2994
3682
  });
2995
- var toolSearchRequestSchema = z15.strictObject({
3683
+ var toolSearchRequestSchema = z18.strictObject({
2996
3684
  opts: toolSearchOptionsSchema.optional(),
2997
- query: z15.string().trim().min(1)
3685
+ query: z18.string().trim().min(1)
2998
3686
  });
2999
- var deviceOperationStateSchema = z15.enum(
3687
+ var deviceOperationStateSchema = z18.enum(
3000
3688
  DEVICE_OPERATION_STATES
3001
3689
  );
3002
- var deviceOperationCallerSchema = z15.object({
3003
- keyId: z15.string().min(1),
3004
- owner: z15.string().min(1)
3690
+ var deviceOperationCallerSchema = z18.object({
3691
+ keyId: z18.string().min(1),
3692
+ owner: z18.string().min(1)
3005
3693
  });
3006
3694
  var deviceOperationSummaryShape = {
3007
- attempt: z15.number().int().nonnegative(),
3695
+ attempt: z18.number().int().nonnegative(),
3008
3696
  caller: deviceOperationCallerSchema,
3009
- cancelRequestedAt: z15.iso.datetime({ offset: true }).optional(),
3010
- createdAt: z15.iso.datetime({ offset: true }),
3011
- deviceId: z15.string().min(1),
3012
- executionMayHaveOccurred: z15.boolean(),
3013
- expiresAt: z15.iso.datetime({ offset: true }),
3014
- leaseUntil: z15.iso.datetime({ offset: true }).optional(),
3015
- mountPath: z15.string().min(1),
3016
- operationId: z15.string().min(1),
3697
+ cancelRequestedAt: z18.iso.datetime({ offset: true }).optional(),
3698
+ createdAt: z18.iso.datetime({ offset: true }),
3699
+ deviceId: z18.string().min(1),
3700
+ executionMayHaveOccurred: z18.boolean(),
3701
+ expiresAt: z18.iso.datetime({ offset: true }),
3702
+ leaseUntil: z18.iso.datetime({ offset: true }).optional(),
3703
+ mountPath: z18.string().min(1),
3704
+ operationId: z18.string().min(1),
3017
3705
  state: deviceOperationStateSchema,
3018
- targetPath: z15.string().min(1),
3019
- terminalAt: z15.iso.datetime({ offset: true }).optional(),
3020
- traceId: z15.string().min(1),
3021
- updatedAt: z15.iso.datetime({ offset: true })
3706
+ targetPath: z18.string().min(1),
3707
+ terminalAt: z18.iso.datetime({ offset: true }).optional(),
3708
+ traceId: z18.string().min(1),
3709
+ updatedAt: z18.iso.datetime({ offset: true })
3022
3710
  };
3023
- var deviceOperationSummarySchema = z15.object(
3711
+ var deviceOperationSummarySchema = z18.object(
3024
3712
  deviceOperationSummaryShape
3025
3713
  );
3026
- var deviceOperationDetailSchema = z15.object({
3714
+ var deviceOperationDetailSchema = z18.object({
3027
3715
  ...deviceOperationSummaryShape,
3028
3716
  error: tbErrorBodySchema.optional(),
3029
- result: z15.json().optional()
3717
+ result: z18.json().optional()
3030
3718
  });
3031
- var deviceOperationListRequestSchema = z15.strictObject({
3032
- deviceId: z15.string().min(1),
3033
- opts: z15.strictObject({
3034
- cursor: z15.string().min(1).optional(),
3035
- limit: z15.number().int().positive().optional(),
3036
- states: z15.array(deviceOperationStateSchema).min(1).optional()
3719
+ var deviceOperationListRequestSchema = z18.strictObject({
3720
+ deviceId: z18.string().min(1),
3721
+ opts: z18.strictObject({
3722
+ cursor: z18.string().min(1).optional(),
3723
+ limit: z18.number().int().positive().optional(),
3724
+ states: z18.array(deviceOperationStateSchema).min(1).optional()
3037
3725
  }).optional()
3038
3726
  });
3039
3727
  var deviceOperationListResponseSchema = pageSchema(deviceOperationSummarySchema);
3040
- var deviceOperationIdentityRequestSchema = z15.strictObject({
3041
- deviceId: z15.string().min(1),
3042
- operationId: z15.string().min(1)
3728
+ var deviceOperationIdentityRequestSchema = z18.strictObject({
3729
+ deviceId: z18.string().min(1),
3730
+ operationId: z18.string().min(1)
3043
3731
  });
3044
- var deviceOperationClaimRequestSchema = z15.strictObject({
3045
- cursor: z15.string().min(1).optional(),
3046
- deviceId: z15.string().min(1),
3047
- limit: z15.number().int().positive().optional()
3732
+ var deviceOperationClaimRequestSchema = z18.strictObject({
3733
+ cursor: z18.string().min(1).optional(),
3734
+ deviceId: z18.string().min(1),
3735
+ limit: z18.number().int().positive().optional()
3048
3736
  });
3049
- var deviceOperationClaimSchema = z15.object({
3050
- arguments: z15.record(z15.string(), z15.json()),
3051
- attempt: z15.number().int().positive(),
3737
+ var deviceOperationClaimSchema = z18.object({
3738
+ arguments: z18.record(z18.string(), z18.json()),
3739
+ attempt: z18.number().int().positive(),
3052
3740
  caller: deviceOperationCallerSchema,
3053
- cancelRequestedAt: z15.iso.datetime({ offset: true }).optional(),
3054
- createdAt: z15.iso.datetime({ offset: true }),
3055
- expiresAt: z15.iso.datetime({ offset: true }),
3056
- leaseId: z15.string().min(1),
3057
- leaseUntil: z15.iso.datetime({ offset: true }),
3058
- operationId: z15.string().min(1),
3059
- path: z15.string().min(1),
3060
- targetPath: z15.string().min(1),
3061
- traceId: z15.string().min(1)
3741
+ cancelRequestedAt: z18.iso.datetime({ offset: true }).optional(),
3742
+ createdAt: z18.iso.datetime({ offset: true }),
3743
+ expiresAt: z18.iso.datetime({ offset: true }),
3744
+ leaseId: z18.string().min(1),
3745
+ leaseUntil: z18.iso.datetime({ offset: true }),
3746
+ operationId: z18.string().min(1),
3747
+ path: z18.string().min(1),
3748
+ targetPath: z18.string().min(1),
3749
+ traceId: z18.string().min(1)
3062
3750
  });
3063
- var deviceOperationClaimResponseSchema = z15.object({
3064
- cursor: z15.string().optional(),
3751
+ var deviceOperationClaimResponseSchema = z18.object({
3752
+ cursor: z18.string().optional(),
3065
3753
  operation: deviceOperationClaimSchema.optional(),
3066
- serverNow: z15.iso.datetime({ offset: true })
3754
+ serverNow: z18.iso.datetime({ offset: true })
3067
3755
  });
3068
3756
  var deviceOperationLeaseShape = {
3069
- deviceId: z15.string().min(1),
3070
- leaseId: z15.string().min(1),
3071
- operationId: z15.string().min(1)
3757
+ deviceId: z18.string().min(1),
3758
+ leaseId: z18.string().min(1),
3759
+ operationId: z18.string().min(1)
3072
3760
  };
3073
- var deviceOperationRenewRequestSchema = z15.strictObject(deviceOperationLeaseShape);
3074
- var deviceOperationRenewResponseSchema = z15.object({
3075
- cancelRequestedAt: z15.iso.datetime({ offset: true }).optional(),
3076
- leaseUntil: z15.iso.datetime({ offset: true }),
3077
- serverNow: z15.iso.datetime({ offset: true })
3761
+ var deviceOperationRenewRequestSchema = z18.strictObject(deviceOperationLeaseShape);
3762
+ var deviceOperationRenewResponseSchema = z18.object({
3763
+ cancelRequestedAt: z18.iso.datetime({ offset: true }).optional(),
3764
+ leaseUntil: z18.iso.datetime({ offset: true }),
3765
+ serverNow: z18.iso.datetime({ offset: true })
3078
3766
  });
3079
- var deviceOperationCompleteRequestSchema = z15.discriminatedUnion("outcome", [
3080
- z15.strictObject({
3767
+ var deviceOperationCompleteRequestSchema = z18.discriminatedUnion("outcome", [
3768
+ z18.strictObject({
3081
3769
  ...deviceOperationLeaseShape,
3082
- outcome: z15.literal("succeeded"),
3083
- result: z15.json()
3770
+ outcome: z18.literal("succeeded"),
3771
+ result: z18.json()
3084
3772
  }),
3085
- z15.strictObject({
3773
+ z18.strictObject({
3086
3774
  ...deviceOperationLeaseShape,
3087
3775
  error: tbErrorBodySchema,
3088
- outcome: z15.literal("rejected")
3776
+ outcome: z18.literal("rejected")
3089
3777
  }),
3090
- z15.strictObject({
3778
+ z18.strictObject({
3091
3779
  ...deviceOperationLeaseShape,
3092
3780
  error: tbErrorBodySchema,
3093
- outcome: z15.literal("failed")
3781
+ outcome: z18.literal("failed")
3094
3782
  }),
3095
- z15.strictObject({
3783
+ z18.strictObject({
3096
3784
  ...deviceOperationLeaseShape,
3097
3785
  error: tbErrorBodySchema.optional(),
3098
- outcome: z15.literal("result_unknown")
3786
+ outcome: z18.literal("result_unknown")
3099
3787
  })
3100
3788
  ]);
3101
- var registryNodeSchema = z15.object({
3102
- config: z15.record(z15.string(), z15.unknown()).optional(),
3103
- createdAt: z15.string().optional(),
3104
- description: z15.string(),
3105
- deviceId: z15.string().optional(),
3789
+ var registryNodeSchema = z18.object({
3790
+ config: z18.record(z18.string(), z18.unknown()).optional(),
3791
+ createdAt: z18.string().optional(),
3792
+ description: z18.string(),
3793
+ deviceId: z18.string().optional(),
3106
3794
  deviceEnvironment: deviceEnvironmentSchema.optional(),
3107
- deviceReportedAt: z15.iso.datetime({ offset: true }).optional(),
3795
+ deviceReportedAt: z18.iso.datetime({ offset: true }).optional(),
3108
3796
  kind: nodeKindSchema,
3109
- lastSeenAt: z15.string().optional(),
3110
- online: z15.boolean().optional(),
3111
- path: z15.string(),
3112
- registeredBy: z15.string().optional(),
3113
- updatedAt: z15.string().optional(),
3114
- virtualize: z15.record(z15.string(), z15.unknown()).optional()
3797
+ lastSeenAt: z18.string().optional(),
3798
+ online: z18.boolean().optional(),
3799
+ path: z18.string(),
3800
+ registeredBy: z18.string().optional(),
3801
+ updatedAt: z18.string().optional(),
3802
+ virtualize: z18.record(z18.string(), z18.unknown()).optional()
3115
3803
  });
3116
3804
  var feedbackViewShape = {
3117
- at: z15.string(),
3118
- by: z15.string(),
3119
- down: z15.number().int().nonnegative(),
3120
- id: z15.string(),
3121
- score: z15.number().int(),
3122
- title: z15.string(),
3123
- up: z15.number().int().nonnegative()
3805
+ at: z18.string(),
3806
+ by: z18.string(),
3807
+ down: z18.number().int().nonnegative(),
3808
+ id: z18.string(),
3809
+ score: z18.number().int(),
3810
+ title: z18.string(),
3811
+ up: z18.number().int().nonnegative()
3124
3812
  };
3125
- var feedbackViewSchema = z15.object(feedbackViewShape);
3126
- var feedbackDetailSchema = z15.object({
3813
+ var feedbackViewSchema = z18.object(feedbackViewShape);
3814
+ var feedbackDetailSchema = z18.object({
3127
3815
  ...feedbackViewShape,
3128
- detail: z15.string(),
3129
- path: z15.string()
3816
+ detail: z18.string(),
3817
+ path: z18.string()
3130
3818
  });
3131
- var feedbackListSchema = z15.object({ items: z15.array(feedbackViewSchema) });
3132
- var feedbackSubmitRequestSchema = z15.strictObject({
3133
- detail: z15.string(),
3134
- title: z15.string()
3819
+ var feedbackListSchema = z18.object({ items: z18.array(feedbackViewSchema) });
3820
+ var feedbackSubmitRequestSchema = z18.strictObject({
3821
+ detail: z18.string(),
3822
+ title: z18.string()
3135
3823
  });
3136
- var feedbackSubmitResponseSchema = z15.object({
3137
- at: z15.string().optional(),
3138
- id: z15.string(),
3139
- path: z15.string(),
3140
- title: z15.string()
3824
+ var feedbackSubmitResponseSchema = z18.object({
3825
+ at: z18.string().optional(),
3826
+ id: z18.string(),
3827
+ path: z18.string(),
3828
+ title: z18.string()
3141
3829
  });
3142
- var feedbackVoteRequestSchema = z15.strictObject({
3143
- vote: z15.enum(["up", "down", "clear"])
3830
+ var feedbackVoteRequestSchema = z18.strictObject({
3831
+ vote: z18.enum(["up", "down", "clear"])
3144
3832
  });
3145
- var feedbackRemoveResponseSchema = z15.object({ ok: z15.literal(true) });
3146
- var oauthAuthorizeRequestSchema = z15.strictObject({
3147
- redirectUri: z15.string().optional()
3833
+ var feedbackRemoveResponseSchema = z18.object({ ok: z18.literal(true) });
3834
+ var oauthAuthorizeRequestSchema = z18.strictObject({
3835
+ redirectUri: z18.string().optional()
3148
3836
  });
3149
- var oauthAuthorizeResponseSchema = z15.discriminatedUnion("status", [
3150
- z15.object({ status: z15.literal("authorized") }),
3151
- z15.object({ authorizationUrl: z15.url(), status: z15.literal("redirect") })
3837
+ var oauthAuthorizeResponseSchema = z18.discriminatedUnion("status", [
3838
+ z18.object({ status: z18.literal("authorized") }),
3839
+ z18.object({ authorizationUrl: z18.url(), status: z18.literal("redirect") })
3152
3840
  ]);
3153
- var healthResponseSchema = z15.object({
3154
- catalog: z15.object({
3155
- count: z15.number().int().nonnegative(),
3156
- digest: z15.string()
3841
+ var healthResponseSchema = z18.object({
3842
+ catalog: z18.object({
3843
+ count: z18.number().int().nonnegative(),
3844
+ digest: z18.string()
3157
3845
  }).optional(),
3158
- healthy: z15.boolean(),
3159
- version: z15.string()
3846
+ healthy: z18.boolean(),
3847
+ version: z18.string()
3160
3848
  });
3161
- var livenessResponseSchema = z15.object({ live: z15.boolean() });
3162
- var readinessResponseSchema = z15.object({
3163
- checks: z15.record(z15.string(), z15.object({
3164
- detail: z15.string().optional(),
3165
- ok: z15.boolean()
3849
+ var livenessResponseSchema = z18.object({ live: z18.boolean() });
3850
+ var readinessResponseSchema = z18.object({
3851
+ checks: z18.record(z18.string(), z18.object({
3852
+ detail: z18.string().optional(),
3853
+ ok: z18.boolean()
3166
3854
  })),
3167
- ready: z15.boolean()
3855
+ ready: z18.boolean()
3168
3856
  });
3169
3857
 
3170
3858
  // ../core/src/builtin/registry.ts
@@ -3187,8 +3875,8 @@ var COMMANDS6 = new BuiltinCommandRegistry("registry", DESCRIPTION6).register(
3187
3875
  "list",
3188
3876
  {
3189
3877
  h: "list registered nodes, optionally under a path prefix",
3190
- inputSchema: z16.strictObject({
3191
- prefix: z16.string().optional().describe("only nodes under this path prefix"),
3878
+ inputSchema: z19.strictObject({
3879
+ prefix: z19.string().optional().describe("only nodes under this path prefix"),
3192
3880
  opts: HTBP_LIST_OPTIONS_SCHEMA.optional()
3193
3881
  }),
3194
3882
  returns: "Page<Node>",
@@ -3204,8 +3892,8 @@ var COMMANDS6 = new BuiltinCommandRegistry("registry", DESCRIPTION6).register(
3204
3892
  "get",
3205
3893
  {
3206
3894
  h: "fetch one node registration (kind, description, config) by path",
3207
- inputSchema: z16.strictObject({
3208
- path: z16.string().min(1).describe("exact tree path")
3895
+ inputSchema: z19.strictObject({
3896
+ path: z19.string().min(1).describe("exact tree path")
3209
3897
  }),
3210
3898
  returns: "Node",
3211
3899
  scope: "read"
@@ -3229,8 +3917,8 @@ var COMMANDS6 = new BuiltinCommandRegistry("registry", DESCRIPTION6).register(
3229
3917
  "update",
3230
3918
  {
3231
3919
  h: "patch fields of a mounted node (description, config, virtualize, \u2026) without remounting",
3232
- inputSchema: z16.strictObject({
3233
- path: z16.string().min(1).describe("exact tree path"),
3920
+ inputSchema: z19.strictObject({
3921
+ path: z19.string().min(1).describe("exact tree path"),
3234
3922
  patch: nodePatchSchema
3235
3923
  }),
3236
3924
  returns: "Node",
@@ -3241,8 +3929,8 @@ var COMMANDS6 = new BuiltinCommandRegistry("registry", DESCRIPTION6).register(
3241
3929
  "delete",
3242
3930
  {
3243
3931
  h: "unmount a node (and reclaim empty auto-created parents); a node registered by another key can only be removed by its registrar or by a key holding the 'admin' scope on that path",
3244
- inputSchema: z16.strictObject({
3245
- path: z16.string().min(1).describe("exact tree path")
3932
+ inputSchema: z19.strictObject({
3933
+ path: z19.string().min(1).describe("exact tree path")
3246
3934
  }),
3247
3935
  returns: "void",
3248
3936
  scope: "register"
@@ -3257,7 +3945,7 @@ function createRegistryModule(store, now, visibility) {
3257
3945
  }
3258
3946
 
3259
3947
  // ../core/src/builtin/secret.ts
3260
- import { z as z17 } from "zod/v4";
3948
+ import { z as z20 } from "zod/v4";
3261
3949
  var DESCRIPTION7 = "Upstream credential vault: write-only; mounts reference entries by name (authRef), values can never be read back (admin only)";
3262
3950
  function assertUserSecretName(name) {
3263
3951
  if (name.includes(":")) {
@@ -3271,11 +3959,11 @@ var COMMANDS7 = new BuiltinCommandRegistry("secret", DESCRIPTION7).register(
3271
3959
  "set",
3272
3960
  {
3273
3961
  h: "store or rotate a credential under a name; mount configs reference it as authRef",
3274
- inputSchema: z17.strictObject({
3275
- name: z17.string().min(1).describe(
3962
+ inputSchema: z20.strictObject({
3963
+ name: z20.string().min(1).describe(
3276
3964
  'reference name used as authRef in mount configs (":" is reserved)'
3277
3965
  ),
3278
- value: z17.string().min(1).describe(
3966
+ value: z20.string().min(1).describe(
3279
3967
  "the credential (token / key / JSON); encrypted at rest, never echoed"
3280
3968
  )
3281
3969
  }),
@@ -3291,7 +3979,7 @@ var COMMANDS7 = new BuiltinCommandRegistry("secret", DESCRIPTION7).register(
3291
3979
  "list",
3292
3980
  {
3293
3981
  h: "list stored credential names (names and timestamps only, never values)",
3294
- inputSchema: z17.strictObject({ opts: HTBP_LIST_OPTIONS_SCHEMA.optional() }),
3982
+ inputSchema: z20.strictObject({ opts: HTBP_LIST_OPTIONS_SCHEMA.optional() }),
3295
3983
  returns: "Page<{ name, updatedAt }>",
3296
3984
  scope: "admin"
3297
3985
  },
@@ -3300,8 +3988,8 @@ var COMMANDS7 = new BuiltinCommandRegistry("secret", DESCRIPTION7).register(
3300
3988
  "delete",
3301
3989
  {
3302
3990
  h: "delete a credential; mounts still referencing it will fail to resolve",
3303
- inputSchema: z17.strictObject({
3304
- name: z17.string().min(1).describe("reference name")
3991
+ inputSchema: z20.strictObject({
3992
+ name: z20.string().min(1).describe("reference name")
3305
3993
  }),
3306
3994
  returns: "void",
3307
3995
  scope: "admin"
@@ -3317,13 +4005,13 @@ function createSecretModule(store, now) {
3317
4005
  }
3318
4006
 
3319
4007
  // ../core/src/builtin/status.ts
3320
- import { z as z18 } from "zod/v4";
4008
+ import { z as z21 } from "zod/v4";
3321
4009
  var DESCRIPTION8 = "Gateway health and summary (readable without admin)";
3322
4010
  var COMMANDS8 = new BuiltinCommandRegistry("status", DESCRIPTION8).register(
3323
4011
  "get",
3324
4012
  {
3325
4013
  h: "health summary: gateway version and node count; no arguments",
3326
- inputSchema: z18.strictObject({}),
4014
+ inputSchema: z21.strictObject({}),
3327
4015
  returns: "{ healthy, version, nodeCount }",
3328
4016
  scope: "read"
3329
4017
  },
@@ -3341,41 +4029,41 @@ function createStatusModule(deps) {
3341
4029
  }
3342
4030
 
3343
4031
  // ../core/src/builtin/sk.ts
3344
- import { z as z19 } from "zod/v4";
4032
+ import { z as z22 } from "zod/v4";
3345
4033
  var DESCRIPTION9 = "Secret Key registry: issue / list / update / revoke access keys (the only credential form; admin only)";
3346
- var actionSchema2 = z19.enum(["read", "write", "call", "register", "admin"]);
3347
- var scopeSchema = z19.strictObject({
3348
- pattern: z19.string().describe('tree path glob, e.g. "**" (everything) or "docs/**"'),
3349
- actions: z19.array(actionSchema2),
3350
- effect: z19.enum(["allow", "deny"]).optional().describe('default "allow"')
4034
+ var actionSchema2 = z22.enum(["read", "write", "call", "register", "admin"]);
4035
+ var scopeSchema = z22.strictObject({
4036
+ pattern: z22.string().describe('tree path glob, e.g. "**" (everything) or "docs/**"'),
4037
+ actions: z22.array(actionSchema2),
4038
+ effect: z22.enum(["allow", "deny"]).optional().describe('default "allow"')
3351
4039
  });
3352
- var ownerSchema = z19.string().min(1).describe(
4040
+ var ownerSchema = z22.string().min(1).describe(
3353
4041
  'owner ref: "user:<name>" | "agent:<name>" | "device:<id>"'
3354
4042
  );
3355
- var descriptionSchema = z19.string().optional().describe("what this key is for (shown in list)");
3356
- var scopesSchema = z19.array(scopeSchema).describe(
4043
+ var descriptionSchema = z22.string().optional().describe("what this key is for (shown in list)");
4044
+ var scopesSchema = z22.array(scopeSchema).describe(
3357
4045
  "permission grants; deny wins over allow, no match = denied"
3358
4046
  );
3359
- var registerPathsSchema = z19.array(z19.string()).optional().describe(
4047
+ var registerPathsSchema = z22.array(z22.string()).optional().describe(
3360
4048
  "path prefixes this key may self-register nodes under (via ~register)"
3361
4049
  );
3362
- var expiresAtSchema = z19.string().optional().describe(
4050
+ var expiresAtSchema = z22.string().optional().describe(
3363
4051
  "expiry, ISO 8601 timestamp with timezone; omit = never"
3364
4052
  );
3365
- var writeSchema = z19.strictObject({
4053
+ var writeSchema = z22.strictObject({
3366
4054
  owner: ownerSchema,
3367
4055
  description: descriptionSchema,
3368
4056
  scopes: scopesSchema,
3369
4057
  registerPaths: registerPathsSchema,
3370
4058
  expiresAt: expiresAtSchema
3371
4059
  });
3372
- var patchSchema2 = z19.strictObject({
4060
+ var patchSchema2 = z22.strictObject({
3373
4061
  owner: ownerSchema.optional(),
3374
4062
  description: descriptionSchema,
3375
4063
  scopes: scopesSchema.optional(),
3376
4064
  registerPaths: registerPathsSchema,
3377
4065
  expiresAt: expiresAtSchema,
3378
- disabled: z19.boolean().optional().describe("true = key rejected until re-enabled")
4066
+ disabled: z22.boolean().optional().describe("true = key rejected until re-enabled")
3379
4067
  }).describe("fields to change; same shape as write (all optional) plus disabled");
3380
4068
  function toSecretKeyInput(input) {
3381
4069
  return {
@@ -3400,7 +4088,7 @@ var COMMANDS9 = new BuiltinCommandRegistry("sk", DESCRIPTION9).register(
3400
4088
  "list",
3401
4089
  {
3402
4090
  h: "list issued keys (id, owner, scopes; the secret itself is never returned)",
3403
- inputSchema: z19.strictObject({ opts: HTBP_LIST_OPTIONS_SCHEMA.optional() }),
4091
+ inputSchema: z22.strictObject({ opts: HTBP_LIST_OPTIONS_SCHEMA.optional() }),
3404
4092
  returns: "Page<SecretKey without hash>",
3405
4093
  scope: "admin"
3406
4094
  },
@@ -3409,8 +4097,8 @@ var COMMANDS9 = new BuiltinCommandRegistry("sk", DESCRIPTION9).register(
3409
4097
  "get",
3410
4098
  {
3411
4099
  h: "fetch one key by id",
3412
- inputSchema: z19.strictObject({
3413
- id: z19.string().min(1).describe("key id (from list or the issue response)")
4100
+ inputSchema: z22.strictObject({
4101
+ id: z22.string().min(1).describe("key id (from list or the issue response)")
3414
4102
  }),
3415
4103
  returns: "SecretKey without hash",
3416
4104
  scope: "admin"
@@ -3429,8 +4117,8 @@ var COMMANDS9 = new BuiltinCommandRegistry("sk", DESCRIPTION9).register(
3429
4117
  "update",
3430
4118
  {
3431
4119
  h: "patch fields of an issued key (scopes, expiresAt, disabled, \u2026); takes effect immediately",
3432
- inputSchema: z19.strictObject({
3433
- id: z19.string().min(1).describe("key id"),
4120
+ inputSchema: z22.strictObject({
4121
+ id: z22.string().min(1).describe("key id"),
3434
4122
  patch: patchSchema2
3435
4123
  }),
3436
4124
  returns: "SecretKey without hash",
@@ -3441,7 +4129,7 @@ var COMMANDS9 = new BuiltinCommandRegistry("sk", DESCRIPTION9).register(
3441
4129
  "delete",
3442
4130
  {
3443
4131
  h: "revoke a key permanently; takes effect immediately",
3444
- inputSchema: z19.strictObject({ id: z19.string().min(1).describe("key id") }),
4132
+ inputSchema: z22.strictObject({ id: z22.string().min(1).describe("key id") }),
3445
4133
  returns: "void",
3446
4134
  scope: "admin"
3447
4135
  },
@@ -3455,24 +4143,24 @@ function createSkModule(store, now) {
3455
4143
  }
3456
4144
 
3457
4145
  // ../core/src/builtin/keys.ts
3458
- import { z as z21 } from "zod";
4146
+ import { z as z24 } from "zod";
3459
4147
 
3460
4148
  // ../core/src/keyManagement.ts
3461
- import { z as z20 } from "zod";
3462
- var keyRotateSchema = z20.strictObject({
3463
- expectedRevision: z20.number().int().nonnegative(),
3464
- target: z20.enum(["encryption", "signing"]),
3465
- revokeExisting: z20.boolean().optional()
4149
+ import { z as z23 } from "zod";
4150
+ var keyRotateSchema = z23.strictObject({
4151
+ expectedRevision: z23.number().int().nonnegative(),
4152
+ target: z23.enum(["encryption", "signing"]),
4153
+ revokeExisting: z23.boolean().optional()
3466
4154
  });
3467
- var keyRetireSchema = z20.strictObject({
3468
- expectedRevision: z20.number().int().nonnegative(),
3469
- keyId: z20.string().regex(/^[A-Za-z0-9_-]{1,64}$/),
3470
- target: z20.enum(["encryption", "signing"])
4155
+ var keyRetireSchema = z23.strictObject({
4156
+ expectedRevision: z23.number().int().nonnegative(),
4157
+ keyId: z23.string().regex(/^[A-Za-z0-9_-]{1,64}$/),
4158
+ target: z23.enum(["encryption", "signing"])
3471
4159
  });
3472
- var keyResumeSchema = z20.strictObject({ jobId: z20.string().min(1).max(128) });
4160
+ var keyResumeSchema = z23.strictObject({ jobId: z23.string().min(1).max(128) });
3473
4161
 
3474
4162
  // ../core/src/builtin/keys.ts
3475
- var commands = new BuiltinCommandRegistry("keys", "\u52A0\u5BC6\u6839\u3001\u7B7E\u540D\u5BC6\u94A5\u4E0E\u53EF\u6062\u590D\u8F6E\u6362\uFF08\u7BA1\u7406\u5458\uFF09").register("status", { inputSchema: z21.strictObject({}), scope: "admin", h: "\u67E5\u770B\u5BC6\u94A5\u7248\u672C\u3001\u5F15\u7528\u548C\u8F6E\u6362\u8FDB\u5EA6\uFF0C\u4E0D\u542B\u6839\u6750\u6599", returns: "KeyStatus" }, async (_, { deps }) => deps.status()).register("rotate", { inputSchema: keyRotateSchema, scope: "admin", h: "\u7EF4\u62A4\u7A97\u53E3\u5185\u751F\u6210\u65B0\u6839\uFF1B\u65E7\u6839\u9ED8\u8BA4\u4FDD\u7559\uFF0C\u91CD\u52A0\u5BC6\u53EF\u6062\u590D", returns: "KeyStatus" }, async (input, { deps }) => deps.rotate(input)).register("resume", { inputSchema: keyResumeSchema, scope: "admin", h: "\u7EE7\u7EED\u4E00\u6279\u91CD\u52A0\u5BC6\u4EFB\u52A1\uFF0C\u5B8C\u6210\u540E\u68C0\u67E5\u65E7\u5BC6\u6587\u5F15\u7528", returns: "KeyStatus" }, async (input, { deps }) => deps.resume(input)).register("retire", { inputSchema: keyRetireSchema, scope: "admin", h: "\u4EC5\u5728\u65E0\u5F15\u7528\u4E14\u7B7E\u540D\u5B89\u5168\u7A97\u53E3\u5DF2\u8FC7\u540E\u5220\u9664\u65E7\u6839", returns: "KeyStatus" }, async (input, { deps }) => deps.retire(input)).register("backup", { inputSchema: z21.strictObject({}), scope: "admin", h: "\u663E\u5F0F\u5BFC\u51FA\u5305\u542B\u5BC6\u94A5\u7684\u5B9E\u4F8B\u6062\u590D\u6587\u4EF6\uFF1B\u8BF7\u5B89\u5168\u4FDD\u5B58", returns: "KeyBackup" }, async (_, { deps }) => deps.backup());
4163
+ var commands = new BuiltinCommandRegistry("keys", "\u52A0\u5BC6\u6839\u3001\u7B7E\u540D\u5BC6\u94A5\u4E0E\u53EF\u6062\u590D\u8F6E\u6362\uFF08\u7BA1\u7406\u5458\uFF09").register("status", { inputSchema: z24.strictObject({}), scope: "admin", h: "\u67E5\u770B\u5BC6\u94A5\u7248\u672C\u3001\u5F15\u7528\u548C\u8F6E\u6362\u8FDB\u5EA6\uFF0C\u4E0D\u542B\u6839\u6750\u6599", returns: "KeyStatus" }, async (_, { deps }) => deps.status()).register("rotate", { inputSchema: keyRotateSchema, scope: "admin", h: "\u7EF4\u62A4\u7A97\u53E3\u5185\u751F\u6210\u65B0\u6839\uFF1B\u65E7\u6839\u9ED8\u8BA4\u4FDD\u7559\uFF0C\u91CD\u52A0\u5BC6\u53EF\u6062\u590D", returns: "KeyStatus" }, async (input, { deps }) => deps.rotate(input)).register("resume", { inputSchema: keyResumeSchema, scope: "admin", h: "\u7EE7\u7EED\u4E00\u6279\u91CD\u52A0\u5BC6\u4EFB\u52A1\uFF0C\u5B8C\u6210\u540E\u68C0\u67E5\u65E7\u5BC6\u6587\u5F15\u7528", returns: "KeyStatus" }, async (input, { deps }) => deps.resume(input)).register("retire", { inputSchema: keyRetireSchema, scope: "admin", h: "\u4EC5\u5728\u65E0\u5F15\u7528\u4E14\u7B7E\u540D\u5B89\u5168\u7A97\u53E3\u5DF2\u8FC7\u540E\u5220\u9664\u65E7\u6839", returns: "KeyStatus" }, async (input, { deps }) => deps.retire(input)).register("backup", { inputSchema: z24.strictObject({}), scope: "admin", h: "\u663E\u5F0F\u5BFC\u51FA\u5305\u542B\u5BC6\u94A5\u7684\u5B9E\u4F8B\u6062\u590D\u6587\u4EF6\uFF1B\u8BF7\u5B89\u5168\u4FDD\u5B58", returns: "KeyBackup" }, async (_, { deps }) => deps.backup());
3476
4164
  var createKeysModule = (deps) => commands.module(deps);
3477
4165
 
3478
4166
  // ../core/src/builtin/index.ts
@@ -3517,47 +4205,47 @@ function createBuiltins(deps) {
3517
4205
  }
3518
4206
 
3519
4207
  // ../core/src/builtin/deployment.ts
3520
- import { z as z23 } from "zod";
4208
+ import { z as z26 } from "zod";
3521
4209
 
3522
4210
  // ../core/src/deployment.ts
3523
- import { z as z22 } from "zod";
3524
- var directory = z22.string().min(2).startsWith("/").refine((value) => !/(?:^|\/)\.\.(?:\/|$)/.test(value) && !/^\/(?:etc|proc|sys|dev|var\/run)(?:\/|$)/.test(value), "\u8BF7\u9009\u62E9\u90E8\u7F72\u76EE\u5F55\u5185\u7684\u7EDD\u5BF9\u8DEF\u5F84");
3525
- var deploymentSettingsSchema = z22.strictObject({
3526
- image: z22.string().min(1).max(512).regex(/^[a-zA-Z0-9][a-zA-Z0-9._:/@-]*$/).describe("\u5E94\u7528\u955C\u50CF"),
3527
- hostPort: z22.number().int().min(1).max(65535).describe("\u5BBF\u4E3B\u8BBF\u95EE\u7AEF\u53E3"),
3528
- bindAddress: z22.enum(["127.0.0.1", "0.0.0.0"]).describe("\u76D1\u542C\u8303\u56F4"),
4211
+ import { z as z25 } from "zod";
4212
+ var directory = z25.string().min(2).startsWith("/").refine((value) => !/(?:^|\/)\.\.(?:\/|$)/.test(value) && !/^\/(?:etc|proc|sys|dev|var\/run)(?:\/|$)/.test(value), "\u8BF7\u9009\u62E9\u90E8\u7F72\u76EE\u5F55\u5185\u7684\u7EDD\u5BF9\u8DEF\u5F84");
4213
+ var deploymentSettingsSchema = z25.strictObject({
4214
+ image: z25.string().min(1).max(512).regex(/^[a-zA-Z0-9][a-zA-Z0-9._:/@-]*$/).describe("\u5E94\u7528\u955C\u50CF"),
4215
+ hostPort: z25.number().int().min(1).max(65535).describe("\u5BBF\u4E3B\u8BBF\u95EE\u7AEF\u53E3"),
4216
+ bindAddress: z25.enum(["127.0.0.1", "0.0.0.0"]).describe("\u76D1\u542C\u8303\u56F4"),
3529
4217
  stateDirectory: directory.optional().describe("\u5BBF\u4E3B\u6570\u636E\u76EE\u5F55\uFF08\u53EF\u9009\uFF09"),
3530
4218
  uiDirectory: directory.optional().describe("\u5BBF\u4E3B\u7BA1\u7406\u754C\u9762\u76EE\u5F55\uFF08\u53EF\u9009\uFF09")
3531
4219
  });
3532
- var deploymentUpdateSchema = z22.strictObject({ expectedRevision: z22.number().int().nonnegative(), settings: deploymentSettingsSchema });
3533
- var deploymentClaimSchema = z22.strictObject({ agentId: z22.string().min(1).max(128), instanceId: z22.string().min(1), observed: deploymentSettingsSchema });
3534
- var deploymentCompleteSchema = z22.strictObject({ jobId: z22.string().min(1), leaseToken: z22.string().min(1), ok: z22.boolean(), error: z22.enum(["preflight_failed", "apply_failed", "health_failed", "rollback_failed"]).optional() });
4220
+ var deploymentUpdateSchema = z25.strictObject({ expectedRevision: z25.number().int().nonnegative(), settings: deploymentSettingsSchema });
4221
+ var deploymentClaimSchema = z25.strictObject({ agentId: z25.string().min(1).max(128), instanceId: z25.string().min(1), observed: deploymentSettingsSchema });
4222
+ var deploymentCompleteSchema = z25.strictObject({ jobId: z25.string().min(1), leaseToken: z25.string().min(1), ok: z25.boolean(), error: z25.enum(["preflight_failed", "apply_failed", "health_failed", "rollback_failed"]).optional() });
3535
4223
 
3536
4224
  // ../core/src/builtin/deployment.ts
3537
- var commands2 = new BuiltinCommandRegistry("deployment", "\u90E8\u7F72\u6267\u884C\u5668\u3001\u671F\u671B\u914D\u7F6E\u4E0E\u5B9E\u9645\u751F\u6548\u72B6\u6001\uFF08\u7BA1\u7406\u5458\uFF09").register("schema", { inputSchema: z23.strictObject({}), scope: "admin", h: "\u67E5\u8BE2\u90E8\u7F72\u8BBE\u7F6E\u5B57\u6BB5", returns: "JSON Schema" }, async () => z23.toJSONSchema(deploymentSettingsSchema)).register("get", { inputSchema: z23.strictObject({}), scope: "admin", h: "\u8BFB\u53D6\u90E8\u7F72\u914D\u7F6E\u4E0E\u6267\u884C\u5668\u72B6\u6001", returns: "DeploymentStatus" }, async (_, { deps }) => deps.get()).register("status", { inputSchema: z23.strictObject({}), scope: "admin", h: "\u6838\u5BF9\u90E8\u7F72\u4EFB\u52A1\u4E0E\u5DF2\u5E94\u7528\u7248\u672C", returns: "DeploymentStatus" }, async (_, { deps }) => deps.get()).register("update", { inputSchema: deploymentUpdateSchema, scope: "admin", h: "\u4FDD\u5B58\u914D\u7F6E\u5E76\u521B\u5EFA\u767D\u540D\u5355\u90E8\u7F72\u4EFB\u52A1", returns: "DeploymentStatus" }, async (input, { deps }) => deps.update(input)).register("claim", { inputSchema: deploymentClaimSchema, scope: "admin", h: "\u672C\u673A\u6267\u884C\u5668\u72EC\u5360\u9886\u53D6\u56FA\u5B9A\u90E8\u7F72\u4EFB\u52A1", returns: "{job:DeploymentClaim|null}" }, async (input, { deps }) => deps.claim(input)).register("complete", { inputSchema: deploymentCompleteSchema, scope: "admin", h: "\u63D0\u4EA4\u5B9E\u4F8B\u68C0\u67E5\u6216\u6062\u590D\u7ED3\u679C", returns: "DeploymentStatus" }, async (input, { deps }) => deps.complete(input));
4225
+ var commands2 = new BuiltinCommandRegistry("deployment", "\u90E8\u7F72\u6267\u884C\u5668\u3001\u671F\u671B\u914D\u7F6E\u4E0E\u5B9E\u9645\u751F\u6548\u72B6\u6001\uFF08\u7BA1\u7406\u5458\uFF09").register("schema", { inputSchema: z26.strictObject({}), scope: "admin", h: "\u67E5\u8BE2\u90E8\u7F72\u8BBE\u7F6E\u5B57\u6BB5", returns: "JSON Schema" }, async () => z26.toJSONSchema(deploymentSettingsSchema)).register("get", { inputSchema: z26.strictObject({}), scope: "admin", h: "\u8BFB\u53D6\u90E8\u7F72\u914D\u7F6E\u4E0E\u6267\u884C\u5668\u72B6\u6001", returns: "DeploymentStatus" }, async (_, { deps }) => deps.get()).register("status", { inputSchema: z26.strictObject({}), scope: "admin", h: "\u6838\u5BF9\u90E8\u7F72\u4EFB\u52A1\u4E0E\u5DF2\u5E94\u7528\u7248\u672C", returns: "DeploymentStatus" }, async (_, { deps }) => deps.get()).register("update", { inputSchema: deploymentUpdateSchema, scope: "admin", h: "\u4FDD\u5B58\u914D\u7F6E\u5E76\u521B\u5EFA\u767D\u540D\u5355\u90E8\u7F72\u4EFB\u52A1", returns: "DeploymentStatus" }, async (input, { deps }) => deps.update(input)).register("claim", { inputSchema: deploymentClaimSchema, scope: "admin", h: "\u672C\u673A\u6267\u884C\u5668\u72EC\u5360\u9886\u53D6\u56FA\u5B9A\u90E8\u7F72\u4EFB\u52A1", returns: "{job:DeploymentClaim|null}" }, async (input, { deps }) => deps.claim(input)).register("complete", { inputSchema: deploymentCompleteSchema, scope: "admin", h: "\u63D0\u4EA4\u5B9E\u4F8B\u68C0\u67E5\u6216\u6062\u590D\u7ED3\u679C", returns: "DeploymentStatus" }, async (input, { deps }) => deps.complete(input));
3538
4226
  var createDeploymentModule = (deps) => commands2.module(deps);
3539
4227
 
3540
4228
  // ../core/src/builtin/maintenance.ts
3541
- import { z as z25 } from "zod";
4229
+ import { z as z28 } from "zod";
3542
4230
 
3543
4231
  // ../core/src/maintenance.ts
3544
- import { z as z24 } from "zod";
3545
- var revision = z24.number().int().nonnegative();
3546
- var databaseUrl = z24.string().min(1).max(8192);
3547
- var databaseMigrationSchema = z24.strictObject({
4232
+ import { z as z27 } from "zod";
4233
+ var revision = z27.number().int().nonnegative();
4234
+ var databaseUrl = z27.string().min(1).max(8192);
4235
+ var databaseMigrationSchema = z27.strictObject({
3548
4236
  expectedRevision: revision,
3549
- expectedInstanceId: z24.string().min(1),
4237
+ expectedInstanceId: z27.string().min(1),
3550
4238
  databaseUrl
3551
4239
  });
3552
- var databaseCredentialRotationSchema = z24.strictObject({
4240
+ var databaseCredentialRotationSchema = z27.strictObject({
3553
4241
  databaseAdminUrl: databaseUrl.optional(),
3554
4242
  expectedRevision: revision,
3555
- expectedInstanceId: z24.string().min(1),
3556
- password: z24.string().min(24).max(4096)
4243
+ expectedInstanceId: z27.string().min(1),
4244
+ password: z27.string().min(24).max(4096)
3557
4245
  });
3558
- var redisMaintenanceSchema = z24.strictObject({
4246
+ var redisMaintenanceSchema = z27.strictObject({
3559
4247
  expectedRevision: revision,
3560
- redisUrl: z24.string().min(1).max(8192).nullable()
4248
+ redisUrl: z27.string().min(1).max(8192).nullable()
3561
4249
  });
3562
4250
 
3563
4251
  // ../core/src/builtin/maintenance.ts
@@ -3567,7 +4255,7 @@ var commands3 = new BuiltinCommandRegistry(
3567
4255
  ).register(
3568
4256
  "status",
3569
4257
  {
3570
- inputSchema: z25.strictObject({}),
4258
+ inputSchema: z28.strictObject({}),
3571
4259
  scope: "admin",
3572
4260
  h: "\u7EF4\u62A4\u9636\u6BB5\u53CA\u5DF2\u8131\u654F\u7684\u8FDE\u63A5\u72B6\u6001",
3573
4261
  returns: "MaintenanceStatus"
@@ -3604,20 +4292,20 @@ var commands3 = new BuiltinCommandRegistry(
3604
4292
  var createMaintenanceModule = (deps) => commands3.module(deps);
3605
4293
 
3606
4294
  // ../core/src/builtin/management.ts
3607
- import { z as z27 } from "zod";
4295
+ import { z as z30 } from "zod";
3608
4296
 
3609
4297
  // ../core/src/managedConfig.ts
3610
- import { z as z26 } from "zod";
4298
+ import { z as z29 } from "zod";
3611
4299
 
3612
4300
  // ../core/src/runtimeConfig.ts
3613
4301
  var DEFAULT_MAX_HOPS = 4;
3614
4302
 
3615
4303
  // ../core/src/managedConfig.ts
3616
- var positive = z26.number().int().positive().max(Number.MAX_SAFE_INTEGER);
4304
+ var positive = z29.number().int().positive().max(Number.MAX_SAFE_INTEGER);
3617
4305
  var ttl = positive.max(604800);
3618
- var runtimeConfigSchema = z26.strictObject({
3619
- canonicalOrigin: z26.union([z26.literal(""), z26.url({ protocol: /^https?$/ })]).default("").describe("\u516C\u5F00\u8BBF\u95EE\u5730\u5740"),
3620
- remoteAllowlist: z26.array(z26.string().min(1)).default([]).describe("\u5141\u8BB8\u8054\u90A6\u8FDE\u63A5\u7684\u4E3B\u673A"),
4306
+ var runtimeConfigSchema = z29.strictObject({
4307
+ canonicalOrigin: z29.union([z29.literal(""), z29.url({ protocol: /^https?$/ })]).default("").describe("\u516C\u5F00\u8BBF\u95EE\u5730\u5740"),
4308
+ remoteAllowlist: z29.array(z29.string().min(1)).default([]).describe("\u5141\u8BB8\u8054\u90A6\u8FDE\u63A5\u7684\u4E3B\u673A"),
3621
4309
  maxHops: positive.max(16).default(DEFAULT_MAX_HOPS).describe("\u8054\u90A6\u6700\u5927\u8DF3\u6570"),
3622
4310
  deviceReclaimSec: positive.max(2147483).default(86400).describe("\u79BB\u7EBF\u8BBE\u5907\u56DE\u6536\u7B49\u5F85\uFF08\u79D2\uFF09"),
3623
4311
  toolCacheTtlSec: positive.default(300).describe("\u5DE5\u5177\u7F13\u5B58\u6709\u6548\u671F\uFF08\u79D2\uFF09"),
@@ -3629,7 +4317,7 @@ var runtimeConfigSchema = z26.strictObject({
3629
4317
  storeCallMaxBytes: positive.default(536870912).describe("\u5355\u6B21\u8C03\u7528\u7D2F\u8BA1\u4E0A\u4F20\u5927\u5C0F\uFF08\u5B57\u8282\uFF09"),
3630
4318
  storeCallMaxObjectBytes: positive.max(1073741824).default(268435456).describe("\u8C03\u7528\u5185\u5355\u4E2A\u5BF9\u8C61\u6700\u5927\u5927\u5C0F\uFF08\u5B57\u8282\uFF09"),
3631
4319
  storeCallMaxObjects: positive.default(4).describe("\u5355\u6B21\u8C03\u7528\u6700\u591A\u5BF9\u8C61\u6570"),
3632
- storeCallAllowedContentTypes: z26.array(z26.string().min(1)).min(1).default(["*/*"]).describe("\u8C03\u7528\u4E0A\u4F20\u5141\u8BB8\u7684 MIME \u7C7B\u578B"),
4320
+ storeCallAllowedContentTypes: z29.array(z29.string().min(1)).min(1).default(["*/*"]).describe("\u8C03\u7528\u4E0A\u4F20\u5141\u8BB8\u7684 MIME \u7C7B\u578B"),
3633
4321
  storeUploadTtlSec: ttl.default(900).describe("\u4E0A\u4F20\u4F1A\u8BDD\u6709\u6548\u671F\uFF08\u79D2\uFF09"),
3634
4322
  storeShareTtlSec: ttl.default(900).describe("\u5206\u4EAB\u6709\u6548\u671F\uFF08\u79D2\uFF09"),
3635
4323
  storeReadTtlSec: ttl.default(900).describe("\u4E0B\u8F7D\u5F15\u7528\u6709\u6548\u671F\uFF08\u79D2\uFF09"),
@@ -3641,37 +4329,37 @@ var runtimeConfigSchema = z26.strictObject({
3641
4329
  searchMinChildWorkMs: positive.default(200).describe("\u5B50\u641C\u7D22\u6700\u5C11\u5DE5\u4F5C\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09"),
3642
4330
  searchReturnReserveMs: positive.default(100).describe("\u641C\u7D22\u8FD4\u56DE\u9884\u7559\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09"),
3643
4331
  searchSessionTtlSec: positive.default(300).describe("\u641C\u7D22\u5FEB\u7167\u6709\u6548\u671F\uFF08\u79D2\uFF09"),
3644
- shutdownDrainSec: z26.number().int().min(0).max(300).default(0).describe("\u5173\u505C\u6392\u7A7A\u7B49\u5F85\uFF08\u79D2\uFF09")
4332
+ shutdownDrainSec: z29.number().int().min(0).max(300).default(0).describe("\u5173\u505C\u6392\u7A7A\u7B49\u5F85\uFF08\u79D2\uFF09")
3645
4333
  });
3646
- var configUpdateSchema = z26.strictObject({
3647
- expectedRevision: z26.number().int().nonnegative(),
4334
+ var configUpdateSchema = z29.strictObject({
4335
+ expectedRevision: z29.number().int().nonnegative(),
3648
4336
  settings: runtimeConfigSchema
3649
4337
  });
3650
- var revisionSchema = z26.strictObject({ expectedRevision: z26.number().int().nonnegative() });
3651
- var s3ConnectionSchema = z26.strictObject({
3652
- endpoint: z26.url(),
3653
- bucket: z26.string().min(1).max(255),
3654
- region: z26.string().min(1).default("us-east-1"),
3655
- accessKeyId: z26.string().min(1).max(4096),
3656
- secretAccessKey: z26.string().min(1).max(4096)
4338
+ var revisionSchema = z29.strictObject({ expectedRevision: z29.number().int().nonnegative() });
4339
+ var s3ConnectionSchema = z29.strictObject({
4340
+ endpoint: z29.url(),
4341
+ bucket: z29.string().min(1).max(255),
4342
+ region: z29.string().min(1).default("us-east-1"),
4343
+ accessKeyId: z29.string().min(1).max(4096),
4344
+ secretAccessKey: z29.string().min(1).max(4096)
3657
4345
  });
3658
- var storageWriteSchema = z26.strictObject({
3659
- name: z26.string().min(1).max(120),
4346
+ var storageWriteSchema = z29.strictObject({
4347
+ name: z29.string().min(1).max(120),
3660
4348
  connection: s3ConnectionSchema
3661
4349
  });
3662
- var storageIdSchema = z26.strictObject({ id: z26.string().min(1).max(128) });
4350
+ var storageIdSchema = z29.strictObject({ id: z29.string().min(1).max(128) });
3663
4351
  var storageRevisionSchema = storageIdSchema.extend({
3664
- expectedRevision: z26.number().int().nonnegative()
4352
+ expectedRevision: z29.number().int().nonnegative()
3665
4353
  });
3666
4354
  var storageActivateSchema = storageRevisionSchema.extend({
3667
- expectedActiveRevision: z26.number().int().nonnegative()
4355
+ expectedActiveRevision: z29.number().int().nonnegative()
3668
4356
  });
3669
4357
  var storageRotateSchema = storageRevisionSchema.extend({
3670
- accessKeyId: z26.string().min(1),
3671
- secretAccessKey: z26.string().min(1)
4358
+ accessKeyId: z29.string().min(1),
4359
+ secretAccessKey: z29.string().min(1)
3672
4360
  });
3673
- var setupInputSchema = z26.strictObject({
3674
- databaseUrl: z26.string().min(1).refine((value) => {
4361
+ var setupInputSchema = z29.strictObject({
4362
+ databaseUrl: z29.string().min(1).refine((value) => {
3675
4363
  try {
3676
4364
  return ["postgres:", "postgresql:"].includes(new URL(value).protocol);
3677
4365
  } catch {
@@ -3679,47 +4367,47 @@ var setupInputSchema = z26.strictObject({
3679
4367
  }
3680
4368
  }, "\u9700\u8981 PostgreSQL \u8FDE\u63A5\u5730\u5740").optional(),
3681
4369
  storage: s3ConnectionSchema.optional(),
3682
- redisUrl: z26.string().optional(),
4370
+ redisUrl: z29.string().optional(),
3683
4371
  settings: runtimeConfigSchema.default(() => runtimeConfigSchema.parse({}))
3684
4372
  });
3685
- var setupStatusSchema = z26.object({
3686
- state: z26.enum(["setup", "installing", "ready", "recovery"]),
3687
- instanceId: z26.string().min(1),
3688
- pairingRequired: z26.boolean()
4373
+ var setupStatusSchema = z29.object({
4374
+ state: z29.enum(["setup", "installing", "ready", "recovery"]),
4375
+ instanceId: z29.string().min(1),
4376
+ pairingRequired: z29.boolean()
3689
4377
  });
3690
- var setupDefaultsSchema = z26.object({
3691
- databaseConfigured: z26.boolean(),
3692
- databaseHost: z26.string().optional(),
3693
- redisConfigured: z26.boolean(),
3694
- storageConfigured: z26.boolean(),
3695
- storage: z26.object({ endpoint: z26.string(), bucket: z26.string(), region: z26.string() }).optional()
4378
+ var setupDefaultsSchema = z29.object({
4379
+ databaseConfigured: z29.boolean(),
4380
+ databaseHost: z29.string().optional(),
4381
+ redisConfigured: z29.boolean(),
4382
+ storageConfigured: z29.boolean(),
4383
+ storage: z29.object({ endpoint: z29.string(), bucket: z29.string(), region: z29.string() }).optional()
3696
4384
  });
3697
- var setupResultSchema = z26.object({
3698
- state: z26.literal("ready"),
3699
- adminSk: z26.string().min(1),
3700
- baseUrl: z26.string()
4385
+ var setupResultSchema = z29.object({
4386
+ state: z29.literal("ready"),
4387
+ adminSk: z29.string().min(1),
4388
+ baseUrl: z29.string()
3701
4389
  });
3702
- var backupKeyringSchema = z26.strictObject({ activeKeyId: z26.string().min(1), keys: z26.record(z26.string(), z26.string()) });
4390
+ var backupKeyringSchema = z29.strictObject({ activeKeyId: z29.string().min(1), keys: z29.record(z29.string(), z29.string()) });
3703
4391
  var recoveryInputSchema = setupInputSchema.extend({
3704
- backup: z26.strictObject({
3705
- version: z26.literal(1),
3706
- instanceId: z26.string().min(1),
3707
- exportedAt: z26.string().min(1),
4392
+ backup: z29.strictObject({
4393
+ version: z29.literal(1),
4394
+ instanceId: z29.string().min(1),
4395
+ exportedAt: z29.string().min(1),
3708
4396
  keyring: backupKeyringSchema,
3709
4397
  storeTokenKeyring: backupKeyringSchema,
3710
- oauthKey: z26.string().min(1),
3711
- signingRetireAfter: z26.record(z26.string(), z26.string()).optional()
4398
+ oauthKey: z29.string().min(1),
4399
+ signingRetireAfter: z29.record(z29.string(), z29.string()).optional()
3712
4400
  }).optional()
3713
4401
  });
3714
- var recoveryResultSchema = z26.object({
3715
- state: z26.literal("ready"),
3716
- baseUrl: z26.string(),
3717
- adminSk: z26.string().min(1).optional()
4402
+ var recoveryResultSchema = z29.object({
4403
+ state: z29.literal("ready"),
4404
+ baseUrl: z29.string(),
4405
+ adminSk: z29.string().min(1).optional()
3718
4406
  });
3719
4407
 
3720
4408
  // ../core/src/builtin/management.ts
3721
- var configCommands = new BuiltinCommandRegistry("config", "\u5B9E\u4F8B\u914D\u7F6E\u4E0E\u751F\u6548\u72B6\u6001\uFF08\u7BA1\u7406\u5458\uFF09").register("schema", { inputSchema: z27.strictObject({}), scope: "admin", h: "\u914D\u7F6E\u76EE\u5F55\u3001\u5B57\u6BB5\u8BF4\u660E\u4E0E\u9ED8\u8BA4\u503C", returns: "JSON Schema" }, async () => z27.toJSONSchema(runtimeConfigSchema)).register("get", { inputSchema: z27.strictObject({}), scope: "admin", h: "\u8BFB\u53D6\u671F\u671B\u503C\u3001\u5B9E\u9645\u503C\u548C revision", returns: "ConfigStatus" }, async (_, { deps }) => deps.get()).register("status", { inputSchema: z27.strictObject({}), scope: "admin", h: "\u68C0\u67E5\u914D\u7F6E\u5E94\u7528\u72B6\u6001", returns: "ConfigStatus" }, async (_, { deps }) => deps.get()).register("validate", { inputSchema: runtimeConfigSchema, scope: "admin", h: "\u6821\u9A8C\u5B8C\u6574\u5019\u9009\u914D\u7F6E", returns: "RuntimeConfig" }, async (input) => input).register("update", { inputSchema: configUpdateSchema, scope: "admin", h: "\u6309 revision \u4FDD\u5B58\u914D\u7F6E\uFF1B\u5C1A\u672A\u5E94\u7528", returns: "ConfigStatus" }, async (input, { deps }) => deps.update(input)).register("apply", { inputSchema: revisionSchema, scope: "admin", h: "\u5E94\u7528\u6307\u5B9A revision \u5E76\u68C0\u67E5\u5B9E\u9645\u72B6\u6001", returns: "ConfigStatus" }, async (input, { deps }) => deps.apply(input));
3722
- var storageCommands = new BuiltinCommandRegistry("storage", "\u5BF9\u8C61\u5B58\u50A8\u540E\u7AEF\u3001\u9A8C\u8BC1\u548C\u9ED8\u8BA4\u4E0A\u4F20\u76EE\u6807\uFF08\u7BA1\u7406\u5458\uFF09").register("list", { inputSchema: z27.strictObject({}), scope: "admin", h: "\u5217\u51FA\u9ED8\u8BA4\u4E0E\u5386\u53F2\u5B58\u50A8\u540E\u7AEF", returns: "Page<StorageBackendView>" }, async (_, { deps }) => deps.list()).register("get", { inputSchema: storageIdSchema, scope: "admin", h: "\u8BFB\u53D6\u540E\u7AEF\u72B6\u6001\uFF0C\u4E0D\u56DE\u663E\u51ED\u8BC1", returns: "StorageBackendView" }, async (input, { deps }) => deps.get(input)).register("write", { inputSchema: storageWriteSchema, scope: "admin", h: "\u521B\u5EFA\u672A\u542F\u7528\u7684\u540E\u7AEF\uFF0C\u51ED\u8BC1\u53EA\u5199\u5165\u52A0\u5BC6\u4FDD\u7BA1\u5E93", returns: "StorageBackendView" }, async (input, { deps }) => deps.write(input)).register("test", { inputSchema: storageRevisionSchema, scope: "admin", h: "\u9A8C\u8BC1\u5B9E\u9645\u8BFB\u5199\u548C\u6761\u4EF6\u5199\u80FD\u529B", returns: "StorageBackendView" }, async (input, { deps }) => deps.test(input)).register("activate", { inputSchema: storageActivateSchema, scope: "admin", h: "\u8BBE\u4E3A\u65B0\u4E0A\u4F20\u9ED8\u8BA4\u503C\uFF1B\u65E7\u5BF9\u8C61\u4FDD\u7559\u539F\u540E\u7AEF", returns: "StorageBackendView" }, async (input, { deps }) => deps.activate(input)).register("update", { inputSchema: storageRotateSchema, scope: "admin", h: "\u9A8C\u8BC1\u5E76\u8F6E\u6362\u51ED\u8BC1\uFF0C\u4F4D\u7F6E\u4E0D\u53D8", returns: "StorageBackendView" }, async (input, { deps }) => deps.update(input)).register("delete", { inputSchema: storageRevisionSchema, scope: "admin", h: "\u5220\u9664\u6CA1\u6709\u5BF9\u8C61\u6216 Context \u5F15\u7528\u7684\u975E\u9ED8\u8BA4\u540E\u7AEF", returns: "{ok:true}" }, async (input, { deps }) => deps.delete(input));
4409
+ var configCommands = new BuiltinCommandRegistry("config", "\u5B9E\u4F8B\u914D\u7F6E\u4E0E\u751F\u6548\u72B6\u6001\uFF08\u7BA1\u7406\u5458\uFF09").register("schema", { inputSchema: z30.strictObject({}), scope: "admin", h: "\u914D\u7F6E\u76EE\u5F55\u3001\u5B57\u6BB5\u8BF4\u660E\u4E0E\u9ED8\u8BA4\u503C", returns: "JSON Schema" }, async () => z30.toJSONSchema(runtimeConfigSchema)).register("get", { inputSchema: z30.strictObject({}), scope: "admin", h: "\u8BFB\u53D6\u671F\u671B\u503C\u3001\u5B9E\u9645\u503C\u548C revision", returns: "ConfigStatus" }, async (_, { deps }) => deps.get()).register("status", { inputSchema: z30.strictObject({}), scope: "admin", h: "\u68C0\u67E5\u914D\u7F6E\u5E94\u7528\u72B6\u6001", returns: "ConfigStatus" }, async (_, { deps }) => deps.get()).register("validate", { inputSchema: runtimeConfigSchema, scope: "admin", h: "\u6821\u9A8C\u5B8C\u6574\u5019\u9009\u914D\u7F6E", returns: "RuntimeConfig" }, async (input) => input).register("update", { inputSchema: configUpdateSchema, scope: "admin", h: "\u6309 revision \u4FDD\u5B58\u914D\u7F6E\uFF1B\u5C1A\u672A\u5E94\u7528", returns: "ConfigStatus" }, async (input, { deps }) => deps.update(input)).register("apply", { inputSchema: revisionSchema, scope: "admin", h: "\u5E94\u7528\u6307\u5B9A revision \u5E76\u68C0\u67E5\u5B9E\u9645\u72B6\u6001", returns: "ConfigStatus" }, async (input, { deps }) => deps.apply(input));
4410
+ var storageCommands = new BuiltinCommandRegistry("storage", "\u5BF9\u8C61\u5B58\u50A8\u540E\u7AEF\u3001\u9A8C\u8BC1\u548C\u9ED8\u8BA4\u4E0A\u4F20\u76EE\u6807\uFF08\u7BA1\u7406\u5458\uFF09").register("list", { inputSchema: z30.strictObject({}), scope: "admin", h: "\u5217\u51FA\u9ED8\u8BA4\u4E0E\u5386\u53F2\u5B58\u50A8\u540E\u7AEF", returns: "Page<StorageBackendView>" }, async (_, { deps }) => deps.list()).register("get", { inputSchema: storageIdSchema, scope: "admin", h: "\u8BFB\u53D6\u540E\u7AEF\u72B6\u6001\uFF0C\u4E0D\u56DE\u663E\u51ED\u8BC1", returns: "StorageBackendView" }, async (input, { deps }) => deps.get(input)).register("write", { inputSchema: storageWriteSchema, scope: "admin", h: "\u521B\u5EFA\u672A\u542F\u7528\u7684\u540E\u7AEF\uFF0C\u51ED\u8BC1\u53EA\u5199\u5165\u52A0\u5BC6\u4FDD\u7BA1\u5E93", returns: "StorageBackendView" }, async (input, { deps }) => deps.write(input)).register("test", { inputSchema: storageRevisionSchema, scope: "admin", h: "\u9A8C\u8BC1\u5B9E\u9645\u8BFB\u5199\u548C\u6761\u4EF6\u5199\u80FD\u529B", returns: "StorageBackendView" }, async (input, { deps }) => deps.test(input)).register("activate", { inputSchema: storageActivateSchema, scope: "admin", h: "\u8BBE\u4E3A\u65B0\u4E0A\u4F20\u9ED8\u8BA4\u503C\uFF1B\u65E7\u5BF9\u8C61\u4FDD\u7559\u539F\u540E\u7AEF", returns: "StorageBackendView" }, async (input, { deps }) => deps.activate(input)).register("update", { inputSchema: storageRotateSchema, scope: "admin", h: "\u9A8C\u8BC1\u5E76\u8F6E\u6362\u51ED\u8BC1\uFF0C\u4F4D\u7F6E\u4E0D\u53D8", returns: "StorageBackendView" }, async (input, { deps }) => deps.update(input)).register("delete", { inputSchema: storageRevisionSchema, scope: "admin", h: "\u5220\u9664\u6CA1\u6709\u5BF9\u8C61\u6216 Context \u5F15\u7528\u7684\u975E\u9ED8\u8BA4\u540E\u7AEF", returns: "{ok:true}" }, async (input, { deps }) => deps.delete(input));
3723
4411
  var createConfigModule = (deps) => configCommands.module(deps);
3724
4412
  var createStorageModule = (deps) => storageCommands.module(deps);
3725
4413
 
@@ -3885,7 +4573,7 @@ async function createObjectContextUploadGrant(store, opts, input) {
3885
4573
  expiresAt
3886
4574
  };
3887
4575
  }
3888
- function clampLimit4(limit) {
4576
+ function clampLimit5(limit) {
3889
4577
  if (limit === void 0) return LIST_LIMIT_DEFAULT;
3890
4578
  if (!Number.isInteger(limit) || limit < 1) {
3891
4579
  throw new TBError("invalid_argument", `limit \u975E\u6CD5:${limit}`);
@@ -3959,7 +4647,7 @@ function createObjectContextProvider(store, opts) {
3959
4647
  return {
3960
4648
  async list(path, listOpts) {
3961
4649
  rejectFilter(listOpts);
3962
- const limit = clampLimit4(listOpts?.limit);
4650
+ const limit = clampLimit5(listOpts?.limit);
3963
4651
  const rel = path === "" ? "" : `${normalizeEntryPath(path)}/`;
3964
4652
  const full = keyPrefix + rel;
3965
4653
  assertContextKeyAllowed(full.slice(0, -1), path, false);
@@ -4069,7 +4757,7 @@ function createObjectContextProvider(store, opts) {
4069
4757
  throw new TBError("invalid_argument", "query \u4E0D\u80FD\u4E3A\u7A7A");
4070
4758
  }
4071
4759
  rejectFilter(searchOpts);
4072
- const limit = clampLimit4(searchOpts?.limit);
4760
+ const limit = clampLimit5(searchOpts?.limit);
4073
4761
  const q = query.toLowerCase();
4074
4762
  const after = searchOpts?.cursor;
4075
4763
  const items = [];
@@ -4124,79 +4812,79 @@ function isContextExpired(createdAt, ttlSec, now) {
4124
4812
  }
4125
4813
 
4126
4814
  // ../core/src/device/frames.ts
4127
- import { z as z28 } from "zod";
4128
- var deviceNodeCmdSchema = z28.object({
4129
- name: z28.string().min(1),
4130
- delivery: z28.enum(["realtime", "mailbox", "both"]).optional(),
4131
- description: z28.string().optional(),
4132
- inputSchema: z28.unknown().optional(),
4133
- outputSchema: z28.unknown().optional(),
4134
- effect: z28.string().optional(),
4135
- confirm: z28.boolean().optional()
4815
+ import { z as z31 } from "zod";
4816
+ var deviceNodeCmdSchema = z31.object({
4817
+ name: z31.string().min(1),
4818
+ delivery: z31.enum(["realtime", "mailbox", "both"]).optional(),
4819
+ description: z31.string().optional(),
4820
+ inputSchema: z31.unknown().optional(),
4821
+ outputSchema: z31.unknown().optional(),
4822
+ effect: z31.string().optional(),
4823
+ confirm: z31.boolean().optional()
4136
4824
  }).passthrough();
4137
- var nodeInputSchema2 = z28.object({
4138
- path: z28.string().min(1),
4139
- kind: z28.enum(NODE_KINDS),
4140
- description: z28.string(),
4141
- cmds: z28.array(deviceNodeCmdSchema).optional()
4825
+ var nodeInputSchema2 = z31.object({
4826
+ path: z31.string().min(1),
4827
+ kind: z31.enum(NODE_KINDS),
4828
+ description: z31.string(),
4829
+ cmds: z31.array(deviceNodeCmdSchema).optional()
4142
4830
  }).passthrough();
4143
- var deviceExposeSchema = z28.object({
4831
+ var deviceExposeSchema = z31.object({
4144
4832
  environment: deviceEnvironmentSchema.optional(),
4145
- shell: z28.object({
4146
- description: z28.string().optional(),
4147
- allow: z28.array(z28.string()).optional()
4833
+ shell: z31.object({
4834
+ description: z31.string().optional(),
4835
+ allow: z31.array(z31.string()).optional()
4148
4836
  }).optional(),
4149
- fs: z28.object({
4150
- roots: z28.array(z28.string().min(1)).min(1),
4151
- readOnly: z28.boolean().optional()
4837
+ fs: z31.object({
4838
+ roots: z31.array(z31.string().min(1)).min(1),
4839
+ readOnly: z31.boolean().optional()
4152
4840
  }).optional(),
4153
- nodes: z28.array(nodeInputSchema2).optional()
4841
+ nodes: z31.array(nodeInputSchema2).optional()
4154
4842
  });
4155
- var idSchema = z28.string().min(1);
4156
- var deviceCallContextSchema = z28.object({
4157
- caller: z28.object({
4158
- keyId: z28.string().min(1),
4159
- owner: z28.string().min(1),
4160
- displayName: z28.string().optional()
4843
+ var idSchema = z31.string().min(1);
4844
+ var deviceCallContextSchema = z31.object({
4845
+ caller: z31.object({
4846
+ keyId: z31.string().min(1),
4847
+ owner: z31.string().min(1),
4848
+ displayName: z31.string().optional()
4161
4849
  }).passthrough(),
4162
- traceId: z28.string().min(1),
4163
- createdAt: z28.string().min(1),
4164
- expiresAt: z28.string().min(1),
4165
- upload: z28.object({
4166
- token: z28.string().min(1),
4167
- expiresAt: z28.iso.datetime({ offset: true }),
4168
- maxBytes: z28.number().int().positive(),
4169
- maxObjects: z28.number().int().positive()
4850
+ traceId: z31.string().min(1),
4851
+ createdAt: z31.string().min(1),
4852
+ expiresAt: z31.string().min(1),
4853
+ upload: z31.object({
4854
+ token: z31.string().min(1),
4855
+ expiresAt: z31.iso.datetime({ offset: true }),
4856
+ maxBytes: z31.number().int().positive(),
4857
+ maxObjects: z31.number().int().positive()
4170
4858
  }).strict().optional()
4171
4859
  }).passthrough();
4172
4860
  var schemaByType = {
4173
- hello: z28.object({
4174
- type: z28.literal("hello"),
4175
- deviceId: z28.string().min(1),
4176
- mountPath: z28.string().min(1).optional(),
4861
+ hello: z31.object({
4862
+ type: z31.literal("hello"),
4863
+ deviceId: z31.string().min(1),
4864
+ mountPath: z31.string().min(1).optional(),
4177
4865
  expose: deviceExposeSchema
4178
4866
  }),
4179
- ready: z28.object({ type: z28.literal("ready"), mountPath: z28.string().min(1) }),
4180
- error: z28.object({ type: z28.literal("error"), error: tbErrorBodySchema }),
4181
- call: z28.object({
4182
- type: z28.literal("call"),
4867
+ ready: z31.object({ type: z31.literal("ready"), mountPath: z31.string().min(1) }),
4868
+ error: z31.object({ type: z31.literal("error"), error: tbErrorBodySchema }),
4869
+ call: z31.object({
4870
+ type: z31.literal("call"),
4183
4871
  id: idSchema,
4184
- path: z28.string().min(1),
4185
- arguments: z28.record(z28.string(), z28.unknown()),
4872
+ path: z31.string().min(1),
4873
+ arguments: z31.record(z31.string(), z31.unknown()),
4186
4874
  context: deviceCallContextSchema.optional()
4187
4875
  }),
4188
- result: z28.discriminatedUnion("ok", [
4189
- z28.object({ type: z28.literal("result"), id: idSchema, ok: z28.literal(true), value: z28.unknown() }),
4190
- z28.object({
4191
- type: z28.literal("result"),
4876
+ result: z31.discriminatedUnion("ok", [
4877
+ z31.object({ type: z31.literal("result"), id: idSchema, ok: z31.literal(true), value: z31.unknown() }),
4878
+ z31.object({
4879
+ type: z31.literal("result"),
4192
4880
  id: idSchema,
4193
- ok: z28.literal(false),
4881
+ ok: z31.literal(false),
4194
4882
  error: tbErrorBodySchema
4195
4883
  })
4196
4884
  ]),
4197
- ping: z28.object({ type: z28.literal("ping") }),
4198
- pong: z28.object({ type: z28.literal("pong") }),
4199
- cancel: z28.object({ type: z28.literal("cancel"), id: idSchema })
4885
+ ping: z31.object({ type: z31.literal("ping") }),
4886
+ pong: z31.object({ type: z31.literal("pong") }),
4887
+ cancel: z31.object({ type: z31.literal("cancel"), id: idSchema })
4200
4888
  };
4201
4889
  var PING_FRAME_JSON = '{"type":"ping"}';
4202
4890
  var PONG_FRAME_JSON = '{"type":"pong"}';
@@ -4213,14 +4901,14 @@ function decodeDeviceFrame(text) {
4213
4901
  if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
4214
4902
  throw invalidFrame("\u5FC5\u987B\u662F JSON \u5BF9\u8C61");
4215
4903
  }
4216
- const type = raw.type;
4217
- if (typeof type !== "string" || !(type in schemaByType)) {
4218
- throw invalidFrame(`\u672A\u77E5 type:${JSON.stringify(type)}`);
4904
+ const type2 = raw.type;
4905
+ if (typeof type2 !== "string" || !(type2 in schemaByType)) {
4906
+ throw invalidFrame(`\u672A\u77E5 type:${JSON.stringify(type2)}`);
4219
4907
  }
4220
- const parsed = schemaByType[type].safeParse(raw);
4908
+ const parsed = schemaByType[type2].safeParse(raw);
4221
4909
  if (!parsed.success) {
4222
4910
  const issue = parsed.error.issues[0];
4223
- throw invalidFrame(`${type} \u5E27\u5B57\u6BB5\u975E\u6CD5:${issue?.path.join(".") ?? ""} ${issue?.message ?? ""}`);
4911
+ throw invalidFrame(`${type2} \u5E27\u5B57\u6BB5\u975E\u6CD5:${issue?.path.join(".") ?? ""} ${issue?.message ?? ""}`);
4224
4912
  }
4225
4913
  return parsed.data;
4226
4914
  }
@@ -4487,6 +5175,63 @@ var DeviceGatewaySession = class {
4487
5175
  }
4488
5176
  };
4489
5177
 
5178
+ // ../core/src/events.ts
5179
+ import { z as z33 } from "zod/v4";
5180
+
5181
+ // ../core/src/protocol/eventWire.ts
5182
+ import { z as z32 } from "zod/v4";
5183
+ var EVENT_MAX_WAIT_MS = 3e4;
5184
+ var EVENT_MAX_BYTES = 16384;
5185
+ var type = z32.string().min(1).max(128);
5186
+ var cursor = z32.string().min(1).max(2048);
5187
+ var schemaVersion = z32.number().int().min(1).max(2147483647);
5188
+ var subject = z32.string().min(1).max(512).optional();
5189
+ var eventPublishSchema = z32.strictObject({
5190
+ type,
5191
+ schemaVersion: schemaVersion.optional(),
5192
+ subject,
5193
+ data: z32.json(),
5194
+ idempotencyKey: z32.string().min(1).max(256).optional()
5195
+ });
5196
+ var eventReadSchema = z32.strictObject({
5197
+ after: cursor.optional(),
5198
+ type: type.optional(),
5199
+ limit: z32.number().int().min(1).max(100).optional(),
5200
+ waitMs: z32.number().int().min(0).max(EVENT_MAX_WAIT_MS).optional()
5201
+ });
5202
+ var eventReceiptSchema = z32.object({ id: z32.uuid(), cursor });
5203
+ var eventEnvelopeSchema = eventReceiptSchema.extend({
5204
+ type,
5205
+ schemaVersion,
5206
+ source: z32.string(),
5207
+ recordedAt: z32.iso.datetime(),
5208
+ subject,
5209
+ data: z32.json()
5210
+ });
5211
+ var eventReadResultSchema = z32.object({
5212
+ events: z32.array(eventEnvelopeSchema),
5213
+ nextCursor: cursor,
5214
+ timedOut: z32.boolean(),
5215
+ gap: z32.object({ reason: z32.enum(["retention", "generation"]), earliestCursor: cursor }).optional()
5216
+ });
5217
+
5218
+ // ../core/src/events.ts
5219
+ var eventCommands = new HtbpCommandRegistry().register("publish", {
5220
+ h: "Append an event. Idempotency keys retain their first receipt for 24 hours.",
5221
+ inputSchema: eventPublishSchema,
5222
+ outputSchema: z33.toJSONSchema(eventReceiptSchema),
5223
+ returns: "EventReceipt",
5224
+ scope: "write",
5225
+ effect: "write"
5226
+ }, (input, ctx) => ctx.publish(input)).register("read", {
5227
+ h: "Read after a cursor, or from the current tail when omitted. Stop on a retention or generation gap.",
5228
+ inputSchema: eventReadSchema,
5229
+ outputSchema: z33.toJSONSchema(eventReadResultSchema),
5230
+ returns: "EventReadResult",
5231
+ scope: "read",
5232
+ effect: "read"
5233
+ }, (input, ctx) => ctx.read(input));
5234
+
4490
5235
  // ../core/src/feedback/store.ts
4491
5236
  var FEEDBACK_TITLE_MAX = 80;
4492
5237
  var FEEDBACK_DETAIL_MAX = 500;
@@ -4979,9 +5724,9 @@ function reserveUploadQuota(input, capability) {
4979
5724
  if (capability.status !== "active" || capability.reservations.length >= capability.maxObjects) {
4980
5725
  throw new TBError("rate_limited", "call upload object \u6570\u91CF\u5DF2\u8FBE\u4E0A\u9650");
4981
5726
  }
4982
- const type = input.object.contentType;
4983
- if (!capability.allowedContentTypes.some((allowed) => allowed === "*/*" || allowed === type || allowed.endsWith("/*") && type.startsWith(allowed.slice(0, -1)))) {
4984
- throw new TBError("permission_denied", `call \u4E0D\u5141\u8BB8\u4E0A\u4F20 ${type}`);
5727
+ const type2 = input.object.contentType;
5728
+ if (!capability.allowedContentTypes.some((allowed) => allowed === "*/*" || allowed === type2 || allowed.endsWith("/*") && type2.startsWith(allowed.slice(0, -1)))) {
5729
+ throw new TBError("permission_denied", `call \u4E0D\u5141\u8BB8\u4E0A\u4F20 ${type2}`);
4985
5730
  }
4986
5731
  const maxBytes = Math.min(
4987
5732
  input.session.maxBytes,
@@ -5011,7 +5756,7 @@ function assertUploadBinding(existing, requested, now) {
5011
5756
  }
5012
5757
 
5013
5758
  // ../core/src/objectStoreService/service.ts
5014
- import { z as z29 } from "zod/v4";
5759
+ import { z as z34 } from "zod/v4";
5015
5760
 
5016
5761
  // ../core/src/objectStoreService/uri.ts
5017
5762
  var STORE_OBJECT_ID_RE = /^[A-Za-z0-9_-]{22,64}$/;
@@ -5050,18 +5795,18 @@ var TOKEN_PREFIX = {
5050
5795
  function stateCorrupt(kind) {
5051
5796
  return new TBError("internal", `Store ${kind} \u72B6\u6001\u635F\u574F`, { retryable: false });
5052
5797
  }
5053
- var persistedId = z29.string().min(1);
5054
- var persistedOwner = z29.string().min(1).refine((value) => !/[\r\n\0]/.test(value));
5055
- var persistedTimestamp = z29.string().refine((value) => Number.isFinite(Date.parse(value)));
5056
- var persistedNonNegativeInt = z29.number().int().nonnegative().refine(Number.isSafeInteger);
5798
+ var persistedId = z34.string().min(1);
5799
+ var persistedOwner = z34.string().min(1).refine((value) => !/[\r\n\0]/.test(value));
5800
+ var persistedTimestamp = z34.string().refine((value) => Number.isFinite(Date.parse(value)));
5801
+ var persistedNonNegativeInt = z34.number().int().nonnegative().refine(Number.isSafeInteger);
5057
5802
  var persistedPositiveInt = persistedNonNegativeInt.refine((value) => value > 0);
5058
- var persistedHash = z29.string().regex(/^[0-9a-f]{64}$/);
5059
- var persistedChecksum = z29.looseObject({
5060
- algorithm: z29.literal("sha256"),
5061
- value: z29.string().min(1)
5803
+ var persistedHash = z34.string().regex(/^[0-9a-f]{64}$/);
5804
+ var persistedChecksum = z34.looseObject({
5805
+ algorithm: z34.literal("sha256"),
5806
+ value: z34.string().min(1)
5062
5807
  });
5063
5808
  function stateParser(kind, shape) {
5064
- const schema = z29.looseObject({ revision: persistedPositiveInt, ...shape });
5809
+ const schema = z34.looseObject({ revision: persistedPositiveInt, ...shape });
5065
5810
  return (value) => {
5066
5811
  const parsed = schema.safeParse(value);
5067
5812
  if (!parsed.success) throw stateCorrupt(kind);
@@ -5072,22 +5817,22 @@ var parseObject = stateParser("object", {
5072
5817
  backendId: persistedId,
5073
5818
  bytesDeletedAt: persistedTimestamp.optional(),
5074
5819
  checksum: persistedChecksum.optional(),
5075
- contentType: z29.string().min(1),
5820
+ contentType: z34.string().min(1),
5076
5821
  createdAt: persistedTimestamp,
5077
5822
  driverKey: persistedId,
5078
- etag: z29.string().optional(),
5823
+ etag: z34.string().optional(),
5079
5824
  expectedChecksum: persistedChecksum.optional(),
5080
5825
  expectedSize: persistedNonNegativeInt.optional(),
5081
5826
  expiresAt: persistedTimestamp.optional(),
5082
- filename: z29.string().optional(),
5827
+ filename: z34.string().optional(),
5083
5828
  id: persistedId,
5084
5829
  originCallId: persistedId.optional(),
5085
5830
  owner: persistedOwner,
5086
5831
  producer: persistedOwner.optional(),
5087
5832
  readyAt: persistedTimestamp.optional(),
5088
5833
  size: persistedNonNegativeInt.optional(),
5089
- status: z29.enum(["pending", "ready", "failed", "abandoned", "deleted"]),
5090
- store: z29.literal(DEFAULT_STORE_NAME),
5834
+ status: z34.enum(["pending", "ready", "failed", "abandoned", "deleted"]),
5835
+ store: z34.literal(DEFAULT_STORE_NAME),
5091
5836
  updatedAt: persistedTimestamp,
5092
5837
  uploadId: persistedId
5093
5838
  });
@@ -5097,7 +5842,7 @@ var parseSessionRecord = stateParser("upload session", {
5097
5842
  backendId: persistedId,
5098
5843
  capabilityHash: persistedHash,
5099
5844
  completedAt: persistedTimestamp.optional(),
5100
- contentType: z29.string().min(1),
5845
+ contentType: z34.string().min(1),
5101
5846
  createdAt: persistedTimestamp,
5102
5847
  expectedChecksum: persistedChecksum.optional(),
5103
5848
  expectedSize: persistedNonNegativeInt.optional(),
@@ -5105,13 +5850,13 @@ var parseSessionRecord = stateParser("upload session", {
5105
5850
  id: persistedId,
5106
5851
  maxBytes: persistedPositiveInt,
5107
5852
  objectId: persistedId,
5108
- status: z29.enum(["created", "completed", "aborted", "expired", "failed"]),
5853
+ status: z34.enum(["created", "completed", "aborted", "expired", "failed"]),
5109
5854
  terminalAt: persistedTimestamp.optional(),
5110
- transport: z29.enum(["relay", "presigned-put"])
5855
+ transport: z34.enum(["relay", "presigned-put"])
5111
5856
  });
5112
5857
  var parseCallCapabilityRecord = stateParser("call capability", {
5113
5858
  signingKeyId: persistedId,
5114
- allowedContentTypes: z29.array(z29.string().min(1)).min(1),
5859
+ allowedContentTypes: z34.array(z34.string().min(1)).min(1),
5115
5860
  callId: persistedId,
5116
5861
  createdAt: persistedTimestamp,
5117
5862
  expiresAt: persistedTimestamp,
@@ -5121,12 +5866,12 @@ var parseCallCapabilityRecord = stateParser("call capability", {
5121
5866
  maxObjects: persistedPositiveInt,
5122
5867
  owner: persistedOwner,
5123
5868
  producer: persistedOwner,
5124
- reservations: z29.array(z29.looseObject({
5869
+ reservations: z34.array(z34.looseObject({
5125
5870
  maxBytes: persistedPositiveInt,
5126
5871
  objectId: persistedId
5127
5872
  })),
5128
5873
  reservedBytes: persistedNonNegativeInt,
5129
- status: z29.enum(["active", "exhausted", "revoked", "expired"]),
5874
+ status: z34.enum(["active", "exhausted", "revoked", "expired"]),
5130
5875
  terminalAt: persistedTimestamp.optional(),
5131
5876
  tokenHash: persistedHash
5132
5877
  });
@@ -5137,13 +5882,13 @@ var parseShare = stateParser("share grant", {
5137
5882
  expiresAt: persistedTimestamp,
5138
5883
  id: persistedId,
5139
5884
  objectId: persistedId,
5140
- status: z29.enum(["active", "revoked", "expired"]),
5885
+ status: z34.enum(["active", "revoked", "expired"]),
5141
5886
  terminalAt: persistedTimestamp.optional(),
5142
5887
  tokenHash: persistedHash
5143
5888
  });
5144
5889
  var parseIdempotencyBinding = stateParser("idempotency binding", {
5145
5890
  createdAt: persistedTimestamp,
5146
- domain: z29.enum(["owner", "call"]),
5891
+ domain: z34.enum(["owner", "call"]),
5147
5892
  expiresAt: persistedTimestamp,
5148
5893
  fingerprint: persistedHash,
5149
5894
  objectId: persistedId,
@@ -5781,7 +6526,7 @@ var StoreService = class {
5781
6526
  idempotencyBindings: idempotencyBindings.cursor ?? null,
5782
6527
  objects: objectRecords.cursor ?? null
5783
6528
  };
5784
- return Object.values(cursors).some((cursor) => cursor !== null) ? { ...result, cursors } : result;
6529
+ return Object.values(cursors).some((cursor2) => cursor2 !== null) ? { ...result, cursors } : result;
5785
6530
  }
5786
6531
  async beginNormalized(input, identity) {
5787
6532
  const now = this.nowIso();
@@ -6032,13 +6777,13 @@ var StoreService = class {
6032
6777
  }
6033
6778
  return body;
6034
6779
  }
6035
- const source = body;
6780
+ const source2 = body;
6036
6781
  const bounded = {
6037
6782
  async cancel(reason) {
6038
- await source.cancel?.(reason);
6783
+ await source2.cancel?.(reason);
6039
6784
  },
6040
6785
  getReader() {
6041
- const reader = source.getReader();
6786
+ const reader = source2.getReader();
6042
6787
  let consumed = 0;
6043
6788
  return {
6044
6789
  async read() {
@@ -6048,7 +6793,7 @@ var StoreService = class {
6048
6793
  if (consumed > maxBytes) {
6049
6794
  try {
6050
6795
  if (reader.cancel !== void 0) await reader.cancel("Store upload size limit");
6051
- else await source.cancel?.("Store upload size limit");
6796
+ else await source2.cancel?.("Store upload size limit");
6052
6797
  } catch {
6053
6798
  }
6054
6799
  throw new TBError("rate_limited", `\u4E0A\u4F20\u5BF9\u8C61\u8D85\u8FC7 ${maxBytes} bytes`);
@@ -6061,7 +6806,7 @@ var StoreService = class {
6061
6806
  },
6062
6807
  async cancel(reason) {
6063
6808
  if (reader.cancel !== void 0) await reader.cancel(reason);
6064
- else await source.cancel?.(reason);
6809
+ else await source2.cancel?.(reason);
6065
6810
  }
6066
6811
  };
6067
6812
  }
@@ -6203,97 +6948,25 @@ var StoreService = class {
6203
6948
  }
6204
6949
  };
6205
6950
 
6206
- // ../core/src/plugin/catalog.ts
6207
- function canonicalCatalogJson(value) {
6208
- const normalize = (input) => {
6209
- if (Array.isArray(input)) return input.map(normalize);
6210
- if (input === null || typeof input !== "object") return input;
6211
- const source = input;
6212
- const out = {};
6213
- for (const key of Object.keys(source).sort()) {
6214
- if (source[key] !== void 0) out[key] = normalize(source[key]);
6215
- }
6216
- return out;
6217
- };
6218
- return JSON.stringify(normalize(value));
6219
- }
6220
- async function catalogDigest(value) {
6221
- const bytes2 = new TextEncoder().encode(canonicalCatalogJson(value));
6222
- const hash = await crypto.subtle.digest("SHA-256", bytes2);
6223
- return [...new Uint8Array(hash)].map((b) => b.toString(16).padStart(2, "0")).join("");
6224
- }
6225
- async function catalogSetDigest(catalog) {
6226
- const pairs = Object.keys(catalog).sort().map((id) => ({ id, digest: catalog[id].digest }));
6227
- return await catalogDigest(pairs);
6228
- }
6229
- function builtinManifestOf(id) {
6230
- return {
6231
- id,
6232
- protocolVersion: "plugin/v2",
6233
- endpoint: `binding:${id}`,
6234
- auth: { kind: "platform-token" },
6235
- healthPath: "/healthz",
6236
- enabled: true
6237
- };
6238
- }
6239
- function resolveBuiltinExport(catalog, id, nodeKind, what, exportId) {
6240
- const entry = catalog[id];
6241
- if (entry === void 0) {
6242
- throw new TBError("invalid_argument", `\u672A\u77E5 ${what} provider:'${id}'`);
6243
- }
6244
- const chosen = resolvePluginExport(entry.describe, {
6245
- nodeKind,
6246
- pluginId: id,
6247
- ...exportId !== void 0 ? { exportId } : {}
6248
- });
6249
- return { manifest: builtinManifestOf(id), export: chosen, source: "builtin" };
6250
- }
6251
- async function resolveExternalExport(store, id, nodeKind, what, exportId) {
6252
- const manifest = await store.get(KEY_PLUGIN + id);
6253
- if (manifest === null) {
6254
- throw new TBError("invalid_argument", `\u672A\u77E5 ${what} provider:'${id}'`);
6255
- }
6256
- if (manifest.enabled !== true) {
6257
- throw new TBError("invalid_argument", `plugin '${id}' \u5DF2\u7981\u7528`);
6258
- }
6259
- const describe = await store.get(KEY_PLUGIN_META + id);
6260
- if (describe === null) {
6261
- throw new TBError("invalid_argument", `plugin '${id}' \u7F3A\u5C11 ~describe \u7F13\u5B58,\u8BF7\u91CD\u65B0\u6CE8\u518C`);
6262
- }
6263
- const chosen = resolvePluginExport(describe, {
6264
- nodeKind,
6265
- pluginId: id,
6266
- ...exportId !== void 0 ? { exportId } : {}
6267
- });
6268
- return { manifest, export: chosen, source: "external" };
6269
- }
6270
- async function resolveIntegration(store, catalog, id, nodeKind, what, exportId) {
6271
- const manifest = await store.get(KEY_PLUGIN + id);
6272
- if (manifest !== null) {
6273
- return await resolveExternalExport(store, id, nodeKind, what, exportId);
6274
- }
6275
- return resolveBuiltinExport(catalog, id, nodeKind, what, exportId);
6276
- }
6277
-
6278
6951
  // ../core/src/plugin/credential.ts
6279
- function parseCredentialValues(raw, fields) {
6952
+ function parseCredentialValues(raw, fields2) {
6280
6953
  let parsed;
6281
6954
  try {
6282
6955
  parsed = JSON.parse(raw);
6283
6956
  } catch {
6284
6957
  throw new TBError(
6285
6958
  "invalid_argument",
6286
- `\u8BE5 plugin \u9700\u8981\u591A\u5B57\u6BB5\u51ED\u8BC1(${fields.map((f) => f.key).join("\u3001")}),\u4F46 secret \u5B58\u7684\u4E0D\u662F JSON \u5BF9\u8C61\u3002\u7528 \`tb secret set <name> --field k=v\` \u5199\u5165`
6959
+ `\u8BE5 plugin \u9700\u8981\u591A\u5B57\u6BB5\u51ED\u8BC1(${fields2.map((f) => f.key).join("\u3001")}),\u4F46 secret \u5B58\u7684\u4E0D\u662F JSON \u5BF9\u8C61\u3002\u7528 \`tb secret set <name> --field k=v\` \u5199\u5165`
6287
6960
  );
6288
6961
  }
6289
6962
  if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
6290
6963
  throw new TBError("invalid_argument", "\u591A\u5B57\u6BB5\u51ED\u8BC1\u7684 secret \u5FC5\u987B\u662F\u4E00\u4E2A JSON \u5BF9\u8C61");
6291
6964
  }
6292
- const source = parsed;
6965
+ const source2 = parsed;
6293
6966
  const values = {};
6294
6967
  const missing = [];
6295
- for (const field of fields) {
6296
- const value = source[field.key];
6968
+ for (const field of fields2) {
6969
+ const value = source2[field.key];
6297
6970
  if (typeof value === "string" && value !== "") {
6298
6971
  values[field.key] = value;
6299
6972
  continue;
@@ -6350,24 +7023,24 @@ var RequestDedupe = class {
6350
7023
  };
6351
7024
 
6352
7025
  // ../core/src/plugin/envelope.ts
6353
- import { z as z30 } from "zod";
7026
+ import { z as z35 } from "zod";
6354
7027
  var HEADER_TB_CONTEXT = "X-TB-Context";
6355
7028
  var HEADER_TB_REQUEST_ID = "X-TB-Request-Id";
6356
7029
  var HEADER_TB_UPSTREAM_AUTH = "X-TB-Upstream-Auth";
6357
7030
  var PLUGIN_PAYLOAD_MAX_BYTES = 1024 * 1024;
6358
- var callContextSchema = z30.object({
6359
- keyId: z30.string().min(1),
6360
- owner: z30.string().min(1),
6361
- scopes: z30.array(
6362
- z30.object({
6363
- pattern: z30.string().min(1),
6364
- actions: z30.array(z30.enum(ACTIONS)),
6365
- effect: z30.enum(["allow", "deny"]).optional()
7031
+ var callContextSchema = z35.object({
7032
+ keyId: z35.string().min(1),
7033
+ owner: z35.string().min(1),
7034
+ scopes: z35.array(
7035
+ z35.object({
7036
+ pattern: z35.string().min(1),
7037
+ actions: z35.array(z35.enum(ACTIONS)),
7038
+ effect: z35.enum(["allow", "deny"]).optional()
6366
7039
  })
6367
7040
  ),
6368
- registerPaths: z30.array(z30.string()).optional(),
6369
- traceId: z30.string().min(1),
6370
- mountPath: z30.string().min(1).optional(),
7041
+ registerPaths: z35.array(z35.string()).optional(),
7042
+ traceId: z35.string().min(1),
7043
+ mountPath: z35.string().min(1).optional(),
6371
7044
  /**
6372
7045
  * 挂载节点的 `providerConfig`。**只发给该节点对应的那个 plugin**(随本次调用的信封),
6373
7046
  * 插件之间不共享 —— 同一 plugin 部署的不同挂载各自收到自己那份。
@@ -6379,9 +7052,9 @@ var callContextSchema = z30.object({
6379
7052
  *
6380
7053
  * 放这里的应当是:region / baseUrl override / 功能开关 / workspace 归属之类的**非敏感**配置。
6381
7054
  */
6382
- mountConfig: z30.record(z30.string(), z30.unknown()).optional(),
7055
+ mountConfig: z35.record(z35.string(), z35.unknown()).optional(),
6383
7056
  /** v2 多 export 路由:本次调用命中 plugin 的哪个 export。 */
6384
- exportId: z30.string().min(1).optional()
7057
+ exportId: z35.string().min(1).optional()
6385
7058
  });
6386
7059
  function encodeCallContext(ctx) {
6387
7060
  return base64urlEncode(new TextEncoder().encode(JSON.stringify(ctx)));
@@ -6409,9 +7082,9 @@ function decodeCallContext(header) {
6409
7082
  }
6410
7083
  return parsed.data;
6411
7084
  }
6412
- var pluginCallSchema = z30.object({
6413
- tool: z30.string().min(1),
6414
- arguments: z30.record(z30.string(), z30.unknown())
7085
+ var pluginCallSchema = z35.object({
7086
+ tool: z35.string().min(1),
7087
+ arguments: z35.record(z35.string(), z35.unknown())
6415
7088
  });
6416
7089
  function assertPluginPayloadSize(payload) {
6417
7090
  const bytes2 = new TextEncoder().encode(payload).length;
@@ -6849,11 +7522,11 @@ async function encodeToolSearchCursor(query, mode, revision2, offset, secret, op
6849
7522
  toolSearchOptionsFingerprint(opts)
6850
7523
  );
6851
7524
  }
6852
- async function decodeToolSearchCursor(cursor, query, mode, revision2, secret, opts) {
6853
- if (cursor === void 0) return 0;
7525
+ async function decodeToolSearchCursor(cursor2, query, mode, revision2, secret, opts) {
7526
+ if (cursor2 === void 0) return 0;
6854
7527
  let value;
6855
7528
  try {
6856
- const sealed = cursorBase64UrlDecode(cursor);
7529
+ const sealed = cursorBase64UrlDecode(cursor2);
6857
7530
  if (sealed.length <= 12) throw new Error("truncated cursor");
6858
7531
  const plaintext = await crypto.subtle.decrypt(
6859
7532
  { iv: sealed.slice(0, 12), name: "AES-GCM" },
@@ -7336,13 +8009,13 @@ var SecretStoreImpl = class {
7336
8009
  */
7337
8010
  async list(opts) {
7338
8011
  const limit = Math.min(opts?.limit ?? LIST_LIMIT_DEFAULT, LIST_LIMIT_MAX);
7339
- const { items, cursor } = await this.store.list(KEY_SECRET, { cursor: opts?.cursor, limit });
8012
+ const { items, cursor: cursor2 } = await this.store.list(KEY_SECRET, { cursor: opts?.cursor, limit });
7340
8013
  return {
7341
8014
  items: items.map(({ key, value }) => ({
7342
8015
  name: key.slice(KEY_SECRET.length),
7343
8016
  updatedAt: isStoredSecret(value) ? value.updatedAt : ""
7344
8017
  })),
7345
- cursor
8018
+ cursor: cursor2
7346
8019
  };
7347
8020
  }
7348
8021
  /** 删除 secret;不存在 → not_found。 */
@@ -7425,19 +8098,19 @@ function parseFrontmatter(text) {
7425
8098
  }
7426
8099
 
7427
8100
  // ../core/src/skillhub/commands.ts
7428
- import { z as z31 } from "zod/v4";
7429
- var publishFileSchema = z31.strictObject({
7430
- path: z31.string().describe(
8101
+ import { z as z36 } from "zod/v4";
8102
+ var publishFileSchema = z36.strictObject({
8103
+ path: z36.string().describe(
7431
8104
  "file path relative to the skill root, e.g. 'SKILL.md', 'scripts/run.sh'"
7432
8105
  ),
7433
- content: z31.string().describe("UTF-8 text content"),
7434
- contentType: z31.string().optional().describe("optional; inferred from extension when omitted")
8106
+ content: z36.string().describe("UTF-8 text content"),
8107
+ contentType: z36.string().optional().describe("optional; inferred from extension when omitted")
7435
8108
  });
7436
8109
  var skillhubCommands = new HtbpCommandRegistry().register(
7437
8110
  "list",
7438
8111
  {
7439
8112
  h: "list published skills (id / name / description from SKILL.md frontmatter, paginated)",
7440
- inputSchema: z31.strictObject({ opts: HTBP_LIST_OPTIONS_SCHEMA.optional() }),
8113
+ inputSchema: z36.strictObject({ opts: HTBP_LIST_OPTIONS_SCHEMA.optional() }),
7441
8114
  returns: "Page<SkillSummary>",
7442
8115
  scope: "read"
7443
8116
  },
@@ -7446,9 +8119,9 @@ var skillhubCommands = new HtbpCommandRegistry().register(
7446
8119
  "get",
7447
8120
  {
7448
8121
  h: "read a skill: SKILL.md body + file manifest; pass 'file' to fetch one bundled file (oversized/binary as { $ref })",
7449
- inputSchema: z31.strictObject({
7450
- id: z31.string().describe("skill id"),
7451
- file: z31.string().optional().describe(
8122
+ inputSchema: z36.strictObject({
8123
+ id: z36.string().describe("skill id"),
8124
+ file: z36.string().optional().describe(
7452
8125
  "optional: path of one bundled file to fetch instead of the manifest"
7453
8126
  )
7454
8127
  }),
@@ -7460,8 +8133,8 @@ var skillhubCommands = new HtbpCommandRegistry().register(
7460
8133
  "search",
7461
8134
  {
7462
8135
  h: "keyword search over skill id / name / description",
7463
- inputSchema: z31.strictObject({
7464
- query: z31.string().describe("substring to match"),
8136
+ inputSchema: z36.strictObject({
8137
+ query: z36.string().describe("substring to match"),
7465
8138
  opts: HTBP_LIST_OPTIONS_SCHEMA.optional()
7466
8139
  }),
7467
8140
  returns: "Page<SkillSummary>",
@@ -7472,11 +8145,11 @@ var skillhubCommands = new HtbpCommandRegistry().register(
7472
8145
  "publish",
7473
8146
  {
7474
8147
  h: "publish/replace a skill from a set of text files (must include SKILL.md with name+description frontmatter)",
7475
- inputSchema: z31.strictObject({
7476
- id: z31.string().optional().describe(
8148
+ inputSchema: z36.strictObject({
8149
+ id: z36.string().optional().describe(
7477
8150
  "skill id; defaults to a slug derived from the frontmatter name"
7478
8151
  ),
7479
- files: z31.array(publishFileSchema).describe(
8152
+ files: z36.array(publishFileSchema).describe(
7480
8153
  "the skill files; whole-skill replace (files not listed are removed)"
7481
8154
  )
7482
8155
  }),
@@ -7494,7 +8167,7 @@ var skillhubCommands = new HtbpCommandRegistry().register(
7494
8167
  "remove",
7495
8168
  {
7496
8169
  h: "delete a skill and all its files (not_found if it does not exist)",
7497
- inputSchema: z31.strictObject({ id: z31.string().describe("skill id") }),
8170
+ inputSchema: z36.strictObject({ id: z36.string().describe("skill id") }),
7498
8171
  scope: "write",
7499
8172
  effect: "destructive"
7500
8173
  },
@@ -7547,7 +8220,7 @@ function guessContentType(path) {
7547
8220
  if (dot < 0) return "text/plain";
7548
8221
  return CONTENT_TYPE_BY_EXT[path.slice(dot + 1).toLowerCase()] ?? "text/plain";
7549
8222
  }
7550
- function clampLimit5(limit) {
8223
+ function clampLimit6(limit) {
7551
8224
  if (limit === void 0) return LIST_LIMIT_DEFAULT;
7552
8225
  if (!Number.isInteger(limit) || limit < 1) {
7553
8226
  throw new TBError("invalid_argument", `limit \u975E\u6CD5:${limit}`);
@@ -7602,7 +8275,7 @@ function createSkillhubProvider(store, opts) {
7602
8275
  };
7603
8276
  return {
7604
8277
  async list(listOpts) {
7605
- const limit = clampLimit5(listOpts?.limit);
8278
+ const limit = clampLimit6(listOpts?.limit);
7606
8279
  const res = await store.list(keyPrefix, {
7607
8280
  delimiter: "/",
7608
8281
  cursor: listOpts?.cursor,
@@ -7627,9 +8300,9 @@ function createSkillhubProvider(store, opts) {
7627
8300
  const summary = summaryOf(id, text, meta);
7628
8301
  const files = [];
7629
8302
  const prefix = skillPrefix(id);
7630
- let cursor;
8303
+ let cursor2;
7631
8304
  do {
7632
- const page = await store.list(prefix, { cursor, limit: LIST_LIMIT_MAX });
8305
+ const page = await store.list(prefix, { cursor: cursor2, limit: LIST_LIMIT_MAX });
7633
8306
  for (const it of page.items) {
7634
8307
  if ("prefix" in it) continue;
7635
8308
  files.push({
@@ -7639,8 +8312,8 @@ function createSkillhubProvider(store, opts) {
7639
8312
  version: it.etag
7640
8313
  });
7641
8314
  }
7642
- cursor = page.cursor;
7643
- } while (cursor !== void 0);
8315
+ cursor2 = page.cursor;
8316
+ } while (cursor2 !== void 0);
7644
8317
  return { ...summary, content: text, files };
7645
8318
  },
7646
8319
  async get_file(idRaw, file) {
@@ -7662,7 +8335,7 @@ function createSkillhubProvider(store, opts) {
7662
8335
  if (typeof query !== "string" || query === "") {
7663
8336
  throw new TBError("invalid_argument", "query \u4E0D\u80FD\u4E3A\u7A7A");
7664
8337
  }
7665
- const limit = clampLimit5(searchOpts?.limit);
8338
+ const limit = clampLimit6(searchOpts?.limit);
7666
8339
  const q = query.toLowerCase();
7667
8340
  const after = searchOpts?.cursor;
7668
8341
  const items = [];
@@ -7738,546 +8411,235 @@ ${summary.description}`.toLowerCase();
7738
8411
  const id = assertSkillId(input.id ?? slugify(fm.name));
7739
8412
  const prefix = skillPrefix(id);
7740
8413
  const keep = new Set(files.map((f) => `${prefix}${f.rel}`));
7741
- let cursor;
8414
+ let cursor2;
7742
8415
  do {
7743
- const page = await store.list(prefix, { cursor, limit: LIST_LIMIT_MAX });
8416
+ const page = await store.list(prefix, { cursor: cursor2, limit: LIST_LIMIT_MAX });
7744
8417
  for (const it of page.items) {
7745
8418
  if ("prefix" in it) continue;
7746
8419
  if (!keep.has(it.key)) await store.delete(it.key);
7747
8420
  }
7748
- cursor = page.cursor;
7749
- } while (cursor !== void 0);
8421
+ cursor2 = page.cursor;
8422
+ } while (cursor2 !== void 0);
7750
8423
  for (const f of files) {
7751
- await store.put(`${prefix}${f.rel}`, f.content, {
7752
- contentType: f.contentType || guessContentType(f.rel)
7753
- });
7754
- }
7755
- return { id, name: fm.name, description: fm.description, fileCount: files.length };
7756
- },
7757
- async remove(idRaw) {
7758
- assertWritable("remove");
7759
- const id = assertSkillId(idRaw);
7760
- const prefix = skillPrefix(id);
7761
- let cursor;
7762
- let removed = 0;
7763
- do {
7764
- const page = await store.list(prefix, { cursor, limit: LIST_LIMIT_MAX });
7765
- for (const it of page.items) {
7766
- if ("prefix" in it) continue;
7767
- await store.delete(it.key);
7768
- removed++;
7769
- }
7770
- cursor = page.cursor;
7771
- } while (cursor !== void 0);
7772
- if (removed === 0) throw TBError.notFound(`skill \u4E0D\u5B58\u5728:'${id}'`);
7773
- }
7774
- };
7775
- }
7776
-
7777
- // ../core/src/tool/httpTool.ts
7778
- var PARAM_RE = /\{([^{}]+)\}/g;
7779
- function buildQuery(params) {
7780
- const parts = [];
7781
- for (const [k, v] of Object.entries(params)) {
7782
- if (v === void 0) continue;
7783
- parts.push(`${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`);
7784
- }
7785
- return parts.join("&");
7786
- }
7787
- function buildHttpRequest(def, endpoint, args) {
7788
- const consumed = /* @__PURE__ */ new Set();
7789
- const path = def.pathTemplate.replace(PARAM_RE, (_match, name) => {
7790
- const value = args[name];
7791
- if (value === void 0) {
7792
- throw new TBError(
7793
- "invalid_argument",
7794
- `\u7F3A\u5C11\u8DEF\u5F84\u53C2\u6570 '${name}'(pathTemplate '${def.pathTemplate}')`
7795
- );
7796
- }
7797
- consumed.add(name);
7798
- return encodeURIComponent(String(value));
7799
- });
7800
- const remaining = {};
7801
- for (const [k, v] of Object.entries(args)) {
7802
- if (!consumed.has(k)) remaining[k] = v;
7803
- }
7804
- const base = endpoint.replace(/\/+$/, "");
7805
- const rel = path.startsWith("/") ? path : `/${path}`;
7806
- let url = `${base}${rel}`;
7807
- const headers = {};
7808
- let body;
7809
- if (def.method === "GET" || def.method === "DELETE") {
7810
- const qs = buildQuery(remaining);
7811
- if (qs) url += `?${qs}`;
7812
- } else {
7813
- body = JSON.stringify(remaining);
7814
- headers["content-type"] = "application/json";
7815
- }
7816
- return { url, method: def.method, body, headers };
7817
- }
7818
- function effectFor(def) {
7819
- if (def.effect !== void 0) return def.effect;
7820
- return def.method === "GET" ? "read" : "write";
7821
- }
7822
- function authHeaderFor(config, secret) {
7823
- const name = config.authHeader ?? "Authorization";
7824
- const scheme = config.authScheme;
7825
- const value = scheme === void 0 ? `Bearer ${secret}` : scheme === "" ? secret : `${scheme} ${secret}`;
7826
- return [name, value];
7827
- }
7828
-
7829
- // ../core/src/tool/mcpSchema.ts
7830
- function toolToCmd(nodePath, tool, index) {
7831
- const cmd = {
7832
- name: tool.name,
7833
- method: "POST",
7834
- path: `/${nodePath}/${tool.name}`,
7835
- scope: "call"
7836
- };
7837
- if (tool.description !== void 0) {
7838
- cmd.h = index ? summarizeOneLine(tool.description) : tool.description;
7839
- }
7840
- if (tool.delivery !== void 0) cmd.delivery = tool.delivery;
7841
- if (!index && tool.inputSchema !== void 0) cmd.inputSchema = tool.inputSchema;
7842
- if (!index && tool.outputSchema !== void 0) cmd.outputSchema = tool.outputSchema;
7843
- if (tool.effect !== void 0) cmd.effect = tool.effect;
7844
- const confirm = tool.confirm ?? (tool.effect === "destructive" ? true : void 0);
7845
- if (confirm) cmd.confirm = confirm;
7846
- return cmd;
7847
- }
7848
- function toolsToHelpModel(nodePath, node, tools, opts = {}) {
7849
- const index = opts.index === true;
7850
- const model = {
7851
- node: { path: nodePath, kind: node.kind, description: node.description },
7852
- cmds: tools.map((tool) => toolToCmd(nodePath, tool, index))
7853
- };
7854
- if (index) {
7855
- model.index = true;
7856
- model.hint = `this is an index (descriptions summarized, input schemas omitted); GET /${nodePath}/<tool>/~help returns one tool's full spec`;
7857
- }
7858
- return model;
7859
- }
7860
- function toolHelpModel(nodePath, node, tool) {
7861
- return {
7862
- node: {
7863
- path: `${nodePath}/${tool.name}`,
7864
- kind: node.kind,
7865
- description: summarizeOneLine(tool.description ?? node.description)
7866
- },
7867
- cmds: [toolToCmd(nodePath, tool, false)]
7868
- };
7869
- }
7870
-
7871
- // ../core/src/tool/remote.ts
7872
- function rewriteRemotePath(nodePath, requestPath, baseUrl) {
7873
- const base = baseUrl.replace(/\/+$/, "");
7874
- const rawSegs = requestPath.replace(/^\/+|\/+$/g, "").split("/").filter((s) => s.length > 0);
7875
- const reserved = rawSegs.length > 0 && rawSegs[rawSegs.length - 1]?.startsWith("~") ? rawSegs.pop() : void 0;
7876
- const nodeSegs = segments(nodePath);
7877
- const pathSegs = rawSegs;
7878
- let relSegs;
7879
- const isPrefix = nodeSegs.length <= pathSegs.length && nodeSegs.every((s, i) => s === pathSegs[i]);
7880
- if (isPrefix) {
7881
- relSegs = pathSegs.slice(nodeSegs.length);
7882
- } else {
7883
- relSegs = pathSegs;
7884
- }
7885
- const tail = reserved !== void 0 ? [...relSegs, reserved] : relSegs;
7886
- const rel = tail.join("/");
7887
- return rel === "" ? base : `${base}/${rel}`;
7888
- }
7889
- function hostOf(url) {
7890
- const m = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/([^/?#\\]*)/.exec(url);
7891
- if (m === null) return void 0;
7892
- let authority = m[1] ?? "";
7893
- const at = authority.lastIndexOf("@");
7894
- if (at >= 0) authority = authority.slice(at + 1);
7895
- if (authority.startsWith("[")) {
7896
- const close = authority.indexOf("]");
7897
- if (close >= 0) return authority.slice(0, close + 1).toLowerCase();
7898
- }
7899
- const colon = authority.indexOf(":");
7900
- const host = colon >= 0 ? authority.slice(0, colon) : authority;
7901
- return host.toLowerCase();
7902
- }
7903
- function checkAllowlist(baseUrl, allowlist) {
7904
- if (allowlist.length === 0) return false;
7905
- const host = hostOf(baseUrl);
7906
- if (host === void 0 || host === "") return false;
7907
- return allowlist.some((entry) => {
7908
- const suffix = entry.trim().toLowerCase();
7909
- if (suffix === "") return false;
7910
- return host === suffix || host.endsWith(`.${suffix}`);
7911
- });
8424
+ await store.put(`${prefix}${f.rel}`, f.content, {
8425
+ contentType: f.contentType || guessContentType(f.rel)
8426
+ });
8427
+ }
8428
+ return { id, name: fm.name, description: fm.description, fileCount: files.length };
8429
+ },
8430
+ async remove(idRaw) {
8431
+ assertWritable("remove");
8432
+ const id = assertSkillId(idRaw);
8433
+ const prefix = skillPrefix(id);
8434
+ let cursor2;
8435
+ let removed = 0;
8436
+ do {
8437
+ const page = await store.list(prefix, { cursor: cursor2, limit: LIST_LIMIT_MAX });
8438
+ for (const it of page.items) {
8439
+ if ("prefix" in it) continue;
8440
+ await store.delete(it.key);
8441
+ removed++;
8442
+ }
8443
+ cursor2 = page.cursor;
8444
+ } while (cursor2 !== void 0);
8445
+ if (removed === 0) throw TBError.notFound(`skill \u4E0D\u5B58\u5728:'${id}'`);
8446
+ }
8447
+ };
7912
8448
  }
7913
8449
 
7914
- // ../core/src/tool/via.ts
7915
- function parseVia(header) {
7916
- if (header === void 0) return [];
7917
- return header.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
7918
- }
7919
- function checkVia(chain, selfId, maxHops) {
7920
- if (chain.includes(selfId)) {
7921
- return new TBError("unavailable", `\u68C0\u6D4B\u5230\u900F\u4F20\u73AF:'${selfId}' \u5DF2\u5728 X-TB-Via \u94FE\u4E2D`, {
7922
- retryable: false
7923
- });
7924
- }
7925
- if (chain.length >= maxHops) {
7926
- return new TBError("unavailable", `\u900F\u4F20\u8DF3\u6570\u8D85\u9650:\u94FE\u957F ${chain.length} \u2265 maxHops ${maxHops}`, {
7927
- retryable: false
7928
- });
8450
+ // ../core/src/tool/httpTool.ts
8451
+ var PARAM_RE = /\{([^{}]+)\}/g;
8452
+ function buildQuery(params) {
8453
+ const parts = [];
8454
+ for (const [k, v] of Object.entries(params)) {
8455
+ if (v === void 0) continue;
8456
+ parts.push(`${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`);
7929
8457
  }
7930
- return null;
7931
- }
7932
- function appendVia(chain, selfId) {
7933
- return [...chain, selfId].join(", ");
7934
- }
7935
-
7936
- // ../core/src/tool/virtualize.ts
7937
- function virtualName(v, upstreamName) {
7938
- const renamed = v.rename?.[upstreamName] ?? upstreamName;
7939
- return v.prefix !== void 0 ? `${v.prefix}${renamed}` : renamed;
8458
+ return parts.join("&");
7940
8459
  }
7941
- function virtualizeTools(v, upstream) {
7942
- const exposed = [];
7943
- const reverse = /* @__PURE__ */ new Map();
7944
- const hidden = new Set(v?.hide ?? []);
7945
- for (const tool of upstream) {
7946
- if (hidden.has(tool.name)) continue;
7947
- const projectedName = v ? virtualName(v, tool.name) : tool.name;
7948
- const name = canonicalizeSegment(projectedName);
7949
- const previous = reverse.get(name);
7950
- if (previous !== void 0) {
8460
+ function buildHttpRequest(def, endpoint, args) {
8461
+ const consumed = /* @__PURE__ */ new Set();
8462
+ const path = def.pathTemplate.replace(PARAM_RE, (_match, name) => {
8463
+ const value = args[name];
8464
+ if (value === void 0) {
7951
8465
  throw new TBError(
7952
8466
  "invalid_argument",
7953
- `\u5DE5\u5177\u540D '${previous}' \u4E0E '${tool.name}' \u89C4\u8303\u5316\u540E\u51B2\u7A81:'${name}',\u8BF7\u663E\u5F0F rename`
8467
+ `\u7F3A\u5C11\u8DEF\u5F84\u53C2\u6570 '${name}'(pathTemplate '${def.pathTemplate}')`
7954
8468
  );
7955
8469
  }
7956
- const description = v?.describe?.[tool.name] ?? tool.description;
7957
- exposed.push({ ...tool, name, description });
7958
- reverse.set(name, tool.name);
8470
+ consumed.add(name);
8471
+ return encodeURIComponent(String(value));
8472
+ });
8473
+ const remaining = {};
8474
+ for (const [k, v] of Object.entries(args)) {
8475
+ if (!consumed.has(k)) remaining[k] = v;
7959
8476
  }
7960
- return { exposed, reverse };
7961
- }
7962
- function resolveUpstreamTool(v, source, virtualName2) {
7963
- const reverse = source instanceof Map ? source : virtualizeTools(v, source).reverse;
7964
- const upstream = reverse.get(virtualName2);
7965
- if (upstream === void 0) {
7966
- throw TBError.notFound(`\u672A\u77E5\u5DE5\u5177:'${virtualName2}'`);
8477
+ const base = endpoint.replace(/\/+$/, "");
8478
+ const rel = path.startsWith("/") ? path : `/${path}`;
8479
+ let url = `${base}${rel}`;
8480
+ const headers = {};
8481
+ let body;
8482
+ if (def.method === "GET" || def.method === "DELETE") {
8483
+ const qs = buildQuery(remaining);
8484
+ if (qs) url += `?${qs}`;
8485
+ } else {
8486
+ body = JSON.stringify(remaining);
8487
+ headers["content-type"] = "application/json";
7967
8488
  }
7968
- return upstream;
7969
- }
7970
-
7971
- // ../core/src/tree/registry.ts
7972
- function clampLimit6(limit) {
7973
- if (limit === void 0 || limit < 1) return LIST_LIMIT_DEFAULT;
7974
- return limit > LIST_LIMIT_MAX ? LIST_LIMIT_MAX : limit;
8489
+ return { url, method: def.method, body, headers };
7975
8490
  }
7976
- function assertKindConfig(node) {
7977
- if (node.config === void 0) return;
7978
- if (node.config.kind !== node.kind) {
7979
- throw new TBError(
7980
- "invalid_argument",
7981
- `kind='${node.kind}' \u4E0E config.kind='${node.config.kind}' \u4E0D\u4E00\u81F4`
7982
- );
7983
- }
8491
+ function effectFor(def) {
8492
+ if (def.effect !== void 0) return def.effect;
8493
+ return def.method === "GET" ? "read" : "write";
7984
8494
  }
7985
- function byPath(a, b) {
7986
- return a.path < b.path ? -1 : a.path > b.path ? 1 : 0;
8495
+ function authHeaderFor(config, secret) {
8496
+ const name = config.authHeader ?? "Authorization";
8497
+ const scheme = config.authScheme;
8498
+ const value = scheme === void 0 ? `Bearer ${secret}` : scheme === "" ? secret : `${scheme} ${secret}`;
8499
+ return [name, value];
7987
8500
  }
7988
- var NodeRegistryStore = class {
7989
- store;
7990
- constructor(store) {
7991
- this.store = store;
7992
- }
7993
- keyOf(path) {
7994
- return KEY_NODE + path;
7995
- }
7996
- async read(path) {
7997
- return await this.store.get(this.keyOf(path));
7998
- }
7999
- /** 翻页取尽 node:* 全量。 */
8000
- async scanAll() {
8001
- return this.scanPrefix(KEY_NODE);
8002
- }
8003
- /**
8004
- * 翻页扫描给定 KV 键前缀下的所有 TreeNode。
8005
- *
8006
- * 只扫子树(前缀限定),不再对全树做内存过滤——避免 children/hasChildren/subtree 的
8007
- * O(N²)(每层各扫全树)。`opts.limit` 传给底层 `store.list` 以小步取(hasChildren 短路用)。
8008
- *
8009
- * **Workers 查询预算约束**:D1StateStore.list 是单条 SQL 直接带值返回(ADR-001 迁 D1 后
8010
- * 不再逐键 get),每页只花一次 D1 查询;但 Workers 单请求仍有查询/子请求预算,深翻页的
8011
- * 页数应远小于预算——当前树规模小(节点数十级)可接受。
8012
- */
8013
- async scanPrefix(keyPrefix, opts) {
8014
- const out = [];
8015
- let cursor;
8016
- do {
8017
- const limit = opts?.maxNodes === void 0 ? opts?.limit ?? LIST_LIMIT_MAX : Math.min(
8018
- opts.limit ?? LIST_LIMIT_MAX,
8019
- opts.maxNodes - out.length + (opts.truncate === true ? 0 : 1)
8020
- );
8021
- if (limit < 1) return out;
8022
- const page = await this.store.list(keyPrefix, {
8023
- limit,
8024
- ...cursor !== void 0 ? { cursor } : {}
8025
- });
8026
- for (const { value } of page.items) out.push(value);
8027
- if (opts?.truncate === true && out.length >= (opts.maxNodes ?? Number.POSITIVE_INFINITY)) {
8028
- return out;
8029
- }
8030
- if (opts?.maxNodes !== void 0 && out.length > opts.maxNodes) {
8031
- throw new TBError(
8032
- "rate_limited",
8033
- `registry scan \u6700\u591A\u8BFB\u53D6 ${opts.maxNodes} \u4E2A\u8282\u70B9`
8034
- );
8035
- }
8036
- cursor = page.cursor;
8037
- } while (cursor);
8038
- return out;
8039
- }
8040
- /** KV 前缀:某路径的子树(含中间 directory)= `node:<path>/`;根('')= `node:`。 */
8041
- subtreePrefix(norm) {
8042
- return norm === "" ? KEY_NODE : `${KEY_NODE}${norm}/`;
8043
- }
8044
- async hasChildren(path) {
8045
- const norm = normalizePath(path);
8046
- const page = await this.store.list(this.subtreePrefix(norm), { limit: 1 });
8047
- return page.items.length > 0;
8048
- }
8049
- /** 取单个;不存在 → not_found。路径大小写不敏感(规范化为小写后查)。 */
8050
- async get(path) {
8051
- const norm = canonicalizePath(path);
8052
- const node = await this.read(norm);
8053
- if (!node) throw new TBError("not_found", `\u8282\u70B9\u4E0D\u5B58\u5728:'${norm}'`);
8054
- return node;
8055
- }
8056
- /** 批量取节点;路径先规范化(小写)去重,不存在的节点不进入返回 Map。 */
8057
- async getMany(paths) {
8058
- const canonical = [...new Set(paths.map((path) => canonicalizePath(path)))];
8059
- const values = await this.store.getMany(canonical.map((path) => this.keyOf(path)));
8060
- const out = /* @__PURE__ */ new Map();
8061
- for (const path of canonical) {
8062
- const value = values.get(this.keyOf(path));
8063
- if (value !== void 0) out.set(path, value);
8064
- }
8065
- return out;
8066
- }
8067
- /**
8068
- * 枚举 `prefix` 之下(含 prefix 自身,按段前缀匹配)的节点,分页。
8069
- * 无 prefix = 全树。cursor 为上一页末节点的 path。
8070
- */
8071
- async list(prefix, opts) {
8072
- const normPrefix = prefix === void 0 ? "" : canonicalizePath(prefix);
8073
- const limit = clampLimit6(opts?.limit);
8074
- const all = (await this.scanAll()).filter((n) => isPrefixOf(normPrefix, n.path)).sort(byPath);
8075
- const cursor = opts?.cursor;
8076
- const start = cursor ? all.findIndex((n) => n.path === cursor) + 1 : 0;
8077
- const items = all.slice(start, start + limit);
8078
- const hasMore = start + limit < all.length;
8079
- return {
8080
- items,
8081
- cursor: hasMore ? items[items.length - 1]?.path : void 0
8082
- };
8083
- }
8084
- /** 直接子节点(段深恰好 +1);~help 列子节点用。只扫子树前缀,不扫全树。 */
8085
- async children(path) {
8086
- const norm = canonicalizePath(path);
8087
- const depth = segments(norm).length;
8088
- const sub = await this.scanPrefix(this.subtreePrefix(norm));
8089
- return sub.filter((n) => segments(n.path).length === depth + 1).sort(byPath);
8090
- }
8091
- /**
8092
- * 一次性取整棵子树的节点数组(含 `path` 自身 + 全部后代),按 path 排序。
8093
- * 供 `~tree` 建树一次读入内存(而非每层递归各扫一遍)。根('')= 全树。
8094
- * 不存在的根返回空数组(调用方自行判 not_found)。
8095
- */
8096
- async subtree(path, opts) {
8097
- const norm = canonicalizePath(path);
8098
- if (opts?.maxNodes !== void 0 && (!Number.isInteger(opts.maxNodes) || opts.maxNodes < 1)) {
8099
- throw new TBError("invalid_argument", "maxNodes \u5FC5\u987B\u662F\u6B63\u6574\u6570");
8100
- }
8101
- const descendants = await this.scanPrefix(this.subtreePrefix(norm), opts);
8102
- if (norm === "") return descendants.sort(byPath);
8103
- const self = await this.read(norm);
8104
- const all = self ? [self, ...descendants] : descendants;
8105
- if (opts?.maxNodes !== void 0 && all.length > opts.maxNodes) {
8106
- throw new TBError(
8107
- "rate_limited",
8108
- `registry scan \u6700\u591A\u8BFB\u53D6 ${opts.maxNodes} \u4E2A\u8282\u70B9`
8109
- );
8110
- }
8111
- return all.sort(byPath);
8112
- }
8113
- /**
8114
- * 取按 key 确定排序的有界根快照,并显式报告是否截断。派生索引用 truncated
8115
- * 选择保留 last-known-good,不把 canonical registry 的规模限制反向施加到主数据面。
8116
- */
8117
- async rootSnapshot(maxNodes) {
8118
- if (!Number.isInteger(maxNodes) || maxNodes < 1) {
8119
- throw new TBError("invalid_argument", "maxNodes \u5FC5\u987B\u662F\u6B63\u6574\u6570");
8120
- }
8121
- const items = await this.scanPrefix(KEY_NODE, { maxNodes: maxNodes + 1, truncate: true });
8122
- return {
8123
- items: items.slice(0, maxNodes).sort(byPath),
8124
- truncated: items.length > maxNodes
8125
- };
8501
+
8502
+ // ../core/src/tool/mcpSchema.ts
8503
+ function toolToCmd(nodePath, tool, index) {
8504
+ const cmd = {
8505
+ name: tool.name,
8506
+ method: "POST",
8507
+ path: `/${nodePath}/${tool.name}`,
8508
+ scope: "call"
8509
+ };
8510
+ if (tool.description !== void 0) {
8511
+ cmd.h = index ? summarizeOneLine(tool.description) : tool.description;
8126
8512
  }
8127
- /**
8128
- * 幂等 upsert:
8129
- * - 校验路径(空/空段/保留段)与 kind↔config 一致性;
8130
- * - 自动物化 parentPaths 中缺失的中间 directory(registeredBy=system:auto,description='');
8131
- * 已存在的祖先(无论显式或自动)一律不动;
8132
- * - createdAt 保留原值(存在时)否则取 now;updatedAt 始终刷新为 now;
8133
- * - registeredBy 由调用方注入(device 节点由 Gateway 代写)。
8134
- *
8135
- * conflict(覆盖他人节点)判定在网关注册路径层,不在此——本层是幂等 upsert。
8136
- */
8137
- async write(node, registeredBy, now, opts = {}) {
8138
- const invalid2 = validatePath(node.path);
8139
- if (invalid2) throw invalid2;
8140
- const path = canonicalizePath(node.path);
8141
- assertKindConfig(node);
8142
- for (const parent of parentPaths(path)) {
8143
- if (!await this.read(parent)) {
8144
- const dir = {
8145
- path: parent,
8146
- kind: "directory",
8147
- description: "",
8148
- registeredBy: SYSTEM_AUTO,
8149
- createdAt: now,
8150
- updatedAt: now
8151
- };
8152
- await this.store.put(this.keyOf(parent), dir);
8153
- }
8154
- }
8155
- const existing = await this.read(path);
8156
- const full = {
8157
- path,
8158
- kind: node.kind,
8159
- description: node.description,
8160
- ...node.config !== void 0 ? { config: node.config } : {},
8161
- ...node.virtualize !== void 0 ? { virtualize: node.virtualize } : {},
8162
- ...opts.deviceId !== void 0 ? { deviceId: opts.deviceId } : {},
8163
- ...opts.deviceEnvironment !== void 0 ? { deviceEnvironment: opts.deviceEnvironment } : {},
8164
- ...opts.deviceReportedAt !== void 0 ? { deviceReportedAt: opts.deviceReportedAt } : {},
8165
- ...opts.online !== void 0 ? { online: opts.online } : {},
8166
- ...opts.lastSeenAt !== void 0 ? { lastSeenAt: opts.lastSeenAt } : {},
8167
- registeredBy,
8168
- createdAt: existing?.createdAt ?? now,
8169
- updatedAt: now
8170
- };
8171
- await this.store.put(this.keyOf(path), full);
8172
- return full;
8513
+ if (tool.delivery !== void 0) cmd.delivery = tool.delivery;
8514
+ if (!index && tool.inputSchema !== void 0) cmd.inputSchema = tool.inputSchema;
8515
+ if (!index && tool.outputSchema !== void 0) cmd.outputSchema = tool.outputSchema;
8516
+ if (tool.effect !== void 0) cmd.effect = tool.effect;
8517
+ const confirm = tool.confirm ?? (tool.effect === "destructive" ? true : void 0);
8518
+ if (confirm) cmd.confirm = confirm;
8519
+ return cmd;
8520
+ }
8521
+ function toolsToHelpModel(nodePath, node, tools, opts = {}) {
8522
+ const index = opts.index === true;
8523
+ const model = {
8524
+ node: { path: nodePath, kind: node.kind, description: node.description },
8525
+ cmds: tools.map((tool) => toolToCmd(nodePath, tool, index))
8526
+ };
8527
+ if (index) {
8528
+ model.index = true;
8529
+ model.hint = `this is an index (descriptions summarized, input schemas omitted); GET /${nodePath}/<tool>/~help returns one tool's full spec`;
8173
8530
  }
8174
- /** 部分更新(patch);不存在 → not_found;path 不可改。 */
8175
- async update(path, patch, now) {
8176
- const norm = canonicalizePath(path);
8177
- const existing = await this.read(norm);
8178
- if (!existing) throw new TBError("not_found", `\u8282\u70B9\u4E0D\u5B58\u5728:'${norm}'`);
8179
- if (patch.path !== void 0 && canonicalizePath(patch.path) !== norm) {
8180
- throw new TBError("invalid_argument", "path \u4E0D\u53EF\u901A\u8FC7 Update \u53D8\u66F4");
8181
- }
8182
- const merged = {
8183
- ...existing,
8184
- ...patch.kind !== void 0 ? { kind: patch.kind } : {},
8185
- ...patch.description !== void 0 ? { description: patch.description } : {},
8186
- ...patch.config !== void 0 ? { config: patch.config } : {},
8187
- ...patch.virtualize !== void 0 ? { virtualize: patch.virtualize } : {},
8188
- path: norm,
8189
- updatedAt: now
8190
- };
8191
- assertKindConfig(merged);
8192
- await this.store.put(this.keyOf(norm), merged);
8193
- return merged;
8531
+ return model;
8532
+ }
8533
+ function toolHelpModel(nodePath, node, tool) {
8534
+ return {
8535
+ node: {
8536
+ path: `${nodePath}/${tool.name}`,
8537
+ kind: node.kind,
8538
+ description: summarizeOneLine(tool.description ?? node.description)
8539
+ },
8540
+ cmds: [toolToCmd(nodePath, tool, false)]
8541
+ };
8542
+ }
8543
+
8544
+ // ../core/src/tool/remote.ts
8545
+ function rewriteRemotePath(nodePath, requestPath, baseUrl) {
8546
+ const base = baseUrl.replace(/\/+$/, "");
8547
+ const rawSegs = requestPath.replace(/^\/+|\/+$/g, "").split("/").filter((s) => s.length > 0);
8548
+ const reserved = rawSegs.length > 0 && rawSegs[rawSegs.length - 1]?.startsWith("~") ? rawSegs.pop() : void 0;
8549
+ const nodeSegs = segments(nodePath);
8550
+ const pathSegs = rawSegs;
8551
+ let relSegs;
8552
+ const isPrefix = nodeSegs.length <= pathSegs.length && nodeSegs.every((s, i) => s === pathSegs[i]);
8553
+ if (isPrefix) {
8554
+ relSegs = pathSegs.slice(nodeSegs.length);
8555
+ } else {
8556
+ relSegs = pathSegs;
8194
8557
  }
8195
- /**
8196
- * 设备生命周期专用:更新节点 online 状态,不存在 → not_found。
8197
- * online 翻 true 时视为一次存活观察,同步把 `lastSeenAt` 刷到 now;翻 false 时保留原
8198
- * `lastSeenAt`(用于展示"最后在线于")。
8199
- */
8200
- async setOnline(path, online, now) {
8201
- const norm = canonicalizePath(path);
8202
- const existing = await this.read(norm);
8203
- if (!existing) throw new TBError("not_found", `\u8282\u70B9\u4E0D\u5B58\u5728:'${norm}'`);
8204
- const updated = {
8205
- ...existing,
8206
- online,
8207
- ...online ? { lastSeenAt: now } : {},
8208
- updatedAt: now
8209
- };
8210
- await this.store.put(this.keyOf(norm), updated);
8211
- return updated;
8558
+ const tail = reserved !== void 0 ? [...relSegs, reserved] : relSegs;
8559
+ const rel = tail.join("/");
8560
+ return rel === "" ? base : `${base}/${rel}`;
8561
+ }
8562
+ function hostOf(url) {
8563
+ const m = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/([^/?#\\]*)/.exec(url);
8564
+ if (m === null) return void 0;
8565
+ let authority = m[1] ?? "";
8566
+ const at = authority.lastIndexOf("@");
8567
+ if (at >= 0) authority = authority.slice(at + 1);
8568
+ if (authority.startsWith("[")) {
8569
+ const close = authority.indexOf("]");
8570
+ if (close >= 0) return authority.slice(0, close + 1).toLowerCase();
8212
8571
  }
8213
- /**
8214
- * 设备心跳专用:只把 `lastSeenAt` 刷到 now,不改 online 也不动 updatedAt(心跳不是元数据变更,
8215
- * 不该扰动 updatedAt 的语义)。节点不存在时静默返回——心跳晚于节点删除是正常竞态,不报错。
8216
- */
8217
- async touchSeen(path, now) {
8218
- const norm = canonicalizePath(path);
8219
- const existing = await this.read(norm);
8220
- if (!existing) return;
8221
- await this.store.put(this.keyOf(norm), { ...existing, lastSeenAt: now });
8572
+ const colon = authority.indexOf(":");
8573
+ const host = colon >= 0 ? authority.slice(0, colon) : authority;
8574
+ return host.toLowerCase();
8575
+ }
8576
+ function checkAllowlist(baseUrl, allowlist) {
8577
+ if (allowlist.length === 0) return false;
8578
+ const host = hostOf(baseUrl);
8579
+ if (host === void 0 || host === "") return false;
8580
+ return allowlist.some((entry) => {
8581
+ const suffix = entry.trim().toLowerCase();
8582
+ if (suffix === "") return false;
8583
+ return host === suffix || host.endsWith(`.${suffix}`);
8584
+ });
8585
+ }
8586
+
8587
+ // ../core/src/tool/via.ts
8588
+ function parseVia(header) {
8589
+ if (header === void 0) return [];
8590
+ return header.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
8591
+ }
8592
+ function checkVia(chain, selfId, maxHops) {
8593
+ if (chain.includes(selfId)) {
8594
+ return new TBError("unavailable", `\u68C0\u6D4B\u5230\u900F\u4F20\u73AF:'${selfId}' \u5DF2\u5728 X-TB-Via \u94FE\u4E2D`, {
8595
+ retryable: false
8596
+ });
8222
8597
  }
8223
- /**
8224
- * 卸载;不存在 → not_found。删除后自底向上级联回收:
8225
- * 仅回收 registeredBy=system:auto 且再无子节点的 directory,遇显式节点/仍有子节点即停。
8226
- *
8227
- * 实现决策(待回写 docs):被删节点若仍有后代 → conflict
8228
- * (不允许删除非空子树;显式 directory 同理)。
8229
- */
8230
- async delete(path) {
8231
- const norm = canonicalizePath(path);
8232
- const existing = await this.read(norm);
8233
- if (!existing) throw new TBError("not_found", `\u8282\u70B9\u4E0D\u5B58\u5728:'${norm}'`);
8234
- if (await this.hasChildren(norm)) {
8235
- throw new TBError("conflict", `\u8282\u70B9 '${norm}' \u4ECD\u6709\u5B50\u8282\u70B9,\u4E0D\u5141\u8BB8\u5220\u9664\u975E\u7A7A\u5B50\u6811`);
8236
- }
8237
- await this.store.delete(this.keyOf(norm));
8238
- for (const parent of [...parentPaths(norm)].reverse()) {
8239
- const p = await this.read(parent);
8240
- if (!p || p.registeredBy !== SYSTEM_AUTO || p.kind !== "directory") break;
8241
- if (await this.hasChildren(parent)) break;
8242
- await this.store.delete(this.keyOf(parent));
8243
- }
8598
+ if (chain.length >= maxHops) {
8599
+ return new TBError("unavailable", `\u900F\u4F20\u8DF3\u6570\u8D85\u9650:\u94FE\u957F ${chain.length} \u2265 maxHops ${maxHops}`, {
8600
+ retryable: false
8601
+ });
8244
8602
  }
8245
- /**
8246
- * 设备回收专用:删除一个已知子树(含根与全部后代),再按普通 delete 规则回收自动目录。
8247
- * 普通管理面仍使用 delete(),不允许误删非空子树。
8248
- */
8249
- async deleteSubtree(path) {
8250
- const norm = canonicalizePath(path);
8251
- const existing = await this.read(norm);
8252
- if (!existing) throw new TBError("not_found", `\u8282\u70B9\u4E0D\u5B58\u5728:'${norm}'`);
8253
- const descendants = await this.scanPrefix(this.subtreePrefix(norm));
8254
- descendants.sort((a, b) => segments(b.path).length - segments(a.path).length || byPath(b, a));
8255
- for (const n of descendants) await this.store.delete(this.keyOf(n.path));
8256
- await this.store.delete(this.keyOf(norm));
8257
- for (const parent of [...parentPaths(norm)].reverse()) {
8258
- const p = await this.read(parent);
8259
- if (!p || p.registeredBy !== SYSTEM_AUTO || p.kind !== "directory") break;
8260
- if (await this.hasChildren(parent)) break;
8261
- await this.store.delete(this.keyOf(parent));
8603
+ return null;
8604
+ }
8605
+ function appendVia(chain, selfId) {
8606
+ return [...chain, selfId].join(", ");
8607
+ }
8608
+
8609
+ // ../core/src/tool/virtualize.ts
8610
+ function virtualName(v, upstreamName) {
8611
+ const renamed = v.rename?.[upstreamName] ?? upstreamName;
8612
+ return v.prefix !== void 0 ? `${v.prefix}${renamed}` : renamed;
8613
+ }
8614
+ function virtualizeTools(v, upstream) {
8615
+ const exposed = [];
8616
+ const reverse = /* @__PURE__ */ new Map();
8617
+ const hidden = new Set(v?.hide ?? []);
8618
+ for (const tool of upstream) {
8619
+ if (hidden.has(tool.name)) continue;
8620
+ const projectedName = v ? virtualName(v, tool.name) : tool.name;
8621
+ const name = canonicalizeSegment(projectedName);
8622
+ const previous = reverse.get(name);
8623
+ if (previous !== void 0) {
8624
+ throw new TBError(
8625
+ "invalid_argument",
8626
+ `\u5DE5\u5177\u540D '${previous}' \u4E0E '${tool.name}' \u89C4\u8303\u5316\u540E\u51B2\u7A81:'${name}',\u8BF7\u663E\u5F0F rename`
8627
+ );
8262
8628
  }
8629
+ const description = v?.describe?.[tool.name] ?? tool.description;
8630
+ exposed.push({ ...tool, name, description });
8631
+ reverse.set(name, tool.name);
8263
8632
  }
8264
- /**
8265
- * 最长前缀匹配:返回命中节点与剩余段('/' 连接)。
8266
- * 完全匹配 → rest=''。无任何匹配 → not_found。
8267
- */
8268
- async resolve(path) {
8269
- const norm = canonicalizePath(path);
8270
- const candidates = [norm, ...parentPaths(norm).reverse()];
8271
- for (const cand of candidates) {
8272
- const node = await this.read(cand);
8273
- if (node) {
8274
- const rest = segments(norm).slice(segments(cand).length).join("/");
8275
- return { node, rest };
8276
- }
8277
- }
8278
- throw new TBError("not_found", `\u65E0\u5339\u914D\u8282\u70B9:'${norm}'`);
8633
+ return { exposed, reverse };
8634
+ }
8635
+ function resolveUpstreamTool(v, source2, virtualName2) {
8636
+ const reverse = source2 instanceof Map ? source2 : virtualizeTools(v, source2).reverse;
8637
+ const upstream = reverse.get(virtualName2);
8638
+ if (upstream === void 0) {
8639
+ throw TBError.notFound(`\u672A\u77E5\u5DE5\u5177:'${virtualName2}'`);
8279
8640
  }
8280
- };
8641
+ return upstream;
8642
+ }
8281
8643
 
8282
8644
  export {
8283
8645
  TB_ERROR_CODES,
@@ -8290,6 +8652,7 @@ export {
8290
8652
  validatePath,
8291
8653
  KEY_SK_HASH,
8292
8654
  KEY_SK_ID,
8655
+ KEY_NODE,
8293
8656
  KEY_PLUGIN,
8294
8657
  KEY_BOOTSTRAPPED,
8295
8658
  KEY_FEEDBACK,
@@ -8308,6 +8671,7 @@ export {
8308
8671
  identify,
8309
8672
  toToolResult,
8310
8673
  OperationRegistry,
8674
+ eventBindingSchema,
8311
8675
  OAUTH_CLIENT_FIELDS,
8312
8676
  shouldRefresh,
8313
8677
  buildAuthorizationUrl,
@@ -8323,6 +8687,14 @@ export {
8323
8687
  optionalMethodsForCapabilities,
8324
8688
  normalizeUpstreamError,
8325
8689
  assertSecureUrl,
8690
+ canonicalCatalogJson,
8691
+ catalogSetDigest,
8692
+ resolveIntegration,
8693
+ pluginImageSchema,
8694
+ pluginVersionPattern,
8695
+ httpsReleaseUrl,
8696
+ parsePluginRelease,
8697
+ NodeRegistryStore,
8326
8698
  pluginTokenSecretName,
8327
8699
  createStoreModule,
8328
8700
  RemoteAllowlistStore,
@@ -8394,6 +8766,10 @@ export {
8394
8766
  derivePresence,
8395
8767
  DEVICE_CALL_TIMEOUT_MS,
8396
8768
  DeviceGatewaySession,
8769
+ EVENT_MAX_BYTES,
8770
+ eventPublishSchema,
8771
+ eventReadSchema,
8772
+ eventCommands,
8397
8773
  FEEDBACK_HIDE_SCORE,
8398
8774
  selectFeedbackSearchText,
8399
8775
  parseFeedbackEntries,
@@ -8410,8 +8786,6 @@ export {
8410
8786
  assertUploadBinding,
8411
8787
  storeUri,
8412
8788
  StoreService,
8413
- catalogSetDigest,
8414
- resolveIntegration,
8415
8789
  parseCredentialValues,
8416
8790
  RequestDedupe,
8417
8791
  HEADER_TB_CONTEXT,
@@ -8460,6 +8834,5 @@ export {
8460
8834
  checkVia,
8461
8835
  appendVia,
8462
8836
  virtualizeTools,
8463
- resolveUpstreamTool,
8464
- NodeRegistryStore
8837
+ resolveUpstreamTool
8465
8838
  };