@capybara-hq/plugin-sdk 0.1.0-rc.8 → 0.1.0-rc.80

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 (149) hide show
  1. package/README.md +1 -1
  2. package/agent-docs/agent-templates.md +14 -2
  3. package/agent-docs/concepts.md +14 -5
  4. package/agent-docs/connector-templates.md +11 -3
  5. package/agent-docs/extension-points/channel.md +1 -1
  6. package/agent-docs/extension-points/context.md +15 -0
  7. package/agent-docs/extension-points/device-provider.md +15 -0
  8. package/agent-docs/extension-points/file-preview.md +3 -1
  9. package/agent-docs/extension-points/identity-source.md +2 -0
  10. package/agent-docs/extension-points/model-provider.md +3 -1
  11. package/agent-docs/extension-points/object-store.md +2 -0
  12. package/agent-docs/extension-points/push-provider.md +17 -0
  13. package/agent-docs/extensions.md +77 -4
  14. package/agent-docs/plugin-format.md +45 -10
  15. package/agent-docs/setup.md +54 -0
  16. package/dist/agent-template.d.ts +15 -6
  17. package/dist/agent-template.js +32 -13
  18. package/dist/avatar-presets.d.ts +8 -0
  19. package/dist/avatar-presets.js +17 -0
  20. package/dist/bootstrap.d.ts +109 -1
  21. package/dist/bootstrap.js +185 -2
  22. package/dist/cards.d.ts +60 -13
  23. package/dist/cards.js +88 -18
  24. package/dist/channel.d.ts +128 -47
  25. package/dist/channel.js +10 -5
  26. package/dist/client-css.d.ts +36 -0
  27. package/dist/client-css.js +326 -0
  28. package/dist/client-section.d.ts +35 -0
  29. package/dist/client-section.js +133 -0
  30. package/dist/config-ui.d.ts +28 -6
  31. package/dist/config-ui.js +88 -25
  32. package/dist/config-url-fetch.d.ts +19 -0
  33. package/dist/config-url-fetch.js +43 -0
  34. package/dist/connector-auth.d.ts +13 -2
  35. package/dist/connector-auth.js +82 -8
  36. package/dist/connector.d.ts +74 -32
  37. package/dist/context.d.ts +40 -0
  38. package/dist/context.js +2 -0
  39. package/dist/ctx.d.ts +224 -30
  40. package/dist/ctx.js +9 -1
  41. package/dist/define-extension.d.ts +23 -13
  42. package/dist/define-extension.js +19 -5
  43. package/dist/device-denied-paths.d.ts +20 -0
  44. package/dist/device-denied-paths.js +118 -0
  45. package/dist/device-operation.d.ts +339 -0
  46. package/dist/device-operation.js +312 -0
  47. package/dist/device-protocol.d.ts +285 -50
  48. package/dist/device-protocol.js +755 -90
  49. package/dist/device-provider.d.ts +780 -0
  50. package/dist/device-provider.js +409 -0
  51. package/dist/device-service.d.ts +126 -0
  52. package/dist/device-service.js +211 -0
  53. package/dist/dial-in.d.ts +286 -0
  54. package/dist/dial-in.js +213 -0
  55. package/dist/directory.d.ts +15 -12
  56. package/dist/extension-point.d.ts +2 -0
  57. package/dist/extension-point.js +7 -3
  58. package/dist/field-meta.d.ts +19 -0
  59. package/dist/field-meta.js +54 -0
  60. package/dist/file-preview.d.ts +43 -10
  61. package/dist/git-hosts.d.ts +53 -0
  62. package/dist/git-hosts.js +98 -0
  63. package/dist/hooks.d.ts +125 -20
  64. package/dist/hooks.js +5 -0
  65. package/dist/http-access.d.ts +71 -0
  66. package/dist/http-access.js +12 -0
  67. package/dist/identity.d.ts +70 -9
  68. package/dist/identity.js +46 -1
  69. package/dist/index.d.ts +28 -4
  70. package/dist/index.js +28 -4
  71. package/dist/model-params.d.ts +41 -22
  72. package/dist/model-params.js +28 -15
  73. package/dist/model.d.ts +210 -75
  74. package/dist/model.js +152 -19
  75. package/dist/native-failure.d.ts +13 -0
  76. package/dist/native-failure.js +31 -0
  77. package/dist/net.d.ts +52 -0
  78. package/dist/net.js +34 -0
  79. package/dist/network-classes.d.ts +98 -0
  80. package/dist/network-classes.js +291 -0
  81. package/dist/permissions.d.ts +65 -22
  82. package/dist/permissions.js +139 -43
  83. package/dist/platform-only.d.ts +27 -0
  84. package/dist/platform-only.js +35 -0
  85. package/dist/plugin-manifest.d.ts +30 -6
  86. package/dist/plugin-manifest.js +147 -55
  87. package/dist/plugin-package.d.ts +82 -39
  88. package/dist/plugin-package.js +68 -41
  89. package/dist/push.d.ts +75 -0
  90. package/dist/push.js +87 -0
  91. package/dist/sandbox-linux-runtime-source.d.ts +1 -0
  92. package/dist/sandbox-linux-runtime-source.js +2343 -0
  93. package/dist/sandbox-native-runtime-source.d.ts +10 -0
  94. package/dist/sandbox-native-runtime-source.js +480 -0
  95. package/dist/sandbox-runtime-source.d.ts +47 -0
  96. package/dist/sandbox-runtime-source.js +73 -0
  97. package/dist/sandbox-write-denies.d.ts +139 -0
  98. package/dist/sandbox-write-denies.js +869 -0
  99. package/dist/secret.d.ts +8 -2
  100. package/dist/secret.js +11 -4
  101. package/dist/setup-check.d.ts +128 -0
  102. package/dist/setup-check.js +142 -0
  103. package/dist/setup-guide-parse.d.ts +121 -0
  104. package/dist/setup-guide-parse.js +356 -0
  105. package/dist/setup-guide-render.d.ts +45 -0
  106. package/dist/setup-guide-render.js +351 -0
  107. package/dist/setup-guide.d.ts +86 -72
  108. package/dist/setup-guide.js +340 -108
  109. package/dist/shell-capabilities.d.ts +211 -0
  110. package/dist/shell-capabilities.js +44 -0
  111. package/dist/shell-environment.d.ts +57 -0
  112. package/dist/shell-environment.js +21 -0
  113. package/dist/skill-invocation.d.ts +5 -0
  114. package/dist/skill-invocation.js +4 -3
  115. package/dist/skill.d.ts +27 -17
  116. package/dist/skill.js +40 -26
  117. package/dist/storage.d.ts +52 -25
  118. package/dist/svg-viewbox.d.ts +10 -0
  119. package/dist/svg-viewbox.js +24 -0
  120. package/dist/theme-assets.d.ts +25 -9
  121. package/dist/theme-assets.js +87 -47
  122. package/dist/theme-tokens.generated.d.ts +26 -2
  123. package/dist/theme-tokens.generated.js +17 -0
  124. package/dist/theme.d.ts +48 -10
  125. package/dist/theme.js +100 -21
  126. package/dist/tool.d.ts +156 -30
  127. package/dist/tool.js +91 -9
  128. package/dist/ui-parts.d.ts +23 -0
  129. package/dist/ui-parts.js +385 -0
  130. package/dist/ui-resolve.d.ts +35 -0
  131. package/dist/ui-resolve.js +42 -0
  132. package/dist/ui-slots.d.ts +65 -0
  133. package/dist/ui-slots.js +261 -0
  134. package/dist/ui.d.ts +245 -77
  135. package/dist/ui.js +104 -27
  136. package/dist/url.d.ts +4 -1
  137. package/dist/url.js +4 -1
  138. package/dist/web.d.ts +26 -20
  139. package/package.json +12 -1
  140. package/schemas/bootstrap-extra.v1.schema.json +186 -0
  141. package/schemas/bootstrap.v1.schema.json +20 -0
  142. package/schemas/connector-template.v1.schema.json +62 -4
  143. package/schemas/plugin.v1.schema.json +74 -143
  144. package/schemas/theme.v1.schema.json +77 -0
  145. package/agent-docs/extension-points/sandbox.md +0 -15
  146. package/dist/org-access.d.ts +0 -27
  147. package/dist/org-access.js +0 -35
  148. package/dist/sandbox.d.ts +0 -254
  149. package/dist/sandbox.js +0 -153
