@capybara-hq/kernel 0.1.0-rc.47 → 0.1.0-rc.49

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 (121) hide show
  1. package/dist/admin/admin.module.js +2 -0
  2. package/dist/admin/admin.schemas.d.ts +4 -0
  3. package/dist/admin/health.service.d.ts +2 -2
  4. package/dist/admin/health.service.js +8 -4
  5. package/dist/agents/agents.schemas.js +1 -1
  6. package/dist/agents/instruction-files.js +0 -3
  7. package/dist/background/launch.d.ts +4 -0
  8. package/dist/background/launch.js +6 -2
  9. package/dist/catalog/marketplaces.service.d.ts +1 -1
  10. package/dist/channels/channels.module.js +3 -0
  11. package/dist/channels/connections.service.d.ts +18 -5
  12. package/dist/channels/connections.service.js +21 -5
  13. package/dist/channels/features.d.ts +2 -0
  14. package/dist/channels/features.js +9 -5
  15. package/dist/channels/file-delivery.d.ts +74 -0
  16. package/dist/channels/file-delivery.js +176 -0
  17. package/dist/channels/outbound.d.ts +6 -3
  18. package/dist/channels/outbound.js +156 -4
  19. package/dist/channels/phrases.d.ts +19 -0
  20. package/dist/channels/phrases.js +16 -0
  21. package/dist/config/schema.d.ts +2 -0
  22. package/dist/config/schema.js +18 -0
  23. package/dist/conversations/delivery-scope.d.ts +34 -0
  24. package/dist/conversations/delivery-scope.js +23 -0
  25. package/dist/conversations/event-log.d.ts +18 -0
  26. package/dist/conversations/event-log.js +54 -0
  27. package/dist/conversations/events.d.ts +2 -0
  28. package/dist/conversations/events.js +15 -2
  29. package/dist/conversations/prompt-suggestion-request.d.ts +95 -0
  30. package/dist/conversations/prompt-suggestion-request.js +213 -0
  31. package/dist/conversations/prompt-suggestion-store.d.ts +51 -0
  32. package/dist/conversations/prompt-suggestion-store.js +136 -0
  33. package/dist/conversations/prompt-suggestions.d.ts +153 -0
  34. package/dist/conversations/prompt-suggestions.js +563 -0
  35. package/dist/conversations/titles.js +11 -5
  36. package/dist/evals/reconstruct.d.ts +26 -1
  37. package/dist/evals/reconstruct.js +25 -6
  38. package/dist/identity/settings.d.ts +13 -0
  39. package/dist/identity/settings.js +37 -2
  40. package/dist/infra/queue/queue-names.d.ts +1 -1
  41. package/dist/infra/queue/queue-names.js +1 -0
  42. package/dist/kernel.module.js +4 -1
  43. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  44. package/dist/lifecycle/kernel-lifecycle.js +13 -7
  45. package/dist/models/image-usable.d.ts +30 -6
  46. package/dist/models/image-usable.js +38 -7
  47. package/dist/models/images.js +6 -4
  48. package/dist/models/purposes.d.ts +1 -1
  49. package/dist/models/purposes.js +10 -4
  50. package/dist/orgs/settings.service.d.ts +16 -0
  51. package/dist/orgs/settings.service.js +46 -5
  52. package/dist/overrides.d.ts +4 -0
  53. package/dist/overrides.js +2 -0
  54. package/dist/platform/availability.d.ts +5 -0
  55. package/dist/platform/availability.js +7 -3
  56. package/dist/platform/ops/accounts.ops.d.ts +1 -1
  57. package/dist/platform/ops/accounts.ops.js +1 -1
  58. package/dist/platform/ops/admin.ops.js +3 -2
  59. package/dist/platform/ops/agent-skills.ops.js +5 -5
  60. package/dist/platform/ops/agents.ops.js +3 -3
  61. package/dist/platform/ops/approvals.ops.d.ts +1 -1
  62. package/dist/platform/ops/approvals.ops.js +2 -2
  63. package/dist/platform/ops/background.ops.js +1 -1
  64. package/dist/platform/ops/catalog-admin.ops.js +3 -3
  65. package/dist/platform/ops/conversations.ops.js +2 -2
  66. package/dist/platform/ops/devices.ops.js +2 -2
  67. package/dist/platform/ops/extensions-admin.ops.js +2 -2
  68. package/dist/platform/ops/extensions.ops.js +3 -3
  69. package/dist/platform/ops/inbox.ops.js +4 -4
  70. package/dist/platform/ops/org-plugins.ops.js +4 -4
  71. package/dist/platform/ops/org-settings.ops.js +2 -2
  72. package/dist/platform/ops/orgs.ops.js +1 -0
  73. package/dist/platform/ops/plugins.ops.d.ts +1 -1
  74. package/dist/platform/ops/plugins.ops.js +3 -3
  75. package/dist/platform/ops/requests.ops.js +1 -1
  76. package/dist/platform/ops/schedules.ops.js +6 -6
  77. package/dist/roles/worker-role.d.ts +6 -3
  78. package/dist/roles/worker-role.js +21 -13
  79. package/dist/roles/worker.module.js +2 -0
  80. package/dist/runtime/compaction-settings.service.d.ts +8 -0
  81. package/dist/runtime/compaction-settings.service.js +12 -6
  82. package/dist/runtime/run-processors.d.ts +14 -6
  83. package/dist/runtime/run-processors.js +43 -8
  84. package/dist/runtime/run-worker.d.ts +5 -0
  85. package/dist/runtime/run-worker.js +24 -16
  86. package/dist/runtime/runtime.module.d.ts +1 -1
  87. package/dist/runtime/runtime.module.js +7 -1
  88. package/dist/runtime/stream.d.ts +7 -1
  89. package/dist/runtime/stream.js +54 -3
  90. package/dist/runtime/usage-report.d.ts +2 -1
  91. package/dist/runtime/usage-report.js +2 -1
  92. package/dist/sandbox/sandbox-file-reader.js +1 -1
  93. package/dist/storage/storage.service.d.ts +2 -0
  94. package/dist/storage/storage.service.js +3 -0
  95. package/dist/tools/builtin-names.js +2 -2
  96. package/dist/tools/builtins/agent.js +5 -5
  97. package/dist/tools/builtins/artifacts.d.ts +34 -8
  98. package/dist/tools/builtins/artifacts.js +95 -19
  99. package/dist/tools/builtins/image/generate.d.ts +4 -1
  100. package/dist/tools/builtins/image/generate.js +70 -14
  101. package/dist/tools/builtins/platform.d.ts +0 -2
  102. package/dist/tools/builtins/platform.js +3 -5
  103. package/dist/tools/builtins/sandbox/bash.js +15 -11
  104. package/dist/tools/builtins/sandbox/common.d.ts +3 -2
  105. package/dist/tools/builtins/sandbox/deliver.js +13 -7
  106. package/dist/tools/builtins/sandbox/glob.js +1 -1
  107. package/dist/tools/builtins/sandbox/grep.js +1 -1
  108. package/dist/tools/builtins/sandbox/read.js +3 -3
  109. package/dist/tools/builtins/sandbox/task-output.d.ts +1 -1
  110. package/dist/tools/builtins/sandbox/task-output.js +13 -11
  111. package/dist/tools/builtins/send-message.d.ts +1 -1
  112. package/dist/tools/builtins/send-message.js +3 -3
  113. package/dist/tools/builtins/skill-load.d.ts +1 -1
  114. package/dist/tools/builtins/tool-search.js +1 -1
  115. package/dist/tools/builtins/web/extract.js +1 -1
  116. package/dist/tools/builtins/web/search.js +2 -4
  117. package/dist/tools/connector-account-policies.js +1 -1
  118. package/dist/tools/info.d.ts +3 -1
  119. package/dist/tools/registry.d.ts +6 -0
  120. package/dist/tools/registry.js +1 -1
  121. package/package.json +3 -3
