@capybara-hq/kernel 0.1.0-rc.46 → 0.1.0-rc.48
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.
- package/bootstrap.json +3 -3
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/channels/channels.module.js +3 -0
- package/dist/channels/connections.service.d.ts +18 -5
- package/dist/channels/connections.service.js +21 -5
- package/dist/channels/features.d.ts +2 -0
- package/dist/channels/features.js +9 -5
- package/dist/channels/file-delivery.d.ts +74 -0
- package/dist/channels/file-delivery.js +176 -0
- package/dist/channels/outbound.d.ts +6 -3
- package/dist/channels/outbound.js +156 -4
- package/dist/channels/phrases.d.ts +19 -0
- package/dist/channels/phrases.js +16 -0
- package/dist/config/schema.d.ts +2 -0
- package/dist/config/schema.js +18 -0
- package/dist/storage/storage.service.d.ts +2 -0
- package/dist/storage/storage.service.js +3 -0
- package/dist/tools/builtin-names.js +2 -2
- package/dist/tools/builtins/artifacts.d.ts +1 -1
- package/dist/tools/builtins/artifacts.js +3 -5
- package/dist/tools/info.d.ts +3 -1
- package/package.json +4 -4
package/bootstrap.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"schemaVersion": 1,
|
|
4
4
|
"marketplace": {
|
|
5
5
|
"url": "https://github.com/capybara-hq/plugins.git",
|
|
6
|
-
"commit": "
|
|
6
|
+
"commit": "84a5307e2757bd4fc1f9f11b43be456b63f0f9c7"
|
|
7
7
|
},
|
|
8
8
|
"plugins": [
|
|
9
9
|
{
|
|
@@ -115,8 +115,8 @@
|
|
|
115
115
|
"name": "file-preview",
|
|
116
116
|
"source": "npm",
|
|
117
117
|
"npm": "@capybara-hq/plugin-file-preview",
|
|
118
|
-
"version": "0.1.0-rc.
|
|
119
|
-
"integrity": "sha512-
|
|
118
|
+
"version": "0.1.0-rc.3",
|
|
119
|
+
"integrity": "sha512-4GMeq6gpjloCmTrEidiUHX5v6PN4oTfRDWcx+sLb5NlUoSk5DaJVVtJDc5oNDzow09OSm62DJchDOBJItLdwrA==",
|
|
120
120
|
"required": false,
|
|
121
121
|
"builtin": true
|
|
122
122
|
}
|
|
@@ -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.
|
|
191
|
+
readonly sdk: "0.1.0-rc.34";
|
|
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
|
-
*
|
|
273
|
-
* `
|
|
274
|
-
* `
|
|
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
|
-
/**
|
|
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
|
-
*
|
|
821
|
-
* `
|
|
822
|
-
* `
|
|
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
|
-
|
|
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
|
-
/**
|
|
133
|
-
|
|
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,什么都不写。
|
|
@@ -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
|
-
/**
|
|
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: "已停止。";
|
package/dist/channels/phrases.js
CHANGED
|
@@ -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
|
/** 运行失败。 */
|
package/dist/config/schema.d.ts
CHANGED
|
@@ -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>;
|
package/dist/config/schema.js
CHANGED
|
@@ -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({
|
|
@@ -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]: "
|
|
183
|
+
[BUILTIN.TaskOutput]: "task",
|
|
184
184
|
[BUILTIN.TaskStop]: "command",
|
|
185
|
-
[BUILTIN.TaskList]: "
|
|
185
|
+
[BUILTIN.TaskList]: "task",
|
|
186
186
|
[BUILTIN.ToolSearch]: "meta",
|
|
187
187
|
[BUILTIN.Skill]: "meta",
|
|
188
188
|
[BUILTIN.ReadToolOutput]: "meta",
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { EventLog } from "../../conversations/event-log.js";
|
|
2
|
-
import type
|
|
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
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { ToolError } from "@capybara-hq/plugin-sdk";
|
|
3
|
+
import { isStorageUnavailable } from "../../storage/storage.service.js";
|
|
4
4
|
/**
|
|
5
5
|
* The tool error when the deployment has no object store (or it went away): files cannot be
|
|
6
6
|
* delivered. `Deliver` and `GenerateImage` share it.
|
|
@@ -8,8 +8,6 @@ import { ApiError } from "../../errors.js";
|
|
|
8
8
|
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
9
|
/** The same as the "tool unavailable" reason (the kernel adds the final period). */
|
|
10
10
|
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;
|
|
13
11
|
/**
|
|
14
12
|
* Stores `files` as artifacts of the call's conversation, all or none: every object is uploaded
|
|
15
13
|
* under the kernel prefix (`artifacts/<conversationId>/<artifactId>`), then all their
|
|
@@ -58,7 +56,7 @@ export async function storeArtifacts(deps, ctx, files) {
|
|
|
58
56
|
await Promise.all(uploaded.map((key) => Promise.resolve()
|
|
59
57
|
.then(() => deps.storage.kernel(ctx.orgId).delete(key))
|
|
60
58
|
.catch(() => { })));
|
|
61
|
-
if (
|
|
59
|
+
if (isStorageUnavailable(e))
|
|
62
60
|
throw new ToolError(NO_STORAGE);
|
|
63
61
|
throw e;
|
|
64
62
|
}
|
package/dist/tools/info.d.ts
CHANGED
|
@@ -9,7 +9,9 @@ import { ToolRegistry } from "./registry.js";
|
|
|
9
9
|
* kind picks the row verb and the group counts, the title and key arguments the row's wording.
|
|
10
10
|
* Display only: nothing here reaches the model.
|
|
11
11
|
*/
|
|
12
|
-
export type ToolKind = "command" | "read" | "edit" | "search" | "connector" | "meta"
|
|
12
|
+
export type ToolKind = "command" | "read" | "edit" | "search" | "connector" | "meta"
|
|
13
|
+
/** Reading background tasks (`TaskOutput`, `TaskList`): neither a file read nor a command. */
|
|
14
|
+
| "task" | "tool";
|
|
13
15
|
export interface ToolInfo {
|
|
14
16
|
/** The model-visible tool key, as asked for. */
|
|
15
17
|
key: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@capybara-hq/kernel",
|
|
3
|
-
"version": "0.1.0-rc.
|
|
3
|
+
"version": "0.1.0-rc.48",
|
|
4
4
|
"description": "Capybara kernel: config, database, plugin host and HTTP API of the Capybara agent platform",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -65,7 +65,7 @@
|
|
|
65
65
|
"yaml": "^2.9.1",
|
|
66
66
|
"yauzl": "3.4.0",
|
|
67
67
|
"zod": "^4.6.7",
|
|
68
|
-
"@capybara-hq/plugin-sdk": "^0.1.0-rc.
|
|
68
|
+
"@capybara-hq/plugin-sdk": "^0.1.0-rc.34"
|
|
69
69
|
},
|
|
70
70
|
"devDependencies": {
|
|
71
71
|
"@langchain/langgraph-checkpoint-validation": "^1.2.0",
|
|
@@ -74,8 +74,8 @@
|
|
|
74
74
|
"@types/ws": "^8.18.2",
|
|
75
75
|
"@types/yauzl": "3.4.0",
|
|
76
76
|
"ws": "^8.22.0",
|
|
77
|
-
"@capybara-hq/
|
|
78
|
-
"@capybara-hq/
|
|
77
|
+
"@capybara-hq/device": "0.1.0-rc.14",
|
|
78
|
+
"@capybara-hq/testing": "0.1.0-rc.27"
|
|
79
79
|
},
|
|
80
80
|
"scripts": {
|
|
81
81
|
"build": "tsc -b"
|