@capybara-hq/kernel 0.1.0-rc.115 → 0.1.0-rc.116

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 (51) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/agents/agents.controller.d.ts +13 -1
  3. package/dist/agents/agents.controller.js +24 -2
  4. package/dist/catalog/catalog.service.d.ts +11 -1
  5. package/dist/catalog/catalog.service.js +36 -2
  6. package/dist/catalog/marketplaces.service.d.ts +1 -1
  7. package/dist/catalog/platform-components.js +13 -0
  8. package/dist/catalog/plugin-connectors.d.ts +35 -0
  9. package/dist/catalog/plugin-connectors.js +81 -0
  10. package/dist/channels/supervisor.d.ts +5 -1
  11. package/dist/channels/supervisor.js +17 -1
  12. package/dist/conversations/conversations.controller.d.ts +46 -14
  13. package/dist/conversations/conversations.controller.js +82 -47
  14. package/dist/conversations/conversations.service.d.ts +93 -59
  15. package/dist/conversations/conversations.service.js +255 -72
  16. package/dist/conversations/events.d.ts +31 -0
  17. package/dist/conversations/events.js +41 -2
  18. package/dist/conversations/inline-tokens.d.ts +87 -0
  19. package/dist/conversations/inline-tokens.js +154 -0
  20. package/dist/conversations/permission-profiles.controller.d.ts +14 -7
  21. package/dist/conversations/permission-profiles.controller.js +1 -5
  22. package/dist/conversations/prompt-suggestions.js +2 -4
  23. package/dist/conversations/queue.d.ts +0 -2
  24. package/dist/conversations/queue.service.js +9 -13
  25. package/dist/db/kernel-schema.d.ts +2 -0
  26. package/dist/errors.d.ts +12 -0
  27. package/dist/errors.js +12 -0
  28. package/dist/evals/snapshot.js +4 -2
  29. package/dist/files/library-files.service.d.ts +13 -0
  30. package/dist/files/library-files.service.js +33 -6
  31. package/dist/net/safe-fetch.js +1 -1
  32. package/dist/platform/exclusions.js +6 -1
  33. package/dist/runtime/context/build.d.ts +7 -2
  34. package/dist/runtime/context/build.js +17 -6
  35. package/dist/runtime/context/compaction.d.ts +3 -3
  36. package/dist/runtime/context/compaction.js +12 -13
  37. package/dist/sandbox/review/classifier.js +5 -1
  38. package/dist/tools/connector-content.controller.d.ts +6 -2
  39. package/dist/tools/connector-content.controller.js +13 -3
  40. package/dist/tools/connector-content.d.ts +55 -15
  41. package/dist/tools/connector-content.js +112 -54
  42. package/dist/tools/connectors.service.d.ts +3 -2
  43. package/dist/tools/connectors.service.js +6 -20
  44. package/dist/tools/mentionable-connectors.d.ts +88 -0
  45. package/dist/tools/mentionable-connectors.js +218 -0
  46. package/dist/tools/pipeline.js +43 -6
  47. package/dist/tools/specs.d.ts +13 -4
  48. package/dist/tools/specs.js +22 -8
  49. package/dist/tools/tools.module.js +7 -0
  50. package/package.json +3 -3
  51. package/src/migrations/0201_tool_specs_text.sql +8 -0
@@ -284,6 +284,13 @@ export function compactionPlan(events, settings, budget, opts = {}) {
284
284
  const parts = prev ? [`[Earlier summary]\n${prev.payload.text}`, ...lines] : lines;
285
285
  return { coversUpToSeq, transcript: parts.join("\n\n") };
286
286
  }