@@ -7,6 +7,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  import { Module } from "@nestjs/common";
8
8
  import { CatalogModule } from "../catalog/catalog.module.js";
9
9
  import { ChannelsModule } from "../channels/channels.module.js";
10
+ import { PromptSuggestionsModule } from "../conversations/prompt-suggestions.js";
10
11
  import { TitlesModule } from "../conversations/titles.js";
11
12
  import { EvalsModule } from "../evals/evals.module.js";
12
13
  import { ExtensionsModule } from "../extensions/extensions.module.js";
@@ -49,6 +50,7 @@ AdminModule = __decorate([
49
50
  RunJobsModule,
50
51
  ChannelsModule,
51
52
  TitlesModule,
53
+ PromptSuggestionsModule,
52
54
  UsageReportModule,
53
55
  EvalsModule,
54
56
  LifecycleHooksModule,
@@ -87,6 +87,10 @@ export declare const DeploymentSettingsBody: z.ZodObject<{
87
87
  deny: "deny";
88
88
  }>>>;
89
89
  shareMaxExpiryDays: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
90
+ promptSuggestions: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
91
+ off: "off";
92
+ on: "on";
93
+ }>>>;
90
94
  htmlRenderCdnAllowlist: z.ZodOptional<z.ZodArray<z.ZodType<string, unknown, z.core.$ZodTypeInternals<string, unknown>>>>;
91
95
  }, z.core.$strict>;
