@kindgi/api
npm install @kindgi/api · source
REST + SSE HTTP surface for the Kindgi platform. Exposes the runtime
(kernel, agents, HITL, supervisor — reached through the bindings passed
to createApp) behind two wire faces:
/v1/*— the Kindgi REST API. JSON in, JSON out. Bearer token auth. Documented via OpenAPI 3.1 (snapshot shipped as@kindgi/api/openapi.json). Conventions locked indocs/API-ROUTE-CONVENTIONS.md./s3/*— AWS S3 API v4 wire surface. XML in, XML out. SigV4 auth. Documented in this file.
Both surfaces route through the same runtime bindings — an artifact
uploaded via one is readable via the other. Deployments enable
either or both via createApp(...) bindings.
createApp(input)
Section titled “createApp(input)”Assemble the Hono app instance. Every runtime dependency is caller-
plugged; the API package does not own persistence. See
src/app.ts for the full CreateAppInput shape.
Minimal wiring for BOTH surfaces:
import { createApp } from '@kindgi/api';
const app = createApp({ // Required runtime bindings — supplied by the Kindgi runtime in a // deployment; `createStubAppBindings()` from @kindgi/testing in tests. ...runtimeBindings, resolveToken: async (token) => /* ... */, runHandler: /* ... */, blobStorage, // any BlobStorageBinding (filesystem, S3, GCS, …) s3Credentials: { async resolve(accessKeyId) { // Deployment-owned lookup — return { secretKey, tenantId, bucket } // or null for unknown / revoked. return await lookupAccessKey(accessKeyId); }, },});Omit s3Credentials → the /s3/* mount is skipped (Hono 404).
Omit blobStorage → both /v1/artifacts AND /s3 are skipped.
Interactive docs (Scalar)
Section titled “Interactive docs (Scalar)”Set openapi.docs on createApp(...) to mount a Scalar-rendered
interactive API reference alongside the JSON spec. The docs page reads
the (already-public) /v1/openapi.json in the browser, so it sits on
the public side of the auth chain — no bearer required to browse.
const app = createApp({ ...runtimeBindings, resolveToken: /* ... */, runHandler: /* ... */, openapi: { docs: true }, // → mounts /docs (default path)});
// Or customize:openapi: { docs: { path: '/reference', title: 'Acme Legal API' } }docs is opt-in — omit it and the docs UI is unmounted (Hono 404). The
JSON spec at /v1/openapi.json is always mounted independent of this
flag.
The /s3/* mount
Section titled “The /s3/* mount”Any S3-aware client (aws s3 cp, rclone, mc, aws-sdk-js, boto3)
hits /s3/* with zero code changes. The server verifies AWS Signature
Version 4 itself (node:crypto; see
src/middleware/sigv4-verify.ts).
Auth model
Section titled “Auth model”Every /s3/* request carries SigV4 credentials, either as:
- Header auth —
Authorization: AWS4-HMAC-SHA256 Credential=<accessKeyId>/<date>/<region>/s3/aws4_request, SignedHeaders=..., Signature=<hex> - Presigned URL — query params
X-Amz-Algorithm=AWS4-HMAC-SHA256,X-Amz-Credential=...,X-Amz-Date=...,X-Amz-Expires=...,X-Amz-SignedHeaders=...,X-Amz-Signature=....
The middleware:
- Parses the auth params (header OR presigned).
- Checks the signed timestamp and credential scope: within ±15 minutes
of the server clock for header auth (
RequestTimeTooSkewedotherwise); presigned URLs untilX-Amz-Expires. - Calls
S3CredentialBinding.resolve(accessKeyId)→ resolves to{ secretKey, tenantId, bucket, expiresAt? }ornull. - Re-derives the signature under
secretKeyfrom exactly what the client signed (its timestamp and itsSignedHeaders, which for header auth includex-amz-content-sha256) and compares it in constant time. - Compares the URL-declared bucket to the credential's
bucketfield. Mismatch →403 AccessDenied(each credential is scoped to one bucket). - Sets
c.set('tenantId', ...),c.set('bucket', ...)andc.set('s3AccessKeyId', ...), then runs itsbeforeBodyhandlers in order. One that answers ends the request with its body unread.createApppasses the tenant state gate, which withtenantStatesanswers a closing or suspended tenant'sPUTorPOSTwith403 AllAccessDisabled(aGET,HEADorDELETEstill passes). Then, withtenantLimits, it passes the S3 request limit, which answers a request past the tenant's minute with503 SlowDown. - Reads the body (not for
GET,HEADorDELETE), at mostartifactMaxBytes(default 100 MiB): more is400 EntityTooLarge. For header auth, verifiesx-amz-content-sha256matches it, an empty body too, unless it'sUNSIGNED-PAYLOAD: a mismatch is400 XAmzContentSHA256Mismatch. - Passes the request on to the S3 route handlers, which read the body step 7 read.
All auth failures return S3-style XML errors
(<Error><Code>...</Code>...</Error>) with Content-Type: application/xml.
Supported operations
Section titled “Supported operations”Object routes (bucket + key):
| Verb | Path | Op |
|---|---|---|
| PUT | /s3/:bucket/* |
PutObject |
| GET | /s3/:bucket/* |
GetObject |
| HEAD | /s3/:bucket/* |
HeadObject |
| DELETE | /s3/:bucket/* |
DeleteObject |
Bucket routes:
| Verb | Path | Op |
|---|---|---|
| HEAD | /s3/:bucket |
HeadBucket |
| GET | /s3/:bucket |
ListObjectsV2 (requires ?list-type=2) |
Multipart upload (S3-standard md5(concat(md5(part_i)))-N ETag):
| Verb | Path | Op |
|---|---|---|
| POST | /s3/:bucket/*?uploads |
InitiateMultipartUpload |
| PUT | /s3/:bucket/*?partNumber=&uploadId= |
UploadPart |
| POST | /s3/:bucket/*?uploadId= |
CompleteMultipartUpload |
| GET | /s3/:bucket/*?uploadId= |
ListParts |
| DELETE | /s3/:bucket/*?uploadId= |
AbortMultipartUpload |
Semantic notes:
- Size: a request's body is at most
artifactMaxBytes(default 100 MiB), the limitPOST /v1/artifactshas; more is400 EntityTooLarge. A larger object goes up as a multipart upload, each part under the limit. - Content-MD5 on PUT (regular OR part upload) is verified;
mismatch →
400 BadDigest. - Range requests on GET support single-range only (
bytes=N-M,bytes=N-,bytes=-M) — response is206 Partial ContentwithContent-Range: bytes N-M/total. Multi-range (comma-separated) requests are rejected with416 InvalidRange. - Object reads (GET and HEAD, a presigned link's included) answer
X-Content-Type-Options: nosniff. An object of a type a browser shows without running it (PNG, JPEG, GIF, WebP, AVIF, PDF, plain text, MP3, Ogg, WAV, WebM and MP4 audio, and MP4, WebM and Ogg video) is served inline; any other is an attachment (Content-Disposition: attachment) withContent-Security-Policy: default-src 'none'; sandbox, so a browser never runs it as a page of this origin. A stored type that isn't a well-formed media type of at most 255 characters is served asapplication/octet-stream. Theresponse-content-typeand other response override parameters aren't read. - DELETE always returns
204— whether the key existed or not (S3 semantics). - ListObjectsV2 requires
?list-type=2; v1 listing is not implemented (returns501 NotImplemented).?prefix=,?max-keys=,?continuation-token=are honored. - x-amz-tagging header on PUT is form-encoded
(
key1=val1&key2=val2) and stored asBlobMeta.tags. The dedicated?taggingsubresource verbs are not implemented.
Cross-surface interop
Section titled “Cross-surface interop”Every persisted blob carries BOTH a blobId (UUID) AND a
(bucket, key) pair. Bespoke uploads via POST /v1/artifacts land
under bucket: 'artifacts', key: <blobId> by default — S3
credentials granted the artifacts bucket see them via
s3://artifacts/<blobId>.
Conversely, S3 uploads via PUT /s3/:bucket/:key are visible in
GET /v1/artifacts listings under the same blobId and are
downloadable via GET /v1/artifacts/:blobId.
A listing's entries and an upload's answer carry the pair as bucket
and key when the storage gives the blob one, so a client can match an
S3 object to its blobId.
Errors (S3-style XML)
Section titled “Errors (S3-style XML)”| HTTP | S3 Code | When |
|---|---|---|
| 400 | InvalidRequest |
Malformed request |
| 400 | MalformedXML |
CompleteMultipartUpload body invalid |
| 400 | InvalidArgument |
Bad query param (e.g. partNumber OOB) |
| 416 | InvalidRange |
Bad Range header |
| 400 | BadDigest |
Content-MD5 mismatch |
| 400 | XAmzContentSHA256Mismatch |
Payload hash header mismatch |
| 400 | EntityTooLarge |
Body over artifactMaxBytes (default 100 MiB) |
| 400 | InvalidPart |
Multipart part ETag mismatch |
| 403 | AccessDenied |
Credential expired / wrong bucket |
| 403 | InvalidAccessKeyId |
Unknown access key |
| 403 | SignatureDoesNotMatch |
SigV4 verification failed |
| 403 | RequestTimeTooSkewed |
Signed timestamp outside the ±15 min window |
| 403 | InvalidRequest |
Malformed SigV4 authorization |
| 403 | AllAccessDisabled |
A closing or suspended tenant's PUT or POST (with tenantStates) |
| 400 | AuthorizationQueryParametersError |
Malformed presigned-URL parameters |
| 404 | NoSuchKey |
Unknown key |
| 404 | NoSuchUpload |
Unknown or aborted uploadId |
| 501 | NotImplemented |
Unsupported operation |
| 500 | InternalError |
Backing store failure |
| 503 | SlowDown |
Past the tenant's API requests a minute (with tenantLimits; Retry-After) |
| 503 | ServiceUnavailable |
A PUT or POST whose tenant's state can't be read (with tenantStates; Retry-After) |
Drawing a run's result
Section titled “Drawing a run's result”@kindgi/api/run-result is what a place that shows a run's result draws
from, so the Kindgi console and a chat's run view say the same. It's plain
functions and data, with no runtime dependencies, so a browser bundle can
import it.
import { RUN_STATUS_WORDS, RESULT_LIMIT, answerBlocks, answerValue } from '@kindgi/api/run-result';
const run = await (await fetch(`${base}/v1/runs/${runId}?include=output`, { headers })).json();const status = RUN_STATUS_WORDS[run.status]; // 'Done'const { blocks, truncated } = answerBlocks(answerValue(run), RESULT_LIMIT);-
answerValue(run)is what the run answered: an agent's typedoutputwhen it declares one, else its reply's content; a flow's output. It then callsanswerOfText, which reads a JSON object or array written as text (bare, or in one```or```jsonfence) as its value. The text is trimmed for that check, and anything else comes back as it was sent. -
answerBlocks(answer, limit)splits an answer into blocks by its shape alone:The answer Its blocks null, absent, [],{}, or a string that's empty or only white spacenone A string on one line, at most 280 characters; a number; a boolean one valueAny other string one textAn array of objects with only scalar values, and at most 12 different keys between them one records: the keys in the order they first appear are its columns, and a missing key or null is an empty cellAn object a block for each key, in key order, as below Anything else one textof its JSONIn an object, the value-sized scalars (a string
valuewould take, a number, a boolean, null) make one untitledfieldsblock, at the place of the first one, with null as an empty value. A longer string, an array that makesrecords, and an object of value-sized scalars are each a block of their own, titled with their key. Anything deeper is atextblock of its JSON, indented by two spaces. So{ answer: "<a long, many-line text>", confidence: "high" }is atextblock titledanswer, then afieldsblock withconfidence: high. -
A
text,fieldsorrecordsblock islongpast 1,200 drawn characters, 12 fields or 10 rows, whichever comes first. A place draws a long block folded, with a way to show all of it. -
Every string a block draws counts toward
limit, in UTF-16 units: its title, each field's name and value, each column name and cell, and its text. The block that crosses the limit is cut there, the blocks after it are left out, andtruncatedis true. A cut never ends in half a character. The console draws up toRESULT_LIMIT(100,000), and a chat up to 8,000. -
A block's text is the answer's words as they are: markdown isn't turned into headings, lists or tables. Draw it as text (
textContent), or with a markdown renderer that never passes HTML through; never as HTML. -
RUN_STATUS_WORDSis a run's status in words:Status Words pendingWaiting to start runningRunning suspendedWaiting completedDone failedFailed cancelledCancelled -
clipText(text, limit)cuts a text atlimitUTF-16 units, never in half a character.
In a chat, kindgi.run_state's result and an agent or flow tool's result
carry the answer's blocks, within 8,000 characters, in
_meta["kindgi/blocks"], an AnswerBlocks. That's for the run view to
draw. MCP Apps keeps _meta out of a model's context, so a model doesn't
get the answer twice. When a result comes without _meta, the run view
shows the answer as one text. The
result's structuredContent and its text keep the answer as one string, as
an agent output to treat as data.
Development
Section titled “Development”pnpm --filter @kindgi/api build # compile TS + emit distpnpm --filter @kindgi/api typecheck # no-emit typecheckpnpm --filter @kindgi/api test # vitest runpnpm --filter @kindgi/api gen:openapi # regenerate packages/api/openapi.jsongen:openapi documents the /v1/* surface only. The /s3/* surface
follows the S3 wire (XML, AWS-native SDKs) and is intentionally NOT
in the OpenAPI document — consumers use their own S3 SDKs pointed at
the mount.
Adapters (production-readiness plug-ins)
Section titled “Adapters (production-readiness plug-ins)”createApp(...) bindings are caller-plugged so this package can stay
free of persistence choices. The Kindgi runtime ships production
implementations (e.g. a Postgres-backed idempotencyStore whose retries
survive restarts and multi-instance deployments, filesystem and object-store
blobStorage). This package includes createInMemoryIdempotencyStore(),
which is correct for dev + tests.
See also
Section titled “See also”docs/API-ROUTE-CONVENTIONS.md— locked URL / auth / error-envelope / pagination / SSE conventions for/v1/*.docs/ADDING-A-ROUTE.md— how to add a new/v1/*route.