287
+ /** Whether a `run_started.trigger` belongs to a run opened by a user/automation message. */
288
+ function isMessageRunTrigger(trigger) {
289
+ return (trigger === undefined ||
290
+ trigger === "message" ||
291
+ trigger === "schedule" ||
292
+ trigger === "automation_event");
293
+ }
287
294
  /**
288
295
  * The user messages that started run `runId`, among those a summary covering up to
289
296
  * `coversUpToSeq` covers (context compaction spec §4.2, revision 2026-11-15): recorded in the
@@ -301,13 +308,8 @@ export function openingSeqs(events, runId, coversUpToSeq, absorbedUpToSeq = Numb
301
308
  const start = sorted.findLast((e) => e.type === "run_started" && e.runId === runId);
302
309
  if (start?.type !== "run_started")
303
310
  return [];
304
- const trigger = start.payload.trigger;
305
- if (trigger !== undefined &&
306
- trigger !== "message" &&
307
- trigger !== "schedule" &&
308
- trigger !== "automation_event") {
311
+ if (!isMessageRunTrigger(start.payload.trigger))
309
312
  return [];
310
- }
311
313
  const first = sorted.find((e) => e.type === "model_call" && e.runId === runId && e.seq > start.seq);
312
314
  const upTo = first?.type === "model_call"
313
315
  ? Math.min(first.payload.request.absorbedUpToSeq, first.seq)
@@ -329,16 +331,13 @@ export function openingSeqs(events, runId, coversUpToSeq, absorbedUpToSeq = Numb
329
331
  /**
330
332
  * The opening messages a manual compaction's summary re-renders (context compaction spec §4.7,
331
333
  * maintainer decision 2026-11-28): a compact run is started by no message, so its own run has none;
332
- * the turn it cuts into is the one the latest run a message started (trigger `message` or
333
- * `schedule`) opened, and {@link openingSeqs} of that run decides which of its opening messages the
334
- * summary covers. None when no such run is in the log.
334
+ * the turn it cuts into is the one the latest run a message started (trigger `message`,
335
+ * `schedule` or `automation_event`) opened, and {@link openingSeqs} of that run decides which of
336
+ * its opening messages the summary covers. None when no such run is in the log.
335
337
  */
336
338
  export function manualOpeningSeqs(events, coversUpToSeq, absorbedUpToSeq) {
337
339
  const start = events
338
- .filter((e) => e.type === "run_started" &&
339
- (e.payload.trigger === undefined ||
340
- e.payload.trigger === "message" ||
341
- e.payload.trigger === "schedule"))
340
+ .filter((e) => e.type === "run_started" && isMessageRunTrigger(e.payload.trigger))
342
341
  .reduce((a, e) => (a === null || e.seq > a.seq ? e : a), null);
343
342
  if (start?.runId == null)
344
343
  return [];
@@ -296,7 +296,11 @@ export const PERSON_MESSAGES_READ = 20;
296
296
  * blocks `1 .. attachments.length`) are content read from a connector, not the person's
297
297
  * instructions, so they are skipped, like images, documents and uploaded files. So are the
298
298
  * referenced conversations' blocks (`payload.conversationRefs`, after the project file lines):
299
- * quoted material, not the person's intent.
299
+ * quoted material, not the person's intent. A message with inline tokens (composer inline tokens
300
+ * spec §3.3) keeps that layout: its placeholders stand in `content[0]`, and its connector mention
301
+ * blocks and `[file: …]` lines come after the referenced conversations, so they are skipped too.
302
+ * An upload-only message has no typed text: its `content[0]` is the first file's `[file: <name>]`
303
+ * line, which is read as its words (a file name, harmless to the verdict).
300
304
  */
301
305
  function textOfUserMessage(payload) {
302
306
  const p = payload;
@@ -6,6 +6,7 @@ declare const PromptBody: z.ZodObject<{
6
6
  arguments: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodString>>;
7
7
  }, z.core.$strict>;
8
8
  declare const ResourcesQuery: z.ZodObject<{
9
+ connectorId: z.ZodUUID;
9
10
  query: z.ZodOptional<z.ZodString>;
10
11
  }, z.core.$strip>;
11
12
  /**
@@ -21,10 +22,13 @@ export declare class ConnectorContentController {
21
22
  prompts: ConnectorPromptView[];
22
23
  unavailable: ConnectorUnavailable[];
23
24
  }>;
24
- /** 发起人可用的资源,`query` 按名称 / URI / 描述子串过滤。 */
25
+ /**
26
+ * One connector's resources the sender can use (the `@` menu's second level): one session on
27
+ * that connector, UI templates and empty resources hidden; `query` filters by name, URI or
28
+ * description substring.
29
+ */
25
30
  resources(principal: Principal, org: OrgContext, q: z.infer<typeof ResourcesQuery>): Promise<{
26
31
  resources: ConnectorResourceView[];
27
- unavailable: ConnectorUnavailable[];
28
32
  }>;
29
33
  /** 按参数渲染一个提示模板为文本(放进输入框,由用户发送)。 */
30
34
  renderPrompt(principal: Principal, org: OrgContext, connectorId: string, name: string, body: z.infer<typeof PromptBody>): Promise<{
@@ -22,7 +22,10 @@ const PromptBody = z
22
22
  .default({}),
23
23
  })
24
24
  .strict();
25
- const ResourcesQuery = z.object({ query: z.string().max(200).optional() });
25
+ const ResourcesQuery = z.object({
26
+ connectorId: z.uuid(),
27
+ query: z.string().max(200).optional(),
28
+ });
26
29
  class ConnectorPromptBody extends createZodDto(PromptBody, "ConnectorPromptBody") {
27
30
  }
