Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
name: CI

on:
push:
branches: [main]
pull_request:
branches: [main]

jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [20, 22]
steps:
- uses: actions/checkout@v4

- name: Set up Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: npm

- name: Install dependencies
run: npm ci

- name: Lint
run: npm run lint

- name: Check formatting
run: npm run format:check

- name: Type-check
run: npm run typecheck

- name: Build
run: npm run build

- name: Test
run: npm test
45 changes: 45 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
name: Publish

on:
push:
tags:
- "v*.*.*"

jobs:
publish:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write # required for npm provenance
steps:
- uses: actions/checkout@v4

- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
registry-url: "https://registry.npmjs.org"

- name: Install dependencies
run: npm ci

- name: Verify tag matches package version
run: |
TAG="${GITHUB_REF_NAME#v}"
PKG="$(node -p "require('./package.json').version")"
if [ "$TAG" != "$PKG" ]; then
echo "Tag $TAG does not match package.json version $PKG" >&2
exit 1
fi

- name: Build
run: npm run build

- name: Test
run: npm test

- name: Publish to npm
run: npm publish --access public --provenance
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
10 changes: 10 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
node_modules/
dist/
coverage/
*.log
.DS_Store
.env
.env.local
*.tsbuildinfo
.idea/
.vscode/
4 changes: 4 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
dist/
node_modules/
coverage/
CHANGELOG.md
6 changes: 6 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"semi": true,
"trailingComma": "all",
"singleQuote": false,
"printWidth": 100
}
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added

- Initial release of the Gradient Labs Node.js / TypeScript client.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 Gradient Labs

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
170 changes: 170 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
# Gradient Labs Node.js / TypeScript client

