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

# Project Webhooks

> Subscribe to resource changes in your project, verify event signatures, and process Webhook notifications reliably.

Project Webhooks send signed event notifications to your configured HTTPS endpoint after changes to resources in your project are committed. You can use these notifications to update business state, process follow-up work, or respond to failures.

Notifications carry resource identities and essential state fields rather than complete resource snapshots. After receiving a notification, query the resource API for details and the latest state. Webhooks are not a durable event log—record the full change history separately if you need it, and query the resource API whenever you need to reconcile the latest business state.

If you need detailed real-time output from a session, use the [Event Stream](https://platform.kimi.ai/docs/hosted-agents/event-stream.md). If you only need notifications for scheduled trigger runs, use the trigger's `notification` configuration; see [Run Agents with Triggers](https://platform.kimi.ai/docs/hosted-agents/triggers.md#receive-run-notifications). These three notification mechanisms are independent of one another.

## Register an endpoint

Use a project API key to manage Webhooks. Session work tokens and environment work keys cannot be used to manage Webhooks, and queries return only configurations belonging to the current project.

### Create a Webhook

Call `POST /v1/webhooks` with the receiver URL and the events to subscribe to:

```bash theme={null}
curl --request POST "https://api.moonshot.ai/v1/webhooks" \
  --header "Authorization: Bearer $KIMI_API_KEY" \
  --header "kimi-api-version: 2026-09-01-beta" \
  --header "Content-Type: application/json" \
  --data '{
    "name": "Session status notifications",
    "url": "https://hooks.example.com/kimi",
    "event_types": ["session.status_idled", "session.status_terminated"]
  }'
```

New configurations are disabled by default. The full signing secret is returned only in this creation response, so save it immediately; later queries do not return it. Each project can store up to 32 Webhooks, including disabled configurations, and multiple Webhooks in the same project can use the same URL.

### Prepare the receiver and enable the Webhook

The receiver must be an absolute HTTPS URL with a non-empty hostname. The default port is 443, and an explicit port must be between 1 and 65535. Domain names, IPv4/IPv6 literals, paths, and query parameters are supported. Userinfo, fragments, and IPv6 zone IDs are not accepted. Public targets are allowed by default, while loopback, link-local, cloud provider metadata, and other special-purpose addresses are rejected. The platform performs standard TLS certificate validation and does not follow redirects.

Once your receiver is ready, call `PATCH /v1/webhooks/{id}` to explicitly enable the Webhook:

```bash theme={null}
curl --request PATCH "https://api.moonshot.ai/v1/webhooks/$WEBHOOK_ID" \
  --header "Authorization: Bearer $KIMI_API_KEY" \
  --header "kimi-api-version: 2026-09-01-beta" \
  --header "Content-Type: application/json" \
  --data '{"enabled": true}'
```

The platform delivers an event only to configurations that were enabled and subscribed to that event type when the event occurred. Adding, enabling, or modifying a subscription later does not backfill earlier events.

## Verify the signature

Every HTTPS POST includes the following headers:

```text theme={null}
Webhook-Id: <event_id>
Webhook-Timestamp: <unix_seconds_for_this_attempt>
Webhook-Signature: v1,<standard-base64>
```

The signature scheme and `whsec_<base64>` secret format follow the [Standard Webhooks specification](https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md#signature-scheme). To verify a signature, strip the `whsec_` prefix and decode the standard Base64 value to recover the 32-byte key. Use that key to compute HMAC-SHA256 over `event ID + "." + timestamp + "." + raw request body bytes`.

The example below shows a Node.js receiver with no web framework dependencies:

> [accordion] Node.js receiver example
>
> ```javascript theme={null}
> import http from "node:http";
> import crypto from "node:crypto";
>
> const signingSecret = process.env.KIMI_WEBHOOK_SIGNING_SECRET;
> if (!signingSecret?.startsWith("whsec_")) {
>   throw new Error("Set KIMI_WEBHOOK_SIGNING_SECRET to the whsec_ signing secret");
> }
>
> const key = Buffer.from(signingSecret.slice(6), "base64");
> const seenEvents = new Set();
>
> const server = http.createServer((req, res) => {
>   if (req.method !== "POST") {
>     res.writeHead(405).end();
>     return;
>   }
>
>   const chunks = [];
>   req.on("data", (chunk) => chunks.push(chunk));
>   req.on("end", () => {
>     const body = Buffer.concat(chunks);
>     const eventId = req.headers["webhook-id"];
>     const timestamp = req.headers["webhook-timestamp"];
>     const signature = req.headers["webhook-signature"];
>
>     try {
>       if (
>         typeof eventId !== "string" ||
>         typeof timestamp !== "string" ||
>         typeof signature !== "string"
>       ) {
>         res.writeHead(400).end();
>         return;
>       }
>
>       const timestampSeconds = Number(timestamp);
>       if (
>         !Number.isInteger(timestampSeconds) ||
>         Math.abs(Date.now() / 1000 - timestampSeconds) > 300
>       ) {
>         res.writeHead(400).end();
>         return;
>       }
>
>       const signedContent = Buffer.concat([
>         Buffer.from(`${eventId}.${timestamp}.`, "utf8"),
>         body,
>       ]);
>       const expected = `v1,${crypto
>         .createHmac("sha256", key)
>         .update(signedContent)
>         .digest("base64")}`;
>       const expectedBytes = Buffer.from(expected, "utf8");
>       const signatureBytes = Buffer.from(signature, "utf8");
>
>       if (
>         expectedBytes.length !== signatureBytes.length ||
>         !crypto.timingSafeEqual(expectedBytes, signatureBytes)
>       ) {
>         res.writeHead(400).end();
>         return;
>       }
>
>       const event = JSON.parse(body.toString("utf8"));
>       if (event.id !== eventId) {
>         res.writeHead(400).end();
>         return;
>       }
>
>       if (seenEvents.has(event.id)) {
>         res.writeHead(200).end();
>         return;
>       }
>       seenEvents.add(event.id);
>
>       res.writeHead(200).end();
>       setImmediate(() => {
>         console.log(event.data.type, event.data.id);
>       });
>     } catch {
>       res.writeHead(400).end();
>     }
>   });
> });
>
> server.listen(3000);
> ```

The example uses an in-memory set to demonstrate deduplication. In production, use persistent deduplication storage and return a 2xx response only after reliably storing or queueing the event. When multiple consumers share deduplication storage, scope deduplication keys by consumer.

## Handle events

The notification envelope contains the fixed `type: event`, a unique event `id`, the occurrence time `created_at`, and the resource payload `data`:

```json theme={null}
{
  "type": "event",
  "id": "whev_01h455vb4pex5vsknk084sn02q",
  "created_at": "2026-11-05T10:00:00Z",
  "data": {
    "type": "session.status_idled",
    "id": "sesn_01h455vb4pex5vsknk084sn02q",
    "project_id": "proj_01h455vb4pex5vsknk084sn02q",
    "stop_reason": { "type": "requires_action" }
  }
}
```

The top-level `id` identifies the event, while `data.id` identifies the resource that changed. Different changes to the same resource produce different event IDs. `project_id` identifies the project that persistently owns the resource.

Receivers should process notifications in this order:

1. Verify the signature and timestamp against the raw request body before parsing the JSON.
2. Deduplicate by the top-level event `id`.
3. Return any 2xx response once the event is reliably received, and handle time-consuming business logic asynchronously.
4. Query the latest resource state using `data.type` and `data.id` before updating business data. Late historical notifications must not overwrite newer resource state; treat a deletion notification as the final signal that the resource was permanently deleted.

## Supported event types

When creating a Webhook, specify the events to subscribe to in `event_types`. Each configuration must subscribe to at least one event type, without duplicates. For complete payload fields, see the **Webhooks** group and the **Send a Webhook event** callback in the [API reference](https://platform.kimi.ai/docs/api-reference/webhooks/send-a-webhook-event.md).

> [tab] Sessions and child threads
>
> Session events describe the state of the whole session, while child thread events describe an individual child thread. The resource ID in a child thread event is the child thread ID, and `session_id` identifies the parent session.
>
> | Event | Trigger condition |
> | - | - |
> | `session.status_run_started` | The session entered `running`, including when it resumed running. |
> | `session.status_idled` | The session entered `idle`, or its public stop reason changed while it was `idle`. |
> | `session.status_terminated` | The session entered `terminated`, including when the whole session was archived. |
> | `session.thread_created` | A child thread was actually created for the first time; idempotent re-entry does not send another notification. |
> | `session.thread_idled` | A child thread entered `idle`, or its public stop reason changed while it was `idle`. |
> | `session.thread_terminated` | A child thread entered `terminated`, including when the whole session was archived. |
> | `session.updated` | The title or `agent_overrides` actually changed. |
> | `session.deleted` | The session was permanently deleted. |
>
> The initial `idle` state at session creation does not send a separate notification. `session.status_idled` and `session.thread_idled` carry a stop reason of `end_turn`, `canceled`, `internal_error`, or `requires_action`; writes without an explicit reason do not emit these events.
>
> When a session is archived, separate notifications are sent for the session and for each child thread that actually terminates, but no event is sent for the coordinator thread. A single property-update transaction emits `session.updated` only once. An automatic title emits this event only when the previous title was empty and the title was written successfully. The deletion event retains the session ID and project ownership from before deletion as the final signal that the session was permanently deleted.

> [tab] Vaults and credentials
>
> | Event | Trigger condition |
> | - | - |
> | `vault.created` | A vault was created. |
> | `vault.archived` | A vault was actually archived. |
> | `vault.deleted` | An archived vault was permanently deleted. |
> | `vault_credential.created` | A credential was created individually, in a batch, or upon OAuth authorization completion. |
> | `vault_credential.archived` | A credential was archived directly or as part of its vault's archival. |
> | `vault_credential.deleted` | An archived credential was deleted directly or as part of its vault's deletion. |
> | `vault_credential.refresh_failed` | An MCP OAuth credential refresh received `invalid_grant` and persisted the `revoked` state for the first time. |
>
> Credential events identify the parent vault through `vault_id`. When a vault is archived or deleted, separate notifications are sent for the parent resource and every credential that actually changes. After credential rotation clears `revoked`, another permanent refresh failure can emit `vault_credential.refresh_failed` again.

> [tab] Agents
>
> | Event | Trigger condition |
> | - | - |
> | `agent.created` | An agent was created and its initial version was saved. |
> | `agent.updated` | A new immutable version was published, even if its configuration is identical. |
> | `agent.archived` | An agent was actually archived. |
>
> An archived agent can no longer be used to create new sessions. Existing sessions continue running, and the agent resource and its version history remain readable. Associated triggers automatically pause when a later pre-run check finds that the agent is unavailable, and emit separate trigger events.

> [tab] Triggers
>
> | Event | Trigger condition |
> | - | - |
> | `trigger.created` | A user-managed or platform-managed trigger was actually created. |
> | `trigger.updated` | The schedule, target, or another public configuration field actually changed. |
> | `trigger.paused` | A trigger was paused manually or automatically because of an unrecoverable error, such as an unavailable target. |
> | `trigger.unpaused` | A paused trigger was resumed. |
> | `trigger.archived` | A trigger was actually archived, including when a combined operation on a parent resource (such as a memory store) archives its managed trigger. |
>
> Triggers managed by the platform for workflows such as memory stores are included. Repeated archival and updates with no actual configuration change do not emit duplicate notifications. Resuming a trigger clears its pause reason and recalculates its next fire time; run records remain available after archival.

> [tab] Trigger runs
>
> A Trigger Run tracks task startup until a session accepts the startup input. Events identify the parent trigger through `trigger_id`, and `context.type` distinguishes `schedule`, `manual`, and `system` starts.
>
> | Event | Trigger condition |
> | - | - |
> | `trigger_run.started` | The run record was actually written as `running`. |
> | `trigger_run.succeeded` | The target session was created or reused, its startup input was accepted, and the run record was written as `completed`. |
> | `trigger_run.failed` | The run record was written as `failed`, including execution failure, cleanup failure, or timeout reclamation. |
> | `trigger_run.skipped` | The run record was written as `skipped`, including overlap, a busy session, or a full queue. |
>
> `trigger_run.succeeded` does not mean the task inside the session has finished executing. A run skipped before processing emits only `skipped`; a run skipped after processing starts emits `started` followed by `skipped`. A long-unfinished run may first be reported as failed and later corrected to succeeded by a late result. Query the Trigger Run API for the final result and session association.

> [tab] Execution environments
>
> | Event | Trigger condition |
> | - | - |
> | `environment.created` | An execution environment and its initial version were created. |
> | `environment.updated` | A new immutable configuration version was published, even if its configuration is identical. |
> | `environment.build_ended` | A valid terminal build result was reported. |
> | `environment.archived` | An execution environment was actually archived; existing sessions continue their original lifecycle. |
> | `environment.deleted` | An archived execution environment with no references from unterminated sessions was permanently deleted. |
>
> For cloud environments, the platform asynchronously builds a snapshot for each configuration version. The snapshot may not be ready when `environment.created` arrives; `environment.build_ended` carries the version and a build result of `ready` or `failed`. Self-hosted environments become ready as soon as their configuration is saved and do not emit build-ended events.
>
> Initial builds, rebuilds, older build tasks, duplicate reports, and result corrections each generate notifications with distinct event IDs, without deduplication by build result or current build task. Only the current build task can update the public build status of a configuration version. If rebuilding a `ready` version fails, the original snapshot is retained and a build-ended event with `status: "failed"` is emitted for that attempt.

> [tab] Memory stores
>
> | Event | Trigger condition |
> | - | - |
> | `memory_store.created` | A memory store was actually created. |
> | `memory_store.archived` | A memory store was actually archived and became read-only; repeated archival does not emit a notification. |
> | `memory_store.deleted` | An archived memory store with no session references was permanently deleted. |
>
> Deleting a memory store cascades to the metadata of its memory files and file versions, but emits only the memory store event, not separate file or version events. Archiving an associated managed trigger emits a separate trigger event.

Project ownership is determined by the resource's persistent owner. Official resources and changes without project ownership do not produce project Webhooks; changes made by an administrator to project resources still emit events according to the resource's project ownership.

## Delivery behavior

* **Duplicate deliveries**: The same event may arrive more than once. All targets and retries for an event share the same top-level `id`, which also matches `Webhook-Id`.
* **Subscription scope**: Each delivery task is created after the resource change is committed and captures the target's URL and signing secret at that moment. Later configuration changes do not affect tasks that have already been created.
* **Delivery order**: Events are not guaranteed to arrive in the order they occurred. Drive business logic from the latest state returned by the resource API rather than relying on arrival order.
* **Retries**: Each event-target combination is attempted at most 3 times in total (including the initial attempt), with a 10-second timeout per request. Any 2xx response counts as success; non-2xx responses, temporary DNS or connection failures, and request timeouts are retried while attempts remain.
* **`Retry-After`**: Parsed only for `429` and `503` responses. A valid value of up to 120 seconds sets the lower bound for the backoff delay; a value above 120 seconds stops retries and ends the task as a final delivery failure. Empty, malformed, zero-second, or expired values fall back to the standard backoff.
* **Redirects and rejected addresses**: `3xx` responses are never followed and are treated as ordinary non-2xx responses. If the address policy rejects the target, the current task ends immediately without retries and does not count toward receiver failures.
* **Timestamps**: `Webhook-Timestamp` is generated when each delivery attempt is signed and is updated on retries; use the payload's `created_at` for the event occurrence time.
* **Lost notifications**: Platform failures, publication timeouts, or queue anomalies can cause notifications to be lost. Query the resource API when you need to reconcile business state; do not treat Webhooks as a complete change log.

The platform tracks delivery tasks that end in a final failure separately for each configuration; intermediate retries are not counted. The first final failure opens a fixed 24-hour window, and any 2xx success clears the failure record. If the number of final delivery failures within the window exceeds 20, the platform automatically disables the Webhook and sets `disabled_reason` to `delivery_failures`.

An actual URL change, signing secret rotation, or explicit enable resets the failure record for the new configuration; changing only the name or subscription list preserves the existing record. Automatic disabling only stops capturing new events; tasks that have already been created continue executing. Once you fix the receiver, you can re-enable the Webhook, but events that occurred while it was disabled are not replayed.

## Manage Webhooks

| Operation | Endpoint | Behavior |
| - | - | - |
| Create | `POST /v1/webhooks` | Creates a disabled-by-default configuration and returns the signing secret only in this response. |
| List | `GET /v1/webhooks` | Returns configurations paginated from newest to oldest, without signing secrets. |
| Get | `GET /v1/webhooks/{id}` | Returns the configuration, enabled state, and `disabled_reason` when disabled, without the signing secret. |
| Update and enable/disable | `PATCH /v1/webhooks/{id}` | Partially updates `name`, `url`, `event_types`, and `enabled`. |
| Delete | `DELETE /v1/webhooks/{id}` | Permanently deletes the configuration and stops capturing subsequent events. |
| Rotate signing secret | `POST /v1/webhooks/{id}/regenerate-signing-secret` | Preserves the enabled state and returns the new secret only in this response. |

Creation and signing-secret rotation responses additionally include `signing_secret` and carry `Cache-Control: no-store`. For request fields, response fields, and error definitions, see the [Webhook API reference](https://platform.kimi.ai/docs/api-reference/webhooks/create-a-webhook.md). The update endpoint modifies only fields present in the request body; an empty request body, explicit `null`, empty URL, empty event list, or duplicate or unknown event types all return `400`.

Changing the URL, rotating the signing secret, disabling, or deleting a Webhook affects only subsequent new events. Delivery tasks that have already been created, including their retries, continue using the original URL and secret. After rotating a secret, receivers should support verification with both the old and new secrets until in-flight tasks from the old configuration have drained. Deleting a configuration does not cancel delivery tasks that have already been created.

## Next steps

> [card] [View the Event Stream](https://platform.kimi.ai/docs/hosted-agents/event-stream.md)
>
> Receive detailed real-time output from sessions and threads.

> [card] [Configure scheduled tasks](https://platform.kimi.ai/docs/hosted-agents/triggers.md)
>
> Learn about triggers and their independent scheduled-run notifications.

> [card] [Explore the API reference](https://platform.kimi.ai/docs/api-reference/webhooks/list-webhooks.md)
>
> View management endpoints, callbacks, and complete event schemas.
