# Agents

An agent calls tools in a loop until the task is done or it reaches its step limit. The tools are Harakumo's own actions on the agent's project (read the project and its deployments, search vectors … and, when allowed, query a database, add Roadmap items, store vectors, upload and delete files, make checkout links, send push notifications and email). They run with an API key made for the run and revoked afterwards. That key is limited to the agent's project and is never more than whoever started the run: it is read-only unless the agent may make changes and the starter could make them too, and a key limited to another project cannot start the run.

So a run never has a tool that covers the whole workspace (projects, usage, domains, repos, the Balance), or one its key can never use (a read-only key is refused what changes things, and secrets). When you build an agent they are not offered as usable (they are shown greyed out with the reason, or left out), and saving an agent with one is refused with the reason. Sending email is kept: it sends as the agent's project.

Agents run a business (support, sales, operations); they do not build the app. The tools for building it are not offered to agents: the docs and the build standard, starter files, launch checks, deploys and code, the project's setup (environment variables, functions, new databases and buckets, domains, sign-in, phone-app settings, the mail sender), its Roadmap goal, the business memory and managing agents. Your own AI builds the app with them through the connector. An agent saved with one of them before 2026-10-22 keeps it, and its runs still use it.

Agents act on your own Harakumo resources, and can call your project's own Functions as tools. A run starts when you ask for one (the API, the SDK, the dashboard or an AI assistant): it gets its id at once and keeps going when you leave. It also starts on a schedule, when your app sends the agent a signed event, or when a visitor writes to it from your site (see How an agent starts). Threads, approvals, a callback when a run ends and HTTP tools to other sites are not available yet.

## In plain words

An AI helper that does a job step by step with the tools you allow, such as reading your data or sending an email. You see every step and what it cost.

For example: Each time you run it, an agent reads the new support messages and drafts replies for you to check.

## Agents for your project

Harakumo suggests the agents a kind of app usually needs (a store gets a shopping assistant, order follow-up and a low-stock alert; a booking app a booking assistant and reminders) and creates them in one step: the project's Agents page, `GET`/`POST /api/projects/:id/agents/suggested`, or the AI connector's suggest_agents and create_suggested_agents.

An AI assistant can also design any agent itself with the connector (create_agent, get_agent, update_agent, set_agent_status, delete_agent, list_agent_tools), test it with run_agent and improve it from its steps. run_agent waits up to 35 seconds and otherwise answers the run id to check with get_agent_run (one run with every step) or stop with cancel_agent_run; list_agent_runs pages through an agent's runs. run_agent takes `maxCostUsd`, create_agent and update_agent `maxCostPerRunUsd` and function tools.

Each agent records what starts it (`trigger`: manual, chat, schedule or event, with a label in plain words) and what it does (`purpose`). The project's Agents page draws every agent as a flow: what starts it, the agent, and the services it uses. A schedule, event or chat start runs the agent once it is set up (below); until then, the flow says so and the agent runs when asked.

## How an agent starts

| Start | Set it up | When it runs |
| --- | --- | --- |
| When asked | `POST /api/agents/:id/runs { input, wait? }`, the SDK's `hk.agents.run` or `hk.agents.runs.create`, the dashboard or the connector's run_agent. | At once, in the background: the answer carries the run id straight away (202, `status: "running"`), and the run keeps going if you leave. `wait` (0 to 60 seconds) waits that long for it to end: 200 with the finished run and its steps. Read it with `GET /api/agents/runs/:runId`; stop it with `POST /api/agents/runs/:runId/cancel`. |
| On a schedule | `PATCH /api/agents/:id { schedule: "0 9 * * *" }` (five cron fields in UTC, or @hourly, @daily, @weekly, @monthly), or `{ schedule: { cron, input } }`; `null` removes it. Also on the agent's page and in update_agent. | At the first look at or after each time; the platform looks every ten minutes, so a run can start up to ten minutes late, and a schedule that asks for runs closer together than that is refused. `schedule` on the agent shows the next run and what the last one did. |
| On an app event | `PATCH /api/agents/:id { events: true }` answers the signing secret once (`events: "rotate"` gives a new one, `false` turns events off). Your server POSTs JSON (16 KB at most) to `/api/agents/:id/events`, signed as payment webhooks are: `Harakumo-Signature: t=<seconds>,v1=<HMAC-SHA256 of "<t>.<raw body>">`, with `Harakumo-Event` naming the event and `Harakumo-Delivery` its id. | The endpoint answers 202 at once; a run starts within about ten minutes. A second delivery of the same id is not a second run. 30 events a minute and 100 waiting per agent. |
| From a visitor's chat | `PATCH /api/agents/:id { chat: true }` answers a publishable chat id (`hkchat_…`) and its URL; `{ chat: { allowedOrigins, dailyLimit } }` changes them. Your page POSTs `{ message, history? }` to `/api/agents/chat/<chatId>` from the project's own addresses or an origin you allow. | At once, one run per message, answered in the same request with `{ reply, run_id }`. The run is read-only and has only the project's data tools and the function tools marked `visitorChat: true`, and 60 seconds. It searches only the collections open to visitor chat (Vector DB → Visitor chat), by text across the whole collection (every namespace) with at most 10 matches; `chat.tools` and `chat.missing_tools` say what its runs have, and `chat_note` says when no collection is open yet. 10 messages a minute per visitor's address, and a daily limit (200 unless you set another). |

