@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
@@ -1,9 +1,11 @@
1
1
  import type { Logger } from "@capybara-hq/plugin-sdk";
2
2
  import { ConversationAccess } from "../conversations/access.js";
3
3
  import { EventLog } from "../conversations/event-log.js";
4
+ import { PromptSuggestionStore } from "../conversations/prompt-suggestion-store.js";
4
5
  import type { CredentialCheck } from "../identity/credential-check.js";
5
6
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
6
7
  import { GracefulShutdown } from "../infra/lifecycle/graceful-shutdown.service.js";
8
+ import { OrgSettingsService } from "../orgs/settings.service.js";
7
9
  import { type LiveDraft, RunDrafts } from "./run-drafts.js";
8
10
  /** 一次 SSE 连接的输出端(由 HTTP 层包装原始响应)。 */
9
11
  export interface SseOutput {
@@ -28,6 +30,10 @@ export interface ConversationStreamsDeps {
28
30
  log: Pick<Logger, "warn">;
29
31
  /** The live drafts of the conversation's running run (sent once, after the open catch-up). */
30
32
  drafts(conversationId: string): Promise<LiveDraft[]>;
33
+ /** The stored prompt suggestion of the conversation (the Redis key), freshness not applied. */
34
+ suggestions: Pick<PromptSuggestionStore, "get" | "delete" | "isFresh">;
35
+ /** Whether prompt suggestions are on for the org. */
36
+ suggestionsEnabled(orgId: string): Promise<boolean>;
31
37
  }
32
38
  export interface StreamParams {
33
39
  orgId: string;
@@ -63,7 +69,7 @@ export declare class ConversationStreams {
63
69
  * an event stream. Without `GracefulShutdown` (a standalone HTTP application, tests only) the
64
70
  * streams end with their connections.
65
71
  */
66
- constructor(eventLog: Pick<EventLog, "readAfter">, bus: StreamBus, access: Pick<ConversationAccess, "isAccessible">, config: Pick<KernelConfigService, "get">, log: Pick<Logger, "warn">, drafts: Pick<RunDrafts, "live">, shutdown?: Pick<GracefulShutdown, "signal">);
72
+ constructor(eventLog: Pick<EventLog, "readAfter">, bus: StreamBus, access: Pick<ConversationAccess, "isAccessible">, config: Pick<KernelConfigService, "get">, log: Pick<Logger, "warn">, drafts: Pick<RunDrafts, "live">, suggestions: Pick<PromptSuggestionStore, "get" | "delete" | "isFresh">, settings: Pick<OrgSettingsService, "promptSuggestionsEnabled">, shutdown?: Pick<GracefulShutdown, "signal">);
67
73
  /**
68
74
  * 复核凭据与可见性,并先订阅会话频道(之后再回放,避免遗漏两者之间提交的事件)。
69
75
  * 凭据失效 → 对应的 `auth.*`;不可见 → `conversation.not_found`;订阅失败照常抛出。此时尚未写任何响应,调用方可以按普通错误返回。
@@ -10,10 +10,12 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { Inject, Injectable, Optional } from "@nestjs/common";
11
11
  import { ConversationAccess } from "../conversations/access.js";
12
12
  import { CONVERSATION_CHANGES, conversationTopic, EventLog, } from "../conversations/event-log.js";
13
+ import { PROMPT_SUGGESTION_BUS_KIND, PromptSuggestionStore, } from "../conversations/prompt-suggestion-store.js";
13
14
  import { ApiError } from "../errors.js";
14
15
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
15
16
  import { GracefulShutdown } from "../infra/lifecycle/graceful-shutdown.service.js";
16
17
  import { KERNEL_BUS, KERNEL_LOGGER } from "../infra/tokens.js";
18
+ import { OrgSettingsService } from "../orgs/settings.service.js";
17
19
  import { isUiBusMessage, uiFrame } from "../ui/registry.js";
18
20
  import { RunDrafts } from "./run-drafts.js";
19
21
  /** 补读事件的分页大小。 */
@@ -61,10 +63,19 @@ function isBusMessage(m) {
61
63
  typeof x.startedAt === "number" &&
62
64
  (x.phase === "preparing" || x.phase === "summarizing" || x.phase === "writing"));
63
65
  }
66
+ if (k === PROMPT_SUGGESTION_BUS_KIND) {
67
+ const x = m;
68
+ return (typeof x.conversationId === "string" &&
69
+ typeof x.runId === "string" &&
70
+ typeof x.text === "string" &&
71
+ typeof x.afterSeq === "number" &&
72
+ Number.isInteger(x.afterSeq));
73
+ }
64
74
  return k === "delta" && typeof m.runId === "string";
65
75
  }
66
76
  const eventFrame = (e) => `id: ${e.seq}\nevent: event\ndata: ${JSON.stringify(e)}\n\n`;
67
77
  const draftFrame = (d) => `event: draft\ndata: ${JSON.stringify({ runId: d.runId, step: d.step, text: d.text, thinking: d.thinking })}\n\n`;
78
+ const suggestionFrame = (s) => `event: suggestion\ndata: ${JSON.stringify({ runId: s.runId, afterSeq: s.afterSeq, text: s.text })}\n\n`;
68
79
  /**
69
80
  * 会话事件流(SSE):本进程持有的连接集合,停机时一并关闭。
70
81
  * 跨副本的数据只经 PG(事件日志)与内核 bus(`conv.<id>`)流动,进程内只保存连接本身的资源
@@ -81,7 +92,7 @@ let ConversationStreams = class ConversationStreams {
81
92
  * an event stream. Without `GracefulShutdown` (a standalone HTTP application, tests only) the
82
93
  * streams end with their connections.
83
94
  */
84
- constructor(eventLog, bus, access, config, log, drafts, shutdown) {
95
+ constructor(eventLog, bus, access, config, log, drafts, suggestions, settings, shutdown) {
85
96
  this.d = {
86
97
  eventLog,
87
98
  bus,
@@ -89,6 +100,8 @@ let ConversationStreams = class ConversationStreams {
89
100
  config,
90
101
  log,
91
102
  drafts: (conversationId) => drafts.live(conversationId),
103
+ suggestions,
104
+ suggestionsEnabled: (orgId) => settings.promptSuggestionsEnabled(orgId),
92
105
  };
93
106
  if (shutdown?.signal.aborted)
94
107
  this.closeAll();
@@ -143,8 +156,10 @@ ConversationStreams = __decorate([
143
156
  __param(3, Inject(KernelConfigService)),
144
157
  __param(4, Inject(KERNEL_LOGGER)),
145
158
  __param(5, Inject(RunDrafts)),
146
- __param(6, Optional()),
147
- __param(6, Inject(GracefulShutdown))
159
+ __param(6, Inject(PromptSuggestionStore)),
160
+ __param(7, Inject(OrgSettingsService)),
161
+ __param(8, Optional()),
162
+ __param(8, Inject(GracefulShutdown))
148
163
  ], ConversationStreams);
149
164
  export { ConversationStreams };
150
165
  /**
@@ -191,6 +206,8 @@ class Connection {
191
206
  // live drafts (spec 2026-11-07 §3.2): after the catch-up, before any delta (deltas are queued
192
207
  // behind this); a delta also in the draft is dropped by the client by its offset
193
208
  this.enqueue(() => this.sendDrafts());
209
+ // the stored prompt suggestion (spec 2026-11-19 §4): last, once the client is caught up
210
+ this.enqueue(() => this.sendSuggestion());
194
211
  }
195
212
  async subscribe() {
196
213
  const un = await this.d.bus.subscribe(conversationTopic(this.p.conversationId), (m) => this.onMessage(m));
@@ -271,6 +288,12 @@ class Connection {
271
288
  this.enqueue(() => this.write(frame));
272
289
  return;
273
290
  }
291
+ if (m.kind === PROMPT_SUGGESTION_BUS_KIND) {
292
+ // a new prompt suggestion for this conversation: display-only, never in the log
293
+ // (the switch is checked by the job at write time; a frame racing a switch-off is harmless)
294
+ this.enqueue(() => this.write(suggestionFrame(m)));
295
+ return;
296
+ }
274
297
  const { kind: _kind, ...delta } = m;
275
298
  this.enqueue(() => this.write(`event: delta\ndata: ${JSON.stringify(delta)}\n\n`));
276
299
  }
@@ -322,6 +345,34 @@ class Connection {
322
345
  for (const d of drafts)
323
346
  this.write(draftFrame(d));
324
347
  }
348
+ /**
349
+ * The conversation's stored prompt suggestion when it is fresh and the org's switch is on; a
350
+ * stale key is deleted. A failure is logged: the suggestion is a convenience.
351
+ */
352
+ async sendSuggestion() {
353
+ const { conversationId, orgId } = this.p;
354
+ let frame = null;
355
+ try {
356
+ const stored = await this.d.suggestions.get(conversationId);
357
+ if (stored === null)
358
+ return;
359
+ if (!(await this.d.suggestions.isFresh(conversationId, stored))) {
360
+ await this.d.suggestions.delete(conversationId, stored);
361
+ return;
362
+ }
363
+ if (await this.d.suggestionsEnabled(orgId))
364
+ frame = suggestionFrame(stored);
365
+ }
366
+ catch (err) {
367
+ this.d.log.warn("conversation stream cannot read the prompt suggestion", {
368
+ conversationId,
369
+ err,
370
+ });
371
+ return;
372
+ }
373
+ if (frame !== null)
374
+ this.write(frame);
375
+ }
325
376
  /** 发最后一帧错误并关闭(未发完的排队输出随关闭丢弃)。 */
326
377
  fail(code) {
327
378
  if (this.closed)
@@ -54,7 +54,8 @@ export declare function narrowPending(stored: readonly string[] | undefined, fai
54
54
  * as are conversation title calls (`purpose: "title"`, no run: `runId` is "") and `WebFetch`
55
55
  * extraction calls (`purpose: "web_fetch"`). Command-review classifier calls log usage with
56
56
  * `purpose: "review"` and the reviewed tool call's `callId`; `GenerateImage` calls with
57
- * `purpose: "image"` and their `outputImages`, passed through in `usage`.
57
+ * `purpose: "image"` and their `outputImages`, passed through in `usage`. Prompt suggestion calls
58
+ * (`purpose: "suggestion"`) have no run either: `runId` is "".
58
59
  * Single-step eval replays and judge requests log no usage: not reported (M7).
59
60
  * - **Model usage outside conversations** (spec B §5.4): each `ctx.models.embed` and
60
61
  * `ctx.models.generateImage` call writes a `model_usage` row and owes job `usage-model-<rowId>`
@@ -109,7 +109,8 @@ export function narrowPending(stored, failed) {
109
109
  * as are conversation title calls (`purpose: "title"`, no run: `runId` is "") and `WebFetch`
110
110
  * extraction calls (`purpose: "web_fetch"`). Command-review classifier calls log usage with
111
111
  * `purpose: "review"` and the reviewed tool call's `callId`; `GenerateImage` calls with
112
- * `purpose: "image"` and their `outputImages`, passed through in `usage`.
112
+ * `purpose: "image"` and their `outputImages`, passed through in `usage`. Prompt suggestion calls
113
+ * (`purpose: "suggestion"`) have no run either: `runId` is "".
113
114
  * Single-step eval replays and judge requests log no usage: not reported (M7).
114
115
  * - **Model usage outside conversations** (spec B §5.4): each `ctx.models.embed` and
115
116
  * `ctx.models.generateImage` call writes a `model_usage` row and owes job `usage-model-<rowId>`
@@ -138,5 +138,5 @@ function invalidPathAsApiError(check) {
138
138
  }
139
139
  }
140
140
  const notFound = (path) => new ApiError("sandbox.file_not_found", `File not found in the sandbox: ${clip(path, 200)}. Check the path with Glob.`);
141
- const isDirectory = (path) => new ApiError("sandbox.file_is_directory", `${clip(path, 200)} is a directory; pass one file, e.g. archive the directory first with Bash (zip -r) and retry.`);
141
+ const isDirectory = (path) => new ApiError("sandbox.file_is_directory", `${clip(path, 200)} is a directory; pass the path of one file.`);
142
142
  const tooLarge = (path, size, max) => new ApiError("sandbox.file_too_large", `File ${clip(path, 200)} is ${size} bytes, over the limit of ${max} bytes; make it smaller and retry.`);
@@ -4,6 +4,8 @@ import { KernelDb } from "../infra/database/kernel-db.js";
4
4
  export { StorageKeyError } from "./prefix.js";
5
5
  /** 部署级对象的键前缀(见 {@link StorageService.deployment})。 */
6
6
  export declare const DEPLOYMENT_PREFIX = "deployment/";
7
+ /** True for the errors that mean "no object store right now": `storage.unavailable` or an unavailable provider. */
8
+ export declare const isStorageUnavailable: (e: unknown) => boolean;
7
9
  /** 没有对象存储提供方时的错误(HTTP 层映射为 `storage.unavailable`,503)。 */
8
10
  export declare const storageUnavailable: () => ExtensionPointUnavailableError;
9
11
  /** 预签名 URL 的有效期上限(秒):SigV4 预签名最长 7 天。 */
@@ -16,6 +16,9 @@ import { KeySpace, kernelPrefix, normalizeOrgId, pluginPrefix } from "./prefix.j
16
16
  export { StorageKeyError } from "./prefix.js";
17
17
  /** 部署级对象的键前缀(见 {@link StorageService.deployment})。 */
18
18
  export const DEPLOYMENT_PREFIX = "deployment/";
19
+ /** True for the errors that mean "no object store right now": `storage.unavailable` or an unavailable provider. */
20
+ export const isStorageUnavailable = (e) => (e instanceof ApiError && e.code === "storage.unavailable") ||
21
+ e instanceof ExtensionPointUnavailableError;
19
22
  /** 没有对象存储提供方时的错误(HTTP 层映射为 `storage.unavailable`,503)。 */
20
23
  export const storageUnavailable = () => new ExtensionPointUnavailableError("storage.unavailable: object storage is not available in this deployment");
21
24
  /** 预签名 URL 的有效期上限(秒):SigV4 预签名最长 7 天。 */
@@ -180,9 +180,9 @@ export const BUILTIN_TOOL_KINDS = {
180
180
  [BUILTIN.Grep]: "search",
181
181
  [BUILTIN.Deliver]: "tool",
182
182
  [BUILTIN.FetchAttachment]: "tool",
183
- [BUILTIN.TaskOutput]: "read",
183
+ [BUILTIN.TaskOutput]: "task",
184
184
  [BUILTIN.TaskStop]: "command",
185
- [BUILTIN.TaskList]: "read",
185
+ [BUILTIN.TaskList]: "task",
186
186
  [BUILTIN.ToolSearch]: "meta",
187
187
  [BUILTIN.Skill]: "meta",
188
188
  [BUILTIN.ReadToolOutput]: "meta",
@@ -57,8 +57,8 @@ const INPUT_SCHEMA = {
57
57
  };
58
58
  /** The text before the roster (§4.3, agent map spec §4.1), with the concurrency limit. */
59
59
  const head = (maxConcurrent) => "Dispatch a sub-agent: a fresh agent with its own context that works on one task in the " +
60
- "background. This tool returns at once with the sub-agent's agentId; keep working or end your " +
61
- "turn, and do not wait for it. When the sub-agent hands back a report or finishes, its result " +
60
+ "background. This tool returns at once with the sub-agent's agentId, and you can keep working " +
61
+ "or end your turn while it runs. When the sub-agent hands back a report or finishes, its result " +
62
62
  "arrives in this conversation as a notification. The sub-agent sees only your prompt, not this " +
63
63
  "conversation, so include everything it needs and say what its report must contain. It shares " +
64
64
  "your sandbox files. To run several at once, call this tool several times (at most " +
@@ -107,8 +107,8 @@ export function agentToolSpec(roster, maxConcurrent) {
107
107
  const SPEC = {
108
108
  name: "Agent",
109
109
  description: "Dispatch a sub-agent: a fresh agent with its own context that works on one task in the " +
110
- "background. This tool returns at once with the sub-agent's agentId; keep working or end your " +
111
- "turn, and do not wait for it. When the sub-agent hands back a report or finishes, its result " +
110
+ "background. This tool returns at once with the sub-agent's agentId, and you can keep working " +
111
+ "or end your turn while it runs. When the sub-agent hands back a report or finishes, its result " +
112
112
  "arrives in this conversation as a notification. The sub-agent sees only your prompt, not this " +
113
113
  "conversation, so include everything it needs and say what its report must contain. It shares " +
114
114
  "your sandbox files. To run several at once, call this tool several times (at most 4 of your " +
@@ -156,7 +156,7 @@ function duration(ms) {
156
156
  */
157
157
  export const agentStartedText = (agentId, opts = {}) => `agentId: ${agentId} (running in the background)\n` +
158
158
  "The sub-agent is working on the task. Its result arrives in this conversation as a " +
159
- "notification when it hands back a report or finishes; keep working or end your turn. To send " +
159
+ "notification when it hands back a report or finishes. To send " +
160
160
  "it more instructions, use SendMessage with this agentId." +
161
161
  (opts.ownModel === true ? " It runs on its own model; the model you passed was ignored." : "");
162
162
  /**
@@ -1,5 +1,5 @@
1
1
  import type { EventLog } from "../../conversations/event-log.js";
2
- import type { StorageService } from "../../storage/storage.service.js";
2
+ import { type StorageService } from "../../storage/storage.service.js";
3
3
  import type { BuiltinCallContext } from "../registry.js";
4
4
  /**
5
5
  * The tool error when the deployment has no object store (or it went away): files cannot be
@@ -11,7 +11,7 @@ export declare const NO_STORAGE_REASON: string;
11
11
  /** What {@link storeArtifacts} needs. */
12
12
  export interface ArtifactStoreDeps {
13
13
  storage: Pick<StorageService, "kernel">;
14
- eventLog: Pick<EventLog, "append"> & Partial<Pick<EventLog, "publishChanged">>;
14
+ eventLog: Pick<EventLog, "append" | "readDeliveryScope"> & Partial<Pick<EventLog, "publishChanged">>;
15
15
  }
16
16
  /** One file to deliver as an artifact. */
17
17
  export interface ArtifactFile {
@@ -25,19 +25,45 @@ export interface ArtifactFile {
25
25
  */
26
26
  sourcePath: string;
27
27
  }
28
- /** A stored artifact as the tool result names it. */
28
+ /**
29
+ * A stored artifact as the tool result names it. For a repeat (`repeatOf` set: the same bytes
30
+ * were already delivered in this delivery scope) nothing was stored and `artifactId` is the
31
+ * earlier artifact's.
32
+ */
29
33
  export interface StoredArtifact {
30
34
  artifactId: string;
31
35
  name: string;
32
36
  size: number;
37
+ repeatOf?: {
38
+ artifactId: string;
39
+ name: string;
40
+ };
33
41
  }
42
+ /** The clause that says a file repeats an artifact already delivered in the scope. */
43
+ export declare const REPEAT_CLAUSE: (prior: {
44
+ name: string;
45
+ artifactId: string;
46
+ }) => string;
47
+ /** The result text of a file that repeats an artifact already delivered in the scope. */
48
+ export declare const REPEAT_TEXT: (name: string, prior: {
49
+ name: string;
50
+ artifactId: string;
51
+ }) => string;
34
52
  /**
35
53
  * Stores `files` as artifacts of the call's conversation, all or none: every object is uploaded
36
54
  * under the kernel prefix (`artifacts/<conversationId>/<artifactId>`), then all their
37
- * `artifact_created` events (the call's run and `callId`) go into the log in one append. Any
38
- * failure, an abort of the call before the append included, deletes every object uploaded so far
39
- * (best effort; one left behind is unreferenced and goes with the conversation's purge) and
40
- * rethrows; a store that is not there is the {@link NO_STORAGE} tool error. The conversation's
41
- * files are announced changed once.
55
+ * `artifact_created` events (the call's run and `callId`, the bytes' sha256) go into the log in
56
+ * one append. Any failure, an abort of the call before the append included, deletes every object
57
+ * uploaded so far (best effort; one left behind is unreferenced and goes with the conversation's
58
+ * purge) and rethrows; a store that is not there is the {@link NO_STORAGE} tool error. The
59
+ * conversation's files are announced changed once, when something new was stored.
60
+ *
61
+ * With a run, the same bytes reach the user once per delivery scope (truthful delivery spec §2):
62
+ * a file equal to an earlier file of the call, or a repeat by {@link findRepeat} of the scope's
63
+ * artifacts, is not uploaded and comes back with `repeatOf`. Each event's idempotency key is
64
+ * `artifact:<runId>:<boundary>:<sha256>:<lastOfSource>`, so two parallel calls that both saw no
65
+ * repeat compute the same key: the append's row lock and the unique key give the second the
66
+ * first's event, and the one cleanup rule deletes every object whose returned event is not the
67
+ * one generated for it, making that file a repeat of the returned event. No process state.
42
68
  */
43
69
  export declare function storeArtifacts(deps: ArtifactStoreDeps, ctx: BuiltinCallContext, files: readonly ArtifactFile[]): Promise<StoredArtifact[]>;
@@ -1,6 +1,7 @@
1
- import { randomUUID } from "node:crypto";
2
- import { ExtensionPointUnavailableError, ToolError } from "@capybara-hq/plugin-sdk";
3
- import { ApiError } from "../../errors.js";
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { ToolError } from "@capybara-hq/plugin-sdk";
3
+ import { findRepeat } from "../../conversations/delivery-scope.js";
4
+ import { isStorageUnavailable } from "../../storage/storage.service.js";
4
5
  /**
5
6
  * The tool error when the deployment has no object store (or it went away): files cannot be
6
7
  * delivered. `Deliver` and `GenerateImage` share it.
@@ -8,24 +9,59 @@ import { ApiError } from "../../errors.js";
8
9
  export const NO_STORAGE = "File storage is not configured in this deployment, so files cannot be delivered; ask an administrator, or provide the result in your reply instead.";
9
10
  /** The same as the "tool unavailable" reason (the kernel adds the final period). */
10
11
  export const NO_STORAGE_REASON = NO_STORAGE.slice(0, -1);
11
- const isStorageGone = (e) => (e instanceof ApiError && e.code === "storage.unavailable") ||
12
- e instanceof ExtensionPointUnavailableError;
12
+ /** The clause that says a file repeats an artifact already delivered in the scope. */
13
+ export const REPEAT_CLAUSE = (prior) => `same content as ${prior.name} (artifact ${prior.artifactId}), already delivered to the user since the person last spoke; no new artifact was created.`;
14
+ /** The result text of a file that repeats an artifact already delivered in the scope. */
15
+ export const REPEAT_TEXT = (name, prior) => `${name} has the ${REPEAT_CLAUSE(prior)}`;
13
16
  /**
14
17
  * Stores `files` as artifacts of the call's conversation, all or none: every object is uploaded
15
18
  * under the kernel prefix (`artifacts/<conversationId>/<artifactId>`), then all their
16
- * `artifact_created` events (the call's run and `callId`) go into the log in one append. Any
17
- * failure, an abort of the call before the append included, deletes every object uploaded so far
18
- * (best effort; one left behind is unreferenced and goes with the conversation's purge) and
19
- * rethrows; a store that is not there is the {@link NO_STORAGE} tool error. The conversation's
20
- * files are announced changed once.
19
+ * `artifact_created` events (the call's run and `callId`, the bytes' sha256) go into the log in
20
+ * one append. Any failure, an abort of the call before the append included, deletes every object
21
+ * uploaded so far (best effort; one left behind is unreferenced and goes with the conversation's
22
+ * purge) and rethrows; a store that is not there is the {@link NO_STORAGE} tool error. The
23
+ * conversation's files are announced changed once, when something new was stored.
24
+ *
25
+ * With a run, the same bytes reach the user once per delivery scope (truthful delivery spec §2):
26
+ * a file equal to an earlier file of the call, or a repeat by {@link findRepeat} of the scope's
27
+ * artifacts, is not uploaded and comes back with `repeatOf`. Each event's idempotency key is
28
+ * `artifact:<runId>:<boundary>:<sha256>:<lastOfSource>`, so two parallel calls that both saw no
29
+ * repeat compute the same key: the append's row lock and the unique key give the second the
30
+ * first's event, and the one cleanup rule deletes every object whose returned event is not the
31
+ * one generated for it, making that file a repeat of the returned event. No process state.
21
32
  */
22
33
  export async function storeArtifacts(deps, ctx, files) {
34
+ const hashes = files.map((f) => createHash("sha256").update(f.data).digest("hex"));
35
+ const out = files.map((f) => ({
36
+ artifactId: "",
37
+ name: f.name,
38
+ size: f.data.byteLength,
39
+ }));
40
+ /** Per input: the earlier input of the same call it repeats (with a run), else itself. */
41
+ const firstOf = hashes.map((h, i) => (ctx.runId === undefined ? i : hashes.indexOf(h)));
23
42
  const uploaded = [];
43
+ /** The inputs written as events, in the order of `events`, with their generated ids. */
44
+ const written = [];
24
45
  const events = [];
25
- const out = [];
46
+ let stored = [];
26
47
  try {
48
+ const scope = ctx.runId === undefined
49
+ ? null
50
+ : await deps.eventLog.readDeliveryScope(ctx.conversationId, ctx.runId);
27
51
  const store = deps.storage.kernel(ctx.orgId);
28
- for (const f of files) {
52
+ for (const [i, f] of files.entries()) {
53
+ if (firstOf[i] !== i)
54
+ continue;
55
+ const sha256 = hashes[i];
56
+ let idemKey;
57
+ if (scope !== null) {
58
+ const { repeatOf, lastOfSource } = findRepeat(scope, sha256, f.sourcePath);
59
+ if (repeatOf !== null) {
60
+ setRepeat(out, i, repeatOf);
61
+ continue;
62
+ }
63
+ idemKey = `artifact:${ctx.runId}:${scope.boundary}:${sha256}:${lastOfSource}`;
64
+ }
29
65
  const artifactId = randomUUID();
30
66
  const objectKey = `artifacts/${ctx.conversationId}/${artifactId}`;
31
67
  await store.put(objectKey, f.data, {
@@ -34,9 +70,11 @@ export async function storeArtifacts(deps, ctx, files) {
34
70
  signal: ctx.signal,
35
71
  });
36
72
  uploaded.push(objectKey);
73
+ written.push({ index: i, artifactId, objectKey });
37
74
  events.push({
38
75
  type: "artifact_created",
39
76
  ...(ctx.runId !== undefined && { runId: ctx.runId }),
77
+ ...(idemKey !== undefined && { idemKey }),
40
78
  payload: {
41
79
  artifactId,
42
80
  name: f.name,
@@ -45,23 +83,61 @@ export async function storeArtifacts(deps, ctx, files) {
45
83
  objectKey,
46
84
  sourcePath: f.sourcePath,
47
85
  callId: ctx.callId,
86
+ sha256,
48
87
  },
49
88
  });
50
- out.push({ artifactId, name: f.name, size: f.data.byteLength });
89
+ out[i] = { artifactId, name: f.name, size: f.data.byteLength };
51
90
  }
52
91
  // a call stopped while uploading writes no event: its objects are removed below
53
92
  ctx.signal.throwIfAborted();
54
- await deps.eventLog.append(ctx.conversationId, events);
93
+ if (events.length > 0)
94
+ stored = await deps.eventLog.append(ctx.conversationId, events);
55
95
  }
56
96
  catch (e) {
57
97
  // no event references them: remove what was uploaded (best effort)
58
- await Promise.all(uploaded.map((key) => Promise.resolve()
59
- .then(() => deps.storage.kernel(ctx.orgId).delete(key))
60
- .catch(() => { })));
61
- if (isStorageGone(e))
98
+ await removeObjects(deps, ctx, uploaded);
99
+ if (isStorageUnavailable(e))
62
100
  throw new ToolError(NO_STORAGE);
63
101
  throw e;
64
102
  }
65
- await deps.eventLog.publishChanged?.(ctx.conversationId, "files");
103
+ // the one cleanup rule: an event that is not the one generated (a parallel call appended the
104
+ // same key first) leaves this upload unreferenced, and the file repeats that event
105
+ const unused = [];
106
+ let fresh = false;
107
+ for (const [j, w] of written.entries()) {
108
+ const ev = stored[j];
109
+ const payload = ev?.type === "artifact_created" ? ev.payload : undefined;
110
+ if (payload === undefined || payload.artifactId === w.artifactId) {
111
+ fresh = true;
112
+ continue;
113
+ }
114
+ unused.push(w.objectKey);
115
+ setRepeat(out, w.index, payload);
116
+ }
117
+ await removeObjects(deps, ctx, unused);
118
+ // a file equal to an earlier one of the call repeats whatever that one became
119
+ for (const [i, first] of firstOf.entries()) {
120
+ if (first === i)
121
+ continue;
122
+ const prior = out[first];
123
+ setRepeat(out, i, prior.repeatOf ?? prior);
124
+ }
125
+ if (fresh)
126
+ await deps.eventLog.publishChanged?.(ctx.conversationId, "files");
66
127
  return out;
67
128
  }
129
+ function setRepeat(out, i, prior) {
130
+ const cur = out[i];
131
+ out[i] = {
132
+ artifactId: prior.artifactId,
133
+ name: cur.name,
134
+ size: cur.size,
135
+ repeatOf: { artifactId: prior.artifactId, name: prior.name },
136
+ };
137
+ }
138
+ /** Deletes `keys` from the org's kernel store, best effort (a failure leaves an orphan object). */
139
+ async function removeObjects(deps, ctx, keys) {
140
+ await Promise.all(keys.map((key) => Promise.resolve()
141
+ .then(() => deps.storage.kernel(ctx.orgId).delete(key))
142
+ .catch(() => { })));
143
+ }
@@ -3,6 +3,7 @@ import type { AttachmentsService } from "../../../conversations/attachments.serv
3
3
  import type { EventLog } from "../../../conversations/event-log.js";
4
4
  import type { KernelSchemaDb } from "../../../db/kernel-schema.js";
5
5
  import type { KernelConfigService } from "../../../infra/config/kernel-config.service.js";
6
+ import { type ImageInputCaps } from "../../../models/image-usable.js";
6
7
  import { type ModelImages } from "../../../models/images.js";
7
8
  import type { ModelPurposesService } from "../../../models/purposes.js";
8
9
  import { type HookRunner } from "../../../runtime/hook-calls.js";
@@ -11,6 +12,8 @@ import type { StepLog } from "../../../runtime/step-log.js";
11
12
  import type { StorageService } from "../../../storage/storage.service.js";
12
13
  import type { BuiltinTool } from "../../registry.js";
13
14
  import { type SandboxToolDeps } from "../sandbox/common.js";
15
+ /** The listed spec for an org whose image model accepts `caps` (pure; `n` and references drop or cap). */
16
+ export declare function generateImageSpec(caps: ImageInputCaps): ToolSpec;
14
17
  export declare const GENERATE_IMAGE_SPEC: ToolSpec;
15
18
  /** Why the tool is not listed: the org's `image` purpose has no usable model (spec §5.3). */
16
19
  export declare const NO_IMAGE_MODEL_REASON = "No image model is configured for this organization";
@@ -27,7 +30,7 @@ export interface GenerateImageDeps {
27
30
  purposes: Pick<ModelPurposesService, "resolve">;
28
31
  providers: Pick<ProviderRegistry, "resolve">;
29
32
  storage: Pick<StorageService, "kernel" | "available">;
30
- eventLog: Pick<EventLog, "append" | "notify"> & Partial<Pick<EventLog, "publishChanged">>;
33
+ eventLog: Pick<EventLog, "append" | "notify" | "readDeliveryScope"> & Partial<Pick<EventLog, "publishChanged">>;
31
34
  stepLog: Pick<StepLog, "appendCounted" | "appendReported" | "appendAudited">;
32
35
  config: Pick<KernelConfigService, "get">;
33
36
  log: Pick<Logger, "warn">;