@operad-io/chat 0.3.1 → 0.4.0
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/package.json +6 -6
- package/src/deliver.ts +53 -0
- package/src/index.ts +184 -3
- package/src/model.ts +340 -13
- package/src/notes.ts +53 -0
- package/src/recap.ts +76 -0
- package/src/reply.ts +441 -22
- package/src/segments.ts +125 -0
- package/src/views.ts +192 -18
package/src/model.ts
CHANGED
|
@@ -33,6 +33,33 @@ export const RUN_FACT = "chat.run";
|
|
|
33
33
|
/** The fact type of a run a `/stop` cancelled, so status and retry need not read the command's words. */
|
|
34
34
|
export const STOP_FACT = "chat.stop";
|
|
35
35
|
|
|
36
|
+
/** The fact type of a `/new`: the session in force ends here and the next reply starts a fresh one. */
|
|
37
|
+
export const NEW_FACT = "chat.new";
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The fact type of the brief a `/new <goal>` gives the new session: one model
|
|
41
|
+
* call's text, or why there is none, with the call's model and cost.
|
|
42
|
+
*/
|
|
43
|
+
export const BRIEF_FACT = "chat.brief";
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The fact type of `/private` turned on or off: `on`, and who did it. The chat's
|
|
47
|
+
* `private` field holds the state in force; messages recorded while it is on
|
|
48
|
+
* carry `private: true` (ADR 0026 D23).
|
|
49
|
+
*/
|
|
50
|
+
export const PRIVATE_FACT = "chat.private";
|
|
51
|
+
|
|
52
|
+
/** The standing status a chat shows while a stretch is not remembered (approved words). */
|
|
53
|
+
export const PRIVATE_STATUS = "Not remembered / 不记入记忆";
|
|
54
|
+
|
|
55
|
+
/** The line `/private` answers with when it starts a stretch. */
|
|
56
|
+
export const PRIVATE_ON_LINE =
|
|
57
|
+
"Not remembered / 不记入记忆: on. Messages from here stay in this chat but are not saved to memory or search. Send /private again to end it.";
|
|
58
|
+
|
|
59
|
+
/** The line `/private` answers with when it ends a stretch. */
|
|
60
|
+
export const PRIVATE_OFF_LINE =
|
|
61
|
+
"Not remembered / 不记入记忆: off. What you sent meanwhile was not saved, but this chat may still recall it. Send /new to start clean.";
|
|
62
|
+
|
|
36
63
|
/** The fact type of messages an attempt took, when no reply message can name them. */
|
|
37
64
|
export const ANSWER_FACT = "chat.answered";
|
|
38
65
|
|
|
@@ -110,6 +137,54 @@ export const CLOSED_FACT = "chat.closed";
|
|
|
110
137
|
/** The fact type of one command a person typed in a chat, and how it went. */
|
|
111
138
|
export const COMMAND_FACT = "chat.command";
|
|
112
139
|
|
|
140
|
+
/** The fact type of a request to compact a chat's context (`/compact`) and of its being taken. */
|
|
141
|
+
export const COMPACT_FACT = "chat.compact";
|
|
142
|
+
|
|
143
|
+
/** The share of the model's window at which a pi chat compacts its context after a reply (ADR 0023 D12). */
|
|
144
|
+
export const COMPACT_AT = 0.75;
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* The one silent turn a bot chat runs before a compaction. It names no file:
|
|
148
|
+
* the bot's memory instructions, already on the chat, say how and where memory
|
|
149
|
+
* is written, and the turn writes under the same access rules as any other.
|
|
150
|
+
*/
|
|
151
|
+
export const COMPACT_FLUSH =
|
|
152
|
+
"Your context is about to be compacted, and what is only in it will be lost. " +
|
|
153
|
+
"Write now, to this bot's memory and by its memory instructions, what you should remember from this chat. " +
|
|
154
|
+
"Write only what is worth keeping and not already in memory; if there is nothing, write nothing. " +
|
|
155
|
+
"Do not answer or address the person. When you are done, reply with the one word: done.";
|
|
156
|
+
|
|
157
|
+
/** Whether the latest `chat.compact` fact is a request that no run has taken yet. */
|
|
158
|
+
export function compactRequested(facts: readonly PluginFact[]): boolean {
|
|
159
|
+
for (let index = facts.length - 1; index >= 0; index -= 1) {
|
|
160
|
+
const fact = facts[index];
|
|
161
|
+
if (fact?.type === COMPACT_FACT) return fact.data.kind === "request";
|
|
162
|
+
}
|
|
163
|
+
return false;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** The one line a reply fails with when the context is still over the share right after a compaction. */
|
|
167
|
+
export const CHAT_TOO_FULL_LINE = "This chat is too full to continue: even compacted, its context fills the window. Send /new to start a fresh one.";
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Whether the latest compaction of this session left the context at or over
|
|
171
|
+
* the share of the window (`COMPACT_AT`), so another would only repeat it. A
|
|
172
|
+
* `/new` ends it; so does a later compaction that fits.
|
|
173
|
+
*/
|
|
174
|
+
export function chatTooFull(facts: readonly PluginFact[]): boolean {
|
|
175
|
+
for (let index = facts.length - 1; index >= 0; index -= 1) {
|
|
176
|
+
const fact = facts[index];
|
|
177
|
+
if (fact?.type === NEW_FACT) return false;
|
|
178
|
+
if (fact?.type === COMPACT_FACT && fact.data.kind === "compacted") return fact.data.full === true;
|
|
179
|
+
}
|
|
180
|
+
return false;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Whether a compaction that left `after` tokens in a window of `window` is still over the share. */
|
|
184
|
+
export function stillFull(after: number | undefined, window: number | undefined): boolean {
|
|
185
|
+
return after !== undefined && window !== undefined && window > 0 && after >= COMPACT_AT * window;
|
|
186
|
+
}
|
|
187
|
+
|
|
113
188
|
/** The list filters of chats: closed ones are hidden unless asked for. */
|
|
114
189
|
export const CHAT_FILTERS = [
|
|
115
190
|
{ name: "open", default: true, states: ["open"] },
|
|
@@ -122,8 +197,40 @@ export const CHAT_SOURCES = ["ios", "telegram", "cli", "tui"] as const;
|
|
|
122
197
|
/** The event source of a message from a client the chat does not know by name. */
|
|
123
198
|
export const OTHER_SOURCE = "other";
|
|
124
199
|
|
|
125
|
-
/**
|
|
126
|
-
|
|
200
|
+
/**
|
|
201
|
+
* Who wrote a message: the person, the assistant, or a plugin that delivers a
|
|
202
|
+
* result into the chat (a `delivery`, which never starts a reply), or the
|
|
203
|
+
* recap code writes when the person returns (a `recap`, which neither starts a
|
|
204
|
+
* reply nor reaches the model).
|
|
205
|
+
*/
|
|
206
|
+
export type MessageRole = "user" | "assistant" | "delivery" | "recap";
|
|
207
|
+
|
|
208
|
+
/** What a delivered result says about itself. */
|
|
209
|
+
export interface DeliveryData {
|
|
210
|
+
/** The routine that produced it, as the header names it. */
|
|
211
|
+
readonly routine: string;
|
|
212
|
+
/** The routine's object id (`bot-routine:<id>`), when the plugin knows it. */
|
|
213
|
+
readonly routineId?: string | undefined;
|
|
214
|
+
/** The record of the run, which the agent reads on demand. */
|
|
215
|
+
readonly runId: string;
|
|
216
|
+
/** The short summary that rides on the next message; the message's text is the whole result. */
|
|
217
|
+
readonly summary: string;
|
|
218
|
+
/** True when the run failed. */
|
|
219
|
+
readonly failed?: boolean | undefined;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** The header a delivered result carries, so it is told apart from conversation. */
|
|
223
|
+
export function deliveryHeader(delivery: DeliveryData): string {
|
|
224
|
+
return `Routine · ${delivery.routine}${delivery.failed === true ? " · failed" : ""}`;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** The delivery a fact's data holds, or undefined when it holds none. */
|
|
228
|
+
export function deliveryOf(value: unknown): DeliveryData | undefined {
|
|
229
|
+
if (!isRecord(value)) return undefined;
|
|
230
|
+
const { routine, routineId, runId, summary, failed } = value;
|
|
231
|
+
if (typeof routine !== "string" || typeof runId !== "string" || typeof summary !== "string") return undefined;
|
|
232
|
+
return { routine, ...(typeof routineId === "string" && routineId.length > 0 ? { routineId } : {}), runId, summary, ...(failed === true ? { failed: true as const } : {}) };
|
|
233
|
+
}
|
|
127
234
|
|
|
128
235
|
/** The scheduled prompt that opened a chat: its bot and the entry's name. */
|
|
129
236
|
export interface ScheduledChat {
|
|
@@ -210,6 +317,13 @@ export interface ChatData {
|
|
|
210
317
|
readonly tokensIncomplete?: true | undefined;
|
|
211
318
|
/** The scheduled prompt that opened this chat; absent for every other chat. */
|
|
212
319
|
readonly scheduled?: ScheduledChat | undefined;
|
|
320
|
+
/**
|
|
321
|
+
* True for the record of one run of a routine: it keeps the reply and its
|
|
322
|
+
* process like a chat, takes an `R-` id, and is not in the chat list.
|
|
323
|
+
*/
|
|
324
|
+
readonly run?: true | undefined;
|
|
325
|
+
/** True while a stretch is not remembered (`/private`); see {@link PRIVATE_FACT}. */
|
|
326
|
+
readonly private?: true | undefined;
|
|
213
327
|
}
|
|
214
328
|
|
|
215
329
|
/** What a plugin gives to create a chat. */
|
|
@@ -237,6 +351,8 @@ export interface NewChat {
|
|
|
237
351
|
readonly accessAction?: string | undefined;
|
|
238
352
|
/** See {@link ChatData.scheduled}. */
|
|
239
353
|
readonly scheduled?: ScheduledChat | undefined;
|
|
354
|
+
/** See {@link ChatData.run}. */
|
|
355
|
+
readonly run?: boolean | undefined;
|
|
240
356
|
}
|
|
241
357
|
|
|
242
358
|
/** One file attached to a message: where it is stored, and what a client shows of it. */
|
|
@@ -422,6 +538,8 @@ export interface MessageData {
|
|
|
422
538
|
readonly source: { readonly kind: string; readonly ref: string | null };
|
|
423
539
|
/** An assistant message: the ids of the messages it answers. */
|
|
424
540
|
readonly replyTo?: readonly string[] | undefined;
|
|
541
|
+
/** A delivered result: where it came from and its summary. */
|
|
542
|
+
readonly delivery?: DeliveryData | undefined;
|
|
425
543
|
/** A user message: text only the agent is given after the text; no view shows it. */
|
|
426
544
|
readonly instruction?: string | undefined;
|
|
427
545
|
/** The run whose answer this message or entry belongs to. */
|
|
@@ -439,6 +557,57 @@ export interface MessageData {
|
|
|
439
557
|
readonly context?: ReplyContext | undefined;
|
|
440
558
|
/** An assistant message: how long the step took to start, to its first line, and in all. */
|
|
441
559
|
readonly timings?: AgentTimings | undefined;
|
|
560
|
+
/** True for a message of a stretch that is not remembered; memory, Dreaming and search leave it out. */
|
|
561
|
+
readonly private?: true | undefined;
|
|
562
|
+
/** An assistant message: the memory notes it wrote and the ones it used. */
|
|
563
|
+
readonly memory?: MemoryShown | undefined;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/** A note a reply wrote: its file and a one-line summary. */
|
|
567
|
+
export interface MemoryWrote {
|
|
568
|
+
readonly file: string;
|
|
569
|
+
readonly summary: string;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/** The memory a reply touched: notes it wrote, and notes it used (ADR 0026 D18 and the memory tools). */
|
|
573
|
+
export interface MemoryShown {
|
|
574
|
+
readonly wrote: readonly MemoryWrote[];
|
|
575
|
+
readonly used: readonly string[];
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/** The two labels clients show for a reply's memory, English and Chinese (owner-approved wording). */
|
|
579
|
+
export const MEMORY_LABELS = {
|
|
580
|
+
wrote: { en: "Saved to memory", zh: "已记入记忆" },
|
|
581
|
+
used: { en: "Used memory", zh: "用到的记忆" },
|
|
582
|
+
} as const;
|
|
583
|
+
|
|
584
|
+
/** The memory a stored reply names; undefined when it names none. */
|
|
585
|
+
export function memoryShownOf(value: unknown): MemoryShown | undefined {
|
|
586
|
+
if (!isRecord(value)) return undefined;
|
|
587
|
+
const wrote: MemoryWrote[] = [];
|
|
588
|
+
if (Array.isArray(value.wrote)) {
|
|
589
|
+
for (const item of value.wrote) {
|
|
590
|
+
if (!isRecord(item) || typeof item.file !== "string" || item.file.length === 0) continue;
|
|
591
|
+
wrote.push({ file: item.file, summary: typeof item.summary === "string" ? item.summary : "" });
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
const used = Array.isArray(value.used)
|
|
595
|
+
? value.used.filter((item): item is string => typeof item === "string" && item.length > 0)
|
|
596
|
+
: [];
|
|
597
|
+
return wrote.length === 0 && used.length === 0 ? undefined : { wrote, used };
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/** The line that names the notes a reply wrote, or undefined when it wrote none. */
|
|
601
|
+
export function memoryWroteLine(memory: MemoryShown | undefined): string | undefined {
|
|
602
|
+
if (memory === undefined || memory.wrote.length === 0) return undefined;
|
|
603
|
+
const notes = memory.wrote.map((note) => (note.summary.length === 0 ? note.file : `${note.file} (${note.summary})`));
|
|
604
|
+
return `${MEMORY_LABELS.wrote.en}: ${notes.join("; ")}`;
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
/** The line that names the notes a reply used, or undefined when it used none. */
|
|
608
|
+
export function memoryUsedLine(memory: MemoryShown | undefined): string | undefined {
|
|
609
|
+
if (memory === undefined || memory.used.length === 0) return undefined;
|
|
610
|
+
return `${MEMORY_LABELS.used.en}: ${memory.used.join(", ")}`;
|
|
442
611
|
}
|
|
443
612
|
|
|
444
613
|
/** One message with when it was recorded. */
|
|
@@ -798,9 +967,35 @@ export function chatData(data: Readonly<Record<string, unknown>>): ChatData {
|
|
|
798
967
|
...(tokens === undefined ? {} : { tokens }),
|
|
799
968
|
...(data.tokensIncomplete === true ? { tokensIncomplete: true as const } : {}),
|
|
800
969
|
...(scheduled === undefined ? {} : { scheduled }),
|
|
970
|
+
...(data.run === true ? { run: true as const } : {}),
|
|
971
|
+
...(data.private === true ? { private: true as const } : {}),
|
|
801
972
|
};
|
|
802
973
|
}
|
|
803
974
|
|
|
975
|
+
/**
|
|
976
|
+
* The chat a client with no chosen chat returns to, on one parent (a bot): the
|
|
977
|
+
* newest open chat bound to a channel when there is one, else the newest open
|
|
978
|
+
* chat; a chat a scheduled prompt opened is never the main one. Newest is the
|
|
979
|
+
* largest id. Undefined when the parent has no open chat. The routine delivery
|
|
980
|
+
* reads the same rule.
|
|
981
|
+
*/
|
|
982
|
+
export async function mainChatOf(store: ObjectStore, parent: string): Promise<string | undefined> {
|
|
983
|
+
let bound: string | undefined;
|
|
984
|
+
let latest: string | undefined;
|
|
985
|
+
let cursor: string | undefined;
|
|
986
|
+
do {
|
|
987
|
+
const page = await store.list(CHAT_TYPE, { where: { parent }, ...(cursor === undefined ? {} : { cursor }) });
|
|
988
|
+
for (const object of page.objects) {
|
|
989
|
+
const data = chatData(object.data);
|
|
990
|
+
if (data.parent !== parent || data.closed || data.scheduled !== undefined) continue;
|
|
991
|
+
if (latest === undefined || object.id > latest) latest = object.id;
|
|
992
|
+
if (data.channels.some((channel) => channel.startsWith("telegram:")) && (bound === undefined || object.id > bound)) bound = object.id;
|
|
993
|
+
}
|
|
994
|
+
cursor = page.next;
|
|
995
|
+
} while (cursor !== undefined);
|
|
996
|
+
return bound ?? latest;
|
|
997
|
+
}
|
|
998
|
+
|
|
804
999
|
function isCostQuality(value: unknown): value is CostQuality {
|
|
805
1000
|
return value === "exact" || value === "estimated" || value === "incomplete";
|
|
806
1001
|
}
|
|
@@ -953,18 +1148,18 @@ export function chatRef(id: string): ObjectRef {
|
|
|
953
1148
|
}
|
|
954
1149
|
|
|
955
1150
|
/** The next free chat id, `C-0001` upward. */
|
|
956
|
-
async function nextChatId(store: ObjectStore): Promise<string> {
|
|
1151
|
+
async function nextChatId(store: ObjectStore, prefix: "C" | "R" = "C"): Promise<string> {
|
|
957
1152
|
let highest = 0;
|
|
958
1153
|
let cursor: string | undefined;
|
|
959
1154
|
do {
|
|
960
1155
|
const page = await store.list(CHAT_TYPE, { ...(cursor === undefined ? {} : { cursor }) });
|
|
961
1156
|
for (const object of page.objects) {
|
|
962
|
-
const match = /^
|
|
963
|
-
if (match !== null) highest = Math.max(highest, Number(match[
|
|
1157
|
+
const match = /^([CR])-(\d+)$/.exec(object.id);
|
|
1158
|
+
if (match !== null && match[1] === prefix) highest = Math.max(highest, Number(match[2]));
|
|
964
1159
|
}
|
|
965
1160
|
cursor = page.next;
|
|
966
1161
|
} while (cursor !== undefined);
|
|
967
|
-
return
|
|
1162
|
+
return `${prefix}-${String(highest + 1).padStart(4, "0")}`;
|
|
968
1163
|
}
|
|
969
1164
|
|
|
970
1165
|
/** Creates a chat for a plugin that has every field; returns its id. */
|
|
@@ -999,11 +1194,13 @@ export async function createChat(
|
|
|
999
1194
|
...(input.refresh === undefined ? {} : { refresh: input.refresh }),
|
|
1000
1195
|
...(input.accessAction === undefined ? {} : { accessAction: input.accessAction }),
|
|
1001
1196
|
...(input.scheduled === undefined ? {} : { scheduled: input.scheduled }),
|
|
1197
|
+
...(input.run === true ? { run: true as const } : {}),
|
|
1002
1198
|
};
|
|
1199
|
+
const prefix = input.run === true ? "R" : "C";
|
|
1003
1200
|
// The id counts up; a taken one (two chats made at once) moves on to the next.
|
|
1004
1201
|
for (let attempt = 0; attempt < 20; attempt += 1) {
|
|
1005
|
-
const base = await nextChatId(store);
|
|
1006
|
-
const id =
|
|
1202
|
+
const base = await nextChatId(store, prefix);
|
|
1203
|
+
const id = `${prefix}-${String(Number(base.slice(2)) + attempt).padStart(4, "0")}`;
|
|
1007
1204
|
if ((await store.get(CHAT_TYPE, id)) !== undefined) continue;
|
|
1008
1205
|
await store.put(CHAT_TYPE, id, data, cause);
|
|
1009
1206
|
return id;
|
|
@@ -1015,12 +1212,15 @@ function messageOfFact(fact: PluginFact): Message | undefined {
|
|
|
1015
1212
|
if (fact.type !== MESSAGE_FACT) return undefined;
|
|
1016
1213
|
const data = fact.data;
|
|
1017
1214
|
if (typeof data.id !== "string" || typeof data.text !== "string") return undefined;
|
|
1018
|
-
if (data.role !== "user" && data.role !== "assistant") return undefined;
|
|
1215
|
+
if (data.role !== "user" && data.role !== "assistant" && data.role !== "delivery" && data.role !== "recap") return undefined;
|
|
1216
|
+
const delivery = data.role === "delivery" ? deliveryOf(data.delivery) : undefined;
|
|
1217
|
+
if (data.role === "delivery" && delivery === undefined) return undefined;
|
|
1019
1218
|
const from = isRecord(data.from) ? data.from : {};
|
|
1020
1219
|
const source = isRecord(data.source) ? data.source : {};
|
|
1021
1220
|
const timings = timingsOf(data.timings);
|
|
1022
1221
|
const tokens = usageTokensOf(data.tokens);
|
|
1023
1222
|
const context = replyContextOf(data.context);
|
|
1223
|
+
const memory = memoryShownOf(data.memory);
|
|
1024
1224
|
return {
|
|
1025
1225
|
id: data.id,
|
|
1026
1226
|
role: data.role,
|
|
@@ -1035,6 +1235,7 @@ function messageOfFact(fact: PluginFact): Message | undefined {
|
|
|
1035
1235
|
ref: typeof source.ref === "string" ? source.ref : null,
|
|
1036
1236
|
},
|
|
1037
1237
|
...(Array.isArray(data.replyTo) ? { replyTo: stringList(data.replyTo) } : {}),
|
|
1238
|
+
...(delivery === undefined ? {} : { delivery }),
|
|
1038
1239
|
...(data.role === "user" && typeof data.instruction === "string" && data.instruction.length > 0
|
|
1039
1240
|
? { instruction: data.instruction }
|
|
1040
1241
|
: {}),
|
|
@@ -1046,6 +1247,8 @@ function messageOfFact(fact: PluginFact): Message | undefined {
|
|
|
1046
1247
|
...(tokens === undefined ? {} : { tokens }),
|
|
1047
1248
|
...(context === undefined ? {} : { context }),
|
|
1048
1249
|
...(timings === undefined ? {} : { timings }),
|
|
1250
|
+
...(data.private === true ? { private: true as const } : {}),
|
|
1251
|
+
...(memory === undefined ? {} : { memory }),
|
|
1049
1252
|
at: fact.at,
|
|
1050
1253
|
sequence: fact.sequence,
|
|
1051
1254
|
};
|
|
@@ -1211,7 +1414,9 @@ export function writingReply(
|
|
|
1211
1414
|
if (fact.sequence <= started) return false;
|
|
1212
1415
|
return stopOfFact(fact)?.runId === runId;
|
|
1213
1416
|
});
|
|
1214
|
-
|
|
1417
|
+
// A `/compact` run has no reply: its own done fact ends it.
|
|
1418
|
+
const compacted = facts.some((fact) => fact.type === COMPACT_FACT && fact.data.kind === "done" && fact.data.runId === runId);
|
|
1419
|
+
if (ended || stopped || compacted) return undefined;
|
|
1215
1420
|
const replied = messages.some((message) => message.role === "assistant" && message.runId === runId);
|
|
1216
1421
|
// The flow goes round again while messages arrived during the reply: a reply
|
|
1217
1422
|
// for this run with messages still unanswered is the next round, not an end.
|
|
@@ -1306,14 +1511,135 @@ export function unanswered(
|
|
|
1306
1511
|
);
|
|
1307
1512
|
}
|
|
1308
1513
|
|
|
1309
|
-
/** The
|
|
1514
|
+
/** The sequence of the latest `/new` on a chat, or -1 when it has had none. */
|
|
1515
|
+
export function newSessionAt(facts: readonly PluginFact[]): number {
|
|
1516
|
+
let at = -1;
|
|
1517
|
+
for (const fact of facts) if (fact.type === NEW_FACT && fact.sequence > at) at = fact.sequence;
|
|
1518
|
+
return at;
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
/**
|
|
1522
|
+
* Whether the session in force holds a message of a stretch that is not
|
|
1523
|
+
* remembered: a private message after the latest `/new`. The memory flush
|
|
1524
|
+
* before a compaction summarises the whole session, so it is skipped then.
|
|
1525
|
+
*/
|
|
1526
|
+
export function sessionHoldsPrivate(messages: readonly Message[], facts: readonly PluginFact[]): boolean {
|
|
1527
|
+
const since = newSessionAt(facts);
|
|
1528
|
+
return messages.some((message) => message.private === true && message.sequence > since);
|
|
1529
|
+
}
|
|
1530
|
+
|
|
1531
|
+
/** The goal of the latest `/new`, when it had one and no brief has been recorded for it yet. */
|
|
1532
|
+
export function briefDue(
|
|
1533
|
+
facts: readonly PluginFact[],
|
|
1534
|
+
): { readonly goal: string; readonly from: string | undefined; readonly sequence: number } | undefined {
|
|
1535
|
+
let due: { readonly goal: string; readonly from: string | undefined; readonly sequence: number } | undefined;
|
|
1536
|
+
for (const fact of facts) {
|
|
1537
|
+
if (fact.type === NEW_FACT) {
|
|
1538
|
+
const goal = typeof fact.data.goal === "string" ? fact.data.goal.trim() : "";
|
|
1539
|
+
const from = typeof fact.data.from === "string" && fact.data.from.length > 0 ? fact.data.from : undefined;
|
|
1540
|
+
due = goal.length === 0 ? undefined : { goal, from, sequence: fact.sequence };
|
|
1541
|
+
} else if (fact.type === BRIEF_FACT) {
|
|
1542
|
+
due = undefined;
|
|
1543
|
+
}
|
|
1544
|
+
}
|
|
1545
|
+
return due;
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
/**
|
|
1549
|
+
* The text the new session starts with: the brief of the latest `/new`, until
|
|
1550
|
+
* a reply has been written after it. Undefined when the latest `/new` had no goal.
|
|
1551
|
+
*/
|
|
1552
|
+
export function briefToCarry(messages: readonly Message[], facts: readonly PluginFact[]): string | undefined {
|
|
1553
|
+
let found: PluginFact | undefined;
|
|
1554
|
+
for (const fact of facts) {
|
|
1555
|
+
if (fact.type === NEW_FACT) found = undefined;
|
|
1556
|
+
else if (fact.type === BRIEF_FACT) found = fact;
|
|
1557
|
+
}
|
|
1558
|
+
if (found === undefined) return undefined;
|
|
1559
|
+
const at = found.sequence;
|
|
1560
|
+
if (messages.some((message) => message.role === "assistant" && message.sequence > at)) return undefined;
|
|
1561
|
+
const text = typeof found.data.text === "string" ? found.data.text.trim() : "";
|
|
1562
|
+
const goal = typeof found.data.goal === "string" ? found.data.goal.trim() : "";
|
|
1563
|
+
const failed = typeof found.data.failed === "string" ? found.data.failed : undefined;
|
|
1564
|
+
const lead = "This is a new session of an existing chat.";
|
|
1565
|
+
const body =
|
|
1566
|
+
text.length > 0
|
|
1567
|
+
? `${lead} Brief of the earlier session:\n\n${text}`
|
|
1568
|
+
: `${lead} A brief of the earlier session could not be made${failed === undefined ? "" : ` (${failed})`}.`;
|
|
1569
|
+
return goal.length === 0 ? body : `${body}\n\nGoal for this session: ${goal}`;
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
/**
|
|
1573
|
+
* The results delivered to a chat that its agent has not seen: those recorded
|
|
1574
|
+
* after the latest reply's run began (a reply's prompt carried what was there
|
|
1575
|
+
* when its run began) and after the latest `/new`. Oldest first.
|
|
1576
|
+
*/
|
|
1577
|
+
export function deliveriesToCarry(
|
|
1578
|
+
messages: readonly Message[],
|
|
1579
|
+
facts: readonly PluginFact[],
|
|
1580
|
+
): readonly (Message & { readonly delivery: DeliveryData })[] {
|
|
1581
|
+
const started = new Map<string, number>();
|
|
1582
|
+
for (const fact of facts) {
|
|
1583
|
+
if (fact.type === RUN_FACT && typeof fact.data.runId === "string") started.set(fact.data.runId, fact.sequence);
|
|
1584
|
+
}
|
|
1585
|
+
let seen = newSessionAt(facts);
|
|
1586
|
+
for (const message of messages) {
|
|
1587
|
+
if (message.role !== "assistant" || message.runId === undefined) continue;
|
|
1588
|
+
const at = started.get(message.runId);
|
|
1589
|
+
if (at !== undefined && at > seen) seen = at;
|
|
1590
|
+
}
|
|
1591
|
+
const found: (Message & { readonly delivery: DeliveryData })[] = [];
|
|
1592
|
+
for (const message of messages) {
|
|
1593
|
+
if (message.role === "delivery" && message.delivery !== undefined && message.sequence > seen) {
|
|
1594
|
+
found.push({ ...message, delivery: message.delivery });
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1597
|
+
return found;
|
|
1598
|
+
}
|
|
1599
|
+
|
|
1600
|
+
/**
|
|
1601
|
+
* The block that carries delivered results on a message: each one's summary and
|
|
1602
|
+
* where its whole record is, never the whole result, so several a day do not
|
|
1603
|
+
* stay in the context for good.
|
|
1604
|
+
*/
|
|
1605
|
+
export function deliveryBlock(deliveries: readonly { readonly delivery: DeliveryData }[]): string | undefined {
|
|
1606
|
+
if (deliveries.length === 0) return undefined;
|
|
1607
|
+
const lines = deliveries.map(
|
|
1608
|
+
({ delivery }) => `- ${delivery.routine}${delivery.failed === true ? " (failed)" : ""}, run ${delivery.runId}: ${delivery.summary}`,
|
|
1609
|
+
);
|
|
1610
|
+
return [
|
|
1611
|
+
"[Routine results]",
|
|
1612
|
+
"These results were delivered to this chat since your last reply. Each line is a summary. The person may ask about one; read the whole record of a run on demand with the operad tool `section` (id `chat:<run>`, section `transcript`) instead of guessing.",
|
|
1613
|
+
...lines,
|
|
1614
|
+
"[End of routine results]",
|
|
1615
|
+
].join("\n");
|
|
1616
|
+
}
|
|
1617
|
+
|
|
1618
|
+
/**
|
|
1619
|
+
* Whether the next prompt is the first of a session a `/new` started: a `/new`
|
|
1620
|
+
* is on record and no reply has come since. A reply that failed leaves it true,
|
|
1621
|
+
* so the retry still carries the pointer the agent has not yet seen.
|
|
1622
|
+
*/
|
|
1623
|
+
export function startsAfterNew(facts: readonly PluginFact[], messages: readonly Message[]): boolean {
|
|
1624
|
+
const since = newSessionAt(facts);
|
|
1625
|
+
if (since < 0) return false;
|
|
1626
|
+
return !messages.some((message) => message.role === "assistant" && message.sequence > since);
|
|
1627
|
+
}
|
|
1628
|
+
|
|
1629
|
+
/**
|
|
1630
|
+
* The harness session after the last reply, else the chat's own reference. A
|
|
1631
|
+
* reply from before the latest `/new` is not the session in force.
|
|
1632
|
+
*/
|
|
1310
1633
|
export function currentSession(
|
|
1311
1634
|
chat: ChatData,
|
|
1312
1635
|
messages: readonly Message[],
|
|
1636
|
+
facts: readonly PluginFact[] = [],
|
|
1313
1637
|
): string | undefined {
|
|
1638
|
+
const since = newSessionAt(facts);
|
|
1314
1639
|
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
1315
1640
|
const message = messages[index];
|
|
1316
|
-
if (message
|
|
1641
|
+
if (message === undefined || message.sequence < since) break;
|
|
1642
|
+
if (message.role === "assistant" && message.session !== undefined) return message.session;
|
|
1317
1643
|
}
|
|
1318
1644
|
return typeof chat.session === "string" && chat.session.length > 0 ? chat.session : undefined;
|
|
1319
1645
|
}
|
|
@@ -1327,6 +1653,7 @@ export function currentSession(
|
|
|
1327
1653
|
export function lastReplyContext(
|
|
1328
1654
|
chat: ChatData,
|
|
1329
1655
|
messages: readonly Message[],
|
|
1656
|
+
facts: readonly PluginFact[] = [],
|
|
1330
1657
|
): ChatContext | undefined {
|
|
1331
1658
|
let last: Message | undefined;
|
|
1332
1659
|
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
@@ -1335,7 +1662,7 @@ export function lastReplyContext(
|
|
|
1335
1662
|
last = message;
|
|
1336
1663
|
break;
|
|
1337
1664
|
}
|
|
1338
|
-
if (last?.context === undefined) return undefined;
|
|
1665
|
+
if (last?.context === undefined || last.sequence < newSessionAt(facts)) return undefined;
|
|
1339
1666
|
if ((chat.session ?? undefined) !== (last.session ?? undefined)) return undefined;
|
|
1340
1667
|
const model = last.model ?? chat.model ?? chat.lastModel;
|
|
1341
1668
|
return {
|
package/src/notes.ts
CHANGED
|
@@ -192,3 +192,56 @@ export function noteBlock(notes: readonly NoteContent[]): string {
|
|
|
192
192
|
})
|
|
193
193
|
.join("\n\n");
|
|
194
194
|
}
|
|
195
|
+
|
|
196
|
+
// The pointer the first message after a `/new` carries: the chat's earlier
|
|
197
|
+
// record exists, and the tools the agent already has read it. The person does
|
|
198
|
+
// not see it; it rides on the message like a note.
|
|
199
|
+
export function earlierRecordPointer(chatId: string): string {
|
|
200
|
+
return [
|
|
201
|
+
"[Earlier record of this chat]",
|
|
202
|
+
"The person started a new agent session in this chat, so you do not remember what was said before. The earlier messages are kept.",
|
|
203
|
+
`Read them with the operad tool \`section\` (id \`chat:${chatId}\`, section \`transcript\`; \`cursor\` pages back). Look for a phrase with the operad tool \`search\` (scope \`chats\`) and open a hit with \`read\`. Do this when the person refers to something earlier; do not read it all first.`,
|
|
204
|
+
"[End of earlier record]",
|
|
205
|
+
].join("\n");
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** The tool's own name: the part after the last `__`, `.`, `:` or `/` of a name such as `mcp__operad__read`. */
|
|
209
|
+
function toolBase(name: string): string {
|
|
210
|
+
const parts = name.toLowerCase().split(/__|[.:/]/);
|
|
211
|
+
return parts[parts.length - 1] ?? "";
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** The note name a document id of the `read` tool shows: `memory:<bot>:<path>` is `memory/<path>`, `wiki:<path>` is `wiki/<path>`. */
|
|
215
|
+
function nameOfDocument(id: string): string | undefined {
|
|
216
|
+
if (id.startsWith("wiki:")) return `wiki/${id.slice("wiki:".length)}`;
|
|
217
|
+
if (!id.startsWith("memory:")) return undefined;
|
|
218
|
+
const rest = id.slice("memory:".length);
|
|
219
|
+
const colon = rest.indexOf(":");
|
|
220
|
+
return `memory/${colon < 0 ? rest : rest.slice(colon + 1)}`;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* The memory notes this reply read, from the tool calls it reported: documents
|
|
225
|
+
* of the memory and the wiki read with the operad `read` tool, and files under
|
|
226
|
+
* the bot's `memory/` read with a file tool. A search alone is not a use.
|
|
227
|
+
*/
|
|
228
|
+
export function memoryReadHere(entries: readonly FoldEntry[]): readonly string[] {
|
|
229
|
+
const found: string[] = [];
|
|
230
|
+
for (const entry of entries) {
|
|
231
|
+
if (entry.kind !== "tool" || entry.result !== "done" || toolBase(entry.toolName) !== "read") continue;
|
|
232
|
+
const input = entry.input ?? "";
|
|
233
|
+
for (const match of input.matchAll(/\b(?:memory:[^\s"',}]+|wiki:[^\s"',}]+)/g)) {
|
|
234
|
+
const name = nameOfDocument(match[0]);
|
|
235
|
+
if (name !== undefined) found.push(name);
|
|
236
|
+
}
|
|
237
|
+
for (const match of input.matchAll(/(?:^|[\s"'=:/])(memory\/[^\s"',}]+\.md)\b/g)) {
|
|
238
|
+
if (match[1] !== undefined) found.push(match[1]);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return found;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** The notes a reply used: those that rode on its message, then those it read; each once, in that order. */
|
|
245
|
+
export function memoryUsedBy(carried: readonly NoteContent[], entries: readonly FoldEntry[]): readonly string[] {
|
|
246
|
+
return [...new Set([...carried.map((note) => note.file.name), ...memoryReadHere(entries)])];
|
|
247
|
+
}
|
package/src/recap.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The recap a person gets on coming back to a chat after being away: one short
|
|
3
|
+
* message, built by code from what the chat's record holds, that says which
|
|
4
|
+
* routine results arrived and which replies finished meanwhile. It is a
|
|
5
|
+
* message of its own with the role `recap`; it is never put in the model's
|
|
6
|
+
* context (the delivered results already ride on the next message, ADR 0026
|
|
7
|
+
* D19), so it cannot disturb the cached history.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { PluginFact } from "@operad-io/engine";
|
|
11
|
+
import { COMMAND_FACT, type Message } from "./model.ts";
|
|
12
|
+
|
|
13
|
+
/** How long without the person counts as away, in minutes, unless the setting says otherwise. */
|
|
14
|
+
export const AWAY_MINUTES_DEFAULT = 240;
|
|
15
|
+
|
|
16
|
+
/** The message id of the recap that came with the person's message `messageId`. */
|
|
17
|
+
export function recapIdOf(messageId: string): string {
|
|
18
|
+
return `recap-${messageId}`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function span(ms: number): string {
|
|
22
|
+
const minutes = Math.max(1, Math.round(ms / 60_000));
|
|
23
|
+
if (minutes < 60) return `${minutes} min`;
|
|
24
|
+
const hours = Math.round(minutes / 60);
|
|
25
|
+
return hours < 48 ? `${hours} h` : `${Math.round(hours / 24)} days`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function listed(names: readonly string[]): string {
|
|
29
|
+
const counts = new Map<string, number>();
|
|
30
|
+
for (const name of names) counts.set(name, (counts.get(name) ?? 0) + 1);
|
|
31
|
+
return [...counts].map(([name, count]) => (count > 1 ? `${name} ×${count}` : name)).join(", ");
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The recap for the person's message `current`, or undefined when they were
|
|
36
|
+
* not away (the person's last message or command before it is less than
|
|
37
|
+
* `awayMs` older), when there is no earlier activity, or when nothing
|
|
38
|
+
* happened meanwhile. `messages` holds the chat's messages with `current`;
|
|
39
|
+
* `facts` its facts, for the person's commands. A zero or negative `awayMs`
|
|
40
|
+
* turns recaps off.
|
|
41
|
+
*/
|
|
42
|
+
export function recapOf(
|
|
43
|
+
messages: readonly Message[],
|
|
44
|
+
facts: readonly PluginFact[],
|
|
45
|
+
current: Message,
|
|
46
|
+
awayMs: number,
|
|
47
|
+
): string | undefined {
|
|
48
|
+
if (awayMs <= 0 || current.role !== "user") return undefined;
|
|
49
|
+
let lastAt = -1;
|
|
50
|
+
let lastSequence = -1;
|
|
51
|
+
const activity: { readonly at: number; readonly sequence: number }[] = [
|
|
52
|
+
...messages.filter((message) => message.role === "user"),
|
|
53
|
+
...facts.filter((fact) => fact.type === COMMAND_FACT),
|
|
54
|
+
];
|
|
55
|
+
for (const item of activity) {
|
|
56
|
+
if (item.sequence < current.sequence && item.sequence > lastSequence) {
|
|
57
|
+
lastAt = item.at;
|
|
58
|
+
lastSequence = item.sequence;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (lastSequence < 0) return undefined;
|
|
62
|
+
const gap = current.at - lastAt;
|
|
63
|
+
if (gap < awayMs) return undefined;
|
|
64
|
+
const meanwhile = messages.filter((message) => message.sequence > lastSequence && message.sequence < current.sequence);
|
|
65
|
+
const results = meanwhile.flatMap((message) =>
|
|
66
|
+
message.role === "delivery" && message.delivery !== undefined
|
|
67
|
+
? [`${message.delivery.routine}${message.delivery.failed === true ? " (failed)" : ""}`]
|
|
68
|
+
: [],
|
|
69
|
+
);
|
|
70
|
+
const replies = meanwhile.filter((message) => message.role === "assistant").length;
|
|
71
|
+
if (results.length === 0 && replies === 0) return undefined;
|
|
72
|
+
const lines = [`While you were away (${span(gap)}):`];
|
|
73
|
+
if (results.length > 0) lines.push(`- Routine results: ${listed(results)}`);
|
|
74
|
+
if (replies > 0) lines.push(`- ${replies === 1 ? "1 reply" : `${replies} replies`} finished`);
|
|
75
|
+
return lines.join("\n");
|
|
76
|
+
}
|