> An agent can start on its own in three ways, all on at once if you like: a schedule, app events and visitor chat. Each start is admitted and charged as a run of its own. A scheduled or event run uses a key cut from the access of whoever set it up, as it stands when the run starts, the plan's limit on runs at once and the same credit checks as any run, and has 5 minutes to finish (stop_reason `time_limit` past it). When one could not start, the reason is kept on its schedule, events or chat (`last_error`) for you to read; a due time that finds every run slot taken waits for the next look (`last_error` starts "Waiting"). In a project being deleted nothing starts: app events answer 409 `project_being_deleted`, and visitor chat 503.

## Create and run

**SDK**

```js
const { agent } = await hk.agents.create(project.id, {
  name: 'ops', model: 'claude-sonnet-5',
  instructions: 'Report failed deploys of this project and what their logs say went wrong.',
  tools: ['get_project', 'list_deployments', 'get_deployment'],
  maxSteps: 8,
});
const run = await hk.agents.run(agent.id, 'What needs attention today?'); // starts it, then waits for it to end
// run.status, run.output, run.steps, run.cost_usd, run.model, run.stop_reason

// Or start it and come back for it: the run keeps going.
const { run: started } = await hk.agents.runs.create(agent.id, { input: 'Tidy the Roadmap.', wait: 0, maxCostUsd: 0.1 });
const { run: now } = await hk.agents.runs.get(started.id);   // with its steps
const done = await hk.agents.runs.wait(started.id);          // reads it until it ends
await hk.agents.runs.cancel(started.id);                     // stops before its next step
```

## What a run returns

`POST /api/agents/:id/runs` answers `{ run }`: 202 with `status: "running"` at once, or 200 with the finished run and its steps when it ended within `wait`. `GET /api/agents/runs/:runId` answers one run with its steps; `GET /api/agents/:id/runs` pages through an agent's runs (`limit` 1 to 50, `cursor`, `status`, `startedBy`) as `{ runs, nextCursor }`.

Cancel: `POST /api/agents/runs/:runId/cancel` stops a running run before its next model or tool call. A call already under way finishes and is charged, and what earlier steps did stays done. It ends as failed with stop_reason `cancelled`. A run that already ended comes back as it is.

| Field | Meaning |
| --- | --- |
| status | `completed` or `failed` (`running` while it is still going). |
| stop_reason | null when it completed. `step_limit`: it made maxSteps model calls without finishing. `credits`: the AI credit ran out. `spend_limit`: the monthly spending limit was reached. `budget`: it reached its cost cap. `cancelled`: someone stopped it. `error`: the model or the run failed. `vendor`: the AI service was unavailable on Harakumo's side (our fault, not yours). `time_limit`: it reached its 5 minutes, or a visitor's chat run its 60 seconds. `stale`: the process running it stopped. |
| output | The answer or, for a run that stopped, why it stopped and what to do. |
| started_by | `api` (someone asked: the API, the dashboard, a connector), `schedule`, `event` or `chat`. |
| steps | With one run only: every step in order, `step`, `kind` (`tool`, `text` or `refused`), `tool`, `arguments` (parsed JSON), `result` (its first 4,000 characters) and `ok` (true or false). |
| tokens_used, cost_usd, max_cost_usd | What its steps used and were charged, whether it finished, stopped or failed, and its cost cap. |
| model, duration_ms | The model that ran it, and how long it took. |