92
96
  export declare const PurposeParams: z.ZodObject<{
@@ -4,7 +4,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
4
4
  import { type LiveReplica, ReplicaPresence } from "../infra/presence/replica-presence.js";
5
5
  import type { KernelLogger } from "../log.js";
6
6
  /** The kernel's own queues, in the order the overview lists them (extension queues are not read). */
7
- export declare const KERNEL_QUEUE_NAMES: readonly ["cap-kernel-runs", "cap-kernel-subagent-runs", "cap-kernel-channels", "cap-kernel-maintenance", "cap-kernel-plugin-scope", "cap-kernel-titles", "cap-kernel-usage-report", "cap-kernel-evals", "cap-kernel-lifecycle"];
7
+ export declare const KERNEL_QUEUE_NAMES: readonly ["cap-kernel-runs", "cap-kernel-subagent-runs", "cap-kernel-channels", "cap-kernel-maintenance", "cap-kernel-plugin-scope", "cap-kernel-titles", "cap-kernel-suggestions", "cap-kernel-usage-report", "cap-kernel-evals", "cap-kernel-lifecycle"];
8
8
  /** How long each source's reads may take before the answer marks it unavailable. */
9
9
  export declare const HEALTH_READ_TIMEOUT_MS = 3000;
10
10
  /** A live replica as the overview shows it. */
@@ -97,7 +97,7 @@ export declare class AdminHealthService {
97
97
  private readonly redis;
98
98
  private readonly log;
99
99
  private readonly queues;
100
- constructor(presence: Pick<ReplicaPresence, "live">, db: KernelDb, redis: Pick<Redis, "zcount" | "status">, log: Pick<KernelLogger, "warn">, runs: Queue, subagentRuns: Queue, channels: Queue, maintenance: Queue, pluginScope: Queue, titles: Queue, usageReport: Queue, evals: Queue, lifecycle: Queue);
100
+ constructor(presence: Pick<ReplicaPresence, "live">, db: KernelDb, redis: Pick<Redis, "zcount" | "status">, log: Pick<KernelLogger, "warn">, runs: Queue, subagentRuns: Queue, channels: Queue, maintenance: Queue, pluginScope: Queue, titles: Queue, suggestions: Queue, usageReport: Queue, evals: Queue, lifecycle: Queue);
101
101
  read(): Promise<AdminHealth>;
102
102
  private readRedis;
103
103
  private readDb;
@@ -12,6 +12,7 @@ import { Inject, Injectable } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
13
  import { PLUGIN_SCOPE_QUEUE } from "../catalog/scope-sync.js";
14
14
  import { CHANNEL_QUEUE_NAME } from "../channels/jobs.js";
15
+ import { PROMPT_SUGGESTION_QUEUE } from "../conversations/prompt-suggestions.js";
15
16
  import { TITLE_QUEUE } from "../conversations/titles.js";
16
17
  import { EVAL_QUEUE_NAME } from "../evals/jobs.js";
17
18
  import { LIFECYCLE_QUEUE } from "../extensions/lifecycle-hooks.js";
@@ -30,6 +31,7 @@ export const KERNEL_QUEUE_NAMES = [
30
31
  MAINTENANCE_QUEUE_NAME,
31
32
  PLUGIN_SCOPE_QUEUE,
32
33
  TITLE_QUEUE,
34
+ PROMPT_SUGGESTION_QUEUE,
33
35
  USAGE_REPORT_QUEUE,
34
36
  EVAL_QUEUE_NAME,
35
37
  LIFECYCLE_QUEUE,
@@ -60,7 +62,7 @@ let AdminHealthService = class AdminHealthService {
60
62
  redis;
61
63
  log;
62
64
  queues;
63
- constructor(presence, db, redis, log, runs, subagentRuns, channels, maintenance, pluginScope, titles, usageReport, evals, lifecycle) {
65
+ constructor(presence, db, redis, log, runs, subagentRuns, channels, maintenance, pluginScope, titles, suggestions, usageReport, evals, lifecycle) {
64
66
  this.presence = presence;
65
67
  this.db = db;
66
68
  this.redis = redis;
@@ -73,6 +75,7 @@ let AdminHealthService = class AdminHealthService {
73
75
  maintenance,
74
76
  pluginScope,
75
77
  titles,
78
+ suggestions,
76
79
  usageReport,
77
80
  evals,
78
81
  lifecycle,
@@ -243,8 +246,9 @@ AdminHealthService = __decorate([
243
246
  __param(7, Inject(getQueueToken(MAINTENANCE_QUEUE_NAME))),
244
247
  __param(8, Inject(getQueueToken(PLUGIN_SCOPE_QUEUE))),
245
248
  __param(9, Inject(getQueueToken(TITLE_QUEUE))),
246
- __param(10, Inject(getQueueToken(USAGE_REPORT_QUEUE))),
247
- __param(11, Inject(getQueueToken(EVAL_QUEUE_NAME))),
248
- __param(12, Inject(getQueueToken(LIFECYCLE_QUEUE)))
249
+ __param(10, Inject(getQueueToken(PROMPT_SUGGESTION_QUEUE))),
250
+ __param(11, Inject(getQueueToken(USAGE_REPORT_QUEUE))),
251
+ __param(12, Inject(getQueueToken(EVAL_QUEUE_NAME))),
252
+ __param(13, Inject(getQueueToken(LIFECYCLE_QUEUE)))
249
253
  ], AdminHealthService);
250
254
  export { AdminHealthService };
@@ -15,7 +15,7 @@ const RequestInstructions = z.string().max(100_000).optional();
15
15
  const RequestOnly = {
16
16
  tools: z
17
17
  .undefined({
18
- error: "tools was replaced by disabledTools: an agent has every tool unless it turns it off",
18
+ error: "tools is not a definition field: an agent has every tool unless disabledTools turns it off",
19
19
  })
20
20
  .optional(),
21
21
  subagentTools: z
@@ -19,9 +19,6 @@ export const AGENTS_MD_STARTER = [
19
19
  "You are an assistant for this team. Help people get their work done accurately and efficiently.",
20
20
  "",
21
21
  "- Tone: clear, friendly and concise. Use plain language, keep answers short, and add detail when asked.",
22
- "- When a request is unclear or missing key details, ask one short clarifying question before acting.",
23
- " If you go ahead anyway, say what you assumed.",
24
- "- If you don't know something or can't do it, say so instead of guessing.",
25
22
  ].join("\n");
26
23
  /**
27
24
  * The model-visible join: one file gives exactly its content (so an old agent edited without
@@ -78,6 +78,10 @@ export declare const GROUP_LAUNCHER: string;
78
78
  * go into the script unquoted).
79
79
  */
80
80
  export declare function launchScript(id: string, command: string, seconds: number): string;
81
+ /**
82
+ * The launch result's last line: how the task's end is reported and how to read and stop it.
83
+ */
84
+ export declare const LAUNCH_NEXT_STEP = "You will be told when it finishes. Read its output with TaskOutput (or Read), stop it with TaskStop.";
81
85
  /** The model-visible result of a launch (spec §2.1); `workspace`: the instance's workspace root. */
82
86
  export declare function startedText(id: string, description: string, workspace?: string): string;
83
87
  /**
@@ -150,12 +150,16 @@ export function launchScript(id, command, seconds) {
150
150
  `cat ${t}.sid`,
151
151
  ].join("\n");
152
152
  }
153
+ /**
154
+ * The launch result's last line: how the task's end is reported and how to read and stop it.
155
+ */
156
+ export const LAUNCH_NEXT_STEP = "You will be told when it finishes. Read its output with TaskOutput (or Read), stop it with TaskStop.";
153
157
  /** The model-visible result of a launch (spec §2.1); `workspace`: the instance's workspace root. */
154
158
  export function startedText(id, description, workspace = DEFAULT_SANDBOX_ROOTS.workspace) {
155
159
  return [
156
160
  `Started background task ${id} ("${description}").`,
157
161
  `Output: ${workspace}/${taskOutputPath(id)}`,
158
- "Read it with TaskOutput (or Read), stop it with TaskStop. You will be told when it finishes.",
162
+ LAUNCH_NEXT_STEP,
159
163
  ].join("\n");
160
164
  }
161
165
  /**
@@ -209,6 +213,6 @@ export function managedStartedText(id, description, outputPath) {
209
213
  return [
210
214
  `Started background task ${id} ("${description}").`,
211
215
  `Output: ${outputPath}`,
212
- "Read it with TaskOutput (or Read), stop it with TaskStop. You will be told when it finishes.",
216
+ LAUNCH_NEXT_STEP,
213
217
  ].join("\n");
214
218
  }
@@ -188,7 +188,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
188
188
  /** The host versions (an entry's `minKernel` is judged against them). */
189
189
  export declare const HOST_VERSIONS: {
190
190
  readonly kernel: string;
191
- readonly sdk: "0.1.0-rc.33";
191
+ readonly sdk: "0.1.0-rc.35";
192
192
  };
193
193
  /** Whether this deployment satisfies the entry's `minKernel`. */
194
194
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -23,6 +23,7 @@ import { OrgLockModule } from "../orgs/org-lock.js";
23
23
  import { OrgsModule } from "../orgs/orgs.module.js";
24
24
  import { RuntimeModule } from "../runtime/runtime.module.js";
25
25
  import { SchedulesModule } from "../schedules/schedules.module.js";
26
+ import { StorageModule } from "../storage/storage.module.js";
26
27
  import { ToolsModule } from "../tools/tools.module.js";
27
28
  import { ChannelConnections } from "./connections.service.js";
28
29
  import { ChannelInbound } from "./inbound.js";
@@ -54,6 +55,8 @@ ChannelsModule = __decorate([
54
55
  RuntimeModule,
55
56
  // outbound pauses the scheduled task of a run whose chat is gone (scheduled tasks spec §8)
56
57
  SchedulesModule,
58
+ // outbound reads conversation files to send them into the chat (channel file delivery §4.2)
59
+ StorageModule,
57
60
  CHANNEL_QUEUE_MODULE,
58
61
  ],
59
62
  providers: [
@@ -1,4 +1,4 @@
1
- import { type Channel, type ChannelTarget, type ExtensionContext, type OutboundMessage } from "@capybara-hq/plugin-sdk";
1
+ import { type Channel, type ChannelFile, type ChannelTarget, type ExtensionContext, type OutboundMessage } from "@capybara-hq/plugin-sdk";
2
2
  import { type OnApplicationShutdown } from "@nestjs/common";
3
3
  import type { Redis } from "ioredis";
4
4
  import { type Keyring } from "../ctx/secrets.js";
@@ -30,6 +30,8 @@ export declare const CHANNEL_CHANGED_TOPIC = "channel.changed";
30
30
  /** Redis:连接失败后的退避标记与连续失败次数(任一副本都据此决定何时重试)。 */
31
31
  export declare const channelBackoffKey: (id: string) => string;
32
32
  export declare const channelFailsKey: (id: string) => string;
33
+ /** The time limit of an extension's `sendFile` call, and of reading the file before it. */
34
+ export declare const FILE_CALL_TIMEOUT_MS = 120000;
33
35
  export type UnboundPolicy = "bind" | "anonymous";
34
36
  export type ChannelStatus = "active" | "disabled" | "error";
35
37
  /** How inbound events arrive: a long connection held by a gateway replica (default), or webhooks. */
@@ -269,9 +271,12 @@ export declare class ChannelConnections implements OnApplicationShutdown {
269
271
  inflight?: InflightTracker;
270
272
  }>;
271
273
  /**
272
- * 出站会话:解密一次连接配置,之后经插件发 / 改消息(每次调用 15s 超时)。目标与消息先按渠道的
273
- * `features` 调整(不支持卡片的退回为文本、不支持话题的去掉 threadId,Ruling A33,见 features.ts)。出站投递任务在一次任务内复用它;
274
- * `redact` 按该连接的密钥打码(插件异常信息写进 `last_error` 前使用)。
274
+ * The outbound session: decrypts the connection config once, then sends / edits messages through
275
+ * the extension (15 s per call; `sendFile` 120 s). Targets and messages are first adapted to the
276
+ * channel's `features` (cards become text without card support, `threadId` is dropped without
277
+ * threads, Ruling A33, see features.ts). A delivery job reuses it for the whole job; `redact`
278
+ * masks the connection's secrets (applied to extension errors before they go to `last_error`).
279
+ * `sendFile` is present iff the extension implements it and declares `features.files`.
275
280
  */
276
281
  outbound(connectionId: string): Promise<ChannelOutboundSession>;
277
282
  /**
@@ -283,7 +288,7 @@ export declare class ChannelConnections implements OnApplicationShutdown {
283
288
  messageId: string;
284
289
  }>;
285
290
  }
286
- /** {@link ChannelConnections.outbound} 的返回值。 */
291
+ /** What {@link ChannelConnections.outbound} returns. */
287
292
  export interface ChannelOutboundSession {
288
293
  row: ChannelConnectionRow;
289
294
  features: Channel["features"];
@@ -296,6 +301,14 @@ export interface ChannelOutboundSession {
296
301
  send(target: ChannelTarget, message: OutboundMessage, idempotencyKey?: string, locale?: ChannelLocale): Promise<{
297
302
  messageId: string;
298
303
  }>;
304
+ /**
305
+ * One file as one message (channel file delivery spec §4.1); present iff the extension implements
306
+ * `sendFile` and declares `features.files`. The target loses `threadId` without threads; the key
307
+ * and `locale` as for `send`.
308
+ */
309
+ sendFile?: (target: ChannelTarget, file: ChannelFile, idempotencyKey?: string, locale?: ChannelLocale) => Promise<{
310
+ messageId?: string;
311
+ }>;
299
312
  /** Called only when `features.edit` is true; `locale` as for `send`. */
300
313
  update(target: ChannelTarget, messageId: string, message: OutboundMessage, idempotencyKey?: string, locale?: ChannelLocale): Promise<void>;
301
314
  }
@@ -32,7 +32,7 @@ import { createRedactor } from "../log.js";
32
32
  import { isForbiddenAddress, isLoopbackHost, normalizeHost } from "../net/public-address.js";
33
33
  import { OrgLock } from "../orgs/org-lock.js";
34
34
  import { readOrgSettings } from "../orgs/settings.service.js";
35
- import { adaptToFeatures } from "./features.js";
35
+ import { adaptTarget, adaptToFeatures } from "./features.js";
36
36
  import { ChannelJobs } from "./jobs.js";
37
37
  import { webhookBase, webhookUrlOf } from "./webhook-url.js";
38
38
  /**
@@ -70,8 +70,10 @@ export const CHANNEL_CHANGED_TOPIC = "channel.changed";
70
70
  /** Redis:连接失败后的退避标记与连续失败次数(任一副本都据此决定何时重试)。 */
71
71
  export const channelBackoffKey = (id) => `capk:channel-backoff:${id}`;
72
72
  export const channelFailsKey = (id) => `capk:channel-fails:${id}`;
73
- /** 调用插件 verify / send 的时限。 */
73
+ /** The time limit of an extension's verify / send call. */
74
74
  const PLUGIN_CALL_TIMEOUT_MS = 15_000;
75
+ /** The time limit of an extension's `sendFile` call, and of reading the file before it. */
76
+ export const FILE_CALL_TIMEOUT_MS = 120_000;
75
77
  const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
76
78
  function setDeep(obj, path, value) {
77
79
  const segs = path.split(".");
@@ -817,16 +819,30 @@ let ChannelConnections = class ChannelConnections {
817
819
  return { row, channel, config, inflight: entry.inflight };
818
820
  }
819
821
  /**
820
- * 出站会话:解密一次连接配置,之后经插件发 / 改消息(每次调用 15s 超时)。目标与消息先按渠道的
821
- * `features` 调整(不支持卡片的退回为文本、不支持话题的去掉 threadId,Ruling A33,见 features.ts)。出站投递任务在一次任务内复用它;
822
- * `redact` 按该连接的密钥打码(插件异常信息写进 `last_error` 前使用)。
822
+ * The outbound session: decrypts the connection config once, then sends / edits messages through
823
+ * the extension (15 s per call; `sendFile` 120 s). Targets and messages are first adapted to the
824
+ * channel's `features` (cards become text without card support, `threadId` is dropped without
825
+ * threads, Ruling A33, see features.ts). A delivery job reuses it for the whole job; `redact`
826
+ * masks the connection's secrets (applied to extension errors before they go to `last_error`).
827
+ * `sendFile` is present iff the extension implements it and declares `features.files`.
823
828
  */
824
829
  async outbound(connectionId) {
825
830
  const { row, channel, config } = await this.runtime(connectionId);
826
831
  // the language handed to the extension with each send / update (Ruling A22): the recipient's
827
832
  // when the caller gives it (IM language is per person, run context spec §3.4), else the org's
828
833
  const { locale } = await readOrgSettings(this.db.db, row.orgId);
834
+ const sendFile = channel.features.files !== undefined ? channel.sendFile : undefined;
829
835
  return {
836
+ ...(sendFile !== undefined && {
837
+ sendFile: (target, file, idempotencyKey, to = locale) => sendFile.call(channel, {
838
+ config,
839
+ target: adaptTarget(channel.features, target),
840
+ file,
841
+ signal: AbortSignal.timeout(FILE_CALL_TIMEOUT_MS),
842
+ locale: to,
843
+ ...(idempotencyKey !== undefined && { idempotencyKey }),
844
+ }),
845
+ }),
830
846
  row,
831
847
  features: channel.features,
832
848
  redact: createRedactor(secretValues(channel.connectionSchema, config), 4),
@@ -1,4 +1,6 @@
1
1
  import { type Channel, type ChannelTarget, type OutboundMessage } from "@capybara-hq/plugin-sdk";
2
+ /** `threads: false`: the target loses its `threadId` (the platform has no threads). */
3
+ export declare function adaptTarget(features: Channel["features"], target: ChannelTarget): ChannelTarget;
2
4
  /**
3
5
  * 按渠道声明的 `features` 调整交给插件的目标与消息(Ruling A33),出站投递与入站回复都经过这里:
4
6
  * - `cards: false`:每张卡片按 `renderCardAsText(card, locale)` 退回为文本,以空行分隔拼在正文之后,
@@ -1,4 +1,12 @@
1
1
  import { renderCardAsText, } from "@capybara-hq/plugin-sdk";
2
+ /** `threads: false`: the target loses its `threadId` (the platform has no threads). */
3
+ export function adaptTarget(features, target) {
4
+ if (!features.threads && target.threadId !== undefined) {
5
+ const { threadId: _drop, ...rest } = target;
6
+ return rest;
7
+ }
8
+ return target;
9
+ }
2
10
  /**
3
11
  * 按渠道声明的 `features` 调整交给插件的目标与消息(Ruling A33),出站投递与入站回复都经过这里:
4
12
  * - `cards: false`:每张卡片按 `renderCardAsText(card, locale)` 退回为文本,以空行分隔拼在正文之后,
@@ -7,11 +15,7 @@ import { renderCardAsText, } from "@capybara-hq/plugin-sdk";
7
15
  * 其余原样返回。
8
16
  */
9
17
  export function adaptToFeatures(features, target, message, locale) {
10
- let t = target;
11
- if (!features.threads && target.threadId !== undefined) {
12
- const { threadId: _drop, ...rest } = target;
13
- t = rest;
14
- }
18
+ const t = adaptTarget(features, target);
15
19
  let m = message;
16
20
  if (!features.cards && message.cards !== undefined) {
17
21
  const { cards, ...rest } = message;
@@ -0,0 +1,74 @@
1
+ import { type Channel, type ObjectStore } from "@capybara-hq/plugin-sdk";
2
+ import type { ConversationEvent } from "../conversations/events.js";
3
+ import { type ChannelLocale } from "./phrases.js";
4
+ type ArtifactPayload = Extract<ConversationEvent, {
5
+ type: "artifact_created";
6
+ }>["payload"];
7
+ /** How one conversation file reaches an IM chat. */
8
+ export type FileDeliveryPlan = {
9
+ mode: "native";
10
+ kind: "image" | "file";
11
+ cap: number;
12
+ } | {
13
+ mode: "link";
14
+ reason: "unsupported" | "disabled" | "too_large" | "empty" | "foreign_key";
15
+ };
16
+ /**
17
+ * Decides native upload or a link line for one artifact. Order: a key outside the conversation's
18
+ * `artifacts/<conversationId>/` prefix, an empty file, a channel without `sendFile`, the deployment
19
+ * switch (`fileMaxBytes` 0), then the size cap (the smaller of the channel's and the deployment's).
20
+ */
21
+ export declare function planFileDelivery(input: {
22
+ conversationId: string;
23
+ artifact: Pick<ArtifactPayload, "objectKey" | "size" | "contentType">;
24
+ features: Channel["features"];
25
+ canSendFile: boolean;
26
+ fileMaxBytes: number;
27
+ }): FileDeliveryPlan;
28
+ /** An image iff the content type is a supported raster type and the size fits the image limit. */
29
+ export declare function fileKind(contentType: string, size: number, files: NonNullable<Channel["features"]["files"]>): "image" | "file";
30
+ /**
31
+ * The name handed to a plugin: the model chooses file names, so control characters become spaces
32
+ * and path separators `_`, the length is capped, and an empty result is `file`. The link and root
33
+ * lines show the original name (through `asCode`).
34
+ */
35
+ export declare function pluginFileName(name: string): string;
36
+ /** `512 B`, `1.5 KB`, `2.3 MB`, `1.0 GB` (1024-based). */
37
+ export declare function formatFileSize(bytes: number): string;
38
+ /** The one line that stands in for a file that is not sent natively. */
39
+ export declare function fileLinkText(input: {
40
+ name: string;
41
+ size: number;
42
+ artifactId: string;
43
+ conversationId: string;
44
+ base: string | undefined;
45
+ locale: ChannelLocale;
46
+ }): string;
47
+ /** The root message text of a native file delivery. */
48
+ export declare function fileRootText(name: string, locale: ChannelLocale): string;
49
+ export type CappedRead = {
50
+ kind: "ok";
51
+ data: Uint8Array;
52
+ } | {
53
+ kind: "missing";
54
+ } | {
55
+ kind: "too_large";
56
+ } | {
57
+ kind: "unavailable";
58
+ };
59
+ /**
60
+ * Reads an object into memory, never more than `cap` bytes: a larger head, or a body that passes
61
+ * `cap` while streaming, is `too_large` (the body is cancelled). A missing object is `missing`, a
62
+ * store that is not there `unavailable`; any other error is rethrown (retryable).
63
+ */
64
+ export declare function readArtifactCapped(store: ObjectStore, key: string, cap: number, signal: AbortSignal): Promise<CappedRead>;
65
+ /** A counting semaphore with a FIFO of waiters; one per worker replica (not a provider). */
66
+ export declare class FileSlots {
67
+ private free;
68
+ private readonly waiters;
69
+ constructor(limit: number);
70
+ /** Resolves with a release function; rejects with `signal.reason` when aborted while waiting. */
71
+ acquire(signal: AbortSignal): Promise<() => void>;
72
+ private releaser;
73
+ }
74
+ export {};
@@ -0,0 +1,176 @@
1
+ import { asCode, IMAGE_MEDIA_TYPES } from "@capybara-hq/plugin-sdk";
2
+ import { isStorageUnavailable } from "../storage/storage.service.js";
3
+ import { conversationUrl } from "./cards.js";
4
+ import { phrase } from "./phrases.js";
5
+ /**
6
+ * Decides native upload or a link line for one artifact. Order: a key outside the conversation's
7
+ * `artifacts/<conversationId>/` prefix, an empty file, a channel without `sendFile`, the deployment
8
+ * switch (`fileMaxBytes` 0), then the size cap (the smaller of the channel's and the deployment's).
9
+ */
10
+ export function planFileDelivery(input) {
11
+ const { artifact, features, fileMaxBytes } = input;
12
+ if (!artifact.objectKey.startsWith(`artifacts/${input.conversationId}/`)) {
13
+ return { mode: "link", reason: "foreign_key" };
14
+ }
15
+ if (artifact.size === 0)
16
+ return { mode: "link", reason: "empty" };
17
+ const files = features.files;
18
+ if (!input.canSendFile || !validFiles(files))
19
+ return { mode: "link", reason: "unsupported" };
20
+ if (fileMaxBytes === 0)
21
+ return { mode: "link", reason: "disabled" };
22
+ const cap = Math.min(files.maxBytes, fileMaxBytes);
23
+ if (artifact.size > cap)
24
+ return { mode: "link", reason: "too_large" };
25
+ return { mode: "native", kind: fileKind(artifact.contentType, artifact.size, files), cap };
26
+ }
27
+ function positive(n) {
28
+ return typeof n === "number" && Number.isFinite(n) && n > 0;
29
+ }
30
+ /** A declaration with a finite positive `maxBytes`; anything else is no native file support. */
31
+ function validFiles(files) {
32
+ return files !== undefined && positive(files.maxBytes);
33
+ }
34
+ /** An image iff the content type is a supported raster type and the size fits the image limit. */
35
+ export function fileKind(contentType, size, files) {
36
+ const type = (contentType.split(";")[0] ?? "").trim().toLowerCase();
37
+ const isImage = IMAGE_MEDIA_TYPES.includes(type);
38
+ return isImage && size <= (positive(files.imageMaxBytes) ? files.imageMaxBytes : files.maxBytes)
39
+ ? "image"
40
+ : "file";
41
+ }
42
+ const MAX_PLUGIN_FILE_NAME = 200;
43
+ /**
44
+ * The name handed to a plugin: the model chooses file names, so control characters become spaces
45
+ * and path separators `_`, the length is capped, and an empty result is `file`. The link and root
46
+ * lines show the original name (through `asCode`).
47
+ */
48
+ export function pluginFileName(name) {
49
+ const clean = name
50
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: stripping control characters is the point
51
+ .replace(/[\u0000-\u001f\u007f-\u009f]/g, " ")
52
+ .replace(/ {2,}/g, " ")
53
+ .replace(/[\\/]/g, "_")
54
+ .trim();
55
+ const capped = Array.from(clean).slice(0, MAX_PLUGIN_FILE_NAME).join("").trim();
56
+ return capped === "" ? "file" : capped;
57
+ }
58
+ /** `512 B`, `1.5 KB`, `2.3 MB`, `1.0 GB` (1024-based). */
59
+ export function formatFileSize(bytes) {
60
+ if (bytes < 1024)
61
+ return `${bytes} B`;
62
+ const units = ["KB", "MB", "GB"];
63
+ let v = bytes / 1024;
64
+ let i = 0;
65
+ // A value that rounds up to 1024.0 is shown in the next unit
66
+ while (Number(v.toFixed(1)) >= 1024 && i < units.length - 1) {
67
+ v /= 1024;
68
+ i++;
69
+ }
70
+ return `${v.toFixed(1)} ${units[i]}`;
71
+ }
72
+ function fill(template, values) {
73
+ return template.replace(/\{(name|size|url)\}/g, (_, k) => values[k]);
74
+ }
75
+ /** The one line that stands in for a file that is not sent natively. */
76
+ export function fileLinkText(input) {
77
+ const name = asCode(input.name);
78
+ const size = formatFileSize(input.size);
79
+ if (input.base === undefined) {
80
+ return fill(phrase("fileOnWebNoLink", input.locale), { name, size, url: "" });
81
+ }
82
+ const url = `${conversationUrl(input.base, input.conversationId)}#file=${input.artifactId}`;
83
+ return fill(phrase("fileOnWeb", input.locale), { name, size, url });
84
+ }
85
+ /** The root message text of a native file delivery. */
86
+ export function fileRootText(name, locale) {
87
+ return fill(phrase("fileRoot", locale), { name: asCode(name), size: "", url: "" });
88
+ }
89
+ /**
90
+ * Reads an object into memory, never more than `cap` bytes: a larger head, or a body that passes
91
+ * `cap` while streaming, is `too_large` (the body is cancelled). A missing object is `missing`, a
92
+ * store that is not there `unavailable`; any other error is rethrown (retryable).
93
+ */
94
+ export async function readArtifactCapped(store, key, cap, signal) {
95
+ try {
96
+ const got = await store.get(key, { signal });
97
+ if (got === null)
98
+ return { kind: "missing" };
99
+ const reader = got.body.getReader();
100
+ try {
101
+ if (got.head.size > cap)
102
+ return { kind: "too_large" };
103
+ const chunks = [];
104
+ let total = 0;
105
+ for (;;) {
106
+ const { done, value } = await reader.read();
107
+ if (done)
108
+ break;
109
+ total += value.length;
110
+ if (total > cap)
111
+ return { kind: "too_large" };
112
+ chunks.push(value);
113
+ }
114
+ const data = new Uint8Array(total);
115
+ let off = 0;
116
+ for (const c of chunks) {
117
+ data.set(c, off);
118
+ off += c.length;
119
+ }
120
+ return { kind: "ok", data };
121
+ }
122
+ finally {
123
+ // A no-op after a complete read; cancels the body on every early exit and on a failed read
124
+ await reader.cancel().catch(() => undefined);
125
+ }
126
+ }
127
+ catch (e) {
128
+ if (isStorageUnavailable(e))
129
+ return { kind: "unavailable" };
130
+ throw e;
131
+ }
132
+ }
133
+ /** A counting semaphore with a FIFO of waiters; one per worker replica (not a provider). */
134
+ export class FileSlots {
135
+ free;
136
+ waiters = [];
137
+ constructor(limit) {
138
+ this.free = limit;
139
+ }
140
+ /** Resolves with a release function; rejects with `signal.reason` when aborted while waiting. */
141
+ async acquire(signal) {
142
+ signal.throwIfAborted();
143
+ if (this.free > 0) {
144
+ this.free--;
145
+ return this.releaser();
146
+ }
147
+ await new Promise((resolve, reject) => {
148
+ const onAbort = () => {
149
+ const i = this.waiters.indexOf(wake);
150
+ if (i >= 0)
151
+ this.waiters.splice(i, 1);
152
+ reject(signal.reason);
153
+ };
154
+ const wake = () => {
155
+ signal.removeEventListener("abort", onAbort);
156
+ resolve();
157
+ };
158
+ this.waiters.push(wake);
159
+ signal.addEventListener("abort", onAbort, { once: true });
160
+ });
161
+ return this.releaser();
162
+ }
163
+ releaser() {
164
+ let released = false;
165
+ return () => {
166
+ if (released)
167
+ return;
168
+ released = true;
169
+ const next = this.waiters.shift();
170
+ if (next)
171
+ next();
172
+ else
173
+ this.free++;
174
+ };
175
+ }
176
+ }
@@ -8,6 +8,7 @@ import { TransactionHost } from "../infra/database/transaction-host.js";
8
8
  import { ConversationLock } from "../runtime/conversation-lock.js";
9
9
  import type { StreamBus } from "../runtime/stream.js";
10
10
  import { ScheduledTasksService } from "../schedules/scheduled-tasks.service.js";
11
+ import { StorageService } from "../storage/storage.service.js";
11
12
  import { ApprovalsService } from "../tools/approvals.service.js";
12
13
  import { QuestionsService } from "../tools/questions.service.js";
13
14
  import { ToolRegistry } from "../tools/registry.js";
@@ -99,7 +100,9 @@ export declare class ChannelOutbound {
99
100
  /** 入站任务的处理(worker 上执行 `ChannelInbound.handle`);失败抛错由 BullMQ 重试。 */
100
101
  inbound: Pick<ChannelInbound, "handle">, jobs: Pick<ChannelJobs, "enqueue" | "resumeConnection">, config: Pick<KernelConfigService, "get">, log: Pick<Logger, "error" | "warn" | "info">, txHost: TransactionHost,
101
102
  /** Pauses the task of a scheduled run whose chat is gone (scheduled tasks spec §8). */
102
- schedules: Pick<ScheduledTasksService, "pauseFor">);
103
+ schedules: Pick<ScheduledTasksService, "pauseFor">,
104
+ /** Conversation files sent into the chat (channel file delivery spec §4.2). */
105
+ storage: Pick<StorageService, "kernel">);
103
106
  /**
104
107
  * Starts consuming (worker role only): `worker` is the `@Processor` worker of the channel queue
105
108
  * (its job lock and stalled detection follow the run queue's config).
@@ -129,8 +132,8 @@ export declare class ChannelOutbound {
129
132
  private lastSeq;
130
133
  /** 日志比 `seen` 更新时再排一个任务。 */
131
134
  private followUp;
132
- /** 不可重试(或重试用尽)的发送失败:记连接 `last_error`(已打码)。 */
133
- private recordError;
135
+ /** A non-retryable (or finally failed) send: the connection's `last_error` (already redacted). */
136
+ recordError(connectionId: string, message: string): Promise<void>;
134
137
  /**
135
138
  * 推进 `last_seq`(同一事务记下草稿 / 卡片消息 id,清零失败计数)。以「仍是 `persisted`」为条件:
136
139
  * 被别人推进过(投递锁丢失后另一实例接手)返回 false,什么都不写。