package/dist/cards.js CHANGED
@@ -3,14 +3,16 @@ import { isHttpUrl } from "./url.js";
3
3
  const MAX_INLINE_SINGLE = 5;
4
4
  const MAX_INLINE_MULTI = 10;
5
5
  /**
6
- * 提问能否在 IM 内直接作答:仅当表单恰有一个枚举字段(单选 ≤ 5 项 / 多选 ≤ 10 项)且不允许「其他」时为真;
7
- * 否则卡片只给网页链接。
6
+ * Whether IM can draw the question's controls: exactly one enum field (single choice ≤ 5 options /
7
+ * multi-select ≤ 10). A field with `allowOther` qualifies only when the card has `textReply`
8
+ * (pass `{ textReply: card.textReply !== undefined }`): the Other path is then a plain reply, so
9
+ * never draw an Other button. Otherwise the card only links to the web.
8
10
  */
9
- export function questionRenderableInline(form) {
11
+ export function questionRenderableInline(form, opts) {
10
12
  if (form.fields.length !== 1)
11
13
  return false;
12
14
  const f = form.fields[0];
13
- if (!f || f.allowOther)
15
+ if (!f || (f.allowOther && opts?.textReply !== true))
14
16
  return false;
15
17
  if (f.schema.type !== "string" || !("enum" in f.schema))
16
18
  return false;
@@ -19,11 +21,20 @@ export function questionRenderableInline(form) {
19
21
  }
20
22
  const KINDS = ["approval", "question", "connect", "bind"];
21
23
  const SCOPES = ["once", "session", "always"];
22
- const APPROVAL_STATES = ["pending", "approved", "denied", "expired", "cancelled"];
23
- const QUESTION_STATES = ["pending", "answered", "expired", "cancelled"];
24
+ const APPROVAL_STATES = [
25
+ "pending",
26
+ "approved",
27
+ "denied",
28
+ "expired",
29
+ "cancelled",
30
+ "skipped",
31
+ ];
32
+ const MAX_SCOPE_LABEL = 40;
33
+ const QUESTION_STATES = ["pending", "answered", "skipped", "expired", "cancelled"];
34
+ const TEXT_REPLY = ["plain", "mention"];
24
35
  const ISO_8601 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
25
36
  const list = (xs) => xs.map((x) => JSON.stringify(x)).join(", ");
26
- /** 校验卡片结构,返回问题列表(空 = 合法)。 */
37
+ /** Validates the card structure and returns the list of problems (empty = valid). */
27
38
  export function validateChannelCard(card) {
28
39
  if (typeof card !== "object" || card === null || Array.isArray(card))
29
40
  return ["card must be an object"];
@@ -58,6 +69,16 @@ export function validateChannelCard(card) {
58
69
  new Set(s).size !== s.length ||
59
70
  s.some((x) => !SCOPES.includes(x)))
60
71
  out.push(`scopes must be a non-empty array of ${list(SCOPES)} without duplicates`);
72
+ const labels = c.scopeLabels;
73
+ if (labels !== undefined &&
74
+ (typeof labels !== "object" ||
75
+ labels === null ||
76
+ Array.isArray(labels) ||
77
+ Object.entries(labels).some(([k, v]) => !SCOPES.includes(k) ||
78
+ typeof v !== "string" ||
79
+ v.length === 0 ||
80
+ v.length > MAX_SCOPE_LABEL)))
81
+ out.push(`scopeLabels must map ${list(SCOPES)} to strings of 1 to ${MAX_SCOPE_LABEL} characters`);
61
82
  if (typeof c.expiresAt !== "string" ||
62
83
  !ISO_8601.test(c.expiresAt) ||
63
84
  Number.isNaN(Date.parse(c.expiresAt)))
@@ -74,7 +95,10 @@ export function validateChannelCard(card) {
74
95
  url("webUrl");
75
96
  if (c.answerSummary !== undefined && typeof c.answerSummary !== "string")
76
97
  out.push("answerSummary must be a string");
77
- // 不能在 IM 内作答的表单(见 questionRenderableInline)同样合法:渠道只渲染网页链接。
98
+ if (c.textReply !== undefined)
99
+ oneOf("textReply", TEXT_REPLY);
100
+ // A form that cannot be answered inside the IM (see questionRenderableInline) is equally
101
+ // valid: the channel renders only the web link.
78
102
  for (const p of validateInputForm(c.form))
79
103
  out.push(`form: ${p}`);
80
104
  return out;
@@ -92,12 +116,16 @@ export function validateChannelCard(card) {
92
116
  }
93
117
  }
94
118
  /**
95
- * 把模型可控的值(审批标题、调用摘要、提问标题、回答摘要)放进代码里,退回文本里它们不会变成链接、强调或 HTML:
96
- * 单行用行内代码,多行用围栏代码块(以换行开头),分隔符都比值里最长的反引号串更长(CommonMark 6.1 / 4.5)。
97
- * 选代码而不是给标点加反斜杠:代码是 CommonMark / GFM 里唯一保证内容按原样显示的写法(反斜杠挡不住 GFM 的裸网址
98
- * 自动链接,各渠道转换器对反斜杠的处理也不一致)。
119
+ * Puts model-controllable values (approval title, call summary, question title, answer summary)
120
+ * into code, so that in the fallback text they do not turn into links, emphasis or HTML:
121
+ * single-line values use inline code, multi-line values a fenced code block (starting with a
122
+ * newline); the delimiters are always longer than the longest backtick run in the value (CommonMark
123
+ * 6.1 / 4.5).
124
+ * Code is chosen over backslash-escaping punctuation because code is the only form CommonMark / GFM
125
+ * guarantee to display content verbatim (a backslash does not stop GFM bare-URL
126
+ * autolinks, and channel converters treat backslashes inconsistently).
99
127
  */
100
- function asCode(s) {
128
+ export function asCode(s) {
101
129
  const v = s.replace(/\r\n?/g, "\n");
102
130
  const longest = Math.max(0, ...[...v.matchAll(/`+/g)].map((m) => m[0].length));
103
131
  if (v.includes("\n")) {
@@ -105,11 +133,15 @@ function asCode(s) {
105
133
  return `\n${fence}\n${v}\n${fence}`;
106
134
  }
107
135
  const d = "`".repeat(longest + 1);
108
- // 值以反引号开头 / 结尾、或首尾都是空格时补一个空格(渲染时去掉),否则会与分隔符粘连或被吃掉空格
136
+ // When the value starts / ends with a backtick, or has spaces at both ends, add one space
137
+ // (stripped when rendered); otherwise it would stick to the delimiter or lose its spaces
109
138
  const pad = /^`|`$/.test(v) || (v.startsWith(" ") && v.endsWith(" ")) ? " " : "";
110
139
  return `${d}${pad}${v}${pad}${d}`;
111
140
  }
112
- /** 前缀 + 代码:代码是围栏块(以换行开头)时去掉前缀末尾的空格。 */
141
+ /**
142
+ * Prefix + code: when the code is a fenced block (starting with a newline), drop the trailing space
143
+ * of the prefix.
144
+ */
113
145
  const withCode = (prefix, code) => code.startsWith("\n") ? `${prefix.trimEnd()}${code}` : `${prefix}${code}`;
114
146
  const TEXT = {
115
147
  en: {
@@ -128,19 +160,27 @@ const TEXT = {
128
160
  answerOnWeb: "Answer on the web",
129
161
  details: "Details",
130
162
  connectLink: "Connect",
163
+ options: "Options",
164
+ scopes: { once: "Once", session: "This session", always: "Always" },
131
165
  approvalStates: {
132
166
  pending: "Pending",
133
167
  approved: "Approved",
134
168
  denied: "Denied",
135
169
  expired: "Expired",
136
170
  cancelled: "Cancelled",
171
+ skipped: "Skipped",
137
172
  },
138
173
  questionStates: {
139
174
  pending: "Pending",
140
175
  answered: "Answered",
176
+ skipped: "Skipped (replied instead)",
141
177
  expired: "Expired",
142
178
  cancelled: "Cancelled",
143
179
  },
180
+ textReply: {
181
+ plain: "You can also just reply with text",
182
+ mention: "You can also reply in this thread, mentioning me",
183
+ },
144
184
  },
145
185
  zh: {
146
186
  sep: ":",
@@ -158,24 +198,46 @@ const TEXT = {
158
198
  answerOnWeb: "到网页上回答",
159
199
  details: "详情",
160
200
  connectLink: "连接",
201
+ options: "选项",
202
+ scopes: { once: "这次", session: "本会话", always: "一直" },
161
203
  approvalStates: {
162
204
  pending: "待审批",
163
205
  approved: "已批准",
164
206
  denied: "已拒绝",
165
207
  expired: "已过期",
166
208
  cancelled: "已取消",
209
+ skipped: "已跳过",
167
210
  },
168
211
  questionStates: {
169
212
  pending: "待回答",
170
213
  answered: "已回答",
214
+ skipped: "已跳过(已直接回复)",
171
215
  expired: "已过期",
172
216
  cancelled: "已取消",
173
217
  },
218
+ textReply: {
219
+ plain: "也可以直接回复文字",
220
+ mention: "也可以在本话题 @我 回复文字",
221
+ },
174
222
  },
175
223
  };
224
+ /** The hint line of a pending question card with `textReply`, as {@link renderCardAsText} writes it. */
225
+ export function questionTextReplyHint(mode, locale) {
226
+ return (TEXT[locale] ?? TEXT.en).textReply[mode];
227
+ }
228
+ /**
229
+ * The label of a question card's state, as {@link renderCardAsText} writes it. A state this SDK
230
+ * does not know (a newer kernel) returns the state itself, never `undefined`.
231
+ */
232
+ export function questionStateLabel(state, locale) {
233
+ const states = (TEXT[locale] ?? TEXT.en).questionStates;
234
+ return states[state] ?? state;
235
+ }
176
236
  /**
177
- * 不支持卡片的渠道的统一退回文本(含链接);固定话术按 locale 取 zh / en。结果是 Markdown(放进
178
- * `OutboundMessage.text`,由渠道插件转换):模型可控的字段放在代码里(见 `asCode`),不会产生链接。
237
+ * The uniform fallback text for channels without card support (links included); the fixed phrases
238
+ * are taken by locale, zh / en. The result is Markdown (put into
239
+ * `OutboundMessage.text`, converted by the channel plugin): model-controllable fields go into code
240
+ * (see `asCode`), so they never produce links.
179
241
  */
180
242
  export function renderCardAsText(card, locale) {
181
243
  const t = TEXT[locale] ?? TEXT.en;
@@ -192,6 +254,12 @@ export function renderCardAsText(card, locale) {
192
254
  ];
193
255
  if (card.state === "denied" && card.denyReason)
194
256
  lines.push(line(t.reason, asCode(card.denyReason)));
257
+ // the scopes are listed only when the kernel named them (a network ask): the default
258
+ // approval text stays as it was
259
+ if (card.state === "pending" && card.scopeLabels) {
260
+ const labels = card.scopes.map((s) => card.scopeLabels?.[s] ?? t.scopes[s]);
261
+ lines.push(line(t.options, labels.join(" / ")));
262
+ }
195
263
  if (card.state === "pending")
196
264
  lines.push(line(t.expires, card.expiresAt), line(t.approveOnWeb, card.webUrl));
197
265
  else
@@ -202,11 +270,13 @@ export function renderCardAsText(card, locale) {
202
270
  const title = typeof card.form.title === "string" ? card.form.title : card.form.title[locale];
203
271
  const lines = [
204
272
  withCode(t.question, asCode(title)),
205
- line(t.status, t.questionStates[card.state]),
273
+ line(t.status, questionStateLabel(card.state, locale)),
206
274
  ];
207
275
  if (card.answerSummary)
208
276
  lines.push(line(t.answer, asCode(card.answerSummary)));
209
277
  lines.push(line(card.state === "pending" ? t.answerOnWeb : t.details, card.webUrl));
278
+ if (card.state === "pending" && card.textReply !== undefined)
279
+ lines.push(questionTextReplyHint(card.textReply, locale));
210
280
  return lines.join("\n");
211
281
  }
212
282
  case "connect":
package/dist/channel.d.ts CHANGED
@@ -1,9 +1,12 @@
1
1
  import type { ZodTypeAny } from "zod";
2
2
  import type { CardAction, Locale, OutboundMessage } from "./cards.js";
3
3
  /**
4
- * 消息的投递目标。群聊里的 `threadId` 是话题**根消息的 `messageId`**(内核用它把同一话题归到一个会话,
5
- * 回复也投到这个话题):Slack 为插件所定义的根消息 `messageId`(如 `<频道>:<ts>`,ts 即回复的
6
- * `thread_ts`);飞书为根消息的 `message_id`(`root_id`,`om_…`),**不是** `thread_id`(`omt_…`)。私聊不带。
4
+ * The delivery target of a message. In a group chat `threadId` is the **`messageId` of the thread's
5
+ * root message** (the kernel uses it to map one thread to one conversation,
6
+ * and replies are delivered to this thread): for Slack it is the root message `messageId` as the
7
+ * plugin defines it (e.g. `<channel>:<ts>`, where ts is the reply's
8
+ * `thread_ts`); for Lark it is the root message's `message_id` (`root_id`, `om_…`), **not**
9
+ * `thread_id` (`omt_…`). Absent in direct messages.
7
10
  */
8
11
  export interface ChannelTarget {
9
12
  chatId: string;
@@ -11,10 +14,14 @@ export interface ChannelTarget {
11
14
  chatType: "dm" | "group";
12
15
  }
13
16
  /**
14
- * 入站事件的发言人 / 点击者。`tenantId` 为发言人所属企业:Slack 为 team id(Enterprise Grid 下是 team,
15
- * 不是 enterprise),飞书为 `tenant_key`;与连接的租户(`verify` 返回的 `tenantId`,同一口径)不同的人
16
- * (外部联系人、共享频道里的其他企业)内核只允许绑定,不按匿名访客处理。`displayName`、`avatarUrl` 为平台上的
17
- * 显示名与头像(拿得到就带):内核把显示名用在绑定确认页(没有时回落到 externalId)。
17
+ * The speaker / clicker of an inbound event. `tenantId` is the tenant (company) the speaker belongs
18
+ * to: for Slack the team id (under Enterprise Grid it is the team,
19
+ * not the Grid organization), for Lark `tenant_key`; a person whose tenant differs from the
20
+ * connection's tenant (the `tenantId` returned by `verify`, same convention)
21
+ * (an external contact, another company in a shared channel) can only be bound by the kernel, never
22
+ * treated as an anonymous guest. `displayName` and `avatarUrl` are the display name and avatar
23
+ * on the platform (include them when available): the kernel uses the display name on the binding
24
+ * confirmation page (falling back to externalId when absent).
18
25
  */
19
26
  export interface InboundSender {
20
27
  externalId: string;
@@ -38,14 +45,19 @@ export interface InboundSender {
38
45
  locale?: string;
39
46
  }
40
47
  /**
41
- * 渠道交给内核的入站事件。插件的约定:
42
- * - `message.messageId` 在本连接内唯一(内核按它去重);
43
- * - M4 只处理文本:附件、图片、文件等忽略(消息只有附件时不发事件);
44
- * - 用户编辑、撤回 / 删除消息不发事件(忽略);
45
- * - `text` 里去掉 @ 机器人的部分(`mentionsBot` 另行说明是否 @ 了机器人);
46
- * - `card_action`:`messageId` 为卡片所在消息的 id(同一张卡片的多次点击相同);`eventId` 为平台给这次点击的
47
- * 唯一 id(拿得到就带,本连接内唯一:内核按它去重平台重投);群聊里 `target.threadId` 拿得到就带,
48
- * 拿不到时内核取发出该卡片时记下的话题。
48
+ * An inbound event a channel hands to the kernel. The plugin's conventions:
49
+ * - `message.messageId` is unique within this connection (the kernel deduplicates by it);
50
+ * - M4 handles text only: attachments, images, files and the like are ignored (a message with
51
+ * only attachments emits no event);
52
+ * - user edits and message recalls / deletions emit no event (ignored);
53
+ * - the part of `text` that @-mentions the bot is removed (`mentionsBot` states separately
54
+ * whether the bot was @-mentioned);
55
+ * - `card_action`: `messageId` is the id of the message holding the card (the same for repeated
56
+ * clicks on one card); `eventId` is the platform's
57
+ * unique id for this click (include it when available; unique within this connection: the kernel
58
+ * deduplicates platform redeliveries by it); in a group chat include `target.threadId` when
59
+ * available,
60
+ * otherwise the kernel uses the thread recorded when it sent the card.
49
61
  */
50
62
  export type InboundEvent = {
51
63
  type: "message";
@@ -58,26 +70,34 @@ export type InboundEvent = {
58
70
  type: "card_action";
59
71
  target: ChannelTarget;
60
72
  messageId: string;
61
- /** 平台给这次点击的唯一 id(如飞书回调的 event_id、Slack 的 trigger / action 时间戳组合)。 */
73
+ /**
74
+ * The platform's unique id for this click (e.g. the event_id of a Lark callback, or a
75
+ * combination of Slack's trigger / action timestamps).
76
+ */
62
77
  eventId?: string;
63
78
  sender: InboundSender;
64
79
  action: CardAction;
65
80
  }
66
- /** 平台推送人员变动的提示,内核据此触发通讯录同步。 */
81
+ /** The platform pushes a personnel change hint; the kernel triggers a directory sync from it. */
67
82
  | {
68
83
  type: "directory_changed";
69
84
  tenantId: string;
70
85
  };
71
86
  export interface ChannelConnectArgs {
72
87
  connectionId: string;
73
- /** 已按 connectionSchema 校验,含密钥。 */
88
+ /** Already validated against connectionSchema, secrets included. */
74
89
  config: unknown;
75
90
  /**
76
- * 把入站事件交给内核。内核只做去重并把事件持久地排进队列(很快,不在这里处理消息),resolve 即表示内核已经
77
- * 可靠地收下了这条事件:插件**在它 resolve 之后**才向平台确认(ack);reject 时**不要**确认,让平台重投;
78
- * 插件自己不必重试 `onEvent`。去重范围:`message` 按 `messageId`、带 `eventId` 的 `card_action` 按 `eventId`
79
- * (各保留 24 小时)——重投只处理一次;不带 `eventId` 的 `card_action` 不去重(每次都处理,重复的审批 /
80
- * 回答由内核回「已处理」);`directory_changed` 不去重(同步任务本身按分钟合并)。
91
+ * Hands an inbound event to the kernel. The kernel only deduplicates and durably enqueues the
92
+ * event (fast; it does not process the message here); resolving means the kernel has
93
+ * reliably received the event: the plugin acknowledges (acks) to the platform **only after it
94
+ * resolves**; on reject **do not** acknowledge, so the platform redelivers;
95
+ * the plugin need not retry `onEvent` itself. Deduplication scope: `message` by `messageId`, a
96
+ * `card_action` with `eventId` by `eventId`
97
+ * (each kept for 24 hours), so a redelivery is processed once; a `card_action` without `eventId`
98
+ * is not deduplicated (processed every time; a repeated approval /
99
+ * answer gets an "already handled" reply from the kernel); `directory_changed` is not
100
+ * deduplicated (the sync task itself coalesces per minute).
81
101
  */
82
102
  onEvent(e: InboundEvent): Promise<void>;
83
103
  signal: AbortSignal;
@@ -86,8 +106,9 @@ export interface ChannelSendArgs {
86
106
  config: unknown;
87
107
  target: ChannelTarget;
88
108
  /**
89
- * 消息内容。`text` 超过平台单条长度上限时由插件自行拆成多条按序发送,返回**最后一条**的消息 id
90
- * (内核之后编辑的是这条)。
109
+ * The message content. When `text` exceeds the platform's per-message length limit the plugin
110
+ * splits it into several messages sent in order and returns the id of the **last one**
111
+ * (the kernel edits that one afterwards).
91
112
  */
92
113
  message: OutboundMessage;
93
114
  signal: AbortSignal;
@@ -98,9 +119,13 @@ export interface ChannelSendArgs {
98
119
  */
99
120
  locale: Locale;
100
121
  /**
101
- * 幂等键(可选):不超过 40 个 `[A-Za-z0-9_-]` 字符,同一条逻辑消息的每次重试(崩溃后其他副本续投、
102
- * 可重试失败后重发)都相同——内核由「会话 + 事件 seq」或「卡片 + 状态」稳定哈希得到。平台支持幂等发送
103
- * (如飞书的 `uuid`)时插件应原样透传或按平台要求映射,以免重复消息;不支持的平台忽略即可。
122
+ * Idempotency key (optional): at most 40 characters from `[A-Za-z0-9_-]`, identical for every
123
+ * retry of the same logical message (another replica continuing after a crash,
124
+ * a resend after a retryable failure); the kernel derives it as a stable hash of "conversation +
125
+ * event seq" or "card + state".
126
+ * When the platform supports idempotent sends (e.g. Lark's `uuid`) the plugin should pass it
127
+ * through unchanged or map it as the platform requires, to avoid duplicate messages; platforms
128
+ * without support can ignore it.
104
129
  */
105
130
  idempotencyKey?: string;
106
131
  }
@@ -177,19 +202,46 @@ export interface ChannelWebhook {
177
202
  signal: AbortSignal;
178
203
  }): Promise<ChannelWebhookResult>;
179
204
  }
180
- /** 渠道实现(bot 用渠道连接配置)。 */
205
+ /** One conversation artifact handed to {@link Channel.sendFile}. */
206
+ export interface ChannelFile {
207
+ /** File name shown to the user. Model-controlled: never interpret it as markup, a path or a mention. */
208
+ name: string;
209
+ contentType: string;
210
+ /** Chosen by the kernel (an image type within the image cap, else a file). */
211
+ kind: "image" | "file";
212
+ data: Uint8Array;
213
+ }
214
+ /** Arguments of {@link Channel.sendFile}: one file for one message; the whole file is in memory. */
215
+ export interface ChannelSendFileArgs {
216
+ config: unknown;
217
+ target: ChannelTarget;
218
+ file: ChannelFile;
219
+ signal: AbortSignal;
220
+ locale: Locale;
221
+ /** Same semantics as {@link ChannelSendArgs.idempotencyKey}. */
222
+ idempotencyKey?: string;
223
+ }
224
+ /** A channel implementation (the bot uses the channel connection config). */
181
225
  export interface Channel {
182
- /** 渠道连接配置的 schema;密钥字段用 secret()。 */
226
+ /** Schema of the channel connection config; secret fields use secret(). */
183
227
  connectionSchema: ZodTypeAny;
184
228
  /**
185
- * `minEditIntervalMs`:平台允许的同一条消息两次编辑的最小间隔;内核流式草稿的更新间隔取
186
- * `max(1000, minEditIntervalMs)`。
229
+ * `minEditIntervalMs`: the minimum interval the platform allows between two edits of the same
230
+ * message; the kernel's streaming-draft update interval is
231
+ * `max(1000, minEditIntervalMs)`.
232
+ *
233
+ * `files`: present iff `sendFile` is implemented; the kernel never hands a file larger than
234
+ * `maxBytes`, and sends `kind: "image"` only within `imageMaxBytes ?? maxBytes`.
187
235
  */
188
236
  features: {
189
237
  cards: boolean;
190
238
  edit: boolean;
191
239
  threads: boolean;
192
240
  minEditIntervalMs?: number;
241
+ files?: {
242
+ maxBytes: number;
243
+ imageMaxBytes?: number;
244
+ };
193
245
  };
194
246
  verify(args: {
195
247
  config: unknown;
@@ -199,20 +251,39 @@ export interface Channel {
199
251
  botName: string;
200
252
  tenantId: string;
201
253
  }>;
202
- /** 长连接循环:signal 中止时返回;断线自行重连。 */
254
+ /**
255
+ * Long-connection loop: returns when `signal` aborts; reconnects by itself after a disconnect.
256
+ */
203
257
  connect(args: ChannelConnectArgs): Promise<void>;
204
- /** 失败时抛 {@link ChannelSendError} 说明能否重试;其他异常内核按可重试处理(次数有限)。 */
258
+ /**
259
+ * On failure throw {@link ChannelSendError} to say whether it can be retried; the kernel treats
260
+ * other exceptions as retryable (a limited number of times).
261
+ */
205
262
  send(args: ChannelSendArgs): Promise<{
206
263
  messageId: string;
207
264
  }>;
208
265
  /**
209
- * features.edit 为 false 的渠道不会被调用。失败语义同 send。新文本超过平台单条上限、无法改成一条时
210
- * 抛不可重试的 {@link ChannelSendError}(`reason: "too_large"`):内核改为把完整文本作为新消息 `send`
211
- * (由插件拆分)。
266
+ * Never called for channels whose features.edit is false. Failure semantics are the same as send.
267
+ * When the new text exceeds the platform's per-message limit and cannot be turned into one
268
+ * message,
269
+ * throw a non-retryable {@link ChannelSendError} (`reason: "too_large"`): the kernel then `send`s
270
+ * the full text as a new message
271
+ * (split by the plugin).
212
272
  */
213
273
  update(args: ChannelSendArgs & {
214
274
  messageId: string;
215
275
  }): Promise<void>;
276
+ /**
277
+ * Optional file delivery: one message per file; the kernel picks `kind`; an extension may send an
278
+ * `image` as a file when the platform refuses it as an image, never the reverse; `messageId`
279
+ * when the platform returns it; failures as {@link ChannelSendError} (`send`); never put an
280
+ * upload URL in an error. Throw a missing upload permission or scope as a non-retryable
281
+ * {@link ChannelSendError} with `reason: "rejected"`, never `auth`: `auth` stops the whole
282
+ * delivery of the conversation, text included, while `rejected` only turns this file into a link.
283
+ */
284
+ sendFile?(args: ChannelSendFileArgs): Promise<{
285
+ messageId?: string;
286
+ }>;
216
287
  /**
217
288
  * Optional webhook inbound (see {@link ChannelWebhook}). Only connections of plugins that
218
289
  * implement it can be switched from the default long connection to webhook mode; a connection in
@@ -221,18 +292,26 @@ export interface Channel {
221
292
  webhook?: ChannelWebhook;
222
293
  }
223
294
  /**
224
- * 不可重试失败的原因(`ChannelSendError.reason`),内核据此处理:
225
- * - `auth`:凭据失效 / 权限被收回 → 记连接 `last_error`,停止该会话本轮的投递;
226
- * - `target_gone`:机器人被移出群、会话不存在 → 停止该会话本轮的投递,不计入毒事件;
227
- * - `rejected`(内容被平台拒绝)、`too_large`(拆分后仍超限,如卡片过大)→ 按同一事件失败计数,满 3 次跳过它。
228
- * 未给出原因的按 `rejected` 处理。
295
+ * Reasons for a non-retryable failure (`ChannelSendError.reason`), which the kernel handles
296
+ * accordingly:
297
+ * - `auth`: credentials invalid / permission revoked -> record the connection's `last_error` and
298
+ * stop delivering for this conversation in this round;
299
+ * - `target_gone`: the bot was removed from the group or the conversation does not exist -> stop
300
+ * delivering for this conversation in this round, not counted as a poison event;
301
+ * - `rejected` (content rejected by the platform), `too_large` (still over the limit after
302
+ * splitting, e.g. a card that is too large) -> counted as failures of the same event; after 3 the
303
+ * event is skipped.
304
+ * A failure without a reason is treated as `rejected`.
229
305
  */
230
306
  export type ChannelSendFailure = "auth" | "target_gone" | "rejected" | "too_large";
231
307
  /**
232
- * 渠道发送 / 更新消息失败的分类:`retryable` 为 true(限流、平台 5xx、网络)时内核退避后重试,
233
- * `retryAfterMs` 为平台给出的建议等待时长;为 false 时按 `reason`(见 {@link ChannelSendFailure})处理。
234
- * 编辑流式草稿不可重试地失败(`auth` / `target_gone` 除外)时,内核改为把完整文本作为新消息发出。
235
- * 消息里不要带凭据。
308
+ * Classification of a channel send / update failure: when `retryable` is true (rate limit, platform
309
+ * 5xx, network) the kernel retries after backoff,
310
+ * `retryAfterMs` is the wait the platform suggests; when false it is handled by `reason` (see
311
+ * {@link ChannelSendFailure}).
312
+ * When editing a streaming draft fails non-retryably (except `auth` / `target_gone`), the kernel
313
+ * sends the full text as a new message instead.
314
+ * Do not put credentials in the message.
236
315
  */
237
316
  export declare class ChannelSendError extends Error {
238
317
  readonly retryable: boolean;
@@ -245,5 +324,7 @@ export declare class ChannelSendError extends Error {
245
324
  cause?: unknown;
246
325
  });
247
326
  }
248
- /** 鸭子类型判断(不用 instanceof),兼容插件自带另一份 plugin-sdk 副本的情况。 */
327
+ /**
328
+ * Duck-typed check (no instanceof), compatible with a plugin bundling another copy of plugin-sdk.
329
+ */
249
330
  export declare function isChannelSendError(e: unknown): e is ChannelSendError;
package/dist/channel.js CHANGED
@@ -1,8 +1,11 @@
1
1
  /**
2
- * 渠道发送 / 更新消息失败的分类:`retryable` 为 true(限流、平台 5xx、网络)时内核退避后重试,
3
- * `retryAfterMs` 为平台给出的建议等待时长;为 false 时按 `reason`(见 {@link ChannelSendFailure})处理。
4
- * 编辑流式草稿不可重试地失败(`auth` / `target_gone` 除外)时,内核改为把完整文本作为新消息发出。
5
- * 消息里不要带凭据。
2
+ * Classification of a channel send / update failure: when `retryable` is true (rate limit, platform
3
+ * 5xx, network) the kernel retries after backoff,
4
+ * `retryAfterMs` is the wait the platform suggests; when false it is handled by `reason` (see
5
+ * {@link ChannelSendFailure}).
6
+ * When editing a streaming draft fails non-retryably (except `auth` / `target_gone`), the kernel
7
+ * sends the full text as a new message instead.
8
+ * Do not put credentials in the message.
6
9
  */
7
10
  export class ChannelSendError extends Error {
8
11
  retryable;
@@ -18,7 +21,9 @@ export class ChannelSendError extends Error {
18
21
  this.reason = opts.reason;
19
22
  }
20
23
  }
21
- /** 鸭子类型判断(不用 instanceof),兼容插件自带另一份 plugin-sdk 副本的情况。 */
24
+ /**
25
+ * Duck-typed check (no instanceof), compatible with a plugin bundling another copy of plugin-sdk.
26
+ */
22
27
  export function isChannelSendError(e) {
23
28
  return (e instanceof Error &&
24
29
  e.name === "ChannelSendError" &&
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The client stylesheet rule (client extensions spec §4.1, §7.2): one function both sides run, so
3
+ * a stylesheet that packs cleanly imports cleanly. `capybara-plugin pack` wraps every file in
4
+ * `@layer extensions { … }` ({@link wrapClientCss}) and checks the wrapped text; the kernel checks
5
+ * the stored bytes again at import, because a tgz can be written by hand. A file must be one
6
+ * `@layer extensions` block, may not `@import`, and a URL may name only an asset of the plugin
7
+ * (`../assets/<path>`, a file of `client.assets`), a `data:` URL or a `#fragment`. Any other URL,
8
+ * relative ones included, is refused: the stylesheet is served from
9
+ * `/api/v1/client/<plugin>/<build>/styles/`, so `../../../../…` would reach the kernel's own
10
+ * routes with the viewer's cookies.
11
+ *
12
+ * Two passes, both must pass:
13
+ * - a plain-text pass over the escape-decoded file (`cssRemoteProblem`);
14
+ * - a tokenizer that follows the CSS Syntax tokenization (comments, strings, escapes, url tokens)
15
+ * closely enough that every brace it skips is one a browser skips too: the file must start with
16
+ * `@layer extensions {` and the block that opens must close at the file's last character, so no
17
+ * rule lands outside the layer. Every `url(…)` (token or string) is checked after decoding
18
+ * escapes, and an `@import` at-keyword is refused however it is spelled.
19
+ *
20
+ * Two rules close the spellings a plain string check would miss:
21
+ * - URLs are trimmed with CSS whitespace only (space, tab, LF, CR, FF), and a file holding any other
22
+ * whitespace, a zero-width character (U+200B-U+200D, U+2060) or U+FEFF anywhere, escaped or not,
23
+ * is refused: JavaScript's `trim()` strips an NBSP that CSS and the URL parser keep, so
24
+ * `url("\a0 data:/../../v1")` would pass as `data:` and resolve to `/api/v1`;
25
+ * - functions that turn a plain string (or a `var()`) into a URL or reach outside the stylesheet are
26
+ * refused outright: `image-set(var(--u) 1x)` takes its URL from a custom property no string check
27
+ * can see. Plugins write `url(../assets/x)` directly.
28
+ */
29
+ /** A stylesheet as the packer stores it: wrapped in `@layer extensions { … }` (spec §4.1). */
30
+ export declare function wrapClientCss(css: string): string;
31
+ /**
32
+ * The problem of a client stylesheet as stored (see the file header), or undefined when it is one
33
+ * `@layer extensions` block with no `@import` and every URL a `#fragment`, a `data:` URL or one of
34
+ * the plugin's `assets` (paths relative to `assets/`).
35
+ */
36
+ export declare function clientCssProblem(css: string, assets: ReadonlySet<string>): string | undefined;