> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sense-lab.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# JavaScript SDK

> Start runs, answer them and record outcomes from JavaScript and TypeScript.

The JavaScript SDK is the package `@senselab-ai/sensei`. It comes with its TypeScript types.

```bash theme={null}
npm install @senselab-ai/sensei
```

It needs Node 18 or later. The key comes from `SENSEI_API_KEY`, or from the config file `sensei login` writes.

To update, run `npm install @senselab-ai/sensei@latest`. `VERSION` says which version is installed. `say` needs 0.3.0 or later.

```ts theme={null}
import { VERSION } from "@senselab-ai/sensei";
```

## Run something

```ts theme={null}
import { Sensei } from "@senselab-ai/sensei";

const sensei = new Sensei();

let r = await sensei.run("refund-requests", { input: { ticket: 48213 } });      // a saved agent, by name
r = await sensei.run("agents/refunds.yaml", { input: { ticket: 48213 } });      // a definition file
r = await sensei.run("List the three largest tables and say why they are large.");

console.log(r.status, r.output, r.evidence, r.notSure);
```

`run` waits until the run has finished or has a question for a person. `start` takes the same arguments and returns at once.

## Sensei

```ts theme={null}
new Sensei({ apiKey, baseUrl, fetch })
```

Every option can be left out.

| Method | Returns | Description |
| - | - | - |
| `run(what, options)` | `RunResult` | Starts a run and waits for it to settle. With `timeoutMs` it returns the run as it is when the time is up. |
| `start(what, options)` | `RunResult` | Starts a run and returns |
| `map(what, inputs, options)` | `RunResult[]` | One run for each input, in the order given. `parallel` is 4 unless you say. |
| `batch(params)` | `RunResult` | Several changes to one repository |

`what` is read like this.

| What you pass | What it is |
| - | - |
| An object | A definition |
| A string that ends in `.yaml`, `.yml` or `.json`, or that is a file on disk | A definition file |
| Any other string with no space in it | A saved agent's name |
| Anything else | A task in words |

For a task of one word, pass `task`: `sensei.run(null, { task: "Summarise" })`.

`input` is the agent's input. The rest are options of the run.

| Option | Meaning |
| - | - |
| `budget` | `{ usd: 1, minutes: 10, steps: 40 }` |
| `repo`, `baseRef` | The repository and where to start |
| `attempts` | 1 to 5 |
| `tools`, `askFirst`, `computer`, `output`, `check`, `image` | For a task in words, the same keys a definition has |
| `save` | `false` runs a definition without saving it |
| `openPr`, `approveBeforePush`, `dryRun`, `branch`, `pr`, `testCommand` | Delivery of a repository change |
| `callbackUrl` | An https address to post to when the run waits or finishes |

