@collective-intelligence/external-apps-client-sdk 0.5.0 → 0.6.0
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/AGENTS.md +8 -3
- package/README.md +165 -10
- package/dist/chat.d.ts +65 -3
- package/dist/chat.js +224 -20
- package/dist/{index-BwHhPzAs.d.ts → client-NsqWRz1M.d.ts} +655 -61
- package/dist/effect.d.ts +5 -7
- package/dist/effect.js +4 -4
- package/dist/index.d.ts +3 -5
- package/dist/index.js +74 -12
- package/dist/{proxy-B4MA1pat.d.ts → resources-D_PdfDpJ.d.ts} +1034 -12
- package/dist/{resources-DCOTahAB.js → resources-Vd7ESXEA.js} +2 -2
- package/dist/resources.d.ts +2 -2
- package/dist/resources.js +2 -2
- package/dist/{service-w6n_gspU.js → service-B0QOswoK.js} +59 -5
- package/dist/{service-CM4fS7mV.js → service-DCSU2Gqc.js} +125 -12
- package/docs/chat.md +18 -0
- package/docs/effect.md +4 -0
- package/docs/errors.md +5 -0
- package/docs/guide/platform/entrypoints.md +9 -6
- package/package.json +4 -4
- package/dist/client-C-o7Az4B.d.ts +0 -424
- package/dist/resources-Du03G6Wo.d.ts +0 -582
- package/dist/{errors-B4-Jo4j3.js → errors-DRzZfurr.js} +1 -1
package/AGENTS.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
# `@collective-intelligence/external-apps-client-sdk`: agent guide
|
|
2
2
|
|
|
3
3
|
The browser-safe, React-free SDK of Collective Intelligence (CI) external
|
|
4
|
-
applications: federated sign-in, typed CI operations
|
|
5
|
-
clients and the realtime client. It holds no confidential credential. The
|
|
4
|
+
applications: federated sign-in, typed CI operations (also Intents and the
|
|
5
|
+
Access Check), transports, resource clients and the realtime client. It holds no confidential credential. The
|
|
6
6
|
package `README.md` holds the full API.
|
|
7
7
|
|
|
8
8
|
## Rules
|
|
@@ -18,6 +18,9 @@ package `README.md` holds the full API.
|
|
|
18
18
|
- Treat realtime event ids as opaque: store and resend them unchanged.
|
|
19
19
|
- Branch on an error by its class (`instanceof`, `Effect.catchTag`) and its
|
|
20
20
|
`code`, not by its `message`.
|
|
21
|
+
- Branch on the `step` of a `SignInStep` for every sign-in outcome of
|
|
22
|
+
`createServerSessionAuth().signIn`; a call rejects only when it gets no
|
|
23
|
+
step. Send the next step only after the call in flight ends.
|
|
21
24
|
- Keep server credentials out of this package: they belong to
|
|
22
25
|
`external-apps-server-sdk`.
|
|
23
26
|
|
|
@@ -31,7 +34,9 @@ package `README.md` holds the full API.
|
|
|
31
34
|
sign-in.
|
|
32
35
|
- [docs/chat.md](docs/chat.md): read when you call the External App chat
|
|
33
36
|
(`client.chat`, `Chat`), follow a presentation stream, show a chat
|
|
34
|
-
refusal,
|
|
37
|
+
refusal, show the shared chat UI (`createChatTransport` at `/chat`), or
|
|
38
|
+
wire Intents, the Access Check or the browser session store
|
|
39
|
+
(`createIntentTransport`, `createAccessPort`, `createBrowserSessionStore`).
|
|
35
40
|
- [skills/client-sdk-move-to-effect/SKILL.md](skills/client-sdk-move-to-effect/SKILL.md):
|
|
36
41
|
run when Effect code wraps the Promise API (`Effect.tryPromise`,
|
|
37
42
|
`Effect.promise`) of this SDK.
|
package/README.md
CHANGED
|
@@ -20,8 +20,10 @@ proxy credentials and durable application sessions. See
|
|
|
20
20
|
[Session renewal in the browser](#session-renewal-in-the-browser).
|
|
21
21
|
|
|
22
22
|
`createClient` binds a typed transport to CI operations for agents, attachments,
|
|
23
|
-
the chat, context, Knowledge, runs, skills, and
|
|
24
|
-
`forOrganization` to bind those operations to one
|
|
23
|
+
the chat, context, Intents, the Access Check, Knowledge, runs, skills, and
|
|
24
|
+
workflows. Call `forOrganization` to bind those operations to one
|
|
25
|
+
organization. See [Intents and the Access Check](#intents-and-the-access-check)
|
|
26
|
+
for `client.intents` and `client.access`, and
|
|
25
27
|
[External App chat](#external-app-chat) for `client.chat`.
|
|
26
28
|
|
|
27
29
|
For `workflows_invoke`, pass exactly one target: `workflowId` for a workflow
|
|
@@ -85,6 +87,82 @@ An SDK version from before session renewal ignores the Renewal credential and
|
|
|
85
87
|
keeps the 300 second session against the same CI. The CI wire contract is in
|
|
86
88
|
[Access token renewal](../../../docs/architecture/external-app-gateway.md#access-token-renewal).
|
|
87
89
|
|
|
90
|
+
## Embedded Sign-In on a BFF session
|
|
91
|
+
|
|
92
|
+
`createServerSessionAuth({ basePath })` is the client of a sealed-cookie BFF:
|
|
93
|
+
the app server runs the federated auth handler of
|
|
94
|
+
`@collective-intelligence/external-apps-server-sdk`, and the access token
|
|
95
|
+
stays there. When the app has Embedded Sign-In, `auth.signIn` signs a person
|
|
96
|
+
in on the app's own page. It calls the sign-in routes at
|
|
97
|
+
`<basePath>/sign-in/*`; the client secret, the PKCE verifier and the
|
|
98
|
+
challenge stay on the server. `createFederatedAuth` has no `signIn`: an app
|
|
99
|
+
with no server keeps the CI page.
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
import { createServerSessionAuth } from "@collective-intelligence/external-apps-client-sdk"
|
|
103
|
+
|
|
104
|
+
const auth = createServerSessionAuth({ basePath: "/api/auth" })
|
|
105
|
+
|
|
106
|
+
let step = await auth.signIn.start({ email, uiLocales: "it en" })
|
|
107
|
+
if (step.step === "code_sent") {
|
|
108
|
+
step = await auth.signIn.verify({ code })
|
|
109
|
+
}
|
|
110
|
+
if (step.step === "registration_required") {
|
|
111
|
+
step = await auth.signIn.complete({ name })
|
|
112
|
+
}
|
|
113
|
+
if (step.step === "signed_in") {
|
|
114
|
+
// auth.getState().status is "authenticated".
|
|
115
|
+
}
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
| Call | What it does |
|
|
119
|
+
| ----------------------------------------- | ------------------------------------------------------------------------- |
|
|
120
|
+
| `methods({ uiLocales?, returnTo? })` | Opens a Sign-In Challenge; resolves the `methods` step |
|
|
121
|
+
| `start({ email, uiLocales?, returnTo? })` | The email step; opens a challenge when the browser holds none |
|
|
122
|
+
| `verify({ code, returnTo? })` | The code step |
|
|
123
|
+
| `complete({ name, returnTo? })` | The name step of a new person, after `registration_required` |
|
|
124
|
+
| `sso({ provider, returnTo? })` | Sends the browser to `<basePath>/sign-in/sso`; resolves `redirect_to_web` |
|
|
125
|
+
|
|
126
|
+
`.` exports the input type of each call: `SignInMethodsInput`,
|
|
127
|
+
`SignInStartInput`, `SignInVerifyInput`, `SignInCompleteInput` and
|
|
128
|
+
`SignInSsoInput`.
|
|
129
|
+
|
|
130
|
+
Each call resolves one `SignInStep`, on `step`:
|
|
131
|
+
|
|
132
|
+
| `step` | Fields | What the app does |
|
|
133
|
+
| -------------------------- | --------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
|
|
134
|
+
| `methods` | `emailCode`, `password`, `registrationOpen`, `ssoProviders` (`displayName`, `id`) | Show only the allowed methods |
|
|
135
|
+
| `code_sent` | | Ask for the code that CI sent by email |
|
|
136
|
+
| `registration_required` | | A new person: ask for the name, then call `complete` |
|
|
137
|
+
| `signed_in` | `registered` | The state is `authenticated`; `registered` is true for a new account |
|
|
138
|
+
| `invalid_code` | `attemptsLeft` | Ask for the code again |
|
|
139
|
+
| `retry_after` | `seconds` | Wait before a new code |
|
|
140
|
+
| `email_domain_not_allowed` | `allowedDomains` | Ask for an address in one of the domains |
|
|
141
|
+
| `sso_required` | `provider` (`displayName`, `id`) | Call `sso({ provider: provider.id })` |
|
|
142
|
+
| `redirect_to_web` | | The SDK has sent the browser to the CI page or the SSO provider |
|
|
143
|
+
| `access_denied` | | This person cannot sign in to the app |
|
|
144
|
+
| `code_expired` | | The challenge ended: start again with `start` |
|
|
145
|
+
| `no_sign_in_method` | | The app allows no sign-in method |
|
|
146
|
+
|
|
147
|
+
- A refusal is a step, not an error. A call rejects only when it gets no
|
|
148
|
+
step, with `CiTransportError`: a network error, or an answer of the BFF
|
|
149
|
+
other than a step with HTTP 200, such as `400 invalid_request`,
|
|
150
|
+
`403 invalid_origin`, `409 login_conflict` or `503 user_auth_unavailable`.
|
|
151
|
+
Its `cause` names the HTTP status. `sso`, and a call that answers
|
|
152
|
+
`redirect_to_web`, reject with `FederatedAuthError` `configuration_error`
|
|
153
|
+
when the SDK cannot navigate.
|
|
154
|
+
- The calls of one client run one at a time: a call waits for the call in
|
|
155
|
+
flight, so the challenge gets one request at a time.
|
|
156
|
+
- `signed_in` reads `<basePath>/session`, as `completeLogin` does. A `logout`
|
|
157
|
+
or a `beginLogin` during the call ends its result: the state does not
|
|
158
|
+
become `authenticated`.
|
|
159
|
+
- On `redirect_to_web` the SDK runs `beginLogin({ returnTo })`. `returnTo`
|
|
160
|
+
(default `/`) is also the page that `sso` returns to.
|
|
161
|
+
- Send `uiLocales` (the `ui_locales` list of the person) on the call that
|
|
162
|
+
opens the challenge: `methods`, or the first `start`.
|
|
163
|
+
- The routes answer only requests of the app's own pages: the browser sends
|
|
164
|
+
the page's `Origin`.
|
|
165
|
+
|
|
88
166
|
## Workflow results and read recovery
|
|
89
167
|
|
|
90
168
|
A successful Workflow with a declared output contract exposes its persisted
|
|
@@ -262,6 +340,10 @@ query or includes before retrying; these failures expose no member IDs or counts
|
|
|
262
340
|
The `knowledge_query` and `knowledge_autocomplete` operations answer a
|
|
263
341
|
page-number read past the first 10,000 rows with `invalid_request` and details
|
|
264
342
|
`{ reason: "page_depth_exceeded" }`; page by cursor or narrow the search.
|
|
343
|
+
These operations and `knowledge_facets` answer every other request that
|
|
344
|
+
Knowledge Query refuses, such as a `cursor` that is no `nextCursor` of the same
|
|
345
|
+
search, with a non-retryable `invalid_request` whose `message` names the
|
|
346
|
+
mistake. Correct the request; a retry of the same request fails again.
|
|
265
347
|
Current request-wide ceilings are 100,000 work units, 2,000 nested object
|
|
266
348
|
occurrences, 50,000 relation-ID occurrences and 8,388,608 accounted bytes.
|
|
267
349
|
Repeated serialized occurrences count even when target reads are deduplicated.
|
|
@@ -495,6 +577,46 @@ Effect.runFork(
|
|
|
495
577
|
- Timers use `Clock` and the jitter uses `Random`, so a test can use `TestClock`
|
|
496
578
|
and a fixed `Random`.
|
|
497
579
|
|
|
580
|
+
## Intents and the Access Check
|
|
581
|
+
|
|
582
|
+
An Intent is an application goal that a CI package declares and the app
|
|
583
|
+
dispatches by its FQN. `client.intents` dispatches Intents as the signed-in
|
|
584
|
+
user of the app:
|
|
585
|
+
|
|
586
|
+
```ts
|
|
587
|
+
const intents = client.forOrganization(organizationId).intents
|
|
588
|
+
|
|
589
|
+
const listed = await intents.list({})
|
|
590
|
+
const dispatched = await intents.dispatch({
|
|
591
|
+
fqn: "acme.plans.intents.create-plan",
|
|
592
|
+
inputs: { goal: "Open the Milano Nord site" },
|
|
593
|
+
resultTarget: "nothing"
|
|
594
|
+
})
|
|
595
|
+
if (dispatched.ok && dispatched.value.kind === "started") {
|
|
596
|
+
const end = await intents.wait({ handle: dispatched.value.handle })
|
|
597
|
+
}
|
|
598
|
+
```
|
|
599
|
+
|
|
600
|
+
| Method | What it does |
|
|
601
|
+
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
602
|
+
| `list` | The Intents that the user may trigger now, with their input and output schemas and Result Mode. |
|
|
603
|
+
| `dispatch` | Dispatches one Intent. It answers `completed`, `started` (with the Intent Handle), `needs_input` (each refused field), `not_allowed` or `failed`. |
|
|
604
|
+
| `get` | The state of a dispatch by its Intent Handle: `starting`, `running`, `completed` or `failed`. |
|
|
605
|
+
| `wait` | Resolves at the end of the run: it repeats the bounded wait of CI while the run runs. |
|
|
606
|
+
|
|
607
|
+
- `dispatch` sends an `idempotencyKey` (the `idempotency-key` header). Give one
|
|
608
|
+
key for each user action and the same key only to retry it; a call without
|
|
609
|
+
one gets a new key. The same key with another request is a `conflict`.
|
|
610
|
+
- `resultTarget` is `nothing` or `notification`, with an optional
|
|
611
|
+
`returnPage` for a Studio page.
|
|
612
|
+
- Only the user who dispatched reads or waits with a handle; anyone else gets
|
|
613
|
+
`not_found`.
|
|
614
|
+
|
|
615
|
+
`client.access.check({ targets })` answers the Access Check: `allowed` or
|
|
616
|
+
`denied` for each `AccessTarget`, in target order, with the `accessVersion`.
|
|
617
|
+
It takes at most 200 targets. The answers are a display hint only: CI checks
|
|
618
|
+
access on every call.
|
|
619
|
+
|
|
498
620
|
## External App chat
|
|
499
621
|
|
|
500
622
|
`client.chat` calls the External App chat routes
|
|
@@ -593,18 +715,43 @@ and sends nothing: wrap it as `new File([blob], "notes.txt")`.
|
|
|
593
715
|
### Shared chat UI (`./chat`)
|
|
594
716
|
|
|
595
717
|
The `@collective-intelligence/external-apps-client-sdk/chat` entrypoint
|
|
596
|
-
exports
|
|
597
|
-
|
|
598
|
-
`@collective-intelligence/ai-core` over `client.chat`: give it to
|
|
599
|
-
`<AiProvider transport>` of `@collective-intelligence/ai-react` to show the
|
|
600
|
-
default `<Chat>`.
|
|
718
|
+
exports the adapters of the ai-core ports for
|
|
719
|
+
`@collective-intelligence/ai-react`:
|
|
601
720
|
|
|
602
|
-
|
|
603
|
-
|
|
721
|
+
| Export | What it gives |
|
|
722
|
+
| ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
723
|
+
| `createChatTransport(client)` | The `ChatTransport` over `client.chat`, for `<AiProvider transport>`: the default `<Chat>`. |
|
|
724
|
+
| `createIntentTransport(client)` | The `IntentTransport` over `client.intents`, for `<AiProvider intents>`: the Intent controls. |
|
|
725
|
+
| `createAccessPort(client)` | The `AccessCheckPort` over `client.access`, for the `access` host port: the Visibility Gate. |
|
|
726
|
+
| `createBrowserSessionStore()` | The `sessions` host port: the open Conversation of each Place, the pending Intent waits and whether the Assistant Sidebar is open, in web storage. |
|
|
604
727
|
|
|
605
|
-
|
|
728
|
+
```tsx
|
|
729
|
+
import {
|
|
730
|
+
createAccessPort,
|
|
731
|
+
createBrowserSessionStore,
|
|
732
|
+
createChatTransport,
|
|
733
|
+
createIntentTransport
|
|
734
|
+
} from "@collective-intelligence/external-apps-client-sdk/chat"
|
|
735
|
+
|
|
736
|
+
const org = client.forOrganization(organizationId)
|
|
737
|
+
|
|
738
|
+
<AiProvider
|
|
739
|
+
caller={userId}
|
|
740
|
+
host={{ access: createAccessPort(org), sessions: createBrowserSessionStore() }}
|
|
741
|
+
intents={createIntentTransport(org)}
|
|
742
|
+
transport={createChatTransport(org)}
|
|
743
|
+
>
|
|
744
|
+
{children}
|
|
745
|
+
</AiProvider>
|
|
606
746
|
```
|
|
607
747
|
|
|
748
|
+
`createBrowserSessionStore()` keeps its values in the tab's `sessionStorage`,
|
|
749
|
+
so each tab keeps its own chat and its own pending waits; pass
|
|
750
|
+
`{ storage: localStorage }` to share them across tabs. A value that is missing
|
|
751
|
+
or has another shape reads as none, and a storage that refuses (a sandboxed
|
|
752
|
+
frame, a full quota, a server render) drops the write, so the chat keeps
|
|
753
|
+
working.
|
|
754
|
+
|
|
608
755
|
- `@collective-intelligence/ai-core` is an optional peer dependency: only
|
|
609
756
|
`./chat` imports it, so install it with this entry. `./chat` imports no
|
|
610
757
|
React.
|
|
@@ -616,6 +763,10 @@ const transport = createChatTransport(client.forOrganization(organizationId))
|
|
|
616
763
|
retryable. An aborted call rejects with the reason of its signal.
|
|
617
764
|
- `openPresentationStream` opens one connection. Follow a run with
|
|
618
765
|
`followPresentation` of ai-core, which reconnects.
|
|
766
|
+
- `createIntentTransport` and `createAccessPort` answer a CI refusal, a request
|
|
767
|
+
that does not reach CI, and an answer outside their contract as an
|
|
768
|
+
`AiError`; an aborted call rejects with the reason of its signal. The
|
|
769
|
+
Intent transport's `wait` resolves at the end of the run.
|
|
619
770
|
|
|
620
771
|
## Expected Errors and `./effect`
|
|
621
772
|
|
|
@@ -685,6 +836,9 @@ runtime. A failure gives one of these outcomes:
|
|
|
685
836
|
- `createFederatedAuth` and `createServerSessionAuth` reject with
|
|
686
837
|
`FederatedAuthError`. A bad option throws `FederatedAuthError`
|
|
687
838
|
`configuration_error` when you create the client.
|
|
839
|
+
- `createServerSessionAuth().signIn` resolves a `SignInStep` for every
|
|
840
|
+
sign-in outcome and rejects with `CiTransportError` when it gets no step.
|
|
841
|
+
See [Embedded Sign-In on a BFF session](#embedded-sign-in-on-a-bff-session).
|
|
688
842
|
- `createDelegatedApplicationRuntime().followRun` without a session rejects
|
|
689
843
|
with `FederatedAuthError` `reauthorization_required`.
|
|
690
844
|
- `createResourceClient` and `createEntityHttpTransport` keep the
|
|
@@ -719,6 +873,7 @@ a layer that reads Effect `Config`:
|
|
|
719
873
|
| `Runs` (`follow`) | `layerRuns` (needs `CiClient`) | `followRun`, `client.runs.follow` |
|
|
720
874
|
| `Chat` (the `client.chat` groups) | `layerChat` (needs `CiClient`) | `client.chat` |
|
|
721
875
|
| `FederatedAuth` | `layerFederatedAuth`, `layerServerSessionAuth`, and their `…Config` forms | `createFederatedAuth`, `createServerSessionAuth` |
|
|
876
|
+
| `SignIn` (the `signIn` steps) | `layerServerSessionAuth` and its `…Config` form, with `FederatedAuth` | `createServerSessionAuth().signIn` |
|
|
722
877
|
| `FixedWorkflows` (`invoke`) | `layerFixedWorkflows`, `layerFixedWorkflowsConfig` | `createFixedWorkflowClient` |
|
|
723
878
|
| `DelegatedRuntime` | `layerDelegatedRuntime`, `layerDelegatedRuntimeConfig` | `createDelegatedApplicationRuntime` |
|
|
724
879
|
| `Resources` (`bind(definition)`) | `layerResources`, `layerResourcesConfig`, `layerResourcesFromEntityTransport` | `createResourceClient` with `protocol: "entity"`, `createEntityHttpTransport` |
|
package/dist/chat.d.ts
CHANGED
|
@@ -1,6 +1,58 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { i as OrganizationClient } from "./client-
|
|
1
|
+
import { en as ClientOperationMap } from "./resources-D_PdfDpJ.js";
|
|
2
|
+
import { i as OrganizationClient } from "./client-NsqWRz1M.js";
|
|
3
|
+
import * as Schema from "effect/Schema";
|
|
4
|
+
import { Place } from "@collective-intelligence/ai-core";
|
|
5
|
+
import { AccessCheckPort } from "@collective-intelligence/ai-core/access";
|
|
3
6
|
import { ChatTransport } from "@collective-intelligence/ai-core/chat";
|
|
7
|
+
import { IntentTransport } from "@collective-intelligence/ai-core/intents";
|
|
8
|
+
/** The organization client whose access domain the port calls. */
|
|
9
|
+
type AccessPortClient = Pick<OrganizationClient<ClientOperationMap>, "access">;
|
|
10
|
+
/**
|
|
11
|
+
* The `AccessCheckPort` of the Visibility Gate over `client.access`: one
|
|
12
|
+
* `check` sends one Access Check and answers in target order with the Access
|
|
13
|
+
* Version. `check` answers a CI refusal, a request that does not reach CI,
|
|
14
|
+
* and a value outside the Access Check contract, such as a count of answers
|
|
15
|
+
* other than the count of targets, as an `AiError`; an aborted check rejects
|
|
16
|
+
* with the reason of its signal.
|
|
17
|
+
*/
|
|
18
|
+
declare const createAccessPort: (client: AccessPortClient) => AccessCheckPort;
|
|
19
|
+
/** The web storage that keeps the values: `sessionStorage` or `localStorage`. */
|
|
20
|
+
type ChatSessionStorage = Pick<Storage, "getItem" | "setItem">;
|
|
21
|
+
type BrowserSessionStoreOptions = Readonly<{
|
|
22
|
+
/**
|
|
23
|
+
* The storage of the values; the default is the `sessionStorage` of the
|
|
24
|
+
* tab, so each tab keeps its own chat and its own pending waits.
|
|
25
|
+
*/
|
|
26
|
+
storage?: ChatSessionStorage;
|
|
27
|
+
}>;
|
|
28
|
+
declare const ChatSession: Schema.Struct<{
|
|
29
|
+
readonly conversationId: Schema.NullOr<Schema.String>;
|
|
30
|
+
}>;
|
|
31
|
+
declare const PendingIntentWaits: Schema.$Array<Schema.Struct<{
|
|
32
|
+
readonly displayName: Schema.String;
|
|
33
|
+
readonly fqn: Schema.String;
|
|
34
|
+
readonly handle: Schema.String;
|
|
35
|
+
}>>;
|
|
36
|
+
/** The open Conversation of a Place. */
|
|
37
|
+
type BrowserChatSession = typeof ChatSession.Type;
|
|
38
|
+
/** One pending wait of the AI Page Registry, by its Intent Handle. */
|
|
39
|
+
type BrowserPendingIntentWait = (typeof PendingIntentWaits.Type)[number];
|
|
40
|
+
/**
|
|
41
|
+
* The `SessionStorePort` of ai-react with each optional method: the
|
|
42
|
+
* Assistant Sidebar and the pending Intent waits survive a reload.
|
|
43
|
+
*/
|
|
44
|
+
interface BrowserSessionStore {
|
|
45
|
+
readonly read: (place: Place) => BrowserChatSession | undefined;
|
|
46
|
+
/** `undefined` when the storage keeps no value yet. */
|
|
47
|
+
readonly readAssistantSidebarOpen: () => boolean | undefined;
|
|
48
|
+
readonly readIntentWaits: () => readonly BrowserPendingIntentWait[];
|
|
49
|
+
readonly write: (place: Place, session: BrowserChatSession) => void;
|
|
50
|
+
readonly writeAssistantSidebarOpen: (open: boolean) => void;
|
|
51
|
+
/** Replaces the pending waits that the storage keeps. */
|
|
52
|
+
readonly writeIntentWaits: (waits: readonly BrowserPendingIntentWait[]) => void;
|
|
53
|
+
}
|
|
54
|
+
/** The browser `sessions` port of the shared chat; see the module. */
|
|
55
|
+
declare const createBrowserSessionStore: ({ storage }?: BrowserSessionStoreOptions) => BrowserSessionStore;
|
|
4
56
|
/** The organization client whose chat domain the transport calls. */
|
|
5
57
|
type ChatTransportClient = Pick<OrganizationClient<ClientOperationMap>, "chat">;
|
|
6
58
|
/**
|
|
@@ -12,4 +64,14 @@ type ChatTransportClient = Pick<OrganizationClient<ClientOperationMap>, "chat">;
|
|
|
12
64
|
* `followPresentation` of ai-core reconnects.
|
|
13
65
|
*/
|
|
14
66
|
declare const createChatTransport: (client: ChatTransportClient) => ChatTransport;
|
|
15
|
-
|
|
67
|
+
/** The organization client whose intents domain the transport calls. */
|
|
68
|
+
type IntentTransportClient = Pick<OrganizationClient<ClientOperationMap>, "intents">;
|
|
69
|
+
/**
|
|
70
|
+
* The `IntentTransport` of the Intent controls over `client.intents`. `wait`
|
|
71
|
+
* resolves at the end of the run: `client.intents.wait` repeats the bounded
|
|
72
|
+
* server wait. `call` answers a CI refusal, a request that does not reach
|
|
73
|
+
* CI, and a value outside the Intent contract as an `AiError`; an aborted
|
|
74
|
+
* call rejects with the reason of its signal.
|
|
75
|
+
*/
|
|
76
|
+
declare const createIntentTransport: (client: IntentTransportClient) => IntentTransport;
|
|
77
|
+
export { type AccessPortClient, type BrowserChatSession, type BrowserPendingIntentWait, type BrowserSessionStore, type BrowserSessionStoreOptions, type ChatSessionStorage, type ChatTransportClient, type IntentTransportClient, createAccessPort, createBrowserSessionStore, createChatTransport, createIntentTransport };
|
package/dist/chat.js
CHANGED
|
@@ -1,7 +1,125 @@
|
|
|
1
|
-
import { r as CiTransportError } from "./errors-
|
|
2
|
-
import
|
|
3
|
-
import * as Predicate from "effect/Predicate";
|
|
1
|
+
import { r as CiTransportError } from "./errors-DRzZfurr.js";
|
|
2
|
+
import * as Option from "effect/Option";
|
|
4
3
|
import * as Schema from "effect/Schema";
|
|
4
|
+
import * as Predicate from "effect/Predicate";
|
|
5
|
+
import { AiFailureError } from "@collective-intelligence/ai-core";
|
|
6
|
+
const aiErrorOf = ({ code, details, message, retryable }) => {
|
|
7
|
+
const reason = details?.["reason"];
|
|
8
|
+
return Predicate.isString(reason) ? {
|
|
9
|
+
code,
|
|
10
|
+
message,
|
|
11
|
+
reason,
|
|
12
|
+
retryable
|
|
13
|
+
} : {
|
|
14
|
+
code,
|
|
15
|
+
message,
|
|
16
|
+
retryable
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
const decodeResponse = Schema.decodeUnknownOption(Schema.Struct({
|
|
20
|
+
accessVersion: Schema.Int,
|
|
21
|
+
answers: Schema.Array(Schema.Literals(["allowed", "denied"]))
|
|
22
|
+
}));
|
|
23
|
+
const unreachable$2 = {
|
|
24
|
+
code: "unavailable",
|
|
25
|
+
message: "The Access Check could not reach Collective Intelligence",
|
|
26
|
+
retryable: true
|
|
27
|
+
};
|
|
28
|
+
const outsideContract$1 = {
|
|
29
|
+
code: "internal",
|
|
30
|
+
message: "Collective Intelligence answered a value outside the Access Check contract",
|
|
31
|
+
retryable: false
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* The `AccessCheckPort` of the Visibility Gate over `client.access`: one
|
|
35
|
+
* `check` sends one Access Check and answers in target order with the Access
|
|
36
|
+
* Version. `check` answers a CI refusal, a request that does not reach CI,
|
|
37
|
+
* and a value outside the Access Check contract, such as a count of answers
|
|
38
|
+
* other than the count of targets, as an `AiError`; an aborted check rejects
|
|
39
|
+
* with the reason of its signal.
|
|
40
|
+
*/
|
|
41
|
+
const createAccessPort = (client) => ({ check: async (targets, options) => {
|
|
42
|
+
try {
|
|
43
|
+
const answer = await client.access.check({ targets: [...targets] }, options);
|
|
44
|
+
if (!answer.ok) return {
|
|
45
|
+
error: aiErrorOf(answer.error),
|
|
46
|
+
ok: false
|
|
47
|
+
};
|
|
48
|
+
const value = decodeResponse(answer.value).pipe(Option.filter(({ answers }) => answers.length === targets.length));
|
|
49
|
+
return Option.isSome(value) ? {
|
|
50
|
+
ok: true,
|
|
51
|
+
value: value.value
|
|
52
|
+
} : {
|
|
53
|
+
error: outsideContract$1,
|
|
54
|
+
ok: false
|
|
55
|
+
};
|
|
56
|
+
} catch (error) {
|
|
57
|
+
if (Schema.is(CiTransportError)(error)) return {
|
|
58
|
+
error: unreachable$2,
|
|
59
|
+
ok: false
|
|
60
|
+
};
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
63
|
+
} });
|
|
64
|
+
const ChatSession = Schema.Struct({ conversationId: Schema.NullOr(Schema.String) });
|
|
65
|
+
const PendingIntentWaits = Schema.Array(Schema.Struct({
|
|
66
|
+
displayName: Schema.String,
|
|
67
|
+
fqn: Schema.String,
|
|
68
|
+
handle: Schema.String
|
|
69
|
+
}));
|
|
70
|
+
const keyPrefix = "ci.chat.";
|
|
71
|
+
/**
|
|
72
|
+
* One stored JSON value of `schema`. A value that is missing, that is not
|
|
73
|
+
* JSON or that has another shape reads as `None`. A storage that refuses,
|
|
74
|
+
* such as a sandboxed frame, a full quota or a server render without
|
|
75
|
+
* `sessionStorage`, reads `None` and drops the write, so that the chat keeps
|
|
76
|
+
* working without the stored value.
|
|
77
|
+
*/
|
|
78
|
+
const storedValue = (schema) => {
|
|
79
|
+
const json = Schema.fromJsonString(schema);
|
|
80
|
+
const decode = Schema.decodeOption(json);
|
|
81
|
+
const encode = Schema.encodeOption(json);
|
|
82
|
+
return {
|
|
83
|
+
read: (storage, key) => {
|
|
84
|
+
try {
|
|
85
|
+
const text = storage().getItem(key);
|
|
86
|
+
return text === null ? Option.none() : decode(text);
|
|
87
|
+
} catch {
|
|
88
|
+
return Option.none();
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
write: (storage, key, value) => {
|
|
92
|
+
const text = encode(value);
|
|
93
|
+
try {
|
|
94
|
+
if (Option.isSome(text)) storage().setItem(key, text.value);
|
|
95
|
+
} catch {}
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
};
|
|
99
|
+
const conversation = storedValue(ChatSession);
|
|
100
|
+
const intentWaits = storedValue(PendingIntentWaits);
|
|
101
|
+
const sidebarOpen = storedValue(Schema.Boolean);
|
|
102
|
+
const conversationKey = ({ id, kind }) => `${keyPrefix}conversation:${kind}:${id}`;
|
|
103
|
+
const intentWaitsKey = `${keyPrefix}intentWaits`;
|
|
104
|
+
const sidebarOpenKey = `${keyPrefix}assistantSidebarOpen`;
|
|
105
|
+
/** The browser `sessions` port of the shared chat; see the module. */
|
|
106
|
+
const createBrowserSessionStore = ({ storage } = {}) => {
|
|
107
|
+
const target = () => storage ?? globalThis.sessionStorage;
|
|
108
|
+
return {
|
|
109
|
+
read: (place) => Option.getOrUndefined(conversation.read(target, conversationKey(place))),
|
|
110
|
+
readAssistantSidebarOpen: () => Option.getOrUndefined(sidebarOpen.read(target, sidebarOpenKey)),
|
|
111
|
+
readIntentWaits: () => Option.getOrElse(intentWaits.read(target, intentWaitsKey), () => []),
|
|
112
|
+
write: (place, { conversationId }) => {
|
|
113
|
+
conversation.write(target, conversationKey(place), { conversationId });
|
|
114
|
+
},
|
|
115
|
+
writeAssistantSidebarOpen: (open) => {
|
|
116
|
+
sidebarOpen.write(target, sidebarOpenKey, open);
|
|
117
|
+
},
|
|
118
|
+
writeIntentWaits: (waits) => {
|
|
119
|
+
intentWaits.write(target, intentWaitsKey, waits);
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
};
|
|
5
123
|
const chatCalls = {
|
|
6
124
|
clearAnswerFeedback: (chat, input, options) => chat.feedback.clear(input, options),
|
|
7
125
|
compactConversation: (chat, input, options) => chat.compaction.compact(input, options),
|
|
@@ -51,21 +169,7 @@ const chatCalls = {
|
|
|
51
169
|
uploadProjectFile: (chat, input, options) => chat.projects.uploadFile(input, options),
|
|
52
170
|
upsertAnswerFeedback: (chat, input, options) => chat.feedback.upsert(input, options)
|
|
53
171
|
};
|
|
54
|
-
|
|
55
|
-
const aiErrorOf = ({ code, details, message, retryable }) => {
|
|
56
|
-
const reason = details?.["reason"];
|
|
57
|
-
return Predicate.isString(reason) ? {
|
|
58
|
-
code,
|
|
59
|
-
message,
|
|
60
|
-
reason,
|
|
61
|
-
retryable
|
|
62
|
-
} : {
|
|
63
|
-
code,
|
|
64
|
-
message,
|
|
65
|
-
retryable
|
|
66
|
-
};
|
|
67
|
-
};
|
|
68
|
-
const unreachable = {
|
|
172
|
+
const unreachable$1 = {
|
|
69
173
|
code: "unavailable",
|
|
70
174
|
message: "The chat could not reach Collective Intelligence",
|
|
71
175
|
retryable: true
|
|
@@ -92,7 +196,7 @@ const createChatTransport = (client) => ({
|
|
|
92
196
|
};
|
|
93
197
|
} catch (error) {
|
|
94
198
|
if (Schema.is(CiTransportError)(error)) return {
|
|
95
|
-
error: unreachable,
|
|
199
|
+
error: unreachable$1,
|
|
96
200
|
ok: false
|
|
97
201
|
};
|
|
98
202
|
throw error;
|
|
@@ -107,4 +211,104 @@ const createChatTransport = (client) => ({
|
|
|
107
211
|
for await (const frame of opened.value) yield JSON.parse(frame.data);
|
|
108
212
|
}
|
|
109
213
|
});
|
|
110
|
-
|
|
214
|
+
const Completed = Schema.Struct({
|
|
215
|
+
kind: Schema.Literal("completed"),
|
|
216
|
+
result: Schema.Json
|
|
217
|
+
});
|
|
218
|
+
const Failed = Schema.Struct({
|
|
219
|
+
kind: Schema.Literal("failed"),
|
|
220
|
+
reason: Schema.String
|
|
221
|
+
});
|
|
222
|
+
const CatalogEntry = Schema.Struct({
|
|
223
|
+
description: Schema.String,
|
|
224
|
+
displayName: Schema.String,
|
|
225
|
+
fqn: Schema.String,
|
|
226
|
+
inputSchema: Schema.JsonObject,
|
|
227
|
+
outputSchema: Schema.JsonObject,
|
|
228
|
+
resultMode: Schema.Literals(["async", "sync"])
|
|
229
|
+
});
|
|
230
|
+
const decodeCatalog = Schema.decodeUnknownOption(Schema.Array(CatalogEntry));
|
|
231
|
+
const decodeOutcome = Schema.decodeUnknownOption(Schema.Union([
|
|
232
|
+
Completed,
|
|
233
|
+
Schema.Struct({
|
|
234
|
+
handle: Schema.String,
|
|
235
|
+
kind: Schema.Literal("started")
|
|
236
|
+
}),
|
|
237
|
+
Schema.Struct({
|
|
238
|
+
fields: Schema.Array(Schema.Struct({
|
|
239
|
+
path: Schema.String,
|
|
240
|
+
problem: Schema.Literals(["invalid", "missing"]),
|
|
241
|
+
reason: Schema.String
|
|
242
|
+
})),
|
|
243
|
+
kind: Schema.Literal("needs_input")
|
|
244
|
+
}),
|
|
245
|
+
Schema.Struct({ kind: Schema.Literal("not_allowed") }),
|
|
246
|
+
Failed
|
|
247
|
+
]));
|
|
248
|
+
const decodeState = Schema.decodeUnknownOption(Schema.Union([
|
|
249
|
+
Schema.Struct({ kind: Schema.Literal("starting") }),
|
|
250
|
+
Schema.Struct({ kind: Schema.Literal("running") }),
|
|
251
|
+
Completed,
|
|
252
|
+
Failed
|
|
253
|
+
]));
|
|
254
|
+
const decodeEnd = Schema.decodeUnknownOption(Schema.Union([Completed, Failed]));
|
|
255
|
+
const intentCalls = {
|
|
256
|
+
dispatch: {
|
|
257
|
+
call: (intents, input, options) => intents.dispatch(input, options),
|
|
258
|
+
read: decodeOutcome
|
|
259
|
+
},
|
|
260
|
+
list: {
|
|
261
|
+
call: (intents, _input, options) => intents.list({}, options),
|
|
262
|
+
read: ({ intents }) => decodeCatalog(intents)
|
|
263
|
+
},
|
|
264
|
+
read: {
|
|
265
|
+
call: (intents, input, options) => intents.get(input, options),
|
|
266
|
+
read: decodeState
|
|
267
|
+
},
|
|
268
|
+
wait: {
|
|
269
|
+
call: (intents, input, options) => intents.wait(input, options),
|
|
270
|
+
read: decodeEnd
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
const unreachable = {
|
|
274
|
+
code: "unavailable",
|
|
275
|
+
message: "The Intent request could not reach Collective Intelligence",
|
|
276
|
+
retryable: true
|
|
277
|
+
};
|
|
278
|
+
const outsideContract = {
|
|
279
|
+
code: "internal",
|
|
280
|
+
message: "Collective Intelligence answered a value outside the Intent contract",
|
|
281
|
+
retryable: false
|
|
282
|
+
};
|
|
283
|
+
/**
|
|
284
|
+
* The `IntentTransport` of the Intent controls over `client.intents`. `wait`
|
|
285
|
+
* resolves at the end of the run: `client.intents.wait` repeats the bounded
|
|
286
|
+
* server wait. `call` answers a CI refusal, a request that does not reach
|
|
287
|
+
* CI, and a value outside the Intent contract as an `AiError`; an aborted
|
|
288
|
+
* call rejects with the reason of its signal.
|
|
289
|
+
*/
|
|
290
|
+
const createIntentTransport = (client) => ({ call: async (op, input, options) => {
|
|
291
|
+
const { call, read } = intentCalls[op];
|
|
292
|
+
try {
|
|
293
|
+
const answer = await call(client.intents, input, options);
|
|
294
|
+
if (!answer.ok) return {
|
|
295
|
+
error: aiErrorOf(answer.error),
|
|
296
|
+
ok: false
|
|
297
|
+
};
|
|
298
|
+
const value = read(answer.value);
|
|
299
|
+
return Option.isSome(value) ? {
|
|
300
|
+
ok: true,
|
|
301
|
+
value: value.value
|
|
302
|
+
} : {
|
|
303
|
+
error: outsideContract,
|
|
304
|
+
ok: false
|
|
305
|
+
};
|
|
306
|
+
} catch (error) {
|
|
307
|
+
if (Schema.is(CiTransportError)(error)) return {
|
|
308
|
+
error: unreachable,
|
|
309
|
+
ok: false
|
|
310
|
+
};
|
|
311
|
+
throw error;
|
|
312
|
+
}
|
|
313
|
+
} });
|
|
314
|
+
export { createAccessPort, createBrowserSessionStore, createChatTransport, createIntentTransport };
|