@collective-intelligence/external-apps-client-sdk 0.3.5 → 0.3.7

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
@@ -29,6 +29,9 @@ package `README.md` holds the full API.
29
29
  services, layers, `Config`, realtime streams.
30
30
  - [docs/errors.md](docs/errors.md): read when you handle a failed CI call or
31
31
  sign-in.
32
+ - [docs/chat.md](docs/chat.md): read when you call the External App chat
33
+ (`client.chat`, `Chat`), follow a presentation stream, show a chat
34
+ refusal, or show the shared chat UI (`createChatTransport` at `/chat`).
32
35
  - [skills/client-sdk-move-to-effect/SKILL.md](skills/client-sdk-move-to-effect/SKILL.md):
33
36
  run when Effect code wraps the Promise API (`Effect.tryPromise`,
34
37
  `Effect.promise`) of this SDK.
package/README.md CHANGED
@@ -18,8 +18,9 @@ logout and reauthorization. A server runtime remains responsible for any
18
18
  confidential proxy credentials and durable application sessions.
19
19
 
20
20
  `createClient` binds a typed transport to CI operations for agents, attachments,
21
- context, Knowledge, runs, skills, and workflows. Call `forOrganization` to bind
22
- those operations to one organization.
21
+ the chat, context, Knowledge, runs, skills, and workflows. Call
22
+ `forOrganization` to bind those operations to one organization. See
23
+ [External App chat](#external-app-chat) for `client.chat`.
23
24
 
24
25
  For `workflows_invoke`, pass exactly one target: `workflowId` for a workflow
25
26
  UUID or `workflowFqn` for its stable fully qualified name. Both forms use the
@@ -437,6 +438,128 @@ Effect.runFork(
437
438
  - Timers use `Clock` and the jitter uses `Random`, so a test can use `TestClock`
438
439
  and a fixed `Random`.
439
440
 
441
+ ## External App chat
442
+
443
+ `client.chat` calls the External App chat routes
444
+ (`/application/v1/chat/...`) for a signed-in user of the app. Each method
445
+ runs one `chat_*` operation: it takes the `path`, `query` and `body` of the
446
+ generated operation and resolves a `CiResult`, like the other domain methods.
447
+ The transport maps the method to its route, so the same call works directly
448
+ (`createDirectTransport`) and through the app's proxy or the server SDK BFF
449
+ (`createProxyTransport`).
450
+
451
+ ```ts
452
+ const chat = client.forOrganization(organizationId).chat
453
+
454
+ const listed = await chat.conversations.list({})
455
+ const ownOnly = await chat.conversations.list({
456
+ query: { historyScope: [`external_app:${applicationId}`] }
457
+ })
458
+ const turn = await chat.turns.submit({
459
+ body: { conversationId, message: "Summarize the plan" }
460
+ })
461
+ ```
462
+
463
+ A list without `historyScope` shows the Conversations of the app and of
464
+ every Place that its History Scope Ceiling names. Each `historyScope` value
465
+ names one Place as `external_app:<id>` or `studio_app:<id>`; the values only
466
+ narrow that list and never add a Place.
467
+
468
+ | Group | Methods |
469
+ | -------------------- | ------------------------------------------------------------------------------------------------ |
470
+ | `conversations` | `list`, `create`, `get`, `update`, `delete`, `transcript` |
471
+ | `turns` | `submit`, `stream`, `cancel` |
472
+ | `steeringMessages` | `send` |
473
+ | `queuedMessages` | `create`, `list`, `update`, `delete` |
474
+ | `presentation` | `get`, `stream` |
475
+ | `placeContext` | `get` |
476
+ | `agents` | `list` |
477
+ | `skills` | `list` |
478
+ | `tools` | `list` |
479
+ | `agentConversations` | `submitTurn`, `cancelTurn`, `close` |
480
+ | `attachments` | `upload`, `downloadUrl`, `capabilities` |
481
+ | `feedback` | `upsert`, `clear` |
482
+ | `approvals` | `searchRequests`, `search`, `get`, `decide`, `reject`, `withdraw` |
483
+ | `interactions` | `respond`, `stream` |
484
+ | `permissions` | `decideWait`, `list`, `update`, `revoke` |
485
+ | `artifacts` | `progress` |
486
+ | `compaction` | `get`, `compact`, `regenerate`, `reset` |
487
+ | `evidence` | `resolve` |
488
+ | `projects` | `list`, `create`, `update`, `delete`, `listFiles`, `uploadFile`, `deleteFile`, `fileDownloadUrl` |
489
+ | `speech` | `availability`, `createClip`, `transcribe`, `readAloudPart` |
490
+
491
+ A refusal is a `CiError` with the code of CI. A `forbidden` error names why in
492
+ `details.reason`:
493
+
494
+ - `principal_not_allowed`, `capability_missing`, `app_disabled`: this user
495
+ cannot chat in this app.
496
+ - `not_available_here`: this Conversation or Agent is outside the app's lists.
497
+ - `approval_not_allowed`: the user cannot decide this one approval. The chat
498
+ stays open; do not show it as a blocked chat.
499
+
500
+ `unauthenticated` asks the user to sign in, and `unavailable` is retryable.
501
+ A request that the route schemas refuse, for example an id that is not a
502
+ UUID or a `historyScope` value that names no Place, is `invalid_request`.
503
+
504
+ While an answer runs, `steeringMessages.send` sends a message to that answer
505
+ (`outcome: "steered"`); with no running answer it starts a turn
506
+ (`outcome: "started"`). `queuedMessages.create` ("Send after this answer")
507
+ saves a Queued Message that runs after the answer. `queuedMessages.update`
508
+ and `queuedMessages.delete` name the current `revision`; a message that a
509
+ turn claimed answers `conflict`. The three sends share one space of client
510
+ ids per Conversation (`clientMessageId`, and `clientTurnId` for
511
+ `turns.submit`): a send with an id that one of them already used returns the
512
+ earlier result, a `queued` result when a Queued Message holds the id.
513
+
514
+ `speech.availability` tells which speech controls to show
515
+ (`remoteTranscription`, `readAloud`). Voice input takes two calls:
516
+ `speech.createClip` answers a presigned upload of the recorded clip (at most
517
+ 25 MiB), the browser sends the bytes to it, and `speech.transcribe` returns
518
+ the text and deletes the clip; a `not_found` asks the user to record again.
519
+ `speech.readAloudPart` answers the part count and a signed audio URL of one
520
+ part of an answer; a `conflict` is retryable. In a browser chat,
521
+ `transcribeRecording` of `@collective-intelligence/ai-react/chat` runs the
522
+ voice input calls.
523
+
524
+ `presentation.stream`, `turns.stream` and `interactions.stream` resolve an
525
+ `AsyncIterable` of the frames of one connection: `{ event, id?, data }`, where
526
+ `data` is JSON text. Each frame arrives while the connection stays open. The
527
+ iteration ends when the server closes the stream; a cut connection throws
528
+ `CiTransportError`. Stop the loop to close the connection. A presentation
529
+ always ends with its `closed` frame, so an end before that frame is a cut:
530
+ open the stream again with `query.afterSequence` set to the `id` of the last
531
+ frame. `attachments.upload` and `projects.uploadFile` send
532
+ `multipart/form-data`; give named `File` values. CI reads the type of each
533
+ file from the extension of its name, so a plain `Blob` throws `TypeError`
534
+ and sends nothing: wrap it as `new File([blob], "notes.txt")`.
535
+
536
+ ### Shared chat UI (`./chat`)
537
+
538
+ The `@collective-intelligence/external-apps-client-sdk/chat` entrypoint
539
+ exports `createChatTransport` and the type `ChatTransportClient`.
540
+ `createChatTransport` is the `ChatTransport` of
541
+ `@collective-intelligence/ai-core` over `client.chat`: give it to
542
+ `<AiProvider transport>` of `@collective-intelligence/ai-react` to show the
543
+ default `<Chat>`.
544
+
545
+ ```ts
546
+ import { createChatTransport } from "@collective-intelligence/external-apps-client-sdk/chat"
547
+
548
+ const transport = createChatTransport(client.forOrganization(organizationId))
549
+ ```
550
+
551
+ - `@collective-intelligence/ai-core` is an optional peer dependency: only
552
+ `./chat` imports it, so install it with this entry. `./chat` imports no
553
+ React.
554
+ - Give an organization client (`ChatTransportClient` is its `chat` group).
555
+ The transport works directly, through a proxy or through the server SDK
556
+ BFF.
557
+ - A refusal answers an `AiError`; its `reason` is the `details.reason` of the
558
+ `CiError`. A request that does not reach CI answers `unavailable`, which is
559
+ retryable. An aborted call rejects with the reason of its signal.
560
+ - `openPresentationStream` opens one connection. Follow a run with
561
+ `followPresentation` of ai-core, which reconnects.
562
+
440
563
  ## Expected Errors and `./effect`
441
564
 
442
565
  `effect` `^4.1.0` is a required peer dependency. Install it in the
@@ -537,6 +660,7 @@ a layer that reads Effect `Config`:
537
660
  | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
538
661
  | `CiClient` (`execute`, `executeResult`) | `layerCiClientDirect`, `layerCiClientProxy`, `layerCiClientFromExecutor`, `layerCiClientDirectConfig`, `layerCiClientProxyConfig` | `createClient`, `createDirectTransport`, `createProxyTransport` |
539
662
  | `Runs` (`follow`) | `layerRuns` (needs `CiClient`) | `followRun`, `client.runs.follow` |
663
+ | `Chat` (the `client.chat` groups) | `layerChat` (needs `CiClient`) | `client.chat` |
540
664
  | `FederatedAuth` | `layerFederatedAuth`, `layerServerSessionAuth`, and their `…Config` forms | `createFederatedAuth`, `createServerSessionAuth` |
541
665
  | `FixedWorkflows` (`invoke`) | `layerFixedWorkflows`, `layerFixedWorkflowsConfig` | `createFixedWorkflowClient` |
542
666
  | `DelegatedRuntime` | `layerDelegatedRuntime`, `layerDelegatedRuntimeConfig` | `createDelegatedApplicationRuntime` |
package/dist/chat.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ import { x as ClientOperationMap } from "./proxy-DRPEFvaV.js";
2
+ import { i as OrganizationClient } from "./client-_rl-iXS8.js";
3
+ import { ChatTransport } from "@collective-intelligence/ai-core/chat";
4
+ /** The organization client whose chat domain the transport calls. */
5
+ type ChatTransportClient = Pick<OrganizationClient<ClientOperationMap>, "chat">;
6
+ /**
7
+ * The `ChatTransport` of the shared chat over `client.chat`. `call` answers
8
+ * a CI refusal, and a request that does not reach CI, as an `AiError`; an
9
+ * aborted call rejects with the reason of its signal.
10
+ * `openPresentationStream` opens one connection: a refusal throws a
11
+ * non-retryable `AiFailureError`, a cut throws `CiTransportError`, and
12
+ * `followPresentation` of ai-core reconnects.
13
+ */
14
+ declare const createChatTransport: (client: ChatTransportClient) => ChatTransport;
15
+ export { type ChatTransportClient, createChatTransport };
package/dist/chat.js ADDED
@@ -0,0 +1,110 @@
1
+ import { r as CiTransportError } from "./errors-C3UmgGGu.js";
2
+ import { AiFailureError } from "@collective-intelligence/ai-core";
3
+ import * as Predicate from "effect/Predicate";
4
+ import * as Schema from "effect/Schema";
5
+ const chatCalls = {
6
+ clearAnswerFeedback: (chat, input, options) => chat.feedback.clear(input, options),
7
+ compactConversation: (chat, input, options) => chat.compaction.compact(input, options),
8
+ createConversation: (chat, input, options) => chat.conversations.create(input, options),
9
+ createProject: (chat, input, options) => chat.projects.create(input, options),
10
+ createSpeechClip: (chat, input, options) => chat.speech.createClip(input, options),
11
+ decideApproval: (chat, input, options) => chat.approvals.decide(input, options),
12
+ decidePermissionWait: (chat, input, options) => chat.permissions.decideWait(input, options),
13
+ deleteConversation: (chat, input, options) => chat.conversations.delete(input, options),
14
+ deleteProject: (chat, input, options) => chat.projects.delete(input, options),
15
+ deleteProjectFile: (chat, input, options) => chat.projects.deleteFile(input, options),
16
+ getApproval: (chat, input, options) => chat.approvals.get(input, options),
17
+ getArtifactProgress: (chat, input, options) => chat.artifacts.progress(input, options),
18
+ getAttachmentCapabilities: (chat, input, options) => chat.attachments.capabilities(input, options),
19
+ getAttachmentDownloadUrl: (chat, input, options) => chat.attachments.downloadUrl(input, options),
20
+ getConversation: (chat, input, options) => chat.conversations.get(input, options),
21
+ getPlaceContext: (chat, input, options) => chat.placeContext.get(input, options),
22
+ getPresentation: (chat, input, options) => chat.presentation.get(input, options),
23
+ getProjectFileDownloadUrl: (chat, input, options) => chat.projects.fileDownloadUrl(input, options),
24
+ getReadAloudPart: (chat, input, options) => chat.speech.readAloudPart(input, options),
25
+ getSpeechAvailability: (chat, input, options) => chat.speech.availability(input, options),
26
+ getTranscript: (chat, input, options) => chat.conversations.transcript(input, options),
27
+ listAgents: (chat, input, options) => chat.agents.list(input, options),
28
+ listConversations: (chat, input, options) => chat.conversations.list(input, options),
29
+ listProjectFiles: (chat, input, options) => chat.projects.listFiles(input, options),
30
+ listProjects: (chat, input, options) => chat.projects.list(input, options),
31
+ listQueuedMessages: (chat, input, options) => chat.queuedMessages.list(input, options),
32
+ listSkills: (chat, input, options) => chat.skills.list(input, options),
33
+ listTools: (chat, input, options) => chat.tools.list(input, options),
34
+ queueMessage: (chat, input, options) => chat.queuedMessages.create(input, options),
35
+ regenerateCompaction: (chat, input, options) => chat.compaction.regenerate(input, options),
36
+ rejectApproval: (chat, input, options) => chat.approvals.reject(input, options),
37
+ removeQueuedMessage: (chat, input, options) => chat.queuedMessages.delete(input, options),
38
+ resetCompaction: (chat, input, options) => chat.compaction.reset(input, options),
39
+ resolveEvidence: (chat, input, options) => chat.evidence.resolve(input, options),
40
+ respondToInteraction: (chat, input, options) => chat.interactions.respond(input, options),
41
+ searchApprovals: (chat, input, options) => chat.approvals.search(input, options),
42
+ sendSteeringMessage: (chat, input, options) => chat.steeringMessages.send(input, options),
43
+ stopTurn: (chat, input, options) => chat.turns.cancel(input, options),
44
+ submitAgentTurn: (chat, input, options) => chat.agentConversations.submitTurn(input, options),
45
+ submitTurn: (chat, input, options) => chat.turns.submit(input, options),
46
+ transcribeSpeechClip: (chat, input, options) => chat.speech.transcribe(input, options),
47
+ updateConversation: (chat, input, options) => chat.conversations.update(input, options),
48
+ updateProject: (chat, input, options) => chat.projects.update(input, options),
49
+ updateQueuedMessage: (chat, input, options) => chat.queuedMessages.update(input, options),
50
+ uploadAttachments: (chat, input, options) => chat.attachments.upload(input, options),
51
+ uploadProjectFile: (chat, input, options) => chat.projects.uploadFile(input, options),
52
+ upsertAnswerFeedback: (chat, input, options) => chat.feedback.upsert(input, options)
53
+ };
54
+ /** The `AiError` of a CI refusal; `details.reason` becomes `reason`. */
55
+ const aiErrorOf = ({ code, details, message, retryable }) => {
56
+ const reason = details?.["reason"];
57
+ return Predicate.isString(reason) ? {
58
+ code,
59
+ message,
60
+ reason,
61
+ retryable
62
+ } : {
63
+ code,
64
+ message,
65
+ retryable
66
+ };
67
+ };
68
+ const unreachable = {
69
+ code: "unavailable",
70
+ message: "The chat could not reach Collective Intelligence",
71
+ retryable: true
72
+ };
73
+ /**
74
+ * The `ChatTransport` of the shared chat over `client.chat`. `call` answers
75
+ * a CI refusal, and a request that does not reach CI, as an `AiError`; an
76
+ * aborted call rejects with the reason of its signal.
77
+ * `openPresentationStream` opens one connection: a refusal throws a
78
+ * non-retryable `AiFailureError`, a cut throws `CiTransportError`, and
79
+ * `followPresentation` of ai-core reconnects.
80
+ */
81
+ const createChatTransport = (client) => ({
82
+ call: async (op, input, options) => {
83
+ const chatCall = chatCalls[op];
84
+ try {
85
+ const result = await chatCall(client.chat, input, options);
86
+ return result.ok ? {
87
+ ok: true,
88
+ value: result.value
89
+ } : {
90
+ error: aiErrorOf(result.error),
91
+ ok: false
92
+ };
93
+ } catch (error) {
94
+ if (Schema.is(CiTransportError)(error)) return {
95
+ error: unreachable,
96
+ ok: false
97
+ };
98
+ throw error;
99
+ }
100
+ },
101
+ openPresentationStream: async function* openPresentationStream({ afterSequence, invocationId, signal }) {
102
+ const opened = await client.chat.presentation.stream({
103
+ path: { invocationId },
104
+ query: { afterSequence: String(afterSequence) }
105
+ }, { signal });
106
+ if (!opened.ok) throw new AiFailureError(aiErrorOf(opened.error));
107
+ for await (const frame of opened.value) yield JSON.parse(frame.data);
108
+ }
109
+ });
110
+ export { createChatTransport };