channelstack 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +56 -2
- package/bin/channelstack.mjs +31 -0
- package/dist/integrations/checks/checks.test.d.ts +1 -0
- package/dist/integrations/checks/checks.test.js +31 -0
- package/dist/integrations/checks/index.d.ts +102 -0
- package/dist/integrations/checks/index.js +1034 -0
- package/dist/integrations/matchers-core/index.d.ts +217 -0
- package/dist/integrations/matchers-core/index.js +799 -0
- package/dist/integrations/matchers-core/matchers.test.d.ts +1 -0
- package/dist/integrations/matchers-core/matchers.test.js +407 -0
- package/dist/integrations/vitest/global-setup.d.ts +3 -0
- package/dist/integrations/vitest/global-setup.js +19 -0
- package/dist/integrations/vitest/index.d.ts +82 -0
- package/dist/integrations/vitest/index.js +42 -0
- package/dist/integrations/vitest/plugin.test.d.ts +1 -0
- package/dist/integrations/vitest/plugin.test.js +19 -0
- package/dist/integrations/vitest/refused.d.ts +22 -0
- package/dist/integrations/vitest/refused.js +49 -0
- package/dist/integrations/vitest/setup.d.ts +1 -0
- package/dist/integrations/vitest/setup.js +139 -0
- package/dist/sdks/typescript/client.d.ts +14 -0
- package/dist/sdks/typescript/client.js +11 -0
- package/dist/sdks/typescript/generated/channels.d.ts +32 -0
- package/dist/sdks/typescript/generated/channels.js +4 -0
- package/dist/sdks/typescript/generated/index.d.ts +4178 -0
- package/dist/sdks/typescript/generated/index.js +4608 -0
- package/dist/sdks/typescript/generated/normalisation.d.ts +18 -0
- package/dist/sdks/typescript/generated/normalisation.js +14 -0
- package/dist/sdks/typescript/runtime/client.d.ts +56 -0
- package/dist/sdks/typescript/runtime/client.js +74 -0
- package/dist/sdks/typescript/runtime/credentials.d.ts +7 -0
- package/dist/sdks/typescript/runtime/credentials.js +20 -0
- package/dist/sdks/typescript/runtime/duration.d.ts +4 -0
- package/dist/sdks/typescript/runtime/duration.js +13 -0
- package/dist/sdks/typescript/runtime/files.d.ts +47 -0
- package/dist/sdks/typescript/runtime/files.js +53 -0
- package/dist/sdks/typescript/runtime/launcher.d.ts +27 -0
- package/dist/sdks/typescript/runtime/launcher.js +124 -0
- package/dist/sdks/typescript/runtime/responder.d.ts +26 -0
- package/dist/sdks/typescript/runtime/responder.js +42 -0
- package/dist/sdks/typescript/runtime/transport.d.ts +43 -0
- package/dist/sdks/typescript/runtime/transport.js +95 -0
- package/dist/sdks/typescript/runtime/wait.d.ts +96 -0
- package/dist/sdks/typescript/runtime/wait.js +159 -0
- package/dist/sdks/typescript/types.d.ts +82 -0
- package/dist/sdks/typescript/types.js +1 -0
- package/package.json +82 -4
|
@@ -0,0 +1,799 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The channel matchers, independent of any test framework. Each one reads plain SDK methods and
|
|
3
|
+
* returns whether it passed and what to say if not; `integrations/vitest` only
|
|
4
|
+
* adapt them to their `expect`.
|
|
5
|
+
*
|
|
6
|
+
* - A positive matcher polls until its condition holds, or fails after the timeout.
|
|
7
|
+
* - A negated matcher, and one with an exact count, waits until the agent is quiet and checks once.
|
|
8
|
+
*/
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
10
|
+
import { ChannelstackError, fromMatches, ModelProblemError, parseDuration, QUIET, readMedia, textMatches, unreportedRefusals, untilQuiet, waitFor, WaitTimeoutError, } from "../../sdks/typescript/client.js";
|
|
11
|
+
import { CONTEXT } from "../../sdks/typescript/runtime/client.js";
|
|
12
|
+
import { segment } from "../../sdks/typescript/runtime/transport.js";
|
|
13
|
+
import { normalisedText } from "../../sdks/typescript/runtime/wait.js";
|
|
14
|
+
const nameOf = (author) => (typeof author === "string" ? author : author.name);
|
|
15
|
+
const show = (expected) => typeof expected === "string" ? JSON.stringify(expected) : String(expected);
|
|
16
|
+
const listing = (lines) => lines.length === 0 ? " (nothing)" : lines.map((line) => ` ${line}`).join("\n");
|
|
17
|
+
const says = (messages) => listing(messages.map((message) => `${message.author.name}: ${message.text}`));
|
|
18
|
+
/**
|
|
19
|
+
* What was said in a subject: a thread's replies, or, for a conversation (a DM), everything in
|
|
20
|
+
* it, threads included, as its transcript has it.
|
|
21
|
+
*/
|
|
22
|
+
async function messagesOf(subject) {
|
|
23
|
+
const handle = subject;
|
|
24
|
+
if (typeof handle.replies === "function")
|
|
25
|
+
return handle.replies();
|
|
26
|
+
// A transcript entry says `streaming`; a message has a `stream`. Here they read the same.
|
|
27
|
+
if (typeof handle.transcript === "function") {
|
|
28
|
+
return (await handle.transcript()).entries.map((entry) => ({
|
|
29
|
+
...entry,
|
|
30
|
+
stream: entry.streaming === undefined ? undefined : { state: entry.streaming },
|
|
31
|
+
}));
|
|
32
|
+
}
|
|
33
|
+
throw new TypeError("This matcher needs a thread or a conversation");
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Run a check the way its kind needs: poll until it holds, or wait for quiet and check once.
|
|
37
|
+
* `describe` says what was expected and what was there instead.
|
|
38
|
+
*/
|
|
39
|
+
async function settle(subject, state, timing, options) {
|
|
40
|
+
const timeout = timing?.timeout ?? state.timeout;
|
|
41
|
+
let value;
|
|
42
|
+
if (options.onceQuiet || state.isNot) {
|
|
43
|
+
const handle = subject;
|
|
44
|
+
if (typeof handle[QUIET] !== "function")
|
|
45
|
+
throw new TypeError("This matcher needs a channelstack handle");
|
|
46
|
+
// The check watches for the whole quiet window: what arrives while it looks counts.
|
|
47
|
+
try {
|
|
48
|
+
await untilQuiet(() => handle[QUIET](), {
|
|
49
|
+
timeout,
|
|
50
|
+
quietFor: timing?.quietFor ?? state.quietFor,
|
|
51
|
+
watching: true,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
if (error instanceof ModelProblemError)
|
|
56
|
+
return failing(subject, state, error.message);
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
value = await options.read();
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
let last;
|
|
63
|
+
let polls = 0;
|
|
64
|
+
try {
|
|
65
|
+
value = await waitFor("the condition", async () => {
|
|
66
|
+
last = await options.read();
|
|
67
|
+
if (options.holds(last))
|
|
68
|
+
return last;
|
|
69
|
+
// A model call no script answered won't be answered by waiting: fail now, with why.
|
|
70
|
+
polls += 1;
|
|
71
|
+
if (polls % 5 === 0)
|
|
72
|
+
await failOnProblems(subject);
|
|
73
|
+
return undefined;
|
|
74
|
+
}, { timeout });
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
if (error instanceof ModelProblemError)
|
|
78
|
+
return failing(subject, state, error.message);
|
|
79
|
+
if (!(error instanceof WaitTimeoutError))
|
|
80
|
+
throw error;
|
|
81
|
+
value = last;
|
|
82
|
+
// A timeout whose cause is a model problem says so.
|
|
83
|
+
try {
|
|
84
|
+
await failOnProblems(subject);
|
|
85
|
+
}
|
|
86
|
+
catch (problem) {
|
|
87
|
+
if (problem instanceof ModelProblemError)
|
|
88
|
+
return failing(subject, state, problem.message);
|
|
89
|
+
throw problem;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
const pass = options.holds(value);
|
|
94
|
+
if (pass !== state.isNot)
|
|
95
|
+
return { pass, message: () => options.describe(value) };
|
|
96
|
+
// A failed check also says what the agent left open (a stream it never stopped): often that is the bug.
|
|
97
|
+
const open = await stillOpen(subject);
|
|
98
|
+
const loops = await stoppedLoops(subject);
|
|
99
|
+
const leftover = `${open.length === 0 ? "" : `\nStill open: ${open.join("; ")}`}${loops.length === 0 ? "" : `\nStopped: ${loops.join("; ")}`}`;
|
|
100
|
+
return failing(subject, state, `${options.describe(value)}${leftover}`);
|
|
101
|
+
}
|
|
102
|
+
/** A failed check, its message followed by what the session's model calls say about it. */
|
|
103
|
+
async function failing(subject, state, message) {
|
|
104
|
+
const notes = await modelNotesOf(subject);
|
|
105
|
+
const text = notes.length === 0 ? message : `${message}\n${notes.join("\n")}`;
|
|
106
|
+
return { pass: state.isNot, message: () => text };
|
|
107
|
+
}
|
|
108
|
+
/** How recent a model call no session claimed must be for a failing check to name it (design §8.4). */
|
|
109
|
+
const UNATTRIBUTED_WITHIN_MS = 10_000;
|
|
110
|
+
/**
|
|
111
|
+
* What the session's model calls add to a failing check's message: the recent calls no session
|
|
112
|
+
* claimed, and the calls given to this session only by order, between sessions that sent the same
|
|
113
|
+
* text. Nothing for a subject outside a session, or where the server can't tell (live).
|
|
114
|
+
*/
|
|
115
|
+
async function modelNotesOf(subject) {
|
|
116
|
+
const handle = subject;
|
|
117
|
+
if (typeof handle[CONTEXT] !== "function")
|
|
118
|
+
return [];
|
|
119
|
+
const context = handle[CONTEXT]();
|
|
120
|
+
if (context.session === undefined)
|
|
121
|
+
return [];
|
|
122
|
+
const base = `/sessions/${segment(context.session)}/openai`;
|
|
123
|
+
try {
|
|
124
|
+
const [unattributed, calls] = await unreportedRefusals(() => Promise.all([
|
|
125
|
+
context.transport.request("GET", `${base}/unattributed`, { query: { withinMs: UNATTRIBUTED_WITHIN_MS } }),
|
|
126
|
+
context.transport.request("GET", `${base}/calls`),
|
|
127
|
+
]));
|
|
128
|
+
return modelNotes(unattributed, calls);
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
if (error instanceof ChannelstackError)
|
|
132
|
+
return [];
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
/** The lines of `modelNotesOf`, from what the server answered. */
|
|
137
|
+
export function modelNotes(unattributed, calls) {
|
|
138
|
+
const notes = [];
|
|
139
|
+
if (unattributed.length > 0) {
|
|
140
|
+
const count = unattributed.length === 1 ? "1 model call" : `${unattributed.length} model calls`;
|
|
141
|
+
notes.push(`${count} in the last ${UNATTRIBUTED_WITHIN_MS / 1000}s couldn't be attributed to a test:\n${listing(unattributed.map((call) => `${call.id} (${call.lastUserText === undefined ? "no user message" : JSON.stringify(excerptOf(call.lastUserText))}, ${Math.round(call.sinceMs / 1000)}s ago): ${call.message}`))}`);
|
|
142
|
+
}
|
|
143
|
+
// One line per text the sessions shared, naming every call it decided.
|
|
144
|
+
const tied = new Map();
|
|
145
|
+
for (const call of calls) {
|
|
146
|
+
const { attributedBy, matched, tiedWith } = call.request.context;
|
|
147
|
+
if (attributedBy !== "order" || tiedWith === undefined || tiedWith.length === 0)
|
|
148
|
+
continue;
|
|
149
|
+
const text = matched ?? "";
|
|
150
|
+
const entry = tied.get(text) ?? { ids: [], with: tiedWith };
|
|
151
|
+
entry.ids.push(call.id);
|
|
152
|
+
tied.set(text, entry);
|
|
153
|
+
}
|
|
154
|
+
for (const [text, entry] of tied) {
|
|
155
|
+
const ids = entry.ids.length === 1 ? `Model call ${entry.ids[0]} was` : `Model calls ${entry.ids.join(", ")} were`;
|
|
156
|
+
notes.push(`${ids} attributed by order, between ${entry.with.length + 1} sessions that all sent ${JSON.stringify(excerptOf(text))} (this one and ${entry.with.join(", ")}): each went to the oldest unanswered message. Give each test's prompt something of its own, or have the agent send \`user\`.`);
|
|
157
|
+
}
|
|
158
|
+
return notes;
|
|
159
|
+
}
|
|
160
|
+
/** Throw `ModelProblemError` when the subject's session has model problems. Nothing for a subject outside a session. */
|
|
161
|
+
async function failOnProblems(subject) {
|
|
162
|
+
const handle = subject;
|
|
163
|
+
if (typeof handle[QUIET] !== "function")
|
|
164
|
+
return;
|
|
165
|
+
let problems;
|
|
166
|
+
try {
|
|
167
|
+
problems = (await unreportedRefusals(() => handle[QUIET]())).problems;
|
|
168
|
+
}
|
|
169
|
+
catch (error) {
|
|
170
|
+
if (error instanceof ChannelstackError)
|
|
171
|
+
return;
|
|
172
|
+
throw error;
|
|
173
|
+
}
|
|
174
|
+
if (problems !== undefined && problems.length > 0)
|
|
175
|
+
throw new ModelProblemError(problems);
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* What the agent has left open in the subject's session, in words. Nothing for a subject outside a
|
|
179
|
+
* session, or where the server can't tell (live, without proxy mode): it only adds to a failure's
|
|
180
|
+
* message, so its refusal must not turn the failure into a skip.
|
|
181
|
+
*/
|
|
182
|
+
async function stillOpen(subject) {
|
|
183
|
+
const handle = subject;
|
|
184
|
+
if (typeof handle[QUIET] !== "function")
|
|
185
|
+
return [];
|
|
186
|
+
try {
|
|
187
|
+
return (await unreportedRefusals(() => handle[QUIET]())).open;
|
|
188
|
+
}
|
|
189
|
+
catch (error) {
|
|
190
|
+
if (error instanceof ChannelstackError)
|
|
191
|
+
return [];
|
|
192
|
+
throw error;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
/** The bot loops the fake stopped in the subject's session (decision 0027), in words. */
|
|
196
|
+
async function stoppedLoops(subject) {
|
|
197
|
+
const handle = subject;
|
|
198
|
+
if (typeof handle[QUIET] !== "function")
|
|
199
|
+
return [];
|
|
200
|
+
try {
|
|
201
|
+
return (await unreportedRefusals(() => handle[QUIET]())).loops ?? [];
|
|
202
|
+
}
|
|
203
|
+
catch (error) {
|
|
204
|
+
if (error instanceof ChannelstackError)
|
|
205
|
+
return [];
|
|
206
|
+
throw error;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
const from = (author, text) => (message) => fromMatches(message.author, author) && textMatches(message.text, text);
|
|
210
|
+
/** A Linear agent session, or the latest one of an issue (the subject a session matcher was given). */
|
|
211
|
+
async function sessionOf(subject) {
|
|
212
|
+
const handle = subject;
|
|
213
|
+
if (typeof handle.state === "function" && typeof handle.activities === "function")
|
|
214
|
+
return handle;
|
|
215
|
+
if (typeof handle.sessions === "function")
|
|
216
|
+
return (await handle.sessions()).at(-1);
|
|
217
|
+
throw new TypeError("This matcher needs an agent session or an issue");
|
|
218
|
+
}
|
|
219
|
+
const commentText = (comment) => comment.body ?? comment.text ?? "";
|
|
220
|
+
/** The text of each block of a Notion page, nested ones included: its rich text, or a child page's title. */
|
|
221
|
+
const blockTexts = (blocks) => blocks.flatMap((raw) => {
|
|
222
|
+
const block = raw;
|
|
223
|
+
const data = (block.type ? block[block.type] : undefined);
|
|
224
|
+
const text = data?.rich_text ? data.rich_text.map((item) => item.plain_text ?? "").join("") : (data?.title ?? "");
|
|
225
|
+
return [text, ...blockTexts(block.children ?? [])];
|
|
226
|
+
});
|
|
227
|
+
/**
|
|
228
|
+
* The comments of a subject that has a conversation: a GitHub issue or pull request, a Linear
|
|
229
|
+
* issue, a Notion discussion. A Notion page has none of its own: they are in its discussions.
|
|
230
|
+
*/
|
|
231
|
+
const commentsOf = (subject, matcher) => {
|
|
232
|
+
const handle = subject;
|
|
233
|
+
if (typeof handle.comments === "function")
|
|
234
|
+
return handle.comments();
|
|
235
|
+
throw new Error(typeof handle.discussions === "function"
|
|
236
|
+
? `${matcher} needs a Notion discussion, not a page: a page's comments are in its discussions. Pass \`comment.discussion\`, or one of \`await page.discussions()\`.`
|
|
237
|
+
: `${matcher} needs a GitHub issue or pull request, a Linear issue or a Notion discussion`);
|
|
238
|
+
};
|
|
239
|
+
const commentFrom = (author, text) => (comment) => fromMatches(comment.author, author) && textMatches(commentText(comment), text);
|
|
240
|
+
const written = (comments) => listing(comments.map((comment) => `${comment.author.name}: ${commentText(comment)}`));
|
|
241
|
+
/** Who wrote each message of a conversation, oldest first: its replies, its transcript, or its comments. */
|
|
242
|
+
async function writersOf(subject) {
|
|
243
|
+
const handle = subject;
|
|
244
|
+
const authors = typeof handle.replies === "function" || typeof handle.transcript === "function"
|
|
245
|
+
? (await messagesOf(subject)).map((message) => message.author)
|
|
246
|
+
: typeof handle.comments === "function"
|
|
247
|
+
? (await handle.comments()).map((comment) => comment.author)
|
|
248
|
+
: undefined;
|
|
249
|
+
if (authors === undefined)
|
|
250
|
+
throw new TypeError("toGoQuiet needs a thread, a conversation, or something with comments");
|
|
251
|
+
return authors.map((author) => ({ name: author.name, app: author.kind === "app" }));
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* The app messages of a conversation since a person last wrote in it, those before a check began
|
|
255
|
+
* included, and their authors in turn (`my-agent → coder → my-agent`): what `toGoQuiet` and each
|
|
256
|
+
* `<channel>.no-reply-loop` name when apps answer each other (decision 0027).
|
|
257
|
+
*/
|
|
258
|
+
export async function appTurns(subject) {
|
|
259
|
+
const writers = await writersOf(subject);
|
|
260
|
+
const since = writers.slice(writers.findLastIndex((writer) => !writer.app) + 1);
|
|
261
|
+
return { count: since.length, turns: since.map((writer) => writer.name).join(" → ") };
|
|
262
|
+
}
|
|
263
|
+
export const matchers = {
|
|
264
|
+
/**
|
|
265
|
+
* The conversation goes quiet within `within`, holding at most `maxReplies` app messages since
|
|
266
|
+
* a person last wrote in it, those before the check began included: apps that answer each other
|
|
267
|
+
* without end fail it (decision 0027).
|
|
268
|
+
*/
|
|
269
|
+
async toGoQuiet(state, subject, options) {
|
|
270
|
+
const handle = subject;
|
|
271
|
+
if (typeof handle[QUIET] !== "function")
|
|
272
|
+
throw new TypeError("This matcher needs a channelstack handle");
|
|
273
|
+
const within = options.within ?? state.timeout;
|
|
274
|
+
let quiet = true;
|
|
275
|
+
try {
|
|
276
|
+
await untilQuiet(() => handle[QUIET](), {
|
|
277
|
+
timeout: within,
|
|
278
|
+
quietFor: options.quietFor ?? state.quietFor,
|
|
279
|
+
watching: true,
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
catch (error) {
|
|
283
|
+
if (!(error instanceof WaitTimeoutError))
|
|
284
|
+
throw error;
|
|
285
|
+
quiet = false;
|
|
286
|
+
}
|
|
287
|
+
const since = await appTurns(subject);
|
|
288
|
+
const pass = quiet && since.count <= options.maxReplies;
|
|
289
|
+
const turns = since.count === 0 ? "" : `: ${since.turns}`;
|
|
290
|
+
const open = pass === state.isNot ? await stillOpen(subject) : [];
|
|
291
|
+
const loops = pass === state.isNot ? await stoppedLoops(subject) : [];
|
|
292
|
+
return {
|
|
293
|
+
pass,
|
|
294
|
+
message: () => `Expected the conversation ${state.isNot ? "not " : ""}to go quiet within ${typeof within === "number" ? `${within}ms` : within} with at most ${options.maxReplies} app ${options.maxReplies === 1 ? "message" : "messages"} since a person last wrote. ${quiet ? "It went quiet" : "It was still busy"} with ${since.count} app ${since.count === 1 ? "message" : "messages"} and no person between them${turns}${open.length === 0 ? "" : `\nStill open: ${open.join("; ")}`}${loops.length === 0 ? "" : `\nStopped: ${loops.join("; ")}`}`,
|
|
295
|
+
};
|
|
296
|
+
},
|
|
297
|
+
/** The thread (or DM) has at least one reply from this author. */
|
|
298
|
+
toHaveReplyFrom(state, subject, author, options) {
|
|
299
|
+
const wanted = `a reply from ${nameOf(author)}${options?.text === undefined ? "" : ` matching ${show(options.text)}`}`;
|
|
300
|
+
return settle(subject, state, options, {
|
|
301
|
+
onceQuiet: false,
|
|
302
|
+
read: () => messagesOf(subject),
|
|
303
|
+
holds: (messages) => messages.some(from(author, options?.text)),
|
|
304
|
+
describe: (messages) => `Expected ${state.isNot ? wanted.replace(/^a /, "no ") : wanted}. The thread has:\n${says(messages)}`,
|
|
305
|
+
});
|
|
306
|
+
},
|
|
307
|
+
/** Exactly `count` replies from this author, checked once the agent is quiet. */
|
|
308
|
+
toHaveRepliesFrom(state, subject, author, options) {
|
|
309
|
+
return settle(subject, state, options, {
|
|
310
|
+
onceQuiet: true,
|
|
311
|
+
read: async () => (await messagesOf(subject)).filter(from(author, options.text)),
|
|
312
|
+
holds: (replies) => replies.length === options.count,
|
|
313
|
+
describe: (replies) => `Expected ${state.isNot ? "not " : ""}exactly ${options.count} ${options.count === 1 ? "reply" : "replies"} from ${nameOf(author)}, found ${replies.length}:\n${says(replies)}`,
|
|
314
|
+
});
|
|
315
|
+
},
|
|
316
|
+
/** A message from this author directly in the channel, outside any thread. */
|
|
317
|
+
toHaveChannelMessageFrom(state, subject, author, options) {
|
|
318
|
+
return settle(subject, state, options, {
|
|
319
|
+
onceQuiet: false,
|
|
320
|
+
read: async () => (await subject.messages()).filter(from(author)),
|
|
321
|
+
holds: (messages) => messages.length > 0,
|
|
322
|
+
describe: (messages) => state.isNot
|
|
323
|
+
? `Expected no message from ${nameOf(author)} in the channel itself, found:\n${says(messages)}`
|
|
324
|
+
: `Expected a message from ${nameOf(author)} in the channel itself, found none`,
|
|
325
|
+
});
|
|
326
|
+
},
|
|
327
|
+
/** Some entry a person would see contains this text. `count` makes it exact. */
|
|
328
|
+
toContainText(state, subject, text, options) {
|
|
329
|
+
const read = async () => {
|
|
330
|
+
const transcript = await subject.transcript(options?.as ? { as: options.as } : {});
|
|
331
|
+
const entries = transcript.entries.filter((entry) => options?.from === undefined || fromMatches(entry.author, options.from));
|
|
332
|
+
return { entries, matching: entries.filter((entry) => textMatches(entry.text, text)) };
|
|
333
|
+
};
|
|
334
|
+
return settle(subject, state, options, {
|
|
335
|
+
onceQuiet: options?.count !== undefined,
|
|
336
|
+
read,
|
|
337
|
+
holds: ({ matching }) => (options?.count === undefined ? matching.length > 0 : matching.length === options.count),
|
|
338
|
+
describe: ({ entries, matching }) => `Expected ${state.isNot ? "no text" : options?.count === undefined ? "text" : `exactly ${options.count} entries with text`} matching ${show(text)}, found ${matching.length}. A person sees:\n${listing(entries.map((entry) => `${entry.author.name}: ${entry.text}`))}`,
|
|
339
|
+
});
|
|
340
|
+
},
|
|
341
|
+
/** A reply from this author is being streamed right now. */
|
|
342
|
+
toHaveStreamingReplyFrom(state, subject, author, options) {
|
|
343
|
+
return settle(subject, state, options, {
|
|
344
|
+
onceQuiet: false,
|
|
345
|
+
read: () => messagesOf(subject),
|
|
346
|
+
holds: (messages) => messages.some((message) => message.stream?.state === "open" && (author === undefined || fromMatches(message.author, author))),
|
|
347
|
+
describe: (messages) => `Expected ${state.isNot ? "no" : "a"} reply being streamed${author === undefined ? "" : ` by ${nameOf(author)}`}. The thread has:\n${listing(messages.map((message) => `${message.author.name}: ${message.text} [${message.stream?.state ?? "not a stream"}]`))}`,
|
|
348
|
+
});
|
|
349
|
+
},
|
|
350
|
+
/** The agent's state in this thread: `working`, `streaming`, `stopped` or `idle`. */
|
|
351
|
+
toHaveStatus(state, subject, expected, options) {
|
|
352
|
+
return settle(subject, state, options, {
|
|
353
|
+
onceQuiet: false,
|
|
354
|
+
read: () => subject.status(),
|
|
355
|
+
holds: (status) => status.state === expected,
|
|
356
|
+
describe: (status) => `Expected the thread ${state.isNot ? "not " : ""}to be ${expected}, it is ${status.state}${status.text ? ` ("${status.text}")` : ""}`,
|
|
357
|
+
});
|
|
358
|
+
},
|
|
359
|
+
/** The status line the agent set. */
|
|
360
|
+
toHaveStatusText(state, subject, text, options) {
|
|
361
|
+
return settle(subject, state, options, {
|
|
362
|
+
onceQuiet: false,
|
|
363
|
+
read: () => subject.status(),
|
|
364
|
+
holds: (status) => status.text !== undefined && textMatches(status.text, text),
|
|
365
|
+
describe: (status) => `Expected the status line ${state.isNot ? "not " : ""}to match ${show(text)}, ${status.text === undefined ? "there is none" : `it is "${status.text}"`}`,
|
|
366
|
+
});
|
|
367
|
+
},
|
|
368
|
+
/** The message has a button with this label; for a thread or a conversation, the agent's latest message there. */
|
|
369
|
+
toHaveButton(state, subject, label, options) {
|
|
370
|
+
const handle = subject;
|
|
371
|
+
return settle(subject, state, options, {
|
|
372
|
+
onceQuiet: false,
|
|
373
|
+
read: async () => {
|
|
374
|
+
// A Slack message (it has a thread and a `ts`) is one entry of its thread's transcript.
|
|
375
|
+
if (handle.thread && handle.ts !== undefined) {
|
|
376
|
+
const { entries } = await handle.thread.transcript();
|
|
377
|
+
return entries.filter((entry) => entry.id === handle.ts).flatMap((entry) => entry.controls);
|
|
378
|
+
}
|
|
379
|
+
// A message whose own transcript starts with it (Discord's), or the app's latest message in a thread or channel.
|
|
380
|
+
const { entries } = await handle.transcript();
|
|
381
|
+
const own = handle.id === undefined ? undefined : entries.find((entry) => entry.id === handle.id);
|
|
382
|
+
return (own ?? entries.filter((entry) => entry.author.kind === "app").at(-1))?.controls ?? [];
|
|
383
|
+
},
|
|
384
|
+
holds: (controls) => controls.some((control) => textMatches(control, label)),
|
|
385
|
+
describe: (controls) => `Expected ${state.isNot ? "no" : "a"} button matching ${show(label)}. Buttons there: ${controls.length === 0 ? "none" : controls.join(", ")}`,
|
|
386
|
+
});
|
|
387
|
+
},
|
|
388
|
+
toHaveReaction(state, subject, emoji, options) {
|
|
389
|
+
const name = emoji.replace(/^:|:$/g, "");
|
|
390
|
+
return settle(subject, state, options, {
|
|
391
|
+
onceQuiet: false,
|
|
392
|
+
read: () => subject.reactions(),
|
|
393
|
+
holds: (reactions) => reactions.some((reaction) => reaction.emoji === name &&
|
|
394
|
+
(options?.by === undefined || reaction.by.some((author) => fromMatches(author, options.by)))),
|
|
395
|
+
describe: (reactions) => `Expected ${state.isNot ? "no" : "a"} :${name}: reaction${options?.by === undefined ? "" : ` by ${nameOf(options.by)}`}. Reactions there: ${reactions.length === 0 ? "none" : reactions.map((reaction) => `:${reaction.emoji}: by ${reaction.by.map((author) => author.name).join(", ")}`).join("; ")}`,
|
|
396
|
+
});
|
|
397
|
+
},
|
|
398
|
+
/** Subject: a person. The agent opened a modal for them (it may be submitted by now), with this title if one is given. */
|
|
399
|
+
toHaveOpenedModal(state, subject, title, options) {
|
|
400
|
+
return settle(subject, state, options, {
|
|
401
|
+
onceQuiet: false,
|
|
402
|
+
read: () => subject.modals(),
|
|
403
|
+
holds: (modals) => modals.some((modal) => textMatches(modal.title, title)),
|
|
404
|
+
describe: (modals) => `Expected ${state.isNot ? "no" : "a"} modal${title === undefined ? "" : ` titled ${show(title)}`} to have been opened. Opened: ${modals.length === 0 ? "none" : modals.map((modal) => JSON.stringify(modal.title)).join(", ")}`,
|
|
405
|
+
});
|
|
406
|
+
},
|
|
407
|
+
/** Subject: a GitHub issue or pull request, a Linear issue or a Notion discussion. At least one comment from this author. */
|
|
408
|
+
toHaveCommentFrom(state, subject, author, options) {
|
|
409
|
+
const wanted = `a comment from ${nameOf(author)}${options?.text === undefined ? "" : ` matching ${show(options.text)}`}`;
|
|
410
|
+
return settle(subject, state, options, {
|
|
411
|
+
onceQuiet: false,
|
|
412
|
+
read: () => commentsOf(subject, "toHaveCommentFrom"),
|
|
413
|
+
holds: (comments) => comments.some(commentFrom(author, options?.text)),
|
|
414
|
+
describe: (comments) => `Expected ${state.isNot ? wanted.replace(/^a /, "no ") : wanted}. The conversation has:\n${written(comments)}`,
|
|
415
|
+
});
|
|
416
|
+
},
|
|
417
|
+
/** Exactly `count` comments from this author, checked once the agent is quiet. */
|
|
418
|
+
toHaveCommentsFrom(state, subject, author, options) {
|
|
419
|
+
return settle(subject, state, options, {
|
|
420
|
+
onceQuiet: true,
|
|
421
|
+
read: () => commentsOf(subject, "toHaveCommentsFrom"),
|
|
422
|
+
holds: (comments) => comments.filter(commentFrom(author)).length === options.count,
|
|
423
|
+
describe: (comments) => `Expected ${state.isNot ? "not " : ""}exactly ${options.count} comments from ${nameOf(author)}, found ${comments.filter(commentFrom(author)).length}:\n${written(comments)}`,
|
|
424
|
+
});
|
|
425
|
+
},
|
|
426
|
+
/** Subject: a pull request. A comment on the diff, matched by every field that is given. */
|
|
427
|
+
toHaveReviewComment(state, subject, expected, options) {
|
|
428
|
+
const pull = subject;
|
|
429
|
+
const wanted = [
|
|
430
|
+
expected.path === undefined
|
|
431
|
+
? ""
|
|
432
|
+
: ` on ${expected.path}${expected.line === undefined ? "" : `:${expected.line}`}`,
|
|
433
|
+
expected.from === undefined ? "" : ` from ${nameOf(expected.from)}`,
|
|
434
|
+
expected.text === undefined ? "" : ` matching ${show(expected.text)}`,
|
|
435
|
+
].join("");
|
|
436
|
+
return settle(subject, state, options, {
|
|
437
|
+
onceQuiet: false,
|
|
438
|
+
read: () => pull.reviewComments(),
|
|
439
|
+
holds: (comments) => comments.some((comment) => (expected.path === undefined || comment.path === expected.path) &&
|
|
440
|
+
(expected.line === undefined || comment.line === expected.line) &&
|
|
441
|
+
(expected.from === undefined || fromMatches(comment.author, expected.from)) &&
|
|
442
|
+
textMatches(commentText(comment), expected.text)),
|
|
443
|
+
describe: (comments) => `Expected ${state.isNot ? "no" : "a"} comment on the diff${wanted}. The diff has:\n${listing(comments.map((comment) => `${comment.author.name} on ${comment.path}:${comment.line}: ${comment.body}`))}`,
|
|
444
|
+
});
|
|
445
|
+
},
|
|
446
|
+
/** Subject: a pull request. A review from this author, with this verdict if one is given. */
|
|
447
|
+
toHaveReviewFrom(state, subject, author, options) {
|
|
448
|
+
const pull = subject;
|
|
449
|
+
return settle(subject, state, options, {
|
|
450
|
+
onceQuiet: false,
|
|
451
|
+
read: () => pull.reviews(),
|
|
452
|
+
holds: (reviews) => reviews.some((review) => fromMatches(review.author, author) && (options?.state === undefined || review.state === options.state)),
|
|
453
|
+
describe: (reviews) => `Expected ${state.isNot ? "no" : "a"} review from ${nameOf(author)}${options?.state === undefined ? "" : ` with state ${options.state}`}. Reviews there:\n${listing(reviews.map((review) => `${review.author.name}: ${review.state}${review.body === "" ? "" : ` ${JSON.stringify(review.body)}`}`))}`,
|
|
454
|
+
});
|
|
455
|
+
},
|
|
456
|
+
/** Subject: a pull request or a commit. A check run of this name, in this state if one is given. */
|
|
457
|
+
toHaveCheckRun(state, subject, name, options) {
|
|
458
|
+
const target = subject;
|
|
459
|
+
const wanted = [options?.status, options?.conclusion].filter((part) => part !== undefined).join(", ");
|
|
460
|
+
return settle(subject, state, options, {
|
|
461
|
+
onceQuiet: false,
|
|
462
|
+
read: () => target.checkRuns(),
|
|
463
|
+
holds: (runs) => runs.some((run) => (typeof name === "string" ? run.name === name : textMatches(run.name, name)) &&
|
|
464
|
+
(options?.status === undefined || run.status === options.status) &&
|
|
465
|
+
(options?.conclusion === undefined || run.conclusion === options.conclusion)),
|
|
466
|
+
describe: (runs) => `Expected ${state.isNot ? "no" : "a"} check run ${show(name)}${wanted === "" ? "" : ` (${wanted})`}. Check runs there:\n${listing(runs.map((run) => `${run.name}: ${run.status}${run.conclusion === undefined ? "" : `, ${run.conclusion}`}`))}`,
|
|
467
|
+
});
|
|
468
|
+
},
|
|
469
|
+
/** Subject: an issue or a pull request. It has this label. */
|
|
470
|
+
toHaveLabel(state, subject, name, options) {
|
|
471
|
+
const issue = subject;
|
|
472
|
+
return settle(subject, state, options, {
|
|
473
|
+
onceQuiet: false,
|
|
474
|
+
read: () => issue.labels(),
|
|
475
|
+
holds: (labels) => labels.some((label) => label.toLowerCase() === name.toLowerCase()),
|
|
476
|
+
describe: (labels) => `Expected ${state.isNot ? "no" : "the"} label ${JSON.stringify(name)}. Labels there: ${labels.length === 0 ? "none" : labels.join(", ")}`,
|
|
477
|
+
});
|
|
478
|
+
},
|
|
479
|
+
/** Subject: a pull request. It has been merged. */
|
|
480
|
+
toBeMerged(state, subject, options) {
|
|
481
|
+
const pull = subject;
|
|
482
|
+
return settle(subject, state, options, {
|
|
483
|
+
onceQuiet: false,
|
|
484
|
+
read: () => pull.merged(),
|
|
485
|
+
holds: (merged) => merged,
|
|
486
|
+
describe: () => `Expected the pull request ${state.isNot ? "not " : ""}to be merged`,
|
|
487
|
+
});
|
|
488
|
+
},
|
|
489
|
+
/** Subject: a Linear agent session, or an issue (its latest session). The session's status. */
|
|
490
|
+
toHaveSessionState(state, subject, wanted, options) {
|
|
491
|
+
return settle(subject, state, options, {
|
|
492
|
+
onceQuiet: false,
|
|
493
|
+
read: async () => (await sessionOf(subject))?.state() ?? Promise.resolve("no session"),
|
|
494
|
+
holds: (current) => current === wanted,
|
|
495
|
+
describe: (current) => `Expected the agent session ${state.isNot ? "not " : ""}to be ${wanted}, it is ${current}`,
|
|
496
|
+
});
|
|
497
|
+
},
|
|
498
|
+
/**
|
|
499
|
+
* Subject: a Linear agent session, or an issue (its latest session). An activity of the agent's
|
|
500
|
+
* matching every field that is given: a person's turns (`prompt`, delegating's first among them)
|
|
501
|
+
* aren't what it published.
|
|
502
|
+
*/
|
|
503
|
+
toHaveActivity(state, subject, expected, options) {
|
|
504
|
+
const wanted = [
|
|
505
|
+
expected.type ?? "activity",
|
|
506
|
+
expected.from === undefined ? "" : ` from ${nameOf(expected.from)}`,
|
|
507
|
+
expected.text === undefined ? "" : ` matching ${show(expected.text)}`,
|
|
508
|
+
].join("");
|
|
509
|
+
return settle(subject, state, options, {
|
|
510
|
+
onceQuiet: false,
|
|
511
|
+
read: async () => ((await (await sessionOf(subject))?.activities()) ?? []).filter((activity) => activity.type !== "prompt"),
|
|
512
|
+
holds: (activities) => activities.some((activity) => (expected.type === undefined || activity.type === expected.type) &&
|
|
513
|
+
(expected.from === undefined || fromMatches(activity.author, expected.from)) &&
|
|
514
|
+
textMatches(activity.body ?? "", expected.text)),
|
|
515
|
+
describe: (activities) => `Expected ${state.isNot ? "no" : "a"} ${wanted}. The session has:\n${listing(activities.map((activity) => `${activity.author.name} (${activity.type}): ${activity.body ?? ""}`))}`,
|
|
516
|
+
});
|
|
517
|
+
},
|
|
518
|
+
/** Subject: a Linear issue. It is delegated to this app, or (with `undefined`) to none. */
|
|
519
|
+
toBeDelegatedTo(state, subject, app, options) {
|
|
520
|
+
const issue = subject;
|
|
521
|
+
return settle(subject, state, options, {
|
|
522
|
+
onceQuiet: false,
|
|
523
|
+
read: () => issue.delegatedTo(),
|
|
524
|
+
holds: (delegate) => (app === undefined ? delegate === undefined : delegate?.id === app.id),
|
|
525
|
+
describe: (delegate) => `Expected the issue ${state.isNot ? "not " : ""}to be delegated to ${app?.name ?? "no one"}, it is delegated to ${delegate?.name ?? "no one"}`,
|
|
526
|
+
});
|
|
527
|
+
},
|
|
528
|
+
/** Subject: a Linear issue. It is assigned to this person, or (with `undefined`) to no one. */
|
|
529
|
+
toBeAssignedTo(state, subject, user, options) {
|
|
530
|
+
const issue = subject;
|
|
531
|
+
return settle(subject, state, options, {
|
|
532
|
+
onceQuiet: false,
|
|
533
|
+
read: () => issue.assignee(),
|
|
534
|
+
holds: (assignee) => (user === undefined ? assignee === undefined : assignee?.id === user.id),
|
|
535
|
+
describe: (assignee) => `Expected the issue ${state.isNot ? "not " : ""}to be assigned to ${user?.name ?? "no one"}, it is assigned to ${assignee?.name ?? "no one"}`,
|
|
536
|
+
});
|
|
537
|
+
},
|
|
538
|
+
/** Subject: a Notion page. A block (at any depth) whose text matches. */
|
|
539
|
+
toHaveBlock(state, subject, text, options) {
|
|
540
|
+
const page = subject;
|
|
541
|
+
return settle(subject, state, options, {
|
|
542
|
+
onceQuiet: false,
|
|
543
|
+
read: async () => blockTexts(await page.blocks()),
|
|
544
|
+
holds: (texts) => texts.some((line) => textMatches(line, text)),
|
|
545
|
+
describe: (texts) => `Expected the page ${state.isNot ? "not " : ""}to have a block matching ${show(text)}. Its blocks:\n${listing(texts)}`,
|
|
546
|
+
});
|
|
547
|
+
},
|
|
548
|
+
/** Subject: a Notion page. A property has this value; asymmetric matchers (`expect.any(Number)`) work. */
|
|
549
|
+
toHavePropertyValue(state, subject, name, expected, options) {
|
|
550
|
+
const page = subject;
|
|
551
|
+
const equals = state.equals ?? ((a, b) => JSON.stringify(a) === JSON.stringify(b));
|
|
552
|
+
return settle(subject, state, options, {
|
|
553
|
+
onceQuiet: false,
|
|
554
|
+
read: () => page.property(name),
|
|
555
|
+
holds: (value) => equals(value, expected),
|
|
556
|
+
describe: (value) => `Expected ${name} ${state.isNot ? "not " : ""}to be ${String(expected)}, it is ${JSON.stringify(value)}`,
|
|
557
|
+
});
|
|
558
|
+
},
|
|
559
|
+
/** Subject: a Linear issue. Its workflow state, by name. */
|
|
560
|
+
toHaveState(state, subject, name, options) {
|
|
561
|
+
const issue = subject;
|
|
562
|
+
return settle(subject, state, options, {
|
|
563
|
+
onceQuiet: false,
|
|
564
|
+
read: async () => (await issue.state()).name,
|
|
565
|
+
holds: (current) => current.toLowerCase() === name.toLowerCase(),
|
|
566
|
+
describe: (current) => `Expected the issue ${state.isNot ? "not " : ""}to be in ${JSON.stringify(name)}, it is in ${JSON.stringify(current)}`,
|
|
567
|
+
});
|
|
568
|
+
},
|
|
569
|
+
/** Only this person can see the message. */
|
|
570
|
+
async toBeEphemeralFor(state, subject, user) {
|
|
571
|
+
const visibleTo = subject.visibleTo;
|
|
572
|
+
return {
|
|
573
|
+
pass: visibleTo?.id === user.id,
|
|
574
|
+
message: () => `Expected the message ${state.isNot ? "not " : ""}to be visible only to ${user.name}, ${visibleTo === undefined ? "everyone can see it" : `only ${visibleTo.name} can`}`,
|
|
575
|
+
};
|
|
576
|
+
},
|
|
577
|
+
/** The agent answered the delivery with 2xx, within the platform's window. */
|
|
578
|
+
toBeAccepted(state, subject, options) {
|
|
579
|
+
const delivery = subject;
|
|
580
|
+
const within = options?.within === undefined ? undefined : parseDuration(options.within);
|
|
581
|
+
return settle(subject, state, options, {
|
|
582
|
+
onceQuiet: false,
|
|
583
|
+
read: async () => (await delivery.refresh()).attempts.find((attempt) => !attempt.forgedSignature),
|
|
584
|
+
// Accepted, and with `within`, accepted that fast: the platform's window is only the outer limit.
|
|
585
|
+
holds: (attempt) => attempt?.status === "acknowledged" && (within === undefined || (attempt.durationMs ?? 0) <= within),
|
|
586
|
+
describe: (attempt) => {
|
|
587
|
+
const expected = `Expected delivery ${delivery.id} ${state.isNot ? "not " : ""}to be accepted${within === undefined ? "" : ` within ${within}ms`}`;
|
|
588
|
+
const http = attempt?.responseStatus === undefined ? "" : ` (HTTP ${attempt.responseStatus})`;
|
|
589
|
+
const took = attempt?.durationMs === undefined ? "" : ` after ${attempt.durationMs}ms`;
|
|
590
|
+
return `${expected}, its first attempt is ${attempt?.status ?? "missing"}${http}${took}`;
|
|
591
|
+
},
|
|
592
|
+
});
|
|
593
|
+
},
|
|
594
|
+
/** A forged delivery (bad signature, stale timestamp) was refused by the agent with a 4xx. */
|
|
595
|
+
toBeRejected(state, subject, options) {
|
|
596
|
+
const delivery = subject;
|
|
597
|
+
const refused = (attempt) => attempt?.status === "failed" &&
|
|
598
|
+
attempt.responseStatus !== undefined &&
|
|
599
|
+
attempt.responseStatus >= 400 &&
|
|
600
|
+
attempt.responseStatus < 500;
|
|
601
|
+
return settle(subject, state, options, {
|
|
602
|
+
onceQuiet: false,
|
|
603
|
+
read: async () => (await delivery.refresh()).attempts.filter((attempt) => attempt.forgedSignature).at(-1),
|
|
604
|
+
holds: refused,
|
|
605
|
+
describe: (attempt) => attempt === undefined
|
|
606
|
+
? `Expected delivery ${delivery.id} to be rejected, but no forged attempt was sent. Call delivery.resend({ badSignature: true }) first`
|
|
607
|
+
: `Expected the forged attempt of delivery ${delivery.id} ${state.isNot ? "not " : ""}to be rejected with a 4xx, the agent answered ${attempt.responseStatus ?? attempt.status}`,
|
|
608
|
+
});
|
|
609
|
+
},
|
|
610
|
+
/** The delivery needed retries. */
|
|
611
|
+
toBeRetried(state, subject, options) {
|
|
612
|
+
const delivery = subject;
|
|
613
|
+
return settle(subject, state, options, {
|
|
614
|
+
onceQuiet: options?.times !== undefined,
|
|
615
|
+
read: async () => (await delivery.refresh()).attempts.filter((attempt) => !attempt.forgedSignature).length - 1,
|
|
616
|
+
holds: (retries) => (options?.times === undefined ? retries > 0 : retries === options.times),
|
|
617
|
+
describe: (retries) => `Expected delivery ${delivery.id} ${state.isNot ? "not " : ""}to be retried${options?.times === undefined ? "" : ` ${options.times} times`}, it was retried ${retries} times`,
|
|
618
|
+
});
|
|
619
|
+
},
|
|
620
|
+
/** The agent made this API call. */
|
|
621
|
+
toHaveReceivedCall(state, subject, operation, options) {
|
|
622
|
+
// A channel's calls have an operation; a model call has its endpoint (`chat.completions`).
|
|
623
|
+
const fixture = subject;
|
|
624
|
+
const named = (call) => call.operation ?? call.endpoint ?? "";
|
|
625
|
+
return settle(subject, state, options, {
|
|
626
|
+
onceQuiet: options?.times !== undefined,
|
|
627
|
+
read: async () => {
|
|
628
|
+
const calls = await fixture.calls(options?.error === undefined ? {} : { error: options.error });
|
|
629
|
+
return {
|
|
630
|
+
calls,
|
|
631
|
+
matching: calls.filter((call) => typeof operation === "string" ? named(call) === operation : textMatches(named(call), operation)),
|
|
632
|
+
};
|
|
633
|
+
},
|
|
634
|
+
holds: ({ matching }) => (options?.times === undefined ? matching.length > 0 : matching.length === options.times),
|
|
635
|
+
describe: ({ calls, matching }) => `Expected the agent ${state.isNot ? "not " : ""}to call ${show(operation)}${options?.times === undefined ? "" : ` ${options.times} times`}${options?.error === undefined ? "" : ` with error ${options.error}`}, found ${matching.length}. Its calls:\n${listing(calls.map((call) => `${named(call)}${call.error ? ` → ${call.error}` : ""}`))}`,
|
|
636
|
+
});
|
|
637
|
+
},
|
|
638
|
+
// --- The model (decision 0029) ---------------------------------------------------------------
|
|
639
|
+
/**
|
|
640
|
+
* What the agent sent the model: text, a pattern, a message's text, or several messages in order
|
|
641
|
+
* (thread history). The subject is the `openai` fixture (any of the session's calls), a script
|
|
642
|
+
* (the calls it answered), or one call.
|
|
643
|
+
*/
|
|
644
|
+
toHaveSent(state, subject, expected, options) {
|
|
645
|
+
const wanted = (Array.isArray(expected) ? expected : [expected]);
|
|
646
|
+
const ordered = options?.ordered ?? Array.isArray(expected);
|
|
647
|
+
return settle(subject, state, options, {
|
|
648
|
+
onceQuiet: false,
|
|
649
|
+
read: async () => (await modelCalls(subject)).map((call) => call.request.text),
|
|
650
|
+
holds: (texts) => texts.some((text) => sentIn(text, wanted, ordered)),
|
|
651
|
+
describe: (texts) => `Expected the agent ${state.isNot ? "not " : ""}to send the model ${wanted.map((item) => show(asText(item))).join(", then ")}${ordered && wanted.length > 1 ? " in that order" : ""}. ${texts.length === 0 ? "It made no model call." : `What it sent, newest first:\n${listing(texts.toReversed().map((text) => excerptOf(text)))}`}`,
|
|
652
|
+
});
|
|
653
|
+
},
|
|
654
|
+
/**
|
|
655
|
+
* The agent sent the model this image, file or audio, compared by its SHA-256: a fixture file's
|
|
656
|
+
* path (read as a `MediaSource` is, from the files root) or its bytes. The subject is the
|
|
657
|
+
* `openai` fixture, a script or one call, as for `toHaveSent`.
|
|
658
|
+
*/
|
|
659
|
+
toHaveSentFile(state, subject, file, options) {
|
|
660
|
+
const read = readMedia(file);
|
|
661
|
+
if (!("content" in read))
|
|
662
|
+
throw new TypeError("toHaveSentFile takes a path or bytes");
|
|
663
|
+
const bytes = Buffer.from(read.content, "base64");
|
|
664
|
+
const sha256 = createHash("sha256").update(bytes).digest("hex");
|
|
665
|
+
const named = read.name ?? "these bytes";
|
|
666
|
+
return settle(subject, state, options, {
|
|
667
|
+
onceQuiet: false,
|
|
668
|
+
read: async () =>
|
|
669
|
+
// A media endpoint's file is its message's first part, so the parts are everything.
|
|
670
|
+
(await modelCalls(subject)).flatMap((call) => (call.request.messages ?? []).flatMap((message) => message.parts ?? [])),
|
|
671
|
+
holds: (parts) => parts.some((part) => part.sha256 === sha256),
|
|
672
|
+
describe: (parts) => `Expected the agent ${state.isNot ? "not " : ""}to send the model ${named} (${sizeOf(bytes.length)}, sha256 ${sha256.slice(0, 12)}). ${parts.length === 0 ? "It sent no image, file or audio." : `What it sent, newest first:\n${listing(parts.toReversed().map(partOf))}`}`,
|
|
673
|
+
});
|
|
674
|
+
},
|
|
675
|
+
/** A secret channelstack knows (a token, a signing secret, a key) was sent to the model. Use it as `not.`. */
|
|
676
|
+
toHaveSentSecrets(state, subject, options) {
|
|
677
|
+
const fixture = subject;
|
|
678
|
+
if (typeof fixture.sentSecrets !== "function")
|
|
679
|
+
throw new TypeError("toHaveSentSecrets needs the openai fixture");
|
|
680
|
+
return settle(subject, state, options, {
|
|
681
|
+
onceQuiet: false,
|
|
682
|
+
read: () => fixture.sentSecrets(),
|
|
683
|
+
holds: (sent) => sent.length > 0,
|
|
684
|
+
describe: (sent) => sent.length === 0
|
|
685
|
+
? "Expected the agent to send the model a secret, it sent none"
|
|
686
|
+
: `Expected the agent not to send the model any secret, it sent:\n${listing(sent.map((one) => `${one.call}: ${one.kinds.join(", ")}`))}`,
|
|
687
|
+
});
|
|
688
|
+
},
|
|
689
|
+
/** The call offered the model this tool (with this JSON Schema). */
|
|
690
|
+
toHaveOfferedTool(state, subject, name, options) {
|
|
691
|
+
return settle(subject, state, options, {
|
|
692
|
+
onceQuiet: false,
|
|
693
|
+
read: async () => (await modelCalls(subject)).flatMap((call) => call.request.tools),
|
|
694
|
+
holds: (tools) => tools.some((tool) => (tool.name ?? tool.type) === name &&
|
|
695
|
+
(options?.schema === undefined || (state.equals ?? Object.is)(tool.parameters, options.schema))),
|
|
696
|
+
describe: (tools) => `Expected the agent ${state.isNot ? "not " : ""}to offer the model the tool ${JSON.stringify(name)}, it offered ${tools.length === 0 ? "none" : [...new Set(tools.map((tool) => tool.name ?? tool.type))].join(", ")}`,
|
|
697
|
+
});
|
|
698
|
+
},
|
|
699
|
+
/** The agent ran the model's call to this tool and sent its result back (with this text). */
|
|
700
|
+
toHaveSentToolResult(state, subject, name, options) {
|
|
701
|
+
const handle = subject;
|
|
702
|
+
if (typeof handle.toolCalls !== "function")
|
|
703
|
+
throw new TypeError("toHaveSentToolResult needs the openai fixture or a script");
|
|
704
|
+
return settle(subject, state, options, {
|
|
705
|
+
onceQuiet: false,
|
|
706
|
+
read: () => handle.toolCalls({ name }),
|
|
707
|
+
holds: (calls) => calls.some((call) => call.result !== undefined && textMatches(call.result.text, options?.text)),
|
|
708
|
+
describe: (calls) => `Expected the agent ${state.isNot ? "not " : ""}to send back a result for ${JSON.stringify(name)}${options?.text === undefined ? "" : ` with ${show(options.text)}`}. The model called it ${calls.length} times; ${calls.filter((call) => call.result).length} got a result${calls.some((call) => call.result) ? `:\n${listing(calls.flatMap((call) => (call.result ? [excerptOf(call.result.text)] : [])))}` : ""}`,
|
|
709
|
+
});
|
|
710
|
+
},
|
|
711
|
+
/** The agent hung up before the model's answer was complete: it cancelled the request (Stop), or timed out. */
|
|
712
|
+
toBeAborted(state, subject, options) {
|
|
713
|
+
const call = subject;
|
|
714
|
+
if (typeof call.refresh !== "function")
|
|
715
|
+
throw new TypeError("toBeAborted needs a model call");
|
|
716
|
+
return settle(subject, state, options, {
|
|
717
|
+
onceQuiet: false,
|
|
718
|
+
read: async () => (await call.refresh()).response,
|
|
719
|
+
holds: (response) => response.aborted,
|
|
720
|
+
describe: (response) => `Expected model call ${call.id} ${state.isNot ? "not " : ""}to be aborted by the agent, it ${response.end === undefined ? "is still going" : `ended ${response.end}`}`,
|
|
721
|
+
});
|
|
722
|
+
},
|
|
723
|
+
/**
|
|
724
|
+
* The script answered calls (exactly `times` of them, once the agent is quiet): a call counts once
|
|
725
|
+
* the script's turn reached the agent, not one it was given and the fake refused.
|
|
726
|
+
*/
|
|
727
|
+
toHaveAnswered(state, subject, options) {
|
|
728
|
+
const script = subject;
|
|
729
|
+
if (typeof script.refresh !== "function" || typeof script.calls !== "function")
|
|
730
|
+
throw new TypeError("toHaveAnswered needs a script");
|
|
731
|
+
return settle(subject, state, options, {
|
|
732
|
+
onceQuiet: options?.times !== undefined,
|
|
733
|
+
read: async () => {
|
|
734
|
+
const [calls, { problems }] = await Promise.all([script.calls(), script.refresh()]);
|
|
735
|
+
return { answered: calls.filter(answered).length, problems };
|
|
736
|
+
},
|
|
737
|
+
holds: ({ answered: count }) => (options?.times === undefined ? count > 0 : count === options.times),
|
|
738
|
+
describe: ({ answered: count, problems }) => `Expected script ${script.id} ${state.isNot ? "not " : ""}to answer ${options?.times === undefined ? "a call" : `${options.times} ${options.times === 1 ? "call" : "calls"}`}, it answered ${count}${problems.length === 0 ? "" : `. Its problems:\n${listing(problems)}`}`,
|
|
739
|
+
});
|
|
740
|
+
},
|
|
741
|
+
};
|
|
742
|
+
/**
|
|
743
|
+
* Whether the script's turn reached the agent: an answer (text, tool calls, a refusal) or a
|
|
744
|
+
* scripted error. Not a call the fake refused for the script (`channelstack_no_script`: a turn the
|
|
745
|
+
* real API can't give, a list that ran out, a responder that threw), nor one a responder still
|
|
746
|
+
* holds, nor one the agent hung up on before anything was sent (status 0 without a scripted error).
|
|
747
|
+
*/
|
|
748
|
+
const answered = ({ response }) => response.error !== "channelstack_no_script" &&
|
|
749
|
+
(response.text !== undefined || response.error !== undefined) &&
|
|
750
|
+
(response.status !== 0 || response.error !== undefined);
|
|
751
|
+
/** The model calls a matcher reads: the fixture's or a script's (a list), or one call. */
|
|
752
|
+
async function modelCalls(subject) {
|
|
753
|
+
const handle = subject;
|
|
754
|
+
if (typeof handle.calls === "function")
|
|
755
|
+
return handle.calls();
|
|
756
|
+
if (typeof handle.refresh === "function")
|
|
757
|
+
return [await handle.refresh()];
|
|
758
|
+
if (handle.request !== undefined)
|
|
759
|
+
return [handle];
|
|
760
|
+
throw new TypeError("This matcher needs the openai fixture, a script or a model call");
|
|
761
|
+
}
|
|
762
|
+
const asText = (item) => typeof item === "object" && "text" in item ? item.text : item;
|
|
763
|
+
/** Whether a request's text has every wanted piece, in order when asked. */
|
|
764
|
+
function sentIn(text, wanted, ordered) {
|
|
765
|
+
const haystack = normalisedText(text);
|
|
766
|
+
let from = 0;
|
|
767
|
+
for (const item of wanted) {
|
|
768
|
+
const piece = asText(item);
|
|
769
|
+
if (piece instanceof RegExp) {
|
|
770
|
+
piece.lastIndex = 0;
|
|
771
|
+
const match = piece.exec(text);
|
|
772
|
+
if (!match)
|
|
773
|
+
return false;
|
|
774
|
+
continue;
|
|
775
|
+
}
|
|
776
|
+
const needle = normalisedText(piece);
|
|
777
|
+
const at = haystack.indexOf(needle, ordered ? from : 0);
|
|
778
|
+
if (at === -1)
|
|
779
|
+
return false;
|
|
780
|
+
from = at + needle.length;
|
|
781
|
+
}
|
|
782
|
+
return true;
|
|
783
|
+
}
|
|
784
|
+
const sizeOf = (bytes) => `${bytes} ${bytes === 1 ? "byte" : "bytes"}`;
|
|
785
|
+
/** One part as a failure lists it: its type, media type, size and hash, or where it is when the fake didn't read it. */
|
|
786
|
+
const partOf = (part) => [
|
|
787
|
+
part.type,
|
|
788
|
+
part.mediaType,
|
|
789
|
+
part.bytes === undefined ? undefined : sizeOf(part.bytes),
|
|
790
|
+
part.sha256 === undefined
|
|
791
|
+
? (part.url ?? (part.fileId === undefined ? undefined : `file ${part.fileId}`))
|
|
792
|
+
: `sha256 ${part.sha256.slice(0, 12)}`,
|
|
793
|
+
]
|
|
794
|
+
.filter((piece) => piece !== undefined)
|
|
795
|
+
.join(", ");
|
|
796
|
+
const excerptOf = (text) => {
|
|
797
|
+
const line = text.replace(/\s+/g, " ").trim();
|
|
798
|
+
return line.length > 120 ? `${line.slice(0, 119)}…` : line;
|
|
799
|
+
};
|