`sensei.runs`, `sensei.agents`, `sensei.tools`, `sensei.settings` and `sensei.schedules` are the lower-level groups described under [Client](#client).

## RunResult

| Property | Type | Description |
| - | - | - |
| `id` | `string` | The run's id |
| `status` | `string` | `queued`, `running`, `waiting`, `done`, `verified`, `unverified`, `failed` or `cancelled` |
| `ok` | `boolean` | True when the status is `done` or `verified` |
| `waiting` | `boolean` | True when the run has a question for a person |
| `settled` | `boolean` | True when the run has stopped moving: finished or waiting |
| `output` | any | The output, in the shape the definition names |
| `summary` | `string` | What it did, in a sentence |
| `evidence` | `string[]` | What Sensei checked |
| `notSure` | `string[]` | What it could not confirm |
| `startedWith` | object | `{ learnings: 4, corrections: ["Store credit for gift cards"] }` |
| `ask` | object or `null` | On a waiting run: `tool`, `action`, `arguments`, `why` |
| `steps` | array | The steps of a run with steps |
| `cost` | `number` or `null` | In US dollars |
| `error` | `string` or `null` | Why it failed |
| `url` | `string` or `null` | The run's page |
| `run` | object | The run as the API returned it |

| Method | Description |
| - | - |
| `wait({ timeoutMs })` | Waits for the run to settle |
| `refresh()` | Reads the run again |
| `answer(decision, text, { wait, timeoutMs })` | Answers a waiting run with `"approve"`, `"correct"` or `"reject"` |
| `say(text)` | Tells a working run something. It reads it between two steps and goes on. From version 0.3.0. |
| `outcome(outcome, { note, step })` | Records `"right"` or `"wrong"` |
| `cancel()` | Stops the run |

## Answer a waiting run

```ts theme={null}
let r = await sensei.run("refund-requests", { input: { ticket: 48213 } });
if (r.waiting) {
  console.log(r.ask);
  // { tool: "stripe", action: "refund", arguments: {...}, why: "..." }
  r = await r.answer("correct", "Store credit when they paid with a gift card");
}
```

`correct` takes what to do instead, and the text is kept for the agent's later runs. `answer` waits for what comes next unless you pass `{ wait: false }`.

## Record an outcome

```ts theme={null}
await r.outcome("wrong", { note: "The ticket was reopened" });
```

On a run with steps, `{ step: "refund" }` names the step that was wrong.

## Many at once

```ts theme={null}
const results = await sensei.map("translate-screen", [{ screen: "home" }, { screen: "cart" }], { parallel: 4 });
for (const r of results) console.log(r.status, r.output);
```

A run that asks a person comes back `waiting`, and the others are not held up by it.

## Several changes to one repository

```ts theme={null}
const b = await sensei.batch({
  repo: "acme/api",
  tasks: ["Move billing to the new logger", "Move checkout to the new logger"],
  total: { usd: 24 },
});
await b.wait();
for (const t of b.tasks) console.log(t.index, t.status, t.together, t.pr_url);
console.log(b.pullRequests);
await b.checkAgain();   // after merging some
```

Its other options are `ref`, `instructions`, `parallel`, `together`, `deliver`, `limit`, `check` and `secrets`. See [Several changes at once](https://docs.sense-lab.ai/sensei/runs/batches.md).

## Settings and secrets

```ts theme={null}
await sensei.settings.set("REPORTS_BUCKET", "reports-test");
await sensei.settings.set("NPM_TOKEN", token, { secret: true });
await sensei.settings.list();
await sensei.settings.remove("REPORTS_BUCKET");
```

See [Services, settings and secrets](https://docs.sense-lab.ai/sensei/runs/services-and-settings.md).

## Client

`Client` is the HTTP API with nothing added. Every method returns the API's JSON.

```ts theme={null}
import { Client } from "@senselab-ai/sensei";

const client = new Client();
const run = await client.runs.create({ agent: "refund-requests", input: { ticket: 48213 } });
for await (const event of client.runs.events(run.id)) console.log(event.kind, event.data);
const settled = await client.runs.wait(run.id, { timeoutMs: 60_000 });
```

| Group | Methods |
| - | - |
| `client.runs` | `create`, `batch`, `checkAgain`, `get`, `list`, `wait`, `events`, `answer`, `outcome`, `approve`, `resume`, `cancel` |
| `client.agents` | `list`, `get`, `save`, `check`, `remove`, `forget` |
| `client.tools` | `list`, `connect`, `disconnect` |
| `client.repos` | `list`, `connect`, `disconnect` |
| `client.settings` | `list`, `set`, `remove` |
| `client.schedules` | `list`, `create`, `update`, `remove` |

`events` ends when the run is done or waiting. If the connection closes before that, it connects again from the last event it saw.

## Errors

A response that is not a success throws `SenseiError`, with the `status`, `code` and `message` the service sent.

```ts theme={null}
import { SenseiError } from "@senselab-ai/sensei";

try {
  await sensei.run("refund-requests", { input: { ticket: 48213 } });
} catch (e) {
  if (e instanceof SenseiError && e.code === "too_many_runs") console.log("Try again in a moment.");
  else throw e;
}
```

A definition file that cannot be read throws `FileError`, which says what is wrong with the file.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.