@collective-intelligence/external-apps-client-sdk-react 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 CHANGED
@@ -1,8 +1,9 @@
1
1
  # `@collective-intelligence/external-apps-client-sdk-react`: agent guide
2
2
 
3
3
  React bindings of Collective Intelligence (CI) external applications: the
4
- provider, entity hooks with Optimistic Writes, declared entity views, realtime
5
- hooks, and the Effect bridge for XState machines. The package `README.md`
4
+ provider, Embedded Sign-In components, entity hooks with Optimistic Writes,
5
+ declared entity views, realtime hooks, and the Effect bridge for XState
6
+ machines. The package `README.md`
6
7
  holds the full API.
7
8
 
8
9
  ## Rules
@@ -34,6 +35,10 @@ holds the full API.
34
35
  `ciWriteFailedToast()` of `@collective-intelligence/ui-react/ui`.
35
36
  - Give `RealtimeProvider` an `onReset` that refetches every realtime-driven
36
37
  query.
38
+ - For a sign-in form in the app, give `CollectiveIntelligenceLoginProvider`
39
+ the auth of `createServerSessionAuth` and render `<SignInCard>`, or the
40
+ `SignIn.*` parts, or read `useSignIn()` inside `SignIn.Root`. Do not build
41
+ the step state yourself.
37
42
 
38
43
  ## Index
39
44
 
@@ -41,6 +46,8 @@ holds the full API.
41
46
  that calls CI, or connect Effect code to the QueryClient.
42
47
  - [docs/realtime.md](docs/realtime.md): read when a view must follow changes
43
48
  of a Realtime Topic.
49
+ - [docs/sign-in.md](docs/sign-in.md): read when the app shows its own
50
+ sign-in or registration form.
44
51
  - [docs/errors.md](docs/errors.md): read when you handle a failed entity read
45
52
  or write, or an Optimistic Write goes back.
46
53
  - [skills/client-sdk-react-move-to-effect/SKILL.md](skills/client-sdk-react-move-to-effect/SKILL.md):
package/README.md CHANGED
@@ -66,6 +66,53 @@ The old public TanStack option factories and native-result resource hooks are no
66
66
  Use the deliberate entity hooks above. Existing generic slotted `Resource*` presentation remains
67
67
  separate from common entity CRUD.
68
68
 
69
+ ## Embedded Sign-In
70
+
71
+ The app shows its own sign-in and registration form, and the browser calls
72
+ only the app server. Give `CollectiveIntelligenceLoginProvider` the auth of
73
+ `createServerSessionAuth` of the client SDK; its `auth.signIn` steps go to the
74
+ sign-in routes of the server SDK. The auth of `createFederatedAuth` has no
75
+ `signIn`, and the sign-in components throw with it.
76
+
77
+ ```tsx
78
+ const auth = createServerSessionAuth({ basePath: "/api/auth" })
79
+
80
+ ;<CollectiveIntelligenceLoginProvider auth={auth} client={client}>
81
+ <SignInCard onSignedIn={() => navigate({ to: "/" })} />
82
+ </CollectiveIntelligenceLoginProvider>
83
+ ```
84
+
85
+ - `<SignInCard>` shows each step in `ui-react` components: email, code, name
86
+ of a new person, SSO buttons, a "Sign in with password" button when the app
87
+ allows a password (it opens the CI page), the refusal of the last call and
88
+ the end of the sign-in.
89
+ - `<SignIn.Root>` holds the state. The parts `SignIn.EmailForm`,
90
+ `SignIn.CodeForm`, `SignIn.NameForm`, `SignIn.SsoButtons`,
91
+ `SignIn.PasswordButton`, `SignIn.Notice` and `SignIn.Status` read it from
92
+ context, and each shows only at its step. `useSignIn()` inside
93
+ `SignIn.Root` gives `state`, `pending` and the actions `start(email)`,
94
+ `verify(code)`, `complete(name)`, `sso(provider)` and `password()`.
95
+ - `SignIn.Root` calls `auth.signIn.methods()` when it mounts. The answer sets
96
+ the SSO buttons and the password button. When the app allows only a
97
+ password, it is `redirect_to_web`, and the SDK opens the CI page.
98
+ - `onSignedIn` runs on the `signed_in` step. `onRegistered` runs before it
99
+ when the step has `registered: true`. `onError` gets `CiTransportError`
100
+ (the call got no step) or `FederatedAuthError` (the SDK could not
101
+ navigate); the form keeps its values. A refusal, such as a wrong code, is a
102
+ step: `SignIn.Notice` shows it.
103
+ - `labels` replaces any default text (`SignInLabels`). `className` goes on
104
+ the card and on each part. `components` replaces `EmailField`, `CodeField`,
105
+ `NameField` or `Button`; a field slot gets input props and renders one
106
+ input with them, as the form reads the value by `name`. The default code
107
+ field has six slots, as CI codes have six digits. `returnTo` is the page
108
+ that the CI page returns to, and `uiLocales` the languages of the emails.
109
+ - `pending` is true from an action until its call settles, on React 18 and
110
+ 19; the parts disable their buttons and set `aria-busy` while it is true.
111
+ An action while a call runs does nothing, so a double submit sends one
112
+ call. The SDK sends the calls of one client one at a time.
113
+ - The sign-in components import `@collective-intelligence/ui-react/ui`, so the
114
+ application installs `react-hook-form`, a required peer of `ui-react`.
115
+
69
116
  ## Optimistic Writes
