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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/agents/agents.controller.d.ts +13 -1
  3. package/dist/agents/agents.controller.js +24 -2
  4. package/dist/catalog/catalog-content.d.ts +11 -0
  5. package/dist/catalog/catalog-content.js +1 -0
  6. package/dist/catalog/catalog.service.d.ts +11 -1
  7. package/dist/catalog/catalog.service.js +36 -2
  8. package/dist/catalog/marketplaces.service.d.ts +1 -1
  9. package/dist/catalog/org-catalog.service.d.ts +1 -0
  10. package/dist/catalog/org-catalog.service.js +44 -2
  11. package/dist/catalog/platform-components.js +13 -0
  12. package/dist/catalog/plugin-connectors.d.ts +35 -0
  13. package/dist/catalog/plugin-connectors.js +81 -0
  14. package/dist/catalog/schema-path.d.ts +4 -6
  15. package/dist/catalog/schema-path.js +48 -21
  16. package/dist/channels/outbound.d.ts +5 -0
  17. package/dist/channels/outbound.js +6 -1
  18. package/dist/channels/supervisor.d.ts +5 -1
  19. package/dist/channels/supervisor.js +20 -1
  20. package/dist/conversations/conversations.controller.d.ts +46 -14
  21. package/dist/conversations/conversations.controller.js +82 -47
  22. package/dist/conversations/conversations.service.d.ts +93 -59
  23. package/dist/conversations/conversations.service.js +255 -72
  24. package/dist/conversations/events.d.ts +32 -0
  25. package/dist/conversations/events.js +47 -3
  26. package/dist/conversations/inline-tokens.d.ts +87 -0
  27. package/dist/conversations/inline-tokens.js +154 -0
  28. package/dist/conversations/permission-profiles.controller.d.ts +14 -7
  29. package/dist/conversations/permission-profiles.controller.js +1 -5
  30. package/dist/conversations/prompt-suggestions.js +2 -4
  31. package/dist/conversations/queue.d.ts +0 -2
  32. package/dist/conversations/queue.service.js +9 -13
  33. package/dist/db/kernel-schema.d.ts +2 -0
  34. package/dist/devices/devices.service.d.ts +8 -0
  35. package/dist/devices/devices.service.js +16 -0
  36. package/dist/errors.d.ts +12 -0
  37. package/dist/errors.js +12 -0
  38. package/dist/evals/snapshot.js +4 -2
  39. package/dist/files/library-files.service.d.ts +13 -0
  40. package/dist/files/library-files.service.js +33 -6
  41. package/dist/net/safe-fetch.js +1 -1
  42. package/dist/platform/exclusions.js +11 -1
  43. package/dist/platform/ops/devices.ops.js +14 -0
  44. package/dist/runtime/context/build.d.ts +7 -2
  45. package/dist/runtime/context/build.js +17 -6
  46. package/dist/runtime/context/compaction.d.ts +3 -3
  47. package/dist/runtime/context/compaction.js +12 -13
  48. package/dist/sandbox/review/classifier.js +5 -1
  49. package/dist/sandbox/sandbox.service.d.ts +13 -0
  50. package/dist/sandbox/sandbox.service.js +51 -4
  51. package/dist/tools/builtins/sandbox/common.d.ts +2 -7
  52. package/dist/tools/builtins/sandbox/common.js +4 -2
  53. package/dist/tools/connector-content.controller.d.ts +6 -2
  54. package/dist/tools/connector-content.controller.js +13 -3
  55. package/dist/tools/connector-content.d.ts +55 -15
  56. package/dist/tools/connector-content.js +112 -54
  57. package/dist/tools/connectors.service.d.ts +3 -2
  58. package/dist/tools/connectors.service.js +6 -20
  59. package/dist/tools/mentionable-connectors.d.ts +88 -0
  60. package/dist/tools/mentionable-connectors.js +218 -0
  61. package/dist/tools/pipeline.d.ts +4 -0
  62. package/dist/tools/pipeline.js +98 -22
  63. package/dist/tools/specs.d.ts +13 -4
  64. package/dist/tools/specs.js +22 -8
  65. package/dist/tools/tools.module.js +7 -0
  66. package/dist/ui/admin-ui.controller.d.ts +5 -2
  67. package/dist/ui/admin-ui.controller.js +14 -1
  68. package/dist/ui/ui.schemas.d.ts +9 -0
  69. package/dist/ui/ui.schemas.js +2 -0
  70. package/dist/ui/views.d.ts +1 -1
  71. package/dist/ui/views.js +4 -5
  72. package/package.json +3 -3
  73. package/src/migrations/0201_tool_specs_text.sql +8 -0