28
31
  class ConnectorResourcesQuery extends createZodDto(ResourcesQuery, "ConnectorResourcesQuery") {
@@ -42,10 +45,17 @@ let ConnectorContentController = class ConnectorContentController {
42
45
  const p = requireUser(principal);
43
46
  return this.content.listPrompts(org.orgId, p.account.id);
44
47
  }
45
- /** 发起人可用的资源,`query` 按名称 / URI / 描述子串过滤。 */
48
+ /**
49
+ * One connector's resources the sender can use (the `@` menu's second level): one session on
50
+ * that connector, UI templates and empty resources hidden; `query` filters by name, URI or
51
+ * description substring.
52
+ */
46
53
  async resources(principal, org, q) {
47
54
  const p = requireUser(principal);
48
- return this.content.listResources(org.orgId, p.account.id, q.query);
55
+ return this.content.listResources(org.orgId, p.account.id, {
56
+ connectorId: q.connectorId,
57
+ ...(q.query !== undefined && { query: q.query }),
58
+ });
49
59
  }
50
60
  /** 按参数渲染一个提示模板为文本(放进输入框,由用户发送)。 */
51
61
  async renderPrompt(principal, org, connectorId, name, body) {
@@ -25,6 +25,7 @@ export interface ConnectorResourceView {
25
25
  name: string;
26
26
  description?: string;
27
27
  mimeType?: string;
28
+ size?: number;
28
29
  }
29
30
  /** 列表时某个连接器不可用:发起人没有连接个人凭据,或连接 / 列出失败(含熔断打开)。 */
30
31
  export interface ConnectorUnavailable {
@@ -42,6 +43,34 @@ export interface AttachmentMeta {
42
43
  uri: string;
43
44
  name: string;
44
45
  }
46
+ /** An MCP app UI template (not content a person can attach): `ui:` URI or the mcp-app HTML profile. */
47
+ export declare function isUiTemplate(r: {
48
+ uri: string;
49
+ mimeType?: string;
50
+ }): boolean;
51
+ /** Whether a resource is offered to a person: not a UI template, not empty. */
52
+ export declare function listableResource(r: {
53
+ uri: string;
54
+ name?: string;
55
+ mimeType?: string;
56
+ size?: number;
57
+ }): boolean;
58
+ /** One resource a message references, as read for it (the body redacted and capped). */
59
+ export interface ReadResource {
60
+ connectorId: string;
61
+ connectorName: string;
62
+ uri: string;
63
+ /** The listed name, or the URI. */
64
+ name: string;
65
+ body: string;
66
+ }
67
+ /**
68
+ * The model-visible block of a read resource: its placeholder first when it was a token
69
+ * (`[resource: <label> from <connector label>] `), then the English head and the body.
70
+ */
71
+ export declare const resourceBlockText: (r: ReadResource, placeholder?: string) => string;
72
+ /** The `payload.attachments` entry of a read resource (field names kept, C27). */
73
+ export declare const attachmentMeta: (r: ReadResource) => AttachmentMeta;
45
74
  export declare class ConnectorContent {
46
75
  private readonly db;
47
76
  private readonly registry;
@@ -77,25 +106,36 @@ export declare class ConnectorContent {
77
106
  getPrompt(orgId: string, connectorId: string, name: string, args: Record<string, string>, accountId: string): Promise<{
78
107
  text: string;
79
108
  }>;
80
- /** 发起人可用的资源;`query` 按名称 / URI / 描述的子串过滤(不区分大小写),最多 {@link MAX_RESOURCES} 条。 */
81
- listResources(orgId: string, accountId: string, query?: string): Promise<{
109
+ /**
110
+ * One connector's resources the sender can use (the `@` menu's second level, composer inline
111
+ * tokens spec §5): one session on that connector with the sender's credential, UI templates and
112
+ * empty resources hidden, at most {@link MAX_CONNECTOR_RESOURCES}; `query` filters by name, URI
113
+ * or description substring (case insensitive). A connector that is not live and active →
114
+ * `connector.not_found`; one whose `read_resource` is off → `connector.resources_disabled`; a
115
+ * missing credential or a failed connection is thrown (`credential.missing`,
116
+ * `connector.connect_failed`).
117
+ */
118
+ listResources(orgId: string, accountId: string, opts: {
119
+ connectorId: string;
120
+ query?: string;
121
+ }): Promise<{
82
122
  resources: ConnectorResourceView[];
83
- unavailable: ConnectorUnavailable[];
84
123
  }>;
85
124
  /**
86
- * 解析消息附件:以发送者的凭据**并行**读取每个资源(打码、每个限 {@link MAX_ATTACHMENT_CHARS} 字符;总时限
87
- * min(`tools.timeoutMs`, 30s)),按请求顺序返回要追加在用户消息后的文本块与元数据。名称取资源清单里的 name
88
- * (读不到清单时用 URI)。连接器的 `read_resource` 工具被管理员停用 → 409 `connector.resources_disabled`。
89
- * 任一附件失败整条消息失败(不写入)。
125
+ * Reads the resources a message references with the sender's credentials, **in parallel**
126
+ * (redacted, each capped at {@link MAX_ATTACHMENT_CHARS} characters; total time limit
127
+ * min(`tools.timeoutMs`, 30s)), in request order. The name is the one in the resource listing
128
+ * (the URI when the listing does not have it). Refusals, any of which fails the whole message
129
+ * (nothing is written):
130
+ * - the connector is not live and active, or provides no resources → `connector.not_found`;
131
+ * - its `read_resource` tool is switched off by an admin (Ruling A23), or `readOffered` is given
132
+ * and does not hold the connector (the conversation's agent is not offered that tool) →
133
+ * 409 `connector.resources_disabled`;
134
+ * - an MCP Apps UI template, or a body that is empty after trimming → 422
135
+ * `connector.resource_unreadable` (`details: [{ connectorId, uri, reason }]`).
90
136
  */
91
- resolveAttachments(orgId: string, accountId: string, refs: {
137
+ readResources(orgId: string, accountId: string, refs: readonly {
92
138
  connectorId: string;
93
139
  uri: string;
94
- }[]): Promise<{
95
- blocks: {
96
- type: "text";
97
- text: string;
98
- }[];
99
- attachments: AttachmentMeta[];
100
- }>;
140
+ }[], readOffered?: ReadonlySet<string>): Promise<ReadResource[]>;
101
141
  }
@@ -29,9 +29,10 @@ import { READ_RESOURCE } from "./resources.js";
29
29
  */
30
30
  /** 列表请求里每个连接器的超时上限(毫秒;取它与 `tools.timeoutMs` 的较小值)。 */
31
31
  const LIST_TIMEOUT_MS = 10_000;
32
- /** 一次列出的资源最多条数。 */
33
- const MAX_RESOURCES = 500;
34
- /** 渲染后的提示文本上限(与消息正文上限一致)。 */
32
+ /** One connector's listing shows at most this many resources. */
33
+ const MAX_CONNECTOR_RESOURCES = 200;
34
+ const UI_TEMPLATE_MIME = "text/html;profile=mcp-app";
35
+ /** The cap on a rendered prompt's text (the same as a message's text). */
35
36
  const MAX_PROMPT_CHARS = 100_000;
36
37
  /** 每个附件的正文上限(字符)。 */
37
38
  export const MAX_ATTACHMENT_CHARS = 50_000;
@@ -41,6 +42,28 @@ export const MAX_ATTACHMENTS = 5;
41
42
  const ATTACHMENTS_TIMEOUT_MS = 30_000;
42
43
  /** 错误说明里带的上游错误消息最多字符数。 */
43
44
  const MAX_DETAIL = 500;
45
+ /** An MCP app UI template (not content a person can attach): `ui:` URI or the mcp-app HTML profile. */
46
+ export function isUiTemplate(r) {
47
+ if (r.mimeType !== undefined && r.mimeType.replace(/\s+/g, "").toLowerCase() === UI_TEMPLATE_MIME)
48
+ return true;
49
+ return /^ui:/i.test(r.uri);
50
+ }
51
+ /** Whether a resource is offered to a person: not a UI template, not empty. */
52
+ export function listableResource(r) {
53
+ return !isUiTemplate(r) && r.size !== 0;
54
+ }
55
+ /**
56
+ * The model-visible block of a read resource: its placeholder first when it was a token
57
+ * (`[resource: <label> from <connector label>] `), then the English head and the body.
58
+ */
59
+ export const resourceBlockText = (r, placeholder) => `${placeholder === undefined ? "" : `${placeholder} `}Attached resource ${JSON.stringify(r.name)} (${r.uri}) from the connector ${r.connectorName}:\n\n${r.body}`;
60
+ /** The `payload.attachments` entry of a read resource (field names kept, C27). */
61
+ export const attachmentMeta = (r) => ({
62
+ appId: r.connectorId,
63
+ appName: r.connectorName,
64
+ uri: r.uri,
65
+ name: r.name,
66
+ });
44
67
  const errName = (e) => e instanceof Error && typeof e.name === "string" && e.name !== "" ? e.name : "Error";
45
68
  let ConnectorContent = class ConnectorContent {
46
69
  db;
@@ -155,9 +178,8 @@ let ConnectorContent = class ConnectorContent {
155
178
  }
156
179
  }
157
180
  /** 对每个 active 连接器并行执行 `work`;缺凭据 / 失败的连接器进 `unavailable`,不支持的(undefined)跳过。 */
158
- async acrossConnectors(orgId, accountId, work, only) {
159
- const all = await this.activeConnectors(orgId);
160
- const apps = only ? await only(all) : all;
181
+ async acrossConnectors(orgId, accountId, work) {
182
+ const apps = await this.activeConnectors(orgId);
161
183
  const timeoutMs = Math.min(this.config.get().tools.timeoutMs, LIST_TIMEOUT_MS);
162
184
  const results = await Promise.all(apps.map(async (app) => {
163
185
  try {
@@ -217,50 +239,79 @@ let ConnectorContent = class ConnectorContent {
217
239
  text = text.slice(0, MAX_PROMPT_CHARS);
218
240
  return { text };
219
241
  }
220
- /** 发起人可用的资源;`query` 按名称 / URI / 描述的子串过滤(不区分大小写),最多 {@link MAX_RESOURCES} 条。 */
221
- async listResources(orgId, accountId, query) {
222
- const q = query?.trim().toLowerCase() ?? "";
223
- const { items, unavailable } = await this.acrossConnectors(orgId, accountId, async (s, app) => {
224
- if (!s.listResources)
225
- return undefined;
226
- return (await s.listResources())
227
- .filter((r) => q === "" ||
228
- [r.name, r.uri, r.description ?? ""].some((v) => v.toLowerCase().includes(q)))
229
- .map((r) => ({
230
- connectorId: app.id,
231
- connectorSlug: app.slug,
232
- connectorName: app.name,
233
- uri: r.uri,
234
- name: r.name,
235
- ...(r.description !== undefined && { description: r.description }),
236
- ...(r.mimeType !== undefined && { mimeType: r.mimeType }),
237
- }));
238
- },
239
- // 管理员停用了读取资源的连接器不列出(也不打开会话)
240
- async (apps) => {
241
- const enabled = await this.resourcesEnabled(apps.map((a) => a.id));
242
- return apps.filter((a) => enabled.has(a.id));
242
+ /**
243
+ * One connector's resources the sender can use (the `@` menu's second level, composer inline
244
+ * tokens spec §5): one session on that connector with the sender's credential, UI templates and
245
+ * empty resources hidden, at most {@link MAX_CONNECTOR_RESOURCES}; `query` filters by name, URI
246
+ * or description substring (case insensitive). A connector that is not live and active →
247
+ * `connector.not_found`; one whose `read_resource` is off → `connector.resources_disabled`; a
248
+ * missing credential or a failed connection is thrown (`credential.missing`,
249
+ * `connector.connect_failed`).
250
+ */
251
+ async listResources(orgId, accountId, opts) {
252
+ const q = opts.query?.trim().toLowerCase() ?? "";
253
+ const view = (app, r) => ({
254
+ connectorId: app.id,
255
+ connectorSlug: app.slug,
256
+ connectorName: app.name,
257
+ uri: r.uri,
258
+ name: r.name,
259
+ ...(r.description !== undefined && { description: r.description }),
260
+ ...(r.mimeType !== undefined && { mimeType: r.mimeType }),
261
+ ...(r.size !== undefined && { size: r.size }),
243
262
  });
244
- return { resources: items.slice(0, MAX_RESOURCES), unavailable };
263
+ const matches = (r) => q === "" || [r.name, r.uri, r.description ?? ""].some((v) => v.toLowerCase().includes(q));
264
+ const app = await this.connectorRow(orgId, opts.connectorId);
265
+ if (!(await this.resourcesEnabled([app.id])).has(app.id)) {
266
+ throw new ApiError("connector.resources_disabled", "Reading resources is disabled for this connector");
267
+ }
268
+ // A failing connector throws credential.missing / connector.connect_failed: the caller asked
269
+ // about this one connector only.
270
+ const items = await this.withSession(orgId, app, accountId, Math.min(this.config.get().tools.timeoutMs, LIST_TIMEOUT_MS), async (s) => (s.listResources ? s.listResources() : []));
271
+ return {
272
+ resources: items
273
+ .filter((r) => listableResource(r) && matches(r))
274
+ .slice(0, MAX_CONNECTOR_RESOURCES)
275
+ .map((r) => view(app, r)),
276
+ };
245
277
  }
246
278
  /**
247
- * 解析消息附件:以发送者的凭据**并行**读取每个资源(打码、每个限 {@link MAX_ATTACHMENT_CHARS} 字符;总时限
248
- * min(`tools.timeoutMs`, 30s)),按请求顺序返回要追加在用户消息后的文本块与元数据。名称取资源清单里的 name
249
- * (读不到清单时用 URI)。连接器的 `read_resource` 工具被管理员停用 → 409 `connector.resources_disabled`。
250
- * 任一附件失败整条消息失败(不写入)。
279
+ * Reads the resources a message references with the sender's credentials, **in parallel**
280
+ * (redacted, each capped at {@link MAX_ATTACHMENT_CHARS} characters; total time limit
281
+ * min(`tools.timeoutMs`, 30s)), in request order. The name is the one in the resource listing
282
+ * (the URI when the listing does not have it). Refusals, any of which fails the whole message
283
+ * (nothing is written):
284
+ * - the connector is not live and active, or provides no resources → `connector.not_found`;
285
+ * - its `read_resource` tool is switched off by an admin (Ruling A23), or `readOffered` is given
286
+ * and does not hold the connector (the conversation's agent is not offered that tool) →
287
+ * 409 `connector.resources_disabled`;
288
+ * - an MCP Apps UI template, or a body that is empty after trimming → 422
289
+ * `connector.resource_unreadable` (`details: [{ connectorId, uri, reason }]`).
251
290
  */
252
- async resolveAttachments(orgId, accountId, refs) {
291
+ async readResources(orgId, accountId, refs, readOffered) {
253
292
  const apps = new Map();
254
- for (const id of new Set(refs.map((r) => r.connectorId)))
255
- apps.set(id, await this.connectorRow(orgId, id));
293
+ for (const id of new Set(refs.map((r) => r.connectorId))) {
294
+ // the refusal names the connector, so the sender's composer can mark its tokens
295
+ const app = await this.connectorRow(orgId, id).catch((e) => {
296
+ throw e instanceof ApiError && e.code === "connector.not_found"
297
+ ? new ApiError("connector.not_found", e.message, [{ connectorId: id }])
298
+ : e;
299
+ });
300
+ apps.set(id, app);
301
+ }
256
302
  const enabled = await this.resourcesEnabled([...apps.keys()]);
257
303
  for (const id of apps.keys()) {
258
- if (!enabled.has(id)) {
259
- throw new ApiError("connector.resources_disabled", "Reading resources is turned off for this connector");
304
+ if (!enabled.has(id) || (readOffered !== undefined && !readOffered.has(id))) {
305
+ throw new ApiError("connector.resources_disabled", readOffered !== undefined && enabled.has(id)
306
+ ? "This agent cannot read resources of this connector"
307
+ : "Reading resources is turned off for this connector", [{ connectorId: id }]);
260
308
  }
261
309
  }
262
310
  const timeoutMs = Math.min(this.config.get().tools.timeoutMs, ATTACHMENTS_TIMEOUT_MS);
263
- const read = await Promise.all(refs.map(async (ref) => {
311
+ const unreadable = (ref, reason) => new ApiError("connector.resource_unreadable", reason === "ui_template"
312
+ ? `${ref.uri} is a UI template with nothing to read; remove it`
313
+ : `${ref.uri} is empty; remove it`, [{ connectorId: ref.connectorId, uri: ref.uri, reason }]);
314
+ return Promise.all(refs.map(async (ref) => {
264
315
  const app = apps.get(ref.connectorId);
265
316
  const got = await this.withSession(orgId, app, accountId, timeoutMs, async (s) => {
266
317
  if (!s.readResource)
@@ -268,27 +319,34 @@ let ConnectorContent = class ConnectorContent {
268
319
  const listed = s.listResources
269
320
  ? (await s.listResources().catch(() => [])).find((r) => r.uri === ref.uri)
270
321
  : undefined;
322
+ if (isUiTemplate(listed ?? { uri: ref.uri }))
323
+ return "ui_template";
271
324
  const result = await s.readResource(ref.uri);
272
- return { name: listed?.name ?? ref.uri, text: renderResult(result).text };
325
+ const text = renderResult(result).text;
326
+ // no content at all renders as a placeholder line, which is no content either
327
+ const empty = (result.content?.length ?? 0) === 0 || text.trim() === "";
328
+ return { name: listed?.name ?? ref.uri, text, empty };
273
329
  });
274
330
  if (!got)
275
- throw new ApiError("connector.not_found", "This connector does not provide resources");
276
- return { app, ref, got };
277
- }));
278
- const blocks = [];
279
- const attachments = [];
280
- for (const { app, ref, got } of read) {
331
+ throw new ApiError("connector.not_found", "This connector does not provide resources", [
332
+ { connectorId: ref.connectorId, uri: ref.uri },
333
+ ]);
334
+ if (got === "ui_template")
335
+ throw unreadable(ref, "ui_template");
336
+ if (got.empty)
337
+ throw unreadable(ref, "empty");
281
338
  let body = got.text;
282
339
  if (body.length > MAX_ATTACHMENT_CHARS) {
283
340
  body = `${body.slice(0, MAX_ATTACHMENT_CHARS)}\n[Attachment truncated: showing the first ${MAX_ATTACHMENT_CHARS} of ${got.text.length} characters.]`;
284
341
  }
285
- blocks.push({
286
- type: "text",
287
- text: `Attached resource ${JSON.stringify(got.name)} (${ref.uri}) from app ${app.name}:\n\n${body}`,
288
- });
289
- attachments.push({ appId: app.id, appName: app.name, uri: ref.uri, name: got.name });
290
- }
291
- return { blocks, attachments };
342
+ return {
343
+ connectorId: app.id,
344
+ connectorName: app.name,
345
+ uri: ref.uri,
346
+ name: got.name,
347
+ body,
348
+ };
349
+ }));
292
350
  }
293
351
  };
294
352
  ConnectorContent = __decorate([
@@ -498,8 +498,9 @@ export declare class ConnectorsService {
498
498
  * Disables a connector because its plugin was switched off in the org (spec §5 rule 8): its
499
499
  * endpoint and credentials stay. Only a connector that was active is marked with the plugin
500
500
  * (`connectors.disabled_by_plugin_id`), so switching the plugin back on re-enables exactly what
501
- * this call disabled; one an org admin disabled by hand keeps no marker and stays disabled. The
502
- * caller holds the org row lock and runs in its transaction.
501
+ * this call disabled; one an org admin disabled by hand keeps no marker and stays disabled
502
+ * (`pluginSwitchOff`, which the plugin's delete shares). The caller holds the org row lock and
503
+ * runs in its transaction.
503
504
  */
504
505
  disableWithPluginIn(orgId: string, connectorId: string, itemId: string): Promise<void>;
505
506
  /**
@@ -13,6 +13,7 @@ import { Inject, Injectable } from "@nestjs/common";
13
13
  import { sql } from "kysely";
14
14
  import { z } from "zod";
15
15
  import { connectorTemplateState } from "../catalog/component-state.js";
16
+ import { pluginSwitchOff } from "../catalog/plugin-connectors.js";
16
17
  import { assertItemInstallable } from "../catalog/request-rules.js";
17
18
  import { productName } from "../config/product-name.js";
18
19
  import { ApiError } from "../errors.js";
@@ -1397,29 +1398,14 @@ let ConnectorsService = class ConnectorsService {
1397
1398
  * Disables a connector because its plugin was switched off in the org (spec §5 rule 8): its
1398
1399
  * endpoint and credentials stay. Only a connector that was active is marked with the plugin
1399
1400
  * (`connectors.disabled_by_plugin_id`), so switching the plugin back on re-enables exactly what
1400
- * this call disabled; one an org admin disabled by hand keeps no marker and stays disabled. The
1401
- * caller holds the org row lock and runs in its transaction.
1401
+ * this call disabled; one an org admin disabled by hand keeps no marker and stays disabled
1402
+ * (`pluginSwitchOff`, which the plugin's delete shares). The caller holds the org row lock and
1403
+ * runs in its transaction.
1402
1404
  */
1403
1405
  async disableWithPluginIn(orgId, connectorId, itemId) {
1404
- const t = this.db;
1405
- const row = await t
1406
- .selectFrom("connectors")
1407
- .select(["status"])
1408
- .where("id", "=", connectorId)
1409
- .where("org_id", "=", orgId)
1410
- .where("deleted_at", "is", null)
1411
- .forUpdate()
1412
- .executeTakeFirst();
1413
- if (!row)
1414
- return;
1415
- await t
1406
+ await this.db
1416
1407
  .updateTable("connectors")
1417
- .set({
1418
- status: "disabled",
1419
- // An admin's disable is not the plugin's: it is not marked and so stays off on switch-on
1420
- ...(row.status === "active" && { disabled_by_plugin_id: itemId }),
1421
- updated_at: sql `now()`,
1422
- })
1408
+ .set(pluginSwitchOff(itemId))
1423
1409
  .where("id", "=", connectorId)
1424
1410
  .where("org_id", "=", orgId)
1425
1411
  .where("deleted_at", "is", null)
@@ -0,0 +1,88 @@
1
+ import type { ConversationSource } from "@capybara-hq/plugin-sdk";
2
+ import { AgentLookup } from "../agents/agent-lookup.js";
3
+ import type { AgentDefinition } from "../agents/definition.js";
4
+ import { PluginIcons } from "../extensions/plugin-icons.js";
5
+ import { KernelDb } from "../infra/database/kernel-db.js";
6
+ import type { OrgContext } from "../orgs/org.guard.js";
7
+ import { Credentials } from "./credentials.js";
8
+ import { type ResolvedTool, ToolRegistry } from "./registry.js";
9
+ /**
10
+ * One row of the composer's `@` menu (composer inline tokens spec §4): a connector of the org the
11
+ * agent can be pointed at. `icon` is the connector's kernel icon URL
12
+ * (`/api/v1/orgs/:orgId/connectors/:id/icon?v=…`), null when it shows none; `credential` is the
13
+ * viewer's own credential state for a personal-credential connector, `none` otherwise;
14
+ * `toolCount` counts the agent's offered tools of it (0 for `needs_config`); `resources` says
15
+ * whether the agent is offered its `read_resource` tool.
16
+ */
17
+ export interface MentionableConnector {
18
+ id: string;
19
+ slug: string;
20
+ name: string;
21
+ /**
22
+ * Its own description (one language), else its platform template's English one; with the
23
+ * template's, `descriptionZh` carries the Chinese one when the template has it (the web picks
24
+ * by locale).
25
+ */
26
+ description?: string;
27
+ descriptionZh?: string;
28
+ icon: string | null;
29
+ state: "ready" | "needs_config";
30
+ credential: "connected" | "missing" | "none";
31
+ toolCount: number;
32
+ resources: boolean;
33
+ }
34
+ /** Why a connector named in a message cannot be used (`conversation.connector_unavailable`). */
35
+ export type ConnectorRefusal = "not_found" | "needs_config" | "not_offered";
36
+ /** A connector a message names, as the agent's tools offer it now. */
37
+ export interface MentionedConnector {
38
+ id: string;
39
+ slug: string;
40
+ name: string;
41
+ /** The agent's offered tools of it (at least one). */
42
+ tools: ResolvedTool[];
43
+ }
44
+ /** The tools of `tools` that come from connector `connectorId` (in their order). */
45
+ export declare function connectorToolsFor(tools: readonly ResolvedTool[], connectorId: string): ResolvedTool[];
46
+ /**
47
+ * The connectors an agent can be told to use from the web input box: the org's live, active
48
+ * connectors of which the agent is offered at least one tool (`ToolRegistry.forAgent`, source
49
+ * `web`), plus the `needs_config` ones the agent does not switch off as a whole (shown disabled).
50
+ * Reads only the database and the credential store's key presence: no connector session is opened.
51
+ */
52
+ export declare class MentionableConnectorsService {
53
+ private readonly db;
54
+ private readonly agents;
55
+ private readonly registry;
56
+ private readonly credentials;
57
+ private readonly icons;
58
+ constructor(db: KernelDb, agents: AgentLookup, registry: ToolRegistry, credentials: Credentials, icons: PluginIcons);
59
+ /**
60
+ * The rows for `agentId` as `accountId` sees them in `org` (the org guard's context: its role
61
+ * decides which icons the reader may see); an agent the account may not see (or another org's)
62
+ * -> `agent.not_found`.
63
+ */
64
+ list(org: Pick<OrgContext, "orgId" | "role">, accountId: string, agentId: string): Promise<{
65
+ connectors: MentionableConnector[];
66
+ }>;
67
+ /**
68
+ * The agent's tools for a message that names connectors or their resources (composer inline
69
+ * tokens spec §3.4), resolved once as the conversation's next step would resolve them
70
+ * (`ToolRegistry.forAgent` with the definition's disabled tools and roster, the conversation's
71
+ * source and its sandbox conversation), and each of `mentioned` with its offered tools. A
72
+ * connector of which the agent is offered no tool refuses the message: 422
73
+ * `conversation.connector_unavailable`, `details: [{ connectorId, reason }]`, every refused
74
+ * connector in `mentioned` order: `not_found` (deleted, disabled, another org's), `needs_config`
75
+ * (an org admin must configure it, and nothing else keeps it from the agent), `not_offered` (the
76
+ * agent switches it off, none of its tools is enabled, or its connector extension is not
77
+ * loaded). A personal credential the sender has not connected is no refusal: the tool call
78
+ * answers with the connection card. Opens no connector session.
79
+ */
80
+ resolveForMessage(orgId: string, agent: Pick<AgentDefinition, "disabledTools" | "subagents">, where: {
81
+ source: ConversationSource;
82
+ sandboxConversationId?: string | undefined;
83
+ }, mentioned: readonly string[]): Promise<{
84
+ tools: ResolvedTool[];
85
+ toolSearch: boolean;
86
+ connectors: MentionedConnector[];
87
+ }>;
88
+ }