@collective-intelligence/external-apps-server-sdk 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -74,6 +74,8 @@ error } }`.
74
74
  throws `TypeError`.
75
75
  - `defineCiEntityResource` keeps each failure as a value of its
76
76
  `ResourceResult`, with `transport_error` and its `outcome`.
77
+ - A refusal of `ci.access` rejects with `ServerAccessError`, a
78
+ `Schema.TaggedError` with the HTTP `status` and CI's error `body`.
77
79
  - `GatewayEffectRuntimeError` is a `Schema.TaggedError`; `new
78
80
  GatewayEffectRuntimeError(cause)` keeps its positional form.
79
81
 
@@ -169,7 +171,9 @@ path, query, or fragment. Mount `createExternalApplicationBff` (or
169
171
  `createExternalApplicationBffNextHandlers`) once for federated auth, Resource
170
172
  proxy, and dedicated Capability forwarding. Pass `ciResources` to bind one
171
173
  Resource proxy mount per entity contract by `schemaFqn`; the BFF authorizes
172
- those mounts with `authorizeWithUserAuth`. Dedicated Capability forwarding sends
174
+ those mounts with `authorizeWithUserAuth`, whose `read` and `write` Access
175
+ Requirements are checked against the app's slice of the user's access
176
+ (default: `core.platform.knowledge` for both; CI decides each record again). Dedicated Capability forwarding sends
173
177
  the signed-in user's delegated token and the caller's `x-organization-id` by
174
178
  default. For an application without federated CI users, pass
175
179
  `capabilities: { authentication: { mode: "service", credentials },
@@ -184,10 +188,15 @@ so the backend runs only the Agent's own bindings and never the application's
184
188
  service authority. An Audit subject with `mappedUserId` is refused with `401`
185
189
  for a visitor caller. Forwarding covers `context`, `knowledge`, `agents`,
186
190
  `conversations` (continue and history), `skills`, `workflows`, and `runs/*`.
191
+ In user-token mode, and for each `ciResources` mount, the BFF passes CI's
192
+ answer to `auth.observeCiResponse`: a `401` or a changed `x-access-version`
193
+ drops the identity that lookups of that Access token reuse, so the next
194
+ lookup reads CI again at once.
187
195
  Reconstruct the public origin from
188
196
  `x-forwarded-host` / `x-forwarded-proto`. Compose a Fixed workflow route with
189
197
  `createFixedWorkflowRoute`: it rewrites that public origin, authorizes
190
- `getEntityContext` plus `requiredScopes`, stamps `x-organization-id` from the
198
+ `getEntityContext` plus an optional `requirement` (an Access Requirement on
199
+ the app's slice of the user's access), stamps `x-organization-id` from the
191
200
  session, POSTs `/application/v1/workflows/:id/runs`, and returns `{ runId }`.
192
201
  Configure exactly one server-owned target: `workflowId` for a workflow UUID or
193
202
  `workflowFqn` for its stable fully qualified name. The route rejects either
@@ -214,7 +223,6 @@ import {
214
223
  const { accessToken, expiresAt } = await exchangeMemberSession({
215
224
  credentials: { clientId, clientSecret },
216
225
  organizationId,
217
- scopes: ["context:read", "knowledge:write"],
218
226
  sessionToken: member.ciSessionToken,
219
227
  tenantUrl: "https://ci.example.com"
220
228
  })
@@ -228,8 +236,9 @@ await ci.context.get({ organizationId })
228
236
  Only a confidential application can exchange, with its client secret. CI
229
237
  applies the same checks as the browser login: the session is live, the member
230
238
  is not banned and belongs to the Organization, the application is enabled and
231
- allowed in that Organization, and the requested scopes are a non-empty subset
232
- of the application's scopes. The token acts as the member (`detached_user`),
239
+ allowed in that Organization, and the member enters the app: one of its grants
240
+ holds the app gate. The token acts as the member (`detached_user`), cut to the
241
+ app's Max Privileges,
233
242
  lasts 300 seconds, has no refresh token, and stops working when the member's
234
243
  CI session ends. `expiresAt` is counted from before the request and set 30
235
244
  seconds early, so exchange again once it passes; never send either token to
@@ -243,13 +252,13 @@ with a retryable `MemberSessionExchangeError`.
243
252
  A refusal throws `MemberSessionExchangeError`. `code` is CI's OAuth error:
244
253
  `invalid_grant` means the CI session ended or the member cannot act in the
245
254
  Organization, so sign the member in again. `invalid_client`,
246
- `unauthorized_client`, `invalid_scope` and `invalid_target` point at the
247
- application's credentials, type, scopes or allowed Organizations.
255
+ `unauthorized_client` and `invalid_target` point at the application's
256
+ credentials, type or allowed Organizations.
248
257
  `temporarily_unavailable` is retryable. On the wire this is the RFC 8693 grant
249
258
  `urn:ietf:params:oauth:grant-type:token-exchange` on `POST /oauth/token`, with
250
259
  `subject_token_type`
251
- `urn:collective-intelligence:params:oauth:token-type:session_token`, `scope`
252
- and `organization_id`.
260
+ `urn:collective-intelligence:params:oauth:token-type:session_token` and
261
+ `organization_id`; an external app sends no `scope`.
253
262
 
254
263
  ## Reuse Nest operations and local AI tools
255
264
 
@@ -503,7 +512,7 @@ succeeded before the new turn started count. A turn is
503
512
  retried message replay the same turn instead of adding one. Use each key for
504
513
  one message only; reusing it for a different message or conversation returns
505
514
  `conflict`.
506
- - The `ai:invoke` scope gates conversations.
515
+ - `core.platform.conversations` in the caller's grants gates conversations.
507
516
  - The Agent's current audience gates every turn and every `history` read. When
508
517
  an administrator removes the caller from the audience, the same caller gets
509
518
  `not_found` for its own conversations too.
@@ -511,14 +520,14 @@ succeeded before the new turn started count. A turn is
511
520
  visitor's `auditSubject` (no `mappedUserId`). Only a declared Agent with
512
521
  `audience: { anonymous: true }` that lists this application admits it. The
513
522
  visitor's turns run with the Agent's own bindings under an anonymous visitor
514
- subject, never with the application's scopes. Visitors are separate owners:
523
+ subject, never with the application's grants. Visitors are separate owners:
515
524
  one visitor never reads another visitor's conversation.
516
525
 
517
526
  ## Messages
518
527
 
519
528
  `messages.send` sends one message through a messaging connection of the
520
529
  Organization, for example a Telegram bot or a WhatsApp Business Account. The
521
- application needs the `messaging:send` scope, and an administrator must grant
530
+ caller needs `core.platform.messaging` in its grants, and an administrator must grant
522
531
  the connection to the application on its administration page.
523
532
 
524
533
  ```ts
@@ -562,46 +571,73 @@ const sent = await ci.messages.send({
562
571
  reached its rate limit; it is retryable, and the client repeats it with the
563
572
  same key.
564
573
 
565
- ## Application users and roles
574
+ ## Members, guests, grants and Groups (`ci.access`)
566
575
 
567
- Use `ci.users` and `ci.roles` with a delegated user token or service
568
- credentials. CI checks the caller's current `users.create` and `assignRoles`
569
- permissions. These methods replace the former `ci.members` API.
576
+ `ci.access` manages the access of one Organization from your server. Call it
577
+ with the app's server credentials (`mode: "service"`), which act with the
578
+ grants an administrator gave the app's server, or with a service principal's
579
+ API key as the delegated token. CI authorizes each call with the caller's
580
+ Tuples: members and invitations need `admin.users`, guests `admin.guests`,
581
+ grants `admin.grants`, Groups `admin.groups`, and the read-only model
582
+ `admin.profiles`. A refused call rejects with `ServerAccessError` (`status`
583
+ and CI's error `body`); a request that does not reach CI rejects with
584
+ `CiTransportError`. Calls are not retried. In `/effect`, the same methods
585
+ are `access` of `ServerClient` and fail with `ServerAccessError` or
586
+ `CiTransportError` ([Effect authoring](#effect-authoring)).
570
587
 
571
588
  ```ts
572
- const created = await ci.users.createOrGet({
573
- email: "info@rossi.example",
574
- name: "Rossi Srl",
575
- organizationId,
576
- roles: ["patient"],
577
- serverRole: "onboarding" // Optional for service calls; omission uses the credential default.
589
+ const created = await ci.access.members.create({
590
+ email: "ada@example.test",
591
+ grants: [{ profile: "clinic.profiles.patient" }],
592
+ kind: "guest",
593
+ mode: "direct",
594
+ organizationId
595
+ })
596
+
597
+ const result = await ci.access.grants.sync({
598
+ grants: [
599
+ {
600
+ fqn: "clinic.patients.ada",
601
+ grantee: { user: { email: "ada@example.test" } },
602
+ profile: "clinic.profiles.patient"
603
+ }
604
+ ],
605
+ namespace: "clinic.patients",
606
+ organizationId
578
607
  })
579
- // On success: created.value.result = { userId, email, name, created, kind }
580
- // kind is "member" or "external_app_user".
608
+ // result = { created, updated, deleted, unchanged }: Access Grant FQNs.
581
609
  ```
582
610
 
583
- - `createOrGet` reuses the person's auth identity. A new app user has no
584
- Organization membership. An existing member remains a member.
585
- - `checkEmail({ organizationId, email })` asks whether `createOrGet` would
586
- accept the email, without creating anything. The result is
587
- `{ usable: true }` or `{ usable: false, reason }`, with `user_unavailable`
588
- or `target_inactive` as `createOrGet` would refuse. An unknown email is
589
- usable. It needs service credentials and `users.create`.
590
- - `get({ organizationId, userId })` and
591
- `list({ organizationId, page?, pageSize? })` read users accessible to this
592
- app. A list result contains `items`.
593
- - `deactivate({ organizationId, userId })` ends access to the calling app for
594
- an app user it may deactivate; it does not remove Organization membership.
595
- - `roles.list({ organizationId })` returns `items` with role `id` and `key`.
596
- `roles.assign({ organizationId, userId, roles })` and `roles.revoke(...)`
597
- change this app's assignments within the caller's `assignRoles` permission.
598
- They cannot write Organization Roles, Groups, or another app's roles.
599
- - Pass `serverRole` on a service request to select an allowed Server Role via
600
- `x-external-server-role`. It applies only to that request; credentials and
601
- subsequent calls retain their default. It does not impersonate a user.
602
- - Refusals preserve the structured error, including a reason such as
603
- `role_not_assignable`. Non-retryable refusals are returned without retrying.
604
- CI records the actual user, or application and Server Role, as the actor.
611
+ - `members`: `create` (directly or by invitation, with at least one grant;
612
+ Grant Authority decides each grant), `get`, `list` (`after`, `email`,
613
+ `limit`), `findByEmail`, `suspend`, `resume` and `remove`. An app server
614
+ creates, reads and changes only its own guests.
615
+ - `invitations`: `list` (`status`, `page`, `limit`) and `revoke`. Only a
616
+ service principal invites, so an app server is refused.
617
+ - `grants`: `create`, `get`, `update` and `delete` by `grantId` or `fqn`,
618
+ `list` by `userId`, `groupId` or `namespace`, and `sync` of a namespace.
619
+ A grant names its grantee as `{ user: { email } }`,
620
+ `{ group: { fqn }, coverage }`, `{ servicePrincipal: "<fqn>" }`, or an
621
+ app's `{ applicationServer: "<app fqn>" }` (a `server` profile) or
622
+ `{ applicationVisitors: "<app fqn>" }` (an `anonymous` profile). Every
623
+ grant has an Access Grant FQN; a Group without an FQN gets grants only in
624
+ the Dashboard.
625
+ - `groups`: `create`, `get`, `list` (`page`, `limit`), `update`, `delete`,
626
+ `addMember` and `removeMember` by `userId`. A member change of a Group
627
+ that a holders-only grant reaches also needs Grant Authority over that
628
+ grant. An app server reads Groups but writes none.
629
+ - `profiles.list`, `profiles.get`, `catalog.list`, `axes.list`,
630
+ `maxPrivileges.list`, `maxPrivileges.get`, `knowledgePolicies.list` and
631
+ `knowledgePolicies.forSchema({ organizationId, schemaFqn })` read the
632
+ declared model; the core and packages stay its source of truth.
633
+ `forSchema` answers the policies that decide the reads and the writes of
634
+ the schema, as CI fills its Policy Slots.
635
+ - A paged list answers `{ items, next }`: pass `next` back as `after`
636
+ (members) or `page` (Groups, invitations) to read the page after it.
637
+ - `snapshot({ organizationId, userId })` reads a user's Access Snapshot;
638
+ `explain` tells why a principal may use a capability or act on a record.
639
+ - There is no `ci.users` or `ci.roles`: app users became guests, and roles
640
+ became Access Grants of profiles.
605
641
 
606
642
  ## Durable files
607
643
 
@@ -634,7 +670,7 @@ await ci.workflows.invoke({
634
670
  public URL, and another Organization cannot read it.
635
671
  - `attachments.upload` is different: its file belongs to one run and expires
636
672
  after 24 hours.
637
- - It needs the `ai:attachments` scope. Only service credentials may call it: a
673
+ - It needs `core.platform.attachments` in the app server's grants. Only service credentials may call it: a
638
674
  delegated user token or an anonymous visitor gets `operation_not_allowed`.
639
675
 
640
676
  ### Entity File fields
@@ -785,9 +821,8 @@ A schema declares its accounts field to name the users that act for each of its
785
821
  records (see the [Knowledge User fields](../../../docs/reference/knowledge-user-fields.md)
786
822
  reference). CI stores no other link between a user and a record, and offers no
787
823
  operation that lists or changes one: write the accounts field as an
788
- administrator, with the workflow account step or with the Default Server Role
789
- credential. A policy reads the field as `resource` path `["data", "accounts"]`
790
- and the caller as `subject` path `["user", "id"]`.
824
+ administrator or with the workflow account step. A Knowledge Data Condition
825
+ reads it with `isMe("accounts")` or `includesMe("accounts")`.
791
826
 
792
827
  - A delegated user's `/application/v1/resources` and `knowledge_*` calls, and
793
828
  the Agents, Skills and workflows the user runs, decide under the user's
@@ -1034,7 +1069,11 @@ request)` keeps the CI error envelope as a value; `execute` fails with
1034
1069
  `records.get`, `records.search` ([Record reads](#record-reads)) and
1035
1070
  `records.create`, `records.update`, `records.delete`
1036
1071
  ([Record writes](#record-writes)) fail with `CiError`; `recordsResult`
1037
- has the same methods and keeps the refusal of CI as a value.
1072
+ has the same methods and keeps the refusal of CI as a value. `access`
1073
+ has the methods of `ci.access`
1074
+ ([Members, guests, grants and Groups](#members-guests-grants-and-groups-ciaccess));
1075
+ each fails with `ServerAccessError` or `CiTransportError` and is not
1076
+ retried.
1038
1077
  - `layerDelegatedServerClient(config)`: one app-wide `ServerClient` that
1039
1078
  calls CI as the member of each request. `config` is a client config
1040
1079
  without `authentication`. Each attempt sends the `DelegatedAccessToken` of
@@ -1570,13 +1609,16 @@ const handle = createResourceHttpHandler({
1570
1609
  ```
1571
1610
 
1572
1611
  `auth` is the existing `createFederatedAuth(...)` instance. Its server-only
1573
- `getEntityContext` resolves current CI application, user, organization, scopes,
1574
- the user's effective app roles and App Permissions. CI never sends Group IDs or
1575
- Platform Permissions. The browser session JSON at `<basePath>/session` carries
1576
- `expiresAt` and an `identity` with `userId`, `organizationId`, `appId`, `kind`
1577
- (`member` or `external_app_user`), `roles`, `appPermissions`, `email` and
1578
- `name`; it never carries the Access token. A user without a role on the app has
1579
- no session and no entity access. Local Better Auth sessions do
1612
+ `getEntityContext` resolves the CI application, user, organization and the
1613
+ app's slice of the user's capabilities (`capabilities`) for the session's
1614
+ Access token; CI is asked for that identity once per Access
1615
+ token, and again only after an observed CI answer shows a change. CI never sends Group IDs. The browser session JSON at
1616
+ `<basePath>/session` carries `expiresAt` and an `identity` with `userId`,
1617
+ `organizationId`, `appId`, `kind` (`member`, `guest`, or `null` for a tenant
1618
+ user without a membership), `access` (the app's slice of the user's access),
1619
+ `email` and `name`; it never carries the Access token. A user that does not
1620
+ enter the app (no capability at or below the app gate) has no session and no
1621
+ entity access. Local Better Auth sessions do
1580
1622
  not establish CI entity authority. Browser framework adapters require this
1581
1623
  verified context instead of boolean authorization. Machine gateway calls retain
1582
1624
  their separate caller policy.
@@ -1652,7 +1694,7 @@ pagination, predicates, grouping, aggregates or managed extraction.
1652
1694
  Import `createFederatedAuth` from
1653
1695
  `@collective-intelligence/external-apps-server-sdk/auth/federated`. Supply the
1654
1696
  browser-visible HTTPS application origin, CI issuer, OAuth client, organization,
1655
- audience, scopes, and an application-owned atomic session store. The facade owns
1697
+ audience, and an application-owned atomic session store. The facade owns
1656
1698
  PKCE login, callback, session inspection and logout under `/api/auth` by default.
1657
1699
 
1658
1700
  `applicationOrigin` accepts one HTTPS origin or a list. Use a list when one
@@ -1665,7 +1707,6 @@ const auth = createFederatedAuth({
1665
1707
  clientId,
1666
1708
  issuer,
1667
1709
  organizationId,
1668
- scopes: ["knowledge:read"],
1669
1710
  session: { kind: "sealed_cookie", secrets }
1670
1711
  })
1671
1712
  ```
@@ -1692,9 +1733,12 @@ authorization code to its `redirect_uri`, so an unregistered callback fails at
1692
1733
  authorization.
1693
1734
 
1694
1735
  The store persists only hashed opaque-cookie state, token grants and revisions;
1695
- the browser receives a `Secure`, `HttpOnly`, `SameSite=Lax` host cookie. Every
1696
- session lookup revalidates the short-lived CI identity. Revoked or expired CI
1697
- access ends application authorization on the next validation. A confidential
1736
+ the browser receives a `Secure`, `HttpOnly`, `SameSite=Lax` host cookie. A
1737
+ session lookup reads the CI identity of its Access token once per token and
1738
+ again after a `401` or a changed `x-access-version` that
1739
+ `auth.observeCiResponse` sees. A revocation therefore ends application
1740
+ authorization at the next token renewal (at most 300 seconds) or at once when a
1741
+ forwarded CI answer reports it. A confidential
1698
1742
  OAuth client may supply `clientSecret`; a public PKCE client omits it. The
1699
1743
  client type decides how long the User session lasts; see
1700
1744
  [Session lifetime and renewal](#session-lifetime-and-renewal).
@@ -1732,8 +1776,9 @@ each `sessionTtlSeconds` value in the range and gives no warning.
1732
1776
  `getSession`, `getAccessToken`, `getEntityContext` and
1733
1777
  `GET <basePath>/session` are the session lookups. With renewal, each lookup
1734
1778
  first gets a new Access token when the current one is expired or expires in 30
1735
- seconds or less. Then it checks the current identity at `/oauth/identity`. A
1736
- lookup never returns an expired Access token. Lookups at the same time share
1779
+ seconds or less. Then it reads the identity of that token at
1780
+ `/oauth/identity`, once per token. A lookup never returns an expired Access
1781
+ token. Lookups at the same time share
1737
1782
  one renewal request.
1738
1783
 
1739
1784
  The SDK writes the cookie or the store record one time, at sign-in. A renewal
@@ -1772,10 +1817,8 @@ A renewal applies the same admission rule as `/oauth/identity`:
1772
1817
 
1773
1818
  - the external Application is enabled;
1774
1819
  - the CI session is live;
1775
- - the user is not banned, is a member or an active External App User of the
1776
- Organization, and holds at least one role on the app other than
1777
- `anonymous` (Direct Role Assignments replace the roles that Groups give);
1778
- - the scopes of the sign-in are still allowed.
1820
+ - the user is not banned and enters the app: its Tuples hold the app gate
1821
+ or a capability below it.
1779
1822
 
1780
1823
  A refusal ends nothing. When the condition is corrected, the same Renewal
1781
1824
  credential renews again. A Federated authorization ends for good only by one
@@ -1853,10 +1896,10 @@ import {
1853
1896
  const tokens = createAccessTokenVerifier(readApplicationEnrollment(process.env))
1854
1897
 
1855
1898
  const caller = await tokens.verify(bearerToken)
1856
- // userId, organizationId, applicationId, clientId, scopes, sessionId, expiresAt
1899
+ // userId, organizationId, applicationId, clientId, sessionId, expiresAt
1857
1900
 
1858
1901
  const identity = await tokens.identity(bearerToken, { signal: request.signal })
1859
- // the same fields, and user { id, email, name }, kind, roles, appPermissions
1902
+ // the same fields, and user { id, email, name }, kind, access
1860
1903
  ```
1861
1904
 
1862
1905
  - `verify` is offline against the issuer key set: ES256 signature, issuer,
@@ -1864,10 +1907,10 @@ const identity = await tokens.identity(bearerToken, { signal: request.signal })
1864
1907
  It does not see a revocation before the token expires.
1865
1908
  - `identity` runs `verify`, then reads CI's current identity for the token and
1866
1909
  checks that it describes the same grant. Use it when the API needs the
1867
- user's app roles or App Permissions, or must stop at once when CI revokes
1868
- the token or a role. It
1910
+ app's slice of the user's access (`access.capabilities`), or must stop at
1911
+ once when CI revokes the token or the user leaves the app. It
1869
1912
  is one CI request for each call, with a 10-second limit; cache the result
1870
- for as long as a role change may take to reach your API. Pass the `signal`
1913
+ for as long as an access change may take to reach your API. Pass the `signal`
1871
1914
  of the request you serve: when it aborts, the CI request ends and the call
1872
1915
  rejects with the abort reason.
1873
1916
 
@@ -1885,7 +1928,8 @@ const resource = defineCiEntityResource({
1885
1928
  definition: leadDefinition,
1886
1929
  tenantUrl: "https://ci.example.com",
1887
1930
  organizationId,
1888
- schemaFqn
1931
+ schemaFqn,
1932
+ observeCiResponse: auth.observeCiResponse
1889
1933
  })
1890
1934
  ```
1891
1935
 
@@ -2105,7 +2149,7 @@ CI-backed resources created by `defineCiEntityResource` accept the common client
2105
2149
  mounts `POST /records/:parentId/relation-members/search` below the resource base
2106
2150
  path and forwards `{ field, ...query }` to the bound CI schema route. Existing
2107
2151
  verified tenant, organization, resource and user-grant checks still apply;
2108
- `authorizeWithUserAuth` classifies this operation under `readScope`.
2152
+ `authorizeWithUserAuth` classifies this operation under its `read` Requirement.
2109
2153
 
2110
2154
  The page envelope and exact totals remain unchanged. Member records are JSON
2111
2155
  objects validated independently of the parent schema, as are member query field