Compare commits

..

10 Commits

Author SHA1 Message Date
Waleed
c400e59ea6 feat(sap_s4hana): add get_material_document and fix supplier invoice key order (#4317)
* fix(sap_s4hana): require non-empty items in create_purchase_order

Why: SAP A_PurchaseOrder POST silently fails or returns opaque errors
without to_PurchaseOrderItem entries. Block already required this body
but the tool marked it optional and didn't validate items presence —
mismatched contract with create_sales_order / create_purchase_requisition.

Also clarifies the deliveryDocument placeholder to show both outbound
and inbound number ranges.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(sap_s4hana): add get_material_document and fix supplier invoice key order

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(sap_s4hana): align material doc key order in description and require purchase order body type

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-27 23:41:56 -07:00
Vikhyath Mondreti
2e3de9ac8a feat(governance): external workspace users from outside org (#4313)
* feat(governance): external workspace users from outside org

* update docs

* address comments

* edge case improvements

* remove unused fallback

* address comments

* add outbox for seat reduction

* fix edge case with org join after invite

* add server side batch invites for workspace

* use zod schema for route
2026-04-27 22:07:41 -07:00
Theodore Li
154b9d0883 fix(vm): categorize user or server side errors (#4283)
* fix(vm): categorize user or server side errors

* recategorize function syntax errors as 4xx
2026-04-27 22:27:50 -04:00
Waleed
c95ac3bc23 improvement(browser-use,stagehand): expose live session URLs (#4314)
* improvement(browser-use,stagehand): expose live session URLs and align with latest API specs

- Browser Use: switch to v2 camelCase schema, fetch live URL from sessions endpoint, add startUrl/maxSteps/allowedDomains/vision/flashMode/thinking/systemPromptExtension/structuredOutput/metadata params, surface liveUrl/shareUrl/sessionId outputs
- Stagehand: fetch Browserbase debug URL, add mode/maxSteps params, surface liveViewUrl/sessionId outputs, bump @browserbasehq/stagehand to ^3.2.1, update to claude-sonnet-4-6

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(browser-use): respect API default for highlightElements

Only send highlightElements when user explicitly toggles it; previously defaulted to true which silently overrode the v2 API default of false.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(browser-use,stagehand): address PR review feedback

- Browser Use: fetch liveUrl during polling once sessionId is known, instead of immediately after task creation. Handles tasks started without profile_id (where sessionId isn't returned in create response) and ensures session is active before fetching.
- Stagehand: coerce empty/whitespace maxSteps strings to undefined so they're dropped from the request body instead of failing zod validation as ''.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(stagehand): preserve liveViewUrl and sessionId on agent error

If the agent throws after Browserbase session init succeeds, callers can still surface the live view / session ID for debugging.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(browser-use): coerce empty maxSteps strings to undefined

Mirrors the Stagehand block's handling so a cleared field doesn't pass through as ''.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(browser-use): skip metadata when empty

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-27 18:02:51 -07:00
Theodore Li
ca814f021d fix(ui): display file upload error messages (#4315)
* fix(ui): display file upload messages

* Address pr comments
2026-04-27 18:58:41 -04:00
Waleed
2502369122 feat(integrations): SAP S/4HANA (#4301)
* feat(integrations): SAP S/4HANA tools, block, and proxy with multi-deployment support

* fix(sap_s4hana): address PR review comments

- Validate baseUrl/tokenUrl in Zod schema and at runtime to prevent SSRF
  (https-only, deny loopback/link-local/cloud-metadata hosts)
- Cap proxy token cache at 500 entries with LRU eviction
- Add 30s timeout to outbound token, CSRF, and OData fetches
- Make parseJsonInput return T | undefined so missing input is type-safe
- Reset authType when deploymentType changes and surface OAuth fields
  whenever auth is not basic, so cloud_public users always see clientId/
  clientSecret after switching from a basic-auth private deployment
- Reject OData service names that are not uppercase identifiers and
  paths containing ".." or "." traversal segments

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(sap_s4hana): allow versioned service names; tighten proxy SSRF defenses

- Permit ";v=NNNN" suffix on ServiceName regex so the four delivery tools
  (API_OUTBOUND_DELIVERY_SRV;v=0002, API_INBOUND_DELIVERY_SRV;v=0002) pass
  schema validation
- Restrict subdomain to RFC 1123 label characters and region to lowercase
  alphanumeric short codes; run the constructed cloud_public host through
  assertSafeExternalUrl so a crafted subdomain (e.g. "evil.com#") cannot
  redirect requests carrying SAP credentials
- Block RFC-1918 (10/8, 172.16/12, 192.168/16), 127/8, 169.254/16, and
  0.0.0.0 via isPrivateIPv4, plus IPv4-mapped IPv6 variants
  (::ffff:10.0.0.1, ::10.0.0.1) so private internal hosts cannot be
  reached from baseUrl, tokenUrl, or the resolved cloud_public URL

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(sap_s4hana): catch hex-form IPv4-mapped IPv6 in SSRF check

The WHATWG URL parser normalizes IPv4-mapped IPv6 addresses to hex form
(e.g. [::ffff:169.254.169.254] → [::ffff:a9fe:a9fe]), which slipped past
the dotted-decimal-only extractor. Decode the trailing two 16-bit hex
groups back into IPv4 octets and run them through isPrivateIPv4. Also
add isPrivateOrLoopbackIPv6 so pure IPv6 loopback (::, ::1), unique
local addresses (fc00::/7), and link-local (fe80::/10) cannot be reached.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(sap_s4hana): scope CSRF metadata fetch and isolate token cache by secret

- buildOdataUrl skips request query params when called with an internal
  pathOverride so the /$metadata CSRF probe never carries user OData
  options ($filter, $top, $select), which were causing write operations
  through the generic odata_query tool to fail.
- tokenCacheKey now mixes a sha256 hash of clientSecret into the cache
  key so two tenants sharing the same tokenUrl + clientId but different
  secrets get isolated entries (no cross-tenant token leak).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(sap_s4hana): reject ?/# in service path; trim long update tool descriptions

- ServicePath validator now rejects "?" and "#" so a caller can't smuggle
  query options through the path field (e.g.,
  "/A_BusinessPartner?$format=atomsvc"); the Zod refine now reports
  ".." / "." segments, "?", and "#" together.
- Update Customer / Update Supplier / Update Purchase Requisition tool
  descriptions exceeded the docs generator's 600-char regex window, so
  they were rendering with empty descriptions on the integrations
  landing page. Trimmed them to fit while keeping the limited-fields
  note and the If-Match guidance, then regenerated integrations.json
  and tool docs.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(sap_s4hana): reject percent-encoded path traversal; widen Set-Cookie split

- ServicePath now also rejects %2e/%2E, %2f/%2F, %5c/%5C, %3f/%3F, %23
  so a caller cannot smuggle ".." / "." / "/" / "\" / "?" / "#" past the
  validator and have SAP's ABAP/ICM gateway decode them server-side.
- joinSetCookies fallback regex now allows the ", " separator that's
  used when multiple Set-Cookie values are folded onto one header line
  (older runtimes without Headers.getSetCookie). Prevents CSRF cookies
  from being concatenated into a single value during write operations.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(sap_s4hana): preserve $ in OData query params; reject empty items array

- buildOdataUrl now constructs query strings manually with
  encodeURIComponent and restores literal "$" so OData system options
  ($filter, $top, $select, $expand, $orderby, $skip, $format) reach
  SAP and any intermediary proxies/WAFs as-is, not as "%24filter".
  URLSearchParams was percent-encoding "$" to "%24" which most ICMs
  decode but some intermediaries silently drop, returning unfiltered
  results.
- create_sales_order now rejects an empty items array (matches
  create_purchase_requisition) so callers get a clear client-side
  error instead of an opaque SAP validation failure on the deep-insert.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(sap_s4hana): ignore baseUrl on cloud_public to prevent token redirection

Why: resolveHost previously preferred baseUrl unconditionally. A caller
sending deploymentType=cloud_public with a baseUrl pointing elsewhere
would obtain a real SAP UAA token, then forward it as Bearer to the
attacker host. Zod superRefine did not validate baseUrl for cloud_public.

Fix: resolveHost now constructs the SAP host from subdomain when
deploymentType is cloud_public and only uses baseUrl for cloud_private
and on_premise (where it is already SSRF-checked in superRefine).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(icons): use useId for SapS4HanaIcon and PipedriveIcon gradients

Why: hardcoded SVG gradient/mask IDs collide when an icon renders more
than once on a page (e.g. integrations listing). All other icons in this
file use React's useId() — these were inconsistent.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* icons

* fix(icons): use useId for AWS-style icon gradients

Why: IAMIcon, IdentityCenterIcon, STSIcon, SESIcon, and SecretsManagerIcon
all used hardcoded `id='xxxGradient'` values that collide when an icon
renders more than once on a page (e.g. integrations listing).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(sap_s4hana): ignore tokenUrl on cloud_public to prevent UAA redirection

Why: resolveTokenUrl previously honored caller-supplied tokenUrl
regardless of deploymentType, mirroring the same redirection class as
the prior baseUrl bug. A cloud_public caller could send tokenUrl to an
attacker host, causing the proxy to POST clientId:clientSecret as Basic
auth to it. superRefine for cloud_public did not validate tokenUrl.

Fix: derive UAA URL from subdomain+region for cloud_public; only honor
tokenUrl for cloud_private/on_premise (already SSRF-checked).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(icons): remove unused mask in PipedriveIcon

Why: the <mask> element had no consumer (no mask='url(#...)' anywhere
in the SVG), so both it and the maskId variable were dead code.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-27 15:07:00 -07:00
Waleed
8266f0afdb fix(security): rate limit chat OTP + validate mothership proxy endpoint (#4312)
* fix(security): rate limit chat OTP endpoint to prevent email bombing

* fix(security): validate mothership proxy endpoint to block path traversal

* fix(security): address greptile feedback on OTP rate limiting
2026-04-27 14:51:58 -07:00
Waleed
896a00ae31 fix(security): require internal API key for copilot training endpoints (#4311) 2026-04-27 14:30:47 -07:00
Waleed
74946fb162 improvement(docker): speed up app image build with cache mounts and parallel node-gyp (#4310) 2026-04-27 13:34:57 -07:00
Waleed
f62d274478 fix(mothership): stabilize task sidebar ordering on selection (#4309) 2026-04-27 12:42:20 -07:00
147 changed files with 27327 additions and 802 deletions

View File

@@ -4045,6 +4045,7 @@ export function AsanaIcon(props: SVGProps<SVGSVGElement>) {
}
export function PipedriveIcon(props: SVGProps<SVGSVGElement>) {
const pathId = useId()
return (
<svg
{...props}
@@ -4058,7 +4059,7 @@ export function PipedriveIcon(props: SVGProps<SVGSVGElement>) {
<defs>
<path
d='M59.6807,81.1772 C59.6807,101.5343 70.0078,123.4949 92.7336,123.4949 C109.5872,123.4949 126.6277,110.3374 126.6277,80.8785 C126.6277,55.0508 113.232,37.7119 93.2944,37.7119 C77.0483,37.7119 59.6807,49.1244 59.6807,81.1772 Z M101.3006,0 C142.0482,0 169.4469,32.2728 169.4469,80.3126 C169.4469,127.5978 140.584,160.60942 99.3224,160.60942 C79.6495,160.60942 67.0483,152.1836 60.4595,146.0843 C60.5063,147.5305 60.5374,149.1497 60.5374,150.8788 L60.5374,215 L18.32565,215 L18.32565,44.157 C18.32565,41.6732 17.53126,40.8873 15.07021,40.8873 L0.5531,40.8873 L0.5531,3.4741 L35.9736,3.4741 C52.282,3.4741 56.4564,11.7741 57.2508,18.1721 C63.8708,10.7524 77.5935,0 101.3006,0 Z'
id='path-1'
id={pathId}
/>
</defs>
<g
@@ -4069,10 +4070,7 @@ export function PipedriveIcon(props: SVGProps<SVGSVGElement>) {
fillRule='evenodd'
>
<g transform='translate(67.000000, 44.000000)'>
<mask id='mask-2' fill='white'>
<use href='#path-1' />
</mask>
<use id='Clip-5' fill='#FFFFFF' xlinkHref='#path-1' />
<use fill='#FFFFFF' xlinkHref={`#${pathId}`} />
</g>
</g>
</svg>
@@ -4098,6 +4096,40 @@ export function SalesforceIcon(props: SVGProps<SVGSVGElement>) {
)
}
export function SapS4HanaIcon(props: SVGProps<SVGSVGElement>) {
const id = useId()
return (
<svg {...props} xmlns='http://www.w3.org/2000/svg' viewBox='0 0 412.38 204'>
<defs>
<linearGradient
id={id}
x1='206.19'
y1='0'
x2='206.19'
y2='204'
gradientUnits='userSpaceOnUse'
>
<stop offset='0' stopColor='#00b1eb' />
<stop offset='.212' stopColor='#009ad9' />
<stop offset='.519' stopColor='#007fc4' />
<stop offset='.792' stopColor='#006eb8' />
<stop offset='1' stopColor='#0069b4' />
</linearGradient>
</defs>
<polyline
fill={`url(#${id})`}
fillRule='evenodd'
points='0 204 208.413 204 412.38 0 0 0 0 204'
/>
<path
fill='#fff'
fillRule='evenodd'
d='m244.727,38.359l-40.593-.025v96.518l-35.46-96.518h-35.16l-30.277,80.716c-3.224-20.352-24.277-27.38-40.84-32.649-10.937-3.512-22.541-8.678-22.434-14.387.091-4.687,6.225-9.04,18.377-8.385,8.17.433,15.373,1.092,29.71,8.006l14.102-24.557c-13.088-6.658-31.169-10.867-45.985-10.883h-.086c-17.277,0-31.677,5.598-40.602,14.824-6.221,6.443-9.572,14.626-9.712,23.679-.227,12.454,4.341,21.292,13.938,28.338,8.104,5.944,18.468,9.794,27.603,12.626,11.27,3.492,20.467,6.526,20.36,13.002-.083,2.355-.977,4.552-2.671,6.337-2.807,2.897-7.124,3.986-13.084,4.098-11.497.243-20.026-1.559-33.61-9.585l-12.536,24.903c13.546,7.705,29.586,12.223,45.952,12.223l2.106-.024c14.247-.256,25.745-4.316,34.929-11.712.527-.416,1.001-.845,1.488-1.277l-4.073,10.874h36.875l6.189-18.822c6.477,2.214,13.847,3.437,21.676,3.437,7.618,0,14.795-1.17,21.156-3.252l5.965,18.637h60.137v-38.969h13.113c31.706,0,50.456-16.147,50.456-43.202,0-30.139-18.219-43.969-57.011-43.969Zm-93.816,82.587c-4.737,0-9.177-.828-13.006-2.275l12.866-40.593h.244l12.643,40.708c-3.801,1.349-8.138,2.16-12.746,2.16Zm96.199-23.324h-8.941v-32.711h8.941c11.927,0,21.437,3.961,21.437,16.139,0,12.602-9.51,16.572-21.437,16.572'
/>
</svg>
)
}
export function ServiceNowIcon(props: SVGProps<SVGSVGElement>) {
return (
<svg {...props} xmlns='http://www.w3.org/2000/svg' viewBox='0 0 71.1 63.6'>
@@ -4694,15 +4726,16 @@ export function DynamoDBIcon(props: SVGProps<SVGSVGElement>) {
}
export function IAMIcon(props: SVGProps<SVGSVGElement>) {
const id = useId()
return (
<svg {...props} viewBox='0 0 80 80' xmlns='http://www.w3.org/2000/svg'>
<defs>
<linearGradient x1='0%' y1='100%' x2='100%' y2='0%' id='iamGradient'>
<linearGradient x1='0%' y1='100%' x2='100%' y2='0%' id={id}>
<stop stopColor='#BD0816' offset='0%' />
<stop stopColor='#FF5252' offset='100%' />
</linearGradient>
</defs>
<rect fill='url(#iamGradient)' width='80' height='80' />
<rect fill={`url(#${id})`} width='80' height='80' />
<path
d='M14,59 L66,59 L66,21 L14,21 L14,59 Z M68,20 L68,60 C68,60.552 67.553,61 67,61 L13,61 C12.447,61 12,60.552 12,60 L12,20 C12,19.448 12.447,19 13,19 L67,19 C67.553,19 68,19.448 68,20 L68,20 Z M44,48 L59,48 L59,46 L44,46 L44,48 Z M57,42 L62,42 L62,40 L57,40 L57,42 Z M44,42 L52,42 L52,40 L44,40 L44,42 Z M29,46 C29,45.449 28.552,45 28,45 C27.448,45 27,45.449 27,46 C27,46.551 27.448,47 28,47 C28.552,47 29,46.551 29,46 L29,46 Z M31,46 C31,47.302 30.161,48.401 29,48.816 L29,51 L27,51 L27,48.815 C25.839,48.401 25,47.302 25,46 C25,44.346 26.346,43 28,43 C29.654,43 31,44.346 31,46 L31,46 Z M19,53.993 L36.994,54 L36.996,50 L33,50 L33,48 L36.996,48 L36.998,45 L33,45 L33,43 L36.999,43 L37,40.007 L19.006,40 L19,53.993 Z M22,38.001 L34,38.006 L34,31 C34.001,28.697 31.197,26.677 28,26.675 L27.996,26.675 C24.804,26.675 22.004,28.696 22.002,31 L22,38.001 Z M17,54.992 L17.006,39 C17.006,38.734 17.111,38.48 17.299,38.292 C17.486,38.105 17.741,38 18.006,38 L20,38.001 L20.002,31 C20.004,27.512 23.59,24.675 27.996,24.675 L28,24.675 C32.412,24.677 36.001,27.515 36,31 L36,38.007 L38,38.008 C38.553,38.008 39,38.456 39,39.008 L38.994,55 C38.994,55.266 38.889,55.52 38.701,55.708 C38.514,55.895 38.259,56 37.994,56 L18,55.992 C17.447,55.992 17,55.544 17,54.992 L17,54.992 Z M60,36 L62,36 L62,34 L60,34 L60,36 Z M44,36 L55,36 L55,34 L44,34 L44,36 Z'
fill='#FFFFFF'
@@ -4712,15 +4745,16 @@ export function IAMIcon(props: SVGProps<SVGSVGElement>) {
}
export function IdentityCenterIcon(props: SVGProps<SVGSVGElement>) {
const id = useId()
return (
<svg {...props} viewBox='0 0 80 80' xmlns='http://www.w3.org/2000/svg'>
<defs>
<linearGradient x1='0%' y1='100%' x2='100%' y2='0%' id='identityCenterGradient'>
<linearGradient x1='0%' y1='100%' x2='100%' y2='0%' id={id}>
<stop stopColor='#BD0816' offset='0%' />
<stop stopColor='#FF5252' offset='100%' />
</linearGradient>
</defs>
<rect fill='url(#identityCenterGradient)' width='80' height='80' />
<rect fill={`url(#${id})`} width='80' height='80' />
<path
d='M46.694,46.8194562 C47.376,46.1374562 47.376,45.0294562 46.694,44.3474562 C46.353,44.0074562 45.906,43.8374562 45.459,43.8374562 C45.01,43.8374562 44.563,44.0074562 44.222,44.3474562 C43.542,45.0284562 43.542,46.1384562 44.222,46.8194562 C44.905,47.5014562 46.013,47.4994562 46.694,46.8194562 M47.718,47.1374562 L51.703,51.1204562 L50.996,51.8274562 L49.868,50.6994562 L48.793,51.7754562 L48.086,51.0684562 L49.161,49.9924562 L47.011,47.8444562 C46.545,48.1654562 46.003,48.3294562 45.458,48.3294562 C44.755,48.3294562 44.051,48.0624562 43.515,47.5264562 C42.445,46.4554562 42.445,44.7124562 43.515,43.6404562 C44.586,42.5714562 46.329,42.5694562 47.401,43.6404562 C48.351,44.5904562 48.455,46.0674562 47.718,47.1374562 M53,44.1014562 C53,46.1684562 51.505,47.0934562 50.023,47.0934562 L50.023,46.0934562 C50.487,46.0934562 52,45.9494562 52,44.1014562 C52,43.0044562 51.353,42.3894562 49.905,42.1084562 C49.68,42.0654562 49.514,41.8754562 49.501,41.6484562 C49.446,40.7444562 48.987,40.1124562 48.384,40.1124562 C48.084,40.1124562 47.854,40.2424562 47.616,40.5464562 C47.506,40.6884562 47.324,40.7594562 47.147,40.7324562 C46.968,40.7054562 46.818,40.5844562 46.755,40.4144562 C46.577,39.9434562 46.211,39.4334562 45.723,38.9774562 C45.231,38.5094562 43.883,37.5074562 41.972,38.2734562 C40.885,38.7054562 40.034,39.9494562 40.034,41.1074562 C40.034,41.2354562 40.043,41.3624562 40.058,41.4884562 C40.061,41.5094562 40.062,41.5304562 40.062,41.5514562 C40.062,41.7994562 39.882,42.0064562 39.645,42.0464562 C38.886,42.2394562 38,42.7454562 38,44.0554562 L38.005,44.2104562 C38.069,45.3254562 39.252,45.9954562 40.358,45.9984562 L41,45.9984562 L41,46.9984562 L40.357,46.9984562 C38.536,46.9944562 37.095,45.8194562 37.006,44.2644562 C37.003,44.1944562 37,44.1244562 37,44.0554562 C37,42.6944562 37.752,41.6484562 39.035,41.1884562 C39.034,41.1614562 39.034,41.1344562 39.034,41.1074562 C39.034,39.5434562 40.138,37.9254562 41.602,37.3434562 C43.298,36.6654562 45.095,37.0034562 46.409,38.2494562 C46.706,38.5274562 47.076,38.9264562 47.372,39.4134562 C47.673,39.2124562 48.008,39.1124562 48.384,39.1124562 C49.257,39.1124562 50.231,39.7714562 50.458,41.2074562 C52.145,41.6324562 53,42.6054562 53,44.1014562 M27,53 L27,27 L53,27 L53,34 L51,34 L51,29 L29,29 L29,51 L51,51 L51,46 L53,46 L53,53 Z'
fill='#FFFFFF'
@@ -4730,15 +4764,16 @@ export function IdentityCenterIcon(props: SVGProps<SVGSVGElement>) {
}
export function STSIcon(props: SVGProps<SVGSVGElement>) {
const id = useId()
return (
<svg {...props} viewBox='0 0 80 80' xmlns='http://www.w3.org/2000/svg'>
<defs>
<linearGradient x1='0%' y1='100%' x2='100%' y2='0%' id='stsGradient'>
<linearGradient x1='0%' y1='100%' x2='100%' y2='0%' id={id}>
<stop stopColor='#BD0816' offset='0%' />
<stop stopColor='#FF5252' offset='100%' />
</linearGradient>
</defs>
<rect fill='url(#stsGradient)' width='80' height='80' />
<rect fill={`url(#${id})`} width='80' height='80' />
<path
d='M14,59 L66,59 L66,21 L14,21 L14,59 Z M68,20 L68,60 C68,60.552 67.553,61 67,61 L13,61 C12.447,61 12,60.552 12,60 L12,20 C12,19.448 12.447,19 13,19 L67,19 C67.553,19 68,19.448 68,20 L68,20 Z M44,48 L59,48 L59,46 L44,46 L44,48 Z M57,42 L62,42 L62,40 L57,40 L57,42 Z M44,42 L52,42 L52,40 L44,40 L44,42 Z M29,46 C29,45.449 28.552,45 28,45 C27.448,45 27,45.449 27,46 C27,46.551 27.448,47 28,47 C28.552,47 29,46.551 29,46 L29,46 Z M31,46 C31,47.302 30.161,48.401 29,48.816 L29,51 L27,51 L27,48.815 C25.839,48.401 25,47.302 25,46 C25,44.346 26.346,43 28,43 C29.654,43 31,44.346 31,46 L31,46 Z M19,53.993 L36.994,54 L36.996,50 L33,50 L33,48 L36.996,48 L36.998,45 L33,45 L33,43 L36.999,43 L37,40.007 L19.006,40 L19,53.993 Z M22,38.001 L34,38.006 L34,31 C34.001,28.697 31.197,26.677 28,26.675 L27.996,26.675 C24.804,26.675 22.004,28.696 22.002,31 L22,38.001 Z M17,54.992 L17.006,39 C17.006,38.734 17.111,38.48 17.299,38.292 C17.486,38.105 17.741,38 18.006,38 L20,38.001 L20.002,31 C20.004,27.512 23.59,24.675 27.996,24.675 L28,24.675 C32.412,24.677 36.001,27.515 36,31 L36,38.007 L38,38.008 C38.553,38.008 39,38.456 39,39.008 L38.994,55 C38.994,55.266 38.889,55.52 38.701,55.708 C38.514,55.895 38.259,56 37.994,56 L18,55.992 C17.447,55.992 17,55.544 17,54.992 L17,54.992 Z M60,36 L62,36 L62,34 L60,34 L60,36 Z M44,36 L55,36 L55,34 L44,34 L44,36 Z'
fill='#FFFFFF'
@@ -4748,15 +4783,16 @@ export function STSIcon(props: SVGProps<SVGSVGElement>) {
}
export function SESIcon(props: SVGProps<SVGSVGElement>) {
const id = useId()
return (
<svg {...props} viewBox='0 0 80 80' xmlns='http://www.w3.org/2000/svg'>
<defs>
<linearGradient x1='0%' y1='100%' x2='100%' y2='0%' id='sesGradient'>
<linearGradient x1='0%' y1='100%' x2='100%' y2='0%' id={id}>
<stop stopColor='#BD0816' offset='0%' />
<stop stopColor='#FF5252' offset='100%' />
</linearGradient>
</defs>
<rect fill='url(#sesGradient)' width='80' height='80' />
<rect fill={`url(#${id})`} width='80' height='80' />
<path
d='M57,60.999875 C57,59.373846 55.626,57.9998214 54,57.9998214 C52.374,57.9998214 51,59.373846 51,60.999875 C51,62.625904 52.374,63.9999286 54,63.9999286 C55.626,63.9999286 57,62.625904 57,60.999875 L57,60.999875 Z M40,59.9998571 C38.374,59.9998571 37,61.3738817 37,62.9999107 C37,64.6259397 38.374,65.9999643 40,65.9999643 C41.626,65.9999643 43,64.6259397 43,62.9999107 C43,61.3738817 41.626,59.9998571 40,59.9998571 L40,59.9998571 Z M26,57.9998214 C24.374,57.9998214 23,59.373846 23,60.999875 C23,62.625904 24.374,63.9999286 26,63.9999286 C27.626,63.9999286 29,62.625904 29,60.999875 C29,59.373846 27.626,57.9998214 26,57.9998214 L26,57.9998214 Z M28.605,42.9995536 L51.395,42.9995536 L43.739,36.1104305 L40.649,38.7584778 C40.463,38.9194807 40.23,38.9994821 39.999,38.9994821 C39.768,38.9994821 39.535,38.9194807 39.349,38.7584778 L36.26,36.1104305 L28.605,42.9995536 Z M27,28.1732888 L27,41.7545313 L34.729,34.7984071 L27,28.1732888 Z M51.297,26.9992678 L28.703,26.9992678 L39.999,36.6824408 L51.297,26.9992678 Z M53,41.7545313 L53,28.1732888 L45.271,34.7974071 L53,41.7545313 Z M59,60.999875 C59,63.7099234 56.71,65.9999643 54,65.9999643 C51.29,65.9999643 49,63.7099234 49,60.999875 C49,58.6308327 50.75,56.5837961 53,56.1057876 L53,52.9997321 L41,52.9997321 L41,58.1058233 C43.25,58.5838319 45,60.6308684 45,62.9999107 C45,65.7099591 42.71,68 40,68 C37.29,68 35,65.7099591 35,62.9999107 C35,60.6308684 36.75,58.5838319 39,58.1058233 L39,52.9997321 L27,52.9997321 L27,56.1057876 C29.25,56.5837961 31,58.6308327 31,60.999875 C31,63.7099234 28.71,65.9999643 26,65.9999643 C23.29,65.9999643 21,63.7099234 21,60.999875 C21,58.6308327 22.75,56.5837961 25,56.1057876 L25,51.9997143 C25,51.4477044 25.447,50.9996964 26,50.9996964 L39,50.9996964 L39,44.9995893 L26,44.9995893 C25.447,44.9995893 25,44.5515813 25,43.9995714 L25,25.99925 C25,25.4472401 25.447,24.9992321 26,24.9992321 L54,24.9992321 C54.553,24.9992321 55,25.4472401 55,25.99925 L55,43.9995714 C55,44.5515813 54.553,44.9995893 54,44.9995893 L41,44.9995893 L41,50.9996964 L54,50.9996964 C54.553,50.9996964 55,51.4477044 55,51.9997143 L55,56.1057876 C57.25,56.5837961 59,58.6308327 59,60.999875 L59,60.999875 Z M68,39.9995 C68,45.9066055 66.177,51.5597064 62.727,56.3447919 L61.104,55.174771 C64.307,50.7316916 66,45.4845979 66,39.9995 C66,25.664244 54.337,14.0000357 40.001,14.0000357 C25.664,14.0000357 14,25.664244 14,39.9995 C14,45.4845979 15.693,50.7316916 18.896,55.174771 L17.273,56.3447919 C13.823,51.5597064 12,45.9066055 12,39.9995 C12,24.5612243 24.561,12 39.999,12 C55.438,12 68,24.5612243 68,39.9995 L68,39.9995 Z'
fill='#FFFFFF'
@@ -4766,15 +4802,16 @@ export function SESIcon(props: SVGProps<SVGSVGElement>) {
}
export function SecretsManagerIcon(props: SVGProps<SVGSVGElement>) {
const id = useId()
return (
<svg {...props} viewBox='0 0 80 80' xmlns='http://www.w3.org/2000/svg'>
<defs>
<linearGradient x1='0%' y1='100%' x2='100%' y2='0%' id='secretsManagerGradient'>
<linearGradient x1='0%' y1='100%' x2='100%' y2='0%' id={id}>
<stop stopColor='#BD0816' offset='0%' />
<stop stopColor='#FF5252' offset='100%' />
</linearGradient>
</defs>
<rect fill='url(#secretsManagerGradient)' width='80' height='80' />
<rect fill={`url(#${id})`} width='80' height='80' />
<path
d='M38.76,43.36 C38.76,44.044 39.317,44.6 40,44.6 C40.684,44.6 41.24,44.044 41.24,43.36 C41.24,42.676 40.684,42.12 40,42.12 C39.317,42.12 38.76,42.676 38.76,43.36 L38.76,43.36 Z M36.76,43.36 C36.76,41.573 38.213,40.12 40,40.12 C41.787,40.12 43.24,41.573 43.24,43.36 C43.24,44.796 42.296,46.002 41,46.426 L41,49 L39,49 L39,46.426 C37.704,46.002 36.76,44.796 36.76,43.36 L36.76,43.36 Z M49,38 L31,38 L31,51 L49,51 L49,48 L46,48 L46,46 L49,46 L49,43 L46,43 L46,41 L49,41 L49,38 Z M34,36 L45.999,36 L46,31 C46.001,28.384 43.143,26.002 40.004,26 L40.001,26 C38.472,26 36.928,26.574 35.763,27.575 C34.643,28.537 34,29.786 34,31.001 L34,36 Z M48,31.001 L47.999,36 L50,36 C50.553,36 51,36.448 51,37 L51,52 C51,52.552 50.553,53 50,53 L30,53 C29.447,53 29,52.552 29,52 L29,37 C29,36.448 29.447,36 30,36 L32,36 L32,31 C32.001,29.202 32.897,27.401 34.459,26.058 C35.982,24.75 38.001,24 40.001,24 L40.004,24 C44.265,24.002 48.001,27.273 48,31.001 L48,31.001 Z M19.207,55.049 L20.828,53.877 C18.093,50.097 16.581,45.662 16.396,41 L19,41 L19,39 L16.399,39 C16.598,34.366 18.108,29.957 20.828,26.198 L19.207,25.025 C16.239,29.128 14.599,33.942 14.399,39 L12,39 L12,41 L14.396,41 C14.582,46.086 16.224,50.926 19.207,55.049 L19.207,55.049 Z M53.838,59.208 C50.069,61.936 45.648,63.446 41,63.639 L41,61 L39,61 L39,63.639 C34.352,63.447 29.93,61.937 26.159,59.208 L24.988,60.828 C29.1,63.805 33.928,65.445 39,65.639 L39,68 L41,68 L41,65.639 C46.072,65.445 50.898,63.805 55.01,60.828 L53.838,59.208 Z M26.159,20.866 C29.93,18.138 34.352,16.628 39,16.436 L39,19 L41,19 L41,16.436 C45.648,16.628 50.069,18.138 53.838,20.866 L55.01,19.246 C50.898,16.27 46.072,14.63 41,14.436 L41,12 L39,12 L39,14.436 C33.928,14.629 29.1,16.269 24.988,19.246 L26.159,20.866 Z M65.599,39 C65.399,33.942 63.759,29.128 60.79,25.025 L59.169,26.198 C61.89,29.957 63.4,34.366 63.599,39 L61,39 L61,41 L63.602,41 C63.416,45.662 61.905,50.097 59.169,53.877 L60.79,55.049 C63.774,50.926 65.415,46.086 65.602,41 L68,41 L68,39 L65.599,39 Z M56.386,25.064 L64.226,17.224 L62.812,15.81 L54.972,23.65 L56.386,25.064 Z M23.612,55.01 L15.772,62.85 L17.186,64.264 L25.026,56.424 L23.612,55.01 Z M28.666,27.253 L13.825,12.413 L12.411,13.827 L27.252,28.667 L28.666,27.253 Z M54.193,52.78 L67.586,66.173 L66.172,67.587 L52.779,54.194 L54.193,52.78 Z'
fill='#FFFFFF'

View File

@@ -154,6 +154,7 @@ import {
RootlyIcon,
S3Icon,
SalesforceIcon,
SapS4HanaIcon,
SESIcon,
SearchIcon,
SecretsManagerIcon,
@@ -369,6 +370,7 @@ export const blockTypeToIconMap: Record<string, IconComponent> = {
rootly: RootlyIcon,
s3: S3Icon,
salesforce: SalesforceIcon,
sap_s4hana: SapS4HanaIcon,
search: SearchIcon,
secrets_manager: SecretsManagerIcon,
sendgrid: SendgridIcon,

View File

@@ -25,6 +25,8 @@ Secrets are organized into two sections:
- **Workspace** — shared with all members of your workspace
- **Personal** — private to you
External workspace members count as workspace members for workspace-scoped secrets. They can use workspace secrets according to their workspace permission level, even though they are not members of your organization.
### Adding a Secret
Type a key name (e.g. `OPENAI_API_KEY`) into the **Key** column and its value into the **Value** column in the last empty row. A new empty row appears automatically as you type. Existing values are masked by default.
@@ -89,7 +91,7 @@ Click **Save** to apply changes, or **Back** to return to the list.
| | Workspace | Personal |
|---|---|---|
| **Visibility** | All workspace members | Only you |
| **Visibility** | All workspace members, including external workspace members | Only you |
| **Use in workflows** | Any member can use | Only you can use |
| **Best for** | Production workflows, shared services | Testing, personal API keys |
| **Who can edit** | Workspace admins | Only you |

View File

@@ -130,6 +130,8 @@ Controls visibility of platform features and modules.
Open the group's **Details** view and add members by searching for users by name or email. Only users who already have workspace-level access can be added. A user can only belong to one group per workspace — adding a user to a new group within the same workspace removes them from their current group for that workspace.
External workspace members are treated like other workspace members for access-control purposes. They can be assigned to permission groups in any workspace they have access to, but they do not become organization members or appear in the organization roster.
---
## Enforcement
@@ -159,6 +161,7 @@ When a user opens Mothership, their permission group is read before any block or
- Moving a user to a new group within a workspace automatically removes them from their previous group in that workspace.
- Users not assigned to any group in a workspace have no restrictions applied in that workspace (all blocks, providers, and features are available to them there).
- If **Auto-add new members** is enabled on a group, new members of that workspace are automatically placed in the group. Only one group per workspace can have this setting active.
- External workspace members follow the same per-workspace permission group rules as internal members.
---

View File

@@ -44,7 +44,7 @@ Authorization: Bearer <api-key>
| `resourceType` | string | Filter by resource type (e.g. `workflow`) |
| `resourceId` | string | Filter by a specific resource ID |
| `workspaceId` | string | Filter by workspace |
| `actorId` | string | Filter by user ID (must be an org member) |
| `actorId` | string | Filter by user ID. For organization-wide filters, the actor must be a current or former org member; workspace-scoped logs can also include external workspace members. |
| `startDate` | string | ISO 8601 date — return logs on or after this date |
| `endDate` | string | ISO 8601 date — return logs on or before this date |
| `includeDeparted` | boolean | Include logs from members who have since left the organization (default `false`) |
@@ -98,6 +98,8 @@ Audit log events follow a `resource.action` naming pattern. The table below list
| **Credentials** | `credential.created`, `credential.deleted`, `oauth.disconnected` |
| **Organization** | `organization.updated`, `org_member.added`, `org_member.role_changed` |
Workspace invitation events include whether the invite is for an internal organization member or an external workspace member in their metadata. External workspace members can appear as actors on workspace-scoped events, but they are not organization members and do not appear in the organization roster.
---
<FAQ items={[
@@ -123,7 +125,7 @@ Audit log events follow a `resource.action` naming pattern. The table below list
},
{
question: "Can I filter logs by a specific user?",
answer: "Yes. Pass the actorId query parameter to filter logs by a specific user. The actor must be a current or former member of your organization."
answer: "Yes. Pass the actorId query parameter to filter logs by a specific user. Organization-wide actor filters require the actor to be a current or former member of your organization. Workspace-scoped logs may also include external workspace members who acted inside a workspace without joining the organization."
}
]} />

View File

@@ -13,6 +13,8 @@ Sim Enterprise provides advanced features for organizations with enhanced securi
Define permission groups on a workspace to control what features and integrations its members can use. Permission groups are scoped to a single workspace — a user can belong to different groups (or no group) in different workspaces.
External workspace members can be assigned to permission groups just like internal organization members, but they remain outside the organization roster and do not consume seats.
### Features
- **Allowed Model Providers** - Restrict which AI providers users can access (OpenAI, Anthropic, Google, etc.)
@@ -81,4 +83,4 @@ Self-hosted deployments enable enterprise features via environment variables ins
| `INBOX_ENABLED`, `NEXT_PUBLIC_INBOX_ENABLED` | Sim Mailer inbox |
| `DISABLE_INVITATIONS`, `NEXT_PUBLIC_DISABLE_INVITATIONS` | Disable invitations; manage membership via Admin API |
Once enabled, each feature is configured through the same Settings UI as Sim Cloud. When invitations are disabled, use the Admin API (`x-admin-key` header) to manage organization and workspace membership.
Once enabled, each feature is configured through the same Settings UI as Sim Cloud. When invitations are disabled, use the Admin API (`x-admin-key` header) to manage organization membership and workspace access. Internal members join the organization; external workspace members only receive access to a specific workspace.

View File

@@ -221,6 +221,8 @@ Once SSO is configured, users with your domain (`company.com`) can sign in throu
Users who sign in via SSO for the first time are automatically provisioned and added to your organization — no manual invite required.
SSO provisioning creates internal organization members. External workspace members are different: they are invited to a specific workspace without joining your organization or consuming one of your seats.
<Callout type="info">
Password-based login remains available. Forcing all organization members to use SSO exclusively is not yet supported.
</Callout>
@@ -242,7 +244,7 @@ Users who sign in via SSO for the first time are automatically provisioned and a
},
{
question: "What happens when a user signs in with SSO for the first time?",
answer: "Sim creates an account for them automatically and adds them to your organization. No manual invite is needed. They are assigned the member role by default."
answer: "Sim creates an account for them automatically and adds them to your organization. No manual invite is needed. They are assigned the member role by default. External workspace members are not provisioned through SSO into your organization; they are invited directly to a workspace and remain outside your org roster."
},
{
question: "Can I still use email/password login after enabling SSO?",

View File

@@ -272,6 +272,8 @@ Sim has two paid plan tiers - **Pro** and **Max**. Either can be used individual
To use Pro or Max with a team, select **Get For Team** in subscription settings and choose the tier and number of seats. Credits are pooled across the organization at the per-seat rate (e.g. Max for Teams with 3 seats = 75,000 credits/mo pooled).
Internal organization members use seats and contribute to the team's pooled credit allocation. External workspace members do not join your organization, do not appear in the organization roster, and do not count toward your seat total.
### Daily Refresh Credits
Paid plans include a small daily credit allowance that does not count toward your plan limit. Each day, usage up to the daily refresh amount is excluded from billable usage. This allowance resets every 24 hours and does not carry over - use it or lose it.
@@ -317,7 +319,7 @@ By default, your usage is capped at the credits included in your plan. To allow
| **Max** | Up to 10 | — |
| **Team / Enterprise** | Unlimited | Unlimited |
Team and Enterprise plans unlock shared workspaces that belong to your organization. Members invited to a shared workspace automatically join the organization and count toward your seat total. When a Team or Enterprise subscription is cancelled or downgraded, existing shared workspaces remain accessible to current members but new invites are disabled until the organization is upgraded again.
Team and Enterprise plans unlock shared workspaces that belong to your organization. Internal members invited to a shared workspace join the organization and count toward your seat total. Existing Sim users who already belong to another organization can be added as external workspace members; they get workspace access without joining your organization or using one of your seats. When a Team or Enterprise subscription is cancelled or downgraded, existing shared workspaces remain accessible to current members but new invites are disabled until the organization is upgraded again.
### Rate Limits
@@ -368,7 +370,8 @@ Sim uses a **base subscription + overage** billing model:
- Example: 7,000 credits used = $25 (subscription) + $5 (overage for 1,000 extra credits at $0.005/credit)
**Team Plans:**
- Usage is pooled across all team members in the organization
- Usage is pooled across internal team members in the organization
- External workspace members keep their own organization or personal billing context for runs where they are the billing actor
- Overage is calculated from total team usage against the pooled limit
- Organization owner receives one bill

View File

@@ -42,6 +42,8 @@ Only authorized senders can create tasks. Emails from anyone else are automatica
- **Workspace members** are allowed by default — no setup needed
- **External senders** can be added manually with an optional label for easy identification
External senders are email addresses that can create inbox tasks. They are not the same as external workspace members, who have workspace access in Sim without joining your organization.
Manage your allowed senders list in **Settings** → **Inbox** → **Allowed Senders**.
## Tracking Tasks

View File

@@ -12,7 +12,7 @@ When you invite team members to your organization or workspace, you'll need to c
Sim has two kinds of workspaces:
- **Personal workspaces** live under your individual account. The number you can create depends on your plan.
- **Shared (organization) workspaces** live under an organization and are available on Team and Enterprise plans. Any organization Owner or Admin can create them. Members invited to a shared workspace automatically join the organization and count toward your seat total.
- **Shared (organization) workspaces** live under an organization and are available on Team and Enterprise plans. Any organization Owner or Admin can create them. Internal members invited to a shared workspace join the organization and count toward your seat total. Existing Sim users who already belong to another organization can be added as external workspace members instead, giving them access to the workspace without adding them to your organization roster or using one of your seats.
### Workspace Limits by Plan
@@ -43,6 +43,15 @@ When inviting someone to a workspace, you can assign one of three permission lev
| **Write** | Create and edit workflows, run workflows, manage environment variables |
| **Admin** | Everything Write can do, plus invite/remove users and manage workspace settings |
## Internal Members vs External Workspace Members
Workspace permissions are separate from organization membership:
- **Internal organization members** belong to your organization, appear in the organization roster, and count toward your seat total. Invite new teammates this way when they should be part of your company or team in Sim.
- **External workspace members** have access only to the workspace they are invited to. They keep their own organization membership, do not appear in your organization roster, and do not count toward your organization's seats. Use external access for clients, partners, contractors, or collaborators who already use Sim in another organization.
External workspace members still receive a workspace permission level — Read, Write, or Admin — and that permission controls what they can do inside the workspace.
## What Each Permission Level Can Do
Here's a detailed breakdown of what users can do with each permission level:
@@ -126,7 +135,7 @@ Every workspace has one **Owner** (the person who created it) plus any number of
2. **Workspace level**: Give them **Admin** permission so they can manage the team and see everything
### Adding a Stakeholder or Client
1. **Organization level**: Invite them as an **Organization Member**
1. **Organization level**: If they should not join your organization, add them as an **External workspace member**
2. **Workspace level**: Give them **Read** permission so they can see progress but not make changes
---
@@ -199,12 +208,12 @@ An organization has three roles: **Owner**, **Admin**, and **Member**.
import { FAQ } from '@/components/ui/faq'
<FAQ items={[
{ question: "What is the difference between organization roles and workspace permissions?", answer: "Organization roles (Owner, Admin, or Member) control who can manage the organization itself, including inviting people, creating shared workspaces, and handling billing. Workspace permissions (Read, Write, Admin) control what a user can do within a specific workspace, such as viewing, editing, or managing workflows. A user needs both an organization role and a workspace permission to work within a shared workspace." },
{ question: "What is the difference between organization roles and workspace permissions?", answer: "Organization roles (Owner, Admin, or Member) control who can manage the organization itself, including inviting people, creating shared workspaces, and handling billing. Workspace permissions (Read, Write, Admin) control what a user can do within a specific workspace, such as viewing, editing, or managing workflows. Internal members need both an organization role and a workspace permission to work within a shared workspace. External workspace members do not have an organization role in your org; they only have workspace-level access." },
{ question: "How many workspaces can I create?", answer: "Free users get 1 personal workspace. Pro users get up to 3 personal workspaces. Max users get up to 10 personal workspaces. Team and Enterprise plans support unlimited shared workspaces under the organization — new invites are gated by your seat count." },
{ question: "What happens to my shared workspaces if I cancel or downgrade my Team plan?", answer: "Existing shared workspaces remain accessible to current members, but new invitations are disabled until you upgrade back to a Team or Enterprise plan. No workspaces or members are deleted — the organization is simply dormant until billing is re-enabled." },
{ question: "Can I restrict which integrations or model providers a team member can use?", answer: "Yes, on Enterprise-entitled workspaces. Any workspace admin can create permission groups with fine-grained controls, including restricting allowed integrations and allowed model providers to specific lists. You can also disable access to MCP tools, custom tools, skills, and various platform features like the knowledge base, API keys, or Copilot on a per-group basis. Permission groups are scoped per workspace — a user can belong to different groups in different workspaces." },
{ question: "What happens when a personal environment variable has the same name as a workspace variable?", answer: "The personal environment variable takes priority. When a workflow runs, if both a personal and workspace variable share the same name, the personal value is used. This allows individual users to override shared workspace configuration when needed." },
{ question: "Can an Admin remove the workspace owner?", answer: "No. The workspace owner cannot be removed from the workspace by anyone. Only the workspace owner can delete the workspace or transfer ownership to another user. Admins can do everything else, including inviting and removing other users and managing workspace settings." },
{ question: "What are permission groups and how do they work?", answer: "Permission groups are an Enterprise access control feature that lets workspace admins define granular restrictions beyond the standard Read/Write/Admin roles. Groups are scoped to a single workspace: each user can be in at most one group per workspace, and a user can be in different groups across different workspaces. A permission group can hide UI sections (like trace spans, knowledge base, API keys, or deployment options), disable features (MCP tools, custom tools, skills, invitations), and restrict which integrations and model providers its members can access. Members can be assigned manually, and new members can be auto-added on join. Execution-time enforcement is based on the workflow's workspace, not the user's current UI context." },
{ question: "How should I set up permissions for a new team member?", answer: "Start with the lowest permission level they need. Invite them to the organization as a Member, then add them to the relevant workspace with Read permission if they only need visibility, Write if they need to create and run workflows, or Admin if they need to manage the workspace and its users. You can always increase permissions later." },
{ question: "How should I set up permissions for a new team member?", answer: "Start with the lowest permission level they need. Invite teammates to the organization as Members, then add them to the relevant workspace with Read permission if they only need visibility, Write if they need to create and run workflows, or Admin if they need to manage the workspace and its users. For clients, partners, or users who already belong to another Sim organization, use external workspace access so they can collaborate without joining your organization or consuming a seat." },
]} />

View File

@@ -31,7 +31,7 @@ A quick lookup for everyday actions in the Sim workflow editor. For keyboard sho
</tr>
<tr>
<td>Invite team members</td>
<td>Sidebar → **Invite**</td>
<td>Sidebar → **Invite**. Internal invites join the organization; external workspace members get workspace access only.</td>
<td><ActionVideo src="quick-reference/invite.mp4" alt="Invite team members" /></td>
</tr>
<tr>

View File

@@ -42,9 +42,18 @@ Runs a browser automation task using BrowserUse
| Parameter | Type | Required | Description |
| --------- | ---- | -------- | ----------- |
| `task` | string | Yes | What should the browser agent do |
| `variables` | json | No | Optional variables to use as secrets \(format: \{key: value\}\) |
| `save_browser_data` | boolean | No | Whether to save browser data |
| `model` | string | No | LLM model to use \(default: gpt-4o\) |
| `startUrl` | string | No | Initial page URL to start the agent on \(reduces navigation steps\) |
| `variables` | json | No | Optional secrets injected into the task \(format: \{key: value\}\) |
| `allowedDomains` | string | No | Comma-separated list of domains the agent is allowed to visit |
| `maxSteps` | number | No | Maximum number of steps the agent may take \(default 100, max 10000\) |
| `flashMode` | boolean | No | Enable flash mode \(faster, less careful navigation\) |
| `thinking` | boolean | No | Enable extended reasoning mode |
| `vision` | string | No | Vision capability: "true", "false", or "auto" |
| `systemPromptExtension` | string | No | Optional text appended to the agent system prompt \(max 2000 chars\) |
| `structuredOutput` | string | No | Stringified JSON schema for the structured output |
| `highlightElements` | boolean | No | Highlight interactive elements on the page \(default true\) |
| `metadata` | json | No | Custom key-value metadata \(up to 10 pairs\) for tracking |
| `model` | string | No | LLM model identifier \(e.g. browser-use-2.0\) |
| `apiKey` | string | Yes | API key for BrowserUse API |
| `profile_id` | string | No | Browser profile ID for persistent sessions \(cookies, login state\) |
@@ -54,7 +63,18 @@ Runs a browser automation task using BrowserUse
| --------- | ---- | ----------- |
| `id` | string | Task execution identifier |
| `success` | boolean | Task completion status |
| `output` | json | Task output data |
| `steps` | json | Execution steps taken |
| `output` | json | Final task output \(string or structured\) |
| `steps` | array | Steps the agent executed \(number, memory, nextGoal, url, actions, duration\) |
| ↳ `number` | number | Sequential step number |
| ↳ `memory` | string | Agent memory at this step |
| ↳ `evaluationPreviousGoal` | string | Evaluation of previous goal completion |
| ↳ `nextGoal` | string | Goal for the next step |
| ↳ `url` | string | Current URL of the browser |
| ↳ `screenshotUrl` | string | Optional screenshot URL |
| ↳ `actions` | array | Stringified JSON actions performed |
| ↳ `duration` | number | Step duration in seconds |
| `liveUrl` | string | Embeddable live browser session URL \(active during execution\) |
| `shareUrl` | string | Public shareable URL for the recorded session \(post-run\) |
| `sessionId` | string | Browser Use session identifier |

View File

@@ -150,6 +150,7 @@
"rootly",
"s3",
"salesforce",
"sap_s4hana",
"search",
"secrets_manager",
"sendgrid",

File diff suppressed because it is too large Load Diff

View File

@@ -925,6 +925,139 @@ Create a canvas pinned to a Slack channel as its resource hub
| --------- | ---- | ----------- |
| `canvas_id` | string | ID of the created channel canvas |
### `slack_get_canvas`
Get Slack canvas file metadata by canvas ID
#### Input
| Parameter | Type | Required | Description |
| --------- | ---- | -------- | ----------- |
| `authMethod` | string | No | Authentication method: oauth or bot_token |
| `botToken` | string | No | Bot token for Custom Bot |
| `canvasId` | string | Yes | Canvas file ID to retrieve \(e.g., F1234ABCD\) |
#### Output
| Parameter | Type | Description |
| --------- | ---- | ----------- |
| `canvas` | object | Canvas file information returned by Slack |
| ↳ `id` | string | Unique canvas file identifier |
| ↳ `created` | number | Unix timestamp when the canvas was created |
| ↳ `timestamp` | number | Unix timestamp associated with the canvas |
| ↳ `name` | string | Canvas file name |
| ↳ `title` | string | Canvas title |
| ↳ `mimetype` | string | MIME type of the canvas file |
| ↳ `filetype` | string | Slack file type for the canvas |
| ↳ `pretty_type` | string | Human-readable file type |
| ↳ `user` | string | User ID of the canvas creator |
| ↳ `editable` | boolean | Whether the canvas file is editable |
| ↳ `size` | number | Canvas file size in bytes |
| ↳ `mode` | string | File mode |
| ↳ `is_external` | boolean | Whether the canvas is externally hosted |
| ↳ `is_public` | boolean | Whether the canvas is public |
| ↳ `url_private` | string | Private URL for the canvas file |
| ↳ `url_private_download` | string | Private download URL for the canvas file |
| ↳ `permalink` | string | Permanent URL for the canvas |
| ↳ `channels` | array | Public channel IDs where the canvas appears |
| ↳ `groups` | array | Private channel IDs where the canvas appears |
| ↳ `ims` | array | Direct message IDs where the canvas appears |
| ↳ `canvas_readtime` | number | Approximate read time for canvas content |
| ↳ `is_channel_space` | boolean | Whether this canvas is linked to a channel |
| ↳ `linked_channel_id` | string | Channel ID linked to this canvas |
| ↳ `canvas_creator_id` | string | User ID of the canvas creator |
### `slack_list_canvases`
List Slack canvases available to the authenticated user or bot
#### Input
| Parameter | Type | Required | Description |
| --------- | ---- | -------- | ----------- |
| `authMethod` | string | No | Authentication method: oauth or bot_token |
| `botToken` | string | No | Bot token for Custom Bot |
| `channel` | string | No | Filter canvases appearing in a specific channel ID |
| `count` | number | No | Number of canvases to return per page |
| `page` | number | No | Page number to return |
| `user` | string | No | Filter canvases created by a single user ID |
| `tsFrom` | string | No | Filter canvases created after this Unix timestamp |
| `tsTo` | string | No | Filter canvases created before this Unix timestamp |
| `teamId` | string | No | Encoded team ID, required when using an org-level token |
#### Output
| Parameter | Type | Description |
| --------- | ---- | ----------- |
| `canvases` | array | Canvas file objects returned by Slack |
| ↳ `id` | string | Unique canvas file identifier |
| ↳ `created` | number | Unix timestamp when the canvas was created |
| ↳ `timestamp` | number | Unix timestamp associated with the canvas |
| ↳ `name` | string | Canvas file name |
| ↳ `title` | string | Canvas title |
| ↳ `mimetype` | string | MIME type of the canvas file |
| ↳ `filetype` | string | Slack file type for the canvas |
| ↳ `pretty_type` | string | Human-readable file type |
| ↳ `user` | string | User ID of the canvas creator |
| ↳ `editable` | boolean | Whether the canvas file is editable |
| ↳ `size` | number | Canvas file size in bytes |
| ↳ `mode` | string | File mode |
| ↳ `is_external` | boolean | Whether the canvas is externally hosted |
| ↳ `is_public` | boolean | Whether the canvas is public |
| ↳ `url_private` | string | Private URL for the canvas file |
| ↳ `url_private_download` | string | Private download URL for the canvas file |
| ↳ `permalink` | string | Permanent URL for the canvas |
| ↳ `channels` | array | Public channel IDs where the canvas appears |
| ↳ `groups` | array | Private channel IDs where the canvas appears |
| ↳ `ims` | array | Direct message IDs where the canvas appears |
| ↳ `canvas_readtime` | number | Approximate read time for canvas content |
| ↳ `is_channel_space` | boolean | Whether this canvas is linked to a channel |
| ↳ `linked_channel_id` | string | Channel ID linked to this canvas |
| ↳ `canvas_creator_id` | string | User ID of the canvas creator |
| `paging` | object | Pagination information from Slack |
| ↳ `count` | number | Number of items requested per page |
| ↳ `total` | number | Total number of matching files |
| ↳ `page` | number | Current page number |
| ↳ `pages` | number | Total number of pages |
### `slack_lookup_canvas_sections`
Find Slack canvas section IDs matching criteria for later edits
#### Input
| Parameter | Type | Required | Description |
| --------- | ---- | -------- | ----------- |
| `authMethod` | string | No | Authentication method: oauth or bot_token |
| `botToken` | string | No | Bot token for Custom Bot |
| `canvasId` | string | Yes | Canvas ID to search \(e.g., F1234ABCD\) |
| `criteria` | json | Yes | Section lookup criteria, such as \{"section_types":\["h1"\],"contains_text":"Roadmap"\} |
#### Output
| Parameter | Type | Description |
| --------- | ---- | ----------- |
| `sections` | array | Canvas sections matching the lookup criteria |
| ↳ `id` | string | Canvas section identifier |
### `slack_delete_canvas`
Delete a Slack canvas by its canvas ID
#### Input
| Parameter | Type | Required | Description |
| --------- | ---- | -------- | ----------- |
| `authMethod` | string | No | Authentication method: oauth or bot_token |
| `botToken` | string | No | Bot token for Custom Bot |
| `canvasId` | string | Yes | Canvas ID to delete \(e.g., F1234ABCD\) |
#### Output
| Parameter | Type | Description |
| --------- | ---- | ----------- |
| `ok` | boolean | Whether Slack deleted the canvas successfully |
### `slack_create_conversation`
Create a new public or private channel in a Slack workspace.

View File

@@ -72,6 +72,8 @@ Run an autonomous web agent to complete tasks and extract structured data
| `provider` | string | No | AI provider to use: openai or anthropic |
| `apiKey` | string | Yes | API key for the selected provider |
| `outputSchema` | json | No | Optional JSON schema defining the structure of data the agent should return |
| `mode` | string | No | Agent tool mode: dom \(default\), hybrid, or cua |
| `maxSteps` | number | No | Maximum agent steps \(default 20, max 200\) |
#### Output
@@ -92,5 +94,7 @@ Run an autonomous web agent to complete tasks and extract structured data
| ↳ `timestamp` | number | Unix timestamp when the action was performed |
| ↳ `timeMs` | number | Time in milliseconds \(for wait actions\) |
| `structuredOutput` | object | Extracted data matching the provided output schema |
| `liveViewUrl` | string | Embeddable Browserbase live view URL \(active only while the session is running\) |
| `sessionId` | string | Browserbase session identifier |

View File

@@ -89,6 +89,8 @@ Polling Groups let you monitor multiple team members' Gmail or Outlook inboxes w
Invitees receive an email with a link to connect their account. Once connected, their inbox is automatically included in the polling group. Invitees don't need to be members of your Sim organization.
This is separate from external workspace membership: polling group invitees are granting access to an inbox for a trigger, while external workspace members are collaborators with Read, Write, or Admin access to a workspace.
**Using in a Workflow**
When configuring an email trigger, select your polling group from the credentials dropdown instead of an individual account. The system creates webhooks for each member and routes all emails through your workflow.

View File

@@ -49,7 +49,7 @@ Environment variables store sensitive values like API keys, tokens, and configur
| Scope | Visibility | Use case |
|-------|-----------|----------|
| **Workspace** | All workspace members | Shared API keys, team configuration |
| **Workspace** | All workspace members, including external workspace members | Shared API keys, team configuration |
| **Personal** | Only you | Your personal tokens, dev credentials |
When both a workspace and personal variable share the same key, the workspace value takes precedence.
@@ -84,7 +84,7 @@ If a workflow variable and a block output share the same name, Sim resolves the
<FAQ items={[
{ question: "What's the difference between workflow variables and environment variables?", answer: "Workflow variables store runtime data (text, numbers, objects, arrays) that blocks can read and modify during execution. They use <variable.name> syntax. Environment variables store sensitive configuration like API keys using {{KEY}} syntax. They never appear in logs and are managed at the workspace or personal level." },
{ question: "Can I use environment variables in the Function block?", answer: "Yes. Use the double curly brace syntax {{KEY}} directly in your code. The value is substituted before execution, so the actual secret never appears in logs or outputs." },
{ question: "How do I share an API key with my team?", answer: "Create a workspace-scoped environment variable in Settings → Secrets. All workspace members will be able to use it in their workflows via {{KEY}} syntax." },
{ question: "How do I share an API key with my team?", answer: "Create a workspace-scoped environment variable in Settings → Secrets. All workspace members, including external workspace members, will be able to use it in their workflows via {{KEY}} syntax." },
{ question: "What happens if a variable name has spaces or mixed case?", answer: "Variable resolution is case-insensitive and ignores spaces. A variable named 'My Counter' can be referenced as <variable.mycounter> or <variable.My Counter>. However, using consistent naming (like camelCase) is recommended." },
{ question: "Can I reference environment variables in the Agent system prompt?", answer: "Yes. You can use {{KEY}} syntax in any text field, including system prompts, to inject environment variable values." },
]} />

View File

@@ -154,6 +154,7 @@ import {
RootlyIcon,
S3Icon,
SalesforceIcon,
SapS4HanaIcon,
SESIcon,
SearchIcon,
SecretsManagerIcon,
@@ -351,6 +352,7 @@ export const blockTypeToIconMap: Record<string, IconComponent> = {
rootly: RootlyIcon,
s3: S3Icon,
salesforce: SalesforceIcon,
sap_s4hana: SapS4HanaIcon,
search: SearchIcon,
secrets_manager: SecretsManagerIcon,
sendgrid: SendgridIcon,

View File

@@ -11379,6 +11379,177 @@
"integrationTypes": ["crm", "customer-support", "sales"],
"tags": ["sales-engagement", "customer-support"]
},
{
"type": "sap_s4hana",
"slug": "sap-s-4hana",
"name": "SAP S/4HANA",
"description": "Read and write SAP S/4HANA Cloud business data via OData",
"longDescription": "Connect SAP S/4HANA Cloud Public Edition with per-tenant OAuth 2.0 client credentials configured in your Communication Arrangements. Read and create business partners, customers, suppliers, sales orders, deliveries (inbound/outbound), billing documents, products, stock and material documents, purchase requisitions, purchase orders, and supplier invoices, or run arbitrary OData v2 queries against any whitelisted Communication Scenario.",
"bgColor": "#0A6ED1",
"iconName": "SapS4HanaIcon",
"docsUrl": "https://docs.sim.ai/tools/sap_s4hana",
"operations": [
{
"name": "List Business Partners",
"description": "List business partners from SAP S/4HANA Cloud (API_BUSINESS_PARTNER, A_BusinessPartner) with optional OData $filter, $top, $skip, $orderby, $select, $expand."
},
{
"name": "Get Business Partner",
"description": "Retrieve a single business partner by BusinessPartner key from SAP S/4HANA Cloud (API_BUSINESS_PARTNER, A_BusinessPartner)."
},
{
"name": "Create Business Partner",
"description": "Create a business partner in SAP S/4HANA Cloud (API_BUSINESS_PARTNER, A_BusinessPartner). For Person category 1 provide FirstName and LastName. For Organization category 2 provide OrganizationBPName1."
},
{
"name": "Update Business Partner",
"description": "Update fields on an A_BusinessPartner entity in SAP S/4HANA Cloud (API_BUSINESS_PARTNER). PATCH only sends the fields you provide; existing values are preserved. If-Match defaults to a wildcard (unconditional) — for safe concurrent updates pass the ETag from a prior GET to avoid lost updates."
},
{
"name": "List Customers",
"description": "List customers from SAP S/4HANA Cloud (API_BUSINESS_PARTNER, A_Customer) with optional OData $filter, $top, $skip, $orderby, $select, $expand."
},
{
"name": "Get Customer",
"description": "Retrieve a single customer by Customer key from SAP S/4HANA Cloud (API_BUSINESS_PARTNER, A_Customer)."
},
{
"name": "Update Customer",
"description": "Update fields on an A_Customer entity in SAP S/4HANA Cloud (API_BUSINESS_PARTNER). PATCH only sends the fields you provide; existing values are preserved. A_Customer PATCH is limited to modifiable fields such as OrderIsBlockedForCustomer, DeliveryIsBlock, BillingIsBlockedForCustomer, PostingIsBlocked, and DeletionIndicator. If-Match defaults to a wildcard - for safe concurrent updates pass the ETag from a prior GET to avoid lost updates."
},
{
"name": "List Suppliers",
"description": "List suppliers from SAP S/4HANA Cloud (API_BUSINESS_PARTNER, A_Supplier) with optional OData $filter, $top, $skip, $orderby, $select, $expand."
},
{
"name": "Get Supplier",
"description": "Retrieve a single supplier by Supplier key from SAP S/4HANA Cloud (API_BUSINESS_PARTNER, A_Supplier)."
},
{
"name": "Update Supplier",
"description": "Update fields on an A_Supplier entity in SAP S/4HANA Cloud (API_BUSINESS_PARTNER). PATCH only sends the fields you provide; existing values are preserved. A_Supplier PATCH is limited to modifiable fields such as PostingIsBlocked, PurchasingIsBlocked, PaymentIsBlockedForSupplier, DeletionIndicator, and SupplierAccountGroup. If-Match defaults to a wildcard - for safe concurrent updates pass the ETag from a prior GET to avoid lost updates."
},
{
"name": "List Sales Orders",
"description": "List sales orders from SAP S/4HANA Cloud (API_SALES_ORDER_SRV, A_SalesOrder) with optional OData $filter, $top, $skip, $orderby, $select, $expand."
},
{
"name": "Get Sales Order",
"description": "Retrieve a single sales order by SalesOrder key from SAP S/4HANA Cloud (API_SALES_ORDER_SRV, A_SalesOrder)."
},
{
"name": "Create Sales Order",
"description": "Create a sales order in SAP S/4HANA Cloud (API_SALES_ORDER_SRV, A_SalesOrder) with deep insert of sales order items via to_Item."
},
{
"name": "Update Sales Order",
"description": "Update fields on an A_SalesOrder entity in SAP S/4HANA Cloud (API_SALES_ORDER_SRV). PATCH only sends the fields you provide; existing values are preserved. If-Match defaults to a wildcard (unconditional) — for safe concurrent updates pass the ETag from a prior GET to avoid lost updates."
},
{
"name": "Delete Sales Order",
"description": "Delete an A_SalesOrder entity in SAP S/4HANA Cloud (API_SALES_ORDER_SRV). Only orders without subsequent documents (deliveries, invoices) can be deleted; otherwise reject items via update instead."
},
{
"name": "List Outbound Deliveries",
"description": "List outbound deliveries from SAP S/4HANA Cloud (API_OUTBOUND_DELIVERY_SRV;v=0002, A_OutbDeliveryHeader) with optional OData $filter, $top, $skip, $orderby, $select, $expand."
},
{
"name": "Get Outbound Delivery",
"description": "Retrieve a single outbound delivery by DeliveryDocument key from SAP S/4HANA Cloud (API_OUTBOUND_DELIVERY_SRV;v=0002, A_OutbDeliveryHeader)."
},
{
"name": "List Inbound Deliveries",
"description": "List inbound deliveries from SAP S/4HANA Cloud (API_INBOUND_DELIVERY_SRV;v=0002, A_InbDeliveryHeader) with optional OData $filter, $top, $skip, $orderby, $select, $expand."
},
{
"name": "Get Inbound Delivery",
"description": "Retrieve a single inbound delivery by DeliveryDocument key from SAP S/4HANA Cloud (API_INBOUND_DELIVERY_SRV;v=0002, A_InbDeliveryHeader)."
},
{
"name": "List Billing Documents",
"description": "List billing documents (customer invoices) from SAP S/4HANA Cloud (API_BILLING_DOCUMENT_SRV, A_BillingDocument) with optional OData $filter, $top, $skip, $orderby, $select, $expand."
},
{
"name": "Get Billing Document",
"description": "Retrieve a single billing document (customer invoice) by BillingDocument key from SAP S/4HANA Cloud (API_BILLING_DOCUMENT_SRV, A_BillingDocument)."
},
{
"name": "List Products",
"description": "List products (materials) from SAP S/4HANA Cloud (API_PRODUCT_SRV, A_Product) with optional OData $filter, $top, $skip, $orderby, $select, $expand."
},
{
"name": "Get Product",
"description": "Retrieve a single product (material) by Product key from SAP S/4HANA Cloud (API_PRODUCT_SRV, A_Product)."
},
{
"name": "Update Product",
"description": "Update fields on an A_Product entity in SAP S/4HANA Cloud (API_PRODUCT_SRV). PATCH only sends the fields you provide; existing values are preserved. Flat scalar header fields only — deep/multi-entity updates across navigation properties are not supported by API_PRODUCT_SRV PATCH/PUT (see SAP KBA 2833338); update child entities (plant, valuation, sales data, etc.) via their own endpoints. If-Match defaults to a wildcard (unconditional) — for safe concurrent updates pass the ETag from a prior GET."
},
{
"name": "List Material Stock",
"description": "List material stock quantities from SAP S/4HANA Cloud (API_MATERIAL_STOCK_SRV, A_MatlStkInAcctMod). The entity uses an 11-field composite key (Material, Plant, StorageLocation, Batch, Supplier, Customer, WBSElementInternalID, SDDocument, SDDocumentItem, InventorySpecialStockType, InventoryStockType) — query with $filter on these fields instead of a direct key lookup."
},
{
"name": "List Material Documents",
"description": "List material document headers (goods movements) from SAP S/4HANA Cloud (API_MATERIAL_DOCUMENT_SRV, A_MaterialDocumentHeader) with optional OData $filter, $top, $skip, $orderby, $select, $expand."
},
{
"name": "Get Material Document",
"description": "Retrieve a single material document header by composite key (MaterialDocument + MaterialDocumentYear) from SAP S/4HANA Cloud (API_MATERIAL_DOCUMENT_SRV, A_MaterialDocumentHeader)."
},
{
"name": "List Purchase Requisitions",
"description": "List purchase requisitions from SAP S/4HANA Cloud (API_PURCHASEREQ_PROCESS_SRV, A_PurchaseRequisitionHeader) with optional OData $filter, $top, $skip, $orderby, $select, $expand. Note: API_PURCHASEREQ_PROCESS_SRV is deprecated since S/4HANA Cloud Public Edition 2402; the successor is API_PURCHASEREQUISITION_2 (OData v4). This tool still works against tenants where the legacy service is enabled."
},
{
"name": "Get Purchase Requisition",
"description": "Retrieve a single purchase requisition by PurchaseRequisition key from SAP S/4HANA Cloud (API_PURCHASEREQ_PROCESS_SRV, A_PurchaseRequisitionHeader). Note: API_PURCHASEREQ_PROCESS_SRV is deprecated since S/4HANA Cloud Public Edition 2402; the successor is API_PURCHASEREQUISITION_2 (OData v4). This tool still works against tenants where the legacy service is enabled."
},
{
"name": "Create Purchase Requisition",
"description": "Create a purchase requisition in SAP S/4HANA Cloud (API_PURCHASEREQ_PROCESS_SRV, A_PurchaseRequisitionHeader). PurchaseRequisition is auto-assigned by SAP from the document number range; provide line items via the to_PurchaseReqnItem deep-insert array. Note: API_PURCHASEREQ_PROCESS_SRV is deprecated since S/4HANA Cloud Public Edition 2402; the successor is API_PURCHASEREQUISITION_2 (OData v4). This tool still works against tenants where the legacy service is enabled."
},
{
"name": "Update Purchase Requisition",
"description": "Update fields on an A_PurchaseRequisitionHeader entity in SAP S/4HANA Cloud (API_PURCHASEREQ_PROCESS_SRV; deprecated since S/4HANA 2402, successor is API_PURCHASEREQUISITION_2 OData v4). PATCH only sends the fields you provide; existing values are preserved. If-Match defaults to a wildcard - for safe concurrent updates pass the ETag from a prior GET to avoid lost updates."
},
{
"name": "List Purchase Orders",
"description": "List purchase orders from SAP S/4HANA Cloud (API_PURCHASEORDER_PROCESS_SRV, A_PurchaseOrder) with optional OData $filter, $top, $skip, $orderby, $select, $expand."
},
{
"name": "Get Purchase Order",
"description": "Retrieve a single purchase order by PurchaseOrder key from SAP S/4HANA Cloud (API_PURCHASEORDER_PROCESS_SRV, A_PurchaseOrder)."
},
{
"name": "Create Purchase Order",
"description": "Create a purchase order in SAP S/4HANA Cloud (API_PURCHASEORDER_PROCESS_SRV, A_PurchaseOrder). PurchaseOrder is auto-assigned by SAP from the document number range; provide line items via the body parameter."
},
{
"name": "Update Purchase Order",
"description": "Update fields on an A_PurchaseOrder entity in SAP S/4HANA Cloud (API_PURCHASEORDER_PROCESS_SRV). PATCH only sends the fields you provide; existing values are preserved. If-Match defaults to a wildcard (unconditional) — for safe concurrent updates pass the ETag from a prior GET to avoid lost updates."
},
{
"name": "List Supplier Invoices",
"description": "List supplier invoices from SAP S/4HANA Cloud (API_SUPPLIERINVOICE_PROCESS_SRV, A_SupplierInvoice) with optional OData $filter, $top, $skip, $orderby, $select, $expand."
},
{
"name": "Get Supplier Invoice",
"description": "Retrieve a single supplier invoice by composite key (SupplierInvoice + FiscalYear) from SAP S/4HANA Cloud (API_SUPPLIERINVOICE_PROCESS_SRV, A_SupplierInvoice)."
},
{
"name": "OData Query (advanced)",
"description": "Make an arbitrary OData v2 call against any SAP S/4HANA Cloud whitelisted Communication Scenario. Use when no dedicated tool exists for the entity. The proxy handles auth, CSRF, and OData unwrapping."
}
],
"operationCount": 38,
"triggers": [],
"triggerCount": 0,
"authType": "none",
"category": "tools",
"integrationTypes": ["other", "developer-tools"],
"tags": ["automation"]
},
{
"type": "search",
"slug": "search",
@@ -11983,6 +12154,22 @@
"name": "Create Channel Canvas",
"description": "Create a canvas pinned to a Slack channel as its resource hub"
},
{
"name": "Get Canvas Info",
"description": "Get Slack canvas file metadata by canvas ID"
},
{
"name": "List Canvases",
"description": "List Slack canvases available to the authenticated user or bot"
},
{
"name": "Lookup Canvas Sections",
"description": "Find Slack canvas section IDs matching criteria for later edits"
},
{
"name": "Delete Canvas",
"description": "Delete a Slack canvas by its canvas ID"
},
{
"name": "Create Conversation",
"description": "Create a new public or private channel in a Slack workspace."
@@ -12008,7 +12195,7 @@
"description": "Publish a static view to a user"
}
],
"operationCount": 25,
"operationCount": 29,
"triggers": [
{
"id": "slack_webhook",

View File

@@ -16,6 +16,14 @@ function getMothershipUrl(environment: string): string | null {
return ENV_URLS[environment] ?? null
}
const ENDPOINT_PATTERN = /^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/
function isValidEndpoint(endpoint: string): boolean {
if (!endpoint) return false
if (endpoint.includes('..')) return false
return ENDPOINT_PATTERN.test(endpoint)
}
async function isAdminRequestAuthorized() {
const session = await getSession()
if (!session?.user?.id) return false
@@ -57,6 +65,10 @@ export const POST = withRouteHandler(async (req: NextRequest) => {
return NextResponse.json({ error: 'endpoint query param required' }, { status: 400 })
}
if (!isValidEndpoint(endpoint)) {
return NextResponse.json({ error: 'invalid endpoint' }, { status: 400 })
}
const baseUrl = getMothershipUrl(environment)
if (!baseUrl) {
return NextResponse.json(
@@ -108,6 +120,10 @@ export const GET = withRouteHandler(async (req: NextRequest) => {
return NextResponse.json({ error: 'endpoint query param required' }, { status: 400 })
}
if (!isValidEndpoint(endpoint)) {
return NextResponse.json({ error: 'invalid endpoint' }, { status: 400 })
}
const baseUrl = getMothershipUrl(environment)
if (!baseUrl) {
return NextResponse.json(

View File

@@ -112,6 +112,16 @@ vi.mock('@/lib/core/storage', () => ({
getStorageMethod: mockGetStorageMethod,
}))
const { mockCheckRateLimitDirect } = vi.hoisted(() => ({
mockCheckRateLimitDirect: vi.fn(),
}))
vi.mock('@/lib/core/rate-limiter', () => ({
RateLimiter: class {
checkRateLimitDirect = mockCheckRateLimitDirect
},
}))
vi.mock('@/lib/messaging/email/mailer', () => ({
sendEmail: mockSendEmail,
}))
@@ -234,6 +244,13 @@ describe('Chat OTP API Route', () => {
}))
requestUtilsMockFns.mockGenerateRequestId.mockReturnValue('req-123')
requestUtilsMockFns.mockGetClientIp.mockReturnValue('1.2.3.4')
mockCheckRateLimitDirect.mockResolvedValue({
allowed: true,
remaining: 10,
resetAt: new Date(Date.now() + 60_000),
})
mockZodParse.mockImplementation((data: unknown) => data)
@@ -283,6 +300,134 @@ describe('Chat OTP API Route', () => {
})
})
describe('POST - Rate limiting', () => {
const buildDeploymentSelect = () =>
mockDbSelect.mockImplementationOnce(() => ({
from: vi.fn().mockReturnValue({
where: vi.fn().mockReturnValue({
limit: vi.fn().mockResolvedValue([
{
id: mockChatId,
authType: 'email',
allowedEmails: [mockEmail],
title: 'Test Chat',
},
]),
}),
}),
}))
it('returns 429 with Retry-After when IP rate limit is exceeded', async () => {
mockCheckRateLimitDirect.mockResolvedValueOnce({
allowed: false,
remaining: 0,
resetAt: new Date(Date.now() + 900_000),
retryAfterMs: 900_000,
})
const headerSet = vi.fn()
mockCreateErrorResponse.mockImplementationOnce((message: string, status: number) => ({
json: () => Promise.resolve({ error: message }),
status,
headers: { set: headerSet },
}))
const request = new NextRequest('http://localhost:3000/api/chat/test/otp', {
method: 'POST',
body: JSON.stringify({ email: mockEmail }),
})
const response = await POST(request, {
params: Promise.resolve({ identifier: mockIdentifier }),
})
expect(response.status).toBe(429)
expect(headerSet).toHaveBeenCalledWith('Retry-After', '900')
expect(mockSendEmail).not.toHaveBeenCalled()
expect(mockDbSelect).not.toHaveBeenCalled()
})
it('returns 429 with Retry-After when email rate limit is exceeded', async () => {
mockCheckRateLimitDirect
.mockResolvedValueOnce({
allowed: true,
remaining: 9,
resetAt: new Date(Date.now() + 60_000),
})
.mockResolvedValueOnce({
allowed: false,
remaining: 0,
resetAt: new Date(Date.now() + 900_000),
retryAfterMs: 900_000,
})
const headerSet = vi.fn()
mockCreateErrorResponse.mockImplementationOnce((message: string, status: number) => ({
json: () => Promise.resolve({ error: message }),
status,
headers: { set: headerSet },
}))
buildDeploymentSelect()
const request = new NextRequest('http://localhost:3000/api/chat/test/otp', {
method: 'POST',
body: JSON.stringify({ email: mockEmail }),
})
const response = await POST(request, {
params: Promise.resolve({ identifier: mockIdentifier }),
})
expect(response.status).toBe(429)
expect(headerSet).toHaveBeenCalledWith('Retry-After', '900')
expect(mockSendEmail).not.toHaveBeenCalled()
})
it('falls back to refill interval when retryAfterMs is missing', async () => {
mockCheckRateLimitDirect.mockResolvedValueOnce({
allowed: false,
remaining: 0,
resetAt: new Date(Date.now() + 900_000),
})
const headerSet = vi.fn()
mockCreateErrorResponse.mockImplementationOnce((message: string, status: number) => ({
json: () => Promise.resolve({ error: message }),
status,
headers: { set: headerSet },
}))
const request = new NextRequest('http://localhost:3000/api/chat/test/otp', {
method: 'POST',
body: JSON.stringify({ email: mockEmail }),
})
await POST(request, { params: Promise.resolve({ identifier: mockIdentifier }) })
expect(headerSet).toHaveBeenCalledWith('Retry-After', '900')
})
it('skips IP rate limit when client IP is unknown', async () => {
requestUtilsMockFns.mockGetClientIp.mockReturnValueOnce('unknown')
buildDeploymentSelect()
const request = new NextRequest('http://localhost:3000/api/chat/test/otp', {
method: 'POST',
body: JSON.stringify({ email: mockEmail }),
})
await POST(request, { params: Promise.resolve({ identifier: mockIdentifier }) })
// Only the email-scoped check should run, not the IP-scoped one
expect(mockCheckRateLimitDirect).toHaveBeenCalledTimes(1)
expect(mockCheckRateLimitDirect).toHaveBeenCalledWith(
expect.stringContaining('chat-otp:email:'),
expect.any(Object)
)
})
})
describe('POST - Store OTP (Database path)', () => {
beforeEach(() => {
mockGetStorageMethod.mockReturnValue('database')

View File

@@ -8,9 +8,11 @@ import type { NextRequest } from 'next/server'
import { z } from 'zod'
import { renderOTPEmail } from '@/components/emails'
import { getRedisClient } from '@/lib/core/config/redis'
import type { TokenBucketConfig } from '@/lib/core/rate-limiter'
import { RateLimiter } from '@/lib/core/rate-limiter'
import { addCorsHeaders, isEmailAllowed } from '@/lib/core/security/deployment'
import { getStorageMethod } from '@/lib/core/storage'
import { generateRequestId } from '@/lib/core/utils/request'
import { generateRequestId, getClientIp } from '@/lib/core/utils/request'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { sendEmail } from '@/lib/messaging/email/mailer'
import { setChatAuthCookie } from '@/app/api/chat/utils'
@@ -18,6 +20,20 @@ import { createErrorResponse, createSuccessResponse } from '@/app/api/workflows/
const logger = createLogger('ChatOtpAPI')
const rateLimiter = new RateLimiter()
const OTP_IP_RATE_LIMIT: TokenBucketConfig = {
maxTokens: 10,
refillRate: 10,
refillIntervalMs: 15 * 60_000,
}
const OTP_EMAIL_RATE_LIMIT: TokenBucketConfig = {
maxTokens: 3,
refillRate: 3,
refillIntervalMs: 15 * 60_000,
}
function generateOTP(): string {
return randomInt(100000, 1000000).toString()
}
@@ -214,6 +230,23 @@ export const POST = withRouteHandler(
const requestId = generateRequestId()
try {
const ip = getClientIp(request)
if (ip !== 'unknown') {
const ipRateLimit = await rateLimiter.checkRateLimitDirect(
`chat-otp:ip:${identifier}:${ip}`,
OTP_IP_RATE_LIMIT
)
if (!ipRateLimit.allowed) {
logger.warn(`[${requestId}] OTP IP rate limit exceeded for ${identifier} from ${ip}`)
const retryAfter = Math.ceil(
(ipRateLimit.retryAfterMs ?? OTP_IP_RATE_LIMIT.refillIntervalMs) / 1000
)
const response = createErrorResponse('Too many requests. Please try again later.', 429)
response.headers.set('Retry-After', String(retryAfter))
return addCorsHeaders(response, request)
}
}
const body = await request.json()
const { email } = otpRequestSchema.parse(body)
@@ -255,6 +288,25 @@ export const POST = withRouteHandler(
)
}
const emailRateLimit = await rateLimiter.checkRateLimitDirect(
`chat-otp:email:${deployment.id}:${email.toLowerCase()}`,
OTP_EMAIL_RATE_LIMIT
)
if (!emailRateLimit.allowed) {
logger.warn(
`[${requestId}] OTP email rate limit exceeded for ${email} on chat ${deployment.id}`
)
const retryAfter = Math.ceil(
(emailRateLimit.retryAfterMs ?? OTP_EMAIL_RATE_LIMIT.refillIntervalMs) / 1000
)
const response = createErrorResponse(
'Too many verification code requests. Please try again later.',
429
)
response.headers.set('Retry-After', String(retryAfter))
return addCorsHeaders(response, request)
}
const otp = generateOTP()
await storeOTP(email, deployment.id, otp)

View File

@@ -1,10 +1,7 @@
import { createLogger } from '@sim/logger'
import { type NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import {
authenticateCopilotRequestSessionOnly,
createUnauthorizedResponse,
} from '@/lib/copilot/request/http'
import { checkInternalApiKey, createUnauthorizedResponse } from '@/lib/copilot/request/http'
import { env } from '@/lib/core/config/env'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
@@ -21,8 +18,8 @@ const TrainingExampleSchema = z.object({
})
export const POST = withRouteHandler(async (request: NextRequest) => {
const { userId, isAuthenticated } = await authenticateCopilotRequestSessionOnly()
if (!isAuthenticated || !userId) {
const auth = checkInternalApiKey(request)
if (!auth.success) {
return createUnauthorizedResponse()
}

View File

@@ -1,10 +1,7 @@
import { createLogger } from '@sim/logger'
import { type NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import {
authenticateCopilotRequestSessionOnly,
createUnauthorizedResponse,
} from '@/lib/copilot/request/http'
import { checkInternalApiKey, createUnauthorizedResponse } from '@/lib/copilot/request/http'
import { env } from '@/lib/core/config/env'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
@@ -27,8 +24,8 @@ const TrainingDataSchema = z.object({
})
export const POST = withRouteHandler(async (request: NextRequest) => {
const { userId, isAuthenticated } = await authenticateCopilotRequestSessionOnly()
if (!isAuthenticated || !userId) {
const auth = checkInternalApiKey(request)
if (!auth.success) {
return createUnauthorizedResponse()
}

View File

@@ -191,7 +191,7 @@ describe('Function Execute API Route', () => {
const response = await POST(req)
const data = await response.json()
if (response.status === 500) {
if (response.status === 422 || response.status === 500) {
expect(data.success).toBe(false)
} else {
const result = data.output?.result
@@ -504,7 +504,7 @@ describe('Function Execute API Route', () => {
const response = await POST(req)
const data = await response.json()
expect(response.status).toBe(500)
expect(response.status).toBe(422)
expect(data.success).toBe(false)
expect(data.error).toBeTruthy()
})
@@ -518,7 +518,7 @@ describe('Function Execute API Route', () => {
const response = await POST(req)
const data = await response.json()
expect(response.status).toBe(500)
expect(response.status).toBe(422)
expect(data.success).toBe(false)
expect(data.error).toContain('Type Error')
expect(data.error).toContain('Cannot read properties of null')
@@ -533,7 +533,7 @@ describe('Function Execute API Route', () => {
const response = await POST(req)
const data = await response.json()
expect(response.status).toBe(500)
expect(response.status).toBe(422)
expect(data.success).toBe(false)
expect(data.error).toContain('Reference Error')
expect(data.error).toContain('undefinedVariable is not defined')
@@ -548,7 +548,7 @@ describe('Function Execute API Route', () => {
const response = await POST(req)
const data = await response.json()
expect(response.status).toBe(500)
expect(response.status).toBe(422)
expect(data.success).toBe(false)
expect(data.error).toContain('Custom error message')
})
@@ -562,7 +562,7 @@ describe('Function Execute API Route', () => {
const response = await POST(req)
const data = await response.json()
expect(response.status).toBe(500)
expect(response.status).toBe(422)
expect(data.success).toBe(false)
expect(data.error).toBeTruthy()
})

View File

@@ -1088,9 +1088,12 @@ export const POST = withRouteHandler(async (req: NextRequest) => {
const executionTime = Date.now() - startTime
if (isolatedResult.error) {
logger.error(`[${requestId}] Function execution failed in isolated-vm`, {
const isSystemError = isolatedResult.error.isSystemError === true
const logFn = isSystemError ? logger.error.bind(logger) : logger.warn.bind(logger)
logFn(`[${requestId}] Function execution failed in isolated-vm`, {
error: isolatedResult.error,
executionTime,
isSystemError,
})
const ivmError = isolatedResult.error
@@ -1119,7 +1122,8 @@ export const POST = withRouteHandler(async (req: NextRequest) => {
resolvedCode
)
logger.error(`[${requestId}] Enhanced error details`, {
const detailLogFn = isSystemError ? logger.error.bind(logger) : logger.warn.bind(logger)
detailLogFn(`[${requestId}] Enhanced error details`, {
originalMessage: ivmError.message,
enhancedMessage: userFriendlyErrorMessage,
line: enhancedError.line,
@@ -1145,7 +1149,7 @@ export const POST = withRouteHandler(async (req: NextRequest) => {
stack: enhancedError.stack,
},
},
{ status: 500 }
{ status: isSystemError ? 500 : 422 }
)
}

View File

@@ -146,6 +146,7 @@ export const POST = withRouteHandler(
targetEmail: inv.email,
targetRole: inv.role,
kind: inv.kind,
membershipIntent: inv.membershipIntent,
},
request,
})

View File

@@ -54,6 +54,7 @@ export const GET = withRouteHandler(
email: inv.email,
organizationId: inv.organizationId,
organizationName: inv.organizationName,
membershipIntent: inv.membershipIntent,
role: inv.role,
status: inv.status,
expiresAt: inv.expiresAt,
@@ -121,6 +122,12 @@ export const PATCH = withRouteHandler(
const { role, grants } = parsed.data
if (role !== undefined) {
if (inv.membershipIntent === 'external') {
return NextResponse.json(
{ error: 'Role updates are not valid on external workspace invitations' },
{ status: 400 }
)
}
if (!inv.organizationId) {
return NextResponse.json(
{ error: 'Role updates are only valid on organization-scoped invitations' },
@@ -187,6 +194,7 @@ export const PATCH = withRouteHandler(
invitationId: id,
targetEmail: inv.email,
kind: inv.kind,
membershipIntent: inv.membershipIntent,
roleUpdate: role ?? null,
grantUpdates: grantsToApply,
},

View File

@@ -8,7 +8,11 @@ import { z } from 'zod'
import { getSession } from '@/lib/auth'
import { setActiveOrganizationForCurrentSession } from '@/lib/auth/active-organization'
import { getUserUsageData } from '@/lib/billing/core/usage'
import { removeUserFromOrganization } from '@/lib/billing/organizations/membership'
import {
removeExternalUserFromOrganizationWorkspaces,
removeUserFromOrganization,
} from '@/lib/billing/organizations/membership'
import { reduceOrganizationSeatsByOne } from '@/lib/billing/organizations/seats'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
const logger = createLogger('OrganizationMemberAPI')
@@ -282,6 +286,7 @@ export const DELETE = withRouteHandler(
}
const { id: organizationId, memberId: targetUserId } = await params
const shouldReduceSeats = request.nextUrl.searchParams.get('shouldReduceSeats') === 'true'
const userMember = await db
.select()
@@ -311,7 +316,79 @@ export const DELETE = withRouteHandler(
.limit(1)
if (targetMember.length === 0) {
return NextResponse.json({ error: 'Member not found' }, { status: 404 })
const [targetUser] = await db
.select({ id: user.id, email: user.email, name: user.name })
.from(user)
.where(eq(user.id, targetUserId))
.limit(1)
if (!targetUser) {
return NextResponse.json({ error: 'Member not found' }, { status: 404 })
}
const externalResult = await removeExternalUserFromOrganizationWorkspaces({
userId: targetUserId,
organizationId,
})
if (!externalResult.success) {
const error = externalResult.error || 'External workspace member not found'
const status =
error === 'External workspace member not found'
? 404
: error === 'User is an organization member'
? 409
: 500
return NextResponse.json({ error }, { status })
}
logger.info('External workspace member removed from organization workspaces', {
organizationId,
removedMemberId: targetUserId,
removedBy: session.user.id,
workspaceAccessRevoked: externalResult.workspaceAccessRevoked,
permissionGroupsRevoked: externalResult.permissionGroupsRevoked,
credentialMembershipsRevoked: externalResult.credentialMembershipsRevoked,
pendingInvitationsCancelled: externalResult.pendingInvitationsCancelled,
})
recordAudit({
workspaceId: null,
actorId: session.user.id,
action: AuditAction.ORG_MEMBER_REMOVED,
resourceType: AuditResourceType.ORGANIZATION,
resourceId: organizationId,
actorName: session.user.name ?? undefined,
actorEmail: session.user.email ?? undefined,
description: `Removed external workspace member ${targetUserId} from organization`,
metadata: {
targetUserId,
targetEmail: targetUser.email ?? undefined,
targetName: targetUser.name ?? undefined,
membershipType: 'external',
workspaceAccessRevoked: externalResult.workspaceAccessRevoked,
permissionGroupsRevoked: externalResult.permissionGroupsRevoked,
credentialMembershipsRevoked: externalResult.credentialMembershipsRevoked,
pendingInvitationsCancelled: externalResult.pendingInvitationsCancelled,
},
request,
})
return NextResponse.json({
success: true,
message: 'External member removed successfully',
data: {
removedMemberId: targetUserId,
removedBy: session.user.id,
removedAt: new Date().toISOString(),
membershipType: 'external',
workspaceAccessRevoked: externalResult.workspaceAccessRevoked,
permissionGroupsRevoked: externalResult.permissionGroupsRevoked,
credentialMembershipsRevoked: externalResult.credentialMembershipsRevoked,
pendingInvitationsCancelled: externalResult.pendingInvitationsCancelled,
},
})
}
const result = await removeUserFromOrganization({
@@ -330,6 +407,28 @@ export const DELETE = withRouteHandler(
return NextResponse.json({ error: result.error }, { status: 500 })
}
let seatReduction: Awaited<ReturnType<typeof reduceOrganizationSeatsByOne>> | null = null
if (shouldReduceSeats && session.user.id !== targetUserId) {
try {
seatReduction = await reduceOrganizationSeatsByOne({
organizationId,
actorUserId: session.user.id,
removedUserId: targetUserId,
})
} catch (seatError) {
logger.error('Failed to reduce seats after member removal', {
organizationId,
removedMemberId: targetUserId,
removedBy: session.user.id,
error: seatError,
})
seatReduction = {
reduced: false,
reason: 'Failed to reduce seats after member removal',
}
}
}
if (session.user.id === targetUserId) {
try {
await setActiveOrganizationForCurrentSession(null)
@@ -348,6 +447,7 @@ export const DELETE = withRouteHandler(
removedBy: session.user.id,
wasSelfRemoval: session.user.id === targetUserId,
billingActions: result.billingActions,
seatReduction,
})
recordAudit({
@@ -367,6 +467,7 @@ export const DELETE = withRouteHandler(
targetEmail: targetMember[0].email ?? undefined,
targetName: targetMember[0].name ?? undefined,
wasSelfRemoval: session.user.id === targetUserId,
seatReduction,
},
request,
})
@@ -381,6 +482,7 @@ export const DELETE = withRouteHandler(
removedMemberId: targetUserId,
removedBy: session.user.id,
removedAt: new Date().toISOString(),
seatReduction,
},
})
} catch (error) {

View File

@@ -8,7 +8,7 @@ import {
workspace,
} from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { and, eq, inArray, sql } from 'drizzle-orm'
import { and, eq, inArray, isNull, sql } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import { getSession } from '@/lib/auth'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
@@ -57,7 +57,7 @@ export const GET = withRouteHandler(
const orgWorkspaces = await db
.select({ id: workspace.id, name: workspace.name })
.from(workspace)
.where(eq(workspace.organizationId, organizationId))
.where(and(eq(workspace.organizationId, organizationId), isNull(workspace.archivedAt)))
const orgWorkspaceIds = orgWorkspaces.map((ws) => ws.id)
const workspaceNameById = new Map(orgWorkspaces.map((ws) => [ws.id, ws.name]))
@@ -118,12 +118,82 @@ export const GET = withRouteHandler(
workspaces: permissionsByUser.get(row.userId) ?? [],
}))
const externalPermissionRows =
orgWorkspaceIds.length > 0
? await db
.select({
userId: user.id,
userName: user.name,
userEmail: user.email,
userImage: user.image,
workspaceId: permissions.entityId,
permission: permissions.permissionType,
createdAt: permissions.createdAt,
})
.from(permissions)
.innerJoin(user, eq(permissions.userId, user.id))
.leftJoin(
member,
and(eq(member.userId, user.id), eq(member.organizationId, organizationId))
)
.where(
and(
eq(permissions.entityType, 'workspace'),
inArray(permissions.entityId, orgWorkspaceIds),
isNull(member.id)
)
)
: []
const externalMembersByUser = new Map<
string,
{
memberId: string
userId: string
role: 'external'
createdAt: Date
name: string
email: string
image: string | null
workspaces: RosterWorkspaceAccess[]
}
>()
for (const row of externalPermissionRows) {
const existing = externalMembersByUser.get(row.userId)
const workspaceAccess: RosterWorkspaceAccess = {
workspaceId: row.workspaceId,
workspaceName: workspaceNameById.get(row.workspaceId) ?? 'Workspace',
permission: row.permission,
}
if (existing) {
existing.workspaces.push(workspaceAccess)
if (row.createdAt < existing.createdAt) existing.createdAt = row.createdAt
continue
}
externalMembersByUser.set(row.userId, {
memberId: `external-${row.userId}`,
userId: row.userId,
role: 'external',
createdAt: row.createdAt,
name: row.userName,
email: row.userEmail,
image: row.userImage,
workspaces: [workspaceAccess],
})
}
const rosterMembers = [...members, ...externalMembersByUser.values()]
const pendingInvitationRows = await db
.select({
id: invitation.id,
email: invitation.email,
role: invitation.role,
kind: invitation.kind,
membershipIntent: invitation.membershipIntent,
createdAt: invitation.createdAt,
expiresAt: invitation.expiresAt,
inviteeName: user.name,
@@ -160,8 +230,9 @@ export const GET = withRouteHandler(
const pendingInvitations = pendingInvitationRows.map((row) => ({
id: row.id,
email: row.email,
role: row.role,
role: row.membershipIntent === 'external' ? 'external' : row.role,
kind: row.kind,
membershipIntent: row.membershipIntent,
createdAt: row.createdAt,
expiresAt: row.expiresAt,
inviteeName: row.inviteeName,
@@ -172,7 +243,7 @@ export const GET = withRouteHandler(
return NextResponse.json({
success: true,
data: {
members,
members: rosterMembers,
pendingInvitations,
workspaces: orgWorkspaces,
},

View File

@@ -1,7 +1,7 @@
import { db } from '@sim/db'
import { invitation, member, organization, subscription } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { and, count, eq, inArray } from 'drizzle-orm'
import { and, count, eq, gt, inArray, ne } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { getSession } from '@/lib/auth'
@@ -116,7 +116,14 @@ export const PUT = withRouteHandler(
const [pendingCountRow] = await db
.select({ count: count() })
.from(invitation)
.where(and(eq(invitation.organizationId, organizationId), eq(invitation.status, 'pending')))
.where(
and(
eq(invitation.organizationId, organizationId),
eq(invitation.status, 'pending'),
ne(invitation.membershipIntent, 'external'),
gt(invitation.expiresAt, new Date())
)
)
const memberCount = memberCountRow?.count ?? 0
const pendingCount = pendingCountRow?.count ?? 0

View File

@@ -0,0 +1,614 @@
import { createHash } from 'node:crypto'
import { createLogger } from '@sim/logger'
import { toError } from '@sim/utils/errors'
import { type NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { checkInternalAuth } from '@/lib/auth/hybrid'
import { generateRequestId } from '@/lib/core/utils/request'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
export const dynamic = 'force-dynamic'
const logger = createLogger('SapS4HanaProxyAPI')
const HttpMethod = z.enum(['GET', 'POST', 'PATCH', 'PUT', 'DELETE', 'MERGE'])
const DeploymentType = z.enum(['cloud_public', 'cloud_private', 'on_premise'])
const AuthType = z.enum(['oauth_client_credentials', 'basic'])
const ServiceName = z
.string()
.min(1, 'service is required')
.regex(
/^[A-Z][A-Z0-9_]*(;v=\d+)?$/,
'service must be an uppercase OData service name optionally suffixed with ";v=NNNN" (e.g., API_BUSINESS_PARTNER, API_OUTBOUND_DELIVERY_SRV;v=0002)'
)
const ServicePath = z
.string()
.min(1, 'path is required')
.refine(
(p) =>
!p.split(/[/\\]/).some((seg) => seg === '..' || seg === '.') &&
!p.includes('?') &&
!p.includes('#') &&
!/%(?:2[eEfF]|5[cC]|3[fF]|23)/.test(p),
{
message:
'path must not contain ".." or "." segments, "?", "#", or percent-encoded path/query/fragment characters',
}
)
const Subdomain = z
.string()
.regex(
/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i,
'subdomain must contain only letters, digits, and hyphens (1-63 chars)'
)
const ProxyRequestSchema = z
.object({
deploymentType: DeploymentType.default('cloud_public'),
authType: AuthType.default('oauth_client_credentials'),
subdomain: Subdomain.optional(),
region: z
.string()
.regex(/^[a-z]{2,4}\d{1,3}$/i, 'region must be an SAP BTP region code (e.g., eu10, us30)')
.optional(),
baseUrl: z.string().optional(),
tokenUrl: z.string().optional(),
clientId: z.string().optional(),
clientSecret: z.string().optional(),
username: z.string().optional(),
password: z.string().optional(),
service: ServiceName,
path: ServicePath,
method: HttpMethod.default('GET'),
query: z.record(z.union([z.string(), z.number(), z.boolean()])).optional(),
body: z.unknown().optional(),
ifMatch: z.string().optional(),
})
.superRefine((req, ctx) => {
if (req.deploymentType === 'cloud_public') {
if (!req.subdomain) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['subdomain'],
message: 'subdomain is required for cloud_public deployment',
})
}
if (!req.region) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['region'],
message: 'region is required for cloud_public deployment',
})
}
if (req.authType !== 'oauth_client_credentials') {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['authType'],
message: 'cloud_public deployment only supports oauth_client_credentials',
})
}
if (!req.clientId) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['clientId'],
message: 'clientId is required',
})
}
if (!req.clientSecret) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['clientSecret'],
message: 'clientSecret is required',
})
}
} else {
if (!req.baseUrl) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['baseUrl'],
message: 'baseUrl is required for cloud_private and on_premise deployments',
})
} else {
const baseUrlCheck = checkExternalUrlSafety(req.baseUrl, 'baseUrl')
if (!baseUrlCheck.ok) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['baseUrl'],
message: baseUrlCheck.message,
})
}
}
if (req.authType === 'oauth_client_credentials') {
if (!req.tokenUrl) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['tokenUrl'],
message: 'tokenUrl is required for OAuth on cloud_private/on_premise',
})
} else {
const tokenUrlCheck = checkExternalUrlSafety(req.tokenUrl, 'tokenUrl')
if (!tokenUrlCheck.ok) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['tokenUrl'],
message: tokenUrlCheck.message,
})
}
}
if (!req.clientId) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['clientId'],
message: 'clientId is required for OAuth',
})
}
if (!req.clientSecret) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['clientSecret'],
message: 'clientSecret is required for OAuth',
})
}
} else {
if (!req.username) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['username'],
message: 'username is required for Basic auth',
})
}
if (!req.password) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['password'],
message: 'password is required for Basic auth',
})
}
}
}
})
type ProxyRequest = z.infer<typeof ProxyRequestSchema>
interface CachedToken {
accessToken: string
expiresAt: number
}
const TOKEN_CACHE = new Map<string, CachedToken>()
const TOKEN_CACHE_MAX_ENTRIES = 500
const TOKEN_SAFETY_WINDOW_MS = 60_000
const OUTBOUND_FETCH_TIMEOUT_MS = 30_000
const FORBIDDEN_HOSTS = new Set([
'localhost',
'0.0.0.0',
'127.0.0.1',
'169.254.169.254',
'metadata.google.internal',
'metadata',
'[::1]',
'[::]',
'[::ffff:127.0.0.1]',
'[fd00:ec2::254]',
])
function isPrivateIPv4(host: string): boolean {
const match = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/)
if (!match) return false
const octets = match.slice(1, 5).map(Number) as [number, number, number, number]
if (octets.some((o) => o < 0 || o > 255)) return false
const [a, b] = octets
if (a === 10) return true
if (a === 172 && b >= 16 && b <= 31) return true
if (a === 192 && b === 168) return true
if (a === 127) return true
if (a === 169 && b === 254) return true
if (a === 0) return true
return false
}
function extractIPv4MappedHost(host: string): string | null {
const stripped = host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host
const lower = stripped.toLowerCase()
for (const prefix of ['::ffff:', '::']) {
if (lower.startsWith(prefix)) {
const candidate = lower.slice(prefix.length)
if (/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(candidate)) return candidate
}
}
const hexMatch = lower.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/)
if (hexMatch) {
const high = Number.parseInt(hexMatch[1] as string, 16)
const low = Number.parseInt(hexMatch[2] as string, 16)
if (high >= 0 && high <= 0xffff && low >= 0 && low <= 0xffff) {
const a = (high >> 8) & 0xff
const b = high & 0xff
const c = (low >> 8) & 0xff
const d = low & 0xff
return `${a}.${b}.${c}.${d}`
}
}
return null
}
function isPrivateOrLoopbackIPv6(host: string): boolean {
const stripped = host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host
const lower = stripped.toLowerCase()
if (lower === '::' || lower === '::1') return true
if (/^fc[0-9a-f]{2}:/.test(lower) || /^fd[0-9a-f]{2}:/.test(lower)) return true
if (lower.startsWith('fe80:')) return true
return false
}
function checkExternalUrlSafety(
rawUrl: string,
label: string
): { ok: true; url: URL } | { ok: false; message: string } {
let parsed: URL
try {
parsed = new URL(rawUrl)
} catch {
return { ok: false, message: `${label} must be a valid URL` }
}
if (parsed.protocol !== 'https:') {
return { ok: false, message: `${label} must use https://` }
}
const host = parsed.hostname.toLowerCase()
if (FORBIDDEN_HOSTS.has(host) || FORBIDDEN_HOSTS.has(`[${host}]`)) {
return { ok: false, message: `${label} host is not allowed` }
}
if (isPrivateIPv4(host)) {
return { ok: false, message: `${label} host is not allowed (private/loopback range)` }
}
const mapped = extractIPv4MappedHost(host)
if (mapped && isPrivateIPv4(mapped)) {
return { ok: false, message: `${label} host is not allowed (IPv4-mapped private range)` }
}
if (isPrivateOrLoopbackIPv6(host)) {
return { ok: false, message: `${label} host is not allowed (IPv6 private/loopback)` }
}
return { ok: true, url: parsed }
}
function assertSafeExternalUrl(rawUrl: string, label: string): URL {
const result = checkExternalUrlSafety(rawUrl, label)
if (!result.ok) throw new Error(result.message)
return result.url
}
function resolveTokenUrl(req: ProxyRequest): string {
if (req.deploymentType === 'cloud_public') {
return `https://${req.subdomain}.authentication.${req.region}.hana.ondemand.com/oauth/token`
}
if (!req.tokenUrl) {
throw new Error('tokenUrl is required for OAuth on cloud_private/on_premise')
}
return req.tokenUrl
}
function tokenCacheKey(req: ProxyRequest): string {
const secretHash = req.clientSecret
? createHash('sha256').update(req.clientSecret).digest('hex').slice(0, 16)
: ''
return `${resolveTokenUrl(req)}::${req.clientId ?? ''}::${secretHash}`
}
function rememberToken(key: string, token: CachedToken): void {
if (TOKEN_CACHE.has(key)) TOKEN_CACHE.delete(key)
TOKEN_CACHE.set(key, token)
while (TOKEN_CACHE.size > TOKEN_CACHE_MAX_ENTRIES) {
const oldestKey = TOKEN_CACHE.keys().next().value
if (oldestKey === undefined) break
TOKEN_CACHE.delete(oldestKey)
}
}
async function fetchAccessToken(req: ProxyRequest, requestId: string): Promise<string> {
const cacheKey = tokenCacheKey(req)
const cached = TOKEN_CACHE.get(cacheKey)
if (cached && cached.expiresAt - TOKEN_SAFETY_WINDOW_MS > Date.now()) {
return cached.accessToken
}
const tokenUrl = assertSafeExternalUrl(resolveTokenUrl(req), 'tokenUrl').toString()
const basic = Buffer.from(`${req.clientId}:${req.clientSecret}`).toString('base64')
const response = await fetch(tokenUrl, {
method: 'POST',
headers: {
Authorization: `Basic ${basic}`,
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json',
},
body: 'grant_type=client_credentials',
signal: AbortSignal.timeout(OUTBOUND_FETCH_TIMEOUT_MS),
})
if (!response.ok) {
const text = await response.text().catch(() => '')
logger.warn(`[${requestId}] Token fetch failed (${response.status}): ${text}`)
throw new Error(`SAP token request failed: HTTP ${response.status}`)
}
const data = (await response.json()) as {
access_token?: string
expires_in?: number
}
if (!data.access_token) {
throw new Error('SAP token response missing access_token')
}
const expiresInMs = (data.expires_in ?? 3600) * 1000
rememberToken(cacheKey, {
accessToken: data.access_token,
expiresAt: Date.now() + expiresInMs,
})
return data.access_token
}
interface CsrfBundle {
token: string
cookie: string
}
function joinSetCookies(headers: Headers): string {
const cookies =
typeof (headers as { getSetCookie?: () => string[] }).getSetCookie === 'function'
? (headers as { getSetCookie: () => string[] }).getSetCookie()
: (headers.get('set-cookie') ?? '').split(/,\s*(?=[^=,;\s]+=)/)
return cookies
.map((c) => c.split(';')[0]?.trim())
.filter(Boolean)
.join('; ')
}
function buildAuthHeader(req: ProxyRequest, accessToken: string | null): string {
if (req.authType === 'basic') {
const basic = Buffer.from(`${req.username}:${req.password}`).toString('base64')
return `Basic ${basic}`
}
return `Bearer ${accessToken}`
}
async function fetchCsrf(
req: ProxyRequest,
accessToken: string | null,
requestId: string
): Promise<CsrfBundle | null> {
const url = buildOdataUrl(req, '/$metadata')
const response = await fetch(url, {
method: 'GET',
headers: {
Authorization: buildAuthHeader(req, accessToken),
Accept: 'application/xml',
'X-CSRF-Token': 'Fetch',
},
signal: AbortSignal.timeout(OUTBOUND_FETCH_TIMEOUT_MS),
})
if (!response.ok) {
const text = await response.text().catch(() => '')
logger.warn(`[${requestId}] CSRF fetch failed (${response.status}): ${text}`)
return null
}
const token = response.headers.get('x-csrf-token')
const cookie = joinSetCookies(response.headers)
if (!token) return null
return { token, cookie }
}
function resolveHost(req: ProxyRequest): string {
if (req.deploymentType === 'cloud_public') {
const constructed = `https://${req.subdomain}-api.s4hana.ondemand.com`
return assertSafeExternalUrl(constructed, 'subdomain').toString().replace(/\/+$/, '')
}
if (!req.baseUrl) {
throw new Error('baseUrl is required for cloud_private and on_premise deployments')
}
const trimmed = req.baseUrl.replace(/\/+$/, '')
return assertSafeExternalUrl(trimmed, 'baseUrl').toString().replace(/\/+$/, '')
}
function buildOdataUrl(req: ProxyRequest, pathOverride?: string): string {
const host = resolveHost(req)
const servicePath = `/sap/opu/odata/sap/${req.service}`
const subPath = pathOverride ?? req.path
const normalized = subPath.startsWith('/') ? subPath : `/${subPath}`
const base = `${host}${servicePath}${normalized}`
if (pathOverride !== undefined) {
return base
}
if (!req.query || Object.keys(req.query).length === 0) {
return base
}
const encode = (s: string) => encodeURIComponent(s).replace(/%24/g, '$')
const parts: string[] = []
for (const [key, value] of Object.entries(req.query)) {
if (value === undefined || value === null) continue
parts.push(`${encode(key)}=${encode(String(value))}`)
}
const queryString = parts.join('&')
if (!queryString) return base
return base.includes('?') ? `${base}&${queryString}` : `${base}?${queryString}`
}
const WRITE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE', 'MERGE'])
interface OdataInvocation {
status: number
body: unknown
raw: string
csrfHeader: string
}
async function callOdata(
req: ProxyRequest,
accessToken: string | null,
csrf: CsrfBundle | null
): Promise<OdataInvocation> {
const url = buildOdataUrl(req)
const headers: Record<string, string> = {
Authorization: buildAuthHeader(req, accessToken),
Accept: 'application/json',
}
const isWrite = WRITE_METHODS.has(req.method)
const hasBody = req.body !== undefined && req.body !== null
if (hasBody) headers['Content-Type'] = 'application/json'
if (req.ifMatch) headers['If-Match'] = req.ifMatch
if (isWrite && csrf) {
headers['X-CSRF-Token'] = csrf.token
if (csrf.cookie) headers.Cookie = csrf.cookie
}
const response = await fetch(url, {
method: req.method,
headers,
body: hasBody ? JSON.stringify(req.body) : undefined,
signal: AbortSignal.timeout(OUTBOUND_FETCH_TIMEOUT_MS),
})
const raw = await response.text()
let parsed: unknown = null
if (raw.length > 0) {
try {
parsed = JSON.parse(raw)
} catch {
parsed = raw
}
}
const csrfHeader = response.headers.get('x-csrf-token')?.toLowerCase() ?? ''
return { status: response.status, body: parsed, raw, csrfHeader }
}
function isCsrfRequired(invocation: OdataInvocation): boolean {
if (invocation.status !== 403) return false
if (invocation.csrfHeader === 'required') return true
if (typeof invocation.body !== 'object' || invocation.body === null) return false
const errorObj = (invocation.body as { error?: { message?: { value?: string } | string } }).error
const messageField = errorObj?.message
const message = typeof messageField === 'string' ? messageField : (messageField?.value ?? '')
return message.toLowerCase().includes('csrf')
}
function extractOdataError(body: unknown, status: number): string {
if (body && typeof body === 'object') {
const err = (
body as {
error?: {
message?: { value?: string } | string
code?: string
innererror?: {
errordetails?: Array<{ code?: string; message?: string; severity?: string }>
}
}
}
).error
if (err) {
const messageField = err.message
const base =
typeof messageField === 'string' ? messageField : (messageField?.value ?? err.code ?? '')
const prefix = err.code ? `[${err.code}] ` : ''
const details = err.innererror?.errordetails
?.filter((d) => d.message && (!d.severity || d.severity.toLowerCase() !== 'info'))
.map((d) => {
const tag = d.code ? `[${d.code}] ` : ''
return `${tag}${d.message}`
})
.filter((m): m is string => Boolean(m))
if (details && details.length > 0) {
const extras = details.filter((d) => !d.endsWith(base))
return extras.length > 0 ? `${prefix}${base} (${extras.join('; ')})` : `${prefix}${base}`
}
if (base) return `${prefix}${base}`
}
}
if (typeof body === 'string' && body.length > 0) return body
return `SAP request failed with HTTP ${status}`
}
function unwrapOdata(body: unknown): unknown {
if (!body || typeof body !== 'object') return body
const root = (body as { d?: unknown }).d
if (root === undefined) return body
if (root && typeof root === 'object' && 'results' in (root as Record<string, unknown>)) {
const rootObj = root as { results: unknown; __count?: string; __next?: string }
if (rootObj.__count !== undefined || rootObj.__next !== undefined) {
return {
results: rootObj.results,
...(rootObj.__count !== undefined && { __count: rootObj.__count }),
...(rootObj.__next !== undefined && { __next: rootObj.__next }),
}
}
return rootObj.results
}
return root
}
export const POST = withRouteHandler(async (request: NextRequest) => {
const requestId = generateRequestId()
try {
const authResult = await checkInternalAuth(request, { requireWorkflowId: false })
if (!authResult.success) {
logger.warn(`[${requestId}] Unauthorized SAP proxy request: ${authResult.error}`)
return NextResponse.json(
{ success: false, error: authResult.error || 'Authentication required' },
{ status: 401 }
)
}
const json = await request.json()
const proxyReq = ProxyRequestSchema.parse(json)
const isWrite = WRITE_METHODS.has(proxyReq.method)
const accessToken =
proxyReq.authType === 'oauth_client_credentials'
? await fetchAccessToken(proxyReq, requestId)
: null
const csrf = isWrite ? await fetchCsrf(proxyReq, accessToken, requestId) : null
let invocation = await callOdata(proxyReq, accessToken, csrf)
if (isWrite && isCsrfRequired(invocation)) {
logger.info(`[${requestId}] CSRF token rejected, refetching and retrying`)
const refreshed = await fetchCsrf(proxyReq, accessToken, requestId)
if (refreshed) {
invocation = await callOdata(proxyReq, accessToken, refreshed)
}
}
if (invocation.status >= 200 && invocation.status < 300) {
const data = invocation.status === 204 ? null : unwrapOdata(invocation.body)
return NextResponse.json({ success: true, output: { status: invocation.status, data } })
}
const message = extractOdataError(invocation.body, invocation.status)
logger.warn(
`[${requestId}] SAP API error (${invocation.status}) ${proxyReq.service}${proxyReq.path}: ${message}`
)
return NextResponse.json(
{ success: false, error: message, status: invocation.status },
{ status: invocation.status }
)
} catch (error) {
if (error instanceof z.ZodError) {
logger.warn(`[${requestId}] Validation error:`, error.errors)
return NextResponse.json(
{ success: false, error: error.errors[0]?.message || 'Validation failed' },
{ status: 400 }
)
}
logger.error(`[${requestId}] Unexpected SAP proxy error:`, error)
return NextResponse.json({ success: false, error: toError(error).message }, { status: 500 })
}
})

View File

@@ -22,6 +22,8 @@ const requestSchema = z.object({
variables: z.any(),
provider: z.enum(['openai', 'anthropic']).optional().default('openai'),
apiKey: z.string(),
mode: z.enum(['dom', 'hybrid', 'cua']).optional().default('dom'),
maxSteps: z.number().int().min(1).max(200).optional().default(20),
})
/**
@@ -121,7 +123,7 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
}
const params = validationResult.data
const { task, startUrl: rawStartUrl, outputSchema, provider, apiKey } = params
const { task, startUrl: rawStartUrl, outputSchema, provider, apiKey, mode, maxSteps } = params
const variablesObject = processVariables(params.variables)
const startUrl = normalizeUrl(rawStartUrl)
@@ -165,8 +167,10 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
return NextResponse.json({ error: 'Invalid Anthropic API key format' }, { status: 400 })
}
const modelName =
provider === 'anthropic' ? 'anthropic/claude-sonnet-4-5-20250929' : 'openai/gpt-5'
const modelName = provider === 'anthropic' ? 'anthropic/claude-sonnet-4-6' : 'openai/gpt-5'
let sessionId: string | null = null
let liveViewUrl: string | null = null
try {
logger.info('Initializing Stagehand with Browserbase (v3)', { provider, modelName })
@@ -190,6 +194,35 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
await stagehand.init()
logger.info('Stagehand initialized successfully')
sessionId = stagehand.browserbaseSessionID ?? null
if (sessionId) {
try {
const debugResponse = await fetch(
`https://api.browserbase.com/v1/sessions/${sessionId}/debug`,
{
method: 'GET',
headers: {
'X-BB-API-Key': BROWSERBASE_API_KEY,
},
}
)
if (debugResponse.ok) {
const debugData = (await debugResponse.json()) as {
debuggerFullscreenUrl?: string
debuggerUrl?: string
}
liveViewUrl = debugData.debuggerFullscreenUrl ?? debugData.debuggerUrl ?? null
if (liveViewUrl) {
logger.info(`Browserbase live view URL: ${liveViewUrl}`)
}
} else {
logger.warn(`Failed to fetch Browserbase debug URL: ${debugResponse.statusText}`)
}
} catch (debugError) {
logger.warn('Error fetching Browserbase debug URL', { error: debugError })
}
}
const page = stagehand.context.pages()[0]
logger.info(`Navigating to ${startUrl}`)
await page.goto(startUrl, { waitUntil: 'networkidle' })
@@ -223,13 +256,14 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
apiKey: apiKey,
},
systemPrompt: agentInstructions,
mode,
})
logger.info('Executing agent task', { task: taskWithVariables })
logger.info('Executing agent task', { task: taskWithVariables, mode, maxSteps })
const agentExecutionResult = await agent.execute({
instruction: taskWithVariables,
maxSteps: 20,
maxSteps,
})
const agentResult = {
@@ -293,6 +327,8 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
return NextResponse.json({
agentResult,
structuredOutput,
liveViewUrl,
sessionId,
})
} catch (error) {
logger.error('Stagehand agent execution error', {
@@ -327,6 +363,8 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
{
error: errorMessage,
details: errorDetails,
liveViewUrl,
sessionId,
},
{ status: 500 }
)

View File

@@ -17,8 +17,6 @@ const BROWSERBASE_PROJECT_ID = env.BROWSERBASE_PROJECT_ID
const requestSchema = z.object({
instruction: z.string(),
schema: z.record(z.any()),
useTextExtract: z.boolean().optional().default(false),
selector: z.string().nullable().optional(),
provider: z.enum(['openai', 'anthropic']).optional().default('openai'),
apiKey: z.string(),
url: z.string().url(),
@@ -51,7 +49,7 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
}
const params = validationResult.data
const { url: rawUrl, instruction, selector, provider, apiKey, schema } = params
const { url: rawUrl, instruction, provider, apiKey, schema } = params
const url = normalizeUrl(rawUrl)
const urlValidation = await validateUrlWithDNS(url, 'url')
if (!urlValidation.isValid) {
@@ -101,8 +99,7 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
}
try {
const modelName =
provider === 'anthropic' ? 'anthropic/claude-sonnet-4-5-20250929' : 'openai/gpt-5'
const modelName = provider === 'anthropic' ? 'anthropic/claude-sonnet-4-6' : 'openai/gpt-5'
logger.info('Initializing Stagehand with Browserbase (v3)', { provider, modelName })
@@ -162,14 +159,11 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
logger.info('Calling stagehand.extract with options', {
hasInstruction: !!instruction,
hasSchema: !!zodSchema,
hasSelector: !!selector,
})
let extractedData
if (zodSchema) {
extractedData = await stagehand.extract(instruction, zodSchema, {
selector: selector || undefined,
})
extractedData = await stagehand.extract(instruction, zodSchema)
} else {
extractedData = await stagehand.extract(instruction)
}

View File

@@ -3,7 +3,7 @@ import { toError } from '@sim/utils/errors'
import { type NextRequest, NextResponse } from 'next/server'
import { getSession } from '@/lib/auth'
import { MAX_DOCUMENT_PREVIEW_CODE_BYTES } from '@/lib/execution/constants'
import { runSandboxTask } from '@/lib/execution/sandbox/run-task'
import { runSandboxTask, SandboxUserCodeError } from '@/lib/execution/sandbox/run-task'
import { verifyWorkspaceMembership } from '@/app/api/workflows/utils'
import type { SandboxTaskId } from '@/sandbox-tasks/registry'
@@ -83,6 +83,14 @@ export function createDocumentPreviewRoute(config: DocumentPreviewRouteConfig) {
})
} catch (err) {
const message = toError(err).message
if (err instanceof SandboxUserCodeError) {
logger.warn(`${config.label} preview user code failed`, {
error: message,
errorName: err.name,
workspaceId,
})
return NextResponse.json({ error: message, errorName: err.name }, { status: 422 })
}
logger.error(`${config.label} preview generation failed`, { error: message, workspaceId })
return NextResponse.json({ error: message }, { status: 500 })
}

View File

@@ -6,9 +6,15 @@ import { NextRequest } from 'next/server'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { MAX_DOCUMENT_PREVIEW_CODE_BYTES } from '@/lib/execution/constants'
const { mockRunSandboxTask } = vi.hoisted(() => ({
mockRunSandboxTask: vi.fn(),
}))
const { mockRunSandboxTask, SandboxUserCodeError } = vi.hoisted(() => {
class SandboxUserCodeError extends Error {
constructor(message: string, name: string) {
super(message)
this.name = name
}
}
return { mockRunSandboxTask: vi.fn(), SandboxUserCodeError }
})
const mockVerifyWorkspaceMembership = workflowsApiUtilsMockFns.mockVerifyWorkspaceMembership
@@ -16,6 +22,7 @@ vi.mock('@/app/api/workflows/utils', () => workflowsApiUtilsMock)
vi.mock('@/lib/execution/sandbox/run-task', () => ({
runSandboxTask: mockRunSandboxTask,
SandboxUserCodeError,
}))
import { POST } from '@/app/api/workspaces/[id]/docx/preview/route'
@@ -189,4 +196,31 @@ describe('DOCX preview API route', () => {
expect(response.status).toBe(500)
await expect(response.json()).resolves.toEqual({ error: 'boom: sandbox failed' })
})
it('returns 422 when user code throws inside the sandbox', async () => {
mockRunSandboxTask.mockRejectedValue(
new SandboxUserCodeError('Invalid or unexpected token', 'SyntaxError')
)
const request = new NextRequest(
'http://localhost:3000/api/workspaces/workspace-1/docx/preview',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ code: 'const x = ' }),
}
)
const response = await POST(request, {
params: Promise.resolve({ id: 'workspace-1' }),
})
expect(response.status).toBe(422)
await expect(response.json()).resolves.toEqual({
error: 'Invalid or unexpected token',
errorName: 'SyntaxError',
})
})
})

View File

@@ -6,9 +6,15 @@ import { NextRequest } from 'next/server'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { MAX_DOCUMENT_PREVIEW_CODE_BYTES } from '@/lib/execution/constants'
const { mockRunSandboxTask } = vi.hoisted(() => ({
mockRunSandboxTask: vi.fn(),
}))
const { mockRunSandboxTask, SandboxUserCodeError } = vi.hoisted(() => {
class SandboxUserCodeError extends Error {
constructor(message: string, name: string) {
super(message)
this.name = name
}
}
return { mockRunSandboxTask: vi.fn(), SandboxUserCodeError }
})
const mockVerifyWorkspaceMembership = workflowsApiUtilsMockFns.mockVerifyWorkspaceMembership
@@ -16,6 +22,7 @@ vi.mock('@/app/api/workflows/utils', () => workflowsApiUtilsMock)
vi.mock('@/lib/execution/sandbox/run-task', () => ({
runSandboxTask: mockRunSandboxTask,
SandboxUserCodeError,
}))
import { POST } from '@/app/api/workspaces/[id]/pdf/preview/route'
@@ -187,4 +194,31 @@ describe('PDF preview API route', () => {
expect(response.status).toBe(500)
await expect(response.json()).resolves.toEqual({ error: 'boom: sandbox failed' })
})
it('returns 422 when user code throws inside the sandbox', async () => {
mockRunSandboxTask.mockRejectedValue(
new SandboxUserCodeError('Invalid or unexpected token', 'SyntaxError')
)
const request = new NextRequest(
'http://localhost:3000/api/workspaces/workspace-1/pdf/preview',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ code: 'const x = ' }),
}
)
const response = await POST(request, {
params: Promise.resolve({ id: 'workspace-1' }),
})
expect(response.status).toBe(422)
await expect(response.json()).resolves.toEqual({
error: 'Invalid or unexpected token',
errorName: 'SyntaxError',
})
})
})

View File

@@ -6,9 +6,15 @@ import { NextRequest } from 'next/server'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { MAX_DOCUMENT_PREVIEW_CODE_BYTES } from '@/lib/execution/constants'
const { mockRunSandboxTask } = vi.hoisted(() => ({
mockRunSandboxTask: vi.fn(),
}))
const { mockRunSandboxTask, SandboxUserCodeError } = vi.hoisted(() => {
class SandboxUserCodeError extends Error {
constructor(message: string, name: string) {
super(message)
this.name = name
}
}
return { mockRunSandboxTask: vi.fn(), SandboxUserCodeError }
})
const mockVerifyWorkspaceMembership = workflowsApiUtilsMockFns.mockVerifyWorkspaceMembership
@@ -16,6 +22,7 @@ vi.mock('@/app/api/workflows/utils', () => workflowsApiUtilsMock)
vi.mock('@/lib/execution/sandbox/run-task', () => ({
runSandboxTask: mockRunSandboxTask,
SandboxUserCodeError,
}))
import { POST } from '@/app/api/workspaces/[id]/pptx/preview/route'
@@ -189,4 +196,31 @@ describe('PPTX preview API route', () => {
expect(response.status).toBe(500)
await expect(response.json()).resolves.toEqual({ error: 'boom: sandbox failed' })
})
it('returns 422 when user code throws inside the sandbox', async () => {
mockRunSandboxTask.mockRejectedValue(
new SandboxUserCodeError('Invalid or unexpected token', 'SyntaxError')
)
const request = new NextRequest(
'http://localhost:3000/api/workspaces/workspace-1/pptx/preview',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ code: 'const x = ' }),
}
)
const response = await POST(request, {
params: Promise.resolve({ id: 'workspace-1' }),
})
expect(response.status).toBe(422)
await expect(response.json()).resolves.toEqual({
error: 'Invalid or unexpected token',
errorName: 'SyntaxError',
})
})
})

View File

@@ -0,0 +1,129 @@
import { createLogger } from '@sim/logger'
import { type NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { getSession } from '@/lib/auth'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { normalizeEmail } from '@/lib/invitations/core'
import {
createWorkspaceInvitation,
prepareWorkspaceInvitationContext,
WorkspaceInvitationError,
type WorkspaceInvitationResult,
} from '@/lib/invitations/workspace-invitations'
import { InvitationsNotAllowedError } from '@/ee/access-control/utils/permission-check'
export const dynamic = 'force-dynamic'
const logger = createLogger('WorkspaceInvitationBatchAPI')
interface BatchInvitationFailure {
email: string
error: string
}
const batchInvitationSchema = z.object({
workspaceId: z.string().min(1, 'Workspace ID is required'),
invitations: z
.array(
z.object({
email: z.string().trim().min(1, 'Invitation email is required'),
permission: z.string().optional(),
})
)
.min(1, 'At least one invitation is required'),
})
type BatchInvitationRequest = z.infer<typeof batchInvitationSchema>
function batchErrorResponse(error: unknown) {
if (error instanceof WorkspaceInvitationError) {
return NextResponse.json(
{
error: error.message,
...(error.email ? { email: error.email } : {}),
...(error.upgradeRequired !== undefined ? { upgradeRequired: error.upgradeRequired } : {}),
},
{ status: error.status }
)
}
if (error instanceof InvitationsNotAllowedError) {
return NextResponse.json({ error: error.message }, { status: 403 })
}
logger.error('Error creating workspace invitation batch:', error)
return NextResponse.json({ error: 'Failed to create invitation batch' }, { status: 500 })
}
export const POST = withRouteHandler(async (req: NextRequest) => {
const session = await getSession()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
try {
const parsedBody = batchInvitationSchema.safeParse(await req.json().catch(() => null))
if (!parsedBody.success) {
return NextResponse.json(
{ error: parsedBody.error.errors[0]?.message ?? 'Invalid invitation batch payload' },
{ status: 400 }
)
}
const body: BatchInvitationRequest = parsedBody.data
const context = await prepareWorkspaceInvitationContext({
workspaceId: body.workspaceId,
inviterId: session.user.id,
inviterName: session.user.name || session.user.email || 'A user',
inviterEmail: session.user.email,
})
const successful: string[] = []
const failed: BatchInvitationFailure[] = []
const invitations: WorkspaceInvitationResult[] = []
const seenEmails = new Set<string>()
for (const item of body.invitations) {
const normalizedEmail = normalizeEmail(item.email)
if (seenEmails.has(normalizedEmail)) {
failed.push({
email: normalizedEmail,
error: `${normalizedEmail} appears more than once in this invitation batch`,
})
continue
}
seenEmails.add(normalizedEmail)
try {
const invitation = await createWorkspaceInvitation({
context,
email: item.email,
permission: item.permission,
request: req,
})
successful.push(invitation.email)
invitations.push(invitation)
} catch (error) {
if (error instanceof WorkspaceInvitationError) {
failed.push({ email: error.email ?? normalizedEmail, error: error.message })
continue
}
logger.error('Unexpected workspace invitation batch item failure:', {
email: normalizedEmail,
error,
})
throw error
}
}
return NextResponse.json({
success: failed.length === 0,
successful,
failed,
invitations,
})
} catch (error) {
return batchErrorResponse(error)
}
})

View File

@@ -108,9 +108,9 @@ const mockGetSession = authMockFns.mockGetSession
const mockGetWorkspaceWithOwner = permissionsMockFns.mockGetWorkspaceWithOwner
import { UPGRADE_TO_INVITE_REASON } from '@/lib/workspaces/policy-constants'
import { POST } from '@/app/api/workspaces/invitations/route'
import { POST } from '@/app/api/workspaces/invitations/batch/route'
describe('POST /api/workspaces/invitations', () => {
describe('POST /api/workspaces/invitations/batch', () => {
beforeEach(() => {
vi.clearAllMocks()
mockDbResults.value = []
@@ -169,8 +169,7 @@ describe('POST /api/workspaces/invitations', () => {
const request = createMockRequest('POST', {
workspaceId: 'workspace-1',
email: 'new@example.com',
permission: 'read',
invitations: [{ email: 'new@example.com', permission: 'read' }],
})
const response = await POST(request)
@@ -201,8 +200,7 @@ describe('POST /api/workspaces/invitations', () => {
const request = createMockRequest('POST', {
workspaceId: 'workspace-1',
email: 'new@example.com',
permission: 'read',
invitations: [{ email: 'new@example.com', permission: 'read' }],
})
const response = await POST(request)
@@ -213,7 +211,7 @@ describe('POST /api/workspaces/invitations', () => {
expect(mockCreatePendingInvitation).not.toHaveBeenCalled()
})
it('rejects org-owned invites when the organization has no available seats', async () => {
it('reports org-owned invites as failed when the organization has no available seats', async () => {
mockGetWorkspaceWithOwner.mockResolvedValueOnce({
id: 'workspace-1',
name: 'Org Workspace',
@@ -240,20 +238,25 @@ describe('POST /api/workspaces/invitations', () => {
const request = createMockRequest('POST', {
workspaceId: 'workspace-1',
email: 'new@example.com',
permission: 'read',
invitations: [{ email: 'new@example.com', permission: 'read' }],
})
const response = await POST(request)
const data = await response.json()
expect(response.status).toBe(400)
expect(data.error).toContain('No available seats')
expect(response.status).toBe(200)
expect(data.success).toBe(false)
expect(data.failed).toEqual([
{
email: 'new@example.com',
error: 'No available seats. Currently using 5 of 5 seats.',
},
])
expect(mockValidateSeatAvailability).toHaveBeenCalledWith('org-1', 1)
expect(mockCreatePendingInvitation).not.toHaveBeenCalled()
})
it('rejects org-owned invites for users already in another organization', async () => {
it('creates an external workspace invitation for users already in another organization', async () => {
mockGetWorkspaceWithOwner.mockResolvedValueOnce({
id: 'workspace-1',
name: 'Org Workspace',
@@ -281,16 +284,25 @@ describe('POST /api/workspaces/invitations', () => {
const request = createMockRequest('POST', {
workspaceId: 'workspace-1',
email: 'new@example.com',
permission: 'read',
invitations: [{ email: 'new@example.com', permission: 'read' }],
})
const response = await POST(request)
const data = await response.json()
expect(response.status).toBe(409)
expect(data.error).toContain('already a member of another organization')
expect(mockCreatePendingInvitation).not.toHaveBeenCalled()
expect(response.status).toBe(200)
expect(data.success).toBe(true)
expect(data.invitations[0].membershipIntent).toBe('external')
expect(mockValidateSeatAvailability).not.toHaveBeenCalled()
expect(mockCreatePendingInvitation).toHaveBeenCalledWith(
expect.objectContaining({
kind: 'workspace',
email: 'new@example.com',
organizationId: 'org-1',
membershipIntent: 'external',
grants: [{ workspaceId: 'workspace-1', permission: 'read' }],
})
)
})
it('creates a unified workspace invitation for a grandfathered workspace', async () => {
@@ -306,8 +318,7 @@ describe('POST /api/workspaces/invitations', () => {
const request = createMockRequest('POST', {
workspaceId: 'workspace-1',
email: 'new@example.com',
permission: 'write',
invitations: [{ email: 'new@example.com', permission: 'write' }],
})
const response = await POST(request)
@@ -327,6 +338,40 @@ describe('POST /api/workspaces/invitations', () => {
expect(mockValidateSeatAvailability).not.toHaveBeenCalled()
})
it('creates multiple workspace invitations in one batch request', async () => {
mockDbResults.value = [[{ permissionType: 'admin' }], [], []]
mockCreatePendingInvitation
.mockResolvedValueOnce({
invitationId: 'inv-1',
token: 'tok-1',
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
})
.mockResolvedValueOnce({
invitationId: 'inv-2',
token: 'tok-2',
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
})
const request = createMockRequest('POST', {
workspaceId: 'workspace-1',
invitations: [
{ email: 'first@example.com', permission: 'read' },
{ email: 'second@example.com', permission: 'write' },
],
})
const response = await POST(request)
const data = await response.json()
expect(response.status).toBe(200)
expect(data.success).toBe(true)
expect(data.successful).toEqual(['first@example.com', 'second@example.com'])
expect(data.failed).toEqual([])
expect(data.invitations).toHaveLength(2)
expect(mockCreatePendingInvitation).toHaveBeenCalledTimes(2)
expect(mockSendInvitationEmail).toHaveBeenCalledTimes(2)
})
it('rolls back the unified invitation when email delivery fails', async () => {
mockGetWorkspaceWithOwner.mockResolvedValueOnce({
id: 'workspace-1',
@@ -344,13 +389,18 @@ describe('POST /api/workspaces/invitations', () => {
const request = createMockRequest('POST', {
workspaceId: 'workspace-1',
email: 'new@example.com',
permission: 'read',
invitations: [{ email: 'new@example.com', permission: 'read' }],
})
const response = await POST(request)
expect(response.status).toBe(502)
expect(response.status).toBe(200)
await expect(response.json()).resolves.toEqual(
expect.objectContaining({
success: false,
failed: [{ email: 'new@example.com', error: 'mailer unavailable' }],
})
)
expect(mockCancelPendingInvitation).toHaveBeenCalledWith('inv-1')
})
})

View File

@@ -1,35 +1,16 @@
import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit'
import { db } from '@sim/db'
import { permissions, type permissionTypeEnum, user, workspace } from '@sim/db/schema'
import { permissions, workspace } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { and, eq, isNull, sql } from 'drizzle-orm'
import { and, eq, isNull } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import { getSession } from '@/lib/auth'
import { getUserOrganization } from '@/lib/billing/organizations/membership'
import { validateSeatAvailability } from '@/lib/billing/validation/seat-management'
import { PlatformEvents } from '@/lib/core/telemetry'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { listInvitationsForWorkspaces, normalizeEmail } from '@/lib/invitations/core'
import {
cancelPendingInvitation,
createPendingInvitation,
findPendingGrantForWorkspaceEmail,
sendInvitationEmail,
} from '@/lib/invitations/send'
import { captureServerEvent } from '@/lib/posthog/server'
import { getWorkspaceWithOwner } from '@/lib/workspaces/permissions/utils'
import { getWorkspaceInvitePolicy } from '@/lib/workspaces/policy'
import {
InvitationsNotAllowedError,
validateInvitationsAllowed,
} from '@/ee/access-control/utils/permission-check'
import { listInvitationsForWorkspaces } from '@/lib/invitations/core'
export const dynamic = 'force-dynamic'
const logger = createLogger('WorkspaceInvitationsAPI')
type PermissionType = (typeof permissionTypeEnum.enumValues)[number]
export const GET = withRouteHandler(async (req: NextRequest) => {
const session = await getSession()
if (!session?.user?.id) {
@@ -61,241 +42,3 @@ export const GET = withRouteHandler(async (req: NextRequest) => {
return NextResponse.json({ error: 'Failed to fetch invitations' }, { status: 500 })
}
})
export const POST = withRouteHandler(async (req: NextRequest) => {
const session = await getSession()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
try {
const { workspaceId, email, permission = 'read' } = await req.json()
if (!workspaceId || !email) {
return NextResponse.json({ error: 'Workspace ID and email are required' }, { status: 400 })
}
await validateInvitationsAllowed(session.user.id, workspaceId)
const validPermissions: PermissionType[] = ['admin', 'write', 'read']
if (!validPermissions.includes(permission)) {
return NextResponse.json(
{ error: `Invalid permission: must be one of ${validPermissions.join(', ')}` },
{ status: 400 }
)
}
const normalizedEmail = normalizeEmail(email)
const userPermission = await db
.select()
.from(permissions)
.where(
and(
eq(permissions.entityId, workspaceId),
eq(permissions.entityType, 'workspace'),
eq(permissions.userId, session.user.id),
eq(permissions.permissionType, 'admin')
)
)
.then((rows) => rows[0])
if (!userPermission) {
return NextResponse.json(
{ error: 'You need admin permissions to invite users' },
{ status: 403 }
)
}
const workspaceDetails = await getWorkspaceWithOwner(workspaceId)
if (!workspaceDetails) {
return NextResponse.json({ error: 'Workspace not found' }, { status: 404 })
}
const invitePolicy = await getWorkspaceInvitePolicy(workspaceDetails)
if (!invitePolicy.allowed) {
return NextResponse.json(
{
error: invitePolicy.reason ?? 'Invites are disabled for this workspace.',
upgradeRequired: invitePolicy.upgradeRequired,
},
{ status: 403 }
)
}
const existingUser = await db
.select()
.from(user)
.where(sql`lower(${user.email}) = ${normalizedEmail}`)
.then((rows) => rows[0])
if (existingUser) {
const existingPermission = await db
.select()
.from(permissions)
.where(
and(
eq(permissions.entityId, workspaceId),
eq(permissions.entityType, 'workspace'),
eq(permissions.userId, existingUser.id)
)
)
.then((rows) => rows[0])
if (existingPermission) {
return NextResponse.json(
{
error: `${normalizedEmail} already has access to this workspace`,
email: normalizedEmail,
},
{ status: 400 }
)
}
if (invitePolicy.requiresSeat && invitePolicy.organizationId) {
const existingMembership = await getUserOrganization(existingUser.id)
if (
existingMembership &&
existingMembership.organizationId !== invitePolicy.organizationId
) {
return NextResponse.json(
{
error:
'This user is already a member of another organization. They must leave it before joining this workspace.',
email: normalizedEmail,
},
{ status: 409 }
)
}
if (!existingMembership) {
const seatValidation = await validateSeatAvailability(invitePolicy.organizationId, 1)
if (!seatValidation.canInvite) {
return NextResponse.json(
{
error: seatValidation.reason || 'No available seats for this organization.',
email: normalizedEmail,
},
{ status: 400 }
)
}
}
}
} else if (invitePolicy.requiresSeat && invitePolicy.organizationId) {
const seatValidation = await validateSeatAvailability(invitePolicy.organizationId, 1)
if (!seatValidation.canInvite) {
return NextResponse.json(
{
error: seatValidation.reason || 'No available seats for this organization.',
email: normalizedEmail,
},
{ status: 400 }
)
}
}
const existingInvitation = await findPendingGrantForWorkspaceEmail({
workspaceId,
email: normalizedEmail,
})
if (existingInvitation) {
return NextResponse.json(
{
error: `${normalizedEmail} has already been invited to this workspace`,
email: normalizedEmail,
},
{ status: 400 }
)
}
const { invitationId, token } = await createPendingInvitation({
kind: 'workspace',
email: normalizedEmail,
inviterId: session.user.id,
organizationId: workspaceDetails.organizationId,
role: 'member',
grants: [
{
workspaceId,
permission,
},
],
})
try {
PlatformEvents.workspaceMemberInvited({
workspaceId,
invitedBy: session.user.id,
inviteeEmail: normalizedEmail,
role: permission,
})
} catch {
// telemetry must not fail the operation
}
captureServerEvent(
session.user.id,
'workspace_member_invited',
{ workspace_id: workspaceId, invitee_role: permission },
{
groups: { workspace: workspaceId },
setOnce: { first_invitation_sent_at: new Date().toISOString() },
}
)
const emailResult = await sendInvitationEmail({
invitationId,
token,
kind: 'workspace',
email: normalizedEmail,
inviterName: session.user.name || session.user.email || 'A user',
organizationId: workspaceDetails.organizationId,
organizationRole: 'member',
grants: [{ workspaceId, permission }],
})
if (!emailResult.success) {
await cancelPendingInvitation(invitationId)
return NextResponse.json(
{ error: emailResult.error || 'Failed to send invitation email' },
{ status: 502 }
)
}
recordAudit({
workspaceId,
actorId: session.user.id,
actorName: session.user.name,
actorEmail: session.user.email,
action: AuditAction.MEMBER_INVITED,
resourceType: AuditResourceType.WORKSPACE,
resourceId: workspaceId,
resourceName: normalizedEmail,
description: `Invited ${normalizedEmail} as ${permission}`,
metadata: {
targetEmail: normalizedEmail,
targetRole: permission,
workspaceName: workspaceDetails.name,
invitationId,
},
request: req,
})
return NextResponse.json({
success: true,
invitation: {
id: invitationId,
workspaceId,
email: normalizedEmail,
permission,
expiresAt: undefined,
},
})
} catch (error) {
if (error instanceof InvitationsNotAllowedError) {
return NextResponse.json({ error: error.message }, { status: 403 })
}
logger.error('Error creating workspace invitation:', error)
return NextResponse.json({ error: 'Failed to create invitation' }, { status: 500 })
}
})

View File

@@ -1,13 +1,14 @@
import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit'
import { db } from '@sim/db'
import { permissions, workspace } from '@sim/db/schema'
import { permissionGroupMember, permissions, workspace } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { generateId } from '@sim/utils/id'
import { and, eq } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { getSession } from '@/lib/auth'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { revokeWorkspaceCredentialMemberships } from '@/lib/credentials/access'
import { revokeWorkspaceCredentialMembershipsTx } from '@/lib/credentials/access'
import { captureServerEvent } from '@/lib/posthog/server'
import { hasWorkspaceAdminAccess } from '@/lib/workspaces/permissions/utils'
@@ -32,7 +33,10 @@ export const DELETE = withRouteHandler(
const { workspaceId } = body
const workspaceRow = await db
.select({ billedAccountUserId: workspace.billedAccountUserId })
.select({
ownerId: workspace.ownerId,
billedAccountUserId: workspace.billedAccountUserId,
})
.from(workspace)
.where(eq(workspace.id, workspaceId))
.limit(1)
@@ -61,7 +65,10 @@ export const DELETE = withRouteHandler(
)
.then((rows) => rows[0])
if (!userPermission) {
const isRemovingWorkspaceOwner = workspaceRow[0].ownerId === userId
const isOwnerOnlyRemoval = isRemovingWorkspaceOwner && !userPermission
if (!userPermission && !isOwnerOnlyRemoval) {
return NextResponse.json({ error: 'User not found in workspace' }, { status: 404 })
}
@@ -73,8 +80,19 @@ export const DELETE = withRouteHandler(
return NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 })
}
if (
isRemovingWorkspaceOwner &&
!isSelf &&
session.user.id !== workspaceRow[0].billedAccountUserId
) {
return NextResponse.json(
{ error: 'Only the workspace owner or billing account can remove the workspace owner' },
{ status: 403 }
)
}
// Prevent removing yourself if you're the last admin
if (isSelf && userPermission.permissionType === 'admin') {
if (isSelf && userPermission?.permissionType === 'admin' && !isRemovingWorkspaceOwner) {
const otherAdmins = await db
.select()
.from(permissions)
@@ -95,18 +113,78 @@ export const DELETE = withRouteHandler(
}
}
// Delete the user's permissions for this workspace
await db
.delete(permissions)
.where(
and(
eq(permissions.userId, userId),
eq(permissions.entityType, 'workspace'),
eq(permissions.entityId, workspaceId)
)
)
const ownershipTransferred = await db.transaction(async (tx) => {
let didTransferOwnership = false
await revokeWorkspaceCredentialMemberships(workspaceId, userId)
if (isRemovingWorkspaceOwner) {
/**
* Invariant: the billed account is the org owner for org workspaces,
* the owner for personal workspaces, and a workspace admin for
* grandfathered shared workspaces.
*/
const newOwnerId = workspaceRow[0].billedAccountUserId
await tx
.update(workspace)
.set({ ownerId: newOwnerId, updatedAt: new Date() })
.where(eq(workspace.id, workspaceId))
const [existingNewOwnerPermission] = await tx
.select({ id: permissions.id })
.from(permissions)
.where(
and(
eq(permissions.userId, newOwnerId),
eq(permissions.entityType, 'workspace'),
eq(permissions.entityId, workspaceId)
)
)
.limit(1)
if (existingNewOwnerPermission) {
await tx
.update(permissions)
.set({ permissionType: 'admin', updatedAt: new Date() })
.where(eq(permissions.id, existingNewOwnerPermission.id))
} else {
const now = new Date()
await tx.insert(permissions).values({
id: generateId(),
userId: newOwnerId,
entityType: 'workspace',
entityId: workspaceId,
permissionType: 'admin',
createdAt: now,
updatedAt: now,
})
}
didTransferOwnership = true
}
await tx
.delete(permissions)
.where(
and(
eq(permissions.userId, userId),
eq(permissions.entityType, 'workspace'),
eq(permissions.entityId, workspaceId)
)
)
await revokeWorkspaceCredentialMembershipsTx(tx, workspaceId, userId)
await tx
.delete(permissionGroupMember)
.where(
and(
eq(permissionGroupMember.userId, userId),
eq(permissionGroupMember.workspaceId, workspaceId)
)
)
return didTransferOwnership
})
captureServerEvent(
session.user.id,
@@ -126,8 +204,9 @@ export const DELETE = withRouteHandler(
description: isSelf ? 'Left the workspace' : `Removed member ${userId} from the workspace`,
metadata: {
removedUserId: userId,
removedUserRole: userPermission.permissionType,
removedUserRole: userPermission?.permissionType ?? 'owner',
selfRemoval: isSelf,
ownershipTransferred,
},
request: req,
})

View File

@@ -794,7 +794,7 @@ export function useKnowledgeUpload(options: UseKnowledgeUploadOptions = {}) {
}
throw new DirectUploadError(
`Failed to upload ${file.name}: ${errorData?.error || 'Unknown error'}`,
`Failed to upload ${file.name}: ${errorData?.message || errorData?.error || 'Unknown error'}`,
errorData
)
}

View File

@@ -75,11 +75,11 @@ function apportionCredits(
return result
}
function RoleBadge({ role }: { role: string }) {
const variant = role === 'owner' ? 'blue-secondary' : 'gray-secondary'
function RoleBadge({ memberRole }: { memberRole: string }) {
const variant = memberRole === 'owner' ? 'blue-secondary' : 'gray-secondary'
return (
<Badge variant={variant} size='sm'>
{role.charAt(0).toUpperCase() + role.slice(1)}
{memberRole.charAt(0).toUpperCase() + memberRole.slice(1)}
</Badge>
)
}
@@ -521,6 +521,7 @@ export function OrganizationRoster({
const rowKey = `member-${m.memberId}`
const expanded = expandedRows.has(rowKey)
const isSelf = m.email === currentUserEmail
const isExternal = m.role === 'external'
const credits = memberCredits[m.userId] ?? 0
const canRemove = isAdminOrOwner && m.role !== 'owner' && !isSelf
const canTransferAndLeave = isSelf && m.role === 'owner' && !!onTransferOwnership
@@ -545,8 +546,11 @@ export function OrganizationRoster({
</button>
</TableCell>
<TableCell>
{m.role === 'owner' || !canEditRoles || m.userId === currentUserId ? (
<RoleBadge role={m.role} />
{m.role === 'owner' ||
isExternal ||
!canEditRoles ||
m.userId === currentUserId ? (
<RoleBadge memberRole={m.role} />
) : (
<OrgRoleSelector
value={(m.role === 'admin' ? 'admin' : 'member') as OrgRole}
@@ -630,6 +634,7 @@ export function OrganizationRoster({
{filteredInvitations.map((inv) => {
const rowKey = `invite-${inv.id}`
const expanded = expandedRows.has(rowKey)
const isExternal = inv.membershipIntent === 'external'
const isResending = resendingIds.has(inv.id)
const isCancelling = cancellingIds.has(inv.id)
const cooldown = resendCooldowns[inv.id] ?? 0
@@ -660,7 +665,9 @@ export function OrganizationRoster({
</button>
</TableCell>
<TableCell>
{isAdminOrOwner ? (
{isExternal ? (
<RoleBadge memberRole='external' />
) : isAdminOrOwner ? (
<OrgRoleSelector
value={(inv.role === 'admin' ? 'admin' : 'member') as OrgRole}
onChange={(next) =>
@@ -677,7 +684,7 @@ export function OrganizationRoster({
disabled={updateInvitation.isPending}
/>
) : (
<RoleBadge role={inv.role} />
<RoleBadge memberRole={inv.role} />
)}
</TableCell>
<TableCell className='text-right'>

View File

@@ -12,7 +12,10 @@ interface RemoveMemberDialogProps {
open: boolean
memberName: string
shouldReduceSeats: boolean
canReduceSeats?: boolean
isSelfRemoval?: boolean
isExternalRemoval?: boolean
isSubmitting?: boolean
error?: Error | null
onOpenChange: (open: boolean) => void
onShouldReduceSeatsChange: (shouldReduce: boolean) => void
@@ -24,21 +27,37 @@ export function RemoveMemberDialog({
open,
memberName,
shouldReduceSeats,
canReduceSeats = true,
error,
onOpenChange,
onShouldReduceSeatsChange,
onConfirmRemove,
onCancel,
isSelfRemoval = false,
isExternalRemoval = false,
isSubmitting = false,
}: RemoveMemberDialogProps) {
const title = isSelfRemoval
? 'Leave Organization'
: isExternalRemoval
? 'Remove External Member'
: 'Remove Team Member'
return (
<Modal open={open} onOpenChange={onOpenChange}>
<ModalContent size='sm'>
<ModalHeader>{isSelfRemoval ? 'Leave Organization' : 'Remove Team Member'}</ModalHeader>
<ModalHeader>{title}</ModalHeader>
<ModalBody>
<p className='text-[var(--text-secondary)]'>
{isSelfRemoval ? (
'Are you sure you want to leave this organization? You will lose access to all team resources.'
) : isExternalRemoval ? (
<>
Are you sure you want to remove{' '}
<span className='font-medium text-[var(--text-primary)]'>{memberName}</span> from
all organization workspaces? Their workspace access and workspace credential access
will be revoked.
</>
) : (
<>
Are you sure you want to remove{' '}
@@ -49,7 +68,7 @@ export function RemoveMemberDialog({
This action cannot be undone.
</p>
{!isSelfRemoval && (
{!isSelfRemoval && !isExternalRemoval && canReduceSeats && (
<div className='mt-4'>
<div className='flex items-center gap-2'>
<Checkbox
@@ -77,10 +96,16 @@ export function RemoveMemberDialog({
)}
</ModalBody>
<ModalFooter>
<Button variant='default' onClick={onCancel}>
<Button variant='default' disabled={isSubmitting} onClick={onCancel}>
Cancel
</Button>
<Button variant='destructive' onClick={() => onConfirmRemove(shouldReduceSeats)}>
<Button
variant='destructive'
disabled={isSubmitting}
onClick={() =>
onConfirmRemove(isExternalRemoval || !canReduceSeats ? false : shouldReduceSeats)
}
>
{isSelfRemoval ? 'Leave Organization' : 'Remove'}
</Button>
</ModalFooter>

View File

@@ -53,7 +53,9 @@ export function TransferOwnershipDialog({
const [selectedUserId, setSelectedUserId] = useState<string | null>(null)
const candidates = useMemo(() => {
const others = members.filter((m) => m.userId !== currentUserId && m.role !== 'owner')
const others = members.filter(
(m) => m.userId !== currentUserId && m.role !== 'owner' && m.role !== 'external'
)
others.sort((a, b) => {
if (a.role === 'admin' && b.role !== 'admin') return -1
if (a.role !== 'admin' && b.role === 'admin') return 1
@@ -66,7 +68,9 @@ export function TransferOwnershipDialog({
)
}, [members, currentUserId, search])
const hasCandidates = members.some((m) => m.userId !== currentUserId && m.role !== 'owner')
const hasCandidates = members.some(
(m) => m.userId !== currentUserId && m.role !== 'owner' && m.role !== 'external'
)
const handleClose = (next: boolean) => {
if (!next) {

View File

@@ -6,14 +6,9 @@ import { Skeleton, type TagItem } from '@/components/emcn'
import { useSession } from '@/lib/auth/auth-client'
import { getSubscriptionAccessState } from '@/lib/billing/client/utils'
import { getPlanTierCredits, getPlanTierDollars } from '@/lib/billing/plan-helpers'
import { checkEnterprisePlan } from '@/lib/billing/subscriptions/utils'
import { checkEnterprisePlan, checkTeamPlan } from '@/lib/billing/subscriptions/utils'
import { getBaseUrl } from '@/lib/core/utils/urls'
import {
generateSlug,
getUsedSeats,
isAdminOrOwner,
type Member,
} from '@/lib/workspaces/organization'
import { generateSlug, isAdminOrOwner, type Member } from '@/lib/workspaces/organization'
import {
MemberInvitationCard,
NoOrganizationView,
@@ -93,6 +88,7 @@ export function TeamManagement() {
memberName: string
shouldReduceSeats: boolean
isSelfRemoval?: boolean
isExternalRemoval?: boolean
}>({ open: false, memberId: '', memberName: '', shouldReduceSeats: false })
const [transferDialogOpen, setTransferDialogOpen] = useState(false)
const [transferPortalError, setTransferPortalError] = useState<string | null>(null)
@@ -108,8 +104,9 @@ export function TeamManagement() {
)
const adminOrOwner = isAdminOrOwner(organization, session?.user?.email)
const usedSeats = getUsedSeats(organization)
const totalSeats = organizationBillingData?.data?.totalSeats ?? 0
const usedSeats = organizationBillingData?.data?.usedSeats ?? 0
const canReduceSubscriptionSeats = Boolean(subscriptionData && checkTeamPlan(subscriptionData))
useEffect(() => {
if ((hasTeamPlan || hasEnterprisePlan) && session?.user?.name && !orgName) {
@@ -209,6 +206,7 @@ export function TeamManagement() {
memberName: displayName,
shouldReduceSeats: false,
isSelfRemoval: isLeavingSelf,
isExternalRemoval: member.role === 'external',
})
},
[session?.user, activeOrganization?.id]
@@ -225,11 +223,13 @@ export function TeamManagement() {
orgId: activeOrganization?.id,
shouldReduceSeats,
})
setRemoveMemberDialog({
open: false,
memberId: '',
memberName: '',
shouldReduceSeats: false,
isExternalRemoval: false,
})
if (isSelfRemoval) {
@@ -446,7 +446,7 @@ export function TeamManagement() {
subscriptionData={subscriptionData || null}
isLoadingSubscription={isLoadingSubscription}
totalSeats={totalSeats}
usedSeats={usedSeats.used}
usedSeats={usedSeats}
isLoading={isLoading}
onAddSeatDialog={handleAddSeatDialog}
/>
@@ -466,7 +466,7 @@ export function TeamManagement() {
onLoadUserWorkspaces={async () => {}}
onWorkspaceToggle={handleWorkspaceToggle}
inviteSuccess={inviteSuccess}
availableSeats={Math.max(0, totalSeats - usedSeats.used)}
availableSeats={Math.max(0, totalSeats - usedSeats)}
maxSeats={totalSeats}
invitationError={inviteMutation.error}
isLoadingWorkspaces={isLoadingWorkspaces}
@@ -504,7 +504,10 @@ export function TeamManagement() {
open={removeMemberDialog.open}
memberName={removeMemberDialog.memberName}
shouldReduceSeats={removeMemberDialog.shouldReduceSeats}
canReduceSeats={canReduceSubscriptionSeats}
isSelfRemoval={removeMemberDialog.isSelfRemoval}
isExternalRemoval={removeMemberDialog.isExternalRemoval}
isSubmitting={removeMemberMutation.isPending}
error={removeMemberMutation.error}
onOpenChange={(open: boolean) => {
if (!open) setRemoveMemberDialog({ ...removeMemberDialog, open: false })
@@ -523,6 +526,7 @@ export function TeamManagement() {
memberName: '',
shouldReduceSeats: false,
isSelfRemoval: false,
isExternalRemoval: false,
})
}
/>

View File

@@ -78,8 +78,10 @@ export function useProfilePictureUpload({
})
if (!response.ok) {
const errorData = await response.json().catch(() => ({ error: response.statusText }))
throw new Error(errorData.error || `Failed to upload file: ${response.status}`)
const errorData = await response.json().catch(() => ({ message: response.statusText }))
throw new Error(
errorData.message || errorData.error || `Failed to upload file: ${response.status}`
)
}
const data = await response.json()

View File

@@ -2,7 +2,9 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { createLogger } from '@sim/logger'
import { toError } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { toast } from '@/components/emcn'
import { resolveFileType } from '@/lib/uploads/utils/file-utils'
const logger = createLogger('useFileAttachments')
@@ -147,9 +149,13 @@ export function useFileAttachments(props: UseFileAttachmentsProps) {
if (!uploadResponse.ok) {
const errorData = await uploadResponse.json().catch(() => ({
error: `Upload failed: ${uploadResponse.status}`,
message: `Upload failed: ${uploadResponse.status}`,
}))
throw new Error(errorData.error || `Failed to upload file: ${uploadResponse.status}`)
throw new Error(
errorData.message ||
errorData.error ||
`Failed to upload file: ${uploadResponse.status}`
)
}
const uploadData = await uploadResponse.json()
@@ -172,6 +178,9 @@ export function useFileAttachments(props: UseFileAttachmentsProps) {
)
} catch (error) {
logger.error(`File upload failed: ${error}`)
toast.error(`Couldn't upload "${file.name}"`, {
description: toError(error).message,
})
if (placeholder.previewUrl) URL.revokeObjectURL(placeholder.previewUrl)
setAttachedFiles((prev) => prev.filter((f) => f.id !== placeholder.id))
}

View File

@@ -328,7 +328,8 @@ export function FileUpload({
const data = await response.json()
if (!response.ok) {
const errorMessage = data.error || `Failed to upload file: ${response.status}`
const errorMessage =
data.message || data.error || `Failed to upload file: ${response.status}`
uploadErrors.push(`${file.name}: ${errorMessage}`)
setUploadError(errorMessage)

View File

@@ -494,8 +494,14 @@ export function useWorkflowExecution() {
logger.error('Unexpected upload response format:', uploadResult)
}
} else {
const errorText = await response.text()
const message = `Failed to upload ${fileData.name}: ${response.status} ${errorText}`
const cloned = response.clone()
const errorData = await response.json().catch(() => null)
const reason =
errorData?.message ||
errorData?.error ||
(await cloned.text().catch(() => '')) ||
`${response.status}`
const message = `Failed to upload ${fileData.name}: ${reason}`
logger.error(message)
if (isUploadErrorCapable(workflowInput)) {
try {

View File

@@ -89,6 +89,7 @@ export const PermissionsTable = ({
permissionType:
changes.permissionType !== undefined ? changes.permissionType : permissionType,
isCurrentUser: user.email === session?.user?.email,
isExternal: user.isExternal,
}
}) || [],
[workspacePermissions?.users, existingUserPermissionChanges, session?.user?.email]
@@ -212,6 +213,11 @@ export const PermissionsTable = ({
)}
</Badge>
)}
{user.isExternal && (
<Badge variant='default' className='text-caption'>
External
</Badge>
)}
{hasChanges && (
<Badge variant='default' className='text-caption'>
Modified

View File

@@ -8,5 +8,6 @@ export interface UserPermissions {
permissionType: PermissionType
isCurrentUser?: boolean
isPendingInvitation?: boolean
isExternal?: boolean
invitationId?: string
}

View File

@@ -2,7 +2,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { createLogger } from '@sim/logger'
import { useParams, useRouter } from 'next/navigation'
import { useParams } from 'next/navigation'
import {
Button,
type FileInputOptions,
@@ -47,7 +47,6 @@ export function InviteModal({
inviteDisabledReason = null,
organizationId = null,
}: InviteModalProps) {
const router = useRouter()
const formRef = useRef<HTMLFormElement>(null)
const [emailItems, setEmailItems] = useState<TagItem[]>([])
const [userPermissions, setUserPermissions] = useState<UserPermissions[]>([])
@@ -103,9 +102,9 @@ export function InviteModal({
const isOutOfSeats = exceedsSeatCapacity || isAtSeatCapacity
const seatLimitReason = hasSeatData
? availableSeats === 0
? `No available seats. Using ${usedSeats} of ${totalSeats}.`
? `Internal invites may fail: using ${usedSeats} of ${totalSeats} seats. External workspace invites do not require seats.`
: exceedsSeatCapacity
? `Only ${availableSeats} seat${availableSeats === 1 ? '' : 's'} available.`
? `Only ${availableSeats} internal seat${availableSeats === 1 ? '' : 's'} available. External workspace invites do not require seats.`
: null
: null
@@ -235,7 +234,7 @@ export function InviteModal({
}))
updatePermissionsMutation.mutate(
{ workspaceId, updates },
{ workspaceId, organizationId: organizationId ?? undefined, updates },
{
onSuccess: (data) => {
if (data.users && data.total !== undefined) {
@@ -253,6 +252,7 @@ export function InviteModal({
userPerms.canAdmin,
hasPendingChanges,
workspaceId,
organizationId,
existingUserPermissionChanges,
updatePermissions,
updatePermissionsMutation,
@@ -284,7 +284,7 @@ export function InviteModal({
}
removeMember.mutate(
{ userId: memberToRemove.userId, workspaceId },
{ userId: memberToRemove.userId, workspaceId, organizationId },
{
onSuccess: () => {
if (workspacePermissions) {
@@ -318,6 +318,7 @@ export function InviteModal({
workspacePermissions,
updatePermissions,
removeMember,
organizationId,
])
const handleRemoveMemberCancel = useCallback(() => {
@@ -334,7 +335,7 @@ export function InviteModal({
setErrorMessage(null)
cancelInvitation.mutate(
{ invitationId: invitationToRemove.invitationId, workspaceId },
{ invitationId: invitationToRemove.invitationId, workspaceId, organizationId },
{
onSuccess: () => {
setInvitationToRemove(null)
@@ -346,7 +347,7 @@ export function InviteModal({
},
}
)
}, [invitationToRemove, workspaceId, userPerms.canAdmin, cancelInvitation])
}, [invitationToRemove, workspaceId, userPerms.canAdmin, cancelInvitation, organizationId])
const handleRemoveInvitationCancel = useCallback(() => {
setInvitationToRemove(null)
@@ -421,23 +422,12 @@ export function InviteModal({
[workspaceId, userPerms.canAdmin, resendCooldowns, resendingInvitationIds, resendInvitation]
)
const handleUpgradeRedirect = useCallback(() => {
if (!workspaceId) return
onOpenChange(false)
router.push(`/workspace/${workspaceId}/settings/subscription`)
}, [onOpenChange, router, workspaceId])
const handleSubmit = useCallback(
(e: React.FormEvent) => {
e.preventDefault()
setErrorMessage(null)
if (isOutOfSeats) {
handleUpgradeRedirect()
return
}
if (!canInviteMembers || validEmails.length === 0 || !workspaceId) {
return
}
@@ -451,7 +441,7 @@ export function InviteModal({
})
batchSendInvitations.mutate(
{ workspaceId, invitations },
{ workspaceId, organizationId, invitations },
{
onSuccess: (result) => {
if (result.failed.length > 0) {
@@ -474,10 +464,9 @@ export function InviteModal({
},
[
canInviteMembers,
isOutOfSeats,
handleUpgradeRedirect,
validEmails,
workspaceId,
organizationId,
userPermissions,
batchSendInvitations,
]
@@ -504,6 +493,7 @@ export function InviteModal({
email: inv.email,
permissionType: inv.permissionType,
isPendingInvitation: true,
isExternal: inv.isExternal,
invitationId: inv.invitationId,
})),
[pendingInvitations]
@@ -641,10 +631,6 @@ export function InviteModal({
type='button'
variant='primary'
onClick={() => {
if (isOutOfSeats) {
handleUpgradeRedirect()
return
}
formRef.current?.requestSubmit()
}}
disabled={
@@ -653,7 +639,7 @@ export function InviteModal({
isSubmitting ||
isSaving ||
!workspaceId ||
(!isOutOfSeats && !hasNewInvites)
!hasNewInvites
}
className='ml-auto'
>
@@ -663,9 +649,7 @@ export function InviteModal({
? 'Admin Access Required'
: isSubmitting
? 'Inviting...'
: isOutOfSeats
? 'Upgrade to invite'
: 'Invite'}
: 'Invite'}
</Button>
</ModalFooter>
</form>

View File

@@ -73,8 +73,10 @@ export function useWorkspaceLogoUpload({
})
if (!response.ok) {
const errorData = await response.json().catch(() => ({ error: response.statusText }))
throw new Error(errorData.error || `Failed to upload file: ${response.status}`)
const errorData = await response.json().catch(() => ({ message: response.statusText }))
throw new Error(
errorData.message || errorData.error || `Failed to upload file: ${response.status}`
)
}
const data = await response.json()

View File

@@ -206,10 +206,7 @@ const SidebarTaskItem = memo(function SidebarTaskItem({
e.preventDefault()
onMultiSelectClick(task.id, true)
} else {
useFolderStore.setState({
selectedTasks: new Set<string>(),
lastSelectedTaskId: task.id,
})
useFolderStore.getState().selectTaskOnly(task.id)
}
}}
onContextMenu={task.id !== 'new' ? (e) => onContextMenu(e, task.id) : undefined}

View File

@@ -23,6 +23,12 @@ export const BrowserUseBlock: BlockConfig<BrowserUseResponse> = {
placeholder: 'Describe what the browser agent should do...',
required: true,
},
{
id: 'startUrl',
title: 'Start URL',
type: 'short-input',
placeholder: 'https://example.com (optional starting URL)',
},
{
id: 'variables',
title: 'Variables (Secrets)',
@@ -51,22 +57,85 @@ export const BrowserUseBlock: BlockConfig<BrowserUseResponse> = {
{ label: 'Claude 3.7 Sonnet', id: 'claude-3-7-sonnet-20250219' },
{ label: 'Claude Sonnet 4', id: 'claude-sonnet-4-20250514' },
{ label: 'Claude Sonnet 4.5', id: 'claude-sonnet-4-5-20250929' },
{ label: 'Claude Sonnet 4.6', id: 'claude-sonnet-4-6' },
{ label: 'Claude Opus 4.5', id: 'claude-opus-4-5-20251101' },
{ label: 'Llama 4 Maverick', id: 'llama-4-maverick-17b-128e-instruct' },
],
},
{
id: 'save_browser_data',
title: 'Save Browser Data',
type: 'switch',
placeholder: 'Save browser data',
},
{
id: 'profile_id',
title: 'Profile ID',
type: 'short-input',
placeholder: 'Enter browser profile ID (optional)',
},
{
id: 'maxSteps',
title: 'Max Steps',
type: 'short-input',
placeholder: '100',
mode: 'advanced',
},
{
id: 'allowedDomains',
title: 'Allowed Domains',
type: 'short-input',
placeholder: 'example.com, docs.example.com',
mode: 'advanced',
},
{
id: 'vision',
title: 'Vision',
type: 'dropdown',
options: [
{ label: 'Auto (default)', id: 'auto' },
{ label: 'Enabled', id: 'true' },
{ label: 'Disabled', id: 'false' },
],
mode: 'advanced',
},
{
id: 'flashMode',
title: 'Flash Mode',
type: 'switch',
placeholder: 'Faster but less careful navigation',
mode: 'advanced',
},
{
id: 'thinking',
title: 'Thinking',
type: 'switch',
placeholder: 'Enable extended reasoning',
mode: 'advanced',
},
{
id: 'highlightElements',
title: 'Highlight Elements',
type: 'switch',
placeholder: 'Visually mark interactive elements',
mode: 'advanced',
},
{
id: 'systemPromptExtension',
title: 'System Prompt Extension',
type: 'long-input',
placeholder: 'Append custom instructions to the agent system prompt (max 2000 chars)',
mode: 'advanced',
},
{
id: 'structuredOutput',
title: 'Structured Output Schema',
type: 'code',
language: 'json',
placeholder: 'Stringified JSON schema for structured output',
mode: 'advanced',
},
{
id: 'metadata',
title: 'Metadata',
type: 'table',
columns: ['Key', 'Value'],
mode: 'advanced',
},
{
id: 'apiKey',
title: 'API Key',
@@ -78,19 +147,68 @@ export const BrowserUseBlock: BlockConfig<BrowserUseResponse> = {
],
tools: {
access: ['browser_use_run_task'],
config: {
tool: () => 'browser_use_run_task',
params: (params) => {
const next: Record<string, any> = { ...params }
if (typeof next.maxSteps === 'string') {
const trimmed = next.maxSteps.trim()
if (trimmed === '') {
next.maxSteps = undefined
} else {
const n = Number(trimmed)
next.maxSteps = Number.isFinite(n) ? n : undefined
}
}
if (next.vision === 'true') next.vision = true
else if (next.vision === 'false') next.vision = false
if (next.metadata && Array.isArray(next.metadata)) {
const obj: Record<string, string> = {}
for (const row of next.metadata as Array<Record<string, any>>) {
const key = row?.cells?.Key ?? row?.Key
const value = row?.cells?.Value ?? row?.Value
if (key) obj[key] = String(value ?? '')
}
next.metadata = obj
}
return next
},
},
},
inputs: {
task: { type: 'string', description: 'Browser automation task' },
startUrl: { type: 'string', description: 'Starting URL for the agent' },
apiKey: { type: 'string', description: 'BrowserUse API key' },
variables: { type: 'json', description: 'Task variables' },
model: { type: 'string', description: 'AI model to use' },
save_browser_data: { type: 'boolean', description: 'Save browser data' },
variables: { type: 'json', description: 'Secrets to inject into the task' },
model: { type: 'string', description: 'LLM model to use' },
profile_id: { type: 'string', description: 'Browser profile ID for persistent sessions' },
maxSteps: { type: 'number', description: 'Maximum agent steps' },
allowedDomains: { type: 'string', description: 'Comma-separated allowed domains' },
vision: { type: 'string', description: 'Vision capability (auto / true / false)' },
flashMode: { type: 'boolean', description: 'Enable flash mode' },
thinking: { type: 'boolean', description: 'Enable extended reasoning' },
highlightElements: { type: 'boolean', description: 'Highlight interactive elements' },
systemPromptExtension: { type: 'string', description: 'Custom system prompt extension' },
structuredOutput: { type: 'string', description: 'Stringified JSON schema' },
metadata: { type: 'json', description: 'Custom key-value metadata' },
},
outputs: {
id: { type: 'string', description: 'Task execution identifier' },
success: { type: 'boolean', description: 'Task completion status' },
output: { type: 'json', description: 'Task output data' },
steps: { type: 'json', description: 'Execution steps taken' },
output: { type: 'json', description: 'Final task output (string or structured)' },
steps: {
type: 'json',
description:
'Steps the agent executed (number, memory, evaluationPreviousGoal, nextGoal, url, screenshotUrl, actions, duration)',
},
liveUrl: {
type: 'string',
description: 'Embeddable live browser session URL (active during execution)',
},
shareUrl: {
type: 'string',
description: 'Public shareable URL for the session (post-run)',
},
sessionId: { type: 'string', description: 'Browser Use session identifier' },
},
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,28 +1,6 @@
import { StagehandIcon } from '@/components/icons'
import { AuthMode, type BlockConfig, IntegrationType } from '@/blocks/types'
import type { ToolResponse } from '@/tools/types'
export interface StagehandExtractResponse extends ToolResponse {
output: {
data: Record<string, any>
}
}
export interface StagehandAgentResponse extends ToolResponse {
output: {
agentResult: {
success: boolean
completed: boolean
message: string
actions?: Array<{
type: string
description: string
result?: string
}>
}
structuredOutput?: Record<string, any>
}
}
import type { StagehandAgentResponse, StagehandExtractResponse } from '@/tools/stagehand/types'
export type StagehandResponse = StagehandExtractResponse | StagehandAgentResponse
@@ -345,6 +323,27 @@ Example 3 (Data Collection):
generationType: 'json-schema',
},
},
{
id: 'mode',
title: 'Agent Mode',
type: 'dropdown',
options: [
{ label: 'DOM (default)', id: 'dom' },
{ label: 'Hybrid', id: 'hybrid' },
{ label: 'CUA', id: 'cua' },
],
value: () => 'dom',
condition: { field: 'operation', value: 'agent' },
mode: 'advanced',
},
{
id: 'maxSteps',
title: 'Max Steps',
type: 'short-input',
placeholder: '20',
condition: { field: 'operation', value: 'agent' },
mode: 'advanced',
},
// Shared API key field
{
id: 'apiKey',
@@ -361,6 +360,19 @@ Example 3 (Data Collection):
tool: (params) => {
return params.operation === 'agent' ? 'stagehand_agent' : 'stagehand_extract'
},
params: (params) => {
const next: Record<string, any> = { ...params }
if (typeof next.maxSteps === 'string') {
const trimmed = next.maxSteps.trim()
if (trimmed === '') {
next.maxSteps = undefined
} else {
const n = Number(trimmed)
next.maxSteps = Number.isFinite(n) ? n : undefined
}
}
return next
},
},
},
inputs: {
@@ -376,6 +388,8 @@ Example 3 (Data Collection):
task: { type: 'string', description: 'Task description (agent operation)' },
variables: { type: 'json', description: 'Task variables (agent operation)' },
outputSchema: { type: 'json', description: 'Output schema (agent operation)' },
mode: { type: 'string', description: 'Agent mode: dom, hybrid, or cua (agent operation)' },
maxSteps: { type: 'number', description: 'Max agent steps (agent operation)' },
},
outputs: {
// Extract outputs
@@ -383,5 +397,10 @@ Example 3 (Data Collection):
// Agent outputs
agentResult: { type: 'json', description: 'Agent execution result (agent operation)' },
structuredOutput: { type: 'json', description: 'Structured output data (agent operation)' },
liveViewUrl: {
type: 'string',
description: 'Embeddable Browserbase live view URL (agent operation)',
},
sessionId: { type: 'string', description: 'Browserbase session identifier (agent operation)' },
},
}

View File

@@ -169,6 +169,7 @@ import { RouterBlock, RouterV2Block } from '@/blocks/blocks/router'
import { RssBlock } from '@/blocks/blocks/rss'
import { S3Block } from '@/blocks/blocks/s3'
import { SalesforceBlock } from '@/blocks/blocks/salesforce'
import { SapS4HanaBlock } from '@/blocks/blocks/sap_s4hana'
import { ScheduleBlock } from '@/blocks/blocks/schedule'
import { SearchBlock } from '@/blocks/blocks/search'
import { SecretsManagerBlock } from '@/blocks/blocks/secrets_manager'
@@ -419,6 +420,7 @@ export const registry: Record<string, BlockConfig> = {
rss: RssBlock,
s3: S3Block,
salesforce: SalesforceBlock,
sap_s4hana: SapS4HanaBlock,
schedule: ScheduleBlock,
search: SearchBlock,
sendgrid: SendGridBlock,

View File

@@ -4045,6 +4045,7 @@ export function AsanaIcon(props: SVGProps<SVGSVGElement>) {
}
export function PipedriveIcon(props: SVGProps<SVGSVGElement>) {
const pathId = useId()
return (
<svg
{...props}
@@ -4058,7 +4059,7 @@ export function PipedriveIcon(props: SVGProps<SVGSVGElement>) {
<defs>
<path
d='M59.6807,81.1772 C59.6807,101.5343 70.0078,123.4949 92.7336,123.4949 C109.5872,123.4949 126.6277,110.3374 126.6277,80.8785 C126.6277,55.0508 113.232,37.7119 93.2944,37.7119 C77.0483,37.7119 59.6807,49.1244 59.6807,81.1772 Z M101.3006,0 C142.0482,0 169.4469,32.2728 169.4469,80.3126 C169.4469,127.5978 140.584,160.60942 99.3224,160.60942 C79.6495,160.60942 67.0483,152.1836 60.4595,146.0843 C60.5063,147.5305 60.5374,149.1497 60.5374,150.8788 L60.5374,215 L18.32565,215 L18.32565,44.157 C18.32565,41.6732 17.53126,40.8873 15.07021,40.8873 L0.5531,40.8873 L0.5531,3.4741 L35.9736,3.4741 C52.282,3.4741 56.4564,11.7741 57.2508,18.1721 C63.8708,10.7524 77.5935,0 101.3006,0 Z'
id='path-1'
id={pathId}
/>
</defs>
<g
@@ -4069,10 +4070,7 @@ export function PipedriveIcon(props: SVGProps<SVGSVGElement>) {
fillRule='evenodd'
>
<g transform='translate(67.000000, 44.000000)'>
<mask id='mask-2' fill='white'>
<use href='#path-1' />
</mask>
<use id='Clip-5' fill='#FFFFFF' xlinkHref='#path-1' />
<use fill='#FFFFFF' xlinkHref={`#${pathId}`} />
</g>
</g>
</svg>
@@ -4098,6 +4096,40 @@ export function SalesforceIcon(props: SVGProps<SVGSVGElement>) {
)
}
export function SapS4HanaIcon(props: SVGProps<SVGSVGElement>) {
const id = useId()
return (
<svg {...props} xmlns='http://www.w3.org/2000/svg' viewBox='0 0 412.38 204'>
<defs>
<linearGradient
id={id}
x1='206.19'
y1='0'
x2='206.19'
y2='204'
gradientUnits='userSpaceOnUse'
>
<stop offset='0' stopColor='#00b1eb' />
<stop offset='.212' stopColor='#009ad9' />
<stop offset='.519' stopColor='#007fc4' />
<stop offset='.792' stopColor='#006eb8' />
<stop offset='1' stopColor='#0069b4' />
</linearGradient>
</defs>
<polyline
fill={`url(#${id})`}
fillRule='evenodd'
points='0 204 208.413 204 412.38 0 0 0 0 204'
/>
<path
fill='#fff'
fillRule='evenodd'
d='m244.727,38.359l-40.593-.025v96.518l-35.46-96.518h-35.16l-30.277,80.716c-3.224-20.352-24.277-27.38-40.84-32.649-10.937-3.512-22.541-8.678-22.434-14.387.091-4.687,6.225-9.04,18.377-8.385,8.17.433,15.373,1.092,29.71,8.006l14.102-24.557c-13.088-6.658-31.169-10.867-45.985-10.883h-.086c-17.277,0-31.677,5.598-40.602,14.824-6.221,6.443-9.572,14.626-9.712,23.679-.227,12.454,4.341,21.292,13.938,28.338,8.104,5.944,18.468,9.794,27.603,12.626,11.27,3.492,20.467,6.526,20.36,13.002-.083,2.355-.977,4.552-2.671,6.337-2.807,2.897-7.124,3.986-13.084,4.098-11.497.243-20.026-1.559-33.61-9.585l-12.536,24.903c13.546,7.705,29.586,12.223,45.952,12.223l2.106-.024c14.247-.256,25.745-4.316,34.929-11.712.527-.416,1.001-.845,1.488-1.277l-4.073,10.874h36.875l6.189-18.822c6.477,2.214,13.847,3.437,21.676,3.437,7.618,0,14.795-1.17,21.156-3.252l5.965,18.637h60.137v-38.969h13.113c31.706,0,50.456-16.147,50.456-43.202,0-30.139-18.219-43.969-57.011-43.969Zm-93.816,82.587c-4.737,0-9.177-.828-13.006-2.275l12.866-40.593h.244l12.643,40.708c-3.801,1.349-8.138,2.16-12.746,2.16Zm96.199-23.324h-8.941v-32.711h8.941c11.927,0,21.437,3.961,21.437,16.139,0,12.602-9.51,16.572-21.437,16.572'
/>
</svg>
)
}
export function ServiceNowIcon(props: SVGProps<SVGSVGElement>) {
return (
<svg {...props} xmlns='http://www.w3.org/2000/svg' viewBox='0 0 71.1 63.6'>
@@ -4694,15 +4726,16 @@ export function DynamoDBIcon(props: SVGProps<SVGSVGElement>) {
}
export function IAMIcon(props: SVGProps<SVGSVGElement>) {
const id = useId()
return (
<svg {...props} viewBox='0 0 80 80' xmlns='http://www.w3.org/2000/svg'>
<defs>
<linearGradient x1='0%' y1='100%' x2='100%' y2='0%' id='iamGradient'>
<linearGradient x1='0%' y1='100%' x2='100%' y2='0%' id={id}>
<stop stopColor='#BD0816' offset='0%' />
<stop stopColor='#FF5252' offset='100%' />
</linearGradient>
</defs>
<rect fill='url(#iamGradient)' width='80' height='80' />
<rect fill={`url(#${id})`} width='80' height='80' />
<path
d='M14,59 L66,59 L66,21 L14,21 L14,59 Z M68,20 L68,60 C68,60.552 67.553,61 67,61 L13,61 C12.447,61 12,60.552 12,60 L12,20 C12,19.448 12.447,19 13,19 L67,19 C67.553,19 68,19.448 68,20 L68,20 Z M44,48 L59,48 L59,46 L44,46 L44,48 Z M57,42 L62,42 L62,40 L57,40 L57,42 Z M44,42 L52,42 L52,40 L44,40 L44,42 Z M29,46 C29,45.449 28.552,45 28,45 C27.448,45 27,45.449 27,46 C27,46.551 27.448,47 28,47 C28.552,47 29,46.551 29,46 L29,46 Z M31,46 C31,47.302 30.161,48.401 29,48.816 L29,51 L27,51 L27,48.815 C25.839,48.401 25,47.302 25,46 C25,44.346 26.346,43 28,43 C29.654,43 31,44.346 31,46 L31,46 Z M19,53.993 L36.994,54 L36.996,50 L33,50 L33,48 L36.996,48 L36.998,45 L33,45 L33,43 L36.999,43 L37,40.007 L19.006,40 L19,53.993 Z M22,38.001 L34,38.006 L34,31 C34.001,28.697 31.197,26.677 28,26.675 L27.996,26.675 C24.804,26.675 22.004,28.696 22.002,31 L22,38.001 Z M17,54.992 L17.006,39 C17.006,38.734 17.111,38.48 17.299,38.292 C17.486,38.105 17.741,38 18.006,38 L20,38.001 L20.002,31 C20.004,27.512 23.59,24.675 27.996,24.675 L28,24.675 C32.412,24.677 36.001,27.515 36,31 L36,38.007 L38,38.008 C38.553,38.008 39,38.456 39,39.008 L38.994,55 C38.994,55.266 38.889,55.52 38.701,55.708 C38.514,55.895 38.259,56 37.994,56 L18,55.992 C17.447,55.992 17,55.544 17,54.992 L17,54.992 Z M60,36 L62,36 L62,34 L60,34 L60,36 Z M44,36 L55,36 L55,34 L44,34 L44,36 Z'
fill='#FFFFFF'
@@ -4712,15 +4745,16 @@ export function IAMIcon(props: SVGProps<SVGSVGElement>) {
}
export function IdentityCenterIcon(props: SVGProps<SVGSVGElement>) {
const id = useId()
return (
<svg {...props} viewBox='0 0 80 80' xmlns='http://www.w3.org/2000/svg'>
<defs>
<linearGradient x1='0%' y1='100%' x2='100%' y2='0%' id='identityCenterGradient'>
<linearGradient x1='0%' y1='100%' x2='100%' y2='0%' id={id}>
<stop stopColor='#BD0816' offset='0%' />
<stop stopColor='#FF5252' offset='100%' />
</linearGradient>
</defs>
<rect fill='url(#identityCenterGradient)' width='80' height='80' />
<rect fill={`url(#${id})`} width='80' height='80' />
<path
d='M46.694,46.8194562 C47.376,46.1374562 47.376,45.0294562 46.694,44.3474562 C46.353,44.0074562 45.906,43.8374562 45.459,43.8374562 C45.01,43.8374562 44.563,44.0074562 44.222,44.3474562 C43.542,45.0284562 43.542,46.1384562 44.222,46.8194562 C44.905,47.5014562 46.013,47.4994562 46.694,46.8194562 M47.718,47.1374562 L51.703,51.1204562 L50.996,51.8274562 L49.868,50.6994562 L48.793,51.7754562 L48.086,51.0684562 L49.161,49.9924562 L47.011,47.8444562 C46.545,48.1654562 46.003,48.3294562 45.458,48.3294562 C44.755,48.3294562 44.051,48.0624562 43.515,47.5264562 C42.445,46.4554562 42.445,44.7124562 43.515,43.6404562 C44.586,42.5714562 46.329,42.5694562 47.401,43.6404562 C48.351,44.5904562 48.455,46.0674562 47.718,47.1374562 M53,44.1014562 C53,46.1684562 51.505,47.0934562 50.023,47.0934562 L50.023,46.0934562 C50.487,46.0934562 52,45.9494562 52,44.1014562 C52,43.0044562 51.353,42.3894562 49.905,42.1084562 C49.68,42.0654562 49.514,41.8754562 49.501,41.6484562 C49.446,40.7444562 48.987,40.1124562 48.384,40.1124562 C48.084,40.1124562 47.854,40.2424562 47.616,40.5464562 C47.506,40.6884562 47.324,40.7594562 47.147,40.7324562 C46.968,40.7054562 46.818,40.5844562 46.755,40.4144562 C46.577,39.9434562 46.211,39.4334562 45.723,38.9774562 C45.231,38.5094562 43.883,37.5074562 41.972,38.2734562 C40.885,38.7054562 40.034,39.9494562 40.034,41.1074562 C40.034,41.2354562 40.043,41.3624562 40.058,41.4884562 C40.061,41.5094562 40.062,41.5304562 40.062,41.5514562 C40.062,41.7994562 39.882,42.0064562 39.645,42.0464562 C38.886,42.2394562 38,42.7454562 38,44.0554562 L38.005,44.2104562 C38.069,45.3254562 39.252,45.9954562 40.358,45.9984562 L41,45.9984562 L41,46.9984562 L40.357,46.9984562 C38.536,46.9944562 37.095,45.8194562 37.006,44.2644562 C37.003,44.1944562 37,44.1244562 37,44.0554562 C37,42.6944562 37.752,41.6484562 39.035,41.1884562 C39.034,41.1614562 39.034,41.1344562 39.034,41.1074562 C39.034,39.5434562 40.138,37.9254562 41.602,37.3434562 C43.298,36.6654562 45.095,37.0034562 46.409,38.2494562 C46.706,38.5274562 47.076,38.9264562 47.372,39.4134562 C47.673,39.2124562 48.008,39.1124562 48.384,39.1124562 C49.257,39.1124562 50.231,39.7714562 50.458,41.2074562 C52.145,41.6324562 53,42.6054562 53,44.1014562 M27,53 L27,27 L53,27 L53,34 L51,34 L51,29 L29,29 L29,51 L51,51 L51,46 L53,46 L53,53 Z'
fill='#FFFFFF'
@@ -4730,15 +4764,16 @@ export function IdentityCenterIcon(props: SVGProps<SVGSVGElement>) {
}
export function STSIcon(props: SVGProps<SVGSVGElement>) {
const id = useId()
return (
<svg {...props} viewBox='0 0 80 80' xmlns='http://www.w3.org/2000/svg'>
<defs>
<linearGradient x1='0%' y1='100%' x2='100%' y2='0%' id='stsGradient'>
<linearGradient x1='0%' y1='100%' x2='100%' y2='0%' id={id}>
<stop stopColor='#BD0816' offset='0%' />
<stop stopColor='#FF5252' offset='100%' />
</linearGradient>
</defs>
<rect fill='url(#stsGradient)' width='80' height='80' />
<rect fill={`url(#${id})`} width='80' height='80' />
<path
d='M14,59 L66,59 L66,21 L14,21 L14,59 Z M68,20 L68,60 C68,60.552 67.553,61 67,61 L13,61 C12.447,61 12,60.552 12,60 L12,20 C12,19.448 12.447,19 13,19 L67,19 C67.553,19 68,19.448 68,20 L68,20 Z M44,48 L59,48 L59,46 L44,46 L44,48 Z M57,42 L62,42 L62,40 L57,40 L57,42 Z M44,42 L52,42 L52,40 L44,40 L44,42 Z M29,46 C29,45.449 28.552,45 28,45 C27.448,45 27,45.449 27,46 C27,46.551 27.448,47 28,47 C28.552,47 29,46.551 29,46 L29,46 Z M31,46 C31,47.302 30.161,48.401 29,48.816 L29,51 L27,51 L27,48.815 C25.839,48.401 25,47.302 25,46 C25,44.346 26.346,43 28,43 C29.654,43 31,44.346 31,46 L31,46 Z M19,53.993 L36.994,54 L36.996,50 L33,50 L33,48 L36.996,48 L36.998,45 L33,45 L33,43 L36.999,43 L37,40.007 L19.006,40 L19,53.993 Z M22,38.001 L34,38.006 L34,31 C34.001,28.697 31.197,26.677 28,26.675 L27.996,26.675 C24.804,26.675 22.004,28.696 22.002,31 L22,38.001 Z M17,54.992 L17.006,39 C17.006,38.734 17.111,38.48 17.299,38.292 C17.486,38.105 17.741,38 18.006,38 L20,38.001 L20.002,31 C20.004,27.512 23.59,24.675 27.996,24.675 L28,24.675 C32.412,24.677 36.001,27.515 36,31 L36,38.007 L38,38.008 C38.553,38.008 39,38.456 39,39.008 L38.994,55 C38.994,55.266 38.889,55.52 38.701,55.708 C38.514,55.895 38.259,56 37.994,56 L18,55.992 C17.447,55.992 17,55.544 17,54.992 L17,54.992 Z M60,36 L62,36 L62,34 L60,34 L60,36 Z M44,36 L55,36 L55,34 L44,34 L44,36 Z'
fill='#FFFFFF'
@@ -4748,15 +4783,16 @@ export function STSIcon(props: SVGProps<SVGSVGElement>) {
}
export function SESIcon(props: SVGProps<SVGSVGElement>) {
const id = useId()
return (
<svg {...props} viewBox='0 0 80 80' xmlns='http://www.w3.org/2000/svg'>
<defs>
<linearGradient x1='0%' y1='100%' x2='100%' y2='0%' id='sesGradient'>
<linearGradient x1='0%' y1='100%' x2='100%' y2='0%' id={id}>
<stop stopColor='#BD0816' offset='0%' />
<stop stopColor='#FF5252' offset='100%' />
</linearGradient>
</defs>
<rect fill='url(#sesGradient)' width='80' height='80' />
<rect fill={`url(#${id})`} width='80' height='80' />
<path
d='M57,60.999875 C57,59.373846 55.626,57.9998214 54,57.9998214 C52.374,57.9998214 51,59.373846 51,60.999875 C51,62.625904 52.374,63.9999286 54,63.9999286 C55.626,63.9999286 57,62.625904 57,60.999875 L57,60.999875 Z M40,59.9998571 C38.374,59.9998571 37,61.3738817 37,62.9999107 C37,64.6259397 38.374,65.9999643 40,65.9999643 C41.626,65.9999643 43,64.6259397 43,62.9999107 C43,61.3738817 41.626,59.9998571 40,59.9998571 L40,59.9998571 Z M26,57.9998214 C24.374,57.9998214 23,59.373846 23,60.999875 C23,62.625904 24.374,63.9999286 26,63.9999286 C27.626,63.9999286 29,62.625904 29,60.999875 C29,59.373846 27.626,57.9998214 26,57.9998214 L26,57.9998214 Z M28.605,42.9995536 L51.395,42.9995536 L43.739,36.1104305 L40.649,38.7584778 C40.463,38.9194807 40.23,38.9994821 39.999,38.9994821 C39.768,38.9994821 39.535,38.9194807 39.349,38.7584778 L36.26,36.1104305 L28.605,42.9995536 Z M27,28.1732888 L27,41.7545313 L34.729,34.7984071 L27,28.1732888 Z M51.297,26.9992678 L28.703,26.9992678 L39.999,36.6824408 L51.297,26.9992678 Z M53,41.7545313 L53,28.1732888 L45.271,34.7974071 L53,41.7545313 Z M59,60.999875 C59,63.7099234 56.71,65.9999643 54,65.9999643 C51.29,65.9999643 49,63.7099234 49,60.999875 C49,58.6308327 50.75,56.5837961 53,56.1057876 L53,52.9997321 L41,52.9997321 L41,58.1058233 C43.25,58.5838319 45,60.6308684 45,62.9999107 C45,65.7099591 42.71,68 40,68 C37.29,68 35,65.7099591 35,62.9999107 C35,60.6308684 36.75,58.5838319 39,58.1058233 L39,52.9997321 L27,52.9997321 L27,56.1057876 C29.25,56.5837961 31,58.6308327 31,60.999875 C31,63.7099234 28.71,65.9999643 26,65.9999643 C23.29,65.9999643 21,63.7099234 21,60.999875 C21,58.6308327 22.75,56.5837961 25,56.1057876 L25,51.9997143 C25,51.4477044 25.447,50.9996964 26,50.9996964 L39,50.9996964 L39,44.9995893 L26,44.9995893 C25.447,44.9995893 25,44.5515813 25,43.9995714 L25,25.99925 C25,25.4472401 25.447,24.9992321 26,24.9992321 L54,24.9992321 C54.553,24.9992321 55,25.4472401 55,25.99925 L55,43.9995714 C55,44.5515813 54.553,44.9995893 54,44.9995893 L41,44.9995893 L41,50.9996964 L54,50.9996964 C54.553,50.9996964 55,51.4477044 55,51.9997143 L55,56.1057876 C57.25,56.5837961 59,58.6308327 59,60.999875 L59,60.999875 Z M68,39.9995 C68,45.9066055 66.177,51.5597064 62.727,56.3447919 L61.104,55.174771 C64.307,50.7316916 66,45.4845979 66,39.9995 C66,25.664244 54.337,14.0000357 40.001,14.0000357 C25.664,14.0000357 14,25.664244 14,39.9995 C14,45.4845979 15.693,50.7316916 18.896,55.174771 L17.273,56.3447919 C13.823,51.5597064 12,45.9066055 12,39.9995 C12,24.5612243 24.561,12 39.999,12 C55.438,12 68,24.5612243 68,39.9995 L68,39.9995 Z'
fill='#FFFFFF'
@@ -4766,15 +4802,16 @@ export function SESIcon(props: SVGProps<SVGSVGElement>) {
}
export function SecretsManagerIcon(props: SVGProps<SVGSVGElement>) {
const id = useId()
return (
<svg {...props} viewBox='0 0 80 80' xmlns='http://www.w3.org/2000/svg'>
<defs>
<linearGradient x1='0%' y1='100%' x2='100%' y2='0%' id='secretsManagerGradient'>
<linearGradient x1='0%' y1='100%' x2='100%' y2='0%' id={id}>
<stop stopColor='#BD0816' offset='0%' />
<stop stopColor='#FF5252' offset='100%' />
</linearGradient>
</defs>
<rect fill='url(#secretsManagerGradient)' width='80' height='80' />
<rect fill={`url(#${id})`} width='80' height='80' />
<path
d='M38.76,43.36 C38.76,44.044 39.317,44.6 40,44.6 C40.684,44.6 41.24,44.044 41.24,43.36 C41.24,42.676 40.684,42.12 40,42.12 C39.317,42.12 38.76,42.676 38.76,43.36 L38.76,43.36 Z M36.76,43.36 C36.76,41.573 38.213,40.12 40,40.12 C41.787,40.12 43.24,41.573 43.24,43.36 C43.24,44.796 42.296,46.002 41,46.426 L41,49 L39,49 L39,46.426 C37.704,46.002 36.76,44.796 36.76,43.36 L36.76,43.36 Z M49,38 L31,38 L31,51 L49,51 L49,48 L46,48 L46,46 L49,46 L49,43 L46,43 L46,41 L49,41 L49,38 Z M34,36 L45.999,36 L46,31 C46.001,28.384 43.143,26.002 40.004,26 L40.001,26 C38.472,26 36.928,26.574 35.763,27.575 C34.643,28.537 34,29.786 34,31.001 L34,36 Z M48,31.001 L47.999,36 L50,36 C50.553,36 51,36.448 51,37 L51,52 C51,52.552 50.553,53 50,53 L30,53 C29.447,53 29,52.552 29,52 L29,37 C29,36.448 29.447,36 30,36 L32,36 L32,31 C32.001,29.202 32.897,27.401 34.459,26.058 C35.982,24.75 38.001,24 40.001,24 L40.004,24 C44.265,24.002 48.001,27.273 48,31.001 L48,31.001 Z M19.207,55.049 L20.828,53.877 C18.093,50.097 16.581,45.662 16.396,41 L19,41 L19,39 L16.399,39 C16.598,34.366 18.108,29.957 20.828,26.198 L19.207,25.025 C16.239,29.128 14.599,33.942 14.399,39 L12,39 L12,41 L14.396,41 C14.582,46.086 16.224,50.926 19.207,55.049 L19.207,55.049 Z M53.838,59.208 C50.069,61.936 45.648,63.446 41,63.639 L41,61 L39,61 L39,63.639 C34.352,63.447 29.93,61.937 26.159,59.208 L24.988,60.828 C29.1,63.805 33.928,65.445 39,65.639 L39,68 L41,68 L41,65.639 C46.072,65.445 50.898,63.805 55.01,60.828 L53.838,59.208 Z M26.159,20.866 C29.93,18.138 34.352,16.628 39,16.436 L39,19 L41,19 L41,16.436 C45.648,16.628 50.069,18.138 53.838,20.866 L55.01,19.246 C50.898,16.27 46.072,14.63 41,14.436 L41,12 L39,12 L39,14.436 C33.928,14.629 29.1,16.269 24.988,19.246 L26.159,20.866 Z M65.599,39 C65.399,33.942 63.759,29.128 60.79,25.025 L59.169,26.198 C61.89,29.957 63.4,34.366 63.599,39 L61,39 L61,41 L63.602,41 C63.416,45.662 61.905,50.097 59.169,53.877 L60.79,55.049 C63.774,50.926 65.415,46.086 65.602,41 L68,41 L68,39 L65.599,39 Z M56.386,25.064 L64.226,17.224 L62.812,15.81 L54.972,23.65 L56.386,25.064 Z M23.612,55.01 L15.772,62.85 L17.186,64.264 L25.026,56.424 L23.612,55.01 Z M28.666,27.253 L13.825,12.413 L12.411,13.827 L27.252,28.667 L28.666,27.253 Z M54.193,52.78 L67.586,66.173 L66.172,67.587 L52.779,54.194 L54.193,52.78 Z'
fill='#FFFFFF'

View File

@@ -717,10 +717,13 @@ export class LoopOrchestrator {
})
if (vmResult.error) {
logger.error('Failed to evaluate loop condition', {
const isSystemError = vmResult.error.isSystemError === true
const logFn = isSystemError ? logger.error.bind(logger) : logger.warn.bind(logger)
logFn('Failed to evaluate loop condition', {
condition,
evaluatedCondition,
error: vmResult.error,
isSystemError,
})
return false
}

View File

@@ -1,11 +1,8 @@
import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { workspaceCredentialKeys } from '@/hooks/queries/credentials'
import { organizationKeys } from '@/hooks/queries/organization'
import { workspaceKeys } from './workspace'
/**
* Query key factory for invitation-related queries.
* Provides hierarchical cache keys for workspace invitations.
*/
export const invitationKeys = {
all: ['invitations'] as const,
lists: () => [...invitationKeys.all, 'list'] as const,
@@ -17,6 +14,7 @@ export interface PendingInvitationRow {
workspaceId: string
email: string
permission: 'admin' | 'write' | 'read'
membershipIntent?: 'internal' | 'external'
status: string
createdAt: string
}
@@ -25,6 +23,7 @@ export interface WorkspaceInvitation {
email: string
permissionType: 'admin' | 'write' | 'read'
isPendingInvitation: boolean
isExternal: boolean
invitationId?: string
}
@@ -49,6 +48,7 @@ async function fetchPendingInvitations(
email: inv.email,
permissionType: inv.permission,
isPendingInvitation: true,
isExternal: inv.membershipIntent === 'external',
invitationId: inv.id,
})) || []
)
@@ -70,6 +70,7 @@ export function usePendingInvitations(workspaceId: string | undefined) {
interface BatchSendInvitationsParams {
workspaceId: string
organizationId?: string | null
invitations: Array<{ email: string; permission: 'admin' | 'write' | 'read' }>
}
@@ -79,7 +80,7 @@ interface BatchInvitationResult {
}
/**
* Sends multiple workspace invitations in parallel.
* Sends workspace invitations through the server-side batch endpoint.
* Returns results for each invitation indicating success or failure.
*/
export function useBatchSendWorkspaceInvitations() {
@@ -90,45 +91,38 @@ export function useBatchSendWorkspaceInvitations() {
workspaceId,
invitations,
}: BatchSendInvitationsParams): Promise<BatchInvitationResult> => {
const results = await Promise.allSettled(
invitations.map(async ({ email, permission }) => {
const response = await fetch('/api/workspaces/invitations', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
workspaceId,
email,
permission,
}),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.error || 'Failed to send invitation')
}
return { email, data: await response.json() }
})
)
const successful: string[] = []
const failed: Array<{ email: string; error: string }> = []
results.forEach((result, index) => {
const email = invitations[index].email
if (result.status === 'fulfilled') {
successful.push(email)
} else {
failed.push({ email, error: result.reason?.message || 'Unknown error' })
}
const response = await fetch('/api/workspaces/invitations/batch', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
workspaceId,
invitations,
}),
})
return { successful, failed }
const result = await response.json()
if (!response.ok) {
throw new Error(result.error || 'Failed to send invitations')
}
return {
successful: result.successful ?? [],
failed: result.failed ?? [],
}
},
onSuccess: (_data, variables) => {
onSettled: (_data, _error, variables) => {
queryClient.invalidateQueries({
queryKey: invitationKeys.list(variables.workspaceId),
})
if (variables.organizationId) {
queryClient.invalidateQueries({
queryKey: organizationKeys.roster(variables.organizationId),
})
queryClient.invalidateQueries({
queryKey: organizationKeys.billing(variables.organizationId),
})
}
},
})
}
@@ -136,6 +130,7 @@ export function useBatchSendWorkspaceInvitations() {
interface CancelInvitationParams {
invitationId: string
workspaceId: string
organizationId?: string | null
}
/**
@@ -159,10 +154,18 @@ export function useCancelWorkspaceInvitation() {
return response.json()
},
onSuccess: (_data, variables) => {
onSettled: (_data, _error, variables) => {
queryClient.invalidateQueries({
queryKey: invitationKeys.list(variables.workspaceId),
})
if (variables.organizationId) {
queryClient.invalidateQueries({
queryKey: organizationKeys.roster(variables.organizationId),
})
queryClient.invalidateQueries({
queryKey: organizationKeys.billing(variables.organizationId),
})
}
},
})
}
@@ -204,6 +207,7 @@ export function useResendWorkspaceInvitation() {
interface RemoveMemberParams {
userId: string
workspaceId: string
organizationId?: string | null
}
/**
@@ -232,6 +236,17 @@ export function useRemoveWorkspaceMember() {
queryClient.invalidateQueries({
queryKey: workspaceKeys.permissions(variables.workspaceId),
})
queryClient.invalidateQueries({
queryKey: workspaceKeys.members(variables.workspaceId),
})
queryClient.invalidateQueries({
queryKey: workspaceCredentialKeys.all,
})
if (variables.organizationId) {
queryClient.invalidateQueries({
queryKey: organizationKeys.roster(variables.organizationId),
})
}
},
})
}

View File

@@ -3,10 +3,12 @@ import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tansta
import { client } from '@/lib/auth/auth-client'
import { isEnterprise, isPaid, isTeam } from '@/lib/billing/plan-helpers'
import { hasPaidSubscriptionStatus } from '@/lib/billing/subscriptions/utils'
import { workspaceCredentialKeys } from '@/hooks/queries/credentials'
import { subscriptionKeys } from '@/hooks/queries/subscription'
import { workspaceKeys } from '@/hooks/queries/workspace'
const logger = createLogger('OrganizationQueries')
const invitationListsKey = ['invitations', 'list'] as const
/**
* Query key factories for organization-related queries
@@ -33,7 +35,7 @@ export type RosterWorkspaceAccess = {
export type RosterMember = {
memberId: string
userId: string
role: string
role: 'owner' | 'admin' | 'member' | 'external'
createdAt: string
name: string
email: string
@@ -46,6 +48,7 @@ export type RosterPendingInvitation = {
email: string
role: string
kind: 'organization' | 'workspace'
membershipIntent?: 'internal' | 'external'
createdAt: string
expiresAt: string
inviteeName: string | null
@@ -401,6 +404,9 @@ export function useRemoveMember() {
queryClient.invalidateQueries({ queryKey: organizationKeys.roster(variables.orgId) })
queryClient.invalidateQueries({ queryKey: organizationKeys.lists() })
queryClient.invalidateQueries({ queryKey: subscriptionKeys.all })
queryClient.invalidateQueries({ queryKey: workspaceKeys.all })
queryClient.invalidateQueries({ queryKey: workspaceCredentialKeys.all })
queryClient.invalidateQueries({ queryKey: invitationListsKey })
},
})
}
@@ -531,7 +537,9 @@ export function useCancelInvitation() {
onSuccess: (_data, variables) => {
queryClient.invalidateQueries({ queryKey: organizationKeys.detail(variables.orgId) })
queryClient.invalidateQueries({ queryKey: organizationKeys.roster(variables.orgId) })
queryClient.invalidateQueries({ queryKey: organizationKeys.billing(variables.orgId) })
queryClient.invalidateQueries({ queryKey: organizationKeys.lists() })
queryClient.invalidateQueries({ queryKey: invitationListsKey })
},
})
}

View File

@@ -1,4 +1,4 @@
import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type { PersistedMessage } from '@/lib/copilot/chat/persisted-message'
import { normalizeMessage } from '@/lib/copilot/chat/persisted-message'
import {
@@ -254,7 +254,6 @@ export function useTasks(workspaceId?: string) {
queryKey: taskKeys.list(workspaceId),
queryFn: ({ signal }) => fetchTasks(workspaceId as string, signal),
enabled: Boolean(workspaceId),
placeholderData: keepPreviousData,
staleTime: 60 * 1000,
})
}
@@ -535,6 +534,10 @@ async function markTaskUnread(chatId: string): Promise<void> {
/**
* Marks a task as read with optimistic update.
*
* The server only updates `lastSeenAt`, never `updatedAt`, so we deliberately
* do not invalidate the list cache — that would trigger a refetch that can
* reorder the sidebar if any unrelated server-side update landed in between.
*/
export function useMarkTaskRead(workspaceId?: string) {
const queryClient = useQueryClient()
@@ -556,14 +559,14 @@ export function useMarkTaskRead(workspaceId?: string) {
queryClient.setQueryData(taskKeys.list(workspaceId), context.previousTasks)
}
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: taskKeys.list(workspaceId) })
},
})
}
/**
* Marks a task as unread with optimistic update.
*
* Same rationale as `useMarkTaskRead` — no list invalidation, since the server
* only flips `lastSeenAt` and the optimistic update fully reflects the change.
*/
export function useMarkTaskUnread(workspaceId?: string) {
const queryClient = useQueryClient()
@@ -585,8 +588,5 @@ export function useMarkTaskUnread(workspaceId?: string) {
queryClient.setQueryData(taskKeys.list(workspaceId), context.previousTasks)
}
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: taskKeys.list(workspaceId) })
},
})
}

View File

@@ -251,6 +251,7 @@ export interface WorkspaceUser {
name: string | null
image: string | null
permissionType: 'admin' | 'write' | 'read'
isExternal: boolean
}
/** Viewer context for a workspace permissions response. */

View File

@@ -50,12 +50,9 @@ describe('handleTaskStatusEvent', () => {
})
})
it('preserves list invalidation when task event payload is invalid', () => {
it('does not invalidate when task event payload is invalid', () => {
handleTaskStatusEvent(queryClient, 'ws-1', '{')
expect(queryClient.invalidateQueries).toHaveBeenCalledTimes(1)
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({
queryKey: taskKeys.list('ws-1'),
})
expect(queryClient.invalidateQueries).not.toHaveBeenCalled()
})
})

View File

@@ -41,13 +41,13 @@ export function handleTaskStatusEvent(
workspaceId: string,
data: unknown
): void {
queryClient.invalidateQueries({ queryKey: taskKeys.list(workspaceId) })
const payload = parseTaskStatusEventPayload(data)
if (!payload) {
logger.warn('Received invalid task_status payload')
return
}
queryClient.invalidateQueries({ queryKey: taskKeys.list(workspaceId) })
}
/**

View File

@@ -19,11 +19,6 @@ describe('extractSessionDataFromAuthClientResult', () => {
expect(extractSessionDataFromAuthClientResult({ data: session })).toEqual(session)
})
it('unwraps disabled-auth get-session responses wrapped by the auth client', () => {
const session = { user: { id: 'u1' }, session: { id: 's1' } }
expect(extractSessionDataFromAuthClientResult({ data: { data: session } })).toEqual(session)
})
it('falls back to raw session payload shape', () => {
const raw = { user: { id: 'u1' }, session: { id: 's1' } }
expect(extractSessionDataFromAuthClientResult(raw)).toEqual(raw)

View File

@@ -7,23 +7,7 @@ export function extractSessionDataFromAuthClientResult(result: unknown): unknown
// Expected shape from better-auth client: { data: <session> }
if ('data' in record) {
const data = (record as { data?: unknown }).data
if (!data || typeof data !== 'object') {
return null
}
const dataRecord = data as Record<string, unknown>
if ('user' in dataRecord) {
return data
}
if ('data' in dataRecord) {
return dataRecord.data ?? null
}
return data
return (record as { data?: unknown }).data ?? null
}
// Fallback for raw session payloads: { user, session }

View File

@@ -1,7 +1,7 @@
import { db } from '@sim/db'
import { member, organization, user, userStats } from '@sim/db/schema'
import { invitation, member, organization, user, userStats } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { and, eq } from 'drizzle-orm'
import { and, count, eq, gt, ne } from 'drizzle-orm'
import { isOrganizationBillingBlocked } from '@/lib/billing/core/access'
import { getOrganizationSubscription, getPlanPricing } from '@/lib/billing/core/billing'
import {
@@ -172,6 +172,19 @@ export async function getOrganizationBillingData(
const averageUsagePerMember = members.length > 0 ? totalCurrentUsage / members.length : 0
const [pendingInvitationCount] = await db
.select({ count: count() })
.from(invitation)
.where(
and(
eq(invitation.organizationId, organizationId),
eq(invitation.status, 'pending'),
ne(invitation.membershipIntent, 'external'),
gt(invitation.expiresAt, new Date())
)
)
const usedSeats = members.length + (pendingInvitationCount?.count ?? 0)
const billingPeriodStart = subscription.periodStart || null
const billingPeriodEnd = subscription.periodEnd || null
@@ -181,7 +194,7 @@ export async function getOrganizationBillingData(
subscriptionPlan: subscription.plan,
subscriptionStatus: subscription.status || 'inactive',
totalSeats: effectiveSeats,
usedSeats: members.length,
usedSeats,
seatsCount: licensedSeats,
totalCurrentUsage: roundCurrency(totalCurrentUsage),
totalUsageLimit: roundCurrency(totalUsageLimit),

View File

@@ -7,8 +7,12 @@
import { db } from '@sim/db'
import {
credential,
credentialMember,
invitation,
member,
organization,
permissionGroupMember,
permissions,
subscription as subscriptionTable,
user,
@@ -25,7 +29,7 @@ import { toDecimal, toNumber } from '@/lib/billing/utils/decimal'
import { validateSeatAvailability } from '@/lib/billing/validation/seat-management'
import { OUTBOX_EVENT_TYPES } from '@/lib/billing/webhooks/outbox-handlers'
import { enqueueOutboxEvent } from '@/lib/core/outbox/service'
import { revokeWorkspaceCredentialMemberships } from '@/lib/credentials/access'
import type { DbOrTx } from '@/lib/db/types'
const logger = createLogger('OrganizationMembership')
@@ -233,6 +237,7 @@ export interface AddMemberResult {
success: boolean
memberId?: string
error?: string
failureCode?: MembershipAdditionFailureCode
billingActions: {
proUsageSnapshotted: boolean
/**
@@ -265,12 +270,200 @@ export interface RemoveMemberResult {
proRestored: boolean
usageRestored: boolean
workspaceAccessRevoked: number
pendingInvitationsCancelled: number
}
}
export interface RemoveExternalWorkspaceAccessResult {
success: boolean
error?: string
workspaceAccessRevoked: number
permissionGroupsRevoked: number
credentialMembershipsRevoked: number
pendingInvitationsCancelled: number
}
export type MembershipAdditionFailureCode =
| 'user-not-found'
| 'organization-not-found'
| 'already-member'
| 'already-in-other-organization'
| 'no-seats-available'
async function reassignOwnedOrganizationWorkspacesTx({
tx,
userId,
organizationId,
workspaceIds,
}: {
tx: DbOrTx
userId: string
organizationId: string
workspaceIds: string[]
}) {
const [ownerMembership] = await tx
.select({ userId: member.userId })
.from(member)
.where(and(eq(member.organizationId, organizationId), eq(member.role, 'owner')))
.limit(1)
const ownerId = ownerMembership?.userId
if (!ownerId || ownerId === userId || workspaceIds.length === 0) return 0
const reassignedWorkspaces = await tx
.update(workspace)
.set({ ownerId, updatedAt: new Date() })
.where(
and(
eq(workspace.organizationId, organizationId),
eq(workspace.ownerId, userId),
inArray(workspace.id, workspaceIds)
)
)
.returning({ id: workspace.id })
if (reassignedWorkspaces.length === 0) return 0
const now = new Date()
await tx
.update(permissions)
.set({ permissionType: 'admin', updatedAt: now })
.where(
and(
eq(permissions.userId, ownerId),
eq(permissions.entityType, 'workspace'),
inArray(
permissions.entityId,
reassignedWorkspaces.map((row) => row.id)
)
)
)
await tx
.insert(permissions)
.values(
reassignedWorkspaces.map((row) => ({
id: generateId(),
userId: ownerId,
entityType: 'workspace',
entityId: row.id,
permissionType: 'admin' as const,
createdAt: now,
updatedAt: now,
}))
)
.onConflictDoNothing()
return reassignedWorkspaces.length
}
async function revokeWorkspaceCredentialMembershipsTx({
tx,
workspaceIds,
userId,
}: {
tx: DbOrTx
workspaceIds: string[]
userId: string
}) {
if (workspaceIds.length === 0) return 0
const workspaceCredentialRows = await tx
.select({
credentialId: credential.id,
workspaceId: credential.workspaceId,
ownerId: workspace.ownerId,
})
.from(credential)
.innerJoin(workspace, eq(credential.workspaceId, workspace.id))
.where(inArray(credential.workspaceId, workspaceIds))
if (workspaceCredentialRows.length === 0) return 0
const credentialIds = workspaceCredentialRows.map((row) => row.credentialId)
const ownerByCredentialId = new Map(
workspaceCredentialRows.map((row) => [row.credentialId, row.ownerId])
)
const userAdminMemberships = await tx
.select({ credentialId: credentialMember.credentialId })
.from(credentialMember)
.where(
and(
eq(credentialMember.userId, userId),
eq(credentialMember.role, 'admin'),
eq(credentialMember.status, 'active'),
inArray(credentialMember.credentialId, credentialIds)
)
)
for (const { credentialId } of userAdminMemberships) {
const ownerId = ownerByCredentialId.get(credentialId)
if (!ownerId || ownerId === userId) continue
const otherAdmins = await tx
.select({ id: credentialMember.id })
.from(credentialMember)
.where(
and(
eq(credentialMember.credentialId, credentialId),
eq(credentialMember.role, 'admin'),
eq(credentialMember.status, 'active'),
ne(credentialMember.userId, userId)
)
)
.limit(1)
if (otherAdmins.length > 0) continue
const now = new Date()
const [existingOwnerMembership] = await tx
.select({ id: credentialMember.id })
.from(credentialMember)
.where(
and(eq(credentialMember.credentialId, credentialId), eq(credentialMember.userId, ownerId))
)
.limit(1)
if (existingOwnerMembership) {
await tx
.update(credentialMember)
.set({ role: 'admin', status: 'active', updatedAt: now })
.where(eq(credentialMember.id, existingOwnerMembership.id))
} else {
await tx.insert(credentialMember).values({
id: generateId(),
credentialId,
userId: ownerId,
role: 'admin',
status: 'active',
joinedAt: now,
invitedBy: ownerId,
createdAt: now,
updatedAt: now,
})
}
}
const revokedMemberships = await tx
.update(credentialMember)
.set({ status: 'revoked', updatedAt: new Date() })
.where(
and(
eq(credentialMember.userId, userId),
eq(credentialMember.status, 'active'),
inArray(credentialMember.credentialId, credentialIds)
)
)
.returning({ credentialId: credentialMember.credentialId })
return revokedMemberships.length
}
export interface MembershipValidationResult {
canAdd: boolean
reason?: string
failureCode?: MembershipAdditionFailureCode
existingOrgId?: string
seatValidation?: {
currentSeats: number
@@ -301,6 +494,7 @@ export async function ensureUserInOrganization(
success: false,
alreadyMember: false,
existingOrgId: existingMembership.organizationId,
failureCode: 'already-in-other-organization',
error:
'User is already a member of another organization. Users can only belong to one organization at a time.',
billingActions: {
@@ -330,7 +524,7 @@ export async function validateMembershipAddition(
const [userData] = await db.select({ id: user.id }).from(user).where(eq(user.id, userId)).limit(1)
if (!userData) {
return { canAdd: false, reason: 'User not found' }
return { canAdd: false, reason: 'User not found', failureCode: 'user-not-found' }
}
const [orgData] = await db
@@ -340,7 +534,11 @@ export async function validateMembershipAddition(
.limit(1)
if (!orgData) {
return { canAdd: false, reason: 'Organization not found' }
return {
canAdd: false,
reason: 'Organization not found',
failureCode: 'organization-not-found',
}
}
const existingMemberships = await db
@@ -354,13 +552,18 @@ export async function validateMembershipAddition(
)
if (isAlreadyMemberOfThisOrg) {
return { canAdd: false, reason: 'User is already a member of this organization' }
return {
canAdd: false,
reason: 'User is already a member of this organization',
failureCode: 'already-member',
}
}
return {
canAdd: false,
reason:
'User is already a member of another organization. Users can only belong to one organization at a time.',
failureCode: 'already-in-other-organization',
existingOrgId: existingMemberships[0].organizationId,
}
}
@@ -372,6 +575,7 @@ export async function validateMembershipAddition(
return {
canAdd: false,
reason: seatValidation.reason || 'No seats available',
failureCode: 'no-seats-available',
seatValidation: {
currentSeats: seatValidation.currentSeats,
maxSeats: seatValidation.maxSeats,
@@ -573,7 +777,12 @@ export async function addUserToOrganization(params: AddMemberParams): Promise<Ad
acceptingInvitationId,
})
if (!validation.canAdd) {
return { success: false, error: validation.reason, billingActions }
return {
success: false,
error: validation.reason,
failureCode: validation.failureCode,
billingActions,
}
}
} else {
const existingMemberships = await db
@@ -590,6 +799,7 @@ export async function addUserToOrganization(params: AddMemberParams): Promise<Ad
return {
success: false,
error: 'User is already a member of this organization',
failureCode: 'already-member',
billingActions,
}
}
@@ -598,6 +808,7 @@ export async function addUserToOrganization(params: AddMemberParams): Promise<Ad
success: false,
error:
'User is already a member of another organization. Users can only belong to one organization at a time.',
failureCode: 'already-in-other-organization',
billingActions,
}
}
@@ -676,6 +887,7 @@ export async function removeUserFromOrganization(
proRestored: false,
usageRestored: false,
workspaceAccessRevoked: 0,
pendingInvitationsCancelled: 0,
}
try {
@@ -697,7 +909,12 @@ export async function removeUserFromOrganization(
return { success: false, error: 'Cannot remove organization owner', billingActions }
}
const { workspaceIdsToRevoke, usageCaptured } = await db.transaction(async (tx) => {
const {
workspaceIdsToRevoke,
usageCaptured,
credentialMembershipsRevoked,
pendingInvitationsCancelled,
} = await db.transaction(async (tx) => {
const deletedMember = await tx
.delete(member)
.where(and(eq(member.id, memberId), ne(member.role, 'owner')))
@@ -737,22 +954,49 @@ export async function removeUserFromOrganization(
}
}
const [targetUser] = await tx
.select({ email: user.email })
.from(user)
.where(eq(user.id, userId))
.limit(1)
const cancelledInvitations = targetUser?.email
? await tx
.update(invitation)
.set({ status: 'cancelled', updatedAt: new Date() })
.where(
and(
eq(invitation.organizationId, organizationId),
eq(invitation.status, 'pending'),
sql`lower(${invitation.email}) = lower(${targetUser.email})`
)
)
.returning({ id: invitation.id })
: []
const orgWorkspaces = await tx
.select({ id: workspace.id })
.from(workspace)
.where(
and(
eq(workspace.organizationId, organizationId),
eq(workspace.workspaceMode, 'organization')
)
)
.where(eq(workspace.organizationId, organizationId))
if (orgWorkspaces.length === 0) {
return { workspaceIdsToRevoke: [] as string[], usageCaptured: capturedUsage }
return {
workspaceIdsToRevoke: [] as string[],
usageCaptured: capturedUsage,
credentialMembershipsRevoked: 0,
pendingInvitationsCancelled: cancelledInvitations.length,
}
}
const workspaceIds = orgWorkspaces.map((w) => w.id)
await reassignOwnedOrganizationWorkspacesTx({
tx,
userId,
organizationId,
workspaceIds,
})
const deletedPerms = await tx
.delete(permissions)
.where(
@@ -764,14 +1008,32 @@ export async function removeUserFromOrganization(
)
.returning({ entityId: permissions.entityId })
await tx
.delete(permissionGroupMember)
.where(
and(
eq(permissionGroupMember.userId, userId),
inArray(permissionGroupMember.workspaceId, workspaceIds)
)
)
const credentialMembershipsRevoked = await revokeWorkspaceCredentialMembershipsTx({
tx,
workspaceIds,
userId,
})
return {
workspaceIdsToRevoke: deletedPerms.map((row) => row.entityId),
usageCaptured: capturedUsage,
credentialMembershipsRevoked,
pendingInvitationsCancelled: cancelledInvitations.length,
}
})
billingActions.usageCaptured = usageCaptured
billingActions.workspaceAccessRevoked = workspaceIdsToRevoke.length
billingActions.pendingInvitationsCancelled = pendingInvitationsCancelled
if (usageCaptured > 0) {
logger.info('Captured departed member usage', {
@@ -786,21 +1048,10 @@ export async function removeUserFromOrganization(
userId,
memberId,
workspaceAccessRevoked: workspaceIdsToRevoke.length,
credentialMembershipsRevoked,
pendingInvitationsCancelled,
})
for (const workspaceId of workspaceIdsToRevoke) {
try {
await revokeWorkspaceCredentialMemberships(workspaceId, userId)
} catch (credentialError) {
logger.error('Failed to revoke workspace credential memberships on org leave', {
organizationId,
userId,
workspaceId,
error: credentialError,
})
}
}
if (!skipBillingLogic) {
try {
const remainingPaidTeams = await db
@@ -852,6 +1103,167 @@ export async function removeUserFromOrganization(
}
}
/**
* Removes a non-member's access from every workspace owned by an organization.
* External workspace members have workspace permissions but no organization member row.
*/
export async function removeExternalUserFromOrganizationWorkspaces(params: {
userId: string
organizationId: string
}): Promise<RemoveExternalWorkspaceAccessResult> {
const { userId, organizationId } = params
try {
const [existingMember] = await db
.select({ id: member.id })
.from(member)
.where(and(eq(member.organizationId, organizationId), eq(member.userId, userId)))
.limit(1)
if (existingMember) {
return {
success: false,
error: 'User is an organization member',
workspaceAccessRevoked: 0,
permissionGroupsRevoked: 0,
credentialMembershipsRevoked: 0,
pendingInvitationsCancelled: 0,
}
}
const {
workspaceAccessRevoked,
permissionGroupsRevoked,
credentialMembershipsRevoked,
pendingInvitationsCancelled,
} = await db.transaction(async (tx) => {
const orgWorkspaces = await tx
.select({ id: workspace.id })
.from(workspace)
.where(eq(workspace.organizationId, organizationId))
if (orgWorkspaces.length === 0) {
return {
workspaceAccessRevoked: 0,
permissionGroupsRevoked: 0,
credentialMembershipsRevoked: 0,
pendingInvitationsCancelled: 0,
}
}
const workspaceIds = orgWorkspaces.map((w) => w.id)
const [targetUser] = await tx
.select({ email: user.email })
.from(user)
.where(eq(user.id, userId))
.limit(1)
await reassignOwnedOrganizationWorkspacesTx({
tx,
userId,
organizationId,
workspaceIds,
})
const deletedPermissions = await tx
.delete(permissions)
.where(
and(
eq(permissions.userId, userId),
eq(permissions.entityType, 'workspace'),
inArray(permissions.entityId, workspaceIds)
)
)
.returning({ entityId: permissions.entityId })
const deletedPermissionGroups = await tx
.delete(permissionGroupMember)
.where(
and(
eq(permissionGroupMember.userId, userId),
inArray(permissionGroupMember.workspaceId, workspaceIds)
)
)
.returning({ id: permissionGroupMember.id })
const credentialMembershipsRevoked = await revokeWorkspaceCredentialMembershipsTx({
tx,
workspaceIds,
userId,
})
const cancelledInvitations = targetUser?.email
? await tx
.update(invitation)
.set({ status: 'cancelled', updatedAt: new Date() })
.where(
and(
eq(invitation.organizationId, organizationId),
eq(invitation.status, 'pending'),
eq(invitation.membershipIntent, 'external'),
sql`lower(${invitation.email}) = lower(${targetUser.email})`
)
)
.returning({ id: invitation.id })
: []
return {
workspaceAccessRevoked: deletedPermissions.length,
permissionGroupsRevoked: deletedPermissionGroups.length,
credentialMembershipsRevoked,
pendingInvitationsCancelled: cancelledInvitations.length,
}
})
if (
workspaceAccessRevoked === 0 &&
permissionGroupsRevoked === 0 &&
credentialMembershipsRevoked === 0 &&
pendingInvitationsCancelled === 0
) {
return {
success: false,
error: 'External workspace member not found',
workspaceAccessRevoked,
permissionGroupsRevoked,
credentialMembershipsRevoked,
pendingInvitationsCancelled,
}
}
logger.info('Removed external workspace member from organization workspaces', {
organizationId,
userId,
workspaceAccessRevoked,
permissionGroupsRevoked,
credentialMembershipsRevoked,
pendingInvitationsCancelled,
})
return {
success: true,
workspaceAccessRevoked,
permissionGroupsRevoked,
credentialMembershipsRevoked,
pendingInvitationsCancelled,
}
} catch (error) {
logger.error('Failed to remove external workspace member from organization workspaces', {
organizationId,
userId,
error,
})
return {
success: false,
error: 'Failed to remove external workspace member',
workspaceAccessRevoked: 0,
permissionGroupsRevoked: 0,
credentialMembershipsRevoked: 0,
pendingInvitationsCancelled: 0,
}
}
}
export interface TransferOwnershipParams {
organizationId: string
currentOwnerUserId: string
@@ -1044,6 +1456,7 @@ export async function transferOrganizationOwnership(
const [orgSub] = await tx
.select({
id: subscriptionTable.id,
stripeCustomerId: subscriptionTable.stripeCustomerId,
})
.from(subscriptionTable)
@@ -1056,20 +1469,10 @@ export async function transferOrganizationOwnership(
.limit(1)
if (orgSub?.stripeCustomerId) {
const [newOwnerUser] = await tx
.select({ email: user.email, name: user.name })
.from(user)
.where(eq(user.id, newOwnerUserId))
.limit(1)
if (newOwnerUser?.email) {
await enqueueOutboxEvent(tx, OUTBOX_EVENT_TYPES.STRIPE_SYNC_CUSTOMER_CONTACT, {
stripeCustomerId: orgSub.stripeCustomerId,
email: newOwnerUser.email,
name: newOwnerUser.name ?? undefined,
reason: 'ownership-transfer',
})
}
await enqueueOutboxEvent(tx, OUTBOX_EVENT_TYPES.STRIPE_SYNC_CUSTOMER_CONTACT, {
subscriptionId: orgSub.id,
reason: 'ownership-transfer',
})
}
})

View File

@@ -0,0 +1,130 @@
import { db } from '@sim/db'
import { invitation, member, subscription } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { and, count, eq, gt, inArray, ne } from 'drizzle-orm'
import { isOrganizationBillingBlocked } from '@/lib/billing/core/access'
import { isTeam } from '@/lib/billing/plan-helpers'
import { USABLE_SUBSCRIPTION_STATUSES } from '@/lib/billing/subscriptions/utils'
import { OUTBOX_EVENT_TYPES } from '@/lib/billing/webhooks/outbox-handlers'
import { isBillingEnabled } from '@/lib/core/config/feature-flags'
import { enqueueOutboxEvent } from '@/lib/core/outbox/service'
const logger = createLogger('OrganizationSeats')
export interface ReduceOrganizationSeatsResult {
reduced: boolean
previousSeats?: number
seats?: number
reason?: string
outboxEventId?: string
}
interface ReduceOrganizationSeatsByOneParams {
organizationId: string
actorUserId: string
removedUserId: string
}
export async function reduceOrganizationSeatsByOne({
organizationId,
actorUserId,
removedUserId,
}: ReduceOrganizationSeatsByOneParams): Promise<ReduceOrganizationSeatsResult> {
if (!isBillingEnabled) {
return { reduced: false, reason: 'Billing is not enabled' }
}
return db.transaction(async (tx) => {
const [orgSubscription] = await tx
.select()
.from(subscription)
.where(
and(
eq(subscription.referenceId, organizationId),
inArray(subscription.status, USABLE_SUBSCRIPTION_STATUSES)
)
)
.for('update')
.limit(1)
if (!orgSubscription) {
return { reduced: false, reason: 'No active subscription found' }
}
if (await isOrganizationBillingBlocked(organizationId)) {
return { reduced: false, reason: 'An active subscription is required' }
}
if (!isTeam(orgSubscription.plan)) {
return { reduced: false, reason: 'Seat changes are only available for Team plans' }
}
if (!orgSubscription.stripeSubscriptionId) {
return { reduced: false, reason: 'No Stripe subscription found for this organization' }
}
const currentSeats = orgSubscription.seats || 1
if (currentSeats <= 1) {
return {
reduced: false,
previousSeats: currentSeats,
seats: currentSeats,
reason: 'Minimum 1 seat required',
}
}
const [memberCountRow] = await tx
.select({ count: count() })
.from(member)
.where(eq(member.organizationId, organizationId))
const [pendingCountRow] = await tx
.select({ count: count() })
.from(invitation)
.where(
and(
eq(invitation.organizationId, organizationId),
eq(invitation.status, 'pending'),
ne(invitation.membershipIntent, 'external'),
gt(invitation.expiresAt, new Date())
)
)
const occupiedSeats = (memberCountRow?.count ?? 0) + (pendingCountRow?.count ?? 0)
const nextSeats = currentSeats - 1
if (nextSeats < occupiedSeats) {
return {
reduced: false,
previousSeats: currentSeats,
seats: currentSeats,
reason: `Cannot reduce seats below current occupancy (${occupiedSeats}).`,
}
}
await tx
.update(subscription)
.set({ seats: nextSeats })
.where(eq(subscription.id, orgSubscription.id))
const outboxEventId = await enqueueOutboxEvent(
tx,
OUTBOX_EVENT_TYPES.STRIPE_SYNC_SUBSCRIPTION_SEATS,
{
subscriptionId: orgSubscription.id,
reason: 'member-removed-seat-reduction',
}
)
logger.info('Reduced organization seats after member removal', {
organizationId,
actorUserId,
removedUserId,
previousSeats: currentSeats,
seats: nextSeats,
outboxEventId,
})
return { reduced: true, previousSeats: currentSeats, seats: nextSeats, outboxEventId }
})
}

View File

@@ -35,7 +35,10 @@ vi.mock('@/lib/messaging/email/validation', () => ({
quickValidateEmail: vi.fn((email: string) => ({ isValid: email.includes('@') })),
}))
import { getOrganizationSeatInfo } from '@/lib/billing/validation/seat-management'
import {
getOrganizationSeatInfo,
validateSeatAvailability,
} from '@/lib/billing/validation/seat-management'
/**
* Queues the next N responses for `db.select().from(...).where(...)` calls,
@@ -82,3 +85,30 @@ describe('getOrganizationSeatInfo', () => {
expect(mockGetOrganizationSubscription).not.toHaveBeenCalled()
})
})
describe('validateSeatAvailability', () => {
beforeEach(() => {
vi.clearAllMocks()
resetDbChainMock()
mockFeatureFlags.isBillingEnabled = true
mockGetOrganizationSubscription.mockResolvedValue({
id: 'sub-1',
plan: 'team',
status: 'active',
seats: 10,
})
})
it('uses the internal pending invitation count when checking seats', async () => {
queueSelectResponses([[{ count: 2 }], [{ count: 1 }]])
const result = await validateSeatAvailability('org-1', 1)
expect(result).toMatchObject({
canInvite: true,
currentSeats: 3,
maxSeats: 10,
availableSeats: 7,
})
})
})

View File

@@ -82,6 +82,7 @@ export async function validateSeatAvailability(
const pendingFilters = [
eq(invitation.organizationId, organizationId),
eq(invitation.status, 'pending'),
ne(invitation.membershipIntent, 'external'),
gt(invitation.expiresAt, new Date()),
]
if (options.excludePendingInvitationId) {
@@ -164,6 +165,7 @@ export async function getOrganizationSeatInfo(
and(
eq(invitation.organizationId, organizationId),
eq(invitation.status, 'pending'),
ne(invitation.membershipIntent, 'external'),
gt(invitation.expiresAt, new Date())
)
)
@@ -247,6 +249,7 @@ export async function validateBulkInvitations(
and(
eq(invitation.organizationId, organizationId),
eq(invitation.status, 'pending'),
ne(invitation.membershipIntent, 'external'),
gt(invitation.expiresAt, new Date())
)
)

View File

@@ -1,9 +1,11 @@
import { db } from '@sim/db'
import { subscription as subscriptionTable } from '@sim/db/schema'
import { member, subscription as subscriptionTable, user } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { eq } from 'drizzle-orm'
import { and, eq } from 'drizzle-orm'
import { isTeam } from '@/lib/billing/plan-helpers'
import { requireStripeClient } from '@/lib/billing/stripe-client'
import { resolveDefaultPaymentMethod } from '@/lib/billing/stripe-payment-method'
import { hasUsableSubscriptionStatus } from '@/lib/billing/subscriptions/utils'
import type { OutboxHandler } from '@/lib/core/outbox/service'
const logger = createLogger('BillingOutboxHandlers')
@@ -17,6 +19,7 @@ export const OUTBOX_EVENT_TYPES = {
* enqueue this event after every DB change to `cancelAtPeriodEnd`.
*/
STRIPE_SYNC_CANCEL_AT_PERIOD_END: 'stripe.sync-cancel-at-period-end',
STRIPE_SYNC_SUBSCRIPTION_SEATS: 'stripe.sync-subscription-seats',
STRIPE_THRESHOLD_OVERAGE_INVOICE: 'stripe.threshold-overage-invoice',
STRIPE_SYNC_CUSTOMER_CONTACT: 'stripe.sync-customer-contact',
} as const
@@ -29,10 +32,15 @@ export interface StripeSyncCancelAtPeriodEndPayload {
reason?: string
}
export interface StripeSyncSubscriptionSeatsPayload {
/** The DB subscription row id — the handler reads current seats from this row. */
subscriptionId: string
reason?: string
}
export interface StripeSyncCustomerContactPayload {
stripeCustomerId: string
email: string
name?: string
/** The DB subscription row id — handler resolves current owner/contact at processing time. */
subscriptionId: string
reason?: string
}
@@ -49,6 +57,21 @@ export interface StripeThresholdOverageInvoicePayload {
metadata?: Record<string, string>
}
async function getSubscriptionSeatSyncState(subscriptionId: string) {
const [row] = await db
.select({
plan: subscriptionTable.plan,
seats: subscriptionTable.seats,
status: subscriptionTable.status,
stripeSubscriptionId: subscriptionTable.stripeSubscriptionId,
})
.from(subscriptionTable)
.where(eq(subscriptionTable.id, subscriptionId))
.limit(1)
return row ?? null
}
const stripeSyncCancelAtPeriodEnd: OutboxHandler<StripeSyncCancelAtPeriodEndPayload> = async (
payload,
ctx
@@ -86,6 +109,113 @@ const stripeSyncCancelAtPeriodEnd: OutboxHandler<StripeSyncCancelAtPeriodEndPayl
})
}
const stripeSyncSubscriptionSeats: OutboxHandler<StripeSyncSubscriptionSeatsPayload> = async (
payload,
ctx
) => {
const stripe = requireStripeClient()
const maxSyncAttempts = 2
for (let attempt = 1; attempt <= maxSyncAttempts; attempt++) {
const row = await getSubscriptionSeatSyncState(payload.subscriptionId)
if (!row) {
logger.warn('Subscription not found when syncing seats', {
eventId: ctx.eventId,
subscriptionId: payload.subscriptionId,
})
return
}
if (!isTeam(row.plan)) {
logger.info('Skipping seat sync for non-Team subscription', {
eventId: ctx.eventId,
subscriptionId: payload.subscriptionId,
plan: row.plan,
})
return
}
if (!row.stripeSubscriptionId) {
logger.warn('Subscription has no Stripe id when syncing seats', {
eventId: ctx.eventId,
subscriptionId: payload.subscriptionId,
})
return
}
if (!hasUsableSubscriptionStatus(row.status)) {
logger.warn('Skipping seat sync for unusable DB subscription status', {
eventId: ctx.eventId,
subscriptionId: payload.subscriptionId,
status: row.status,
})
return
}
const desiredSeats = row.seats || 1
const stripeSubscription = await stripe.subscriptions.retrieve(row.stripeSubscriptionId)
if (!hasUsableSubscriptionStatus(stripeSubscription.status)) {
logger.warn('Skipping seat sync for unusable Stripe subscription', {
eventId: ctx.eventId,
subscriptionId: payload.subscriptionId,
stripeSubscriptionId: row.stripeSubscriptionId,
stripeStatus: stripeSubscription.status,
})
return
}
const subscriptionItem = stripeSubscription.items.data[0]
if (!subscriptionItem) {
throw new Error(
`No subscription item found for Stripe subscription ${row.stripeSubscriptionId}`
)
}
if (subscriptionItem.quantity !== desiredSeats) {
await stripe.subscriptions.update(
row.stripeSubscriptionId,
{
items: [
{
id: subscriptionItem.id,
quantity: desiredSeats,
},
],
proration_behavior: 'always_invoice',
},
{ idempotencyKey: `outbox:${ctx.eventId}:seats:${desiredSeats}` }
)
}
const latest = await getSubscriptionSeatSyncState(payload.subscriptionId)
const latestSeats = latest?.seats || 1
if (latestSeats !== desiredSeats) {
logger.info('Subscription seats changed during Stripe sync; retrying latest value', {
eventId: ctx.eventId,
subscriptionId: payload.subscriptionId,
stripeSubscriptionId: row.stripeSubscriptionId,
attemptedSeats: desiredSeats,
latestSeats,
attempt,
})
continue
}
logger.info('Synced subscription seats from DB to Stripe', {
eventId: ctx.eventId,
subscriptionId: payload.subscriptionId,
stripeSubscriptionId: row.stripeSubscriptionId,
seats: desiredSeats,
alreadySynced: subscriptionItem.quantity === desiredSeats,
reason: payload.reason,
})
return
}
throw new Error(`Subscription seats changed while syncing ${payload.subscriptionId}`)
}
const stripeThresholdOverageInvoice: OutboxHandler<StripeThresholdOverageInvoicePayload> = async (
payload,
ctx
@@ -178,18 +308,63 @@ const stripeSyncCustomerContact: OutboxHandler<StripeSyncCustomerContactPayload>
payload,
ctx
) => {
const [subscriptionRow] = await db
.select({
referenceId: subscriptionTable.referenceId,
stripeCustomerId: subscriptionTable.stripeCustomerId,
})
.from(subscriptionTable)
.where(eq(subscriptionTable.id, payload.subscriptionId))
.limit(1)
if (!subscriptionRow) {
logger.warn('Subscription not found when syncing Stripe customer contact', {
eventId: ctx.eventId,
subscriptionId: payload.subscriptionId,
})
return
}
if (!subscriptionRow.stripeCustomerId) {
logger.warn('Subscription has no Stripe customer id when syncing contact', {
eventId: ctx.eventId,
subscriptionId: payload.subscriptionId,
})
return
}
const [owner] = await db
.select({
email: user.email,
name: user.name,
})
.from(member)
.innerJoin(user, eq(member.userId, user.id))
.where(and(eq(member.organizationId, subscriptionRow.referenceId), eq(member.role, 'owner')))
.limit(1)
if (!owner) {
logger.warn('Organization owner not found when syncing Stripe customer contact', {
eventId: ctx.eventId,
subscriptionId: payload.subscriptionId,
organizationId: subscriptionRow.referenceId,
})
return
}
const stripe = requireStripeClient()
await stripe.customers.update(
payload.stripeCustomerId,
subscriptionRow.stripeCustomerId,
{
email: payload.email,
...(payload.name ? { name: payload.name } : {}),
email: owner.email,
...(owner.name ? { name: owner.name } : {}),
},
{ idempotencyKey: `outbox:${ctx.eventId}` }
)
logger.info('Synced Stripe customer contact', {
eventId: ctx.eventId,
stripeCustomerId: payload.stripeCustomerId,
stripeCustomerId: subscriptionRow.stripeCustomerId,
subscriptionId: payload.subscriptionId,
reason: payload.reason,
})
}
@@ -197,6 +372,8 @@ const stripeSyncCustomerContact: OutboxHandler<StripeSyncCustomerContactPayload>
export const billingOutboxHandlers = {
[OUTBOX_EVENT_TYPES.STRIPE_SYNC_CANCEL_AT_PERIOD_END]:
stripeSyncCancelAtPeriodEnd as OutboxHandler<unknown>,
[OUTBOX_EVENT_TYPES.STRIPE_SYNC_SUBSCRIPTION_SEATS]:
stripeSyncSubscriptionSeats as OutboxHandler<unknown>,
[OUTBOX_EVENT_TYPES.STRIPE_THRESHOLD_OVERAGE_INVOICE]:
stripeThresholdOverageInvoice as OutboxHandler<unknown>,
[OUTBOX_EVENT_TYPES.STRIPE_SYNC_CUSTOMER_CONTACT]:

View File

@@ -540,11 +540,13 @@ export const PlatformEvents = {
invitedBy: string
inviteeEmail: string
role: string
membershipIntent?: string
}) => {
trackPlatformEvent('platform.workspace.member_invited', {
'workspace.id': attrs.workspaceId,
'user.id': attrs.invitedBy,
'invitation.role': attrs.role,
...(attrs.membershipIntent ? { 'invitation.membership_intent': attrs.membershipIntent } : {}),
})
},

View File

@@ -3,6 +3,7 @@ import { credential, credentialMember, workspace } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { generateId } from '@sim/utils/id'
import { and, eq, inArray, ne } from 'drizzle-orm'
import type { DbOrTx } from '@/lib/db/types'
import { checkWorkspaceAccess } from '@/lib/workspaces/permissions/utils'
const logger = createLogger('CredentialAccess')
@@ -74,7 +75,15 @@ export async function revokeWorkspaceCredentialMemberships(
workspaceId: string,
userId: string
): Promise<void> {
const workspaceCredentialIds = await db
await revokeWorkspaceCredentialMembershipsTx(db, workspaceId, userId)
}
export async function revokeWorkspaceCredentialMembershipsTx(
tx: DbOrTx,
workspaceId: string,
userId: string
): Promise<void> {
const workspaceCredentialIds = await tx
.select({ id: credential.id })
.from(credential)
.where(eq(credential.workspaceId, workspaceId))
@@ -83,7 +92,7 @@ export async function revokeWorkspaceCredentialMemberships(
const credIds = workspaceCredentialIds.map((c) => c.id)
const [workspaceRow] = await db
const [workspaceRow] = await tx
.select({ ownerId: workspace.ownerId })
.from(workspace)
.where(eq(workspace.id, workspaceId))
@@ -92,7 +101,7 @@ export async function revokeWorkspaceCredentialMemberships(
const ownerId = workspaceRow?.ownerId
if (ownerId && ownerId !== userId) {
const userAdminMemberships = await db
const userAdminMemberships = await tx
.select({ credentialId: credentialMember.credentialId })
.from(credentialMember)
.where(
@@ -105,7 +114,7 @@ export async function revokeWorkspaceCredentialMemberships(
)
for (const { credentialId: credId } of userAdminMemberships) {
const otherAdmins = await db
const otherAdmins = await tx
.select({ id: credentialMember.id })
.from(credentialMember)
.where(
@@ -121,19 +130,19 @@ export async function revokeWorkspaceCredentialMemberships(
if (otherAdmins.length > 0) continue
const now = new Date()
const [existingOwnerMembership] = await db
const [existingOwnerMembership] = await tx
.select({ id: credentialMember.id, status: credentialMember.status })
.from(credentialMember)
.where(and(eq(credentialMember.credentialId, credId), eq(credentialMember.userId, ownerId)))
.limit(1)
if (existingOwnerMembership) {
await db
await tx
.update(credentialMember)
.set({ role: 'admin', status: 'active', updatedAt: now })
.where(eq(credentialMember.id, existingOwnerMembership.id))
} else {
await db.insert(credentialMember).values({
await tx.insert(credentialMember).values({
id: generateId(),
credentialId: credId,
userId: ownerId,
@@ -154,7 +163,7 @@ export async function revokeWorkspaceCredentialMemberships(
}
}
await db
await tx
.update(credentialMember)
.set({ status: 'revoked', updatedAt: new Date() })
.where(

View File

@@ -99,6 +99,15 @@ export interface IsolatedVMError {
line?: number
column?: number
lineContent?: string
/**
* True when the failure is host-infrastructure caused (worker crash, IPC
* failure, pool saturation, task misconfig) rather than anything the user's
* code did. Callers use this to keep genuine server failures as 5xx while
* translating user-caused failures (code errors, timeouts, aborts, per-owner
* rate limits) into 4xx. Defaults to undefined/false — new error sites
* default to user-caused unless explicitly marked.
*/
isSystemError?: boolean
}
const POOL_SIZE = Number.parseInt(env.IVM_POOL_SIZE) || 4
@@ -838,7 +847,11 @@ function cleanupWorker(workerId: number) {
pending.resolve({
result: null,
stdout: '',
error: { message: 'Code execution failed unexpectedly. Please try again.', name: 'Error' },
error: {
message: 'Code execution failed unexpectedly. Please try again.',
name: 'Error',
isSystemError: true,
},
})
workerInfo.pendingExecutions.delete(id)
}
@@ -1125,7 +1138,11 @@ function dispatchToWorker(
resolve({
result: null,
stdout: '',
error: { message: 'Code execution failed to start. Please try again.', name: 'Error' },
error: {
message: 'Code execution failed to start. Please try again.',
name: 'Error',
isSystemError: true,
},
})
if (workerInfo.retiring && workerInfo.activeExecutions === 0) {
cleanupWorker(workerInfo.id)
@@ -1159,6 +1176,7 @@ function enqueueExecution(
error: {
message: 'Code execution is at capacity. Please try again in a moment.',
name: 'Error',
isSystemError: true,
},
})
return
@@ -1198,6 +1216,7 @@ function enqueueExecution(
error: {
message: 'Code execution timed out waiting for an available worker. Please try again.',
name: 'Error',
isSystemError: true,
},
})
}, QUEUE_TIMEOUT_MS)
@@ -1294,6 +1313,7 @@ export async function executeInIsolatedVM(
error: {
message: `Task "${req.task.id}" requires broker "${brokerName}" but none was provided`,
name: 'Error',
isSystemError: true,
},
}
}

View File

@@ -20,6 +20,24 @@ export interface RunSandboxTaskOptions {
signal?: AbortSignal
}
/**
* Thrown when the sandbox failure is attributable to the caller — user code
* errors (SyntaxError, ReferenceError, user-thrown exceptions), timeouts from
* user code, client aborts, or per-owner rate limits. Callers should translate
* this into a 4xx response so genuine 5xx remains a signal of server health.
*
* System-origin failures (worker crash, IPC failure, pool saturation, task
* misconfig) are tagged with `isSystemError` at the isolated-vm layer and
* surface as a plain `Error` → 500.
*/
export class SandboxUserCodeError extends Error {
constructor(message: string, name: string, stack?: string) {
super(message)
this.name = name || 'SandboxUserCodeError'
if (stack) this.stack = stack
}
}
/**
* Executes a sandbox task inside the shared isolated-vm pool and returns the
* binary result buffer. Throws with a human-readable message if the task fails
@@ -70,7 +88,9 @@ export async function runSandboxTask<TInput extends SandboxTaskInput>(
const queueMs = result.timings ? Math.max(0, elapsedMs - result.timings.total) : undefined
if (result.error) {
logger.warn('Sandbox task failed', {
const isSystemError = result.error.isSystemError === true
const logFn = isSystemError ? logger.error.bind(logger) : logger.warn.bind(logger)
logFn('Sandbox task failed', {
taskId,
requestId,
workspaceId: input.workspaceId,
@@ -79,11 +99,19 @@ export async function runSandboxTask<TInput extends SandboxTaskInput>(
timings: result.timings,
error: result.error.message,
errorName: result.error.name,
isSystemError,
})
const err = new Error(result.error.message)
err.name = result.error.name || 'SandboxTaskError'
if (result.error.stack) err.stack = result.error.stack
throw err
if (isSystemError) {
const err = new Error(result.error.message)
err.name = result.error.name || 'SandboxSystemError'
if (result.error.stack) err.stack = result.error.stack
throw err
}
throw new SandboxUserCodeError(
result.error.message,
result.error.name || 'SandboxTaskError',
result.error.stack
)
}
if (typeof result.bytesBase64 !== 'string' || result.bytesBase64.length === 0) {

View File

@@ -0,0 +1,209 @@
/**
* @vitest-environment node
*/
import { dbChainMock, dbChainMockFns, resetDbChainMock } from '@sim/testing'
import { beforeEach, describe, expect, it, vi } from 'vitest'
const {
mockEnsureUserInOrganization,
mockSetActiveOrganizationForCurrentSession,
mockSyncUsageLimitsFromSubscription,
mockSyncWorkspaceEnvCredentials,
mockApplyWorkspaceAutoAddGroup,
} = vi.hoisted(() => ({
mockEnsureUserInOrganization: vi.fn(),
mockSetActiveOrganizationForCurrentSession: vi.fn(),
mockSyncUsageLimitsFromSubscription: vi.fn(),
mockSyncWorkspaceEnvCredentials: vi.fn(),
mockApplyWorkspaceAutoAddGroup: vi.fn(),
}))
vi.mock('@sim/db', () => dbChainMock)
vi.mock('@/lib/billing/organizations/membership', () => ({
ensureUserInOrganization: mockEnsureUserInOrganization,
}))
vi.mock('@/lib/auth/active-organization', () => ({
setActiveOrganizationForCurrentSession: mockSetActiveOrganizationForCurrentSession,
}))
vi.mock('@/lib/billing/core/usage', () => ({
syncUsageLimitsFromSubscription: mockSyncUsageLimitsFromSubscription,
}))
vi.mock('@/lib/credentials/environment', () => ({
syncWorkspaceEnvCredentials: mockSyncWorkspaceEnvCredentials,
}))
vi.mock('@/lib/permission-groups/auto-add', () => ({
applyWorkspaceAutoAddGroup: mockApplyWorkspaceAutoAddGroup,
}))
import { acceptInvitation } from '@/lib/invitations/core'
function queueWhereResponses(responses: unknown[][]) {
const queue = [...responses]
dbChainMockFns.where.mockImplementation(() => {
const result = queue.shift() ?? []
const thenable = Promise.resolve(result) as Promise<unknown[]> & {
limit: ReturnType<typeof vi.fn>
orderBy: ReturnType<typeof vi.fn>
returning: ReturnType<typeof vi.fn>
groupBy: ReturnType<typeof vi.fn>
}
thenable.limit = vi.fn(() => Promise.resolve(result))
thenable.orderBy = vi.fn(() => Promise.resolve(result))
thenable.returning = vi.fn(() => Promise.resolve(result))
thenable.groupBy = vi.fn(() => Promise.resolve(result))
return thenable as ReturnType<typeof dbChainMockFns.where>
})
}
describe('acceptInvitation', () => {
beforeEach(() => {
vi.clearAllMocks()
resetDbChainMock()
})
it('accepts external workspace invitations without joining the organization', async () => {
queueWhereResponses([
[
{
id: 'inv-1',
kind: 'workspace',
email: 'external@example.com',
organizationId: 'org-1',
membershipIntent: 'external',
inviterId: 'inviter-1',
role: 'member',
status: 'pending',
token: 'tok-1',
expiresAt: new Date(Date.now() + 60_000),
createdAt: new Date(),
updatedAt: new Date(),
},
],
[
{
id: 'grant-1',
workspaceId: 'workspace-1',
permission: 'write',
workspaceName: 'Workspace',
},
],
[{ name: 'Acme' }],
[{ name: 'Inviter', email: 'inviter@example.com' }],
[],
[],
[{ variables: {} }],
])
const result = await acceptInvitation({
userId: 'external-user',
userEmail: 'external@example.com',
invitationId: 'inv-1',
token: 'tok-1',
})
expect(result.success).toBe(true)
if (result.success) {
expect(result.acceptedWorkspaceIds).toEqual(['workspace-1'])
expect(result.membershipAlreadyExists).toBe(false)
}
expect(mockEnsureUserInOrganization).not.toHaveBeenCalled()
expect(mockSetActiveOrganizationForCurrentSession).not.toHaveBeenCalled()
expect(mockSyncUsageLimitsFromSubscription).not.toHaveBeenCalled()
expect(mockApplyWorkspaceAutoAddGroup).toHaveBeenCalled()
expect(dbChainMockFns.values).toHaveBeenCalledWith(
expect.objectContaining({
userId: 'external-user',
entityType: 'workspace',
entityId: 'workspace-1',
permissionType: 'write',
})
)
})
it('falls back to external access when an internal workspace invitee joined another organization', async () => {
mockEnsureUserInOrganization.mockResolvedValueOnce({
success: false,
alreadyMember: false,
existingOrgId: 'org-2',
error:
'User is already a member of another organization. Users can only belong to one organization at a time.',
billingActions: {
proUsageSnapshotted: false,
proCancelledAtPeriodEnd: false,
},
})
queueWhereResponses([
[
{
id: 'inv-1',
kind: 'workspace',
email: 'invitee@example.com',
organizationId: 'org-1',
membershipIntent: 'internal',
inviterId: 'inviter-1',
role: 'member',
status: 'pending',
token: 'tok-1',
expiresAt: new Date(Date.now() + 60_000),
createdAt: new Date(),
updatedAt: new Date(),
},
],
[
{
id: 'grant-1',
workspaceId: 'workspace-1',
permission: 'read',
workspaceName: 'Workspace',
},
],
[{ name: 'Acme' }],
[{ name: 'Inviter', email: 'inviter@example.com' }],
[],
[],
[{ variables: {} }],
])
const result = await acceptInvitation({
userId: 'invitee-user',
userEmail: 'invitee@example.com',
invitationId: 'inv-1',
token: 'tok-1',
})
expect(result.success).toBe(true)
if (result.success) {
expect(result.invitation.membershipIntent).toBe('external')
expect(result.acceptedWorkspaceIds).toEqual(['workspace-1'])
expect(result.membershipAlreadyExists).toBe(false)
}
expect(mockEnsureUserInOrganization).toHaveBeenCalledWith(
expect.objectContaining({
userId: 'invitee-user',
organizationId: 'org-1',
acceptingInvitationId: 'inv-1',
})
)
expect(mockSetActiveOrganizationForCurrentSession).not.toHaveBeenCalled()
expect(dbChainMockFns.set).toHaveBeenCalledWith(
expect.objectContaining({
status: 'accepted',
membershipIntent: 'external',
})
)
expect(dbChainMockFns.values).toHaveBeenCalledWith(
expect.objectContaining({
userId: 'invitee-user',
entityType: 'workspace',
entityId: 'workspace-1',
permissionType: 'read',
})
)
})
})

View File

@@ -1,6 +1,7 @@
import { db } from '@sim/db'
import {
type InvitationKind,
type InvitationMembershipIntent,
type InvitationStatus,
invitation,
invitationWorkspaceGrant,
@@ -35,6 +36,7 @@ export interface InvitationWithGrants {
kind: InvitationKind
email: string
organizationId: string | null
membershipIntent: InvitationMembershipIntent
inviterId: string
role: string
status: InvitationStatus
@@ -100,6 +102,7 @@ async function hydrateInvitation(
kind: row.kind,
email: row.email,
organizationId: row.organizationId,
membershipIntent: row.membershipIntent,
inviterId: row.inviterId,
role: row.role,
status: row.status,
@@ -254,8 +257,10 @@ export async function acceptInvitation(
}
let membershipAlreadyExists = false
let acceptedMembershipIntent = inv.membershipIntent
let shouldJoinOrganization = Boolean(inv.organizationId && inv.membershipIntent !== 'external')
if (inv.organizationId) {
if (shouldJoinOrganization && inv.organizationId) {
const membershipResult = await ensureUserInOrganization({
userId: input.userId,
organizationId: inv.organizationId,
@@ -265,16 +270,21 @@ export async function acceptInvitation(
if (!membershipResult.success) {
if (membershipResult.existingOrgId) {
await db
.update(invitation)
.set({ status: 'rejected', updatedAt: new Date() })
.where(eq(invitation.id, inv.id))
return { success: false, kind: 'already-in-organization' }
}
if (membershipResult.error?.toLowerCase().includes('no available seats')) {
if (inv.kind === 'workspace' && inv.grants.length > 0) {
acceptedMembershipIntent = 'external'
shouldJoinOrganization = false
} else {
await db
.update(invitation)
.set({ status: 'rejected', updatedAt: new Date() })
.where(eq(invitation.id, inv.id))
return { success: false, kind: 'already-in-organization' }
}
} else if (membershipResult.failureCode === 'no-seats-available') {
return { success: false, kind: 'no-seats-available' }
} else {
return { success: false, kind: 'server-error', message: membershipResult.error }
}
return { success: false, kind: 'server-error', message: membershipResult.error }
}
membershipAlreadyExists = membershipResult.alreadyMember
@@ -285,7 +295,11 @@ export async function acceptInvitation(
await db.transaction(async (tx) => {
await tx
.update(invitation)
.set({ status: 'accepted', updatedAt: new Date() })
.set({
status: 'accepted',
membershipIntent: acceptedMembershipIntent,
updatedAt: new Date(),
})
.where(eq(invitation.id, inv.id))
for (const grant of inv.grants) {
@@ -331,7 +345,7 @@ export async function acceptInvitation(
}
})
if (inv.organizationId) {
if (shouldJoinOrganization && inv.organizationId) {
try {
await setActiveOrganizationForCurrentSession(inv.organizationId)
} catch (activeOrgError) {
@@ -369,7 +383,7 @@ export async function acceptInvitation(
}
}
if (inv.organizationId && !membershipAlreadyExists) {
if (shouldJoinOrganization && inv.organizationId && !membershipAlreadyExists) {
try {
await syncUsageLimitsFromSubscription(input.userId)
} catch (syncError) {
@@ -389,7 +403,7 @@ export async function acceptInvitation(
return {
success: true,
invitation: { ...inv, status: 'accepted' },
invitation: { ...inv, status: 'accepted', membershipIntent: acceptedMembershipIntent },
acceptedWorkspaceIds,
redirectPath,
membershipAlreadyExists,
@@ -444,6 +458,7 @@ export async function listPendingInvitationsForOrganization(organizationId: stri
kind: invitation.kind,
email: invitation.email,
role: invitation.role,
membershipIntent: invitation.membershipIntent,
status: invitation.status,
expiresAt: invitation.expiresAt,
createdAt: invitation.createdAt,
@@ -468,6 +483,7 @@ export async function listInvitationsForWorkspaces(workspaceIds: string[]) {
createdAt: invitation.createdAt,
updatedAt: invitation.updatedAt,
organizationId: invitation.organizationId,
membershipIntent: invitation.membershipIntent,
inviterId: invitation.inviterId,
workspaceId: invitationWorkspaceGrant.workspaceId,
permission: invitationWorkspaceGrant.permission,

View File

@@ -1,6 +1,7 @@
import { db } from '@sim/db'
import {
type InvitationKind,
type InvitationMembershipIntent,
invitation,
invitationWorkspaceGrant,
organization,
@@ -8,7 +9,7 @@ import {
} from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { generateId } from '@sim/utils/id'
import { and, eq, inArray, sql } from 'drizzle-orm'
import { and, eq, inArray, ne, sql } from 'drizzle-orm'
import {
getEmailSubject,
renderBatchInvitationEmail,
@@ -32,6 +33,7 @@ export interface CreatePendingInvitationInput {
email: string
inviterId: string
organizationId: string | null
membershipIntent?: InvitationMembershipIntent
role: 'admin' | 'member'
grants: WorkspaceGrantInput[]
expiresAt?: Date
@@ -58,6 +60,7 @@ export async function createPendingInvitation(
email: normalizeEmail(input.email),
inviterId: input.inviterId,
organizationId: input.organizationId,
membershipIntent: input.membershipIntent ?? 'internal',
role: input.role,
status: 'pending',
token,
@@ -87,7 +90,13 @@ export async function countPendingInvitationsForOrganization(
const [row] = await db
.select({ count: sql<number>`count(*)::int` })
.from(invitation)
.where(and(eq(invitation.organizationId, organizationId), eq(invitation.status, 'pending')))
.where(
and(
eq(invitation.organizationId, organizationId),
eq(invitation.status, 'pending'),
ne(invitation.membershipIntent, 'external')
)
)
return row?.count ?? 0
}

View File

@@ -0,0 +1,310 @@
import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit'
import { db } from '@sim/db'
import { type InvitationMembershipIntent, permissions, user } from '@sim/db/schema'
import { and, eq, sql } from 'drizzle-orm'
import type { NextRequest } from 'next/server'
import { getUserOrganization } from '@/lib/billing/organizations/membership'
import { validateSeatAvailability } from '@/lib/billing/validation/seat-management'
import { PlatformEvents } from '@/lib/core/telemetry'
import { normalizeEmail } from '@/lib/invitations/core'
import {
cancelPendingInvitation,
createPendingInvitation,
findPendingGrantForWorkspaceEmail,
sendInvitationEmail,
} from '@/lib/invitations/send'
import { captureServerEvent } from '@/lib/posthog/server'
import {
getWorkspaceWithOwner,
type PermissionType,
type WorkspaceWithOwner,
} from '@/lib/workspaces/permissions/utils'
import { getWorkspaceInvitePolicy, type WorkspaceInvitePolicy } from '@/lib/workspaces/policy'
import { validateInvitationsAllowed } from '@/ee/access-control/utils/permission-check'
export interface WorkspaceInvitationContext {
workspaceId: string
inviterId: string
inviterName: string
inviterEmail?: string | null
workspaceDetails: WorkspaceWithOwner
invitePolicy: WorkspaceInvitePolicy
}
export interface WorkspaceInvitationResult {
id: string
workspaceId: string
email: string
permission: PermissionType
membershipIntent: InvitationMembershipIntent
expiresAt: Date | undefined
}
export class WorkspaceInvitationError extends Error {
status: number
email?: string
upgradeRequired?: boolean
constructor({
message,
status,
email,
upgradeRequired,
}: {
message: string
status: number
email?: string
upgradeRequired?: boolean
}) {
super(message)
this.name = 'WorkspaceInvitationError'
this.status = status
this.email = email
this.upgradeRequired = upgradeRequired
}
}
export async function prepareWorkspaceInvitationContext({
workspaceId,
inviterId,
inviterName,
inviterEmail,
}: {
workspaceId: string
inviterId: string
inviterName: string
inviterEmail?: string | null
}): Promise<WorkspaceInvitationContext> {
await validateInvitationsAllowed(inviterId, workspaceId)
const userPermission = await db
.select()
.from(permissions)
.where(
and(
eq(permissions.entityId, workspaceId),
eq(permissions.entityType, 'workspace'),
eq(permissions.userId, inviterId),
eq(permissions.permissionType, 'admin')
)
)
.then((rows) => rows[0])
if (!userPermission) {
throw new WorkspaceInvitationError({
message: 'You need admin permissions to invite users',
status: 403,
})
}
const workspaceDetails = await getWorkspaceWithOwner(workspaceId)
if (!workspaceDetails) {
throw new WorkspaceInvitationError({ message: 'Workspace not found', status: 404 })
}
const invitePolicy = await getWorkspaceInvitePolicy(workspaceDetails)
if (!invitePolicy.allowed) {
throw new WorkspaceInvitationError({
message: invitePolicy.reason ?? 'Invites are disabled for this workspace.',
status: 403,
upgradeRequired: invitePolicy.upgradeRequired,
})
}
return {
workspaceId,
inviterId,
inviterName,
inviterEmail,
workspaceDetails,
invitePolicy,
}
}
export async function createWorkspaceInvitation({
context,
email,
permission = 'read',
request,
}: {
context: WorkspaceInvitationContext
email: string
permission?: string
request: NextRequest
}): Promise<WorkspaceInvitationResult> {
const validPermissions: PermissionType[] = ['admin', 'write', 'read']
if (!validPermissions.includes(permission as PermissionType)) {
throw new WorkspaceInvitationError({
message: `Invalid permission: must be one of ${validPermissions.join(', ')}`,
status: 400,
email,
})
}
const invitationPermission = permission as PermissionType
const normalizedEmail = normalizeEmail(email)
let membershipIntent: InvitationMembershipIntent = 'internal'
const existingUser = await db
.select()
.from(user)
.where(sql`lower(${user.email}) = ${normalizedEmail}`)
.then((rows) => rows[0])
if (existingUser) {
const existingPermission = await db
.select()
.from(permissions)
.where(
and(
eq(permissions.entityId, context.workspaceId),
eq(permissions.entityType, 'workspace'),
eq(permissions.userId, existingUser.id)
)
)
.then((rows) => rows[0])
if (existingPermission) {
throw new WorkspaceInvitationError({
message: `${normalizedEmail} already has access to this workspace`,
status: 400,
email: normalizedEmail,
})
}
if (context.invitePolicy.organizationId) {
const existingMembership = await getUserOrganization(existingUser.id)
if (
existingMembership &&
existingMembership.organizationId !== context.invitePolicy.organizationId
) {
membershipIntent = 'external'
} else if (context.invitePolicy.requiresSeat && !existingMembership) {
const seatValidation = await validateSeatAvailability(
context.invitePolicy.organizationId,
1
)
if (!seatValidation.canInvite) {
throw new WorkspaceInvitationError({
message: seatValidation.reason || 'No available seats for this organization.',
status: 400,
email: normalizedEmail,
})
}
}
}
} else if (context.invitePolicy.requiresSeat && context.invitePolicy.organizationId) {
const seatValidation = await validateSeatAvailability(context.invitePolicy.organizationId, 1)
if (!seatValidation.canInvite) {
throw new WorkspaceInvitationError({
message: seatValidation.reason || 'No available seats for this organization.',
status: 400,
email: normalizedEmail,
})
}
}
const existingInvitation = await findPendingGrantForWorkspaceEmail({
workspaceId: context.workspaceId,
email: normalizedEmail,
})
if (existingInvitation) {
throw new WorkspaceInvitationError({
message: `${normalizedEmail} has already been invited to this workspace`,
status: 400,
email: normalizedEmail,
})
}
const { invitationId, token } = await createPendingInvitation({
kind: 'workspace',
email: normalizedEmail,
inviterId: context.inviterId,
organizationId: context.workspaceDetails.organizationId,
membershipIntent,
role: 'member',
grants: [
{
workspaceId: context.workspaceId,
permission: invitationPermission,
},
],
})
try {
PlatformEvents.workspaceMemberInvited({
workspaceId: context.workspaceId,
invitedBy: context.inviterId,
inviteeEmail: normalizedEmail,
role: invitationPermission,
membershipIntent,
})
} catch {
/**
* Telemetry must not fail invitation creation.
*/
}
captureServerEvent(
context.inviterId,
'workspace_member_invited',
{
workspace_id: context.workspaceId,
invitee_role: invitationPermission,
membership_intent: membershipIntent,
},
{
groups: { workspace: context.workspaceId },
setOnce: { first_invitation_sent_at: new Date().toISOString() },
}
)
const emailResult = await sendInvitationEmail({
invitationId,
token,
kind: 'workspace',
email: normalizedEmail,
inviterName: context.inviterName,
organizationId: context.workspaceDetails.organizationId,
organizationRole: 'member',
grants: [{ workspaceId: context.workspaceId, permission: invitationPermission }],
})
if (!emailResult.success) {
await cancelPendingInvitation(invitationId)
throw new WorkspaceInvitationError({
message: emailResult.error || 'Failed to send invitation email',
status: 502,
email: normalizedEmail,
})
}
recordAudit({
workspaceId: context.workspaceId,
actorId: context.inviterId,
actorName: context.inviterName,
actorEmail: context.inviterEmail,
action: AuditAction.MEMBER_INVITED,
resourceType: AuditResourceType.WORKSPACE,
resourceId: context.workspaceId,
resourceName: normalizedEmail,
description: `Invited ${normalizedEmail} as ${invitationPermission}`,
metadata: {
targetEmail: normalizedEmail,
targetRole: invitationPermission,
membershipIntent,
workspaceName: context.workspaceDetails.name,
invitationId,
},
request,
})
return {
id: invitationId,
workspaceId: context.workspaceId,
email: normalizedEmail,
permission: invitationPermission,
membershipIntent,
expiresAt: undefined,
}
}

View File

@@ -88,6 +88,7 @@ export interface PostHogEventMap {
workspace_member_invited: {
workspace_id: string
invitee_role: string
membership_intent?: string
}
workspace_member_removed: {

View File

@@ -15,6 +15,7 @@ export interface Invitation {
id: string
email: string
status: string
membershipIntent?: 'internal' | 'external'
}
export interface Organization {

View File

@@ -0,0 +1,33 @@
import { describe, expect, it } from 'vitest'
import { calculateSeatUsage } from '@/lib/workspaces/organization/utils'
describe('calculateSeatUsage', () => {
it('does not count external pending workspace invitations as occupied seats', () => {
const seats = calculateSeatUsage({
id: 'org-1',
name: 'Acme',
slug: 'acme',
createdAt: new Date(),
members: [
{ id: 'member-1', role: 'owner' },
{ id: 'member-2', role: 'member' },
],
invitations: [
{
id: 'inv-1',
email: 'internal@example.com',
status: 'pending',
membershipIntent: 'internal',
},
{
id: 'inv-2',
email: 'external@example.com',
status: 'pending',
membershipIntent: 'external',
},
],
})
expect(seats).toEqual({ used: 3, members: 2, pending: 1 })
})
})

View File

@@ -45,7 +45,9 @@ export function calculateSeatUsage(organization: Organization | null | undefined
const membersCount = organization.members?.length || 0
const pendingInvitationsCount =
organization.invitations?.filter((inv) => inv.status === 'pending').length || 0
organization.invitations?.filter(
(inv) => inv.status === 'pending' && inv.membershipIntent !== 'external'
).length || 0
return {
used: membersCount + pendingInvitationsCount,

View File

@@ -24,6 +24,7 @@ function createMockChain(finalResult: any) {
chain.where = vi.fn().mockReturnValue(chain)
chain.limit = vi.fn().mockReturnValue(chain)
chain.innerJoin = vi.fn().mockReturnValue(chain)
chain.leftJoin = vi.fn().mockReturnValue(chain)
chain.orderBy = vi.fn().mockReturnValue(chain)
return chain
@@ -225,10 +226,44 @@ describe('Permission Utils', () => {
name: 'Alice Smith',
image: 'https://example.com/alice.png',
permissionType: 'admin',
isExternal: false,
},
])
})
it('marks users as external when they are not members of the workspace organization', async () => {
const mockUsersResults = [
{
userId: 'internal-user',
email: 'internal@example.com',
name: 'Internal User',
image: null,
permissionType: 'admin' as PermissionType,
workspaceOrganizationId: 'org-1',
organizationMemberId: 'member-1',
},
{
userId: 'external-user',
email: 'external@example.com',
name: 'External User',
image: null,
permissionType: 'write' as PermissionType,
workspaceOrganizationId: 'org-1',
organizationMemberId: null,
},
]
const usersChain = createMockChain(mockUsersResults)
mockDb.select.mockReturnValue(usersChain)
const result = await getUsersWithPermissions('workspace456')
expect(result.map((u) => ({ email: u.email, isExternal: u.isExternal }))).toEqual([
{ email: 'internal@example.com', isExternal: false },
{ email: 'external@example.com', isExternal: true },
])
})
it('should return multiple users with different permission levels', async () => {
const mockUsersResults = [
{

View File

@@ -240,6 +240,7 @@ export async function getUsersWithPermissions(workspaceId: string): Promise<
name: string
image: string | null
permissionType: PermissionType
isExternal: boolean
}>
> {
const usersWithPermissions = await db
@@ -249,10 +250,16 @@ export async function getUsersWithPermissions(workspaceId: string): Promise<
name: user.name,
image: user.image,
permissionType: permissions.permissionType,
workspaceOrganizationId: workspace.organizationId,
organizationMemberId: member.id,
})
.from(permissions)
.innerJoin(user, eq(permissions.userId, user.id))
.innerJoin(workspace, eq(permissions.entityId, workspace.id))
.leftJoin(
member,
and(eq(member.userId, user.id), eq(member.organizationId, workspace.organizationId))
)
.where(
and(
eq(permissions.entityType, 'workspace'),
@@ -268,6 +275,7 @@ export async function getUsersWithPermissions(workspaceId: string): Promise<
name: row.name,
image: row.image ?? null,
permissionType: row.permissionType,
isExternal: Boolean(row.workspaceOrganizationId && !row.organizationMemberId),
}))
}

View File

@@ -219,6 +219,23 @@ describe('getWorkspaceCreationPolicy', () => {
expect(result.workspaceMode).toBe(WORKSPACE_MODE.ORGANIZATION)
expect(result.reason).toContain('owners and admins')
})
it('blocks users without org membership from creating workspaces in the active org context', async () => {
mockDbResults.value = [[], [{ userId: 'owner-1' }]]
const result = await getWorkspaceCreationPolicy({
userId: 'external-user-1',
activeOrganizationId: 'org-1',
})
expect(result.canCreate).toBe(false)
expect(result.workspaceMode).toBe(WORKSPACE_MODE.ORGANIZATION)
expect(result.organizationId).toBe('org-1')
expect(result.billedAccountUserId).toBe('owner-1')
expect(result.reason).toContain('owners and admins')
expect(mockGetOrganizationSubscription).not.toHaveBeenCalled()
expect(mockGetHighestPrioritySubscription).not.toHaveBeenCalled()
})
})
describe('getWorkspaceInvitePolicy', () => {

View File

@@ -182,6 +182,21 @@ export async function getWorkspaceCreationPolicy({
.limit(1)
)[0]?.role
if (activeOrganizationId && !orgRole) {
const billedAccountUserId = await requireOrganizationOwnerId(activeOrganizationId)
return {
canCreate: false,
workspaceMode: WORKSPACE_MODE.ORGANIZATION,
organizationId: activeOrganizationId,
billedAccountUserId,
maxWorkspaces: null,
currentWorkspaceCount: 0,
reason: 'Only organization owners and admins can create organization workspaces.',
status: 403,
}
}
if (!isBillingEnabled) {
if (organizationId && orgRole) {
const billedAccountUserId = await requireOrganizationOwnerId(organizationId)

View File

@@ -55,7 +55,7 @@
"@azure/storage-blob": "12.27.0",
"@better-auth/sso": "1.3.12",
"@better-auth/stripe": "1.3.12",
"@browserbasehq/stagehand": "^3.0.5",
"@browserbasehq/stagehand": "^3.2.1",
"@cerebras/cerebras_cloud_sdk": "^1.23.0",
"@e2b/code-interpreter": "^2.0.0",
"@google/genai": "1.34.0",

View File

@@ -9,13 +9,14 @@ const logger = createLogger('BrowserUseTool')
const POLL_INTERVAL_MS = 5000
const MAX_POLL_TIME_MS = getMaxExecutionTimeout()
const MAX_CONSECUTIVE_ERRORS = 3
const API_BASE = 'https://api.browser-use.com/api/v2'
async function createSessionWithProfile(
profileId: string,
apiKey: string
): Promise<{ sessionId: string } | { error: string }> {
try {
const response = await fetch('https://api.browser-use.com/api/v2/sessions', {
const response = await fetch(`${API_BASE}/sessions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@@ -43,7 +44,7 @@ async function createSessionWithProfile(
async function stopSession(sessionId: string, apiKey: string): Promise<void> {
try {
const response = await fetch(`https://api.browser-use.com/api/v2/sessions/${sessionId}`, {
const response = await fetch(`${API_BASE}/sessions/${sessionId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
@@ -62,58 +63,92 @@ async function stopSession(sessionId: string, apiKey: string): Promise<void> {
}
}
async function fetchSessionLiveUrl(
sessionId: string,
apiKey: string
): Promise<{ liveUrl: string | null; publicShareUrl: string | null }> {
try {
const response = await fetch(`${API_BASE}/sessions/${sessionId}`, {
method: 'GET',
headers: { 'X-Browser-Use-API-Key': apiKey },
})
if (!response.ok) {
return { liveUrl: null, publicShareUrl: null }
}
const data = (await response.json()) as { liveUrl?: string; publicShareUrl?: string }
return {
liveUrl: data.liveUrl ?? null,
publicShareUrl: data.publicShareUrl ?? null,
}
} catch (error: any) {
logger.warn(`Error fetching session ${sessionId}:`, error)
return { liveUrl: null, publicShareUrl: null }
}
}
function normalizeSecrets(variables: BrowserUseRunTaskParams['variables']): Record<string, string> {
const secrets: Record<string, string> = {}
if (!variables) return secrets
if (Array.isArray(variables)) {
for (const row of variables as Array<Record<string, any>>) {
if (row?.cells?.Key && row.cells.Value !== undefined) {
secrets[row.cells.Key] = row.cells.Value
} else if (row?.Key && row.Value !== undefined) {
secrets[row.Key] = row.Value
}
}
} else if (typeof variables === 'object') {
for (const [k, v] of Object.entries(variables)) {
if (typeof v === 'string') secrets[k] = v
}
}
return secrets
}
function parseAllowedDomains(input?: string | string[]): string[] | undefined {
if (!input) return undefined
const arr = Array.isArray(input)
? input
: input
.split(',')
.map((s) => s.trim())
.filter(Boolean)
return arr.length > 0 ? arr : undefined
}
function buildRequestBody(
params: BrowserUseRunTaskParams,
sessionId?: string
): Record<string, any> {
const requestBody: Record<string, any> = {
task: params.task,
}
const body: Record<string, any> = { task: params.task }
if (sessionId) {
requestBody.sessionId = sessionId
logger.info(`Using session ${sessionId} for task`)
}
if (sessionId) body.sessionId = sessionId
if (params.model) body.llm = params.model
if (params.startUrl?.trim()) body.startUrl = params.startUrl.trim()
if (typeof params.maxSteps === 'number' && params.maxSteps > 0) body.maxSteps = params.maxSteps
if (params.structuredOutput) body.structuredOutput = params.structuredOutput
if (typeof params.flashMode === 'boolean') body.flashMode = params.flashMode
if (typeof params.thinking === 'boolean') body.thinking = params.thinking
if (typeof params.vision === 'boolean' || params.vision === 'auto') body.vision = params.vision
if (params.systemPromptExtension) body.systemPromptExtension = params.systemPromptExtension
if (typeof params.highlightElements === 'boolean')
body.highlightElements = params.highlightElements
if (params.variables) {
let secrets: Record<string, string> = {}
const allowedDomains = parseAllowedDomains(params.allowedDomains)
if (allowedDomains) body.allowedDomains = allowedDomains
if (Array.isArray(params.variables)) {
logger.info('Converting variables array to dictionary format')
params.variables.forEach((row: any) => {
if (row.cells?.Key && row.cells.Value !== undefined) {
secrets[row.cells.Key] = row.cells.Value
logger.info(`Added secret for key: ${row.cells.Key}`)
} else if (row.Key && row.Value !== undefined) {
secrets[row.Key] = row.Value
logger.info(`Added secret for key: ${row.Key}`)
}
})
} else if (typeof params.variables === 'object' && params.variables !== null) {
logger.info('Using variables object directly')
secrets = params.variables
}
const secrets = normalizeSecrets(params.variables)
if (Object.keys(secrets).length > 0) body.secrets = secrets
if (Object.keys(secrets).length > 0) {
logger.info(`Found ${Object.keys(secrets).length} secrets to include`)
requestBody.secrets = secrets
} else {
logger.warn('No usable secrets found in variables')
}
}
if (
params.metadata &&
typeof params.metadata === 'object' &&
Object.keys(params.metadata).length > 0
)
body.metadata = params.metadata
if (params.model) {
requestBody.llm_model = params.model
}
if (params.save_browser_data) {
requestBody.save_browser_data = params.save_browser_data
}
requestBody.use_adblock = true
requestBody.highlight_elements = true
return requestBody
return body
}
async function fetchTaskStatus(
@@ -121,30 +156,36 @@ async function fetchTaskStatus(
apiKey: string
): Promise<{ ok: true; data: any } | { ok: false; error: string }> {
try {
const response = await fetch(`https://api.browser-use.com/api/v2/tasks/${taskId}`, {
const response = await fetch(`${API_BASE}/tasks/${taskId}`, {
method: 'GET',
headers: {
'X-Browser-Use-API-Key': apiKey,
},
headers: { 'X-Browser-Use-API-Key': apiKey },
})
if (!response.ok) {
return { ok: false, error: `HTTP ${response.status}: ${response.statusText}` }
}
const data = await response.json()
return { ok: true, data }
return { ok: true, data: await response.json() }
} catch (error: any) {
return { ok: false, error: error.message || 'Network error' }
}
}
async function pollForCompletion(
taskId: string,
apiKey: string
): Promise<{ success: boolean; output: any; steps: any[]; error?: string }> {
let liveUrlLogged = false
interface PollResult {
success: boolean
output: any
steps: any[]
sessionId: string | null
liveUrl: string | null
publicShareUrl: string | null
error?: string
}
async function pollForCompletion(taskId: string, apiKey: string): Promise<PollResult> {
let consecutiveErrors = 0
let sessionId: string | null = null
let liveUrl: string | null = null
let publicShareUrl: string | null = null
const startTime = Date.now()
while (Date.now() - startTime < MAX_POLL_TIME_MS) {
@@ -157,11 +198,13 @@ async function pollForCompletion(
)
if (consecutiveErrors >= MAX_CONSECUTIVE_ERRORS) {
logger.error(`Max consecutive errors reached for task ${taskId}`)
return {
success: false,
output: null,
steps: [],
sessionId,
liveUrl,
publicShareUrl,
error: `Failed to poll task status after ${MAX_CONSECUTIVE_ERRORS} attempts: ${result.error}`,
}
}
@@ -172,23 +215,31 @@ async function pollForCompletion(
consecutiveErrors = 0
const taskData = result.data
if (taskData.sessionId) sessionId = taskData.sessionId
const status = taskData.status
logger.info(`BrowserUse task ${taskId} status: ${status}`)
if (sessionId && !liveUrl) {
const session = await fetchSessionLiveUrl(sessionId, apiKey)
if (session.liveUrl) {
liveUrl = session.liveUrl
logger.info(`BrowserUse live URL: ${liveUrl}`)
}
if (session.publicShareUrl) publicShareUrl = session.publicShareUrl
}
if (['finished', 'failed', 'stopped'].includes(status)) {
return {
success: status === 'finished',
output: taskData.output ?? null,
steps: taskData.steps || [],
sessionId,
liveUrl,
publicShareUrl,
}
}
if (!liveUrlLogged && taskData.live_url) {
logger.info(`BrowserUse task ${taskId} live URL: ${taskData.live_url}`)
liveUrlLogged = true
}
await sleep(POLL_INTERVAL_MS)
}
@@ -198,20 +249,58 @@ async function pollForCompletion(
success: finalResult.data.status === 'finished',
output: finalResult.data.output ?? null,
steps: finalResult.data.steps || [],
sessionId: finalResult.data.sessionId ?? sessionId,
liveUrl,
publicShareUrl,
}
}
logger.warn(
`Task ${taskId} did not complete within the maximum polling time (${MAX_POLL_TIME_MS / 1000}s)`
)
return {
success: false,
output: null,
steps: [],
sessionId,
liveUrl,
publicShareUrl,
error: `Task did not complete within the maximum polling time (${MAX_POLL_TIME_MS / 1000}s)`,
}
}
async function createShareUrl(sessionId: string, apiKey: string): Promise<string | null> {
try {
const response = await fetch(`${API_BASE}/sessions/${sessionId}/public-share`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Browser-Use-API-Key': apiKey,
},
})
if (!response.ok) {
logger.warn(`Failed to create share URL for session ${sessionId}: ${response.statusText}`)
return null
}
const data = (await response.json()) as { shareUrl?: string; shareToken?: string }
return data.shareUrl ?? null
} catch (error: any) {
logger.warn(`Error creating share URL for session ${sessionId}:`, error)
return null
}
}
function emptyOutput(): BrowserUseRunTaskResponse['output'] {
return {
id: '',
success: false,
output: null,
steps: [],
liveUrl: null,
shareUrl: null,
sessionId: null,
}
}
export const runTaskTool: ToolConfig<BrowserUseRunTaskParams, BrowserUseRunTaskResponse> = {
id: 'browser_use_run_task',
name: 'Browser Use',
@@ -225,23 +314,77 @@ export const runTaskTool: ToolConfig<BrowserUseRunTaskParams, BrowserUseRunTaskR
visibility: 'user-or-llm',
description: 'What should the browser agent do',
},
startUrl: {
type: 'string',
required: false,
visibility: 'user-or-llm',
description: 'Initial page URL to start the agent on (reduces navigation steps)',
},
variables: {
type: 'json',
required: false,
visibility: 'user-only',
description: 'Optional variables to use as secrets (format: {key: value})',
description: 'Optional secrets injected into the task (format: {key: value})',
},
save_browser_data: {
allowedDomains: {
type: 'string',
required: false,
visibility: 'user-only',
description: 'Comma-separated list of domains the agent is allowed to visit',
},
maxSteps: {
type: 'number',
required: false,
visibility: 'user-only',
description: 'Maximum number of steps the agent may take (default 100, max 10000)',
},
flashMode: {
type: 'boolean',
required: false,
visibility: 'user-only',
description: 'Whether to save browser data',
description: 'Enable flash mode (faster, less careful navigation)',
},
thinking: {
type: 'boolean',
required: false,
visibility: 'user-only',
description: 'Enable extended reasoning mode',
},
vision: {
type: 'string',
required: false,
visibility: 'user-only',
description: 'Vision capability: "true", "false", or "auto"',
},
systemPromptExtension: {
type: 'string',
required: false,
visibility: 'user-only',
description: 'Optional text appended to the agent system prompt (max 2000 chars)',
},
structuredOutput: {
type: 'string',
required: false,
visibility: 'user-only',
description: 'Stringified JSON schema for the structured output',
},
highlightElements: {
type: 'boolean',
required: false,
visibility: 'user-only',
description: 'Highlight interactive elements on the page (default true)',
},
metadata: {
type: 'json',
required: false,
visibility: 'user-only',
description: 'Custom key-value metadata (up to 10 pairs) for tracking',
},
model: {
type: 'string',
required: false,
visibility: 'user-only',
description: 'LLM model to use (default: gpt-4o)',
description: 'LLM model identifier (e.g. browser-use-2.0)',
},
apiKey: {
type: 'string',
@@ -258,7 +401,7 @@ export const runTaskTool: ToolConfig<BrowserUseRunTaskParams, BrowserUseRunTaskR
},
request: {
url: 'https://api.browser-use.com/api/v2/tasks',
url: `${API_BASE}/tasks`,
method: 'POST',
headers: (params) => ({
'Content-Type': 'application/json',
@@ -273,16 +416,7 @@ export const runTaskTool: ToolConfig<BrowserUseRunTaskParams, BrowserUseRunTaskR
logger.info(`Creating session with profile ID: ${params.profile_id}`)
const sessionResult = await createSessionWithProfile(params.profile_id, params.apiKey)
if ('error' in sessionResult) {
return {
success: false,
output: {
id: null,
success: false,
output: null,
steps: [],
},
error: sessionResult.error,
}
return { success: false, output: emptyOutput(), error: sessionResult.error }
}
sessionId = sessionResult.sessionId
}
@@ -291,7 +425,7 @@ export const runTaskTool: ToolConfig<BrowserUseRunTaskParams, BrowserUseRunTaskR
logger.info('Creating BrowserUse task', { hasSession: !!sessionId })
try {
const response = await fetch('https://api.browser-use.com/api/v2/tasks', {
const response = await fetch(`${API_BASE}/tasks`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@@ -305,22 +439,23 @@ export const runTaskTool: ToolConfig<BrowserUseRunTaskParams, BrowserUseRunTaskR
logger.error(`Failed to create task: ${errorText}`)
return {
success: false,
output: {
id: null,
success: false,
output: null,
steps: [],
},
output: emptyOutput(),
error: `Failed to create task: ${response.statusText}`,
}
}
const data = (await response.json()) as { id: string }
const data = (await response.json()) as { id: string; sessionId?: string }
const taskId = data.id
logger.info(`Created BrowserUse task: ${taskId}`)
const initialSessionId = sessionId ?? data.sessionId ?? null
logger.info(`Created BrowserUse task ${taskId}`, { sessionId: initialSessionId })
const result = await pollForCompletion(taskId, params.apiKey)
const finalSessionId = result.sessionId ?? initialSessionId
const shareUrl =
result.publicShareUrl ??
(finalSessionId ? await createShareUrl(finalSessionId, params.apiKey) : null)
if (sessionId) {
await stopSession(sessionId, params.apiKey)
}
@@ -332,24 +467,20 @@ export const runTaskTool: ToolConfig<BrowserUseRunTaskParams, BrowserUseRunTaskR
success: result.success,
output: result.output,
steps: result.steps,
liveUrl: result.liveUrl,
shareUrl,
sessionId: finalSessionId,
},
error: result.error,
}
} catch (error: any) {
logger.error('Error creating BrowserUse task:', error)
if (sessionId) {
await stopSession(sessionId, params.apiKey)
}
return {
success: false,
output: {
id: null,
success: false,
output: null,
steps: [],
},
output: emptyOutput(),
error: `Error creating task: ${error.message}`,
}
}
@@ -358,7 +489,43 @@ export const runTaskTool: ToolConfig<BrowserUseRunTaskParams, BrowserUseRunTaskR
outputs: {
id: { type: 'string', description: 'Task execution identifier' },
success: { type: 'boolean', description: 'Task completion status' },
output: { type: 'json', description: 'Task output data' },
steps: { type: 'json', description: 'Execution steps taken' },
output: { type: 'json', description: 'Final task output (string or structured)' },
steps: {
type: 'array',
description: 'Steps the agent executed (number, memory, nextGoal, url, actions, duration)',
items: {
type: 'object',
properties: {
number: { type: 'number', description: 'Sequential step number' },
memory: { type: 'string', description: 'Agent memory at this step' },
evaluationPreviousGoal: {
type: 'string',
description: 'Evaluation of previous goal completion',
},
nextGoal: { type: 'string', description: 'Goal for the next step' },
url: { type: 'string', description: 'Current URL of the browser' },
screenshotUrl: { type: 'string', description: 'Optional screenshot URL', optional: true },
actions: {
type: 'array',
description: 'Stringified JSON actions performed',
items: { type: 'string', description: 'Action JSON' },
},
duration: {
type: 'number',
description: 'Step duration in seconds',
optional: true,
},
},
},
},
liveUrl: {
type: 'string',
description: 'Embeddable live browser session URL (active during execution)',
},
shareUrl: {
type: 'string',
description: 'Public shareable URL for the recorded session (post-run)',
},
sessionId: { type: 'string', description: 'Browser Use session identifier' },
},
}

View File

@@ -3,26 +3,40 @@ import type { ToolResponse } from '@/tools/types'
export interface BrowserUseRunTaskParams {
task: string
apiKey: string
variables?: Record<string, string>
variables?: Record<string, string> | Array<Record<string, any>>
model?: string
save_browser_data?: boolean
startUrl?: string
allowedDomains?: string | string[]
maxSteps?: number
flashMode?: boolean
thinking?: boolean
vision?: boolean | 'auto'
systemPromptExtension?: string
structuredOutput?: string
highlightElements?: boolean
metadata?: Record<string, string>
profile_id?: string
}
export interface BrowserUseTaskStep {
id: string
step: number
evaluation_previous_goal: string
next_goal: string
url?: string
extracted_data?: Record<string, any>
number: number
memory: string
evaluationPreviousGoal: string
nextGoal: string
url: string
screenshotUrl?: string | null
actions: string[]
duration?: number | null
}
export interface BrowserUseTaskOutput {
id: string
success: boolean
output: any
output: string | null
steps: BrowserUseTaskStep[]
liveUrl: string | null
shareUrl: string | null
sessionId: string | null
}
export interface BrowserUseRunTaskResponse extends ToolResponse {
@@ -30,10 +44,5 @@ export interface BrowserUseRunTaskResponse extends ToolResponse {
}
export interface BrowserUseResponse extends ToolResponse {
output: {
id: string
success: boolean
output: any
steps: BrowserUseTaskStep[]
}
output: BrowserUseTaskOutput
}

View File

@@ -2248,6 +2248,46 @@ import {
salesforceUpdateOpportunityTool,
salesforceUpdateTaskTool,
} from '@/tools/salesforce'
import {
createBusinessPartnerTool as sapS4HanaCreateBusinessPartnerTool,
createPurchaseOrderTool as sapS4HanaCreatePurchaseOrderTool,
createPurchaseRequisitionTool as sapS4HanaCreatePurchaseRequisitionTool,
createSalesOrderTool as sapS4HanaCreateSalesOrderTool,
deleteSalesOrderTool as sapS4HanaDeleteSalesOrderTool,
getBillingDocumentTool as sapS4HanaGetBillingDocumentTool,
getBusinessPartnerTool as sapS4HanaGetBusinessPartnerTool,
getCustomerTool as sapS4HanaGetCustomerTool,
getInboundDeliveryTool as sapS4HanaGetInboundDeliveryTool,
getMaterialDocumentTool as sapS4HanaGetMaterialDocumentTool,
getOutboundDeliveryTool as sapS4HanaGetOutboundDeliveryTool,
getProductTool as sapS4HanaGetProductTool,
getPurchaseOrderTool as sapS4HanaGetPurchaseOrderTool,
getPurchaseRequisitionTool as sapS4HanaGetPurchaseRequisitionTool,
getSalesOrderTool as sapS4HanaGetSalesOrderTool,
getSupplierInvoiceTool as sapS4HanaGetSupplierInvoiceTool,
getSupplierTool as sapS4HanaGetSupplierTool,
listBillingDocumentsTool as sapS4HanaListBillingDocumentsTool,
listBusinessPartnersTool as sapS4HanaListBusinessPartnersTool,
listCustomersTool as sapS4HanaListCustomersTool,
listInboundDeliveriesTool as sapS4HanaListInboundDeliveriesTool,
listMaterialDocumentsTool as sapS4HanaListMaterialDocumentsTool,
listMaterialStockTool as sapS4HanaListMaterialStockTool,
listOutboundDeliveriesTool as sapS4HanaListOutboundDeliveriesTool,
listProductsTool as sapS4HanaListProductsTool,
listPurchaseOrdersTool as sapS4HanaListPurchaseOrdersTool,
listPurchaseRequisitionsTool as sapS4HanaListPurchaseRequisitionsTool,
listSalesOrdersTool as sapS4HanaListSalesOrdersTool,
listSupplierInvoicesTool as sapS4HanaListSupplierInvoicesTool,
listSuppliersTool as sapS4HanaListSuppliersTool,
odataQueryTool as sapS4HanaOdataQueryTool,
updateBusinessPartnerTool as sapS4HanaUpdateBusinessPartnerTool,
updateCustomerTool as sapS4HanaUpdateCustomerTool,
updateProductTool as sapS4HanaUpdateProductTool,
updatePurchaseOrderTool as sapS4HanaUpdatePurchaseOrderTool,
updatePurchaseRequisitionTool as sapS4HanaUpdatePurchaseRequisitionTool,
updateSalesOrderTool as sapS4HanaUpdateSalesOrderTool,
updateSupplierTool as sapS4HanaUpdateSupplierTool,
} from '@/tools/sap_s4hana'
import { searchTool } from '@/tools/search'
import {
secretsManagerCreateSecretTool,
@@ -5286,6 +5326,44 @@ export const tools: Record<string, ToolConfig> = {
salesforce_query_more: salesforceQueryMoreTool,
salesforce_describe_object: salesforceDescribeObjectTool,
salesforce_list_objects: salesforceListObjectsTool,
sap_s4hana_create_business_partner: sapS4HanaCreateBusinessPartnerTool,
sap_s4hana_create_purchase_order: sapS4HanaCreatePurchaseOrderTool,
sap_s4hana_create_purchase_requisition: sapS4HanaCreatePurchaseRequisitionTool,
sap_s4hana_create_sales_order: sapS4HanaCreateSalesOrderTool,
sap_s4hana_delete_sales_order: sapS4HanaDeleteSalesOrderTool,
sap_s4hana_get_billing_document: sapS4HanaGetBillingDocumentTool,
sap_s4hana_get_business_partner: sapS4HanaGetBusinessPartnerTool,
sap_s4hana_get_customer: sapS4HanaGetCustomerTool,
sap_s4hana_get_inbound_delivery: sapS4HanaGetInboundDeliveryTool,
sap_s4hana_get_material_document: sapS4HanaGetMaterialDocumentTool,
sap_s4hana_get_outbound_delivery: sapS4HanaGetOutboundDeliveryTool,
sap_s4hana_get_product: sapS4HanaGetProductTool,
sap_s4hana_get_purchase_order: sapS4HanaGetPurchaseOrderTool,
sap_s4hana_get_purchase_requisition: sapS4HanaGetPurchaseRequisitionTool,
sap_s4hana_get_sales_order: sapS4HanaGetSalesOrderTool,
sap_s4hana_get_supplier: sapS4HanaGetSupplierTool,
sap_s4hana_get_supplier_invoice: sapS4HanaGetSupplierInvoiceTool,
sap_s4hana_list_billing_documents: sapS4HanaListBillingDocumentsTool,
sap_s4hana_list_business_partners: sapS4HanaListBusinessPartnersTool,
sap_s4hana_list_customers: sapS4HanaListCustomersTool,
sap_s4hana_list_inbound_deliveries: sapS4HanaListInboundDeliveriesTool,
sap_s4hana_list_material_documents: sapS4HanaListMaterialDocumentsTool,
sap_s4hana_list_material_stock: sapS4HanaListMaterialStockTool,
sap_s4hana_list_outbound_deliveries: sapS4HanaListOutboundDeliveriesTool,
sap_s4hana_list_products: sapS4HanaListProductsTool,
sap_s4hana_list_purchase_orders: sapS4HanaListPurchaseOrdersTool,
sap_s4hana_list_purchase_requisitions: sapS4HanaListPurchaseRequisitionsTool,
sap_s4hana_list_sales_orders: sapS4HanaListSalesOrdersTool,
sap_s4hana_list_supplier_invoices: sapS4HanaListSupplierInvoicesTool,
sap_s4hana_list_suppliers: sapS4HanaListSuppliersTool,
sap_s4hana_odata_query: sapS4HanaOdataQueryTool,
sap_s4hana_update_business_partner: sapS4HanaUpdateBusinessPartnerTool,
sap_s4hana_update_customer: sapS4HanaUpdateCustomerTool,
sap_s4hana_update_product: sapS4HanaUpdateProductTool,
sap_s4hana_update_purchase_order: sapS4HanaUpdatePurchaseOrderTool,
sap_s4hana_update_purchase_requisition: sapS4HanaUpdatePurchaseRequisitionTool,
sap_s4hana_update_sales_order: sapS4HanaUpdateSalesOrderTool,
sap_s4hana_update_supplier: sapS4HanaUpdateSupplierTool,
sqs_send: sqsSendTool,
sts_assume_role: stsAssumeRoleTool,
sts_get_caller_identity: stsGetCallerIdentityTool,

View File

@@ -0,0 +1,162 @@
import type { CreateBusinessPartnerParams, SapProxyResponse } from '@/tools/sap_s4hana/types'
import {
baseProxyBody,
parseJsonInput,
SAP_PROXY_URL,
transformSapProxyResponse,
} from '@/tools/sap_s4hana/utils'
import type { ToolConfig } from '@/tools/types'
export const createBusinessPartnerTool: ToolConfig<CreateBusinessPartnerParams, SapProxyResponse> =
{
id: 'sap_s4hana_create_business_partner',
name: 'SAP S/4HANA Create Business Partner',
description:
'Create a business partner in SAP S/4HANA Cloud (API_BUSINESS_PARTNER, A_BusinessPartner). For Person category 1 provide FirstName and LastName. For Organization category 2 provide OrganizationBPName1.',
version: '1.0.0',
params: {
subdomain: {
type: 'string',
required: true,
visibility: 'user-only',
description:
'SAP BTP subaccount subdomain (technical name of your subaccount, not the S/4HANA host)',
},
region: {
type: 'string',
required: true,
visibility: 'user-only',
description: 'BTP region (e.g. eu10, us10)',
},
clientId: {
type: 'string',
required: true,
visibility: 'user-only',
description: 'OAuth client ID from the S/4HANA Communication Arrangement',
},
clientSecret: {
type: 'string',
required: true,
visibility: 'user-only',
description: 'OAuth client secret from the S/4HANA Communication Arrangement',
},
deploymentType: {
type: 'string',
required: false,
visibility: 'user-only',
description: 'Deployment type: cloud_public (default), cloud_private, or on_premise',
},
authType: {
type: 'string',
required: false,
visibility: 'user-only',
description: 'Authentication type: oauth_client_credentials (default) or basic',
},
baseUrl: {
type: 'string',
required: false,
visibility: 'user-only',
description: 'Base URL of the S/4HANA host (Cloud Private / On-Premise)',
},
tokenUrl: {
type: 'string',
required: false,
visibility: 'user-only',
description: 'OAuth token URL (Cloud Private / On-Premise + OAuth)',
},
username: {
type: 'string',
required: false,
visibility: 'user-only',
description: 'Username for HTTP Basic auth',
},
password: {
type: 'string',
required: false,
visibility: 'user-only',
description: 'Password for HTTP Basic auth',
},
businessPartnerCategory: {
type: 'string',
required: true,
visibility: 'user-or-llm',
description: 'BusinessPartnerCategory: "1" Person, "2" Organization, "3" Group',
},
businessPartnerGrouping: {
type: 'string',
required: true,
visibility: 'user-or-llm',
description:
'BusinessPartnerGrouping (number range / role grouping configured in S/4HANA, e.g. "0001")',
},
firstName: {
type: 'string',
required: false,
visibility: 'user-or-llm',
description: 'FirstName (required for Person)',
},
lastName: {
type: 'string',
required: false,
visibility: 'user-or-llm',
description: 'LastName (required for Person)',
},
organizationBPName1: {
type: 'string',
required: false,
visibility: 'user-or-llm',
description: 'OrganizationBPName1 (required for Organization)',
},
body: {
type: 'json',
required: false,
visibility: 'user-or-llm',
description: 'Optional additional A_BusinessPartner fields merged into the create payload',
},
},
request: {
url: SAP_PROXY_URL,
method: 'POST',
headers: () => ({ 'Content-Type': 'application/json' }),
body: (params) => {
const extra = parseJsonInput<Record<string, unknown>>(params.body, 'body') ?? {}
const extraHasName = (key: string) => Object.hasOwn(extra, key) && Boolean(extra[key])
if (params.businessPartnerCategory === '1') {
const hasFirst = Boolean(params.firstName) || extraHasName('FirstName')
const hasLast = Boolean(params.lastName) || extraHasName('LastName')
if (!hasFirst || !hasLast) {
throw new Error('BusinessPartnerCategory "1" (Person) requires FirstName and LastName')
}
} else if (params.businessPartnerCategory === '2') {
const hasOrgName =
Boolean(params.organizationBPName1) || extraHasName('OrganizationBPName1')
if (!hasOrgName) {
throw new Error(
'BusinessPartnerCategory "2" (Organization) requires OrganizationBPName1'
)
}
}
const payload: Record<string, unknown> = {
...extra,
BusinessPartnerCategory: params.businessPartnerCategory,
BusinessPartnerGrouping: params.businessPartnerGrouping,
}
if (params.firstName) payload.FirstName = params.firstName
if (params.lastName) payload.LastName = params.lastName
if (params.organizationBPName1) payload.OrganizationBPName1 = params.organizationBPName1
return {
...baseProxyBody(params),
service: 'API_BUSINESS_PARTNER',
path: '/A_BusinessPartner',
method: 'POST',
query: { $format: 'json' },
body: payload,
}
},
},
transformResponse: transformSapProxyResponse,
outputs: {
status: { type: 'number', description: 'HTTP status code returned by SAP' },
data: { type: 'json', description: 'Created A_BusinessPartner entity' },
},
}

View File

@@ -0,0 +1,151 @@
import type { CreatePurchaseOrderParams, SapProxyResponse } from '@/tools/sap_s4hana/types'
import {
baseProxyBody,
parseJsonInput,
SAP_PROXY_URL,
transformSapProxyResponse,
} from '@/tools/sap_s4hana/utils'
import type { ToolConfig } from '@/tools/types'
export const createPurchaseOrderTool: ToolConfig<CreatePurchaseOrderParams, SapProxyResponse> = {
id: 'sap_s4hana_create_purchase_order',
name: 'SAP S/4HANA Create Purchase Order',
description:
'Create a purchase order in SAP S/4HANA Cloud (API_PURCHASEORDER_PROCESS_SRV, A_PurchaseOrder). PurchaseOrder is auto-assigned by SAP from the document number range; provide line items via the body parameter.',
version: '1.0.0',
params: {
subdomain: {
type: 'string',
required: true,
visibility: 'user-only',
description:
'SAP BTP subaccount subdomain (technical name of your subaccount, not the S/4HANA host)',
},
region: {
type: 'string',
required: true,
visibility: 'user-only',
description: 'BTP region (e.g. eu10, us10)',
},
clientId: {
type: 'string',
required: true,
visibility: 'user-only',
description: 'OAuth client ID from the S/4HANA Communication Arrangement',
},
clientSecret: {
type: 'string',
required: true,
visibility: 'user-only',
description: 'OAuth client secret from the S/4HANA Communication Arrangement',
},
deploymentType: {
type: 'string',
required: false,
visibility: 'user-only',
description: 'Deployment type: cloud_public (default), cloud_private, or on_premise',
},
authType: {
type: 'string',
required: false,
visibility: 'user-only',
description: 'Authentication type: oauth_client_credentials (default) or basic',
},
baseUrl: {
type: 'string',
required: false,
visibility: 'user-only',
description: 'Base URL of the S/4HANA host (Cloud Private / On-Premise)',
},
tokenUrl: {
type: 'string',
required: false,
visibility: 'user-only',
description: 'OAuth token URL (Cloud Private / On-Premise + OAuth)',
},
username: {
type: 'string',
required: false,
visibility: 'user-only',
description: 'Username for HTTP Basic auth',
},
password: {
type: 'string',
required: false,
visibility: 'user-only',
description: 'Password for HTTP Basic auth',
},
purchaseOrderType: {
type: 'string',
required: true,
visibility: 'user-or-llm',
description: 'PurchaseOrderType (e.g., "NB" Standard PO)',
},
companyCode: {
type: 'string',
required: true,
visibility: 'user-or-llm',
description: 'CompanyCode (4 chars, e.g., "1010")',
},
purchasingOrganization: {
type: 'string',
required: true,
visibility: 'user-or-llm',
description: 'PurchasingOrganization (4 chars)',
},
purchasingGroup: {
type: 'string',
required: true,
visibility: 'user-or-llm',
description: 'PurchasingGroup (3 chars)',
},
supplier: {
type: 'string',
required: true,
visibility: 'user-or-llm',
description: 'Supplier business partner key (up to 10 chars)',
},
body: {
type: 'json',
required: true,
visibility: 'user-or-llm',
description:
'A_PurchaseOrder body containing to_PurchaseOrderItem deep-insert items (required by SAP) plus any additional header fields, e.g., {"to_PurchaseOrderItem":[{"PurchaseOrderItem":"10","Material":"TG11","OrderQuantity":"5","Plant":"1010","PurchaseOrderQuantityUnit":"PC","NetPriceAmount":"100.00","DocumentCurrency":"USD"}]}.',
},
},
request: {
url: SAP_PROXY_URL,
method: 'POST',
headers: () => ({ 'Content-Type': 'application/json' }),
body: (params) => {
const extra = parseJsonInput<Record<string, unknown>>(params.body, 'body') ?? {}
const items = Array.isArray(extra.to_PurchaseOrderItem) ? extra.to_PurchaseOrderItem : null
if (!items || items.length === 0) {
throw new Error(
'body must include a non-empty "to_PurchaseOrderItem" array of purchase order line items'
)
}
const payload: Record<string, unknown> = {
...extra,
PurchaseOrderType: params.purchaseOrderType,
CompanyCode: params.companyCode,
PurchasingOrganization: params.purchasingOrganization,
PurchasingGroup: params.purchasingGroup,
Supplier: params.supplier,
}
return {
...baseProxyBody(params),
service: 'API_PURCHASEORDER_PROCESS_SRV',
path: '/A_PurchaseOrder',
method: 'POST',
query: { $format: 'json' },
body: payload,
}
},
},
transformResponse: transformSapProxyResponse,
outputs: {
status: { type: 'number', description: 'HTTP status code returned by SAP' },
data: { type: 'json', description: 'Created A_PurchaseOrder entity' },
},
}

View File

@@ -0,0 +1,132 @@
import type { CreatePurchaseRequisitionParams, SapProxyResponse } from '@/tools/sap_s4hana/types'
import {
baseProxyBody,
parseJsonInput,
SAP_PROXY_URL,
transformSapProxyResponse,
} from '@/tools/sap_s4hana/utils'
import type { ToolConfig } from '@/tools/types'
export const createPurchaseRequisitionTool: ToolConfig<
CreatePurchaseRequisitionParams,
SapProxyResponse
> = {
id: 'sap_s4hana_create_purchase_requisition',
name: 'SAP S/4HANA Create Purchase Requisition',
description:
'Create a purchase requisition in SAP S/4HANA Cloud (API_PURCHASEREQ_PROCESS_SRV, A_PurchaseRequisitionHeader). PurchaseRequisition is auto-assigned by SAP from the document number range; provide line items via the to_PurchaseReqnItem deep-insert array. Note: API_PURCHASEREQ_PROCESS_SRV is deprecated since S/4HANA Cloud Public Edition 2402; the successor is API_PURCHASEREQUISITION_2 (OData v4). This tool still works against tenants where the legacy service is enabled.',
version: '1.0.0',
params: {
subdomain: {
type: 'string',
required: true,
visibility: 'user-only',
description:
'SAP BTP subaccount subdomain (technical name of your subaccount, not the S/4HANA host)',
},
region: {
type: 'string',
required: true,
visibility: 'user-only',
description: 'BTP region (e.g. eu10, us10)',
},
clientId: {
type: 'string',
required: true,
visibility: 'user-only',
description: 'OAuth client ID from the S/4HANA Communication Arrangement',
},
clientSecret: {
type: 'string',
required: true,
visibility: 'user-only',
description: 'OAuth client secret from the S/4HANA Communication Arrangement',
},
deploymentType: {
type: 'string',
required: false,
visibility: 'user-only',
description: 'Deployment type: cloud_public (default), cloud_private, or on_premise',
},
authType: {
type: 'string',
required: false,
visibility: 'user-only',
description: 'Authentication type: oauth_client_credentials (default) or basic',
},
baseUrl: {
type: 'string',
required: false,
visibility: 'user-only',
description: 'Base URL of the S/4HANA host (Cloud Private / On-Premise)',
},
tokenUrl: {
type: 'string',
required: false,
visibility: 'user-only',
description: 'OAuth token URL (Cloud Private / On-Premise + OAuth)',
},
username: {
type: 'string',
required: false,
visibility: 'user-only',
description: 'Username for HTTP Basic auth',
},
password: {
type: 'string',
required: false,
visibility: 'user-only',
description: 'Password for HTTP Basic auth',
},
purchaseRequisitionType: {
type: 'string',
required: true,
visibility: 'user-or-llm',
description: 'PurchaseRequisitionType (e.g., "NB" Standard PR)',
},
items: {
type: 'json',
required: true,
visibility: 'user-or-llm',
description:
'to_PurchaseReqnItem deep-insert array (e.g., [{"PurchaseRequisitionItem":"10","Material":"TG11","RequestedQuantity":"5","Plant":"1010","BaseUnit":"PC","DeliveryDate":"/Date(1735689600000)/"}])',
},
body: {
type: 'json',
required: false,
visibility: 'user-or-llm',
description:
'Additional A_PurchaseRequisitionHeader fields merged into the create payload (e.g., {"PurchaseRequisitionDescription":"Office supplies"})',
},
},
request: {
url: SAP_PROXY_URL,
method: 'POST',
headers: () => ({ 'Content-Type': 'application/json' }),
body: (params) => {
const items = parseJsonInput<Array<Record<string, unknown>>>(params.items, 'items')
if (!Array.isArray(items) || items.length === 0) {
throw new Error('items must be a non-empty JSON array of purchase requisition items')
}
const extra = parseJsonInput<Record<string, unknown>>(params.body, 'body') ?? {}
const payload: Record<string, unknown> = {
...extra,
PurchaseRequisitionType: params.purchaseRequisitionType,
to_PurchaseReqnItem: items,
}
return {
...baseProxyBody(params),
service: 'API_PURCHASEREQ_PROCESS_SRV',
path: '/A_PurchaseRequisitionHeader',
method: 'POST',
query: { $format: 'json' },
body: payload,
}
},
},
transformResponse: transformSapProxyResponse,
outputs: {
status: { type: 'number', description: 'HTTP status code returned by SAP' },
data: { type: 'json', description: 'Created A_PurchaseRequisitionHeader entity' },
},
}

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