fix(v2-api): close three secret disclosures, make the surface consistent, and align docs with signatures (#6560)

* fix(v2-api): close two secret disclosures and align docs with signatures

Two P0 disclosures, five correctness bugs, and the standardization and
guard work that came out of auditing them.

**Secret disclosure — workflow version state.** `GET /api/v2/workflows/{id}/
versions/{version}` served the deployed graph unsanitized, so a read-role
workspace API key received plaintext block-password values and OAuth
credential ids. The sibling export route has always sanitized. Every other v2
response is protected structurally because the builder re-parses it, but this
field is `z.custom<WorkflowState>()` — a predicate that validates nothing —
which is why it survived earlier audits. Sanitization now lives in the use
case, secure by default, with a named `includeCredentialValues` opt-in that
only the session-authed deploy-preview route sets.

**Secret disclosure — MCP headers.** The internal list and update routes
returned custom `Authorization` headers verbatim to any read-role member;
headers are stored unencrypted. Values are now gated on write permission and
projected through one shared helper. The settings UI genuinely prefills from
them, so blanking outright would wipe headers on unrelated edits — write-only
headers plus encryption at rest are the follow-up.

Correctness:
- v2 execute ignored `X-Sim-Via`, resetting the call chain on every hop and
  defeating the recursion guard. Wired on both the keyed and anonymous paths.
- v2 knowledge search accepted `searchMode` and dropped it, silently serving
  vector-only results for a hybrid request, and allowed 50MB bodies where
  internal caps at 2MiB.
- v2 run cancel never released the plan concurrency slot and half-cancelled
  group runs; a group conflict now returns 409 instead of reporting success.
- v2 table row writes stamped no secret provenance, so the next internal read
  reported the whole page incomplete. `secretProvenance` is now required on
  the primitives, making the next omission a compile error.
- Folder conflicts and malformed paths returned 500; they are 409/404/400 now.
  `FolderPathError` splits from `FolderHierarchyError` so a corrupt stored
  tree stays a 500 and stays in 5xx alerting.

Standardization and documentation:
- `PUT /files/{id}/share` -> PATCH. The resource is not round-trippable
  (`hasPassword`, never the password), so merge-on-omission is the only
  implementable semantics.
- ~40 spec truthfulness fixes: a 410 the API cannot emit, eight 423s with no
  lock guard, ~30 reachable-but-undocumented 404/400/413s, and six inverted
  field claims. Eleven operations that always reject a workspace key now say
  so — four of them answer 404, so a workspace key was told the resource did
  not exist.
- `NAME_PATTERN` lost its `/i` through `z.toJSONSchema`, publishing 15
  patterns that reject names the runtime accepts. Every generated client
  rejected any capitalized table or column name, and two of the spec's own
  examples failed the spec's own schema.

Guards, so these classes cannot recur:
- `check:route-verbs` (new) cross-checks all 212 builder routes' exported verb
  and path against their contract. The builders only compare at runtime, so a
  half-done rename previously passed CI and 500'd in production.
- Example validation now runs against the published JSON Schema with formats
  on, covering 225 nodes instead of 100 — this is what caught the regex bug.
- The list-pagination sweep is union-aware and fails loudly on a schema it
  cannot introspect, rather than counting it compliant.

* refactor(v2-api)!: flatten the single-resource response envelope

BREAKING: 31 endpoints that returned `{ data: { <resource>: T } }` now return
`{ data: T }`.

This corrects drift, not a design decision. PR #5273 added skills, custom
tools, MCP servers, secrets, and knowledge nested while adding workflows,
files, and logs flat — and in the same commit wrote the `v2/shared.ts`
docblock declaring `single resource: { data: T }` is the standard. The nested
half appears to have been modelled on the v2 tables surface (#6067), which
landed twelve days earlier. Lists were already `{ data: T[], nextCursor }`, so
flat single-resource is what actually matches them; nesting made every client
destructure a layer that carries nothing.

Doing it now because the cost only grows: `v2-api` is still dark-launched, so
today this breaks no one. After GA it needs a deprecation window.

Payloads that carry real information were deliberately left alone — this was a
classification exercise, not a mechanical sweep. Unchanged: delete
acknowledgements (`{ id, deleted }`, `{ path, deleted, deletedItems }`), the
knowledge search envelope (which echoes query, knowledgeBaseIds, topK and
totalResults alongside hits), upload payloads carrying signed tokens and
transfer instructions, bulk-operation counts, `{ row, operation }` upserts,
named acknowledgement scalars (`{ dispatchId }`, `{ cancelled }`), and
`{ columns: [...] }` — a collection, where a bare `{ data: T[] }` would be
indistinguishable from the list envelope but without `nextCursor`.

Also flattened the two file-share responses, which were not in the original
survey: leaving them would have put one resource in two shapes on one path.
`GET /files/{id}/share` now returns `{ "data": null }` when a file has never
been shared.

No consumer is affected. Both SDKs touch exactly two v2 endpoints — execute
and run status — and both were already flat. No docs MDX, client hook, or
internal caller reads a changed response; Copilot table tools call the
application use cases directly rather than the HTTP surface.

The shared `v2FolderSchema` is untouched: every folder flatten was achievable
at the response site, which is itself evidence flat was the intended shape.

* fix(v2-api): close a third secret disclosure and make concealment coherent

**Secret disclosure — run snapshot.** `GET /api/v2/logs/{runId}` returned
`workflowState` straight from `workflowExecutionSnapshots.stateData`, which is
the workflow graph: `blocks[].subBlocks[].value` holds `password: true` field
values and `oauth-input` credential ids. Nothing on that path sanitized it, and
the field was typed `z.unknown()`, so the builder's response parse stripped
nothing. A read-role workspace API key could read plaintext credentials.

This is the third instance of one pattern, and the pattern is the finding: the
builder protects every response by re-parsing it, so the only fields that can
leak are the ones typed `z.unknown()` or `z.custom()`. Both prior disclosures
sat behind exactly such a field. The snapshot is now sanitized in the use case
and the field is typed object-or-null. An inventory of every remaining
`z.unknown()` in the v2 contracts is in the PR description; two carry data with
no projection behind them and are named there as follow-ups.

**Concealment was bypassable.** `createV2ResourceConcealmentPolicy` rewrites
resource-authorization failures to 404 so a caller cannot probe for existence.
Workflows and files applied it on every verb; tables and knowledge applied it
only on reads. A caller could therefore probe with PATCH, read the 403, and
learn the resource exists — the read-side concealment bought nothing. Nine
mutation sites now conceal, plus the three table-column verbs, which were
inconsistent with their own sibling sub-resources.

`lib/logs/api/route-policies.ts` was a second, divergent implementation that
sniffed `response.status === 403` and so also swallowed workspace-policy
denials the canonical helper deliberately preserves. It now uses the helper. A
third such sniff survives in the upload-control helper and is noted as a
follow-up.

Also:
- `DELETE /tables/{tableId}/rows/{rowId}` returned the bulk `{deletedCount,
  deletedRowIds}` shape while nine sibling single-resource deletes return
  `{id, deleted}`. It now matches them.
- Nine operations can 404 on an unknown folder path and did not document it;
  `createWorkflow` could 413 on an oversized folder tree and did not; getting a
  run can 409 when trace data was truncated and did not.
- `queryTableRows` documented a 413 it cannot emit and `resumeWorkflowRun` a
  423 with no lock guard anywhere in its path — the same un-producible-status
  class already cleared for 410 elsewhere.
- Execute's 409 description covered only the run-id case after the
  recursion-guard fix added a second cause, and named a code the route does not
  emit: the wire carries `error.code: CONFLICT` with the specific cause in
  `error.details.code`. `x-sim-via` is now a declared request header.
- Deploy and rollback published examples that were impossible: `isDeployed:
  true` beside `activeDeployment: null`, where the route computes the former
  from the latter.
- `afterRowId`/`beforeRowId` were published on row insert and silently dropped
  by the route, so a positional insert became a tail append.
- A generated document whose script fails permanently answered "still being
  generated, try again" forever; the underlying cause is now preserved.

* docs(v2-api): correct eleven false or misleading spec claims

Structural parity between contracts and specs is CI-enforced; semantic truth is
not. These are claims the spec made that the code does not honour.

Outright false:
- `DELETE /files/{fileId}` said it deletes "the stored bytes". It archives:
  the row is retained with a deletion timestamp and the bytes are never
  removed. Restore exists, but only on the internal API, so the description now
  says so rather than implying v2 offers it.
- Execute documented `409 EXECUTION_ID_CONFLICT` in three places. The wire
  carries `error.code: CONFLICT` with `error.details.code: RUN_ID_CONFLICT`;
  only v1 ever emitted the documented string.
- The files spec claimed every endpoint uses the canonical envelopes while
  `GET /files/{fileId}` returns octet-stream.
- The shared timestamp rule justified itself with a rendering claim that is
  false — 29 bare-form sites publish `format: date-time` identically. The real
  difference is runtime validation, so the rule now says that. It was softened
  rather than enforced: responses are re-parsed, so adding `.datetime()` to a
  field whose producer can emit a non-ISO string turns a working read into a
  500, and that could not be proven for all 29 without a much larger audit.

Misleading:
- The billing ledger silently defaults to a 30-day window, so a client
  paginating to `nextCursor: null` believes it has the whole ledger.
- Deleting a connector-backed knowledge document does not delete its chunks —
  the row survives as excluded and the embeddings remain.
- `listTables` said "all tables"; it is keyset-paged with a default limit.
- `GET /files/{id}/share` omitted the `data: null` never-shared case its own
  schema and example already declare.
- The share PATCH matrix omitted two hard 400s, so following it literally
  against a never-shared file fails.
- Five knowledge operations render a canonical folder path back and can 413 on
  an oversized tree without carrying the sentence that says so.

Also: the upload-control helper was a third implementation of concealment by
sniffing `response.status === 403`, which masks workspace-policy denials the
canonical helper deliberately preserves. It now uses the shared policy, so
those denials keep their 403. And the shared docblock's search-field
enumeration was presented as exhaustive while omitting two lists, and its
error-envelope claim omitted the two upload data-plane routes that emit a bare
`{error: string}` — both now carry the carve-out the CI allowlist already had.

* test(v2-api): align upload concealment test with cross-tenant-only semantics

#6557 narrowed `createV2ResourceConcealmentPolicy` to conceal only the three
cross-tenant authorization classes, deliberately letting a same-workspace
policy denial keep its 403 so the caller learns why. My test predated that and
asserted a workspace-key denial was concealed as 404.

Split into two cases that pin the distinction rather than paper over it: a
cross-tenant reach conceals, a workspace-key policy denial does not.

* fix(v2-api): accept the redacting log status and envelope the knowledge-search 413

The v2 log presenters parsed status against a five-value enum, but the
execution logger persists a sixth, redacting, while a finished run's output
is scrubbed. Any such row failed the response parse; on the list route one
row 500'd the whole page. The enum is now derived from
PersistedWorkflowExecutionStatus with a compile-time exhaustiveness
assertion, so a future status is a type error rather than a production 500.

POST /api/v2/knowledge/search declared maxBodyBytes without
payloadTooLargeResponse, so its 413 returned a bare string instead of the v2
error envelope. It now matches the sibling deploy/rollback routes.

* fix(uploads): restore archive extraction folder parity

Archive extraction into workspace files/ was rewritten onto the authorized
application-operation boundary, and three behavioral regressions came with
that move. Together they broke every archive containing a subdirectory, and
100% of copilot extract() calls (materialize-file always passes
rootFolderSegments: [baseName], and its catch only handles ArchiveError).

1. Non-canonical folder path. The extractor joined the folder segments with
   "/" and passed the result as `path` to createWorkspaceFileFolderOperation.
   That path reaches requireNonRootFolderPath -> parseFolderPath, which
   requires a leading "/" and byte-for-byte canonical per-segment encoding,
   so "bundle/data" threw FolderPathError before anything was written — and
   a folder name containing a space or a reserved character would still have
   thrown after merely prefixing a slash.

2. exactName: true. createWorkspaceFileFromBuffer was told to demand the
   exact leaf name, which sets maxAttempts = 1 and raises FileConflictError
   when the name already exists. The extractor's rollback then deleted every
   file written so far, so one colliding name destroyed the whole
   extraction. Reachable today for flat archives through the unzip action of
   POST /api/tools/file/manage. Restored to auto-suffixing via
   allocateUniqueWorkspaceFileName.

3. Wrong folder primitive. createWorkspaceFileFolderAtPath creates exactly
   one leaf, conflicts on an existing path, and requires the parent to exist
   already. The extractor never creates intermediates and caches by full
   path, so the first nested entry asked for a folder whose parent was never
   created. The correct semantics are ensureWorkspaceFileFolderPath: walk
   every segment, reuse what exists, create only what is missing.

Rather than bypass the operation boundary by calling the manager primitive
directly, this adds ensureWorkspaceFileFolderPathOperation — an authorized
application use case under files.folders.create that expresses "ensure this
whole chain exists" — and routes the extractor through it with raw decoded
segments, so no path string is built and no encoding can be malformed.

archive.test.ts previously mocked the folder operation and asserted the
broken shape (path: 'bundle'), which is why this shipped. The suite now
fakes the workspace-file store in memory while enforcing the real rules:
folder paths run through the production parseFolderPath family, the
create-one-leaf operation conflicts and requires a parent, and exactName
governs conflict vs auto-suffix. Nested, reuse, encoded-name, and collision
cases are covered and each fails against the pre-fix code.

* chore(files): tidy archive extraction cleanup

* fix(uploads): roll back folders archive extraction created

Extraction now materializes folders before uploading files, but the failure
path only deleted the extracted files — every folder the call created was left
behind. That is not cosmetic: `materialize_file` guards re-extraction by looking
up the root folder path and refusing when it has any child, so a half-extracted
nested archive turned every retry into "already extracted — delete that folder
first" until a human cleaned up the tree by hand.

The rollback must delete only folders this call actually inserted, never one it
reused: extracting into an existing path is normal (a sibling entry, an earlier
successful extraction), and deleting a pre-existing folder would destroy
unrelated user data. `ensureWorkspaceFileFolderPath` already distinguishes the
two while walking the segment chain, so it (and its application operation) now
reports `createdFolderIds` alongside the leaf id. The extractor accumulates
those ids in creation order and, on failure, deletes them in reverse — parents
are recorded before their children, so reverse order is deepest-first and a
parent is never removed out from under a child. Folder cleanup is best-effort
like the existing file cleanup, so a cleanup failure never masks the original
error.

* fix(billing): withhold the payer credit pool from v2 status readers

`GET /api/v2/billing/status` resolved the workspace's payer and projected
that payer's pooled allowances — credits used, credit limit, credits
remaining, and the payer entity's storage usage and quota — to any caller
holding only `read` on the workspace, including a personal API key. The
payer pool is shared across every workspace that payer funds, and the
platform already treats it as privileged: the workspace credit-availability
surface computes `canViewPayerPool` from `canManageWorkspaceBilling` and
substitutes member-scoped or null figures for everyone else. The new
versioned endpoint had no equivalent gate.

`credits` and `storage` are now projected only to a caller who may manage
the resolved payer's billing: the billed account holder of a personally
hosted workspace, an admin of the hosting organization, or a workspace API
key, which only a workspace admin can provision. The endpoint stays at
`read` so a plain member keeps the plan, period, and standing the workspace
UI already shows them, and an exceeded pooled limit still reports as
`limit_exceeded` without disclosing the numbers behind it. Both fields are
nullable on the wire and in the regenerated OpenAPI spec.

The decision lives in the application use case, resolved from canonical
workspace state, not in the route: billing authority is payer identity and
organization role, which the workspace permission ladder cannot express —
a plain workspace `admin` is deliberately not enough.

* chore(api): remove the unused public API route builder and dead endpoint labels

`withPublicApiRouteHandler` and 27 `ApiEndpoint` union members landed together
in #5273, but the v2 surface shipped on `defineV2JsonRoute` + `v2RateLimits`
instead. The builder had no production caller — only its own test — and the v2
rate limiter never reads an `ApiEndpoint` label, so those members were never
emitted to telemetry by symbol or by string literal.

Remaining members are exactly the labels a v1 route passes to `checkRateLimit`
or `authenticateRequest`. Drops the now-unreachable `hasZodUsage` branch from
the API validation audit; no ratchet metric moves (route total stays 1093).

* fix(billing): deny the payer pool to actor-less workspace API keys

The first pass gated `credits` and `storage` on billing authority for
personal API keys but let a `workspace_api_key` principal through
unconditionally, which left the excluded role a way back in. Any workspace
`admin` may mint a workspace API key, and a workspace `admin` is
deliberately not a billing manager, so an admin who reads `null` as
themselves could mint a key and read the full pool with it. On an
organization-hosted workspace that pool is the organization's, spanning
workspaces the admin has no standing in.

Billing authority is payer identity or an organization admin role — a
property of a person. A workspace API key is deliberately actor-less, so it
can never satisfy it and now reads both fields as `null`. Attributing the
key to its creator was rejected: it would launder the same workspace-admin
role, it breaks when the creator's authority is revoked while the key lives
on, and substituting a key's owner for the acting principal is what the
application operation boundary forbids. The reasoning sits in TSDoc at the
decision point.

The key keeps the plan, period, and standing it needs to monitor a
workspace, including `limit_exceeded` and `billing_blocked`. No in-repo
caller reads `credits` or `storage` from this endpoint. The payer storage
pool is now read only once disclosure is authorized, so a caller who may
not see it no longer triggers the query at all.

* fix(folders): bound the workflow folderId-branch path index reads

`createWorkflow` and `updateWorkflow` each resolve a folder two ways inside one
function. The folderPath branch goes through `resolveWorkflowFolderPath`, which
loads the path index with `maxRows: MAX_FOLDERS_PER_WORKSPACE`; the folderId
branch loaded it with no bound at all, issuing a `SELECT` over every active
folder row in the workspace. In `updateWorkflow` the unbounded read and the
bounded fallback sit thirty lines apart in the same function.

Passes the cap at both sites, matching the read sites that already opt in.
Exceeding it throws `FolderCollectionLimitExceededError` rather than truncating,
because a partial path index resolves real folder paths to `undefined` and
re-roots resources at the workspace root.

`maxRows` deliberately stays opt-in rather than becoming the default. Folder
creation does not refuse at the same ceiling on every path — `POST /api/folders`
goes through the `createFolder` name/parentId variant, which passes no
`maxFolderRows`, so the count guard in `executeCreateFolderAtPath` never runs
and a workspace can already hold more than `MAX_FOLDERS_PER_WORKSPACE` folders.
Defaulting the bound would make every path-index consumer throw for a state the
product allows to exist. Reconciling reader and writer is a separate change with
a user-facing limit, not a chore.

* chore(billing): tidy payer-pool concealment cleanup

* fix(api): reject an undecodable offset cursor on v2 table rows

GET /api/v2/tables/{tableId}/rows coerced an undecodable pagination cursor to
offset 0 and re-served page one. A client paging forward reads that as a fresh
first page and can loop over it forever. Every sibling v2 cursor list — logs,
files, workflows, workflow runs, workflow versions, workspace members, tables,
knowledge documents — already rejects with a validation error instead.

Extracts the offset-cursor decode both offset-paginated v2 routes had inlined
into `decodeOffsetCursor`, next to the existing `decodeSortedCursor`, so the
reject-don't-restart rule has one home.

* fix(api): restore v1 table error-response parity and stop internal message leak

The v1 table routes were rewritten to consume `lib/table/orchestration`
results, and two response behaviors drifted from what the live API returned.

Information disclosure: an unclassified failure's `outcome.error` carries
whatever text the fault happened to have. Drizzle wraps a throw raised inside
a transaction in an error whose own message is the failed statement and its
bound parameters, so `DELETE /api/v1/tables/{tableId}` and
`DELETE /api/v1/tables/{tableId}/rows/{rowId}` returned that verbatim in the
500 body to any API-key holder. Previously these returned a fixed generic
string.

Lost `lock` field: the 423 body used to be `{ error, lock }`. The delete,
row-delete, and column-update routes (v1 and internal) dropped the lock kind
the orchestration result already computes, leaving clients unable to tell
which lock to clear.

Both are fixed at one altitude: `orchestrationOutcomeErrorResponse` in
`app/api/table/utils.ts` is now the only way a table route projects an
orchestration failure onto the wire. It renders the route's fallback for an
unclassified failure and the real message for a classified one (validation,
not-found, conflict, locked keep their specific text), and carries `lock` on a
423. A future route cannot reintroduce either bug by hand-spelling the body.

Duplicate table names on `POST /api/v1/tables` keep answering 409 rather than
reverting to the previous 400. 409 is the correct semantic, and every other v1
duplicate-name surface (knowledge, files, workflow import) already answers 409;
the tables 400 was the outlier. v1 tables appears in no published OpenAPI
document and no in-repo client branches on the status, so the compatibility
cost is limited to a caller matching 400 specifically for a name collision.

* fix(skills): only reject a built-in name collision on an actual rename

The built-in-name guard ran on every update that carried a `name`, without
comparing it to the skill's current persisted name. Skills created before the
guard existed can legitimately carry a built-in's name (they simply shadowed
the built-in at read time), and the skill modal always submits the full object
including the unchanged name — so every save of such a skill returned 400 with
"The skill name ... is reserved by a built-in skill", with no way to fix it
short of renaming.

Move the guard in `updateSkill` to after the canonical row is loaded and run it
only when the submitted name differs from the current one. Creating a skill
with a built-in name, and renaming an existing skill into one, are still
rejected. The check stays in the shared orchestration primitive because that is
the only layer both the internal `/api/skills` adapter (via `performUpdateSkill`)
and `updateSkillUseCase` (v2 + Copilot) pass through, and it is where the
current name is in hand.

* chore(tables): tidy v1 error projection cleanup

* chore(skills): tidy collision guard cleanup
This commit is contained in:
Waleed
2026-08-11 16:41:27 -07:00
committed by GitHub
parent 3595fa2b6d
commit 9b9f4ee596
153 changed files with 5556 additions and 2543 deletions
+78 -46
View File
@@ -36,7 +36,7 @@
"get": {
"operationId": "getBillingStatus",
"summary": "Get Billing Status",
"description": "Return the current plan, billing standing, credit allowance, and storage quota. Billing history lives at `GET /api/v2/billing/logs`.",
"description": "Return the current plan, billing standing, credit allowance, and storage quota. `credits` and `storage` report the payer's pooled allowances and are null unless the caller can manage that payer's billing; they are always null for a workspace API key. Billing history lives at `GET /api/v2/billing/logs`. Without a Stripe subscription — notably on the free plan — there is no real billing period: `period` is the open interval 1970-01-01 to 9999-12-31 and `credits.used` is lifetime consumption, not consumption since a period start.",
"tags": ["Billing"],
"parameters": [
{
@@ -46,7 +46,8 @@
"description": "Workspace whose payer should be resolved. Workspace API keys are pinned to their own workspace.",
"schema": {
"description": "Workspace whose payer should be resolved. Workspace API keys are pinned to their own workspace.",
"type": "string"
"type": "string",
"minLength": 1
}
}
],
@@ -81,6 +82,9 @@
"403": {
"$ref": "#/components/responses/Forbidden"
},
"404": {
"$ref": "#/components/responses/NotFound"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -97,7 +101,7 @@
"get": {
"operationId": "listBillingLogs",
"summary": "List Billing Logs",
"description": "List the credit-denominated billing ledger with source filtering and opaque cursor pagination.",
"description": "List the credit-denominated billing ledger with source filtering and opaque cursor pagination. `period` defaults to `30d`, so an unqualified request covers only the last 30 days: paginating to `nextCursor: null` exhausts that window, not the whole ledger. Pass `period=all` for full history, or `period=custom` with `startDate` and `endDate` for a specific range.",
"tags": ["Billing"],
"parameters": [
{
@@ -128,7 +132,8 @@
"description": "Restrict results to one workspace whose payer the caller can inspect.",
"schema": {
"description": "Restrict results to one workspace whose payer the caller can inspect.",
"type": "string"
"type": "string",
"minLength": 1
}
},
{
@@ -221,6 +226,9 @@
"403": {
"$ref": "#/components/responses/Forbidden"
},
"404": {
"$ref": "#/components/responses/NotFound"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -240,7 +248,7 @@
"type": "apiKey",
"in": "header",
"name": "X-API-Key",
"description": "Your Sim API key (personal or workspace). Generate one from the Sim dashboard under Settings > API Keys."
"description": "Your Sim API key, personal or workspace-scoped. Generate one from the Sim dashboard under Settings > API Keys. A workspace API key is not accepted everywhere: operations that act on behalf of a specific human — administrative reads, secret access, and irreversible or governance-affecting writes — always reject it, whatever role the key carries. Each such operation says so in its own description, and the rejection surfaces as `403` unless the operation conceals unauthorized resources, in which case it is reported as `404`. Use a personal API key for those."
}
},
"headers": {
@@ -356,7 +364,7 @@
}
},
"RunIdConflict": {
"description": "The run identifier is already associated with a different request.",
"description": "The run cannot be started. Two causes share this status, distinguished by `error.details.code`: `RUN_ID_CONFLICT` when the supplied `X-Run-Id` is already associated with a different request, and `CALL_CHAIN_DEPTH_EXCEEDED` when the incoming `X-Sim-Via` chain has already reached the maximum workflow-to-workflow call depth.",
"headers": {
"X-Run-Id": {
"$ref": "#/components/headers/X-Run-Id"
@@ -381,7 +389,7 @@
}
},
"PayloadTooLarge": {
"description": "The request body exceeds the allowed size.",
"description": "The request, or a resource collection it must materialize, exceeds the allowed size. Besides an oversized request body, this covers a generated artifact that renders past the download ceiling and a workspace folder tree too large to load in full.",
"content": {
"application/json": {
"schema": {
@@ -425,6 +433,16 @@
}
}
},
"ClientClosedRequest": {
"description": "The client closed the connection before the response was produced.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/V2Error"
}
}
}
},
"InternalError": {
"description": "An unexpected server error occurred.",
"content": {
@@ -502,18 +520,18 @@
"properties": {
"start": {
"type": "string",
"description": "ISO 8601 start of the current billing period.",
"description": "ISO 8601 start of the current billing period, or 1970-01-01T00:00:00.000Z when no Stripe subscription defines one.",
"format": "date-time"
},
"end": {
"type": "string",
"description": "ISO 8601 end of the current billing period.",
"description": "ISO 8601 end of the current billing period, or 9999-12-31T00:00:00.000Z when no Stripe subscription defines one.",
"format": "date-time"
}
},
"required": ["start", "end"],
"additionalProperties": false,
"description": "Current billing period."
"description": "Current billing period. Only a Stripe subscription defines a real period; without one — notably on the free plan — this is the open interval 1970-01-01 to 9999-12-31 and must not be read as a monthly window."
},
"plan": {
"type": "string",
@@ -525,47 +543,61 @@
"description": "Current billing standing."
},
"credits": {
"type": "object",
"properties": {
"used": {
"type": "number",
"description": "Credits consumed during the current billing period."
"anyOf": [
{
"type": "object",
"properties": {
"used": {
"type": "number",
"description": "Credits consumed so far. The counter is reset by Stripe invoice webhooks, so on a paid plan it covers the current billing period; on the free plan nothing resets it and the value is lifetime consumption."
},
"limit": {
"type": "number",
"description": "Credit allowance for the reporting window — per billing period on a paid plan, lifetime on the free plan."
},
"remaining": {
"type": "number",
"description": "Allowance minus consumption, over the same window."
}
},
"required": ["used", "limit", "remaining"],
"additionalProperties": false
},
"limit": {
"type": "number",
"description": "Credit allowance for the current billing period."
},
"remaining": {
"type": "number",
"description": "Credits remaining in the current billing period."
{
"type": "null"
}
},
"required": ["used", "limit", "remaining"],
"additionalProperties": false,
"description": "Credit usage and allowance for the current billing period."
],
"description": "The payer's credit usage and allowance — periodic on a paid plan, lifetime on the free plan, where the counter never resets. Null when the caller cannot manage that payer's billing. Always null for a workspace API key."
},
"storage": {
"type": "object",
"properties": {
"usedBytes": {
"type": "number",
"minimum": 0,
"description": "Storage currently consumed, in bytes."
"anyOf": [
{
"type": "object",
"properties": {
"usedBytes": {
"type": "number",
"minimum": 0,
"description": "Storage currently consumed, in bytes."
},
"limitBytes": {
"type": "number",
"minimum": 0,
"description": "Storage quota, in bytes."
},
"percentUsed": {
"type": "number",
"minimum": 0,
"description": "Percentage of the storage quota consumed."
}
},
"required": ["usedBytes", "limitBytes", "percentUsed"],
"additionalProperties": false
},
"limitBytes": {
"type": "number",
"minimum": 0,
"description": "Storage quota, in bytes."
},
"percentUsed": {
"type": "number",
"minimum": 0,
"description": "Percentage of the storage quota consumed."
{
"type": "null"
}
},
"required": ["usedBytes", "limitBytes", "percentUsed"],
"additionalProperties": false,
"description": "Current storage consumption and quota."
],
"description": "The payer's storage consumption and quota, or null when the caller cannot manage that payer's billing. Always null for a workspace API key."
}
},
"required": ["workspaceId", "period", "plan", "status", "credits", "storage"],
@@ -717,7 +749,7 @@
"type": "null"
}
],
"description": "Opaque cursor for the next page, or null when no more items remain."
"description": "Opaque cursor for the next page, or null when no more items remain. Always null on a full-set list, which returns its whole result set in one response."
}
},
"required": ["data", "nextCursor"],
+67 -93
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "Sim API v2 — Files & Audit Logs",
"description": "Version 2 of the Sim REST API for workspace files and organization audit logs. Every endpoint uses the canonical v2 data, cursor-list, and error envelopes. Lists use opaque cursors, and rate-limit state is returned in response headers.",
"description": "Version 2 of the Sim REST API for workspace files and organization audit logs. Lists use opaque cursors, and rate-limit state is returned in response headers. Download File streams raw bytes as `application/octet-stream`; every other response uses the canonical v2 data, cursor-list, or error envelope.",
"version": "2.0.0",
"contact": {
"name": "Sim Support",
@@ -154,6 +154,9 @@
"403": {
"$ref": "#/components/responses/Forbidden"
},
"404": {
"$ref": "#/components/responses/NotFound"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -281,6 +284,9 @@
"403": {
"$ref": "#/components/responses/Forbidden"
},
"404": {
"$ref": "#/components/responses/NotFound"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -356,6 +362,9 @@
}
}
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
@@ -658,7 +667,7 @@
"delete": {
"operationId": "deleteFile",
"summary": "Delete File",
"description": "Delete a workspace file and its stored bytes.",
"description": "Archive a workspace file. This is a soft delete: the row is retained with a deletion timestamp, the file stops appearing in listings and is no longer readable through the API, and its stored bytes are never removed. An archived file can be restored from the workspace Recently Deleted settings; the v2 API exposes no restore operation.",
"tags": ["Files"],
"parameters": [
{
@@ -896,7 +905,7 @@
"get": {
"operationId": "listAuditLogs",
"summary": "List Audit Logs",
"description": "List an organization audit trail with filters and opaque cursor pagination. Requires an Enterprise subscription and organization admin or owner access.",
"description": "List an organization audit trail with filters and opaque cursor pagination. Requires an Enterprise subscription and organization admin or owner access. A workspace API key cannot call this operation and is rejected with `403`; use a personal API key.",
"tags": ["Audit Logs"],
"parameters": [
{
@@ -1065,7 +1074,7 @@
"get": {
"operationId": "getAuditLog",
"summary": "Get Audit Log",
"description": "Return one organization audit-log entry. Requires an Enterprise subscription and organization admin or owner access.",
"description": "Return one organization audit-log entry. Requires an Enterprise subscription and organization admin or owner access. A workspace API key cannot call this operation and is rejected with `403`; use a personal API key.",
"tags": ["Audit Logs"],
"parameters": [
{
@@ -1113,6 +1122,9 @@
}
}
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
@@ -1204,7 +1216,7 @@
"get": {
"operationId": "getFileShare",
"summary": "Get File Share",
"description": "Return the current public-share configuration for a file.",
"description": "Return the nullable current public-share configuration for a file. A file that has never been shared returns `data: null` rather than a 404; a share that was created and later disabled is still returned, with `isActive: false`.",
"tags": ["Files"],
"parameters": [
{
@@ -1277,10 +1289,10 @@
}
}
},
"put": {
"patch": {
"operationId": "upsertFileShare",
"summary": "Enable or Disable File Share",
"description": "Create or update a server-tokenized public share. Disabling retains its token and configuration for later re-enablement.",
"description": "Create or partially update a server-tokenized public share. Only isActive is required, and an omitted authType keeps the stored auth mode. What happens to password and allowedEmails depends on the resulting mode, because enabling a share always rewrites the credentials the chosen mode does not use: 'public' clears the stored password and empties allowedEmails; 'password' keeps the stored password when password is omitted but empties allowedEmails; 'email' and 'sso' clear the stored password and keep the stored allowedEmails when the field is omitted. Only disabling with isActive false preserves the whole access configuration untouched — it also retains the token, so re-enabling restores the share as it was. Two enabling combinations are rejected outright with a 400 instead of being partially applied: 'password' when neither a password is supplied nor one is already stored, and 'email' or 'sso' when the resulting allowedEmails would be empty because none was supplied and none is stored. On a file that has never been shared there is nothing stored to fall back on, so enabling any mode other than 'public' must carry its credential in the same request. A workspace API key cannot call this operation. Because unauthorized resources are concealed, the rejection is reported as `404` rather than `403`; use a personal API key.",
"tags": ["Files"],
"parameters": [
{
@@ -1505,7 +1517,7 @@
"get": {
"operationId": "listFilesFolders",
"summary": "List Folders",
"description": "List workspace file folders with optional parent-path filtering and sorting.",
"description": "List workspace file folders with optional parent-path filtering and sorting. The bounded set is returned in one page with `nextCursor` always null; there is no second page to fetch.",
"tags": ["Files"],
"parameters": [
{
@@ -1600,9 +1612,6 @@
"404": {
"$ref": "#/components/responses/NotFound"
},
"409": {
"$ref": "#/components/responses/Conflict"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -1631,7 +1640,7 @@
}
},
"responses": {
"200": {
"201": {
"description": "The created folder.",
"headers": {
"X-RateLimit-Limit": {
@@ -1837,7 +1846,7 @@
"type": "apiKey",
"in": "header",
"name": "X-API-Key",
"description": "Your Sim API key (personal or workspace). Generate one from the Sim dashboard under Settings > API Keys."
"description": "Your Sim API key, personal or workspace-scoped. Generate one from the Sim dashboard under Settings > API Keys. A workspace API key is not accepted everywhere: operations that act on behalf of a specific human — administrative reads, secret access, and irreversible or governance-affecting writes — always reject it, whatever role the key carries. Each such operation says so in its own description, and the rejection surfaces as `403` unless the operation conceals unauthorized resources, in which case it is reported as `404`. Use a personal API key for those."
}
},
"headers": {
@@ -1978,7 +1987,7 @@
}
},
"RunIdConflict": {
"description": "The run identifier is already associated with a different request.",
"description": "The run cannot be started. Two causes share this status, distinguished by `error.details.code`: `RUN_ID_CONFLICT` when the supplied `X-Run-Id` is already associated with a different request, and `CALL_CHAIN_DEPTH_EXCEEDED` when the incoming `X-Sim-Via` chain has already reached the maximum workflow-to-workflow call depth.",
"headers": {
"X-Run-Id": {
"$ref": "#/components/headers/X-Run-Id"
@@ -2003,7 +2012,7 @@
}
},
"PayloadTooLarge": {
"description": "The request body exceeds the allowed size.",
"description": "The request, or a resource collection it must materialize, exceeds the allowed size. Besides an oversized request body, this covers a generated artifact that renders past the download ceiling and a workspace folder tree too large to load in full.",
"content": {
"application/json": {
"schema": {
@@ -2047,6 +2056,16 @@
}
}
},
"ClientClosedRequest": {
"description": "The client closed the connection before the response was produced.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/V2Error"
}
}
}
},
"InternalError": {
"description": "An unexpected server error occurred.",
"content": {
@@ -2121,12 +2140,12 @@
"size": {
"type": "number",
"minimum": 0,
"description": "File size in bytes.",
"description": "Size in bytes of the stored file. For a generated document (docx, pptx, pdf, xlsx) the stored file is the generation source rather than the rendered document, so this does not predict how many bytes `GET /files/{fileId}` returns — that endpoint serves the compiled artifact, which is typically much larger.",
"examples": [1024]
},
"type": {
"type": "string",
"description": "MIME type of the file.",
"description": "MIME type of the stored file. For a generated document (docx, pptx, pdf, xlsx) the stored file is the generation source, so this describes the source and not what `GET /files/{fileId}` serves — that endpoint returns the compiled artifact under the rendered document type.",
"examples": ["text/csv"]
},
"key": {
@@ -2192,7 +2211,7 @@
"type": "null"
}
],
"description": "Opaque cursor for the next page, or null when no more items remain."
"description": "Opaque cursor for the next page, or null when no more items remain. Always null on a full-set list, which returns its whole result set in one response."
}
},
"required": ["data", "nextCursor"],
@@ -2272,7 +2291,7 @@
},
"content": {
"default": "",
"description": "Initial file content. Omit or send an empty string for a zero-byte file.",
"description": "Initial file content. Omit or send an empty string for a zero-byte file. The 70,000,000-character bound is a JSON-envelope guard, not the file-size limit: the decoded bytes must be at most 50 MiB, so a longer base64 payload is admitted here and then rejected with 413. Use an upload session for anything larger.",
"type": "string",
"maxLength": 70000000
},
@@ -2731,12 +2750,12 @@
"size": {
"type": "number",
"minimum": 0,
"description": "File size in bytes.",
"description": "Size in bytes of the stored file. For a generated document (docx, pptx, pdf, xlsx) the stored file is the generation source rather than the rendered document, so this does not predict how many bytes `GET /files/{fileId}` returns — that endpoint serves the compiled artifact, which is typically much larger.",
"examples": [1024]
},
"type": {
"type": "string",
"description": "MIME type of the file.",
"description": "MIME type of the stored file. For a generated document (docx, pptx, pdf, xlsx) the stored file is the generation source, so this describes the source and not what `GET /files/{fileId}` serves — that endpoint returns the compiled artifact under the rendered document type.",
"examples": ["text/csv"]
},
"key": {
@@ -2980,7 +2999,7 @@
"type": "null"
}
],
"description": "Opaque cursor for the next page, or null when no more items remain."
"description": "Opaque cursor for the next page, or null when no more items remain. Always null on a full-set list, which returns its whole result set in one response."
}
},
"required": ["data", "nextCursor"],
@@ -3117,10 +3136,10 @@
"title": "Move files request",
"description": "Files and destination selected for a bulk move."
},
"V2GetFileShareResult": {
"V2GetFileShareResponse": {
"type": "object",
"properties": {
"share": {
"data": {
"anyOf": [
{
"$ref": "#/components/schemas/V2FileShare"
@@ -3129,20 +3148,7 @@
"type": "null"
}
],
"description": "Current public share, or null when the file has never been shared."
}
},
"required": ["share"],
"additionalProperties": false,
"title": "File share result",
"description": "The nullable public-share state for a file."
},
"V2GetFileShareResponse": {
"type": "object",
"properties": {
"data": {
"description": "Response data.",
"$ref": "#/components/schemas/V2GetFileShareResult"
"description": "Response data."
}
},
"required": ["data"],
@@ -3152,45 +3158,28 @@
"examples": [
{
"data": {
"share": {
"id": "shr_8Hf3kL9wQ2mNpXr6Tz1Vb",
"token": "share-token-example",
"url": "https://www.sim.ai/f/share-token-example",
"isActive": true,
"resourceType": "file",
"resourceId": "wf_V1StGXR8z5jdHi6BmyT91",
"authType": "public",
"hasPassword": false,
"allowedEmails": []
}
"id": "shr_8Hf3kL9wQ2mNpXr6Tz1Vb",
"token": "share-token-example",
"url": "https://www.sim.ai/f/share-token-example",
"isActive": true,
"resourceType": "file",
"resourceId": "wf_V1StGXR8z5jdHi6BmyT91",
"authType": "public",
"hasPassword": false,
"allowedEmails": []
}
},
{
"data": {
"share": null
}
"data": null
}
]
},
"V2UpsertFileShareResult": {
"type": "object",
"properties": {
"share": {
"description": "Updated public share.",
"$ref": "#/components/schemas/V2FileShare"
}
},
"required": ["share"],
"additionalProperties": false,
"title": "Updated file share",
"description": "The updated public-share state for a file."
},
"V2UpsertFileShareResponse": {
"type": "object",
"properties": {
"data": {
"description": "Response data.",
"$ref": "#/components/schemas/V2UpsertFileShareResult"
"$ref": "#/components/schemas/V2FileShare"
}
},
"required": ["data"],
@@ -3200,17 +3189,15 @@
"examples": [
{
"data": {
"share": {
"id": "shr_8Hf3kL9wQ2mNpXr6Tz1Vb",
"token": "share-token-example",
"url": "https://www.sim.ai/f/share-token-example",
"isActive": true,
"resourceType": "file",
"resourceId": "wf_V1StGXR8z5jdHi6BmyT91",
"authType": "public",
"hasPassword": false,
"allowedEmails": []
}
"id": "shr_8Hf3kL9wQ2mNpXr6Tz1Vb",
"token": "share-token-example",
"url": "https://www.sim.ai/f/share-token-example",
"isActive": true,
"resourceType": "file",
"resourceId": "wf_V1StGXR8z5jdHi6BmyT91",
"authType": "public",
"hasPassword": false,
"allowedEmails": []
}
}
]
@@ -3276,7 +3263,7 @@
"content": {
"type": "string",
"maxLength": 70000000,
"description": "Complete replacement content for the file."
"description": "Complete replacement content for the file. The 70,000,000-character bound is a JSON-envelope guard, not the file-size limit: the decoded bytes must be at most 50 MiB, so a longer base64 payload is admitted here and then rejected with 413."
},
"encoding": {
"default": "utf-8",
@@ -3421,7 +3408,7 @@
"type": "null"
}
],
"description": "Opaque cursor for the next page, or null when no more items remain."
"description": "Opaque cursor for the next page, or null when no more items remain. Always null on a full-set list, which returns its whole result set in one response."
}
},
"required": ["data", "nextCursor"],
@@ -3429,25 +3416,12 @@
"title": "File folder list response",
"description": "Workspace file folders in the current page."
},
"V2FileFolderData": {
"type": "object",
"properties": {
"folder": {
"description": "Created or relocated folder.",
"$ref": "#/components/schemas/V2Folder"
}
},
"required": ["folder"],
"additionalProperties": false,
"title": "File folder data",
"description": "A created or relocated file folder."
},
"FileFolderResponse": {
"type": "object",
"properties": {
"data": {
"description": "Response data.",
"$ref": "#/components/schemas/V2FileFolderData"
"$ref": "#/components/schemas/V2Folder"
}
},
"required": ["data"],
+65 -73
View File
@@ -36,7 +36,7 @@
"get": {
"operationId": "listKnowledgeBases",
"summary": "List Knowledge Bases",
"description": "List knowledge bases in a workspace with folder filtering, search, sorting, and the canonical cursor envelope.",
"description": "List knowledge bases in a workspace with folder filtering, search, sorting, and the canonical cursor envelope. The bounded workspace set is returned in one page with `nextCursor` always null; there is no second page to fetch. An unknown `folderPath` is a 404. A workspace whose folder tree exceeds 10,000 folders is a 413, because the response needs the whole tree to render folder paths.",
"tags": ["Knowledge Bases"],
"parameters": [
{
@@ -128,6 +128,12 @@
"403": {
"$ref": "#/components/responses/Forbidden"
},
"404": {
"$ref": "#/components/responses/NotFound"
},
"413": {
"$ref": "#/components/responses/PayloadTooLarge"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -142,7 +148,7 @@
"post": {
"operationId": "createKnowledgeBase",
"summary": "Create Knowledge Base",
"description": "Create a knowledge base in a workspace with optional folder placement and chunking configuration.",
"description": "Create a knowledge base in a workspace with optional folder placement and chunking configuration. An unknown `folderPath` is a 404. A workspace whose folder tree exceeds 10,000 folders is a 413, because the response needs the whole tree to render folder paths.",
"tags": ["Knowledge Bases"],
"requestBody": {
"required": true,
@@ -186,6 +192,9 @@
"403": {
"$ref": "#/components/responses/Forbidden"
},
"404": {
"$ref": "#/components/responses/NotFound"
},
"409": {
"$ref": "#/components/responses/Conflict"
},
@@ -208,7 +217,7 @@
"get": {
"operationId": "getKnowledgeBase",
"summary": "Get Knowledge Base",
"description": "Retrieve a knowledge base by identifier. Inaccessible knowledge bases are reported as not found.",
"description": "Retrieve a knowledge base by identifier. Inaccessible knowledge bases are reported as not found. A workspace whose folder tree exceeds 10,000 folders is a 413, because the response needs the whole tree to render folder paths.",
"tags": ["Knowledge Bases"],
"parameters": [
{
@@ -256,12 +265,18 @@
}
}
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
"404": {
"$ref": "#/components/responses/NotFound"
},
"413": {
"$ref": "#/components/responses/PayloadTooLarge"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -276,7 +291,7 @@
"patch": {
"operationId": "updateKnowledgeBase",
"summary": "Update Knowledge Base",
"description": "Update a knowledge base name, description, chunking configuration, or folder placement.",
"description": "Update a knowledge base name, description, chunking configuration, or folder placement. A workspace whose folder tree exceeds 10,000 folders is a 413, because the response needs the whole tree to render folder paths.",
"tags": ["Knowledge Bases"],
"parameters": [
{
@@ -339,6 +354,9 @@
"409": {
"$ref": "#/components/responses/Conflict"
},
"413": {
"$ref": "#/components/responses/PayloadTooLarge"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -621,6 +639,9 @@
}
}
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
@@ -1123,9 +1144,6 @@
"409": {
"$ref": "#/components/responses/Conflict"
},
"413": {
"$ref": "#/components/responses/PayloadTooLarge"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -1201,6 +1219,9 @@
}
}
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
@@ -1221,7 +1242,7 @@
"delete": {
"operationId": "deleteKnowledgeDocument",
"summary": "Delete Document",
"description": "Delete one document and its indexed chunks from a knowledge base.",
"description": "Remove one document from a knowledge base. What that means depends on the document. A directly uploaded document is deleted outright along with its indexed chunks. A connector-backed document is instead excluded: its row survives, marked excluded and disabled so it stops being searchable and a later connector sync does not re-add it, and its embeddings are not deleted. Either way the document no longer appears in listings or search results.",
"tags": ["Knowledge Bases"],
"parameters": [
{
@@ -1308,7 +1329,7 @@
"get": {
"operationId": "listKnowledgeFolders",
"summary": "List Folders",
"description": "List folders in the knowledge-base folder tree with filtering and sorting.",
"description": "List folders in the knowledge-base folder tree with filtering and sorting. The bounded set is returned in one page with `nextCursor` always null; there is no second page to fetch. A workspace whose folder tree exceeds 10,000 folders is a 413, because the response needs the whole tree to render folder paths.",
"tags": ["Knowledge Bases"],
"parameters": [
{
@@ -1403,8 +1424,8 @@
"404": {
"$ref": "#/components/responses/NotFound"
},
"409": {
"$ref": "#/components/responses/Conflict"
"413": {
"$ref": "#/components/responses/PayloadTooLarge"
},
"429": {
"$ref": "#/components/responses/RateLimited"
@@ -1420,7 +1441,7 @@
"post": {
"operationId": "createKnowledgeFolder",
"summary": "Create Folder",
"description": "Create a folder in the knowledge-base folder tree.",
"description": "Create a folder in the knowledge-base folder tree. A workspace whose folder tree exceeds 10,000 folders is a 413, because the response needs the whole tree to render folder paths.",
"tags": ["Knowledge Bases"],
"requestBody": {
"required": true,
@@ -1470,6 +1491,9 @@
"409": {
"$ref": "#/components/responses/Conflict"
},
"413": {
"$ref": "#/components/responses/PayloadTooLarge"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -1484,7 +1508,7 @@
"patch": {
"operationId": "relocateKnowledgeFolder",
"summary": "Rename or Move Folder",
"description": "Rename or move a folder and atomically rewrite descendant paths.",
"description": "Rename or move a folder and atomically rewrite descendant paths. A workspace whose folder tree exceeds 10,000 folders is a 413, because the response needs the whole tree to render folder paths.",
"tags": ["Knowledge Bases"],
"requestBody": {
"required": true,
@@ -1534,6 +1558,9 @@
"409": {
"$ref": "#/components/responses/Conflict"
},
"413": {
"$ref": "#/components/responses/PayloadTooLarge"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -1621,6 +1648,9 @@
"409": {
"$ref": "#/components/responses/Conflict"
},
"413": {
"$ref": "#/components/responses/PayloadTooLarge"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -1640,7 +1670,7 @@
"type": "apiKey",
"in": "header",
"name": "X-API-Key",
"description": "Your Sim API key (personal or workspace). Generate one from the Sim dashboard under Settings > API Keys."
"description": "Your Sim API key, personal or workspace-scoped. Generate one from the Sim dashboard under Settings > API Keys. A workspace API key is not accepted everywhere: operations that act on behalf of a specific human — administrative reads, secret access, and irreversible or governance-affecting writes — always reject it, whatever role the key carries. Each such operation says so in its own description, and the rejection surfaces as `403` unless the operation conceals unauthorized resources, in which case it is reported as `404`. Use a personal API key for those."
}
},
"headers": {
@@ -1756,7 +1786,7 @@
}
},
"RunIdConflict": {
"description": "The run identifier is already associated with a different request.",
"description": "The run cannot be started. Two causes share this status, distinguished by `error.details.code`: `RUN_ID_CONFLICT` when the supplied `X-Run-Id` is already associated with a different request, and `CALL_CHAIN_DEPTH_EXCEEDED` when the incoming `X-Sim-Via` chain has already reached the maximum workflow-to-workflow call depth.",
"headers": {
"X-Run-Id": {
"$ref": "#/components/headers/X-Run-Id"
@@ -1781,7 +1811,7 @@
}
},
"PayloadTooLarge": {
"description": "The request body exceeds the allowed size.",
"description": "The request, or a resource collection it must materialize, exceeds the allowed size. Besides an oversized request body, this covers a generated artifact that renders past the download ceiling and a workspace folder tree too large to load in full.",
"content": {
"application/json": {
"schema": {
@@ -1825,6 +1855,16 @@
}
}
},
"ClientClosedRequest": {
"description": "The client closed the connection before the response was produced.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/V2Error"
}
}
}
},
"InternalError": {
"description": "An unexpected server error occurred.",
"content": {
@@ -2059,7 +2099,7 @@
"type": "null"
}
],
"description": "Opaque cursor for the next page, or null when no more items remain."
"description": "Opaque cursor for the next page, or null when no more items remain. Always null on a full-set list, which returns its whole result set in one response."
}
},
"required": ["data", "nextCursor"],
@@ -2067,24 +2107,12 @@
"title": "Knowledge base list response",
"description": "A cursor-paginated page of knowledge bases."
},
"V2KnowledgeBaseData": {
"type": "object",
"properties": {
"knowledgeBase": {
"$ref": "#/components/schemas/V2KnowledgeBase"
}
},
"required": ["knowledgeBase"],
"additionalProperties": false,
"title": "Knowledge base data",
"description": "A single knowledge base payload."
},
"V2KnowledgeBaseResponse": {
"type": "object",
"properties": {
"data": {
"description": "Response data.",
"$ref": "#/components/schemas/V2KnowledgeBaseData"
"$ref": "#/components/schemas/V2KnowledgeBase"
}
},
"required": ["data"],
@@ -2448,13 +2476,13 @@
},
"topK": {
"default": 10,
"description": "Maximum number of search results to return.",
"description": "Maximum number of search results to return. Must be a whole number between 1 and 100; the boundary schema only bounds the range, so a fractional value is admitted here and then rejected with 400 during search.",
"type": "number",
"minimum": 1,
"maximum": 100
},
"tagFilters": {
"description": "Structured tag filters; supported only for one knowledge base.",
"description": "Structured tag filters. Supported across multiple knowledge bases, but each filtered tag must resolve to the same slot and field type in every knowledge base selected; a tag missing from one of them, or defined inconsistently across them, is rejected and those knowledge bases must be searched separately. With a single knowledge base, an unknown tag name is simply ignored.",
"type": "array",
"items": {
"$ref": "#/components/schemas/V2KnowledgeSearchTagFilter"
@@ -2582,7 +2610,7 @@
"type": "null"
}
],
"description": "Opaque cursor for the next page, or null when no more items remain."
"description": "Opaque cursor for the next page, or null when no more items remain. Always null on a full-set list, which returns its whole result set in one response."
}
},
"required": ["data", "nextCursor"],
@@ -2590,24 +2618,12 @@
"title": "Knowledge document list response",
"description": "A cursor-paginated page of knowledge documents."
},
"V2KnowledgeDocumentSummaryData": {
"type": "object",
"properties": {
"document": {
"$ref": "#/components/schemas/V2KnowledgeDocumentSummary"
}
},
"required": ["document"],
"additionalProperties": false,
"title": "Knowledge document summary data",
"description": "A knowledge document upload acknowledgement."
},
"V2KnowledgeDocumentSummaryResponse": {
"type": "object",
"properties": {
"data": {
"description": "Response data.",
"$ref": "#/components/schemas/V2KnowledgeDocumentSummaryData"
"$ref": "#/components/schemas/V2KnowledgeDocumentSummary"
}
},
"required": ["data"],
@@ -3176,24 +3192,12 @@
"title": "Knowledge document",
"description": "Full document detail including processing state and connector provenance."
},
"V2KnowledgeDocumentData": {
"type": "object",
"properties": {
"document": {
"$ref": "#/components/schemas/V2KnowledgeDocument"
}
},
"required": ["document"],
"additionalProperties": false,
"title": "Knowledge document data",
"description": "A single knowledge document payload."
},
"V2KnowledgeDocumentResponse": {
"type": "object",
"properties": {
"data": {
"description": "Response data.",
"$ref": "#/components/schemas/V2KnowledgeDocumentData"
"$ref": "#/components/schemas/V2KnowledgeDocument"
}
},
"required": ["data"],
@@ -3251,7 +3255,7 @@
"type": "null"
}
],
"description": "Opaque cursor for the next page, or null when no more items remain."
"description": "Opaque cursor for the next page, or null when no more items remain. Always null on a full-set list, which returns its whole result set in one response."
}
},
"required": ["data", "nextCursor"],
@@ -3259,24 +3263,12 @@
"title": "Knowledge folder list response",
"description": "A cursor-paginated page of knowledge-base folders."
},
"V2KnowledgeFolderData": {
"type": "object",
"properties": {
"folder": {
"$ref": "#/components/schemas/V2Folder"
}
},
"required": ["folder"],
"additionalProperties": false,
"title": "Knowledge folder data",
"description": "A single knowledge-base folder payload."
},
"V2KnowledgeFolderResponse": {
"type": "object",
"properties": {
"data": {
"description": "Response data.",
"$ref": "#/components/schemas/V2KnowledgeFolderData"
"$ref": "#/components/schemas/V2Folder"
}
},
"required": ["data"],
+54 -15
View File
@@ -36,7 +36,7 @@
"get": {
"operationId": "listLogs",
"summary": "List Logs",
"description": "List workflow execution logs for a workspace with filters, selectable detail, and opaque cursor pagination.",
"description": "List workflow execution logs for a workspace with filters, selectable detail, and opaque cursor pagination. This list predates the shared sort convention: it has no `sortBy` (the sort column is fixed to execution start time) and spells the direction `order` rather than `sortOrder`. Trace spans are stored separately from the log row and are pruned on their own retention schedule: `includeTraceSpans=true` on a run whose stored spans have aged out returns `traceSpans: []` rather than an error, so an empty array does not mean the run recorded no spans.",
"tags": ["Logs"],
"parameters": [
{
@@ -269,6 +269,9 @@
"403": {
"$ref": "#/components/responses/Forbidden"
},
"404": {
"$ref": "#/components/responses/NotFound"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -285,7 +288,7 @@
"get": {
"operationId": "getLog",
"summary": "Get Log",
"description": "Retrieve the diagnostic representation of a run, including its workflow snapshot, trace spans, final output, and cost.",
"description": "Retrieve the diagnostic representation of a run, including its workflow snapshot, trace spans, final output, and cost. The returned `workflowState` snapshot has credential values redacted: OAuth credential references and secret (`password`) sub-block values are null, while `{{VAR}}` environment-variable references are preserved so consecutive snapshots stay diffable. Trace spans are stored separately from the log row and are pruned on their own retention schedule: a run whose stored spans have aged out returns `traceSpans: []` rather than an error, so an empty array does not mean the run recorded no spans.",
"tags": ["Logs"],
"parameters": [
{
@@ -353,7 +356,7 @@
"type": "apiKey",
"in": "header",
"name": "X-API-Key",
"description": "Your Sim API key (personal or workspace). Generate one from the Sim dashboard under Settings > API Keys."
"description": "Your Sim API key, personal or workspace-scoped. Generate one from the Sim dashboard under Settings > API Keys. A workspace API key is not accepted everywhere: operations that act on behalf of a specific human — administrative reads, secret access, and irreversible or governance-affecting writes — always reject it, whatever role the key carries. Each such operation says so in its own description, and the rejection surfaces as `403` unless the operation conceals unauthorized resources, in which case it is reported as `404`. Use a personal API key for those."
}
},
"headers": {
@@ -469,7 +472,7 @@
}
},
"RunIdConflict": {
"description": "The run identifier is already associated with a different request.",
"description": "The run cannot be started. Two causes share this status, distinguished by `error.details.code`: `RUN_ID_CONFLICT` when the supplied `X-Run-Id` is already associated with a different request, and `CALL_CHAIN_DEPTH_EXCEEDED` when the incoming `X-Sim-Via` chain has already reached the maximum workflow-to-workflow call depth.",
"headers": {
"X-Run-Id": {
"$ref": "#/components/headers/X-Run-Id"
@@ -494,7 +497,7 @@
}
},
"PayloadTooLarge": {
"description": "The request body exceeds the allowed size.",
"description": "The request, or a resource collection it must materialize, exceeds the allowed size. Besides an oversized request body, this covers a generated artifact that renders past the download ceiling and a workspace folder tree too large to load in full.",
"content": {
"application/json": {
"schema": {
@@ -538,6 +541,16 @@
}
}
},
"ClientClosedRequest": {
"description": "The client closed the connection before the response was produced.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/V2Error"
}
}
}
},
"InternalError": {
"description": "An unexpected server error occurred.",
"content": {
@@ -627,8 +640,8 @@
},
"status": {
"type": "string",
"enum": ["pending", "running", "completed", "failed", "cancelled"],
"description": "Current execution status."
"enum": ["pending", "running", "redacting", "completed", "failed", "cancelled"],
"description": "Current execution status. `redacting` is transient while run output is scrubbed."
},
"level": {
"type": "string",
@@ -640,12 +653,16 @@
},
"startedAt": {
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$",
"description": "ISO 8601 execution start timestamp."
},
"endedAt": {
"anyOf": [
{
"type": "string"
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$"
},
{
"type": "null"
@@ -950,7 +967,7 @@
"type": "null"
}
],
"description": "Opaque cursor for the next page, or null when no more items remain."
"description": "Opaque cursor for the next page, or null when no more items remain. Always null on a full-set list, which returns its whole result set in one response."
}
},
"required": ["data", "nextCursor"],
@@ -1011,8 +1028,8 @@
},
"status": {
"type": "string",
"enum": ["pending", "running", "completed", "failed", "cancelled"],
"description": "Current execution status."
"enum": ["pending", "running", "redacting", "completed", "failed", "cancelled"],
"description": "Current execution status. `redacting` is transient while run output is scrubbed."
},
"level": {
"type": "string",
@@ -1024,12 +1041,16 @@
},
"startedAt": {
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$",
"description": "ISO 8601 execution start timestamp."
},
"endedAt": {
"anyOf": [
{
"type": "string"
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$"
},
{
"type": "null"
@@ -1130,7 +1151,9 @@
"createdAt": {
"anyOf": [
{
"type": "string"
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$"
},
{
"type": "null"
@@ -1141,7 +1164,9 @@
"updatedAt": {
"anyOf": [
{
"type": "string"
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$"
},
{
"type": "null"
@@ -1169,7 +1194,19 @@
"description": "Workflow snapshot associated with the execution."
},
"workflowState": {
"description": "Workflow state snapshot captured for the run."
"anyOf": [
{
"type": "object",
"properties": {},
"additionalProperties": {
"description": "One top-level snapshot section — `blocks`, `edges`, `loops`, `parallels`, or `variables` — passed through as stored."
}
},
{
"type": "null"
}
],
"description": "Workflow graph snapshot captured for the run, with credential values redacted: `oauth-input` values and `password: true` sub-block values are null, while `{{VAR}}` environment-variable references are preserved. Null when no snapshot is retained."
},
"traceSpans": {
"type": "array",
@@ -1210,6 +1247,8 @@
},
"createdAt": {
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$",
"description": "ISO 8601 log creation timestamp."
}
},
+256 -263
View File
@@ -210,7 +210,7 @@
"get": {
"operationId": "listMcpServers",
"summary": "List MCP Servers",
"description": "List MCP servers registered in a workspace. Request-header values and OAuth client secrets are never returned. The bounded workspace set uses the standard cursor envelope with `nextCursor` set to null.",
"description": "List MCP servers registered in a workspace. Request-header values and OAuth client secrets are never returned. The bounded workspace set uses the standard cursor envelope with `nextCursor` always null; there is no second page to fetch.",
"tags": ["MCP Servers"],
"parameters": [
{
@@ -292,6 +292,9 @@
"403": {
"$ref": "#/components/responses/Forbidden"
},
"404": {
"$ref": "#/components/responses/NotFound"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -306,7 +309,7 @@
"post": {
"operationId": "createMcpServer",
"summary": "Create MCP Server",
"description": "Register an MCP server in a workspace. The endpoint URL determines server identity, must be absolute HTTP or HTTPS, and cannot contain environment-variable references. Header values and OAuth client secrets are write-only.",
"description": "Register an MCP server in a workspace. The endpoint URL determines server identity, must be absolute HTTP or HTTPS, and cannot contain environment-variable references. Header values and OAuth client secrets are write-only. `transport`, `timeout`, `retries`, and `enabled` are applied server-side when omitted; the effective values are in the response.",
"tags": ["MCP Servers"],
"requestBody": {
"required": true,
@@ -350,6 +353,9 @@
"403": {
"$ref": "#/components/responses/Forbidden"
},
"404": {
"$ref": "#/components/responses/NotFound"
},
"409": {
"$ref": "#/components/responses/Conflict"
},
@@ -443,7 +449,7 @@
"patch": {
"operationId": "updateMcpServer",
"summary": "Update MCP Server",
"description": "Update the supplied MCP server fields. The URL is immutable because it determines server identity; delete and recreate the server to change endpoints. Authentication changes invalidate the existing OAuth grant.",
"description": "Update the supplied MCP server fields. The URL is immutable because it determines server identity; delete and recreate the server to change endpoints. Two fields do not follow the omitted-fields-are-retained rule. `headers` is replaced wholesale rather than merged: sending it drops every stored header it does not repeat, and the only way to keep a header is to resend it. Changing `oauthClientId`, or sending `oauthClientSecret` as null or a new value, revokes the stored OAuth grant and forces reauthorization; switching away from OAuth authentication revokes it too.",
"tags": ["MCP Servers"],
"parameters": [
{
@@ -593,7 +599,7 @@
"get": {
"operationId": "listSkills",
"summary": "List Skills",
"description": "List workspace and built-in skills. Built-ins are marked read-only. The list omits skill bodies and uses the standard cursor envelope with `nextCursor` set to null; fetch one skill to read its content.",
"description": "List workspace and built-in skills. Built-ins are marked read-only. The list omits skill bodies and uses the standard cursor envelope with `nextCursor` always null, so there is no second page to fetch; fetch one skill to read its content.",
"tags": ["Skills"],
"parameters": [
{
@@ -675,6 +681,9 @@
"403": {
"$ref": "#/components/responses/Forbidden"
},
"404": {
"$ref": "#/components/responses/NotFound"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -689,7 +698,7 @@
"post": {
"operationId": "createSkill",
"summary": "Create Skill",
"description": "Create one skill in a workspace. Its kebab-case name must be unique and cannot be reserved by a built-in skill.",
"description": "Create one skill in a workspace. Its kebab-case name must be unique and cannot be reserved by a built-in skill. Note that a workspace API key may create a skill but may not later update or delete it.",
"tags": ["Skills"],
"requestBody": {
"required": true,
@@ -733,6 +742,9 @@
"403": {
"$ref": "#/components/responses/Forbidden"
},
"404": {
"$ref": "#/components/responses/NotFound"
},
"409": {
"$ref": "#/components/responses/Conflict"
},
@@ -826,7 +838,7 @@
"patch": {
"operationId": "updateSkill",
"summary": "Update Skill",
"description": "Update the supplied fields on a workspace skill. Omitted fields retain their stored values. Built-in skills are read-only.",
"description": "Update the supplied fields on a workspace skill. Omitted fields retain their stored values. Built-in skills are read-only. A workspace API key cannot call this operation and is rejected with `403`; use a personal API key.",
"tags": ["Skills"],
"parameters": [
{
@@ -903,7 +915,7 @@
"delete": {
"operationId": "deleteSkill",
"summary": "Delete Skill",
"description": "Delete a workspace skill. Built-in skills are read-only and cannot be deleted.",
"description": "Delete a workspace skill. Built-in skills are read-only and cannot be deleted. A workspace API key cannot call this operation and is rejected with `403`; use a personal API key.",
"tags": ["Skills"],
"parameters": [
{
@@ -979,7 +991,7 @@
"get": {
"operationId": "listCustomTools",
"summary": "List Custom Tools",
"description": "List code-backed custom tools defined in a workspace. Legacy personal tools are excluded. The bounded workspace set uses the standard cursor envelope with `nextCursor` set to null.",
"description": "List code-backed custom tools defined in a workspace. Legacy personal tools are excluded. The bounded workspace set uses the standard cursor envelope with `nextCursor` always null; there is no second page to fetch.",
"tags": ["Custom Tools"],
"parameters": [
{
@@ -1061,6 +1073,9 @@
"403": {
"$ref": "#/components/responses/Forbidden"
},
"404": {
"$ref": "#/components/responses/NotFound"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -1119,6 +1134,9 @@
"403": {
"$ref": "#/components/responses/Forbidden"
},
"404": {
"$ref": "#/components/responses/NotFound"
},
"409": {
"$ref": "#/components/responses/Conflict"
},
@@ -1365,7 +1383,7 @@
"get": {
"operationId": "listCredentials",
"summary": "List Credentials",
"description": "List OAuth and service-account connections visible to the caller. Secret material is never returned. Credential mutations and single-resource reads are intentionally not exposed.",
"description": "List OAuth and service-account connections visible to the caller. Secret material is never returned. Credential mutations and single-resource reads are intentionally not exposed. The bounded set uses the standard cursor envelope with `nextCursor` always null; there is no second page to fetch.",
"tags": ["Credentials"],
"parameters": [
{
@@ -1469,6 +1487,9 @@
"403": {
"$ref": "#/components/responses/Forbidden"
},
"404": {
"$ref": "#/components/responses/NotFound"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -1485,7 +1506,7 @@
"get": {
"operationId": "listSecrets",
"summary": "List Secrets",
"description": "List workspace and caller-owned personal secret metadata. Only names, scope, role, and timestamps are returned; secret values are never read or returned.",
"description": "List workspace and caller-owned personal secret metadata. Only names, scope, role, and timestamps are returned; secret values are never read or returned. The bounded set uses the standard cursor envelope with `nextCursor` always null; there is no second page to fetch. A workspace API key cannot call this operation and is rejected with `403`; use a personal API key.",
"tags": ["Secrets"],
"parameters": [
{
@@ -1578,6 +1599,9 @@
"403": {
"$ref": "#/components/responses/Forbidden"
},
"404": {
"$ref": "#/components/responses/NotFound"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -1594,7 +1618,7 @@
"put": {
"operationId": "setSecret",
"summary": "Set Secret",
"description": "Create or replace a workspace or caller-owned personal secret. The value is encrypted at rest, is write-only, and is never included in the response.",
"description": "Create or replace a workspace or caller-owned personal secret. The value is encrypted at rest, is write-only, and is never included in the response. A workspace API key cannot call this operation and is rejected with `403`; use a personal API key.",
"tags": ["Secrets"],
"parameters": [
{
@@ -1674,6 +1698,9 @@
"403": {
"$ref": "#/components/responses/Forbidden"
},
"404": {
"$ref": "#/components/responses/NotFound"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -1688,7 +1715,7 @@
"delete": {
"operationId": "deleteSecret",
"summary": "Delete Secret",
"description": "Delete a workspace or caller-owned personal secret without reading or returning its stored value.",
"description": "Delete a workspace or caller-owned personal secret without reading or returning its stored value. A workspace API key cannot call this operation and is rejected with `403`; use a personal API key.",
"tags": ["Secrets"],
"parameters": [
{
@@ -1780,7 +1807,7 @@
"type": "apiKey",
"in": "header",
"name": "X-API-Key",
"description": "Your Sim API key (personal or workspace). Generate one from the Sim dashboard under Settings > API Keys."
"description": "Your Sim API key, personal or workspace-scoped. Generate one from the Sim dashboard under Settings > API Keys. A workspace API key is not accepted everywhere: operations that act on behalf of a specific human — administrative reads, secret access, and irreversible or governance-affecting writes — always reject it, whatever role the key carries. Each such operation says so in its own description, and the rejection surfaces as `403` unless the operation conceals unauthorized resources, in which case it is reported as `404`. Use a personal API key for those."
}
},
"headers": {
@@ -1896,7 +1923,7 @@
}
},
"RunIdConflict": {
"description": "The run identifier is already associated with a different request.",
"description": "The run cannot be started. Two causes share this status, distinguished by `error.details.code`: `RUN_ID_CONFLICT` when the supplied `X-Run-Id` is already associated with a different request, and `CALL_CHAIN_DEPTH_EXCEEDED` when the incoming `X-Sim-Via` chain has already reached the maximum workflow-to-workflow call depth.",
"headers": {
"X-Run-Id": {
"$ref": "#/components/headers/X-Run-Id"
@@ -1921,7 +1948,7 @@
}
},
"PayloadTooLarge": {
"description": "The request body exceeds the allowed size.",
"description": "The request, or a resource collection it must materialize, exceeds the allowed size. Besides an oversized request body, this covers a generated artifact that renders past the download ceiling and a workspace folder tree too large to load in full.",
"content": {
"application/json": {
"schema": {
@@ -1965,6 +1992,16 @@
}
}
},
"ClientClosedRequest": {
"description": "The client closed the connection before the response was produced.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/V2Error"
}
}
}
},
"InternalError": {
"description": "An unexpected server error occurred.",
"content": {
@@ -2131,7 +2168,7 @@
},
"isExternal": {
"type": "boolean",
"description": "Whether access is inherited from outside the explicit workspace member list."
"description": "Whether the member belongs to a different organization than the workspace. True for an explicitly granted member whose own organization differs from the workspace's; false for the workspace owner and for a member sharing the workspace organization. Inherited organization-administrator access is always reported as false, so this is not a signal that access came from outside the explicit member list."
},
"joinedAt": {
"type": "string",
@@ -2164,7 +2201,7 @@
"type": "null"
}
],
"description": "Opaque cursor for the next page, or null when no more items remain."
"description": "Opaque cursor for the next page, or null when no more items remain. Always null on a full-set list, which returns its whole result set in one response."
}
},
"required": ["data", "nextCursor"],
@@ -2251,19 +2288,27 @@
},
"lastToolsRefresh": {
"description": "ISO 8601 timestamp of the most recent tool-list refresh.",
"type": "string"
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$"
},
"lastConnected": {
"description": "ISO 8601 timestamp of the most recent successful connection.",
"type": "string"
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$"
},
"createdAt": {
"description": "ISO 8601 timestamp when the server was registered.",
"type": "string"
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$"
},
"updatedAt": {
"description": "ISO 8601 timestamp when the server was last updated.",
"type": "string"
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$"
},
"oauthClientId": {
"description": "Pre-registered OAuth client identifier, when configured.",
@@ -2320,7 +2365,7 @@
"type": "null"
}
],
"description": "Opaque cursor for the next page, or null when no more items remain."
"description": "Opaque cursor for the next page, or null when no more items remain. Always null on a full-set list, which returns its whole result set in one response."
}
},
"required": ["data", "nextCursor"],
@@ -2356,25 +2401,12 @@
}
]
},
"V2McpServerData": {
"type": "object",
"properties": {
"mcpServer": {
"description": "The MCP server.",
"$ref": "#/components/schemas/V2McpServer"
}
},
"required": ["mcpServer"],
"additionalProperties": false,
"title": "MCP server data",
"description": "A single public MCP server payload."
},
"CreateMcpServerResponse": {
"type": "object",
"properties": {
"data": {
"description": "Response data.",
"$ref": "#/components/schemas/V2McpServerData"
"$ref": "#/components/schemas/V2McpServer"
}
},
"required": ["data"],
@@ -2384,27 +2416,25 @@
"examples": [
{
"data": {
"mcpServer": {
"id": "mcp-3f7a9c21",
"name": "Docs server",
"description": "Internal documentation tools",
"transport": "streamable-http",
"authType": "headers",
"url": "https://mcp.example.com/sse",
"timeout": 30000,
"retries": 3,
"enabled": true,
"connectionStatus": "connected",
"lastError": null,
"toolCount": 7,
"lastToolsRefresh": "2026-06-20T14:02:11.000Z",
"lastConnected": "2026-06-20T14:02:11.000Z",
"createdAt": "2026-06-01T09:14:00.000Z",
"updatedAt": "2026-06-20T14:02:11.000Z",
"hasHeaders": true,
"headerNames": ["Authorization"],
"hasOauthClientSecret": false
}
"id": "mcp-3f7a9c21",
"name": "Docs server",
"description": "Internal documentation tools",
"transport": "streamable-http",
"authType": "headers",
"url": "https://mcp.example.com/sse",
"timeout": 30000,
"retries": 3,
"enabled": true,
"connectionStatus": "connected",
"lastError": null,
"toolCount": 7,
"lastToolsRefresh": "2026-06-20T14:02:11.000Z",
"lastConnected": "2026-06-20T14:02:11.000Z",
"createdAt": "2026-06-01T09:14:00.000Z",
"updatedAt": "2026-06-20T14:02:11.000Z",
"hasHeaders": true,
"headerNames": ["Authorization"],
"hasOauthClientSecret": false
}
}
]
@@ -2429,7 +2459,8 @@
"maxLength": 2000
},
"transport": {
"description": "Transport used to communicate with the server. Defaults to `streamable-http`.",
"description": "Transport used to communicate with the server. Applied server-side as `streamable-http` when omitted on create.",
"default": "streamable-http",
"type": "string",
"enum": ["streamable-http"]
},
@@ -2458,19 +2489,22 @@
}
},
"timeout": {
"description": "Per-request timeout in milliseconds. Defaults to 30000.",
"description": "Per-request timeout in milliseconds. Applied server-side as 30000 when omitted on create.",
"default": 30000,
"type": "integer",
"minimum": 1000,
"maximum": 300000
},
"retries": {
"description": "Number of retries per request. Defaults to 3.",
"description": "Number of retries per request. Applied server-side as 3 when omitted on create.",
"default": 3,
"type": "integer",
"minimum": 0,
"maximum": 10
},
"enabled": {
"description": "Whether the server tools are available to workflows. Defaults to true.",
"description": "Whether the server tools are available to workflows. Applied server-side as true when omitted on create.",
"default": true,
"type": "boolean"
},
"oauthClientId": {
@@ -2520,7 +2554,7 @@
"properties": {
"data": {
"description": "Response data.",
"$ref": "#/components/schemas/V2McpServerData"
"$ref": "#/components/schemas/V2McpServer"
}
},
"required": ["data"],
@@ -2530,27 +2564,25 @@
"examples": [
{
"data": {
"mcpServer": {
"id": "mcp-3f7a9c21",
"name": "Docs server",
"description": "Internal documentation tools",
"transport": "streamable-http",
"authType": "headers",
"url": "https://mcp.example.com/sse",
"timeout": 30000,
"retries": 3,
"enabled": true,
"connectionStatus": "connected",
"lastError": null,
"toolCount": 7,
"lastToolsRefresh": "2026-06-20T14:02:11.000Z",
"lastConnected": "2026-06-20T14:02:11.000Z",
"createdAt": "2026-06-01T09:14:00.000Z",
"updatedAt": "2026-06-20T14:02:11.000Z",
"hasHeaders": true,
"headerNames": ["Authorization"],
"hasOauthClientSecret": false
}
"id": "mcp-3f7a9c21",
"name": "Docs server",
"description": "Internal documentation tools",
"transport": "streamable-http",
"authType": "headers",
"url": "https://mcp.example.com/sse",
"timeout": 30000,
"retries": 3,
"enabled": true,
"connectionStatus": "connected",
"lastError": null,
"toolCount": 7,
"lastToolsRefresh": "2026-06-20T14:02:11.000Z",
"lastConnected": "2026-06-20T14:02:11.000Z",
"createdAt": "2026-06-01T09:14:00.000Z",
"updatedAt": "2026-06-20T14:02:11.000Z",
"hasHeaders": true,
"headerNames": ["Authorization"],
"hasOauthClientSecret": false
}
}
]
@@ -2560,7 +2592,7 @@
"properties": {
"data": {
"description": "Response data.",
"$ref": "#/components/schemas/V2McpServerData"
"$ref": "#/components/schemas/V2McpServer"
}
},
"required": ["data"],
@@ -2570,27 +2602,25 @@
"examples": [
{
"data": {
"mcpServer": {
"id": "mcp-3f7a9c21",
"name": "Docs server",
"description": "Internal documentation tools",
"transport": "streamable-http",
"authType": "headers",
"url": "https://mcp.example.com/sse",
"timeout": 30000,
"retries": 3,
"enabled": false,
"connectionStatus": "connected",
"lastError": null,
"toolCount": 7,
"lastToolsRefresh": "2026-06-20T14:02:11.000Z",
"lastConnected": "2026-06-20T14:02:11.000Z",
"createdAt": "2026-06-01T09:14:00.000Z",
"updatedAt": "2026-06-20T14:02:11.000Z",
"hasHeaders": true,
"headerNames": ["Authorization"],
"hasOauthClientSecret": false
}
"id": "mcp-3f7a9c21",
"name": "Docs server",
"description": "Internal documentation tools",
"transport": "streamable-http",
"authType": "headers",
"url": "https://mcp.example.com/sse",
"timeout": 30000,
"retries": 3,
"enabled": false,
"connectionStatus": "connected",
"lastError": null,
"toolCount": 7,
"lastToolsRefresh": "2026-06-20T14:02:11.000Z",
"lastConnected": "2026-06-20T14:02:11.000Z",
"createdAt": "2026-06-01T09:14:00.000Z",
"updatedAt": "2026-06-20T14:02:11.000Z",
"hasHeaders": true,
"headerNames": ["Authorization"],
"hasOauthClientSecret": false
}
}
]
@@ -2615,7 +2645,8 @@
"maxLength": 2000
},
"transport": {
"description": "Transport used to communicate with the server. Defaults to `streamable-http`.",
"description": "Transport used to communicate with the server. Applied server-side as `streamable-http` when omitted on create.",
"default": "streamable-http",
"type": "string",
"enum": ["streamable-http"]
},
@@ -2644,19 +2675,22 @@
}
},
"timeout": {
"description": "Per-request timeout in milliseconds. Defaults to 30000.",
"description": "Per-request timeout in milliseconds. Applied server-side as 30000 when omitted on create.",
"default": 30000,
"type": "integer",
"minimum": 1000,
"maximum": 300000
},
"retries": {
"description": "Number of retries per request. Defaults to 3.",
"description": "Number of retries per request. Applied server-side as 3 when omitted on create.",
"default": 3,
"type": "integer",
"minimum": 0,
"maximum": 10
},
"enabled": {
"description": "Whether the server tools are available to workflows. Defaults to true.",
"description": "Whether the server tools are available to workflows. Applied server-side as true when omitted on create.",
"default": true,
"type": "boolean"
},
"oauthClientId": {
@@ -2756,11 +2790,15 @@
},
"createdAt": {
"type": "string",
"description": "ISO 8601 timestamp when the skill was created."
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$",
"description": "ISO 8601 timestamp when the skill was created. Built-in skills report the Unix epoch."
},
"updatedAt": {
"type": "string",
"description": "ISO 8601 timestamp when the skill was last updated."
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$",
"description": "ISO 8601 timestamp when the skill was last updated. Built-in skills report the Unix epoch."
}
},
"required": ["id", "name", "description", "readOnly", "createdAt", "updatedAt"],
@@ -2787,7 +2825,7 @@
"type": "null"
}
],
"description": "Opaque cursor for the next page, or null when no more items remain."
"description": "Opaque cursor for the next page, or null when no more items remain. Always null on a full-set list, which returns its whole result set in one response."
}
},
"required": ["data", "nextCursor"],
@@ -2831,11 +2869,15 @@
},
"createdAt": {
"type": "string",
"description": "ISO 8601 timestamp when the skill was created."
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$",
"description": "ISO 8601 timestamp when the skill was created. Built-in skills report the Unix epoch."
},
"updatedAt": {
"type": "string",
"description": "ISO 8601 timestamp when the skill was last updated."
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$",
"description": "ISO 8601 timestamp when the skill was last updated. Built-in skills report the Unix epoch."
},
"content": {
"type": "string",
@@ -2847,25 +2889,12 @@
"title": "Skill",
"description": "A workspace or built-in skill including its instruction body."
},
"V2SkillData": {
"type": "object",
"properties": {
"skill": {
"description": "The skill.",
"$ref": "#/components/schemas/V2Skill"
}
},
"required": ["skill"],
"additionalProperties": false,
"title": "Skill data",
"description": "A single skill payload including its instruction body."
},
"CreateSkillResponse": {
"type": "object",
"properties": {
"data": {
"description": "Response data.",
"$ref": "#/components/schemas/V2SkillData"
"$ref": "#/components/schemas/V2Skill"
}
},
"required": ["data"],
@@ -2875,15 +2904,13 @@
"examples": [
{
"data": {
"skill": {
"id": "V1StGXR8Z5jdHi6BmyT",
"name": "refund-policy",
"description": "How support should handle refund requests",
"readOnly": false,
"createdAt": "2026-06-01T09:14:00.000Z",
"updatedAt": "2026-06-20T14:02:11.000Z",
"content": "# Refund policy\n\nAlways check the order date first."
}
"id": "V1StGXR8Z5jdHi6BmyT",
"name": "refund-policy",
"description": "How support should handle refund requests",
"readOnly": false,
"createdAt": "2026-06-01T09:14:00.000Z",
"updatedAt": "2026-06-20T14:02:11.000Z",
"content": "# Refund policy\n\nAlways check the order date first."
}
}
]
@@ -2934,7 +2961,7 @@
"properties": {
"data": {
"description": "Response data.",
"$ref": "#/components/schemas/V2SkillData"
"$ref": "#/components/schemas/V2Skill"
}
},
"required": ["data"],
@@ -2944,15 +2971,13 @@
"examples": [
{
"data": {
"skill": {
"id": "V1StGXR8Z5jdHi6BmyT",
"name": "refund-policy",
"description": "How support should handle refund requests",
"readOnly": false,
"createdAt": "2026-06-01T09:14:00.000Z",
"updatedAt": "2026-06-20T14:02:11.000Z",
"content": "# Refund policy\n\nAlways check the order date first."
}
"id": "V1StGXR8Z5jdHi6BmyT",
"name": "refund-policy",
"description": "How support should handle refund requests",
"readOnly": false,
"createdAt": "2026-06-01T09:14:00.000Z",
"updatedAt": "2026-06-20T14:02:11.000Z",
"content": "# Refund policy\n\nAlways check the order date first."
}
}
]
@@ -2962,7 +2987,7 @@
"properties": {
"data": {
"description": "Response data.",
"$ref": "#/components/schemas/V2SkillData"
"$ref": "#/components/schemas/V2Skill"
}
},
"required": ["data"],
@@ -2972,15 +2997,13 @@
"examples": [
{
"data": {
"skill": {
"id": "V1StGXR8Z5jdHi6BmyT",
"name": "refund-policy",
"description": "Updated refund guidance",
"readOnly": false,
"createdAt": "2026-06-01T09:14:00.000Z",
"updatedAt": "2026-06-20T14:02:11.000Z",
"content": "# Refund policy\n\nAlways check the order date first."
}
"id": "V1StGXR8Z5jdHi6BmyT",
"name": "refund-policy",
"description": "Updated refund guidance",
"readOnly": false,
"createdAt": "2026-06-01T09:14:00.000Z",
"updatedAt": "2026-06-20T14:02:11.000Z",
"content": "# Refund policy\n\nAlways check the order date first."
}
}
]
@@ -3145,10 +3168,14 @@
},
"createdAt": {
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$",
"description": "ISO 8601 timestamp when the tool was created."
},
"updatedAt": {
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$",
"description": "ISO 8601 timestamp when the tool was last updated."
}
},
@@ -3176,7 +3203,7 @@
"type": "null"
}
],
"description": "Opaque cursor for the next page, or null when no more items remain."
"description": "Opaque cursor for the next page, or null when no more items remain. Always null on a full-set list, which returns its whole result set in one response."
}
},
"required": ["data", "nextCursor"],
@@ -3214,25 +3241,12 @@
}
]
},
"V2CustomToolData": {
"type": "object",
"properties": {
"customTool": {
"description": "The custom tool.",
"$ref": "#/components/schemas/V2CustomTool"
}
},
"required": ["customTool"],
"additionalProperties": false,
"title": "Custom tool data",
"description": "A single workspace custom tool payload."
},
"CreateCustomToolResponse": {
"type": "object",
"properties": {
"data": {
"description": "Response data.",
"$ref": "#/components/schemas/V2CustomToolData"
"$ref": "#/components/schemas/V2CustomTool"
}
},
"required": ["data"],
@@ -3242,29 +3256,27 @@
"examples": [
{
"data": {
"customTool": {
"id": "V1StGXR8Z5jdHi6BmyT",
"title": "lookup_order",
"schema": {
"type": "function",
"function": {
"name": "lookup_order",
"description": "Look up an order by id",
"parameters": {
"type": "object",
"properties": {
"orderId": {
"type": "string"
}
},
"required": ["orderId"]
}
"id": "V1StGXR8Z5jdHi6BmyT",
"title": "lookup_order",
"schema": {
"type": "function",
"function": {
"name": "lookup_order",
"description": "Look up an order by id",
"parameters": {
"type": "object",
"properties": {
"orderId": {
"type": "string"
}
},
"required": ["orderId"]
}
},
"code": "return { ok: true }",
"createdAt": "2026-06-01T09:14:00.000Z",
"updatedAt": "2026-06-20T14:02:11.000Z"
}
}
},
"code": "return { ok: true }",
"createdAt": "2026-06-01T09:14:00.000Z",
"updatedAt": "2026-06-20T14:02:11.000Z"
}
}
]
@@ -3387,7 +3399,7 @@
"properties": {
"data": {
"description": "Response data.",
"$ref": "#/components/schemas/V2CustomToolData"
"$ref": "#/components/schemas/V2CustomTool"
}
},
"required": ["data"],
@@ -3397,29 +3409,27 @@
"examples": [
{
"data": {
"customTool": {
"id": "V1StGXR8Z5jdHi6BmyT",
"title": "lookup_order",
"schema": {
"type": "function",
"function": {
"name": "lookup_order",
"description": "Look up an order by id",
"parameters": {
"type": "object",
"properties": {
"orderId": {
"type": "string"
}
},
"required": ["orderId"]
}
"id": "V1StGXR8Z5jdHi6BmyT",
"title": "lookup_order",
"schema": {
"type": "function",
"function": {
"name": "lookup_order",
"description": "Look up an order by id",
"parameters": {
"type": "object",
"properties": {
"orderId": {
"type": "string"
}
},
"required": ["orderId"]
}
},
"code": "return { ok: true }",
"createdAt": "2026-06-01T09:14:00.000Z",
"updatedAt": "2026-06-20T14:02:11.000Z"
}
}
},
"code": "return { ok: true }",
"createdAt": "2026-06-01T09:14:00.000Z",
"updatedAt": "2026-06-20T14:02:11.000Z"
}
}
]
@@ -3429,7 +3439,7 @@
"properties": {
"data": {
"description": "Response data.",
"$ref": "#/components/schemas/V2CustomToolData"
"$ref": "#/components/schemas/V2CustomTool"
}
},
"required": ["data"],
@@ -3439,29 +3449,27 @@
"examples": [
{
"data": {
"customTool": {
"id": "V1StGXR8Z5jdHi6BmyT",
"title": "lookup_order",
"schema": {
"type": "function",
"function": {
"name": "lookup_order",
"description": "Look up an order by id",
"parameters": {
"type": "object",
"properties": {
"orderId": {
"type": "string"
}
},
"required": ["orderId"]
}
"id": "V1StGXR8Z5jdHi6BmyT",
"title": "lookup_order",
"schema": {
"type": "function",
"function": {
"name": "lookup_order",
"description": "Look up an order by id",
"parameters": {
"type": "object",
"properties": {
"orderId": {
"type": "string"
}
},
"required": ["orderId"]
}
},
"code": "return { ok: false }",
"createdAt": "2026-06-01T09:14:00.000Z",
"updatedAt": "2026-06-20T14:02:11.000Z"
}
}
},
"code": "return { ok: false }",
"createdAt": "2026-06-01T09:14:00.000Z",
"updatedAt": "2026-06-20T14:02:11.000Z"
}
}
]
@@ -3707,7 +3715,7 @@
"type": "null"
}
],
"description": "Opaque cursor for the next page, or null when no more items remain."
"description": "Opaque cursor for the next page, or null when no more items remain. Always null on a full-set list, which returns its whole result set in one response."
}
},
"required": ["data", "nextCursor"],
@@ -3791,7 +3799,7 @@
"type": "null"
}
],
"description": "Opaque cursor for the next page, or null when no more items remain."
"description": "Opaque cursor for the next page, or null when no more items remain. Always null on a full-set list, which returns its whole result set in one response."
}
},
"required": ["data", "nextCursor"],
@@ -3813,25 +3821,12 @@
}
]
},
"V2SecretData": {
"type": "object",
"properties": {
"secret": {
"description": "Secret metadata. The stored value is never returned.",
"$ref": "#/components/schemas/V2Secret"
}
},
"required": ["secret"],
"additionalProperties": false,
"title": "Secret data",
"description": "A single secret-metadata payload without its stored value."
},
"SetSecretResponse": {
"type": "object",
"properties": {
"data": {
"description": "Response data.",
"$ref": "#/components/schemas/V2SecretData"
"$ref": "#/components/schemas/V2Secret"
}
},
"required": ["data"],
@@ -3841,13 +3836,11 @@
"examples": [
{
"data": {
"secret": {
"name": "STRIPE_API_KEY",
"scope": "workspace",
"role": "admin",
"createdAt": "2026-06-01T09:14:00.000Z",
"updatedAt": "2026-06-20T14:02:11.000Z"
}
"name": "STRIPE_API_KEY",
"scope": "workspace",
"role": "admin",
"createdAt": "2026-06-01T09:14:00.000Z",
"updatedAt": "2026-06-20T14:02:11.000Z"
}
}
]
File diff suppressed because it is too large Load Diff
+159 -77
View File
@@ -40,7 +40,7 @@
"get": {
"operationId": "listWorkflows",
"summary": "List Workflows",
"description": "List workflows in a workspace with folder and deployment filters, search, sorting, and opaque cursor pagination.",
"description": "List workflows in a workspace with folder and deployment filters, search, sorting, and opaque cursor pagination. A workspace whose folder tree exceeds 10,000 folders is a 413, because the response needs the whole tree to render folder paths.",
"tags": ["Workflows"],
"parameters": [
{
@@ -165,6 +165,12 @@
"403": {
"$ref": "#/components/responses/Forbidden"
},
"404": {
"$ref": "#/components/responses/NotFound"
},
"413": {
"$ref": "#/components/responses/PayloadTooLarge"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -179,7 +185,7 @@
"post": {
"operationId": "createWorkflowV2",
"summary": "Create Workflow",
"description": "Create a workflow in a workspace root or canonical workflow folder.",
"description": "Create a workflow in a workspace root or canonical workflow folder. A workspace whose folder tree exceeds 10,000 folders is a 413, because the response needs the whole tree to render folder paths.",
"tags": ["Workflows"],
"requestBody": {
"required": true,
@@ -223,9 +229,15 @@
"403": {
"$ref": "#/components/responses/Forbidden"
},
"404": {
"$ref": "#/components/responses/NotFound"
},
"409": {
"$ref": "#/components/responses/Conflict"
},
"413": {
"$ref": "#/components/responses/PayloadTooLarge"
},
"423": {
"$ref": "#/components/responses/Locked"
},
@@ -245,7 +257,7 @@
"get": {
"operationId": "getWorkflow",
"summary": "Get Workflow",
"description": "Get a workflow with its variables and deployed API-trigger inputs.",
"description": "Get a workflow with its variables and deployed API-trigger inputs. A workspace whose folder tree exceeds 10,000 folders is a 413, because the response needs the whole tree to render folder paths.",
"tags": ["Workflows"],
"parameters": [
{
@@ -295,6 +307,9 @@
"404": {
"$ref": "#/components/responses/NotFound"
},
"413": {
"$ref": "#/components/responses/PayloadTooLarge"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -309,7 +324,7 @@
"patch": {
"operationId": "updateWorkflowV2",
"summary": "Update Workflow",
"description": "Rename, describe, or move a workflow to a canonical folder path.",
"description": "Rename, describe, or move a workflow to a canonical folder path. A workspace whose folder tree exceeds 10,000 folders is a 413, because the response needs the whole tree to render folder paths.",
"tags": ["Workflows"],
"parameters": [
{
@@ -373,6 +388,9 @@
"409": {
"$ref": "#/components/responses/Conflict"
},
"413": {
"$ref": "#/components/responses/PayloadTooLarge"
},
"423": {
"$ref": "#/components/responses/Locked"
},
@@ -626,7 +644,7 @@
"post": {
"operationId": "deployWorkflow",
"summary": "Deploy Workflow",
"description": "Create and asynchronously activate a deployment version. Poll the workflow until the lifecycle attempt reaches a terminal state.",
"description": "Create and asynchronously activate a deployment version. This request is not idempotent: it accepts no idempotency key and every call mints a new deployment version, so retrying after a timeout creates a second version rather than returning the first. The response carries `latestDeploymentAttempt` for the accepted attempt, but `GET /workflows/{id}` does not expose that field — poll activation with `isDeployed` and `deployedAt` on the workflow, or with `isActive` on `GET /workflows/{id}/versions`. Returns 409 when the deployment would conflict with an existing webhook path. A workspace API key cannot call this operation. Because unauthorized resources are concealed, the rejection is reported as `404` rather than `403`; use a personal API key.",
"tags": ["Workflows"],
"parameters": [
{
@@ -687,6 +705,9 @@
"404": {
"$ref": "#/components/responses/NotFound"
},
"409": {
"$ref": "#/components/responses/Conflict"
},
"413": {
"$ref": "#/components/responses/PayloadTooLarge"
},
@@ -707,7 +728,7 @@
"delete": {
"operationId": "undeployWorkflow",
"summary": "Undeploy Workflow",
"description": "Deactivate the currently serving workflow version.",
"description": "Deactivate the currently serving workflow version. A workspace API key cannot call this operation. Because unauthorized resources are concealed, the rejection is reported as `404` rather than `403`; use a personal API key.",
"tags": ["Workflows"],
"parameters": [
{
@@ -776,7 +797,7 @@
"post": {
"operationId": "rollbackWorkflow",
"summary": "Rollback Workflow",
"description": "Asynchronously reactivate a previous deployment version, selecting the preceding active version when no version is supplied.",
"description": "Asynchronously reactivate a previous deployment version, selecting the preceding active version when no version is supplied. A workspace API key cannot call this operation. Because unauthorized resources are concealed, the rejection is reported as `404` rather than `403`; use a personal API key.",
"tags": ["Workflows"],
"parameters": [
{
@@ -859,7 +880,7 @@
"get": {
"operationId": "exportWorkflow",
"summary": "Export Workflow",
"description": "Export a portable, secret-sanitized workflow. Workspace-scoped bindings must be selected again after import.",
"description": "Export a portable, secret-sanitized workflow. Workspace-scoped bindings must be selected again after import. A workspace whose folder tree exceeds 10,000 folders is a 413, because the response needs the whole tree to render folder paths.",
"tags": ["Workflows"],
"parameters": [
{
@@ -909,6 +930,9 @@
"404": {
"$ref": "#/components/responses/NotFound"
},
"413": {
"$ref": "#/components/responses/PayloadTooLarge"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -997,7 +1021,7 @@
"post": {
"operationId": "executeWorkflowV2",
"summary": "Execute Workflow",
"description": "Execute a deployed workflow synchronously, asynchronously, or as Server-Sent Events. Public workflows permit anonymous synchronous and streaming execution; asynchronous execution requires an API key.",
"description": "Execute a deployed workflow synchronously, asynchronously, or as Server-Sent Events. Public workflows permit anonymous synchronous and streaming execution; asynchronous execution requires an API key. A synchronous run that exceeds its execution timeout returns HTTP 200 with `status: \"failed\"` and `error.code: \"TIMEOUT\"` rather than an HTTP error, so branch on `status`. The optional `X-Run-Id` header is a one-shot uniqueness claim, not an idempotency key: reusing a value returns 409 with `error.details.code: \"RUN_ID_CONFLICT\"` and never replays the earlier run. Option constraints — each is a 400: (1) `async: true` requires an API key; anonymous public-workflow callers may only execute synchronously or as a stream. (2) `async` and `stream` cannot both be true. (3) `executionTimeoutSeconds` is accepted only when `async: true`. (4) `async: true` rejects every streaming and output-shaping option — `selectedOutputs`, `includeThinking`, `includeToolCalls`, `includeFileBase64`, and `base64MaxBytes`. (5) `includeThinking` and `includeToolCalls` require the `X-Sim-Stream-Protocol: agent-events-v1` request header, which declares that the client understands agent-event frames.",
"tags": ["Workflows"],
"security": [
{
@@ -1022,20 +1046,30 @@
"name": "x-run-id",
"in": "header",
"required": false,
"description": "Caller-supplied run identifier. Available only to API-key callers.",
"description": "Caller-supplied run identifier, available only to API-key callers. This is a one-shot uniqueness claim, NOT an idempotency key: the first request to use a value starts a run, and any later request reusing it fails with 409 and `error.details.code: \"RUN_ID_CONFLICT\"` instead of replaying the original result. To retry safely, generate a fresh value per attempt and reconcile duplicates yourself, or omit the header and let the server allocate the run identifier.",
"schema": {
"description": "Caller-supplied run identifier. Available only to API-key callers.",
"description": "Caller-supplied run identifier, available only to API-key callers. This is a one-shot uniqueness claim, NOT an idempotency key: the first request to use a value starts a run, and any later request reusing it fails with 409 and `error.details.code: \"RUN_ID_CONFLICT\"` instead of replaying the original result. To retry safely, generate a fresh value per attempt and reconcile duplicates yourself, or omit the header and let the server allocate the run identifier.",
"type": "string",
"minLength": 1,
"maxLength": 128,
"pattern": "^[A-Za-z0-9._:-]+$",
"examples": ["run_8f14e45f-ceea-467f-a"]
}
},
{
"name": "x-sim-via",
"in": "header",
"required": false,
"description": "Comma-separated workflow identifiers describing the workflow-to-workflow call chain that led to this request. Each hop appends its own workflow id, and Sim sets it automatically when one workflow calls another; supply it yourself only when relaying an existing chain. A chain already at the maximum depth is rejected with 409 and `error.details.code: \"CALL_CHAIN_DEPTH_EXCEEDED\"`, which is how runaway recursion between workflows is stopped.",
"schema": {
"description": "Comma-separated workflow identifiers describing the workflow-to-workflow call chain that led to this request. Each hop appends its own workflow id, and Sim sets it automatically when one workflow calls another; supply it yourself only when relaying an existing chain. A chain already at the maximum depth is rejected with 409 and `error.details.code: \"CALL_CHAIN_DEPTH_EXCEEDED\"`, which is how runaway recursion between workflows is stopped.",
"type": "string"
}
}
],
"requestBody": {
"required": true,
"description": "Input and execution-mode options for a deployed workflow.",
"description": "Input and execution-mode options for a deployed workflow. Option constraints — each is a 400: (1) `async: true` requires an API key; anonymous public-workflow callers may only execute synchronously or as a stream. (2) `async` and `stream` cannot both be true. (3) `executionTimeoutSeconds` is accepted only when `async: true`. (4) `async: true` rejects every streaming and output-shaping option — `selectedOutputs`, `includeThinking`, `includeToolCalls`, `includeFileBase64`, and `base64MaxBytes`. (5) `includeThinking` and `includeToolCalls` require the `X-Sim-Stream-Protocol: agent-events-v1` request header, which declares that the client understands agent-event frames.",
"content": {
"application/json": {
"schema": {
@@ -1122,6 +1156,9 @@
"429": {
"$ref": "#/components/responses/RateLimited"
},
"499": {
"$ref": "#/components/responses/ClientClosedRequest"
},
"500": {
"$ref": "#/components/responses/InternalError"
},
@@ -1135,7 +1172,7 @@
"get": {
"operationId": "listWorkflowRunsV2",
"summary": "List Workflow Runs",
"description": "List recorded runs of a workflow with filtering and opaque cursor pagination.",
"description": "List recorded runs of a workflow with filtering and opaque cursor pagination. Ordering deviates from the v2 `sortBy` + `sortOrder` convention: runs are sortable only by start time, so direction is carried by the single `order` param.",
"tags": ["Workflow Runs"],
"parameters": [
{
@@ -1224,10 +1261,10 @@
"name": "order",
"in": "query",
"required": false,
"description": "Sort order by run start time.",
"description": "Sort direction by run start time. This operation deviates from the v2 `sortBy` + `sortOrder` convention: runs are sortable only by start time, so the direction is carried by this single `order` param and `sortBy`/`sortOrder` are not accepted.",
"schema": {
"default": "desc",
"description": "Sort order by run start time.",
"description": "Sort direction by run start time. This operation deviates from the v2 `sortBy` + `sortOrder` convention: runs are sortable only by start time, so the direction is carried by this single `order` param and `sortBy`/`sortOrder` are not accepted.",
"type": "string",
"enum": ["asc", "desc"]
}
@@ -1367,6 +1404,9 @@
"404": {
"$ref": "#/components/responses/NotFound"
},
"409": {
"$ref": "#/components/responses/Conflict"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -1493,9 +1533,6 @@
"413": {
"$ref": "#/components/responses/PayloadTooLarge"
},
"423": {
"$ref": "#/components/responses/Locked"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -1512,7 +1549,7 @@
"post": {
"operationId": "cancelRunV2",
"summary": "Cancel Workflow Run",
"description": "Request cancellation of a running, queued, or paused workflow run.",
"description": "Request cancellation of a running, queued, or paused workflow run. Cancelling a run that has already reached a terminal state succeeds with no effect rather than returning an error. The `reason` field is present on every response, including full successes — `recorded` is the success value; it is not a partial-failure marker. A run produced by a table workflow group is a 409 when its cell can no longer accept the cancellation, because the run and its cell must reach the cancelled state together.",
"tags": ["Workflow Runs"],
"parameters": [
{
@@ -1575,6 +1612,9 @@
"404": {
"$ref": "#/components/responses/NotFound"
},
"409": {
"$ref": "#/components/responses/Conflict"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -1591,7 +1631,7 @@
"get": {
"operationId": "listWorkflowsFolders",
"summary": "List Workflow Folders",
"description": "List canonical workflow folders in a workspace.",
"description": "List canonical workflow folders in a workspace. The bounded set is returned in one page with `nextCursor` always null; there is no second page to fetch.",
"tags": ["Workflows"],
"parameters": [
{
@@ -1683,6 +1723,12 @@
"403": {
"$ref": "#/components/responses/Forbidden"
},
"404": {
"$ref": "#/components/responses/NotFound"
},
"413": {
"$ref": "#/components/responses/PayloadTooLarge"
},
"429": {
"$ref": "#/components/responses/RateLimited"
},
@@ -1747,6 +1793,9 @@
"409": {
"$ref": "#/components/responses/Conflict"
},
"413": {
"$ref": "#/components/responses/PayloadTooLarge"
},
"423": {
"$ref": "#/components/responses/Locked"
},
@@ -1814,6 +1863,9 @@
"409": {
"$ref": "#/components/responses/Conflict"
},
"413": {
"$ref": "#/components/responses/PayloadTooLarge"
},
"423": {
"$ref": "#/components/responses/Locked"
},
@@ -1904,6 +1956,9 @@
"409": {
"$ref": "#/components/responses/Conflict"
},
"413": {
"$ref": "#/components/responses/PayloadTooLarge"
},
"423": {
"$ref": "#/components/responses/Locked"
},
@@ -1926,7 +1981,7 @@
"type": "apiKey",
"in": "header",
"name": "X-API-Key",
"description": "Your Sim API key (personal or workspace). Generate one from the Sim dashboard under Settings > API Keys."
"description": "Your Sim API key, personal or workspace-scoped. Generate one from the Sim dashboard under Settings > API Keys. A workspace API key is not accepted everywhere: operations that act on behalf of a specific human — administrative reads, secret access, and irreversible or governance-affecting writes — always reject it, whatever role the key carries. Each such operation says so in its own description, and the rejection surfaces as `403` unless the operation conceals unauthorized resources, in which case it is reported as `404`. Use a personal API key for those."
}
},
"headers": {
@@ -2042,7 +2097,7 @@
}
},
"RunIdConflict": {
"description": "The run identifier is already associated with a different request.",
"description": "The run cannot be started. Two causes share this status, distinguished by `error.details.code`: `RUN_ID_CONFLICT` when the supplied `X-Run-Id` is already associated with a different request, and `CALL_CHAIN_DEPTH_EXCEEDED` when the incoming `X-Sim-Via` chain has already reached the maximum workflow-to-workflow call depth.",
"headers": {
"X-Run-Id": {
"$ref": "#/components/headers/X-Run-Id"
@@ -2067,7 +2122,7 @@
}
},
"PayloadTooLarge": {
"description": "The request body exceeds the allowed size.",
"description": "The request, or a resource collection it must materialize, exceeds the allowed size. Besides an oversized request body, this covers a generated artifact that renders past the download ceiling and a workspace folder tree too large to load in full.",
"content": {
"application/json": {
"schema": {
@@ -2111,6 +2166,16 @@
}
}
},
"ClientClosedRequest": {
"description": "The client closed the connection before the response was produced.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/V2Error"
}
}
}
},
"InternalError": {
"description": "An unexpected server error occurred.",
"content": {
@@ -2283,7 +2348,7 @@
"type": "null"
}
],
"description": "Opaque cursor for the next page, or null when no more items remain."
"description": "Opaque cursor for the next page, or null when no more items remain. Always null on a full-set list, which returns its whole result set in one response."
}
},
"required": ["data", "nextCursor"],
@@ -2735,7 +2800,7 @@
"type": "null"
}
],
"description": "Opaque cursor for the next page, or null when no more items remain."
"description": "Opaque cursor for the next page, or null when no more items remain. Always null on a full-set list, which returns its whole result set in one response."
}
},
"required": ["data", "nextCursor"],
@@ -3067,7 +3132,7 @@
],
"additionalProperties": false,
"title": "Deploy result",
"description": "Deployment attempt accepted for processing. Activation is asynchronous; inspect `isDeployed` and `latestDeploymentAttempt` for current state."
"description": "Deployment attempt accepted for processing. Activation is asynchronous; `latestDeploymentAttempt` on this response is the attempt handle. The request is NOT idempotent — every POST mints a new deployment version, so a retry after a timeout creates a second version rather than returning the first. `latestDeploymentAttempt` is returned only here: `GET /workflows/{id}` does not carry it, so poll activation with `isDeployed` and `deployedAt` on the workflow, or with `isActive` on `GET /workflows/{id}/versions`."
},
"DeployWorkflowResponse": {
"type": "object",
@@ -3085,11 +3150,26 @@
{
"data": {
"id": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36",
"isDeployed": true,
"deployedAt": "2026-06-12T10:30:00.000Z",
"isDeployed": false,
"deployedAt": null,
"warnings": [],
"activeDeployment": null,
"latestDeploymentAttempt": null,
"latestDeploymentAttempt": {
"id": "depop_01J8ZK3QW4M6X2R9T7B5C0V1",
"deploymentVersionId": "depver_01J8ZK3QW4M6X2R9T7B5C0V2",
"version": 3,
"action": "deploy",
"status": "preparing",
"isCurrent": true,
"readiness": {
"webhooks": "pending",
"schedules": "ready",
"mcp": "not_applicable"
},
"requestedAt": "2026-06-12T10:30:00.000Z",
"activatedAt": null,
"error": null
},
"version": 3
}
}
@@ -3309,11 +3389,26 @@
{
"data": {
"id": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36",
"isDeployed": true,
"deployedAt": "2026-06-12T10:30:00.000Z",
"isDeployed": false,
"deployedAt": null,
"warnings": [],
"activeDeployment": null,
"latestDeploymentAttempt": null,
"latestDeploymentAttempt": {
"id": "depop_01J8ZK4RX5N7Y3S0U8D6E1W2",
"deploymentVersionId": "depver_01J8ZK4RX5N7Y3S0U8D6E1W3",
"version": 2,
"action": "activate",
"status": "activating",
"isCurrent": true,
"readiness": {
"webhooks": "ready",
"schedules": "ready",
"mcp": "not_applicable"
},
"requestedAt": "2026-06-12T10:30:00.000Z",
"activatedAt": null,
"error": null
},
"version": 2
}
}
@@ -3652,7 +3747,7 @@
"required": ["runId", "workflowId", "status", "output", "error"],
"additionalProperties": false,
"title": "Workflow run result",
"description": "Synchronous workflow run output and in-band execution status."
"description": "Synchronous workflow run output and in-band execution status. Run failures are reported in band, not as HTTP errors — a synchronous run that exceeds its execution timeout returns HTTP 200 with `status: \"failed\"` and `error.code: \"TIMEOUT\"`, so always branch on `status` rather than on the HTTP status alone."
},
"ExecuteWorkflowSyncResponse": {
"type": "object",
@@ -3741,22 +3836,22 @@
},
"async": {
"default": false,
"description": "Queue the run and return a 202 receipt when true.",
"description": "Queue the run and return a 202 receipt when true. Requires an API key, cannot be combined with `stream`, and rejects all streaming and output-shaping options (`selectedOutputs`, `includeThinking`, `includeToolCalls`, `includeFileBase64`, `base64MaxBytes`).",
"type": "boolean"
},
"executionTimeoutSeconds": {
"description": "Server-side timeout for an asynchronous run, in seconds.",
"description": "Requested server-side timeout for an asynchronous run, in seconds. This is an upper bound on the request, not the effective timeout: the run uses the smaller of this value and the account plan's execution timeout, so requesting more than the plan allows silently yields the plan timeout with no warning. Rejected with 400 unless `async` is true.",
"type": "integer",
"minimum": 1,
"maximum": 604800
},
"stream": {
"default": false,
"description": "Return Server-Sent Events instead of JSON when true.",
"description": "Return Server-Sent Events instead of JSON when true. Cannot be combined with `async`.",
"type": "boolean"
},
"selectedOutputs": {
"description": "Block output references to include in a streamed response.",
"description": "Block output references to include in a streamed response. Rejected when `async` is true.",
"maxItems": 100,
"type": "array",
"items": {
@@ -3766,12 +3861,12 @@
},
"includeThinking": {
"default": false,
"description": "Include model reasoning events in an agent-event stream.",
"description": "Include model reasoning events in an agent-event stream. Requires the `X-Sim-Stream-Protocol: agent-events-v1` request header, and is rejected when `async` is true.",
"type": "boolean"
},
"includeToolCalls": {
"default": false,
"description": "Include tool-call events in an agent-event stream.",
"description": "Include tool-call events in an agent-event stream. Requires the `X-Sim-Stream-Protocol: agent-events-v1` request header, and is rejected when `async` is true.",
"type": "boolean"
},
"includeFileBase64": {
@@ -3787,7 +3882,7 @@
},
"additionalProperties": false,
"title": "Execute workflow request",
"description": "Input and execution-mode options for a deployed workflow.",
"description": "Input and execution-mode options for a deployed workflow. Option constraints — each is a 400: (1) `async: true` requires an API key; anonymous public-workflow callers may only execute synchronously or as a stream. (2) `async` and `stream` cannot both be true. (3) `executionTimeoutSeconds` is accepted only when `async: true`. (4) `async: true` rejects every streaming and output-shaping option — `selectedOutputs`, `includeThinking`, `includeToolCalls`, `includeFileBase64`, and `base64MaxBytes`. (5) `includeThinking` and `includeToolCalls` require the `X-Sim-Stream-Protocol: agent-events-v1` request header, which declares that the client understands agent-event frames.",
"examples": [
{
"input": {
@@ -3913,7 +4008,7 @@
"type": "null"
}
],
"description": "Opaque cursor for the next page, or null when no more items remain."
"description": "Opaque cursor for the next page, or null when no more items remain. Always null on a full-set list, which returns its whole result set in one response."
}
},
"required": ["data", "nextCursor"],
@@ -4017,18 +4112,22 @@
},
"pausedAt": {
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$",
"description": "ISO 8601 timestamp when the execution entered the paused state."
},
"resumeAt": {
"anyOf": [
{
"type": "string"
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$"
},
{
"type": "null"
}
],
"description": "Scheduled automatic-resume timestamp, or null when no resume time is set."
"description": "ISO 8601 scheduled automatic-resume timestamp, or null when no resume time is set."
},
"pauseKind": {
"anyOf": [
@@ -4338,7 +4437,7 @@
"description": "Whether a paused execution was cancelled."
},
"reason": {
"description": "Machine-readable cancellation outcome when cancellation was partial.",
"description": "Machine-readable cancellation outcome. Present on every cancellation, including full successes — it is not a partial-failure marker. `recorded` means cancellation was durably recorded (the normal success value). `redis_unavailable` and `redis_write_failed` mean the distributed cancellation signal could not be written, so an already-running execution may not observe the cancellation. `paused_event_publish_failed` and `paused_database_cancel_failed` name the failing step when cancelling a paused human-in-the-loop run.",
"type": "string",
"enum": [
"recorded",
@@ -4359,7 +4458,7 @@
],
"additionalProperties": false,
"title": "Cancel workflow run result",
"description": "Outcome of a workflow run cancellation request."
"description": "Outcome of a workflow run cancellation request. Cancelling a run that has already reached a terminal state (completed, failed, or cancelled) succeeds with no effect rather than returning an error — treat this endpoint as best-effort and poll the run to observe the final state."
},
"CancelWorkflowRunResponse": {
"type": "object",
@@ -4441,7 +4540,7 @@
"type": "null"
}
],
"description": "Opaque cursor for the next page, or null when no more items remain."
"description": "Opaque cursor for the next page, or null when no more items remain. Always null on a full-set list, which returns its whole result set in one response."
}
},
"required": ["data", "nextCursor"],
@@ -4464,25 +4563,12 @@
}
]
},
"WorkflowFolderData": {
"type": "object",
"properties": {
"folder": {
"description": "Created or relocated workflow folder.",
"$ref": "#/components/schemas/WorkflowFolder"
}
},
"required": ["folder"],
"additionalProperties": false,
"title": "Workflow folder data",
"description": "A created or relocated workflow folder."
},
"CreateWorkflowFolderResponse": {
"type": "object",
"properties": {
"data": {
"description": "Response data.",
"$ref": "#/components/schemas/WorkflowFolderData"
"$ref": "#/components/schemas/WorkflowFolder"
}
},
"required": ["data"],
@@ -4492,14 +4578,12 @@
"examples": [
{
"data": {
"folder": {
"name": "Operations",
"path": "/Operations",
"parentPath": "/",
"createdAt": "2026-05-01T09:00:00.000Z",
"updatedAt": "2026-05-01T09:00:00.000Z",
"locked": false
}
"name": "Operations",
"path": "/Operations",
"parentPath": "/",
"createdAt": "2026-05-01T09:00:00.000Z",
"updatedAt": "2026-05-01T09:00:00.000Z",
"locked": false
}
}
]
@@ -4527,7 +4611,7 @@
"properties": {
"data": {
"description": "Response data.",
"$ref": "#/components/schemas/WorkflowFolderData"
"$ref": "#/components/schemas/WorkflowFolder"
}
},
"required": ["data"],
@@ -4537,14 +4621,12 @@
"examples": [
{
"data": {
"folder": {
"name": "Support",
"path": "/Support",
"parentPath": "/",
"createdAt": "2026-05-01T09:00:00.000Z",
"updatedAt": "2026-05-01T09:00:00.000Z",
"locked": false
}
"name": "Support",
"path": "/Support",
"parentPath": "/",
"createdAt": "2026-05-01T09:00:00.000Z",
"updatedAt": "2026-05-01T09:00:00.000Z",
"locked": false
}
}
]
@@ -0,0 +1,94 @@
/**
* @vitest-environment node
*/
import { resetDbChainMock } from '@sim/testing'
import type { NextRequest } from 'next/server'
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'
const { mockPerformUpdateMcpServer } = vi.hoisted(() => ({
mockPerformUpdateMcpServer: vi.fn(),
}))
vi.mock('@/lib/mcp/middleware', () => ({
getParsedBody: () => undefined,
readMcpJsonBodyWithLimit: (request: NextRequest) => request.json(),
mcpBodyReadErrorResponse: () => null,
withMcpAuth:
() =>
(
handler: (
request: NextRequest,
context: Record<string, string>,
routeContext: { params: Promise<{ id: string }> }
) => Promise<Response>
) =>
(request: NextRequest, routeContext: { params: Promise<{ id: string }> }) =>
handler(
request,
{
userId: 'user-1',
userName: 'Test User',
userEmail: 'test@example.com',
workspaceId: 'workspace-1',
requestId: 'request-1',
permission: 'admin',
},
routeContext
),
}))
vi.mock('@/lib/mcp/orchestration', () => ({
performUpdateMcpServer: mockPerformUpdateMcpServer,
mcpOrchestrationStatus: () => 500,
}))
import { PATCH } from '@/app/api/mcp/servers/[id]/route'
const SECRET_HEADER_VALUE = 'Bearer super-secret-upstream-token'
function updateRequest() {
return new Request('http://localhost:3000/api/mcp/servers/server-1?workspaceId=workspace-1', {
method: 'PATCH',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ name: 'Renamed' }),
}) as NextRequest
}
describe('MCP server PATCH route', () => {
beforeEach(() => {
vi.clearAllMocks()
resetDbChainMock()
})
afterAll(() => {
resetDbChainMock()
})
it('echoes the updated server without header values or the client secret', async () => {
mockPerformUpdateMcpServer.mockResolvedValueOnce({
success: true,
server: {
id: 'server-1',
workspaceId: 'workspace-1',
name: 'Renamed',
transport: 'streamable-http',
url: 'https://mcp.example.com',
headers: { Authorization: SECRET_HEADER_VALUE },
enabled: true,
createdAt: new Date('2026-01-01T00:00:00.000Z'),
updatedAt: new Date('2026-01-02T00:00:00.000Z'),
oauthClientSecret: 'encrypted-secret',
},
})
const response = await PATCH(updateRequest(), { params: Promise.resolve({ id: 'server-1' }) })
const body = await response.json()
expect(JSON.stringify(body)).not.toContain(SECRET_HEADER_VALUE)
expect(body.data.server.headers).toBeUndefined()
expect(body.data.server.hasHeaders).toBe(true)
expect(body.data.server.headerNames).toEqual(['Authorization'])
expect(body.data.server.oauthClientSecret).toBeUndefined()
expect(body.data.server.hasOauthClientSecret).toBe(true)
})
})
+7 -2
View File
@@ -9,6 +9,7 @@ import {
withMcpAuth,
} from '@/lib/mcp/middleware'
import { performUpdateMcpServer } from '@/lib/mcp/orchestration'
import { projectInternalMcpServer } from '@/lib/mcp/projection'
import {
createMcpErrorResponse,
createMcpSuccessResponse,
@@ -81,9 +82,13 @@ export const PATCH = withRouteHandler(
logger.info(`[${requestId}] Successfully updated MCP server: ${serverId}`)
const { oauthClientSecret: _secret, ...rest } = updatedServer
/**
* The echoed row never carries header values: the caller just supplied
* whatever it wanted stored, and the client refetches the list rather
* than reading headers off this response.
*/
return createMcpSuccessResponse({
server: { ...rest, hasOauthClientSecret: !!_secret },
server: projectInternalMcpServer(updatedServer, { includeHeaderValues: false }),
})
} catch (error) {
const bodyErrorResponse = mcpBodyReadErrorResponse(error, request)
+90 -3
View File
@@ -1,12 +1,13 @@
/**
* @vitest-environment node
*/
import { resetDbChainMock } from '@sim/testing'
import { queueTableRows, resetDbChainMock, schemaMock } from '@sim/testing'
import type { NextRequest } from 'next/server'
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'
const { mockPerformDeleteMcpServer } = vi.hoisted(() => ({
const { mockPerformDeleteMcpServer, authState } = vi.hoisted(() => ({
mockPerformDeleteMcpServer: vi.fn(),
authState: { permission: 'read' as string },
}))
vi.mock('@/lib/mcp/middleware', () => ({
@@ -22,6 +23,7 @@ vi.mock('@/lib/mcp/middleware', () => ({
userEmail: string
workspaceId: string
requestId: string
permission: string
}
) => Promise<Response>
) =>
@@ -32,6 +34,7 @@ vi.mock('@/lib/mcp/middleware', () => ({
userEmail: 'test@example.com',
workspaceId: 'workspace-1',
requestId: 'request-1',
permission: authState.permission,
}),
}))
@@ -40,7 +43,42 @@ vi.mock('@/lib/mcp/orchestration', () => ({
performDeleteMcpServer: mockPerformDeleteMcpServer,
}))
import { DELETE } from '@/app/api/mcp/servers/route'
import { DELETE, GET } from '@/app/api/mcp/servers/route'
const SECRET_HEADER_VALUE = 'Bearer super-secret-upstream-token'
function serverRow() {
return {
id: 'server-1',
workspaceId: 'workspace-1',
name: 'Internal MCP',
description: null,
transport: 'streamable-http',
url: 'https://mcp.example.com',
headers: { Authorization: SECRET_HEADER_VALUE, 'X-Api-Key': 'k-123' },
timeout: 30000,
retries: 3,
enabled: true,
connectionStatus: 'connected',
lastError: null,
statusConfig: null,
toolCount: 2,
lastToolsRefresh: null,
lastConnected: null,
createdAt: new Date('2026-01-01T00:00:00.000Z'),
updatedAt: new Date('2026-01-02T00:00:00.000Z'),
deletedAt: null,
authType: 'headers',
oauthClientId: 'client-1',
oauthClientSecret: 'encrypted-secret',
}
}
function listRequest() {
return new Request('http://localhost:3000/api/mcp/servers?workspaceId=workspace-1', {
method: 'GET',
}) as NextRequest
}
function createDeleteRequest(serverId = 'server-1') {
return new Request(
@@ -49,6 +87,55 @@ function createDeleteRequest(serverId = 'server-1') {
) as NextRequest
}
describe('MCP servers GET route', () => {
beforeEach(() => {
vi.clearAllMocks()
resetDbChainMock()
authState.permission = 'read'
})
afterAll(() => {
resetDbChainMock()
})
it('never returns header values to a read-only member, only their names', async () => {
queueTableRows(schemaMock.mcpServers, [serverRow()])
const response = await GET(listRequest())
const body = await response.json()
const [server] = body.data.servers
expect(JSON.stringify(body)).not.toContain(SECRET_HEADER_VALUE)
expect(JSON.stringify(body)).not.toContain('k-123')
expect(server.headers).toBeUndefined()
expect(server.hasHeaders).toBe(true)
expect(server.headerNames).toEqual(['Authorization', 'X-Api-Key'])
expect(server.oauthClientSecret).toBeUndefined()
expect(server.hasOauthClientSecret).toBe(true)
})
it('reports absent headers without inventing names', async () => {
queueTableRows(schemaMock.mcpServers, [{ ...serverRow(), headers: null }])
const response = await GET(listRequest())
const [server] = (await response.json()).data.servers
expect(server.hasHeaders).toBe(false)
expect(server.headerNames).toEqual([])
})
it('still serves header values to an editor, who round-trips them on save', async () => {
authState.permission = 'write'
queueTableRows(schemaMock.mcpServers, [serverRow()])
const response = await GET(listRequest())
const [server] = (await response.json()).data.servers
expect(server.headers).toEqual({ Authorization: SECRET_HEADER_VALUE, 'X-Api-Key': 'k-123' })
expect(server.oauthClientSecret).toBeUndefined()
})
})
describe('MCP servers DELETE route', () => {
beforeEach(() => {
vi.clearAllMocks()
+27 -19
View File
@@ -1,6 +1,7 @@
import { db } from '@sim/db'
import { mcpServers } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { permissionSatisfies } from '@sim/platform-authz/workspace'
import { toError } from '@sim/utils/errors'
import { and, eq, isNull } from 'drizzle-orm'
import type { NextRequest } from 'next/server'
@@ -13,6 +14,7 @@ import {
withMcpAuth,
} from '@/lib/mcp/middleware'
import { performCreateMcpServer, performDeleteMcpServer } from '@/lib/mcp/orchestration'
import { projectInternalMcpServer } from '@/lib/mcp/projection'
import {
createMcpErrorResponse,
createMcpSuccessResponse,
@@ -27,29 +29,35 @@ export const dynamic = 'force-dynamic'
* GET - List all registered MCP servers for the workspace
*/
export const GET = withRouteHandler(
withMcpAuth('read')(async (request: NextRequest, { userId, workspaceId, requestId }) => {
try {
logger.info(`[${requestId}] Listing MCP servers for workspace ${workspaceId}`)
withMcpAuth('read')(
async (request: NextRequest, { userId, workspaceId, requestId, permission }) => {
try {
logger.info(`[${requestId}] Listing MCP servers for workspace ${workspaceId}`)
const rows = await db
.select()
.from(mcpServers)
.where(and(eq(mcpServers.workspaceId, workspaceId), isNull(mcpServers.deletedAt)))
const rows = await db
.select()
.from(mcpServers)
.where(and(eq(mcpServers.workspaceId, workspaceId), isNull(mcpServers.deletedAt)))
const servers = rows.map(({ oauthClientSecret: _secret, ...rest }) => ({
...rest,
hasOauthClientSecret: !!_secret,
}))
/**
* Header values are the upstream credential and are stored unencrypted, so
* they are withheld from anyone who cannot already rewrite them. Editors and
* admins still receive them because the settings form round-trips the
* existing values on save.
*/
const includeHeaderValues = permissionSatisfies(permission, 'write')
const servers = rows.map((row) => projectInternalMcpServer(row, { includeHeaderValues }))
logger.info(
`[${requestId}] Listed ${servers.length} MCP servers for workspace ${workspaceId}`
)
return createMcpSuccessResponse({ servers })
} catch (error) {
logger.error(`[${requestId}] Error listing MCP servers:`, error)
return createMcpErrorResponse(toError(error), 'Failed to list MCP servers', 500)
logger.info(
`[${requestId}] Listed ${servers.length} MCP servers for workspace ${workspaceId}`
)
return createMcpSuccessResponse({ servers })
} catch (error) {
logger.error(`[${requestId}] Error listing MCP servers:`, error)
return createMcpErrorResponse(toError(error), 'Failed to list MCP servers', 500)
}
}
})
)
)
/**
@@ -1,272 +0,0 @@
/**
* @vitest-environment node
*/
import { NextRequest, NextResponse } from 'next/server'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { z } from 'zod'
import { defineRouteContract } from '@/lib/api/contracts'
import { recordRateLimitSnapshot } from '@/lib/api/server/rate-limit-context'
const {
mockCheckRateLimit,
mockGate,
mockHandler,
mockLoggerError,
mockLoggerInfo,
requestContextState,
} = vi.hoisted(() => ({
mockCheckRateLimit: vi.fn(),
mockGate: vi.fn(),
mockHandler: vi.fn(),
mockLoggerError: vi.fn(),
mockLoggerInfo: vi.fn(),
requestContextState: {
current: undefined as { requestId: string; method?: string; path?: string } | undefined,
},
}))
vi.mock('@sim/logger', () => ({
createLogger: () => ({
info: (...arguments_: unknown[]) =>
mockLoggerInfo(requestContextState.current?.requestId, ...arguments_),
warn: vi.fn(),
error: (...arguments_: unknown[]) =>
mockLoggerError(requestContextState.current?.requestId, ...arguments_),
}),
getRequestContext: () => requestContextState.current,
runWithRequestContext: async <T>(
context: { requestId: string; method?: string; path?: string },
callback: () => T | Promise<T>
): Promise<T> => {
requestContextState.current = context
try {
return await callback()
} finally {
requestContextState.current = undefined
}
},
}))
vi.mock('@/lib/core/utils/request', () => ({
generateRequestId: () => requestContextState.current?.requestId ?? 'outer-request-id',
}))
vi.mock('@/app/api/v1/middleware', () => ({
checkRateLimit: mockCheckRateLimit,
}))
vi.mock('@/app/api/v2/lib/gate', () => ({
v2ApiGateError: mockGate,
}))
import { withPublicApiRouteHandler } from '@/app/api/public-api-route-handler'
const RATE_LIMIT = {
allowed: true,
limit: 400,
remaining: 399,
resetAt: new Date('2026-08-06T20:00:00.000Z'),
userId: 'user-1',
keyType: 'personal' as const,
}
const queryContract = defineRouteContract({
method: 'POST',
path: '/api/test/:itemId',
params: z.object({ itemId: z.string().min(1) }),
query: z.object({ limit: z.coerce.number().int().positive() }),
body: z.object({ name: z.string().min(1) }),
response: { mode: 'json', schema: z.object({ ok: z.boolean() }) },
})
const listContract = defineRouteContract({
method: 'GET',
path: '/api/test',
query: z.object({ workspaceId: z.string().min(1) }),
response: { mode: 'json', schema: z.object({ ok: z.boolean() }) },
})
const POST = withPublicApiRouteHandler({
contract: queryContract,
rateLimitEndpoint: 'table-rows',
parseOptions: {
maxBodyBytes: 32,
payloadTooLargeResponse: () =>
NextResponse.json({ error: 'Custom payload limit response' }, { status: 413 }),
},
handler: async (arguments_) => {
mockHandler(arguments_)
return NextResponse.json({ ok: true })
},
})
const GET = withPublicApiRouteHandler({
contract: listContract,
rateLimitEndpoint: 'tables',
handler: async (arguments_) => {
mockHandler(arguments_)
return NextResponse.json({ ok: true })
},
})
const FAILING_GET = withPublicApiRouteHandler({
contract: listContract,
rateLimitEndpoint: 'tables',
handler: async () => {
throw new Error('handler failed')
},
})
function postRequest(body: string): NextRequest {
return new NextRequest('http://localhost:3000/api/test/item-1?limit=10', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
})
}
function listRequest(query = 'workspaceId=workspace-1'): NextRequest {
return new NextRequest(`http://localhost:3000/api/test?${query}`)
}
describe('withPublicApiRouteHandler', () => {
beforeEach(() => {
vi.clearAllMocks()
mockGate.mockResolvedValue(null)
mockCheckRateLimit.mockImplementation(async (request: NextRequest) => {
recordRateLimitSnapshot(request, RATE_LIMIT)
return RATE_LIMIT
})
})
it.each([
['authentication failure', 401],
['rate-limit denial', 429],
])('short-circuits %s before reading or parsing the body', async (_label, status) => {
mockCheckRateLimit.mockImplementation(async (request: NextRequest) => {
if (status === 401) {
return {
allowed: false,
limit: 0,
remaining: 0,
resetAt: new Date('2026-08-06T20:00:00.000Z'),
error: 'API key required',
}
}
recordRateLimitSnapshot(request, RATE_LIMIT)
return { ...RATE_LIMIT, allowed: false, remaining: 0, retryAfterMs: 30_000 }
})
const request = postRequest('{not valid json')
const response = await POST(request, { params: { itemId: 'item-1' } })
expect(response.status).toBe(status)
expect(request.bodyUsed).toBe(false)
expect(mockHandler).not.toHaveBeenCalled()
expect(mockCheckRateLimit).toHaveBeenCalledWith(request, 'table-rows')
expect(mockGate).not.toHaveBeenCalled()
if (status === 401) {
expect(response.headers.get('X-RateLimit-Limit')).toBe('0')
} else {
expect(response.headers.get('Retry-After')).toBe('30')
expect(response.headers.get('X-RateLimit-Limit')).toBe('400')
}
})
it('checks the v2 rollout gate before reading or parsing the body', async () => {
mockGate.mockResolvedValue(NextResponse.json({ error: 'Not found' }, { status: 404 }))
const request = postRequest('{not valid json')
const response = await POST(request, { params: { itemId: 'item-1' } })
expect(response.status).toBe(404)
expect(request.bodyUsed).toBe(false)
expect(mockGate).toHaveBeenCalledWith('user-1')
expect(mockHandler).not.toHaveBeenCalled()
})
it('fails fast when an allowed rate-limit result has no user ID', async () => {
mockCheckRateLimit.mockResolvedValue({ ...RATE_LIMIT, userId: undefined })
const response = await GET(listRequest())
expect(response.status).toBe(500)
expect(mockGate).not.toHaveBeenCalled()
expect(mockHandler).not.toHaveBeenCalled()
})
it('returns a contract validation response after authentication', async () => {
const response = await POST(postRequest(JSON.stringify({ name: '' })), {
params: { itemId: 'item-1' },
})
expect(response.status).toBe(400)
expect(response.headers.get('X-RateLimit-Limit')).toBe('400')
expect(mockHandler).not.toHaveBeenCalled()
})
it('forwards the body-size parse option', async () => {
const response = await POST(postRequest(JSON.stringify({ name: 'x'.repeat(40) })), {
params: { itemId: 'item-1' },
})
expect(response.status).toBe(413)
expect(response.headers.get('X-RateLimit-Remaining')).toBe('399')
await expect(response.json()).resolves.toEqual({ error: 'Custom payload limit response' })
expect(mockHandler).not.toHaveBeenCalled()
})
it('provides parsed params, query, body, and auth to the handler', async () => {
const request = postRequest(JSON.stringify({ name: 'Ada' }))
const response = await POST(request, { params: Promise.resolve({ itemId: 'item-1' }) })
expect(response.status).toBe(200)
expect(mockHandler).toHaveBeenCalledWith({
request,
input: {
params: { itemId: 'item-1' },
query: { limit: 10 },
body: { name: 'Ada' },
headers: undefined,
},
auth: {
requestId: 'outer-request-id',
userId: 'user-1',
rateLimit: RATE_LIMIT,
},
})
expect(response.headers.get('x-request-id')).toBe('outer-request-id')
expect(response.headers.get('X-RateLimit-Reset')).toBe(RATE_LIMIT.resetAt.toISOString())
expect(mockLoggerInfo).toHaveBeenCalledWith(
'outer-request-id',
'OK',
expect.objectContaining({ status: 200 })
)
})
it('supports direct invocation without a route context', async () => {
const request = listRequest()
const response = await GET(request)
expect(response.status).toBe(200)
expect(mockHandler.mock.calls[0][0].input.query).toEqual({ workspaceId: 'workspace-1' })
expect(mockCheckRateLimit).toHaveBeenCalledWith(request, 'tables')
})
it('keeps rate-limit and request headers on unhandled endpoint errors', async () => {
const response = await FAILING_GET(listRequest())
expect(response.status).toBe(500)
await expect(response.json()).resolves.toEqual({
error: { code: 'INTERNAL_ERROR', message: 'Internal server error' },
})
expect(response.headers.get('x-request-id')).toBe('outer-request-id')
expect(response.headers.get('X-RateLimit-Limit')).toBe('400')
expect(mockLoggerError).toHaveBeenCalledWith(
'outer-request-id',
'Unhandled route error',
expect.objectContaining({ error: 'handler failed' })
)
})
})
@@ -1,79 +0,0 @@
import type { NextRequest, NextResponse } from 'next/server'
import type { AnyApiRouteContract } from '@/lib/api/contracts'
import { type ParsedRequest, type ParseRequestOptions, parseRequest } from '@/lib/api/server'
import { generateRequestId } from '@/lib/core/utils/request'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { type ApiEndpoint, type AuthorizedRequest, checkRateLimit } from '@/app/api/v1/middleware'
import { v2ApiGateError } from '@/app/api/v2/lib/gate'
import { v2Error, v2RateLimitError, v2ValidationError } from '@/app/api/v2/lib/response'
interface PublicApiRouteContext {
params?:
| Promise<Record<string, string | string[] | undefined>>
| Record<string, string | string[] | undefined>
}
interface PublicApiRouteHandlerArguments<C extends AnyApiRouteContract> {
request: NextRequest
input: ParsedRequest<C>
auth: AuthorizedRequest
}
interface PublicApiRouteHandlerOptions<C extends AnyApiRouteContract> {
contract: C
rateLimitEndpoint: ApiEndpoint
parseOptions?: ParseRequestOptions
handler: (
arguments_: PublicApiRouteHandlerArguments<C>
) => Promise<NextResponse | Response> | NextResponse | Response
}
type PublicApiNextRouteHandler = (
request: NextRequest,
context?: PublicApiRouteContext
) => Promise<NextResponse | Response>
/**
* Wraps an API-key-authenticated public route with request context, rate
* limiting, authentication, and contract parsing before invoking the route's
* authorization and business logic. Unexpected endpoint errors are logged once
* by the shared route handler and rendered as the canonical v2 500 envelope.
*/
export function withPublicApiRouteHandler<C extends AnyApiRouteContract>({
contract,
rateLimitEndpoint,
parseOptions,
handler,
}: PublicApiRouteHandlerOptions<C>): PublicApiNextRouteHandler {
const wrapped = withRouteHandler<PublicApiRouteContext | undefined>(
async (request, context) => {
const requestId = generateRequestId()
const rateLimit = await checkRateLimit(request, rateLimitEndpoint)
if (!rateLimit.allowed) return v2RateLimitError(rateLimit)
if (!rateLimit.userId) {
throw new Error('Allowed public API request is missing a user ID')
}
const userId = rateLimit.userId
const gate = await v2ApiGateError(userId)
if (gate) return gate
const parsed = await parseRequest(contract, request, context ?? {}, {
validationErrorResponse: v2ValidationError,
...parseOptions,
})
if (!parsed.success) return parsed.response
return handler({
request,
input: parsed.data,
auth: { requestId, userId, rateLimit },
})
},
{
unhandledErrorResponse: () => v2Error('INTERNAL_ERROR', 'Internal server error'),
}
)
return async (request, context) => wrapped(request, context)
}
@@ -10,7 +10,7 @@
*/
import { hybridAuthMockFns } from '@sim/testing'
import { getErrorMessage } from '@sim/utils/errors'
import { NextRequest } from 'next/server'
import { NextRequest, NextResponse } from 'next/server'
import { beforeEach, describe, expect, it, vi } from 'vitest'
const {
@@ -53,11 +53,24 @@ vi.mock('@/app/api/table/utils', () => ({
accessError: () => new Response('denied', { status: 403 }),
checkAccess: mockCheckAccess,
normalizeColumn: (c: unknown) => c,
orchestrationOutcomeErrorResponse: (
outcome: { error?: string; errorCode?: OrchestrationErrorCode },
fallback: string
) =>
NextResponse.json(
{ error: messageForOrchestrationError(outcome, fallback) },
{ status: statusForOrchestrationError(outcome.errorCode) }
),
rootErrorMessage: (e: unknown) => getErrorMessage(e),
tableLockErrorResponse: () => null,
}))
import { OrchestrationError } from '@/lib/core/orchestration/types'
import {
messageForOrchestrationError,
OrchestrationError,
type OrchestrationErrorCode,
statusForOrchestrationError,
} from '@/lib/core/orchestration/types'
import { PATCH } from '@/app/api/table/[tableId]/columns/route'
const WORKSPACE_ID = '11111111-1111-4111-8111-111111111111'
@@ -8,7 +8,6 @@ import {
import { parseRequest } from '@/lib/api/server'
import { isZodError, validationErrorResponse } from '@/lib/api/server/validation'
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
import { statusForOrchestrationError } from '@/lib/core/orchestration/types'
import { generateRequestId } from '@/lib/core/utils/request'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { addTableColumn, deleteColumn } from '@/lib/table'
@@ -18,6 +17,7 @@ import {
accessError,
checkAccess,
normalizeColumn,
orchestrationOutcomeErrorResponse,
rootErrorMessage,
tableLockErrorResponse,
} from '@/app/api/table/utils'
@@ -122,10 +122,7 @@ export const PATCH = withRouteHandler(async (request: NextRequest, context: Colu
request,
})
if (!outcome.success || !outcome.table) {
return NextResponse.json(
{ error: outcome.error ?? 'Failed to update column' },
{ status: statusForOrchestrationError(outcome.errorCode) }
)
return orchestrationOutcomeErrorResponse(outcome, 'Failed to update column')
}
// Live-collab: tell open viewers the change landed so they refetch.
+9 -18
View File
@@ -5,7 +5,6 @@ import { getTableQuerySchema, updateTableContract } from '@/lib/api/contracts/ta
import { isZodError, parseRequest, validationErrorResponse } from '@/lib/api/server/validation'
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
import { isFeatureEnabled } from '@/lib/core/config/feature-flags'
import { statusForOrchestrationError } from '@/lib/core/orchestration/types'
import { generateRequestId } from '@/lib/core/utils/request'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { findActiveFolder } from '@/lib/folders/queries'
@@ -24,6 +23,7 @@ import {
accessError,
checkAccess,
normalizeColumn,
orchestrationOutcomeErrorResponse,
tableLockErrorResponse,
} from '@/app/api/table/utils'
@@ -187,10 +187,7 @@ export const PATCH = withRouteHandler(
request,
})
if (!lockOutcome.success) {
return NextResponse.json(
{ error: lockOutcome.error ?? 'Failed to update table locks' },
{ status: statusForOrchestrationError(lockOutcome.errorCode) }
)
return orchestrationOutcomeErrorResponse(lockOutcome, 'Failed to update table locks')
}
}
@@ -203,10 +200,7 @@ export const PATCH = withRouteHandler(
request,
})
if (!renameOutcome.success) {
return NextResponse.json(
{ error: renameOutcome.error ?? 'Failed to rename table' },
{ status: statusForOrchestrationError(renameOutcome.errorCode) }
)
return orchestrationOutcomeErrorResponse(renameOutcome, 'Failed to rename table')
}
}
@@ -229,11 +223,11 @@ export const PATCH = withRouteHandler(
request,
})
if (!moveOutcome.success) {
return NextResponse.json(
{
error: moveOutcome.errorCode === 'not_found' ? 'Table not found' : moveOutcome.error,
},
{ status: statusForOrchestrationError(moveOutcome.errorCode) }
return orchestrationOutcomeErrorResponse(
moveOutcome.errorCode === 'not_found'
? { ...moveOutcome, error: 'Table not found' }
: moveOutcome,
'Failed to move table'
)
}
}
@@ -302,10 +296,7 @@ export const DELETE = withRouteHandler(
request,
})
if (!outcome.success) {
return NextResponse.json(
{ error: outcome.error ?? 'Failed to delete table' },
{ status: statusForOrchestrationError(outcome.errorCode) }
)
return orchestrationOutcomeErrorResponse(outcome, 'Failed to delete table')
}
return NextResponse.json({
@@ -10,7 +10,6 @@ import {
} from '@/lib/api/contracts/tables'
import { isZodError, parseRequest, validationErrorResponse } from '@/lib/api/server/validation'
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
import { statusForOrchestrationError } from '@/lib/core/orchestration/types'
import { generateRequestId } from '@/lib/core/utils/request'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import type { RowData, TableSchema } from '@/lib/table'
@@ -27,7 +26,7 @@ import {
accessError,
checkAccess,
orchestrationErrorResponse,
rowWriteErrorResponse,
orchestrationOutcomeErrorResponse,
tableLockErrorResponse,
} from '@/app/api/table/utils'
@@ -211,7 +210,7 @@ export const PATCH = withRouteHandler(async (request: NextRequest, context: RowR
rows: [updatedRow],
})
} catch (error) {
const response = rowWriteErrorResponse(error)
const response = orchestrationErrorResponse(error)
if (response) return response
logger.error(`[${requestId}] Error updating row:`, error)
@@ -248,10 +247,7 @@ export const DELETE = withRouteHandler(async (request: NextRequest, context: Row
const outcome = await performDeleteTableRow({ table, rowId, requestId })
if (!outcome.success) {
return NextResponse.json(
{ error: outcome.error ?? 'Failed to delete row' },
{ status: statusForOrchestrationError(outcome.errorCode) }
)
return orchestrationOutcomeErrorResponse(outcome, 'Failed to delete row')
}
// Live-collab: tell open viewers the change landed so they refetch.
@@ -40,7 +40,7 @@ import {
resolveTableWriteSecretProvenance,
} from '@/app/api/table/row-secret-provenance'
import { type RowWireTranslators, rowWireTranslators } from '@/app/api/table/row-wire'
import { accessError, checkAccess, rowWriteErrorResponse } from '@/app/api/table/utils'
import { accessError, checkAccess, orchestrationErrorResponse } from '@/app/api/table/utils'
const logger = createLogger('TableRowsAPI')
@@ -168,7 +168,7 @@ async function handleBatchInsert(
rows: insertedRows,
})
} catch (error) {
const response = rowWriteErrorResponse(error)
const response = orchestrationErrorResponse(error)
if (response) return response
logger.error(`[${requestId}] Error batch inserting rows:`, error)
@@ -284,7 +284,7 @@ export const POST = withRouteHandler(
return validationErrorResponse(error)
}
const response = rowWriteErrorResponse(error)
const response = orchestrationErrorResponse(error)
if (response) return response
logger.error(`[${requestId}] Error inserting row:`, error)
@@ -527,7 +527,7 @@ export const PUT = withRouteHandler(
return NextResponse.json({ error: error.message }, { status: 400 })
}
const response = rowWriteErrorResponse(error)
const response = orchestrationErrorResponse(error)
if (response) return response
logger.error(`[${requestId}] Error updating rows by filter:`, error)
@@ -627,7 +627,7 @@ export const DELETE = withRouteHandler(
return NextResponse.json({ error: error.message }, { status: 400 })
}
const response = rowWriteErrorResponse(error)
const response = orchestrationErrorResponse(error)
if (response) return response
logger.error(`[${requestId}] Error deleting rows:`, error)
@@ -716,7 +716,7 @@ export const PATCH = withRouteHandler(
return validationErrorResponse(error)
}
const response = rowWriteErrorResponse(error)
const response = orchestrationErrorResponse(error)
if (response) return response
logger.error(`[${requestId}] Error batch updating rows:`, error)
@@ -15,7 +15,7 @@ import {
resolveTableWriteSecretProvenance,
} from '@/app/api/table/row-secret-provenance'
import { rowWireTranslators } from '@/app/api/table/row-wire'
import { accessError, checkAccess, rowWriteErrorResponse } from '@/app/api/table/utils'
import { accessError, checkAccess, orchestrationErrorResponse } from '@/app/api/table/utils'
const logger = createLogger('TableUpsertAPI')
@@ -105,7 +105,7 @@ export const POST = withRouteHandler(async (request: NextRequest, context: Upser
return validationErrorResponse(error)
}
const response = rowWriteErrorResponse(error)
const response = orchestrationErrorResponse(error)
if (response) return response
logger.error(`[${requestId}] Error upserting row:`, error)
+74 -10
View File
@@ -5,7 +5,12 @@ import { describe, expect, it } from 'vitest'
import { OrchestrationError } from '@/lib/core/orchestration/types'
import { TableRowLimitError } from '@/lib/table/billing'
import type { ColumnDefinition } from '@/lib/table/types'
import { rootErrorMessage, rowWriteErrorResponse, tableFilterError } from '@/app/api/table/utils'
import {
orchestrationErrorResponse,
orchestrationOutcomeErrorResponse,
rootErrorMessage,
tableFilterError,
} from '@/app/api/table/utils'
/** Mimics drizzle's DrizzleQueryError: message is the failed SQL, real error on `cause`. */
function wrapLikeDrizzle(cause: Error): Error {
@@ -29,9 +34,9 @@ describe('rootErrorMessage', () => {
})
})
describe('rowWriteErrorResponse', () => {
describe('orchestrationErrorResponse', () => {
it('passes the plan row-limit error through as a 400', async () => {
const response = rowWriteErrorResponse(new TableRowLimitError(10000))
const response = orchestrationErrorResponse(new TableRowLimitError(10000))
expect(response?.status).toBe(400)
const body = await response?.json()
expect(body.error).toBe(
@@ -40,7 +45,7 @@ describe('rowWriteErrorResponse', () => {
})
it('passes a classified validation failure through as 400', async () => {
const response = rowWriteErrorResponse(
const response = orchestrationErrorResponse(
new OrchestrationError('validation', 'Value for column "email" must be unique')
)
expect(response?.status).toBe(400)
@@ -50,24 +55,26 @@ describe('rowWriteErrorResponse', () => {
it('answers the code the failure carries, not one derived from its wording', () => {
expect(
rowWriteErrorResponse(new OrchestrationError('not_found', 'Row not found'))?.status
orchestrationErrorResponse(new OrchestrationError('not_found', 'Row not found'))?.status
).toBe(404)
// The phrase that used to force a 400 no longer decides anything.
expect(
rowWriteErrorResponse(new OrchestrationError('conflict', 'Row 3: must be unique'))?.status
orchestrationErrorResponse(new OrchestrationError('conflict', 'Row 3: must be unique'))
?.status
).toBe(409)
})
it('unwraps a classified failure drizzle wrapped in a query error', () => {
expect(
rowWriteErrorResponse(wrapLikeDrizzle(new OrchestrationError('validation', 'Row 3: bad')))
?.status
orchestrationErrorResponse(
wrapLikeDrizzle(new OrchestrationError('validation', 'Row 3: bad'))
)?.status
).toBe(400)
})
it('returns null for unknown errors so callers keep their generic 500', () => {
expect(rowWriteErrorResponse(new Error('connection refused'))).toBeNull()
expect(rowWriteErrorResponse(wrapLikeDrizzle(new Error('deadlock detected')))).toBeNull()
expect(orchestrationErrorResponse(new Error('connection refused'))).toBeNull()
expect(orchestrationErrorResponse(wrapLikeDrizzle(new Error('deadlock detected')))).toBeNull()
})
})
@@ -117,3 +124,60 @@ describe('tableFilterError', () => {
expect(tableFilterError({ col_status: { $regex: 'x' } } as never, columns)?.status).toBe(400)
})
})
describe('orchestrationOutcomeErrorResponse', () => {
/**
* Shaped like a driver fault surfacing verbatim — a statement plus its bound
* parameters — so the assertion proves none of it reaches the response body.
*/
const leakyMessage =
'Failed query: delete from "user_table" where "user_table"."id" = $1 params: tbl-1'
it('replaces an unclassified failure message with the fallback', async () => {
const response = orchestrationOutcomeErrorResponse(
{ success: false, error: leakyMessage, errorCode: 'internal' },
'Failed to delete table'
)
expect(response.status).toBe(500)
const body = await response.json()
expect(body).toEqual({ error: 'Failed to delete table' })
expect(JSON.stringify(body)).not.toContain('Failed query')
expect(JSON.stringify(body)).not.toContain('params:')
})
it('replaces an unclassified failure with no error code too', async () => {
const response = orchestrationOutcomeErrorResponse(
{ error: leakyMessage },
'Failed to delete table'
)
expect(response.status).toBe(500)
expect(await response.json()).toEqual({ error: 'Failed to delete table' })
})
it('keeps the message of a classified failure', async () => {
const response = orchestrationOutcomeErrorResponse(
{ error: 'A table named "Orders" already exists in this workspace', errorCode: 'conflict' },
'Failed to rename table'
)
expect(response.status).toBe(409)
expect(await response.json()).toEqual({
error: 'A table named "Orders" already exists in this workspace',
})
})
it('carries the rejecting lock kind on a 423', async () => {
const response = orchestrationOutcomeErrorResponse(
{ error: 'Table is locked against deletion', errorCode: 'locked', lock: 'delete' },
'Failed to delete table'
)
expect(response.status).toBe(423)
expect(await response.json()).toEqual({
error: 'Table is locked against deletion',
lock: 'delete',
})
})
})
+43 -4
View File
@@ -8,7 +8,12 @@ import {
updateTableColumnBodySchema,
} from '@/lib/api/contracts/tables'
import { isFeatureEnabled } from '@/lib/core/config/feature-flags'
import { asOrchestrationError, statusForOrchestrationError } from '@/lib/core/orchestration/types'
import {
asOrchestrationError,
messageForOrchestrationError,
type OrchestrationErrorCode,
statusForOrchestrationError,
} from '@/lib/core/orchestration/types'
import type { MultipartError } from '@/lib/core/utils/multipart'
import type { ColumnDefinition, Filter, TableDefinition, TablePredicate } from '@/lib/table'
import { buildFilterClause, getTableById, TableQueryValidationError } from '@/lib/table'
@@ -17,6 +22,7 @@ import { USER_TABLE_ROWS_SQL_NAME } from '@/lib/table/constants'
import { TableLockedError } from '@/lib/table/mutation-locks'
import { isTablePredicate } from '@/lib/table/query-builder/converters'
import { validateStoragePredicate } from '@/lib/table/query-builder/validate'
import type { TableLockKind } from '@/lib/table/types'
import { getUserEntityPermissions } from '@/lib/workspaces/permissions/utils'
import { getWorkspaceOrganizationId } from '@/lib/workspaces/utils'
@@ -133,10 +139,43 @@ export function orchestrationErrorResponse(error: unknown): NextResponse | null
}
/**
* {@link orchestrationErrorResponse} under the name the row-write routes call
* it by. Row writes have no classification rules of their own any more.
* The failure half of a `lib/table/orchestration` result. Every `perform*`
* function returns this shape, so one projection serves all of them.
*/
export const rowWriteErrorResponse = orchestrationErrorResponse
export interface TableOrchestrationFailure {
error?: string
errorCode?: OrchestrationErrorCode
/** Which lock rejected the write. Set only when `errorCode` is `'locked'`. */
lock?: TableLockKind
}
/**
* Projects an orchestration failure RESULT onto its HTTP response, the
* counterpart of {@link orchestrationErrorResponse} for the functions that
* return a failure instead of throwing one.
*
* Routes go through this rather than reading `outcome.error` themselves, for
* two reasons the per-route spellings kept getting wrong:
*
* - An unclassified failure carries whatever text the fault happened to have —
* a driver's failed SQL and its bound parameters — so it renders `fallback`
* instead. Only a classified, caller-fixable failure keeps its own message.
* - A `'locked'` failure answers 423 with `{ error, lock }`. The lock kind is
* the only thing that tells a client which lock to clear, and it is computed
* by every `perform*` function already.
*/
export function orchestrationOutcomeErrorResponse(
outcome: TableOrchestrationFailure,
fallback: string
): NextResponse {
return NextResponse.json(
{
error: messageForOrchestrationError(outcome, fallback),
...(outcome.lock ? { lock: outcome.lock } : {}),
},
{ status: statusForOrchestrationError(outcome.errorCode) }
)
}
/**
* Next.js buffers the request body for the proxy and silently truncates it past this
+7 -30
View File
@@ -20,9 +20,13 @@ const logger = createLogger('V1Middleware')
const rateLimiter = new RateLimiter()
/**
* Endpoint labels for public API auth/rate-limit telemetry. Version-neutral: the
* v1 and v2 public surfaces share the same `authenticateV1Request` + `api-endpoint`
* rate bucket, so the label is only a log/metric dimension, not a policy switch.
* Endpoint labels for v1 public API auth/rate-limit telemetry. The label is only
* a log/metric dimension, not a policy switch — every label resolves to the same
* `authenticateV1Request` + `api-endpoint` rate bucket.
*
* The v2 surface does not use these labels: v2 routes are built with
* `defineV2JsonRoute` and rate-limited through `v2RateLimits`. Add a member only
* when a route actually passes it to `checkRateLimit` / `authenticateRequest`.
*/
export type ApiEndpoint =
| 'logs'
@@ -31,8 +35,6 @@ export type ApiEndpoint =
| 'workflow-detail'
| 'workflow-deploy'
| 'workflow-rollback'
| 'workflow-versions'
| 'workflow-version-detail'
| 'workflow-export'
| 'workflow-import'
| 'audit-logs'
@@ -40,37 +42,12 @@ export type ApiEndpoint =
| 'table-detail'
| 'table-rows'
| 'table-row-detail'
| 'table-rows-find'
| 'table-columns'
| 'table-views'
| 'table-view-detail'
| 'table-groups'
| 'table-enrichment'
| 'table-import'
| 'table-export'
| 'table-jobs'
| 'files'
| 'file-detail'
| 'file-share'
| 'file-content'
| 'file-move'
| 'file-bulk-delete'
| 'knowledge'
| 'knowledge-detail'
| 'knowledge-search'
| 'copilot-chat'
| 'billing-usage'
| 'mcp-servers'
| 'mcp-server-detail'
| 'skills'
| 'skill-detail'
| 'custom-tools'
| 'custom-tool-detail'
| 'credentials'
| 'secrets'
| 'secret-detail'
| 'workspaces'
| 'workspace-members'
export interface RateLimitResult {
allowed: boolean
@@ -7,7 +7,6 @@ import {
v1UpdateTableColumnContract,
} from '@/lib/api/contracts/v1/tables'
import { parseRequest } from '@/lib/api/server'
import { statusForOrchestrationError } from '@/lib/core/orchestration/types'
import { generateRequestId } from '@/lib/core/utils/request'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { addTableColumn, deleteColumn } from '@/lib/table'
@@ -18,6 +17,7 @@ import {
checkAccess,
normalizeColumn,
orchestrationErrorResponse,
orchestrationOutcomeErrorResponse,
tableLockErrorResponse,
} from '@/app/api/table/utils'
import {
@@ -143,10 +143,7 @@ export const PATCH = withRouteHandler(async (request: NextRequest, context: Colu
request,
})
if (!outcome.success || !outcome.table) {
return NextResponse.json(
{ error: outcome.error ?? 'Failed to update column' },
{ status: statusForOrchestrationError(outcome.errorCode) }
)
return orchestrationOutcomeErrorResponse(outcome, 'Failed to update column')
}
// Live-collab: tell open viewers the change landed so they refetch.
@@ -0,0 +1,148 @@
/**
* @vitest-environment node
*
* DELETE /api/v1/tables/[tableId] projects an orchestration failure onto the
* wire. Two properties of that projection are load-bearing and have regressed
* before, so they are pinned here rather than left to the helper's own unit
* test: an UNCLASSIFIED failure must never reach an API-key holder (its message
* is whatever the fault happened to carry — a driver's failed SQL and its bound
* parameters), and a `locked` failure must carry `lock` so the client knows
* which lock to clear.
*/
import { createMockRequest } from '@sim/testing'
import { NextResponse } from 'next/server'
import { beforeEach, describe, expect, it, vi } from 'vitest'
const {
mockCheckRateLimit,
mockCheckWorkspaceScope,
mockGetTableById,
mockGetUserEntityPermissions,
mockPerformDeleteTable,
} = vi.hoisted(() => ({
mockCheckRateLimit: vi.fn(),
mockCheckWorkspaceScope: vi.fn(),
mockGetTableById: vi.fn(),
mockGetUserEntityPermissions: vi.fn(),
mockPerformDeleteTable: vi.fn(),
}))
vi.mock('@/app/api/v1/middleware', () => ({
checkRateLimit: mockCheckRateLimit,
checkWorkspaceScope: mockCheckWorkspaceScope,
createRateLimitResponse: () => NextResponse.json({ error: 'Rate limited' }, { status: 429 }),
}))
vi.mock('@/lib/table', () => ({
buildFilterClause: vi.fn(),
getTableById: mockGetTableById,
TableQueryValidationError: class TableQueryValidationError extends Error {},
}))
vi.mock('@/lib/workspaces/permissions/utils', () => ({
getUserEntityPermissions: mockGetUserEntityPermissions,
}))
vi.mock('@/lib/workspaces/utils', () => ({
getWorkspaceOrganizationId: vi.fn().mockResolvedValue(null),
}))
vi.mock('@/lib/table/orchestration', () => ({
performDeleteTable: mockPerformDeleteTable,
}))
import { DELETE } from '@/app/api/v1/tables/[tableId]/route'
const TABLE_ID = '22222222-2222-4222-8222-222222222222'
const WORKSPACE_ID = '11111111-1111-4111-8111-111111111111'
/**
* Stands in for a driver fault surfacing verbatim. Shaped like a real one —
* a statement plus its bound parameters — so the assertions can prove none of
* it reaches the response body.
*/
const LEAKY_INTERNAL_MESSAGE =
'Failed query: delete from "user_table" where "user_table"."id" = $1 params: 22222222-2222-4222-8222-222222222222'
function makeRequest() {
return createMockRequest(
'DELETE',
undefined,
{},
`http://localhost:3000/api/v1/tables/${TABLE_ID}?workspaceId=${WORKSPACE_ID}`
)
}
function makeContext() {
return { params: Promise.resolve({ tableId: TABLE_ID }) }
}
describe('DELETE /api/v1/tables/[tableId] — orchestration failure projection', () => {
beforeEach(() => {
vi.clearAllMocks()
mockCheckRateLimit.mockResolvedValue({ allowed: true, userId: 'user-1' })
mockCheckWorkspaceScope.mockResolvedValue(null)
mockGetTableById.mockResolvedValue({
id: TABLE_ID,
name: 'Table',
workspaceId: WORKSPACE_ID,
})
mockGetUserEntityPermissions.mockResolvedValue('admin')
})
it('renders an unclassified internal failure as a fixed generic message', async () => {
mockPerformDeleteTable.mockResolvedValue({
success: false,
error: LEAKY_INTERNAL_MESSAGE,
errorCode: 'internal',
})
const response = await DELETE(makeRequest(), makeContext())
const body = await response.json()
expect(response.status).toBe(500)
expect(body).toEqual({ error: 'Failed to delete table' })
expect(JSON.stringify(body)).not.toContain('Failed query')
expect(JSON.stringify(body)).not.toContain('params:')
expect(JSON.stringify(body)).not.toContain('$1')
})
it('renders an unclassified failure with no error code as the same generic message', async () => {
mockPerformDeleteTable.mockResolvedValue({ success: false, error: LEAKY_INTERNAL_MESSAGE })
const response = await DELETE(makeRequest(), makeContext())
expect(response.status).toBe(500)
expect(await response.json()).toEqual({ error: 'Failed to delete table' })
})
it('keeps the specific message of a classified failure', async () => {
mockPerformDeleteTable.mockResolvedValue({
success: false,
error: 'Table not found',
errorCode: 'not_found',
})
const response = await DELETE(makeRequest(), makeContext())
expect(response.status).toBe(404)
expect(await response.json()).toEqual({ error: 'Table not found' })
})
it('returns 423 with the rejecting lock kind', async () => {
mockPerformDeleteTable.mockResolvedValue({
success: false,
error: 'Table is locked against deletion',
errorCode: 'locked',
lock: 'delete',
})
const response = await DELETE(makeRequest(), makeContext())
expect(response.status).toBe(423)
expect(await response.json()).toEqual({
error: 'Table is locked against deletion',
lock: 'delete',
})
})
})
@@ -2,7 +2,6 @@ import { createLogger } from '@sim/logger'
import { type NextRequest, NextResponse } from 'next/server'
import { v1DeleteTableContract, v1GetTableContract } from '@/lib/api/contracts/v1/tables'
import { parseRequest } from '@/lib/api/server'
import { statusForOrchestrationError } from '@/lib/core/orchestration/types'
import { generateRequestId } from '@/lib/core/utils/request'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import type { TableSchema } from '@/lib/table'
@@ -11,6 +10,7 @@ import {
accessError,
checkAccess,
normalizeColumn,
orchestrationOutcomeErrorResponse,
tableLockErrorResponse,
} from '@/app/api/table/utils'
import {
@@ -142,10 +142,7 @@ export const DELETE = withRouteHandler(async (request: NextRequest, context: Tab
const outcome = await performDeleteTable({ table: result.table, userId, requestId, request })
if (!outcome.success) {
return NextResponse.json(
{ error: outcome.error ?? 'Failed to delete table' },
{ status: statusForOrchestrationError(outcome.errorCode) }
)
return orchestrationOutcomeErrorResponse(outcome, 'Failed to delete table')
}
return NextResponse.json({
@@ -9,7 +9,6 @@ import {
v1UpdateTableRowContract,
} from '@/lib/api/contracts/v1/tables'
import { parseRequest } from '@/lib/api/server'
import { statusForOrchestrationError } from '@/lib/core/orchestration/types'
import { generateRequestId } from '@/lib/core/utils/request'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import type { RowData, TableSchema } from '@/lib/table'
@@ -23,6 +22,7 @@ import {
accessError,
checkAccess,
orchestrationErrorResponse,
orchestrationOutcomeErrorResponse,
tableLockErrorResponse,
} from '@/app/api/table/utils'
import {
@@ -240,10 +240,7 @@ export const DELETE = withRouteHandler(async (request: NextRequest, context: Row
const outcome = await performDeleteTableRow({ table: result.table, rowId, requestId })
if (!outcome.success) {
return NextResponse.json(
{ error: outcome.error ?? 'Failed to delete row' },
{ status: statusForOrchestrationError(outcome.errorCode) }
)
return orchestrationOutcomeErrorResponse(outcome, 'Failed to delete row')
}
// Live-collab: tell open viewers the change landed so they refetch.
@@ -33,7 +33,7 @@ import { signalTableRowsChanged } from '@/lib/table/events'
import { createExactEmptyTableRowSecretProvenance } from '@/lib/table/rows/secret-provenance'
import { queryRows } from '@/lib/table/rows/service'
import { resolveFilterSelectValues } from '@/lib/table/select-values'
import { accessError, checkAccess, rowWriteErrorResponse } from '@/app/api/table/utils'
import { accessError, checkAccess, orchestrationErrorResponse } from '@/app/api/table/utils'
import {
checkRateLimit,
checkWorkspaceScope,
@@ -109,7 +109,7 @@ async function handleBatchInsert(
},
})
} catch (error) {
const response = rowWriteErrorResponse(error)
const response = orchestrationErrorResponse(error)
if (response) return response
logger.error(`[${requestId}] Error batch inserting rows:`, error)
@@ -306,7 +306,7 @@ export const POST = withRouteHandler(
const validationResponse = v1ValidationErrorResponseFromError(error)
if (validationResponse) return validationResponse
const response = rowWriteErrorResponse(error)
const response = orchestrationErrorResponse(error)
if (response) return response
logger.error(`[${requestId}] Error inserting row:`, error)
@@ -402,7 +402,7 @@ export const PUT = withRouteHandler(async (request: NextRequest, context: TableR
return NextResponse.json({ error: error.message }, { status: 400 })
}
const response = rowWriteErrorResponse(error)
const response = orchestrationErrorResponse(error)
if (response) return response
logger.error(`[${requestId}] Error updating rows by filter:`, error)
@@ -497,7 +497,7 @@ export const DELETE = withRouteHandler(
return NextResponse.json({ error: error.message }, { status: 400 })
}
const response = rowWriteErrorResponse(error)
const response = orchestrationErrorResponse(error)
if (response) return response
logger.error(`[${requestId}] Error deleting rows:`, error)
+118
View File
@@ -0,0 +1,118 @@
/**
* @vitest-environment node
*
* POST /api/v1/tables maps the create-table service's classified failures onto
* status codes. A duplicate name is a `conflict` and answers 409 — the same
* status every other v1 duplicate-name surface uses (knowledge, files, workflow
* import) — while bad input stays 400 and a quota ceiling stays 403.
*/
import { createMockRequest } from '@sim/testing'
import { NextResponse } from 'next/server'
import { beforeEach, describe, expect, it, vi } from 'vitest'
const { mockCheckRateLimit, mockValidateWorkspaceAccess, mockCreateTable, mockGetLimits } =
vi.hoisted(() => ({
mockCheckRateLimit: vi.fn(),
mockValidateWorkspaceAccess: vi.fn(),
mockCreateTable: vi.fn(),
mockGetLimits: vi.fn(),
}))
vi.mock('@/app/api/v1/middleware', () => ({
checkRateLimit: mockCheckRateLimit,
createRateLimitResponse: () => NextResponse.json({ error: 'Rate limited' }, { status: 429 }),
validateWorkspaceAccess: mockValidateWorkspaceAccess,
v1ValidationErrorResponse: (error: { issues: unknown[] }) =>
NextResponse.json({ error: 'Validation error', details: error.issues }, { status: 400 }),
v1ValidationErrorResponseFromError: () => null,
}))
vi.mock('@/lib/table', () => ({
buildFilterClause: vi.fn(),
createTable: mockCreateTable,
getTableById: vi.fn(),
getWorkspaceTableLimits: mockGetLimits,
listTables: vi.fn(),
TableQueryValidationError: class TableQueryValidationError extends Error {},
}))
vi.mock('@/lib/workspaces/permissions/utils', () => ({
getUserEntityPermissions: vi.fn(),
}))
vi.mock('@/lib/workspaces/utils', () => ({
getWorkspaceOrganizationId: vi.fn().mockResolvedValue(null),
}))
import { OrchestrationError } from '@/lib/core/orchestration/types'
import { POST } from '@/app/api/v1/tables/route'
const WORKSPACE_ID = '11111111-1111-4111-8111-111111111111'
function makeRequest() {
return createMockRequest(
'POST',
{
workspaceId: WORKSPACE_ID,
name: 'Orders',
schema: { columns: [{ name: 'amount', type: 'number' }] },
},
{},
'http://localhost:3000/api/v1/tables'
)
}
describe('POST /api/v1/tables — create failure statuses', () => {
beforeEach(() => {
vi.clearAllMocks()
mockCheckRateLimit.mockResolvedValue({ allowed: true, userId: 'user-1' })
mockValidateWorkspaceAccess.mockResolvedValue(null)
mockGetLimits.mockResolvedValue({ maxTables: 100 })
})
it('answers 409 for a duplicate table name', async () => {
mockCreateTable.mockRejectedValue(
new OrchestrationError('conflict', 'A table named "Orders" already exists in this workspace')
)
const response = await POST(makeRequest())
expect(response.status).toBe(409)
expect(await response.json()).toEqual({
error: 'A table named "Orders" already exists in this workspace',
})
})
it('answers 400 for invalid input', async () => {
mockCreateTable.mockRejectedValue(
new OrchestrationError('validation', 'Invalid table name: name is reserved')
)
const response = await POST(makeRequest())
expect(response.status).toBe(400)
})
it('answers 403 for a workspace at its table limit', async () => {
mockCreateTable.mockRejectedValue(
new OrchestrationError('forbidden', 'Workspace has reached maximum table limit (100)')
)
const response = await POST(makeRequest())
expect(response.status).toBe(403)
})
it('answers a fixed generic 500 for an unclassified failure', async () => {
mockCreateTable.mockRejectedValue(
new Error('Failed query: insert into "user_table" ... params: Orders')
)
const response = await POST(makeRequest())
const body = await response.json()
expect(response.status).toBe(500)
expect(body).toEqual({ error: 'Failed to create table' })
expect(JSON.stringify(body)).not.toContain('Failed query')
})
})
@@ -69,6 +69,17 @@ describe('GET /api/v2/billing/status', () => {
expect(response.headers.get('x-ratelimit-limit')).toBe('100')
})
it('serializes a withheld payer pool as null without failing response validation', async () => {
mocks.execute.mockResolvedValueOnce({ ...result, credits: null, storage: null })
const response = await GET(
new NextRequest('http://localhost:3000/api/v2/billing/status?workspaceId=workspace-1')
)
expect(response.status).toBe(200)
expect(await response.json()).toEqual({ data: { ...result, credits: null, storage: null } })
})
it('projects typed workspace-policy errors', async () => {
mocks.execute.mockRejectedValueOnce(
new OrchestrationError('forbidden', 'API key is not authorized for this workspace')
@@ -33,7 +33,7 @@ export const GET = defineV2JsonRoute({
errorPolicy: customToolResourceErrorPolicy,
mapInput: ({ params, query }) => ({ workspaceId: query.workspaceId, toolId: params.id }),
useCase: getWorkspaceCustomToolUseCase,
present: ({ tool }) => ({ data: { customTool: toV2CustomTool(tool) } }),
present: ({ tool }) => ({ data: toV2CustomTool(tool) }),
})
/** PATCH /api/v2/custom-tools/[id] — Update a custom tool. */
@@ -49,7 +49,7 @@ export const PATCH = defineV2JsonRoute({
source: 'api' as const,
}),
useCase: updateWorkspaceCustomToolUseCase,
present: ({ tool }) => ({ data: { customTool: toV2CustomTool(tool) } }),
present: ({ tool }) => ({ data: toV2CustomTool(tool) }),
})
/** DELETE /api/v2/custom-tools/[id] — Delete a custom tool. */
@@ -144,7 +144,7 @@ describe('/api/v2/custom-tools', () => {
)
expect(response.status).toBe(201)
expect((await response.json()).data.customTool.id).toBe('tool-1')
expect((await response.json()).data.id).toBe('tool-1')
expect(mocks.create).toHaveBeenCalledWith({
principal: PRINCIPAL,
input: {
+1 -1
View File
@@ -39,5 +39,5 @@ export const POST = defineV2JsonRoute({
errorPolicy: v2OrchestrationErrorPolicy,
mapInput: ({ body }) => ({ ...body, source: 'api' as const }),
useCase: createWorkspaceCustomToolUseCase,
present: ({ tool }) => ({ data: { customTool: toV2CustomTool(tool) } }),
present: ({ tool }) => ({ data: toV2CustomTool(tool) }),
})
@@ -66,7 +66,7 @@ vi.mock('@/lib/workspace-files/application/share-workspace-file', () => ({
}))
import { OrchestrationError } from '@/lib/core/orchestration/types'
import { GET, PUT } from '@/app/api/v2/files/[fileId]/share/route'
import { GET, PATCH } from '@/app/api/v2/files/[fileId]/share/route'
const WORKSPACE_ID = 'workspace-1'
const FILE_ID = 'wf_1'
@@ -107,10 +107,10 @@ function callGet(query = `workspaceId=${WORKSPACE_ID}`) {
)
}
function callPut(body: unknown) {
return PUT(
function callPatch(body: unknown) {
return PATCH(
new NextRequest(`http://localhost:3000/api/v2/files/${FILE_ID}/share`, {
method: 'PUT',
method: 'PATCH',
headers: { 'Content-Type': 'application/json', 'x-api-key': 'key' },
body: JSON.stringify(body),
}),
@@ -176,7 +176,7 @@ describe('GET /api/v2/files/[fileId]/share', () => {
const response = await callGet()
expect(response.status).toBe(200)
expect((await response.json()).data).toEqual({ share: SHARE })
expect((await response.json()).data).toEqual(SHARE)
})
it('returns the rate-limit response when denied', async () => {
@@ -190,7 +190,7 @@ describe('GET /api/v2/files/[fileId]/share', () => {
})
})
describe('PUT /api/v2/files/[fileId]/share', () => {
describe('PATCH /api/v2/files/[fileId]/share', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.authenticate.mockResolvedValue(AUTH)
@@ -201,7 +201,7 @@ describe('PUT /api/v2/files/[fileId]/share', () => {
})
it('rejects a caller-supplied token at the v2 boundary', async () => {
const response = await callPut({
const response = await callPatch({
workspaceId: WORKSPACE_ID,
isActive: true,
token: 'attacker-chosen-token',
@@ -217,7 +217,7 @@ describe('PUT /api/v2/files/[fileId]/share', () => {
new OrchestrationError('validation', 'Password is required for password-protected shares')
)
const response = await callPut({ workspaceId: WORKSPACE_ID, isActive: true })
const response = await callPatch({ workspaceId: WORKSPACE_ID, isActive: true })
const body = await response.json()
expect(response.status).toBe(400)
@@ -228,7 +228,7 @@ describe('PUT /api/v2/files/[fileId]/share', () => {
})
it('passes the shared principal and canonical workspace assertion to the use case', async () => {
const response = await callPut({
const response = await callPatch({
workspaceId: WORKSPACE_ID,
isActive: true,
authType: 'password',
@@ -236,7 +236,7 @@ describe('PUT /api/v2/files/[fileId]/share', () => {
})
expect(response.status).toBe(200)
expect((await response.json()).data).toEqual({ share: SHARE })
expect((await response.json()).data).toEqual(SHARE)
expect(mocks.updateShare).toHaveBeenCalledWith({
principal: PRINCIPAL,
input: {
@@ -254,7 +254,7 @@ describe('PUT /api/v2/files/[fileId]/share', () => {
it('preserves generic forbidden updates as forbidden', async () => {
mocks.updateShare.mockRejectedValueOnce(new OrchestrationError('forbidden', 'Access denied'))
const response = await callPut({ workspaceId: WORKSPACE_ID, isActive: true })
const response = await callPatch({ workspaceId: WORKSPACE_ID, isActive: true })
expect(response.status).toBe(403)
expect((await response.json()).error.code).toBe('FORBIDDEN')
@@ -263,7 +263,7 @@ describe('PUT /api/v2/files/[fileId]/share', () => {
it('returns the rate-limit response when denied', async () => {
mocks.operationRate.mockResolvedValueOnce({ ...RATE_LIMIT_OK, allowed: false, remaining: 0 })
const response = await callPut({ workspaceId: WORKSPACE_ID, isActive: true })
const response = await callPatch({ workspaceId: WORKSPACE_ID, isActive: true })
expect(response.status).toBe(429)
expect((await response.json()).error.code).toBe('RATE_LIMITED')
@@ -21,10 +21,10 @@ export const GET = defineV2JsonRoute({
assertedWorkspaceId: query.workspaceId,
}),
useCase: getWorkspaceFileShare,
present: ({ share }) => ({ data: { share } }),
present: ({ share }) => ({ data: share }),
})
export const PUT = defineV2JsonRoute({
export const PATCH = defineV2JsonRoute({
contract: v2UpsertFileShareContract,
auth: v2ApiKeyAuth,
operation: fileOperations.updateShare,
@@ -39,5 +39,5 @@ export const PUT = defineV2JsonRoute({
allowedEmails: body.allowedEmails,
}),
useCase: updateWorkspaceFileShare,
present: ({ share }) => ({ data: { share } }),
present: ({ share }) => ({ data: share }),
})
@@ -64,6 +64,10 @@ vi.mock('@/lib/workspace-files/application/workspace-file-folders', () => ({
},
}))
import {
WorkspaceFileFolderConflictError,
WorkspaceFileItemsNotFoundError,
} from '@/lib/uploads/contexts/workspace/workspace-file-folder-manager'
import { DELETE, GET, PATCH, POST } from '@/app/api/v2/files/folders/route'
const WORKSPACE_ID = 'workspace-1'
@@ -158,8 +162,8 @@ describe('/api/v2/files/folders', () => {
context
)
expect(response.status).toBe(200)
expect((await response.json()).data.folder).toEqual({
expect(response.status).toBe(201)
expect((await response.json()).data).toEqual({
name: 'Reports',
path: '/Reports',
parentPath: '/',
@@ -212,6 +216,52 @@ describe('/api/v2/files/folders', () => {
})
})
it('maps a duplicate folder name to 409 rather than a 500', async () => {
mocks.createFolder.mockRejectedValueOnce(new WorkspaceFileFolderConflictError('Reports'))
const response = await POST(
request('POST', '/api/v2/files/folders', { workspaceId: WORKSPACE_ID, path: '/Reports' }),
context
)
expect(response.status).toBe(409)
const body = await response.json()
expect(body.error.code).toBe('CONFLICT')
expect(body.error.message).toContain('already exists')
})
it('maps a duplicate folder name raised inside a drizzle transaction to 409', async () => {
const wrapped = new Error('insert into "folder" ...', {
cause: new WorkspaceFileFolderConflictError('Reports'),
})
mocks.createFolder.mockRejectedValueOnce(wrapped)
const response = await POST(
request('POST', '/api/v2/files/folders', { workspaceId: WORKSPACE_ID, path: '/Reports' }),
context
)
expect(response.status).toBe(409)
})
it('maps missing folder items to 404 rather than a 500', async () => {
mocks.updateFolder.mockRejectedValueOnce(
new WorkspaceFileItemsNotFoundError([], ['folder-missing'])
)
const response = await PATCH(
request('PATCH', '/api/v2/files/folders', {
workspaceId: WORKSPACE_ID,
path: '/Reports',
destinationPath: '/Archive/Reports',
}),
context
)
expect(response.status).toBe(404)
expect((await response.json()).error.code).toBe('NOT_FOUND')
})
it('authenticates before parsing folder input', async () => {
mocks.authenticate.mockRejectedValueOnce(new MockV2ApiKeyUnauthenticatedError())
+2 -2
View File
@@ -54,7 +54,7 @@ export const POST = defineV2JsonRoute({
errorPolicy: v2FileErrorPolicies.default,
mapInput: ({ body }) => ({ workspaceId: body.workspaceId, path: body.path }),
useCase: createWorkspaceFileFolderOperation,
present: ({ folder }) => ({ data: { folder: toV2Folder(folder) } }),
present: ({ folder }) => ({ data: toV2Folder(folder) }),
})
export const PATCH = defineV2JsonRoute({
@@ -69,7 +69,7 @@ export const PATCH = defineV2JsonRoute({
destinationPath: body.destinationPath,
}),
useCase: updateWorkspaceFileFolderOperation,
present: ({ folder }) => ({ data: { folder: toV2Folder(folder) } }),
present: ({ folder }) => ({ data: toV2Folder(folder) }),
})
export const DELETE = defineV2JsonRoute({
@@ -1,15 +1,16 @@
import { v2CompleteFileUploadContract } from '@/lib/api/contracts/v2/files'
import { defineV2JsonRoute, v2ApiKeyAuth, v2RateLimits } from '@/lib/api/server/routes'
import { completeWorkspaceFileUploadOperation } from '@/lib/uploads/upload-session/application'
import { v2FileErrorPolicies } from '@/lib/workspace-files/api'
import { fileOperations } from '@/lib/workspace-files/application/operations'
import { toV2FileUpload, v2UploadControlError } from '@/app/api/v2/files/uploads/utils'
import { toV2FileUpload } from '@/app/api/v2/files/uploads/utils'
export const POST = defineV2JsonRoute({
contract: v2CompleteFileUploadContract,
auth: v2ApiKeyAuth,
operation: fileOperations.uploadComplete,
rateLimit: v2RateLimits.publicApi,
errorPolicy: { render: v2UploadControlError },
errorPolicy: v2FileErrorPolicies.concealUploadAuthorization,
mapInput: ({ params, query, headers }) => ({
uploadId: params.uploadId,
workspaceId: query.workspaceId,
@@ -1,15 +1,15 @@
import { v2CreateFileUploadPartUrlsContract } from '@/lib/api/contracts/v2/files'
import { defineV2JsonRoute, v2ApiKeyAuth, v2RateLimits } from '@/lib/api/server/routes'
import { issueWorkspaceFileUploadPartsOperation } from '@/lib/uploads/upload-session/application'
import { v2FileErrorPolicies } from '@/lib/workspace-files/api'
import { fileOperations } from '@/lib/workspace-files/application/operations'
import { v2UploadControlError } from '@/app/api/v2/files/uploads/utils'
export const POST = defineV2JsonRoute({
contract: v2CreateFileUploadPartUrlsContract,
auth: v2ApiKeyAuth,
operation: fileOperations.uploadParts,
rateLimit: v2RateLimits.publicApi,
errorPolicy: { render: v2UploadControlError },
errorPolicy: v2FileErrorPolicies.concealUploadAuthorization,
mapInput: ({ params, query, headers, body }) => ({
uploadId: params.uploadId,
workspaceId: query.workspaceId,
@@ -0,0 +1,136 @@
/**
* @vitest-environment node
*/
import { NextRequest } from 'next/server'
import { beforeEach, describe, expect, it, vi } from 'vitest'
const mocks = vi.hoisted(() => ({
abort: vi.fn(),
authenticateV2ApiKey: vi.fn(),
checkRateLimitDirect: vi.fn(),
checkRateLimitDirectOrThrow: vi.fn(),
}))
vi.mock('@/lib/uploads/upload-session/application', () => ({
abortWorkspaceFileUploadOperation: {
operation: { id: 'files.upload.cancel', minimumRole: 'write', workspaceApiKey: 'allow' },
execute: mocks.abort,
},
}))
vi.mock('@/lib/api/server/routes/v2-api-key-auth', () => ({
authenticateV2ApiKey: mocks.authenticateV2ApiKey,
V2ApiKeyUnauthenticatedError: class V2ApiKeyUnauthenticatedError extends Error {},
}))
vi.mock('@/lib/core/rate-limiter', () => ({
getRateLimit: () => ({ maxTokens: 100, refillRate: 50, refillIntervalMs: 60_000 }),
RateLimiter: class RateLimiter {
checkRateLimitDirect = mocks.checkRateLimitDirect
checkRateLimitDirectOrThrow = mocks.checkRateLimitDirectOrThrow
},
}))
vi.mock('@/app/api/v2/lib/gate', () => ({ v2ApiGateError: vi.fn().mockResolvedValue(null) }))
vi.mock('@/app/api/v2/files/uploads/utils', () => ({
toV2FileUpload: vi.fn(async () => ({
id: 'upload-1',
status: 'aborted',
name: 'file.csv',
contentType: 'text/csv',
size: 10,
expiresAt: '2026-08-04T21:00:00.000Z',
error: null,
file: null,
})),
}))
import {
InsufficientWorkspacePermissionsError,
NoWorkspaceAccessError,
WorkspaceApiKeyAuthorizationError,
} from '@/lib/core/application'
import { DELETE } from '@/app/api/v2/files/uploads/[uploadId]/route'
const WORKSPACE_ID = '6fc7631d-88cd-46f8-9f0a-d4764daef7f8'
const UPLOAD_ID = 'upload-1'
const context = { params: Promise.resolve({ uploadId: UPLOAD_ID }) }
const AUTH = {
principal: {
kind: 'workspace_api_key' as const,
workspaceId: WORKSPACE_ID,
keyId: 'key-1',
},
rolloutUserId: 'billing-owner-1',
rateLimitSubjectIds: ['api-key:key-1', `workspace:${WORKSPACE_ID}`] as const,
rateLimitSubscription: null,
keyType: 'workspace' as const,
}
function abortRequest() {
return new NextRequest(
`http://localhost:3000/api/v2/files/uploads/${UPLOAD_ID}?workspaceId=${WORKSPACE_ID}`,
{ method: 'DELETE', headers: { 'x-api-key': 'secret', 'upload-token': 'signed-token' } }
)
}
describe('DELETE /api/v2/files/uploads/[uploadId]', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.authenticateV2ApiKey.mockResolvedValue(AUTH)
mocks.checkRateLimitDirect.mockResolvedValue({
allowed: true,
remaining: 599,
resetAt: new Date('2026-08-04T21:00:00.000Z'),
})
mocks.checkRateLimitDirectOrThrow.mockResolvedValue({
allowed: true,
remaining: 99,
resetAt: new Date('2026-08-04T21:00:00.000Z'),
})
mocks.abort.mockResolvedValue({ id: UPLOAD_ID })
})
it('aborts through the shared use case', async () => {
const response = await DELETE(abortRequest(), context)
expect(response.status).toBe(200)
expect(await response.json()).toMatchObject({ data: { id: UPLOAD_ID, status: 'aborted' } })
})
it('conceals a cross-tenant reach as a missing upload session', async () => {
mocks.abort.mockRejectedValueOnce(new NoWorkspaceAccessError())
const response = await DELETE(abortRequest(), context)
expect(response.status).toBe(404)
expect(await response.json()).toEqual({
error: { code: 'NOT_FOUND', message: 'Upload session not found' },
})
})
/**
* Only cross-tenant reaches are concealed. A workspace key barred from this
* operation is a same-workspace policy denial — the caller owns the session
* and needs to be told why, not handed a misleading 404.
*/
it('keeps a workspace-key policy denial as a 403', async () => {
mocks.abort.mockRejectedValueOnce(new WorkspaceApiKeyAuthorizationError())
const response = await DELETE(abortRequest(), context)
expect(response.status).toBe(403)
})
it('does not conceal a workspace-policy denial behind a not-found', async () => {
mocks.abort.mockRejectedValueOnce(new InsufficientWorkspacePermissionsError())
const response = await DELETE(abortRequest(), context)
expect(response.status).toBe(403)
expect(await response.json()).toEqual({
error: { code: 'FORBIDDEN', message: 'Insufficient workspace permissions' },
})
})
})
@@ -1,15 +1,16 @@
import { v2AbortFileUploadContract } from '@/lib/api/contracts/v2/files'
import { defineV2JsonRoute, v2ApiKeyAuth, v2RateLimits } from '@/lib/api/server/routes'
import { abortWorkspaceFileUploadOperation } from '@/lib/uploads/upload-session/application'
import { v2FileErrorPolicies } from '@/lib/workspace-files/api'
import { fileOperations } from '@/lib/workspace-files/application/operations'
import { toV2FileUpload, v2UploadControlError } from '@/app/api/v2/files/uploads/utils'
import { toV2FileUpload } from '@/app/api/v2/files/uploads/utils'
export const DELETE = defineV2JsonRoute({
contract: v2AbortFileUploadContract,
auth: v2ApiKeyAuth,
operation: fileOperations.uploadCancel,
rateLimit: v2RateLimits.publicApi,
errorPolicy: { render: v2UploadControlError },
errorPolicy: v2FileErrorPolicies.concealUploadAuthorization,
mapInput: ({ params, query, headers }) => ({
uploadId: params.uploadId,
workspaceId: query.workspaceId,
@@ -35,23 +35,3 @@ function uploadStatus(status: string): V2UploadStatus {
}
return status
}
import type { Principal } from '@sim/auth/principal'
import type { NextRequest, NextResponse } from 'next/server'
import { createV2ResourceConcealmentPolicy } from '@/lib/api/server/routes'
import { authenticateV2ApiKey } from '@/lib/api/server/routes/v2-api-key-auth'
const uploadControlErrorPolicy = createV2ResourceConcealmentPolicy({
notFoundMessage: 'Upload session not found',
})
/** Re-authenticates the API key for each upload control leg. */
export async function authenticateUploadPrincipal(request: NextRequest): Promise<Principal> {
const auth = await authenticateV2ApiKey(request.headers.get('x-api-key'))
return auth.principal
}
/** Conceals cross-tenant upload-session authorization while preserving same-workspace denials. */
export function v2UploadControlError(error: unknown): NextResponse | null {
return uploadControlErrorPolicy.render(error)
}
@@ -42,25 +42,23 @@ export const GET = defineV2JsonRoute({
useCase: readKnowledgeDocument,
present: ({ document }) => ({
data: {
document: {
id: document.id,
knowledgeBaseId: document.knowledgeBaseId,
filename: document.filename,
fileSize: document.fileSize,
mimeType: document.mimeType,
processingStatus: toProcessingStatus(document.processingStatus),
processingError: document.processingError,
processingStartedAt: serializeDate(document.processingStartedAt),
processingCompletedAt: serializeDate(document.processingCompletedAt),
chunkCount: document.chunkCount,
tokenCount: document.tokenCount,
characterCount: document.characterCount,
enabled: document.enabled,
connectorId: document.connectorId,
connectorType: document.connectorType,
sourceUrl: document.sourceUrl,
createdAt: serializeDate(document.uploadedAt),
},
id: document.id,
knowledgeBaseId: document.knowledgeBaseId,
filename: document.filename,
fileSize: document.fileSize,
mimeType: document.mimeType,
processingStatus: toProcessingStatus(document.processingStatus),
processingError: document.processingError,
processingStartedAt: serializeDate(document.processingStartedAt),
processingCompletedAt: serializeDate(document.processingCompletedAt),
chunkCount: document.chunkCount,
tokenCount: document.tokenCount,
characterCount: document.characterCount,
enabled: document.enabled,
connectorId: document.connectorId,
connectorType: document.connectorType,
sourceUrl: document.sourceUrl,
createdAt: serializeDate(document.uploadedAt),
},
}),
})
@@ -30,7 +30,7 @@ import { uploadWorkspaceFile } from '@/lib/uploads/contexts/workspace'
import { MAX_KNOWLEDGE_DOCUMENT_FILE_SIZE } from '@/lib/uploads/shared/types'
import { validateFileType } from '@/lib/uploads/utils/validation'
import { serializeDate } from '@/app/api/v1/knowledge/utils'
import { decodeCursor, encodeCursor } from '@/app/api/v2/lib/response'
import { decodeOffsetCursor, encodeCursor } from '@/app/api/v2/lib/response'
export const dynamic = 'force-dynamic'
export const revalidate = 0
@@ -72,25 +72,16 @@ export const GET = defineV2JsonRoute({
operation: knowledgeOperations.listDocuments,
rateLimit: v2RateLimits.publicApi,
errorPolicy: v2KnowledgeErrorPolicies.concealKnowledgeBaseAuthorization,
mapInput: ({ params, query }) => {
const decodedCursor = query.cursor ? decodeCursor<{ offset: number }>(query.cursor) : null
if (
query.cursor &&
(!decodedCursor || !Number.isInteger(decodedCursor.offset) || decodedCursor.offset < 0)
) {
throw new OrchestrationError('validation', 'Invalid cursor')
}
return {
knowledgeBaseId: params.id,
assertedWorkspaceId: query.workspaceId,
enabledFilter: query.enabledFilter,
search: query.search,
limit: query.limit,
offset: decodedCursor?.offset ?? 0,
sortBy: query.sortBy,
sortOrder: query.sortOrder,
}
},
mapInput: ({ params, query }) => ({
knowledgeBaseId: params.id,
assertedWorkspaceId: query.workspaceId,
enabledFilter: query.enabledFilter,
search: query.search,
limit: query.limit,
offset: decodeOffsetCursor(query.cursor),
sortBy: query.sortBy,
sortOrder: query.sortOrder,
}),
useCase: listKnowledgeDocuments,
present: ({ documents, pagination }) => ({
data: documents.map(toV2DocumentSummary),
@@ -169,7 +160,7 @@ export const POST = defineV2BodyLifecycleRoute({
source: 'api' as const,
}),
useCase: uploadKnowledgeDocument,
present: (result) => ({ data: { document: toV2DocumentSummary(result.document) } }),
present: (result) => ({ data: toV2DocumentSummary(result.document) }),
onSuccess: ({ principal, admission, result }) => {
PlatformEvents.knowledgeBaseDocumentsUploaded({
knowledgeBaseId: result.document.knowledgeBaseId,
+2 -2
View File
@@ -31,7 +31,7 @@ export const GET = defineV2JsonRoute({
}),
useCase: readKnowledgeBase,
present: async ({ knowledgeBase, folderPath }) => ({
data: { knowledgeBase: await toV2KnowledgeBase(knowledgeBase, folderPath) },
data: await toV2KnowledgeBase(knowledgeBase, folderPath),
}),
})
@@ -56,7 +56,7 @@ export const PATCH = defineV2JsonRoute({
}),
useCase: updateKnowledgeBaseOperation,
present: async ({ knowledgeBase, folderPath }) => ({
data: { knowledgeBase: await toV2KnowledgeBase(knowledgeBase, folderPath) },
data: await toV2KnowledgeBase(knowledgeBase, folderPath),
}),
})
@@ -54,7 +54,7 @@ export const POST = defineV2JsonRoute({
},
mapInput: ({ body }) => ({ workspaceId: body.workspaceId, path: body.path, source: 'api' }),
useCase: createKnowledgeFolder,
present: ({ folder }) => ({ data: { folder: toFolderPathView(folder, folder.path) } }),
present: ({ folder }) => ({ data: toFolderPathView(folder, folder.path) }),
})
export const PATCH = defineV2JsonRoute({
@@ -73,7 +73,7 @@ export const PATCH = defineV2JsonRoute({
source: 'api',
}),
useCase: relocateKnowledgeFolder,
present: ({ folder }) => ({ data: { folder: toFolderPathView(folder, folder.path) } }),
present: ({ folder }) => ({ data: toFolderPathView(folder, folder.path) }),
})
export const DELETE = defineV2JsonRoute({
+1 -1
View File
@@ -152,7 +152,7 @@ describe('/api/v2/knowledge route composition', () => {
const response = await POST(request)
expect(response.status).toBe(201)
expect((await response.clone().json()).data.knowledgeBase.ownerEmail).toBe('owner@example.com')
expect((await response.clone().json()).data.ownerEmail).toBe('owner@example.com')
expect(mockCreate).toHaveBeenCalledWith({
principal: { kind: 'personal_api_key', userId: 'user-1', keyId: 'key-1' },
input: {
+1 -1
View File
@@ -86,6 +86,6 @@ export const POST = defineV2JsonRoute({
}
},
present: async ({ knowledgeBase, folderPath }) => ({
data: { knowledgeBase: await toV2KnowledgeBase(knowledgeBase, folderPath) },
data: await toV2KnowledgeBase(knowledgeBase, folderPath),
}),
})
@@ -24,9 +24,8 @@ vi.mock('@/lib/knowledge/application/search', () => ({
searchKnowledge: { operation: { id: 'knowledge.search' }, execute: mockSearch },
}))
import { DEFAULT_MAX_JSON_BODY_BYTES } from '@/lib/api/server/validation'
import { KnowledgeUsageLimitExceededError } from '@/lib/knowledge/application/billing'
import { POST } from '@/app/api/v2/knowledge/search/route'
import { POST, V2_KNOWLEDGE_SEARCH_MAX_BODY_BYTES } from '@/app/api/v2/knowledge/search/route'
const WORKSPACE_ID = 'workspace-1'
const PRINCIPAL = { kind: 'workspace_api_key', workspaceId: WORKSPACE_ID, keyId: 'key-1' } as const
@@ -103,6 +102,27 @@ describe('POST /api/v2/knowledge/search', () => {
expect(response.headers.get('x-ratelimit-limit')).toBe('100')
})
it('forwards an opted-in hybrid search mode to the application use case', async () => {
const response = await POST(
buildRequest(
JSON.stringify({
workspaceId: WORKSPACE_ID,
knowledgeBaseIds: ['kb-1'],
query: 'hello',
topK: 10,
searchMode: 'hybrid',
})
)
)
expect(response.status).toBe(200)
expect(mockSearch).toHaveBeenCalledWith(
expect.objectContaining({
input: expect.objectContaining({ searchMode: 'hybrid' }),
})
)
})
it('authenticates before rejecting malformed JSON', async () => {
const response = await POST(buildRequest('{'))
@@ -131,14 +151,14 @@ describe('POST /api/v2/knowledge/search', () => {
})
})
it('preserves the bounded JSON rejection before application execution', async () => {
it('rejects a body over the internal-parity cap before application execution', async () => {
const response = await POST(
buildRequest('{}', { 'content-length': String(DEFAULT_MAX_JSON_BODY_BYTES + 1) })
buildRequest('{}', { 'content-length': String(V2_KNOWLEDGE_SEARCH_MAX_BODY_BYTES + 1) })
)
expect(response.status).toBe(413)
expect(await response.json()).toEqual({
error: `Request body exceeds the maximum allowed size of ${DEFAULT_MAX_JSON_BODY_BYTES} bytes`,
error: { code: 'PAYLOAD_TOO_LARGE', message: 'Request body is too large' },
})
expect(mockSearch).not.toHaveBeenCalled()
expect(response.headers.get('x-ratelimit-limit')).toBe('100')
@@ -8,6 +8,13 @@ import { v2Error } from '@/app/api/v2/lib/response'
export const dynamic = 'force-dynamic'
export const revalidate = 0
/**
* Mirrors the internal Knowledge-search cap in `app/api/knowledge/search/route.ts`
* so the public surface is never more permissive than the internal one. Kept as a
* literal because the internal route declares the same literal inline.
*/
export const V2_KNOWLEDGE_SEARCH_MAX_BODY_BYTES = 2 * 1024 * 1024
/** POST /api/v2/knowledge/search — Vector / tag search across knowledge bases. */
export const POST = defineV2JsonRoute({
contract: v2SearchKnowledgeContract,
@@ -16,7 +23,9 @@ export const POST = defineV2JsonRoute({
rateLimit: v2RateLimits.publicApi,
errorPolicy: v2KnowledgeErrorPolicies.concealKnowledgeBaseUsageAuthorization,
parseOptions: {
maxBodyBytes: V2_KNOWLEDGE_SEARCH_MAX_BODY_BYTES,
invalidJsonResponse: () => v2Error('BAD_REQUEST', 'Request body must be valid JSON'),
payloadTooLargeResponse: () => v2Error('PAYLOAD_TOO_LARGE', 'Request body is too large'),
},
mapInput: ({ body }) => ({
workspaceId: body.workspaceId,
+23 -1
View File
@@ -2,7 +2,11 @@ import { NextResponse } from 'next/server'
import type { ZodError } from 'zod'
import { type CursorKey, INVALID_CURSOR_MESSAGE } from '@/lib/api/list-query'
import { getValidationErrorMessage, serializeZodIssues } from '@/lib/api/server'
import { asOrchestrationError, type OrchestrationErrorCode } from '@/lib/core/orchestration/types'
import {
asOrchestrationError,
OrchestrationError,
type OrchestrationErrorCode,
} from '@/lib/core/orchestration/types'
import type { RateLimitResult, WorkspaceAccessError } from '@/app/api/v1/middleware'
/**
@@ -158,6 +162,24 @@ export function decodeCursor<T = Record<string, unknown>>(cursor: string): T | n
}
}
/**
* Reads back an offset cursor minted by `encodeCursor({ offset })`.
*
* An absent cursor means page one. A cursor that is not valid base64-JSON, or
* that does not carry a non-negative integer `offset`, is rejected rather than
* coerced to 0: silently restarting at page one while the caller believes it is
* paging forward makes a paging client loop over the first page forever. The v2
* error policies render the thrown validation error as the canonical 400.
*/
export function decodeOffsetCursor(cursor: string | undefined): number {
if (!cursor) return 0
const offset = decodeCursor<{ offset?: unknown }>(cursor)?.offset
if (typeof offset !== 'number' || !Number.isInteger(offset) || offset < 0) {
throw new OrchestrationError('validation', 'Invalid cursor')
}
return offset
}
/**
* The sort a keyset cursor was minted under, as it is written into the cursor
* payload. Comparing the whole string is what makes a mid-pagination sort
@@ -34,7 +34,7 @@ export const GET = defineV2JsonRoute({
errorPolicy: mcpServerResourceErrorPolicy,
mapInput: ({ params, query }) => ({ workspaceId: query.workspaceId, serverId: params.id }),
useCase: getMcpServerUseCase,
present: ({ server }) => ({ data: { mcpServer: toV2McpServer(server) } }),
present: ({ server }) => ({ data: toV2McpServer(server) }),
})
/** PATCH /api/v2/mcp-servers/[id] — Update an MCP server's configuration. */
@@ -46,7 +46,7 @@ export const PATCH = defineV2JsonRoute({
errorPolicy: mcpServerResourceErrorPolicy,
mapInput: ({ params, body }) => ({ ...body, serverId: params.id, source: 'api' as const }),
useCase: updateMcpServerUseCase,
present: ({ server }) => ({ data: { mcpServer: toV2McpServer(server) } }),
present: ({ server }) => ({ data: toV2McpServer(server) }),
})
/** DELETE /api/v2/mcp-servers/[id] — Remove an MCP server from the workspace. */
+1 -1
View File
@@ -53,5 +53,5 @@ export const POST = defineV2JsonRoute({
}
)
},
present: ({ server }) => ({ data: { mcpServer: toV2McpServer(server) } }),
present: ({ server }) => ({ data: toV2McpServer(server) }),
})
+5 -5
View File
@@ -1,5 +1,6 @@
import type { NextResponse } from 'next/server'
import { type V2McpServer, v2McpServerSchema } from '@/lib/api/contracts/v2/mcp-servers'
import { projectMcpHeaders } from '@/lib/mcp/projection'
import type { McpServerRow } from '@/lib/mcp/queries'
import { v2Error } from '@/app/api/v2/lib/response'
@@ -13,15 +14,14 @@ import { v2Error } from '@/app/api/v2/lib/response'
* The row is parsed through {@link v2McpServerSchema}, whose strip behaviour is
* the security boundary: `headers`, `oauthClientSecret`, `statusConfig`, and the
* rest of the row are dropped rather than enumerated by hand, so a column added
* later cannot leak by omission. Header *names* are lifted out explicitly.
* later cannot leak by omission. Header *names* are lifted out explicitly by
* {@link projectMcpHeaders}, shared with the internal surface so both read
* surfaces withhold header values by the same rule.
*/
export function toV2McpServer(row: McpServerRow): V2McpServer {
const headers = (row.headers ?? {}) as Record<string, string>
const headerNames = Object.keys(headers)
return v2McpServerSchema.parse({
...row,
hasHeaders: headerNames.length > 0,
headerNames,
...projectMcpHeaders(row.headers),
hasOauthClientSecret: Boolean(row.oauthClientSecret),
})
}
+1 -1
View File
@@ -22,7 +22,7 @@ export const PUT = defineV2JsonRoute({
mapInput: ({ params, body }) => ({ ...body, name: params.name }),
useCase: setSecretUseCase,
statusForResult: ({ created }) => (created ? 201 : 200),
present: ({ secret, userId }) => ({ data: { secret: toV2Secret(secret, userId) } }),
present: ({ secret, userId }) => ({ data: toV2Secret(secret, userId) }),
})
/** DELETE /api/v2/secrets/[name] — Delete a secret without reading its value. */
@@ -116,7 +116,7 @@ describe('/api/v2/skills/[id]', () => {
const response = await GET(request('GET'), context)
expect(response.status).toBe(200)
expect((await response.json()).data.skill.content).toBe(skill.content)
expect((await response.json()).data.content).toBe(skill.content)
expect(mocks.get).toHaveBeenCalledWith({
principal: PRINCIPAL,
input: { workspaceId: WORKSPACE_ID, skillId: skill.id },
+2 -2
View File
@@ -34,7 +34,7 @@ export const GET = defineV2JsonRoute({
errorPolicy: skillResourceErrorPolicy,
mapInput: ({ params, query }) => ({ workspaceId: query.workspaceId, skillId: params.id }),
useCase: getSkillUseCase,
present: ({ skill }) => ({ data: { skill: toV2Skill(skill) } }),
present: ({ skill }) => ({ data: toV2Skill(skill) }),
})
/** PATCH /api/v2/skills/[id] — Update a skill. */
@@ -64,7 +64,7 @@ export const PATCH = defineV2JsonRoute({
{ groups: { workspace: input.workspaceId } }
)
},
present: ({ skill }) => ({ data: { skill: toV2Skill(skill) } }),
present: ({ skill }) => ({ data: toV2Skill(skill) }),
})
/** DELETE /api/v2/skills/[id] — Delete a skill. */
+1 -1
View File
@@ -129,7 +129,7 @@ describe('/api/v2/skills', () => {
)
expect(response.status).toBe(201)
expect((await response.json()).data.skill.id).toBe(skill.id)
expect((await response.json()).data.id).toBe(skill.id)
expect(mocks.create).toHaveBeenCalledWith({
principal: PRINCIPAL,
input: {
+1 -1
View File
@@ -48,5 +48,5 @@ export const POST = defineV2JsonRoute({
{ groups: { workspace: input.workspaceId } }
)
},
present: ({ skill }) => ({ data: { skill: toV2Skill(skill) } }),
present: ({ skill }) => ({ data: toV2Skill(skill) }),
})
@@ -40,6 +40,7 @@ vi.mock('@/lib/users/queries', () => ({
requireResolvedUserEmail: (emails: Map<string, string>, userId: string) => emails.get(userId)!,
}))
import { NoWorkspaceAccessError } from '@/lib/core/application'
import { OrchestrationError } from '@/lib/core/orchestration/types'
import { DELETE, GET, PATCH } from '@/app/api/v2/tables/[tableId]/route'
@@ -129,7 +130,7 @@ describe('/api/v2/tables/[tableId]', () => {
const response = await GET(req, context)
expect(response.status).toBe(200)
expect((await response.json()).data.table).toMatchObject({
expect((await response.json()).data).toMatchObject({
id: 'table-1',
ownerEmail: 'owner@example.com',
})
@@ -147,7 +148,7 @@ describe('/api/v2/tables/[tableId]', () => {
)
expect(response.status).toBe(200)
expect((await response.json()).data.table).toMatchObject({
expect((await response.json()).data).toMatchObject({
name: 'Contacts',
ownerEmail: 'owner@example.com',
})
@@ -175,6 +176,26 @@ describe('/api/v2/tables/[tableId]', () => {
expect((await response.json()).error.details).toEqual({ applied: ['name'] })
})
it('conceals a typed authorization failure on every verb, not just the read', async () => {
mocks.read.mockRejectedValueOnce(new NoWorkspaceAccessError())
mocks.update.mockRejectedValueOnce(new NoWorkspaceAccessError())
mocks.remove.mockRejectedValueOnce(new NoWorkspaceAccessError())
const responses = await Promise.all([
GET(request('GET'), context),
PATCH(request('PATCH', { workspaceId: WORKSPACE_ID, name: 'Renamed' }), context),
DELETE(request('DELETE'), context),
])
for (const response of responses) {
expect(response.status).toBe(404)
expect((await response.json()).error).toEqual({
code: 'NOT_FOUND',
message: 'Table not found',
})
}
})
it('keeps delete analytics surface-specific after authoritative success', async () => {
const response = await DELETE(request('DELETE'), context)
@@ -51,7 +51,7 @@ export const GET = defineV2JsonRoute({
errorPolicy: v2TableErrorPolicies.concealTableAuthorization,
mapInput: ({ params, query }) => ({ tableId: params.tableId, workspaceId: query.workspaceId }),
present: async ({ table, folderPath }) => ({
data: { table: await toApiTable(table, folderPath) },
data: await toApiTable(table, folderPath),
}),
})
@@ -68,7 +68,7 @@ export const PATCH = defineV2JsonRoute({
if (!result.table || result.folderPath === null) {
throw new Error('Updated table is missing from the authoritative result')
}
return { data: { table: await toApiTable(result.table, result.folderPath) } }
return { data: await toApiTable(result.table, result.folderPath) }
},
})
@@ -106,7 +106,7 @@ describe('/api/v2/tables/[tableId]/rows/[rowId]', () => {
const response = await GET(req, CONTEXT)
expect(response.status).toBe(200)
expect((await response.json()).data.row).toEqual({
expect((await response.json()).data).toEqual({
id: 'row-1',
data: { name: 'Ada' },
createdAt: '2026-01-01T00:00:00.000Z',
@@ -136,15 +136,12 @@ describe('/api/v2/tables/[tableId]/rows/[rowId]', () => {
})
})
it('returns the compatible authoritative single-delete envelope', async () => {
it('returns the shared single-resource delete envelope', async () => {
const req = request('DELETE')
const response = await DELETE(req, CONTEXT)
expect(response.status).toBe(200)
expect((await response.json()).data).toEqual({
deletedCount: 1,
deletedRowIds: ['row-1'],
})
expect((await response.json()).data).toEqual({ id: 'row-1', deleted: true })
expect(mocks.deleteRow).toHaveBeenCalledWith(
expect.objectContaining({
principal: PRINCIPAL,
@@ -26,7 +26,7 @@ export const GET = defineV2JsonRoute({
}),
useCase: readTableRow,
present: ({ table, row }) => ({
data: { row: toApiRow(row, namedRowMapper(table.schema.columns)) },
data: toApiRow(row, namedRowMapper(table.schema.columns)),
}),
})
@@ -44,7 +44,7 @@ export const PATCH = defineV2JsonRoute({
}),
useCase: updateTableRow,
present: ({ table, row }) => ({
data: { row: toApiRow(row, namedRowMapper(table.schema.columns)) },
data: toApiRow(row, namedRowMapper(table.schema.columns)),
}),
})
@@ -61,6 +61,6 @@ export const DELETE = defineV2JsonRoute({
}),
useCase: deleteTableRow,
present: ({ deletedRowId }) => ({
data: { deletedCount: 1, deletedRowIds: [deletedRowId] },
data: { id: deletedRowId, deleted: true as const },
}),
})
@@ -111,8 +111,36 @@ describe('/api/v2/tables/[tableId]/rows', () => {
})
})
it('retains malformed GET cursor fallback compatibility', async () => {
const req = request('GET', undefined, `?workspaceId=${WORKSPACE_ID}&limit=25&cursor=malformed`)
/**
* Coercing an undecodable cursor to offset 0 re-served page one while the
* client believed it was paging forward, which loops a paging client forever.
* Every sibling v2 cursor list rejects instead, so this one does too.
*/
it.each([
['undecodable base64-JSON', 'malformed'],
['a payload with no offset', Buffer.from(JSON.stringify({ o: 5 })).toString('base64')],
['a non-integer offset', Buffer.from(JSON.stringify({ offset: 1.5 })).toString('base64')],
['a negative offset', Buffer.from(JSON.stringify({ offset: -1 })).toString('base64')],
])('rejects a GET cursor with %s instead of restarting pagination', async (_label, cursor) => {
const req = request(
'GET',
undefined,
`?workspaceId=${WORKSPACE_ID}&limit=25&cursor=${encodeURIComponent(cursor)}`
)
const response = await GET(req, CONTEXT)
expect(response.status).toBe(400)
expect((await response.json()).error).toMatchObject({ message: 'Invalid cursor' })
expect(mocks.listRows).not.toHaveBeenCalled()
})
it('resumes at the encoded offset for a well-formed cursor', async () => {
const cursor = Buffer.from(JSON.stringify({ offset: 50 })).toString('base64')
const req = request(
'GET',
undefined,
`?workspaceId=${WORKSPACE_ID}&limit=25&cursor=${encodeURIComponent(cursor)}`
)
const response = await GET(req, CONTEXT)
expect(response.status).toBe(200)
@@ -122,7 +150,7 @@ describe('/api/v2/tables/[tableId]/rows', () => {
tableId: 'table-1',
assertedWorkspaceId: WORKSPACE_ID,
limit: 25,
offset: 0,
offset: 50,
},
request: req,
})
@@ -130,7 +158,7 @@ describe('/api/v2/tables/[tableId]/rows', () => {
it('delegates single and batch creation through one semantic use case', async () => {
const single = request('POST', { workspaceId: WORKSPACE_ID, data: { name: 'Ada' } })
expect((await (await POST(single, CONTEXT)).json()).data.row.id).toBe('row-1')
expect((await (await POST(single, CONTEXT)).json()).data.id).toBe('row-1')
expect(mocks.createRows).toHaveBeenLastCalledWith({
principal: PRINCIPAL,
input: {
@@ -14,7 +14,7 @@ import {
updateTableRows,
} from '@/lib/table/application/rows'
import { namedRowMapper } from '@/lib/table/cell-format'
import { decodeCursor, encodeCursor } from '@/app/api/v2/lib/response'
import { decodeOffsetCursor, encodeCursor } from '@/app/api/v2/lib/response'
import { toApiRow } from '@/app/api/v2/tables/utils'
export const dynamic = 'force-dynamic'
@@ -30,7 +30,7 @@ export const GET = defineV2JsonRoute({
tableId: params.tableId,
assertedWorkspaceId: query.workspaceId,
limit: query.limit,
offset: query.cursor ? (decodeCursor<{ offset: number }>(query.cursor)?.offset ?? 0) : 0,
offset: decodeOffsetCursor(query.cursor),
}),
useCase: listTableRows,
present: ({ table, rows, nextOffset }) => {
@@ -61,12 +61,14 @@ export const POST = defineV2JsonRoute({
tableId: params.tableId,
assertedWorkspaceId: body.workspaceId,
data: body.data,
afterRowId: body.afterRowId,
beforeRowId: body.beforeRowId,
},
useCase: createTableRows,
present: (result) => {
const toNamedRow = namedRowMapper(result.table.schema.columns)
return result.kind === 'single'
? { data: { row: toApiRow(result.row, toNamedRow) } }
? { data: toApiRow(result.row, toNamedRow) }
: {
data: {
rows: result.rows.map((row) => toApiRow(row, toNamedRow)),
@@ -97,7 +97,7 @@ describe('/api/v2/tables/[tableId]/views/[viewId]', () => {
const response = await GET(req, context)
expect(response.status).toBe(200)
expect((await response.json()).data.view.id).toBe('view-1')
expect((await response.json()).data.id).toBe('view-1')
expect(mocks.read).toHaveBeenCalledWith({
principal,
input: { tableId: 'table-1', viewId: 'view-1', workspaceId: WORKSPACE_ID },
@@ -112,14 +112,14 @@ describe('/api/v2/tables/[tableId]/views/[viewId]', () => {
)
expect(response.status).toBe(200)
expect((await response.json()).data.view.name).toBe('Active')
expect((await response.json()).data.name).toBe('Active')
})
it('deletes through the authorized view use case', async () => {
const response = await DELETE(request('DELETE'), context)
expect(response.status).toBe(200)
expect(await response.json()).toEqual({ data: { id: 'view-1' } })
expect(await response.json()).toEqual({ data: { id: 'view-1', deleted: true } })
expect(mocks.remove).toHaveBeenCalledOnce()
})
})
@@ -20,9 +20,7 @@ export const revalidate = 0
async function presentView(result: { view: Parameters<typeof toApiView>[0] }) {
const { view } = result
return {
data: {
view: toApiView(view, view.createdBy ? await getRequiredUserEmail(view.createdBy) : null),
},
data: toApiView(view, view.createdBy ? await getRequiredUserEmail(view.createdBy) : null),
}
}
@@ -56,5 +54,5 @@ export const DELETE = defineV2JsonRoute({
rateLimit: v2RateLimits.publicApi,
errorPolicy: v2TableErrorPolicies.concealTableAuthorization,
mapInput: ({ params, query }) => ({ ...params, workspaceId: query.workspaceId }),
present: ({ viewId }) => ({ data: { id: viewId } }),
present: ({ viewId }) => ({ data: { id: viewId, deleted: true as const } }),
})
@@ -122,7 +122,7 @@ describe('/api/v2/tables/[tableId]/views', () => {
const response = await POST(req, context)
expect(response.status).toBe(201)
expect((await response.json()).data.view.createdByEmail).toBe('user@example.com')
expect((await response.json()).data.createdByEmail).toBe('user@example.com')
expect(mocks.create).toHaveBeenCalledWith({
principal,
input: { tableId: 'table-1', workspaceId: WORKSPACE_ID, name: 'Active', config: {} },
@@ -46,8 +46,6 @@ export const POST = defineV2JsonRoute({
errorPolicy: v2TableErrorPolicies.concealTableAuthorization,
mapInput: ({ params, body }) => ({ tableId: params.tableId, ...body }),
present: async ({ view }) => ({
data: {
view: toApiView(view, view.createdBy ? await getRequiredUserEmail(view.createdBy) : null),
},
data: toApiView(view, view.createdBy ? await getRequiredUserEmail(view.createdBy) : null),
}),
})
+2 -2
View File
@@ -40,7 +40,7 @@ export const POST = defineV2JsonRoute({
rateLimit: v2RateLimits.publicApi,
errorPolicy: v2TableErrorPolicies.default,
mapInput: ({ body }) => body,
present: ({ folder, index }) => ({ data: { folder: toV2PathFolder(folder, index, false) } }),
present: ({ folder, index }) => ({ data: toV2PathFolder(folder, index, false) }),
})
export const PATCH = defineV2JsonRoute({
@@ -51,7 +51,7 @@ export const PATCH = defineV2JsonRoute({
rateLimit: v2RateLimits.publicApi,
errorPolicy: v2TableErrorPolicies.default,
mapInput: ({ body }) => body,
present: ({ folder, index }) => ({ data: { folder: toV2PathFolder(folder, index, false) } }),
present: ({ folder, index }) => ({ data: toV2PathFolder(folder, index, false) }),
})
export const DELETE = defineV2JsonRoute({
+1 -1
View File
@@ -163,7 +163,7 @@ describe('/api/v2/tables', () => {
const response = await POST(request)
expect(response.status).toBe(201)
expect((await response.json()).data.table).toMatchObject({
expect((await response.json()).data).toMatchObject({
id: 'table-1',
ownerEmail: 'owner@example.com',
})
+1 -1
View File
@@ -55,6 +55,6 @@ export const POST = defineV2JsonRoute({
folderPath: body.folderPath,
}),
present: async ({ table, folderPath }) => ({
data: { table: await toApiTable(table, folderPath) },
data: await toApiTable(table, folderPath),
}),
})
+12 -5
View File
@@ -17,8 +17,8 @@ import { getUserEmailsByIds, requireResolvedUserEmail } from '@/lib/users/querie
import {
CSV_IMPORT_PROXY_BODY_CAP_BYTES,
normalizeColumn,
orchestrationErrorResponse,
rootErrorMessage,
rowWriteErrorResponse,
} from '@/app/api/table/utils'
import { v2Error, v2ErrorForOrchestration } from '@/app/api/v2/lib/response'
@@ -30,9 +30,16 @@ import { v2Error, v2ErrorForOrchestration } from '@/app/api/v2/lib/response'
* only the HTTP envelope is upgraded.
*/
/** ISO-serializes a `Date | string` timestamp from the table service layer. */
/**
* ISO-serializes a `Date | string` timestamp from the table service layer.
*
* Every current producer is a drizzle select over a `timestamp` column, so the
* value arrives as a `Date`. The string branch normalizes rather than passing the
* value through: the v2 contract promises a strict ISO-8601 instant, and a raw
* Postgres literal (`2026-01-15 10:30:00+00`) would fail response validation.
*/
function toIso(value: Date | string): string {
return value instanceof Date ? value.toISOString() : String(value)
return value instanceof Date ? value.toISOString() : new Date(value).toISOString()
}
/**
@@ -250,12 +257,12 @@ export function v2TableOrchestrationError(
/**
* Maps a known user-facing row-write failure (schema/size/unique/limit) to a v2
* `BAD_REQUEST`, reusing v1's {@link rowWriteErrorResponse} classifier as the
* `BAD_REQUEST`, reusing v1's {@link orchestrationErrorResponse} classifier as the
* single source of truth for which messages are safe to surface. Returns `null`
* for unrecognized errors so the caller logs and returns a generic 500.
*/
export function v2RowWriteError(error: unknown): NextResponse | null {
if (!rowWriteErrorResponse(error)) return null
if (!orchestrationErrorResponse(error)) return null
return v2Error('BAD_REQUEST', rootErrorMessage(error))
}
@@ -63,10 +63,14 @@ export const DELETE = defineV2JsonRoute({
latestDeploymentAttempt: null,
},
}),
/**
* Telemetry only. `workflowOperations.undeploy` denies a workspace API key at
* admission, so a non-personal principal cannot reach here — and this hook runs
* after the undeploy has already committed, so asserting the invariant here
* would report a succeeded undeploy as a 500 rather than catching anything.
*/
onSuccess: ({ principal, result }) => {
if (principal.kind !== 'personal_api_key') {
throw new Error('Admin undeployment unexpectedly admitted a workspace API key')
}
if (principal.kind !== 'personal_api_key') return
captureServerEvent(
principal.userId,
'workflow_undeployed',
@@ -603,6 +603,49 @@ describe('POST /api/v2/workflows/[id]/execute', () => {
expect(mockReleaseExecutionIdClaim).toHaveBeenCalled()
})
it('rejects a call chain at the depth limit on the keyed and anonymous paths', async () => {
const maxChain = Array.from({ length: 25 }, (_, i) => `wf-${i}`).join(',')
const keyed = await callExecute({ input: {} }, { 'X-Sim-Via': maxChain })
expect(keyed.status).toBe(409)
const keyedBody = await keyed.json()
expect(keyedBody.error.code).toBe('CONFLICT')
expect(keyedBody.error.message).toContain('Maximum workflow call chain depth (25) exceeded')
dbChainMockFns.limit.mockReset()
dbChainMockFns.limit.mockResolvedValueOnce([
{ isPublicApi: true, isDeployed: true, userId: 'owner-1', workspaceId: 'workspace-1' },
])
const anonymous = await callPublicExecute({ input: {} }, { 'X-Sim-Via': maxChain })
expect(anonymous.status).toBe(409)
expect((await anonymous.json()).error.code).toBe('CONFLICT')
expect(mockPreprocessExecution).not.toHaveBeenCalled()
expect(mockExecuteWorkflowCore).not.toHaveBeenCalled()
})
it('propagates an incoming call chain into the execution instead of resetting it', async () => {
const keyed = await callExecute({ input: {} }, { 'X-Sim-Via': 'wf-a, wf-b' })
expect(keyed.status).toBe(200)
expect(mockExecuteWorkflowCore.mock.calls[0][0].snapshot.metadata.callChain).toEqual([
'wf-a',
'wf-b',
'workflow-1',
])
dbChainMockFns.limit.mockReset()
dbChainMockFns.limit.mockResolvedValueOnce([
{ isPublicApi: true, isDeployed: true, userId: 'owner-1', workspaceId: 'workspace-1' },
])
const anonymous = await callPublicExecute({ input: {} }, { 'X-Sim-Via': 'wf-a, wf-b' })
expect(anonymous.status).toBe(200)
expect(mockExecuteWorkflowCore.mock.calls[1][0].snapshot.metadata.callChain).toEqual([
'wf-a',
'wf-b',
'workflow-1',
])
})
it('returns a safe error when canonical workflow lookup fails', async () => {
dbChainMockFns.limit.mockReset()
dbChainMockFns.limit.mockRejectedValueOnce(new Error('database connection details'))
@@ -22,6 +22,12 @@ import { ADMISSION_ERROR_DESCRIPTOR } from '@/lib/core/admission/transient-failu
import { generateRequestId } from '@/lib/core/utils/request'
import { getBaseUrl } from '@/lib/core/utils/urls'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import {
buildNextCallChain,
parseCallChain,
SIM_VIA_HEADER,
validateCallChain,
} from '@/lib/execution/call-chain'
import { v2WorkflowErrorPolicies } from '@/lib/workflows/api'
import { executeWorkflowOperation } from '@/lib/workflows/application/execute-workflow'
import { workflowOperations } from '@/lib/workflows/application/operations'
@@ -120,6 +126,19 @@ export const POST = withRouteHandler(
)
if (!admission.success) return admission.response
/**
* Workflow-recursion guard. Mirrors the internal execute route: reject an
* incoming chain that is already at the depth limit, then append this
* workflow so the chain keeps growing across hops instead of resetting.
*/
const incomingCallChain = parseCallChain(req.headers.get(SIM_VIA_HEADER))
const callChainError = validateCallChain(incomingCallChain)
if (callChainError) {
logger.warn(`[${requestId}] Call chain rejected`, { workflowId, error: callChainError })
return v2Error('CONFLICT', callChainError, { details: { code: 'CALL_CHAIN_DEPTH_EXCEEDED' } })
}
const callChain = buildNextCallChain(incomingCallChain, workflowId)
if (admission.auth) {
apiKeyPrincipal = admission.auth.principal
userId = admission.auth.rolloutUserId
@@ -235,6 +254,7 @@ export const POST = withRouteHandler(
requestHeaders: req.headers,
includeThinking: body.includeThinking,
includeToolCalls: body.includeToolCalls,
callChain,
},
request: req,
})
@@ -271,6 +291,7 @@ export const POST = withRouteHandler(
requestHeaders: req.headers,
includeThinking: body.includeThinking,
includeToolCalls: body.includeToolCalls,
callChain,
})
}
@@ -8,15 +8,38 @@ const mocks = vi.hoisted(() => ({
authenticateV2ApiKey: vi.fn(),
checkRateLimitDirect: vi.fn(),
checkRateLimitDirectOrThrow: vi.fn(),
resolvePermission: vi.fn(),
resolveWorkflowContext: vi.fn(),
readVersion: vi.fn(),
gate: vi.fn(),
}))
vi.mock('@/lib/workflows/application/read-workflow-version', () => ({
readWorkflowVersion: {
operation: { id: 'workflows.versions.read' },
execute: mocks.readVersion,
vi.mock('@sim/platform-authz/workspace', () => ({
permissionSatisfies: (actual: string | null, required: string) => {
const rank = { read: 1, write: 2, admin: 3 } as const
return (
actual !== null && rank[actual as keyof typeof rank] >= rank[required as keyof typeof rank]
)
},
resolveEffectiveWorkspacePermission: mocks.resolvePermission,
}))
vi.mock('@/lib/workflows/application/context', () => ({
resolveActiveWorkflowApplicationContext: mocks.resolveWorkflowContext,
}))
vi.mock('@/lib/workflows/persistence/utils', () => ({
getWorkflowDeploymentVersion: mocks.readVersion,
}))
vi.mock('@/blocks/registry', () => ({
getBlock: () => ({
name: 'Slack',
subBlocks: [
{ id: 'credential', type: 'oauth-input' },
{ id: 'botToken', type: 'short-input', password: true },
{ id: 'envToken', type: 'short-input', password: true },
{ id: 'channel', type: 'short-input' },
],
outputs: {},
}),
}))
vi.mock('@/lib/api/server/routes/v2-api-key-auth', () => ({
authenticateV2ApiKey: mocks.authenticateV2ApiKey,
@@ -45,11 +68,44 @@ const auth = {
keyType: 'personal' as const,
}
const workflowContext = {
workspaceId: 'workspace-1',
workspaceOrganizationId: null,
allowPersonalApiKeys: true,
billedAccountUserId: 'billing-owner-1',
workflowId: 'workflow-1',
workflow: { id: 'workflow-1', workspaceId: 'workspace-1' },
}
function versionState() {
return {
blocks: {
'block-1': {
id: 'block-1',
type: 'slack',
name: 'Slack',
subBlocks: {
credential: { id: 'credential', type: 'oauth-input', value: 'oauth-credential-id' },
botToken: { id: 'botToken', type: 'short-input', value: 'xoxb-plaintext-secret' },
envToken: { id: 'envToken', type: 'short-input', value: '{{SLACK_BOT_TOKEN}}' },
channel: { id: 'channel', type: 'short-input', value: '#general' },
},
},
},
edges: [],
loops: {},
parallels: {},
version: '1.0',
}
}
describe('GET /api/v2/workflows/[id]/versions/[version]', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.authenticateV2ApiKey.mockResolvedValue(auth)
mocks.gate.mockResolvedValue(null)
mocks.resolvePermission.mockResolvedValue('admin')
mocks.resolveWorkflowContext.mockResolvedValue(workflowContext)
mocks.checkRateLimitDirect.mockResolvedValue({
allowed: true,
remaining: 599,
@@ -61,30 +117,38 @@ describe('GET /api/v2/workflows/[id]/versions/[version]', () => {
resetAt: new Date('2026-08-01T01:00:00.000Z'),
})
mocks.readVersion.mockResolvedValue({
version: {
id: 'version-2',
version: 2,
name: 'Production',
description: null,
isActive: true,
createdAt: new Date('2026-08-01T00:00:00.000Z'),
state: { blocks: {}, edges: [], loops: {}, parallels: {}, version: '1.0' },
},
id: 'version-2',
version: 2,
name: 'Production',
description: null,
isActive: true,
createdAt: new Date('2026-08-01T00:00:00.000Z'),
state: versionState(),
})
})
it('reads the requested version through the semantic use case', async () => {
async function get() {
const request = new NextRequest('http://localhost/api/v2/workflows/workflow-1/versions/2')
const response = await GET(request, {
params: Promise.resolve({ id: 'workflow-1', version: '2' }),
})
return GET(request, { params: Promise.resolve({ id: 'workflow-1', version: '2' }) })
}
it('reads the requested version only after canonical workflow authorization', async () => {
const response = await get()
expect(response.status).toBe(200)
expect((await response.json()).data).toMatchObject({ id: 'version-2', version: 2 })
expect(mocks.readVersion).toHaveBeenCalledWith({
principal: auth.principal,
input: { workflowId: 'workflow-1', version: 2 },
request,
})
expect(mocks.resolveWorkflowContext).toHaveBeenCalledBefore(mocks.readVersion)
expect(mocks.readVersion).toHaveBeenCalledWith('workflow-1', 2)
})
it('never serves credential values in the pinned graph', async () => {
const response = await get()
expect(response.status).toBe(200)
const subBlocks = (await response.json()).data.state.blocks['block-1'].subBlocks
expect(subBlocks.credential.value).toBeNull()
expect(subBlocks.botToken.value).toBeNull()
expect(subBlocks.envToken.value).toBe('{{SLACK_BOT_TOKEN}}')
expect(subBlocks.channel.value).toBe('#general')
})
})
@@ -55,9 +55,7 @@ export const POST = defineV2JsonRoute({
errorPolicy: v2WorkflowErrorPolicies.default,
mapInput: ({ body }) => ({ workspaceId: body.workspaceId, path: body.path }),
useCase: createWorkflowFolder,
present: ({ folder, index }) => ({
data: { folder: toV2WorkflowFolder(folder, index) },
}),
present: ({ folder, index }) => ({ data: toV2WorkflowFolder(folder, index) }),
})
export const PATCH = defineV2JsonRoute({
@@ -72,9 +70,7 @@ export const PATCH = defineV2JsonRoute({
destinationPath: body.destinationPath,
}),
useCase: relocateWorkflowFolder,
present: ({ folder, index }) => ({
data: { folder: toV2WorkflowFolder(folder, index) },
}),
present: ({ folder, index }) => ({ data: toV2WorkflowFolder(folder, index) }),
})
export const DELETE = defineV2JsonRoute({
@@ -38,7 +38,17 @@ export const GET = defineInternalJsonRoute({
reason: 'Authenticated workspace UI version reads retain their existing admission policy.',
}),
errorPolicy: createInternalWorkflowErrorPolicy('Failed to fetch deployment version'),
mapInput: ({ params }) => ({ workflowId: params.id, version: params.version }),
/**
* The deploy modal renders this graph in the preview editor for a member of the owning
* workspace, who already sees the same credential selections and workspace references on the
* draft graph. Redacting here would blank OAuth accounts and resource selectors in that viewer
* without closing any disclosure boundary, so this surface opts into the raw graph.
*/
mapInput: ({ params }) => ({
workflowId: params.id,
version: params.version,
includeCredentialValues: true,
}),
present: ({ version }) => ({ deployedState: version.state }),
})
@@ -47,7 +47,7 @@ const CSV_PREVIEW_BYTES = 512 * 1024
/**
* Sentinel value for the "Do not import" option in the mapping combobox. The
* whitespace is intentional: valid column names must match `NAME_PATTERN`
* (`/^[a-z_][a-z0-9_]*$/i`), so no real column can share this value.
* (`/^[A-Za-z_][A-Za-z0-9_]*$/`), so no real column can share this value.
*/
const SKIP_VALUE = '__ skip __'
/**
@@ -179,6 +179,8 @@ export function buildTableUsageLimitClear(args: {
tableId,
rowId,
data: {},
/** No cell values are written, so there is nothing to stamp. */
secretProvenance: undefined,
workspaceId,
executionsPatch: { [groupId]: null },
cancellationGuard: { groupId, executionId },
+9 -2
View File
@@ -1,12 +1,13 @@
import { z } from 'zod'
import { type ContractJsonResponse, defineRouteContract } from '@/lib/api/contracts/types'
import { v2TimestampSchema } from '@/lib/api/contracts/v2/shared'
import type { McpToolSchema, McpToolSchemaProperty } from '@/lib/mcp/types'
const MAX_MCP_REFRESH_SERVER_IDS = 100
const dateStringSchema = z.preprocess(
(value) => (value instanceof Date ? value.toISOString() : value),
z.string()
v2TimestampSchema
)
const optionalStringFromNullableSchema = z.preprocess(
@@ -17,7 +18,7 @@ const optionalStringFromNullableSchema = z.preprocess(
const optionalDateStringFromNullableSchema = z.preprocess((value) => {
if (value instanceof Date) return value.toISOString()
return value === null ? undefined : value
}, z.string().optional())
}, v2TimestampSchema.optional())
const optionalNumberFromNullableSchema = z.preprocess(
(value) => (value === null ? undefined : value),
@@ -120,7 +121,13 @@ export const mcpServerSchema = z
url: optionalStringFromNullableSchema,
timeout: optionalNumberFromNullableSchema,
retries: optionalNumberFromNullableSchema,
/**
* Header *values* are the upstream credential and are served only to callers
* who may already rewrite them; readers get `hasHeaders`/`headerNames` alone.
*/
headers: optionalHeadersFromNullableSchema,
hasHeaders: z.boolean().optional(),
headerNames: z.array(z.string()).optional(),
enabled: z.boolean(),
connectionStatus: optionalConnectionStatusFromNullableSchema,
lastError: z.string().nullable().optional(),
@@ -4,7 +4,7 @@
import { readdirSync } from 'node:fs'
import path from 'node:path'
import { describe, expect, it } from 'vitest'
import type { z } from 'zod'
import { z } from 'zod'
/**
* Pins which v2 lists are paged.
@@ -18,6 +18,26 @@ import type { z } from 'zod'
* makes flipping a shipped list from full-set to paged a deliberate edit: a
* `limit` with a default silently truncates callers that read the full set
* today.
*
* The sweep guarantees, for every contract under `contracts/v2` whose response
* is `mode: 'json'`:
*
* - Its response schema is introspectable down to concrete object variants. A
* schema the walk cannot resolve is a hard failure, not a silent pass — a
* list hidden behind an opaque schema would otherwise never be discovered and
* "classifies every v2 list" would succeed vacuously.
* - A response counts as a list only when *every* variant carries both `data`
* and `nextCursor`. A union where only some variants are list-shaped throws:
* that is a genuine design decision (is it paged or not?), not something a
* pinning test should quietly pick a side on.
* - Each discovered list's `query` and `body` are introspectable too, and the
* pagination params are read per variant. The full-set assertion uses
* *any-member* presence, so a defaulted `limit` added to a single union
* member still fails; the paged assertion uses *all-member* presence, so a
* paged list must offer `limit` + `cursor` on every accepted input shape.
*
* `mode !== 'json'` contracts (binary/stream downloads) are skipped — they have
* no JSON envelope to classify.
*/
const CONTRACTS_DIR = path.resolve(import.meta.dirname, '..', '..')
@@ -75,22 +95,110 @@ function isContract(value: unknown): value is ContractLike {
)
}
/** Unwraps `.optional()` / `.default()` / `.superRefine()` / pipe wrappers to the object underneath. */
function objectShape(schema: z.ZodType | undefined): Record<string, unknown> | null {
let current: unknown = schema
for (let depth = 0; current && depth < 8; depth++) {
const def = (current as { def?: Record<string, unknown> }).def
if (!def) return null
if (def.type === 'object') return def.shape as Record<string, unknown>
current = def.innerType ?? def.in ?? def.schema
const MAX_SCHEMA_DEPTH = 12
const PAGINATION_PARAMS = ['limit', 'cursor'] as const
/**
* Resolves a schema to the key sets of every concrete object variant it can
* accept, or `null` when it cannot be resolved.
*
* Unions contribute one entry per member, intersections the cross-product union
* of both sides, wrappers (`.optional()` / `.default()` / `.nullable()` /
* `.catch()` / `.readonly()` / pipes) recurse into the inner (input) type, and
* `z.lazy` is forced once under the depth cap. Returning `null` rather than an
* empty shape is what lets callers treat "cannot introspect" as a failure
* instead of "has no keys".
*/
function variantKeySets(schema: unknown, depth: number = MAX_SCHEMA_DEPTH): string[][] | null {
if (!schema || depth <= 0) return null
const def = (schema as { def?: Record<string, unknown> }).def
if (!def) return null
switch (def.type) {
case 'object':
return [Object.keys(def.shape as Record<string, unknown>)]
case 'union': {
const options = def.options as unknown[] | undefined
if (!options?.length) return null
const variants: string[][] = []
for (const option of options) {
const sets = variantKeySets(option, depth - 1)
if (!sets) return null
variants.push(...sets)
}
return variants
}
case 'intersection': {
const left = variantKeySets(def.left, depth - 1)
const right = variantKeySets(def.right, depth - 1)
if (!left || !right) return null
return left.flatMap((l) => right.map((r) => [...new Set([...l, ...r])]))
}
case 'lazy': {
const getter = def.getter
if (typeof getter !== 'function') return null
try {
return variantKeySets(getter(), depth - 1)
} catch {
return null
}
}
default: {
const inner = def.innerType ?? def.in ?? def.schema
return inner ? variantKeySets(inner, depth - 1) : null
}
}
return null
}
/** A `{ data: T[], nextCursor: string | null }` response. */
function isListResponse(schema: z.ZodType | undefined): boolean {
const shape = objectShape(schema)
return !!shape && 'data' in shape && 'nextCursor' in shape
/**
* Whether a response is the `{ data, nextCursor }` envelope. Throws when the
* schema is opaque, or when a union is only partly list-shaped.
*/
function isListResponse(label: string, schema: z.ZodType | undefined): boolean {
const variants = variantKeySets(schema)
if (!variants) {
throw new Error(
`${label}: v2 json response schema could not be introspected. Teach variantKeySets about it — an opaque response silently hides a list from this sweep.`
)
}
const listy = variants.filter((keys) => keys.includes('data') && keys.includes('nextCursor'))
if (listy.length === 0) return false
if (listy.length === variants.length) return true
throw new Error(
`${label}: response union mixes ${listy.length} list-shaped variant(s) with ${
variants.length - listy.length
} non-list variant(s). Whether this endpoint is paged must be a deliberate decision, not an accident of union ordering.`
)
}
/** Key sets of every input shape the contract accepts across `query` × `body`. */
function inputVariants(label: string, contract: ContractLike): string[][] {
let variants: string[][] = [[]]
for (const [slot, schema] of [
['query', contract.query],
['body', contract.body],
] as const) {
if (!schema) continue
const sets = variantKeySets(schema)
if (!sets) {
throw new Error(
`${label}: ${slot} schema of a v2 list could not be introspected, so its pagination params cannot be checked.`
)
}
variants = variants.flatMap((base) => sets.map((s) => [...new Set([...base, ...s])]))
}
return variants
}
/**
* `any` fails a full-set list the moment one input shape gains a pagination
* param; `all` requires a paged list to offer them on every input shape.
*/
function paginationParams(variants: string[][]): { any: string[]; all: string[] } {
return {
any: PAGINATION_PARAMS.filter((param) => variants.some((keys) => keys.includes(param))),
all: PAGINATION_PARAMS.filter((param) => variants.every((keys) => keys.includes(param))),
}
}
function listContractFiles(dir: string): string[] {
@@ -112,7 +220,7 @@ function listContractFiles(dir: string): string[] {
interface V2ListContract {
key: string
name: string
paginationParams: string[]
params: { any: string[]; all: string[] }
}
/**
@@ -132,15 +240,12 @@ async function sweepV2ListContracts(): Promise<V2ListContract[]> {
for (const [name, value] of Object.entries(mod)) {
if (!isContract(value)) continue
if (!value.path.startsWith('/api/v2/')) continue
if (!isListResponse(value.response?.schema)) continue
if (value.response?.mode !== 'json') continue
const key = `${value.method.toUpperCase()} ${value.path}`
const label = `${name} (${key})`
if (!isListResponse(label, value.response?.schema)) continue
if (found.has(key)) continue
const inputShape = { ...objectShape(value.query), ...objectShape(value.body) }
found.set(key, {
key,
name,
paginationParams: ['limit', 'cursor'].filter((param) => param in inputShape),
})
found.set(key, { key, name, params: paginationParams(inputVariants(label, value)) })
}
}
return [...found.values()].sort((a, b) => a.key.localeCompare(b.key))
@@ -175,10 +280,10 @@ describe('v2 list pagination split', () => {
const byKey = new Map(contracts.map((c) => [c.key, c]))
for (const key of PAGED_LISTS) {
expect(byKey.get(key)?.paginationParams, `${key} is declared paged`).toEqual([
'limit',
'cursor',
])
expect(
byKey.get(key)?.params.all,
`${key} is declared paged, so every input shape it accepts must offer limit and cursor`
).toEqual(['limit', 'cursor'])
}
})
@@ -188,9 +293,40 @@ describe('v2 list pagination split', () => {
for (const key of FULL_SET_LISTS) {
expect(
byKey.get(key)?.paginationParams,
`${key} returns the full set; adding a defaulted limit would truncate existing callers`
byKey.get(key)?.params.any,
`${key} returns the full set; adding a defaulted limit to any accepted input shape would truncate existing callers`
).toEqual([])
}
})
it('sees a pagination param hidden in a single union member', () => {
const unionQuery = z.union([
z.object({ workspaceId: z.string(), limit: z.coerce.number().default(50) }),
z.object({ workspaceId: z.string() }),
])
const variants = inputVariants('synthetic union query', {
method: 'GET',
path: '/api/v2/synthetic',
query: unionQuery,
})
expect(variants).toEqual([['workspaceId', 'limit'], ['workspaceId']])
expect(paginationParams(variants).any).toEqual(['limit'])
expect(paginationParams(variants).all).toEqual([])
})
it('refuses to classify a schema it cannot introspect', () => {
expect(() => isListResponse('synthetic opaque', z.string())).toThrow(
/could not be introspected/
)
expect(() =>
isListResponse(
'synthetic ambiguous',
z.union([
z.object({ data: z.array(z.string()), nextCursor: z.string().nullable() }),
z.object({ error: z.string() }),
])
)
).toThrow(/mixes 1 list-shaped variant/)
})
})
+40 -12
View File
@@ -1,4 +1,5 @@
import { z } from 'zod'
import { workspaceIdSchema } from '@/lib/api/contracts/primitives'
import { defineRouteContract } from '@/lib/api/contracts/types'
import { usageLogPeriodSchema, usageLogSourceSchema } from '@/lib/api/contracts/user'
import { v2CursorListResponse, v2DataResponse } from '@/lib/api/contracts/v2/shared'
@@ -24,8 +25,7 @@ export const v2BillingStatusQuerySchema = z.object({
* Resolve status against one workspace's payer. A workspace-scoped API key
* is always pinned to its own workspace; passing a different id returns 403.
*/
workspaceId: z
.string()
workspaceId: workspaceIdSchema
.optional()
.describe(
'Workspace whose payer should be resolved. Workspace API keys are pinned to their own workspace.'
@@ -35,6 +35,15 @@ export const v2BillingStatusQuerySchema = z.object({
/**
* Current billing standing, credit allowance, and storage quota. Ledger rows
* and source analytics deliberately live outside this status resource.
*
* `credits` and `storage` report the resolved payer's pooled allowances, which
* are shared across every workspace that payer funds. They are populated only
* for a caller who may manage that payer's billing: the billed account holder,
* or an admin of the hosting organization. Billing authority is a property of
* a person, so an actor-less workspace API key never qualifies. Every other
* caller reads both as `null` while still seeing the plan, period, and
* standing that the workspace already surfaces to them enough to monitor for
* `limit_exceeded` and `billing_blocked`.
*/
export const v2BillingStatusDataSchema = z
.object({
@@ -46,32 +55,52 @@ export const v2BillingStatusDataSchema = z
.object({
start: z
.string()
.describe('ISO 8601 start of the current billing period.')
.describe(
'ISO 8601 start of the current billing period, or 1970-01-01T00:00:00.000Z when no Stripe subscription defines one.'
)
.meta({ format: 'date-time' }),
end: z
.string()
.describe('ISO 8601 end of the current billing period.')
.describe(
'ISO 8601 end of the current billing period, or 9999-12-31T00:00:00.000Z when no Stripe subscription defines one.'
)
.meta({ format: 'date-time' }),
})
.describe('Current billing period.'),
.describe(
'Current billing period. Only a Stripe subscription defines a real period; without one — notably on the free plan — this is the open interval 1970-01-01 to 9999-12-31 and must not be read as a monthly window.'
),
plan: z.string().describe('Current billing plan.'),
status: z
.enum(['active', 'limit_exceeded', 'billing_blocked'])
.describe('Current billing standing.'),
credits: z
.object({
used: z.number().describe('Credits consumed during the current billing period.'),
limit: z.number().describe('Credit allowance for the current billing period.'),
remaining: z.number().describe('Credits remaining in the current billing period.'),
used: z
.number()
.describe(
'Credits consumed so far. The counter is reset by Stripe invoice webhooks, so on a paid plan it covers the current billing period; on the free plan nothing resets it and the value is lifetime consumption.'
),
limit: z
.number()
.describe(
'Credit allowance for the reporting window — per billing period on a paid plan, lifetime on the free plan.'
),
remaining: z.number().describe('Allowance minus consumption, over the same window.'),
})
.describe('Credit usage and allowance for the current billing period.'),
.nullable()
.describe(
"The payer's credit usage and allowance — periodic on a paid plan, lifetime on the free plan, where the counter never resets. Null when the caller cannot manage that payer's billing. Always null for a workspace API key."
),
storage: z
.object({
usedBytes: z.number().nonnegative().describe('Storage currently consumed, in bytes.'),
limitBytes: z.number().nonnegative().describe('Storage quota, in bytes.'),
percentUsed: z.number().nonnegative().describe('Percentage of the storage quota consumed.'),
})
.describe('Current storage consumption and quota.'),
.nullable()
.describe(
"The payer's storage consumption and quota, or null when the caller cannot manage that payer's billing. Always null for a workspace API key."
),
})
.meta({
id: 'V2BillingStatus',
@@ -94,8 +123,7 @@ export const v2BillingLogsQuerySchema = z
.object({
source: usageLogSourceSchema.optional().describe('Restrict results to one usage source.'),
/** See {@link v2BillingStatusQuerySchema}'s `workspaceId` — same pinning rules. */
workspaceId: z
.string()
workspaceId: workspaceIdSchema
.optional()
.describe('Restrict results to one workspace whose payer the caller can inspect.'),
period: usageLogPeriodSchema
+10 -9
View File
@@ -2,7 +2,12 @@ import { z } from 'zod'
import { workspaceCredentialRoleSchema } from '@/lib/api/contracts/credentials'
import { workspaceIdSchema } from '@/lib/api/contracts/primitives'
import { defineRouteContract } from '@/lib/api/contracts/types'
import { v2CursorListResponse, v2SearchSchema, v2SortFields } from '@/lib/api/contracts/v2/shared'
import {
v2CursorListResponse,
v2SearchSchema,
v2SortFields,
v2TimestampSchema,
} from '@/lib/api/contracts/v2/shared'
/** Public credentials are authenticated connections, never raw environment secrets. */
export const v2CredentialTypeSchema = z
@@ -26,14 +31,10 @@ export const v2CredentialSchema = z
.boolean()
.describe('Whether a service-account payload is stored. Its contents are never returned.'),
role: workspaceCredentialRoleSchema.describe('Caller role for the credential.'),
createdAt: z
.string()
.datetime()
.describe('ISO 8601 timestamp when the credential was created.'),
updatedAt: z
.string()
.datetime()
.describe('ISO 8601 timestamp when the credential was last updated.'),
createdAt: v2TimestampSchema.describe('ISO 8601 timestamp when the credential was created.'),
updatedAt: v2TimestampSchema.describe(
'ISO 8601 timestamp when the credential was last updated.'
),
})
.meta({
id: 'V2Credential',
+6 -17
View File
@@ -10,6 +10,7 @@ import {
v2DataResponse,
v2SearchSchema,
v2SortFields,
v2TimestampSchema,
} from '@/lib/api/contracts/v2/shared'
/**
@@ -81,8 +82,8 @@ export const v2CustomToolSchema = z
schema: v2CustomToolDeclarationSchema,
/** The tool's implementation body, executed in Sim's sandboxed function runtime. */
code: z.string().describe('Tool implementation executed in the sandboxed function runtime.'),
createdAt: z.string().describe('ISO 8601 timestamp when the tool was created.'),
updatedAt: z.string().describe('ISO 8601 timestamp when the tool was last updated.'),
createdAt: v2TimestampSchema.describe('ISO 8601 timestamp when the tool was created.'),
updatedAt: v2TimestampSchema.describe('ISO 8601 timestamp when the tool was last updated.'),
})
.meta({
id: 'V2CustomTool',
@@ -91,18 +92,6 @@ export const v2CustomToolSchema = z
})
export type V2CustomTool = z.output<typeof v2CustomToolSchema>
/** `{ customTool }` payload for single-tool reads and mutations. */
export const v2CustomToolDataSchema = z
.object({
customTool: v2CustomToolSchema.describe('The custom tool.'),
})
.meta({
id: 'V2CustomToolData',
title: 'Custom tool data',
description: 'A single workspace custom tool payload.',
})
export type V2CustomToolData = z.output<typeof v2CustomToolDataSchema>
export const v2CustomToolDeleteDataSchema = z
.object({
id: z.string().describe('Identifier of the deleted custom tool.'),
@@ -190,7 +179,7 @@ export const v2CreateCustomToolContract = defineRouteContract({
body: v2CreateCustomToolBodySchema,
response: {
mode: 'json',
schema: v2DataResponse(v2CustomToolDataSchema),
schema: v2DataResponse(v2CustomToolSchema),
status: 201,
},
})
@@ -202,7 +191,7 @@ export const v2GetCustomToolContract = defineRouteContract({
query: v2CustomToolWorkspaceQuerySchema,
response: {
mode: 'json',
schema: v2DataResponse(v2CustomToolDataSchema),
schema: v2DataResponse(v2CustomToolSchema),
},
})
@@ -213,7 +202,7 @@ export const v2UpdateCustomToolContract = defineRouteContract({
body: v2UpdateCustomToolBodySchema,
response: {
mode: 'json',
schema: v2DataResponse(v2CustomToolDataSchema),
schema: v2DataResponse(v2CustomToolSchema),
},
})
+35 -46
View File
@@ -12,7 +12,6 @@ import {
v2CursorListResponse,
v2DataResponse,
v2DeleteFolderQuerySchema,
v2ErrorResponseSchema,
v2FolderPathInputSchema,
v2FolderPathSchema,
v2FolderSchema,
@@ -20,6 +19,7 @@ import {
v2RelocateFolderBodySchema,
v2SearchSchema,
v2SortFields,
v2TimestampSchema,
} from '@/lib/api/contracts/v2/shared'
import {
v2PartUrlsBodySchema,
@@ -57,11 +57,15 @@ export const v2FileSchema = z
size: z
.number()
.nonnegative()
.describe('File size in bytes.')
.describe(
'Size in bytes of the stored file. For a generated document (docx, pptx, pdf, xlsx) the stored file is the generation source rather than the rendered document, so this does not predict how many bytes `GET /files/{fileId}` returns — that endpoint serves the compiled artifact, which is typically much larger.'
)
.meta({ examples: [1024] }),
type: z
.string()
.describe('MIME type of the file.')
.describe(
'MIME type of the stored file. For a generated document (docx, pptx, pdf, xlsx) the stored file is the generation source, so this describes the source and not what `GET /files/{fileId}` serves — that endpoint returns the compiled artifact under the rendered document type.'
)
.meta({ examples: ['text/csv'] }),
key: z
.string()
@@ -170,7 +174,7 @@ export const v2FileUploadSchema = z
name: z.string().describe('File name supplied when the session was created.'),
contentType: z.string().describe('MIME type supplied when the session was created.'),
size: z.number().int().nonnegative().describe('Expected file size in bytes.'),
expiresAt: z.string().datetime().describe('ISO 8601 time when the upload session expires.'),
expiresAt: v2TimestampSchema.describe('ISO 8601 time when the upload session expires.'),
error: z.string().nullable().describe('Failure message, or null when no failure has occurred.'),
file: v2FileSchema
.nullable()
@@ -239,7 +243,9 @@ export const v2CreateFileBodySchema = z
.string()
.max(70_000_000, 'content is too large')
.default('')
.describe('Initial file content. Omit or send an empty string for a zero-byte file.'),
.describe(
'Initial file content. Omit or send an empty string for a zero-byte file. The 70,000,000-character bound is a JSON-envelope guard, not the file-size limit: the decoded bytes must be at most 50 MiB, so a longer base64 payload is admitted here and then rejected with 413. Use an upload session for anything larger.'
),
encoding: z
.enum(['utf-8', 'base64'])
.default('utf-8')
@@ -371,16 +377,6 @@ export const v2BulkDeleteFilesResultSchema = z
export type V2BulkDeleteFilesResult = z.output<typeof v2BulkDeleteFilesResultSchema>
export const v2FileFolderDataSchema = z
.object({
folder: v2FolderSchema.describe('Created or relocated folder.'),
})
.meta({
id: 'V2FileFolderData',
title: 'File folder data',
description: 'A created or relocated file folder.',
})
export const v2DeleteFileFolderDataSchema = z
.object({
path: v2FolderPathSchema.describe('Deleted folder path.'),
@@ -409,14 +405,14 @@ export const v2CreateFileFolderContract = defineRouteContract({
method: 'POST',
path: '/api/v2/files/folders',
body: v2CreateFolderBodySchema,
response: { mode: 'json', schema: v2DataResponse(v2FileFolderDataSchema) },
response: { mode: 'json', schema: v2DataResponse(v2FolderSchema), status: 201 },
})
export const v2RelocateFileFolderContract = defineRouteContract({
method: 'PATCH',
path: '/api/v2/files/folders',
body: v2RelocateFolderBodySchema,
response: { mode: 'json', schema: v2DataResponse(v2FileFolderDataSchema) },
response: { mode: 'json', schema: v2DataResponse(v2FolderSchema) },
})
export const v2DeleteFileFolderContract = defineRouteContract({
@@ -426,31 +422,13 @@ export const v2DeleteFileFolderContract = defineRouteContract({
response: { mode: 'json', schema: v2DataResponse(v2DeleteFileFolderDataSchema) },
})
export const v2GetFileShareResultSchema = z
.object({
share: v2FileShareSchema
.nullable()
.describe('Current public share, or null when the file has never been shared.'),
})
.meta({
id: 'V2GetFileShareResult',
title: 'File share result',
description: 'The nullable public-share state for a file.',
})
/**
* The share resource as the read endpoint returns it: `null` when the file has
* never been shared.
*/
export const v2NullableFileShareSchema = v2FileShareSchema.nullable()
export type V2GetFileShareResult = z.output<typeof v2GetFileShareResultSchema>
export const v2UpsertFileShareResultSchema = z
.object({
share: v2FileShareSchema.describe('Updated public share.'),
})
.meta({
id: 'V2UpsertFileShareResult',
title: 'Updated file share',
description: 'The updated public-share state for a file.',
})
export type V2UpsertFileShareResult = z.output<typeof v2UpsertFileShareResultSchema>
export type V2NullableFileShare = z.output<typeof v2NullableFileShareSchema>
/**
* Share upsert body. The internal surface accepts a caller-supplied `token` so
@@ -489,7 +467,9 @@ export const v2UpdateFileContentBodySchema = z
content: z
.string()
.max(70_000_000, 'content is too large')
.describe('Complete replacement content for the file.'),
.describe(
'Complete replacement content for the file. The 70,000,000-character bound is a JSON-envelope guard, not the file-size limit: the decoded bytes must be at most 50 MiB, so a longer base64 payload is admitted here and then rejected with 413.'
),
encoding: z
.enum(['utf-8', 'base64'])
.default('utf-8')
@@ -594,7 +574,6 @@ export const v2RenameFileContract = defineRouteContract({
mode: 'json',
schema: v2DataResponse(v2FileSchema),
},
error: v2ErrorResponseSchema,
})
export const v2DeleteFileContract = defineRouteContract({
@@ -635,18 +614,28 @@ export const v2GetFileShareContract = defineRouteContract({
query: v2FileWorkspaceQuerySchema,
response: {
mode: 'json',
schema: v2DataResponse(v2GetFileShareResultSchema),
schema: v2DataResponse(v2NullableFileShareSchema),
},
})
/**
* PATCH, not PUT: only `isActive` is required, and omitting `authType`,
* `password`, or `allowedEmails` preserves whatever is already stored rather
* than resetting it. The resource is not round-trippable either the share
* representation reports `hasPassword` and never the password itself, so a
* client cannot construct a full replacement body from a prior read.
*
* Disabling with `{ isActive: false }` keeps the token and the whole access
* configuration, so a later `{ isActive: true }` restores the share as it was.
*/
export const v2UpsertFileShareContract = defineRouteContract({
method: 'PUT',
method: 'PATCH',
path: '/api/v2/files/[fileId]/share',
params: v2FileParamsSchema,
body: v2UpsertFileShareBodySchema,
response: {
mode: 'json',
schema: v2DataResponse(v2UpsertFileShareResultSchema),
schema: v2DataResponse(v2FileShareSchema),
},
})
+13 -46
View File
@@ -28,6 +28,7 @@ import {
v2RelocateFolderBodySchema,
v2SearchSchema,
v2SortFields,
v2TimestampSchema,
} from '@/lib/api/contracts/v2/shared'
import {
v2PartUrlsBodySchema,
@@ -150,14 +151,6 @@ export const v2KnowledgeBaseSchema = knowledgeBaseDataSchema
})
export type V2KnowledgeBase = z.output<typeof v2KnowledgeBaseSchema>
/** `{ knowledgeBase }` payload for single-KB reads and mutations. */
export const v2KnowledgeBaseDataSchema = z.object({ knowledgeBase: v2KnowledgeBaseSchema }).meta({
id: 'V2KnowledgeBaseData',
title: 'Knowledge base data',
description: 'A single knowledge base payload.',
})
export type V2KnowledgeBaseData = z.output<typeof v2KnowledgeBaseDataSchema>
/** Delete acknowledgement — the id of the resource that was deleted. */
export const v2KnowledgeDeleteDataSchema = z
.object({
@@ -266,28 +259,6 @@ export const v2KnowledgeDocumentSchema = v2KnowledgeDocumentSummarySchema
})
export type V2KnowledgeDocument = z.output<typeof v2KnowledgeDocumentSchema>
/** `{ document }` payload for the upload acknowledgement (summary shape). */
export const v2KnowledgeDocumentSummaryDataSchema = z
.object({
document: v2KnowledgeDocumentSummarySchema,
})
.meta({
id: 'V2KnowledgeDocumentSummaryData',
title: 'Knowledge document summary data',
description: 'A knowledge document upload acknowledgement.',
})
export type V2KnowledgeDocumentSummaryData = z.output<typeof v2KnowledgeDocumentSummaryDataSchema>
/** `{ document }` payload for the document detail read. */
export const v2KnowledgeDocumentDataSchema = z
.object({ document: v2KnowledgeDocumentSchema })
.meta({
id: 'V2KnowledgeDocumentData',
title: 'Knowledge document data',
description: 'A single knowledge document payload.',
})
export type V2KnowledgeDocumentData = z.output<typeof v2KnowledgeDocumentDataSchema>
/**
* A single vector/tag search hit. `metadata` is the document's display-named tag
* map; values are user-defined and of mixed type (string/number/boolean/date),
@@ -478,7 +449,7 @@ export const v2KnowledgeDocumentUploadSchema = z
name: z.string().describe('Filename recorded on the knowledge document.'),
contentType: z.string().describe('MIME type declared for the document.'),
size: z.number().int().positive().describe('Exact file size in bytes.'),
expiresAt: z.string().datetime().describe('ISO 8601 upload-session expiration time.'),
expiresAt: v2TimestampSchema.describe('ISO 8601 upload-session expiration time.'),
error: z.string().nullable().describe('Terminal upload error, or null when none occurred.'),
document: v2KnowledgeDocumentSummarySchema
.nullable()
@@ -629,7 +600,7 @@ export const v2CreateKnowledgeBaseContract = defineRouteContract({
body: v2CreateKnowledgeBaseBodySchema,
response: {
mode: 'json',
schema: v2DataResponse(v2KnowledgeBaseDataSchema),
schema: v2DataResponse(v2KnowledgeBaseSchema),
status: 201,
},
})
@@ -645,7 +616,7 @@ export const v2GetKnowledgeBaseContract = defineRouteContract({
}),
response: {
mode: 'json',
schema: v2DataResponse(v2KnowledgeBaseDataSchema),
schema: v2DataResponse(v2KnowledgeBaseSchema),
},
})
@@ -660,7 +631,7 @@ export const v2UpdateKnowledgeBaseContract = defineRouteContract({
body: v2UpdateKnowledgeBaseBodySchema,
response: {
mode: 'json',
schema: v2DataResponse(v2KnowledgeBaseDataSchema),
schema: v2DataResponse(v2KnowledgeBaseSchema),
},
})
@@ -679,12 +650,6 @@ export const v2DeleteKnowledgeBaseContract = defineRouteContract({
},
})
export const v2KnowledgeFolderDataSchema = z.object({ folder: v2FolderSchema }).meta({
id: 'V2KnowledgeFolderData',
title: 'Knowledge folder data',
description: 'A single knowledge-base folder payload.',
})
export const v2DeleteKnowledgeFolderDataSchema = z
.object({
path: v2FolderPathSchema.describe('Canonical path of the deleted folder.'),
@@ -717,14 +682,14 @@ export const v2CreateKnowledgeFolderContract = defineRouteContract({
method: 'POST',
path: '/api/v2/knowledge/folders',
body: v2CreateFolderBodySchema,
response: { mode: 'json', schema: v2DataResponse(v2KnowledgeFolderDataSchema), status: 201 },
response: { mode: 'json', schema: v2DataResponse(v2FolderSchema), status: 201 },
})
export const v2RelocateKnowledgeFolderContract = defineRouteContract({
method: 'PATCH',
path: '/api/v2/knowledge/folders',
body: v2RelocateFolderBodySchema,
response: { mode: 'json', schema: v2DataResponse(v2KnowledgeFolderDataSchema) },
response: { mode: 'json', schema: v2DataResponse(v2FolderSchema) },
})
export const v2DeleteKnowledgeFolderContract = defineRouteContract({
@@ -767,12 +732,14 @@ export const v2KnowledgeSearchBodySchema = v1KnowledgeSearchBodySchema.safeExten
.describe('Natural-language query; required when tag filters are omitted.')
.meta({ examples: ['How do I reset my password?'] }),
topK: v1KnowledgeSearchBodySchema.shape.topK.describe(
'Maximum number of search results to return.'
'Maximum number of search results to return. Must be a whole number between 1 and 100; the boundary schema only bounds the range, so a fractional value is admitted here and then rejected with 400 during search.'
),
tagFilters: z
.array(v2KnowledgeSearchTagFilterSchema)
.optional()
.describe('Structured tag filters; supported only for one knowledge base.'),
.describe(
'Structured tag filters. Supported across multiple knowledge bases, but each filtered tag must resolve to the same slot and field type in every knowledge base selected; a tag missing from one of them, or defined inconsistently across them, is rejected and those knowledge bases must be searched separately. With a single knowledge base, an unknown tag name is simply ignored.'
),
searchMode: v1KnowledgeSearchBodySchema.shape.searchMode.describe(
'Retrieval strategy: vector is semantic-only, while hybrid also runs full-text search.'
),
@@ -835,7 +802,7 @@ export const v2UploadKnowledgeDocumentContract = defineRouteContract({
query: v2UploadKnowledgeDocumentQuerySchema,
response: {
mode: 'json',
schema: v2DataResponse(v2KnowledgeDocumentSummaryDataSchema),
schema: v2DataResponse(v2KnowledgeDocumentSummarySchema),
status: 201,
},
})
@@ -891,7 +858,7 @@ export const v2GetKnowledgeDocumentContract = defineRouteContract({
}),
response: {
mode: 'json',
schema: v2DataResponse(v2KnowledgeDocumentDataSchema),
schema: v2DataResponse(v2KnowledgeDocumentSchema),
},
})
+57 -15
View File
@@ -8,7 +8,9 @@ import {
v2DataResponse,
v2FolderPathInputSchema,
v2FolderPathSchema,
v2TimestampSchema,
} from '@/lib/api/contracts/v2/shared'
import type { PersistedWorkflowExecutionStatus } from '@/lib/logs/types'
/**
* v2 logs contracts. The query schemas are reused verbatim from v1 (the request
@@ -20,9 +22,30 @@ const v2LogCostSchema = z
.object({ total: z.number().describe('Total execution cost in USD.') })
.nullable()
.describe('Cost charged for the run, or null when unavailable.')
/**
* Every status the execution logger can persist, including the transient
* `redacting` state written while a finished run's output is scrubbed. The
* column is free text, so a value missing here fails the response parse and
* turns a single row into a 500 for the whole page. `_ExhaustiveLogStatus`
* makes a future addition to the persisted union a compile error instead.
*/
const V2_LOG_STATUSES = [
'pending',
'running',
'redacting',
'completed',
'failed',
'cancelled',
] as const satisfies readonly PersistedWorkflowExecutionStatus[]
type AssertNever<T extends never> = T
type _ExhaustiveLogStatus = AssertNever<
Exclude<PersistedWorkflowExecutionStatus, (typeof V2_LOG_STATUSES)[number]>
>
export const v2LogStatusSchema = z
.enum(['pending', 'running', 'completed', 'failed', 'cancelled'])
.describe('Current execution status.')
.enum(V2_LOG_STATUSES)
.describe('Current execution status. `redacting` is transient while run output is scrubbed.')
/** Execution `files` is a per-run jsonb array of attachment metadata. */
const v2LogFilesSchema = z
@@ -30,6 +53,30 @@ const v2LogFilesSchema = z
.nullable()
.describe('Files attached to the run, or null when none are recorded.')
/**
* The graph as executed, sourced from the run's snapshot row. Declared loose because the
* snapshot is a stored jsonb blob whose interior evolves with the block registry, and the
* response is re-parsed on the way out a strict shape would silently strip block fields a
* diagnostic consumer depends on, or reject an older snapshot outright. `null` when the run's
* snapshot has aged out of retention.
*
* Looseness means the response parse cannot enforce redaction: credential values are nulled in
* the `getPublicLog` use case, which is the single point of truth for what this field may carry.
*/
const v2LogWorkflowStateSchema = z
.object({})
.catchall(
z
.unknown()
.describe(
'One top-level snapshot section — `blocks`, `edges`, `loops`, `parallels`, or `variables` — passed through as stored.'
)
)
.nullable()
.describe(
'Workflow graph snapshot captured for the run, with credential values redacted: `oauth-input` values and `password: true` sub-block values are null, while `{{VAR}}` environment-variable references are preserved. Null when no snapshot is retained.'
)
const v2LogWorkflowSummarySchema = z.object({
id: z.string().nullable().describe('Workflow identifier, or null when unavailable.'),
name: z.string().describe('Workflow name.'),
@@ -48,9 +95,8 @@ export const v2LogListItemSchema = z
status: v2LogStatusSchema,
level: z.string().describe('Log severity level.'),
trigger: z.string().describe('Trigger that started the run.'),
startedAt: z.string().describe('ISO 8601 execution start timestamp.'),
endedAt: z
.string()
startedAt: v2TimestampSchema.describe('ISO 8601 execution start timestamp.'),
endedAt: v2TimestampSchema
.nullable()
.describe('ISO 8601 execution end timestamp, or null while the run is active.'),
totalDurationMs: z
@@ -87,9 +133,8 @@ export const v2LogDetailSchema = z
status: v2LogStatusSchema,
level: z.string().describe('Log severity level.'),
trigger: z.string().describe('Trigger that started the run.'),
startedAt: z.string().describe('ISO 8601 execution start timestamp.'),
endedAt: z
.string()
startedAt: v2TimestampSchema.describe('ISO 8601 execution start timestamp.'),
endedAt: v2TimestampSchema
.nullable()
.describe('ISO 8601 execution end timestamp, or null while the run is active.'),
totalDurationMs: z
@@ -113,19 +158,16 @@ export const v2LogDetailSchema = z
.string()
.nullable()
.describe('Owning workspace identifier, or null when unavailable.'),
createdAt: z
.string()
createdAt: v2TimestampSchema
.nullable()
.describe('ISO 8601 workflow creation timestamp, or null when unavailable.'),
updatedAt: z
.string()
updatedAt: v2TimestampSchema
.nullable()
.describe('ISO 8601 workflow update timestamp, or null when unavailable.'),
deleted: z.boolean().describe('Whether the workflow has been deleted.'),
})
.describe('Workflow snapshot associated with the execution.'),
/** Workflow state snapshot captured for this execution. */
workflowState: z.unknown().describe('Workflow state snapshot captured for the run.'),
workflowState: v2LogWorkflowStateSchema,
/** Materialized block-level execution trace spans. */
traceSpans: traceSpansSchema.describe('Materialized block-level execution trace spans.'),
/** Materialized final output, when the execution produced one. */
@@ -135,7 +177,7 @@ export const v2LogDetailSchema = z
.nullable()
.describe('Materialized final workflow output, or null when none was produced.'),
cost: v2LogCostSchema,
createdAt: z.string().describe('ISO 8601 log creation timestamp.'),
createdAt: v2TimestampSchema.describe('ISO 8601 log creation timestamp.'),
})
.meta({
id: 'V2LogDetail',
+17 -19
View File
@@ -149,18 +149,6 @@ export const v2McpServerSchema = z
})
export type V2McpServer = z.output<typeof v2McpServerSchema>
/** `{ mcpServer }` payload for single-server reads and mutations. */
export const v2McpServerDataSchema = z
.object({
mcpServer: v2McpServerSchema.describe('The MCP server.'),
})
.meta({
id: 'V2McpServerData',
title: 'MCP server data',
description: 'A single public MCP server payload.',
})
export type V2McpServerData = z.output<typeof v2McpServerDataSchema>
/** Delete acknowledgement — the id of the server that was deleted. */
export const v2McpServerDeleteDataSchema = z
.object({
@@ -210,7 +198,10 @@ export const v2CreateMcpServerBodySchema = z
.describe('Optional server description.'),
transport: mcpTransportSchema
.optional()
.describe('Transport used to communicate with the server. Defaults to `streamable-http`.'),
.describe(
'Transport used to communicate with the server. Applied server-side as `streamable-http` when omitted on create.'
)
.meta({ default: 'streamable-http' }),
url: v2McpServerUrlSchema,
authType: mcpAuthTypeSchema
.optional()
@@ -226,18 +217,25 @@ export const v2CreateMcpServerBodySchema = z
.min(1000, 'timeout must be at least 1000ms')
.max(300000, 'timeout must be at most 300000ms')
.optional()
.describe('Per-request timeout in milliseconds. Defaults to 30000.'),
.describe(
'Per-request timeout in milliseconds. Applied server-side as 30000 when omitted on create.'
)
.meta({ default: 30_000 }),
retries: z
.number()
.int('retries must be an integer')
.min(0, 'retries cannot be negative')
.max(10, 'retries must be at most 10')
.optional()
.describe('Number of retries per request. Defaults to 3.'),
.describe('Number of retries per request. Applied server-side as 3 when omitted on create.')
.meta({ default: 3 }),
enabled: z
.boolean()
.optional()
.describe('Whether the server tools are available to workflows. Defaults to true.'),
.describe(
'Whether the server tools are available to workflows. Applied server-side as true when omitted on create.'
)
.meta({ default: true }),
oauthClientId: z
.string()
.max(512, 'oauthClientId is too long')
@@ -294,7 +292,7 @@ export const v2CreateMcpServerContract = defineRouteContract({
body: v2CreateMcpServerBodySchema,
response: {
mode: 'json',
schema: v2DataResponse(v2McpServerDataSchema),
schema: v2DataResponse(v2McpServerSchema),
status: 201,
},
})
@@ -306,7 +304,7 @@ export const v2GetMcpServerContract = defineRouteContract({
query: v2McpServerWorkspaceQuerySchema,
response: {
mode: 'json',
schema: v2DataResponse(v2McpServerDataSchema),
schema: v2DataResponse(v2McpServerSchema),
},
})
@@ -317,7 +315,7 @@ export const v2UpdateMcpServerContract = defineRouteContract({
body: v2UpdateMcpServerBodySchema,
response: {
mode: 'json',
schema: v2DataResponse(v2McpServerDataSchema),
schema: v2DataResponse(v2McpServerSchema),
},
})
@@ -80,8 +80,8 @@ const routes = [
operationId: 'getBillingStatus',
summary: 'Get Billing Status',
description:
'Return the current plan, billing standing, credit allowance, and storage quota. Billing history lives at `GET /api/v2/billing/logs`.',
errors: WORKSPACE_ERRORS,
"Return the current plan, billing standing, credit allowance, and storage quota. `credits` and `storage` report the payer's pooled allowances and are null unless the caller can manage that payer's billing; they are always null for a workspace API key. Billing history lives at `GET /api/v2/billing/logs`. Without a Stripe subscription — notably on the free plan — there is no real billing period: `period` is the open interval 1970-01-01 to 9999-12-31 and `credits.used` is lifetime consumption, not consumption since a period start.",
errors: [...WORKSPACE_ERRORS, 'NotFound'],
success: { description: 'The current billing and storage status.' },
}),
{
@@ -106,8 +106,8 @@ const routes = [
operationId: 'listBillingLogs',
summary: 'List Billing Logs',
description:
'List the credit-denominated billing ledger with source filtering and opaque cursor pagination.',
errors: WORKSPACE_ERRORS,
'List the credit-denominated billing ledger with source filtering and opaque cursor pagination. `period` defaults to `30d`, so an unqualified request covers only the last 30 days: paginating to `nextCursor: null` exhausts that window, not the whole ledger. Pass `period=all` for full history, or `period=custom` with `startDate` and `endDate` for a specific range.',
errors: [...WORKSPACE_ERRORS, 'NotFound'],
success: { description: 'A page of usage events.' },
}),
{
@@ -26,11 +26,15 @@ import {
ERROR_RESPONSES,
type ErrorResponseId,
RATE_LIMIT_HEADERS,
RESOURCE_ERRORS,
STANDARD_ERRORS,
V2_API_KEY_SECURITY,
V2_API_KEY_SECURITY_SCHEMES,
V2_COMMON_HEADERS,
V2_ERROR_SCHEMA,
VALIDATED_ERRORS,
WORKSPACE_API_KEY_DENIED,
WORKSPACE_API_KEY_DENIED_AS_NOT_FOUND,
WORKSPACE_ERRORS,
} from '@/lib/api/contracts/v2/openapi/shared'
import {
@@ -118,7 +122,7 @@ const routes = [
summary: 'List Files',
description:
'List workspace files with search, sorting, folder filtering, and opaque cursor pagination.',
errors: WORKSPACE_ERRORS,
errors: [...WORKSPACE_ERRORS, 'NotFound'],
success: { description: 'A page of workspace files.' },
}),
{
@@ -177,7 +181,7 @@ const routes = [
summary: 'Create File Upload',
description:
'Create a resumable upload session and receive either a signed PUT URL or multipart instructions.',
errors: WORKSPACE_ERRORS,
errors: [...WORKSPACE_ERRORS, 'NotFound'],
success: { description: 'The created upload session and transfer instructions.' },
}),
{
@@ -209,7 +213,7 @@ const routes = [
operationId: 'abortFileUpload',
summary: 'Abort File Upload',
description: 'Abort an active upload session and release provider-side multipart state.',
errors: [...STANDARD_ERRORS, 'NotFound', 'Conflict'],
errors: [...VALIDATED_ERRORS, 'NotFound', 'Conflict'],
success: { description: 'The aborted upload session.' },
}),
{
@@ -353,7 +357,8 @@ const routes = [
filesOperation({
operationId: 'deleteFile',
summary: 'Delete File',
description: 'Delete a workspace file and its stored bytes.',
description:
'Archive a workspace file. This is a soft delete: the row is retained with a deletion timestamp, the file stops appearing in listings and is no longer readable through the API, and its stored bytes are never removed. An archived file can be restored from the workspace Recently Deleted settings; the v2 API exposes no restore operation.',
errors: [...WORKSPACE_ERRORS, 'NotFound', 'Conflict'],
success: { description: 'Deletion confirmation.' },
}),
@@ -454,8 +459,7 @@ const routes = [
auditOperation({
operationId: 'listAuditLogs',
summary: 'List Audit Logs',
description:
'List an organization audit trail with filters and opaque cursor pagination. Requires an Enterprise subscription and organization admin or owner access.',
description: `List an organization audit trail with filters and opaque cursor pagination. Requires an Enterprise subscription and organization admin or owner access. ${WORKSPACE_API_KEY_DENIED}`,
errors: [...STANDARD_ERRORS, 'BadRequest', 'Forbidden'],
success: { description: 'A page of audit-log entries.' },
}),
@@ -480,9 +484,8 @@ const routes = [
auditOperation({
operationId: 'getAuditLog',
summary: 'Get Audit Log',
description:
'Return one organization audit-log entry. Requires an Enterprise subscription and organization admin or owner access.',
errors: [...STANDARD_ERRORS, 'Forbidden', 'NotFound'],
description: `Return one organization audit-log entry. Requires an Enterprise subscription and organization admin or owner access. ${WORKSPACE_API_KEY_DENIED}`,
errors: [...VALIDATED_ERRORS, 'Forbidden', 'NotFound'],
success: { description: 'The requested audit-log entry.' },
}),
{
@@ -544,7 +547,8 @@ const routes = [
filesOperation({
operationId: 'getFileShare',
summary: 'Get File Share',
description: 'Return the current public-share configuration for a file.',
description:
'Return the nullable current public-share configuration for a file. A file that has never been shared returns `data: null` rather than a 404; a share that was created and later disabled is still returned, with `isActive: false`.',
errors: [...WORKSPACE_ERRORS, 'NotFound'],
success: { description: 'Current nullable file-share state.' },
}),
@@ -566,7 +570,7 @@ const routes = [
'V2GetFileShareResponse',
'Get file share response',
'Current public-share state for a file.',
[{ data: { share: SHARE_EXAMPLE } }, { data: { share: null } }]
[{ data: SHARE_EXAMPLE }, { data: null }]
),
}
),
@@ -575,8 +579,7 @@ const routes = [
filesOperation({
operationId: 'upsertFileShare',
summary: 'Enable or Disable File Share',
description:
'Create or update a server-tokenized public share. Disabling retains its token and configuration for later re-enablement.',
description: `Create or partially update a server-tokenized public share. Only isActive is required, and an omitted authType keeps the stored auth mode. What happens to password and allowedEmails depends on the resulting mode, because enabling a share always rewrites the credentials the chosen mode does not use: 'public' clears the stored password and empties allowedEmails; 'password' keeps the stored password when password is omitted but empties allowedEmails; 'email' and 'sso' clear the stored password and keep the stored allowedEmails when the field is omitted. Only disabling with isActive false preserves the whole access configuration untouched — it also retains the token, so re-enabling restores the share as it was. Two enabling combinations are rejected outright with a 400 instead of being partially applied: 'password' when neither a password is supplied nor one is already stored, and 'email' or 'sso' when the resulting allowedEmails would be empty because none was supplied and none is stored. On a file that has never been shared there is nothing stored to fall back on, so enabling any mode other than 'public' must carry its credential in the same request. ${WORKSPACE_API_KEY_DENIED_AS_NOT_FOUND}`,
errors: [...WORKSPACE_ERRORS, 'NotFound'],
success: { description: 'The updated file share.' },
}),
@@ -609,7 +612,7 @@ const routes = [
'V2UpsertFileShareResponse',
'Upsert file share response',
'Updated public-share state for a file.',
[{ data: { share: SHARE_EXAMPLE } }]
[{ data: SHARE_EXAMPLE }]
),
}
),
@@ -686,8 +689,9 @@ const routes = [
filesOperation({
operationId: 'listFilesFolders',
summary: 'List Folders',
description: 'List workspace file folders with optional parent-path filtering and sorting.',
errors: [...WORKSPACE_ERRORS, 'NotFound', 'Conflict'],
description:
'List workspace file folders with optional parent-path filtering and sorting. The bounded set is returned in one page with `nextCursor` always null; there is no second page to fetch.',
errors: RESOURCE_ERRORS,
success: { description: 'Workspace file folders.' },
}),
{
@@ -797,7 +801,7 @@ export const filesAuditOpenApiDocument = defineOpenApiDocument({
info: {
title: 'Sim API v2 — Files & Audit Logs',
description:
'Version 2 of the Sim REST API for workspace files and organization audit logs. Every endpoint uses the canonical v2 data, cursor-list, and error envelopes. Lists use opaque cursors, and rate-limit state is returned in response headers.',
'Version 2 of the Sim REST API for workspace files and organization audit logs. Lists use opaque cursors, and rate-limit state is returned in response headers. Download File streams raw bytes as `application/octet-stream`; every other response uses the canonical v2 data, cursor-list, or error envelope.',
version: '2.0.0',
contact: {
name: 'Sim Support',
@@ -23,12 +23,15 @@ import {
documentedSchema,
ERROR_RESPONSES,
type ErrorResponseId,
FOLDER_TREE_TOO_LARGE,
RATE_LIMIT_HEADERS,
STANDARD_ERRORS,
RESOURCE_CONFLICT_ERRORS,
RESOURCE_ERRORS,
V2_API_KEY_SECURITY,
V2_API_KEY_SECURITY_SCHEMES,
V2_COMMON_HEADERS,
V2_ERROR_SCHEMA,
VALIDATED_ERRORS,
WORKSPACE_ERRORS,
} from '@/lib/api/contracts/v2/openapi/shared'
import {
@@ -63,9 +66,8 @@ const routes = [
knowledgeOperation({
operationId: 'listKnowledgeBases',
summary: 'List Knowledge Bases',
description:
'List knowledge bases in a workspace with folder filtering, search, sorting, and the canonical cursor envelope.',
errors: WORKSPACE_ERRORS,
description: `List knowledge bases in a workspace with folder filtering, search, sorting, and the canonical cursor envelope. The bounded workspace set is returned in one page with \`nextCursor\` always null; there is no second page to fetch. An unknown \`folderPath\` is a 404. ${FOLDER_TREE_TOO_LARGE}`,
errors: [...RESOURCE_ERRORS, 'PayloadTooLarge'],
success: { description: 'A page of knowledge bases.' },
}),
{
@@ -88,9 +90,8 @@ const routes = [
knowledgeOperation({
operationId: 'createKnowledgeBase',
summary: 'Create Knowledge Base',
description:
'Create a knowledge base in a workspace with optional folder placement and chunking configuration.',
errors: [...WORKSPACE_ERRORS, 'Conflict', 'PayloadTooLarge'],
description: `Create a knowledge base in a workspace with optional folder placement and chunking configuration. An unknown \`folderPath\` is a 404. ${FOLDER_TREE_TOO_LARGE}`,
errors: [...RESOURCE_CONFLICT_ERRORS, 'PayloadTooLarge'],
success: { description: 'The created knowledge base.' },
}),
{
@@ -114,9 +115,8 @@ const routes = [
knowledgeOperation({
operationId: 'getKnowledgeBase',
summary: 'Get Knowledge Base',
description:
'Retrieve a knowledge base by identifier. Inaccessible knowledge bases are reported as not found.',
errors: [...STANDARD_ERRORS, 'NotFound'],
description: `Retrieve a knowledge base by identifier. Inaccessible knowledge bases are reported as not found. ${FOLDER_TREE_TOO_LARGE}`,
errors: [...VALIDATED_ERRORS, 'NotFound', 'PayloadTooLarge'],
success: { description: 'The requested knowledge base.' },
}),
{
@@ -145,9 +145,8 @@ const routes = [
knowledgeOperation({
operationId: 'updateKnowledgeBase',
summary: 'Update Knowledge Base',
description:
'Update a knowledge base name, description, chunking configuration, or folder placement.',
errors: [...WORKSPACE_ERRORS, 'NotFound', 'Conflict'],
description: `Update a knowledge base name, description, chunking configuration, or folder placement. ${FOLDER_TREE_TOO_LARGE}`,
errors: [...RESOURCE_CONFLICT_ERRORS, 'PayloadTooLarge'],
success: { description: 'The updated knowledge base.' },
}),
{
@@ -242,7 +241,7 @@ const routes = [
summary: 'List Documents',
description:
'List documents in a knowledge base with filename search, state filtering, sorting, and opaque cursor pagination.',
errors: [...STANDARD_ERRORS, 'NotFound'],
errors: [...VALIDATED_ERRORS, 'NotFound'],
success: { description: 'A page of knowledge documents.' },
}),
{
@@ -443,13 +442,7 @@ const routes = [
summary: 'Complete Document Upload',
description:
'Verify a direct upload or assemble multipart parts, create the knowledge document, and queue asynchronous processing.',
errors: [
...WORKSPACE_ERRORS,
'UsageLimitExceeded',
'NotFound',
'Conflict',
'PayloadTooLarge',
],
errors: [...WORKSPACE_ERRORS, 'UsageLimitExceeded', 'NotFound', 'Conflict'],
success: { description: 'The completed upload and queued document.' },
}),
{
@@ -485,7 +478,7 @@ const routes = [
operationId: 'getKnowledgeDocument',
summary: 'Get Document',
description: 'Retrieve document detail, processing state, and connector provenance.',
errors: [...STANDARD_ERRORS, 'NotFound'],
errors: [...VALIDATED_ERRORS, 'NotFound'],
success: { description: 'The requested knowledge document.' },
}),
{
@@ -514,7 +507,8 @@ const routes = [
knowledgeOperation({
operationId: 'deleteKnowledgeDocument',
summary: 'Delete Document',
description: 'Delete one document and its indexed chunks from a knowledge base.',
description:
'Remove one document from a knowledge base. What that means depends on the document. A directly uploaded document is deleted outright along with its indexed chunks. A connector-backed document is instead excluded: its row survives, marked excluded and disabled so it stops being searchable and a later connector sync does not re-add it, and its embeddings are not deleted. Either way the document no longer appears in listings or search results.',
errors: [...WORKSPACE_ERRORS, 'NotFound'],
success: { description: 'Knowledge document deletion acknowledgement.' },
}),
@@ -544,8 +538,8 @@ const routes = [
knowledgeOperation({
operationId: 'listKnowledgeFolders',
summary: 'List Folders',
description: 'List folders in the knowledge-base folder tree with filtering and sorting.',
errors: [...WORKSPACE_ERRORS, 'NotFound', 'Conflict'],
description: `List folders in the knowledge-base folder tree with filtering and sorting. The bounded set is returned in one page with \`nextCursor\` always null; there is no second page to fetch. ${FOLDER_TREE_TOO_LARGE}`,
errors: [...RESOURCE_ERRORS, 'PayloadTooLarge'],
success: { description: 'A page of knowledge-base folders.' },
}),
{
@@ -568,8 +562,8 @@ const routes = [
knowledgeOperation({
operationId: 'createKnowledgeFolder',
summary: 'Create Folder',
description: 'Create a folder in the knowledge-base folder tree.',
errors: [...WORKSPACE_ERRORS, 'NotFound', 'Conflict'],
description: `Create a folder in the knowledge-base folder tree. ${FOLDER_TREE_TOO_LARGE}`,
errors: [...RESOURCE_CONFLICT_ERRORS, 'PayloadTooLarge'],
success: { description: 'The created knowledge-base folder.' },
}),
{
@@ -593,8 +587,8 @@ const routes = [
knowledgeOperation({
operationId: 'relocateKnowledgeFolder',
summary: 'Rename or Move Folder',
description: 'Rename or move a folder and atomically rewrite descendant paths.',
errors: [...WORKSPACE_ERRORS, 'NotFound', 'Conflict'],
description: `Rename or move a folder and atomically rewrite descendant paths. ${FOLDER_TREE_TOO_LARGE}`,
errors: [...RESOURCE_CONFLICT_ERRORS, 'PayloadTooLarge'],
success: { description: 'The relocated knowledge-base folder.' },
}),
{
@@ -625,7 +619,7 @@ const routes = [
operationId: 'deleteKnowledgeFolder',
summary: 'Delete Folder',
description: 'Delete a folder, optionally including nested folders and knowledge bases.',
errors: [...WORKSPACE_ERRORS, 'NotFound', 'Conflict'],
errors: [...RESOURCE_CONFLICT_ERRORS, 'PayloadTooLarge'],
success: { description: 'Folder deletion acknowledgement and deleted item counts.' },
}),
{
@@ -95,8 +95,8 @@ const routes = [
operationId: 'listLogs',
summary: 'List Logs',
description:
'List workflow execution logs for a workspace with filters, selectable detail, and opaque cursor pagination.',
errors: WORKSPACE_ERRORS,
'List workflow execution logs for a workspace with filters, selectable detail, and opaque cursor pagination. This list predates the shared sort convention: it has no `sortBy` (the sort column is fixed to execution start time) and spells the direction `order` rather than `sortOrder`. Trace spans are stored separately from the log row and are pruned on their own retention schedule: `includeTraceSpans=true` on a run whose stored spans have aged out returns `traceSpans: []` rather than an error, so an empty array does not mean the run recorded no spans.',
errors: [...WORKSPACE_ERRORS, 'NotFound'],
success: { description: 'A page of execution logs matching the filters.' },
}),
{
@@ -121,7 +121,7 @@ const routes = [
operationId: 'getLog',
summary: 'Get Log',
description:
'Retrieve the diagnostic representation of a run, including its workflow snapshot, trace spans, final output, and cost.',
'Retrieve the diagnostic representation of a run, including its workflow snapshot, trace spans, final output, and cost. The returned `workflowState` snapshot has credential values redacted: OAuth credential references and secret (`password`) sub-block values are null, while `{{VAR}}` environment-variable references are preserved so consecutive snapshots stay diffable. Trace spans are stored separately from the log row and are pruned on their own retention schedule: a run whose stored spans have aged out returns `traceSpans: []` rather than an error, so an empty array does not mean the run recorded no spans.',
errors: [...WORKSPACE_ERRORS, 'NotFound'],
success: { description: 'The requested diagnostic log representation.' },
}),
@@ -22,6 +22,7 @@ import {
V2_API_KEY_SECURITY_SCHEMES,
V2_COMMON_HEADERS,
V2_ERROR_SCHEMA,
WORKSPACE_API_KEY_DENIED,
WORKSPACE_ERRORS,
} from '@/lib/api/contracts/v2/openapi/shared'
import {
@@ -250,8 +251,8 @@ const routes = [
operationId: 'listMcpServers',
summary: 'List MCP Servers',
description:
'List MCP servers registered in a workspace. Request-header values and OAuth client secrets are never returned. The bounded workspace set uses the standard cursor envelope with `nextCursor` set to null.',
errors: WORKSPACE_ERRORS,
'List MCP servers registered in a workspace. Request-header values and OAuth client secrets are never returned. The bounded workspace set uses the standard cursor envelope with `nextCursor` always null; there is no second page to fetch.',
errors: [...WORKSPACE_ERRORS, 'NotFound'],
success: { description: 'MCP servers registered in the workspace.' },
}),
{
@@ -276,8 +277,8 @@ const routes = [
operationId: 'createMcpServer',
summary: 'Create MCP Server',
description:
'Register an MCP server in a workspace. The endpoint URL determines server identity, must be absolute HTTP or HTTPS, and cannot contain environment-variable references. Header values and OAuth client secrets are write-only.',
errors: [...WORKSPACE_ERRORS, 'Conflict'],
'Register an MCP server in a workspace. The endpoint URL determines server identity, must be absolute HTTP or HTTPS, and cannot contain environment-variable references. Header values and OAuth client secrets are write-only. `transport`, `timeout`, `retries`, and `enabled` are applied server-side when omitted; the effective values are in the response.',
errors: [...WORKSPACE_ERRORS, 'NotFound', 'Conflict'],
success: { description: 'The MCP server was registered.' },
}),
{
@@ -301,7 +302,7 @@ const routes = [
'CreateMcpServerResponse',
'Create MCP server response',
'The registered MCP server without write-only credentials.',
[{ data: { mcpServer: MCP_SERVER_EXAMPLE } }]
[{ data: MCP_SERVER_EXAMPLE }]
),
}
),
@@ -333,7 +334,7 @@ const routes = [
'GetMcpServerResponse',
'Get MCP server response',
'One MCP server without write-only credentials.',
[{ data: { mcpServer: MCP_SERVER_EXAMPLE } }]
[{ data: MCP_SERVER_EXAMPLE }]
),
}
),
@@ -343,7 +344,7 @@ const routes = [
operationId: 'updateMcpServer',
summary: 'Update MCP Server',
description:
'Update the supplied MCP server fields. The URL is immutable because it determines server identity; delete and recreate the server to change endpoints. Authentication changes invalidate the existing OAuth grant.',
'Update the supplied MCP server fields. The URL is immutable because it determines server identity; delete and recreate the server to change endpoints. Two fields do not follow the omitted-fields-are-retained rule. `headers` is replaced wholesale rather than merged: sending it drops every stored header it does not repeat, and the only way to keep a header is to resend it. Changing `oauthClientId`, or sending `oauthClientSecret` as null or a new value, revokes the stored OAuth grant and forces reauthorization; switching away from OAuth authentication revokes it too.',
errors: [...WORKSPACE_ERRORS, 'NotFound'],
success: { description: 'The updated MCP server.' },
}),
@@ -366,7 +367,7 @@ const routes = [
'UpdateMcpServerResponse',
'Update MCP server response',
'The updated MCP server.',
[{ data: { mcpServer: { ...MCP_SERVER_EXAMPLE, enabled: false } } }]
[{ data: { ...MCP_SERVER_EXAMPLE, enabled: false } }]
),
}
),
@@ -408,8 +409,8 @@ const routes = [
operationId: 'listSkills',
summary: 'List Skills',
description:
'List workspace and built-in skills. Built-ins are marked read-only. The list omits skill bodies and uses the standard cursor envelope with `nextCursor` set to null; fetch one skill to read its content.',
errors: WORKSPACE_ERRORS,
'List workspace and built-in skills. Built-ins are marked read-only. The list omits skill bodies and uses the standard cursor envelope with `nextCursor` always null, so there is no second page to fetch; fetch one skill to read its content.',
errors: [...WORKSPACE_ERRORS, 'NotFound'],
success: { description: 'Skills available in the workspace.' },
}),
{
@@ -434,8 +435,8 @@ const routes = [
operationId: 'createSkill',
summary: 'Create Skill',
description:
'Create one skill in a workspace. Its kebab-case name must be unique and cannot be reserved by a built-in skill.',
errors: [...WORKSPACE_ERRORS, 'Conflict'],
'Create one skill in a workspace. Its kebab-case name must be unique and cannot be reserved by a built-in skill. Note that a workspace API key may create a skill but may not later update or delete it.',
errors: [...WORKSPACE_ERRORS, 'NotFound', 'Conflict'],
success: { description: 'The skill was created.' },
}),
{
@@ -458,7 +459,7 @@ const routes = [
'CreateSkillResponse',
'Create skill response',
'The created skill including its content.',
[{ data: { skill: SKILL_EXAMPLE } }]
[{ data: SKILL_EXAMPLE }]
),
}
),
@@ -490,7 +491,7 @@ const routes = [
'GetSkillResponse',
'Get skill response',
'One skill including its full content.',
[{ data: { skill: SKILL_EXAMPLE } }]
[{ data: SKILL_EXAMPLE }]
),
}
),
@@ -499,8 +500,7 @@ const routes = [
resourceOperation('Skills', {
operationId: 'updateSkill',
summary: 'Update Skill',
description:
'Update the supplied fields on a workspace skill. Omitted fields retain their stored values. Built-in skills are read-only.',
description: `Update the supplied fields on a workspace skill. Omitted fields retain their stored values. Built-in skills are read-only. ${WORKSPACE_API_KEY_DENIED}`,
errors: [...WORKSPACE_ERRORS, 'NotFound', 'Conflict'],
success: { description: 'The updated skill.' },
}),
@@ -523,13 +523,7 @@ const routes = [
'UpdateSkillResponse',
'Update skill response',
'The updated skill including its full content.',
[
{
data: {
skill: { ...SKILL_EXAMPLE, description: 'Updated refund guidance' },
},
},
]
[{ data: { ...SKILL_EXAMPLE, description: 'Updated refund guidance' } }]
),
}
),
@@ -538,7 +532,7 @@ const routes = [
resourceOperation('Skills', {
operationId: 'deleteSkill',
summary: 'Delete Skill',
description: 'Delete a workspace skill. Built-in skills are read-only and cannot be deleted.',
description: `Delete a workspace skill. Built-in skills are read-only and cannot be deleted. ${WORKSPACE_API_KEY_DENIED}`,
errors: [...WORKSPACE_ERRORS, 'NotFound'],
success: { description: 'The skill was deleted.' },
}),
@@ -570,8 +564,8 @@ const routes = [
operationId: 'listCustomTools',
summary: 'List Custom Tools',
description:
'List code-backed custom tools defined in a workspace. Legacy personal tools are excluded. The bounded workspace set uses the standard cursor envelope with `nextCursor` set to null.',
errors: WORKSPACE_ERRORS,
'List code-backed custom tools defined in a workspace. Legacy personal tools are excluded. The bounded workspace set uses the standard cursor envelope with `nextCursor` always null; there is no second page to fetch.',
errors: [...WORKSPACE_ERRORS, 'NotFound'],
success: { description: 'Custom tools defined in the workspace.' },
}),
{
@@ -597,7 +591,7 @@ const routes = [
summary: 'Create Custom Tool',
description:
'Create a code-backed custom tool in a workspace. Its title must be unique because tools resolve by title at call time.',
errors: [...WORKSPACE_ERRORS, 'Conflict'],
errors: [...WORKSPACE_ERRORS, 'NotFound', 'Conflict'],
success: { description: 'The custom tool was created.' },
}),
{
@@ -620,7 +614,7 @@ const routes = [
'CreateCustomToolResponse',
'Create custom tool response',
'The created custom tool.',
[{ data: { customTool: CUSTOM_TOOL_EXAMPLE } }]
[{ data: CUSTOM_TOOL_EXAMPLE }]
),
}
),
@@ -651,7 +645,7 @@ const routes = [
'GetCustomToolResponse',
'Get custom tool response',
'One custom tool.',
[{ data: { customTool: CUSTOM_TOOL_EXAMPLE } }]
[{ data: CUSTOM_TOOL_EXAMPLE }]
),
}
),
@@ -684,13 +678,7 @@ const routes = [
'UpdateCustomToolResponse',
'Update custom tool response',
'The updated custom tool.',
[
{
data: {
customTool: { ...CUSTOM_TOOL_EXAMPLE, code: 'return { ok: false }' },
},
},
]
[{ data: { ...CUSTOM_TOOL_EXAMPLE, code: 'return { ok: false }' } }]
),
}
),
@@ -732,8 +720,8 @@ const routes = [
operationId: 'listCredentials',
summary: 'List Credentials',
description:
'List OAuth and service-account connections visible to the caller. Secret material is never returned. Credential mutations and single-resource reads are intentionally not exposed.',
errors: WORKSPACE_ERRORS,
'List OAuth and service-account connections visible to the caller. Secret material is never returned. Credential mutations and single-resource reads are intentionally not exposed. The bounded set uses the standard cursor envelope with `nextCursor` always null; there is no second page to fetch.',
errors: [...WORKSPACE_ERRORS, 'NotFound'],
success: { description: 'Credentials visible to the caller.' },
}),
{
@@ -757,9 +745,8 @@ const routes = [
resourceOperation('Secrets', {
operationId: 'listSecrets',
summary: 'List Secrets',
description:
'List workspace and caller-owned personal secret metadata. Only names, scope, role, and timestamps are returned; secret values are never read or returned.',
errors: WORKSPACE_ERRORS,
description: `List workspace and caller-owned personal secret metadata. Only names, scope, role, and timestamps are returned; secret values are never read or returned. The bounded set uses the standard cursor envelope with \`nextCursor\` always null; there is no second page to fetch. ${WORKSPACE_API_KEY_DENIED}`,
errors: [...WORKSPACE_ERRORS, 'NotFound'],
success: { description: 'Secret metadata visible to the caller.' },
}),
{
@@ -783,9 +770,8 @@ const routes = [
resourceOperation('Secrets', {
operationId: 'setSecret',
summary: 'Set Secret',
description:
'Create or replace a workspace or caller-owned personal secret. The value is encrypted at rest, is write-only, and is never included in the response.',
errors: WORKSPACE_ERRORS,
description: `Create or replace a workspace or caller-owned personal secret. The value is encrypted at rest, is write-only, and is never included in the response. ${WORKSPACE_API_KEY_DENIED}`,
errors: [...WORKSPACE_ERRORS, 'NotFound'],
success: {
byStatus: {
200: { description: 'The existing secret value was replaced.' },
@@ -818,7 +804,7 @@ const routes = [
'SetSecretResponse',
'Set secret response',
'Metadata for the created or replaced secret without its value.',
[{ data: { secret: SECRET_EXAMPLE } }]
[{ data: SECRET_EXAMPLE }]
),
}
),
@@ -827,8 +813,7 @@ const routes = [
resourceOperation('Secrets', {
operationId: 'deleteSecret',
summary: 'Delete Secret',
description:
'Delete a workspace or caller-owned personal secret without reading or returning its stored value.',
description: `Delete a workspace or caller-owned personal secret without reading or returning its stored value. ${WORKSPACE_API_KEY_DENIED}`,
errors: [...WORKSPACE_ERRORS, 'NotFound'],
success: { description: 'The secret was deleted.' },
}),
@@ -40,11 +40,16 @@ export const ERROR_RESPONSES = {
Conflict: { status: 409, description: 'The request conflicts with current resource state.' },
RunIdConflict: {
status: 409,
description: 'The run identifier is already associated with a different request.',
description:
'The run cannot be started. Two causes share this status, distinguished by `error.details.code`: `RUN_ID_CONFLICT` when the supplied `X-Run-Id` is already associated with a different request, and `CALL_CHAIN_DEPTH_EXCEEDED` when the incoming `X-Sim-Via` chain has already reached the maximum workflow-to-workflow call depth.',
headers: ['X-Run-Id'],
},
Gone: { status: 410, description: 'The requested generated resource has expired.' },
PayloadTooLarge: { status: 413, description: 'The request body exceeds the allowed size.' },
PayloadTooLarge: {
status: 413,
description:
'The request, or a resource collection it must materialize, exceeds the allowed size. Besides an oversized request body, this covers a generated artifact that renders past the download ceiling and a workspace folder tree too large to load in full.',
},
UnsupportedMediaType: {
status: 415,
description: 'The request uses an unsupported media type.',
@@ -55,6 +60,10 @@ export const ERROR_RESPONSES = {
description: 'The caller exceeded the request rate limit.',
headers: ['Retry-After'],
},
ClientClosedRequest: {
status: 499,
description: 'The client closed the connection before the response was produced.',
},
InternalError: { status: 500, description: 'An unexpected server error occurred.' },
ServiceUnavailable: {
status: 503,
@@ -64,6 +73,55 @@ export const ERROR_RESPONSES = {
export type ErrorResponseId = keyof typeof ERROR_RESPONSES
/**
* {@link STANDARD_ERRORS} plus the 400 that any operation parsing required path,
* query, header, or body input returns when that input fails contract validation.
* `STANDARD_ERRORS` alone is only correct for an operation with nothing to parse.
*/
export const VALIDATED_ERRORS = [
'BadRequest',
...STANDARD_ERRORS,
] as const satisfies readonly ErrorResponseId[]
/**
* The three sets below are the only shapes every workspace-scoped resource
* operation in the v2 API actually emits, so they live here once rather than
* being re-derived per domain. Eight per-domain aliases previously denoted these
* same three sets under names that implied distinctions the generated spec never
* had responses are keyed by status, so two spellings of the same status set
* produce byte-identical output.
*
* The base: an operation that resolves a workspace-scoped resource and can report
* it missing.
*/
export const RESOURCE_ERRORS = [
...WORKSPACE_ERRORS,
'NotFound',
] as const satisfies readonly ErrorResponseId[]
/**
* {@link RESOURCE_ERRORS} plus the `409` a name collision, a duplicate or cyclic
* folder destination, or a competing lifecycle state produces.
*/
export const RESOURCE_CONFLICT_ERRORS = [
...RESOURCE_ERRORS,
'Conflict',
] as const satisfies readonly ErrorResponseId[]
/**
* {@link RESOURCE_CONFLICT_ERRORS} plus the `423` a mutation lock raises the
* `lib/table/mutation-locks` asserts, the workflow-folder lock (the only folder
* type with `supportsLocking`), and the delete-locked-table subtree guard.
*
* Reads, exports, and metadata edits never cross a lock assert, so they must use
* one of the two narrower sets: a documented `423` an operation cannot emit is
* worse than none.
*/
export const RESOURCE_MUTATION_ERRORS = [
...RESOURCE_CONFLICT_ERRORS,
'Locked',
] as const satisfies readonly ErrorResponseId[]
export const V2_API_KEY_SECURITY = [{ apiKey: [] }] as const
export const V2_API_KEY_SECURITY_SCHEMES = {
@@ -72,10 +130,38 @@ export const V2_API_KEY_SECURITY_SCHEMES = {
in: 'header',
name: 'X-API-Key',
description:
'Your Sim API key (personal or workspace). Generate one from the Sim dashboard under Settings > API Keys.',
'Your Sim API key, personal or workspace-scoped. Generate one from the Sim dashboard under Settings > API Keys. A workspace API key is not accepted everywhere: operations that act on behalf of a specific human — administrative reads, secret access, and irreversible or governance-affecting writes — always reject it, whatever role the key carries. Each such operation says so in its own description, and the rejection surfaces as `403` unless the operation conceals unauthorized resources, in which case it is reported as `404`. Use a personal API key for those.',
},
} as const satisfies Readonly<Record<string, OpenApiSecurityScheme>>
/**
* Appended to an operation whose response must resolve a canonical folder path,
* which requires loading the workspace's whole folder tree. The `413` is the
* tree-size ceiling, not a request-body limit see `ERROR_RESPONSES.PayloadTooLarge`.
*
* Operations that merely *accept* a `folderPath` and can emit the `413` without
* rendering one back do not need this sentence: the shared `413` response
* description already covers them.
*/
export const FOLDER_TREE_TOO_LARGE =
'A workspace whose folder tree exceeds 10,000 folders is a 413, because the response needs the whole tree to render folder paths.'
/**
* Appended to an operation whose semantic operation sets `workspaceApiKey: 'deny'`.
* That policy is structural an `admin` operation can never accept a workspace key
* so it is not something a workspace owner can grant around.
*/
export const WORKSPACE_API_KEY_DENIED =
'A workspace API key cannot call this operation and is rejected with `403`; use a personal API key.'
/**
* {@link WORKSPACE_API_KEY_DENIED} for an operation behind the resource-concealment
* error policy, which rewrites the authorization failure to a not-found response so
* the caller learns nothing about the resource.
*/
export const WORKSPACE_API_KEY_DENIED_AS_NOT_FOUND =
'A workspace API key cannot call this operation. Because unauthorized resources are concealed, the rejection is reported as `404` rather than `403`; use a personal API key.'
export const V2_COMMON_HEADERS = {
'X-RateLimit-Limit': {
schema: z.number().int().nonnegative().meta({
+66 -62
View File
@@ -2,8 +2,11 @@ import {
documentedSchema,
ERROR_RESPONSES,
type ErrorResponseId,
FOLDER_TREE_TOO_LARGE,
RATE_LIMIT_HEADERS,
STANDARD_ERRORS,
RESOURCE_CONFLICT_ERRORS,
RESOURCE_ERRORS,
RESOURCE_MUTATION_ERRORS,
V2_API_KEY_SECURITY,
V2_API_KEY_SECURITY_SCHEMES,
V2_COMMON_HEADERS,
@@ -70,23 +73,22 @@ const GROUP_ID = 'grp_5d8b2f0a6c1e4739a8b3d5f7e9c1a204'
const IMPORT_ID = 'imp_4f6a8c0e2b1d43759a7c9e1f3b5d7082'
const EXPORT_ID = 'exp_3e5f7a9c1b2d4068a0c2e4f6b8d0f193'
const TABLE_RESOURCE_ERRORS = [
...WORKSPACE_ERRORS,
'NotFound',
] as const satisfies readonly ErrorResponseId[]
/**
* Only for operations that genuinely reach a `lib/table/mutation-locks` assert
* (`assertRowInsert` / `assertRowUpdate` / `assertRowDelete` /
* `assertSchemaMutable` / `assertColumnDestructive`) or the equivalent inline
* lock predicate in `deleteTable`, and that cannot also conflict.
*
* The four lock flags gate row writes and schema changes only. Reads, exports,
* saved-view edits, table metadata edits (`renameTable` /
* `updateTableDescription` / `moveTableToFolder` all assert nothing), and
* run dispatch/cancellation are never blocked, so those operations must NOT use
* this set a documented `423` they cannot emit is worse than none.
*/
const TABLE_MUTATION_ERRORS = [
...TABLE_RESOURCE_ERRORS,
...RESOURCE_ERRORS,
'Locked',
] as const satisfies readonly ErrorResponseId[]
const TABLE_CONFLICT_ERRORS = [
...TABLE_MUTATION_ERRORS,
'Conflict',
] as const satisfies readonly ErrorResponseId[]
const TRANSFER_RESOURCE_ERRORS = [
...STANDARD_ERRORS,
'NotFound',
'Conflict',
] as const satisfies readonly ErrorResponseId[]
function tableOperation(
operation: Omit<OpenApiOperationMetadata, 'tags' | 'success' | 'errors'> & {
@@ -110,10 +112,9 @@ const routes = [
tableOperation({
operationId: 'listTables',
summary: 'List Tables',
description:
'List all tables in a workspace with optional folder filtering, search, sorting, and an opaque cursor envelope.',
errors: WORKSPACE_ERRORS,
success: { description: 'The tables in the workspace.' },
description: `List tables in a workspace with optional folder filtering, search, sorting, and an opaque cursor envelope. ${FOLDER_TREE_TOO_LARGE}`,
errors: [...WORKSPACE_ERRORS, 'NotFound', 'PayloadTooLarge'],
success: { description: 'A page of tables in the workspace.' },
}),
{
query: documentedSchema(
@@ -136,7 +137,7 @@ const routes = [
operationId: 'createTable',
summary: 'Create Table',
description: 'Create a table with a typed column schema and optional folder placement.',
errors: [...WORKSPACE_ERRORS, 'Conflict'],
errors: [...WORKSPACE_ERRORS, 'NotFound', 'Conflict', 'PayloadTooLarge'],
success: { description: 'The created table.' },
}),
{
@@ -172,8 +173,8 @@ const routes = [
tableOperation({
operationId: 'getTable',
summary: 'Get Table',
description: 'Retrieve a table with its metadata, column schema, locks, and current job.',
errors: TABLE_RESOURCE_ERRORS,
description: `Retrieve a table with its metadata, column schema, locks, and current job. ${FOLDER_TREE_TOO_LARGE}`,
errors: [...RESOURCE_ERRORS, 'PayloadTooLarge'],
success: { description: 'The requested table.' },
}),
{
@@ -232,9 +233,8 @@ const routes = [
tableOperation({
operationId: 'updateTable',
summary: 'Update Table',
description:
'Rename a table, edit its description, or move it to a canonical folder. At least one mutable field is required; lock flags remain read-only.',
errors: TABLE_CONFLICT_ERRORS,
description: `Rename a table, edit its description, or move it to a canonical folder. At least one mutable field is required; lock flags remain read-only.\n\nThis operation is NOT atomic. The name, description, and folder changes are written independently in that order, so a failure part-way through leaves the earlier writes committed — a 4xx does NOT mean nothing changed. When at least one field landed before the failure, the error body carries \`details.applied\`: the list of fields (\`name\`, \`description\`, \`folderPath\`) that were successfully written. Re-read the table, or retry with only the fields missing from \`details.applied\`.\n\n${FOLDER_TREE_TOO_LARGE}`,
errors: [...RESOURCE_CONFLICT_ERRORS, 'PayloadTooLarge'],
success: { description: 'The updated table.' },
}),
{
@@ -359,7 +359,7 @@ const routes = [
summary: 'List Rows',
description:
'List a plain cursor page in default row order. Use the query endpoint for predicate filtering and sorting.',
errors: TABLE_RESOURCE_ERRORS,
errors: RESOURCE_ERRORS,
success: { description: 'A page of table rows.' },
}),
{
@@ -490,7 +490,7 @@ const routes = [
operationId: 'getTableRow',
summary: 'Get Row',
description: 'Retrieve one row by identifier.',
errors: TABLE_RESOURCE_ERRORS,
errors: RESOURCE_ERRORS,
success: { description: 'The requested table row.' },
}),
{
@@ -571,7 +571,7 @@ const routes = [
v2DeleteTableRowContract.response.schema,
'V2DeleteTableRowResponse',
'Delete table row response',
'Deleted row count and identifier.'
'Row deletion acknowledgement.'
),
}
),
@@ -581,7 +581,7 @@ const routes = [
operationId: 'upsertTableRow',
summary: 'Upsert Row',
description:
'Insert a row or update the existing row that conflicts on a selected unique column.',
'Insert a row or update the existing row that conflicts on a selected unique column.\n\nWARNING — the update branch REPLACES the row, it does not merge. `data` is treated as the complete new row value, so every column you omit is cleared on the matched row. Upserting 2 of 10 columns blanks the other 8. This differs from `PATCH /api/v2/tables/{tableId}/rows/{rowId}`, which merges the patch into the existing row data. Send the full row here, or use PATCH when you only mean to change a subset.',
errors: TABLE_MUTATION_ERRORS,
success: { description: 'The upserted row and operation performed.' },
}),
@@ -620,7 +620,7 @@ const routes = [
summary: 'Query Rows',
description:
'Query rows with a typed predicate, ordered sort specification, and opaque cursor pagination.',
errors: [...TABLE_RESOURCE_ERRORS, 'PayloadTooLarge'],
errors: RESOURCE_ERRORS,
success: { description: 'A page of matching table rows.' },
}),
{
@@ -658,8 +658,8 @@ const routes = [
operationId: 'listTableViews',
summary: 'List Views',
description:
'List the bounded set of saved table views, with references to removed columns pruned on read.',
errors: TABLE_RESOURCE_ERRORS,
'List the bounded set of saved table views, with references to removed columns pruned on read. The bounded set is returned in one page with `nextCursor` always null; there is no second page to fetch.',
errors: RESOURCE_ERRORS,
success: { description: 'The saved table views.' },
}),
{
@@ -689,7 +689,7 @@ const routes = [
operationId: 'createTableView',
summary: 'Create View',
description: 'Save a filter, sort, and column layout as a named presentation of a table.',
errors: TABLE_MUTATION_ERRORS,
errors: RESOURCE_ERRORS,
success: { description: 'The created table view.' },
}),
{
@@ -729,7 +729,7 @@ const routes = [
operationId: 'getTableView',
summary: 'Get View',
description: 'Retrieve one saved table view by identifier.',
errors: TABLE_RESOURCE_ERRORS,
errors: RESOURCE_ERRORS,
success: { description: 'The requested table view.' },
}),
{
@@ -761,7 +761,7 @@ const routes = [
summary: 'Update View',
description:
'Rename a view, replace or shallow-merge its configuration, or promote it to the table default.',
errors: TABLE_MUTATION_ERRORS,
errors: RESOURCE_ERRORS,
success: { description: 'The updated table view.' },
}),
{
@@ -792,7 +792,7 @@ const routes = [
operationId: 'deleteTableView',
summary: 'Delete View',
description: 'Delete a saved presentation without changing any table rows.',
errors: TABLE_MUTATION_ERRORS,
errors: RESOURCE_ERRORS,
success: { description: 'Table view deletion acknowledgement.' },
}),
{
@@ -821,8 +821,9 @@ const routes = [
tableOperation({
operationId: 'listTableWorkflowGroups',
summary: 'List Workflow Groups',
description: 'List the workflow and enrichment groups that can be dispatched for a table.',
errors: TABLE_RESOURCE_ERRORS,
description:
'List the workflow and enrichment groups that can be dispatched for a table. The bounded set is returned in one page with `nextCursor` always null; there is no second page to fetch.',
errors: RESOURCE_ERRORS,
success: { description: 'The table workflow groups.' },
}),
{
@@ -893,8 +894,9 @@ const routes = [
tableOperation({
operationId: 'updateTableWorkflowGroup',
summary: 'Update Workflow Group',
description: 'Restructure a workflow group, its producer, outputs, or execution behavior.',
errors: TABLE_MUTATION_ERRORS,
description:
'Restructure a workflow group, its producer, outputs, or execution behavior.\n\nOutput leaf types are resolved against the group\u2019s workflow outside the write lock. If the group is repointed at a different workflow concurrently, that snapshot is invalidated and the request returns `409` — retry the update.',
errors: RESOURCE_MUTATION_ERRORS,
success: { description: 'The updated workflow group and resulting columns.' },
}),
{
@@ -957,7 +959,7 @@ const routes = [
summary: 'Run Column Groups',
description:
'Asynchronously run workflow or enrichment groups across all rows or a selected row subset.',
errors: TABLE_MUTATION_ERRORS,
errors: RESOURCE_ERRORS,
success: { description: 'The accepted table-column dispatch.' },
}),
{
@@ -988,7 +990,7 @@ const routes = [
operationId: 'runRowEnrichment',
summary: 'Run Enrichment For One Row',
description: 'Asynchronously run one workflow or enrichment group for one table row.',
errors: TABLE_MUTATION_ERRORS,
errors: RESOURCE_ERRORS,
success: { description: 'The accepted row enrichment dispatch.' },
}),
{
@@ -1020,7 +1022,7 @@ const routes = [
summary: 'Find Rows',
description:
'Search every cell case-insensitively, optionally within a predicate-filtered and sorted view.',
errors: TABLE_RESOURCE_ERRORS,
errors: RESOURCE_ERRORS,
success: { description: 'The matching table cells.' },
}),
{
@@ -1058,7 +1060,7 @@ const routes = [
summary: 'Create Table Import',
description:
'Create a durable CSV import. Upload sources receive signed transfer instructions; workspace-file sources begin processing directly.',
errors: [...WORKSPACE_ERRORS, 'Conflict', 'Locked', 'PayloadTooLarge'],
errors: [...WORKSPACE_ERRORS, 'NotFound', 'Conflict', 'Locked', 'PayloadTooLarge'],
success: { description: 'The created table import and optional transfer instructions.' },
}),
{
@@ -1090,7 +1092,7 @@ const routes = [
operationId: 'getTableImport',
summary: 'Get Table Import',
description: 'Read progress and terminal state for a durable table import.',
errors: [...STANDARD_ERRORS, 'NotFound'],
errors: RESOURCE_ERRORS,
success: { description: 'The requested table import.' },
}),
{
@@ -1121,8 +1123,8 @@ const routes = [
operationId: 'cancelTableImport',
summary: 'Cancel Table Import',
description:
'Cancel an upload or processing import without rolling back committed row batches.',
errors: [...TRANSFER_RESOURCE_ERRORS, 'Gone'],
'Cancel an upload or processing import without rolling back committed row batches.\n\nCanceling an import that is not in a cancelable state returns `409` naming the current status, and that includes an expired import — `expired` is a terminal import status, not a `410`. An import id that never existed, or one whose retention window already purged the record, returns `404`.',
errors: RESOURCE_CONFLICT_ERRORS,
success: { description: 'The canceled table import.' },
}),
{
@@ -1157,8 +1159,9 @@ const routes = [
tableOperation({
operationId: 'createTableImportPartUrls',
summary: 'Create Table Import Part URLs',
description: 'Issue short-lived signed PUT URLs for a bounded set of multipart part numbers.',
errors: [...TRANSFER_RESOURCE_ERRORS, 'Gone'],
description:
'Issue short-lived signed PUT URLs for a bounded set of multipart part numbers.\n\nThe import must still be in the `uploading` state. An import that has moved on — including one that has `expired` — returns `409` naming the current status; a purged or unknown import id returns `404`.',
errors: RESOURCE_CONFLICT_ERRORS,
success: { description: 'The signed multipart upload URLs.' },
}),
{
@@ -1201,8 +1204,8 @@ const routes = [
operationId: 'completeTableImportUpload',
summary: 'Complete Table Import Upload',
description:
'Verify or assemble the uploaded CSV and begin processing with the same import id.',
errors: [...TRANSFER_RESOURCE_ERRORS, 'Gone', 'Locked'],
'Verify or assemble the uploaded CSV and begin processing with the same import id.\n\nCompleting an import that is no longer awaiting an upload — including one that has `expired` — returns `409` naming the current status; a purged or unknown import id returns `404`.',
errors: [...RESOURCE_CONFLICT_ERRORS, 'Locked'],
success: { description: 'The table import after upload completion.' },
}),
{
@@ -1239,7 +1242,7 @@ const routes = [
summary: 'Create Table Export',
description:
'Create a durable CSV or JSON export that completes inline for small tables and queues larger work.',
errors: TABLE_CONFLICT_ERRORS,
errors: RESOURCE_CONFLICT_ERRORS,
success: { description: 'The created table export.' },
}),
{
@@ -1270,7 +1273,7 @@ const routes = [
operationId: 'getTableExport',
summary: 'Get Table Export',
description: 'Read progress and terminal state for a durable table export.',
errors: [...STANDARD_ERRORS, 'NotFound'],
errors: RESOURCE_ERRORS,
success: { description: 'The requested table export.' },
}),
{
@@ -1301,7 +1304,7 @@ const routes = [
operationId: 'cancelTableExport',
summary: 'Cancel Table Export',
description: 'Cancel an export that has not reached a terminal state.',
errors: TRANSFER_RESOURCE_ERRORS,
errors: RESOURCE_CONFLICT_ERRORS,
success: { description: 'The canceled table export.' },
}),
{
@@ -1330,8 +1333,9 @@ const routes = [
tableOperation({
operationId: 'downloadTableExport',
summary: 'Download Table Export',
description: 'Return a short-lived signed download URL for a completed table export.',
errors: [...TRANSFER_RESOURCE_ERRORS, 'Gone'],
description:
'Return a short-lived signed download URL for a completed table export.\n\nThe export must have reached the `completed` status. An export still processing, or one that failed or was canceled, returns `409` naming the current status. An export whose generated file is no longer available — the retention window elapsed, or the object was purged — returns `404` (`Export file is no longer available`), not `410`.',
errors: RESOURCE_CONFLICT_ERRORS,
success: { description: 'Signed table-export download information.' },
}),
{
@@ -1362,7 +1366,7 @@ const routes = [
summary: 'Cancel Column Runs',
description:
'Stop in-flight and pending workflow or enrichment cell runs across the table or one selected row.',
errors: TABLE_MUTATION_ERRORS,
errors: RESOURCE_ERRORS,
success: { description: 'The number of canceled cell runs.' },
}),
{
@@ -1393,8 +1397,8 @@ const routes = [
operationId: 'listTablesFolders',
summary: 'List Folders',
description:
'List table folders, optionally restricting the result to direct children of a canonical parent path.',
errors: WORKSPACE_ERRORS,
'List table folders, optionally restricting the result to direct children of a canonical parent path. The bounded set is returned in one page with `nextCursor` always null; there is no second page to fetch.',
errors: [...WORKSPACE_ERRORS, 'NotFound', 'PayloadTooLarge'],
success: { description: 'The table folders.' },
}),
{
@@ -1418,7 +1422,7 @@ const routes = [
operationId: 'createTablesFolder',
summary: 'Create Folder',
description: 'Create one table-folder leaf whose parent path already exists.',
errors: TABLE_CONFLICT_ERRORS,
errors: [...RESOURCE_CONFLICT_ERRORS, 'PayloadTooLarge'],
success: { description: 'The created table folder.' },
}),
{
@@ -1443,7 +1447,7 @@ const routes = [
operationId: 'relocateTablesFolder',
summary: 'Rename or Move Folder',
description: 'Rename or move a table folder and update all descendant paths.',
errors: TABLE_CONFLICT_ERRORS,
errors: [...RESOURCE_CONFLICT_ERRORS, 'PayloadTooLarge'],
success: { description: 'The relocated table folder.' },
}),
{
@@ -1475,7 +1479,7 @@ const routes = [
summary: 'Delete Folder',
description:
'Delete an empty table folder, or recursively delete its descendants and tables when explicitly requested.',
errors: TABLE_CONFLICT_ERRORS,
errors: [...RESOURCE_MUTATION_ERRORS, 'PayloadTooLarge'],
success: { description: 'Table-folder deletion acknowledgement.' },
}),
{
@@ -2,11 +2,14 @@ import {
documentedSchema,
ERROR_RESPONSES,
type ErrorResponseId,
FOLDER_TREE_TOO_LARGE,
RATE_LIMIT_HEADERS,
RESOURCE_CONFLICT_ERRORS,
V2_API_KEY_SECURITY,
V2_API_KEY_SECURITY_SCHEMES,
V2_COMMON_HEADERS,
V2_ERROR_SCHEMA,
WORKSPACE_API_KEY_DENIED_AS_NOT_FOUND,
} from '@/lib/api/contracts/v2/openapi/shared'
import {
v2CancelWorkflowRunContract,
@@ -99,7 +102,7 @@ const QUEUED_RUN_EXAMPLE = {
},
} as const
const BASE_ERRORS = [
const WORKSPACE_ERRORS = [
'BadRequest',
'Unauthorized',
'Forbidden',
@@ -108,8 +111,11 @@ const BASE_ERRORS = [
'ServiceUnavailable',
] as const satisfies readonly ErrorResponseId[]
const RESOURCE_ERRORS = [...BASE_ERRORS, 'NotFound'] as const satisfies readonly ErrorResponseId[]
const MUTATION_ERRORS = [
const RESOURCE_ERRORS = [
...WORKSPACE_ERRORS,
'NotFound',
] as const satisfies readonly ErrorResponseId[]
const RESOURCE_MUTATION_ERRORS = [
...RESOURCE_ERRORS,
'Conflict',
'Locked',
@@ -169,9 +175,8 @@ const routes = [
workflowOperation({
operationId: 'listWorkflows',
summary: 'List Workflows',
description:
'List workflows in a workspace with folder and deployment filters, search, sorting, and opaque cursor pagination.',
errors: BASE_ERRORS,
description: `List workflows in a workspace with folder and deployment filters, search, sorting, and opaque cursor pagination. ${FOLDER_TREE_TOO_LARGE}`,
errors: [...WORKSPACE_ERRORS, 'NotFound', 'PayloadTooLarge'],
success: jsonSuccess('A page of workflows.'),
}),
{
@@ -190,8 +195,8 @@ const routes = [
workflowOperation({
operationId: 'createWorkflowV2',
summary: 'Create Workflow',
description: 'Create a workflow in a workspace root or canonical workflow folder.',
errors: [...BASE_ERRORS, 'Conflict', 'Locked'],
description: `Create a workflow in a workspace root or canonical workflow folder. ${FOLDER_TREE_TOO_LARGE}`,
errors: [...WORKSPACE_ERRORS, 'NotFound', 'Conflict', 'Locked', 'PayloadTooLarge'],
success: jsonSuccess('The created workflow.'),
}),
{
@@ -210,8 +215,8 @@ const routes = [
workflowOperation({
operationId: 'getWorkflow',
summary: 'Get Workflow',
description: 'Get a workflow with its variables and deployed API-trigger inputs.',
errors: RESOURCE_ERRORS,
description: `Get a workflow with its variables and deployed API-trigger inputs. ${FOLDER_TREE_TOO_LARGE}`,
errors: [...RESOURCE_ERRORS, 'PayloadTooLarge'],
success: jsonSuccess('The requested workflow.'),
}),
{
@@ -230,8 +235,8 @@ const routes = [
workflowOperation({
operationId: 'updateWorkflowV2',
summary: 'Update Workflow',
description: 'Rename, describe, or move a workflow to a canonical folder path.',
errors: MUTATION_ERRORS,
description: `Rename, describe, or move a workflow to a canonical folder path. ${FOLDER_TREE_TOO_LARGE}`,
errors: [...RESOURCE_MUTATION_ERRORS, 'PayloadTooLarge'],
success: jsonSuccess('The updated workflow.'),
}),
{
@@ -324,9 +329,8 @@ const routes = [
workflowOperation({
operationId: 'deployWorkflow',
summary: 'Deploy Workflow',
description:
'Create and asynchronously activate a deployment version. Poll the workflow until the lifecycle attempt reaches a terminal state.',
errors: [...RESOURCE_ERRORS, 'PayloadTooLarge', 'Locked'],
description: `Create and asynchronously activate a deployment version. This request is not idempotent: it accepts no idempotency key and every call mints a new deployment version, so retrying after a timeout creates a second version rather than returning the first. The response carries \`latestDeploymentAttempt\` for the accepted attempt, but \`GET /workflows/{id}\` does not expose that field — poll activation with \`isDeployed\` and \`deployedAt\` on the workflow, or with \`isActive\` on \`GET /workflows/{id}/versions\`. Returns 409 when the deployment would conflict with an existing webhook path. ${WORKSPACE_API_KEY_DENIED_AS_NOT_FOUND}`,
errors: [...RESOURCE_ERRORS, 'Conflict', 'PayloadTooLarge', 'Locked'],
success: jsonSuccess('The accepted deployment attempt.'),
}),
{
@@ -341,11 +345,22 @@ const routes = [
{
data: {
id: WORKFLOW_ID,
isDeployed: true,
deployedAt: '2026-06-12T10:30:00.000Z',
isDeployed: false,
deployedAt: null,
warnings: [],
activeDeployment: null,
latestDeploymentAttempt: null,
latestDeploymentAttempt: {
id: 'depop_01J8ZK3QW4M6X2R9T7B5C0V1',
deploymentVersionId: 'depver_01J8ZK3QW4M6X2R9T7B5C0V2',
version: 3,
action: 'deploy',
status: 'preparing',
isCurrent: true,
readiness: { webhooks: 'pending', schedules: 'ready', mcp: 'not_applicable' },
requestedAt: '2026-06-12T10:30:00.000Z',
activatedAt: null,
error: null,
},
version: 3,
},
},
@@ -358,7 +373,7 @@ const routes = [
workflowOperation({
operationId: 'undeployWorkflow',
summary: 'Undeploy Workflow',
description: 'Deactivate the currently serving workflow version.',
description: `Deactivate the currently serving workflow version. ${WORKSPACE_API_KEY_DENIED_AS_NOT_FOUND}`,
errors: [...RESOURCE_ERRORS, 'Locked'],
success: jsonSuccess('The workflow was undeployed.'),
}),
@@ -389,8 +404,7 @@ const routes = [
workflowOperation({
operationId: 'rollbackWorkflow',
summary: 'Rollback Workflow',
description:
'Asynchronously reactivate a previous deployment version, selecting the preceding active version when no version is supplied.',
description: `Asynchronously reactivate a previous deployment version, selecting the preceding active version when no version is supplied. ${WORKSPACE_API_KEY_DENIED_AS_NOT_FOUND}`,
errors: [...RESOURCE_ERRORS, 'PayloadTooLarge', 'Locked'],
success: jsonSuccess('The accepted rollback attempt.'),
}),
@@ -406,11 +420,22 @@ const routes = [
{
data: {
id: WORKFLOW_ID,
isDeployed: true,
deployedAt: '2026-06-12T10:30:00.000Z',
isDeployed: false,
deployedAt: null,
warnings: [],
activeDeployment: null,
latestDeploymentAttempt: null,
latestDeploymentAttempt: {
id: 'depop_01J8ZK4RX5N7Y3S0U8D6E1W2',
deploymentVersionId: 'depver_01J8ZK4RX5N7Y3S0U8D6E1W3',
version: 2,
action: 'activate',
status: 'activating',
isCurrent: true,
readiness: { webhooks: 'ready', schedules: 'ready', mcp: 'not_applicable' },
requestedAt: '2026-06-12T10:30:00.000Z',
activatedAt: null,
error: null,
},
version: 2,
},
},
@@ -423,9 +448,8 @@ const routes = [
workflowOperation({
operationId: 'exportWorkflow',
summary: 'Export Workflow',
description:
'Export a portable, secret-sanitized workflow. Workspace-scoped bindings must be selected again after import.',
errors: RESOURCE_ERRORS,
description: `Export a portable, secret-sanitized workflow. Workspace-scoped bindings must be selected again after import. ${FOLDER_TREE_TOO_LARGE}`,
errors: [...RESOURCE_ERRORS, 'PayloadTooLarge'],
success: jsonSuccess('The workflow export payload.'),
}),
{
@@ -460,7 +484,7 @@ const routes = [
operationId: 'importWorkflow',
summary: 'Import Workflow',
description: 'Create a workflow from a portable export object, bare state, or JSON string.',
errors: [...MUTATION_ERRORS, 'PayloadTooLarge'],
errors: [...RESOURCE_MUTATION_ERRORS, 'PayloadTooLarge'],
success: jsonSuccess('The imported workflow.'),
}),
{
@@ -492,7 +516,7 @@ const routes = [
operationId: 'executeWorkflowV2',
summary: 'Execute Workflow',
description:
'Execute a deployed workflow synchronously, asynchronously, or as Server-Sent Events. Public workflows permit anonymous synchronous and streaming execution; asynchronous execution requires an API key.',
'Execute a deployed workflow synchronously, asynchronously, or as Server-Sent Events. Public workflows permit anonymous synchronous and streaming execution; asynchronous execution requires an API key. A synchronous run that exceeds its execution timeout returns HTTP 200 with `status: "failed"` and `error.code: "TIMEOUT"` rather than an HTTP error, so branch on `status`. The optional `X-Run-Id` header is a one-shot uniqueness claim, not an idempotency key: reusing a value returns 409 with `error.details.code: "RUN_ID_CONFLICT"` and never replays the earlier run. Option constraints — each is a 400: (1) `async: true` requires an API key; anonymous public-workflow callers may only execute synchronously or as a stream. (2) `async` and `stream` cannot both be true. (3) `executionTimeoutSeconds` is accepted only when `async: true`. (4) `async: true` rejects every streaming and output-shaping option — `selectedOutputs`, `includeThinking`, `includeToolCalls`, `includeFileBase64`, and `base64MaxBytes`. (5) `includeThinking` and `includeToolCalls` require the `X-Sim-Stream-Protocol: agent-events-v1` request header, which declares that the client understands agent-event frames.',
errors: [
'BadRequest',
'Unauthorized',
@@ -502,6 +526,7 @@ const routes = [
'RunIdConflict',
'PayloadTooLarge',
'RateLimited',
'ClientClosedRequest',
'InternalError',
'ServiceUnavailable',
],
@@ -533,7 +558,8 @@ const routes = [
workflowRunOperation({
operationId: 'listWorkflowRunsV2',
summary: 'List Workflow Runs',
description: 'List recorded runs of a workflow with filtering and opaque cursor pagination.',
description:
'List recorded runs of a workflow with filtering and opaque cursor pagination. Ordering deviates from the v2 `sortBy` + `sortOrder` convention: runs are sortable only by start time, so direction is carried by the single `order` param.',
errors: RESOURCE_ERRORS,
success: jsonSuccess('A page of workflow runs.'),
}),
@@ -571,7 +597,7 @@ const routes = [
operationId: 'getWorkflowRunV2',
summary: 'Get Workflow Run',
description: 'Get current workflow run state, optionally including final and block outputs.',
errors: RESOURCE_ERRORS,
errors: RESOURCE_CONFLICT_ERRORS,
success: jsonSuccess('The workflow run status.'),
}),
{
@@ -610,7 +636,7 @@ const routes = [
summary: 'Resume Workflow Run',
description:
'Resume one human-in-the-loop pause context. The resumed attempt receives a new run identifier and may complete synchronously or return a queue receipt.',
errors: [...RESOURCE_ERRORS, 'UsageLimitExceeded', 'Conflict', 'PayloadTooLarge', 'Locked'],
errors: [...RESOURCE_ERRORS, 'UsageLimitExceeded', 'Conflict', 'PayloadTooLarge'],
success: {
byStatus: {
200: {
@@ -636,8 +662,9 @@ const routes = [
workflowRunOperation({
operationId: 'cancelRunV2',
summary: 'Cancel Workflow Run',
description: 'Request cancellation of a running, queued, or paused workflow run.',
errors: RESOURCE_ERRORS,
description:
'Request cancellation of a running, queued, or paused workflow run. Cancelling a run that has already reached a terminal state succeeds with no effect rather than returning an error. The `reason` field is present on every response, including full successes — `recorded` is the success value; it is not a partial-failure marker. A run produced by a table workflow group is a 409 when its cell can no longer accept the cancellation, because the run and its cell must reach the cancelled state together.',
errors: RESOURCE_CONFLICT_ERRORS,
success: jsonSuccess('The cancellation outcome.'),
}),
{
@@ -668,8 +695,9 @@ const routes = [
workflowOperation({
operationId: 'listWorkflowsFolders',
summary: 'List Workflow Folders',
description: 'List canonical workflow folders in a workspace.',
errors: BASE_ERRORS,
description:
'List canonical workflow folders in a workspace. The bounded set is returned in one page with `nextCursor` always null; there is no second page to fetch.',
errors: [...WORKSPACE_ERRORS, 'NotFound', 'PayloadTooLarge'],
success: jsonSuccess('A list of workflow folders.'),
}),
{
@@ -694,7 +722,7 @@ const routes = [
operationId: 'createWorkflowsFolder',
summary: 'Create Workflow Folder',
description: 'Create a canonical workflow folder in a workspace.',
errors: MUTATION_ERRORS,
errors: [...RESOURCE_MUTATION_ERRORS, 'PayloadTooLarge'],
success: jsonSuccess('The created workflow folder.'),
}),
{
@@ -710,7 +738,7 @@ const routes = [
'CreateWorkflowFolderResponse',
'Create workflow folder response',
'The created workflow folder.',
[{ data: { folder: WORKFLOW_FOLDER_EXAMPLE } }]
[{ data: WORKFLOW_FOLDER_EXAMPLE }]
),
}
),
@@ -720,7 +748,7 @@ const routes = [
operationId: 'relocateWorkflowsFolder',
summary: 'Rename or Move Workflow Folder',
description: 'Rename or move a workflow folder and its descendants to a canonical path.',
errors: MUTATION_ERRORS,
errors: [...RESOURCE_MUTATION_ERRORS, 'PayloadTooLarge'],
success: jsonSuccess('The relocated workflow folder.'),
}),
{
@@ -742,7 +770,7 @@ const routes = [
'RelocateWorkflowFolderResponse',
'Relocate workflow folder response',
'The relocated workflow folder.',
[{ data: { folder: { ...WORKFLOW_FOLDER_EXAMPLE, name: 'Support', path: '/Support' } } }]
[{ data: { ...WORKFLOW_FOLDER_EXAMPLE, name: 'Support', path: '/Support' } }]
),
}
),
@@ -752,7 +780,7 @@ const routes = [
operationId: 'deleteWorkflowsFolder',
summary: 'Delete Workflow Folder',
description: 'Delete a workflow folder, optionally including its descendants and workflows.',
errors: MUTATION_ERRORS,
errors: [...RESOURCE_MUTATION_ERRORS, 'PayloadTooLarge'],
success: jsonSuccess('The workflow folder was deleted.'),
}),
{
+4 -17
View File
@@ -7,6 +7,7 @@ import {
v2DataResponse,
v2SearchSchema,
v2SortFields,
v2TimestampSchema,
} from '@/lib/api/contracts/v2/shared'
const SECRET_NAME_REGEX = /^[A-Za-z0-9_]+$/
@@ -30,11 +31,8 @@ export const v2SecretSchema = z
name: v2SecretNameSchema,
scope: v2SecretScopeSchema,
role: workspaceCredentialRoleSchema.describe('Caller role for the secret.'),
createdAt: z.string().datetime().describe('ISO 8601 timestamp when the secret was created.'),
updatedAt: z
.string()
.datetime()
.describe('ISO 8601 timestamp when the secret was last updated.'),
createdAt: v2TimestampSchema.describe('ISO 8601 timestamp when the secret was created.'),
updatedAt: v2TimestampSchema.describe('ISO 8601 timestamp when the secret was last updated.'),
})
.meta({
id: 'V2Secret',
@@ -43,17 +41,6 @@ export const v2SecretSchema = z
})
export type V2Secret = z.output<typeof v2SecretSchema>
export const v2SecretDataSchema = z
.object({
secret: v2SecretSchema.describe('Secret metadata. The stored value is never returned.'),
})
.meta({
id: 'V2SecretData',
title: 'Secret data',
description: 'A single secret-metadata payload without its stored value.',
})
export type V2SecretData = z.output<typeof v2SecretDataSchema>
export const v2SecretDeleteDataSchema = z
.object({
name: v2SecretNameSchema,
@@ -122,7 +109,7 @@ export const v2SetSecretContract = defineRouteContract({
body: v2SetSecretBodySchema,
response: {
mode: 'json',
schema: v2DataResponse(v2SecretDataSchema),
schema: v2DataResponse(v2SecretSchema),
status: [200, 201],
},
})
+52 -5
View File
@@ -11,6 +11,16 @@ import { FolderPathError, parseFolderPath, requireNonRootFolderPath } from '@/li
* - list: `{ data: T[], nextCursor: string | null }`
* - error: `{ error: { code, message, details? } }`
*
* Every documented v2 operation uses that family. The two exceptions are the
* local-storage upload data plane `PUT /api/v2/uploads/{uploadId}` and
* `PUT /api/v2/uploads/{uploadId}/parts/{partNumber}` which emit a bare
* `{ error: string }` body. They are authenticated by a short-lived upload
* token rather than an API key, are deliberately absent from the public
* OpenAPI specs (see `UNDOCUMENTED_V2_ROUTES` in
* `scripts/check-openapi-specs.ts`), and are only ever reached through a URL
* handed back by a documented operation, so no caller writes against them
* from docs.
*
* Every list returns the opaque-cursor envelope (Stripe/Slack-style)
* `{ data, nextCursor }`, but not every list is *paged*. A paged list also
* accepts `limit` + `cursor` and can return a non-null `nextCursor`; a list
@@ -28,16 +38,25 @@ import { FolderPathError, parseFolderPath, requireNonRootFolderPath } from '@/li
*
* ## Search, filtering, and sorting
*
* One convention, applied by every v2 list. It is deliberately the narrow
* One convention, applied by every v2 list that sorts on a selectable column.
* It is deliberately the narrow
* scalar-param form the app's own list endpoints already speak not a third
* dialect alongside the Logs filter set and the Tables predicate grammar.
* A list that needs a real expression tree (Tables) keeps its own `POST /query`.
*
* Two lists predate the convention and are the documented exceptions:
* `GET /api/v2/logs` and `GET /api/v2/workflows/{id}/runs` have no `sortBy`
* (the sort column is fixed to execution start time) and spell the direction
* `order`, not `sortOrder`. They are not a pattern to copy, and renaming the
* param would break shipped callers.
*
* - **`search`** ({@link v2SearchSchema}) a case-insensitive substring match
* against the resource's *single* natural name field, and nothing else:
* `name` for files/folders/workflows/tables/knowledge bases/MCP servers/
* skills, `title` for custom tools, `displayName` for credentials. It never
* matches ids, descriptions, or content. `%` and `_` in the term are matched
* skills, `title` for custom tools, `filename` for knowledge documents
* (`GET /knowledge/{id}/documents`), and `displayName` for both credentials
* and secrets (`GET /secrets`, where the secret's name *is* the credential
* `displayName`). It never matches ids, descriptions, or content. `%` and `_` in the term are matched
* literally, not as wildcards. Empty is rejected rather than silently
* ignored omit the param instead.
* - **`sortBy` + `sortOrder`** ({@link v2SortFields}) `sortBy` is a
@@ -60,7 +79,10 @@ import { FolderPathError, parseFolderPath, requireNonRootFolderPath } from '@/li
* ## Which lists are paged
*
* The authoritative split is pinned in `v2/__tests__/list-pagination.test.ts`,
* not restated here. Adding `limit`/`cursor` to a full-set list is additive,
* not restated here. A full-set list returns `nextCursor: null` on every
* response its OpenAPI description says so explicitly, so a caller never
* writes a pagination loop that can only ever run once.
* Adding `limit`/`cursor` to a full-set list is additive,
* but making a `limit` *default* would silently truncate callers that rely on
* the full set today, so a default page size cannot be introduced without a
* version bump.
@@ -77,6 +99,29 @@ import { FolderPathError, parseFolderPath, requireNonRootFolderPath } from '@/li
* is opaque in exactly the same way.
*/
/**
* Canonical v2 timestamp: a strict ISO-8601 UTC instant, exactly what
* `Date.prototype.toISOString()` emits.
*
* What this buys over a bare `z.string().meta({ format: 'date-time' })` is
* *runtime* validation, not documentation. Both render the same OpenAPI schema
* `format: date-time` comes from the `meta`, so a generated client parses
* either one as a date and roughly two dozen v2 fields use the bare form,
* including {@link v2FolderSchema} below and most of `contracts/v2/workflows.ts`.
* The real difference is that `.datetime()` also *asserts* the shape, and a v2
* response body is `.parse`d on the way out
* (`lib/api/server/routes/v2-json-route.ts`), so asserting a field a producer
* does not actually emit as ISO-8601 turns a successful read into a 500.
*
* Use this schema wherever every producer of the field provably emits
* `toISOString()` output most commonly a `Date` column projected straight
* through. Keep the bare form for a value that is persisted as text,
* reconstructed from a third party, or otherwise may have drifted: the document
* is identical, and a lenient read beats a 500. Tightening an existing field
* means proving the producer first.
*/
export const v2TimestampSchema = z.string().datetime().meta({ format: 'date-time' })
/** Canonical v2 error envelope. */
export const v2ErrorResponseSchema = z.object({
error: z
@@ -101,7 +146,9 @@ export const v2CursorListResponse = <T extends z.ZodType>(itemSchema: T) =>
nextCursor: z
.string()
.nullable()
.describe('Opaque cursor for the next page, or null when no more items remain.'),
.describe(
'Opaque cursor for the next page, or null when no more items remain. Always null on a full-set list, which returns its whole result set in one response.'
),
})
/**
+10 -13
View File
@@ -11,6 +11,7 @@ import {
v2DataResponse,
v2SearchSchema,
v2SortFields,
v2TimestampSchema,
} from '@/lib/api/contracts/v2/shared'
/**
@@ -41,8 +42,12 @@ export const v2SkillSummarySchema = z
readOnly: z
.boolean()
.describe('Whether this is a built-in skill that cannot be modified or deleted.'),
createdAt: z.string().describe('ISO 8601 timestamp when the skill was created.'),
updatedAt: z.string().describe('ISO 8601 timestamp when the skill was last updated.'),
createdAt: v2TimestampSchema.describe(
'ISO 8601 timestamp when the skill was created. Built-in skills report the Unix epoch.'
),
updatedAt: v2TimestampSchema.describe(
'ISO 8601 timestamp when the skill was last updated. Built-in skills report the Unix epoch.'
),
})
.meta({
id: 'V2SkillSummary',
@@ -63,14 +68,6 @@ export const v2SkillSchema = v2SkillSummarySchema
})
export type V2Skill = z.output<typeof v2SkillSchema>
/** `{ skill }` payload for single-skill reads and mutations. */
export const v2SkillDataSchema = z.object({ skill: v2SkillSchema.describe('The skill.') }).meta({
id: 'V2SkillData',
title: 'Skill data',
description: 'A single skill payload including its instruction body.',
})
export type V2SkillData = z.output<typeof v2SkillDataSchema>
export const v2SkillDeleteDataSchema = z
.object({
id: z.string().describe('Identifier of the deleted skill.'),
@@ -166,7 +163,7 @@ export const v2CreateSkillContract = defineRouteContract({
body: v2CreateSkillBodySchema,
response: {
mode: 'json',
schema: v2DataResponse(v2SkillDataSchema),
schema: v2DataResponse(v2SkillSchema),
status: 201,
},
})
@@ -178,7 +175,7 @@ export const v2GetSkillContract = defineRouteContract({
query: v2SkillWorkspaceQuerySchema,
response: {
mode: 'json',
schema: v2DataResponse(v2SkillDataSchema),
schema: v2DataResponse(v2SkillSchema),
},
})
@@ -189,7 +186,7 @@ export const v2UpdateSkillContract = defineRouteContract({
body: v2UpdateSkillBodySchema,
response: {
mode: 'json',
schema: v2DataResponse(v2SkillDataSchema),
schema: v2DataResponse(v2SkillSchema),
},
})

Some files were not shown because too many files have changed in this diff Show More