@capybara-hq/kernel 0.1.0-rc.111 → 0.1.0-rc.113
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/dist/automations/errors.js +1 -1
- package/dist/automations/events/acceptance.d.ts +7 -2
- package/dist/automations/events/acceptance.js +7 -2
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/conversations/conversation-ref.d.ts +58 -0
- package/dist/conversations/conversation-ref.js +103 -0
- package/dist/conversations/conversations.controller.d.ts +6 -0
- package/dist/conversations/conversations.controller.js +23 -6
- package/dist/conversations/conversations.service.d.ts +40 -1
- package/dist/conversations/conversations.service.js +163 -11
- package/dist/conversations/events.d.ts +9 -0
- package/dist/conversations/events.js +14 -0
- package/dist/conversations/permission-profiles.controller.d.ts +3 -0
- package/dist/conversations/permission-profiles.controller.js +3 -0
- package/dist/db/kernel-schema.d.ts +11 -0
- package/dist/errors.d.ts +8 -0
- package/dist/errors.js +8 -0
- package/dist/inbox/inbox-items.service.d.ts +5 -3
- package/dist/inbox/inbox-items.service.js +12 -4
- package/dist/log.d.ts +6 -0
- package/dist/log.js +47 -19
- package/dist/platform/ops/agent-skills.ops.js +6 -2
- package/dist/platform/ops/inbox.ops.js +6 -4
- package/dist/push/recipients.js +2 -2
- package/dist/push/texts.d.ts +8 -2
- package/dist/push/texts.js +4 -1
- package/dist/sandbox/review/classifier.js +3 -1
- package/dist/skills/invocable.controller.d.ts +4 -0
- package/dist/skills/invocable.controller.js +5 -1
- package/dist/skills/invoke.d.ts +68 -2
- package/dist/skills/invoke.js +128 -13
- package/dist/skills/skills.schemas.d.ts +7 -1
- package/dist/skills/skills.schemas.js +11 -2
- package/dist/themes/render-css.js +9 -2
- package/package.json +2 -2
- package/src/migrations/0196_conversation_events_compaction_summary_idx.sql +8 -0
- package/src/migrations/0197_inbox_item_localized_text.sql +8 -0
- 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
|
|
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
|
-
/**
|
|
18
|
-
|
|
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
|
-
/**
|
|
38
|
-
|
|
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.
|
|
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]
|
|
113
|
-
// `content[0]` must be the user's text: with `@` resources
|
|
114
|
-
//
|
|
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 &&
|
|
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
|
|
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
|
/**
|
|
@@ -28,6 +28,7 @@ import { TransactionHost, withTransactionFencePrelude, } from "../infra/database
|
|
|
28
28
|
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
29
29
|
import { KernelEvents } from "../infra/events/kernel-events.js";
|
|
30
30
|
import { OutboxService } from "../infra/outbox/outbox.service.js";
|
|
31
|
+
import { projectSkillOf } from "../runtime/context/project-root.js";
|
|
31
32
|
import { ProviderRegistry } from "../runtime/providers.js";
|
|
32
33
|
import { RunControl as RunControlService } from "../runtime/run-control.js";
|
|
33
34
|
import { RunDeletion } from "../runtime/run-deletion.js";
|
|
@@ -41,6 +42,7 @@ import { ConnectorContent } from "../tools/connector-content.js";
|
|
|
41
42
|
import { QuestionsService } from "../tools/questions.service.js";
|
|
42
43
|
import { ConversationAccess, parentReachable } from "./access.js";
|
|
43
44
|
import { readAgentTree } from "./agent-tree.js";
|
|
45
|
+
import { conversationRefText, REF_TURN_MESSAGES, refMessageText } from "./conversation-ref.js";
|
|
44
46
|
import { EventLog } from "./event-log.js";
|
|
45
47
|
import { peopleOfEvents } from "./event-people.js";
|
|
46
48
|
import { refFileId } from "./events.js";
|
|
@@ -109,6 +111,13 @@ export { MAX_PROJECT_FILES } from "../devices/device-project-files.service.js";
|
|
|
109
111
|
* the `user_message`, so replay rebuilds it from the log as it is.
|
|
110
112
|
*/
|
|
111
113
|
export const projectFileText = (path, root) => `Referenced project file: ${path} (in the project root ${root}; read it with Read when needed).`;
|
|
114
|
+
/**
|
|
115
|
+
* A referenced conversation that cannot be referenced (422, `details: [{ id, reason? }]`): one
|
|
116
|
+
* code and one message for every case, so another person's conversation reads as a missing one.
|
|
117
|
+
*/
|
|
118
|
+
const conversationRefUnavailable = (details) => new ApiError("conversation.reference_unavailable", details.every((d) => d.reason === "empty")
|
|
119
|
+
? "A referenced conversation has no messages yet; remove it and send again"
|
|
120
|
+
: "A referenced conversation is not available; remove it and send again", details);
|
|
112
121
|
/** A message's project file that cannot be referenced (422, `details: [{ path }]` or `reason`). */
|
|
113
122
|
const projectFileUnavailable = (message, details) => new ApiError("conversation.project_file_unavailable", message, details);
|
|
114
123
|
export { userMessageIdemKey } from "./idem-keys.js";
|
|
@@ -318,8 +327,10 @@ let ConversationsService = class ConversationsService {
|
|
|
318
327
|
return prior;
|
|
319
328
|
const deviceId = await this.devices.forNew(orgId, accountId, pick);
|
|
320
329
|
const next = await this.planSwitch(orgId, agent.definition, NO_SELECTION, input);
|
|
321
|
-
// the project its files are checked in,
|
|
322
|
-
|
|
330
|
+
// the project its files are checked in, or its project skill is rendered from, read before the
|
|
331
|
+
// write (the binding inside it decides)
|
|
332
|
+
const project = (input.projectFiles?.length ?? 0) > 0 ||
|
|
333
|
+
(input.skill !== undefined && projectSkillOf(input.skill.name) !== undefined)
|
|
323
334
|
? await this.bindingFor(orgId, accountId, deviceId, pick.project)
|
|
324
335
|
: undefined;
|
|
325
336
|
const extra = await this.resolveExtra(orgId, accountId, input, {
|
|
@@ -327,7 +338,7 @@ let ConversationsService = class ConversationsService {
|
|
|
327
338
|
project,
|
|
328
339
|
signal: internal.signal,
|
|
329
340
|
});
|
|
330
|
-
const invoked = await this.prepareSkill(orgId, accountId, agentId, { conversationId: undefined, deviceId }, agent.definition, input);
|
|
341
|
+
const invoked = await this.prepareSkill(orgId, accountId, agentId, { conversationId: undefined, deviceId, ...(project !== undefined && { project }) }, agent.definition, input);
|
|
331
342
|
const id = randomUUID();
|
|
332
343
|
let all;
|
|
333
344
|
try {
|
|
@@ -999,6 +1010,10 @@ let ConversationsService = class ConversationsService {
|
|
|
999
1010
|
* write ({@link resolveExtra}); one block each after the `@` resources' bodies, before the
|
|
1000
1011
|
* uploaded files' blocks, and `payload.projectFiles`. Any refusal writes nothing; a repeated
|
|
1001
1012
|
* send with the same `clientMessageId` returns the written event without checking again.
|
|
1013
|
+
*
|
|
1014
|
+
* `conversationRefs` (@ conversations spec §1): read as the sender in the same step, one block
|
|
1015
|
+
* each after the project files' blocks, and `payload.conversationRefs`; refused and retried
|
|
1016
|
+
* like the project files.
|
|
1002
1017
|
*/
|
|
1003
1018
|
async postUserMessage(orgId, conversationId, accountId, input,
|
|
1004
1019
|
/** The request's signal: the project file check on the device stops when the client hangs up. */
|
|
@@ -1016,7 +1031,11 @@ let ConversationsService = class ConversationsService {
|
|
|
1016
1031
|
const agent = needsAgent
|
|
1017
1032
|
? (await this.agents.get(orgId, conv.agentId, accountId)).definition
|
|
1018
1033
|
: undefined;
|
|
1019
|
-
const extra = await this.resolveExtra(orgId, accountId, input, {
|
|
1034
|
+
const extra = await this.resolveExtra(orgId, accountId, input, {
|
|
1035
|
+
...conv,
|
|
1036
|
+
conversationId,
|
|
1037
|
+
signal,
|
|
1038
|
+
});
|
|
1020
1039
|
const invoked = agent === undefined
|
|
1021
1040
|
? undefined
|
|
1022
1041
|
: await this.prepareSkill(orgId, accountId, conv.agentId, { conversationId, deviceId: conv.deviceId }, agent, input);
|
|
@@ -1248,16 +1267,20 @@ let ConversationsService = class ConversationsService {
|
|
|
1248
1267
|
* against the agent's current version and, for an existing conversation, its trial drafts.
|
|
1249
1268
|
*/
|
|
1250
1269
|
async prepareSkill(orgId, accountId, agentId,
|
|
1251
|
-
/**
|
|
1270
|
+
/**
|
|
1271
|
+
* The conversation (absent before it is created), its device (its skills root) and, before it
|
|
1272
|
+
* is created, the project it is created bound to.
|
|
1273
|
+
*/
|
|
1252
1274
|
where, agent, input) {
|
|
1253
1275
|
if (input.skill === undefined)
|
|
1254
1276
|
return undefined;
|
|
1255
|
-
const { conversationId, deviceId } = where;
|
|
1277
|
+
const { conversationId, deviceId, project } = where;
|
|
1256
1278
|
return this.invoker.prepare({
|
|
1257
1279
|
orgId,
|
|
1258
1280
|
agentId,
|
|
1259
1281
|
accountId,
|
|
1260
1282
|
...(conversationId !== undefined && { conversationId }),
|
|
1283
|
+
...(project !== undefined && { project }),
|
|
1261
1284
|
deviceId,
|
|
1262
1285
|
agent,
|
|
1263
1286
|
name: input.skill.name,
|
|
@@ -1290,22 +1313,149 @@ let ConversationsService = class ConversationsService {
|
|
|
1290
1313
|
async resolveExtra(orgId, accountId, input, target) {
|
|
1291
1314
|
const refs = input.attachments ?? [];
|
|
1292
1315
|
const files = await this.checkProjectFiles(orgId, accountId, input.projectFiles ?? [], target);
|
|
1316
|
+
const conversations = await this.readConversationRefs(orgId, accountId, input.conversationRefs ?? [], target?.conversationId);
|
|
1293
1317
|
const resolved = refs.length === 0
|
|
1294
1318
|
? { blocks: [], attachments: [] }
|
|
1295
1319
|
: await this.content.resolveAttachments(orgId, accountId, refs);
|
|
1296
|
-
if (files === undefined)
|
|
1320
|
+
if (files === undefined && conversations.length === 0)
|
|
1297
1321
|
return resolved;
|
|
1298
1322
|
return {
|
|
1299
1323
|
blocks: [
|
|
1300
1324
|
...resolved.blocks,
|
|
1301
|
-
...files
|
|
1325
|
+
...(files?.paths ?? []).map((path) => ({
|
|
1302
1326
|
type: "text",
|
|
1303
|
-
text: projectFileText(path, files
|
|
1327
|
+
text: projectFileText(path, files?.root ?? ""),
|
|
1304
1328
|
})),
|
|
1329
|
+
...conversations.map((c) => ({ type: "text", text: c.text })),
|
|
1305
1330
|
],
|
|
1306
1331
|
attachments: resolved.attachments,
|
|
1307
|
-
|
|
1308
|
-
|
|
1332
|
+
...(files !== undefined && {
|
|
1333
|
+
projectFiles: files.paths.map((path) => ({ path })),
|
|
1334
|
+
projectRoot: files.root,
|
|
1335
|
+
}),
|
|
1336
|
+
...(conversations.length > 0 && { conversationRefs: conversations.map((c) => c.meta) }),
|
|
1337
|
+
};
|
|
1338
|
+
}
|
|
1339
|
+
/**
|
|
1340
|
+
* {@link resolveExtra}'s referenced conversations (@ conversations spec §1), read as the sender
|
|
1341
|
+
* outside any transaction, once each in the body's order. Each must be the sender's own chat in
|
|
1342
|
+
* this org, not deleted, its agent still visible ({@link readable} plus `kind = 'chat'`); any
|
|
1343
|
+
* other → `conversation.reference_unavailable` (`details: [{ id }]`, the same for every case);
|
|
1344
|
+
* one with no `user_message` yet → the same code with `reason: "empty"`; the conversation
|
|
1345
|
+
* being written in → `conversation.reference_self`.
|
|
1346
|
+
*/
|
|
1347
|
+
async readConversationRefs(orgId, accountId, refs, selfId) {
|
|
1348
|
+
if (refs.length === 0)
|
|
1349
|
+
return [];
|
|
1350
|
+
const ids = [...new Set(refs.map((r) => r.id))];
|
|
1351
|
+
if (selfId !== undefined && ids.includes(selfId)) {
|
|
1352
|
+
throw new ApiError("conversation.reference_self", "A message cannot reference the conversation it is written in; remove that reference", [{ id: selfId }]);
|
|
1353
|
+
}
|
|
1354
|
+
const refused = [];
|
|
1355
|
+
const read = [];
|
|
1356
|
+
for (const id of ids) {
|
|
1357
|
+
const one = await this.readConversationRef(orgId, accountId, id);
|
|
1358
|
+
if (one === "unavailable")
|
|
1359
|
+
refused.push({ id });
|
|
1360
|
+
else if (one === "empty")
|
|
1361
|
+
refused.push({ id, reason: "empty" });
|
|
1362
|
+
else
|
|
1363
|
+
read.push(one);
|
|
1364
|
+
}
|
|
1365
|
+
// the unavailable ones first: a client reads the first detail's reason for its copy
|
|
1366
|
+
if (refused.length > 0) {
|
|
1367
|
+
throw conversationRefUnavailable([
|
|
1368
|
+
...refused.filter((r) => r.reason === undefined),
|
|
1369
|
+
...refused.filter((r) => r.reason !== undefined),
|
|
1370
|
+
]);
|
|
1371
|
+
}
|
|
1372
|
+
return read;
|
|
1373
|
+
}
|
|
1374
|
+
/** One referenced conversation's block and metadata, or why it cannot be referenced. */
|
|
1375
|
+
async readConversationRef(orgId, accountId, id) {
|
|
1376
|
+
const row = await this.db
|
|
1377
|
+
.selectFrom("conversations")
|
|
1378
|
+
.select(["id", "title", "agent_id", "updated_at"])
|
|
1379
|
+
.select(activitySql("conversations").as("activity"))
|
|
1380
|
+
.where("id", "=", id)
|
|
1381
|
+
.where("org_id", "=", orgId)
|
|
1382
|
+
.where("account_id", "=", accountId)
|
|
1383
|
+
.where("deleted_at", "is", null)
|
|
1384
|
+
// a sub-agent's or an eval replay conversation is never referenced
|
|
1385
|
+
.where("kind", "=", "chat")
|
|
1386
|
+
.executeTakeFirst();
|
|
1387
|
+
if (!row)
|
|
1388
|
+
return "unavailable";
|
|
1389
|
+
let agentName;
|
|
1390
|
+
try {
|
|
1391
|
+
agentName = (await this.agents.get(orgId, row.agent_id, accountId)).definition.name;
|
|
1392
|
+
}
|
|
1393
|
+
catch (e) {
|
|
1394
|
+
if (e instanceof ApiError && e.code === "agent.not_found")
|
|
1395
|
+
return "unavailable";
|
|
1396
|
+
throw e;
|
|
1397
|
+
}
|
|
1398
|
+
// the latest summary (conversation_events_compaction_summary_idx), then the newest messages
|
|
1399
|
+
// after what it covers
|
|
1400
|
+
const summary = await this.db
|
|
1401
|
+
.selectFrom("conversation_events")
|
|
1402
|
+
.select(["seq", sql `payload`.as("payload")])
|
|
1403
|
+
.where("conversation_id", "=", id)
|
|
1404
|
+
.where("type", "=", "compaction_summary")
|
|
1405
|
+
.orderBy("seq", "desc")
|
|
1406
|
+
.limit(1)
|
|
1407
|
+
.executeTakeFirst();
|
|
1408
|
+
const summaryPayload = summary?.payload;
|
|
1409
|
+
const rows = await this.db
|
|
1410
|
+
.selectFrom("conversation_events")
|
|
1411
|
+
.select(["seq", "type", sql `payload`.as("payload")])
|
|
1412
|
+
.where("conversation_id", "=", id)
|
|
1413
|
+
.where("type", "in", ["user_message", "assistant_message"])
|
|
1414
|
+
// only messages with text count toward the cap (a run's tool-only steps carry none)
|
|
1415
|
+
.where(sql `payload -> 'content' @> '[{"type":"text"}]'::jsonb`)
|
|
1416
|
+
.where("seq", ">", String(summaryPayload?.coversUpToSeq ?? 0))
|
|
1417
|
+
.orderBy("seq", "desc")
|
|
1418
|
+
.limit(REF_TURN_MESSAGES)
|
|
1419
|
+
.execute();
|
|
1420
|
+
// nothing to quote: no summary and no message of the person yet (a long run's text replies may
|
|
1421
|
+
// fill the newest rows, and a files-only message has no text, so the log is asked when they
|
|
1422
|
+
// hold none)
|
|
1423
|
+
if (summary === undefined && !rows.some((r) => r.type === "user_message")) {
|
|
1424
|
+
const anyUser = await this.db
|
|
1425
|
+
.selectFrom("conversation_events")
|
|
1426
|
+
.select("seq")
|
|
1427
|
+
.where("conversation_id", "=", id)
|
|
1428
|
+
.where("type", "=", "user_message")
|
|
1429
|
+
.limit(1)
|
|
1430
|
+
.executeTakeFirst();
|
|
1431
|
+
if (anyUser === undefined)
|
|
1432
|
+
return "empty";
|
|
1433
|
+
}
|
|
1434
|
+
const messages = rows
|
|
1435
|
+
.slice()
|
|
1436
|
+
.reverse()
|
|
1437
|
+
.map((r) => ({
|
|
1438
|
+
role: r.type === "user_message" ? "user" : "assistant",
|
|
1439
|
+
text: refMessageText(r.type, r.payload),
|
|
1440
|
+
}))
|
|
1441
|
+
.filter((m) => m.text !== "");
|
|
1442
|
+
const upToSeq = Math.max(Number(rows[0]?.seq ?? 0), Number(summary?.seq ?? 0));
|
|
1443
|
+
return {
|
|
1444
|
+
text: conversationRefText({
|
|
1445
|
+
id,
|
|
1446
|
+
title: row.title,
|
|
1447
|
+
agentName,
|
|
1448
|
+
lastActiveAt: row.updated_at,
|
|
1449
|
+
running: row.activity === "running",
|
|
1450
|
+
summary: summaryPayload?.text ?? null,
|
|
1451
|
+
messages,
|
|
1452
|
+
}),
|
|
1453
|
+
meta: {
|
|
1454
|
+
id,
|
|
1455
|
+
title: row.title,
|
|
1456
|
+
source: summary === undefined ? "excerpt" : "summary",
|
|
1457
|
+
upToSeq,
|
|
1458
|
+
},
|
|
1309
1459
|
};
|
|
1310
1460
|
}
|
|
1311
1461
|
/** {@link resolveExtra}'s project file check: the normalized paths and the root, or none. */
|
|
@@ -1356,6 +1506,8 @@ let ConversationsService = class ConversationsService {
|
|
|
1356
1506
|
...(extra.attachments.length > 0 && { attachments: extra.attachments }),
|
|
1357
1507
|
...(extra.projectFiles !== undefined &&
|
|
1358
1508
|
extra.projectFiles.length > 0 && { projectFiles: extra.projectFiles }),
|
|
1509
|
+
...(extra.conversationRefs !== undefined &&
|
|
1510
|
+
extra.conversationRefs.length > 0 && { conversationRefs: extra.conversationRefs }),
|
|
1359
1511
|
authorAccountId: accountId,
|
|
1360
1512
|
...context,
|
|
1361
1513
|
...(input.clientMessageId !== undefined && { clientMessageId: input.clientMessageId }),
|