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

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 (73) 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-content.d.ts +11 -0
  5. package/dist/catalog/catalog-content.js +1 -0
  6. package/dist/catalog/catalog.service.d.ts +11 -1
  7. package/dist/catalog/catalog.service.js +36 -2
  8. package/dist/catalog/marketplaces.service.d.ts +1 -1
  9. package/dist/catalog/org-catalog.service.d.ts +1 -0
  10. package/dist/catalog/org-catalog.service.js +44 -2
  11. package/dist/catalog/platform-components.js +13 -0
  12. package/dist/catalog/plugin-connectors.d.ts +35 -0
  13. package/dist/catalog/plugin-connectors.js +81 -0
  14. package/dist/catalog/schema-path.d.ts +4 -6
  15. package/dist/catalog/schema-path.js +48 -21
  16. package/dist/channels/outbound.d.ts +5 -0
  17. package/dist/channels/outbound.js +6 -1
  18. package/dist/channels/supervisor.d.ts +5 -1
  19. package/dist/channels/supervisor.js +20 -1
  20. package/dist/conversations/conversations.controller.d.ts +46 -14
  21. package/dist/conversations/conversations.controller.js +82 -47
  22. package/dist/conversations/conversations.service.d.ts +93 -59
  23. package/dist/conversations/conversations.service.js +255 -72
  24. package/dist/conversations/events.d.ts +32 -0
  25. package/dist/conversations/events.js +47 -3
  26. package/dist/conversations/inline-tokens.d.ts +87 -0
  27. package/dist/conversations/inline-tokens.js +154 -0
  28. package/dist/conversations/permission-profiles.controller.d.ts +14 -7
  29. package/dist/conversations/permission-profiles.controller.js +1 -5
  30. package/dist/conversations/prompt-suggestions.js +2 -4
  31. package/dist/conversations/queue.d.ts +0 -2
  32. package/dist/conversations/queue.service.js +9 -13
  33. package/dist/db/kernel-schema.d.ts +2 -0
  34. package/dist/devices/devices.service.d.ts +8 -0
  35. package/dist/devices/devices.service.js +16 -0
  36. package/dist/errors.d.ts +12 -0
  37. package/dist/errors.js +12 -0
  38. package/dist/evals/snapshot.js +4 -2
  39. package/dist/files/library-files.service.d.ts +13 -0
  40. package/dist/files/library-files.service.js +33 -6
  41. package/dist/net/safe-fetch.js +1 -1
  42. package/dist/platform/exclusions.js +11 -1
  43. package/dist/platform/ops/devices.ops.js +14 -0
  44. package/dist/runtime/context/build.d.ts +7 -2
  45. package/dist/runtime/context/build.js +17 -6
  46. package/dist/runtime/context/compaction.d.ts +3 -3
  47. package/dist/runtime/context/compaction.js +12 -13
  48. package/dist/sandbox/review/classifier.js +5 -1
  49. package/dist/sandbox/sandbox.service.d.ts +13 -0
  50. package/dist/sandbox/sandbox.service.js +51 -4
  51. package/dist/tools/builtins/sandbox/common.d.ts +2 -7
  52. package/dist/tools/builtins/sandbox/common.js +4 -2
  53. package/dist/tools/connector-content.controller.d.ts +6 -2
  54. package/dist/tools/connector-content.controller.js +13 -3
  55. package/dist/tools/connector-content.d.ts +55 -15
  56. package/dist/tools/connector-content.js +112 -54
  57. package/dist/tools/connectors.service.d.ts +3 -2
  58. package/dist/tools/connectors.service.js +6 -20
  59. package/dist/tools/mentionable-connectors.d.ts +88 -0
  60. package/dist/tools/mentionable-connectors.js +218 -0
  61. package/dist/tools/pipeline.d.ts +4 -0
  62. package/dist/tools/pipeline.js +98 -22
  63. package/dist/tools/specs.d.ts +13 -4
  64. package/dist/tools/specs.js +22 -8
  65. package/dist/tools/tools.module.js +7 -0
  66. package/dist/ui/admin-ui.controller.d.ts +5 -2
  67. package/dist/ui/admin-ui.controller.js +14 -1
  68. package/dist/ui/ui.schemas.d.ts +9 -0
  69. package/dist/ui/ui.schemas.js +2 -0
  70. package/dist/ui/views.d.ts +1 -1
  71. package/dist/ui/views.js +4 -5
  72. package/package.json +3 -3
  73. package/src/migrations/0201_tool_specs_text.sql +8 -0
