@operad-io/chat 0.1.1 → 0.2.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 +8 -3
- package/src/command.ts +198 -0
- package/src/index.ts +595 -66
- package/src/model.ts +791 -83
- package/src/notes.ts +194 -0
- package/src/queue.ts +93 -0
- package/src/reply.ts +1144 -122
- package/src/skills.ts +173 -0
- package/src/tail.ts +33 -8
- package/src/views.ts +1177 -90
package/src/notes.ts
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Notes a chat's refresh step puts on the message: files whose whole text the
|
|
3
|
+
* agent should see when its session may not know them. A bot's memory index and
|
|
4
|
+
* its instructions are the first use. A note is never part of the system
|
|
5
|
+
* prompt, and the hashes of what this session last saw live on the chat object,
|
|
6
|
+
* so a serve restart keeps them and a chat holds only its current files.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { messageOf } from "@operad-io/engine";
|
|
10
|
+
import { createHash } from "node:crypto";
|
|
11
|
+
import { readFile } from "node:fs/promises";
|
|
12
|
+
import { isAbsolute, join } from "node:path";
|
|
13
|
+
import { isRecord } from "@operad-io/engine";
|
|
14
|
+
import type { FoldEntry } from "@operad-io/harness-process";
|
|
15
|
+
import type { ChatNoteHashes } from "./model.ts";
|
|
16
|
+
|
|
17
|
+
/** One file a chat's refresh step gives as a note on the message. */
|
|
18
|
+
export interface NoteFile {
|
|
19
|
+
/** The name the prompt shows, such as `memory/index.md`. */
|
|
20
|
+
readonly name: string;
|
|
21
|
+
/** The file to read; an absolute path, or one under the chat's working directory. */
|
|
22
|
+
readonly path: string;
|
|
23
|
+
/** The most characters attached; the rest is cut with a line saying it was cut. */
|
|
24
|
+
readonly maxChars?: number | undefined;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A note as this reply reads it: the descriptor, where it is, its whole text and that text's hash. */
|
|
28
|
+
export interface NoteContent {
|
|
29
|
+
readonly file: NoteFile;
|
|
30
|
+
/** The file's resolved path. */
|
|
31
|
+
readonly path: string;
|
|
32
|
+
readonly text: string;
|
|
33
|
+
readonly hash: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The notes a refresh step names, ignoring a malformed one. */
|
|
37
|
+
export function noteFilesOf(value: unknown): readonly NoteFile[] | undefined {
|
|
38
|
+
if (!Array.isArray(value)) return undefined;
|
|
39
|
+
const files: NoteFile[] = [];
|
|
40
|
+
for (const item of value) {
|
|
41
|
+
if (!isRecord(item)) continue;
|
|
42
|
+
const name = item.name;
|
|
43
|
+
const path = item.path;
|
|
44
|
+
if (typeof name !== "string" || name.length === 0) continue;
|
|
45
|
+
if (typeof path !== "string" || path.length === 0) continue;
|
|
46
|
+
const limit = item.maxChars;
|
|
47
|
+
const maxChars =
|
|
48
|
+
typeof limit === "number" && Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : undefined;
|
|
49
|
+
files.push({ name, path, ...(maxChars === undefined ? {} : { maxChars }) });
|
|
50
|
+
}
|
|
51
|
+
return files;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The hash a note's whole text is compared by. */
|
|
55
|
+
export function noteHash(text: string): string {
|
|
56
|
+
return createHash("sha256").update(text).digest("hex");
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Reads the notes of this reply. A file that cannot be read is left out and its
|
|
61
|
+
* problem logged: a missing note never fails the answer.
|
|
62
|
+
*/
|
|
63
|
+
export async function readNoteFiles(
|
|
64
|
+
files: readonly NoteFile[],
|
|
65
|
+
cwd: string,
|
|
66
|
+
onProblem?: ((message: string) => void) | undefined,
|
|
67
|
+
): Promise<readonly NoteContent[]> {
|
|
68
|
+
const notes: NoteContent[] = [];
|
|
69
|
+
for (const file of files) {
|
|
70
|
+
const path = isAbsolute(file.path) ? file.path : join(cwd, file.path);
|
|
71
|
+
try {
|
|
72
|
+
const text = await readFile(path, "utf8");
|
|
73
|
+
notes.push({ file, path, text, hash: noteHash(text) });
|
|
74
|
+
} catch (error) {
|
|
75
|
+
onProblem?.(`the note ${file.name} could not be read: ${messageOf(error)}`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return notes;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The notes this message carries: all of them in a new session or after a compaction, else the changed ones. */
|
|
82
|
+
export function notesToAttach(
|
|
83
|
+
notes: readonly NoteContent[],
|
|
84
|
+
hashes: ChatNoteHashes | undefined,
|
|
85
|
+
session: string | undefined,
|
|
86
|
+
): readonly NoteContent[] {
|
|
87
|
+
if (notes.length === 0) return [];
|
|
88
|
+
if (session === undefined) return notes;
|
|
89
|
+
// A hash one session saw says nothing about the session now in force.
|
|
90
|
+
if (hashes === undefined || hashes.session !== session) return notes;
|
|
91
|
+
return notes.filter((note) => hashes.files[note.file.name] !== note.hash);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The tool names that write a file; a run that reports one may have written that note itself. */
|
|
95
|
+
const EDIT_TOOLS = new Set(["write", "edit", "multiedit", "notebookedit", "patch", "apply_patch"]);
|
|
96
|
+
|
|
97
|
+
/** The tool names that run a shell command; one may write a note through redirection. */
|
|
98
|
+
const SHELL_TOOLS = new Set(["bash", "sh", "shell", "exec", "exec_command", "run_shell_command", "terminal"]);
|
|
99
|
+
|
|
100
|
+
/** A shell command that writes a file: redirection, tee, in-place edit, or a file operation. */
|
|
101
|
+
const SHELL_WRITE = /(?:>>?|\btee\b|\b(?:rm|mv|cp|touch|truncate|dd|install)\b|\bsed\b[^\n]*\s-i\b|\bperl\b[^\n]*\s-[a-z]*i)/;
|
|
102
|
+
|
|
103
|
+
/** Whether a tool call's summarized input names this note. */
|
|
104
|
+
function mentionsNote(input: string | null | undefined, note: NoteContent): boolean {
|
|
105
|
+
if (input === null || input === undefined || input.length === 0) return false;
|
|
106
|
+
return input.includes(note.path) || input.includes(note.file.path) || input.includes(note.file.name);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Whether a tool call is one that may write the note it names. */
|
|
110
|
+
function writesNamedNote(entry: FoldEntry, note: NoteContent): boolean {
|
|
111
|
+
if (entry.kind !== "tool" || !mentionsNote(entry.input, note)) return false;
|
|
112
|
+
const tool = entry.toolName.toLowerCase();
|
|
113
|
+
if (EDIT_TOOLS.has(tool)) return true;
|
|
114
|
+
return SHELL_TOOLS.has(tool) && SHELL_WRITE.test(entry.input ?? "");
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* The notes this run wrote itself, from the tool calls it reported. A change no
|
|
119
|
+
* call of this run claims is somebody else's: another chat, a scheduled run or
|
|
120
|
+
* a tidy step, even when it happened while this reply was running.
|
|
121
|
+
*/
|
|
122
|
+
export function notesWrittenHere(
|
|
123
|
+
notes: readonly NoteContent[],
|
|
124
|
+
entries: readonly FoldEntry[],
|
|
125
|
+
): ReadonlySet<string> {
|
|
126
|
+
const written = new Set<string>();
|
|
127
|
+
for (const entry of entries) {
|
|
128
|
+
if (entry.kind !== "tool" || entry.result !== "done") continue;
|
|
129
|
+
for (const note of notes) {
|
|
130
|
+
if (writesNamedNote(entry, note)) written.add(note.file.name);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return written;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* The state after this reply. The session knows the text it was given, so an
|
|
138
|
+
* unchanged file keeps the hash it had before the run. A file this run wrote
|
|
139
|
+
* itself keeps its hash after the run; a file somebody else changed during the
|
|
140
|
+
* run keeps the older hash, so the next message carries the new text whole.
|
|
141
|
+
* A compacted session knows none of them, so the next message carries them all.
|
|
142
|
+
*/
|
|
143
|
+
export function noteHashesAfter(
|
|
144
|
+
before: readonly NoteContent[],
|
|
145
|
+
after: readonly NoteContent[],
|
|
146
|
+
written: ReadonlySet<string>,
|
|
147
|
+
session: string | undefined,
|
|
148
|
+
compacted: boolean,
|
|
149
|
+
): ChatNoteHashes {
|
|
150
|
+
const files: Record<string, string> = {};
|
|
151
|
+
if (!compacted) {
|
|
152
|
+
const now = new Map(after.map((note) => [note.file.name, note]));
|
|
153
|
+
for (const note of before) {
|
|
154
|
+
const name = note.file.name;
|
|
155
|
+
const latest = now.get(name);
|
|
156
|
+
files[name] = written.has(name) && latest !== undefined ? latest.hash : note.hash;
|
|
157
|
+
}
|
|
158
|
+
// A note that first appeared during the run is the session's only if this run wrote it.
|
|
159
|
+
for (const note of after) {
|
|
160
|
+
if (files[note.file.name] === undefined && written.has(note.file.name)) {
|
|
161
|
+
files[note.file.name] = note.hash;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return { ...(session === undefined ? {} : { session }), files };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Cuts text to a character count without splitting a surrogate pair. */
|
|
169
|
+
function cutCharacters(text: string, maxChars: number): string {
|
|
170
|
+
if (text.length <= maxChars) return text;
|
|
171
|
+
let end = maxChars;
|
|
172
|
+
const code = text.charCodeAt(end - 1);
|
|
173
|
+
if (code >= 0xd800 && code <= 0xdbff) end -= 1;
|
|
174
|
+
return text.slice(0, end);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** The line a cut note ends with. */
|
|
178
|
+
export function cutNoteLine(name: string, maxChars: number): string {
|
|
179
|
+
return `[${name} was cut at ${maxChars} characters.]`;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** One note as the prompt shows it: its name, its text (cut when a limit is set) and an end marker. */
|
|
183
|
+
export function noteBlock(notes: readonly NoteContent[]): string {
|
|
184
|
+
return notes
|
|
185
|
+
.map((note) => {
|
|
186
|
+
const limit = note.file.maxChars;
|
|
187
|
+
const body =
|
|
188
|
+
limit !== undefined && note.text.length > limit
|
|
189
|
+
? `${cutCharacters(note.text, limit)}\n\n${cutNoteLine(note.file.name, limit)}`
|
|
190
|
+
: note.text;
|
|
191
|
+
return `[${note.file.name}]\n${body}\n[End of ${note.file.name}]`;
|
|
192
|
+
})
|
|
193
|
+
.join("\n\n");
|
|
194
|
+
}
|
package/src/queue.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The queue of a chat's messages: the lock that makes taking one and changing
|
|
3
|
+
* one a single choice, and the copy of the queue a chat's row carries.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { safeFileName, type FactWriter, type MaybePromise, type ObjectStore } from "@operad-io/engine";
|
|
8
|
+
import { withLockFile } from "@operad-io/engine/platform";
|
|
9
|
+
import {
|
|
10
|
+
CHAT_TYPE,
|
|
11
|
+
chatRef,
|
|
12
|
+
queuedData,
|
|
13
|
+
queuedMessages,
|
|
14
|
+
queuedOf,
|
|
15
|
+
readChat,
|
|
16
|
+
TAKEN_FACT,
|
|
17
|
+
takenIds,
|
|
18
|
+
type ChatRead,
|
|
19
|
+
} from "./model.ts";
|
|
20
|
+
|
|
21
|
+
/** Where a chat's queue lock lives. */
|
|
22
|
+
export function queueLockPath(home: string, chat: string): string {
|
|
23
|
+
return join(home, "chat", safeFileName(chat), "queue.lock");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Runs work while holding a chat's queue lock; a take and a change take turns. */
|
|
27
|
+
export async function withQueueLock<T>(
|
|
28
|
+
home: string,
|
|
29
|
+
chat: string,
|
|
30
|
+
work: () => MaybePromise<T>,
|
|
31
|
+
): Promise<T> {
|
|
32
|
+
return withLockFile(queueLockPath(home, chat), work, { label: "chat queue" });
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Writes what is queued into the chat object, so its row can show it. */
|
|
36
|
+
export async function syncQueuedLocked(
|
|
37
|
+
store: ObjectStore,
|
|
38
|
+
chat: string,
|
|
39
|
+
cause: string,
|
|
40
|
+
read: ChatRead = readChat(store, chat),
|
|
41
|
+
taken: readonly string[] = [],
|
|
42
|
+
): Promise<void> {
|
|
43
|
+
const justTaken = new Set(taken);
|
|
44
|
+
const queued = queuedData(
|
|
45
|
+
queuedMessages(read.messages, read.facts).filter((message) => !justTaken.has(message.id)),
|
|
46
|
+
);
|
|
47
|
+
const stored = await store.get(CHAT_TYPE, chat);
|
|
48
|
+
if (stored === undefined) return;
|
|
49
|
+
const before = queuedOf(stored.data.queued);
|
|
50
|
+
if (JSON.stringify(before) === JSON.stringify(queued)) return;
|
|
51
|
+
const next: Record<string, unknown> = { ...stored.data };
|
|
52
|
+
if (queued.length === 0) delete next.queued;
|
|
53
|
+
else next.queued = queued;
|
|
54
|
+
await store.put(CHAT_TYPE, chat, next, cause);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Reads the queue again and writes it to the chat object, under the queue lock. */
|
|
58
|
+
export async function syncQueued(
|
|
59
|
+
store: ObjectStore,
|
|
60
|
+
home: string,
|
|
61
|
+
chat: string,
|
|
62
|
+
cause: string,
|
|
63
|
+
): Promise<void> {
|
|
64
|
+
await withQueueLock(home, chat, () => syncQueuedLocked(store, chat, cause));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Records that a run took these messages, unless another run already did. */
|
|
68
|
+
export async function takeLocked(
|
|
69
|
+
store: ObjectStore,
|
|
70
|
+
facts: FactWriter,
|
|
71
|
+
chat: string,
|
|
72
|
+
runId: string,
|
|
73
|
+
ids: readonly string[],
|
|
74
|
+
cause: string,
|
|
75
|
+
read: ChatRead = readChat(store, chat),
|
|
76
|
+
): Promise<void> {
|
|
77
|
+
const seen = takenIds(read.facts);
|
|
78
|
+
const fresh = ids.filter((id) => !seen.has(id));
|
|
79
|
+
if (fresh.length > 0) {
|
|
80
|
+
await facts.append({
|
|
81
|
+
type: TAKEN_FACT,
|
|
82
|
+
object: chatRef(chat),
|
|
83
|
+
data: { runId, ids: fresh },
|
|
84
|
+
cause,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
await syncQueuedLocked(store, chat, cause, read, fresh);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** A test waits here before a message is taken, to start an action against it. */
|
|
91
|
+
export const queueTestHooks: {
|
|
92
|
+
beforeTake?: ((id: string) => MaybePromise<void>) | undefined;
|
|
93
|
+
} = {};
|