@capybara-hq/kernel 0.1.0-rc.111 → 0.1.0-rc.112

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 (31) hide show
  1. package/dist/automations/errors.js +1 -1
  2. package/dist/automations/events/acceptance.d.ts +7 -2
  3. package/dist/automations/events/acceptance.js +7 -2
  4. package/dist/catalog/marketplaces.service.d.ts +1 -1
  5. package/dist/conversations/conversation-ref.d.ts +58 -0
  6. package/dist/conversations/conversation-ref.js +103 -0
  7. package/dist/conversations/conversations.controller.d.ts +6 -0
  8. package/dist/conversations/conversations.controller.js +23 -6
  9. package/dist/conversations/conversations.service.d.ts +40 -1
  10. package/dist/conversations/conversations.service.js +151 -6
  11. package/dist/conversations/events.d.ts +9 -0
  12. package/dist/conversations/events.js +14 -0
  13. package/dist/conversations/permission-profiles.controller.d.ts +3 -0
  14. package/dist/conversations/permission-profiles.controller.js +3 -0
  15. package/dist/db/kernel-schema.d.ts +11 -0
  16. package/dist/errors.d.ts +8 -0
  17. package/dist/errors.js +8 -0
  18. package/dist/inbox/inbox-items.service.d.ts +5 -3
  19. package/dist/inbox/inbox-items.service.js +12 -4
  20. package/dist/log.d.ts +6 -0
  21. package/dist/log.js +47 -19
  22. package/dist/platform/ops/inbox.ops.js +6 -4
  23. package/dist/push/recipients.js +2 -2
  24. package/dist/push/texts.d.ts +8 -2
  25. package/dist/push/texts.js +4 -1
  26. package/dist/sandbox/review/classifier.js +3 -1
  27. package/dist/themes/render-css.js +9 -2
  28. package/package.json +2 -2
  29. package/src/migrations/0196_conversation_events_compaction_summary_idx.sql +8 -0
  30. package/src/migrations/0197_inbox_item_localized_text.sql +8 -0
  31. package/src/migrations/0198_acceptance_prompt.sql +10 -0