## See what a run did

The project's Agents page → an agent lists its recent runs. Open one to see its input, its output or why it stopped, the model, the tokens and the cost, and every step: the tool it called, the arguments it passed and what came back, with failed tool calls marked. `GET /api/agents/runs/:runId` (`hk.agents.runs.get`) returns the same for one run; `GET /api/agents/:id` (`hk.agents.get`) answers the agent with its 5 newest runs without steps (`recent_runs`).

## Settings

| Field | Meaning |
| --- | --- |
| model | A tool-capable model (Claude, GPT, Grok, Kimi) or `auto` (runs on claude-sonnet-5). On Hobby, vendor models need the workspace owner's verified email. |
| tools | Tool names from `GET /api/agents/tools` (add `?writes=1` to see the ones that change things); a name that is not one of them is refused with 400. Left empty, the agent gets every tool this listing offers for its `allowWrites` setting, and never one for building the app. A run gets only the tools its key, limited to the agent's project, can use, so the listing, list_agent_tools and the dashboard's agent builder offer only those: a tool that covers the whole workspace is marked `available: false` with a `reason`, and saving an agent with one is refused with 400 and that reason. The tools for building the app (above) are not offered: the listing leaves them out (the workspace-wide ones among them show as `available: false` like the rest), and a new agent saved with one is refused with 400. `?agent=<id>` adds the ones that agent kept, marked `kept: true`. With `?writes=1`, the tools only an agent with `allowWrites` can use (everything that changes something) are marked `needsWrites: true` with a `writesReason`. Tools that manage API keys, switch workspace, run agents or need an admin (members, the audit log, the Balance, service settings) are never given to an agent. |
| allowWrites | false by default: the run's key is read-only, so only read tools. true lets the agent use tools that change things in its own project: run SQL, add and change Roadmap items, store vectors, upload and delete files, make checkout links and send push notifications and mail. Turn it on deliberately. An agent that may send email is given the workspace owner's verified address for mail meant for the owner, never an address it read in its data. |
| maxSteps | Model calls per run, 1–24, default 8. Each model call may call up to 8 tools at once (more are recorded as not run, and the model is told). A run that makes maxSteps model calls without finishing stops as failed with stop_reason step_limit. |
| maxCostPerRunUsd | The most one run may cost, 0.01 to 100 dollars, or null for the plan's default: $0.25 on Hobby, $1 on paid plans. A run is checked after each model call, so it can go over by one call. A run can be given its own with `maxCostUsd` on `POST /api/agents/:id/runs`. |
| function tools | In `tools`, besides tool names, up to 10 of `{ type: "function", name, functionId, description, inputSchema, visitorChat? }`: the project's own Functions. The model calls one with JSON arguments, which the run POSTs to the Function (15 seconds, its first 64 KB read), signed with the project's environment variable `HARAKUMO_AGENT_TOOLS_SECRET` (made when the first one is saved; redeploy the Function to read it) as `Harakumo-Signature`: check it as below. `Harakumo-Agent-Mode` says `owner` or `visitor`. Only those with `visitorChat: true` are offered to a visitor's chat run. They run your own code, so `allowWrites` does not limit them: they are offered to every run, read-only ones too, and your code decides what a call may do. A `tools` list with no names offers the tools `GET /api/agents/tools` lists for the agent's `allowWrites`, but a list of function tools alone offers only those: list the tool names beside them to keep them. |
| instructions | Up to 16,000 characters. |

## A function tool's Function

A function tool is called as a POST of its arguments as JSON to the Function's address. A Function is one module with no packages, so it checks the signature with Web Crypto: `Harakumo-Signature` is `t=<seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">`, made with `HARAKUMO_AGENT_TOOLS_SECRET`. A server of your own that has the SDK can call its `verifyWebhookSignature(secret, rawBody, header)` instead. Whatever the Function answers (its status and its first 64 KB) is what the model reads.

**The Function**

