@operad-io/chat 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +12 -2
- package/package.json +22 -4
- package/src/index.ts +373 -0
- package/src/model.ts +717 -0
- package/src/reply.ts +687 -0
- package/src/tail.ts +107 -0
- package/src/views.ts +444 -0
package/src/reply.ts
ADDED
|
@@ -0,0 +1,687 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `chat/reply` step: one round of an answer. It builds the prompt from the
|
|
3
|
+
* chat's unanswered messages, continues the chat's harness session, records the
|
|
4
|
+
* reply as a fact and looks again for messages that came meanwhile; the flow
|
|
5
|
+
* goes round again while there are some. The kernel keeps no prompt text.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
9
|
+
import { dirname, join } from "node:path";
|
|
10
|
+
import { AskTimeoutError, attachmentDir, isRecord, messageOf, safeFileName, type AskOutcome, type AskRequest, type JsonValue, type PluginStepResult, type RunObject, type StepAsker, type StepContext } from "@operad-io/engine";
|
|
11
|
+
import { emptyFold, foldLines, maskSecrets, type FoldEntry, type FoldState } from "@operad-io/harness-process";
|
|
12
|
+
import {
|
|
13
|
+
allEntries,
|
|
14
|
+
allMessages,
|
|
15
|
+
chatFacts,
|
|
16
|
+
IMAGE_TYPES,
|
|
17
|
+
chatData,
|
|
18
|
+
type ChatData,
|
|
19
|
+
type CostQuality,
|
|
20
|
+
chatRef,
|
|
21
|
+
currentSession,
|
|
22
|
+
ENTRY_FACT,
|
|
23
|
+
latestRunOf,
|
|
24
|
+
MESSAGE_FACT,
|
|
25
|
+
RUN_FACT,
|
|
26
|
+
newMessageId,
|
|
27
|
+
promptFor,
|
|
28
|
+
unanswered,
|
|
29
|
+
usageOf,
|
|
30
|
+
worseQuality,
|
|
31
|
+
CHAT_TYPE,
|
|
32
|
+
type EntryData,
|
|
33
|
+
type Message,
|
|
34
|
+
type MessageData,
|
|
35
|
+
} from "./model.ts";
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Brings the chat object in line with its facts: the session after a reply, and
|
|
39
|
+
* the model and the cost so far, summed from the replies recorded. Reading the
|
|
40
|
+
* facts, not adding to the object, makes a rerun after a crash end in the same state.
|
|
41
|
+
*/
|
|
42
|
+
async function syncChat(ctx: StepContext, id: string, session: string | undefined): Promise<void> {
|
|
43
|
+
const fresh = await ctx.store.get(CHAT_TYPE, id);
|
|
44
|
+
if (fresh === undefined) return;
|
|
45
|
+
const next: Record<string, unknown> = { ...fresh.data };
|
|
46
|
+
if (session !== undefined) next.session = session;
|
|
47
|
+
let micros: number | undefined;
|
|
48
|
+
let quality: CostQuality | undefined;
|
|
49
|
+
for (const message of allMessages(ctx.store, id)) {
|
|
50
|
+
if (message.role !== "assistant") continue;
|
|
51
|
+
if (message.model !== undefined) next.lastModel = message.model;
|
|
52
|
+
if (message.costMicros !== undefined) {
|
|
53
|
+
micros = (micros ?? 0) + message.costMicros;
|
|
54
|
+
quality = worseQuality(quality, message.costQuality);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if (micros !== undefined) next.costMicros = micros;
|
|
58
|
+
if (quality !== undefined) next.costQuality = quality;
|
|
59
|
+
if (JSON.stringify(next) !== JSON.stringify(fresh.data)) {
|
|
60
|
+
await ctx.store.put(CHAT_TYPE, id, next, "step:chat/reply");
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The question a read-only chat asks when the call is not known. */
|
|
65
|
+
export const WORKTREE_QUESTION =
|
|
66
|
+
"The agent wants to change code, and this chat is read-only. Open a worktree for it?";
|
|
67
|
+
|
|
68
|
+
/** How the worktree question starts and ends; what is between names the call. */
|
|
69
|
+
const WORKTREE_QUESTION_START = "The agent wants to ";
|
|
70
|
+
const WORKTREE_QUESTION_END = " in this read-only chat. Open a worktree for it?";
|
|
71
|
+
|
|
72
|
+
/** The longest call the question shows; the ask keeps the whole call. */
|
|
73
|
+
export const WORKTREE_CALL_LIMIT = 120;
|
|
74
|
+
|
|
75
|
+
/** What a read-only chat tells its agent after it refused a call. */
|
|
76
|
+
export const READ_ONLY_REFUSAL =
|
|
77
|
+
"The call was refused because this chat is read-only. Answer in the chat or use read-only commands.";
|
|
78
|
+
|
|
79
|
+
/** The answers to the worktree question. */
|
|
80
|
+
export const WORKTREE_CHOICES = ["yes", "no"] as const;
|
|
81
|
+
|
|
82
|
+
/** The event a "yes" sends; the plugin that owns the working directory acts on it. */
|
|
83
|
+
export const WORKTREE_EVENT = "chat.worktree";
|
|
84
|
+
|
|
85
|
+
/** The call a harness question asks about. */
|
|
86
|
+
export interface WorktreeCall {
|
|
87
|
+
readonly kind: "command" | "path";
|
|
88
|
+
readonly value: string;
|
|
89
|
+
readonly tool?: string;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The call behind a write question: its grant, or the words of a question with no session. */
|
|
93
|
+
function worktreeCall(request: AskRequest): WorktreeCall | undefined {
|
|
94
|
+
const resume = request.resume;
|
|
95
|
+
if (isRecord(resume) && isRecord(resume.grant)) {
|
|
96
|
+
const grant = resume.grant;
|
|
97
|
+
if ((grant.kind === "command" || grant.kind === "path") && typeof grant.value === "string" && grant.value.length > 0) {
|
|
98
|
+
return {
|
|
99
|
+
kind: grant.kind,
|
|
100
|
+
value: grant.value,
|
|
101
|
+
...(typeof grant.tool === "string" ? { tool: grant.tool } : {}),
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const command = /^Run this command\? ([\s\S]+)$/.exec(request.prompt);
|
|
106
|
+
if (command?.[1] !== undefined && command[1].trim().length > 0) {
|
|
107
|
+
return { kind: "command", value: command[1] };
|
|
108
|
+
}
|
|
109
|
+
const path = /^Let (write|edit) use this path\? ([\s\S]+)$/.exec(request.prompt);
|
|
110
|
+
if (path?.[1] !== undefined && path[2] !== undefined && path[2].trim().length > 0) {
|
|
111
|
+
return { kind: "path", value: path[2], tool: path[1] };
|
|
112
|
+
}
|
|
113
|
+
return undefined;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** One line, cut to what a question can show. */
|
|
117
|
+
function cutCall(value: string): string {
|
|
118
|
+
const oneLine = value.replace(/\s+/g, " ").trim();
|
|
119
|
+
return oneLine.length <= WORKTREE_CALL_LIMIT
|
|
120
|
+
? oneLine
|
|
121
|
+
: `${oneLine.slice(0, WORKTREE_CALL_LIMIT - 1)}…`;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** The worktree question for one call. */
|
|
125
|
+
export function worktreeQuestion(call: WorktreeCall): string {
|
|
126
|
+
const what =
|
|
127
|
+
call.kind === "command"
|
|
128
|
+
? `run \`${cutCall(call.value)}\``
|
|
129
|
+
: `${call.tool === "edit" ? "edit" : "write"} \`${cutCall(call.value)}\``;
|
|
130
|
+
return `${WORKTREE_QUESTION_START}${what}${WORKTREE_QUESTION_END}`;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Whether a prompt is a worktree question, including the older one without a call. */
|
|
134
|
+
export function isWorktreeQuestion(prompt: string): boolean {
|
|
135
|
+
return (
|
|
136
|
+
prompt === WORKTREE_QUESTION ||
|
|
137
|
+
(prompt.startsWith(WORKTREE_QUESTION_START) && prompt.endsWith(WORKTREE_QUESTION_END))
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** The session and the full call a late answer needs; the full call stays in the history. */
|
|
142
|
+
function worktreeResume(request: AskRequest, call: WorktreeCall | undefined): JsonValue {
|
|
143
|
+
const session = sessionOnly(request.resume);
|
|
144
|
+
return {
|
|
145
|
+
...(session === null ? {} : session),
|
|
146
|
+
...(call === undefined
|
|
147
|
+
? {}
|
|
148
|
+
: {
|
|
149
|
+
call: {
|
|
150
|
+
kind: call.kind,
|
|
151
|
+
value: call.value,
|
|
152
|
+
...(call.tool === undefined ? {} : { tool: call.tool }),
|
|
153
|
+
},
|
|
154
|
+
}),
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Whether a harness question is about a call in the working directory: a
|
|
160
|
+
* path write or edit, or a shell command. A read-only chat lets no such call
|
|
161
|
+
* through on a one-time permission (the profile already let the read-only ones
|
|
162
|
+
* run), so each becomes the worktree question.
|
|
163
|
+
*/
|
|
164
|
+
export function isWriteQuestion(request: AskRequest): boolean {
|
|
165
|
+
const resume = request.resume;
|
|
166
|
+
if (isRecord(resume) && isRecord(resume.grant)) {
|
|
167
|
+
const grant = resume.grant;
|
|
168
|
+
if (grant.kind === "command") return true;
|
|
169
|
+
return grant.kind === "path" && (grant.tool === "write" || grant.tool === "edit");
|
|
170
|
+
}
|
|
171
|
+
// A question with no session to continue carries no grant; its words say what it is about.
|
|
172
|
+
return /^(?:Run this command\?|Let (?:write|edit) use this path\?)/.test(request.prompt);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function failed(reason: string, message: string): PluginStepResult {
|
|
176
|
+
return { result: "failed", data: { reason, message } };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* The asker a read-only chat's harness gets: a question about writing a file
|
|
181
|
+
* becomes the worktree question and never a one-time permission; any other
|
|
182
|
+
* question goes where it would have gone.
|
|
183
|
+
*/
|
|
184
|
+
function readOnlyAsker(ctx: StepContext, onYes: () => Promise<void>): StepAsker {
|
|
185
|
+
return {
|
|
186
|
+
async ask(request): Promise<AskOutcome> {
|
|
187
|
+
const write = isWriteQuestion(request);
|
|
188
|
+
const call = write ? worktreeCall(request) : undefined;
|
|
189
|
+
const shaped: AskRequest = write
|
|
190
|
+
? {
|
|
191
|
+
prompt: call === undefined ? WORKTREE_QUESTION : worktreeQuestion(call),
|
|
192
|
+
choices: [...WORKTREE_CHOICES],
|
|
193
|
+
...(request.resume === undefined ? {} : { resume: worktreeResume(request, call) }),
|
|
194
|
+
...(request.onTimeout === undefined ? {} : { onTimeout: request.onTimeout }),
|
|
195
|
+
...(request.graceSecs === undefined ? {} : { graceSecs: request.graceSecs }),
|
|
196
|
+
}
|
|
197
|
+
: request;
|
|
198
|
+
try {
|
|
199
|
+
const answer = await ctx.ask(shaped);
|
|
200
|
+
if (shaped === request) return { kind: "answered", answer };
|
|
201
|
+
if (answer.choice === "yes") await onYes();
|
|
202
|
+
// The call itself is never let through in the main clone. A no says why.
|
|
203
|
+
return {
|
|
204
|
+
kind: "answered",
|
|
205
|
+
answer: {
|
|
206
|
+
choice: "reject_once",
|
|
207
|
+
...(answer.choice === "yes" ? {} : { note: READ_ONLY_REFUSAL }),
|
|
208
|
+
...(answer.actor === undefined ? {} : { actor: answer.actor }),
|
|
209
|
+
},
|
|
210
|
+
};
|
|
211
|
+
} catch (error) {
|
|
212
|
+
if (error instanceof AskTimeoutError) {
|
|
213
|
+
return {
|
|
214
|
+
kind: "timeout",
|
|
215
|
+
waitId: error.waitId,
|
|
216
|
+
prompt: error.prompt,
|
|
217
|
+
choices: error.choices,
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
throw error;
|
|
221
|
+
}
|
|
222
|
+
},
|
|
223
|
+
useGrant: (waitId) => ctx.useGrant(waitId),
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** What a late answer needs: the session, and no permission for the call. */
|
|
228
|
+
function sessionOnly(resume: unknown): { readonly session: string } | null {
|
|
229
|
+
if (isRecord(resume) && typeof resume.session === "string") {
|
|
230
|
+
return { session: resume.session };
|
|
231
|
+
}
|
|
232
|
+
return null;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** The params of the step the kernel gives back after a question was answered. */
|
|
236
|
+
function answeredQuestion(
|
|
237
|
+
params: unknown,
|
|
238
|
+
): { readonly prompt: string; readonly choice: string; readonly note?: string } | undefined {
|
|
239
|
+
if (!isRecord(params) || !isRecord(params.askAnswer)) return undefined;
|
|
240
|
+
const { prompt, choice, note } = params.askAnswer;
|
|
241
|
+
if (typeof prompt !== "string" || typeof choice !== "string") return undefined;
|
|
242
|
+
return { prompt, choice, ...(typeof note === "string" ? { note } : {}) };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** The harnesses that take an image as input; any other gets every file as a path. */
|
|
246
|
+
export const IMAGE_HARNESSES = ["claude", "pi"] as const;
|
|
247
|
+
|
|
248
|
+
/** The largest image given as image input; a bigger one goes as a path only. */
|
|
249
|
+
export const IMAGE_INPUT_MAX_BYTES = 5 * 1024 * 1024;
|
|
250
|
+
|
|
251
|
+
/** An image given to a harness: where it is, and its media type. */
|
|
252
|
+
export interface ImageInput {
|
|
253
|
+
readonly path: string;
|
|
254
|
+
readonly mediaType: string;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* The images of the messages to answer that the harness takes as input. Only a
|
|
259
|
+
* file under this chat's attachment directory counts: a path a message names
|
|
260
|
+
* from elsewhere is never read.
|
|
261
|
+
*/
|
|
262
|
+
export function imagesOf(pending: readonly Message[], harness: string, directory: string): readonly ImageInput[] {
|
|
263
|
+
if (!(IMAGE_HARNESSES as readonly string[]).includes(harness)) return [];
|
|
264
|
+
const images: ImageInput[] = [];
|
|
265
|
+
for (const message of pending) {
|
|
266
|
+
for (const file of message.attachments) {
|
|
267
|
+
if (!(IMAGE_TYPES as readonly string[]).includes(file.type)) continue;
|
|
268
|
+
if (!file.path.startsWith(`${directory}/`) || file.path.includes("/../")) continue;
|
|
269
|
+
if (file.size > IMAGE_INPUT_MAX_BYTES) continue;
|
|
270
|
+
images.push({ path: file.path, mediaType: file.type });
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return images;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** What a chat's `refresh` step gives back. */
|
|
277
|
+
interface Live {
|
|
278
|
+
readonly cwd: string;
|
|
279
|
+
readonly access: Readonly<Record<string, JsonValue>>;
|
|
280
|
+
readonly skills: readonly string[];
|
|
281
|
+
/** Servers the harness starts for the agent, by name, each as a command. */
|
|
282
|
+
readonly mcpServers: Readonly<Record<string, JsonValue>>;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* The working directory, access profile and skills for this reply: the
|
|
287
|
+
* chat's own, or what its `refresh` step says now. A reply that cannot read
|
|
288
|
+
* them fails; it never falls back to the older, possibly looser, copy.
|
|
289
|
+
*/
|
|
290
|
+
async function liveSettings(
|
|
291
|
+
ctx: StepContext,
|
|
292
|
+
chat: ChatData,
|
|
293
|
+
object: RunObject,
|
|
294
|
+
runStep: NonNullable<StepContext["runStep"]>,
|
|
295
|
+
): Promise<Live | PluginStepResult> {
|
|
296
|
+
const own: Live = { cwd: chat.cwd, access: chat.access, skills: chat.skills, mcpServers: {} };
|
|
297
|
+
if (chat.refresh === undefined) return own;
|
|
298
|
+
if (ctx.stepLoaded !== undefined && !ctx.stepLoaded(chat.refresh)) {
|
|
299
|
+
return failed("settings", `"${chat.refresh}", which gives this chat's settings, is not loaded`);
|
|
300
|
+
}
|
|
301
|
+
let outcome: PluginStepResult;
|
|
302
|
+
try {
|
|
303
|
+
outcome = await runStep(chat.refresh, { chat: object.id }, { runId: ctx.runId, object, params: ctx.params, signal: ctx.signal });
|
|
304
|
+
} catch (error) {
|
|
305
|
+
return failed("settings", messageOf(error));
|
|
306
|
+
}
|
|
307
|
+
const data = isRecord(outcome.data) ? outcome.data : {};
|
|
308
|
+
if (outcome.result !== "done") {
|
|
309
|
+
return failed("settings", typeof data.message === "string" ? data.message : "the chat's settings could not be read");
|
|
310
|
+
}
|
|
311
|
+
if (typeof data.cwd !== "string" || data.cwd.length === 0 || !isRecord(data.access) || !Array.isArray(data.skills)) {
|
|
312
|
+
return failed("settings", "the chat's settings came back in a shape the chat cannot use");
|
|
313
|
+
}
|
|
314
|
+
return {
|
|
315
|
+
cwd: data.cwd,
|
|
316
|
+
access: data.access as Record<string, JsonValue>,
|
|
317
|
+
skills: data.skills.filter((item): item is string => typeof item === "string"),
|
|
318
|
+
mcpServers: isRecord(data.mcpServers) ? (data.mcpServers as Record<string, JsonValue>) : {},
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* The profile with the chat's attachment directory readable and nothing else
|
|
324
|
+
* added: the access profile's `readPaths` lets reads through a deny of the
|
|
325
|
+
* operad home, and a write there still asks.
|
|
326
|
+
*/
|
|
327
|
+
export function withAttachmentReads(
|
|
328
|
+
access: Readonly<Record<string, JsonValue>>,
|
|
329
|
+
directory: string,
|
|
330
|
+
): Readonly<Record<string, JsonValue>> {
|
|
331
|
+
const own = Array.isArray(access.readPaths) ? access.readPaths : [];
|
|
332
|
+
return { ...access, readPaths: [...own, directory] };
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** How much of a tool call's output a fact keeps; the rest goes to a file. */
|
|
336
|
+
export const TOOL_OUTPUT_FACT_BYTES = 4 * 1024;
|
|
337
|
+
|
|
338
|
+
/** Cuts text to a byte count without splitting a character. */
|
|
339
|
+
function cutUtf8(text: string, maxBytes: number): string {
|
|
340
|
+
const bytes = new TextEncoder().encode(text);
|
|
341
|
+
if (bytes.length <= maxBytes) return text;
|
|
342
|
+
let end = maxBytes;
|
|
343
|
+
while (end > 0 && ((bytes[end] ?? 0) & 0xc0) === 0x80) end -= 1;
|
|
344
|
+
return new TextDecoder().decode(bytes.subarray(0, end));
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** The file that holds a tool call's whole output, under the chat's own directory. */
|
|
348
|
+
export function toolOutputPath(home: string, chat: string, runId: string, callId: string): string {
|
|
349
|
+
return join(
|
|
350
|
+
attachmentDir(home, CHAT_TYPE, chat),
|
|
351
|
+
"tool-output",
|
|
352
|
+
safeFileName(runId),
|
|
353
|
+
`${safeFileName(callId)}.txt`,
|
|
354
|
+
);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** The chat's own secret values, so nothing recorded or written can carry one. */
|
|
358
|
+
export async function secretValues(ctx: Pick<StepContext, "secrets">): Promise<readonly string[]> {
|
|
359
|
+
try {
|
|
360
|
+
const values: string[] = [];
|
|
361
|
+
for (const name of await ctx.secrets.names()) {
|
|
362
|
+
const secret = await ctx.secrets.get(name);
|
|
363
|
+
if (secret !== undefined) values.push(secret.reveal());
|
|
364
|
+
}
|
|
365
|
+
return values;
|
|
366
|
+
} catch {
|
|
367
|
+
return [];
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/** The entries to record: what finished, and the reply a stopped run got only half way through. */
|
|
372
|
+
function entriesToRecord(
|
|
373
|
+
folded: FoldState,
|
|
374
|
+
options: { readonly finalText?: string | undefined; readonly stopped: boolean },
|
|
375
|
+
secrets: readonly string[],
|
|
376
|
+
): readonly (FoldEntry | { readonly kind: "stopped"; readonly text: string })[] {
|
|
377
|
+
const entries: (FoldEntry | { readonly kind: "stopped"; readonly text: string })[] = [...folded.entries];
|
|
378
|
+
// What is still only an increment is not an entry. A stopped run keeps the
|
|
379
|
+
// text it got half way through; finished text and thinking are already above.
|
|
380
|
+
if (options.stopped && folded.text.length > 0) entries.push({ kind: "stopped", text: folded.text });
|
|
381
|
+
// The final reply is a chat.message of its own; its text is not an entry too.
|
|
382
|
+
if (options.finalText !== undefined) {
|
|
383
|
+
const final = options.finalText.trim();
|
|
384
|
+
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
385
|
+
const entry = entries[index];
|
|
386
|
+
// `finalText` is already masked, so compare the entry after masking too.
|
|
387
|
+
if (entry?.kind === "text" && maskSecrets(entry.text, secrets).trim() === final) {
|
|
388
|
+
entries.splice(index, 1);
|
|
389
|
+
break;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
return entries;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** One folded entry as a fact's data, with secrets masked and a long output written to a file. */
|
|
397
|
+
async function entryData(
|
|
398
|
+
ctx: StepContext,
|
|
399
|
+
chat: string,
|
|
400
|
+
runId: string,
|
|
401
|
+
entry: FoldEntry | { readonly kind: "stopped"; readonly text: string },
|
|
402
|
+
secrets: readonly string[],
|
|
403
|
+
): Promise<EntryData> {
|
|
404
|
+
if (entry.kind !== "tool") {
|
|
405
|
+
return { runId, kind: entry.kind, text: maskSecrets(entry.text, secrets) };
|
|
406
|
+
}
|
|
407
|
+
const output = entry.output === null ? null : maskSecrets(entry.output, secrets);
|
|
408
|
+
const data: EntryData = {
|
|
409
|
+
runId,
|
|
410
|
+
kind: "tool",
|
|
411
|
+
callId: maskSecrets(entry.callId, secrets),
|
|
412
|
+
toolName: maskSecrets(entry.toolName, secrets),
|
|
413
|
+
input: entry.input === null ? null : maskSecrets(entry.input, secrets),
|
|
414
|
+
result: entry.result,
|
|
415
|
+
startedAt: entry.at,
|
|
416
|
+
durationMs: entry.durationMs,
|
|
417
|
+
output,
|
|
418
|
+
error: entry.error === null ? null : maskSecrets(entry.error, secrets),
|
|
419
|
+
...(entry.outputTruncated ? { outputTruncated: true } : {}),
|
|
420
|
+
};
|
|
421
|
+
// The harness's output decides whether it needs a file; masking does not
|
|
422
|
+
// make a long output short enough to leave no file behind.
|
|
423
|
+
if (output === null || new TextEncoder().encode(entry.output ?? "").length <= TOOL_OUTPUT_FACT_BYTES) return data;
|
|
424
|
+
const path = toolOutputPath(ctx.home, chat, runId, entry.callId);
|
|
425
|
+
await mkdir(dirname(path), { recursive: true });
|
|
426
|
+
await writeFile(path, output, "utf8");
|
|
427
|
+
return { ...data, output: cutUtf8(output, TOOL_OUTPUT_FACT_BYTES), outputPath: path };
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** The key that tells a repeated entry from a new one. A tool call is its call id. */
|
|
431
|
+
function entryKey(entry: EntryData): string {
|
|
432
|
+
return entry.kind === "tool" ? `tool:${entry.callId ?? ""}` : `${entry.kind}:${entry.text ?? ""}`;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* Records the finished entries on the chat. A step that runs again after a
|
|
437
|
+
* restart emits the same tool calls again: a call id already recorded is
|
|
438
|
+
* skipped, and text that an unanswered attempt already left is not added twice.
|
|
439
|
+
*/
|
|
440
|
+
async function recordEntries(
|
|
441
|
+
ctx: StepContext,
|
|
442
|
+
chat: string,
|
|
443
|
+
folded: FoldState,
|
|
444
|
+
options: { readonly finalText?: string | undefined; readonly stopped: boolean },
|
|
445
|
+
): Promise<void> {
|
|
446
|
+
const secrets = await secretValues(ctx);
|
|
447
|
+
const wanted = entriesToRecord(folded, options, secrets);
|
|
448
|
+
if (wanted.length === 0) return;
|
|
449
|
+
const existing = allEntries(ctx.store, chat);
|
|
450
|
+
const lastReply = new Map<string, number>();
|
|
451
|
+
for (const message of allMessages(ctx.store, chat)) {
|
|
452
|
+
if (message.role !== "assistant" || message.runId === undefined) continue;
|
|
453
|
+
lastReply.set(message.runId, Math.max(lastReply.get(message.runId) ?? 0, message.sequence));
|
|
454
|
+
}
|
|
455
|
+
// An entry with no reply after it belongs to an attempt that never finished.
|
|
456
|
+
const unansweredEntries = existing.filter((entry) => {
|
|
457
|
+
const reply = lastReply.get(entry.runId);
|
|
458
|
+
return reply === undefined || reply < entry.sequence;
|
|
459
|
+
});
|
|
460
|
+
const counts = new Map<string, number>();
|
|
461
|
+
for (const entry of unansweredEntries) {
|
|
462
|
+
const key = entryKey(entry);
|
|
463
|
+
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
464
|
+
}
|
|
465
|
+
const callIds = new Set(
|
|
466
|
+
existing
|
|
467
|
+
.filter((entry) => entry.kind === "tool" && entry.callId !== undefined)
|
|
468
|
+
.map((entry) => entry.callId as string),
|
|
469
|
+
);
|
|
470
|
+
for (const entry of wanted) {
|
|
471
|
+
if (entry.kind === "tool" && callIds.has(entry.callId)) continue;
|
|
472
|
+
const data = await entryData(ctx, chat, ctx.runId, entry, secrets);
|
|
473
|
+
if (data.kind === "tool") {
|
|
474
|
+
if (data.callId !== undefined) callIds.add(data.callId);
|
|
475
|
+
} else {
|
|
476
|
+
const key = entryKey(data);
|
|
477
|
+
const seen = counts.get(key) ?? 0;
|
|
478
|
+
if (seen > 0) {
|
|
479
|
+
counts.set(key, seen - 1);
|
|
480
|
+
continue;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
await ctx.facts.append({ type: ENTRY_FACT, object: chatRef(chat), data });
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/** Runs one round of an answer; see the file's comment. */
|
|
488
|
+
export async function runReply(ctx: StepContext, params: unknown): Promise<PluginStepResult> {
|
|
489
|
+
const object = ctx.object;
|
|
490
|
+
if (object === undefined || object.type !== CHAT_TYPE) {
|
|
491
|
+
return failed("object", "chat:reply runs on a chat");
|
|
492
|
+
}
|
|
493
|
+
const stored = await ctx.store.get(CHAT_TYPE, object.id);
|
|
494
|
+
if (stored === undefined) return failed("object", `there is no chat ${object.id}`);
|
|
495
|
+
const chat = chatData(stored.data);
|
|
496
|
+
const messages = allMessages(ctx.store, object.id);
|
|
497
|
+
const pending = unanswered(messages);
|
|
498
|
+
if (pending.length === 0) {
|
|
499
|
+
// A run that stopped after recording a reply still owes the chat its model and cost.
|
|
500
|
+
await syncChat(ctx, object.id, undefined);
|
|
501
|
+
return { result: "done", data: { answered: 0 } };
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
const runStep = ctx.runStep;
|
|
505
|
+
if (runStep === undefined) return failed("host", "the kernel did not offer a way to run the agent");
|
|
506
|
+
const use = `${chat.harness}/agent`;
|
|
507
|
+
if (ctx.stepLoaded !== undefined && !ctx.stepLoaded(use)) {
|
|
508
|
+
return failed("harness", `the agent "${chat.harness}" is not loaded`);
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// A model the agent cannot take fails the reply by name; it never falls back.
|
|
512
|
+
if (chat.model !== undefined && ctx.harnessModels?.(chat.harness)?.list.includes(chat.model) !== true) {
|
|
513
|
+
return failed("model", `the agent "${chat.harness}" cannot use the model "${chat.model}"`);
|
|
514
|
+
}
|
|
515
|
+
// The same for an effort: the agent's list is the only one that can take it.
|
|
516
|
+
const efforts = ctx.harnessEfforts?.(chat.harness);
|
|
517
|
+
if (chat.effort !== undefined && efforts?.list.includes(chat.effort) !== true) {
|
|
518
|
+
return failed("effort", `the agent "${chat.harness}" cannot use the effort "${chat.effort}"`);
|
|
519
|
+
}
|
|
520
|
+
const effortFlag = efforts?.flag ?? (chat.harness === "pi" ? "--thinking" : "--effort");
|
|
521
|
+
|
|
522
|
+
const settled = await liveSettings(ctx, chat, object, runStep);
|
|
523
|
+
if ("result" in settled) return settled;
|
|
524
|
+
const live = settled;
|
|
525
|
+
|
|
526
|
+
const resumed = isRecord(params) ? params : {};
|
|
527
|
+
const session =
|
|
528
|
+
typeof resumed.resumeSession === "string" ? resumed.resumeSession : currentSession(chat, messages);
|
|
529
|
+
const readOnly = live.access.readOnly === true;
|
|
530
|
+
let worktreeAsked = 0;
|
|
531
|
+
const asker = readOnly
|
|
532
|
+
? readOnlyAsker(ctx, async () => {
|
|
533
|
+
worktreeAsked += 1;
|
|
534
|
+
await ctx.emit({
|
|
535
|
+
type: WORKTREE_EVENT,
|
|
536
|
+
key: `${ctx.runId}:${worktreeAsked}`,
|
|
537
|
+
object: `${CHAT_TYPE}:${object.id}`,
|
|
538
|
+
});
|
|
539
|
+
})
|
|
540
|
+
: undefined;
|
|
541
|
+
|
|
542
|
+
// A "yes" that came back after the wait (the grace had passed) is the same
|
|
543
|
+
// answer as one given live. A "no" carries the same refusal a live answer gets.
|
|
544
|
+
const late = answeredQuestion(params);
|
|
545
|
+
const lateWorktree = readOnly && late !== undefined && isWorktreeQuestion(late.prompt);
|
|
546
|
+
if (lateWorktree && late.choice === "yes") {
|
|
547
|
+
await ctx.emit({
|
|
548
|
+
type: WORKTREE_EVENT,
|
|
549
|
+
key: `${ctx.runId}:late`,
|
|
550
|
+
object: `${CHAT_TYPE}:${object.id}`,
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
const askAnswer =
|
|
554
|
+
lateWorktree && late.choice !== "yes"
|
|
555
|
+
? {
|
|
556
|
+
prompt: late.prompt,
|
|
557
|
+
choice: late.choice,
|
|
558
|
+
note: late.note === undefined ? READ_ONLY_REFUSAL : `${READ_ONLY_REFUSAL}\n${late.note}`,
|
|
559
|
+
}
|
|
560
|
+
: resumed.askAnswer;
|
|
561
|
+
|
|
562
|
+
// The files sent with a message: images as input where the harness takes
|
|
563
|
+
// them, every file as a path, and the chat's own attachment directory open to reads.
|
|
564
|
+
const directory = attachmentDir(ctx.home, CHAT_TYPE, object.id);
|
|
565
|
+
const images = imagesOf(pending, chat.harness, directory);
|
|
566
|
+
const access = messages.some((message) => message.attachments.length > 0)
|
|
567
|
+
? withAttachmentReads(live.access, directory)
|
|
568
|
+
: live.access;
|
|
569
|
+
|
|
570
|
+
// The harness hands each log line over as it writes it; the fold keeps what
|
|
571
|
+
// is finished and what is still being written. None of this is stored until
|
|
572
|
+
// the harness returns, so the final reply can be left out of the entries.
|
|
573
|
+
let folded = emptyFold;
|
|
574
|
+
const receiver = (line: string): void => {
|
|
575
|
+
let value: unknown;
|
|
576
|
+
try {
|
|
577
|
+
value = JSON.parse(line);
|
|
578
|
+
} catch {
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
581
|
+
folded = foldLines([value], folded);
|
|
582
|
+
};
|
|
583
|
+
|
|
584
|
+
// The run is a fact before the agent starts: a view finds the step's log by it.
|
|
585
|
+
if (latestRunOf(chatFacts(ctx.store, object.id)) !== ctx.runId) {
|
|
586
|
+
await ctx.facts.append({ type: RUN_FACT, object: chatRef(object.id), data: { runId: ctx.runId } });
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
let outcome: PluginStepResult;
|
|
590
|
+
try {
|
|
591
|
+
outcome = await runStep(
|
|
592
|
+
use,
|
|
593
|
+
{
|
|
594
|
+
prompt: promptFor(pending, new Set(images.map((image) => image.path))),
|
|
595
|
+
...(images.length === 0 ? {} : { images }),
|
|
596
|
+
cwd: live.cwd,
|
|
597
|
+
...(chat.model === undefined && chat.effort === undefined
|
|
598
|
+
? {}
|
|
599
|
+
: {
|
|
600
|
+
args: [
|
|
601
|
+
...(chat.model === undefined ? [] : ["--model", chat.model]),
|
|
602
|
+
...(chat.effort === undefined ? [] : [effortFlag, chat.effort]),
|
|
603
|
+
],
|
|
604
|
+
}),
|
|
605
|
+
...(chat.effort === undefined ? {} : { effort: chat.effort }),
|
|
606
|
+
...(live.skills.length === 0 ? {} : { skills: live.skills }),
|
|
607
|
+
// Operad's own tools, so the agent never runs the `operad` command.
|
|
608
|
+
operadTools: { home: ctx.home },
|
|
609
|
+
...(Object.keys(live.mcpServers).length === 0 ? {} : { mcpServers: live.mcpServers }),
|
|
610
|
+
...(session === undefined ? {} : { resumeSession: session }),
|
|
611
|
+
...(askAnswer === undefined ? {} : { askAnswer }),
|
|
612
|
+
},
|
|
613
|
+
{
|
|
614
|
+
runId: ctx.runId,
|
|
615
|
+
cwd: live.cwd,
|
|
616
|
+
object,
|
|
617
|
+
params: ctx.params,
|
|
618
|
+
access,
|
|
619
|
+
...(ctx.trigger === undefined ? {} : { trigger: ctx.trigger }),
|
|
620
|
+
signal: ctx.signal,
|
|
621
|
+
receiver,
|
|
622
|
+
...(asker === undefined ? {} : { asker }),
|
|
623
|
+
},
|
|
624
|
+
);
|
|
625
|
+
} catch (error) {
|
|
626
|
+
await recordEntries(ctx, object.id, folded, { stopped: true });
|
|
627
|
+
return failed("harness", messageOf(error));
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
if (outcome.result === "waiting") {
|
|
631
|
+
await recordEntries(ctx, object.id, folded, { stopped: true });
|
|
632
|
+
return { result: "waiting", ...(outcome.data === undefined ? {} : { data: outcome.data }) };
|
|
633
|
+
}
|
|
634
|
+
const data = isRecord(outcome.data) ? outcome.data : {};
|
|
635
|
+
// A harness that stopped may name the part it wrote in its result instead of
|
|
636
|
+
// sending finished increments; either way the half reply is kept.
|
|
637
|
+
if (outcome.result !== "done" && folded.text.length === 0 && typeof data.finalMessage === "string" && data.finalMessage.trim().length > 0) {
|
|
638
|
+
folded = { ...folded, text: data.finalMessage.trim() };
|
|
639
|
+
}
|
|
640
|
+
if (outcome.result === "interrupted") {
|
|
641
|
+
await recordEntries(ctx, object.id, folded, { stopped: true });
|
|
642
|
+
return { result: "interrupted", data };
|
|
643
|
+
}
|
|
644
|
+
if (outcome.result !== "done") {
|
|
645
|
+
await recordEntries(ctx, object.id, folded, { stopped: true });
|
|
646
|
+
return {
|
|
647
|
+
result: "failed",
|
|
648
|
+
data: {
|
|
649
|
+
reason: typeof data.reason === "string" ? data.reason : "harness",
|
|
650
|
+
message: typeof data.message === "string" ? data.message : `the agent ended "${outcome.result}"`,
|
|
651
|
+
},
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
const said = typeof data.finalMessage === "string" ? data.finalMessage.trim() : "";
|
|
655
|
+
const text = maskSecrets(said, await secretValues(ctx));
|
|
656
|
+
if (text.length === 0) {
|
|
657
|
+
await recordEntries(ctx, object.id, folded, { stopped: true });
|
|
658
|
+
return failed("empty", "the agent gave no reply");
|
|
659
|
+
}
|
|
660
|
+
const sessionId = typeof data.sessionId === "string" && data.sessionId.length > 0 ? data.sessionId : undefined;
|
|
661
|
+
|
|
662
|
+
const usage = usageOf(data.usage);
|
|
663
|
+
|
|
664
|
+
await recordEntries(ctx, object.id, folded, { finalText: text, stopped: false });
|
|
665
|
+
|
|
666
|
+
// The reply is a fact before the step counts as done: a rerun reads it and
|
|
667
|
+
// does not answer the same messages twice.
|
|
668
|
+
const reply: MessageData = {
|
|
669
|
+
id: newMessageId(),
|
|
670
|
+
role: "assistant",
|
|
671
|
+
from: { via: chat.harness, id: chat.harness },
|
|
672
|
+
text,
|
|
673
|
+
attachments: [],
|
|
674
|
+
source: { kind: chat.harness, ref: null },
|
|
675
|
+
replyTo: pending.map((message) => message.id),
|
|
676
|
+
runId: ctx.runId,
|
|
677
|
+
...(sessionId === undefined ? {} : { session: sessionId }),
|
|
678
|
+
...usage,
|
|
679
|
+
};
|
|
680
|
+
await ctx.facts.append({ type: MESSAGE_FACT, object: chatRef(object.id), data: reply });
|
|
681
|
+
|
|
682
|
+
// The chat's own reference follows; read again, so a change made meanwhile stays.
|
|
683
|
+
await syncChat(ctx, object.id, sessionId);
|
|
684
|
+
|
|
685
|
+
const left = unanswered(allMessages(ctx.store, object.id));
|
|
686
|
+
return { result: left.length > 0 ? "more" : "done", data: { answered: pending.length, left: left.length } };
|
|
687
|
+
}
|