@collective-intelligence/external-apps-client-sdk 0.3.9 → 0.4.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/README.md CHANGED
@@ -13,9 +13,11 @@ to the Server SDK.
13
13
 
14
14
  `createFederatedAuth` implements the public OAuth authorization-code flow with
15
15
  PKCE. It validates same-origin return targets, keeps the login transaction in
16
- session storage, exchanges the callback code, tracks token expiry, and supports
17
- logout and reauthorization. A server runtime remains responsible for any
18
- confidential proxy credentials and durable application sessions.
16
+ session storage, exchanges the callback code, tracks token expiry, renews the
17
+ Access token while the page stays open, and supports logout and
18
+ reauthorization. A server runtime remains responsible for any confidential
19
+ proxy credentials and durable application sessions. See
20
+ [Session renewal in the browser](#session-renewal-in-the-browser).
19
21
 
20
22
  `createClient` binds a typed transport to CI operations for agents, attachments,
21
23
  the chat, context, Knowledge, runs, skills, and workflows. Call
@@ -38,6 +40,51 @@ plus slack) before throwing `Run did not finish`; pass `deadlineMs` to change
38
40
  it and `signal` to cancel. Polling starts every `idleMs` (50 ms) and backs off
39
41
  to at most one second while no new events arrive.
40
42
 
