@collective-intelligence/external-apps-client-sdk-react 0.8.0 → 0.9.1
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 +9 -3
- package/README.md +47 -12
- package/dist/effect.d.ts +60 -11
- package/dist/effect.js +1 -1
- package/dist/index-ktw8msmm.js +2 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -1
- package/dist/realtime.d.ts +41 -0
- package/dist/realtime.js +2 -0
- package/docs/effect.md +83 -15
- package/docs/guide/ai/index.md +4 -2
- package/docs/guide/ai/studio.md +1 -1
- package/docs/realtime.md +10 -2
- package/package.json +12 -6
package/AGENTS.md
CHANGED
|
@@ -8,8 +8,11 @@ holds the full API.
|
|
|
8
8
|
|
|
9
9
|
## Rules
|
|
10
10
|
|
|
11
|
-
- Import entity hooks and views from `/resources`,
|
|
12
|
-
(`fromEffect`, `EffectRuntimeProvider`, `QueryCache`) from `/effect
|
|
11
|
+
- Import entity hooks and views from `/resources`, the Effect bridge
|
|
12
|
+
(`fromEffect`, `EffectRuntimeProvider`, `QueryCache`) from `/effect`, and
|
|
13
|
+
the realtime bindings (`RealtimeProvider`, `useRealtimeTopic`,
|
|
14
|
+
`useRealtimeClient`) from `/realtime`. The root holds them too, but it
|
|
15
|
+
bundles the sign-in, agent prompt and entity UI with them.
|
|
13
16
|
- Install the peers once in the app: `react`, `react-dom`,
|
|
14
17
|
`@tanstack/react-query`, `xstate`, `effect` (`^4.1.0`) and
|
|
15
18
|
`@collective-intelligence/ui-react`.
|
|
@@ -22,7 +25,10 @@ holds the full API.
|
|
|
22
25
|
in `QueryCache`, never in machine context. After a write, refresh reads with
|
|
23
26
|
`QueryCache` (`invalidate`, `setData`, `update`, `remove`); do not put the
|
|
24
27
|
QueryClient in machine input. An optimistic write of one key uses
|
|
25
|
-
`QueryCache.optimisticUpdate`;
|
|
28
|
+
`QueryCache.optimisticUpdate`; build its payload in a `write` function,
|
|
29
|
+
which gets the confirmed value when CI gets the write, and give CI's answer
|
|
30
|
+
to `confirm`. Its edit must give the same value for a value that already
|
|
31
|
+
holds it, as a fetch can end under it. A write of several keys calls `cancel` on
|
|
26
32
|
them before `update`, and `invalidate` when the write settles. A view
|
|
27
33
|
renders: it calls no `fetch` and runs no Effect.
|
|
28
34
|
- Give a single action of a view, such as a download or a share, an
|
package/README.md
CHANGED
|
@@ -11,7 +11,8 @@ Install these required peer dependencies in the application: `react`, `react-dom
|
|
|
11
11
|
`@tanstack/react-query`, `xstate`, `effect` and `@collective-intelligence/ui-react`. The package
|
|
12
12
|
depends on `@collective-intelligence/external-apps-client-sdk` as a normal dependency. The packed
|
|
13
13
|
JavaScript bundles none of these packages, so the application holds one copy of each. The `./effect` entry
|
|
14
|
-
holds the [Effect bridge](#effect-bridge) for XState machines.
|
|
14
|
+
holds the [Effect bridge](#effect-bridge) for XState machines. The `./realtime` entry holds the
|
|
15
|
+
[realtime bindings](#realtime-topics) without the sign-in, agent prompt and entity UI.
|
|
15
16
|
|
|
16
17
|
Configure the provider's `entitySource` once, alongside its existing Promise `client`. `EntitySource`
|
|
17
18
|
exposes a stable `getSnapshot`, a `subscribe` function, and a typed `bind(contract)` function returning
|
|
@@ -235,6 +236,20 @@ Drafts and operation keys never enter the URL.
|
|
|
235
236
|
|
|
236
237
|
## Realtime topics
|
|
237
238
|
|
|
239
|
+
Import `RealtimeProvider`, `useRealtimeTopic` and `useRealtimeClient` from `./realtime`. The root
|
|
240
|
+
entry exports them too, but it also holds the sign-in, agent prompt and entity UI and imports the
|
|
241
|
+
ui-react code that they use. A Next.js Server Component that renders `RealtimeProvider` makes its
|
|
242
|
+
entry a client reference, and the page's client bundle keeps the whole entry: about 660 KB minified
|
|
243
|
+
through the root, ui-react included, and about 2 KB through `./realtime` (the client SDK and the
|
|
244
|
+
peers not counted).
|
|
245
|
+
|
|
246
|
+
```ts
|
|
247
|
+
import {
|
|
248
|
+
RealtimeProvider,
|
|
249
|
+
useRealtimeTopic
|
|
250
|
+
} from "@collective-intelligence/external-apps-client-sdk-react/realtime"
|
|
251
|
+
```
|
|
252
|
+
|
|
238
253
|
`RealtimeProvider` takes the options of `createRealtimeClient` as props. It
|
|
239
254
|
creates one client, and so one connection, for its tree, and closes it when the
|
|
240
255
|
tree unmounts. Its effects and the hooks below it hold the client by reference
|
|
@@ -251,15 +266,25 @@ delivery per tab, 250 to 1000 ms after the first pending change, with the
|
|
|
251
266
|
latest change of each record.
|
|
252
267
|
|
|
253
268
|
Pass `onReset` and refetch every realtime-driven query in it. The client calls
|
|
254
|
-
it when the server cannot replay a gap
|
|
255
|
-
|
|
256
|
-
|
|
269
|
+
it with a reason: `"gap"` when the server cannot replay a gap, `"server"` at a
|
|
270
|
+
delete the server cannot name, and `"initial"` after a stream opens without a
|
|
271
|
+
last event id unless the server confirms with `resumed` that it replays the
|
|
272
|
+
changes since the page started. A current server confirms it only when it
|
|
273
|
+
can show that nothing is missed (the client SDK README lists the first opens
|
|
274
|
+
that still resync), so most page loads need no refetch. The page
|
|
275
|
+
starts at `startedAt`, by default `performance.timeOrigin`, which also covers
|
|
276
|
+
a server render of the navigation; a page that shows cached data read
|
|
277
|
+
earlier passes `performance.timeOrigin - ageMs`, with `ageMs` the age of that
|
|
278
|
+
data when the server sent it. Without `onReset` the client cannot recover
|
|
279
|
+
from such a gap, so a change can be lost. The client
|
|
257
280
|
calls `onAccessChanged` when the user's access changes, and `onRefused` once
|
|
258
281
|
when the server refuses the realtime link with 401 or 403 and the connection
|
|
259
282
|
stops. They stay callbacks of the application; the client calls the ones of the latest render, also when a
|
|
260
283
|
render adds or removes one. Only a client with `onReset` resyncs, so a render
|
|
261
284
|
that adds or removes `onReset` replaces the client and its stream. The new
|
|
262
|
-
stream opens without a last event id
|
|
285
|
+
stream opens without a last event id and asks for the changes since
|
|
286
|
+
`startedAt`, so with `onReset` it resyncs once only when the server does not
|
|
287
|
+
confirm that replay.
|
|
263
288
|
|
|
264
289
|
```tsx
|
|
265
290
|
const AppRealtime = ({ children }: { children: ReactNode }) => {
|
|
@@ -335,13 +360,23 @@ the shared chat run one copy of the bridge.
|
|
|
335
360
|
`cancel(queryKey)` cancels the running fetches and interrupts their
|
|
336
361
|
queries, so they write no value; it keeps the cached values and starts no
|
|
337
362
|
fetch.
|
|
338
|
-
`optimisticUpdate(queryKey, edit, write)` is an optimistic write
|
|
339
|
-
key: it
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
363
|
+
`optimisticUpdate(queryKey, edit, write, options?)` is an optimistic write
|
|
364
|
+
of one key: it runs `write` and gives its result. Each pending write of the
|
|
365
|
+
key is a layer of its `edit` over the confirmed value, and views show the
|
|
366
|
+
layers in call order at once. The writes to one key, of every `QueryCache`
|
|
367
|
+
over the same QueryClient, go to CI one at a time in call order; when CI
|
|
368
|
+
gets one, the running fetch of the key is cancelled, and a `write`
|
|
369
|
+
function gets `{ confirmed, optimistic }` of that moment, so a refused
|
|
370
|
+
write before it is not in its payload. A fetch that ends while writes are
|
|
371
|
+
pending updates the confirmed value, and the layers show over it again.
|
|
372
|
+
When CI confirms the write, the confirmed value becomes
|
|
373
|
+
`options.confirm(result, confirmed)` or gets the edit; when `write` fails,
|
|
374
|
+
is interrupted or dies, only its own layer goes. A value that `setData`,
|
|
375
|
+
`update` or `remove` puts meanwhile stays, and the `confirm` of the writes
|
|
376
|
+
before it does not run. Each run of the effect is one write. The key is invalidated
|
|
377
|
+
when `write` ends, also when `confirm` throws. The QueryClient holds the
|
|
378
|
+
writes, so two bundled copies of the SDK over it share them. `pending(queryKey)` gives the number of optimistic
|
|
379
|
+
writes of the key that wait or run.
|
|
345
380
|
`setData(queryKey, value)` writes a value that views show at once.
|
|
346
381
|
`update(queryKey, (current) => next)` replaces each cached value with the
|
|
347
382
|
result of the function for its current value, without a refetch, for
|
package/dist/effect.d.ts
CHANGED
|
@@ -16,6 +16,32 @@ export type QueryCacheFetchOptions<Data> = Readonly<{
|
|
|
16
16
|
/** Milliseconds for which a cached value stays fresh; without it, the QueryClient default applies. */
|
|
17
17
|
staleTime?: number;
|
|
18
18
|
}>;
|
|
19
|
+
/** The values of the entry of a key when CI gets its optimistic write. */
|
|
20
|
+
export type QueryCacheWriteValues<Data> = Readonly<{
|
|
21
|
+
/**
|
|
22
|
+
* CI's value of the key: the value of the last fetch with the answers of
|
|
23
|
+
* the writes before this one, without any pending edit. `undefined` when
|
|
24
|
+
* the entry has no value.
|
|
25
|
+
*/
|
|
26
|
+
confirmed: Data | undefined;
|
|
27
|
+
/**
|
|
28
|
+
* `confirmed` with the edit of this write only, so a refused write before
|
|
29
|
+
* it is not in it. `undefined` when the entry has no value.
|
|
30
|
+
*/
|
|
31
|
+
optimistic: Data | undefined;
|
|
32
|
+
}>;
|
|
33
|
+
export type QueryCacheOptimisticOptions<Data, A> = Readonly<{
|
|
34
|
+
/**
|
|
35
|
+
* The confirmed value after CI confirms the write with `result`, for
|
|
36
|
+
* example CI's row with its new revision in `confirmed`. Without it, or
|
|
37
|
+
* when it gives `undefined`, the confirmed value gets the edit. It does not
|
|
38
|
+
* run when `setData`, `update` or `remove` replaced the value of the key
|
|
39
|
+
* after the edit: the newer value stays. When it throws, the write dies
|
|
40
|
+
* with its error, and the key still shows its other layers and is
|
|
41
|
+
* invalidated.
|
|
42
|
+
*/
|
|
43
|
+
confirm?: (result: A, confirmed: Data | undefined) => Data | undefined;
|
|
44
|
+
}>;
|
|
19
45
|
declare const QueryCache_base: Context.ServiceClass<QueryCache, "@collective-intelligence/external-apps-client-sdk-react/QueryCache", Readonly<{
|
|
20
46
|
/**
|
|
21
47
|
* The fresh cached value of `queryKey`, or the value of one run of `query`,
|
|
@@ -58,18 +84,41 @@ declare const QueryCache_base: Context.ServiceClass<QueryCache, "@collective-int
|
|
|
58
84
|
remove: (queryKey: QueryKey) => Effect.Effect<void>;
|
|
59
85
|
/**
|
|
60
86
|
* Runs `write`, the remote write of an optimistic edit of the entry of
|
|
61
|
-
* `queryKey`, and gives its result.
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
87
|
+
* `queryKey`, and gives its result. Each pending write of a key is a layer
|
|
88
|
+
* of its edit over the confirmed value, CI's value of the key, and views
|
|
89
|
+
* show the layers in call order at once; an entry without a value shows no
|
|
90
|
+
* edit until a fetch gives it one. The writes to one key, of every
|
|
91
|
+
* `QueryCache` over the same `QueryClient`, go to CI one at a time in call
|
|
92
|
+
* order; writes to other keys, also keys below `queryKey`, do not wait.
|
|
93
|
+
* The `QueryClient` holds these writes, so each bundled copy of the SDK
|
|
94
|
+
* over it shares them. Each run of the returned effect is one write, so an
|
|
95
|
+
* effect that runs twice writes twice.
|
|
96
|
+
*
|
|
97
|
+
* When CI gets the write, the running fetch of the key is cancelled, and a
|
|
98
|
+
* `write` function is called with the `QueryCacheWriteValues` of that
|
|
99
|
+
* moment: the confirmed value with the answers of the writes before it,
|
|
100
|
+
* and that value with this edit only. A fetch that ends while writes are
|
|
101
|
+
* pending updates the confirmed value, and the edits show over it again,
|
|
102
|
+
* so each edit must give the same value for a value that already holds
|
|
103
|
+
* it, for example set fields or replace a row by its id.
|
|
104
|
+
*
|
|
105
|
+
* When CI confirms the write, its layer goes, and the confirmed value
|
|
106
|
+
* becomes `options.confirm(result, confirmed)` or gets the edit. When
|
|
107
|
+
* `write` fails, is interrupted or dies, only its own layer goes: the
|
|
108
|
+
* other layers show over the confirmed value. A value that `setData`,
|
|
109
|
+
* `update` or `remove` puts while writes are pending stays: the edits
|
|
110
|
+
* before it no longer show or roll back, and CI's answer to them does not
|
|
111
|
+
* change the value. When the write ends, the key is invalidated, and its
|
|
112
|
+
* views read it again. The key is the entry that `getQueryData` finds,
|
|
113
|
+
* also with a `queryKeyHashFn` of the `QueryClient`.
|
|
114
|
+
*/
|
|
115
|
+
optimisticUpdate: <Data, A, E, R>(queryKey: QueryKey, edit: (current: Data) => Data, write: Effect.Effect<A, E, R> | ((values: QueryCacheWriteValues<Data>) => Effect.Effect<A, E, R>), options?: QueryCacheOptimisticOptions<Data, A>) => Effect.Effect<A, E, R>;
|
|
116
|
+
/**
|
|
117
|
+
* The number of optimistic writes of `queryKey` that wait for CI or run,
|
|
118
|
+
* of every `QueryCache` over the same `QueryClient`, also of another
|
|
119
|
+
* bundled copy of the SDK. Keys below `queryKey` do not count.
|
|
71
120
|
*/
|
|
72
|
-
|
|
121
|
+
pending: (queryKey: QueryKey) => Effect.Effect<number>;
|
|
73
122
|
}>>;
|
|
74
123
|
/**
|
|
75
124
|
* The remote data of the app's `QueryClient`, as machine actors read and
|
package/dist/effect.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{effectTask,fromEffect}from"@collective-intelligence/effect-xstate/actors";import{CiError,CiTransportError}from"@collective-intelligence/external-apps-client-sdk/effect";import{
|
|
2
|
+
import{effectTask,fromEffect}from"@collective-intelligence/effect-xstate/actors";import{CiError,CiTransportError}from"@collective-intelligence/external-apps-client-sdk/effect";import{isCancelledError,QueryObserver}from"@tanstack/react-query";import*as Context from"effect/Context";import*as Effect from"effect/Effect";import*as Exit from"effect/Exit";import{constVoid}from"effect/Function";import*as Layer from"effect/Layer";import*as Schema from"effect/Schema";class QueryCache extends Context.Service()("@collective-intelligence/external-apps-client-sdk-react/QueryCache"){}var writesKey=Symbol.for("@collective-intelligence/query-cache/optimistic-writes/v1");var writesOf=(queryClient)=>queryClient[writesKey];var hashIn=(queryClient,queryKey)=>queryClient.defaultQueryOptions({queryKey}).queryHash;var supersede=(key)=>{for(const layer of key.layers){layer.shown=false}};var show=(queryClient,key)=>{if(key.confirmed===undefined){return}let shown=key.confirmed;for(const layer of key.layers){if(layer.shown){shown=layer.apply(shown)}}key.showing=true;try{queryClient.setQueryData(key.queryKey,shown)}finally{key.showing=false}};var keepLayers=(queryClient,keys)=>(event)=>{const key=keys.get(event.query.queryHash);if(key===undefined||key.showing){return}if(event.type==="removed"){key.confirmed=undefined;supersede(key);return}if(event.type!=="updated"){return}const{action}=event;if(action.type==="success"){key.confirmed=event.query.state.data;if(action.manual===true){supersede(key)}else{show(queryClient,key)}}else if(action.type==="setState"){if(event.query.state.data===undefined){key.confirmed=undefined;supersede(key)}else{show(queryClient,key)}}};var listen=(queryClient)=>{const keys=new Map;const client={keys,stop:queryClient.getQueryCache().subscribe(keepLayers(queryClient,keys))};Object.defineProperty(queryClient,writesKey,{configurable:true,value:client});return client};var dropLayer=(key,layer)=>{const index=key.layers.indexOf(layer);if(index===-1){return false}key.layers.splice(index,1);return true};var wakeFirst=(key)=>{key.layers[0]?.wake?.()};var turnOf=(key,layer)=>Effect.callback((resume)=>{if(key.layers[0]===layer){resume(Effect.undefined);return}layer.wake=()=>{layer.wake=undefined;resume(Effect.undefined)};return Effect.sync(()=>{layer.wake=undefined})});var forgetIfDone=(queryClient,key)=>{const client=writesOf(queryClient);if(key.layers.length>0||client?.keys.get(key.hash)!==key){return}client.keys.delete(key.hash);if(client.keys.size===0){client.stop();Reflect.deleteProperty(queryClient,writesKey)}};var addLayer=(queryClient,queryKey,layer)=>{const client=writesOf(queryClient)??listen(queryClient);const hash=hashIn(queryClient,queryKey);const key=client.keys.get(hash)??{confirmed:queryClient.getQueryData(queryKey),hash,layers:[],queryKey,showing:false};client.keys.set(hash,key);key.layers.push(layer);try{show(queryClient,key)}catch(error){dropLayer(key,layer);forgetIfDone(queryClient,key);throw error}return key};var make=(queryClient)=>{const fetchExit=async({query,...options},context)=>{try{return Exit.succeed(await queryClient.fetchQuery({...options,queryFn:({signal})=>Effect.runPromiseWith(context)(query,{signal}),retry:false}))}catch(error){if(isCancelledError(error)){return Exit.interrupt()}return Schema.is(CiError)(error)||Schema.is(CiTransportError)(error)?Exit.fail(error):Exit.die(error)}};const waitOn=(queryKey)=>Effect.sync(()=>new QueryObserver(queryClient,{enabled:false,queryKey}).subscribe(constVoid));return QueryCache.of({cancel:(queryKey)=>Effect.promise(()=>queryClient.cancelQueries({queryKey})),fetch:(options)=>Effect.flatMap(Effect.context(),(context)=>Effect.acquireUseRelease(waitOn(options.queryKey),()=>Effect.flatten(Effect.promise(()=>fetchExit(options,context))),(stopWaiting)=>Effect.sync(stopWaiting))),invalidate:(queryKey)=>Effect.promise(()=>queryClient.invalidateQueries({queryKey})),optimisticUpdate:(queryKey,edit,write,options)=>Effect.suspend(()=>{const layer={apply:edit,confirm:(confirmed,result)=>{if(!layer.shown){return confirmed}const answered=options?.confirm?.(result,confirmed);if(answered!==undefined){return answered}return confirmed===undefined?undefined:edit(confirmed)},send:(confirmed)=>Effect.isEffect(write)?write:write({confirmed,optimistic:confirmed===undefined?undefined:edit(confirmed)}),shown:true,wake:undefined};const keyLayer=layer;const settle=(key,exit)=>Effect.sync(()=>{dropLayer(key,keyLayer);const before=key.confirmed;try{if(Exit.isSuccess(exit)){key.confirmed=keyLayer.confirm(key.confirmed,exit.value)}}finally{if(layer.shown||key.confirmed!==before){show(queryClient,key)}queryClient.invalidateQueries({exact:true,queryKey})}});return Effect.acquireUseRelease(Effect.sync(()=>addLayer(queryClient,queryKey,keyLayer)),(key)=>turnOf(key,keyLayer).pipe(Effect.andThen(Effect.promise(()=>queryClient.cancelQueries({exact:true,queryKey})).pipe(Effect.andThen(Effect.suspend(()=>keyLayer.send(key.confirmed))),Effect.onExit((exit)=>settle(key,exit))))),(key)=>Effect.sync(()=>{if(dropLayer(key,keyLayer)&&layer.shown){show(queryClient,key)}wakeFirst(key);forgetIfDone(queryClient,key)}))}),pending:(queryKey)=>Effect.sync(()=>writesOf(queryClient)?.keys.get(hashIn(queryClient,queryKey))?.layers.length??0),remove:(queryKey)=>Effect.sync(()=>{queryClient.removeQueries({queryKey})}),setData:(queryKey,data)=>Effect.sync(()=>{queryClient.setQueryData(queryKey,data)}),update:(queryKey,updater)=>Effect.sync(()=>{queryClient.setQueriesData({queryKey},updater)})})};var layer=(queryClient)=>Layer.succeed(QueryCache,make(queryClient));import{QueryClient}from"@tanstack/react-query";import*as Effect2 from"effect/Effect";import*as Layer2 from"effect/Layer";var makeTestQueryCache=(options={})=>{const queryClient=options.queryClient??new QueryClient({defaultOptions:{queries:{gcTime:Infinity}}});for(const[queryKey,data]of options.seed??[]){queryClient.setQueryData(queryKey,data)}const real=make(queryClient);const overrides=options.overrides??{};const calls=[];const logged=(member,queryKey,run)=>Effect2.suspend(()=>{calls.push({member,queryKey});return run()});return{calls,layer:Layer2.succeed(QueryCache,QueryCache.of({cancel:(queryKey)=>logged("cancel",queryKey,()=>(overrides.cancel??real.cancel)(queryKey)),fetch:(fetchOptions)=>logged("fetch",fetchOptions.queryKey,()=>(overrides.fetch??real.fetch)(fetchOptions)),invalidate:(queryKey)=>logged("invalidate",queryKey,()=>(overrides.invalidate??real.invalidate)(queryKey)),optimisticUpdate:(queryKey,edit,write,writeOptions)=>logged("optimisticUpdate",queryKey,()=>(overrides.optimisticUpdate??real.optimisticUpdate)(queryKey,edit,write,writeOptions)),pending:(queryKey)=>logged("pending",queryKey,()=>(overrides.pending??real.pending)(queryKey)),remove:(queryKey)=>logged("remove",queryKey,()=>(overrides.remove??real.remove)(queryKey)),setData:(queryKey,data)=>logged("setData",queryKey,()=>(overrides.setData??real.setData)(queryKey,data)),update:(queryKey,updater)=>logged("update",queryKey,()=>(overrides.update??real.update)(queryKey,updater))})),queryClient}};import{EffectRuntimeProvider as BridgeRuntimeProvider,makeEffectRuntimeContext,useEffectRuntime as useBridgeRuntime}from"@collective-intelligence/effect-xstate/react";import{useQueryClient}from"@tanstack/react-query";import*as ManagedRuntime from"effect/ManagedRuntime";import{useMemo}from"react";import{jsx}from"react/jsx-runtime";var RuntimeContext=makeEffectRuntimeContext();var EffectRuntimeProvider=({children})=>{const queryClient=useQueryClient();const runtime=useMemo(()=>ManagedRuntime.make(layer(queryClient)),[queryClient]);return jsx(BridgeRuntimeProvider,{context:RuntimeContext,runtime,children})};var useEffectRuntime=()=>useBridgeRuntime(RuntimeContext);export{EffectRuntimeProvider,QueryCache,effectTask,fromEffect,makeTestQueryCache,useEffectRuntime};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRealtimeClient}from"@collective-intelligence/external-apps-client-sdk";import{createContext,useContext,useEffect,useState}from"react";import{jsx}from"react/jsx-runtime";var idle={connections:0,lastEventId:undefined,status:"idle",topics:[]};var hasOnReset=(options)=>options.onReset!==undefined;var shareClient=(initial)=>{let options=initial;let shared={status:"none"};const subscriptions=new Set;const create=()=>createRealtimeClient({document:globalThis.document,window:globalThis.window,...options,onAccessChanged:()=>options.onAccessChanged?.(),onRefused:()=>options.onRefused?.(),...hasOnReset(options)&&{onReset:(reason)=>options.onReset?.(reason)}});const acquire=()=>{const client=shared.status==="none"?create():shared.client;shared={client,holders:shared.status==="held"?shared.holders+1:1,status:"held"};return client};const release=()=>{if(shared.status!=="held"){return}if(shared.holders>1){shared={...shared,holders:shared.holders-1};return}shared={client:shared.client,status:"releasing"};queueMicrotask(()=>{if(shared.status==="releasing"){shared.client.close();shared={status:"none"}}})};const subscribe=(topic,onChanges)=>{const subscription={onChanges,topic,unsubscribe:acquire().subscribe(topic,onChanges)};subscriptions.add(subscription);return()=>{if(subscriptions.delete(subscription)){subscription.unsubscribe();release()}}};return{acquire,getState:()=>shared.status==="none"?idle:shared.client.getState(),release,subscribe,update:(next)=>{const previous=options;options=next;if(shared.status==="none"||hasOnReset(next)===hasOnReset(previous)){return}for(const subscription of subscriptions){subscription.unsubscribe()}shared.client.close();const client=create();shared={...shared,client};for(const subscription of subscriptions){subscription.unsubscribe=client.subscribe(subscription.topic,subscription.onChanges)}}}};var RealtimeContext=createContext(null);var RealtimeProvider2=({children,...options})=>{const[shared]=useState(()=>shareClient(options));useEffect(()=>{shared.update(options)});useEffect(()=>{shared.acquire();return shared.release},[shared]);return jsx(RealtimeContext.Provider,{value:shared,children})};var useRealtimeClient2=()=>{const client=useContext(RealtimeContext);if(client===null){throw new Error("useRealtimeClient requires a RealtimeProvider")}return client};import{realtimeTopicKey}from"@collective-intelligence/external-apps-client-sdk";import{useEffect as useEffect2,useRef,useState as useState2}from"react";var useRealtimeTopic2=(topic,onChanges)=>{const client=useRealtimeClient2();const latest=useRef(onChanges);const key=topic===null?null:realtimeTopicKey(topic);const[subscribed,setSubscribed]=useState2({key,topic});if(subscribed.key!==key){setSubscribed({key,topic})}useEffect2(()=>{latest.current=onChanges});useEffect2(()=>subscribed.topic===null?undefined:client.subscribe(subscribed.topic,(changes)=>latest.current(changes)),[client,subscribed])};
|
|
2
|
+
export{RealtimeProvider2,useRealtimeClient2,useRealtimeTopic2};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Generated by dts-bundle-generator v9.5.1
|
|
2
2
|
|
|
3
|
-
import { CiError as CiErrorEnvelope, CiErrorCode, CiResult, CiStreamPage, ClientDomains, ClientFetch, ClientOperationDefinition, ClientOperationId, ClientOperationInput, ClientOperationMap, ClientOperationOutput, ClientSdkClient, FederatedAuth, FederatedAuthError, FederatedAuthErrorCode, FederatedAuthState, FederatedSessionIdentity, FollowRunOptions, JsonValue, KnowledgeQuery, OperationExecutionOptions, OrganizationClient, QueryFilter, RealtimeChange, RealtimeClient, RealtimeClientOptions, RealtimeClientState, RealtimeClientStatus, RealtimeTopic, RealtimeTopicFilter, SearchQuery, ServerSessionAuth, SignInStep, TypedOperationExecutor, WorkflowInvokeTarget } from '@collective-intelligence/external-apps-client-sdk';
|
|
3
|
+
import { CiError as CiErrorEnvelope, CiErrorCode, CiResult, CiStreamPage, ClientDomains, ClientFetch, ClientOperationDefinition, ClientOperationId, ClientOperationInput, ClientOperationMap, ClientOperationOutput, ClientSdkClient, FederatedAuth, FederatedAuthError, FederatedAuthErrorCode, FederatedAuthState, FederatedSessionIdentity, FollowRunOptions, JsonValue, KnowledgeQuery, OperationExecutionOptions, OrganizationClient, QueryFilter, RealtimeChange, RealtimeClient, RealtimeClientOptions, RealtimeClientState, RealtimeClientStatus, RealtimeResetReason, RealtimeTopic, RealtimeTopicFilter, SearchQuery, ServerSessionAuth, SignInStep, TypedOperationExecutor, WorkflowInvokeTarget } from '@collective-intelligence/external-apps-client-sdk';
|
|
4
4
|
import { CiError, CiTransportError } from '@collective-intelligence/external-apps-client-sdk/effect';
|
|
5
5
|
import { EntityClient, EntityCreateInput, EntityDeleteInput, EntityListQuery, EntityMemberValue, EntityPage, EntityUpdateInput, EntityUploadInput, EntityUploadSlot, IdempotencyKey, PortableResourceSchema, ResourceCapabilities, ResourceCreateInput, ResourceCursor, ResourceDefinition, ResourceError, ResourceErrorCode, ResourceFilter, ResourceId, ResourceIdentityField, ResourceJsonValue, ResourceLifecycleInput, ResourceListQuery, ResourceListResult, ResourceMutationInput, ResourcePagination, ResourcePaginationMode, ResourceRecord, ResourceRecordAccess, ResourceRecordId, ResourceRequestOptions, ResourceResult, ResourceRevision, ResourceSort } from '@collective-intelligence/external-apps-client-sdk/resources';
|
|
6
6
|
import { ResourceField, ResourceFieldControlProps, ResourceObject, ResourceValue } from '@collective-intelligence/ui-react/resources';
|
|
@@ -496,6 +496,7 @@ export {
|
|
|
496
496
|
RealtimeClient,
|
|
497
497
|
RealtimeClientState,
|
|
498
498
|
RealtimeClientStatus,
|
|
499
|
+
RealtimeResetReason,
|
|
499
500
|
RealtimeTopic,
|
|
500
501
|
RealtimeTopicFilter,
|
|
501
502
|
ResourceCapabilities,
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{EntityRuntimeProvider,createDelegatedEntitySource2,defineEntity2,useEntityViewState2,useMemoryEntityViewState2,EntityTable2,EntityList2,EntityForm2}from"./index-5t792h25.js";import{useCallback,useId,useRef,useState as useState2}from"react";import{QueryClient,QueryClientProvider}from"@tanstack/react-query";import{createContext,useContext,useMemo,useState}from"react";import{jsx}from"react/jsx-runtime";var ClientContext=createContext(null);var CollectiveIntelligenceProvider=(props)=>{const{clientFactory}=props;const[ownedQueryClient]=useState(()=>new QueryClient({defaultOptions:{mutations:{retry:false},queries:{retry:false}}}));const ownedClient=useMemo(()=>clientFactory===undefined?undefined:clientFactory(),[clientFactory]);const client=props.client??ownedClient;const queryClient=props.queryClient??ownedQueryClient;if(client===undefined){throw new TypeError("A client or clientFactory is required")}return jsx(ClientContext.Provider,{value:client,children:jsx(QueryClientProvider,{client:queryClient,children:props.entitySource===undefined?props.children:jsx(EntityRuntimeProvider,{onWriteFailed:props.onWriteFailed,source:props.entitySource,children:props.children})})})};var useCollectiveIntelligenceClient=()=>{const client=useContext(ClientContext);if(client===null){throw new Error("CollectiveIntelligenceProvider must wrap Collective Intelligence hooks")}return client};var useOrganizationClient=(organizationId)=>{const client=useCollectiveIntelligenceClient();return useMemo(()=>client.forOrganization(organizationId),[client,organizationId])};var useKnowledge=(organizationId)=>useOrganizationClient(organizationId).knowledge;var useAgents=(organizationId)=>useOrganizationClient(organizationId).agents;var useSkills=(organizationId)=>useOrganizationClient(organizationId).skills;var useWorkflows=(organizationId)=>useOrganizationClient(organizationId).workflows;var useRuns=(organizationId)=>useOrganizationClient(organizationId).runs;var useAttachments=(organizationId)=>useOrganizationClient(organizationId).attachments;var useClientContext=(organizationId)=>useOrganizationClient(organizationId).context;import{jsx as jsx2,jsxs}from"react/jsx-runtime";var ignoreSubmit=()=>false;var createPromptKeyHandler=(onSubmit)=>(event)=>{if(event.key==="Enter"&&!event.shiftKey&&!event.isComposing){event.preventDefault();onSubmit()}};var AgentPromptPrimitive=({autoFocus=false,className,components,id,label,onChange,onSubmit,pending,status,style,submitLabel="Send",value})=>{const Form=components?.Form??"form";const Label=components?.Label??"label";const Textarea=components?.Textarea??"textarea";const Button=components?.Button??"button";const Status=components?.Status??"div";const statusId=`${id}-status`;const submit=(event)=>{event.preventDefault();if(!pending){onSubmit()}};const onKeyDown=(event)=>{createPromptKeyHandler(pending?ignoreSubmit:onSubmit)({isComposing:event.nativeEvent.isComposing,key:event.key,preventDefault:()=>{event.preventDefault()},shiftKey:event.shiftKey})};return jsxs(Form,{className:["ci-agent-prompt",className].filter(Boolean).join(" "),onSubmit:submit,style,children:[jsx2(Label,{className:"ci-agent-prompt__label",htmlFor:id,children:label}),jsx2(Textarea,{"aria-describedby":statusId,autoFocus,className:"ci-agent-prompt__input",disabled:pending,id,onChange:(event)=>{onChange(event.currentTarget.value)},onKeyDown,value}),jsx2(Button,{className:"ci-agent-prompt__submit",disabled:pending||value.trim().length===0,type:"submit",children:submitLabel}),jsx2(Status,{"aria-live":"polite",className:"ci-agent-prompt__status",id:statusId,children:status})]})};var useAgentInvocation=(organizationId)=>{const{agents}=useOrganizationClient(organizationId);const[state,setState]=useState2({status:"idle"});const generation=useRef(0);const invoke=useCallback(async(input)=>{generation.current+=1;const request=generation.current;const settle=(settled)=>{if(request===generation.current){setState(settled)}};setState({status:"submitting"});try{const result=await agents.invoke(input);settle(result.ok?{result,status:"success"}:{result,status:"failure"});return result}catch(error){settle({error,status:"error"});throw error}},[agents]);return{invoke,reset:()=>{generation.current+=1;setState({status:"idle"})},state}};var invocationStatus=(state)=>{switch(state.status){case"submitting":{return"Sending"}case"success":{return"Request started"}case"failure":{return state.result.error.message}case"error":{return"Request failed"}case"idle":{return null}default:{return null}}};var EMPTY_AGENT_PROMPT_COMPONENTS={};var EMPTY_AGENT_PROMPT_STYLE={};var createDefaultIdempotencyKey=()=>globalThis.crypto.randomUUID();var AgentPrompt=({agentId,autoFocus=false,className="",components=EMPTY_AGENT_PROMPT_COMPONENTS,createIdempotencyKey=createDefaultIdempotencyKey,label="Message",onResult,organizationId,style=EMPTY_AGENT_PROMPT_STYLE,submitLabel="Send"})=>{const id=`ci-agent-prompt-${useId().replaceAll(":","")}`;const[value,setValue]=useState2("");const invocation=useAgentInvocation(organizationId);const submit=()=>{const prompt=value.trim();if(prompt.length===0||invocation.state.status==="submitting"){return}const submitInvocation=async()=>{try{const result=await invocation.invoke({agentId,idempotencyKey:createIdempotencyKey(),input:{prompt}});if(result.ok){setValue("")}onResult?.(result)}catch{}};submitInvocation()};return jsx2(AgentPromptPrimitive,{autoFocus,className,components,id,label,onChange:setValue,onSubmit:submit,pending:invocation.state.status==="submitting",status:invocationStatus(invocation.state),style,submitLabel,value})};import{FederatedAuthError}from"@collective-intelligence/external-apps-client-sdk";import{createContext as createContext2,useCallback as useCallback2,useContext as useContext2,useEffect,useMemo as useMemo2,useSyncExternalStore}from"react";import{jsx as jsx3}from"react/jsx-runtime";var AuthContext=createContext2(null);var toFederatedAuthError=(error)=>new FederatedAuthError("authorization_failed",error.message);var unknownAuthError=()=>new FederatedAuthError("authorization_failed","Sign in failed");var CollectiveIntelligenceLoginProvider=(props)=>{const state=useSyncExternalStore(props.auth.subscribe,props.auth.getState,props.auth.getState);const contextValue=useMemo2(()=>({auth:props.auth,state}),[props.auth,state]);return jsx3(AuthContext.Provider,{value:contextValue,children:props.clientFactory===undefined?jsx3(CollectiveIntelligenceProvider,{client:props.client,entitySource:props.entitySource,onWriteFailed:props.onWriteFailed,queryClient:props.queryClient,children:props.children}):jsx3(CollectiveIntelligenceProvider,{clientFactory:props.clientFactory,entitySource:props.entitySource,onWriteFailed:props.onWriteFailed,queryClient:props.queryClient,children:props.children})})};var useCollectiveIntelligenceAuth=()=>{const value=useContext2(AuthContext);if(value===null){throw new Error("CollectiveIntelligenceLoginProvider must wrap authentication bindings")}return{...value,beginLogin:value.auth.beginLogin,completeLogin:value.auth.completeLogin,logout:value.auth.logout,reauthorize:value.auth.reauthorize}};var LoginButton=({children="Sign in with Collective Intelligence",className,components,disabled=false,onError,returnTo,style})=>{const{auth,state}=useCollectiveIntelligenceAuth();const Button=components?.Button??"button";const redirecting=state.status==="redirecting";const onClick=useCallback2((event)=>{event.preventDefault();const target=returnTo??globalThis.location.href;const begin=async()=>{try{await auth.beginLogin({returnTo:target})}catch(error){onError?.(error instanceof Error?toFederatedAuthError(error):unknownAuthError())}};begin()},[auth,onError,returnTo]);return jsx3(Button,{"aria-busy":redirecting,className:["ci-login-button",className].filter(Boolean).join(" "),disabled:disabled||redirecting,onClick,style,type:"button",children})};var callbackMessage=(state)=>{switch(state.status){case"authenticated":{return"Sign in complete"}case"error":{return state.error.message}case"expired":{return"Sign in expired"}case"anonymous":case"redirecting":{return"Completing sign in"}default:{return"Completing sign in"}}};var LoginCallbackPrimitive=({className,components,state,style})=>{const Status=components?.Status??"div";return jsx3(Status,{"aria-live":"polite",className:["ci-login-callback",className].filter(Boolean).join(" "),style,children:callbackMessage(state)})};var LoginCallback=({callbackUrl,onComplete,onError,...primitiveProps})=>{const{auth,state}=useCollectiveIntelligenceAuth();useEffect(()=>{const url=callbackUrl??globalThis.location.href;const complete=async()=>{try{const{returnTo}=await auth.completeLogin(url);onComplete?.(returnTo)}catch(error){onError?.(error instanceof Error?toFederatedAuthError(error):unknownAuthError())}};complete()},[auth,callbackUrl,onComplete,onError]);return jsx3(LoginCallbackPrimitive,{...primitiveProps,state})};var useSession=()=>{const{state}=useCollectiveIntelligenceAuth();return state};var SessionGate=({children,fallback=null})=>{const session=useSession();if(session.status!=="authenticated"){return fallback}return children};import{FederatedAuthError as FederatedAuthError2}from"@collective-intelligence/external-apps-client-sdk";import{CiTransportError}from"@collective-intelligence/external-apps-client-sdk/effect";import*as Schema from"effect/Schema";import{createContext as createContext3,useCallback as useCallback3,useContext as useContext3,useEffect as useEffect2,useMemo as useMemo3,useReducer,useRef as useRef2,useState as useState3}from"react";var initialSignInState={email:"",methods:null,notice:null,stage:"email"};var reduceSignIn=(state,{email=state.email,step})=>{const next={email,methods:state.methods,notice:null};switch(step.step){case"methods":{const{step:_methods,...methods}=step;return{...state,methods}}case"code_sent":{return{...next,stage:"code"}}case"registration_required":{return{...next,stage:"name"}}case"invalid_code":{return{...next,notice:step,stage:"code"}}case"retry_after":{return{...state,email,notice:step}}case"invalid_input":{return{...state,notice:{step:step.step}}}case"email_domain_not_allowed":{return{...next,notice:step,stage:"email"}}case"access_denied":case"code_expired":{return{...next,notice:{step:step.step},stage:"email"}}case"sso_required":{return{...next,provider:step.provider,stage:"sso_required"}}case"signed_in":{return{...next,registered:step.registered,stage:"signed_in"}}case"no_sign_in_method":case"redirect_to_web":{return{...next,stage:step.step}}default:{return step}}};import{jsx as jsx4}from"react/jsx-runtime";var defaultLabels={accessDenied:"You cannot sign in to this app with this address.",code:"Code",codeExpired:"The code is no longer valid. Enter your email again.",codeSentTo:(email)=>`Enter the code that we sent to ${email}.`,codeSubmit:"Continue",email:"Email",emailContinue:"Continue",emailDomainNotAllowed:(allowedDomains)=>`Use an address of ${allowedDomains.join(", ")}.`,emailSubmit:"Send code",invalidCode:(attemptsLeft)=>`The code is not correct. Attempts left: ${attemptsLeft}.`,invalidInput:"Check what you typed, then try again.",name:"Name",nameSubmit:"Create account",noSignInMethod:"No sign-in method is available for this app.",password:"Sign in with password",redirecting:"Opening the sign-in page…",resendCode:"Send a new code",retryAfter:(seconds)=>`Wait ${seconds} seconds, then ask for a new code.`,signedIn:"You are signed in.",sso:(provider)=>`Continue with ${provider}`,ssoRequired:(provider)=>`Your organization signs you in with ${provider}.`,title:"Sign in"};var SignInContext=createContext3(null);var noComponents={};var isSignInError=Schema.is(Schema.Union([CiTransportError,FederatedAuthError2]));var redirectToWeb={step:"redirect_to_web"};var SignInRoot=({children,components=noComponents,labels,...options})=>{const{auth}=useCollectiveIntelligenceAuth();if(!("signIn"in auth)){throw new Error("The sign-in components need the auth of createServerSessionAuth")}const{beginLogin,signIn}=auth;const[state,dispatch]=useReducer(reduceSignIn,initialSignInState);const[pending,setPending]=useState3(false);const running=useRef2(false);const latest=useRef2(options);useEffect2(()=>{latest.current=options});const run=useCallback3(async(call,email)=>{if(running.current){return}running.current=true;setPending(true);const answer=async()=>{try{const step=await call();dispatch(email===undefined?{step}:{email,step});if(step.step==="signed_in"){if(step.registered){latest.current.onRegistered?.()}latest.current.onSignedIn?.()}}catch(error){latest.current.onError?.(isSignInError(error)?error:new CiTransportError({cause:error}))}};await answer().finally(()=>{running.current=false;setPending(false)})},[]);const{actions,methods}=useMemo3(()=>{const returnTarget=()=>{const{returnTo}=latest.current;return returnTo===undefined?{}:{returnTo}};const languages=()=>{const{uiLocales}=latest.current;return uiLocales===undefined?{}:{uiLocales}};return{actions:{complete:(name)=>{run(()=>signIn.complete({name,...returnTarget()}))},password:()=>{run(async()=>{await beginLogin({returnTo:latest.current.returnTo??"/"});return redirectToWeb})},sso:(provider)=>{run(()=>signIn.sso({provider,...returnTarget()}))},start:(email)=>{run(()=>signIn.start({email,...languages(),...returnTarget()}),email)},verify:(code)=>{run(()=>signIn.verify({code,...returnTarget()}))}},methods:()=>{run(()=>signIn.methods({...languages(),...returnTarget()}))}}},[beginLogin,run,signIn]);useEffect2(()=>{methods()},[methods]);const value=useMemo3(()=>({binding:{...actions,pending,state},components,labels:{...defaultLabels,...labels}}),[actions,components,labels,pending,state]);return jsx4(SignInContext.Provider,{value,children})};var useSignInParts=()=>{const value=useContext3(SignInContext);if(value===null){throw new Error("SignIn.Root must wrap the sign-in components")}return value};var useSignIn=()=>useSignInParts().binding;import{Alert,AlertDescription,Button,Input,InputOTP,InputOTPGroup,InputOTPSlot}from"@collective-intelligence/ui-react/ui";import{LabeledField}from"@collective-intelligence/ui-react/ui-extensions/labeled-field";import{cn}from"@collective-intelligence/ui-react/utils/cn";import{useId as useId2}from"react";import{jsx as jsx5,jsxs as jsxs2}from"react/jsx-runtime";var codeSlots=[0,1,2,3,4,5];var CodeInput=(props)=>jsx5(InputOTP,{...props,maxLength:codeSlots.length,pattern:"^[0-9]+$",children:jsx5(InputOTPGroup,{children:codeSlots.map((index)=>jsx5(InputOTPSlot,{index},index))})});var Action=({variant,...props})=>{const{components}=useSignInParts();return components.Button===undefined?jsx5(Button,{variant,...props}):jsx5(components.Button,{...props})};var submitted=(event,name)=>{event.preventDefault();const value=new FormData(event.currentTarget).get(name);return value instanceof File||value===null?"":value.trim()};var EmailForm=({className})=>{const{binding,components,labels}=useSignInParts();const id=useId2();if(binding.state.stage!=="email"){return null}const Field=components.EmailField??Input;const submitLabel=binding.state.methods?.emailCode===false?labels.emailContinue:labels.emailSubmit;return jsxs2("form",{"aria-busy":binding.pending,className:cn("grid gap-4",className),onSubmit:(event)=>{binding.start(submitted(event,"email"))},children:[jsx5(LabeledField,{id,label:labels.email,children:jsx5(Field,{autoComplete:"email",defaultValue:binding.state.email,id,name:"email",required:true,type:"email"})}),jsx5(Action,{disabled:binding.pending,type:"submit",variant:"default",children:submitLabel})]})};var CodeForm=({className})=>{const{binding,components,labels}=useSignInParts();const id=useId2();if(binding.state.stage!=="code"){return null}const{email}=binding.state;const Field=components.CodeField??CodeInput;return jsxs2("form",{"aria-busy":binding.pending,className:cn("grid gap-4",className),onSubmit:(event)=>{binding.verify(submitted(event,"code"))},children:[jsx5("p",{className:"text-sm",id:`${id}-sent`,children:labels.codeSentTo(email)}),jsx5(LabeledField,{id,label:labels.code,children:jsx5(Field,{"aria-describedby":`${id}-sent`,autoComplete:"one-time-code",id,name:"code",required:true})}),jsx5(Action,{disabled:binding.pending,type:"submit",variant:"default",children:labels.codeSubmit}),jsx5(Action,{disabled:binding.pending,onClick:()=>{binding.start(email)},type:"button",variant:"link",children:labels.resendCode})]})};var NameForm=({className})=>{const{binding,components,labels}=useSignInParts();const id=useId2();if(binding.state.stage!=="name"){return null}const Field=components.NameField??Input;return jsxs2("form",{"aria-busy":binding.pending,className:cn("grid gap-4",className),onSubmit:(event)=>{binding.complete(submitted(event,"name"))},children:[jsx5(LabeledField,{id,label:labels.name,children:jsx5(Field,{autoComplete:"name",id,maxLength:255,name:"name",required:true})}),jsx5(Action,{disabled:binding.pending,type:"submit",variant:"default",children:labels.nameSubmit})]})};var ssoProviders=(state)=>{if(state.stage==="sso_required"){return[state.provider]}return state.stage==="email"?state.methods?.ssoProviders??[]:[]};var SsoButtons=({className})=>{const{binding,labels}=useSignInParts();const providers=ssoProviders(binding.state);if(providers.length===0){return null}return jsx5("div",{className:cn("grid gap-2",className),children:providers.map((provider)=>jsx5(Action,{disabled:binding.pending,onClick:()=>{binding.sso(provider.id)},type:"button",variant:"outline",children:labels.sso(provider.displayName)},provider.id))})};var PasswordButton=({className})=>{const{binding,labels}=useSignInParts();if(binding.state.stage!=="email"||binding.state.methods?.password!==true){return null}return jsx5(Action,{className,disabled:binding.pending,onClick:()=>{binding.password()},type:"button",variant:"outline",children:labels.password})};var noticeText=(notice,labels)=>{switch(notice.step){case"access_denied":{return labels.accessDenied}case"code_expired":{return labels.codeExpired}case"email_domain_not_allowed":{return labels.emailDomainNotAllowed(notice.allowedDomains)}case"invalid_code":{return labels.invalidCode(notice.attemptsLeft)}case"invalid_input":{return labels.invalidInput}case"retry_after":{return labels.retryAfter(notice.seconds)}default:{return notice}}};var Notice=({className})=>{const{binding,labels}=useSignInParts();const{notice}=binding.state;if(notice===null){return null}return jsx5(Alert,{className,variant:"destructive",children:jsx5(AlertDescription,{children:noticeText(notice,labels)})})};var statusText=(state,labels)=>{switch(state.stage){case"no_sign_in_method":{return labels.noSignInMethod}case"redirect_to_web":{return labels.redirecting}case"signed_in":{return labels.signedIn}case"sso_required":{return labels.ssoRequired(state.provider.displayName)}default:{return null}}};var Status=({className})=>{const{binding,labels}=useSignInParts();const text=statusText(binding.state,labels);if(text===null){return null}return jsx5("output",{className:cn("text-sm",className),children:text})};var SignIn={CodeForm,EmailForm,NameForm,Notice,PasswordButton,Root:SignInRoot,SsoButtons,Status};import{Card,CardContent,CardHeader,CardTitle}from"@collective-intelligence/ui-react/ui";import{jsx as jsx6,jsxs as jsxs3}from"react/jsx-runtime";var Title=()=>jsx6(CardTitle,{children:useSignInParts().labels.title});var SignInCard=({className,...rootProps})=>jsx6(SignIn.Root,{...rootProps,children:jsxs3(Card,{className,children:[jsx6(CardHeader,{children:jsx6(Title,{})}),jsxs3(CardContent,{className:"grid gap-4",children:[jsx6(SignIn.Notice,{}),jsx6(SignIn.EmailForm,{}),jsx6(SignIn.CodeForm,{}),jsx6(SignIn.NameForm,{}),jsx6(SignIn.SsoButtons,{}),jsx6(SignIn.PasswordButton,{}),jsx6(SignIn.Status,{})]})]})});import{createRealtimeClient}from"@collective-intelligence/external-apps-client-sdk";import{createContext as createContext4,useContext as useContext4,useEffect as useEffect3,useState as useState4}from"react";import{jsx as jsx7}from"react/jsx-runtime";var idle={connections:0,lastEventId:undefined,status:"idle",topics:[]};var hasOnReset=(options)=>options.onReset!==undefined;var shareClient=(initial)=>{let options=initial;let shared={status:"none"};const subscriptions=new Set;const create=()=>createRealtimeClient({document:globalThis.document,window:globalThis.window,...options,onAccessChanged:()=>options.onAccessChanged?.(),onRefused:()=>options.onRefused?.(),...hasOnReset(options)&&{onReset:()=>options.onReset?.()}});const acquire=()=>{const client=shared.status==="none"?create():shared.client;shared={client,holders:shared.status==="held"?shared.holders+1:1,status:"held"};return client};const release=()=>{if(shared.status!=="held"){return}if(shared.holders>1){shared={...shared,holders:shared.holders-1};return}shared={client:shared.client,status:"releasing"};queueMicrotask(()=>{if(shared.status==="releasing"){shared.client.close();shared={status:"none"}}})};const subscribe=(topic,onChanges)=>{const subscription={onChanges,topic,unsubscribe:acquire().subscribe(topic,onChanges)};subscriptions.add(subscription);return()=>{if(subscriptions.delete(subscription)){subscription.unsubscribe();release()}}};return{acquire,getState:()=>shared.status==="none"?idle:shared.client.getState(),release,subscribe,update:(next)=>{const previous=options;options=next;if(shared.status==="none"||hasOnReset(next)===hasOnReset(previous)){return}for(const subscription of subscriptions){subscription.unsubscribe()}shared.client.close();const client=create();shared={...shared,client};for(const subscription of subscriptions){subscription.unsubscribe=client.subscribe(subscription.topic,subscription.onChanges)}}}};var RealtimeContext=createContext4(null);var RealtimeProvider=({children,...options})=>{const[shared]=useState4(()=>shareClient(options));useEffect3(()=>{shared.update(options)});useEffect3(()=>{shared.acquire();return shared.release},[shared]);return jsx7(RealtimeContext.Provider,{value:shared,children})};var useRealtimeClient=()=>{const client=useContext4(RealtimeContext);if(client===null){throw new Error("useRealtimeClient requires a RealtimeProvider")}return client};import{realtimeTopicKey}from"@collective-intelligence/external-apps-client-sdk";import{useEffect as useEffect4,useRef as useRef3,useState as useState5}from"react";var useRealtimeTopic=(topic,onChanges)=>{const client=useRealtimeClient();const latest=useRef3(onChanges);const key=topic===null?null:realtimeTopicKey(topic);const[subscribed,setSubscribed]=useState5({key,topic});if(subscribed.key!==key){setSubscribed({key,topic})}useEffect4(()=>{latest.current=onChanges});useEffect4(()=>subscribed.topic===null?undefined:client.subscribe(subscribed.topic,(changes)=>latest.current(changes)),[client,subscribed])};var clientSdkReactEntrypoint="react";export{AgentPrompt,AgentPromptPrimitive,CollectiveIntelligenceLoginProvider,CollectiveIntelligenceProvider,EntityForm2 as EntityForm,EntityList2 as EntityList,EntityTable2 as EntityTable,LoginButton,LoginCallback,LoginCallbackPrimitive,RealtimeProvider,SessionGate,SignIn,SignInCard,clientSdkReactEntrypoint,createDelegatedEntitySource2 as createDelegatedEntitySource,createPromptKeyHandler,defineEntity2 as defineEntity,useAgentInvocation,useAgents,useAttachments,useClientContext,useCollectiveIntelligenceAuth,useCollectiveIntelligenceClient,useEntityViewState2 as useEntityViewState,useKnowledge,useMemoryEntityViewState2 as useMemoryEntityViewState,useOrganizationClient,useRealtimeClient,useRealtimeTopic,useRuns,useSession,useSignIn,useSkills,useWorkflows};
|
|
2
|
+
import{EntityRuntimeProvider,createDelegatedEntitySource2,defineEntity2,useEntityViewState2,useMemoryEntityViewState2,EntityTable2,EntityList2,EntityForm2}from"./index-5t792h25.js";import{RealtimeProvider2,useRealtimeClient2,useRealtimeTopic2}from"./index-ktw8msmm.js";import{useCallback,useId,useRef,useState as useState2}from"react";import{QueryClient,QueryClientProvider}from"@tanstack/react-query";import{createContext,useContext,useMemo,useState}from"react";import{jsx}from"react/jsx-runtime";var ClientContext=createContext(null);var CollectiveIntelligenceProvider=(props)=>{const{clientFactory}=props;const[ownedQueryClient]=useState(()=>new QueryClient({defaultOptions:{mutations:{retry:false},queries:{retry:false}}}));const ownedClient=useMemo(()=>clientFactory===undefined?undefined:clientFactory(),[clientFactory]);const client=props.client??ownedClient;const queryClient=props.queryClient??ownedQueryClient;if(client===undefined){throw new TypeError("A client or clientFactory is required")}return jsx(ClientContext.Provider,{value:client,children:jsx(QueryClientProvider,{client:queryClient,children:props.entitySource===undefined?props.children:jsx(EntityRuntimeProvider,{onWriteFailed:props.onWriteFailed,source:props.entitySource,children:props.children})})})};var useCollectiveIntelligenceClient=()=>{const client=useContext(ClientContext);if(client===null){throw new Error("CollectiveIntelligenceProvider must wrap Collective Intelligence hooks")}return client};var useOrganizationClient=(organizationId)=>{const client=useCollectiveIntelligenceClient();return useMemo(()=>client.forOrganization(organizationId),[client,organizationId])};var useKnowledge=(organizationId)=>useOrganizationClient(organizationId).knowledge;var useAgents=(organizationId)=>useOrganizationClient(organizationId).agents;var useSkills=(organizationId)=>useOrganizationClient(organizationId).skills;var useWorkflows=(organizationId)=>useOrganizationClient(organizationId).workflows;var useRuns=(organizationId)=>useOrganizationClient(organizationId).runs;var useAttachments=(organizationId)=>useOrganizationClient(organizationId).attachments;var useClientContext=(organizationId)=>useOrganizationClient(organizationId).context;import{jsx as jsx2,jsxs}from"react/jsx-runtime";var ignoreSubmit=()=>false;var createPromptKeyHandler=(onSubmit)=>(event)=>{if(event.key==="Enter"&&!event.shiftKey&&!event.isComposing){event.preventDefault();onSubmit()}};var AgentPromptPrimitive=({autoFocus=false,className,components,id,label,onChange,onSubmit,pending,status,style,submitLabel="Send",value})=>{const Form=components?.Form??"form";const Label=components?.Label??"label";const Textarea=components?.Textarea??"textarea";const Button=components?.Button??"button";const Status=components?.Status??"div";const statusId=`${id}-status`;const submit=(event)=>{event.preventDefault();if(!pending){onSubmit()}};const onKeyDown=(event)=>{createPromptKeyHandler(pending?ignoreSubmit:onSubmit)({isComposing:event.nativeEvent.isComposing,key:event.key,preventDefault:()=>{event.preventDefault()},shiftKey:event.shiftKey})};return jsxs(Form,{className:["ci-agent-prompt",className].filter(Boolean).join(" "),onSubmit:submit,style,children:[jsx2(Label,{className:"ci-agent-prompt__label",htmlFor:id,children:label}),jsx2(Textarea,{"aria-describedby":statusId,autoFocus,className:"ci-agent-prompt__input",disabled:pending,id,onChange:(event)=>{onChange(event.currentTarget.value)},onKeyDown,value}),jsx2(Button,{className:"ci-agent-prompt__submit",disabled:pending||value.trim().length===0,type:"submit",children:submitLabel}),jsx2(Status,{"aria-live":"polite",className:"ci-agent-prompt__status",id:statusId,children:status})]})};var useAgentInvocation=(organizationId)=>{const{agents}=useOrganizationClient(organizationId);const[state,setState]=useState2({status:"idle"});const generation=useRef(0);const invoke=useCallback(async(input)=>{generation.current+=1;const request=generation.current;const settle=(settled)=>{if(request===generation.current){setState(settled)}};setState({status:"submitting"});try{const result=await agents.invoke(input);settle(result.ok?{result,status:"success"}:{result,status:"failure"});return result}catch(error){settle({error,status:"error"});throw error}},[agents]);return{invoke,reset:()=>{generation.current+=1;setState({status:"idle"})},state}};var invocationStatus=(state)=>{switch(state.status){case"submitting":{return"Sending"}case"success":{return"Request started"}case"failure":{return state.result.error.message}case"error":{return"Request failed"}case"idle":{return null}default:{return null}}};var EMPTY_AGENT_PROMPT_COMPONENTS={};var EMPTY_AGENT_PROMPT_STYLE={};var createDefaultIdempotencyKey=()=>globalThis.crypto.randomUUID();var AgentPrompt=({agentId,autoFocus=false,className="",components=EMPTY_AGENT_PROMPT_COMPONENTS,createIdempotencyKey=createDefaultIdempotencyKey,label="Message",onResult,organizationId,style=EMPTY_AGENT_PROMPT_STYLE,submitLabel="Send"})=>{const id=`ci-agent-prompt-${useId().replaceAll(":","")}`;const[value,setValue]=useState2("");const invocation=useAgentInvocation(organizationId);const submit=()=>{const prompt=value.trim();if(prompt.length===0||invocation.state.status==="submitting"){return}const submitInvocation=async()=>{try{const result=await invocation.invoke({agentId,idempotencyKey:createIdempotencyKey(),input:{prompt}});if(result.ok){setValue("")}onResult?.(result)}catch{}};submitInvocation()};return jsx2(AgentPromptPrimitive,{autoFocus,className,components,id,label,onChange:setValue,onSubmit:submit,pending:invocation.state.status==="submitting",status:invocationStatus(invocation.state),style,submitLabel,value})};import{FederatedAuthError}from"@collective-intelligence/external-apps-client-sdk";import{createContext as createContext2,useCallback as useCallback2,useContext as useContext2,useEffect,useMemo as useMemo2,useSyncExternalStore}from"react";import{jsx as jsx3}from"react/jsx-runtime";var AuthContext=createContext2(null);var toFederatedAuthError=(error)=>new FederatedAuthError("authorization_failed",error.message);var unknownAuthError=()=>new FederatedAuthError("authorization_failed","Sign in failed");var CollectiveIntelligenceLoginProvider=(props)=>{const state=useSyncExternalStore(props.auth.subscribe,props.auth.getState,props.auth.getState);const contextValue=useMemo2(()=>({auth:props.auth,state}),[props.auth,state]);return jsx3(AuthContext.Provider,{value:contextValue,children:props.clientFactory===undefined?jsx3(CollectiveIntelligenceProvider,{client:props.client,entitySource:props.entitySource,onWriteFailed:props.onWriteFailed,queryClient:props.queryClient,children:props.children}):jsx3(CollectiveIntelligenceProvider,{clientFactory:props.clientFactory,entitySource:props.entitySource,onWriteFailed:props.onWriteFailed,queryClient:props.queryClient,children:props.children})})};var useCollectiveIntelligenceAuth=()=>{const value=useContext2(AuthContext);if(value===null){throw new Error("CollectiveIntelligenceLoginProvider must wrap authentication bindings")}return{...value,beginLogin:value.auth.beginLogin,completeLogin:value.auth.completeLogin,logout:value.auth.logout,reauthorize:value.auth.reauthorize}};var LoginButton=({children="Sign in with Collective Intelligence",className,components,disabled=false,onError,returnTo,style})=>{const{auth,state}=useCollectiveIntelligenceAuth();const Button=components?.Button??"button";const redirecting=state.status==="redirecting";const onClick=useCallback2((event)=>{event.preventDefault();const target=returnTo??globalThis.location.href;const begin=async()=>{try{await auth.beginLogin({returnTo:target})}catch(error){onError?.(error instanceof Error?toFederatedAuthError(error):unknownAuthError())}};begin()},[auth,onError,returnTo]);return jsx3(Button,{"aria-busy":redirecting,className:["ci-login-button",className].filter(Boolean).join(" "),disabled:disabled||redirecting,onClick,style,type:"button",children})};var callbackMessage=(state)=>{switch(state.status){case"authenticated":{return"Sign in complete"}case"error":{return state.error.message}case"expired":{return"Sign in expired"}case"anonymous":case"redirecting":{return"Completing sign in"}default:{return"Completing sign in"}}};var LoginCallbackPrimitive=({className,components,state,style})=>{const Status=components?.Status??"div";return jsx3(Status,{"aria-live":"polite",className:["ci-login-callback",className].filter(Boolean).join(" "),style,children:callbackMessage(state)})};var LoginCallback=({callbackUrl,onComplete,onError,...primitiveProps})=>{const{auth,state}=useCollectiveIntelligenceAuth();useEffect(()=>{const url=callbackUrl??globalThis.location.href;const complete=async()=>{try{const{returnTo}=await auth.completeLogin(url);onComplete?.(returnTo)}catch(error){onError?.(error instanceof Error?toFederatedAuthError(error):unknownAuthError())}};complete()},[auth,callbackUrl,onComplete,onError]);return jsx3(LoginCallbackPrimitive,{...primitiveProps,state})};var useSession=()=>{const{state}=useCollectiveIntelligenceAuth();return state};var SessionGate=({children,fallback=null})=>{const session=useSession();if(session.status!=="authenticated"){return fallback}return children};import{FederatedAuthError as FederatedAuthError2}from"@collective-intelligence/external-apps-client-sdk";import{CiTransportError}from"@collective-intelligence/external-apps-client-sdk/effect";import*as Schema from"effect/Schema";import{createContext as createContext3,useCallback as useCallback3,useContext as useContext3,useEffect as useEffect2,useMemo as useMemo3,useReducer,useRef as useRef2,useState as useState3}from"react";var initialSignInState={email:"",methods:null,notice:null,stage:"email"};var reduceSignIn=(state,{email=state.email,step})=>{const next={email,methods:state.methods,notice:null};switch(step.step){case"methods":{const{step:_methods,...methods}=step;return{...state,methods}}case"code_sent":{return{...next,stage:"code"}}case"registration_required":{return{...next,stage:"name"}}case"invalid_code":{return{...next,notice:step,stage:"code"}}case"retry_after":{return{...state,email,notice:step}}case"invalid_input":{return{...state,notice:{step:step.step}}}case"email_domain_not_allowed":{return{...next,notice:step,stage:"email"}}case"access_denied":case"code_expired":{return{...next,notice:{step:step.step},stage:"email"}}case"sso_required":{return{...next,provider:step.provider,stage:"sso_required"}}case"signed_in":{return{...next,registered:step.registered,stage:"signed_in"}}case"no_sign_in_method":case"redirect_to_web":{return{...next,stage:step.step}}default:{return step}}};import{jsx as jsx4}from"react/jsx-runtime";var defaultLabels={accessDenied:"You cannot sign in to this app with this address.",code:"Code",codeExpired:"The code is no longer valid. Enter your email again.",codeSentTo:(email)=>`Enter the code that we sent to ${email}.`,codeSubmit:"Continue",email:"Email",emailContinue:"Continue",emailDomainNotAllowed:(allowedDomains)=>`Use an address of ${allowedDomains.join(", ")}.`,emailSubmit:"Send code",invalidCode:(attemptsLeft)=>`The code is not correct. Attempts left: ${attemptsLeft}.`,invalidInput:"Check what you typed, then try again.",name:"Name",nameSubmit:"Create account",noSignInMethod:"No sign-in method is available for this app.",password:"Sign in with password",redirecting:"Opening the sign-in page…",resendCode:"Send a new code",retryAfter:(seconds)=>`Wait ${seconds} seconds, then ask for a new code.`,signedIn:"You are signed in.",sso:(provider)=>`Continue with ${provider}`,ssoRequired:(provider)=>`Your organization signs you in with ${provider}.`,title:"Sign in"};var SignInContext=createContext3(null);var noComponents={};var isSignInError=Schema.is(Schema.Union([CiTransportError,FederatedAuthError2]));var redirectToWeb={step:"redirect_to_web"};var SignInRoot=({children,components=noComponents,labels,...options})=>{const{auth}=useCollectiveIntelligenceAuth();if(!("signIn"in auth)){throw new Error("The sign-in components need the auth of createServerSessionAuth")}const{beginLogin,signIn}=auth;const[state,dispatch]=useReducer(reduceSignIn,initialSignInState);const[pending,setPending]=useState3(false);const running=useRef2(false);const latest=useRef2(options);useEffect2(()=>{latest.current=options});const run=useCallback3(async(call,email)=>{if(running.current){return}running.current=true;setPending(true);const answer=async()=>{try{const step=await call();dispatch(email===undefined?{step}:{email,step});if(step.step==="signed_in"){if(step.registered){latest.current.onRegistered?.()}latest.current.onSignedIn?.()}}catch(error){latest.current.onError?.(isSignInError(error)?error:new CiTransportError({cause:error}))}};await answer().finally(()=>{running.current=false;setPending(false)})},[]);const{actions,methods}=useMemo3(()=>{const returnTarget=()=>{const{returnTo}=latest.current;return returnTo===undefined?{}:{returnTo}};const languages=()=>{const{uiLocales}=latest.current;return uiLocales===undefined?{}:{uiLocales}};return{actions:{complete:(name)=>{run(()=>signIn.complete({name,...returnTarget()}))},password:()=>{run(async()=>{await beginLogin({returnTo:latest.current.returnTo??"/"});return redirectToWeb})},sso:(provider)=>{run(()=>signIn.sso({provider,...returnTarget()}))},start:(email)=>{run(()=>signIn.start({email,...languages(),...returnTarget()}),email)},verify:(code)=>{run(()=>signIn.verify({code,...returnTarget()}))}},methods:()=>{run(()=>signIn.methods({...languages(),...returnTarget()}))}}},[beginLogin,run,signIn]);useEffect2(()=>{methods()},[methods]);const value=useMemo3(()=>({binding:{...actions,pending,state},components,labels:{...defaultLabels,...labels}}),[actions,components,labels,pending,state]);return jsx4(SignInContext.Provider,{value,children})};var useSignInParts=()=>{const value=useContext3(SignInContext);if(value===null){throw new Error("SignIn.Root must wrap the sign-in components")}return value};var useSignIn=()=>useSignInParts().binding;import{Alert,AlertDescription,Button,Input,InputOTP,InputOTPGroup,InputOTPSlot}from"@collective-intelligence/ui-react/ui";import{LabeledField}from"@collective-intelligence/ui-react/ui-extensions/labeled-field";import{cn}from"@collective-intelligence/ui-react/utils/cn";import{useId as useId2}from"react";import{jsx as jsx5,jsxs as jsxs2}from"react/jsx-runtime";var codeSlots=[0,1,2,3,4,5];var CodeInput=(props)=>jsx5(InputOTP,{...props,maxLength:codeSlots.length,pattern:"^[0-9]+$",children:jsx5(InputOTPGroup,{children:codeSlots.map((index)=>jsx5(InputOTPSlot,{index},index))})});var Action=({variant,...props})=>{const{components}=useSignInParts();return components.Button===undefined?jsx5(Button,{variant,...props}):jsx5(components.Button,{...props})};var submitted=(event,name)=>{event.preventDefault();const value=new FormData(event.currentTarget).get(name);return value instanceof File||value===null?"":value.trim()};var EmailForm=({className})=>{const{binding,components,labels}=useSignInParts();const id=useId2();if(binding.state.stage!=="email"){return null}const Field=components.EmailField??Input;const submitLabel=binding.state.methods?.emailCode===false?labels.emailContinue:labels.emailSubmit;return jsxs2("form",{"aria-busy":binding.pending,className:cn("grid gap-4",className),onSubmit:(event)=>{binding.start(submitted(event,"email"))},children:[jsx5(LabeledField,{id,label:labels.email,children:jsx5(Field,{autoComplete:"email",defaultValue:binding.state.email,id,name:"email",required:true,type:"email"})}),jsx5(Action,{disabled:binding.pending,type:"submit",variant:"default",children:submitLabel})]})};var CodeForm=({className})=>{const{binding,components,labels}=useSignInParts();const id=useId2();if(binding.state.stage!=="code"){return null}const{email}=binding.state;const Field=components.CodeField??CodeInput;return jsxs2("form",{"aria-busy":binding.pending,className:cn("grid gap-4",className),onSubmit:(event)=>{binding.verify(submitted(event,"code"))},children:[jsx5("p",{className:"text-sm",id:`${id}-sent`,children:labels.codeSentTo(email)}),jsx5(LabeledField,{id,label:labels.code,children:jsx5(Field,{"aria-describedby":`${id}-sent`,autoComplete:"one-time-code",id,name:"code",required:true})}),jsx5(Action,{disabled:binding.pending,type:"submit",variant:"default",children:labels.codeSubmit}),jsx5(Action,{disabled:binding.pending,onClick:()=>{binding.start(email)},type:"button",variant:"link",children:labels.resendCode})]})};var NameForm=({className})=>{const{binding,components,labels}=useSignInParts();const id=useId2();if(binding.state.stage!=="name"){return null}const Field=components.NameField??Input;return jsxs2("form",{"aria-busy":binding.pending,className:cn("grid gap-4",className),onSubmit:(event)=>{binding.complete(submitted(event,"name"))},children:[jsx5(LabeledField,{id,label:labels.name,children:jsx5(Field,{autoComplete:"name",id,maxLength:255,name:"name",required:true})}),jsx5(Action,{disabled:binding.pending,type:"submit",variant:"default",children:labels.nameSubmit})]})};var ssoProviders=(state)=>{if(state.stage==="sso_required"){return[state.provider]}return state.stage==="email"?state.methods?.ssoProviders??[]:[]};var SsoButtons=({className})=>{const{binding,labels}=useSignInParts();const providers=ssoProviders(binding.state);if(providers.length===0){return null}return jsx5("div",{className:cn("grid gap-2",className),children:providers.map((provider)=>jsx5(Action,{disabled:binding.pending,onClick:()=>{binding.sso(provider.id)},type:"button",variant:"outline",children:labels.sso(provider.displayName)},provider.id))})};var PasswordButton=({className})=>{const{binding,labels}=useSignInParts();if(binding.state.stage!=="email"||binding.state.methods?.password!==true){return null}return jsx5(Action,{className,disabled:binding.pending,onClick:()=>{binding.password()},type:"button",variant:"outline",children:labels.password})};var noticeText=(notice,labels)=>{switch(notice.step){case"access_denied":{return labels.accessDenied}case"code_expired":{return labels.codeExpired}case"email_domain_not_allowed":{return labels.emailDomainNotAllowed(notice.allowedDomains)}case"invalid_code":{return labels.invalidCode(notice.attemptsLeft)}case"invalid_input":{return labels.invalidInput}case"retry_after":{return labels.retryAfter(notice.seconds)}default:{return notice}}};var Notice=({className})=>{const{binding,labels}=useSignInParts();const{notice}=binding.state;if(notice===null){return null}return jsx5(Alert,{className,variant:"destructive",children:jsx5(AlertDescription,{children:noticeText(notice,labels)})})};var statusText=(state,labels)=>{switch(state.stage){case"no_sign_in_method":{return labels.noSignInMethod}case"redirect_to_web":{return labels.redirecting}case"signed_in":{return labels.signedIn}case"sso_required":{return labels.ssoRequired(state.provider.displayName)}default:{return null}}};var Status=({className})=>{const{binding,labels}=useSignInParts();const text=statusText(binding.state,labels);if(text===null){return null}return jsx5("output",{className:cn("text-sm",className),children:text})};var SignIn={CodeForm,EmailForm,NameForm,Notice,PasswordButton,Root:SignInRoot,SsoButtons,Status};import{Card,CardContent,CardHeader,CardTitle}from"@collective-intelligence/ui-react/ui";import{jsx as jsx6,jsxs as jsxs3}from"react/jsx-runtime";var Title=()=>jsx6(CardTitle,{children:useSignInParts().labels.title});var SignInCard=({className,...rootProps})=>jsx6(SignIn.Root,{...rootProps,children:jsxs3(Card,{className,children:[jsx6(CardHeader,{children:jsx6(Title,{})}),jsxs3(CardContent,{className:"grid gap-4",children:[jsx6(SignIn.Notice,{}),jsx6(SignIn.EmailForm,{}),jsx6(SignIn.CodeForm,{}),jsx6(SignIn.NameForm,{}),jsx6(SignIn.SsoButtons,{}),jsx6(SignIn.PasswordButton,{}),jsx6(SignIn.Status,{})]})]})});var clientSdkReactEntrypoint="react";export{AgentPrompt,AgentPromptPrimitive,CollectiveIntelligenceLoginProvider,CollectiveIntelligenceProvider,EntityForm2 as EntityForm,EntityList2 as EntityList,EntityTable2 as EntityTable,LoginButton,LoginCallback,LoginCallbackPrimitive,RealtimeProvider2 as RealtimeProvider,SessionGate,SignIn,SignInCard,clientSdkReactEntrypoint,createDelegatedEntitySource2 as createDelegatedEntitySource,createPromptKeyHandler,defineEntity2 as defineEntity,useAgentInvocation,useAgents,useAttachments,useClientContext,useCollectiveIntelligenceAuth,useCollectiveIntelligenceClient,useEntityViewState2 as useEntityViewState,useKnowledge,useMemoryEntityViewState2 as useMemoryEntityViewState,useOrganizationClient,useRealtimeClient2 as useRealtimeClient,useRealtimeTopic2 as useRealtimeTopic,useRuns,useSession,useSignIn,useSkills,useWorkflows};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// Generated by dts-bundle-generator v9.5.1
|
|
2
|
+
|
|
3
|
+
import { RealtimeChange, RealtimeClient, RealtimeClientOptions, RealtimeClientState, RealtimeClientStatus, RealtimeResetReason, RealtimeTopic, RealtimeTopicFilter } from '@collective-intelligence/external-apps-client-sdk';
|
|
4
|
+
import { ReactNode } from 'react';
|
|
5
|
+
|
|
6
|
+
export type RealtimeProviderProps = Readonly<RealtimeClientOptions & {
|
|
7
|
+
children: ReactNode;
|
|
8
|
+
}>;
|
|
9
|
+
/** The client of a provider tree, as its hooks use it: the provider closes it. */
|
|
10
|
+
export type TreeClient = Omit<RealtimeClient, "close">;
|
|
11
|
+
/**
|
|
12
|
+
* Gives its tree one realtime client of the client SDK, and so one connection.
|
|
13
|
+
* It creates the client in the browser when it mounts or a hook subscribes,
|
|
14
|
+
* and closes it when the tree unmounts. `onReset`, `onAccessChanged` and
|
|
15
|
+
* `onRefused` are the app's callbacks; the client calls the ones of the latest
|
|
16
|
+
* render. Only a
|
|
17
|
+
* client with `onReset` resyncs, so a render that adds or removes `onReset`
|
|
18
|
+
* replaces the client, and with it the stream. It reads the other options
|
|
19
|
+
* once, when it creates the client.
|
|
20
|
+
*/
|
|
21
|
+
export declare const RealtimeProvider: ({ children, ...options }: RealtimeProviderProps) => import("react").JSX.Element;
|
|
22
|
+
/** The client of the nearest `RealtimeProvider`; a subscription holds it open. */
|
|
23
|
+
export declare const useRealtimeClient: () => TreeClient;
|
|
24
|
+
/**
|
|
25
|
+
* Calls `onChanges` with each batch of changes of `topic` while the component
|
|
26
|
+
* is mounted; `null` listens to nothing. Equal topics share one subscription
|
|
27
|
+
* key, so a new topic object on each render does not resubscribe.
|
|
28
|
+
*/
|
|
29
|
+
export declare const useRealtimeTopic: (topic: RealtimeTopic | null, onChanges: (changes: readonly RealtimeChange[]) => void) => void;
|
|
30
|
+
|
|
31
|
+
export {
|
|
32
|
+
RealtimeChange,
|
|
33
|
+
RealtimeClient,
|
|
34
|
+
RealtimeClientState,
|
|
35
|
+
RealtimeClientStatus,
|
|
36
|
+
RealtimeResetReason,
|
|
37
|
+
RealtimeTopic,
|
|
38
|
+
RealtimeTopicFilter,
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export {};
|
package/dist/realtime.js
ADDED
package/docs/effect.md
CHANGED
|
@@ -109,36 +109,104 @@ const LeadEditor = ({ id }: { id: string }) => {
|
|
|
109
109
|
### Optimistic write
|
|
110
110
|
|
|
111
111
|
An optimistic write shows its value before CI answers. For one key, use
|
|
112
|
-
`QueryCache.optimisticUpdate(queryKey, edit, write)
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
112
|
+
`QueryCache.optimisticUpdate(queryKey, edit, write, options?)`. It runs
|
|
113
|
+
`write` and gives its result.
|
|
114
|
+
|
|
115
|
+
- **Layers.** Each pending write of a key is a layer of its `edit` over the
|
|
116
|
+
confirmed value, which is CI's value of the key. Views show the layers in
|
|
117
|
+
call order at once, so a second quick write shows while CI has not
|
|
118
|
+
answered the first. An entry without a value shows no edit until a fetch
|
|
119
|
+
gives it one.
|
|
120
|
+
- **Order.** The writes to one key go to CI one at a time, in call order.
|
|
121
|
+
When CI gets a write, the running fetch of the key is cancelled.
|
|
122
|
+
- **Fetches.** A fetch that ends while writes are pending, for example after
|
|
123
|
+
a realtime change or a window focus, updates the confirmed value, and the
|
|
124
|
+
layers show over it again. Thus an edit must give the same value for a
|
|
125
|
+
value that already holds it: set fields, or replace or remove a row by its
|
|
126
|
+
id. To add a row, skip the add when the row is there.
|
|
127
|
+
- **Send-time payload.** Give `write` as a function to build the payload when
|
|
128
|
+
CI gets the write. It gets `{ confirmed, optimistic }`: the confirmed value
|
|
129
|
+
with the answers of the writes before it, and that value with this edit
|
|
130
|
+
only. A refused write before it is not in either value.
|
|
131
|
+
- **Answer.** When CI confirms the write, its layer goes, and the confirmed
|
|
132
|
+
value becomes `options.confirm(result, confirmed)`, for example CI's row
|
|
133
|
+
with its new revision. Without `confirm`, or when it gives `undefined`, the
|
|
134
|
+
confirmed value gets the edit. When `write` fails, is interrupted or dies,
|
|
135
|
+
only its own layer goes; the other layers show over the confirmed value.
|
|
136
|
+
When `confirm` throws, the write dies with its error, the confirmed value
|
|
137
|
+
stays, and its layer still goes. When the write ends, the key is
|
|
138
|
+
invalidated, so views read CI's value.
|
|
139
|
+
- **Other members.** A value that `setData`, `update` or `remove` puts while
|
|
140
|
+
writes are pending stays. The edits before it no longer show or roll back,
|
|
141
|
+
and their `confirm` does not run, so an older answer of CI never replaces
|
|
142
|
+
the newer value.
|
|
143
|
+
- **Runs.** Each run of the effect that `optimisticUpdate` returns is one
|
|
144
|
+
write with its own layer, so an actor can run one save effect twice.
|
|
145
|
+
- **Pending.** `pending(queryKey)` gives the number of optimistic writes of
|
|
146
|
+
the key that wait for CI or run, for example to show "Saving…".
|
|
147
|
+
|
|
148
|
+
The writes of one key share their layers across every `QueryCache` over the
|
|
149
|
+
same QueryClient. The QueryClient holds them, so two bundled copies of the
|
|
150
|
+
SDK over it, such as the app's and a library's, also share them. Copies of
|
|
151
|
+
releases with another layout of these writes keep their own. A write that changes several keys does the steps itself:
|
|
152
|
+
`cancel` the keys, `update` them, run the write, and `invalidate` the keys
|
|
153
|
+
when the actor ends.
|
|
121
154
|
|
|
122
155
|
```ts
|
|
123
|
-
|
|
156
|
+
type Task = Readonly<{
|
|
157
|
+
done: boolean
|
|
158
|
+
id: string
|
|
159
|
+
revision: string
|
|
160
|
+
title: string
|
|
161
|
+
}>
|
|
162
|
+
const tasksKey = ["portal", "tasks"]
|
|
163
|
+
|
|
164
|
+
const saveTask = fromEffect(
|
|
124
165
|
(
|
|
125
166
|
input: Readonly<{
|
|
126
|
-
|
|
167
|
+
patch: Partial<Pick<Task, "done" | "title">>
|
|
127
168
|
id: string
|
|
128
169
|
runtime: EffectRunner<QueryCache>
|
|
129
170
|
}>
|
|
130
171
|
) =>
|
|
131
172
|
QueryCache.use((cache) =>
|
|
132
|
-
// An entry without a value stays without one: `edit` gets a cached lead.
|
|
133
173
|
cache.optimisticUpdate(
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
174
|
+
tasksKey,
|
|
175
|
+
// Replaces the row by its id, so a fetch under the layer keeps it.
|
|
176
|
+
(tasks: readonly Task[]) =>
|
|
177
|
+
tasks.map((task) =>
|
|
178
|
+
task.id === input.id ? { ...task, ...input.patch } : task
|
|
179
|
+
),
|
|
180
|
+
// Built when CI gets the save: the revision of the save before it,
|
|
181
|
+
// and no change of a refused save.
|
|
182
|
+
({ optimistic }) => {
|
|
183
|
+
const task = optimistic?.find(({ id }) => id === input.id)
|
|
184
|
+
return task === undefined
|
|
185
|
+
? Effect.die("no task")
|
|
186
|
+
: writeTask(input.id, {
|
|
187
|
+
done: task.done,
|
|
188
|
+
revision: task.revision,
|
|
189
|
+
title: task.title
|
|
190
|
+
})
|
|
191
|
+
},
|
|
192
|
+
// `writeTask` answers CI's row with its new revision.
|
|
193
|
+
{
|
|
194
|
+
confirm: (row: Task, confirmed) =>
|
|
195
|
+
confirmed?.map((task) => (task.id === row.id ? row : task))
|
|
196
|
+
}
|
|
137
197
|
)
|
|
138
198
|
)
|
|
139
199
|
)
|
|
200
|
+
|
|
201
|
+
const savingTasks = fromEffect(
|
|
202
|
+
(input: Readonly<{ runtime: EffectRunner<QueryCache> }>) =>
|
|
203
|
+
QueryCache.use((cache) => cache.pending(tasksKey))
|
|
204
|
+
)
|
|
140
205
|
```
|
|
141
206
|
|
|
207
|
+
A `write` given as an Effect works as before: it is the same for each
|
|
208
|
+
confirmed value.
|
|
209
|
+
|
|
142
210
|
## Rules
|
|
143
211
|
|
|
144
212
|
- Make each side-effect actor with `fromEffect`. The
|
package/docs/guide/ai/index.md
CHANGED
|
@@ -224,9 +224,11 @@ Your server invokes an Agent with `agents.invoke({ agentId, input })`, which ret
|
|
|
224
224
|
|
|
225
225
|
`runs.stream` returns three kinds of event. `agent.tool` gives the tool name and its state (running, completed or failed) without arguments or results. `agent.reasoning` gives the provider's reasoning-summary text in batches, and `agent.context` gives input and output token counts for each model step. A page holds at most 100 events, so keep polling with the last cursor. Filter the reasoning text on your server before you show it to visitors.
|
|
226
226
|
|
|
227
|
-
For a multi-turn chat,
|
|
227
|
+
For a multi-turn chat, use the shared chat. Start a Conversation with the Agent with `ci.chat.createConversation({ organizationId, payload: { agentId } })`, send each message with `createChatClient(ci, { organizationId }).send({ conversationId, message })` from `@collective-intelligence/external-apps-server-sdk/chat`, and read earlier turns with `ci.chat.getTranscript`. Each turn is an ordinary Agent run, and the earlier successful turns, with their saved Agent Output, become the model's conversation history. A message sent while a turn still runs steers that turn and starts no second turn, and a resend with the same message `id` adds nothing.
|
|
228
228
|
|
|
229
|
-
|
|
229
|
+
`send` resolves `{ ok: true, value, runId }`: `runId` is the id of the turn's run, which the answer message also carries as `metadata.invocationId`, and `turnRunId(message)` reads it from any answer message. `runs.get`, `runs.sources` and `runs.feedback` accept that id like the `runId` of `agents.invoke`. They answer only the caller that owns the Conversation (the member, the app server or the visitor) through the application where the Conversation started, and answer `not_found` to every other caller. As for any run, only a signed-in member reads `runs.sources` and gives `runs.feedback`. `runs.get` gives the status and `result: { message, output? }`, where `output` is the Agent Output that the turn saved. `runs.feedback` also rates a succeeded turn whose answer is only its Agent Output, with the Output's JSON text as the rated answer; a turn with neither text nor Output has no answer to rate and gets `not_found`. `runs.sources` gives the searched Document Versions with their pages and a download link. `runs.stream` and `runs.cancel` read only runs that `agents.invoke` started: follow a turn with `GET /runs/:runId/stream` of the chat mount, and stop it with `ci.chat.cancelTurn`.
|
|
230
|
+
|
|
231
|
+
Anonymous visitors can chat with an Agent only when its audience has `anonymous: [app]` for that application and the call passes `caller: { kind: "anonymous_visitor", visitor: { issuer, subjectId } }`. Their turns run with the Agent's own bindings, never with the application's grants, and visitors never see each other's conversations.
|
|
230
232
|
|
|
231
233
|
## Workflows
|
|
232
234
|
|
package/docs/guide/ai/studio.md
CHANGED
|
@@ -228,7 +228,7 @@ Workflows and agents can start from either side:
|
|
|
228
228
|
| Primitive | From the web app | From Studio |
|
|
229
229
|
| --------- | ----------------------------------------------------------------------------- | ------------------------------------------- |
|
|
230
230
|
| Workflow | An External application trigger, started by the server's Fixed workflow route | An On-demand trigger with a trigger form |
|
|
231
|
-
| Agent | `agents.invoke` or
|
|
231
|
+
| Agent | `agents.invoke` or a shared-chat Conversation from the app server | The Agents and Chat pages, or an agent form |
|
|
232
232
|
| Audience | `applications: [application]` | `groups`, `profiles` or `organization` |
|
|
233
233
|
|
|
234
234
|
A trigger form needs a trigger that people start, so an External application trigger cannot back it. One workflow can declare both triggers when the same work must start from both sides. The template's convert-lead workflow has only the External application trigger.
|
package/docs/realtime.md
CHANGED
|
@@ -3,7 +3,9 @@
|
|
|
3
3
|
`RealtimeProvider` takes the options of `createRealtimeClient` of
|
|
4
4
|
`external-apps-client-sdk` as props. It makes one client, and so one
|
|
5
5
|
connection, for its tree, and closes it on unmount. A server render makes no
|
|
6
|
-
client; a Strict Mode double mount opens one stream.
|
|
6
|
+
client; a Strict Mode double mount opens one stream. Import both from
|
|
7
|
+
`external-apps-client-sdk-react/realtime`: the root entry also bundles the
|
|
8
|
+
sign-in, agent prompt and entity UI.
|
|
7
9
|
|
|
8
10
|
```tsx
|
|
9
11
|
const AppRealtime = ({ children }: { children: ReactNode }) => {
|
|
@@ -33,7 +35,13 @@ const LeadBoard = () => {
|
|
|
33
35
|
## Rules
|
|
34
36
|
|
|
35
37
|
- Pass `onReset` and refetch every realtime-driven query in it. Without it,
|
|
36
|
-
the client cannot recover from a gap, and a change can be lost.
|
|
38
|
+
the client cannot recover from a gap, and a change can be lost. Its
|
|
39
|
+
`reason` (`"initial"`, `"gap"`, `"server"`) is for logs and metrics; every
|
|
40
|
+
reason means refetch. A first open that the server confirms with `resumed`
|
|
41
|
+
calls no `onReset`.
|
|
42
|
+
- `startedAt` (default `performance.timeOrigin`) is when the page started to
|
|
43
|
+
read its data. A page that shows cached data read before its navigation
|
|
44
|
+
passes `performance.timeOrigin - ageMs`; never a server timestamp.
|
|
37
45
|
- `useRealtimeTopic(topic, onChanges)` subscribes while the component is
|
|
38
46
|
mounted. A new object for the same topic keeps the subscription; `null`
|
|
39
47
|
subscribes to nothing. The latest `onChanges` runs, with no resubscribe.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@collective-intelligence/external-apps-client-sdk-react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.1",
|
|
4
4
|
"description": "React bindings for Collective Intelligence external applications.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -31,6 +31,12 @@
|
|
|
31
31
|
"types": "./dist/effect.d.ts",
|
|
32
32
|
"import": "./dist/effect.js",
|
|
33
33
|
"default": "./dist/effect.js"
|
|
34
|
+
},
|
|
35
|
+
"./realtime": {
|
|
36
|
+
"ci-source": "./src/realtime.ts",
|
|
37
|
+
"types": "./dist/realtime.d.ts",
|
|
38
|
+
"import": "./dist/realtime.js",
|
|
39
|
+
"default": "./dist/realtime.js"
|
|
34
40
|
}
|
|
35
41
|
},
|
|
36
42
|
"scripts": {
|
|
@@ -48,12 +54,12 @@
|
|
|
48
54
|
"type-check": "bun check --no-script -p tsconfig.json"
|
|
49
55
|
},
|
|
50
56
|
"dependencies": {
|
|
51
|
-
"@collective-intelligence/effect-xstate": "0.
|
|
52
|
-
"@collective-intelligence/external-apps-client-sdk": "0.
|
|
57
|
+
"@collective-intelligence/effect-xstate": "0.9.1",
|
|
58
|
+
"@collective-intelligence/external-apps-client-sdk": "0.9.1",
|
|
53
59
|
"nuqs": "2.10.1"
|
|
54
60
|
},
|
|
55
61
|
"peerDependencies": {
|
|
56
|
-
"@collective-intelligence/ui-react": "0.
|
|
62
|
+
"@collective-intelligence/ui-react": "0.9.1",
|
|
57
63
|
"@tanstack/react-query": "^5.101.4",
|
|
58
64
|
"effect": "^4.1.0",
|
|
59
65
|
"react": ">=18.2 <20",
|
|
@@ -64,7 +70,7 @@
|
|
|
64
70
|
"access": "public"
|
|
65
71
|
},
|
|
66
72
|
"devDependencies": {
|
|
67
|
-
"@collective-intelligence/ui-react": "0.
|
|
73
|
+
"@collective-intelligence/ui-react": "0.9.1",
|
|
68
74
|
"@effect/eslint-plugin": "0.3.2",
|
|
69
75
|
"@oxlint/plugins": "1.94.0",
|
|
70
76
|
"@punks/lints": "0.2.0",
|
|
@@ -93,5 +99,5 @@
|
|
|
93
99
|
"vitest": "4.1.10",
|
|
94
100
|
"xstate": "5.33.3"
|
|
95
101
|
},
|
|
96
|
-
"gitHead": "
|
|
102
|
+
"gitHead": "31d4f895460d3b7dbc111d97034124364d78d900"
|
|
97
103
|
}
|