channelstack 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/README.md +1 -1
- package/dist/integrations/checks/index.d.ts +40 -7
- package/dist/integrations/checks/index.js +525 -69
- package/dist/integrations/matchers-core/index.d.ts +90 -11
- package/dist/integrations/matchers-core/index.js +356 -15
- package/dist/integrations/matchers-core/matchers.test.js +251 -3
- package/dist/integrations/vitest/index.d.ts +4 -2
- package/dist/integrations/vitest/setup.js +33 -3
- package/dist/sdks/typescript/client.d.ts +5 -4
- package/dist/sdks/typescript/client.js +4 -4
- package/dist/sdks/typescript/generated/channels.d.ts +17 -9
- package/dist/sdks/typescript/generated/channels.js +3 -1
- package/dist/sdks/typescript/generated/index.d.ts +1744 -313
- package/dist/sdks/typescript/generated/index.js +1991 -422
- 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 +9 -0
- package/dist/sdks/typescript/runtime/client.js +5 -0
- package/dist/sdks/typescript/runtime/files.d.ts +17 -2
- package/dist/sdks/typescript/runtime/files.js +11 -3
- package/dist/sdks/typescript/runtime/launcher.d.ts +5 -2
- package/dist/sdks/typescript/runtime/launcher.js +6 -3
- package/dist/sdks/typescript/runtime/responder.d.ts +26 -0
- package/dist/sdks/typescript/runtime/responder.js +42 -0
- package/dist/sdks/typescript/runtime/wait.d.ts +14 -0
- package/dist/sdks/typescript/runtime/wait.js +23 -0
- package/dist/sdks/typescript/types.d.ts +16 -6
- package/package.json +9 -7
|
@@ -1,12 +1,4 @@
|
|
|
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 { type Duration, type SlackConversation } from "../../sdks/typescript/client.ts";
|
|
1
|
+
import { type DiscordChannel, type Duration, type SlackConversation } from "../../sdks/typescript/client.ts";
|
|
10
2
|
export interface MatcherResult {
|
|
11
3
|
pass: boolean;
|
|
12
4
|
/** Why it failed (or, for a negated matcher, why it unexpectedly passed). */
|
|
@@ -30,9 +22,59 @@ type Author = {
|
|
|
30
22
|
readonly name: string;
|
|
31
23
|
};
|
|
32
24
|
type AuthorRef = Author | string;
|
|
33
|
-
/**
|
|
34
|
-
|
|
25
|
+
/**
|
|
26
|
+
* Who a transcript is read as, in the channels that show some messages to one person only (Slack's
|
|
27
|
+
* and Discord's ephemeral ones): the SDK's own types, so a change to that signature fails to compile here.
|
|
28
|
+
*/
|
|
29
|
+
type ViewerOf<Handle extends {
|
|
30
|
+
transcript(options?: {
|
|
31
|
+
as?: unknown;
|
|
32
|
+
}): unknown;
|
|
33
|
+
}> = NonNullable<NonNullable<Parameters<Handle["transcript"]>[0]>["as"]>;
|
|
34
|
+
type Viewer = ViewerOf<SlackConversation> | ViewerOf<DiscordChannel>;
|
|
35
|
+
/** A model call no session claimed, as `GET /sessions/{sid}/openai/unattributed` lists it. */
|
|
36
|
+
interface UnattributedCall {
|
|
37
|
+
readonly id: string;
|
|
38
|
+
readonly lastUserText?: string | undefined;
|
|
39
|
+
readonly sinceMs: number;
|
|
40
|
+
readonly message: string;
|
|
41
|
+
}
|
|
42
|
+
/** A model call of the session, as far as its attribution goes. */
|
|
43
|
+
interface AttributedCall {
|
|
44
|
+
readonly id: string;
|
|
45
|
+
readonly request: {
|
|
46
|
+
readonly context: {
|
|
47
|
+
readonly attributedBy?: string | undefined;
|
|
48
|
+
readonly matched?: string | undefined;
|
|
49
|
+
readonly tiedWith?: readonly string[] | undefined;
|
|
50
|
+
};
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/** The lines of `modelNotesOf`, from what the server answered. */
|
|
54
|
+
export declare function modelNotes(unattributed: readonly UnattributedCall[], calls: readonly AttributedCall[]): string[];
|
|
55
|
+
/**
|
|
56
|
+
* The app messages of a conversation since a person last wrote in it, those before a check began
|
|
57
|
+
* included, and their authors in turn (`my-agent → coder → my-agent`): what `toGoQuiet` and each
|
|
58
|
+
* `<channel>.no-reply-loop` name when apps answer each other (decision 0027).
|
|
59
|
+
*/
|
|
60
|
+
export declare function appTurns(subject: unknown): Promise<{
|
|
61
|
+
count: number;
|
|
62
|
+
turns: string;
|
|
63
|
+
}>;
|
|
35
64
|
export declare const matchers: {
|
|
65
|
+
/**
|
|
66
|
+
* The conversation goes quiet within `within`, holding at most `maxReplies` app messages since
|
|
67
|
+
* a person last wrote in it, those before the check began included: apps that answer each other
|
|
68
|
+
* without end fail it (decision 0027).
|
|
69
|
+
*/
|
|
70
|
+
toGoQuiet(state: MatcherState, subject: unknown, options: {
|
|
71
|
+
within?: Duration;
|
|
72
|
+
maxReplies: number;
|
|
73
|
+
quietFor?: Duration;
|
|
74
|
+
}): Promise<{
|
|
75
|
+
pass: boolean;
|
|
76
|
+
message: () => string;
|
|
77
|
+
}>;
|
|
36
78
|
/** The thread (or DM) has at least one reply from this author. */
|
|
37
79
|
toHaveReplyFrom(state: MatcherState, subject: unknown, author: AuthorRef, options?: Timing & {
|
|
38
80
|
text?: string | RegExp;
|
|
@@ -133,6 +175,43 @@ export declare const matchers: {
|
|
|
133
175
|
times?: number;
|
|
134
176
|
error?: string;
|
|
135
177
|
}): Promise<MatcherResult>;
|
|
178
|
+
/**
|
|
179
|
+
* What the agent sent the model: text, a pattern, a message's text, or several messages in order
|
|
180
|
+
* (thread history). The subject is the `openai` fixture (any of the session's calls), a script
|
|
181
|
+
* (the calls it answered), or one call.
|
|
182
|
+
*/
|
|
183
|
+
toHaveSent(state: MatcherState, subject: unknown, expected: string | RegExp | Texted | readonly (string | Texted)[], options?: Timing & {
|
|
184
|
+
ordered?: boolean;
|
|
185
|
+
}): Promise<MatcherResult>;
|
|
186
|
+
/**
|
|
187
|
+
* The agent sent the model this image, file or audio, compared by its SHA-256: a fixture file's
|
|
188
|
+
* path (read as a `MediaSource` is, from the files root) or its bytes. The subject is the
|
|
189
|
+
* `openai` fixture, a script or one call, as for `toHaveSent`.
|
|
190
|
+
*/
|
|
191
|
+
toHaveSentFile(state: MatcherState, subject: unknown, file: string | Uint8Array, options?: Timing): Promise<MatcherResult>;
|
|
192
|
+
/** A secret channelstack knows (a token, a signing secret, a key) was sent to the model. Use it as `not.`. */
|
|
193
|
+
toHaveSentSecrets(state: MatcherState, subject: unknown, options?: Timing): Promise<MatcherResult>;
|
|
194
|
+
/** The call offered the model this tool (with this JSON Schema). */
|
|
195
|
+
toHaveOfferedTool(state: MatcherState, subject: unknown, name: string, options?: Timing & {
|
|
196
|
+
schema?: unknown;
|
|
197
|
+
}): Promise<MatcherResult>;
|
|
198
|
+
/** The agent ran the model's call to this tool and sent its result back (with this text). */
|
|
199
|
+
toHaveSentToolResult(state: MatcherState, subject: unknown, name: string, options?: Timing & {
|
|
200
|
+
text?: string | RegExp;
|
|
201
|
+
}): Promise<MatcherResult>;
|
|
202
|
+
/** The agent hung up before the model's answer was complete: it cancelled the request (Stop), or timed out. */
|
|
203
|
+
toBeAborted(state: MatcherState, subject: unknown, options?: Timing): Promise<MatcherResult>;
|
|
204
|
+
/**
|
|
205
|
+
* The script answered calls (exactly `times` of them, once the agent is quiet): a call counts once
|
|
206
|
+
* the script's turn reached the agent, not one it was given and the fake refused.
|
|
207
|
+
*/
|
|
208
|
+
toHaveAnswered(state: MatcherState, subject: unknown, options?: Timing & {
|
|
209
|
+
times?: number;
|
|
210
|
+
}): Promise<MatcherResult>;
|
|
136
211
|
};
|
|
212
|
+
/** Something with text: a channel's message, comment or email. */
|
|
213
|
+
interface Texted {
|
|
214
|
+
readonly text: string;
|
|
215
|
+
}
|
|
137
216
|
export type MatcherName = keyof typeof matchers;
|
|
138
217
|
export {};
|
|
@@ -6,7 +6,11 @@
|
|
|
6
6
|
* - A positive matcher polls until its condition holds, or fails after the timeout.
|
|
7
7
|
* - A negated matcher, and one with an exact count, waits until the agent is quiet and checks once.
|
|
8
8
|
*/
|
|
9
|
-
import {
|
|
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";
|
|
10
14
|
const nameOf = (author) => (typeof author === "string" ? author : author.name);
|
|
11
15
|
const show = (expected) => typeof expected === "string" ? JSON.stringify(expected) : String(expected);
|
|
12
16
|
const listing = (lines) => lines.length === 0 ? " (nothing)" : lines.map((line) => ` ${line}`).join("\n");
|
|
@@ -40,32 +44,135 @@ async function settle(subject, state, timing, options) {
|
|
|
40
44
|
if (typeof handle[QUIET] !== "function")
|
|
41
45
|
throw new TypeError("This matcher needs a channelstack handle");
|
|
42
46
|
// The check watches for the whole quiet window: what arrives while it looks counts.
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
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
|
+
}
|
|
48
59
|
value = await options.read();
|
|
49
60
|
}
|
|
50
61
|
else {
|
|
51
62
|
let last;
|
|
63
|
+
let polls = 0;
|
|
52
64
|
try {
|
|
53
65
|
value = await waitFor("the condition", async () => {
|
|
54
66
|
last = await options.read();
|
|
55
|
-
|
|
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;
|
|
56
74
|
}, { timeout });
|
|
57
75
|
}
|
|
58
76
|
catch (error) {
|
|
77
|
+
if (error instanceof ModelProblemError)
|
|
78
|
+
return failing(subject, state, error.message);
|
|
59
79
|
if (!(error instanceof WaitTimeoutError))
|
|
60
80
|
throw error;
|
|
61
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
|
+
}
|
|
62
91
|
}
|
|
63
92
|
}
|
|
64
93
|
const pass = options.holds(value);
|
|
94
|
+
if (pass !== state.isNot)
|
|
95
|
+
return { pass, message: () => options.describe(value) };
|
|
65
96
|
// A failed check also says what the agent left open (a stream it never stopped): often that is the bug.
|
|
66
|
-
const open =
|
|
67
|
-
const
|
|
68
|
-
|
|
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);
|
|
69
176
|
}
|
|
70
177
|
/**
|
|
71
178
|
* What the agent has left open in the subject's session, in words. Nothing for a subject outside a
|
|
@@ -85,6 +192,20 @@ async function stillOpen(subject) {
|
|
|
85
192
|
throw error;
|
|
86
193
|
}
|
|
87
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
|
+
}
|
|
88
209
|
const from = (author, text) => (message) => fromMatches(message.author, author) && textMatches(message.text, text);
|
|
89
210
|
/** A Linear agent session, or the latest one of an issue (the subject a session matcher was given). */
|
|
90
211
|
async function sessionOf(subject) {
|
|
@@ -117,7 +238,62 @@ const commentsOf = (subject, matcher) => {
|
|
|
117
238
|
};
|
|
118
239
|
const commentFrom = (author, text) => (comment) => fromMatches(comment.author, author) && textMatches(commentText(comment), text);
|
|
119
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
|
+
}
|
|
120
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
|
+
},
|
|
121
297
|
/** The thread (or DM) has at least one reply from this author. */
|
|
122
298
|
toHaveReplyFrom(state, subject, author, options) {
|
|
123
299
|
const wanted = `a reply from ${nameOf(author)}${options?.text === undefined ? "" : ` matching ${show(options.text)}`}`;
|
|
@@ -195,13 +371,15 @@ export const matchers = {
|
|
|
195
371
|
return settle(subject, state, options, {
|
|
196
372
|
onceQuiet: false,
|
|
197
373
|
read: async () => {
|
|
198
|
-
// A message (it has a thread) is one entry of its thread's transcript.
|
|
199
|
-
if (handle.thread) {
|
|
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) {
|
|
200
376
|
const { entries } = await handle.thread.transcript();
|
|
201
377
|
return entries.filter((entry) => entry.id === handle.ts).flatMap((entry) => entry.controls);
|
|
202
378
|
}
|
|
379
|
+
// A message whose own transcript starts with it (Discord's), or the app's latest message in a thread or channel.
|
|
203
380
|
const { entries } = await handle.transcript();
|
|
204
|
-
|
|
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 ?? [];
|
|
205
383
|
},
|
|
206
384
|
holds: (controls) => controls.some((control) => textMatches(control, label)),
|
|
207
385
|
describe: (controls) => `Expected ${state.isNot ? "no" : "a"} button matching ${show(label)}. Buttons there: ${controls.length === 0 ? "none" : controls.join(", ")}`,
|
|
@@ -441,18 +619,181 @@ export const matchers = {
|
|
|
441
619
|
},
|
|
442
620
|
/** The agent made this API call. */
|
|
443
621
|
toHaveReceivedCall(state, subject, operation, options) {
|
|
622
|
+
// A channel's calls have an operation; a model call has its endpoint (`chat.completions`).
|
|
444
623
|
const fixture = subject;
|
|
624
|
+
const named = (call) => call.operation ?? call.endpoint ?? "";
|
|
445
625
|
return settle(subject, state, options, {
|
|
446
626
|
onceQuiet: options?.times !== undefined,
|
|
447
627
|
read: async () => {
|
|
448
628
|
const calls = await fixture.calls(options?.error === undefined ? {} : { error: options.error });
|
|
449
629
|
return {
|
|
450
630
|
calls,
|
|
451
|
-
matching: calls.filter((call) => typeof operation === "string" ? call
|
|
631
|
+
matching: calls.filter((call) => typeof operation === "string" ? named(call) === operation : textMatches(named(call), operation)),
|
|
452
632
|
};
|
|
453
633
|
},
|
|
454
634
|
holds: ({ matching }) => (options?.times === undefined ? matching.length > 0 : matching.length === options.times),
|
|
455
|
-
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) => `${call
|
|
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)] : [])))}` : ""}`,
|
|
456
709
|
});
|
|
457
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;
|
|
458
799
|
};
|