70
117
 
71
118
  Entity writes are Optimistic Writes. The value is in the QueryClient cache, so every view that
package/dist/index.d.ts CHANGED
@@ -1,14 +1,14 @@
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, 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, 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
- 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, ResourceRecordId, ResourceRequestOptions, ResourceResult, ResourceRevision, ResourceSort } from '@collective-intelligence/external-apps-client-sdk/resources';
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';
7
7
  import { QueryClient } from '@tanstack/react-query';
8
8
  import * as Context from 'effect/Context';
9
9
  import * as Effect from 'effect/Effect';
10
10
  import * as Layer from 'effect/Layer';
11
- import { CSSProperties, ElementType, ReactNode } from 'react';
11
+ import { CSSProperties, ComponentProps, ComponentType, ElementType, ReactNode } from 'react';
12
12
 
13
13
  export type PromptKeyEvent = Readonly<{
14
14
  isComposing: boolean;
@@ -153,11 +153,12 @@ export declare const useRuns: (organizationId: string) => Organization["runs"];
153
153
  export declare const useAttachments: (organizationId: string) => Organization["attachments"];
154
154
  export declare const useClientContext: (organizationId: string) => Organization["context"];
155
155
  export type AuthContextValue = Readonly<{
156
- auth: FederatedAuth;
156
+ auth: FederatedAuth | ServerSessionAuth;
157
157
  state: FederatedAuthState;
158
158
  }>;
159
+ /** `auth` of `createServerSessionAuth` also gives `useSignIn` and the `SignIn` components. */
159
160
  export type CollectiveIntelligenceLoginProviderProps = Readonly<{
160
- auth: FederatedAuth;
161
+ auth: FederatedAuth | ServerSessionAuth;
161
162
  } & CollectiveIntelligenceProviderProps>;
162
163
  export declare const CollectiveIntelligenceLoginProvider: (props: CollectiveIntelligenceLoginProviderProps) => import("react").JSX.Element;
163
164
  export type CollectiveIntelligenceAuthBinding = AuthContextValue & Readonly<{
@@ -204,6 +205,124 @@ export type SessionGateProps = Readonly<{
204
205
  export declare const useSession: () => FederatedAuthState;
205
206
  /** Renders children only when the BFF sealed-cookie session is authenticated. */
206
207
  export declare const SessionGate: ({ children, fallback }: SessionGateProps) => ReactNode;
208
+ /** The methods that the app allows, from the `methods` step. */
209
+ export type SignInMethods = Omit<Extract<SignInStep, Readonly<{
210
+ step: "methods";
211
+ }>>, "step">;
212
+ /** A refusal that the current form shows; the person can try again. */
213
+ export type SignInNotice = Extract<SignInStep, Readonly<{
214
+ step: "email_domain_not_allowed" | "invalid_code" | "retry_after";
215
+ }>> | Readonly<{
216
+ step: "access_denied" | "code_expired";
217
+ }>;
218
+ /**
219
+ * The state of one Embedded Sign-In. `stage` names the form or the end that
220
+ * the components show; `email` is the address of the challenge, for a
221
+ * resend; `methods` is `null` until the `methods` step.
222
+ */
223
+ export type SignInState = Readonly<{
224
+ email: string;
225
+ methods: SignInMethods | null;
226
+ notice: SignInNotice | null;
227
+ }> & (Readonly<{
228
+ stage: "code" | "email" | "name";
229
+ }> | Readonly<{
230
+ stage: "no_sign_in_method" | "redirect_to_web";
231
+ }> | Readonly<{
232
+ registered: boolean;
233
+ stage: "signed_in";
234
+ }> | Readonly<{
235
+ provider: SignInMethods["ssoProviders"][number];
236
+ stage: "sso_required";
237
+ }>);
238
+ /** A fault of a sign-in call: it gave no step, or the SDK could not navigate. */
239
+ export type SignInError = CiTransportError | FederatedAuthError;
240
+ /** The texts of the sign-in components; `labels` replaces any of them. */
241
+ export type SignInLabels = Readonly<{
242
+ accessDenied: string;
243
+ code: string;
244
+ codeExpired: string;
245
+ codeSentTo: (email: string) => string;
246
+ codeSubmit: string;
247
+ email: string;
248
+ emailDomainNotAllowed: (allowedDomains: readonly string[]) => string;
249
+ emailSubmit: string;
250
+ invalidCode: (attemptsLeft: number) => string;
251
+ name: string;
252
+ nameSubmit: string;
253
+ noSignInMethod: string;
254
+ password: string;
255
+ redirecting: string;
256
+ resendCode: string;
257
+ retryAfter: (seconds: number) => string;
258
+ signedIn: string;
259
+ sso: (provider: string) => string;
260
+ ssoRequired: (provider: string) => string;
261
+ title: string;
262
+ }>;
263
+ /** The props that a field slot gets; it renders one input with them. */
264
+ export type SignInFieldProps = Readonly<Pick<ComponentProps<"input">, "aria-describedby" | "autoComplete" | "defaultValue" | "id" | "maxLength" | "name" | "required" | "type">>;
265
+ /** Components that replace the default parts of the sign-in components. */
266
+ export type SignInComponents = Readonly<{
267
+ Button?: ComponentType<ComponentProps<"button">>;
268
+ CodeField?: ComponentType<SignInFieldProps>;
269
+ EmailField?: ComponentType<SignInFieldProps>;
270
+ NameField?: ComponentType<SignInFieldProps>;
271
+ }>;
272
+ /**
273
+ * The state and the actions of one Embedded Sign-In. Each action runs one
274
+ * `auth.signIn` call: `pending` is true from the action until the call
275
+ * settles, on React 18 and 19. An action while a call runs does nothing.
276
+ */
277
+ export type SignInBinding = Readonly<{
278
+ complete: (name: string) => void;
279
+ /** Continues on the CI page, where the person signs in with a password. */
280
+ password: () => void;
281
+ pending: boolean;
282
+ sso: (provider: string) => void;
283
+ start: (email: string) => void;
284
+ state: SignInState;
285
+ verify: (code: string) => void;
286
+ }>;
287
+ export type SignInRootProps = Readonly<{
288
+ children: ReactNode;
289
+ components?: SignInComponents;
290
+ labels?: Partial<SignInLabels>;
291
+ /** A call that failed: the form stays as it was. */
292
+ onError?: (error: SignInError) => void;
293
+ /** The sign-in made a new person a Guest of the app; `onSignedIn` follows. */
294
+ onRegistered?: () => void;
295
+ onSignedIn?: () => void;
296
+ /** The page that the CI page returns to; `/` when absent. */
297
+ returnTo?: string;
298
+ /** The languages of the person (`ui_locales`) for the emails of CI. */
299
+ uiLocales?: string;
300
+ }>;
301
+ /** The state and the actions of the nearest `SignIn.Root`. */
302
+ export declare const useSignIn: () => SignInBinding;
303
+ /** The props of each `SignIn` part but `Root`. */
304
+ export type SignInPartProps = Readonly<{
305
+ className?: string;
306
+ }>;
307
+ /**
308
+ * The parts of Embedded Sign-In. `Root` holds the state; each other part
309
+ * reads it from context and shows only at its step.
310
+ */
311
+ export declare const SignIn: {
312
+ CodeForm: ({ className }: SignInPartProps) => import("react").JSX.Element | null;
313
+ EmailForm: ({ className }: SignInPartProps) => import("react").JSX.Element | null;
314
+ NameForm: ({ className }: SignInPartProps) => import("react").JSX.Element | null;
315
+ Notice: ({ className }: SignInPartProps) => import("react").JSX.Element | null;
316
+ PasswordButton: ({ className }: SignInPartProps) => import("react").JSX.Element | null;
317
+ Root: ({ children, components, labels, ...options }: SignInRootProps) => import("react").JSX.Element;
318
+ SsoButtons: ({ className }: SignInPartProps) => import("react").JSX.Element | null;
319
+ Status: ({ className }: SignInPartProps) => import("react").JSX.Element | null;
320
+ };
321
+ export type SignInCardProps = Omit<SignInRootProps, "children"> & Readonly<{
322
+ className?: string;
323
+ }>;
324
+ /** Drop-in Embedded Sign-In: every `SignIn` part in a `ui-react` card. */
325
+ export declare const SignInCard: ({ className, ...rootProps }: SignInCardProps) => import("react").JSX.Element;
207
326
  export type RealtimeProviderProps = Readonly<RealtimeClientOptions & {
208
327
  children: ReactNode;
209
328
  }>;
@@ -395,6 +514,7 @@ export {
395
514
  ResourcePagination,
396
515
  ResourcePaginationMode,
397
516
  ResourceRecord,
517
+ ResourceRecordAccess,
398
518
  ResourceRecordId,
399
519
  ResourceRequestOptions,
400
520
  ResourceResult,
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-0fbftb7q.js";import"./index-e0z6c7w9.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{createRealtimeClient}from"@collective-intelligence/external-apps-client-sdk";import{createContext as createContext3,useContext as useContext3,useEffect as useEffect2,useState as useState3}from"react";import{jsx as jsx4}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=createContext3(null);var RealtimeProvider=({children,...options})=>{const[shared]=useState3(()=>shareClient(options));useEffect2(()=>{shared.update(options)});useEffect2(()=>{shared.acquire();return shared.release},[shared]);return jsx4(RealtimeContext.Provider,{value:shared,children})};var useRealtimeClient=()=>{const client=useContext3(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 useEffect3,useRef as useRef2,useState as useState4}from"react";var useRealtimeTopic=(topic,onChanges)=>{const client=useRealtimeClient();const latest=useRef2(onChanges);const key=topic===null?null:realtimeTopicKey(topic);const[subscribed,setSubscribed]=useState4({key,topic});if(subscribed.key!==key){setSubscribed({key,topic})}useEffect3(()=>{latest.current=onChanges});useEffect3(()=>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,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,useSkills,useWorkflows};
2
+ import{EntityRuntimeProvider,createDelegatedEntitySource2,defineEntity2,useEntityViewState2,useMemoryEntityViewState2,EntityTable2,EntityList2,EntityForm2}from"./index-0fbftb7q.js";import"./index-e0z6c7w9.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"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",emailDomainNotAllowed:(allowedDomains)=>`Use an address of ${allowedDomains.join(", ")}.`,emailSubmit:"Send code",invalidCode:(attemptsLeft)=>`The code is not correct. Attempts left: ${attemptsLeft}.`,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,Label}from"@collective-intelligence/ui-react/ui";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 Labeled=({children,id,label})=>jsxs2("div",{className:"grid gap-2",children:[jsx5(Label,{htmlFor:id,children:label}),children]});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;return jsxs2("form",{"aria-busy":binding.pending,className:cn("grid gap-4",className),onSubmit:(event)=>{binding.start(submitted(event,"email"))},children:[jsx5(Labeled,{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:labels.emailSubmit})]})};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(Labeled,{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(Labeled,{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"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};
@@ -1,7 +1,7 @@
1
1
  // Generated by dts-bundle-generator v9.5.1
2
2
 
3
3
  import { ClientFetch, FederatedAuthErrorCode, FederatedAuthState, FederatedSessionIdentity, RealtimeChange } from '@collective-intelligence/external-apps-client-sdk';
4
- import { EntityClient, EntityCreateInput, EntityDeleteInput, EntityListQuery, EntityMemberValue, EntityPage, EntityUpdateInput, EntityUploadInput, EntityUploadSlot, IdempotencyKey, PortableResourceSchema, ResourceCapabilities, ResourceClient, ResourceCreateInput, ResourceCursor, ResourceDefinition, ResourceError, ResourceErrorCode, ResourceFilter, ResourceId, ResourceIdentityField, ResourceJsonValue, ResourceLifecycleInput, ResourceListQuery, ResourceListResult, ResourceMutationInput, ResourcePaginationMode, ResourceRecord, ResourceRecordId, ResourceRequestOptions, ResourceResult, ResourceRevision, ResourceSort } from '@collective-intelligence/external-apps-client-sdk/resources';
4
+ import { EntityClient, EntityCreateInput, EntityDeleteInput, EntityListQuery, EntityMemberValue, EntityPage, EntityUpdateInput, EntityUploadInput, EntityUploadSlot, IdempotencyKey, PortableResourceSchema, ResourceCapabilities, ResourceClient, ResourceCreateInput, ResourceCursor, ResourceDefinition, ResourceError, ResourceErrorCode, ResourceFilter, ResourceId, ResourceIdentityField, ResourceJsonValue, ResourceLifecycleInput, ResourceListQuery, ResourceListResult, ResourceMutationInput, ResourcePaginationMode, ResourceRecord, ResourceRecordAccess, ResourceRecordId, ResourceRequestOptions, ResourceResult, ResourceRevision, ResourceSort } from '@collective-intelligence/external-apps-client-sdk/resources';
5
5
  import { ResourceField, ResourceFieldControlProps, ResourceObject, ResourceValue } from '@collective-intelligence/ui-react/resources';
6
6
  import * as Context from 'effect/Context';
7
7
  import * as Effect from 'effect/Effect';
@@ -224,6 +224,10 @@ export declare const useEntityRecord: <Value, Create, Patch>(contract: ResourceD
224
224
  upload?: boolean;
225
225
  }>;
226
226
  data: NoInfer<Readonly<{
227
+ access?: Readonly<{
228
+ writableFields: readonly string[];
229
+ write: boolean;
230
+ }> | undefined;
227
231
  deletedAt?: string;
228
232
  id: import("@collective-intelligence/external-apps-client-sdk").ResourceRecordId;
229
233
  included?: Readonly<Record<string, import("@collective-intelligence/external-apps-client-sdk").ResourceJsonValue>>;
@@ -242,6 +246,10 @@ export declare const useEntityUpdate: <Value, Create, Patch>(contract: ResourceD
242
246
  }>) => {
243
247
  available: boolean;
244
248
  data: Readonly<{
249
+ access?: Readonly<{
250
+ writableFields: readonly string[];
251
+ write: boolean;
252
+ }> | undefined;
245
253
  deletedAt?: string;
246
254
  id: import("@collective-intelligence/external-apps-client-sdk").ResourceRecordId;
247
255
  included?: Readonly<Record<string, import("@collective-intelligence/external-apps-client-sdk").ResourceJsonValue>>;
@@ -252,6 +260,10 @@ export declare const useEntityUpdate: <Value, Create, Patch>(contract: ResourceD
252
260
  error: ResourceQueryError | null;
253
261
  pending: boolean;
254
262
  resubmit: () => Promise<ResourceResult<Readonly<{
263
+ access?: Readonly<{
264
+ writableFields: readonly string[];
265
+ write: boolean;
266
+ }> | undefined;
255
267
  deletedAt?: string;
256
268
  id: import("@collective-intelligence/external-apps-client-sdk").ResourceRecordId;
257
269
  included?: Readonly<Record<string, import("@collective-intelligence/external-apps-client-sdk").ResourceJsonValue>>;
@@ -261,6 +273,10 @@ export declare const useEntityUpdate: <Value, Create, Patch>(contract: ResourceD
261
273
  }>>>;
262
274
  status: "pending" | "success" | "idle" | "conflict" | "rejected" | "uncertain";
263
275
  submit: (input: Omit<EntityUpdateInput<Patch>, "id" | "idempotencyKey">) => Promise<ResourceResult<Readonly<{
276
+ access?: Readonly<{
277
+ writableFields: readonly string[];
278
+ write: boolean;
279
+ }> | undefined;
264
280
  deletedAt?: string;
265
281
  id: import("@collective-intelligence/external-apps-client-sdk").ResourceRecordId;
266
282
  included?: Readonly<Record<string, import("@collective-intelligence/external-apps-client-sdk").ResourceJsonValue>>;
@@ -273,6 +289,10 @@ export declare const useEntityUpdate: <Value, Create, Patch>(contract: ResourceD
273
289
  export declare const useEntityCreate: <Value, Create, Patch>(contract: ResourceDefinition<Value, Create, Patch>) => {
274
290
  available: boolean;
275
291
  data: Readonly<{
292
+ access?: Readonly<{
293
+ writableFields: readonly string[];
294
+ write: boolean;
295
+ }> | undefined;
276
296
  deletedAt?: string;
277
297
  id: import("@collective-intelligence/external-apps-client-sdk").ResourceRecordId;
278
298
  included?: Readonly<Record<string, import("@collective-intelligence/external-apps-client-sdk").ResourceJsonValue>>;
@@ -283,6 +303,10 @@ export declare const useEntityCreate: <Value, Create, Patch>(contract: ResourceD
283
303
  error: ResourceQueryError | null;
284
304
  pending: boolean;
285
305
  resubmit: () => Promise<ResourceResult<Readonly<{
306
+ access?: Readonly<{
307
+ writableFields: readonly string[];
308
+ write: boolean;
309
+ }> | undefined;
286
310
  deletedAt?: string;
287
311
  id: import("@collective-intelligence/external-apps-client-sdk").ResourceRecordId;
288
312
  included?: Readonly<Record<string, import("@collective-intelligence/external-apps-client-sdk").ResourceJsonValue>>;
@@ -295,6 +319,10 @@ export declare const useEntityCreate: <Value, Create, Patch>(contract: ResourceD
295
319
  idempotencyKey: import("@collective-intelligence/external-apps-client-sdk").IdempotencyKey;
296
320
  value: Create;
297
321
  }>, "idempotencyKey">) => Promise<ResourceResult<Readonly<{
322
+ access?: Readonly<{
323
+ writableFields: readonly string[];
324
+ write: boolean;
325
+ }> | undefined;
298
326
  deletedAt?: string;
299
327
  id: import("@collective-intelligence/external-apps-client-sdk").ResourceRecordId;
300
328
  included?: Readonly<Record<string, import("@collective-intelligence/external-apps-client-sdk").ResourceJsonValue>>;
@@ -313,6 +341,10 @@ export declare const useEntityDelete: <Value, Create, Patch>(contract: ResourceD
313
341
  }>) => {
314
342
  available: boolean;
315
343
  data: Readonly<{
344
+ access?: Readonly<{
345
+ writableFields: readonly string[];
346
+ write: boolean;
347
+ }> | undefined;
316
348
  deletedAt?: string;
317
349
  id: import("@collective-intelligence/external-apps-client-sdk").ResourceRecordId;
318
350
  included?: Readonly<Record<string, import("@collective-intelligence/external-apps-client-sdk").ResourceJsonValue>>;
@@ -323,6 +355,10 @@ export declare const useEntityDelete: <Value, Create, Patch>(contract: ResourceD
323
355
  error: ResourceQueryError | null;
324
356
  pending: boolean;
325
357
  resubmit: () => Promise<ResourceResult<Readonly<{
358
+ access?: Readonly<{
359
+ writableFields: readonly string[];
360
+ write: boolean;
361
+ }> | undefined;
326
362
  deletedAt?: string;
327
363
  id: import("@collective-intelligence/external-apps-client-sdk").ResourceRecordId;
328
364
  included?: Readonly<Record<string, import("@collective-intelligence/external-apps-client-sdk").ResourceJsonValue>>;
@@ -332,6 +368,10 @@ export declare const useEntityDelete: <Value, Create, Patch>(contract: ResourceD
332
368
  }>>>;
333
369
  status: "pending" | "success" | "idle" | "conflict" | "rejected" | "uncertain";
334
370
  submit: (input: Omit<EntityDeleteInput, "id" | "idempotencyKey">) => Promise<ResourceResult<Readonly<{
371
+ access?: Readonly<{
372
+ writableFields: readonly string[];
373
+ write: boolean;
374
+ }> | undefined;
335
375
  deletedAt?: string;
336
376
  id: import("@collective-intelligence/external-apps-client-sdk").ResourceRecordId;
337
377
  included?: Readonly<Record<string, import("@collective-intelligence/external-apps-client-sdk").ResourceJsonValue>>;
@@ -479,6 +519,7 @@ export {
479
519
  ResourceObject,
480
520
  ResourcePaginationMode,
481
521
  ResourceRecord,
522
+ ResourceRecordAccess,
482
523
  ResourceRecordId,
483
524
  ResourceRequestOptions,
484
525
  ResourceResult,
@@ -77,7 +77,9 @@ ci login <api-url> --organization <organization-id>
77
77
  ci whoami
78
78
  ```
79
79
 
80
- `ci login` asks you to approve the device in the Dashboard and stores a 30-day CLI Session in your user profile. `ci upgrade` updates a global install.
80
+ `ci login` asks you to approve the device in the Dashboard and stores a 30-day CLI Session in your user profile. `ci upgrade` updates a global install. For a pipeline, `ci login <api-url> --pipeline-token --name <name> --expires <date|never>` issues a Pipeline Token instead: store it as `CI_MANAGEMENT_TOKEN` and pass `--organization`.
81
+
82
+ The Backend declares the oldest `ci` version it supports. Before a command that calls the Backend, a released `ci` reads this minimum from the discovery document. If `ci` is older, the command stops with `CliVersionUnsupportedError` and tells you to run `ci upgrade`.
81
83
 
82
84
  > **Note:** `ci login` needs the API URL. It reads the tenant's discovery document at
83
85
  > `/.well-known/ci-configuration` and rejects a Dashboard URL as "not a CI API
@@ -209,11 +211,12 @@ The Connect Studio link that the Dashboard shows only tells the Studio desktop a
209
211
 
210
212
  #### Held by pipelines and scripts
211
213
 
212
- | Credential | Type | Lifetime or rotation | Used for |
213
- | ------------------------------------------- | ------------------------------------------------------- | --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
214
- | API key | Opaque secret with the prefix `dpk_` | No expiry at creation; a rotation keeps the old secret 24 hours; a revocation ends both | Calls with a service principal's grants, cut to a Max Privileges template |
215
- | `CI_MANAGEMENT_TOKEN` | Environment variable with an API key or a session token | That of the token it holds | Unattended `ci` commands; an API key fixes the Organization |
216
- | Publisher credential (`CI_PUBLISHER_TOKEN`) | Opaque secret for one exact package name | Optional expiry; a revocation stops it at once | Publish and promote for that package only |
214
+ | Credential | Type | Lifetime or rotation | Used for |
215
+ | ------------------------------------------- | ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
216
+ | Pipeline Token | Opaque secret with the prefix `cpt_`; a session of a technical account | The end chosen when it is issued, or never; the account or a Tenant Admin revokes it | Unattended `ci` commands and calls as that account, such as `ci deploy` |
217
+ | API key | Opaque secret with the prefix `dpk_` | No expiry at creation; a rotation keeps the old secret 24 hours; a revocation ends both | Calls with a service principal's grants, cut to a Max Privileges template |
218
+ | `CI_MANAGEMENT_TOKEN` | Environment variable with a Pipeline Token, an API key or a session token | That of the token it holds | Unattended `ci` commands; an API key fixes the Organization |
219
+ | Publisher credential (`CI_PUBLISHER_TOKEN`) | Opaque secret for one exact package name | Optional expiry; a revocation stops it at once | Publish and promote for that package only |
217
220
 
218
221
  #### Held by your external app
219
222
 
@@ -0,0 +1,70 @@
1
+ # Embedded Sign-In
2
+
3
+ The app shows its own sign-in and registration form. The browser calls only
4
+ the app server: the sign-in routes of the server SDK at `<basePath>/sign-in/*`.
5
+ Give `CollectiveIntelligenceLoginProvider` the auth of
6
+ `createServerSessionAuth` of `external-apps-client-sdk`, then render
7
+ `<SignInCard>`.
8
+
9
+ ```tsx
10
+ const auth = createServerSessionAuth({ basePath: "/api/auth" })
11
+
12
+ const SignInPage = () => {
13
+ const navigate = useNavigate()
14
+ return (
15
+ <CollectiveIntelligenceLoginProvider auth={auth} client={client}>
16
+ <SignInCard
17
+ labels={{ title: "Sign in to Acme" }}
18
+ onError={reportSignInFault}
19
+ onSignedIn={() => navigate({ to: "/" })}
20
+ />
21
+ </CollectiveIntelligenceLoginProvider>
22
+ )
23
+ }
24
+ ```
25
+
26
+ For an own layout, compose the parts inside `SignIn.Root`. Each part reads the
27
+ state from context and shows only at its step:
28
+
29
+ ```tsx
30
+ <SignIn.Root onSignedIn={goHome}>
31
+ <SignIn.Notice />
32
+ <SignIn.EmailForm className="acme-form" />
33
+ <SignIn.CodeForm />
34
+ <SignIn.NameForm />
35
+ <SignIn.SsoButtons />
36
+ <SignIn.PasswordButton />
37
+ <SignIn.Status />
38
+ </SignIn.Root>
39
+ ```
40
+
41
+ For a fully own UI, read `useSignIn()` inside `SignIn.Root`: `state`,
42
+ `pending`, and the actions `start(email)`, `verify(code)`, `complete(name)`,
43
+ `sso(provider)` and `password()`. `state.stage` is `email`, `code`, `name`,
44
+ `sso_required`, `signed_in`, `redirect_to_web` or `no_sign_in_method`;
45
+ `state.notice` holds the refusal of the last call, such as `invalid_code`.
46
+
47
+ ## Rules
48
+
49
+ - `SignIn.Root` (and so `SignInCard`) calls `auth.signIn.methods()` when it
50
+ mounts; the SSO buttons and the password button follow its answer. Run each
51
+ later step through the actions of `useSignIn`, not through `auth.signIn`,
52
+ so the state follows every answer.
53
+ - `pending` is true from an action until its call settles, on React 18
54
+ and 19. An action while a call runs does nothing: show `pending` in an
55
+ own UI, and do not queue the next step.
56
+ - `onSignedIn` runs when a call answers `signed_in`; the session is then
57
+ `authenticated`. `onRegistered` runs before it when the step carries
58
+ `registered: true` (a new Guest).
59
+ - `onError` gets `CiTransportError` (the call got no step) or
60
+ `FederatedAuthError` (the SDK could not navigate). The form keeps its
61
+ values. A refusal such as a wrong code is no error: `SignIn.Notice` shows it.
62
+ - `labels` replaces any default text; some texts are functions, such as
63
+ `invalidCode(attemptsLeft)`. `className` goes on the card and on each part.
64
+ - `components` replaces `EmailField`, `CodeField`, `NameField` or `Button`. A
65
+ field slot gets input props (`id`, `name`, `autoComplete`, `required`, ...):
66
+ render one input with them, because the form reads the value by `name`.
67
+ - The auth of `createFederatedAuth` has no `signIn`: the sign-in components
68
+ throw with it. Use `LoginButton` for the CI page instead.
69
+ - The components import `@collective-intelligence/ui-react/ui`; install its
70
+ required peer `react-hook-form`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@collective-intelligence/external-apps-client-sdk-react",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "React bindings for Collective Intelligence external applications.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -48,11 +48,11 @@
48
48
  "type-check": "bun check --no-script -p tsconfig.json"
49
49
  },
50
50
  "dependencies": {
51
- "@collective-intelligence/external-apps-client-sdk": "0.5.0",
51
+ "@collective-intelligence/external-apps-client-sdk": "0.6.0",
52
52
  "nuqs": "2.10.1"
53
53
  },
54
54
  "peerDependencies": {
55
- "@collective-intelligence/ui-react": "0.5.0",
55
+ "@collective-intelligence/ui-react": "0.6.0",
56
56
  "@tanstack/react-query": "^5.101.4",
57
57
  "effect": "^4.1.0",
58
58
  "react": ">=18.2 <20",
@@ -63,7 +63,7 @@
63
63
  "access": "public"
64
64
  },
65
65
  "devDependencies": {
66
- "@collective-intelligence/ui-react": "0.5.0",
66
+ "@collective-intelligence/ui-react": "0.6.0",
67
67
  "@effect/eslint-plugin": "0.3.2",
68
68
  "@oxlint/plugins": "1.94.0",
69
69
  "@punks/lints": "0.2.0",
@@ -92,5 +92,5 @@
92
92
  "vitest": "4.1.10",
93
93
  "xstate": "5.33.3"
94
94
  },
95
- "gitHead": "a8245252c396252c381dafd86a4fcb31af310906"
95
+ "gitHead": "94535cc59ece904d4a9374a368edb09222688bb6"
96
96
  }