```js
const enc = new TextEncoder();

// Harakumo-Signature: t=<seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">, at most 5 minutes old.
async function signedByHarakumo(secret, body, header) {
  const parts = Object.fromEntries(String(header || '').split(',').map(p => p.split('=')));
  const t = Number(parts.t);
  if (!t || !/^[0-9a-f]{64}$/.test(parts.v1 || '') || Math.abs(Date.now() / 1000 - t) > 300) return false;
  const key = await crypto.subtle.importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']);
  const mac = new Uint8Array(parts.v1.match(/../g).map(h => parseInt(h, 16)));
  return crypto.subtle.verify('HMAC', key, mac, enc.encode(`${t}.${body}`));
}

export default {
  async fetch(request, env) {
    const body = await request.text();
    if (!(await signedByHarakumo(env.HARAKUMO_AGENT_TOOLS_SECRET, body, request.headers.get('harakumo-signature')))) {
      return new Response('Not signed by Harakumo', { status: 401 });
    }
    const { orderId } = JSON.parse(body);
    // 'visitor' when a visitor's chat run called it: answer only what a visitor may see.
    const visitor = request.headers.get('harakumo-agent-mode') === 'visitor';
    return Response.json({ orderId, status: 'shipped', ...(visitor ? {} : { internalNote: 'left the warehouse Monday' }) });
  },
};
```

## Limits

| What | Limit |
| --- | --- |
| Runs started | 6 a minute per workspace (429 `rate_limited`) |
| Runs at once | 1 on hobby, 1 on indie, 5 on pro, 10 on team, 20 on scale (429 `plan_limit`) |
| Model calls per run (maxSteps) | 1 to 24, default 8; up to 8 tool calls per model call |
| Time per run | 5 minutes (`timeLimitSeconds` 10 to 300 for less); a visitor's chat run 60 seconds |
| Cost per run | $0.25 on Hobby, $1 on paid plans, unless the agent or the run sets its own (0.01 to 100 dollars) |
| Input | 32,000 characters |
| App event body | 16 KB |
| Function tools | 10 per agent; each call 15 seconds, its first 64 KB read |
| A run with no sign of life | marked failed (`stale`) after 5 minutes, and its slot is free again |
| Run history | finished runs are kept 90 days |

## Limits and cost

- Before a run starts, Harakumo sets aside an estimate of a few steps. With no AI credit left, or no room under the monthly spending limit, the run is refused with 402 (the same codes as an AI Gateway call) and never starts; nothing is charged.
- Each step is charged as it happens at the model's price, from included AI credit and then the Balance (on a paid plan, the Balance of the workspace that pays for the plan, for every workspace it covers, under that workspace's spending limit; on Hobby, the workspace's own). A run stops as failed when the money runs out (stop_reason `credits`), the monthly spending limit is reached (`spend_limit`) or it reaches its cost cap (`budget`); its output says which, and where on the Billing page to add funds or raise the limit.
- A run's `tokens_used` and `cost_usd` are what its steps used and were charged, whether it finished, stopped or failed. Every model call is in the AI request log (`GET /api/ai/requests?source=agent`) under the run's id.
- Runs: 6 a minute per workspace (429 `rate_limited` past it); 1 at once on hobby, 1 at once on indie, 5 at once on pro, 10 at once on team, 20 at once on scale (429 `plan_limit` with `limit` and `current`). Input up to 32,000 characters.
- Every run has 5 minutes (`timeLimitSeconds` from 10 to 300 asks for less), and a visitor's chat run 60 seconds. A run that shows no sign of life for 5 minutes died with the process running it: it is marked failed (stale) and its run slot is free again. A live run is never cut off by this.
- Billing → Balance breaks this month's AI spend down by model, agent runs included: each step is recorded under the model that ran it. Charges recorded before that, without a model, are one Unattributed row; each run also shows its own model and cost.

## Memory and documents as tools

- `query_vectors` (and `list_vector_collections`, `get_vector_collection`, `fetch_vectors`) answer from your documents; `search_memory` recalls what your app knows about a customer. On a store of kind "memory", `search_memory` needs `userId`: the customer's id, which the agent's instructions or input must give it.
- `add_memory` and `delete_vectors` change data, so they are offered only to an agent with `allowWrites`. Managing stores and collections (create, delete, `forget_memory_user`, `list_memory_users`, `update_vector_collection`) is for your own AI, not offered to agents.

## Errors

Every refusal is `{ error, code, param? }`. A run that started and then failed is not an error: it answers the run, with `status: "failed"` and its `stop_reason`.