@@ -10,9 +10,10 @@ const WRAPPERS = new Set([
10
10
  "success",
11
11
  ]);
12
12
  const defOf = (s) => s._zod.def;
13
- function unwrap(s, depth) {
13
+ function unwrap(s, depth, visit) {
14
14
  let node = s;
15
15
  for (let i = 0; i < 50; i++) {
16
+ visit?.(node);
16
17
  const d = defOf(node);
17
18
  if (WRAPPERS.has(d.type) && d.innerType)
18
19
  node = d.innerType;
@@ -25,39 +26,65 @@ function unwrap(s, depth) {
25
26
  }
26
27
  return undefined;
27
28
  }
28
- /**
29
- * zod schema(v4)里是否有点路径 `segs` 指向的字段(连接器模板的 `editableEndpoint` 用):对象按 shape(或非 never 的
30
- * catchall)、记录类型的任意键、union / 交叉的任一分支;包装(optional、default、pipe 的输入端等)剥掉再看。
31
- * 空路径即 schema 本身,恒为 true。叶子之下还有路径 → false。
32
- */
33
- export function schemaHasPath(schema, segs, depth = 0) {
29
+ /** Whether the Zod schema admits the template's editable path. */
30
+ export function schemaHasPath(schema, segs) {
31
+ return schemaFields(schema, segs, 0).next().done === false;
32
+ }
33
+ /** The title shared by the endpoint field's titled alternatives, when available. */
34
+ export function schemaPathTitle(schema, segs) {
35
+ let title;
36
+ for (const field of schemaFields(schema, segs, 0)) {
37
+ let name;
38
+ unwrap(field, 0, (node) => {
39
+ if (name)
40
+ return;
41
+ const metadata = node.meta()?.title;
42
+ if (typeof metadata === "string")
43
+ name = metadata.trim();
44
+ });
45
+ if (!name)
46
+ continue;
47
+ if (title !== undefined && title !== name)
48
+ return undefined;
49
+ title = name;
50
+ }
51
+ return title;
52
+ }
53
+ function* schemaFields(schema, segs, depth) {
34
54
  if (depth > 40)
35
- return false;
55
+ return;
36
56
  const node = unwrap(schema, depth);
37
57
  if (!node)
38
- return false;
39
- if (segs.length === 0)
40
- return true;
58
+ return;
59
+ if (segs.length === 0) {
60
+ yield schema;
61
+ return;
62
+ }
41
63
  const [head, ...rest] = segs;
42
64
  const d = defOf(node);
43
65
  switch (d.type) {
44
66
  case "object": {
45
67
  const child = d.shape && Object.hasOwn(d.shape, head) ? d.shape[head] : undefined;
46
68
  if (child)
47
- return schemaHasPath(child, rest, depth + 1);
48
- if (d.catchall && defOf(d.catchall).type !== "never") {
49
- return schemaHasPath(d.catchall, rest, depth + 1);
69
+ yield* schemaFields(child, rest, depth + 1);
70
+ else if (d.catchall && defOf(d.catchall).type !== "never") {
71
+ yield* schemaFields(d.catchall, rest, depth + 1);
50
72
  }
51
- return false;
73
+ break;
52
74
  }
53
75
  case "record":
54
- return d.valueType ? schemaHasPath(d.valueType, rest, depth + 1) : false;
76
+ if (d.valueType)
77
+ yield* schemaFields(d.valueType, rest, depth + 1);
78
+ break;
55
79
  case "union":
56
- return (d.options ?? []).some((o) => schemaHasPath(o, segs, depth + 1));
80
+ for (const option of d.options ?? [])
81
+ yield* schemaFields(option, segs, depth + 1);
82
+ break;
57
83
  case "intersection":
58
- return ((d.left !== undefined && schemaHasPath(d.left, segs, depth + 1)) ||
59
- (d.right !== undefined && schemaHasPath(d.right, segs, depth + 1)));
60
- default:
61
- return false;
84
+ if (d.left)
85
+ yield* schemaFields(d.left, segs, depth + 1);
86
+ if (d.right)
87
+ yield* schemaFields(d.right, segs, depth + 1);
88
+ break;
62
89
  }
63
90
  }
@@ -41,6 +41,11 @@ export declare const DRAFT_INTERVAL_MS = 1000;
41
41
  export declare const MILESTONE_INTERVAL_MS = 60000;
42
42
  /** 同一事件不可重试地失败这么多次后跳过它(Ruling A14)。 */
43
43
  export declare const POISON_FAILURES = 3;
44
+ /**
45
+ * How a delivery failure starts in a connection's `last_error`: the connection holding again does
46
+ * not clear it (the supervisor clears only the connect failures it recovered from).
47
+ */
48
+ export declare const DELIVERY_ERROR_PREFIX = "delivery failed: ";
44
49
  /**
45
50
  * The language of the kernel text a conversation's IM thread gets (cards, notices; maintainer
46
51
  * decision 2026-11-08: in IM, language is per person). The person who triggered the run speaks:
@@ -83,6 +83,11 @@ const BACKOFF_BASE_MS = 1000;
83
83
  const BACKOFF_MAX_MS = 60_000;
84
84
  /** 补读事件的分页大小。 */
85
85
  const PAGE = 200;
86
+ /**
87
+ * How a delivery failure starts in a connection's `last_error`: the connection holding again does
88
+ * not clear it (the supervisor clears only the connect failures it recovered from).
89
+ */
90
+ export const DELIVERY_ERROR_PREFIX = "delivery failed: ";
86
91
  /** `last_error` 的最大长度(同渠道选主)。 */
87
92
  const MAX_ERROR_CHARS = 1000;
88
93
  /** 可重试的投递失败:带已打码的说明与平台建议的等待时长,供退避策略与最后一次失败时记录。 */
@@ -396,7 +401,7 @@ let ChannelOutbound = class ChannelOutbound {
396
401
  }
397
402
  /** A non-retryable (or finally failed) send: the connection's `last_error` (already redacted). */
398
403
  async recordError(connectionId, message) {
399
- const text = `delivery failed: ${message}`.slice(0, MAX_ERROR_CHARS);
404
+ const text = `${DELIVERY_ERROR_PREFIX}${message}`.slice(0, MAX_ERROR_CHARS);
400
405
  this.log.warn("channel delivery failed", { connectionId, error: text });
401
406
  // org-filter: connectionId is the delivery's own connection (kernel-written job / row)
402
407
  await this.kdb
@@ -137,7 +137,11 @@ export declare class ChannelSupervisor {
137
137
  private handOff;
138
138
  /** After-release callback: tells the other replicas a connection of `plugin` is free to claim. */
139
139
  private nudge;
140
- /** A renewal succeeded: one lease period connected in a row clears the failure count. */
140
+ /**
141
+ * A renewal succeeded: one lease period connected in a row clears the failure count and the
142
+ * connection's `last_error`, so a failure the connection has recovered from does not stay on its
143
+ * page next to "running".
144
+ */
141
145
  private afterRenew;
142
146
  /**
143
147
  * 可以持有的连接:active、未删除、所属组织未删除、插件在该组织启用(组织停用插件 / 删除组织时持有方据此断开),
@@ -23,6 +23,7 @@ import { createRedactor } from "../log.js";
23
23
  import { CHANNEL_CHANGED_TOPIC, ChannelConnections, channelBackoffKey, channelFailsKey, } from "./connections.service.js";
24
24
  import { ChannelInbound } from "./inbound.js";
25
25
  import { GATEWAY_CHECK_JOB } from "./job-ids.js";
26
+ import { DELIVERY_ERROR_PREFIX } from "./outbound.js";
26
27
  /** 长连接租约键(内核锁):值为持有方的随机 token。 */
27
28
  export const channelLeaseKey = (connectionId) => `capk:channel-lease:${connectionId}`;
28
29
  /**
@@ -341,12 +342,30 @@ let ChannelSupervisor = class ChannelSupervisor {
341
342
  .publish(CHANNEL_HANDOFF_TOPIC, { plugin, replicaId: this.replicaId })
342
343
  .catch((err) => this.log.warn("cannot publish channel handoff", { err }));
343
344
  }
344
- /** A renewal succeeded: one lease period connected in a row clears the failure count. */
345
+ /**
346
+ * A renewal succeeded: one lease period connected in a row clears the failure count and the
347
+ * connection's `last_error`, so a failure the connection has recovered from does not stay on its
348
+ * page next to "running".
349
+ */
345
350
  async afterRenew(id, h, ttl) {
346
351
  h.renewedAt = Date.now();
347
352
  if (!h.stable && Date.now() - h.startedAt >= ttl) {
348
353
  h.stable = true;
349
354
  await this.redis.del(channelFailsKey(id)).catch(() => { });
355
+ try {
356
+ // org-filter: id is a connection this gateway supervisor holds the lease of, not caller input
357
+ await this.db
358
+ .updateTable("channel_connections")
359
+ .set({ last_error: null })
360
+ .where("id", "=", id)
361
+ .where("last_error", "is not", null)
362
+ // a delivery failure is not a connect failure the connection recovered from
363
+ .where("last_error", "not like", `${DELIVERY_ERROR_PREFIX}%`)
364
+ .execute();
365
+ }
366
+ catch (e) {
367
+ this.log.warn("cannot clear channel error", { connectionId: id, err: e });
368
+ }
350
369
  }
351
370
  }
352
371
  /**
@@ -53,20 +53,45 @@ declare const DownloadQuery: z.ZodObject<{
53
53
  url: "url";
54
54
  }>>;
55
55
  }, z.core.$strip>;
56
+ /** One inline token of a message (composer inline tokens spec §3.1); its place is a U+FFFC in `text`. */
57
+ export declare const MessageTokenSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
58
+ type: z.ZodLiteral<"connector">;
59
+ connectorId: z.ZodUUID;
60
+ }, z.core.$strict>, z.ZodObject<{
61
+ type: z.ZodLiteral<"resource">;
62
+ connectorId: z.ZodUUID;
63
+ uri: z.ZodString;
64
+ }, z.core.$strict>, z.ZodObject<{
65
+ type: z.ZodLiteral<"file">;
66
+ id: z.ZodUUID;
67
+ }, z.core.$strict>, z.ZodObject<{
68
+ type: z.ZodLiteral<"projectFile">;
69
+ path: z.ZodString;
70
+ }, z.core.$strict>, z.ZodObject<{
71
+ type: z.ZodLiteral<"conversation">;
72
+ id: z.ZodString;
73
+ }, z.core.$strict>], "type">;
56
74
  declare const MessageBody: z.ZodObject<{
57
75
  text: z.ZodString;
58
76
  clientMessageId: z.ZodOptional<z.ZodString>;
59
- attachments: z.ZodOptional<z.ZodArray<z.ZodObject<{
77
+ tokens: z.ZodOptional<z.ZodArray<z.ZodDiscriminatedUnion<[z.ZodObject<{
78
+ type: z.ZodLiteral<"connector">;
79
+ connectorId: z.ZodUUID;
80
+ }, z.core.$strict>, z.ZodObject<{
81
+ type: z.ZodLiteral<"resource">;
60
82
  connectorId: z.ZodUUID;
61
83
  uri: z.ZodString;
62
- }, z.core.$strict>>>;
63
- files: z.ZodOptional<z.ZodArray<z.ZodUUID>>;
64
- projectFiles: z.ZodOptional<z.ZodArray<z.ZodObject<{
84
+ }, z.core.$strict>, z.ZodObject<{
85
+ type: z.ZodLiteral<"file">;
86
+ id: z.ZodUUID;
87
+ }, z.core.$strict>, z.ZodObject<{
88
+ type: z.ZodLiteral<"projectFile">;
65
89
  path: z.ZodString;
66
- }, z.core.$strict>>>;
67
- conversationRefs: z.ZodOptional<z.ZodArray<z.ZodObject<{
90
+ }, z.core.$strict>, z.ZodObject<{
91
+ type: z.ZodLiteral<"conversation">;
68
92
  id: z.ZodString;
69
- }, z.core.$strict>>>;
93
+ }, z.core.$strict>], "type">>>;
94
+ files: z.ZodOptional<z.ZodArray<z.ZodUUID>>;
70
95
  model: z.ZodOptional<z.ZodObject<{
71
96
  provider: z.ZodString;
72
97
  model: z.ZodString;
@@ -103,17 +128,24 @@ export declare const CreateBody: z.ZodObject<{
103
128
  project: z.ZodOptional<z.ZodString & z.ZodType<string, string, z.core.$ZodTypeInternals<string, string>>>;
104
129
  message: z.ZodOptional<z.ZodObject<{
105
130
  text: z.ZodString;
106
- attachments: z.ZodOptional<z.ZodArray<z.ZodObject<{
131
+ tokens: z.ZodOptional<z.ZodArray<z.ZodDiscriminatedUnion<[z.ZodObject<{
132
+ type: z.ZodLiteral<"connector">;
133
+ connectorId: z.ZodUUID;
134
+ }, z.core.$strict>, z.ZodObject<{
135
+ type: z.ZodLiteral<"resource">;
107
136
  connectorId: z.ZodUUID;
108
137
  uri: z.ZodString;
109
- }, z.core.$strict>>>;
110
- files: z.ZodOptional<z.ZodArray<z.ZodUUID>>;
111
- projectFiles: z.ZodOptional<z.ZodArray<z.ZodObject<{
138
+ }, z.core.$strict>, z.ZodObject<{
139
+ type: z.ZodLiteral<"file">;
140
+ id: z.ZodUUID;
141
+ }, z.core.$strict>, z.ZodObject<{
142
+ type: z.ZodLiteral<"projectFile">;
112
143
  path: z.ZodString;
113
- }, z.core.$strict>>>;
114
- conversationRefs: z.ZodOptional<z.ZodArray<z.ZodObject<{
144
+ }, z.core.$strict>, z.ZodObject<{
145
+ type: z.ZodLiteral<"conversation">;
115
146
  id: z.ZodString;
116
- }, z.core.$strict>>>;
147
+ }, z.core.$strict>], "type">>>;
148
+ files: z.ZodOptional<z.ZodArray<z.ZodUUID>>;
117
149
  model: z.ZodOptional<z.ZodObject<{
118
150
  provider: z.ZodString;
119
151
  model: z.ZodString;
@@ -24,6 +24,7 @@ import { CompactBody, DOWNLOAD_AS, EventsQuery, FilesQuery, IdParams, ListQuery,
24
24
  import { ConversationsService, MAX_PROJECT_FILES, } from "./conversations.service.js";
25
25
  import { ConversationDeviceStatus } from "./device-status.js";
26
26
  import { ConversationFiles, FILE_CONTENT_MAX_BYTES } from "./files.js";
27
+ import { countMarkers, MAX_CONNECTOR_MENTIONS, MAX_TOKENS, tokenEntityKey, } from "./inline-tokens.js";
27
28
  import { ConversationOutputs, OUTPUT_PAGE_MAX_CHARS } from "./outputs-read.js";
28
29
  import { ConversationQueue } from "./queue.service.js";
29
30
  const GroupsQuery = z.object({
@@ -57,40 +58,39 @@ const DownloadQuery = z.object({
57
58
  inline: z.enum(["0", "1"]).optional(),
58
59
  as: DOWNLOAD_AS.optional(),
59
60
  });
61
+ /** One inline token of a message (composer inline tokens spec §3.1); its place is a U+FFFC in `text`. */
62
+ export const MessageTokenSchema = z.discriminatedUnion("type", [
63
+ z.object({ type: z.literal("connector"), connectorId: z.uuid() }).strict(),
64
+ z
65
+ .object({
66
+ type: z.literal("resource"),
67
+ connectorId: z.uuid(),
68
+ uri: z.string().min(1).max(2000),
69
+ })
70
+ .strict(),
71
+ z.object({ type: z.literal("file"), id: z.uuid() }).strict(),
72
+ z.object({ type: z.literal("projectFile"), path: z.string().min(1).max(4096) }).strict(),
73
+ z.object({ type: z.literal("conversation"), id: z.string().min(1).max(100) }).strict(),
74
+ ]);
60
75
  const MessageFields = z.object({
61
- /** 用户输入的文本;只有带 `files` 且不带 `attachments` 时可以为空(只发图片 / 文件)。 */
62
- text: z.string().max(100_000),
63
- clientMessageId: z.string().min(1).max(200).optional(),
64
- /** `@` 资源引用:内核以发送者的凭据读取并作为附加文本块写入(见 ConversationsService.postUserMessage)。 */
65
- attachments: z
66
- .array(z.object({ connectorId: z.uuid(), uri: z.string().min(1).max(2000) }).strict())
67
- .max(MAX_ATTACHMENTS)
68
- .optional(),
69
76
  /**
70
- * 上传的附件 id(已 finalize,见 AttachmentsController);条数上限由 `attachments.maxPerMessage` 决定,
71
- * 这里的 100 只是硬上限。
77
+ * The person's text; each U+FFFC marks one token's place, in order. Empty only with a skill, or
78
+ * with `files` and no tokens (an upload-only message).
72
79
  */
73
- files: z.array(z.uuid()).max(100).optional(),
80
+ text: z.string().max(100_000),
81
+ clientMessageId: z.string().min(1).max(200).optional(),
74
82
  /**
75
- * Files of the conversation's device project, by path relative to its root (composer menus §5):
76
- * checked on the device, never read or uploaded; each becomes a text block after the `@`
77
- * resources' bodies. A path repeated (after normalization) is referenced once, so
78
- * `payload.projectFiles` may be shorter than this list. A new conversation needs `project` in
79
- * the create body.
83
+ * Inline tokens (composer inline tokens spec §3.1), in text order: connectors, connector
84
+ * resources, library files, project files and the sender's conversations. A repeated entity is
85
+ * resolved and counted once. A project file token needs the conversation's device project (a
86
+ * new conversation: `project` in the create body).
80
87
  */
81
- projectFiles: z
82
- .array(z.object({ path: z.string().min(1).max(4096) }).strict())
83
- .max(MAX_PROJECT_FILES)
84
- .optional(),
88
+ tokens: z.array(MessageTokenSchema).max(MAX_TOKENS).optional(),
85
89
  /**
86
- * The sender's own conversations, by id (@ conversations spec §1): each is read at send time
87
- * into a quoted text block after the project files' blocks. An id repeated is referenced once,
88
- * so `payload.conversationRefs` may be shorter than this list.
90
+ * Uploaded file ids (finalized, see the files routes); the per-message cap is
91
+ * `attachments.maxPerMessage` (file tokens count toward it), 100 is only the hard ceiling here.
89
92
  */
90
- conversationRefs: z
91
- .array(z.object({ id: z.string().min(1).max(100) }).strict())
92
- .max(MAX_CONVERSATION_REFS)
93
- .optional(),
93
+ files: z.array(z.uuid()).max(100).optional(),
94
94
  /** Switch the conversation's model from the next run (UI refresh B); the agent's own = back. */
95
95
  model: ModelRef.strict().optional(),
96
96
  /** Switch the effort: one of the (selected) model's declared `effort` values. */
@@ -119,23 +119,63 @@ const MessageFields = z.object({
119
119
  /** The sender's UI language (run context spec §3.4). */
120
120
  locale: z.enum(["zh", "en"]).optional(),
121
121
  });
122
- // The body of `@` resource i is `content[i + 1]`, then the project files' and the referenced
123
- // conversations' blocks follow, so `content[0]` must be the user's text: with `@` resources,
124
- // project files or conversation references the text must not be empty. A skill invocation's
125
- // `content[0]` is the rendered skill, so its text (the arguments) may be empty.
126
122
  const textRule = [
127
- (b) => b.text.length > 0 ||
128
- b.skill !== undefined ||
129
- ((b.files?.length ?? 0) > 0 &&
130
- !b.attachments?.length &&
131
- !b.projectFiles?.length &&
132
- !b.conversationRefs?.length),
123
+ (b) => b.text.length > 0 || b.skill !== undefined || ((b.files?.length ?? 0) > 0 && !b.tokens?.length),
133
124
  {
134
- message: "Text is required unless the message invokes a skill or carries files (and no @ resources, project files or conversation references)",
125
+ message: "Text is required unless the message invokes a skill or carries files and no tokens",
135
126
  path: ["text"],
136
127
  },
137
128
  ];
138
- const MessageBody = MessageFields.strict().refine(...textRule);
129
+ /** The per-kind token caps (a repeated entity counts once); file tokens are capped with `files`. */
130
+ const TOKEN_KIND_MAX = {
131
+ connector: MAX_CONNECTOR_MENTIONS,
132
+ resource: MAX_ATTACHMENTS,
133
+ projectFile: MAX_PROJECT_FILES,
134
+ conversation: MAX_CONVERSATION_REFS,
135
+ };
136
+ /**
137
+ * The token rules: one U+FFFC per token, the per-kind caps. A project file path that leaves the
138
+ * project is counted by its raw text here and refused with `device.path_outside_project` when the
139
+ * message resolves it, before anything is written.
140
+ */
141
+ function tokenRules(b, ctx) {
142
+ const tokens = b.tokens ?? [];
143
+ if (countMarkers(b.text) !== tokens.length) {
144
+ ctx.addIssue({
145
+ code: "custom",
146
+ message: "Each token needs one U+FFFC marker in text, in order",
147
+ path: ["text"],
148
+ });
149
+ }
150
+ if (b.tokens === undefined)
151
+ return;
152
+ const seen = new Map();
153
+ for (const t of tokens) {
154
+ let key;
155
+ try {
156
+ key = tokenEntityKey(t);
157
+ }
158
+ catch {
159
+ key = `${t.type}:raw:${t.type === "projectFile" ? t.path : ""}`;
160
+ }
161
+ const keys = seen.get(t.type) ?? new Set();
162
+ keys.add(key);
163
+ seen.set(t.type, keys);
164
+ }
165
+ for (const [kind, keys] of seen) {
166
+ const max = TOKEN_KIND_MAX[kind];
167
+ if (max !== undefined && keys.size > max) {
168
+ ctx.addIssue({
169
+ code: "custom",
170
+ message: `At most ${max} different ${kind} tokens per message`,
171
+ path: ["tokens"],
172
+ });
173
+ }
174
+ }
175
+ }
176
+ const MessageBody = MessageFields.strict()
177
+ .refine(...textRule)
178
+ .superRefine(tokenRules);
139
179
  /**
140
180
  * `POST /conversations`: `message` creates the conversation with its first message (create on
141
181
  * first send; `clientMessageId` is required and makes a retry return the same conversation).
@@ -159,6 +199,7 @@ export const CreateBody = z
159
199
  .extend({ clientMessageId: z.string().min(1).max(200) })
160
200
  .strict()
161
201
  .refine(...textRule)
202
+ .superRefine(tokenRules)
162
203
  .optional(),
163
204
  })
164
205
  .strict();
@@ -237,10 +278,8 @@ let ConversationsController = class ConversationsController {
237
278
  const out = await this.conversations.createWithMessage(org.orgId, p.account.id, body.agentId, {
238
279
  text: m.text,
239
280
  clientMessageId: m.clientMessageId,
240
- ...(m.attachments !== undefined && { attachments: m.attachments }),
281
+ ...(m.tokens !== undefined && { tokens: m.tokens }),
241
282
  ...(m.files !== undefined && { files: m.files }),
242
- ...(m.projectFiles !== undefined && { projectFiles: m.projectFiles }),
243
- ...(m.conversationRefs !== undefined && { conversationRefs: m.conversationRefs }),
244
283
  ...(m.model !== undefined && { model: m.model }),
245
284
  ...(m.effort !== undefined && { effort: m.effort }),
246
285
  ...(m.skill !== undefined && { skill: m.skill }),
@@ -452,12 +491,8 @@ let ConversationsController = class ConversationsController {
452
491
  event: await this.conversations.postUserMessage(org.orgId, id, p.account.id, {
453
492
  text: body.text,
454
493
  ...(body.clientMessageId !== undefined && { clientMessageId: body.clientMessageId }),
455
- ...(body.attachments !== undefined && { attachments: body.attachments }),
494
+ ...(body.tokens !== undefined && { tokens: body.tokens }),
456
495
  ...(body.files !== undefined && { files: body.files }),
457
- ...(body.projectFiles !== undefined && { projectFiles: body.projectFiles }),
458
- ...(body.conversationRefs !== undefined && {
459
- conversationRefs: body.conversationRefs,
460
- }),
461
496
  ...(body.model !== undefined && { model: body.model }),
462
497
  ...(body.effort !== undefined && { effort: body.effort }),
463
498
  ...(body.retryOf !== undefined && { retryOf: body.retryOf }),