Official client for the [Gradient Labs API](https://api.gradient-labs.ai). Written
in TypeScript, ships full type declarations and both ESM and CommonJS builds, and
has **zero runtime dependencies** (it uses Node's built-in `fetch` and `crypto`).

Requires **Node.js 20** or newer.

## Installation

```bash
npm install @gradientlabs/client
```

## Quick start

```ts
import { GradientLabs } from "@gradientlabs/client";

const client = new GradientLabs({ apiKey: process.env.GRADIENT_LABS_API_KEY! });

const conversation = await client.conversations.start({
id: "ticket-12345",
customer_id: "customer-678",
channel: "web",
assignee_type: "AI Agent",
});

console.log(conversation.status);
```

The client is organised into resource namespaces, e.g. `client.conversations`,
`client.tools`, `client.procedures`. There are two API key roles:

- **Integration** — conversation runtime endpoints (`conversations`,
`outboundConversations`, `backOfficeTasks`, `voice`).
- **Management** — configuration endpoints (`tools`, `articles`, `topics`,
`procedures`, `handOffTargets`, `resourceSources`, `resourceTypes`, `secrets`,
`notes`, `terminologySubstitutions`, `trafficGroups`, `ipAddresses`).

## Configuration

```ts
const client = new GradientLabs({
apiKey: "sk_live_...", // required
baseUrl: "https://api.gradient-labs.ai", // optional (this is the default)
webhookSigningKey: "whsec_...", // optional, required to verify webhooks
webhookLeewayMs: 5 * 60 * 1000, // optional, default 5 minutes
timeoutMs: 30_000, // optional per-request timeout
fetch: myFetch, // optional, inject a custom fetch (tests, proxies, instrumentation)
});
```

Every method accepts an optional final argument carrying an `AbortSignal` for
cancellation:

```ts
const controller = new AbortController();
const tools = await client.tools.list({ signal: controller.signal });
```

## Error handling

Non-2xx responses throw an `ApiError`; client misconfiguration throws a
`ConfigurationError`. Both extend `GradientLabsError`.

```ts
import { ApiError, ErrorCode } from "@gradientlabs/client";

try {
await client.conversations.get("missing");
} catch (err) {
if (err instanceof ApiError) {
console.error(err.statusCode, err.code, err.message);
if (err.code === ErrorCode.NotFound) {
// handle 404
}
console.error("trace id:", err.traceId); // give this to support
}
}
```

The client never retries failed requests — retry policy is left to you.

## Pagination

List endpoints that paginate return a `Page<T>` with opaque `next`/`prev`
cursors. Use `listAll()` to iterate every page automatically:

```ts
for await (const procedure of client.procedures.listAll()) {
console.log(procedure.name);
}

// or page manually:
const page = await client.procedures.list();
const next = await client.procedures.list({ cursor: page.pageInfo.next });
```

## Webhook verification

Construct the client with your `webhookSigningKey`, then verify and parse
incoming requests. Pass the **raw** request body — the signature is computed over
the exact bytes received.

```ts
import { GradientLabs, InvalidWebhookSignatureError } from "@gradientlabs/client";

const client = new GradientLabs({
apiKey: process.env.GRADIENT_LABS_API_KEY!,
webhookSigningKey: process.env.GL_WEBHOOK_SIGNING_KEY!,
});

// Express example (use express.raw() so req.body is the raw payload):
app.post("/webhooks", express.raw({ type: "*/*" }), (req, res) => {
try {
const { event, token } = client.webhooks.parse({
body: req.body, // Buffer
headers: req.headers,
});

switch (event.type) {
case "agent.message":
console.log(event.data.body);
break;
case "conversation.hand_off":
console.log(event.data.reason_code);
break;
// ...other event types
}

res.sendStatus(200);
} catch (err) {
if (err instanceof InvalidWebhookSignatureError) {
res.sendStatus(401);
} else {
res.sendStatus(500);
}
}
});
```

`event` is a discriminated union on `event.type`, so narrowing gives you a
fully-typed `event.data`. The optional `X-GradientLabs-Token` header is returned
as `token`.

Supported event types: `agent.message`, `conversation.hand_off`,
`conversation.finished`, `action.execute`, `resource.pull`,
`back-office-task.complete`, `back-office-task.hand-off`, `back-office-task.fail`.

## Examples

See the [`examples/`](./examples) directory for runnable examples covering
conversations, tools, articles, procedures, resources, back-office tasks, and a
webhook server.

## Development

```bash
npm install
npm run build # dual ESM/CJS + type declarations
npm test # vitest (no network required)
npm run lint
npm run typecheck
npm run format
```

## License

[MIT](./LICENSE)
16 changes: 16 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import js from "@eslint/js";
import tseslint from "typescript-eslint";

export default tseslint.config(
{
ignores: ["dist/**", "node_modules/**"],
},
js.configs.recommended,
...tseslint.configs.recommended,
{
rules: {
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-empty-object-type": "off",
},
},
);
43 changes: 43 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Examples

Runnable smoke tests against the real Gradient Labs API. Each example reads your
API key from the `GRADIENT_LABS_API_KEY` environment variable.

> These examples import the client from `../../src` so they run straight from a
> checkout. In your own project, install the package and import from
> `@gradientlabs/client` instead.

## Prerequisites

```bash
npm install
export GRADIENT_LABS_API_KEY="sk_live_..."
```

Some examples need a **Management** API key (tools, articles, procedures,
resources); the conversation, back-office-task, and voice examples need an
**Integration** key.

## Running

Use [`tsx`](https://github.com/privatenumber/tsx) to run the TypeScript directly:

```bash
npx tsx examples/conversations/index.ts
npx tsx examples/tools/index.ts
npx tsx examples/articles/index.ts
npx tsx examples/procedures/index.ts
npx tsx examples/resources/index.ts
npx tsx examples/back-office-tasks/index.ts
```

### Webhooks

The webhooks example starts a local HTTP server that verifies and dispatches
incoming webhooks:

```bash
export GL_WEBHOOK_SIGNING_KEY="whsec_..."
npx tsx examples/webhooks/index.ts
# then point your workspace's webhook URL at http://localhost:3000/
```
Loading
Loading