| Code | Status | When |
| --- | --- | --- |
| invalid_request | 400 | A field is wrong (`param` names it): a tool list, maxSteps, a cron line, `wait` or `timeLimitSeconds` out of range. |
| input_required | 400 | A run was asked for with no input. |
| unknown_tool | 400 | A tool name nothing implements; `GET /api/agents/tools` lists them. |
| ai_credits_exhausted / spend_limit_reached | 402 | No AI credit or no room under the spending limit for the run's estimate; nothing ran. |
| ai_gateway_off / ai_model_off | 403 | The AI Gateway, or the agent's model, is switched off. |
| not_found | 404 | No such agent or run, or it is in another workspace. |
| agent_paused | 409 | The agent is paused: resume it to run it. |
| already_exists | 409 | An agent of that name is already in the project. |
| project_being_deleted | 409 | The project is being deleted; nothing starts. |
| plan_limit | 429 | The plan's runs at once are all going (`limit`, `current`). |
| rate_limited | 429 | More than 6 runs a minute in the workspace; retry after `Retry-After`. |
| run_not_started | 503 | The run could not be started; nothing was done or charged. Try again. |

## Changing an agent

- Edit an agent with `PATCH /api/agents/:id` (model, instructions, tools, maxSteps, allowWrites, maxCostPerRunUsd, schedule, events, chat); its run history is kept. A paused agent answers 409 `agent_paused` until it is resumed, and its schedule, events and chat start nothing meanwhile.
- The older `POST /api/agents/:id` still starts a run until 2026-11-23 (it answers with `Deprecation` and `Sunset` headers); use `POST /api/agents/:id/runs`. See What changed.

## Reference

**SDK**

```js
const { agent } = await hk.agents.create(project.id, { name: 'triage', model: 'auto', tools: ['list_deployments'] });
const run = await hk.agents.run(agent.id, 'Is this project live, and when was it last deployed?');
console.log(run.status, run.stop_reason, run.cost_usd, run.steps.length);
const { runs, nextCursor } = await hk.agents.runs.list(agent.id, { status: 'failed' }); // a page, newest first
await hk.agents.update(agent.id, { maxSteps: 12 });          // run history is kept
await hk.agents.pause(agent.id);                             // hk.agents.resume(agent.id) to run again
```

**CLI**

```bash
harakumo agents <projectId>                                   # list agents
harakumo agents run <agentId> "What needs attention today?"     # waits for it to end
harakumo agents run <agentId> "Tidy the Roadmap" --no-wait --time-limit 120 --max-cost 0.5
harakumo agents runs <agentId> --status failed
harakumo agents runs get <runId>                                 # with every step
harakumo agents runs cancel <runId>
```

**REST**

```http
GET    /api/agents/tools?writes=1
POST   /api/projects/:id/agents   { "name" (64 characters at most), "model", "instructions"?, "tools"?: [], "maxSteps"?, "allowWrites"?, "maxCostPerRunUsd"?, "schedule"?, "trigger"?: { "kind", "label" }, "purpose"? }
GET    /api/projects/:id/agents/suggested?appType=store     # the agents this kind of app usually needs
POST   /api/projects/:id/agents/suggested   { "appType", "keys": [] }   # create them
POST   /api/agents/:id/runs       { "input": "…", "wait"?: 0-60, "maxCostUsd"?, "timeLimitSeconds"? }   # 202 { run } at once, or 200 once it ended
GET    /api/agents/:id/runs?limit=&cursor=&status=&startedBy=     # { runs, nextCursor }
GET    /api/agents/runs/:runId    # one run with its steps
POST   /api/agents/runs/:runId/cancel
GET    /api/agents/:id            # the agent, its 5 newest runs, schedule, events and chat
PATCH  /api/agents/:id            { "model"?, "instructions"?, "tools"?, "maxSteps"?, "allowWrites"?, "maxCostPerRunUsd"? } | { "action": "pause"|"resume" }
PATCH  /api/agents/:id            { "schedule": "0 9 * * *" | { "cron", "input" } | null }
PATCH  /api/agents/:id            { "events": true | "rotate" | false } | { "chat": true | { "allowedOrigins", "dailyLimit" } | "rotate" | false }
POST   /api/agents/:id/events     # from your server, signed with the events secret (Harakumo-Signature)
POST   /api/agents/chat/:chatId   { "message", "history"? }   # from a web page; → { reply, run_id }
DELETE /api/agents/:id
```
