@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
@@ -22,11 +22,13 @@ import { Transactional } from "../infra/database/transactional.decorator.js";
22
22
  import { KERNEL_BUS, KERNEL_LOGGER } from "../infra/tokens.js";
23
23
  import { ConversationLock, } from "../runtime/conversation-lock.js";
24
24
  import { ScheduledTasksService } from "../schedules/scheduled-tasks.service.js";
25
+ import { StorageService } from "../storage/storage.service.js";
25
26
  import { ApprovalsService } from "../tools/approvals.service.js";
26
27
  import { QuestionsService } from "../tools/questions.service.js";
27
28
  import { ToolRegistry } from "../tools/registry.js";
28
29
  import { approvalCard, cardMessage, connectUrl, conversationUrl, questionCard, webBase, } from "./cards.js";
29
- import { ChannelConnections } from "./connections.service.js";
30
+ import { ChannelConnections, FILE_CALL_TIMEOUT_MS, } from "./connections.service.js";
31
+ import { FileSlots, fileKind, fileLinkText, fileRootText, planFileDelivery, pluginFileName, readArtifactCapped, } from "./file-delivery.js";
30
32
  import { ChannelInbound } from "./inbound.js";
31
33
  import { ChannelJobs, INBOUND_JOB, idempotencyKey, RESUME_JOB, } from "./jobs.js";
32
34
  import { phrase } from "./phrases.js";