43
+ ## Session renewal in the browser
44
+
45
+ The Access token of `createFederatedAuth` lasts 300 seconds. CI returns a
46
+ Renewal credential at sign-in. The SDK keeps it only in the memory of the tab,
47
+ never in browser storage. `getAccessToken()` renews the Access token while the
48
+ page stays open:
49
+
50
+ - A call in the last 30 seconds of the Access token, or after its expiry,
51
+ sends one renewal request; calls at the same time share it. There is no
52
+ timer: the renewal happens at the next call.
53
+ - Each renewal replaces the Renewal credential (Rotation). After it,
54
+ `expiresAt` of the state is the expiry of the new Access token.
55
+ - A reload, a new tab or a return to the application starts with no Renewal
56
+ credential. It uses Redirect renewal: `beginLogin` or `reauthorize` sends
57
+ the browser to CI, which returns a new code with no prompt while the CI
58
+ session is live.
59
+ - Each tab has its own sign-in. It ends 7 days after that sign-in, or with the
60
+ CI session if that is earlier.
61
+
62
+ When `getAccessToken()` fails, read `getState()` before you act. Branch on the
63
+ state, not on the error code alone:
64
+
65
+ | State | Error code | Cause | Action |
66
+ | --------------- | -------------------------- | --------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
67
+ | `authenticated` | `renewal_unavailable` | CI did not answer the renewal: a network error, a timeout, a `5xx`, a `429` or an unreadable answer | Retry later. The session and its Renewal credential stay, also after the Access token expires. |
68
+ | `expired` | `reauthorization_required` | CI refused the renewal (any other `4xx`), or the session has no Renewal credential and expired | Keep unsaved state, then call `reauthorize`. It leaves the page. |
69
+ | `anonymous` | `reauthorization_required` | A logout in this tab or in another tab of the Application ended the session during the call | Show the signed-out view. Start a sign-in only when the user asks for it. |
70
+
71
+ Before it fails with `renewal_unavailable`, the SDK tries the renewal up to
72
+ three times, after waits of 250 ms and 1 s, with 8 s for each attempt. A `429`
73
+ fails at once, with no retry.
74
+
75
+ `logout()` signs out every tab of the Application in this browser. It first
76
+ sends a notice to the other tabs through a `BroadcastChannel`; they go to
77
+ `anonymous` and ignore renewal answers that arrive later. Then it calls CI,
78
+ which ends every Federated authorization of the Application in the CI session
79
+ of the user. A tab in `expired` logs out too, with its last Access token. The
80
+ call to CI is best effort: when CI cannot be reached, the SDK does not retry,
81
+ and the local state and the other tabs are still cleared. Where
82
+ `BroadcastChannel` is not available, no notice is sent.
83
+
84
+ An SDK version from before session renewal ignores the Renewal credential and
85
+ keeps the 300 second session against the same CI. The CI wire contract is in
86
+ [Access token renewal](../../../docs/architecture/external-app-gateway.md#access-token-renewal).
87
+
41
88
  ## Workflow results and read recovery
42
89
 
43
90
  A successful Workflow with a declared output contract exposes its persisted
package/dist/chat.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { x as ClientOperationMap } from "./proxy-DRPEFvaV.js";
2
- import { i as OrganizationClient } from "./client-_rl-iXS8.js";
1
+ import { x as ClientOperationMap } from "./proxy-B4MA1pat.js";
2
+ import { i as OrganizationClient } from "./client-C-o7Az4B.js";
3
3
  import { ChatTransport } from "@collective-intelligence/ai-core/chat";
4
4
  /** The organization client whose chat domain the transport calls. */
5
5
  type ChatTransportClient = Pick<OrganizationClient<ClientOperationMap>, "chat">;
package/dist/chat.js CHANGED
@@ -1,4 +1,4 @@
1
- import { r as CiTransportError } from "./errors-C3UmgGGu.js";
1
+ import { r as CiTransportError } from "./errors-B4-Jo4j3.js";
2
2
  import { AiFailureError } from "@collective-intelligence/ai-core";
3
3
  import * as Predicate from "effect/Predicate";
4
4
  import * as Schema from "effect/Schema";
@@ -1,4 +1,4 @@
1
- import { C as OperationExecutionOptions, D as CiError, P as CiResult, S as ClientOperationOutput, V as ExternalApplicationChatOperationId, b as ClientOperationInput, i as ClientFetch, k as CiTransportError, n as ProxyTransportOptions, w as TypedOperationExecutor, x as ClientOperationMap, y as ClientOperationId } from "./proxy-DRPEFvaV.js";
1
+ import { C as OperationExecutionOptions, D as CiError, P as CiResult, S as ClientOperationOutput, V as ExternalApplicationChatOperationId, b as ClientOperationInput, i as ClientFetch, k as CiTransportError, n as ProxyTransportOptions, w as TypedOperationExecutor, x as ClientOperationMap, y as ClientOperationId } from "./proxy-B4MA1pat.js";
2
2
  import "effect/Clock";
3
3
  import * as Config from "effect/Config";
4
4
  import * as Context from "effect/Context";
package/dist/effect.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { A as FederatedAuthError, D as CiError, O as CiErrorCode, d as FederatedAuthValue, f as layerFederated, h as layerServerSessionConfig, i as ClientFetch, j as FederatedAuthErrorCode, k as CiTransportError, m as layerServerSession, p as layerFederatedConfig, u as FederatedAuth } from "./proxy-DRPEFvaV.js";
2
- import { A as layerProxyConfig, C as CiClient, D as layerDirectConfig, E as layerDirect, O as layerFromExecutor, S as layer, T as ExecuteResult, _ as CiStreamPage$1, b as Chat, d as RunFollowOptions, f as Runs, k as layerProxy, m as layer$5, p as RunsValue, u as DEFAULT_FOLLOW_RUN_DEADLINE_MS, w as CiClientValue, x as ChatValue } from "./client-_rl-iXS8.js";
3
- import { C as RealtimeChange, T as RealtimeTopicFilter, f as DelegatedApplicationRuntimeOptions, p as DelegatedRuntimeState, w as RealtimeTopic } from "./index-D0f9UvVk.js";
4
- import { _ as layerLegacy, a as LegacyResourceClient, c as LegacyResourcesValue, d as ResourcesFromEntityTransportOptions, f as ResourcesLayerOptions, g as layerFromEntityTransport, h as layerConfig$3, i as makeEntityHttpExecute, l as ResourceEntityClient, m as layer$4, o as LegacyResources, p as ResourcesValue, s as LegacyResourcesLayerOptions, u as Resources, v as layerLegacyConfig } from "./resources-r2t8pcv2.js";
1
+ import { A as FederatedAuthError, D as CiError, O as CiErrorCode, d as FederatedAuthValue, f as layerFederated, h as layerServerSessionConfig, i as ClientFetch, j as FederatedAuthErrorCode, k as CiTransportError, m as layerServerSession, p as layerFederatedConfig, u as FederatedAuth } from "./proxy-B4MA1pat.js";
2
+ import { A as layerProxyConfig, C as CiClient, D as layerDirectConfig, E as layerDirect, O as layerFromExecutor, S as layer, T as ExecuteResult, _ as CiStreamPage$1, b as Chat, d as RunFollowOptions, f as Runs, k as layerProxy, m as layer$5, p as RunsValue, u as DEFAULT_FOLLOW_RUN_DEADLINE_MS, w as CiClientValue, x as ChatValue } from "./client-C-o7Az4B.js";
3
+ import { C as RealtimeChange, T as RealtimeTopicFilter, f as DelegatedApplicationRuntimeOptions, p as DelegatedRuntimeState, w as RealtimeTopic } from "./index-DaFbcQb9.js";
4
+ import { _ as layerLegacy, a as LegacyResourceClient, c as LegacyResourcesValue, d as ResourcesFromEntityTransportOptions, f as ResourcesLayerOptions, g as layerFromEntityTransport, h as layerConfig$3, i as makeEntityHttpExecute, l as ResourceEntityClient, m as layer$4, o as LegacyResources, p as ResourcesValue, s as LegacyResourcesLayerOptions, u as Resources, v as layerLegacyConfig } from "./resources-Dbdfbb44.js";
5
5
  import * as Schema from "effect/Schema";
6
6
  import * as Config from "effect/Config";
7
7
  import * as Context from "effect/Context";
package/dist/effect.js CHANGED
@@ -1,6 +1,6 @@
1
- import { a as FederatedAuthErrorCode, i as FederatedAuthError, n as CiErrorCode, r as CiTransportError, t as CiError } from "./errors-C3UmgGGu.js";
2
- import { a as layerConfig$3, c as layerLegacyConfig, f as makeEntityHttpExecute, i as layer$4, n as Resources, o as layerFromEntityTransport, s as layerLegacy, t as LegacyResources } from "./service-l8wUAlPK.js";
3
- import { A as subscribe, C as layerProxy, D as layer$3, E as RealtimeClient, O as layerConfig$2, S as layerFromExecutor, a as layer$2, b as layerDirect, c as layerFederated, d as layerServerSessionConfig, f as Chat, g as Runs, h as DEFAULT_FOLLOW_RUN_DEADLINE_MS, i as FixedWorkflows, l as layerFederatedConfig, n as layer$1, o as layerConfig$1, p as layer, r as layerConfig, s as FederatedAuth, t as DelegatedRuntime, u as layerServerSession, v as layer$5, w as layerProxyConfig, x as layerDirectConfig, y as CiClient } from "./service-D-POpqlt.js";
1
+ import { a as FederatedAuthErrorCode, i as FederatedAuthError, n as CiErrorCode, r as CiTransportError, t as CiError } from "./errors-B4-Jo4j3.js";
2
+ import { a as layerConfig$3, c as layerLegacyConfig, f as makeEntityHttpExecute, i as layer$4, n as Resources, o as layerFromEntityTransport, s as layerLegacy, t as LegacyResources } from "./service-CimYXTmK.js";
3
+ import { A as subscribe, C as layerProxy, D as layer$3, E as RealtimeClient, O as layerConfig$2, S as layerFromExecutor, a as layer$2, b as layerDirect, c as layerFederated, d as layerServerSessionConfig, f as Chat, g as Runs, h as DEFAULT_FOLLOW_RUN_DEADLINE_MS, i as FixedWorkflows, l as layerFederatedConfig, n as layer$1, o as layerConfig$1, p as layer, r as layerConfig, s as FederatedAuth, t as DelegatedRuntime, u as layerServerSession, v as layer$5, w as layerProxyConfig, x as layerDirectConfig, y as CiClient } from "./service-CREcfOem.js";
4
4
  import * as Schema from "effect/Schema";
5
5
  /**
6
6
  * The wire Schemas of the CI envelopes that `./effect` exports. The Type of
@@ -50,7 +50,11 @@ var errors_exports = /* @__PURE__ */ __exportAll({
50
50
  });
51
51
  /** Code of an Expected Error that CI returns for an operation. */
52
52
  const CiErrorCode = Schema.Literals(ciErrorCodes);
53
- /** Code of an Expected Error of the federated sign-in flow. */
53
+ /**
54
+ * Code of an Expected Error of the federated sign-in flow.
55
+ * `renewal_unavailable` is retryable: CI did not answer a renewal, the
56
+ * session stays authenticated, and the next call renews again.
57
+ */
54
58
  const FederatedAuthErrorCode = Schema.Literals([
55
59
  "configuration_error",
56
60
  "invalid_return_target",
@@ -59,7 +63,8 @@ const FederatedAuthErrorCode = Schema.Literals([
59
63
  "transaction_expired",
60
64
  "authorization_failed",
61
65
  "token_exchange_failed",
62
- "reauthorization_required"
66
+ "reauthorization_required",
67
+ "renewal_unavailable"
63
68
  ]);
64
69
  /** An Expected Error that CI returns for an operation. */
65
70
  var CiError = class extends Schema.TaggedError()("CiError", {
@@ -1,6 +1,6 @@
1
- import { B as ConversationHistory, D as CiError$1, F as JsonValue, G as SearchQuery, H as JsonObject, K as WorkflowInvokeTarget, M as CiError$2, R as AgentInvokeTarget, U as KnowledgeQuery, W as QueryFilter, c as FederatedSessionIdentity, i as ClientFetch, s as FederatedAuthState, v as ClientOperationDefinition, z as ConversationContinueTarget } from "./proxy-DRPEFvaV.js";
2
- import { n as ClientSdkClient } from "./client-_rl-iXS8.js";
3
- import "./resources-r2t8pcv2.js";
1
+ import { B as ConversationHistory, D as CiError$1, F as JsonValue, G as SearchQuery, H as JsonObject, K as WorkflowInvokeTarget, M as CiError$2, R as AgentInvokeTarget, U as KnowledgeQuery, W as QueryFilter, c as FederatedSessionIdentity, i as ClientFetch, s as FederatedAuthState, v as ClientOperationDefinition, z as ConversationContinueTarget } from "./proxy-B4MA1pat.js";
2
+ import { n as ClientSdkClient } from "./client-C-o7Az4B.js";
3
+ import "./resources-Dbdfbb44.js";
4
4
  import "effect/Context";
5
5
  import "effect/Effect";
6
6
  import "effect/Layer";
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as FederatedAuthError, C as OperationExecutionOptions, E as isClientOperationId, F as JsonValue, G as SearchQuery, H as JsonObject, I as OperationRequest, K as WorkflowInvokeTarget, L as OperationSuccess, N as CiErrorCode, P as CiResult, S as ClientOperationOutput, T as clientOperationIds, U as KnowledgeQuery, W as QueryFilter, _ as createServerSessionAuth, a as FederatedAuth, b as ClientOperationInput, c as FederatedSessionIdentity, g as ServerSessionAuthOptions, i as ClientFetch, j as FederatedAuthErrorCode, k as CiTransportError, l as createFederatedAuth, n as ProxyTransportOptions, o as FederatedAuthOptions, r as createProxyTransport, s as FederatedAuthState, t as ProxyAuthentication, v as ClientOperationDefinition, w as TypedOperationExecutor, x as ClientOperationMap, y as ClientOperationId } from "./proxy-DRPEFvaV.js";
2
- import { M as createDirectTransport, _ as CiStreamPage, a as clientSdkProtocolVersion, c as FollowRunSource, g as CiStreamEvent, h as CiRunCancellation, i as OrganizationClient, j as DirectTransportOptions, l as followRun, n as ClientSdkClient, o as createClient, r as ClientSdkEntrypoint, s as FollowRunOptions, t as ClientDomains, u as DEFAULT_FOLLOW_RUN_DEADLINE_MS, v as nextStreamCursor, y as ChatClient } from "./client-_rl-iXS8.js";
3
- import { C as RealtimeChange, E as realtimeTopicKey, S as RealtimeWindow, T as RealtimeTopicFilter, _ as RealtimeStreamEnd, a as RealtimeClientStatus, b as createFetchEventSourceFactory, c as FixedWorkflowClient, d as DelegatedApplicationRuntime, f as DelegatedApplicationRuntimeOptions, g as RealtimeEventSourceFactory, h as RealtimeEventSource, i as RealtimeClientState, l as FixedWorkflowClientOptions, m as createDelegatedApplicationRuntime, n as RealtimeClient, o as RealtimeTimers, p as DelegatedRuntimeState, r as RealtimeClientOptions, s as createRealtimeClient, t as CiError, u as createFixedWorkflowClient, v as RealtimeStreamEvent, w as RealtimeTopic, x as RealtimeDocument, y as RealtimeStreamHandlers } from "./index-D0f9UvVk.js";
4
- import { $ as ResourceDefinition, A as EntityFileFieldWrite, B as EntityRequest, C as EntityBatchInput, Ct as ResourceUpdateRequest, D as EntityClient, E as EntityBatchRefusedDetails, F as EntityOperation, G as EntityUploadSlot, H as EntityTransport, I as EntityOperationResult, J as ResourceCapabilities, K as IdempotencyKey, L as EntityPage, M as EntityFileWrite, N as EntityListQuery, O as EntityCreateInput, P as EntityMemberValue, Q as ResourceCursor, R as EntityProtocol, S as createResourceClient, St as ResourceTransportRequest, T as EntityBatchRefusal, U as EntityUpdateInput, V as EntityRestoreInput, W as EntityUploadInput, X as ResourceCreateInput, Y as ResourceClient, Z as ResourceCreateRequest, _t as ResourceRequestOptions, at as ResourceIdentityField, b as isEntityBatchRefusedError, bt as ResourceSort, ct as ResourceLifecycleRequest, dt as ResourceListResult, et as ResourceError, ft as ResourceMutationInput, gt as ResourceRecordId, ht as ResourceRecord, it as ResourceId, j as EntityFileValue, k as EntityDeleteInput, lt as ResourceListQuery, mt as ResourcePaginationMode, n as EntityHttpTransportOptions, nt as ResourceFilter, ot as ResourceJsonValue, pt as ResourcePagination, q as PortableResourceSchema, r as createEntityHttpTransport, rt as ResourceGetRequest, st as ResourceLifecycleInput, t as EntityHttpDestination, tt as ResourceErrorCode, ut as ResourceListRequest, vt as ResourceResult, w as EntityBatchOp, x as isEntityReadLimitError, xt as ResourceTransport, y as createEntityProtocol, yt as ResourceRevision, z as EntityReadLimitDetails } from "./resources-r2t8pcv2.js";
1
+ import { A as FederatedAuthError, C as OperationExecutionOptions, E as isClientOperationId, F as JsonValue, G as SearchQuery, H as JsonObject, I as OperationRequest, K as WorkflowInvokeTarget, L as OperationSuccess, N as CiErrorCode, P as CiResult, S as ClientOperationOutput, T as clientOperationIds, U as KnowledgeQuery, W as QueryFilter, _ as createServerSessionAuth, a as FederatedAuth, b as ClientOperationInput, c as FederatedSessionIdentity, g as ServerSessionAuthOptions, i as ClientFetch, j as FederatedAuthErrorCode, k as CiTransportError, l as createFederatedAuth, n as ProxyTransportOptions, o as FederatedAuthOptions, r as createProxyTransport, s as FederatedAuthState, t as ProxyAuthentication, v as ClientOperationDefinition, w as TypedOperationExecutor, x as ClientOperationMap, y as ClientOperationId } from "./proxy-B4MA1pat.js";
2
+ import { M as createDirectTransport, _ as CiStreamPage, a as clientSdkProtocolVersion, c as FollowRunSource, g as CiStreamEvent, h as CiRunCancellation, i as OrganizationClient, j as DirectTransportOptions, l as followRun, n as ClientSdkClient, o as createClient, r as ClientSdkEntrypoint, s as FollowRunOptions, t as ClientDomains, u as DEFAULT_FOLLOW_RUN_DEADLINE_MS, v as nextStreamCursor, y as ChatClient } from "./client-C-o7Az4B.js";
3
+ import { C as RealtimeChange, E as realtimeTopicKey, S as RealtimeWindow, T as RealtimeTopicFilter, _ as RealtimeStreamEnd, a as RealtimeClientStatus, b as createFetchEventSourceFactory, c as FixedWorkflowClient, d as DelegatedApplicationRuntime, f as DelegatedApplicationRuntimeOptions, g as RealtimeEventSourceFactory, h as RealtimeEventSource, i as RealtimeClientState, l as FixedWorkflowClientOptions, m as createDelegatedApplicationRuntime, n as RealtimeClient, o as RealtimeTimers, p as DelegatedRuntimeState, r as RealtimeClientOptions, s as createRealtimeClient, t as CiError, u as createFixedWorkflowClient, v as RealtimeStreamEvent, w as RealtimeTopic, x as RealtimeDocument, y as RealtimeStreamHandlers } from "./index-DaFbcQb9.js";
4
+ import { $ as ResourceDefinition, A as EntityFileFieldWrite, B as EntityRequest, C as EntityBatchInput, Ct as ResourceUpdateRequest, D as EntityClient, E as EntityBatchRefusedDetails, F as EntityOperation, G as EntityUploadSlot, H as EntityTransport, I as EntityOperationResult, J as ResourceCapabilities, K as IdempotencyKey, L as EntityPage, M as EntityFileWrite, N as EntityListQuery, O as EntityCreateInput, P as EntityMemberValue, Q as ResourceCursor, R as EntityProtocol, S as createResourceClient, St as ResourceTransportRequest, T as EntityBatchRefusal, U as EntityUpdateInput, V as EntityRestoreInput, W as EntityUploadInput, X as ResourceCreateInput, Y as ResourceClient, Z as ResourceCreateRequest, _t as ResourceRequestOptions, at as ResourceIdentityField, b as isEntityBatchRefusedError, bt as ResourceSort, ct as ResourceLifecycleRequest, dt as ResourceListResult, et as ResourceError, ft as ResourceMutationInput, gt as ResourceRecordId, ht as ResourceRecord, it as ResourceId, j as EntityFileValue, k as EntityDeleteInput, lt as ResourceListQuery, mt as ResourcePaginationMode, n as EntityHttpTransportOptions, nt as ResourceFilter, ot as ResourceJsonValue, pt as ResourcePagination, q as PortableResourceSchema, r as createEntityHttpTransport, rt as ResourceGetRequest, st as ResourceLifecycleInput, t as EntityHttpDestination, tt as ResourceErrorCode, ut as ResourceListRequest, vt as ResourceResult, w as EntityBatchOp, x as isEntityReadLimitError, xt as ResourceTransport, y as createEntityProtocol, yt as ResourceRevision, z as EntityReadLimitDetails } from "./resources-Dbdfbb44.js";
5
5
  export { type ChatClient, CiError, type CiErrorCode, type CiResult, type CiRunCancellation, type CiStreamEvent, type CiStreamPage, CiTransportError, type ClientDomains, type ClientFetch, type ClientOperationDefinition, type ClientOperationId, type ClientOperationInput, type ClientOperationMap, type ClientOperationOutput, type ClientSdkClient, type ClientSdkEntrypoint, DEFAULT_FOLLOW_RUN_DEADLINE_MS, type DelegatedApplicationRuntime, type DelegatedApplicationRuntimeOptions, type DelegatedRuntimeState, type DirectTransportOptions, type EntityBatchInput, type EntityBatchOp, type EntityBatchRefusal, type EntityBatchRefusedDetails, type EntityClient, type EntityCreateInput, type EntityDeleteInput, type EntityFileFieldWrite, type EntityFileValue, type EntityFileWrite, type EntityHttpDestination, type EntityHttpTransportOptions, type EntityListQuery, type EntityMemberValue, type EntityOperation, type EntityOperationResult, type EntityPage, type EntityProtocol, type EntityReadLimitDetails, type EntityRequest, type EntityRestoreInput, type EntityTransport, type EntityUpdateInput, type EntityUploadInput, type EntityUploadSlot, type FederatedAuth, FederatedAuthError, type FederatedAuthErrorCode, type FederatedAuthOptions, type FederatedAuthState, type FederatedSessionIdentity, type FixedWorkflowClient, type FixedWorkflowClientOptions, type FollowRunOptions, type FollowRunSource, type IdempotencyKey, type JsonObject, type JsonValue, type KnowledgeQuery, type OperationExecutionOptions, type OperationRequest, type OperationSuccess, type OrganizationClient, type PortableResourceSchema, type ProxyAuthentication, type ProxyTransportOptions, type QueryFilter, type RealtimeChange, type RealtimeClient, type RealtimeClientOptions, type RealtimeClientState, type RealtimeClientStatus, type RealtimeDocument, type RealtimeEventSource, type RealtimeEventSourceFactory, type RealtimeStreamEnd, type RealtimeStreamEvent, type RealtimeStreamHandlers, type RealtimeTimers, type RealtimeTopic, type RealtimeTopicFilter, type RealtimeWindow, type ResourceCapabilities, type ResourceClient, type ResourceCreateInput, type ResourceCreateRequest, type ResourceCursor, type ResourceDefinition, type ResourceError, type ResourceErrorCode, type ResourceFilter, type ResourceGetRequest, type ResourceId, type ResourceIdentityField, type ResourceJsonValue, type ResourceLifecycleInput, type ResourceLifecycleRequest, type ResourceListQuery, type ResourceListRequest, type ResourceListResult, type ResourceMutationInput, type ResourcePagination, type ResourcePaginationMode, type ResourceRecord, type ResourceRecordId, type ResourceRequestOptions, type ResourceResult, type ResourceRevision, type ResourceSort, type ResourceTransport, type ResourceTransportRequest, type ResourceUpdateRequest, type SearchQuery, type ServerSessionAuthOptions, type TypedOperationExecutor, type WorkflowInvokeTarget, clientOperationIds, clientSdkProtocolVersion, createClient, createDelegatedApplicationRuntime, createDirectTransport, createEntityHttpTransport, createEntityProtocol, createFederatedAuth, createFetchEventSourceFactory, createFixedWorkflowClient, createProxyTransport, createRealtimeClient, createResourceClient, createServerSessionAuth, followRun, isClientOperationId, isEntityBatchRefusedError, isEntityReadLimitError, nextStreamCursor, realtimeTopicKey };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import { i as FederatedAuthError, o as errors_exports, r as CiTransportError } from "./errors-C3UmgGGu.js";
2
- import { C as isClientOperationId, T as createFetchEventSourceFactory, b as proxyHttpOptions, d as createEntityHttpTransport, g as isEntityReadLimitError, h as isEntityBatchRefusedError, m as createEntityProtocol, v as directHttpOptions, w as toCiResult, x as clientOperationIds, y as makeHttpExecute } from "./service-l8wUAlPK.js";
3
- import { F as currentLink, M as layer$3, N as layerFromFactory, P as layerBrowser, S as layerFromExecutor, T as make, _ as followSource, a as layer$2, c as layerFederated, g as Runs, h as DEFAULT_FOLLOW_RUN_DEADLINE_MS, i as FixedWorkflows, j as realtimeTopicKey, k as makeConnection, m as mapChatOperations, n as layer$1, s as FederatedAuth, t as DelegatedRuntime, u as layerServerSession, v as layer, y as CiClient } from "./service-D-POpqlt.js";
4
- import { t as createResourceClient } from "./resources-BZKqGxBT.js";
1
+ import { i as FederatedAuthError, o as errors_exports, r as CiTransportError } from "./errors-B4-Jo4j3.js";
2
+ import { C as isClientOperationId, T as createFetchEventSourceFactory, b as proxyHttpOptions, d as createEntityHttpTransport, g as isEntityReadLimitError, h as isEntityBatchRefusedError, m as createEntityProtocol, v as directHttpOptions, w as toCiResult, x as clientOperationIds, y as makeHttpExecute } from "./service-CimYXTmK.js";
3
+ import { F as currentLink, M as layer$3, N as layerFromFactory, P as layerBrowser, S as layerFromExecutor, T as make, _ as followSource, a as layer$2, c as layerFederated, g as Runs, h as DEFAULT_FOLLOW_RUN_DEADLINE_MS, i as FixedWorkflows, j as realtimeTopicKey, k as makeConnection, m as mapChatOperations, n as layer$1, s as FederatedAuth, t as DelegatedRuntime, u as layerServerSession, v as layer, y as CiClient } from "./service-CREcfOem.js";
4
+ import { t as createResourceClient } from "./resources-BiYIVzGa.js";
5
5
  import * as Schema from "effect/Schema";
6
6
  import * as Clock from "effect/Clock";
7
7
  import * as Context from "effect/Context";
@@ -5,6 +5,50 @@ import * as Effect from "effect/Effect";
5
5
  import * as Layer from "effect/Layer";
6
6
  import * as Stream from "effect/Stream";
7
7
  import "effect/ManagedRuntime";
8
+ type ExternalApplicationRunSource = {
9
+ documentId: string;
10
+ downloadUrl: string;
11
+ pages: Array<{
12
+ end: number;
13
+ start: number;
14
+ }>;
15
+ title: string;
16
+ versionId: string;
17
+ };
18
+ type ExternalApplicationsPutRunFeedbackData = {
19
+ body: {
20
+ sentiment: 'positive' | 'negative';
21
+ submitterNote?: string;
22
+ };
23
+ headers: {
24
+ authorization?: string;
25
+ 'x-organization-id': string;
26
+ 'x-correlation-id'?: string;
27
+ 'x-external-audit-issuer'?: string;
28
+ 'x-external-audit-subject'?: string;
29
+ 'x-external-caller-kind'?: 'anonymous_visitor';
30
+ 'x-external-ci-user-id'?: string;
31
+ };
32
+ path: {
33
+ runId: string;
34
+ };
35
+ query?: never;
36
+ url: '/application/v1/runs/{runId}/feedback';
37
+ };
38
+ type ExternalApplicationsPutRunFeedbackResponses = {
39
+ /**
40
+ * Success
41
+ */
42
+ 200: {
43
+ correlationId: string;
44
+ result: {
45
+ runId: string;
46
+ sentiment: 'positive' | 'negative';
47
+ submitterNote: string | null;
48
+ };
49
+ };
50
+ };
51
+ type ExternalApplicationsPutRunFeedbackResponse = ExternalApplicationsPutRunFeedbackResponses[keyof ExternalApplicationsPutRunFeedbackResponses];
8
52
  type ExternalAppChatConversationsListData = {
9
53
  body?: never;
10
54
  headers: {
@@ -2605,13 +2649,28 @@ interface DurableFileUpload {
2605
2649
  fileName: string;
2606
2650
  sizeBytes: number;
2607
2651
  }
2608
- interface ExternalApplicationServiceOperationRequest {
2652
+ /** The rating of the answer of a run: a not useful one needs a note with text. */
2653
+ type ExternalApplicationRunFeedback = ExternalApplicationsPutRunFeedbackData["body"] & {
2654
+ runId: string;
2655
+ };
2656
+ /** Operations that only a server client invokes. */
2657
+ type ExternalApplicationServiceOperationRequest = {
2609
2658
  input: DurableFileUpload;
2610
2659
  operationId: "files_upload";
2611
- }
2660
+ } | {
2661
+ input: {
2662
+ runId: string;
2663
+ };
2664
+ operationId: "runs_sources";
2665
+ } | {
2666
+ input: ExternalApplicationRunFeedback;
2667
+ operationId: "runs_feedback";
2668
+ };
2612
2669
  type ExternalApplicationServiceOperationSuccess = EnvelopeSuccess<"files_upload", {
2613
2670
  storageFileId: StorageFileId;
2614
- }>;
2671
+ }> | EnvelopeSuccess<"runs_sources", {
2672
+ sources: ExternalApplicationRunSource[];
2673
+ }> | EnvelopeSuccess<"runs_feedback", ExternalApplicationsPutRunFeedbackResponse["result"]>;
2615
2674
  /** Every operation a confidential server client may invoke. */
2616
2675
  type ExternalApplicationServerOperationRequest = ExternalApplicationOperationRequest | ExternalApplicationServiceOperationRequest;
2617
2676
  type ExternalApplicationOperationId = ExternalApplicationOperationRequest["operationId"];
@@ -2652,8 +2711,12 @@ type OperationSuccess<Id extends ClientOperationId> = Id extends ExternalApplica
2652
2711
  /** Code of an Expected Error that CI returns for an operation. */
2653
2712
  declare const CiErrorCode: Schema.Literals<readonly ["unauthenticated", "forbidden", "not_found", "conflict", "invalid_request", "rate_limited", "unavailable", "internal"]>;
2654
2713
  type CiErrorCode = typeof CiErrorCode.Type;
2655
- /** Code of an Expected Error of the federated sign-in flow. */
2656
- declare const FederatedAuthErrorCode: Schema.Literals<readonly ["configuration_error", "invalid_return_target", "invalid_callback", "invalid_state", "transaction_expired", "authorization_failed", "token_exchange_failed", "reauthorization_required"]>;
2714
+ /**
2715
+ * Code of an Expected Error of the federated sign-in flow.
2716
+ * `renewal_unavailable` is retryable: CI did not answer a renewal, the
2717
+ * session stays authenticated, and the next call renews again.
2718
+ */
2719
+ declare const FederatedAuthErrorCode: Schema.Literals<readonly ["configuration_error", "invalid_return_target", "invalid_callback", "invalid_state", "transaction_expired", "authorization_failed", "token_exchange_failed", "reauthorization_required", "renewal_unavailable"]>;
2657
2720
  type FederatedAuthErrorCode = typeof FederatedAuthErrorCode.Type;
2658
2721
  declare const CiError_base: Schema.Class<CiError, Schema.TaggedStruct<"CiError", {
2659
2722
  readonly code: Schema.Literals<readonly ["unauthenticated", "forbidden", "not_found", "conflict", "invalid_request", "rate_limited", "unavailable", "internal"]>;
@@ -2668,7 +2731,7 @@ type FederatedAuthErrorFields = Readonly<{
2668
2731
  message: string;
2669
2732
  }>;
2670
2733
  declare const FederatedAuthError_base: Schema.Class<FederatedAuthError, Schema.TaggedStruct<"FederatedAuthError", {
2671
- readonly code: Schema.Literals<readonly ["configuration_error", "invalid_return_target", "invalid_callback", "invalid_state", "transaction_expired", "authorization_failed", "token_exchange_failed", "reauthorization_required"]>;
2734
+ readonly code: Schema.Literals<readonly ["configuration_error", "invalid_return_target", "invalid_callback", "invalid_state", "transaction_expired", "authorization_failed", "token_exchange_failed", "reauthorization_required", "renewal_unavailable"]>;
2672
2735
  readonly message: Schema.String;
2673
2736
  }>, import("effect/Cause").YieldableError>;
2674
2737
  /** An Expected Error of the federated sign-in flow. */
@@ -1,5 +1,5 @@
1
- import { r as CiTransportError } from "./errors-C3UmgGGu.js";
2
- import { l as makeEntityCore, p as runEntityRequest, r as fromEntityTransport, u as makeLegacyResourceCore } from "./service-l8wUAlPK.js";
1
+ import { r as CiTransportError } from "./errors-B4-Jo4j3.js";
2
+ import { l as makeEntityCore, p as runEntityRequest, r as fromEntityTransport, u as makeLegacyResourceCore } from "./service-CimYXTmK.js";
3
3
  import * as Schema from "effect/Schema";
4
4
  import * as Layer from "effect/Layer";
5
5
  import * as ManagedRuntime from "effect/ManagedRuntime";
@@ -1,4 +1,4 @@
1
- import { D as CiError, i as ClientFetch, k as CiTransportError, t as ProxyAuthentication } from "./proxy-DRPEFvaV.js";
1
+ import { D as CiError, i as ClientFetch, k as CiTransportError, t as ProxyAuthentication } from "./proxy-B4MA1pat.js";
2
2
  import * as Config from "effect/Config";
3
3
  import * as Context from "effect/Context";
4
4
  import * as Effect from "effect/Effect";
@@ -1,2 +1,2 @@
1
- import { $ as ResourceDefinition, A as EntityFileFieldWrite, B as EntityRequest, C as EntityBatchInput, Ct as ResourceUpdateRequest, D as EntityClient, E as EntityBatchRefusedDetails, F as EntityOperation, G as EntityUploadSlot, H as EntityTransport, I as EntityOperationResult, J as ResourceCapabilities, K as IdempotencyKey, L as EntityPage, M as EntityFileWrite, N as EntityListQuery, O as EntityCreateInput, P as EntityMemberValue, Q as ResourceCursor, R as EntityProtocol, S as createResourceClient, St as ResourceTransportRequest, T as EntityBatchRefusal, U as EntityUpdateInput, V as EntityRestoreInput, W as EntityUploadInput, X as ResourceCreateInput, Y as ResourceClient, Z as ResourceCreateRequest, _t as ResourceRequestOptions, at as ResourceIdentityField, b as isEntityBatchRefusedError, bt as ResourceSort, ct as ResourceLifecycleRequest, dt as ResourceListResult, et as ResourceError, ft as ResourceMutationInput, gt as ResourceRecordId, ht as ResourceRecord, it as ResourceId, j as EntityFileValue, k as EntityDeleteInput, lt as ResourceListQuery, mt as ResourcePaginationMode, n as EntityHttpTransportOptions, nt as ResourceFilter, ot as ResourceJsonValue, pt as ResourcePagination, q as PortableResourceSchema, r as createEntityHttpTransport, rt as ResourceGetRequest, st as ResourceLifecycleInput, t as EntityHttpDestination, tt as ResourceErrorCode, ut as ResourceListRequest, vt as ResourceResult, w as EntityBatchOp, x as isEntityReadLimitError, xt as ResourceTransport, y as createEntityProtocol, yt as ResourceRevision, z as EntityReadLimitDetails } from "./resources-r2t8pcv2.js";
1
+ import { $ as ResourceDefinition, A as EntityFileFieldWrite, B as EntityRequest, C as EntityBatchInput, Ct as ResourceUpdateRequest, D as EntityClient, E as EntityBatchRefusedDetails, F as EntityOperation, G as EntityUploadSlot, H as EntityTransport, I as EntityOperationResult, J as ResourceCapabilities, K as IdempotencyKey, L as EntityPage, M as EntityFileWrite, N as EntityListQuery, O as EntityCreateInput, P as EntityMemberValue, Q as ResourceCursor, R as EntityProtocol, S as createResourceClient, St as ResourceTransportRequest, T as EntityBatchRefusal, U as EntityUpdateInput, V as EntityRestoreInput, W as EntityUploadInput, X as ResourceCreateInput, Y as ResourceClient, Z as ResourceCreateRequest, _t as ResourceRequestOptions, at as ResourceIdentityField, b as isEntityBatchRefusedError, bt as ResourceSort, ct as ResourceLifecycleRequest, dt as ResourceListResult, et as ResourceError, ft as ResourceMutationInput, gt as ResourceRecordId, ht as ResourceRecord, it as ResourceId, j as EntityFileValue, k as EntityDeleteInput, lt as ResourceListQuery, mt as ResourcePaginationMode, n as EntityHttpTransportOptions, nt as ResourceFilter, ot as ResourceJsonValue, pt as ResourcePagination, q as PortableResourceSchema, r as createEntityHttpTransport, rt as ResourceGetRequest, st as ResourceLifecycleInput, t as EntityHttpDestination, tt as ResourceErrorCode, ut as ResourceListRequest, vt as ResourceResult, w as EntityBatchOp, x as isEntityReadLimitError, xt as ResourceTransport, y as createEntityProtocol, yt as ResourceRevision, z as EntityReadLimitDetails } from "./resources-Dbdfbb44.js";
2
2
  export { type EntityBatchInput, type EntityBatchOp, type EntityBatchRefusal, type EntityBatchRefusedDetails, type EntityClient, type EntityCreateInput, type EntityDeleteInput, type EntityFileFieldWrite, type EntityFileValue, type EntityFileWrite, type EntityHttpDestination, type EntityHttpTransportOptions, type EntityListQuery, type EntityMemberValue, type EntityOperation, type EntityOperationResult, type EntityPage, type EntityProtocol, type EntityReadLimitDetails, type EntityRequest, type EntityRestoreInput, type EntityTransport, type EntityUpdateInput, type EntityUploadInput, type EntityUploadSlot, type IdempotencyKey, type PortableResourceSchema, type ResourceCapabilities, type ResourceClient, type ResourceCreateInput, type ResourceCreateRequest, type ResourceCursor, type ResourceDefinition, type ResourceError, type ResourceErrorCode, type ResourceFilter, type ResourceGetRequest, type ResourceId, type ResourceIdentityField, type ResourceJsonValue, type ResourceLifecycleInput, type ResourceLifecycleRequest, type ResourceListQuery, type ResourceListRequest, type ResourceListResult, type ResourceMutationInput, type ResourcePagination, type ResourcePaginationMode, type ResourceRecord, type ResourceRecordId, type ResourceRequestOptions, type ResourceResult, type ResourceRevision, type ResourceSort, type ResourceTransport, type ResourceTransportRequest, type ResourceUpdateRequest, createEntityHttpTransport, createEntityProtocol, createResourceClient, isEntityBatchRefusedError, isEntityReadLimitError };
package/dist/resources.js CHANGED
@@ -1,3 +1,3 @@
1
- import { d as createEntityHttpTransport, g as isEntityReadLimitError, h as isEntityBatchRefusedError, m as createEntityProtocol } from "./service-l8wUAlPK.js";
2
- import { t as createResourceClient } from "./resources-BZKqGxBT.js";
1
+ import { d as createEntityHttpTransport, g as isEntityReadLimitError, h as isEntityBatchRefusedError, m as createEntityProtocol } from "./service-CimYXTmK.js";
2
+ import { t as createResourceClient } from "./resources-BiYIVzGa.js";
3
3
  export { createEntityHttpTransport, createEntityProtocol, createResourceClient, isEntityBatchRefusedError, isEntityReadLimitError };
@@ -1,5 +1,5 @@
1
- import { i as FederatedAuthError, r as CiTransportError, s as ciErrorCodes, t as CiError } from "./errors-C3UmgGGu.js";
2
- import { E as retryAfterMilliseconds, S as fromCiResult, T as createFetchEventSourceFactory, _ as backendErrorCode, b as proxyHttpOptions, v as directHttpOptions, w as toCiResult, y as makeHttpExecute } from "./service-l8wUAlPK.js";
1
+ import { i as FederatedAuthError, r as CiTransportError, s as ciErrorCodes, t as CiError } from "./errors-B4-Jo4j3.js";
2
+ import { E as retryAfterMilliseconds, S as fromCiResult, T as createFetchEventSourceFactory, _ as backendErrorCode, b as proxyHttpOptions, v as directHttpOptions, w as toCiResult, y as makeHttpExecute } from "./service-CimYXTmK.js";
3
3
  import * as Predicate from "effect/Predicate";
4
4
  import * as Schema from "effect/Schema";
5
5
  import * as Arr from "effect/Array";
@@ -25,8 +25,8 @@ import * as Random from "effect/Random";
25
25
  import * as Schedule from "effect/Schedule";
26
26
  import * as Stream from "effect/Stream";
27
27
  import * as Deferred from "effect/Deferred";
28
- import * as Data from "effect/Data";
29
28
  import * as Equal from "effect/Equal";
29
+ import * as Data from "effect/Data";
30
30
  import * as Exit from "effect/Exit";
31
31
  const topicSetDebounceMilliseconds = 300;
32
32
  const pingTimeoutMilliseconds = 45e3;
@@ -1041,7 +1041,8 @@ const createPkcePair = async (crypto = globalThis.crypto) => {
1041
1041
  * Internal. The client SDK Session of one `FederatedAuth`: one tagged enum,
1042
1042
  * the pure `transition` that the store applies to its value
1043
1043
  * `{ epoch, session }`, and `toPublicState`, the public projection. The access
1044
- * token is a field of `Authenticated`, so no other state holds one.
1044
+ * token and the Renewal credential are private fields of `Authenticated`;
1045
+ * `Expired` keeps only the last access token, for `logout`.
1045
1046
  */
1046
1047
  const SessionEnum = Data.taggedEnum();
1047
1048
  const matchSession = SessionEnum.$match;
@@ -1064,7 +1065,7 @@ const transition = (value, event) => {
1064
1065
  session: Anonymous()
1065
1066
  }),
1066
1067
  LoginStarted: () => ({
1067
- epoch: value.epoch,
1068
+ epoch: value.epoch + 1,
1068
1069
  session: Redirecting()
1069
1070
  }),
1070
1071
  Settled: ({ epoch, session }) => epoch === value.epoch ? {
@@ -1073,7 +1074,7 @@ const transition = (value, event) => {
1073
1074
  } : value,
1074
1075
  TokenExpired: () => value.session._tag === "Authenticated" ? {
1075
1076
  epoch: value.epoch,
1076
- session: Expired()
1077
+ session: Expired({ accessToken: value.session.accessToken })
1077
1078
  } : value
1078
1079
  });
1079
1080
  if (!Equal.equals(next.session, value.session)) return next;
@@ -1119,7 +1120,7 @@ const navigation = (navigate) => {
1119
1120
  /**
1120
1121
  * The synchronous store of one Session: one value `{ epoch, session }` that
1121
1122
  * only `dispatch` changes. `dispatch` assigns the next value, then notifies
1122
- * when the Session changed, so a listener reads the new state. A dispatch
1123
+ * when the public state changed, so a listener reads the new state. A dispatch
1123
1124
  * that a listener makes is applied after the current notification ends. A
1124
1125
  * listener that throws stops no other listener and no queued change; the
1125
1126
  * first error is thrown when the queue is empty.
@@ -1145,7 +1146,9 @@ const makeState = () => {
1145
1146
  const previous = value;
1146
1147
  value = transition(previous, next);
1147
1148
  if (value.session === previous.session) continue;
1148
- state = toPublicState(value.session);
1149
+ const changed = toPublicState(value.session);
1150
+ if (Equal.equals(changed, state)) continue;
1151
+ state = changed;
1149
1152
  for (const listener of listeners) try {
1150
1153
  listener(state);
1151
1154
  } catch (error) {
@@ -1190,6 +1193,17 @@ const makeCompletion = () => {
1190
1193
  };
1191
1194
  const transactionLifetimeMs = 6e5;
1192
1195
  const maxReturnTargetLength = 2048;
1196
+ /** `getAccessToken` renews `min(30 s, lifetime / 10)` before expiry. */
1197
+ const maxRenewalMarginMs = 3e4;
1198
+ /**
1199
+ * The waits before the second and the third renewal attempt. With 8 s per
1200
+ * attempt, the last one starts by 17.25 s, inside CI's 30 s reuse window.
1201
+ */
1202
+ const renewalRetryWaitsMs = [250, 1e3];
1203
+ const renewalAttemptTimeoutMs = 8e3;
1204
+ /** After a refusal, the wait for the logout notice of another tab. */
1205
+ const refusalGraceMillis = 500;
1206
+ const formContentType = { "content-type": "application/x-www-form-urlencoded" };
1193
1207
  /** An absolute URL without credentials, else `null`. */
1194
1208
  const absoluteUrl = (value) => {
1195
1209
  try {
@@ -1228,15 +1242,24 @@ const parseToken = (value, now) => {
1228
1242
  const accessToken = own("access_token");
1229
1243
  const expiresIn = own("expires_in");
1230
1244
  if (typeof accessToken !== "string" || accessToken.length === 0 || typeof expiresIn !== "number" || !Number.isFinite(expiresIn) || expiresIn <= 0 || own("token_type") !== "Bearer") return null;
1245
+ const lifetimeMs = expiresIn * 1e3;
1246
+ const refreshToken = own("refresh_token");
1231
1247
  return {
1232
1248
  accessToken,
1233
- expiresAt: now + expiresIn * 1e3
1249
+ expiresAt: now + lifetimeMs,
1250
+ refreshToken: typeof refreshToken === "string" && refreshToken.length > 0 ? refreshToken : null,
1251
+ renewAt: now + lifetimeMs - Math.min(maxRenewalMarginMs, lifetimeMs / 10)
1234
1252
  };
1235
1253
  };
1254
+ const unanswered = { kind: "unanswered" };
1255
+ /** The logout notice between the tabs of one Application in one browser. */
1256
+ const logoutNotice = { type: "logout" };
1236
1257
  /**
1237
1258
  * The session of browser federated sign-in: one PKCE login transaction in
1238
- * `sessionStorage`, and the access token in memory only. A configuration
1239
- * error fails with `FederatedAuthError`.
1259
+ * `sessionStorage`, and the access token and the Renewal credential in
1260
+ * memory only. A logout tells the other tabs through the `BroadcastChannel`
1261
+ * of the client, which the scope closes. A configuration error fails with
1262
+ * `FederatedAuthError`.
1240
1263
  */
1241
1264
  const makeFederated = Effect.fnUntraced(function* makeFederated(options) {
1242
1265
  const tenantUrl = yield* parseUrl(options.tenantUrl, "tenantUrl");
@@ -1253,7 +1276,104 @@ const makeFederated = Effect.fnUntraced(function* makeFederated(options) {
1253
1276
  const storageKey = `ci:federated-auth:${redirectUri.origin}:${options.clientId}`;
1254
1277
  const { changes, dispatch, epoch, getState, session, subscribe } = makeState();
1255
1278
  const completion = makeCompletion();
1279
+ const renewal = makeCompletion();
1256
1280
  let rememberedReturnTo;
1281
+ /** The local part of a logout, also on the notice of another tab. */
1282
+ const clearLocal = () => {
1283
+ completion.reset();
1284
+ renewal.reset();
1285
+ rememberedReturnTo = void 0;
1286
+ storage.removeItem(storageKey);
1287
+ dispatch(LoggedOut());
1288
+ };
1289
+ const channel = yield* Effect.acquireRelease(Effect.sync(() => {
1290
+ if (typeof globalThis.BroadcastChannel !== "function") return null;
1291
+ const opened = new BroadcastChannel(`ci-federated-auth:${options.clientId}`);
1292
+ opened.addEventListener("message", (event) => {
1293
+ if (asRecord$1(event.data)?.type === logoutNotice.type) clearLocal();
1294
+ });
1295
+ return opened;
1296
+ }), (opened) => Effect.sync(() => opened?.close()));
1297
+ const renewalAttempt = (refreshToken) => Effect.tryPromise((signal) => fetch(new URL("/oauth/token", tenantOrigin), {
1298
+ body: new URLSearchParams({
1299
+ client_id: options.clientId,
1300
+ grant_type: "refresh_token",
1301
+ refresh_token: refreshToken
1302
+ }),
1303
+ headers: formContentType,
1304
+ method: "POST",
1305
+ signal
1306
+ })).pipe(Effect.flatMap((response) => {
1307
+ if (response.status === 429) return Effect.succeed({ kind: "throttled" });
1308
+ if (response.status >= 400 && response.status < 500) return Effect.succeed({ kind: "refused" });
1309
+ if (!response.ok) return Effect.succeed(unanswered);
1310
+ return Effect.map(readJson(response), (body) => {
1311
+ const token = parseToken(body, now());
1312
+ return token === null ? unanswered : {
1313
+ kind: "renewed",
1314
+ token
1315
+ };
1316
+ });
1317
+ }), Effect.timeoutOrElse({
1318
+ duration: renewalAttemptTimeoutMs,
1319
+ orElse: () => Effect.succeed(unanswered)
1320
+ }), Effect.orElseSucceed(() => unanswered));
1321
+ /** Up to 3 attempts with one credential, while CI does not answer. */
1322
+ const requestRenewal = Effect.fnUntraced(function* requestRenewal(refreshToken) {
1323
+ let answer = yield* renewalAttempt(refreshToken);
1324
+ for (const wait of renewalRetryWaitsMs) {
1325
+ if (answer.kind !== "unanswered") break;
1326
+ yield* Effect.sleep(wait);
1327
+ answer = yield* renewalAttempt(refreshToken);
1328
+ }
1329
+ return answer;
1330
+ });
1331
+ /**
1332
+ * One renewal of `held`. CI's refusal drops the credential, then waits the
1333
+ * grace for the logout notice of another tab: with no notice the Session
1334
+ * becomes Expired. A result that ends after a logout or a notice changes
1335
+ * nothing (SDK-1).
1336
+ */
1337
+ const renew = Effect.fnUntraced(function* renew(held, refreshToken) {
1338
+ const started = epoch();
1339
+ const answer = yield* requestRenewal(refreshToken);
1340
+ if (answer.kind === "refused") {
1341
+ dispatch(Settled({
1342
+ epoch: started,
1343
+ session: Authenticated({
1344
+ ...held,
1345
+ refreshToken: null
1346
+ })
1347
+ }));
1348
+ yield* Effect.sleep(refusalGraceMillis);
1349
+ dispatch(Settled({
1350
+ epoch: started,
1351
+ session: Expired({ accessToken: held.accessToken })
1352
+ }));
1353
+ return yield* loginRequired();
1354
+ }
1355
+ if (answer.kind === "renewed") {
1356
+ const { token } = answer;
1357
+ dispatch(Settled({
1358
+ epoch: started,
1359
+ session: Authenticated({
1360
+ ...token,
1361
+ identity: null,
1362
+ refreshToken: token.refreshToken ?? refreshToken
1363
+ })
1364
+ }));
1365
+ }
1366
+ if (epoch() !== started) return yield* loginRequired();
1367
+ return answer.kind === "renewed" ? answer.token.accessToken : yield* new FederatedAuthError("renewal_unavailable", "CI did not answer the session renewal");
1368
+ });
1369
+ /** The held token until it expires, for a session with no credential. */
1370
+ const untilExpiry = (accessToken, expiresAt) => Effect.suspend(() => {
1371
+ if (expiresAt <= now()) {
1372
+ dispatch(TokenExpired());
1373
+ return Effect.fail(loginRequired());
1374
+ }
1375
+ return Effect.succeed(accessToken);
1376
+ });
1257
1377
  const normalizedReturnTarget = (value) => Effect.suspend(() => {
1258
1378
  if (value.length > maxReturnTargetLength) return Effect.fail(new FederatedAuthError("invalid_return_target", "The return target is too long"));
1259
1379
  const target = new URL(value, redirectUri.origin);
@@ -1278,6 +1398,7 @@ const makeFederated = Effect.fnUntraced(function* makeFederated(options) {
1278
1398
  authorizationUrl.searchParams.set("code_challenge", pkce.challenge);
1279
1399
  authorizationUrl.searchParams.set("code_challenge_method", pkce.method);
1280
1400
  completion.reset();
1401
+ renewal.reset();
1281
1402
  dispatch(LoginStarted());
1282
1403
  yield* navigate(authorizationUrl.href);
1283
1404
  return authorizationUrl.href;
@@ -1350,22 +1471,34 @@ const makeFederated = Effect.fnUntraced(function* makeFederated(options) {
1350
1471
  getAccessToken: Effect.suspend(() => {
1351
1472
  const current = session();
1352
1473
  if (current._tag !== "Authenticated" || current.accessToken === null) return Effect.fail(loginRequired());
1353
- if (current.expiresAt <= now()) {
1354
- dispatch(TokenExpired());
1355
- return Effect.fail(loginRequired());
1356
- }
1357
- return Effect.succeed(current.accessToken);
1474
+ if (now() < current.renewAt) return Effect.succeed(current.accessToken);
1475
+ return renewal.run(current.refreshToken === null ? untilExpiry(current.accessToken, current.expiresAt) : renew(current, current.refreshToken));
1358
1476
  }),
1359
1477
  getState,
1360
1478
  logout: Effect.suspend(() => {
1361
1479
  const current = session();
1362
- const accessToken = current._tag === "Authenticated" ? current.accessToken : null;
1363
- completion.reset();
1364
- rememberedReturnTo = void 0;
1365
- storage.removeItem(storageKey);
1366
- dispatch(LoggedOut());
1367
- return accessToken === null ? Effect.void : Effect.tryPromise((signal) => fetch(new URL("/oauth/logout", tenantOrigin), {
1368
- headers: { authorization: `Bearer ${accessToken}` },
1480
+ const accessToken = current._tag === "Authenticated" || current._tag === "Expired" ? current.accessToken : null;
1481
+ const refreshToken = current._tag === "Authenticated" ? current.refreshToken : null;
1482
+ clearLocal();
1483
+ channel?.postMessage(logoutNotice);
1484
+ if (accessToken === null) return Effect.void;
1485
+ const request = refreshToken === null ? {
1486
+ body: new URLSearchParams({ client_id: options.clientId }),
1487
+ headers: {
1488
+ ...formContentType,
1489
+ authorization: `Bearer ${accessToken}`
1490
+ }
1491
+ } : {
1492
+ body: new URLSearchParams({
1493
+ access_token: accessToken,
1494
+ client_id: options.clientId,
1495
+ token: refreshToken,
1496
+ token_type_hint: "refresh_token"
1497
+ }),
1498
+ headers: formContentType
1499
+ };
1500
+ return Effect.tryPromise((signal) => fetch(new URL("/oauth/logout", tenantOrigin), {
1501
+ ...request,
1369
1502
  method: "POST",
1370
1503
  signal
1371
1504
  })).pipe(Effect.ignore);
@@ -1458,15 +1591,18 @@ const makeServerSession = Effect.fnUntraced(function* makeServerSession(options)
1458
1591
  invalidSession("The application session is invalid");
1459
1592
  return;
1460
1593
  }
1461
- settle(expiresAt <= now() ? Expired() : Authenticated({
1594
+ settle(expiresAt <= now() ? Expired({ accessToken: null }) : Authenticated({
1462
1595
  accessToken: null,
1463
1596
  expiresAt,
1464
- identity
1597
+ identity,
1598
+ refreshToken: null,
1599
+ renewAt: expiresAt
1465
1600
  }));
1466
1601
  });
1467
1602
  const beginLogin = ({ returnTo }) => Effect.suspend(() => {
1468
1603
  rememberedReturnTo = returnTo;
1469
1604
  const url = `${origin}${basePath}/login?returnTo=${encodeURIComponent(returnTo)}`;
1605
+ completion.reset();
1470
1606
  dispatch(LoginStarted());
1471
1607
  return Effect.as(navigate(url), url);
1472
1608
  });
@@ -1,4 +1,4 @@
1
- import { c as __commonJSMin, l as __toESM, r as CiTransportError, s as ciErrorCodes, t as CiError } from "./errors-C3UmgGGu.js";
1
+ import { c as __commonJSMin, l as __toESM, r as CiTransportError, s as ciErrorCodes, t as CiError } from "./errors-B4-Jo4j3.js";
2
2
  import * as Predicate from "effect/Predicate";
3
3
  import * as Schema from "effect/Schema";
4
4
  import * as Config from "effect/Config";
package/docs/errors.md CHANGED
@@ -26,6 +26,17 @@ class extends `Error`, and `.` and `/effect` export the same class.
26
26
  - A run that does not finish before `deadlineMs` rejects with `CiError`
27
27
  `unavailable` (`retryable: true`).
28
28
 
29
+ ## `getAccessToken` failures
30
+
31
+ `createFederatedAuth().getAccessToken()` fails with `FederatedAuthError`.
32
+ Branch on `getState()` and the code together:
33
+
34
+ | State | `code` | When | What the Application does |
35
+ | --------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
36
+ | `authenticated` | `renewal_unavailable` | CI did not answer the renewal after up to three attempts: a network error, a timeout, a 5xx or an unreadable answer; a 429 at once | Retry later. The session and its Renewal credential stay. |
37
+ | `expired` | `reauthorization_required` | CI refused the renewal, or the session has no Renewal credential and its Access token expired | Keep unsaved state, then call `reauthorize`. |
38
+ | `anonymous` | `reauthorization_required` | A logout in this tab or another tab of the Application ended the session during the call | Show the signed-out view. Sign in again only on a user action. |
39
+
29
40
  ## Rules
30
41
 
31
42
  - Branch with `instanceof` (Promise) or `Effect.catchTag` (Effect), then on
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@collective-intelligence/external-apps-client-sdk",
3
- "version": "0.3.9",
3
+ "version": "0.4.1",
4
4
  "description": "Framework-neutral client for Collective Intelligence external applications.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -62,7 +62,7 @@
62
62
  "ajv-formats": "3.0.1"
63
63
  },
64
64
  "peerDependencies": {
65
- "@collective-intelligence/ai-core": "0.3.9",
65
+ "@collective-intelligence/ai-core": "0.4.1",
66
66
  "effect": "^4.1.0"
67
67
  },
68
68
  "peerDependenciesMeta": {
@@ -71,7 +71,7 @@
71
71
  }
72
72
  },
73
73
  "devDependencies": {
74
- "@collective-intelligence/ai-core": "0.3.9",
74
+ "@collective-intelligence/ai-core": "0.4.1",
75
75
  "@effect/eslint-plugin": "0.3.2",
76
76
  "@effect/vitest": "4.1.4",
77
77
  "@oxlint/plugins": "1.94.0",
@@ -88,5 +88,5 @@
88
88
  "ultracite": "7.10.7",
89
89
  "vitest": "5.0.2"
90
90
  },
91
- "gitHead": "56627fcab8f5db0afbfc57347d0887e6cf7f12a9"
91
+ "gitHead": "1aea8fbbdc15de6ed86458def4327d8b799d0473"
92
92
  }