@@ -21,4 +21,4 @@ export const filterInvalid = (message) => new ApiError("automation.filter_invali
21
21
  * An edit of an acceptance automation's trigger, agent or target: the kernel keeps them as the
22
22
  * person's acceptance rule made them (collaboration spec §4.4).
23
23
  */
24
- export const acceptanceFixed = () => new ApiError("automation.acceptance_fixed", "This automation accepts work assigned to you and your agent, so its trigger, agent and target are fixed; change its name, prompt, approved tools or unattended setting, pause it, or change your acceptance rule for the source");
24
+ export const acceptanceFixed = () => new ApiError("automation.acceptance_fixed", "This automation accepts the events a source directs to you and your agent, so its trigger, agent and target are fixed; change its name, prompt, approved tools or unattended setting, pause it, or change your acceptance rule for the source");
@@ -14,8 +14,13 @@ import { type EventCause, type EventRow } from "./deliver.js";
14
14
  export type { AcceptanceMode } from "../../db/kernel-schema.js";
15
15
  /** How long a work offer stays open (collaboration spec §4.4). */
16
16
  export declare const OFFER_TTL_SECONDS: number;
17
- /** The prompt of an acceptance automation (model-visible; the event block carries the work). */
18
- export declare const ACCEPTANCE_PROMPT = "This work was assigned to you. Read the assigned item, do what it asks within what you are allowed to do, and report what you did.";
17
+ /**
18
+ * The prompt of an acceptance automation (model-visible, stored on the automation and recorded as
19
+ * each fire's message text). It states only the mechanism: a directed event is any event its
20
+ * source addressed to this person and agent (an assignment, an unassignment, an answer, ...), so
21
+ * what happened is the event block's type, subject and summary, never this text.
22
+ */
23
+ export declare const ACCEPTANCE_PROMPT = "The events above were directed to you and your agent by their source; your acceptance rule for that source delivers them to this automation. Each one names its type, its subject and the source's own summary of what happened. Decide from them what, if anything, is now expected of you: do it within what you are allowed to do and report what you did, or say why nothing needs doing.";
19
24
  /** A person's acceptance rule for one trigger source with directed event types. */
20
25
  export interface AcceptanceRuleView {
21
26
  source: string;
@@ -34,8 +34,13 @@ import { deliverEvent } from "./deliver.js";
34
34
  import { isSelfTriggered } from "./guards.js";
35
35
  /** How long a work offer stays open (collaboration spec §4.4). */
36
36
  export const OFFER_TTL_SECONDS = 7 * 24 * 3600;
37
- /** The prompt of an acceptance automation (model-visible; the event block carries the work). */
38
- export const ACCEPTANCE_PROMPT = "This work was assigned to you. Read the assigned item, do what it asks within what you are allowed to do, and report what you did.";
37
+ /**
38
+ * The prompt of an acceptance automation (model-visible, stored on the automation and recorded as
39
+ * each fire's message text). It states only the mechanism: a directed event is any event its
40
+ * source addressed to this person and agent (an assignment, an unassignment, an answer, ...), so
41
+ * what happened is the event block's type, subject and summary, never this text.
42
+ */
43
+ export const ACCEPTANCE_PROMPT = "The events above were directed to you and your agent by their source; your acceptance rule for that source delivers them to this automation. Each one names its type, its subject and the source's own summary of what happened. Decide from them what, if anything, is now expected of you: do it within what you are allowed to do and report what you did, or say why nothing needs doing.";
39
44
  /** The most open offers one inbox read returns. */
40
45
  export const OFFERS_LIST_MAX = 100;
41
46
  const offerNotFound = () => new ApiError("automation.offer_not_found", "Work offer not found");
@@ -208,7 +208,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
208
208
  /** The host versions (an entry's `minKernel` is judged against them). */
209
209
  export declare const HOST_VERSIONS: {
210
210
  readonly kernel: string;
211
- readonly sdk: "0.1.0-rc.88";
211
+ readonly sdk: "0.1.0-rc.89";
212
212
  };
213
213
  /** Whether this deployment satisfies the entry's `minKernel`. */
214
214
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Referenced conversations (@ conversations spec §1–§2): a message may name up to
3
+ * {@link MAX_CONVERSATION_REFS} of the sender's own conversations; each becomes one English text
4
+ * block built here from what was read at send time and logged in the `user_message`, so request
5
+ * building and replay never read another conversation.
6
+ */
7
+ /** The most conversations one message may reference. */
8
+ export declare const MAX_CONVERSATION_REFS = 3;
9
+ /** The newest user / assistant message events read after the latest summary (or from the start). */
10
+ export declare const REF_TURN_MESSAGES = 12;
11
+ /** The longest summary text kept (characters); longer keeps its head and tail. */
12
+ export declare const REF_SUMMARY_MAX = 12000;
13
+ /** The longest message text kept (characters); longer keeps its head and tail. */
14
+ export declare const REF_MESSAGE_MAX = 1500;
15
+ /** The longest block (characters); older messages are dropped first to fit. */
16
+ export declare const REF_BLOCK_MAX = 16000;
17
+ /** What a referenced conversation's block is built from, read at send time. */
18
+ export interface ConversationRefSource {
19
+ id: string;
20
+ /** The title at send time; null: untitled. */
21
+ title: string | null;
22
+ /** The name of the conversation's agent. */
23
+ agentName: string;
24
+ /** When the conversation was last active (its `updated_at`). */
25
+ lastActiveAt: Date;
26
+ /** A run was in progress when it was read: what it had not logged yet is absent. */
27
+ running: boolean;
28
+ /** The latest `compaction_summary` text; null: none. */
29
+ summary: string | null;
30
+ /** The messages after the summary (or the latest ones without one), oldest first. */
31
+ messages: readonly {
32
+ role: "user" | "assistant";
33
+ text: string;
34
+ }[];
35
+ }
36
+ /**
37
+ * `text` clipped to at most `max` characters, the omission marker included: its head and its tail
38
+ * are kept (the end of a summary holds its current work), the middle replaced by
39
+ * `[… n characters omitted …]`.
40
+ */
41
+ export declare function clipMiddle(text: string, max: number): string;
42
+ /**
43
+ * The model-visible text of one referenced conversation: a header naming it (title, id, agent,
44
+ * last active date, a running note), its summary clipped to {@link REF_SUMMARY_MAX}, its latest
45
+ * messages each clipped to {@link REF_MESSAGE_MAX}, and a closing line pointing to the Platform
46
+ * tool's `conversations.events` read. The whole block stays within {@link REF_BLOCK_MAX}
47
+ * characters by dropping the oldest messages first.
48
+ */
49
+ export declare function conversationRefText(src: ConversationRefSource): string;
50
+ /**
51
+ * The text a referenced conversation's message contributes: a `user_message`'s first block when
52
+ * it is text (the typed text, so a message that itself referenced files or conversations brings
53
+ * no nested blocks), an `assistant_message`'s text blocks (no thinking, tool calls or results).
54
+ * A skill invocation contributes what the person typed (`/name args`), never the rendered skill
55
+ * in `content[0]`; a template sub-agent's skill (or its notice) contributes nothing, like
56
+ * `caseTitle` (evals/sets.service.ts).
57
+ */
58
+ export declare function refMessageText(type: string, payload: unknown): string;
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Referenced conversations (@ conversations spec §1–§2): a message may name up to
3
+ * {@link MAX_CONVERSATION_REFS} of the sender's own conversations; each becomes one English text
4
+ * block built here from what was read at send time and logged in the `user_message`, so request
5
+ * building and replay never read another conversation.
6
+ */
7
+ import { typedInvocation } from "./events.js";
8
+ /** The most conversations one message may reference. */
9
+ export const MAX_CONVERSATION_REFS = 3;
10
+ /** The newest user / assistant message events read after the latest summary (or from the start). */
11
+ export const REF_TURN_MESSAGES = 12;
12
+ /** The longest summary text kept (characters); longer keeps its head and tail. */
13
+ export const REF_SUMMARY_MAX = 12_000;
14
+ /** The longest message text kept (characters); longer keeps its head and tail. */
15
+ export const REF_MESSAGE_MAX = 1_500;
16
+ /** The longest block (characters); older messages are dropped first to fit. */
17
+ export const REF_BLOCK_MAX = 16_000;
18
+ /** Characters of `text` (code points, so a clip never splits a surrogate pair). */
19
+ const chars = (text) => Array.from(text);
20
+ /** The omission marker that stands for `n` clipped characters. */
21
+ const omission = (n) => `\n[… ${n} characters omitted …]\n`;
22
+ /**
23
+ * `text` clipped to at most `max` characters, the omission marker included: its head and its tail
24
+ * are kept (the end of a summary holds its current work), the middle replaced by
25
+ * `[… n characters omitted …]`.
26
+ */
27
+ export function clipMiddle(text, max) {
28
+ const cs = chars(text);
29
+ if (cs.length <= max)
30
+ return text;
31
+ // the marker's room is reserved with the digits of the whole length, never fewer than it needs
32
+ const keep = max - chars(omission(cs.length)).length;
33
+ if (keep <= 0)
34
+ return cs.slice(0, max).join("");
35
+ const head = Math.ceil(keep / 2);
36
+ const tail = keep - head;
37
+ return `${cs.slice(0, head).join("")}${omission(cs.length - keep)}${cs
38
+ .slice(cs.length - tail)
39
+ .join("")}`;
40
+ }
41
+ /**
42
+ * The model-visible text of one referenced conversation: a header naming it (title, id, agent,
43
+ * last active date, a running note), its summary clipped to {@link REF_SUMMARY_MAX}, its latest
44
+ * messages each clipped to {@link REF_MESSAGE_MAX}, and a closing line pointing to the Platform
45
+ * tool's `conversations.events` read. The whole block stays within {@link REF_BLOCK_MAX}
46
+ * characters by dropping the oldest messages first.
47
+ */
48
+ export function conversationRefText(src) {
49
+ const title = src.title !== null && src.title.trim() !== "" ? src.title : "Untitled conversation";
50
+ const header = `Referenced conversation: "${title}" (id ${src.id}; another conversation of this person, with ` +
51
+ `the agent ${src.agentName}, last active ${src.lastActiveAt.toISOString().slice(0, 10)}). ` +
52
+ "The text below is quoted from it as context for this message." +
53
+ (src.running ? " It was still running when referenced." : "");
54
+ const summary = src.summary === null
55
+ ? []
56
+ : [`Summary of the conversation: ${clipMiddle(src.summary, REF_SUMMARY_MAX)}`];
57
+ const closing = "End of the referenced conversation. If the Platform tool is available, more of it can be " +
58
+ `read with its conversations.events operation (conversationId ${src.id}).`;
59
+ const lines = src.messages.map((m) => `${m.role === "user" ? "User" : "Agent"}: ${clipMiddle(m.text, REF_MESSAGE_MAX)}`);
60
+ const build = (kept) => [header, ...summary, ...(kept.length > 0 ? ["Latest messages:", ...kept] : []), closing].join("\n");
61
+ let start = 0;
62
+ let text = build(lines);
63
+ while (chars(text).length > REF_BLOCK_MAX && start < lines.length) {
64
+ start++;
65
+ text = build(lines.slice(start));
66
+ }
67
+ return text;
68
+ }
69
+ /**
70
+ * The text a referenced conversation's message contributes: a `user_message`'s first block when
71
+ * it is text (the typed text, so a message that itself referenced files or conversations brings
72
+ * no nested blocks), an `assistant_message`'s text blocks (no thinking, tool calls or results).
73
+ * A skill invocation contributes what the person typed (`/name args`), never the rendered skill
74
+ * in `content[0]`; a template sub-agent's skill (or its notice) contributes nothing, like
75
+ * `caseTitle` (evals/sets.service.ts).
76
+ */
77
+ export function refMessageText(type, payload) {
78
+ const content = payload?.content;
79
+ if (!Array.isArray(content))
80
+ return "";
81
+ const textOf = (b) => {
82
+ const block = b;
83
+ return block !== null &&
84
+ typeof block === "object" &&
85
+ block.type === "text" &&
86
+ typeof block.text === "string"
87
+ ? block.text
88
+ : undefined;
89
+ };
90
+ if (type === "user_message") {
91
+ const p = payload;
92
+ if (p.skill?.template || p.templateSkillNotice !== undefined)
93
+ return "";
94
+ if (p.skill !== undefined)
95
+ return typedInvocation(p.skill).trim();
96
+ return (textOf(content[0]) ?? "").trim();
97
+ }
98
+ return content
99
+ .map(textOf)
100
+ .filter((t) => t !== undefined)
101
+ .join("\n")
102
+ .trim();
103
+ }
@@ -64,6 +64,9 @@ declare const MessageBody: z.ZodObject<{
64
64
  projectFiles: z.ZodOptional<z.ZodArray<z.ZodObject<{
65
65
  path: z.ZodString;
66
66
  }, z.core.$strict>>>;
67
+ conversationRefs: z.ZodOptional<z.ZodArray<z.ZodObject<{
68
+ id: z.ZodString;
69
+ }, z.core.$strict>>>;
67
70
  model: z.ZodOptional<z.ZodObject<{
68
71
  provider: z.ZodString;
69
72
  model: z.ZodString;
@@ -108,6 +111,9 @@ export declare const CreateBody: z.ZodObject<{
108
111
  projectFiles: z.ZodOptional<z.ZodArray<z.ZodObject<{
109
112
  path: z.ZodString;
110
113
  }, z.core.$strict>>>;
114
+ conversationRefs: z.ZodOptional<z.ZodArray<z.ZodObject<{
115
+ id: z.ZodString;
116
+ }, z.core.$strict>>>;
111
117
  model: z.ZodOptional<z.ZodObject<{
112
118
  provider: z.ZodString;
113
119
  model: z.ZodString;
@@ -19,6 +19,7 @@ import { CurrentOrg, OrgAction } from "../orgs/org.guard.js";
19
19
  import { MAX_ATTACHMENTS } from "../tools/connector-content.js";
20
20
  import { ConversationToolInfo, TOOL_INFO_KEY_MAX, TOOL_INFO_MAX_KEYS, } from "../tools/info.js";
21
21
  import { ARTIFACT_DOWNLOAD_CACHE_SECONDS, ConversationArtifacts, } from "./artifacts.js";
22
+ import { MAX_CONVERSATION_REFS } from "./conversation-ref.js";
22
23
  import { CompactBody, DOWNLOAD_AS, EventsQuery, FilesQuery, IdParams, ListQuery, PatchBody, SubagentsQuery, searchFields, } from "./conversations.schemas.js";
23
24
  import { ConversationsService, MAX_PROJECT_FILES, } from "./conversations.service.js";
24
25
  import { ConversationDeviceStatus } from "./device-status.js";
@@ -81,6 +82,15 @@ const MessageFields = z.object({
81
82
  .array(z.object({ path: z.string().min(1).max(4096) }).strict())
82
83
  .max(MAX_PROJECT_FILES)
83
84
  .optional(),
85
+ /**
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.
89
+ */
90
+ conversationRefs: z
91
+ .array(z.object({ id: z.string().min(1).max(100) }).strict())
92
+ .max(MAX_CONVERSATION_REFS)
93
+ .optional(),
84
94
  /** Switch the conversation's model from the next run (UI refresh B); the agent's own = back. */
85
95
  model: ModelRef.strict().optional(),
86
96
  /** Switch the effort: one of the (selected) model's declared `effort` values. */
@@ -109,16 +119,19 @@ const MessageFields = z.object({
109
119
  /** The sender's UI language (run context spec §3.4). */
110
120
  locale: z.enum(["zh", "en"]).optional(),
111
121
  });
112
- // The body of `@` resource i is `content[i + 1]` and project file i's block follows them, so
113
- // `content[0]` must be the user's text: with `@` resources or project files the text must not be
114
- // empty. A skill invocation's `content[0]` is the rendered skill, so its text (the arguments) may
115
- // be empty.
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.
116
126
  const textRule = [
117
127
  (b) => b.text.length > 0 ||
118
128
  b.skill !== undefined ||
119
- ((b.files?.length ?? 0) > 0 && !b.attachments?.length && !b.projectFiles?.length),
129
+ ((b.files?.length ?? 0) > 0 &&
130
+ !b.attachments?.length &&
131
+ !b.projectFiles?.length &&
132
+ !b.conversationRefs?.length),
120
133
  {
121
- message: "Text is required unless the message invokes a skill or carries files (and no @ resources or project files)",
134
+ message: "Text is required unless the message invokes a skill or carries files (and no @ resources, project files or conversation references)",
122
135
  path: ["text"],
123
136
  },
124
137
  ];
@@ -227,6 +240,7 @@ let ConversationsController = class ConversationsController {
227
240
  ...(m.attachments !== undefined && { attachments: m.attachments }),
228
241
  ...(m.files !== undefined && { files: m.files }),
229
242
  ...(m.projectFiles !== undefined && { projectFiles: m.projectFiles }),
243
+ ...(m.conversationRefs !== undefined && { conversationRefs: m.conversationRefs }),
230
244
  ...(m.model !== undefined && { model: m.model }),
231
245
  ...(m.effort !== undefined && { effort: m.effort }),
232
246
  ...(m.skill !== undefined && { skill: m.skill }),
@@ -441,6 +455,9 @@ let ConversationsController = class ConversationsController {
441
455
  ...(body.attachments !== undefined && { attachments: body.attachments }),
442
456
  ...(body.files !== undefined && { files: body.files }),
443
457
  ...(body.projectFiles !== undefined && { projectFiles: body.projectFiles }),
458
+ ...(body.conversationRefs !== undefined && {
459
+ conversationRefs: body.conversationRefs,
460
+ }),
444
461
  ...(body.model !== undefined && { model: body.model }),
445
462
  ...(body.effort !== undefined && { effort: body.effort }),
446
463
  ...(body.retryOf !== undefined && { retryOf: body.retryOf }),
@@ -239,10 +239,27 @@ export interface ResolvedExtra {
239
239
  }[];
240
240
  /** The project root the project file blocks name (set with `projectFiles`). */
241
241
  projectRoot?: string;
242
+ /**
243
+ * The referenced conversations (@ conversations spec §2), in block order after the project
244
+ * files' blocks; absent: none.
245
+ */
246
+ conversationRefs?: ConversationRefMeta[];
247
+ }
248
+ /** One referenced conversation as `payload.conversationRefs` names it. */
249
+ export interface ConversationRefMeta {
250
+ id: string;
251
+ /** The title at send time; null: untitled. */
252
+ title: string | null;
253
+ /** `summary`: built from its latest compaction summary; `excerpt`: from its last messages. */
254
+ source: "summary" | "excerpt";
255
+ /** The highest seq read from it. */
256
+ upToSeq: number;
242
257
  }
243
258
  export { MAX_PROJECT_FILES } from "../devices/device-project-files.service.js";
244
259
  /** Where a message's project files are checked: the conversation's device and bound project. */
245
260
  export interface ProjectFilesTarget {
261
+ /** The conversation being written in (a reference to it is refused); absent: a new one. */
262
+ conversationId?: string | undefined;
246
263
  deviceId: string | null;
247
264
  project: {
248
265
  name: string;
@@ -277,6 +294,13 @@ export interface UserMessageInput {
277
294
  projectFiles?: {
278
295
  path: string;
279
296
  }[];
297
+ /**
298
+ * The sender's own conversations referenced by id (@ conversations spec §1): each is read at
299
+ * send time into one text block ({@link conversationRefText}).
300
+ */
301
+ conversationRefs?: {
302
+ id: string;
303
+ }[];
280
304
  /** Switch the conversation's model from the next run (the agent's own model = back to it). */
281
305
  model?: ModelRef;
282
306
  /** Switch the effort (one of the model's declared `effort` values). */
@@ -605,6 +629,10 @@ export declare class ConversationsService {
605
629
  * write ({@link resolveExtra}); one block each after the `@` resources' bodies, before the
606
630
  * uploaded files' blocks, and `payload.projectFiles`. Any refusal writes nothing; a repeated
607
631
  * send with the same `clientMessageId` returns the written event without checking again.
632
+ *
633
+ * `conversationRefs` (@ conversations spec §1): read as the sender in the same step, one block
634
+ * each after the project files' blocks, and `payload.conversationRefs`; refused and retried
635
+ * like the project files.
608
636
  */
609
637
  postUserMessage(orgId: string, conversationId: string, accountId: string, input: UserMessageInput,
610
638
  /** The request's signal: the project file check on the device stops when the client hangs up. */
@@ -687,7 +715,18 @@ export declare class ConversationsService {
687
715
  * file there → `conversation.project_file_unavailable` with its path; the device codes pass on.
688
716
  * Each becomes a {@link projectFileText} block after the resources' bodies.
689
717
  */
690
- resolveExtra(orgId: string, accountId: string, input: Pick<UserMessageInput, "attachments" | "projectFiles">, target?: ProjectFilesTarget): Promise<ResolvedExtra>;
718
+ resolveExtra(orgId: string, accountId: string, input: Pick<UserMessageInput, "attachments" | "projectFiles" | "conversationRefs">, target?: ProjectFilesTarget): Promise<ResolvedExtra>;
719
+ /**
720
+ * {@link resolveExtra}'s referenced conversations (@ conversations spec §1), read as the sender
721
+ * outside any transaction, once each in the body's order. Each must be the sender's own chat in
722
+ * this org, not deleted, its agent still visible ({@link readable} plus `kind = 'chat'`); any
723
+ * other → `conversation.reference_unavailable` (`details: [{ id }]`, the same for every case);
724
+ * one with no `user_message` yet → the same code with `reason: "empty"`; the conversation
725
+ * being written in → `conversation.reference_self`.
726
+ */
727
+ private readConversationRefs;
728
+ /** One referenced conversation's block and metadata, or why it cannot be referenced. */
729
+ private readConversationRef;
691
730
  /** {@link resolveExtra}'s project file check: the normalized paths and the root, or none. */
692
731
  private checkProjectFiles;
693
732
  /**
@@ -41,6 +41,7 @@ import { ConnectorContent } from "../tools/connector-content.js";
41
41
  import { QuestionsService } from "../tools/questions.service.js";
42
42
  import { ConversationAccess, parentReachable } from "./access.js";
43
43
  import { readAgentTree } from "./agent-tree.js";
44
+ import { conversationRefText, REF_TURN_MESSAGES, refMessageText } from "./conversation-ref.js";
44
45
  import { EventLog } from "./event-log.js";
45
46
  import { peopleOfEvents } from "./event-people.js";
46
47
  import { refFileId } from "./events.js";
@@ -109,6 +110,13 @@ export { MAX_PROJECT_FILES } from "../devices/device-project-files.service.js";
109
110
  * the `user_message`, so replay rebuilds it from the log as it is.
110
111
  */
111
112
  export const projectFileText = (path, root) => `Referenced project file: ${path} (in the project root ${root}; read it with Read when needed).`;
113
+ /**
114
+ * A referenced conversation that cannot be referenced (422, `details: [{ id, reason? }]`): one
115
+ * code and one message for every case, so another person's conversation reads as a missing one.
116
+ */
117
+ const conversationRefUnavailable = (details) => new ApiError("conversation.reference_unavailable", details.every((d) => d.reason === "empty")
118
+ ? "A referenced conversation has no messages yet; remove it and send again"
119
+ : "A referenced conversation is not available; remove it and send again", details);
112
120
  /** A message's project file that cannot be referenced (422, `details: [{ path }]` or `reason`). */
113
121
  const projectFileUnavailable = (message, details) => new ApiError("conversation.project_file_unavailable", message, details);
114
122
  export { userMessageIdemKey } from "./idem-keys.js";
@@ -999,6 +1007,10 @@ let ConversationsService = class ConversationsService {
999
1007
  * write ({@link resolveExtra}); one block each after the `@` resources' bodies, before the
1000
1008
  * uploaded files' blocks, and `payload.projectFiles`. Any refusal writes nothing; a repeated
1001
1009
  * send with the same `clientMessageId` returns the written event without checking again.
1010
+ *
1011
+ * `conversationRefs` (@ conversations spec §1): read as the sender in the same step, one block
1012
+ * each after the project files' blocks, and `payload.conversationRefs`; refused and retried
1013
+ * like the project files.
1002
1014
  */
1003
1015
  async postUserMessage(orgId, conversationId, accountId, input,
1004
1016
  /** The request's signal: the project file check on the device stops when the client hangs up. */
@@ -1016,7 +1028,11 @@ let ConversationsService = class ConversationsService {
1016
1028
  const agent = needsAgent
1017
1029
  ? (await this.agents.get(orgId, conv.agentId, accountId)).definition
1018
1030
  : undefined;
1019
- const extra = await this.resolveExtra(orgId, accountId, input, { ...conv, signal });
1031
+ const extra = await this.resolveExtra(orgId, accountId, input, {
1032
+ ...conv,
1033
+ conversationId,
1034
+ signal,
1035
+ });
1020
1036
  const invoked = agent === undefined
1021
1037
  ? undefined
1022
1038
  : await this.prepareSkill(orgId, accountId, conv.agentId, { conversationId, deviceId: conv.deviceId }, agent, input);
@@ -1290,22 +1306,149 @@ let ConversationsService = class ConversationsService {
1290
1306
  async resolveExtra(orgId, accountId, input, target) {
1291
1307
  const refs = input.attachments ?? [];
1292
1308
  const files = await this.checkProjectFiles(orgId, accountId, input.projectFiles ?? [], target);
1309
+ const conversations = await this.readConversationRefs(orgId, accountId, input.conversationRefs ?? [], target?.conversationId);
1293
1310
  const resolved = refs.length === 0
1294
1311
  ? { blocks: [], attachments: [] }
1295
1312
  : await this.content.resolveAttachments(orgId, accountId, refs);
1296
- if (files === undefined)
1313
+ if (files === undefined && conversations.length === 0)
1297
1314
  return resolved;
1298
1315
  return {
1299
1316
  blocks: [
1300
1317
  ...resolved.blocks,
1301
- ...files.paths.map((path) => ({
1318
+ ...(files?.paths ?? []).map((path) => ({
1302
1319
  type: "text",
1303
- text: projectFileText(path, files.root),
1320
+ text: projectFileText(path, files?.root ?? ""),
1304
1321
  })),
1322
+ ...conversations.map((c) => ({ type: "text", text: c.text })),
1305
1323
  ],
1306
1324
  attachments: resolved.attachments,
1307
- projectFiles: files.paths.map((path) => ({ path })),
1308
- projectRoot: files.root,
1325
+ ...(files !== undefined && {
1326
+ projectFiles: files.paths.map((path) => ({ path })),
1327
+ projectRoot: files.root,
1328
+ }),
1329
+ ...(conversations.length > 0 && { conversationRefs: conversations.map((c) => c.meta) }),
1330
+ };
1331
+ }
1332
+ /**
1333
+ * {@link resolveExtra}'s referenced conversations (@ conversations spec §1), read as the sender
1334
+ * outside any transaction, once each in the body's order. Each must be the sender's own chat in
1335
+ * this org, not deleted, its agent still visible ({@link readable} plus `kind = 'chat'`); any
1336
+ * other → `conversation.reference_unavailable` (`details: [{ id }]`, the same for every case);
1337
+ * one with no `user_message` yet → the same code with `reason: "empty"`; the conversation
1338
+ * being written in → `conversation.reference_self`.
1339
+ */
1340
+ async readConversationRefs(orgId, accountId, refs, selfId) {
1341
+ if (refs.length === 0)
1342
+ return [];
1343
+ const ids = [...new Set(refs.map((r) => r.id))];
1344
+ if (selfId !== undefined && ids.includes(selfId)) {
1345
+ throw new ApiError("conversation.reference_self", "A message cannot reference the conversation it is written in; remove that reference", [{ id: selfId }]);
1346
+ }
1347
+ const refused = [];
1348
+ const read = [];
1349
+ for (const id of ids) {
1350
+ const one = await this.readConversationRef(orgId, accountId, id);
1351
+ if (one === "unavailable")
1352
+ refused.push({ id });
1353
+ else if (one === "empty")
1354
+ refused.push({ id, reason: "empty" });
1355
+ else
1356
+ read.push(one);
1357
+ }
1358
+ // the unavailable ones first: a client reads the first detail's reason for its copy
1359
+ if (refused.length > 0) {
1360
+ throw conversationRefUnavailable([
1361
+ ...refused.filter((r) => r.reason === undefined),
1362
+ ...refused.filter((r) => r.reason !== undefined),
1363
+ ]);
1364
+ }
1365
+ return read;
1366
+ }
1367
+ /** One referenced conversation's block and metadata, or why it cannot be referenced. */
1368
+ async readConversationRef(orgId, accountId, id) {
1369
+ const row = await this.db
1370
+ .selectFrom("conversations")
1371
+ .select(["id", "title", "agent_id", "updated_at"])
1372
+ .select(activitySql("conversations").as("activity"))
1373
+ .where("id", "=", id)
1374
+ .where("org_id", "=", orgId)
1375
+ .where("account_id", "=", accountId)
1376
+ .where("deleted_at", "is", null)
1377
+ // a sub-agent's or an eval replay conversation is never referenced
1378
+ .where("kind", "=", "chat")
1379
+ .executeTakeFirst();
1380
+ if (!row)
1381
+ return "unavailable";
1382
+ let agentName;
1383
+ try {
1384
+ agentName = (await this.agents.get(orgId, row.agent_id, accountId)).definition.name;
1385
+ }
1386
+ catch (e) {
1387
+ if (e instanceof ApiError && e.code === "agent.not_found")
1388
+ return "unavailable";
1389
+ throw e;
1390
+ }
1391
+ // the latest summary (conversation_events_compaction_summary_idx), then the newest messages
1392
+ // after what it covers
1393
+ const summary = await this.db
1394
+ .selectFrom("conversation_events")
1395
+ .select(["seq", sql `payload`.as("payload")])
1396
+ .where("conversation_id", "=", id)
1397
+ .where("type", "=", "compaction_summary")
1398
+ .orderBy("seq", "desc")
1399
+ .limit(1)
1400
+ .executeTakeFirst();
1401
+ const summaryPayload = summary?.payload;
1402
+ const rows = await this.db
1403
+ .selectFrom("conversation_events")
1404
+ .select(["seq", "type", sql `payload`.as("payload")])
1405
+ .where("conversation_id", "=", id)
1406
+ .where("type", "in", ["user_message", "assistant_message"])
1407
+ // only messages with text count toward the cap (a run's tool-only steps carry none)
1408
+ .where(sql `payload -> 'content' @> '[{"type":"text"}]'::jsonb`)
1409
+ .where("seq", ">", String(summaryPayload?.coversUpToSeq ?? 0))
1410
+ .orderBy("seq", "desc")
1411
+ .limit(REF_TURN_MESSAGES)
1412
+ .execute();
1413
+ // nothing to quote: no summary and no message of the person yet (a long run's text replies may
1414
+ // fill the newest rows, and a files-only message has no text, so the log is asked when they
1415
+ // hold none)
1416
+ if (summary === undefined && !rows.some((r) => r.type === "user_message")) {
1417
+ const anyUser = await this.db
1418
+ .selectFrom("conversation_events")
1419
+ .select("seq")
1420
+ .where("conversation_id", "=", id)
1421
+ .where("type", "=", "user_message")
1422
+ .limit(1)
1423
+ .executeTakeFirst();
1424
+ if (anyUser === undefined)
1425
+ return "empty";
1426
+ }
1427
+ const messages = rows
1428
+ .slice()
1429
+ .reverse()
1430
+ .map((r) => ({
1431
+ role: r.type === "user_message" ? "user" : "assistant",
1432
+ text: refMessageText(r.type, r.payload),
1433
+ }))
1434
+ .filter((m) => m.text !== "");
1435
+ const upToSeq = Math.max(Number(rows[0]?.seq ?? 0), Number(summary?.seq ?? 0));
1436
+ return {
1437
+ text: conversationRefText({
1438
+ id,
1439
+ title: row.title,
1440
+ agentName,
1441
+ lastActiveAt: row.updated_at,
1442
+ running: row.activity === "running",
1443
+ summary: summaryPayload?.text ?? null,
1444
+ messages,
1445
+ }),
1446
+ meta: {
1447
+ id,
1448
+ title: row.title,
1449
+ source: summary === undefined ? "excerpt" : "summary",
1450
+ upToSeq,
1451
+ },
1309
1452
  };
1310
1453
  }
1311
1454
  /** {@link resolveExtra}'s project file check: the normalized paths and the root, or none. */
@@ -1356,6 +1499,8 @@ let ConversationsService = class ConversationsService {
1356
1499
  ...(extra.attachments.length > 0 && { attachments: extra.attachments }),
1357
1500
  ...(extra.projectFiles !== undefined &&
1358
1501
  extra.projectFiles.length > 0 && { projectFiles: extra.projectFiles }),
1502
+ ...(extra.conversationRefs !== undefined &&
1503
+ extra.conversationRefs.length > 0 && { conversationRefs: extra.conversationRefs }),
1359
1504
  authorAccountId: accountId,
1360
1505
  ...context,
1361
1506
  ...(input.clientMessageId !== undefined && { clientMessageId: input.clientMessageId }),
@@ -969,6 +969,15 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
969
969
  projectFiles: z.ZodOptional<z.ZodArray<z.ZodObject<{
970
970
  path: z.ZodString;
971
971
  }, z.core.$strip>>>;
972
+ conversationRefs: z.ZodOptional<z.ZodArray<z.ZodObject<{
973
+ id: z.ZodString;
974
+ title: z.ZodNullable<z.ZodString>;
975
+ source: z.ZodEnum<{
976
+ excerpt: "excerpt";
977
+ summary: "summary";
978
+ }>;
979
+ upToSeq: z.ZodNumber;
980
+ }, z.core.$strip>>>;
972
981
  authorAccountId: z.ZodString;
973
982
  sender: z.ZodOptional<z.ZodObject<{
974
983
  name: z.ZodString;
@@ -890,6 +890,20 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
890
890
  * body's list. Absent: none.
891
891
  */
892
892
  projectFiles: z.array(z.object({ path: z.string() })).optional(),
893
+ /**
894
+ * The referenced conversations (@ conversations spec §2): the quoted block of reference i is
895
+ * `content[1 + attachments.length + projectFiles.length + i]`, before the uploaded files'
896
+ * blocks. `title` is the title at send time (null: untitled), `source` what the block was
897
+ * built from, `upToSeq` the highest seq read. Deduplicated. Absent: none.
898
+ */
899
+ conversationRefs: z
900
+ .array(z.object({
901
+ id: z.string(),
902
+ title: z.string().nullable(),
903
+ source: z.enum(["summary", "excerpt"]),
904
+ upToSeq: z.number().int().nonnegative(),
905
+ }))
906
+ .optional(),
893
907
  authorAccountId: z.string(),
894
908
  /**
895
909
  * Who wrote the message, at send time (run context spec §3.2): display name and org role
@@ -19,6 +19,9 @@ export declare const FirstMessageBody: z.ZodObject<{
19
19
  projectFiles: z.ZodOptional<z.ZodArray<z.ZodObject<{
20
20
  path: z.ZodString;
21
21
  }, z.core.$strict>>>;
22
+ conversationRefs: z.ZodOptional<z.ZodArray<z.ZodObject<{
23
+ id: z.ZodString;
24
+ }, z.core.$strict>>>;
22
25
  model: z.ZodOptional<z.ZodObject<{
23
26
  provider: z.ZodString;
24
27
  model: z.ZodString;
@@ -52,6 +52,9 @@ let PermissionProfilesController = class PermissionProfilesController {
52
52
  ...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
53
53
  ...(message.files !== undefined ? { files: message.files } : {}),
54
54
  ...(message.projectFiles !== undefined ? { projectFiles: message.projectFiles } : {}),
55
+ ...(message.conversationRefs !== undefined
56
+ ? { conversationRefs: message.conversationRefs }
57
+ : {}),
55
58
  ...(message.model !== undefined ? { model: message.model } : {}),
56
59
  ...(message.effort !== undefined ? { effort: message.effort } : {}),
57
60
  ...(message.skill !== undefined ? { skill: message.skill } : {}),
@@ -1778,8 +1778,19 @@ export interface InboxItemsTable {
1778
1778
  /** The posting extension; null for a kernel item. */
1779
1779
  plugin: NullableText;
1780
1780
  kind: string;
1781
+ /** The title as a single string; the English one when the post gave `{ zh, en }`. */
1781
1782
  title: string;
1782
1783
  body: ColumnType<string, string | undefined, string>;
1784
+ /** The post's `{ zh, en }` title as given; null when it gave a single string. */
1785
+ title_localized: ColumnType<{
1786
+ zh: string;
1787
+ en: string;
1788
+ } | null, string | null | undefined, string | null>;
1789
+ /** The post's `{ zh, en }` body as given; null when it gave a single string or none. */
1790
+ body_localized: ColumnType<{
1791
+ zh: string;
1792
+ en: string;
1793
+ } | null, string | null | undefined, string | null>;
1783
1794
  link: NullableText;
1784
1795
  actions: ColumnType<StoredInboxAction[], string | undefined, string>;
1785
1796
  dedupe_key: NullableText;
package/dist/errors.d.ts CHANGED
@@ -396,6 +396,14 @@ export declare const ERROR_CODES: {
396
396
  * `details: [{ path?, reason? }]`.
397
397
  */
398
398
  readonly "conversation.project_file_unavailable": 422;
399
+ /**
400
+ * A referenced conversation cannot be referenced (@ conversations spec §1): missing, deleted,
401
+ * another person's or org's, a sub-agent's or eval conversation, or its agent no longer visible,
402
+ * all alike; or it has no messages yet (`reason: "empty"`); `details: [{ id, reason? }]`.
403
+ */
404
+ readonly "conversation.reference_unavailable": 422;
405
+ /** A message references the conversation it is written in; `details: [{ id }]`. */
406
+ readonly "conversation.reference_self": 422;
399
407
  readonly "run.not_active": 409;
400
408
  /** A run that is not one of the conversation's (the live draft route, spec 2026-11-07 §3.2). */
401
409
  readonly "run.not_found": 404;
package/dist/errors.js CHANGED
@@ -396,6 +396,14 @@ export const ERROR_CODES = {
396
396
  * `details: [{ path?, reason? }]`.
397
397
  */
398
398
  "conversation.project_file_unavailable": 422,
399
+ /**
400
+ * A referenced conversation cannot be referenced (@ conversations spec §1): missing, deleted,
401
+ * another person's or org's, a sub-agent's or eval conversation, or its agent no longer visible,
402
+ * all alike; or it has no messages yet (`reason: "empty"`); `details: [{ id, reason? }]`.
403
+ */
404
+ "conversation.reference_unavailable": 422,
405
+ /** A message references the conversation it is written in; `details: [{ id }]`. */
406
+ "conversation.reference_self": 422,
399
407
  "run.not_active": 409,
400
408
  /** A run that is not one of the conversation's (the live draft route, spec 2026-11-07 §3.2). */
401
409
  "run.not_found": 404,
@@ -1,4 +1,4 @@
1
- import { type InboxPost, type LocalizedName } from "@capybara-hq/plugin-sdk";
1
+ import { type InboxPost, type LocalizedName, type LocalizedText } from "@capybara-hq/plugin-sdk";
2
2
  import type { StoredInboxAction } from "../db/kernel-schema.js";
3
3
  import { KernelDb } from "../infra/database/kernel-db.js";
4
4
  import { TransactionHost } from "../infra/database/transaction-host.js";
@@ -24,8 +24,10 @@ export interface PersonalInboxItemView {
24
24
  /** The plugin's display name (its name in both languages when it has none); null for the kernel. */
25
25
  pluginName: LocalizedName | null;
26
26
  kind: string;
27
- title: string;
28
- body: string;
27
+ /** As posted: a single string, or `{ zh, en }` the reader sees in their language. */
28
+ title: LocalizedText;
29
+ /** As posted, like `title` (`""`: none). */
30
+ body: LocalizedText;
29
31
  /** An in-app path; a plugin item's is one of the plugin's pages (`/p/<plugin>/…`). */
30
32
  link: string | null;
31
33
  actions: {
@@ -31,6 +31,10 @@ const kernelLinkOk = (link) => link.startsWith("/") &&
31
31
  !link.startsWith("//") &&
32
32
  link.length <= INBOX_LIMITS.linkChars &&
33
33
  !/[\\\p{Cc}]/u.test(link);
34
+ /** A posted text as one string: itself, or the English one of `{ zh, en }`. */
35
+ const single = (t) => (typeof t === "string" ? t : t.en);
36
+ /** A posted `{ zh, en }` text as its stored JSON (only the two languages); null for a string. */
37
+ const localized = (t) => typeof t === "string" ? null : JSON.stringify({ zh: t.zh, en: t.en });
34
38
  const notFound = () => new ApiError("inbox.item_not_found", "Inbox item not found");
35
39
  /**
36
40
  * Personal inbox items (`inbox_items`, collaboration spec §4.9): an item for one person in one
@@ -125,8 +129,10 @@ let InboxItemsService = class InboxItemsService {
125
129
  source: source.kind,
126
130
  plugin,
127
131
  kind: p.kind,
128
- title: p.title,
129
- body: p.body ?? "",
132
+ title: single(p.title),
133
+ body: p.body === undefined ? "" : single(p.body),
134
+ title_localized: localized(p.title),
135
+ body_localized: p.body === undefined ? null : localized(p.body),
130
136
  link: p.link ?? null,
131
137
  actions: JSON.stringify(actions),
132
138
  dedupe_key: dedupe,
@@ -253,6 +259,8 @@ let InboxItemsService = class InboxItemsService {
253
259
  "kind",
254
260
  "title",
255
261
  "body",
262
+ "title_localized",
263
+ "body_localized",
256
264
  "link",
257
265
  "actions",
258
266
  "detail",
@@ -274,8 +282,8 @@ let InboxItemsService = class InboxItemsService {
274
282
  plugin: r.plugin,
275
283
  pluginName: r.plugin === null ? null : (names.get(r.plugin) ?? null),
276
284
  kind: r.kind,
277
- title: r.title,
278
- body: r.body,
285
+ title: r.title_localized ?? r.title,
286
+ body: r.body_localized ?? r.body,
279
287
  link: r.link,
280
288
  actions: r.actions.map((a) => ({
281
289
  id: a.id,
package/dist/log.d.ts CHANGED
@@ -36,6 +36,10 @@ export interface KernelLogger extends Logger {
36
36
  */
37
37
  child(fields: Record<string, string>): KernelLogger;
38
38
  }
39
+ /** Counts the candidate comparisons a matcher makes (tests). */
40
+ export interface MatcherProbes {
41
+ count: number;
42
+ }
39
43
  /**
40
44
  * 用与 logger 相同的匹配器打码任意文本(工具结果等不经过日志的内容用):展开规则同 `addOrgSecrets`
41
45
  * (URL 形式的值另登记 `user:password@` 片段),只取长度 ≥ `minLength` 的值(默认 12,同组织来源密钥;
@@ -78,6 +82,8 @@ export interface LoggerOptions {
78
82
  orgSecretCapacity?: number;
79
83
  /** Called on every matcher rebuild (tests). */
80
84
  onMatcherBuild?: () => void;
85
+ /** Counts the candidate comparisons the matchers make (tests). */
86
+ matcherProbes?: MatcherProbes;
81
87
  }
82
88
  /**
83
89
  * Creates the kernel logger on pino. Each record is `{ time, level, msg, ...base, ...fields }` with
package/dist/log.js CHANGED
@@ -17,38 +17,66 @@ const ORG_SECRET_CAPACITY = 10_000;
17
17
  /** 匹配器按前缀分桶的前缀长度(不超过两种最短登记长度)。 */
18
18
  const PREFIX_LEN = MIN_SECRET_LEN;
19
19
  /**
20
- * 编译后的打码匹配器:按值的前 `PREFIX_LEN` 个字符分桶,桶内按长度降序。扫描字符串时每个位置查一次桶、
21
- * 记下最长命中的区间,重叠或相邻的区间合并后替换;开销与字符串长度成正比,与登记的密钥数基本无关。
20
+ * The compiled redaction matcher. Values are bucketed by their first `PREFIX_LEN` characters; inside a
21
+ * bucket, by length, one set per distinct length, longest first. At each position of the scanned
22
+ * string it looks up the bucket once and probes each of its lengths once (a set lookup of the slice of
23
+ * that length), keeping the longest hit; overlapping or adjacent hits merge and are replaced. The cost
24
+ * grows with the string's length and the number of distinct lengths in a bucket, never with the
25
+ * number of registered values: many secrets sharing a prefix (`sk-proj-`, `ghp_`) cost no more.
22
26
  */
23
- function compileMatcher(values) {
24
- const buckets = new Map();
27
+ function compileMatcher(values, probes) {
28
+ const byPrefix = new Map();
25
29
  for (const v of values) {
26
30
  const key = v.slice(0, PREFIX_LEN);
27
- const b = buckets.get(key);
28
- if (b)
29
- b.push(v);
31
+ let byLen = byPrefix.get(key);
32
+ if (!byLen) {
33
+ byLen = new Map();
34
+ byPrefix.set(key, byLen);
35
+ }
36
+ const set = byLen.get(v.length);
37
+ if (set)
38
+ set.add(v);
30
39
  else
31
- buckets.set(key, [v]);
40
+ byLen.set(v.length, new Set([v]));
32
41
  }
33
- if (buckets.size === 0)
42
+ if (byPrefix.size === 0)
34
43
  return (s) => s;
35
- for (const b of buckets.values())
36
- b.sort((a, c) => c.length - a.length);
44
+ const buckets = new Map();
45
+ for (const [key, byLen] of byPrefix) {
46
+ const lens = [...byLen.keys()].sort((a, c) => c - a);
47
+ buckets.set(key, { lens, sets: lens.map((l) => byLen.get(l)) });
48
+ }
49
+ const longest = (s, i) => {
50
+ const b = buckets.get(s.slice(i, i + PREFIX_LEN));
51
+ if (!b)
52
+ return 0;
53
+ const room = s.length - i;
54
+ for (let k = 0; k < b.lens.length; k++) {
55
+ const len = b.lens[k];
56
+ if (len > room)
57
+ continue;
58
+ if (probes)
59
+ probes.count++;
60
+ if (b.sets[k].has(s.slice(i, i + len)))
61
+ return len;
62
+ }
63
+ return 0;
64
+ };
37
65
  return (s) => {
38
66
  if (s.length < PREFIX_LEN)
39
67
  return s;
40
- // 每个位置都记下最长命中的区间 [i, i + len),不跳过(否则先开始的密钥会吞掉与之重叠的后一个密钥的开头,
41
- // 使后者剩余部分明文输出);重叠或相邻的区间合并后整段替换为一个 [REDACTED]。
68
+ // Record the longest hit [i, i + len) at every position without skipping ahead (skipping would
69
+ // let an earlier secret swallow the start of an overlapping later one and leave its rest in
70
+ // clear text); overlapping or adjacent hits merge into one [REDACTED].
42
71
  let out = "";
43
72
  let last = 0;
44
73
  let runStart = -1;
45
74
  let runEnd = -1;
46
75
  for (let i = 0; i <= s.length - PREFIX_LEN; i++) {
47
- const b = buckets.get(s.slice(i, i + PREFIX_LEN));
48
- const hit = b?.find((v) => s.startsWith(v, i));
49
- if (!hit)
76
+ const len = longest(s, i);
77
+ if (len === 0)
50
78
  continue;
51
- const end = i + hit.length;
79
+ const end = i + len;
52
80
  if (runStart >= 0 && i <= runEnd) {
53
81
  if (end > runEnd)
54
82
  runEnd = end;
@@ -220,7 +248,7 @@ export function createLogger(level = "info", opts = {}) {
220
248
  let deployMatcher;
221
249
  const redact = (s) => {
222
250
  if (!matcher) {
223
- matcher = compileMatcher(new Set([...secrets, ...orgSecrets]));
251
+ matcher = compileMatcher(new Set([...secrets, ...orgSecrets]), opts.matcherProbes);
224
252
  opts.onMatcherBuild?.();
225
253
  }
226
254
  return matcher(s);
@@ -228,7 +256,7 @@ export function createLogger(level = "info", opts = {}) {
228
256
  /** 顶层 msg 只按部署方密钥打码:组织来源的值不能遮蔽日志消息。 */
229
257
  const redactMsg = (s) => {
230
258
  if (!deployMatcher) {
231
- deployMatcher = compileMatcher(secrets);
259
+ deployMatcher = compileMatcher(secrets, opts.matcherProbes);
232
260
  opts.onMatcherBuild?.();
233
261
  }
234
262
  return deployMatcher(s);
@@ -38,6 +38,8 @@ const NOT_FOUND = {
38
38
  const DECIDE_REQUEST_ON_WEB = "Decide it on the web, in the inbox.";
39
39
  const DISMISS_ORG = "Dismiss it with inbox.dismiss-notice once read.";
40
40
  const ADMIN_CONSOLE_PENDING = "Review it in the admin console (plugins, pending tab).";
41
+ /** A personal item's text in `lang`: a single string as is, else that language of `{ zh, en }`. */
42
+ const textIn = (t, lang) => typeof t === "string" ? t : t[lang];
41
43
  /** What a request asks for, by name (the plugin, the marketplace entry or the agent). */
42
44
  const requestName = (r) => r.item?.name ?? r.entry?.name ?? r.agent?.name ?? r.kind;
43
45
  const requester = (r) => r.requestedByName ?? "a deleted account";
@@ -140,7 +142,7 @@ function orgRow(i) {
140
142
  ...base,
141
143
  name: it.pluginName?.en ?? "Capybara",
142
144
  state: "open",
143
- summary: `${it.title}${it.body !== "" ? `: ${it.body}` : ""}`,
145
+ summary: `${textIn(it.title, "en")}${textIn(it.body, "en") !== "" ? `: ${textIn(it.body, "en")}` : ""}`,
144
146
  next: it.actions.length > 0
145
147
  ? "Its buttons are pressed by you on the web, in the inbox; dismiss it with inbox.item-dismiss once read."
146
148
  : "Dismiss it with inbox.item-dismiss once read.",
@@ -384,10 +386,10 @@ let InboxOperations = class InboxOperations {
384
386
  summary: async (input, ctx) => {
385
387
  const open = await orElse(() => this.items.listOpen(ctx.orgId, ctx.actorAccountId), []);
386
388
  const it = open.find((x) => x.id === input.id);
387
- const name = named(it === undefined ? input.id : it.title);
389
+ const name = (lang) => named(it === undefined ? input.id : textIn(it.title, lang));
388
390
  return {
389
- zh: `从你的收件箱移除「${name}」`,
390
- en: `Dismiss "${name}" from your inbox`,
391
+ zh: `从你的收件箱移除「${name("zh")}」`,
392
+ en: `Dismiss "${name("en")}" from your inbox`,
391
393
  };
392
394
  },
393
395
  run: async (input, ctx) => {
@@ -43,7 +43,7 @@ async function resolveInboxItem(db, itemId) {
43
43
  // org, which every later read filters by
44
44
  const item = await db
45
45
  .selectFrom("inbox_items")
46
- .select(["org_id", "account_id", "plugin", "title", "state", "expires_at"])
46
+ .select(["org_id", "account_id", "plugin", "title", "title_localized", "state", "expires_at"])
47
47
  .where("id", "=", itemId)
48
48
  .executeTakeFirst();
49
49
  if (!item || item.state !== "open" || item.expires_at.getTime() <= Date.now())
@@ -66,7 +66,7 @@ async function resolveInboxItem(db, itemId) {
66
66
  path: `/inbox?org=${encodeURIComponent(orgId)}#item=${encodeURIComponent(itemId)}`,
67
67
  threadId: "inbox",
68
68
  title,
69
- conversationTitle: item.title,
69
+ conversationTitle: item.title_localized ?? item.title,
70
70
  text: "inboxItem",
71
71
  };
72
72
  }
@@ -26,8 +26,14 @@ export interface ResolvedPush {
26
26
  zh: string;
27
27
  en: string;
28
28
  };
29
- /** Shown only with `push.previews: "titles"` (an inbox item's title). */
30
- conversationTitle: string | null;
29
+ /**
30
+ * Shown only with `push.previews: "titles"` (an inbox item's title; a localized one is shown in
31
+ * the registration's locale).
32
+ */
33
+ conversationTitle: string | {
34
+ zh: string;
35
+ en: string;
36
+ } | null;
31
37
  text: PushTextKey;
32
38
  }
33
39
  /**
@@ -34,7 +34,10 @@ function cut(s, max) {
34
34
  */
35
35
  export function renderPushMessage(r, locale, previews, origin) {
36
36
  const sentence = pushText(r.text, locale);
37
- const lead = previews === "titles" && r.conversationTitle ? r.conversationTitle : null;
37
+ const conversationTitle = r.conversationTitle === null || typeof r.conversationTitle === "string"
38
+ ? r.conversationTitle
39
+ : r.conversationTitle[locale];
40
+ const lead = previews === "titles" && conversationTitle ? conversationTitle : null;
38
41
  const body = lead === null ? sentence : `${lead}${locale === "zh" ? ":" : ": "}${sentence}`;
39
42
  return {
40
43
  title: cut(typeof r.title === "string" ? r.title : r.title[locale], PUSH_LIMITS.titleChars),
@@ -267,7 +267,9 @@ export const PERSON_MESSAGES_READ = 20;
267
267
  * referenced project files (`payload.projectFiles`, blocks `1 + attachments.length + i`: the
268
268
  * person's intent, worded by the kernel). The `@` resources' bodies (`payload.attachments`,
269
269
  * blocks `1 .. attachments.length`) are content read from a connector, not the person's
270
- * instructions, so they are skipped, like images, documents and uploaded files.
270
+ * instructions, so they are skipped, like images, documents and uploaded files. So are the
271
+ * referenced conversations' blocks (`payload.conversationRefs`, after the project file lines):
272
+ * quoted material, not the person's intent.
271
273
  */
272
274
  function textOfUserMessage(payload) {
273
275
  const p = payload;
@@ -2,7 +2,7 @@
2
2
  // definition was validated at import, but it is read back from a database row: every value is
3
3
  // checked again here with the SDK's grammars before it is written into CSS, so a changed row cannot
4
4
  // inject CSS. A value that fails is left out and reported.
5
- import { canonicalThemeValue, isThemeAssetPath, isThemeFontFamily, THEME_FONTS, THEME_OVERRIDABLE, THEME_TOKENS, } from "@capybara-hq/plugin-sdk";
5
+ import { canonicalThemeValue, isThemeAssetPath, isThemeFontFamily, THEME_FONTS, THEME_OVERRIDABLE, THEME_TOKENS, themeSchemeFallbacks, } from "@capybara-hq/plugin-sdk";
6
6
  const SCHEMES = ["dark", "light"];
7
7
  const GROUPS = ["color", "shadow"];
8
8
  const OVERRIDABLE = {
@@ -36,6 +36,7 @@ function schemeDeclarations(theme, scheme, full, skip) {
36
36
  const over = theme.schemes?.[scheme];
37
37
  if (!isRecord(over))
38
38
  return out;
39
+ const colors = new Set();
39
40
  for (const g of GROUPS) {
40
41
  const values = over[g];
41
42
  if (!isRecord(values))
@@ -44,10 +45,16 @@ function schemeDeclarations(theme, scheme, full, skip) {
44
45
  const v = OVERRIDABLE[g].has(n) ? canonicalThemeValue(g, raw) : undefined;
45
46
  if (v === undefined)
46
47
  skip(`schemes.${scheme}.${g}.${n}`);
47
- else
48
+ else {
48
49
  out.set(VARIABLE[g](n), v);
50
+ if (g === "color")
51
+ colors.add(n);
52
+ }
49
53
  }
50
54
  }
55
+ // A token the built-in palette fills only for itself (the SDK names them)
56
+ for (const [n, v] of Object.entries(themeSchemeFallbacks(colors)))
57
+ out.set(VARIABLE.color(n), v);
51
58
  const radius = over.radius;
52
59
  if (isRecord(radius)) {
53
60
  for (const [n, raw] of Object.entries(radius)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.111",
3
+ "version": "0.1.0-rc.112",
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": {
@@ -66,7 +66,7 @@
66
66
  "yaml": "^2.9.1",
67
67
  "yauzl": "3.4.0",
68
68
  "zod": "^4.6.7",
69
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.88"
69
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.89"
70
70
  },
71
71
  "devDependencies": {
72
72
  "@langchain/langgraph-checkpoint-validation": "^1.2.0",
@@ -0,0 +1,8 @@
1
+ -- @ conversations (spec §1): a message referencing another conversation reads that conversation's
2
+ -- latest `compaction_summary` at send time, as do skill loads (`invokedInContext`); a summary is
3
+ -- written rarely, so without this partial index the lookup scans the conversation's events
4
+ -- backwards. `conversation_events` has no `org_id`, so no RLS policy. Not CONCURRENTLY, like the
5
+ -- other index migrations (0025, 0094, 0133).
6
+ CREATE INDEX IF NOT EXISTS conversation_events_compaction_summary_idx
7
+ ON conversation_events (conversation_id, seq)
8
+ WHERE type = 'compaction_summary';
@@ -0,0 +1,8 @@
1
+ -- Localized inbox item texts: `ctx.inbox.post` takes a title and a body as a single string or as
2
+ -- `{ zh, en }` (like its action labels). A bilingual text is kept as given in `title_localized` /
3
+ -- `body_localized`, and `title` / `body` keep its English text, so every reader of the single
4
+ -- string (the Platform tool's English rows, a replica still on the previous version) reads one.
5
+ -- Null: the post gave a single string (or no body).
6
+
7
+ ALTER TABLE inbox_items ADD COLUMN IF NOT EXISTS title_localized jsonb;
8
+ ALTER TABLE inbox_items ADD COLUMN IF NOT EXISTS body_localized jsonb;
@@ -0,0 +1,10 @@
1
+ -- The acceptance automation's prompt states the mechanism for any directed event (an assignment,
2
+ -- an unassignment, an answer, ...), not "this work was assigned to you". Acceptance automations
3
+ -- that still carry the old kernel text, unedited, get the new one; a prompt the person edited stays
4
+ -- as it is. Past fires keep the text their messages recorded (the event log is never rewritten).
5
+
6
+ UPDATE automations
7
+ SET prompt = 'The events above were directed to you and your agent by their source; your acceptance rule for that source delivers them to this automation. Each one names its type, its subject and the source''s own summary of what happened. Decide from them what, if anything, is now expected of you: do it within what you are allowed to do and report what you did, or say why nothing needs doing.',
8
+ updated_at = now()
9
+ WHERE origin = 'acceptance'
10
+ AND prompt = 'This work was assigned to you. Read the assigned item, do what it asks within what you are allowed to do, and report what you did.';