Recipes

Complete examples you can copy. They use Node 20 or later with no extra packages.

const API = 'https://api.refundhunter.io';
const headers = {
  Authorization: `Bearer ${process.env.CHATTER_API_KEY}`,
  'Content-Type': 'application/json',
};

async function api(method, path, body, extraHeaders = {}) {
  const res = await fetch(API + path, {
    method,
    headers: { ...headers, ...extraHeaders },
    body: body ? JSON.stringify(body) : undefined,
  });
  const data = await res.json();
  if (!res.ok) throw Object.assign(new Error(data.error), { code: data.code, status: res.status, data });
  return data;
}

The recipes below all use this api helper.

Get a refund, start to finish

Launch one chat, wait for it, answer if it asks for help, and print the result.

import { randomUUID } from 'node:crypto';

const { taskId } = await api('POST', '/api/tasks', {
  template: 'bestbuy',
  details: {
    orderNumber: 'BBY01-806912345678',
    customerName: 'Jordan Lee',
    customerEmail: 'jordan@example.com',
    customerPhone: '555-010-2030',
    issue: 'Item arrived with a cracked screen',
    resolution: 'refund',
  },
}, { 'Idempotency-Key': randomUUID() });

for (;;) {
  const { reason, task } = await api('GET', `/api/tasks/${taskId}/wait?timeout=50`);

  if (reason === 'needs_help') {
    console.log('The AI is asking:', task.helpRequest.reason);
    // Decide the answer here: ask a person, look it up, or let it carry on.
    await api('POST', `/api/tasks/${taskId}/intervention`, { action: 'ignore_and_push' });
  }

  if (reason === 'finished') {
    console.log(task.outcome, '-', task.summary);
    break;
  }
}

Price-match a whole list

Create a draft for each row, launch them all, and collect the results as they come in.

const rows = [
  { orderNumber: 'BBY01-1', productName: '65" TV', bestbuyPrice: 999.99, competitorPrice: 849.99, competitorUrl: 'https://example.com/tv' },
  { orderNumber: 'BBY01-2', productName: 'Headphones', bestbuyPrice: 399.99, competitorPrice: 329.99, competitorUrl: 'https://example.com/hp' },
];
const customer = { customerName: 'Jordan Lee', customerEmail: 'jordan@example.com', customerPhone: '555-010-2030' };

const { drafts } = await api('POST', '/api/drafts', {
  tasks: rows.map((row) => ({ template: 'bestbuypricematch', details: { ...customer, ...row } })),
});
await api('POST', '/api/drafts/deploy', { ids: drafts.map((d) => d.id) });

let waiting = drafts.map((d) => d.id);
while (waiting.length > 0) {
  const result = await api('POST', '/api/tasks/wait', { ids: waiting, timeout: 50 });

  for (const id of result.needsHelp) {
    await api('POST', `/api/tasks/${id}/intervention`, { action: 'ignore_and_push' });
  }
  for (const task of result.tasks.filter((t) => result.finished.includes(t.id))) {
    console.log(task.orderNumber, task.outcome, '-', task.summary);
  }
  waiting = result.stillRunning.concat(result.needsHelp);
}

If you already have the list as a CSV file, POST /api/orders/bulk-upload does the first step for you. See Orders and CSV upload.

Launch now, or at the next opening time

async function launchWhenOpen(body) {
  try {
    return await api('POST', '/api/tasks', body);
  } catch (err) {
    if (err.code !== 'chat_closed') throw err;
    return api('POST', '/api/tasks', { ...body, scheduledAt: err.data.nextOpenAt });
  }
}

Check what needs attention

One call, suitable for running every few minutes or at the start of a conversation.

const overview = await api('GET', '/api/overview');

for (const chat of overview.chats.needsHelp) {
  console.log(`${chat.name} needs help: ${chat.helpRequest.reason}`);
}
for (const chat of overview.chats.recentlyFinished) {
  console.log(`${chat.name}: ${chat.outcome} - ${chat.summary}`);
}
if (!overview.canLaunchNow) {
  console.log('Cannot launch right now:', overview.blockers.map((b) => b.message).join(' '));
}

Chase a promised refund

Start a follow-up that knows what was said last time, and record the amount when it lands.

const { taskId } = await api('POST', `/api/tasks/${previousTaskId}/followup`, {
  note: 'The refund promised last week has not arrived. Ask for a status and a reference number.',
});

const { task } = await api('GET', `/api/tasks/${taskId}/wait?timeout=50`);
// ...keep waiting until task.outcome is set, as in the first recipe...

const { orders } = await api('GET', `/api/orders?q=${task.orderNumber}`);
console.log(orders[0].keyDetails); // e.g. { case_id: "...", refund_amount: "129.99" }
await api('PATCH', `/api/orders/${orders[0].id}`, { receivedAmount: 129.99, status: 'closed' });

React to a webhook

A small server that answers the AI's help requests as they arrive. See Webhooks for the signature check.

import { createServer } from 'node:http';

createServer(async (req, res) => {
  let raw = '';
  for await (const chunk of req) raw += chunk;
  if (!isFromChatter(process.env.CHATTER_WEBHOOK_SECRET, raw, req.headers['x-chatter-signature'] ?? '')) {
    res.writeHead(401).end();
    return;
  }
  res.writeHead(200).end(); // answer first, work after

  const event = JSON.parse(raw);
  if (event.type === 'chat.needs_help') {
    const { chat } = event.data;
    console.log(`${chat.name} needs help: ${chat.helpRequest.reason}`);
    await api('POST', `/api/tasks/${chat.id}/intervention`, { action: 'ignore_and_push' });
  }
}).listen(3000);