@@ -88,6 +90,10 @@ class RetryableDeliveryError extends Error {
88
90
  class DeliveryLostError extends Error {
89
91
  name = "DeliveryLostError";
90
92
  }
93
+ /** The replica stops while a delivery waits for a file slot: the job is handed back as it is. */
94
+ class DeliveryShutdownError extends Error {
95
+ name = "DeliveryShutdownError";
96
+ }
91
97
  const errMsg = (e) => (e instanceof Error ? e.message : String(e));
92
98
  /** 编辑草稿被平台不可重试地拒绝(凭据失效、目标已不存在除外:那两种改发新消息同样会失败)。 */
93
99
  const editRejected = (e) => isChannelSendError(e) && !e.retryable && e.reason !== "auth" && e.reason !== "target_gone";
@@ -177,7 +183,9 @@ let ChannelOutbound = class ChannelOutbound {
177
183
  /** 入站任务的处理(worker 上执行 `ChannelInbound.handle`);失败抛错由 BullMQ 重试。 */
178
184
  inbound, jobs, config, log, txHost,
179
185
  /** Pauses the task of a scheduled run whose chat is gone (scheduled tasks spec §8). */
180
- schedules) {
186
+ schedules,
187
+ /** Conversation files sent into the chat (channel file delivery spec §4.2). */
188
+ storage) {
181
189
  this.kdb = kdb;
182
190
  this.inbound = inbound;
183
191
  this.jobs = jobs;
@@ -198,6 +206,9 @@ let ChannelOutbound = class ChannelOutbound {
198
206
  questions,
199
207
  config,
200
208
  log,
209
+ storage,
210
+ // one per process: it bounds this replica's memory (not shared state)
211
+ fileSlots: new FileSlots(config.get().channels.fileConcurrency),
201
212
  writes: this,
202
213
  };
203
214
  }
@@ -371,7 +382,7 @@ let ChannelOutbound = class ChannelOutbound {
371
382
  if (last !== undefined && last > seen)
372
383
  await this.jobs.enqueue(conversationId, { followUp: true });
373
384
  }
374
- /** 不可重试(或重试用尽)的发送失败:记连接 `last_error`(已打码)。 */
385
+ /** A non-retryable (or finally failed) send: the connection's `last_error` (already redacted). */
375
386
  async recordError(connectionId, message) {
376
387
  const text = `delivery failed: ${message}`.slice(0, MAX_ERROR_CHARS);
377
388
  this.log.warn("channel delivery failed", { connectionId, error: text });
@@ -510,7 +521,8 @@ ChannelOutbound = __decorate([
510
521
  __param(10, Inject(KernelConfigService)),
511
522
  __param(11, Inject(KERNEL_LOGGER)),
512
523
  __param(12, Inject(TransactionHost)),
513
- __param(13, Inject(ScheduledTasksService))
524
+ __param(13, Inject(ScheduledTasksService)),
525
+ __param(14, Inject(StorageService))
514
526
  ], ChannelOutbound);
515
527
  export { ChannelOutbound };
516
528
  /** 一次投递任务(本进程持有):订阅、补读、草稿节流。 */
@@ -622,6 +634,8 @@ class Delivery {
622
634
  catch (err) {
623
635
  if (err instanceof DeliveryLostError)
624
636
  return { kind: "lost" };
637
+ if (err instanceof DeliveryShutdownError)
638
+ return { kind: "shutdown" };
625
639
  if (isChannelSendError(err) && !err.retryable) {
626
640
  const message = this.redact(errMsg(err));
627
641
  // Ruling A22:机器人被移出群 / 会话不存在 → 停止本轮,不计毒事件(不是连接的问题,不记 last_error)
@@ -975,6 +989,8 @@ class Delivery {
975
989
  return;
976
990
  await this.send({ text: phrase("runFailed", this.locale) }, this.key(e.seq));
977
991
  return this.advance(e.seq);
992
+ case "artifact_created":
993
+ return this.deliverArtifact(e);
978
994
  case "run_aborted":
979
995
  // 中止时还挂着的草稿:加「已停止」并清掉,避免下一次回复去编辑它
980
996
  await this.closeDraft(e.seq, "stopped");
@@ -1000,6 +1016,142 @@ class Delivery {
1000
1016
  const { messageId } = await this.send(cardMessage(card.title, card), this.key(seq));
1001
1017
  return this.advance(seq, { card: { kind: "approval", id: card.id, messageId } });
1002
1018
  }
1019
+ /**
1020
+ * A conversation file (channel file delivery spec §4.2-§4.5): sent into the target as a native
1021
+ * file or image when the channel can take it, else as one link line. The object is read under the
1022
+ * connection's org within the cap (the stored size is authoritative); a missing object, an
1023
+ * unavailable store and a platform `too_large` / `rejected` (or a non-retryable failure without
1024
+ * a reason) become the link line, so the event is delivered and never counts towards poisoning;
1025
+ * `rejected` and no reason also record `last_error`. `auth`, `target_gone` and retryable failures
1026
+ * go to `run()` as for text. A scheduled group run whose first post is this file gets a text root
1027
+ * first (`sendFile` need not return a message id to bind the thread to).
1028
+ */
1029
+ async deliverArtifact(e) {
1030
+ const a = e.payload;
1031
+ const plan = planFileDelivery({
1032
+ conversationId: this.conversationId,
1033
+ artifact: a,
1034
+ features: this.s.features,
1035
+ canSendFile: this.s.sendFile !== undefined,
1036
+ fileMaxBytes: this.d.config.get().channels.fileMaxBytes,
1037
+ });
1038
+ if (plan.mode === "link") {
1039
+ if (plan.reason === "foreign_key") {
1040
+ this.d.log.warn("channel file outside the conversation's artifacts sent as a link", {
1041
+ conversationId: this.conversationId,
1042
+ seq: e.seq,
1043
+ });
1044
+ }
1045
+ return this.linkLine(e.seq, a);
1046
+ }
1047
+ let release;
1048
+ try {
1049
+ release = await this.d.fileSlots.acquire(this.stopping);
1050
+ }
1051
+ catch (err) {
1052
+ // stopping while waiting for a slot: hand the job back (another replica resumes it)
1053
+ if (this.stopping.aborted)
1054
+ throw new DeliveryShutdownError();
1055
+ throw err;
1056
+ }
1057
+ let sent;
1058
+ try {
1059
+ sent = await this.sendNative(e.seq, a, plan);
1060
+ }
1061
+ finally {
1062
+ release();
1063
+ }
1064
+ if (!sent)
1065
+ return this.linkLine(e.seq, a);
1066
+ return this.advance(e.seq);
1067
+ }
1068
+ /**
1069
+ * Reads and sends one file while holding a file slot; false when the link line stands in for it
1070
+ * (see {@link deliverArtifact}).
1071
+ */
1072
+ async sendNative(seq, a, plan) {
1073
+ // the replica stopped while this delivery waited for its slot: hand the job back untouched
1074
+ if (this.stopping.aborted)
1075
+ throw new DeliveryShutdownError();
1076
+ if (this.lease.lost)
1077
+ throw new DeliveryLostError();
1078
+ const sendFile = this.s.sendFile;
1079
+ const files = this.s.features.files;
1080
+ // cannot happen: the plan is `native` only when both exist (narrows the types)
1081
+ if (sendFile === undefined || files === undefined)
1082
+ return false;
1083
+ let read;
1084
+ try {
1085
+ // the read stops with the replica: nothing has reached the platform yet
1086
+ read = await readArtifactCapped(this.d.storage.kernel(this.s.row.orgId), a.objectKey, plan.cap, AbortSignal.any([this.stopping, AbortSignal.timeout(FILE_CALL_TIMEOUT_MS)]));
1087
+ }
1088
+ catch (err) {
1089
+ if (this.stopping.aborted)
1090
+ throw new DeliveryShutdownError();
1091
+ throw err;
1092
+ }
1093
+ if (this.stopping.aborted)
1094
+ throw new DeliveryShutdownError();
1095
+ if (read.kind !== "ok") {
1096
+ const meta = { conversationId: this.conversationId, seq, reason: read.kind };
1097
+ if (read.kind === "too_large")
1098
+ this.d.log.info("channel file over the cap sent as a link", meta);
1099
+ else
1100
+ this.d.log.warn("channel file unreadable, sent as a link", meta);
1101
+ return false;
1102
+ }
1103
+ if (this.threadPending) {
1104
+ await this.send({ text: fileRootText(a.name, this.locale) }, this.key(seq, "-root"));
1105
+ }
1106
+ const file = {
1107
+ name: pluginFileName(a.name),
1108
+ contentType: a.contentType,
1109
+ kind: fileKind(a.contentType, read.data.byteLength, files),
1110
+ data: read.data,
1111
+ };
1112
+ // As before a card send (recordCard): a read of up to 120 s can outlast the lease; a new holder
1113
+ // then delivers this event, so do not post the file a second time
1114
+ if (this.lease.lost)
1115
+ throw new DeliveryLostError();
1116
+ try {
1117
+ // Not aborted on shutdown: an upload cut off midway may already have reached the platform,
1118
+ // and the retry posts it again on platforms without idempotent uploads (Slack, Telegram).
1119
+ // It finishes or times out (FILE_CALL_TIMEOUT_MS); one longer than the stop budget is
1120
+ // abandoned with the process and comes back by stalled detection, the window spec §4.6
1121
+ // accepts for a crash between send and advance.
1122
+ await sendFile(this.target, file, this.key(seq), this.locale);
1123
+ }
1124
+ catch (err) {
1125
+ if (!isChannelSendError(err) || err.retryable)
1126
+ throw err;
1127
+ if (err.reason === "too_large") {
1128
+ this.d.log.info("channel file refused as too large, sent as a link", {
1129
+ conversationId: this.conversationId,
1130
+ seq,
1131
+ });
1132
+ return false;
1133
+ }
1134
+ if (err.reason === "rejected" || err.reason === undefined) {
1135
+ await this.d.writes.recordError(this.s.row.id, this.redact(errMsg(err)));
1136
+ return false;
1137
+ }
1138
+ throw err;
1139
+ }
1140
+ return true;
1141
+ }
1142
+ /** The line standing in for a file that is not sent natively, then the advance past its event. */
1143
+ async linkLine(seq, a) {
1144
+ const text = fileLinkText({
1145
+ name: a.name,
1146
+ size: a.size,
1147
+ artifactId: a.artifactId,
1148
+ conversationId: this.conversationId,
1149
+ base: this.base,
1150
+ locale: this.locale,
1151
+ });
1152
+ await this.send({ text }, this.key(seq, "-link"));
1153
+ return this.advance(seq);
1154
+ }
1003
1155
  /**
1004
1156
  * Sends the (pending) question card of `questionId` for the event at `seq` (or the web hint). A
1005
1157
  * sub-agent's question (`child` = its conversation) links to the parent with the child open, as
@@ -207,6 +207,25 @@ export declare const CHANNEL_PHRASES: {
207
207
  readonly zh: "项目技能没有运行:这个智能体不能加载项目技能,请为它打开 Skill 工具。你的消息没有发送。";
208
208
  readonly en: "The project skill was not run: this agent cannot load project skills; turn on its Skill tool. Your message was not sent.";
209
209
  };
210
+ /** A conversation file too large (or not sendable) for the IM chat; `{name}` is already code. */
211
+ readonly fileOnWeb: {
212
+ readonly zh: "{name}({size})在网页会话里:{url}";
213
+ readonly en: "{name} ({size}) is in the web conversation: {url}";
214
+ };
215
+ /** The same without a web link (no public base URL configured). */
216
+ readonly fileOnWebNoLink: {
217
+ readonly zh: "{name}({size})已交付,请在网页上打开 Capybara 中的这个会话获取。";
218
+ readonly en: "{name} ({size}) was delivered; open the conversation in Capybara on the web to get it.";
219
+ };
220
+ /**
221
+ * The root message of a native file delivery (a scheduled group run's first post); `{name}` is
222
+ * already code. Neutral about the outcome: the platform may still refuse the file, and then the
223
+ * link line follows it.
224
+ */
225
+ readonly fileRoot: {
226
+ readonly zh: "文件 {name}:";
227
+ readonly en: "File {name}:";
228
+ };
210
229
  /** 运行被中止(收尾挂着的草稿时附在已有文本之后)。 */
211
230
  readonly runStopped: {
212
231
  readonly zh: "已停止。";
@@ -169,6 +169,22 @@ export const CHANNEL_PHRASES = {
169
169
  zh: "项目技能没有运行:这个智能体不能加载项目技能,请为它打开 Skill 工具。你的消息没有发送。",
170
170
  en: "The project skill was not run: this agent cannot load project skills; turn on its Skill tool. Your message was not sent.",
171
171
  },
172
+ /** A conversation file too large (or not sendable) for the IM chat; `{name}` is already code. */
173
+ fileOnWeb: {
174
+ zh: "{name}({size})在网页会话里:{url}",
175
+ en: "{name} ({size}) is in the web conversation: {url}",
176
+ },
177
+ /** The same without a web link (no public base URL configured). */
178
+ fileOnWebNoLink: {
179
+ zh: "{name}({size})已交付,请在网页上打开 Capybara 中的这个会话获取。",
180
+ en: "{name} ({size}) was delivered; open the conversation in Capybara on the web to get it.",
181
+ },
182
+ /**
183
+ * The root message of a native file delivery (a scheduled group run's first post); `{name}` is
184
+ * already code. Neutral about the outcome: the platform may still refuse the file, and then the
185
+ * link line follows it.
186
+ */
187
+ fileRoot: { zh: "文件 {name}:", en: "File {name}:" },
172
188
  /** 运行被中止(收尾挂着的草稿时附在已有文本之后)。 */
173
189
  runStopped: { zh: "已停止。", en: "Stopped." },
174
190
  /** 运行失败。 */
@@ -178,6 +178,8 @@ export declare const KernelConfigSchema: z.ZodObject<{
178
178
  deliveryIdleMs: z.ZodDefault<z.ZodNumber>;
179
179
  webhookBaseUrl: z.ZodOptional<z.ZodURL>;
180
180
  webhookMaxBodyBytes: z.ZodDefault<z.ZodNumber>;
181
+ fileMaxBytes: z.ZodDefault<z.ZodNumber>;
182
+ fileConcurrency: z.ZodDefault<z.ZodNumber>;
181
183
  }, z.core.$strict>>;
182
184
  storage: z.ZodDefault<z.ZodObject<{
183
185
  purgeDeletedOrgsAfterDays: z.ZodDefault<z.ZodNumber>;
@@ -1056,6 +1056,22 @@ export const KernelConfigSchema = z.strictObject({
1056
1056
  .meta(meta({
1057
1057
  description: "Largest channel webhook request body in bytes; a larger request is rejected with 413",
1058
1058
  })),
1059
+ fileMaxBytes: z
1060
+ .number()
1061
+ .int()
1062
+ .nonnegative()
1063
+ .default(20_971_520)
1064
+ .meta(meta({
1065
+ description: "Largest conversation file a channel delivery sends into the IM chat as a native file or image, in bytes; larger files, and every file when 0, become one line linking to the web conversation. Each worker replica holds at most fileConcurrency such files in memory at once",
1066
+ })),
1067
+ fileConcurrency: z
1068
+ .number()
1069
+ .int()
1070
+ .positive()
1071
+ .default(4)
1072
+ .meta(meta({
1073
+ description: "How many conversation files one worker replica reads and uploads to IM platforms at the same time; further file deliveries wait for a slot",
1074
+ })),
1059
1075
  })
1060
1076
  // 续租周期必须明显短于 TTL:至少能在租约过期前续两次,偶尔一次 Redis 抖动不至于丢租约
1061
1077
  .refine((c) => c.scanIntervalMs <= c.leaseTtlMs / 2, {
@@ -1070,6 +1086,8 @@ export const KernelConfigSchema = z.strictObject({
1070
1086
  deliveryConcurrency: 100,
1071
1087
  deliveryIdleMs: 15000,
1072
1088
  webhookMaxBodyBytes: 1_048_576,
1089
+ fileMaxBytes: 20_971_520,
1090
+ fileConcurrency: 4,
1073
1091
  }),
1074
1092
  storage: z
1075
1093
  .strictObject({
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The delivery scope (truthful delivery spec §2): the current run of a conversation after the
3
+ * person last spoke in it. The same bytes reach the user once per scope; this file holds the
4
+ * shapes and the pure repeat decision, {@link EventLog.readDeliveryScope} reads a scope.
5
+ */
6
+ /** An `artifact_created` event of the scope, as the repeat decision needs it. */
7
+ export interface ScopeArtifact {
8
+ seq: number;
9
+ artifactId: string;
10
+ name: string;
11
+ /** Absent on events written before the field existed: such an artifact never matches. */
12
+ sha256?: string;
13
+ sourcePath: string;
14
+ }
15
+ /** A run's delivery scope: its boundary seq and the artifacts delivered after it. */
16
+ export interface DeliveryScope {
17
+ /**
18
+ * The highest seq among the run's `user_message` events and `question_answered` events with
19
+ * outcome `answered` / `skipped`; the run's `run_started` seq when there is none.
20
+ */
21
+ boundary: number;
22
+ /** This scope's `artifact_created` events (seq above the boundary), in ascending seq. */
23
+ artifacts: ScopeArtifact[];
24
+ }
25
+ /**
26
+ * Whether a file with `sha256` from `sourcePath` repeats an artifact of the scope: with M the
27
+ * latest scope artifact with that hash and L the latest with that source path, the file repeats
28
+ * M when M exists and L does not come after M (so v1, v2, v1 of one path delivers v1 again).
29
+ * `lastOfSource` is L's seq (0 without one), part of the append's idempotency key.
30
+ */
31
+ export declare function findRepeat(scope: DeliveryScope, sha256: string, sourcePath: string): {
32
+ repeatOf: ScopeArtifact | null;
33
+ lastOfSource: number;
34
+ };
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The delivery scope (truthful delivery spec §2): the current run of a conversation after the
3
+ * person last spoke in it. The same bytes reach the user once per scope; this file holds the
4
+ * shapes and the pure repeat decision, {@link EventLog.readDeliveryScope} reads a scope.
5
+ */
6
+ /**
7
+ * Whether a file with `sha256` from `sourcePath` repeats an artifact of the scope: with M the
8
+ * latest scope artifact with that hash and L the latest with that source path, the file repeats
9
+ * M when M exists and L does not come after M (so v1, v2, v1 of one path delivers v1 again).
10
+ * `lastOfSource` is L's seq (0 without one), part of the append's idempotency key.
11
+ */
12
+ export function findRepeat(scope, sha256, sourcePath) {
13
+ let m = null;
14
+ let lastOfSource = 0;
15
+ for (const a of scope.artifacts) {
16
+ if (a.sha256 !== undefined && a.sha256 === sha256 && (m === null || a.seq > m.seq))
17
+ m = a;
18
+ if (a.sourcePath === sourcePath && a.seq > lastOfSource)
19
+ lastOfSource = a.seq;
20
+ }
21
+ const repeatOf = m !== null && !(lastOfSource > m.seq) ? m : null;
22
+ return { repeatOf, lastOfSource };
23
+ }
@@ -2,6 +2,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
2
2
  import { TransactionHost } from "../infra/database/transaction-host.js";
3
3
  import { OutboxService } from "../infra/outbox/outbox.service.js";
4
4
  import type { KernelLogger } from "../log.js";
5
+ import type { DeliveryScope } from "./delivery-scope.js";
5
6
  import { type ConversationEvent, type ConversationEventType } from "./events.js";
6
7
  /** 事件日志依赖的总线:内核 bus(命名空间 `kernel`)。 */
7
8
  export interface EventBus {
@@ -41,6 +42,8 @@ export declare const conversationTopic: (conversationId: string) => string;
41
42
  * - `compaction_progress`: a compaction of a run is running (context compaction spec §4.6), on that
42
43
  * run's own conversation's topic **only** (a child's compaction stays on the child's stream); the
43
44
  * SSE forwards the flat data as `event: compaction`. Ephemeral, display-only, not in the log.
45
+ * - `prompt_suggestion`: a completed run's prompt suggestion was stored (prompt suggestions spec
46
+ * §4, `PromptSuggestionStore`). Ephemeral, display-only, not in the log.
44
47
  */
45
48
  export type ConversationBusMessage = {
46
49
  kind: "events";
@@ -76,6 +79,12 @@ export type ConversationBusMessage = {
76
79
  chunks?: number;
77
80
  chars?: number;
78
81
  startedAt: number;
82
+ } | {
83
+ kind: "prompt_suggestion";
84
+ conversationId: string;
85
+ runId: string;
86
+ afterSeq: number;
87
+ text: string;
79
88
  };
80
89
  /**
81
90
  * What changed about a conversation outside its event log (UI refresh B): the SSE stream sends it as
@@ -148,6 +157,15 @@ export declare class EventLog {
148
157
  * 往前翻页读较早的运行时不扫更晚运行的事件。
149
158
  */
150
159
  readRunsAfter(conversationId: string, runIds: readonly string[], afterSeq: number, limit?: number): Promise<ConversationEvent[]>;
160
+ /**
161
+ * The delivery scope of `runId` in the conversation (truthful delivery spec §2 step 2): the run's
162
+ * `run_started` seq `S` through the run index (0 when the run has none), then one range read of
163
+ * the `user_message`, `question_answered` and `artifact_created` events from `S` on (a
164
+ * `user_message` carries no run id, so the run index cannot find it). The boundary is the highest
165
+ * seq of a `user_message` or of a `question_answered` answered / skipped, else `S`; the artifacts
166
+ * are the `artifact_created` events after it.
167
+ */
168
+ readDeliveryScope(conversationId: string, runId: string): Promise<DeliveryScope>;
151
169
  /** 按幂等键取事件;没有 → undefined。 */
152
170
  findByIdem(conversationId: string, idemKey: string): Promise<ConversationEvent | undefined>;
153
171
  /**
@@ -251,6 +251,60 @@ let EventLog = class EventLog {
251
251
  .execute();
252
252
  return rows.map(toEvent);
253
253
  }
254
+ /**
255
+ * The delivery scope of `runId` in the conversation (truthful delivery spec §2 step 2): the run's
256
+ * `run_started` seq `S` through the run index (0 when the run has none), then one range read of
257
+ * the `user_message`, `question_answered` and `artifact_created` events from `S` on (a
258
+ * `user_message` carries no run id, so the run index cannot find it). The boundary is the highest
259
+ * seq of a `user_message` or of a `question_answered` answered / skipped, else `S`; the artifacts
260
+ * are the `artifact_created` events after it.
261
+ */
262
+ async readDeliveryScope(conversationId, runId) {
263
+ const start = await this.db
264
+ .selectFrom("conversation_events")
265
+ .select("seq")
266
+ .where("conversation_id", "=", conversationId)
267
+ .where("run_id", "=", runId)
268
+ .where("type", "=", "run_started")
269
+ .orderBy("seq")
270
+ .limit(1)
271
+ .executeTakeFirst();
272
+ const s = start === undefined ? 0 : Number(start.seq);
273
+ const rows = await this.db
274
+ .selectFrom("conversation_events")
275
+ .select(["seq", "type", "payload"])
276
+ .where("conversation_id", "=", conversationId)
277
+ .where("seq", ">=", String(s))
278
+ .where("type", "in", ["user_message", "question_answered", "artifact_created"])
279
+ .orderBy("seq")
280
+ .execute();
281
+ let boundary = s;
282
+ for (const r of rows) {
283
+ const seq = Number(r.seq);
284
+ if (r.type === "user_message")
285
+ boundary = Math.max(boundary, seq);
286
+ else if (r.type === "question_answered") {
287
+ const outcome = r.payload.outcome;
288
+ if (outcome === "answered" || outcome === "skipped")
289
+ boundary = Math.max(boundary, seq);
290
+ }
291
+ }
292
+ const artifacts = [];
293
+ for (const r of rows) {
294
+ const seq = Number(r.seq);
295
+ if (r.type !== "artifact_created" || seq <= boundary)
296
+ continue;
297
+ const p = r.payload;
298
+ artifacts.push({
299
+ seq,
300
+ artifactId: p.artifactId,
301
+ name: p.name,
302
+ ...(p.sha256 !== undefined && { sha256: p.sha256 }),
303
+ sourcePath: p.sourcePath,
304
+ });
305
+ }
306
+ return { boundary, artifacts };
307
+ }
254
308
  /** 按幂等键取事件;没有 → undefined。 */
255
309
  async findByIdem(conversationId, idemKey) {
256
310
  const r = await this.db
@@ -907,6 +907,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
907
907
  compaction: "compaction";
908
908
  image: "image";
909
909
  review: "review";
910
+ suggestion: "suggestion";
910
911
  title: "title";
911
912
  web_fetch: "web_fetch";
912
913
  }>>;
@@ -1306,6 +1307,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1306
1307
  objectKey: z.ZodString;
1307
1308
  sourcePath: z.ZodString;
1308
1309
  callId: z.ZodString;
1310
+ sha256: z.ZodOptional<z.ZodString>;
1309
1311
  }, z.core.$strip>;
1310
1312
  }, z.core.$strip>, z.ZodObject<{
1311
1313
  type: z.ZodLiteral<"skills_catalog">;
@@ -839,14 +839,18 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
839
839
  * `review` = the command-review classifier's call (auto mode spec §5.3: not model-visible, billed
840
840
  * and reported, `callId` = the reviewed tool call); `image` = a `GenerateImage` call (image
841
841
  * generation spec §7: the tool call's run and step, `callId` = the call, `outputImages` = the
842
- * images produced; not model-visible, billed and reported, counted on a sub-agent's parent).
842
+ * images produced; not model-visible, billed and reported, counted on a sub-agent's parent);
843
+ * `suggestion` = the prompt suggestion call after a completed run (prompt suggestions spec §7: no
844
+ * run, `step` 0, one per run, not model-visible, billed and reported).
843
845
  */
844
846
  ev("usage", z.object({
845
847
  step: count,
846
848
  provider: z.string(),
847
849
  model: z.string(),
848
850
  ...ModelUsageShape,
849
- purpose: z.enum(["compaction", "title", "web_fetch", "review", "image"]).optional(),
851
+ purpose: z
852
+ .enum(["compaction", "title", "web_fetch", "review", "image", "suggestion"])
853
+ .optional(),
850
854
  /**
851
855
  * The chunk a chunked compaction call summarised (1-based), with the number of calls the
852
856
  * compaction attempted (the full chunk count on a completed one; on a failed or hook-denied
@@ -1155,6 +1159,15 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
1155
1159
  objectKey: z.string().min(1),
1156
1160
  sourcePath: z.string().min(1),
1157
1161
  callId: z.string(),
1162
+ /**
1163
+ * The hex sha256 of the bytes (truthful delivery spec §2): the same bytes are delivered once
1164
+ * per delivery scope. Optional only because earlier events cannot be backfilled; an event
1165
+ * without it never matches.
1166
+ */
1167
+ sha256: z
1168
+ .string()
1169
+ .regex(/^[0-9a-f]{64}$/)
1170
+ .optional(),
1158
1171
  })),
1159
1172
  /**
1160
1173
  * 本对话此刻生效的技能(M5 T14,Ruling M17):运行开始时内核解析生效的技能集合(agent 版本选中的组织技能 +
@@ -0,0 +1,95 @@
1
+ import type { ConversationSource, ModelInfo, ModelRequest } from "@capybara-hq/plugin-sdk";
2
+ import type { ConversationKind } from "../db/kernel-schema.js";
3
+ import { type CaseSnapshot } from "../evals/snapshot.js";
4
+ import type { MediaBytes, MediaInfo } from "../runtime/context/build.js";
5
+ import type { ConversationEvent, EventPayload } from "./events.js";
6
+ /**
7
+ * Prompt suggestions (spec 2026-11-19 §1, §2): the pure part of the side request sent after a
8
+ * completed web run. The request is the run's last request rebuilt through the eval zero-drift
9
+ * path, plus the final reply and {@link PROMPT_SUGGESTION_INSTRUCTION}; only the output cap and
10
+ * `purpose` change besides, so the provider's prompt cache serves the prefix.
11
+ */
12
+ /** The appended instruction (model-facing, English; spec §1.3). */
13
+ export declare const PROMPT_SUGGESTION_INSTRUCTION: string;
14
+ /** The side request's output cap ceiling (a cost ceiling, not a target; spec §1.4). */
15
+ export declare const PROMPT_SUGGESTION_MAX_OUTPUT_TOKENS = 2048;
16
+ /** Above this many input tokens with no cache activity on the last step, skip (spec §1.5). */
17
+ export declare const PROMPT_SUGGESTION_UNCACHED_INPUT_MAX = 8000;
18
+ /** A job that starts later than this after the run finished is stale (spec §1.5). */
19
+ export declare const PROMPT_SUGGESTION_MAX_DELAY_MS = 60000;
20
+ /** The side call's time limit (spec §1.6). */
21
+ export declare const PROMPT_SUGGESTION_TIMEOUT_MS = 60000;
22
+ /** The longest suggestion kept, in characters (code points; spec §1.7). */
23
+ export declare const PROMPT_SUGGESTION_MAX_CHARS = 200;
24
+ /** Why no side request is built for a run. */
25
+ export type SuggestionSkip = "no_model_call"
26
+ /** The resolved `model` is not the model of the run's last call. */
27
+ | "model_mismatch" | "no_final_reply" | "final_reply_has_tool_call" | "drift" | "fit" | "prefix_mismatch" | "too_large" | "uncached";
28
+ type ModelCallEvent = Extract<ConversationEvent, {
29
+ type: "model_call";
30
+ }>;
31
+ /** The run's last `model_call` (the highest seq with the run's id), or undefined. */
32
+ export declare function lastModelCallOf(events: readonly ConversationEvent[], runId: string): ModelCallEvent | undefined;
33
+ /**
34
+ * The side request, or why there is none (spec §1). `model` is the current info of the last
35
+ * call's provider and model as the caller resolved it for the org; `mediaInfo` / `media` come from
36
+ * `loadSnapshotMedia` for that call; `reserveTokens` is the org's compaction reserve.
37
+ *
38
+ * Checks, in order: the run has a `model_call` (`no_model_call`); `model` is that call's model
39
+ * (`model_mismatch`); the call carries no fit plan (`fit`); a final `assistant_message` follows
40
+ * the call (`no_final_reply`) without a `tool_call` block (`final_reply_has_tool_call`) and with
41
+ * text (`no_final_reply`); the run's last step usage shows cache activity or at most
42
+ * {@link PROMPT_SUGGESTION_UNCACHED_INPUT_MAX} input tokens (`uncached`); the baseline
43
+ * reconstruction of the call has no drift and the snapshot is valid (`drift`); the extension, the
44
+ * same inputs with every snapshot event up to the run's terminal event, keeps `model`, `system`,
45
+ * `tools`, `toolChoice`, `params` and the messages as a prefix, followed by exactly one assistant
46
+ * message, so only usage and the terminal event follow the final reply (`prefix_mismatch`); the
47
+ * estimate plus the cap fits `contextWindow - reserveTokens` (`too_large`). Never throws for a
48
+ * snapshot's content.
49
+ */
50
+ export declare function buildSuggestionRequest(input: {
51
+ snapshot: CaseSnapshot;
52
+ model: ModelInfo;
53
+ mediaInfo?: ReadonlyMap<string, MediaInfo>;
54
+ media?: ReadonlyMap<string, MediaBytes | null>;
55
+ reserveTokens: number;
56
+ }): {
57
+ request: ModelRequest;
58
+ lastCall: {
59
+ seq: number;
60
+ provider: string;
61
+ model: string;
62
+ };
63
+ finalText: string;
64
+ estimate: number;
65
+ } | {
66
+ skip: SuggestionSkip;
67
+ };
68
+ /** The run facts eligibility reads (spec §2, the first four rows). */
69
+ export interface SuggestionEligibilityInput {
70
+ /** `run_finished.reason`. */
71
+ outcome: EventPayload<"run_finished">["reason"];
72
+ /** `conversations.kind`. */
73
+ kind: ConversationKind;
74
+ /** `conversations.source`. */
75
+ source: ConversationSource;
76
+ /** `run_started.trigger` (absent = a person's message). */
77
+ trigger: EventPayload<"run_started">["trigger"];
78
+ }
79
+ /**
80
+ * Whether a finished run may get a suggestion by its outcome, conversation and trigger (spec §2):
81
+ * `completed` or `max_steps`, a `chat` conversation from `web`, not a scheduled or compact run.
82
+ * The final reply, freshness and the switches are checked elsewhere.
83
+ */
84
+ export declare function suggestionEligible(i: SuggestionEligibilityInput): boolean;
85
+ /**
86
+ * The suggestion from the model's reply text (spec §1.7), or null for none: the first non-empty
87
+ * line with control and hidden format characters removed, a leading user label (`User:`, or the
88
+ * Chinese word for user with a full-width colon, `LABEL_RE`) and balanced wrapping quotes
89
+ * stripped, trimmed, cut to {@link PROMPT_SUGGESTION_MAX_CHARS} code points.
90
+ * `NONE` (any case), an empty result or an echo of the final reply (`finalText`) is null.
91
+ */
92
+ export declare function cleanSuggestion(reply: string, finalText: string): string | null;
93
+ /** Whether the job is too late (`now - finishedAt > PROMPT_SUGGESTION_MAX_DELAY_MS`). */
94
+ export declare function suggestionStale(finishedAt: number, now: number): boolean;
95
+ export {};