@senselab-ai/sensei 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/dist/run.d.ts ADDED
@@ -0,0 +1,138 @@
1
+ /**
2
+ * The short way to run something from code:
3
+ *
4
+ * import { Sensei } from "@senselab-ai/sensei";
5
+ *
6
+ * const sensei = new Sensei(); // SENSEI_API_KEY
7
+ * let r = await sensei.run("refund-requests", { input: { ticket: 48213 } }); // a saved agent, by name
8
+ * r = await sensei.run("agents/refunds.yaml", { input: { ticket: 48213 } }); // a definition file
9
+ * r = await sensei.run("List the three largest tables and say why they are large.");
10
+ *
11
+ * r.status // done | verified | waiting | failed | ...
12
+ * r.output // in the shape the definition names
13
+ * r.evidence // what Sensei checked
14
+ * r.notSure // what it could not confirm
15
+ * r.startedWith // { learnings: 4, corrections: ["Store credit for gift cards"] }
16
+ *
17
+ * if (r.waiting) { // an action the team marked ask_first
18
+ * console.log(r.ask); // { tool: "stripe", action: "refund", arguments: {...}, why: "..." }
19
+ * await r.answer("correct", "Store credit when they paid with a gift card");
20
+ * }
21
+ *
22
+ * await r.outcome("wrong", { note: "The ticket was reopened" }); // later, when you know
23
+ *
24
+ * Many at once: `sensei.map("translate-screen", [{ screen: "home" }, { screen: "cart" }])`.
25
+ *
26
+ * Many changes to one repository, tested together before any pull request:
27
+ *
28
+ * const b = await sensei.batch({ repo: "acme/api", tasks: ["Add retries to the payments client", "Remove the v1 export"], total: { usd: 24 } });
29
+ * await b.wait();
30
+ * for (const t of b.tasks) console.log(t.index, t.status, t.together, t.pr_url);
31
+ * await b.checkAgain(); // after merging some: the rest, together, on the branch as it is now
32
+ */
33
+ import { Client, type Agents, type ClientOptions, type Model, type Runs, type Schedules, type Settings, type Tools } from "./client.js";
34
+ import type { Evals } from "./evals.js";
35
+ import type { Ask, BatchData, BatchParams, BatchTask, Decision, Definition, Outcome, OutcomeOptions, Run, RunCreateParams, StepSummary, WaitOptions } from "./types.js";
36
+ /** A run, read the way a person asks about it. */
37
+ export declare class RunResult {
38
+ #private;
39
+ /** The run as the API last returned it. */
40
+ run: Run;
41
+ constructor(client: Client, run: Run);
42
+ get id(): string;
43
+ get status(): Run["status"];
44
+ get url(): string | null;
45
+ get ok(): boolean;
46
+ get waiting(): boolean;
47
+ get settled(): boolean;
48
+ get output(): unknown;
49
+ get summary(): string;
50
+ get evidence(): string[];
51
+ get notSure(): string[];
52
+ get startedWith(): {
53
+ learnings: number | null;
54
+ corrections: string[];
55
+ };
56
+ /** What a waiting run is asking: the action, its arguments, and why. */
57
+ get ask(): Ask | null;
58
+ /** On a run with steps: each step and how it went. */
59
+ get steps(): StepSummary[];
60
+ /** On a batch: its tasks, counts and what testing them together found. */
61
+ get batch(): BatchData | null;
62
+ /** On a batch: each task, how it did alone (`status`) and with the others (`together`). */
63
+ get tasks(): BatchTask[];
64
+ /** On a batch: the pull requests it opened. */
65
+ get pullRequests(): string[];
66
+ /** What it cost, in US dollars. */
67
+ get cost(): number | null;
68
+ get error(): string | null;
69
+ wait(options?: WaitOptions): Promise<this>;
70
+ refresh(): Promise<this>;
71
+ /** `approve`, `correct` (with what to do instead) or `reject`. */
72
+ answer(decision: Decision, text?: string, options?: {
73
+ wait?: boolean;
74
+ timeoutMs?: number;
75
+ }): Promise<this>;
76
+ /** How it turned out, said later: `right` or `wrong`. */
77
+ outcome(outcome: Outcome, options?: OutcomeOptions): Promise<this>;
78
+ /**
79
+ * On a finished batch: test its changes together once more, against the
80
+ * branch as it is now, and wait for it unless `wait` is false.
81
+ */
82
+ checkAgain(options?: {
83
+ wait?: boolean;
84
+ timeoutMs?: number;
85
+ }): Promise<this>;
86
+ cancel(): Promise<this>;
87
+ toString(): string;
88
+ }
89
+ /** What a run is started with, besides the thing to run. */
90
+ export type StartOptions = Omit<RunCreateParams, "agent" | "definition">;
91
+ export interface RunOptions extends StartOptions {
92
+ /** Return the run as it is when this much time is up. */
93
+ timeoutMs?: number;
94
+ }
95
+ export interface MapOptions extends Omit<StartOptions, "input"> {
96
+ /** How many run at a time. Default: 4. */
97
+ parallel?: number;
98
+ /** Return what there is when this much time is up. */
99
+ timeoutMs?: number;
100
+ }
101
+ export interface SenseiOptions extends ClientOptions {
102
+ /** A client to use as it is. The other options are then not read. */
103
+ client?: Client;
104
+ }
105
+ export declare class Sensei {
106
+ readonly client: Client;
107
+ readonly runs: Runs;
108
+ readonly agents: Agents;
109
+ readonly tools: Tools;
110
+ /** What the project's runs are given by name: plain settings, and secrets for setup. */
111
+ readonly settings: Settings;
112
+ readonly schedules: Schedules;
113
+ /** The project's own trained model: where it is, its versions, the decisions. */
114
+ readonly model: Model;
115
+ /** The end-to-end check: saved tasks rerun on two versions of the model. */
116
+ readonly evals: Evals;
117
+ constructor(options?: SenseiOptions);
118
+ /**
119
+ * Start a run and return at once. `what` is a definition, a definition
120
+ * file, a saved agent's name, or a task in words. A single word is taken
121
+ * as an agent's name: pass `task` to say a one-word task.
122
+ */
123
+ start(what?: string | Definition | null, options?: StartOptions): Promise<RunResult>;
124
+ /** Start a run and wait until it has finished or has a question. */
125
+ run(what?: string | Definition | null, options?: RunOptions): Promise<RunResult>;
126
+ /**
127
+ * Many changes to one repository: one task for each change, each a run of
128
+ * its own, the verified ones tested together, then pull requests. It
129
+ * returns at once: `wait()` follows it, and `tasks` says how each did.
130
+ */
131
+ batch(params: BatchParams): Promise<RunResult>;
132
+ /**
133
+ * One run per input, at most `parallel` at a time, in the order given. A
134
+ * run that asks a person comes back `waiting`; the others are not held up
135
+ * by it.
136
+ */
137
+ map(what: string | Definition, inputs: Array<Record<string, unknown>>, options?: MapOptions): Promise<RunResult[]>;
138
+ }
package/dist/run.js ADDED
@@ -0,0 +1,272 @@
1
+ /**
2
+ * The short way to run something from code:
3
+ *
4
+ * import { Sensei } from "@senselab-ai/sensei";
5
+ *
6
+ * const sensei = new Sensei(); // SENSEI_API_KEY
7
+ * let r = await sensei.run("refund-requests", { input: { ticket: 48213 } }); // a saved agent, by name
8
+ * r = await sensei.run("agents/refunds.yaml", { input: { ticket: 48213 } }); // a definition file
9
+ * r = await sensei.run("List the three largest tables and say why they are large.");
10
+ *
11
+ * r.status // done | verified | waiting | failed | ...
12
+ * r.output // in the shape the definition names
13
+ * r.evidence // what Sensei checked
14
+ * r.notSure // what it could not confirm
15
+ * r.startedWith // { learnings: 4, corrections: ["Store credit for gift cards"] }
16
+ *
17
+ * if (r.waiting) { // an action the team marked ask_first
18
+ * console.log(r.ask); // { tool: "stripe", action: "refund", arguments: {...}, why: "..." }
19
+ * await r.answer("correct", "Store credit when they paid with a gift card");
20
+ * }
21
+ *
22
+ * await r.outcome("wrong", { note: "The ticket was reopened" }); // later, when you know
23
+ *
24
+ * Many at once: `sensei.map("translate-screen", [{ screen: "home" }, { screen: "cart" }])`.
25
+ *
26
+ * Many changes to one repository, tested together before any pull request:
27
+ *
28
+ * const b = await sensei.batch({ repo: "acme/api", tasks: ["Add retries to the payments client", "Remove the v1 export"], total: { usd: 24 } });
29
+ * await b.wait();
30
+ * for (const t of b.tasks) console.log(t.index, t.status, t.together, t.pr_url);
31
+ * await b.checkAgain(); // after merging some: the rest, together, on the branch as it is now
32
+ */
33
+ import { Client, SETTLED, SenseiError } from "./client.js";
34
+ import { load, looksLikeFile } from "./files.js";
35
+ const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
36
+ /** A run, read the way a person asks about it. */
37
+ export class RunResult {
38
+ /** The run as the API last returned it. */
39
+ run;
40
+ #c;
41
+ constructor(client, run) {
42
+ this.#c = client;
43
+ this.run = run;
44
+ }
45
+ // -- what it is ------------------------------------------------------
46
+ get id() {
47
+ return this.run.id;
48
+ }
49
+ get status() {
50
+ return this.run.status;
51
+ }
52
+ get url() {
53
+ return this.run.url ?? null;
54
+ }
55
+ get ok() {
56
+ return this.status === "done" || this.status === "verified";
57
+ }
58
+ get waiting() {
59
+ return this.status === "waiting";
60
+ }
61
+ get settled() {
62
+ return SETTLED.includes(this.status);
63
+ }
64
+ get #result() {
65
+ return this.run.result ?? {};
66
+ }
67
+ // -- what it found -----------------------------------------------------
68
+ get output() {
69
+ return this.#result.output ?? null;
70
+ }
71
+ get summary() {
72
+ return this.#result.summary || "";
73
+ }
74
+ get evidence() {
75
+ return [...(this.#result.evidence ?? [])];
76
+ }
77
+ get notSure() {
78
+ return [...(this.#result.not_sure ?? [])];
79
+ }
80
+ get startedWith() {
81
+ const s = this.#result.started_with ?? {};
82
+ const corrections = (s.kept ?? []).map((note) => note.text).filter((text) => typeof text === "string");
83
+ return { learnings: s.learnings ?? null, corrections };
84
+ }
85
+ /** What a waiting run is asking: the action, its arguments, and why. */
86
+ get ask() {
87
+ if (!this.waiting)
88
+ return null;
89
+ const own = this.#result.ask;
90
+ if (own && Object.keys(own).length > 0)
91
+ return own;
92
+ for (const step of this.run.steps ?? []) {
93
+ const asked = step.result?.ask;
94
+ if (step.status === "waiting" && asked && Object.keys(asked).length > 0) {
95
+ return { ...asked, step: step.step ?? null };
96
+ }
97
+ }
98
+ if (this.run.waiting_for === "approval") {
99
+ return { action: "push the change", why: this.summary, diff_stat: this.#result.diff_stat ?? null };
100
+ }
101
+ return null;
102
+ }
103
+ /** On a run with steps: each step and how it went. */
104
+ get steps() {
105
+ const steps = this.#result.steps;
106
+ return this.#result.kind === "steps" && Array.isArray(steps) ? [...steps] : [];
107
+ }
108
+ /** On a batch: its tasks, counts and what testing them together found. */
109
+ get batch() {
110
+ return this.#result.kind === "batch" ? (this.#result.batch ?? null) : null;
111
+ }
112
+ /** On a batch: each task, how it did alone (`status`) and with the others (`together`). */
113
+ get tasks() {
114
+ return [...(this.batch?.tasks ?? [])];
115
+ }
116
+ /** On a batch: the pull requests it opened. */
117
+ get pullRequests() {
118
+ const one = this.batch?.pr_url;
119
+ if (one)
120
+ return [one];
121
+ return this.tasks.map((t) => t.pr_url).filter((url) => typeof url === "string" && url !== "");
122
+ }
123
+ /** What it cost, in US dollars. */
124
+ get cost() {
125
+ return this.run.usage?.usd ?? null;
126
+ }
127
+ get error() {
128
+ return this.run.error ?? null;
129
+ }
130
+ // -- what you do with it -------------------------------------------------
131
+ async wait(options = {}) {
132
+ this.run = await this.#c.runs.wait(this.id, options);
133
+ return this;
134
+ }
135
+ async refresh() {
136
+ this.run = await this.#c.runs.get(this.id);
137
+ return this;
138
+ }
139
+ /** `approve`, `correct` (with what to do instead) or `reject`. */
140
+ async answer(decision, text, options = {}) {
141
+ const { wait = true, timeoutMs } = options;
142
+ await this.#c.runs.answer(this.id, decision, text);
143
+ if (wait) {
144
+ // The step that was waiting goes back to work a moment later.
145
+ await sleep(200);
146
+ return this.wait({ timeoutMs });
147
+ }
148
+ return this.refresh();
149
+ }
150
+ /** How it turned out, said later: `right` or `wrong`. */
151
+ async outcome(outcome, options = {}) {
152
+ this.run = { ...this.run, ...(await this.#c.runs.outcome(this.id, outcome, options)) };
153
+ return this;
154
+ }
155
+ /**
156
+ * On a finished batch: test its changes together once more, against the
157
+ * branch as it is now, and wait for it unless `wait` is false.
158
+ */
159
+ async checkAgain(options = {}) {
160
+ const { wait = true, timeoutMs } = options;
161
+ this.run = await this.#c.runs.checkAgain(this.id);
162
+ return wait ? this.wait({ timeoutMs, pollMs: 3000 }) : this;
163
+ }
164
+ async cancel() {
165
+ this.run = await this.#c.runs.cancel(this.id);
166
+ return this;
167
+ }
168
+ toString() {
169
+ return `<RunResult ${this.id.slice(0, 8)} ${this.status}>`;
170
+ }
171
+ }
172
+ export class Sensei {
173
+ client;
174
+ runs;
175
+ agents;
176
+ tools;
177
+ /** What the project's runs are given by name: plain settings, and secrets for setup. */
178
+ settings;
179
+ schedules;
180
+ /** The project's own trained model: where it is, its versions, the decisions. */
181
+ model;
182
+ /** The end-to-end check: saved tasks rerun on two versions of the model. */
183
+ evals;
184
+ constructor(options = {}) {
185
+ const { client, ...rest } = options;
186
+ this.client = client ?? new Client(rest);
187
+ this.runs = this.client.runs;
188
+ this.agents = this.client.agents;
189
+ this.tools = this.client.tools;
190
+ this.settings = this.client.settings;
191
+ this.schedules = this.client.schedules;
192
+ this.model = this.client.model;
193
+ this.evals = this.client.evals;
194
+ }
195
+ /**
196
+ * Start a run and return at once. `what` is a definition, a definition
197
+ * file, a saved agent's name, or a task in words. A single word is taken
198
+ * as an agent's name: pass `task` to say a one-word task.
199
+ */
200
+ async start(what, options = {}) {
201
+ const { task, ...rest } = options;
202
+ let run;
203
+ if (typeof what === "object" && what !== null) {
204
+ run = await this.runs.create({ ...rest, definition: what });
205
+ }
206
+ else if (typeof what === "string" && looksLikeFile(what)) {
207
+ run = await this.runs.create({ ...rest, definition: load(what) });
208
+ }
209
+ else if (typeof what === "string" && task == null && !what.trim().includes(" ")) {
210
+ run = await this.runs.create({ ...rest, agent: what });
211
+ }
212
+ else {
213
+ run = await this.runs.create({ ...rest, task: task || what || undefined });
214
+ }
215
+ return new RunResult(this.client, run);
216
+ }
217
+ /** Start a run and wait until it has finished or has a question. */
218
+ async run(what, options = {}) {
219
+ const { timeoutMs, ...rest } = options;
220
+ return (await this.start(what, rest)).wait({ timeoutMs });
221
+ }
222
+ /**
223
+ * Many changes to one repository: one task for each change, each a run of
224
+ * its own, the verified ones tested together, then pull requests. It
225
+ * returns at once: `wait()` follows it, and `tasks` says how each did.
226
+ */
227
+ async batch(params) {
228
+ return new RunResult(this.client, await this.runs.batch(params));
229
+ }
230
+ /**
231
+ * One run per input, at most `parallel` at a time, in the order given. A
232
+ * run that asks a person comes back `waiting`; the others are not held up
233
+ * by it.
234
+ */
235
+ async map(what, inputs, options = {}) {
236
+ const { parallel = 4, timeoutMs, ...rest } = options;
237
+ const definition = typeof what === "string" && looksLikeFile(what) ? load(what) : what;
238
+ const results = new Array(inputs.length).fill(undefined);
239
+ const todo = inputs.map((item, i) => ({ i, item }));
240
+ const live = new Map();
241
+ const deadline = timeoutMs != null ? performance.now() + timeoutMs : null;
242
+ while (todo.length > 0 || live.size > 0) {
243
+ while (todo.length > 0 && live.size < Math.max(1, parallel)) {
244
+ const next = todo[0];
245
+ try {
246
+ live.set(next.i, await this.start(definition, { ...rest, input: next.item }));
247
+ }
248
+ catch (e) {
249
+ // The account's ceiling: wait for one to finish.
250
+ if (e instanceof SenseiError && e.code === "too_many_runs" && live.size > 0)
251
+ break;
252
+ throw e;
253
+ }
254
+ todo.shift();
255
+ }
256
+ for (const [i, r] of [...live]) {
257
+ if ((await r.refresh()).settled) {
258
+ results[i] = r;
259
+ live.delete(i);
260
+ }
261
+ }
262
+ if (deadline !== null && performance.now() >= deadline) {
263
+ for (const [i, r] of live)
264
+ results[i] = r;
265
+ break;
266
+ }
267
+ if (live.size > 0)
268
+ await sleep(1500);
269
+ }
270
+ return results.filter((r) => r !== undefined);
271
+ }
272
+ }