diff --git a/api/openapi.json b/api/openapi.json index 12e8bfcf3..3d6f961ab 100644 --- a/api/openapi.json +++ b/api/openapi.json @@ -21524,8 +21524,8 @@ "secureDashboardSession": [] } ], - "summary": "List connected agents and their agent tokens", - "description": "Agent tokens are how agents use Nightmail: an agent signs in over MCP as you, and can make short-lived tokens for scripts (createAgentToken). Each connected agent is listed once with its access, last use and the tokens it made in this workspace. Owners and admins also see other members' agents that made tokens here. Dashboard session only.", + "summary": "List agents", + "description": "List connected agents and their agent tokens. Agent tokens are how agents use Nightmail: an agent signs in over MCP as you, and can make short-lived tokens for scripts (createAgentToken). Each connected agent is listed once with its access, last use and the tokens it made in this workspace. Owners and admins also see other members' agents that made tokens here. Dashboard session only.", "parameters": [ { "schema": { @@ -21691,7 +21691,7 @@ "secureDashboardSession": [] } ], - "summary": "Revoke a connected agent and its agent tokens", + "summary": "Revoke an agent", "description": "Your own agent: its sign-in, every agent token it made and everything it created stop working at once (it can sign in again as a new connection). Another member's agent (owners and admins): the agent tokens it made in this workspace are revoked; the sign-in belongs to that person. Dashboard session only.", "parameters": [ { @@ -24096,7 +24096,7 @@ "Auth" ], "security": [], - "summary": "Exchange a setup token for the agent's API key", + "summary": "Exchange a setup token for an API key", "description": "For a coding agent: the setup token in the prompt a person copied from the dashboard (nm_setup_…) becomes a lasting API key for the agent, in that person's workspace, named after client_name. It works once, within 15 minutes of copying. A wrong token gets 400 SETUP_TOKEN_INVALID, a used one 409 SETUP_TOKEN_USED (naming the key it gave, in error.details, never the key again), and an expired or replaced one 410 SETUP_TOKEN_EXPIRED or SETUP_TOKEN_REPLACED with a device code in error.details[0] (startAgentDeviceAuthorization's answer) for the person who copied it to approve: show them its link and poll it. The key is shown once.", "requestBody": { "required": true, @@ -24274,7 +24274,7 @@ "Auth" ], "security": [], - "summary": "Start the device flow for a coding agent", + "summary": "Start the device flow for an agent", "description": "For a coding agent without a setup token (RFC 8628): returns a device code to keep and a user code to show. Show the person verification_uri_complete as a link on its own line and ask them to open it, sign in, check the code and approve; nextStep says so in words. Then poll pollAgentDeviceToken every interval seconds until it returns the key. Codes work once, for 15 minutes. With setup_token (one from the person's prompt that expired or was replaced before it was used), their dashboard shows you waiting.", "requestBody": { "required": false, @@ -24613,7 +24613,7 @@ "secureDashboardSession": [] } ], - "summary": "Look up an agent waiting with a user code", + "summary": "Look up an agent by user code", "description": "The /connect page: the agent behind a user code, before you approve or deny it. Each attempt counts against 10 a minute per person. Dashboard session only.", "requestBody": { "required": true, @@ -24930,7 +24930,7 @@ "secureDashboardSession": [] } ], - "summary": "Approve an agent waiting with a user code", + "summary": "Approve an agent by user code", "description": "Gives the agent behind the user code its own API key in the workspace this request acts in (X-Nightmail-Workspace), which you must own or administer. It receives the key on its next poll. Dashboard session only.", "requestBody": { "required": true, @@ -49691,7 +49691,8 @@ "Rules" ], "operationId": "restoreRuleVersion", - "summary": "Recompile a retained version and restore it as a new version", + "summary": "Restore a rules version", + "description": "Recompile a retained version and restore it as a new version.", "parameters": [ { "schema": { @@ -49984,7 +49985,8 @@ "Rules" ], "operationId": "setDecisionOptIns", - "summary": "Set the domains and routes whose mail the AI may read for decisions", + "summary": "Set the AI decision opt-ins", + "description": "Set the domains and routes whose mail the AI may read for decisions.", "parameters": [ { "schema": { @@ -50478,8 +50480,8 @@ "Endpoints" ], "operationId": "createEndpoint", - "summary": "Create a named Slack, Discord, webhook or forward endpoint", - "description": "Slack and Discord URLs are credentials: stored encrypted, pinned to the provider host and never returned. A webhook endpoint is a route-only inbound webhook; its signing secret is returned once. A forward emails its recipient a single-use confirmation link (24 hours); it stays pending until they choose Allow. With preverify, an address on a domain this workspace has verified is ready at once. Once ready, a rule calls it as endpoints.() and a route forwards to it as forward:; either way the recipient gets each message whole: text, HTML and attachments.", + "summary": "Create an endpoint", + "description": "Create a named Slack, Discord, webhook or forward endpoint. Slack and Discord URLs are credentials: stored encrypted, pinned to the provider host and never returned. A webhook endpoint is a route-only inbound webhook; its signing secret is returned once. A forward emails its recipient a single-use confirmation link (24 hours); it stays pending until they choose Allow. With preverify, an address on a domain this workspace has verified is ready at once. Once ready, a rule calls it as endpoints.() and a route forwards to it as forward:; either way the recipient gets each message whole: text, HTML and attachments.", "requestBody": { "required": true, "content": { @@ -50641,7 +50643,8 @@ "Endpoints" ], "operationId": "getEndpoint", - "summary": "Read one endpoint, its status and the next step", + "summary": "Read an endpoint", + "description": "Read one endpoint, its status and the next step.", "parameters": [ { "schema": { @@ -50803,8 +50806,8 @@ "Endpoints" ], "operationId": "updateEndpoint", - "summary": "Edit an endpoint: its name, type, URL, pause state, rate or retry policy", - "description": "Send only what changes. URLs and headers are write-only: an omitted url keeps the current one, and none is ever returned. A forward’s address is fixed (its recipient confirmed it); create a new forward instead.", + "summary": "Edit an endpoint", + "description": "Edit an endpoint: its name, type, URL, pause state, rate or retry policy. Send only what changes. URLs and headers are write-only: an omitted url keeps the current one, and none is ever returned. A forward’s address is fixed (its recipient confirmed it); create a new forward instead.", "parameters": [ { "schema": { @@ -50977,7 +50980,8 @@ "Endpoints" ], "operationId": "deleteEndpoint", - "summary": "Delete an endpoint no rule or route uses", + "summary": "Delete an endpoint", + "description": "Delete an endpoint no rule or route uses.", "parameters": [ { "schema": { @@ -51142,8 +51146,8 @@ "Endpoints" ], "operationId": "sendEndpointVerification", - "summary": "Email a forward recipient a new confirmation link", - "description": "For a pending, expired or (after 30 days) declined forward. The recipient must open the link and choose Allow; no API call can confirm on their behalf.", + "summary": "Resend a forward confirmation link", + "description": "Email a forward recipient a new confirmation link. For a pending, expired or (after 30 days) declined forward. The recipient must open the link and choose Allow; no API call can confirm on their behalf.", "parameters": [ { "schema": { @@ -51325,8 +51329,8 @@ "Endpoints" ], "operationId": "testEndpoint", - "summary": "Post a fixed test message to a Slack, Discord or webhook endpoint now", - "description": "Bypasses rules and queues: one synchronous post, counted against the endpoint rate. Forwards send real mail, so they are not tested this way; use testRules for a dry run.", + "summary": "Test an endpoint", + "description": "Post a fixed test message to a Slack, Discord or webhook endpoint now. Bypasses rules and queues: one synchronous post, counted against the endpoint rate. Forwards send real mail, so they are not tested this way; use testRules for a dry run.", "parameters": [ { "schema": { @@ -51491,7 +51495,8 @@ "secureDashboardSession": [] } ], - "summary": "Generate client config with a key limited to selected inboxes. Key shown once.", + "summary": "Create an inbox connection", + "description": "Key shown once. Generate client config with a key limited to selected inboxes.", "requestBody": { "required": true, "content": { @@ -51720,8 +51725,8 @@ "tags": [ "Rules" ], - "summary": "Read the rules and routes version, or wait for it to change", - "description": "Without after, returns the current version at once. With after (and endpoints, to include endpoint changes), waits up to wait seconds for a rule, route or endpoint save and returns as soon as one commits, with who saved it. The dashboard keeps one of these open while you edit rules so an agent’s saves appear live. Each waited 2.5 seconds counts as one request against the credential’s per-minute budget.", + "summary": "Read or wait for the rules version", + "description": "Read the rules and routes version, or wait for it to change. Without after, returns the current version at once. With after (and endpoints, to include endpoint changes), waits up to wait seconds for a rule, route or endpoint save and returns as soon as one commits, with who saved it. The dashboard keeps one of these open while you edit rules so an agent’s saves appear live. Each waited 2.5 seconds counts as one request against the credential’s per-minute budget.", "parameters": [ { "schema": { @@ -51916,8 +51921,8 @@ "Rules" ], "operationId": "checkRule", - "summary": "Compile one rule source against this workspace without saving", - "description": "Returns every problem with its line, column and a hint, and what the rule calls. Use it while editing; nothing is saved, delivered or sent to the AI.", + "summary": "Check a rule without saving it", + "description": "Compile one rule source against this workspace without saving. Returns every problem with its line, column and a hint, and what the rule calls. Use it while editing; nothing is saved, delivered or sent to the AI.", "requestBody": { "required": true, "content": { @@ -52107,8 +52112,8 @@ "Rules" ], "operationId": "getRuleTypings", - "summary": "TypeScript declarations and editor completions for this workspace", - "description": "Generated from the workspace’s endpoints, inbox keys and sender lists. Load typescript into an editor as a .d.ts, or read it to learn exactly what a rule can call.", + "summary": "Read the rules’ TypeScript declarations", + "description": "TypeScript declarations and editor completions for this workspace. Generated from the workspace’s endpoints, inbox keys and sender lists. Load typescript into an editor as a .d.ts, or read it to learn exactly what a rule can call.", "responses": { "200": { "description": "Success", @@ -52259,8 +52264,8 @@ "Rules" ], "operationId": "listRuleTemplates", - "summary": "Starting points for common rules, filled in with this workspace’s endpoints", - "description": "Each template compiles. An endpoint template uses the first endpoint of the type it needs; endpoint is null when there is none yet, and source then uses a placeholder name to replace.", + "summary": "List rule templates", + "description": "Starting points for common rules, filled in with this workspace’s endpoints. Each template compiles. An endpoint template uses the first endpoint of the type it needs; endpoint is null when there is none yet, and source then uses a placeholder name to replace.", "responses": { "200": { "description": "Success", @@ -52411,8 +52416,8 @@ "Rules" ], "operationId": "listRuleRecipes", - "summary": "Ready-made rules and the fields each one takes", - "description": "Each recipe writes an ordinary rule from one or two fields. Create one with createRuleFromRecipe; endpoint fields name an endpoint of the right type, created first with createEndpoint.", + "summary": "List rule recipes", + "description": "Ready-made rules and the fields each one takes. Each recipe writes an ordinary rule from one or two fields. Create one with createRuleFromRecipe; endpoint fields name an endpoint of the right type, created first with createEndpoint.", "responses": { "200": { "description": "Success", @@ -52561,7 +52566,7 @@ "Rules" ], "operationId": "createRuleFromRecipe", - "summary": "Create a rule from a recipe and attach it to addresses", + "summary": "Create a rule from a recipe", "description": "Writes the recipe’s script, saves it as a new rule (key from the recipe and address unless given) and attaches it to each address, after their other recipes and before their own scripts. An AI recipe lets the AI read mail at those addresses’ domains. Returns the new version and key. Besides listRuleRecipes, it takes the two-way rules the dashboard builds: split ({ test: always, from, subject, text or attachment; value: words, or senders for from; then; otherwise }) and split-by-meaning ({ meaning, then, otherwise }), where then and otherwise are inbox:, an endpoint name, store or drop. Give the address the route [] (createRoute) so each side gets exactly its destination.", "parameters": [ { @@ -52901,7 +52906,7 @@ "Rules" ], "operationId": "updateRuleFromRecipe", - "summary": "Change a rule’s recipe fields and addresses", + "summary": "Update a rule from its recipe", "description": "Rewrites the rule from its recipe with these fields. addresses, when given, replaces where it runs (kept addresses keep their place). Passing recipe turns a script into that recipe.", "parameters": [ { @@ -54316,7 +54321,8 @@ "Rules" ], "operationId": "attachRules", - "summary": "Attach, reorder and detach rules by replacing the ordered attachment list", + "summary": "Attach rules", + "description": "Attach, reorder and detach rules by replacing the ordered attachment list.", "parameters": [ { "schema": { @@ -54640,7 +54646,8 @@ "Rules" ], "operationId": "getRules", - "summary": "Read rules, ordered attachments, and sender lists", + "summary": "Read rules", + "description": "Read rules, ordered attachments, and sender lists.", "parameters": [ { "schema": { @@ -54911,7 +54918,8 @@ "Rules" ], "operationId": "applyRules", - "summary": "Create, replace or remove rules and ordered attachments in one version", + "summary": "Apply rules", + "description": "Create, replace or remove rules and ordered attachments in one version.", "parameters": [ { "schema": { @@ -55331,7 +55339,8 @@ "Rules" ], "operationId": "testRules", - "summary": "Trace saved or proposed rules on a stored message or pasted MIME; never asks the AI or delivers mail", + "summary": "Test rules on a message", + "description": "Trace saved or proposed rules on a stored message or pasted MIME; never asks the AI or delivers mail.", "requestBody": { "required": true, "content": { @@ -55686,7 +55695,8 @@ } ], "operationId": "listInboxFolders", - "summary": "List folders, stable UID namespaces and counts", + "summary": "List inbox folders", + "description": "List folders, stable UID namespaces and counts.", "parameters": [ { "schema": { @@ -56219,7 +56229,8 @@ } ], "operationId": "updateInboxFolder", - "summary": "Rename a folder tree or change its subscription", + "summary": "Update an inbox folder", + "description": "Rename a folder tree or change its subscription.", "parameters": [ { "schema": { @@ -56472,7 +56483,8 @@ } ], "operationId": "deleteInboxFolder", - "summary": "Remove a custom folder; preserve otherwise orphaned mail in Trash", + "summary": "Delete an inbox folder", + "description": "Remove a custom folder; preserve otherwise orphaned mail in Trash.", "parameters": [ { "schema": { @@ -56690,7 +56702,8 @@ } ], "operationId": "updateInboxMessage", - "summary": "Set read state or flags; deleted applies to one folder entry", + "summary": "Update an inbox message", + "description": "Set read state or flags; deleted applies to one folder entry.", "parameters": [ { "schema": { @@ -56981,7 +56994,8 @@ } ], "operationId": "deleteInboxMessage", - "summary": "Move one entry to Trash, or expunge it permanently", + "summary": "Delete an inbox message", + "description": "Move one entry to Trash, or expunge it permanently.", "parameters": [ { "schema": { @@ -57443,7 +57457,8 @@ } ], "operationId": "moveInboxMessage", - "summary": "Move one entry and allocate a new destination UID", + "summary": "Move an inbox message", + "description": "Move one entry and allocate a new destination UID.", "parameters": [ { "schema": { @@ -57712,7 +57727,8 @@ } ], "operationId": "copyInboxMessage", - "summary": "Copy one entry with a fresh destination UID", + "summary": "Copy an inbox message", + "description": "Copy one entry with a fresh destination UID.", "parameters": [ { "schema": { @@ -57981,7 +57997,8 @@ } ], "operationId": "expungeInboxFolder", - "summary": "Remove entries marked deleted; repeat while hasMore is true", + "summary": "Expunge an inbox folder", + "description": "Remove entries marked deleted; repeat while hasMore is true.", "parameters": [ { "schema": { @@ -58205,7 +58222,8 @@ } ], "operationId": "getInboxChanges", - "summary": "Sync changed and removed message IDs since an inbox MODSEQ", + "summary": "Read an inbox’s changes", + "description": "Sync changed and removed message IDs since an inbox MODSEQ.", "parameters": [ { "schema": { @@ -58407,7 +58425,8 @@ } ], "operationId": "createInboxAppPassword", - "summary": "Grant mail client access to a persistent inbox. Password shown once; a billable day starts immediately.", + "summary": "Create an inbox app password", + "description": "Password shown once; a billable day starts immediately. Grant mail client access to a persistent inbox.", "parameters": [ { "schema": { @@ -58648,7 +58667,8 @@ } ], "operationId": "listInboxAppPasswords", - "summary": "List active app passwords without their secrets", + "summary": "List an inbox’s app passwords", + "description": "List active app passwords without their secrets.", "parameters": [ { "schema": { @@ -58849,7 +58869,8 @@ } ], "operationId": "listAppPasswords", - "summary": "List the active app passwords of every inbox, without their secrets", + "summary": "List every inbox’s app passwords", + "description": "List the active app passwords of every inbox, without their secrets.", "responses": { "200": { "description": "Success", @@ -59000,7 +59021,8 @@ } ], "operationId": "revokeInboxAppPassword", - "summary": "Revoke a mail client password and invalidate sessions", + "summary": "Revoke an inbox app password", + "description": "Revoke a mail client password and invalidate sessions.", "parameters": [ { "schema": { @@ -60936,7 +60958,8 @@ "secureDashboardSession": [] } ], - "summary": "Release a retired address for reuse (workspace admin)", + "summary": "Release a retired address", + "description": "Release a retired address for reuse (workspace admin).", "parameters": [ { "schema": { @@ -64893,8 +64916,8 @@ "secureDashboardSession": [] } ], - "summary": "Change where one address’s mail goes, in one version", - "description": "Changes the route for the address’s own address and its two-way rule together: one transaction and one routing version, so all of it is saved or none of it. Omitted fields stay as they are, a field equal to what is saved writes nothing, and when nothing changes the version stays. deliver replaces only the route’s destinations (a paused route stays paused). Send the version from getInboundOverview or getRouting as If-Match; a stale one is refused with 409 and nothing changes.", + "summary": "Set where an address’s mail goes", + "description": "Change where one address’s mail goes, in one version. Changes the route for the address’s own address and its two-way rule together: one transaction and one routing version, so all of it is saved or none of it. Omitted fields stay as they are, a field equal to what is saved writes nothing, and when nothing changes the version stays. deliver replaces only the route’s destinations (a paused route stays paused). Send the version from getInboundOverview or getRouting as If-Match; a stale one is refused with 409 and nothing changes.", "parameters": [ { "schema": { @@ -65294,7 +65317,8 @@ "secureDashboardSession": [] } ], - "summary": "Start a conversation from an inbound address", + "summary": "Start a conversation", + "description": "Start a conversation from an inbound address.", "parameters": [ { "schema": { @@ -65666,7 +65690,8 @@ "secureDashboardSession": [] } ], - "summary": "Mark a conversation read, star, archive or label it for one address", + "summary": "Update a conversation", + "description": "Mark a conversation read, star, archive or label it for one address.", "parameters": [ { "schema": { @@ -66315,7 +66340,8 @@ "secureDashboardSession": [] } ], - "summary": "Download an attachment from a visible message", + "summary": "Download an inbound attachment", + "description": "Download an attachment from a visible message.", "parameters": [ { "schema": { @@ -66499,7 +66525,7 @@ "secureDashboardSession": [] } ], - "summary": "Follow an attachment link from a webhook", + "summary": "Follow a webhook attachment link", "description": "The downloadUrl (inbound format) or url (message attachments) in webhook payloads. Answers 307 to a download link that works for five minutes, also returned as url in the body. Any credential that can read the message can follow it, exactly as with getInboundAttachment: an inbound key for the address it reached, a member, an agent token.", "parameters": [ { @@ -66991,8 +67017,8 @@ "secureDashboardSession": [] } ], - "summary": "Every route mail can take, with its rules and endpoints, in one read", - "description": "One page of routes (addresses, agent inboxes, address patterns, explicit routes and catch-alls) merged and ordered by host, kind and address, each resolved to the rules that run on it and where its mail goes. Also returns counts per kind, the rules, up to 100 endpoints and 100 inbound webhooks, and the domains. Members and scoped keys see only their addresses. With an MCP sign-in (approval), it requires an owner or admin, like the other receiving reads.", + "summary": "Read the receiving overview", + "description": "Every route mail can take, with its rules and endpoints, in one read. One page of routes (addresses, agent inboxes, address patterns, explicit routes and catch-alls) merged and ordered by host, kind and address, each resolved to the rules that run on it and where its mail goes. Also returns counts per kind, the rules, up to 100 endpoints and 100 inbound webhooks, and the domains. Members and scoped keys see only their addresses. With an MCP sign-in (approval), it requires an owner or admin, like the other receiving reads.", "parameters": [ { "schema": { @@ -67212,8 +67238,8 @@ "secureDashboardSession": [] } ], - "summary": "List every endpoint a page at a time, with the routes and rules that use it", - "description": "Named endpoints of every type (Slack, Discord, webhook, forward) by name, then webhooks without a name. Pass nextCursor back as cursor until it is null. addressId lists only the webhooks that get that address's received mail (subscribed to it or to every address), the full list a route's toMore points to.", + "summary": "List every endpoint", + "description": "List every endpoint a page at a time, with the routes and rules that use it. Named endpoints of every type (Slack, Discord, webhook, forward) by name, then webhooks without a name. Pass nextCursor back as cursor until it is null. addressId lists only the webhooks that get that address's received mail (subscribed to it or to every address), the full list a route's toMore points to.", "parameters": [ { "schema": { @@ -67587,8 +67613,8 @@ "tags": [ "Inbound events" ], - "summary": "Poll events for the receiving addresses this key can read", - "description": "Use the returned cursor as after to continue polling. Workspace-wide message.stored events require admin access, no address filter, and an explicit message.stored type filter.", + "summary": "List inbound events", + "description": "Poll events for the receiving addresses this key can read. Use the returned cursor as after to continue polling. Workspace-wide message.stored events require admin access, no address filter, and an explicit message.stored type filter.", "parameters": [ { "schema": { @@ -67973,8 +67999,8 @@ "tags": [ "Inbound webhooks" ], - "summary": "List inbound webhooks a page at a time, in a stable ID order", - "description": "Every webhook endpoint, named or not. Pass nextCursor back as cursor until it is null to read every webhook. addressId and eventType narrow the list to the webhooks that get that address's events (subscribed to it or to every address); getInboundOverview links a route's full list of subscribers this way.", + "summary": "List inbound webhooks", + "description": "List inbound webhooks a page at a time, in a stable ID order. Every webhook endpoint, named or not. Pass nextCursor back as cursor until it is null to read every webhook. addressId and eventType narrow the list to the webhooks that get that address's events (subscribed to it or to every address); getInboundOverview links a route's full list of subscribers this way.", "parameters": [ { "schema": { @@ -68875,7 +68901,7 @@ "tags": [ "Inbound webhooks" ], - "summary": "Redeliver a message to its route webhooks", + "summary": "Redeliver an inbound message", "description": "Queues this message again for every route webhook that already finished with it (delivered or failed), or only destination. Returns how many deliveries were queued; 0 means none are eligible. Previously redelivered successes have a 10-minute cooldown. The workspace gets 1,000 manual posts per hour. Receivers deduplicate by Webhook-Id.", "parameters": [ { @@ -73330,8 +73356,8 @@ "secureDashboardSession": [] } ], - "summary": "What this workspace has set up, in one read", - "description": "The newest domains, the number of active API keys, outbound webhooks and pending invitations, whether any email exists, each focus's first steps and whether an agent is connected. Each part follows the permission rules of its own list operation and is null where that operation would refuse the caller. Counts only: no webhook URL, key, address or subject.", + "summary": "Read the workspace setup", + "description": "What this workspace has set up, in one read. The newest domains, the number of active API keys, outbound webhooks and pending invitations, whether any email exists, each focus's first steps and whether an agent is connected. Each part follows the permission rules of its own list operation and is null where that operation would refuse the caller. Counts only: no webhook URL, key, address or subject.", "responses": { "200": { "description": "Success", @@ -73951,7 +73977,7 @@ "secureDashboardSession": [] } ], - "summary": "Balance, free allowance and billing state", + "summary": "Read the balance and billing state", "description": "Hosted only. The prepaid balance, this month’s free allowances (sent and received, counted separately) and cost, whether sending or receiving is paused for an empty balance, auto-recharge and the saved card, and the prices. Amounts are null unless the caller is an owner or admin session, or a manage key or grant. Keys restricted to domains get 403.", "responses": { "200": { diff --git a/api/scripts/check-premerge.ts b/api/scripts/check-premerge.ts index 4a5b263f0..e21e12e70 100644 --- a/api/scripts/check-premerge.ts +++ b/api/scripts/check-premerge.ts @@ -478,6 +478,23 @@ const warn = (check: string, message: string, file?: string) => console.log(`::w if (failed === before) console.log(`Job handlers: all ${types.size} enqueued and registered job types resolve through dispatch.ts.`); } +// 12. An operation's summary is a name. It is the docs page's title in the browser tab and in search results +// (docsTitle, app/src/features/docs/meta.ts), the docs sidebar's entry and the SDK's comment, and the MCP tool leads +// with it: a sentence there runs past the 60 characters a search result shows. Sentences go in the description. +{ + // The app's own title rule, by URL: the API's type check doesn't take in the app's sources. + const { docsTitle, operationTitle } = await import(new URL('../../app/src/features/docs/meta.ts', import.meta.url).href) as { docsTitle: (page: string) => string; operationTitle: (id: string) => string }; + const before = failed; + const spec = JSON.parse(readFileSync(new URL('openapi.json', api), 'utf8')) as { paths: Record> }; + const operations = Object.values(spec.paths).flatMap(item => Object.values(item)).filter(op => op.operationId); + const most = 60 - docsTitle('').length; + for (const op of operations) { + const name = op.summary ?? operationTitle(op.operationId!), title = docsTitle(name); + if (title.length > 60 || /[.;:!?](\s|$)/.test(name)) fail('Operation summaries', `${op.operationId}'s summary “${name}” is ${title.length > 60 ? `${name.length} characters` : 'a sentence'}. A summary is a name of at most ${most} characters with no full stop, because it is the docs page's title (“${title}”, ${title.length} of 60 characters) and the SDK's comment. Keep a short name (“Create an inbox app password”), move the sentence word for word into the operation's description, warnings first, and run bun run sdk in api/.`); + } + if (failed === before) console.log(`Operation summaries: all ${operations.length} operations are named in at most ${most} characters, so every docs title fits in 60.`); +} + if (failed) { console.log(`\n${failed} pre-merge check${failed === 1 ? '' : 's'} failed. docs/ci.md explains each one and how to fix it.`); process.exitCode = 1; diff --git a/api/src/address-flow.ts b/api/src/address-flow.ts index 73d5f2ac8..4cb73fdc9 100644 --- a/api/src/address-flow.ts +++ b/api/src/address-flow.ts @@ -164,8 +164,8 @@ export async function releaseAddress(tx: DbExecutor, c: Ctx, w: string, box: { i export function registerAddressFlow(app: App) { app.openapi(createRoute({ method: 'patch', path: '/v1/inbound/addresses/{addressId}/flow', operationId: 'setInboundAddressFlow', tags: ['Inbound addresses'], security, - summary: 'Change where one address’s mail goes, in one version', - description: 'Changes the route for the address’s own address and its two-way rule together: one transaction and one routing version, so all of it is saved or none of it. Omitted fields stay as they are, a field equal to what is saved writes nothing, and when nothing changes the version stays. deliver replaces only the route’s destinations (a paused route stays paused). Send the version from getInboundOverview or getRouting as If-Match; a stale one is refused with 409 and nothing changes.', + summary: 'Set where an address’s mail goes', + description: 'Change where one address’s mail goes, in one version. Changes the route for the address’s own address and its two-way rule together: one transaction and one routing version, so all of it is saved or none of it. Omitted fields stay as they are, a field equal to what is saved writes nothing, and when nothing changes the version stays. deliver replaces only the route’s destinations (a paused route stays paused). Send the version from getInboundOverview or getRouting as If-Match; a stale one is refused with 409 and nothing changes.', request: { params: z.object({ addressId: InboundAddressId }), headers: z.object({ 'if-match': z.string().max(32).optional().describe('Apply only if routes and rules are still at this version, from getInboundOverview, GET /v1/routing or a previous ETag.') }), diff --git a/api/src/agent-setup.ts b/api/src/agent-setup.ts index 14bb9cb74..c7cefab83 100644 --- a/api/src/agent-setup.ts +++ b/api/src/agent-setup.ts @@ -217,7 +217,7 @@ export function registerAgentSetup(app: App) { return c.json({ id: setupId, status, expiresAt: isoTime(row.expires_at)!, connectedAt: isoTime(row.used_at), keyId: row.key_id, keyName: row.key_name }, 200); }); app.openapi(createRoute({ method: 'post', path: '/v1/agent/setup', operationId: 'exchangeAgentSetupToken', tags, security: [], - summary: 'Exchange a setup token for the agent\'s API key', + summary: 'Exchange a setup token for an API key', description: `For a coding agent: the setup token in the prompt a person copied from the dashboard (${secretPrefixes.agentSetup}…) becomes a lasting API key for the agent, in that person's workspace, named after client_name. It works once, within ${SETUP_MINUTES} minutes of copying. A wrong token gets 400 SETUP_TOKEN_INVALID, a used one 409 SETUP_TOKEN_USED (naming the key it gave, in error.details, never the key again), and an expired or replaced one 410 SETUP_TOKEN_EXPIRED or SETUP_TOKEN_REPLACED with a device code in error.details[0] (startAgentDeviceAuthorization's answer) for the person who copied it to approve: show them its link and poll it. The key is shown once.`, request: { body: json(z.object({ token: Token.openapi({ example: `${secretPrefixes.agentSetup}${'0'.repeat(32)}.${'0'.repeat(64)}` }).describe('The setup token from the prompt.'), client_name: ClientName }).strict()) }, @@ -254,7 +254,7 @@ export function registerAgentSetup(app: App) { // ---------- device: RFC 8628 for an agent started without the prompt ---------- app.openapi(createRoute({ method: 'post', path: '/v1/agent/device', operationId: 'startAgentDeviceAuthorization', tags, security: [], - summary: 'Start the device flow for a coding agent', + summary: 'Start the device flow for an agent', description: `For a coding agent without a setup token (RFC 8628): returns a device code to keep and a user code to show. Show the person verification_uri_complete as a link on its own line and ask them to open it, sign in, check the code and approve; nextStep says so in words. Then poll pollAgentDeviceToken every interval seconds until it returns the key. Codes work once, for ${DEVICE_MINUTES} minutes. With setup_token (one from the person's prompt that expired or was replaced before it was used), their dashboard shows you waiting.`, request: { body: { ...json(z.object({ client_name: ClientName, setup_token: Token.optional().describe('The setup token from the person\'s prompt, even if it expired or was replaced: their dashboard then shows you waiting for their approval. One that was used already addresses nobody.') }).strict()), required: false } }, @@ -357,7 +357,7 @@ export function registerAgentSetup(app: App) { throw new ApiError(409, 'DEVICE_CODE_DECIDED', `This code was already ${row.status === 'denied' ? 'denied' : 'approved'}.`); } app.openapi(createRoute({ method: 'post', path: '/v1/agent/device/lookup', operationId: 'lookUpAgentDevice', tags, security: dashboardSecurity, - summary: 'Look up an agent waiting with a user code', + summary: 'Look up an agent by user code', description: `The /connect page: the agent behind a user code, before you approve or deny it. Each attempt counts against ${LIMITS.userCode} a minute per person. Dashboard session only.`, request: { body: json(z.object({ userCode: UserCode }).strict()) }, responses: { 200: response(DeviceRequest), ...errors } }), async c => { const { userId } = person(c, false), code = await codeOf(c, userId, c.req.valid('json').userCode); @@ -383,7 +383,7 @@ export function registerAgentSetup(app: App) { return c.json({ data: rows.map(row => ({ userCode: shownCode(row.user_code), clientName: row.client_name, createdAt: isoTime(row.created_at)!, expiresAt: isoTime(row.expires_at)!, promptCopiedAt: isoTime(row.copied)! })) }, 200); }); app.openapi(createRoute({ method: 'post', path: '/v1/agent/device/approve', operationId: 'approveAgentDevice', tags, security: dashboardSecurity, - summary: 'Approve an agent waiting with a user code', + summary: 'Approve an agent by user code', description: 'Gives the agent behind the user code its own API key in the workspace this request acts in (X-Nightmail-Workspace), which you must own or administer. It receives the key on its next poll. Dashboard session only.', request: { body: json(z.object({ userCode: UserCode }).strict()) }, responses: { 200: response(z.object({ userCode: z.string(), status: z.literal('approved'), workspaceId: z.string() }).openapi('AgentDeviceApproval')), ...errors, ...gone } }), async c => { const { workspaceId, userId } = person(c, true), code = await codeOf(c, userId, c.req.valid('json').userCode); diff --git a/api/src/billing/routes.ts b/api/src/billing/routes.ts index c8bc3b586..b23ad4363 100644 --- a/api/src/billing/routes.ts +++ b/api/src/billing/routes.ts @@ -146,7 +146,7 @@ async function ledgerPage(db: DbExecutor, workspaceId: string, cursor: string | } export function registerBilling(app: App) { - app.openapi(createRoute({ method: 'get', path: '/v1/billing', operationId: 'getBilling', tags: ['Billing'], security, summary: 'Balance, free allowance and billing state', + app.openapi(createRoute({ method: 'get', path: '/v1/billing', operationId: 'getBilling', tags: ['Billing'], security, summary: 'Read the balance and billing state', description: 'Hosted only. The prepaid balance, this month’s free allowances (sent and received, counted separately) and cost, whether sending or receiving is paused for an empty balance, auto-recharge and the saved card, and the prices. Amounts are null unless the caller is an owner or admin session, or a manage key or grant. Keys restricted to domains get 403.', responses: { 200: response(BillingSummarySchema), ...errors } }), async c => { const a = billingActor(c, 'read'); diff --git a/api/src/endpoints.ts b/api/src/endpoints.ts index f887f0bc2..17dae8a78 100644 --- a/api/src/endpoints.ts +++ b/api/src/endpoints.ts @@ -417,13 +417,13 @@ export function registerEndpoints(app: App) { const w = receivingAdmin(c).workspaceId, q = c.req.valid('query'), rows = await endpointRows(c.env.db, w, q); return c.json({ data: await Promise.all(rows.slice(0, q.limit).map(r => endpointView(c.env, w, r))), nextCursor: rows.length > q.limit ? rows[q.limit - 1]!.key : null }, 200); }); - app.openapi(createRoute({ ...meta, method: 'get', path: `${base}/{name}`, operationId: 'getEndpoint', summary: 'Read one endpoint, its status and the next step', request: { params: NameParam }, responses: { 200: response(Endpoint), ...errors } }), async c => { + app.openapi(createRoute({ ...meta, method: 'get', path: `${base}/{name}`, operationId: 'getEndpoint', summary: 'Read an endpoint', description: 'Read one endpoint, its status and the next step.', request: { params: NameParam }, responses: { 200: response(Endpoint), ...errors } }), async c => { const w = receivingAdmin(c).workspaceId; return c.json(await endpointView(c.env, w, await findEndpoint(c.env.db, w, c.req.valid('param').name)), 200); }); app.openapi(createRoute({ - ...meta, method: 'post', path: base, operationId: 'createEndpoint', summary: 'Create a named Slack, Discord, webhook or forward endpoint', - description: 'Slack and Discord URLs are credentials: stored encrypted, pinned to the provider host and never returned. A webhook endpoint is a route-only inbound webhook; its signing secret is returned once. A forward emails its recipient a single-use confirmation link (24 hours); it stays pending until they choose Allow. With preverify, an address on a domain this workspace has verified is ready at once. Once ready, a rule calls it as endpoints.() and a route forwards to it as forward:; either way the recipient gets each message whole: text, HTML and attachments.', + ...meta, method: 'post', path: base, operationId: 'createEndpoint', summary: 'Create an endpoint', + description: 'Create a named Slack, Discord, webhook or forward endpoint. Slack and Discord URLs are credentials: stored encrypted, pinned to the provider host and never returned. A webhook endpoint is a route-only inbound webhook; its signing secret is returned once. A forward emails its recipient a single-use confirmation link (24 hours); it stays pending until they choose Allow. With preverify, an address on a domain this workspace has verified is ready at once. Once ready, a rule calls it as endpoints.() and a route forwards to it as forward:; either way the recipient gets each message whole: text, HTML and attachments.', request: { body: json(CreateEndpoint) }, responses: { 201: response(Endpoint.extend({ secret: z.string().optional().describe('Webhook signing secret, shown once.') }).openapi('CreatedEndpoint')), ...errors }, }), async c => { const q = c.req.valid('json'), w = receivingAdmin(c, manage).workspaceId; @@ -442,8 +442,8 @@ export function registerEndpoints(app: App) { if (created.status === 'pending') c.get('actor').wakeJobs = 1; return c.json({ ...created, ...(secret ? { secret } : {}) }, 201); }); - app.openapi(createRoute({ ...meta, method: 'patch', path: `${base}/{name}`, operationId: 'updateEndpoint', summary: 'Edit an endpoint: its name, type, URL, pause state, rate or retry policy', - description: 'Send only what changes. URLs and headers are write-only: an omitted url keeps the current one, and none is ever returned. A forward’s address is fixed (its recipient confirmed it); create a new forward instead.', + app.openapi(createRoute({ ...meta, method: 'patch', path: `${base}/{name}`, operationId: 'updateEndpoint', summary: 'Edit an endpoint', + description: 'Edit an endpoint: its name, type, URL, pause state, rate or retry policy. Send only what changes. URLs and headers are write-only: an omitted url keeps the current one, and none is ever returned. A forward’s address is fixed (its recipient confirmed it); create a new forward instead.', request: { params: NameParam, body: json(UpdateEndpoint) }, responses: { 200: response(Endpoint), ...errors } }), async c => { const w = receivingAdmin(c, manage).workspaceId, name = c.req.valid('param').name, { name: rename, ...q } = c.req.valid('json'); const updated = await c.env.db.transaction(async tx => { @@ -458,7 +458,7 @@ export function registerEndpoints(app: App) { }); return c.json(await endpointView(c.env, w, rowOf(updated)), 200); }); - app.openapi(createRoute({ ...meta, method: 'delete', path: `${base}/{name}`, operationId: 'deleteEndpoint', summary: 'Delete an endpoint no rule or route uses', request: { params: NameParam }, responses: { 200: response(z.object({ name: Name, deleted: z.literal(true) }).openapi('DeletedEndpoint')), ...errors } }), async c => { + app.openapi(createRoute({ ...meta, method: 'delete', path: `${base}/{name}`, operationId: 'deleteEndpoint', summary: 'Delete an endpoint', description: 'Delete an endpoint no rule or route uses.', request: { params: NameParam }, responses: { 200: response(z.object({ name: Name, deleted: z.literal(true) }).openapi('DeletedEndpoint')), ...errors } }), async c => { const w = receivingAdmin(c, manage).workspaceId, name = c.req.valid('param').name; await c.env.db.transaction(async tx => { const row = await lockEndpoint(tx, c, w, { name }, false); @@ -468,13 +468,13 @@ export function registerEndpoints(app: App) { }); return c.json({ name, deleted: true as const }, 200); }); - app.openapi(createRoute({ ...meta, method: 'post', path: `${base}/{name}/verification`, operationId: 'sendEndpointVerification', summary: 'Email a forward recipient a new confirmation link', description: 'For a pending, expired or (after 30 days) declined forward. The recipient must open the link and choose Allow; no API call can confirm on their behalf.', request: { params: NameParam, body: json(z.object({ from: z.string().max(254).optional() }).strict()) }, responses: { 202: response(Endpoint), ...errors } }), async c => { + app.openapi(createRoute({ ...meta, method: 'post', path: `${base}/{name}/verification`, operationId: 'sendEndpointVerification', summary: 'Resend a forward confirmation link', description: 'Email a forward recipient a new confirmation link. For a pending, expired or (after 30 days) declined forward. The recipient must open the link and choose Allow; no API call can confirm on their behalf.', request: { params: NameParam, body: json(z.object({ from: z.string().max(254).optional() }).strict()) }, responses: { 202: response(Endpoint), ...errors } }), async c => { const w = receivingAdmin(c, manage).workspaceId, name = c.req.valid('param').name, q = c.req.valid('json'); await c.env.db.transaction(async tx => { if (!await resendForwardConfirmation(c, tx, w, { name }, q.from)) throw missingEndpoint(name); }); c.get('actor').wakeJobs = 1; return c.json(await endpointView(c.env, w, await findEndpoint(c.env.db, w, name)), 202); }); - app.openapi(createRoute({ ...meta, method: 'post', path: `${base}/{name}/test`, operationId: 'testEndpoint', summary: 'Post a fixed test message to a Slack, Discord or webhook endpoint now', description: 'Bypasses rules and queues: one synchronous post, counted against the endpoint rate. Forwards send real mail, so they are not tested this way; use testRules for a dry run.', request: { params: NameParam }, responses: { 200: response(z.object({ ok: z.boolean(), status: z.number().int().nullable(), error: z.string().nullable() }).openapi('EndpointTest')), ...errors } }), async c => { + app.openapi(createRoute({ ...meta, method: 'post', path: `${base}/{name}/test`, operationId: 'testEndpoint', summary: 'Test an endpoint', description: 'Post a fixed test message to a Slack, Discord or webhook endpoint now. Bypasses rules and queues: one synchronous post, counted against the endpoint rate. Forwards send real mail, so they are not tested this way; use testRules for a dry run.', request: { params: NameParam }, responses: { 200: response(z.object({ ok: z.boolean(), status: z.number().int().nullable(), error: z.string().nullable() }).openapi('EndpointTest')), ...errors } }), async c => { const w = receivingAdmin(c, manage).workspaceId, name = c.req.valid('param').name; const [row] = await c.env.db.select().from(endpoints).where(and(eq(endpoints.workspaceId, w), eq(endpoints.key, name))); if (!row) throw missingEndpoint(name); @@ -593,8 +593,8 @@ export function registerInboundWebhooks(app: App, deps: Access) { return c.json({ ...view, ...view.approval ? { nextStep: tiedNextStep('webhook', view.approval) } : {}, secret: secret!, ...await inboundToken(format, secret!) }, 201); }); app.openapi(createRoute({ method: 'get', path, operationId: 'listInboundWebhooks', security, tags, - summary: 'List inbound webhooks a page at a time, in a stable ID order', - description: 'Every webhook endpoint, named or not. Pass nextCursor back as cursor until it is null to read every webhook. addressId and eventType narrow the list to the webhooks that get that address\'s events (subscribed to it or to every address); getInboundOverview links a route\'s full list of subscribers this way.', + summary: 'List inbound webhooks', + description: 'List inbound webhooks a page at a time, in a stable ID order. Every webhook endpoint, named or not. Pass nextCursor back as cursor until it is null to read every webhook. addressId and eventType narrow the list to the webhooks that get that address\'s events (subscribed to it or to every address); getInboundOverview links a route\'s full list of subscribers this way.', request: { query: z.object({ cursor: z.string().max(200).optional().describe('nextCursor from the previous page.'), limit: z.coerce.number().int().min(1).max(100).default(100), @@ -643,7 +643,7 @@ export function registerInboundWebhooks(app: App, deps: Access) { const w = deps.admin(c).workspaceId; return c.json(await testInboundWebhook(c.env, w, c.req.valid('param').id, c.req.valid('json')), 200); }); - app.openapi(createRoute({ method: 'post', path: '/v1/inbound/messages/{messageId}/redeliver', operationId: 'redeliverInboundMessage', security, tags, summary: 'Redeliver a message to its route webhooks', + app.openapi(createRoute({ method: 'post', path: '/v1/inbound/messages/{messageId}/redeliver', operationId: 'redeliverInboundMessage', security, tags, summary: 'Redeliver an inbound message', description: `Queues this message again for every route webhook that already finished with it (delivered or failed), or only destination. Returns how many deliveries were queued; 0 means none are eligible. Previously redelivered successes have a 10-minute cooldown. The workspace gets ${MANUAL_DELIVERY_BUDGET.toLocaleString('en-US')} manual posts per hour. Receivers deduplicate by Webhook-Id.`, request: { params: z.object({ messageId: z.string().max(120) }), body: json(z.object({ destination: z.string().max(128).optional().describe('A webhook ID: redeliver to that webhook only.') }).strict().openapi('RedeliverInboundMessage')) }, responses: { 202: response(z.object({ queued: z.number().int() }).openapi('InboundRedelivery')), ...errors } }), async c => { const { workspaceId: w } = deps.admin(c), { messageId } = c.req.valid('param'), { destination } = c.req.valid('json'); diff --git a/api/src/inbound-overview.ts b/api/src/inbound-overview.ts index 5e0768c2c..51f32e313 100644 --- a/api/src/inbound-overview.ts +++ b/api/src/inbound-overview.ts @@ -151,8 +151,8 @@ export function registerInboundOverview(app: App, deps: Deps) { app.openapi(createRoute({ method: 'get', path: '/v1/inbound/overview', operationId: 'getInboundOverview', tags: ['Inbound addresses'], security: deps.security, - summary: 'Every route mail can take, with its rules and endpoints, in one read', - description: 'One page of routes (addresses, agent inboxes, address patterns, explicit routes and catch-alls) merged and ordered by host, kind and address, each resolved to the rules that run on it and where its mail goes. Also returns counts per kind, the rules, up to 100 endpoints and 100 inbound webhooks, and the domains. Members and scoped keys see only their addresses. With an MCP sign-in (approval), it requires an owner or admin, like the other receiving reads.', + summary: 'Read the receiving overview', + description: 'Every route mail can take, with its rules and endpoints, in one read. One page of routes (addresses, agent inboxes, address patterns, explicit routes and catch-alls) merged and ordered by host, kind and address, each resolved to the rules that run on it and where its mail goes. Also returns counts per kind, the rules, up to 100 endpoints and 100 inbound webhooks, and the domains. Members and scoped keys see only their addresses. With an MCP sign-in (approval), it requires an owner or admin, like the other receiving reads.', request: { query: z.object({ kind: Kinds.optional(), origin: z.enum(['api', 'auto']).optional().describe('Filters address rows only: api (created on purpose) or auto (created by a catch-all). Other kinds are unaffected.'), domain: z.string().max(253).optional().describe('Receiving host, e.g. reply.acme.com.'), q: z.string().max(200).optional().describe('Matches the address, an alias or the display name.'), @@ -363,8 +363,8 @@ export function registerInboundOverview(app: App, deps: Deps) { // Every endpoint, a page at a time: what the Receiving screen's Endpoints list reads (the overview lists the first 100 of each kind). app.openapi(createRoute({ method: 'get', path: '/v1/inbound/endpoints', operationId: 'listInboundEndpoints', tags: ['Endpoints'], security: deps.security, - summary: 'List every endpoint a page at a time, with the routes and rules that use it', - description: 'Named endpoints of every type (Slack, Discord, webhook, forward) by name, then webhooks without a name. Pass nextCursor back as cursor until it is null. addressId lists only the webhooks that get that address\'s received mail (subscribed to it or to every address), the full list a route\'s toMore points to.', + summary: 'List every endpoint', + description: 'List every endpoint a page at a time, with the routes and rules that use it. Named endpoints of every type (Slack, Discord, webhook, forward) by name, then webhooks without a name. Pass nextCursor back as cursor until it is null. addressId lists only the webhooks that get that address\'s received mail (subscribed to it or to every address), the full list a route\'s toMore points to.', request: { query: z.object({ cursor: z.string().max(400).optional().describe('nextCursor from the previous page.'), limit: z.coerce.number().int().min(1).max(100).default(50), diff --git a/api/src/inbound-threads.ts b/api/src/inbound-threads.ts index 4f9e956f0..9443e6aa2 100644 --- a/api/src/inbound-threads.ts +++ b/api/src/inbound-threads.ts @@ -538,10 +538,10 @@ export function registerInboundThreadReads(app: App, access: (c: Ctx, permission if (!file?.region) throw new ApiError(404,'NOT_FOUND','Attachment was not found.'); return signedUrl(c.env,v.workspaceId,'att',file.region,file.bucket,file.key,file.filename,file.sourceId?p.messageId:undefined); } - app.openapi(createRoute({method:'get',path:'/v1/inbound/messages/{messageId}/attachments/{attachmentId}',operationId:'getInboundAttachment',tags,security,summary:'Download an attachment from a visible message', + app.openapi(createRoute({method:'get',path:'/v1/inbound/messages/{messageId}/attachments/{attachmentId}',operationId:'getInboundAttachment',tags,security,summary:'Download an inbound attachment',description:'Download an attachment from a visible message.', request:{params:AttachmentParams,query:AddressFilter},responses:{200:response(AttachmentDownload),...errors}}),async c=>c.json(await attachmentLink(c,c.req.valid('param'),c.req.valid('query')),200)); // The persistent link in webhook payloads (downloadUrl, or url in a message's attachments). - app.openapi(createRoute({method:'get',path:'/v1/inbound/messages/{messageId}/parts/{attachmentId}',operationId:'downloadInboundAttachment',tags,security,summary:'Follow an attachment link from a webhook', + app.openapi(createRoute({method:'get',path:'/v1/inbound/messages/{messageId}/parts/{attachmentId}',operationId:'downloadInboundAttachment',tags,security,summary:'Follow a webhook attachment link', description:'The downloadUrl (inbound format) or url (message attachments) in webhook payloads. Answers 307 to a download link that works for five minutes, also returned as url in the body. Any credential that can read the message can follow it, exactly as with getInboundAttachment: an inbound key for the address it reached, a member, an agent token.', request:{params:AttachmentParams,query:AddressFilter},responses:{307:{description:'Follow Location within five minutes.',headers:z.object({Location:z.string()}),content:{'application/json':{schema:AttachmentDownload}}},...errors}}),async c=>{ const link=await attachmentLink(c,c.req.valid('param'),c.req.valid('query')); @@ -551,7 +551,7 @@ export function registerInboundThreadReads(app: App, access: (c: Ctx, permission } export function createInboundThreadRoute(input: T) { - return createRoute({ method: 'post', path: base, operationId: 'createInboundThread', tags, security, summary: 'Start a conversation from an inbound address', + return createRoute({ method: 'post', path: base, operationId: 'createInboundThread', tags, security, summary: 'Start a conversation', description: 'Start a conversation from an inbound address.', request: { headers: SendIdempotencyHeaders, body: json(input) }, responses: { 202: response(Message, 'Queued, not yet delivered.'), ...errors } }); } export function replyToInboundThreadRoute(input: T) { diff --git a/api/src/inbox-connection.ts b/api/src/inbox-connection.ts index f6aec0805..40a14f70d 100644 --- a/api/src/inbox-connection.ts +++ b/api/src/inbox-connection.ts @@ -11,7 +11,7 @@ import { secretPrefixes, shownPrefix } from './brand.js'; // screen choice that no longer exists). export function registerInboxConnection(app:App){ const body=z.object({inboxes:z.array(z.string().min(1).max(120)).min(1).max(20),client:z.enum(mcpClients).describe('opencode, claude (Claude Code), cursor, or generic for any other MCP client.'),auth:z.enum(['key','oauth']).describe('key. oauth is refused with 422: a sign-in can’t be limited to inboxes.'),reply:z.boolean().default(false)}).strict(); - app.openapi(createRoute({method:'post',path:'/v1/inbox-connections',operationId:'createInboxConnection',tags:['Agent inboxes'],security,summary:'Generate client config with a key limited to selected inboxes. Key shown once.',request:{body:json(body)},responses:{201:response(z.object({id:z.string().nullable(),inboxes:z.array(z.string()),config:z.record(z.string(),z.unknown()),nextStep:z.string()})),...errors}}),async c=>{ + app.openapi(createRoute({method:'post',path:'/v1/inbox-connections',operationId:'createInboxConnection',tags:['Agent inboxes'],security,summary:'Create an inbox connection',description:'Key shown once. Generate client config with a key limited to selected inboxes.',request:{body:json(body)},responses:{201:response(z.object({id:z.string().nullable(),inboxes:z.array(z.string()),config:z.record(z.string(),z.unknown()),nextStep:z.string()})),...errors}}),async c=>{ const a=receivingAdmin(c,'create inbox connections'),q=c.req.valid('json'),w=a.workspaceId,url=mcpServerUrl(c.env.config.publicUrl); if(q.auth==='oauth')throw new ApiError(422,'VALIDATION_FAILED','A sign-in can’t be limited to inboxes. Use auth:"key" for a key limited to these inboxes.','auth'); const ids=[...new Set(q.inboxes)],key=randomSecret(secretPrefixes.addressKey),kid=id('mbk'); diff --git a/api/src/inbox-folders.ts b/api/src/inbox-folders.ts index 08c85a6c7..b98bee230 100644 --- a/api/src/inbox-folders.ts +++ b/api/src/inbox-folders.ts @@ -39,7 +39,7 @@ export function registerInboxFolders(app:App,access:(c:Ctx,p?:MailboxPermission) return unwrap(rows[0]?.r); }; const folder=z.object({id:Role,role:Special.nullable(),path:z.string(),subscribed:z.boolean(),uidValidity:uid,uidNext:z.number(),highestModseq:z.string(),total:z.number(),unseen:z.number()}); - app.openapi(createRoute({...meta,method:'get',path:`${base}/folders`,operationId:'listInboxFolders',summary:'List folders, stable UID namespaces and counts',request:{params:box},responses:{200:response(z.object({data:z.array(folder.extend({role:LegacyRole})),additionalFolders:z.array(folder).describe('Drafts and custom folders, outside the original five-role contract.'),state:z.string()})),...errors}}),async c=>{ + app.openapi(createRoute({...meta,method:'get',path:`${base}/folders`,operationId:'listInboxFolders',summary:'List inbox folders',description:'List folders, stable UID namespaces and counts.',request:{params:box},responses:{200:response(z.object({data:z.array(folder.extend({role:LegacyRole})),additionalFolders:z.array(folder).describe('Drafts and custom folders, outside the original five-role contract.'),state:z.string()})),...errors}}),async c=>{ const v=access(c,'read'),{id}=c.req.valid('param'); const {rows}=await c.env.db.execute<{r:{data:z.infer[];state:string}}>(sql`SELECT jsonb_build_object('state',s.modseq::text,'data',(SELECT jsonb_agg(jsonb_build_object('id',role,'role',CASE WHEN custom_path IS NULL THEN role END,'path',inbox_folder_path(f),'subscribed',subscribed,'uidValidity',uid_validity,'uidNext',uid_next,'highestModseq',highest_modseq::text,'total',total,'unseen',unseen) ORDER BY role) FROM inbox_folders f WHERE inbox_id=b.id)) r FROM mailboxes b JOIN inbox_state s ON s.inbox_id=b.id WHERE ${inboxVisible(v)} AND b.id=${id}`); const {state,data}=unwrap(rows[0]?.r); @@ -52,27 +52,27 @@ export function registerInboxFolders(app:App,access:(c:Ctx,p?:MailboxPermission) if(r.error)throw new ApiError(r.error==='NOT_FOUND'?404:409,r.error,'Folder operation refused.');return r; }; app.openapi(createRoute({...meta,method:'post',path:`${base}/folders`,operationId:'createInboxFolder',summary:'Create a custom folder',request:{params:box,body:json(z.object({path}).strict())},responses:{201:response(edited),...errors}}),async c=>c.json(await edit(c,c.req.valid('param').id,'create',null,c.req.valid('json').path,null),201)); - app.openapi(createRoute({...meta,method:'patch',path:`${base}/folders/{folder}`,operationId:'updateInboxFolder',summary:'Rename a folder tree or change its subscription',request:{params:fp,body:json(z.union([z.object({path}).strict(),z.object({subscribed:z.boolean()}).strict()]))},responses:{200:response(edited),...errors}}),async c=>{const {id,folder}=c.req.valid('param'),q=c.req.valid('json');return c.json('path'in q?await edit(c,id,'rename',folder,q.path,null):await edit(c,id,'subscribe',folder,null,q.subscribed),200)}); - app.openapi(createRoute({...meta,method:'delete',path:`${base}/folders/{folder}`,operationId:'deleteInboxFolder',summary:'Remove a custom folder; preserve otherwise orphaned mail in Trash',request:{params:fp},responses:{200:response(edited),...errors}}),async c=>{const {id,folder}=c.req.valid('param');return c.json(await edit(c,id,'delete',folder,null,null),200)}); - app.openapi(createRoute({...meta,method:'patch',path:detail,operationId:'updateInboxMessage',summary:'Set read state or flags; deleted applies to one folder entry',request:{params,body:json(patch)},responses:{200:response(result),...errors}}),async c=>{ + app.openapi(createRoute({...meta,method:'patch',path:`${base}/folders/{folder}`,operationId:'updateInboxFolder',summary:'Update an inbox folder',description:'Rename a folder tree or change its subscription.',request:{params:fp,body:json(z.union([z.object({path}).strict(),z.object({subscribed:z.boolean()}).strict()]))},responses:{200:response(edited),...errors}}),async c=>{const {id,folder}=c.req.valid('param'),q=c.req.valid('json');return c.json('path'in q?await edit(c,id,'rename',folder,q.path,null):await edit(c,id,'subscribe',folder,null,q.subscribed),200)}); + app.openapi(createRoute({...meta,method:'delete',path:`${base}/folders/{folder}`,operationId:'deleteInboxFolder',summary:'Delete an inbox folder',description:'Remove a custom folder; preserve otherwise orphaned mail in Trash.',request:{params:fp},responses:{200:response(edited),...errors}}),async c=>{const {id,folder}=c.req.valid('param');return c.json(await edit(c,id,'delete',folder,null,null),200)}); + app.openapi(createRoute({...meta,method:'patch',path:detail,operationId:'updateInboxMessage',summary:'Update an inbox message',description:'Set read state or flags; deleted applies to one folder entry.',request:{params,body:json(patch)},responses:{200:response(result),...errors}}),async c=>{ const {id,messageId}=c.req.valid('param');return c.json(await mutate(c,id,messageId,'flags',c.req.valid('json')),200); }); for(const op of ['move','copy'] as const){ - app.openapi(createRoute({...meta,method:'post',path:`${detail}/${op}`,operationId:op==='move'?'moveInboxMessage':'copyInboxMessage',summary:op==='move'?'Move one entry and allocate a new destination UID':'Copy one entry with a fresh destination UID',request:{params,body:json(transfer)},responses:{200:response(result),...errors}}),async c=>{ + app.openapi(createRoute({...meta,method:'post',path:`${detail}/${op}`,operationId:op==='move'?'moveInboxMessage':'copyInboxMessage',summary:op==='move'?'Move an inbox message':'Copy an inbox message',description:op==='move'?'Move one entry and allocate a new destination UID.':'Copy one entry with a fresh destination UID.',request:{params,body:json(transfer)},responses:{200:response(result),...errors}}),async c=>{ const {id,messageId}=c.req.valid('param');return c.json(await mutate(c,id,messageId,op,c.req.valid('json')),200); }); } - app.openapi(createRoute({...meta,method:'delete',path:detail,operationId:'deleteInboxMessage',summary:'Move one entry to Trash, or expunge it permanently',request:{params,query:z.object({source:Role.optional(),uid:z.coerce.number().int().min(1).max(4294967295).optional(),permanent:z.enum(['true','false']).default('false'),ifModseq:seq.optional()})},responses:{200:response(result),...errors}}),async c=>{ + app.openapi(createRoute({...meta,method:'delete',path:detail,operationId:'deleteInboxMessage',summary:'Delete an inbox message',description:'Move one entry to Trash, or expunge it permanently.',request:{params,query:z.object({source:Role.optional(),uid:z.coerce.number().int().min(1).max(4294967295).optional(),permanent:z.enum(['true','false']).default('false'),ifModseq:seq.optional()})},responses:{200:response(result),...errors}}),async c=>{ const {id,messageId}=c.req.valid('param'),q=c.req.valid('query');return c.json(await mutate(c,id,messageId,q.permanent==='true'?'expunge':'move',{...q,folder:'trash'}),200); }); const expunged=z.object({expunged:z.number(),hasMore:z.boolean()}); - app.openapi(createRoute({...meta,method:'post',path:`${base}/folders/{folder}/expunge`,operationId:'expungeInboxFolder',summary:'Remove entries marked deleted; repeat while hasMore is true',request:{params:box.extend({folder:Role}),body:json(z.object({uids:z.array(uid).min(1).max(500).optional()}).strict())},responses:{200:response(expunged),...errors}}),async c=>{ + app.openapi(createRoute({...meta,method:'post',path:`${base}/folders/{folder}/expunge`,operationId:'expungeInboxFolder',summary:'Expunge an inbox folder',description:'Remove entries marked deleted; repeat while hasMore is true.',request:{params:box.extend({folder:Role}),body:json(z.object({uids:z.array(uid).min(1).max(500).optional()}).strict())},responses:{200:response(expunged),...errors}}),async c=>{ const v=access(c,'modify'),{id,folder}=c.req.valid('param'),{uids}=c.req.valid('json'); const {rows}=await c.env.db.execute<{r:z.infer}>(sql`SELECT inbox_expunge_folder(b.workspace_id,b.id,${folder},${sql.param(uids??null)}::bigint[]) r FROM mailboxes b WHERE ${inboxVisible(v)} AND b.id=${id}`); return c.json(unwrap(rows[0]?.r),200); }); const changes=z.object({changed:z.array(key),removed:z.array(key),state:seq,hasMore:z.boolean()}); - app.openapi(createRoute({...meta,method:'get',path:`${base}/changes`,operationId:'getInboxChanges',summary:'Sync changed and removed message IDs since an inbox MODSEQ',request:{params:box,query:z.object({since:seq})},responses:{200:response(changes),...errors}}),async c=>{ + app.openapi(createRoute({...meta,method:'get',path:`${base}/changes`,operationId:'getInboxChanges',summary:'Read an inbox’s changes',description:'Sync changed and removed message IDs since an inbox MODSEQ.',request:{params:box,query:z.object({since:seq})},responses:{200:response(changes),...errors}}),async c=>{ const v=access(c,'read'),{id}=c.req.valid('param'),{since}=c.req.valid('query'); const {rows}=await c.env.db.execute<{r:z.infer;future:boolean}>(sql`SELECT (s.modseq<${since}::bigint OR s.changes_floor>${since}::bigint) future,page.r FROM mailboxes b JOIN inbox_state s ON s.inbox_id=b.id CROSS JOIN LATERAL ( WITH touched AS (SELECT * FROM (SELECT modseq,message_id FROM mailbox_messages WHERE mailbox_id=b.id AND modseq>${since}::bigint ORDER BY modseq LIMIT 501) live UNION SELECT * FROM (SELECT modseq,message_id FROM inbox_vanished WHERE inbox_id=b.id AND modseq>${since}::bigint ORDER BY modseq LIMIT 501) gone), diff --git a/api/src/inbox-passwords.ts b/api/src/inbox-passwords.ts index 73bcde40c..b2eab3b53 100644 --- a/api/src/inbox-passwords.ts +++ b/api/src/inbox-passwords.ts @@ -33,8 +33,8 @@ export function registerInboxPasswords(app: App, access: (c: Ctx) => MailboxAcce method: 'post', path: base, operationId: 'createInboxAppPassword', - summary: - 'Grant mail client access to a persistent inbox. Password shown once; a billable day starts immediately.', + summary: 'Create an inbox app password', + description: 'Password shown once; a billable day starts immediately. Grant mail client access to a persistent inbox.', request: { params, body: json( @@ -82,7 +82,8 @@ export function registerInboxPasswords(app: App, access: (c: Ctx) => MailboxAcce method: 'get', path: base, operationId: 'listInboxAppPasswords', - summary: 'List active app passwords without their secrets', + summary: 'List an inbox’s app passwords', + description: 'List active app passwords without their secrets.', request: { params }, responses: { 200: response(z.object({ data: z.array(item) })), ...errors }, }), @@ -103,7 +104,8 @@ export function registerInboxPasswords(app: App, access: (c: Ctx) => MailboxAcce method: 'get', path: '/v1/app-passwords', operationId: 'listAppPasswords', - summary: 'List the active app passwords of every inbox, without their secrets', + summary: 'List every inbox’s app passwords', + description: 'List the active app passwords of every inbox, without their secrets.', responses: { 200: response(z.object({ data: z.array(item.extend({ inboxId: z.string(), inboxAddress: z.string() })) }).openapi('AppPasswordList')), ...errors }, }), async (c) => { @@ -122,7 +124,8 @@ export function registerInboxPasswords(app: App, access: (c: Ctx) => MailboxAcce method: 'delete', path: base + '/{passwordId}', operationId: 'revokeInboxAppPassword', - summary: 'Revoke a mail client password and invalidate sessions', + summary: 'Revoke an inbox app password', + description: 'Revoke a mail client password and invalidate sessions.', request: { params: params.extend({ passwordId: z.string().min(1).max(120) }) }, responses: { 200: response(z.object({ revoked: z.boolean() })), ...errors }, }), diff --git a/api/src/mailbox.ts b/api/src/mailbox.ts index 47de6c84a..7df43985a 100644 --- a/api/src/mailbox.ts +++ b/api/src/mailbox.ts @@ -632,7 +632,7 @@ export function registerMailbox(app: App) { registerInboxes(app, access); registerMailObjects(app); registerMailGateway(app); - app.openapi(createRoute({method:'delete',path:'/v1/inbound/retired/{address}',operationId:'releaseRetiredAddress',tags:['Inbound addresses'],security,summary:'Release a retired address for reuse (workspace admin)',request:{params:z.object({address:z.email().max(254)})},responses:{200:response(Ok),...errors}}),async c=>{ + app.openapi(createRoute({method:'delete',path:'/v1/inbound/retired/{address}',operationId:'releaseRetiredAddress',tags:['Inbound addresses'],security,summary:'Release a retired address',description:'Release a retired address for reuse (workspace admin).',request:{params:z.object({address:z.email().max(254)})},responses:{200:response(Ok),...errors}}),async c=>{ const v=admin(c);await c.env.db.execute(sql`WITH released AS (DELETE FROM mail_retired_addresses WHERE workspace_id=${v.workspaceId} AND address=${c.req.valid('param').address.toLowerCase()} RETURNING address), audit AS (${auditInsert(auditContext(c),{action:'address.release',workspaceId:v.workspaceId,target:{type:'address',id:sql`released.address`},before:sql`jsonb_build_object('address',released.address)`},{from:sql`released`})}) SELECT 1`);return c.json({ok:true as const},200); }); @@ -733,7 +733,7 @@ export function registerMailbox(app: App) { registerInboundThreadReads(app, access); registerLogs(app, actorMailAccess); registerInboundOverview(app, { access, mailboxView, InboundAddressSchema, InboundDomainStatus, InboundCatchAll, security }); - app.openapi(createRoute({method:'patch',path:'/v1/inbound/threads/{threadId}',operationId:'updateInboundThread',tags:['Inbound threads'],security,summary:'Mark a conversation read, star, archive or label it for one address',request:{params:z.object({threadId:z.string().min(1).max(120)}),body:json(UpdateInboundThread)},responses:{200:response(AddressState),...errors}}),async c=>{ + app.openapi(createRoute({method:'patch',path:'/v1/inbound/threads/{threadId}',operationId:'updateInboundThread',tags:['Inbound threads'],security,summary:'Update a conversation',description:'Mark a conversation read, star, archive or label it for one address.',request:{params:z.object({threadId:z.string().min(1).max(120)}),body:json(UpdateInboundThread)},responses:{200:response(AddressState),...errors}}),async c=>{ const v=access(c,'modify'),{threadId}=c.req.valid('param'),{addressId,...changes}=c.req.valid('json'); const options=await c.env.db.select({id:mailboxThreads.mailboxId}).from(mailboxThreads).where(visibleThreadAddresses(v,threadId,addressId)).limit(2); if (!options.length) throw new ApiError(404,'NOT_FOUND','Thread was not found.'); @@ -775,7 +775,7 @@ export function registerMailbox(app: App) { return rows.length ? { data: rows.map(eventView), cursor: String(rows.at(-1)!.seq) } : { data: [], cursor: String(after) }; } const InboundEventQuery = EventQuery.extend({ addressId: z.string().min(1).max(120).optional().describe('Include only this receiving address.'), addressIds: z.string().max(4000).optional().describe('Comma-separated receiving address IDs. Use instead of addressId.') }).strict().refine(q => q.addressId === undefined || q.addressIds === undefined, { path: ['addressIds'], message: 'Supply addressId or addressIds, not both.' }); - app.openapi(createRoute({ method: 'get', path: '/v1/inbound/events', operationId: 'listInboundEvents', security, tags: ['Inbound events'], summary: 'Poll events for the receiving addresses this key can read', description: 'Use the returned cursor as after to continue polling. Workspace-wide message.stored events require admin access, no address filter, and an explicit message.stored type filter.', request: { query: InboundEventQuery }, responses: { 200: response(z.object({ data: z.array(InboundEventSchema), cursor: z.string().describe('Pass as after on the next call.') }).openapi('InboundEventPage')), ...errors } }), async c => { + app.openapi(createRoute({ method: 'get', path: '/v1/inbound/events', operationId: 'listInboundEvents', security, tags: ['Inbound events'], summary: 'List inbound events', description: 'Poll events for the receiving addresses this key can read. Use the returned cursor as after to continue polling. Workspace-wide message.stored events require admin access, no address filter, and an explicit message.stored type filter.', request: { query: InboundEventQuery }, responses: { 200: response(z.object({ data: z.array(InboundEventSchema), cursor: z.string().describe('Pass as after on the next call.') }).openapi('InboundEventPage')), ...errors } }), async c => { const q = c.req.valid('query'); return c.json(await poll(c, q.addressId ? [q.addressId] : parseEventIds(q.addressIds), q), 200); }); diff --git a/api/src/mcp-auth.ts b/api/src/mcp-auth.ts index db3924e00..c4220f4a6 100644 --- a/api/src/mcp-auth.ts +++ b/api/src/mcp-auth.ts @@ -88,8 +88,8 @@ export function registerMcpAuth(app:App) { tokens:z.array(AgentTokenRecord).describe('Short-lived agent tokens it made in this workspace, newest first (at most 20). Revoking the agent revokes them.')}).openapi('Agent'); const time=(value:string|null)=>value?new Date(value).toISOString():null; app.openapi(createRoute({method:'get',path:'/v1/agents',operationId:'listAgents',tags:['Auth'],security, - summary:'List connected agents and their agent tokens', - description:`Agent tokens are how agents use ${productName}: an agent signs in over MCP as you, and can make short-lived tokens for scripts (createAgentToken). Each connected agent is listed once with its access, last use and the tokens it made in this workspace. Owners and admins also see other members' agents that made tokens here. Dashboard session only.`, + summary:'List agents', + description:`List connected agents and their agent tokens. Agent tokens are how agents use ${productName}: an agent signs in over MCP as you, and can make short-lived tokens for scripts (createAgentToken). Each connected agent is listed once with its access, last use and the tokens it made in this workspace. Owners and admins also see other members' agents that made tokens here. Dashboard session only.`, request:{query:z.object({includeInactive:z.enum(['true','false']).default('false').describe('Also list revoked and expired sign-ins and tokens.')})},responses:{200:response(z.object({data:z.array(Agent)}).openapi('AgentList')),...errors}}),async c=>{ const user=owner(c),a=c.get('actor'),w=a.workspaceId,all=c.req.valid('query').includeInactive==='true'; const admin=a.role==='owner'||a.role==='admin',live=all?sql``:sql`AND t.revoked_at IS NULL AND t.expires_at>now()`; @@ -112,7 +112,7 @@ export function registerMcpAuth(app:App) { tokens:r.tokens.map(t=>({id:t.id,grantId:t.grant_id,permissions:t.permissions,domains:t.domains,purpose:t.purpose,expiresAt:time(t.expires_at)!,createdAt:time(t.created_at)!,lastUsedAt:time(t.last_used_at),revokedAt:time(t.revoked_at)}))}))},200); }); app.openapi(createRoute({method:'post',path:'/v1/agents/{id}/revoke',operationId:'revokeAgent',tags:['Auth'],security, - summary:'Revoke a connected agent and its agent tokens', + summary:'Revoke an agent', description:'Your own agent: its sign-in, every agent token it made and everything it created stop working at once (it can sign in again as a new connection). Another member\'s agent (owners and admins): the agent tokens it made in this workspace are revoked; the sign-in belongs to that person. Dashboard session only.', request:{params:IdParams},responses:{200:response(z.object({id:z.string(),revoked:z.literal(true),scope:z.enum(['agent','tokens']).describe('agent: the sign-in and everything it made. tokens: its agent tokens in this workspace.')})),...errors}}),async c=>{ const user=owner(c),a=c.get('actor'),{id}=c.req.valid('param'); diff --git a/api/src/mcp-catalog.ts b/api/src/mcp-catalog.ts index fbab6bb44..fcbadb2ef 100644 --- a/api/src/mcp-catalog.ts +++ b/api/src/mcp-catalog.ts @@ -293,10 +293,12 @@ const PATH_IDS: Record = { function descriptionFor(name: string, operation: ObjectValue): string { if (DESCRIPTIONS[name]) return DESCRIPTIONS[name]; const summary = operation.summary ?? name.replace(/([a-z])([A-Z])/g, '$1 $2').replace(/^./, (c: string) => c.toUpperCase()); - let text = summary.replace(/\.?$/, '.'); - if (EMAIL_SEND_TOOLS.has(name)) return `${text} Confirm the recipients or audience, content and time before sending. Use campaigns for shared outreach to more than 50 people.`; - for (const sentence of (operation.description ?? '').split(/(?<=\.)\s+/)) { - if (!sentence || text.length + sentence.length >= 400) break; + if (EMAIL_SEND_TOOLS.has(name)) return `${summary.replace(/\.?$/, '.')} Confirm the recipients or audience, content and time before sending. Use campaigns for shared outreach to more than 50 people.`; + const sentences = (operation.description ?? '').split(/(?<=\.)\s+/).filter(Boolean); + // A summary is a name (scripts/check-premerge.ts). A description that opens with the same words says them once. + let text = sentences[0]?.startsWith(summary) ? sentences.shift()! : summary.replace(/\.?$/, '.'); + for (const sentence of sentences) { + if (text.length + sentence.length >= 400) break; text += ` ${sentence}`; } return text; diff --git a/api/src/overview-setup.ts b/api/src/overview-setup.ts index 674d727e0..060188e7c 100644 --- a/api/src/overview-setup.ts +++ b/api/src/overview-setup.ts @@ -44,8 +44,8 @@ const LAUNCHED = sql`('preparing','scheduled','sending','paused','done')`; export function registerOverviewSetup(app: App) { app.openapi(createRoute({ method: 'get', path: '/v1/overview/setup', operationId: 'getOverviewSetup', tags: ['Settings'], security, - summary: 'What this workspace has set up, in one read', - description: 'The newest domains, the number of active API keys, outbound webhooks and pending invitations, whether any email exists, each focus\'s first steps and whether an agent is connected. Each part follows the permission rules of its own list operation and is null where that operation would refuse the caller. Counts only: no webhook URL, key, address or subject.', + summary: 'Read the workspace setup', + description: 'What this workspace has set up, in one read. The newest domains, the number of active API keys, outbound webhooks and pending invitations, whether any email exists, each focus\'s first steps and whether an agent is connected. Each part follows the permission rules of its own list operation and is null where that operation would refuse the caller. Counts only: no webhook URL, key, address or subject.', responses: { 200: response(Setup), ...errors } }), async c => { const a = actor(c), w = a.workspaceId; const readable = (path: string, guard: () => unknown) => !memberRefused(a, 'GET', path) && admits(guard); diff --git a/api/src/ritual-version.ts b/api/src/ritual-version.ts index 99c1d022d..b0570593b 100644 --- a/api/src/ritual-version.ts +++ b/api/src/ritual-version.ts @@ -60,8 +60,8 @@ export async function credentialName(db: DbExecutor, a: Actor) { } export function registerRitualVersion(app: App) { - const summary = 'Read the rules and routes version, or wait for it to change'; - const description = 'Without after, returns the current version at once. With after (and endpoints, to include endpoint changes), waits up to wait seconds for a rule, route or endpoint save and returns as soon as one commits, with who saved it. The dashboard keeps one of these open while you edit rules so an agent’s saves appear live. Each waited 2.5 seconds counts as one request against the credential’s per-minute budget.'; + const summary = 'Read or wait for the rules version'; + const description = 'Read the rules and routes version, or wait for it to change. Without after, returns the current version at once. With after (and endpoints, to include endpoint changes), waits up to wait seconds for a rule, route or endpoint save and returns as soon as one commits, with who saved it. The dashboard keeps one of these open while you edit rules so an agent’s saves appear live. Each waited 2.5 seconds counts as one request against the credential’s per-minute budget.'; app.openapi(createRoute({ method: 'get', path: '/v1/rules/version', operationId: 'getRuleVersion', security, tags: ['Rules'], summary, description, request: { query: Query }, diff --git a/api/src/rituals.ts b/api/src/rituals.ts index 5635778cf..d9ebec23b 100644 --- a/api/src/rituals.ts +++ b/api/src/rituals.ts @@ -255,9 +255,9 @@ async function edit(c: Ctx, change: (config: Config, tx: DbExecutor) => Config | } export function registerRituals(app: App) { rule(app, {...meta,method:'get',path:path+'/history',operationId:'listRuleVersions',summary:'List saved rule versions, newest first',request:{query:z.object({cursor:z.coerce.number().int().positive().optional(),limit:z.coerce.number().int().min(1).max(100).default(25)})},responses:{200:response(z.object({data:z.array(z.object({version:z.number(),actor:z.string()})),nextCursor:z.number().nullable()})),...errors}},async c=>{const w=receivingAdmin(c).workspaceId,q=c.req.valid('query' as never) as {cursor?:number;limit:number},rows=(await c.env.db.execute<{version:number;actor:string}>(sql`SELECT version,actor FROM mail_ritual_versions WHERE workspace_id=${w} AND version<${Math.min(q.cursor??2147483647,2147483647)} ORDER BY version DESC LIMIT ${q.limit+1}`)).rows;return c.json({data:rows.slice(0,q.limit),nextCursor:rows.length>q.limit?rows[q.limit-1].version:null},200)}); - rule(app, {...meta,method:'post',path:path+'/restore',operationId:'restoreRuleVersion',summary:'Recompile a retained version and restore it as a new version',request:{headers:versionHeader,body:json(z.object({version:z.number().int().positive()}))},responses:ok},async c=>{const w=receivingAdmin(c, 'change rules').workspaceId,v=(c.req.valid('json' as never) as {version:number}).version,row=v>2147483647?undefined:(await c.env.db.execute<{config:Config}>(sql`SELECT config FROM mail_ritual_versions WHERE workspace_id=${w} AND version=${v}`)).rows[0];if(!row)throw new ApiError(404,'NOT_FOUND','Version no longer retained.');return c.json(stateOf(await edit(c,()=>row.config,{action:'ritual.restore',after:x=>({restoredVersion:v,...counts(x)})})),200)}); + rule(app, {...meta,method:'post',path:path+'/restore',operationId:'restoreRuleVersion',summary:'Restore a rules version',description:'Recompile a retained version and restore it as a new version.',request:{headers:versionHeader,body:json(z.object({version:z.number().int().positive()}))},responses:ok},async c=>{const w=receivingAdmin(c, 'change rules').workspaceId,v=(c.req.valid('json' as never) as {version:number}).version,row=v>2147483647?undefined:(await c.env.db.execute<{config:Config}>(sql`SELECT config FROM mail_ritual_versions WHERE workspace_id=${w} AND version=${v}`)).rows[0];if(!row)throw new ApiError(404,'NOT_FOUND','Version no longer retained.');return c.json(stateOf(await edit(c,()=>row.config,{action:'ritual.restore',after:x=>({restoredVersion:v,...counts(x)})})),200)}); const evalSettings=RitualConfig.pick({evaluateDomains:true,evaluateRoutes:true}); - rule(app, {...meta,method:'put',path:path+'/decisions',operationId:'setDecisionOptIns',summary:'Set the domains and routes whose mail the AI may read for decisions',request:{headers:versionHeader,body:json(evalSettings)},responses:ok},async c=>c.json(stateOf(await edit(c,x=>({...x,...(c.req.valid('json' as never) as z.infer)}),{action:'ritual.omens',after:x=>({evaluateDomains:x.evaluateDomains,evaluateRoutes:x.evaluateRoutes})})),200)); + rule(app, {...meta,method:'put',path:path+'/decisions',operationId:'setDecisionOptIns',summary:'Set the AI decision opt-ins',description:'Set the domains and routes whose mail the AI may read for decisions.',request:{headers:versionHeader,body:json(evalSettings)},responses:ok},async c=>c.json(stateOf(await edit(c,x=>({...x,...(c.req.valid('json' as never) as z.infer)}),{action:'ritual.omens',after:x=>({evaluateDomains:x.evaluateDomains,evaluateRoutes:x.evaluateRoutes})})),200)); registerEndpoints(app); registerInboxConnection(app); registerRitualVersion(app); @@ -265,8 +265,8 @@ export function registerRituals(app: App) { const check = z.object({ ok: z.boolean(), diagnostics: z.array(diagnostic), calls: z.array(z.string()).describe('Endpoints and inboxes the rule calls.'), decisions: z.array(z.string()).describe('The names of the AI decisions it asks for.'), questions: z.record(z.string(), z.string()).describe('Decision name → its question. testRules takes scores keyed by question.'), lists: z.array(z.string()) }).openapi('RuleCheck'); rule(app, { ...meta, method: 'post', path: path + '/check', operationId: 'checkRule', - summary: 'Compile one rule source against this workspace without saving', - description: 'Returns every problem with its line, column and a hint, and what the rule calls. Use it while editing; nothing is saved, delivered or sent to the AI.', + summary: 'Check a rule without saving it', + description: 'Compile one rule source against this workspace without saving. Returns every problem with its line, column and a hint, and what the rule calls. Use it while editing; nothing is saved, delivered or sent to the AI.', request: { body: json(z.object({ source: z.string().max(65536), key: z.string().regex(/^[a-z0-9][a-z0-9-]{0,62}$/).default('draft'), senderLists: RitualConfig.shape.senderLists.optional().describe('Lists to check against. Defaults to the saved sender lists.') }).strict()) }, responses: { 200: response(check), ...errors }, }, async c => { @@ -291,8 +291,8 @@ export function registerRituals(app: App) { const typings = z.object({ typescript: z.string(), completions: z.array(z.object({ label: z.string(), type: z.enum(['function', 'property', 'variable', 'keyword']), detail: z.string(), info: z.string(), apply: z.string().optional() })), endpoints: z.array(z.object({ name: z.string(), type: z.enum(['slack', 'discord', 'webhook', 'forward']), status: z.string() })), inboxes: z.array(z.string()), lists: z.array(z.string()) }); rule(app, { ...meta, method: 'get', path: path + '/typings', operationId: 'getRuleTypings', - summary: 'TypeScript declarations and editor completions for this workspace', - description: 'Generated from the workspace’s endpoints, inbox keys and sender lists. Load typescript into an editor as a .d.ts, or read it to learn exactly what a rule can call.', + summary: 'Read the rules’ TypeScript declarations', + description: 'TypeScript declarations and editor completions for this workspace. Generated from the workspace’s endpoints, inbox keys and sender lists. Load typescript into an editor as a .d.ts, or read it to learn exactly what a rule can call.', responses: { 200: response(typings.openapi('RuleTypings')), ...errors }, }, async c => { const symbols = await workspaceSymbols(c); @@ -302,8 +302,8 @@ export function registerRituals(app: App) { const templates = z.object({ data: z.array(z.object({ id: z.string(), name: z.string(), description: z.string(), needs: z.enum(['slack', 'discord', 'webhook', 'forward']).nullable(), endpoint: z.string().nullable(), source: z.string() })) }); rule(app, { ...meta, method: 'get', path: path + '/templates', operationId: 'listRuleTemplates', - summary: 'Starting points for common rules, filled in with this workspace’s endpoints', - description: 'Each template compiles. An endpoint template uses the first endpoint of the type it needs; endpoint is null when there is none yet, and source then uses a placeholder name to replace.', + summary: 'List rule templates', + description: 'Starting points for common rules, filled in with this workspace’s endpoints. Each template compiles. An endpoint template uses the first endpoint of the type it needs; endpoint is null when there is none yet, and source then uses a placeholder name to replace.', responses: { 200: response(templates.openapi('RuleTemplates')), ...errors }, }, async c => { const { endpoints } = await workspaceSymbols(c); @@ -319,7 +319,8 @@ export function registerRituals(app: App) { rule(app, {...meta,method:'delete',path:item,operationId:'deleteRule',summary:'Remove a rule and detach it everywhere',request:{params,headers:versionHeader},responses:ok},async c=>{const {key}=c.req.valid('param' as never) as {key:string};return c.json(stateOf(await edit(c,s=>({...s,rituals:s.rituals.filter(h=>h.key!==key),attachments:s.attachments.filter(h=>h.ritual!==key)}),{action:'ritual.delete',target:{type:'ritual',id:key},after:()=>({key})})),200)}); rule(app, { ...meta, method: 'put', path: path + '/attachments', operationId: 'attachRules', - summary: 'Attach, reorder and detach rules by replacing the ordered attachment list', + summary: 'Attach rules', + description: 'Attach, reorder and detach rules by replacing the ordered attachment list.', request: { headers: versionHeader, body: json(z.object({ attachments: z.array(RuleBindingInput).max(256) })) }, responses: ok, }, async c => { @@ -328,7 +329,8 @@ export function registerRituals(app: App) { }); rule(app, { ...meta, method: 'get', path, operationId: 'getRules', - summary: 'Read rules, ordered attachments, and sender lists', + summary: 'Read rules', + description: 'Read rules, ordered attachments, and sender lists.', request: { query: z.object({ version: z.coerce.number().int().positive().optional() }) }, responses: ok, }, async c => { @@ -343,7 +345,8 @@ export function registerRituals(app: App) { }); rule(app, { ...meta, method: 'put', path, operationId: 'applyRules', - summary: 'Create, replace or remove rules and ordered attachments in one version', + summary: 'Apply rules', + description: 'Create, replace or remove rules and ordered attachments in one version.', request: { headers: versionHeader, body: json(RuleConfigInput) }, responses: ok, }, async c => c.json(stateOf(await edit(c, () => configFrom(c.req.valid('json' as never)), { action: 'ritual.apply', after: counts })), 200)); @@ -359,7 +362,8 @@ export function registerRituals(app: App) { const tested = z.object({ version: z.number(), recipients: z.array(z.record(z.string(), z.unknown())), trace: z.array(TraceRow), steps: z.number() }); rule(app, { ...meta, method: 'post', path: path + '/test', operationId: 'testRules', - summary: 'Trace saved or proposed rules on a stored message or pasted MIME; never asks the AI or delivers mail', + summary: 'Test rules on a message', + description: 'Trace saved or proposed rules on a stored message or pasted MIME; never asks the AI or delivers mail.', request: { body: json(dry) }, responses: { 200: response(tested), ...errors }, }, async c => { @@ -520,8 +524,8 @@ export async function apply(config: Config, tx: DbExecutor, w: string, key: stri function registerRecipes(app: App, item: string, keyParams: z.ZodObject<{ key: z.ZodString }>) { rule(app, { ...meta, method: 'get', path: path + '/recipes', operationId: 'listRuleRecipes', - summary: 'Ready-made rules and the fields each one takes', - description: 'Each recipe writes an ordinary rule from one or two fields. Create one with createRuleFromRecipe; endpoint fields name an endpoint of the right type, created first with createEndpoint.', + summary: 'List rule recipes', + description: 'Ready-made rules and the fields each one takes. Each recipe writes an ordinary rule from one or two fields. Create one with createRuleFromRecipe; endpoint fields name an endpoint of the right type, created first with createEndpoint.', responses: { 200: response(recipeCatalog), ...errors }, }, async c => { receivingAdmin(c); @@ -535,7 +539,7 @@ function registerRecipes(app: App, item: string, keyParams: z.ZodObject<{ key: z const created = state.extend({ key: z.string().describe('The new rule’s key.') }); rule(app, { ...meta, method: 'post', path: path + '/recipes', operationId: 'createRuleFromRecipe', - summary: 'Create a rule from a recipe and attach it to addresses', + summary: 'Create a rule from a recipe', description: 'Writes the recipe’s script, saves it as a new rule (key from the recipe and address unless given) and attaches it to each address, after their other recipes and before their own scripts. An AI recipe lets the AI read mail at those addresses’ domains. Returns the new version and key. Besides listRuleRecipes, it takes the two-way rules the dashboard builds: split ({ test: always, from, subject, text or attachment; value: words, or senders for from; then; otherwise }) and split-by-meaning ({ meaning, then, otherwise }), where then and otherwise are inbox:, an endpoint name, store or drop. Give the address the route [] (createRoute) so each side gets exactly its destination.', request: { headers: versionHeader, body: json(z.object({ recipe: z.string().max(40), params: RecipeInputParams, addresses: RecipeAddresses, key: z.string().regex(/^[a-z0-9][a-z0-9-]{0,62}$/).optional(), enabled: z.boolean().optional() }).strict()) }, responses: { 201: response(created), ...errors }, @@ -552,7 +556,7 @@ function registerRecipes(app: App, item: string, keyParams: z.ZodObject<{ key: z }); rule(app, { ...meta, method: 'put', path: item + '/recipe', operationId: 'updateRuleFromRecipe', - summary: 'Change a rule’s recipe fields and addresses', + summary: 'Update a rule from its recipe', description: 'Rewrites the rule from its recipe with these fields. addresses, when given, replaces where it runs (kept addresses keep their place). Passing recipe turns a script into that recipe.', request: { params: keyParams, headers: versionHeader, body: json(z.object({ recipe: z.string().max(40).optional(), params: RecipeInputParams, addresses: RecipeAddresses.optional(), enabled: z.boolean().optional() }).strict()) }, responses: ok, diff --git a/docs/ci.md b/docs/ci.md index eb2506aa0..1ccd4a6d6 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -122,6 +122,12 @@ Every operation states what it needs: `x-nightmail-permission` in `api/openapi.j **Fix:** add or update the row in the same change as the route or guard, run `bun run sdk` in `api/`, then run the `permission table` acceptance test. +### Operation summaries + +An operation's `summary` is its name: the docs page's title in the browser tab and in search results (` · Nightmail API docs`), the docs sidebar's entry and the SDK's comment, and an MCP tool's description leads with it. **Fails when** a summary has a full stop, colon or semicolon followed by more words, or makes a docs title longer than the 60 characters a search result shows (a summary of at most 39 characters). + +**Fix:** keep a short name ("Create an inbox app password") and move the sentence, word for word, to the start of the operation's `description`, a warning ("Password shown once") first. Then run `bun run sdk` in `api/`. + ### BYO role templates Connected AWS accounts run a published role template (`api/byo-templates/..yaml`, served from S3 as `byo/.yaml`), and Nightmail must keep working with every supported version. **Fails when** a published file was edited, renamed or deleted, a new file isn't named `..yaml`, or a new version isn't newer than the newest published one. diff --git a/sdk/src/sdk.gen.ts b/sdk/src/sdk.gen.ts index 2aa55d03a..ffe3971b5 100644 --- a/sdk/src/sdk.gen.ts +++ b/sdk/src/sdk.gen.ts @@ -44,9 +44,9 @@ export const bindMcpConnection = (options: }); /** - * List connected agents and their agent tokens + * List agents * - * Agent tokens are how agents use Nightmail: an agent signs in over MCP as you, and can make short-lived tokens for scripts (createAgentToken). Each connected agent is listed once with its access, last use and the tokens it made in this workspace. Owners and admins also see other members' agents that made tokens here. Dashboard session only. + * List connected agents and their agent tokens. Agent tokens are how agents use Nightmail: an agent signs in over MCP as you, and can make short-lived tokens for scripts (createAgentToken). Each connected agent is listed once with its access, last use and the tokens it made in this workspace. Owners and admins also see other members' agents that made tokens here. Dashboard session only. */ export const listAgents = (options?: Options): RequestResult => (options?.client ?? client).get({ security: [ @@ -67,7 +67,7 @@ export const listAgents = (options?: Optio }); /** - * Revoke a connected agent and its agent tokens + * Revoke an agent * * Your own agent: its sign-in, every agent token it made and everything it created stop working at once (it can sign in again as a new connection). Another member's agent (owners and admins): the agent tokens it made in this workspace are revoked; the sign-in belongs to that person. Dashboard session only. */ @@ -320,7 +320,7 @@ export const getAgentSetupToken = (options }); /** - * Exchange a setup token for the agent's API key + * Exchange a setup token for an API key * * For a coding agent: the setup token in the prompt a person copied from the dashboard (nm_setup_…) becomes a lasting API key for the agent, in that person's workspace, named after client_name. It works once, within 15 minutes of copying. A wrong token gets 400 SETUP_TOKEN_INVALID, a used one 409 SETUP_TOKEN_USED (naming the key it gave, in error.details, never the key again), and an expired or replaced one 410 SETUP_TOKEN_EXPIRED or SETUP_TOKEN_REPLACED with a device code in error.details[0] (startAgentDeviceAuthorization's answer) for the person who copied it to approve: show them its link and poll it. The key is shown once. */ @@ -334,7 +334,7 @@ export const exchangeAgentSetupToken = (op }); /** - * Start the device flow for a coding agent + * Start the device flow for an agent * * For a coding agent without a setup token (RFC 8628): returns a device code to keep and a user code to show. Show the person verification_uri_complete as a link on its own line and ask them to open it, sign in, check the code and approve; nextStep says so in words. Then poll pollAgentDeviceToken every interval seconds until it returns the key. Codes work once, for 15 minutes. With setup_token (one from the person's prompt that expired or was replaced before it was used), their dashboard shows you waiting. */ @@ -362,7 +362,7 @@ export const pollAgentDeviceToken = (optio }); /** - * Look up an agent waiting with a user code + * Look up an agent by user code * * The /connect page: the agent behind a user code, before you approve or deny it. Each attempt counts against 10 a minute per person. Dashboard session only. */ @@ -404,7 +404,7 @@ export const listWaitingAgentDevices = (op }); /** - * Approve an agent waiting with a user code + * Approve an agent by user code * * Gives the agent behind the user code its own API key in the workspace this request acts in (X-Nightmail-Workspace), which you must own or administer. It receives the key on its next poll. Dashboard session only. */ @@ -3373,7 +3373,9 @@ export const listRuleVersions = (options?: }); /** - * Recompile a retained version and restore it as a new version + * Restore a rules version + * + * Recompile a retained version and restore it as a new version. */ export const restoreRuleVersion = (options: Options): RequestResult => (options.client ?? client).post({ security: [ @@ -3398,7 +3400,9 @@ export const restoreRuleVersion = (options }); /** - * Set the domains and routes whose mail the AI may read for decisions + * Set the AI decision opt-ins + * + * Set the domains and routes whose mail the AI may read for decisions. */ export const setDecisionOptIns = (options: Options): RequestResult => (options.client ?? client).put({ security: [ @@ -3444,9 +3448,9 @@ export const listEndpoints = (options?: Op }); /** - * Create a named Slack, Discord, webhook or forward endpoint + * Create an endpoint * - * Slack and Discord URLs are credentials: stored encrypted, pinned to the provider host and never returned. A webhook endpoint is a route-only inbound webhook; its signing secret is returned once. A forward emails its recipient a single-use confirmation link (24 hours); it stays pending until they choose Allow. With preverify, an address on a domain this workspace has verified is ready at once. Once ready, a rule calls it as endpoints.() and a route forwards to it as forward:; either way the recipient gets each message whole: text, HTML and attachments. + * Create a named Slack, Discord, webhook or forward endpoint. Slack and Discord URLs are credentials: stored encrypted, pinned to the provider host and never returned. A webhook endpoint is a route-only inbound webhook; its signing secret is returned once. A forward emails its recipient a single-use confirmation link (24 hours); it stays pending until they choose Allow. With preverify, an address on a domain this workspace has verified is ready at once. Once ready, a rule calls it as endpoints.() and a route forwards to it as forward:; either way the recipient gets each message whole: text, HTML and attachments. */ export const createEndpoint = (options: Options): RequestResult => (options.client ?? client).post({ security: [ @@ -3471,7 +3475,9 @@ export const createEndpoint = (options: Op }); /** - * Delete an endpoint no rule or route uses + * Delete an endpoint + * + * Delete an endpoint no rule or route uses. */ export const deleteEndpoint = (options: Options): RequestResult => (options.client ?? client).delete({ security: [ @@ -3492,7 +3498,9 @@ export const deleteEndpoint = (options: Op }); /** - * Read one endpoint, its status and the next step + * Read an endpoint + * + * Read one endpoint, its status and the next step. */ export const getEndpoint = (options: Options): RequestResult => (options.client ?? client).get({ security: [ @@ -3513,9 +3521,9 @@ export const getEndpoint = (options: Optio }); /** - * Edit an endpoint: its name, type, URL, pause state, rate or retry policy + * Edit an endpoint * - * Send only what changes. URLs and headers are write-only: an omitted url keeps the current one, and none is ever returned. A forward’s address is fixed (its recipient confirmed it); create a new forward instead. + * Edit an endpoint: its name, type, URL, pause state, rate or retry policy. Send only what changes. URLs and headers are write-only: an omitted url keeps the current one, and none is ever returned. A forward’s address is fixed (its recipient confirmed it); create a new forward instead. */ export const updateEndpoint = (options: Options): RequestResult => (options.client ?? client).patch({ security: [ @@ -3540,9 +3548,9 @@ export const updateEndpoint = (options: Op }); /** - * Email a forward recipient a new confirmation link + * Resend a forward confirmation link * - * For a pending, expired or (after 30 days) declined forward. The recipient must open the link and choose Allow; no API call can confirm on their behalf. + * Email a forward recipient a new confirmation link. For a pending, expired or (after 30 days) declined forward. The recipient must open the link and choose Allow; no API call can confirm on their behalf. */ export const sendEndpointVerification = (options: Options): RequestResult => (options.client ?? client).post({ security: [ @@ -3567,9 +3575,9 @@ export const sendEndpointVerification = (o }); /** - * Post a fixed test message to a Slack, Discord or webhook endpoint now + * Test an endpoint * - * Bypasses rules and queues: one synchronous post, counted against the endpoint rate. Forwards send real mail, so they are not tested this way; use testRules for a dry run. + * Post a fixed test message to a Slack, Discord or webhook endpoint now. Bypasses rules and queues: one synchronous post, counted against the endpoint rate. Forwards send real mail, so they are not tested this way; use testRules for a dry run. */ export const testEndpoint = (options: Options): RequestResult => (options.client ?? client).post({ security: [ @@ -3590,7 +3598,9 @@ export const testEndpoint = (options: Opti }); /** - * Generate client config with a key limited to selected inboxes. Key shown once. + * Create an inbox connection + * + * Key shown once. Generate client config with a key limited to selected inboxes. */ export const createInboxConnection = (options: Options): RequestResult => (options.client ?? client).post({ security: [ @@ -3615,9 +3625,9 @@ export const createInboxConnection = (opti }); /** - * Read the rules and routes version, or wait for it to change + * Read or wait for the rules version * - * Without after, returns the current version at once. With after (and endpoints, to include endpoint changes), waits up to wait seconds for a rule, route or endpoint save and returns as soon as one commits, with who saved it. The dashboard keeps one of these open while you edit rules so an agent’s saves appear live. Each waited 2.5 seconds counts as one request against the credential’s per-minute budget. + * Read the rules and routes version, or wait for it to change. Without after, returns the current version at once. With after (and endpoints, to include endpoint changes), waits up to wait seconds for a rule, route or endpoint save and returns as soon as one commits, with who saved it. The dashboard keeps one of these open while you edit rules so an agent’s saves appear live. Each waited 2.5 seconds counts as one request against the credential’s per-minute budget. */ export const getRuleVersion = (options?: Options): RequestResult => (options?.client ?? client).get({ security: [ @@ -3638,9 +3648,9 @@ export const getRuleVersion = (options?: O }); /** - * Compile one rule source against this workspace without saving + * Check a rule without saving it * - * Returns every problem with its line, column and a hint, and what the rule calls. Use it while editing; nothing is saved, delivered or sent to the AI. + * Compile one rule source against this workspace without saving. Returns every problem with its line, column and a hint, and what the rule calls. Use it while editing; nothing is saved, delivered or sent to the AI. */ export const checkRule = (options: Options): RequestResult => (options.client ?? client).post({ security: [ @@ -3665,9 +3675,9 @@ export const checkRule = (options: Options }); /** - * TypeScript declarations and editor completions for this workspace + * Read the rules’ TypeScript declarations * - * Generated from the workspace’s endpoints, inbox keys and sender lists. Load typescript into an editor as a .d.ts, or read it to learn exactly what a rule can call. + * TypeScript declarations and editor completions for this workspace. Generated from the workspace’s endpoints, inbox keys and sender lists. Load typescript into an editor as a .d.ts, or read it to learn exactly what a rule can call. */ export const getRuleTypings = (options?: Options): RequestResult => (options?.client ?? client).get({ security: [ @@ -3688,9 +3698,9 @@ export const getRuleTypings = (options?: O }); /** - * Starting points for common rules, filled in with this workspace’s endpoints + * List rule templates * - * Each template compiles. An endpoint template uses the first endpoint of the type it needs; endpoint is null when there is none yet, and source then uses a placeholder name to replace. + * Starting points for common rules, filled in with this workspace’s endpoints. Each template compiles. An endpoint template uses the first endpoint of the type it needs; endpoint is null when there is none yet, and source then uses a placeholder name to replace. */ export const listRuleTemplates = (options?: Options): RequestResult => (options?.client ?? client).get({ security: [ @@ -3711,9 +3721,9 @@ export const listRuleTemplates = (options? }); /** - * Ready-made rules and the fields each one takes + * List rule recipes * - * Each recipe writes an ordinary rule from one or two fields. Create one with createRuleFromRecipe; endpoint fields name an endpoint of the right type, created first with createEndpoint. + * Ready-made rules and the fields each one takes. Each recipe writes an ordinary rule from one or two fields. Create one with createRuleFromRecipe; endpoint fields name an endpoint of the right type, created first with createEndpoint. */ export const listRuleRecipes = (options?: Options): RequestResult => (options?.client ?? client).get({ security: [ @@ -3734,7 +3744,7 @@ export const listRuleRecipes = (options?: }); /** - * Create a rule from a recipe and attach it to addresses + * Create a rule from a recipe * * Writes the recipe’s script, saves it as a new rule (key from the recipe and address unless given) and attaches it to each address, after their other recipes and before their own scripts. An AI recipe lets the AI read mail at those addresses’ domains. Returns the new version and key. Besides listRuleRecipes, it takes the two-way rules the dashboard builds: split ({ test: always, from, subject, text or attachment; value: words, or senders for from; then; otherwise }) and split-by-meaning ({ meaning, then, otherwise }), where then and otherwise are inbox:, an endpoint name, store or drop. Give the address the route [] (createRoute) so each side gets exactly its destination. */ @@ -3761,7 +3771,7 @@ export const createRuleFromRecipe = (optio }); /** - * Change a rule’s recipe fields and addresses + * Update a rule from its recipe * * Rewrites the rule from its recipe with these fields. addresses, when given, replaces where it runs (kept addresses keep their place). Passing recipe turns a script into that recipe. */ @@ -3882,7 +3892,9 @@ export const saveRule = (options: Options< }); /** - * Attach, reorder and detach rules by replacing the ordered attachment list + * Attach rules + * + * Attach, reorder and detach rules by replacing the ordered attachment list. */ export const attachRules = (options: Options): RequestResult => (options.client ?? client).put({ security: [ @@ -3907,7 +3919,9 @@ export const attachRules = (options: Optio }); /** - * Read rules, ordered attachments, and sender lists + * Read rules + * + * Read rules, ordered attachments, and sender lists. */ export const getRules = (options?: Options): RequestResult => (options?.client ?? client).get({ security: [ @@ -3928,7 +3942,9 @@ export const getRules = (options?: Options }); /** - * Create, replace or remove rules and ordered attachments in one version + * Apply rules + * + * Create, replace or remove rules and ordered attachments in one version. */ export const applyRules = (options: Options): RequestResult => (options.client ?? client).put({ security: [ @@ -3953,7 +3969,9 @@ export const applyRules = (options: Option }); /** - * Trace saved or proposed rules on a stored message or pasted MIME; never asks the AI or delivers mail + * Test rules on a message + * + * Trace saved or proposed rules on a stored message or pasted MIME; never asks the AI or delivers mail. */ export const testRules = (options: Options): RequestResult => (options.client ?? client).post({ security: [ @@ -3978,7 +3996,9 @@ export const testRules = (options: Options }); /** - * List folders, stable UID namespaces and counts + * List inbox folders + * + * List folders, stable UID namespaces and counts. */ export const listInboxFolders = (options: Options): RequestResult => (options.client ?? client).get({ security: [ @@ -4024,7 +4044,9 @@ export const createInboxFolder = (options: }); /** - * Remove a custom folder; preserve otherwise orphaned mail in Trash + * Delete an inbox folder + * + * Remove a custom folder; preserve otherwise orphaned mail in Trash. */ export const deleteInboxFolder = (options: Options): RequestResult => (options.client ?? client).delete({ security: [ @@ -4045,7 +4067,9 @@ export const deleteInboxFolder = (options: }); /** - * Rename a folder tree or change its subscription + * Update an inbox folder + * + * Rename a folder tree or change its subscription. */ export const updateInboxFolder = (options: Options): RequestResult => (options.client ?? client).patch({ security: [ @@ -4070,7 +4094,9 @@ export const updateInboxFolder = (options: }); /** - * Move one entry to Trash, or expunge it permanently + * Delete an inbox message + * + * Move one entry to Trash, or expunge it permanently. */ export const deleteInboxMessage = (options: Options): RequestResult => (options.client ?? client).delete({ security: [ @@ -4114,7 +4140,9 @@ export const getInboxMessage = (options: O }); /** - * Set read state or flags; deleted applies to one folder entry + * Update an inbox message + * + * Set read state or flags; deleted applies to one folder entry. */ export const updateInboxMessage = (options: Options): RequestResult => (options.client ?? client).patch({ security: [ @@ -4139,7 +4167,9 @@ export const updateInboxMessage = (options }); /** - * Move one entry and allocate a new destination UID + * Move an inbox message + * + * Move one entry and allocate a new destination UID. */ export const moveInboxMessage = (options: Options): RequestResult => (options.client ?? client).post({ security: [ @@ -4164,7 +4194,9 @@ export const moveInboxMessage = (options: }); /** - * Copy one entry with a fresh destination UID + * Copy an inbox message + * + * Copy one entry with a fresh destination UID. */ export const copyInboxMessage = (options: Options): RequestResult => (options.client ?? client).post({ security: [ @@ -4189,7 +4221,9 @@ export const copyInboxMessage = (options: }); /** - * Remove entries marked deleted; repeat while hasMore is true + * Expunge an inbox folder + * + * Remove entries marked deleted; repeat while hasMore is true. */ export const expungeInboxFolder = (options: Options): RequestResult => (options.client ?? client).post({ security: [ @@ -4214,7 +4248,9 @@ export const expungeInboxFolder = (options }); /** - * Sync changed and removed message IDs since an inbox MODSEQ + * Read an inbox’s changes + * + * Sync changed and removed message IDs since an inbox MODSEQ. */ export const getInboxChanges = (options: Options): RequestResult => (options.client ?? client).get({ security: [ @@ -4235,7 +4271,9 @@ export const getInboxChanges = (options: O }); /** - * List active app passwords without their secrets + * List an inbox’s app passwords + * + * List active app passwords without their secrets. */ export const listInboxAppPasswords = (options: Options): RequestResult => (options.client ?? client).get({ security: [ @@ -4256,7 +4294,9 @@ export const listInboxAppPasswords = (opti }); /** - * Grant mail client access to a persistent inbox. Password shown once; a billable day starts immediately. + * Create an inbox app password + * + * Password shown once; a billable day starts immediately. Grant mail client access to a persistent inbox. */ export const createInboxAppPassword = (options: Options): RequestResult => (options.client ?? client).post({ security: [ @@ -4281,7 +4321,9 @@ export const createInboxAppPassword = (opt }); /** - * List the active app passwords of every inbox, without their secrets + * List every inbox’s app passwords + * + * List the active app passwords of every inbox, without their secrets. */ export const listAppPasswords = (options?: Options): RequestResult => (options?.client ?? client).get({ security: [ @@ -4302,7 +4344,9 @@ export const listAppPasswords = (options?: }); /** - * Revoke a mail client password and invalidate sessions + * Revoke an inbox app password + * + * Revoke a mail client password and invalidate sessions. */ export const revokeInboxAppPassword = (options: Options): RequestResult => (options.client ?? client).delete({ security: [ @@ -4519,7 +4563,9 @@ export const getInboxAttachment = (options }); /** - * Release a retired address for reuse (workspace admin) + * Release a retired address + * + * Release a retired address for reuse (workspace admin). */ export const releaseRetiredAddress = (options: Options): RequestResult => (options.client ?? client).delete({ security: [ @@ -5055,9 +5101,9 @@ export const updateInboundAddress = (optio }); /** - * Change where one address’s mail goes, in one version + * Set where an address’s mail goes * - * Changes the route for the address’s own address and its two-way rule together: one transaction and one routing version, so all of it is saved or none of it. Omitted fields stay as they are, a field equal to what is saved writes nothing, and when nothing changes the version stays. deliver replaces only the route’s destinations (a paused route stays paused). Send the version from getInboundOverview or getRouting as If-Match; a stale one is refused with 409 and nothing changes. + * Change where one address’s mail goes, in one version. Changes the route for the address’s own address and its two-way rule together: one transaction and one routing version, so all of it is saved or none of it. Omitted fields stay as they are, a field equal to what is saved writes nothing, and when nothing changes the version stays. deliver replaces only the route’s destinations (a paused route stays paused). Send the version from getInboundOverview or getRouting as If-Match; a stale one is refused with 409 and nothing changes. */ export const setInboundAddressFlow = (options: Options): RequestResult => (options.client ?? client).patch({ security: [ @@ -5105,7 +5151,9 @@ export const listInboundThreads = (options }); /** - * Start a conversation from an inbound address + * Start a conversation + * + * Start a conversation from an inbound address. */ export const createInboundThread = (options: Options): RequestResult => (options.client ?? client).post({ security: [ @@ -5153,7 +5201,9 @@ export const getInboundThread = (options: }); /** - * Mark a conversation read, star, archive or label it for one address + * Update a conversation + * + * Mark a conversation read, star, archive or label it for one address. */ export const updateInboundThread = (options: Options): RequestResult => (options.client ?? client).patch({ security: [ @@ -5224,7 +5274,9 @@ export const getInboundMessage = (options: }); /** - * Download an attachment from a visible message + * Download an inbound attachment + * + * Download an attachment from a visible message. */ export const getInboundAttachment = (options: Options): RequestResult => (options.client ?? client).get({ security: [ @@ -5245,7 +5297,7 @@ export const getInboundAttachment = (optio }); /** - * Follow an attachment link from a webhook + * Follow a webhook attachment link * * The downloadUrl (inbound format) or url (message attachments) in webhook payloads. Answers 307 to a download link that works for five minutes, also returned as url in the body. Any credential that can read the message can follow it, exactly as with getInboundAttachment: an inbound key for the address it reached, a member, an agent token. */ @@ -5291,9 +5343,9 @@ export const listLogs = (options?: Options }); /** - * Every route mail can take, with its rules and endpoints, in one read + * Read the receiving overview * - * One page of routes (addresses, agent inboxes, address patterns, explicit routes and catch-alls) merged and ordered by host, kind and address, each resolved to the rules that run on it and where its mail goes. Also returns counts per kind, the rules, up to 100 endpoints and 100 inbound webhooks, and the domains. Members and scoped keys see only their addresses. With an MCP sign-in (approval), it requires an owner or admin, like the other receiving reads. + * Every route mail can take, with its rules and endpoints, in one read. One page of routes (addresses, agent inboxes, address patterns, explicit routes and catch-alls) merged and ordered by host, kind and address, each resolved to the rules that run on it and where its mail goes. Also returns counts per kind, the rules, up to 100 endpoints and 100 inbound webhooks, and the domains. Members and scoped keys see only their addresses. With an MCP sign-in (approval), it requires an owner or admin, like the other receiving reads. */ export const getInboundOverview = (options?: Options): RequestResult => (options?.client ?? client).get({ security: [ @@ -5314,9 +5366,9 @@ export const getInboundOverview = (options }); /** - * List every endpoint a page at a time, with the routes and rules that use it + * List every endpoint * - * Named endpoints of every type (Slack, Discord, webhook, forward) by name, then webhooks without a name. Pass nextCursor back as cursor until it is null. addressId lists only the webhooks that get that address's received mail (subscribed to it or to every address), the full list a route's toMore points to. + * List every endpoint a page at a time, with the routes and rules that use it. Named endpoints of every type (Slack, Discord, webhook, forward) by name, then webhooks without a name. Pass nextCursor back as cursor until it is null. addressId lists only the webhooks that get that address's received mail (subscribed to it or to every address), the full list a route's toMore points to. */ export const listInboundEndpoints = (options?: Options): RequestResult => (options?.client ?? client).get({ security: [ @@ -5364,9 +5416,9 @@ export const replyToInboundThread = (optio }); /** - * Poll events for the receiving addresses this key can read + * List inbound events * - * Use the returned cursor as after to continue polling. Workspace-wide message.stored events require admin access, no address filter, and an explicit message.stored type filter. + * Poll events for the receiving addresses this key can read. Use the returned cursor as after to continue polling. Workspace-wide message.stored events require admin access, no address filter, and an explicit message.stored type filter. */ export const listInboundEvents = (options?: Options): RequestResult => (options?.client ?? client).get({ security: [ @@ -5387,9 +5439,9 @@ export const listInboundEvents = (options? }); /** - * List inbound webhooks a page at a time, in a stable ID order + * List inbound webhooks * - * Every webhook endpoint, named or not. Pass nextCursor back as cursor until it is null to read every webhook. addressId and eventType narrow the list to the webhooks that get that address's events (subscribed to it or to every address); getInboundOverview links a route's full list of subscribers this way. + * List inbound webhooks a page at a time, in a stable ID order. Every webhook endpoint, named or not. Pass nextCursor back as cursor until it is null to read every webhook. addressId and eventType narrow the list to the webhooks that get that address's events (subscribed to it or to every address); getInboundOverview links a route's full list of subscribers this way. */ export const listInboundWebhooks = (options?: Options): RequestResult => (options?.client ?? client).get({ security: [ @@ -5525,7 +5577,7 @@ export const testInboundWebhook = (options }); /** - * Redeliver a message to its route webhooks + * Redeliver an inbound message * * Queues this message again for every route webhook that already finished with it (delivered or failed), or only destination. Returns how many deliveries were queued; 0 means none are eligible. Previously redelivered successes have a 10-minute cooldown. The workspace gets 1,000 manual posts per hour. Receivers deduplicate by Webhook-Id. */ @@ -5995,9 +6047,9 @@ export const verifyConnection = (options: export const getPublicStats = (options?: Options): RequestResult => (options?.client ?? client).get({ url: '/v1/public/stats', ...options }); /** - * What this workspace has set up, in one read + * Read the workspace setup * - * The newest domains, the number of active API keys, outbound webhooks and pending invitations, whether any email exists, each focus's first steps and whether an agent is connected. Each part follows the permission rules of its own list operation and is null where that operation would refuse the caller. Counts only: no webhook URL, key, address or subject. + * What this workspace has set up, in one read. The newest domains, the number of active API keys, outbound webhooks and pending invitations, whether any email exists, each focus's first steps and whether an agent is connected. Each part follows the permission rules of its own list operation and is null where that operation would refuse the caller. Counts only: no webhook URL, key, address or subject. */ export const getOverviewSetup = (options?: Options): RequestResult => (options?.client ?? client).get({ security: [ @@ -6056,7 +6108,7 @@ export const contactSupport = (options: Op }); /** - * Balance, free allowance and billing state + * Read the balance and billing state * * Hosted only. The prepaid balance, this month’s free allowances (sent and received, counted separately) and cost, whether sending or receiving is paused for an empty balance, auto-recharge and the saved card, and the prices. Amounts are null unless the caller is an owner or admin session, or a manage key or grant. Keys restricted to domains get 403. */