@@ -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
+ }
@@ -0,0 +1,218 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { AgentLookup } from "../agents/agent-lookup.js";
12
+ import { ApiError } from "../errors.js";
13
+ import { orgIconScope, PluginIcons } from "../extensions/plugin-icons.js";
14
+ import { KernelDb } from "../infra/database/kernel-db.js";
15
+ import { connectorSetups } from "./connector-setup.js";
16
+ import { Credentials } from "./credentials.js";
17
+ import { ToolRegistry } from "./registry.js";
18
+ import { READ_RESOURCE } from "./resources.js";
19
+ /** The tools of `tools` that come from connector `connectorId` (in their order). */
20
+ export function connectorToolsFor(tools, connectorId) {
21
+ return tools.filter((t) => t.source.kind === "connector" && t.source.connectorId === connectorId);
22
+ }
23
+ /**
24
+ * The connectors an agent can be told to use from the web input box: the org's live, active
25
+ * connectors of which the agent is offered at least one tool (`ToolRegistry.forAgent`, source
26
+ * `web`), plus the `needs_config` ones the agent does not switch off as a whole (shown disabled).
27
+ * Reads only the database and the credential store's key presence: no connector session is opened.
28
+ */
29
+ let MentionableConnectorsService = class MentionableConnectorsService {
30
+ db;
31
+ agents;
32
+ registry;
33
+ credentials;
34
+ icons;
35
+ constructor(db, agents, registry, credentials, icons) {
36
+ this.db = db;
37
+ this.agents = agents;
38
+ this.registry = registry;
39
+ this.credentials = credentials;
40
+ this.icons = icons;
41
+ }
42
+ /**
43
+ * The rows for `agentId` as `accountId` sees them in `org` (the org guard's context: its role
44
+ * decides which icons the reader may see); an agent the account may not see (or another org's)
45
+ * -> `agent.not_found`.
46
+ */
47
+ async list(org, accountId, agentId) {
48
+ const { orgId } = org;
49
+ const agent = await this.agents.get(orgId, agentId, accountId);
50
+ const disabled = agent.definition.disabledTools ?? [];
51
+ // no conversation yet: the listing names no sandbox conversation, which only decides the
52
+ // device-bound builtins, never a connector's tools
53
+ const { tools } = await this.registry.forAgent(orgId, {
54
+ disabledTools: disabled,
55
+ source: "web",
56
+ });
57
+ const rows = await this.db
58
+ .selectFrom("connectors")
59
+ .select([
60
+ "id",
61
+ "slug",
62
+ "name",
63
+ "description",
64
+ "connector",
65
+ "auth",
66
+ "platform_template_id",
67
+ "catalog_item_id",
68
+ ])
69
+ .where("org_id", "=", orgId)
70
+ .where("deleted_at", "is", null)
71
+ .where("status", "=", "active")
72
+ .orderBy("slug")
73
+ .orderBy("id")
74
+ .execute();
75
+ if (rows.length === 0)
76
+ return { connectors: [] };
77
+ const setups = await connectorSetups(this.credentials, orgId, rows.map((r) => ({ id: r.id, auth: r.auth })));
78
+ const shown = rows.flatMap((r) => {
79
+ const state = setups.get(r.id) ?? "needs_config";
80
+ const offered = connectorToolsFor(tools, r.id);
81
+ if (state === "ready" && offered.length === 0)
82
+ return [];
83
+ // a needs_config one is shown unless the agent switches it off as a whole or its connector
84
+ // extension is not loaded (forAgent would not offer it once configured either)
85
+ if (state === "needs_config" &&
86
+ (disabled.some((d) => d.kind === "connector" && d.connectorId === r.id && d.tools === "all") ||
87
+ !this.registry.findConnector(r.connector))) {
88
+ return [];
89
+ }
90
+ return [{ row: r, state, offered }];
91
+ });
92
+ if (shown.length === 0)
93
+ return { connectors: [] };
94
+ const scope = orgIconScope(org);
95
+ const templateIds = shown.flatMap((s) => s.row.platform_template_id ? [s.row.platform_template_id] : []);
96
+ const [urls, descriptions, credentials] = await Promise.all([
97
+ this.icons.ofConnectors(shown.map((s) => ({
98
+ id: s.row.id,
99
+ templateId: s.row.platform_template_id ?? null,
100
+ itemId: s.row.catalog_item_id ?? null,
101
+ })), scope),
102
+ this.icons.templateDescriptions(templateIds, scope),
103
+ Promise.all(shown.map(async ({ row }) => {
104
+ const auth = row.auth;
105
+ if (auth.type === "none" || auth.ownership !== "personal")
106
+ return "none";
107
+ return this.credentials.status(orgId, row.id, auth, accountId);
108
+ })),
109
+ ]);
110
+ return {
111
+ connectors: shown.map(({ row, state, offered }, i) => {
112
+ // its own description first, else its platform template's (as the connector pages)
113
+ const template = row.platform_template_id
114
+ ? descriptions.get(row.platform_template_id)
115
+ : undefined;
116
+ const own = row.description?.trim() ? row.description : null;
117
+ const description = own ?? template?.description ?? null;
118
+ const descriptionZh = own === null ? (template?.descriptionZh ?? null) : null;
119
+ const ready = state === "ready";
120
+ return {
121
+ id: row.id,
122
+ slug: row.slug,
123
+ name: row.name,
124
+ ...(description !== null && { description }),
125
+ ...(descriptionZh !== null && { descriptionZh }),
126
+ icon: urls[i] ?? null,
127
+ state,
128
+ credential: credentials[i] ?? "none",
129
+ toolCount: ready ? offered.length : 0,
130
+ resources: ready &&
131
+ offered.some((t) => t.source.kind === "connector" &&
132
+ t.source.resources === true &&
133
+ t.source.name === READ_RESOURCE),
134
+ };
135
+ }),
136
+ };
137
+ }
138
+ /**
139
+ * The agent's tools for a message that names connectors or their resources (composer inline
140
+ * tokens spec §3.4), resolved once as the conversation's next step would resolve them
141
+ * (`ToolRegistry.forAgent` with the definition's disabled tools and roster, the conversation's
142
+ * source and its sandbox conversation), and each of `mentioned` with its offered tools. A
143
+ * connector of which the agent is offered no tool refuses the message: 422
144
+ * `conversation.connector_unavailable`, `details: [{ connectorId, reason }]`, every refused
145
+ * connector in `mentioned` order: `not_found` (deleted, disabled, another org's), `needs_config`
146
+ * (an org admin must configure it, and nothing else keeps it from the agent), `not_offered` (the
147
+ * agent switches it off, none of its tools is enabled, or its connector extension is not
148
+ * loaded). A personal credential the sender has not connected is no refusal: the tool call
149
+ * answers with the connection card. Opens no connector session.
150
+ */
151
+ async resolveForMessage(orgId, agent, where, mentioned) {
152
+ const disabled = agent.disabledTools ?? [];
153
+ const resolved = await this.registry.forAgent(orgId, {
154
+ disabledTools: disabled,
155
+ subagents: agent.subagents,
156
+ ...(where.sandboxConversationId !== undefined && {
157
+ sandboxConversationId: where.sandboxConversationId,
158
+ }),
159
+ source: where.source,
160
+ });
161
+ const tools = resolved.tools;
162
+ const toolSearch = resolved.toolSearch === true;
163
+ if (mentioned.length === 0)
164
+ return { tools, toolSearch, connectors: [] };
165
+ const rows = await this.db
166
+ .selectFrom("connectors")
167
+ .select(["id", "slug", "name", "connector", "auth"])
168
+ .where("org_id", "=", orgId)
169
+ .where("id", "in", [...mentioned])
170
+ .where("deleted_at", "is", null)
171
+ .where("status", "=", "active")
172
+ .execute();
173
+ const byId = new Map(rows.map((r) => [r.id, r]));
174
+ const connectors = [];
175
+ const unoffered = [];
176
+ const refused = new Map();
177
+ for (const id of mentioned) {
178
+ const row = byId.get(id);
179
+ if (!row) {
180
+ refused.set(id, "not_found");
181
+ continue;
182
+ }
183
+ const offered = connectorToolsFor(tools, id);
184
+ if (offered.length > 0) {
185
+ connectors.push({ id, slug: row.slug, name: row.name, tools: offered });
186
+ }
187
+ else {
188
+ unoffered.push(row);
189
+ }
190
+ }
191
+ if (unoffered.length > 0) {
192
+ const setups = await connectorSetups(this.credentials, orgId, unoffered.map((r) => ({ id: r.id, auth: r.auth })));
193
+ for (const r of unoffered) {
194
+ const switchedOff = disabled.some((d) => d.kind === "connector" && d.connectorId === r.id && d.tools === "all");
195
+ refused.set(r.id, setups.get(r.id) !== "ready" && !switchedOff && this.registry.findConnector(r.connector)
196
+ ? "needs_config"
197
+ : "not_offered");
198
+ }
199
+ }
200
+ if (refused.size > 0) {
201
+ const details = mentioned.flatMap((connectorId) => {
202
+ const reason = refused.get(connectorId);
203
+ return reason === undefined ? [] : [{ connectorId, reason }];
204
+ });
205
+ throw new ApiError("conversation.connector_unavailable", "A connector this message names cannot be used by this agent now; remove it and send again", details);
206
+ }
207
+ return { tools, toolSearch, connectors };
208
+ }
209
+ };
210
+ MentionableConnectorsService = __decorate([
211
+ Injectable(),
212
+ __param(0, Inject(KernelDb)),
213
+ __param(1, Inject(AgentLookup)),
214
+ __param(2, Inject(ToolRegistry)),
215
+ __param(3, Inject(Credentials)),
216
+ __param(4, Inject(PluginIcons))
217
+ ], MentionableConnectorsService);
218
+ export { MentionableConnectorsService };
@@ -740,6 +740,10 @@ export declare class ToolPipeline {
740
740
  private networkBlocked;
741
741
  /** The call's live loopback port grant (null: none, ended, or no grants service). */
742
742
  private loopbackGrantOf;
743
+ /**
744
+ * The attempt that recorded a ready-grant loopback rerun for this call, or null when none did.
745
+ */
746
+ private readyLoopbackRerunOf;
743
747
  /**
744
748
  * A device service's loopback refusal (browser loopback port grants): the port of the person's
745
749
  * own device a service of an extension declaring `permissions.deviceAccess.loopbackPorts` was