js-bao-wss-client 3.4.1 → 3.5.0-alpha.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
@@ -889,7 +889,7 @@ Additional flags:
889
889
  ### Pagination and tags
890
890
 
891
891
  - Paging params: `limit`, `cursor`, `forward`, `returnPage`. Default sort is by `grantedAt` (document permission grant time) descending; pass `forward: true` for ascending.
892
- - `returnPage: true` returns `{ items, cursor }` (backward-compatible array when omitted). With `refreshFromServer: true`, a background page walker fetches the remaining pages and updates the cache/`documentMetadataChanged` events; set `refreshFromServer: false` if you only want the first page. Note: cursors come from server responses; local-only/local-first paths do not fabricate cursors or enforce `limit` sizing—use `returnPage: true` when you need a cursor even if data is cached. To synchronously walk all pages yourself, loop on `{ returnPage: true, limit, cursor }` until `cursor` is null. To hydrate the full cache in one call, use `client.syncMetadata({ scope: "all", pageSize, includeRoot })` and then list with `refreshFromServer: false`.
892
+ - `returnPage: true` returns `{ items, hasMore, nextCursor }` (backward-compatible array when omitted). With `refreshFromServer: true`, a background page walker fetches the remaining pages and updates the cache/`documentMetadataChanged` events; set `refreshFromServer: false` if you only want the first page. Note: cursors come from server responses; local-only/local-first paths do not fabricate cursors or enforce `limit` sizing—use `returnPage: true` when you need a cursor even if data is cached. To synchronously walk all pages yourself, loop on `{ returnPage: true, limit, cursor }`, passing each page's `nextCursor` back as `cursor`, until `nextCursor` is absent. To hydrate the full cache in one call, use `client.syncMetadata({ scope: "all", pageSize, includeRoot })` and then list with `refreshFromServer: false`.
893
893
  - Server page size defaults to 100 when `limit` is omitted; you can request smaller/larger pages within server limits.
894
894
  - Tag filtering: `tag: string` performs an exact-match filter server-side. Responses include `tags: string[]` and `grantedAt`; both are cached locally and usable offline (e.g., list + `tag` will be filtered from cache when offline/local-only). Root is also considered for tag queries—if you tag the root, it can appear in tag-filtered results even when the default list filters root out. When `refreshFromServer` is true with a tag, the client still fetches the full dataset in the background to keep the cache complete, then filters locally for the tag.
895
895
  - Tag CRUD: server endpoints exist (`POST /documents/:id/tags { tag }`, `DELETE /documents/:id/tags/:tag`) and document create accepts optional tags; the high-level client currently exposes tagging via HTTP helpers or `client.makeRequest`.
@@ -1410,8 +1410,8 @@ const page1 = await client.document(documentId).blobs().list({ limit: 10 });
1410
1410
  page1.items.forEach((b) => {
1411
1411
  console.log(b.blobId, b.filename, b.size);
1412
1412
  });
1413
- if (page1.cursor) {
1414
- const page2 = await blobs.list({ cursor: page1.cursor });
1413
+ if (page1.nextCursor) {
1414
+ const page2 = await blobs.list({ cursor: page1.nextCursor });
1415
1415
  }
1416
1416
  ```
1417
1417
 
@@ -1941,6 +1941,13 @@ const group = await client.groups.create({
1941
1941
  description: "All engineers",
1942
1942
  });
1943
1943
 
1944
+ // Create a group and stamp resource metadata on it in the same call
1945
+ const readingGroup = await client.groups.create({
1946
+ groupType: "class-reading-group",
1947
+ name: "Reading group",
1948
+ initialMetadata: { classLink: { classId: "class-A" } },
1949
+ });
1950
+
1944
1951
  // List groups
1945
1952
  const groups = await client.groups.list();
1946
1953
  const teams = await client.groups.list({ type: "team" });
@@ -33,6 +33,7 @@ import { GroupTypeConfigsAPI } from "./api/groupTypeConfigsApi";
33
33
  import { CollectionTypeConfigsAPI } from "./api/collectionTypeConfigsApi";
34
34
  import { DatabaseTypeConfigsAPI } from "./api/databaseTypeConfigsApi";
35
35
  import { CollectionsAPI } from "./api/collectionsApi";
36
+ import { AgentsAPI } from "./api/agentSessionsApi";
36
37
  import { InvitationsAPI } from "./api/invitationsApi";
37
38
  import { NotificationsAPI } from "./api/notificationsApi";
38
39
  export { JsBaoError, isJsBaoError, LockTimeoutError, JsBaoApiError, isJsBaoApiError, JsBaoNetworkError, isJsBaoNetworkError, } from "./errors";
@@ -43,7 +44,7 @@ export type { DocumentInfo, DocumentPermissionEntry, DocumentAccessResult, Docum
43
44
  export type { UserProfile, SharedDocument, SharedDocumentListResult, SharedDocumentsOptions, OwnedDocumentsOptions, } from "./api/meApi";
44
45
  export type { SessionInfo } from "./api/sessionApi";
45
46
  export type { BasicUserInfo, BatchUserProfile } from "./api/usersApi";
46
- export type { DatabaseInfo, DatabasePermissionEntry, DatabaseGroupPermissionEntry, GrantDatabaseGroupPermissionParams, DatabaseOwnershipTransferResult, DatabaseOperationInfo, AddManagerParams, GrantPermissionParams, CsvImportOptions, CsvImportProgress, CsvImportResult, CelContextResult, ExecuteOperationOptions, DatabaseChangeEvent, DatabaseChangePayload, DatabaseSubscribeOptions, ListDatabasesOptions, DatabaseListPage, OperationType, OperationFilter, QueryDefinition, MutationOperation, MutationDefinition, CountDefinition, AggregateOperation, AggregateDefinition, PipelineStep, PipelineDefinition, ApplyToQuerySource, ApplyToQueryAction, ApplyToQueryDefinition, OperationDefinition, CreateOperationParams, UpdateOperationParams, } from "./api/databasesApi";
47
+ export type { DatabaseInfo, DatabasePermissionEntry, DatabaseGroupPermissionEntry, GrantDatabaseGroupPermissionParams, DatabaseOwnershipTransferResult, DatabaseOperationInfo, AddManagerParams, CsvImportOptions, CsvImportProgress, CsvImportResult, ExecuteOperationOptions, DatabaseChangeEvent, DatabaseChangePayload, DatabaseSubscribeOptions, ListDatabasesOptions, DatabaseListPage, OperationType, OperationFilter, QueryDefinition, MutationOperation, MutationDefinition, CountDefinition, AggregateOperation, AggregateDefinition, PipelineStep, PipelineDefinition, ApplyToQuerySource, ApplyToQueryAction, ApplyToQueryDefinition, OperationDefinition, CreateOperationParams, UpdateOperationParams, } from "./api/databasesApi";
47
48
  export type { GroupInfo, GroupMemberInfo, GroupMembershipInfo, GroupDocumentInfo, GroupDatabaseInfo, ListUserMembershipsOptions, DirectGroupAdd, DeferredGroupAdd, GroupAddMemberResult, } from "./api/groupsApi";
48
49
  export type { CollectionInfo, CollectionDocumentInfo, CollectionGroupPermissionInfo, CollectionMemberInfo, CollectionAccessInfo, DocumentCollectionInfo, AddCollectionMemberParams, DirectCollectionAdd, DeferredCollectionAdd, CollectionAddMemberResult, PendingCollectionInvitationEntry, } from "./api/collectionsApi";
49
50
  export type { RuleSetInfo, RuleSetSchema, RuleSetTestResult, RuleSetDebugResult, TraceEntry, TriggerDefInfo, ModelRulesInfo, PathDeclaration, RuleLoads, RuleExpression, CategoryRules, } from "./api/ruleSetsApi";
@@ -60,19 +61,21 @@ export type { DocumentBlobContext, BlobUploadSourceOptions, BlobUploadResult, Bl
60
61
  export type { DocumentsAPI, DocumentContext, DocumentAliasesAPI, DocumentIngestsAPI, DocumentSnapshotsAPI, } from "./api/documentsApi";
61
62
  export type { DatabasesAPI } from "./api/databasesApi";
62
63
  export type { CollectionsAPI } from "./api/collectionsApi";
64
+ export type { AgentsAPI, AgentSessionsAPI } from "./api/agentSessionsApi";
65
+ export type { AgentSessionMemberRole, AgentSessionMembers, AgentSessionInfo, AgentSessionListItem, ListAgentSessionsOptions, AgentSessionRenameResult, AgentSessionDeleteResult, AgentSessionMembersResult, } from "./api/agentSessionsApi";
63
66
  export type { MeAPI } from "./api/meApi";
64
67
  export type { SessionAPI } from "./api/sessionApi";
65
68
  export type { UsersAPI } from "./api/usersApi";
66
69
  export type { GroupsAPI } from "./api/groupsApi";
67
70
  export type { RuleSetsAPI } from "./api/ruleSetsApi";
68
71
  export type { NotificationsAPI, NotificationInfo, NotificationListOptions, NotificationListResult, NotificationSendResult, SendNotificationParams, PushDeviceInfo, RegisterPushDeviceParams, } from "./api/notificationsApi";
69
- export type { BlobBucketsAPI, BlobBucketInfo, BlobBucketTtlTier, BlobBucketPreset, BlobBucketAccessPolicy, CreateBlobBucketParams, UpdateBlobBucketParams, BlobInfo, BlobUploadParams, BucketBlobUploadResult, BucketBlobListResult, BlobListOptions, BlobSignedUrlResult, BatchBlobDeleteResult, } from "./api/blobBucketsApi";
72
+ export type { BlobBucketsAPI, BlobBucketInfo, BlobBucketTtlTier, BlobBucketPreset, CreateBlobBucketParams, UpdateBlobBucketParams, BlobInfo, BlobUploadParams, BucketBlobUploadResult, BucketBlobListResult, BlobListOptions, BlobSignedUrlResult, BatchBlobDeleteResult, } from "./api/blobBucketsApi";
70
73
  export type { GroupTypeConfigsAPI } from "./api/groupTypeConfigsApi";
71
74
  export type { CollectionTypeConfigsAPI } from "./api/collectionTypeConfigsApi";
72
75
  export type { DatabaseTypeConfigsAPI } from "./api/databaseTypeConfigsApi";
73
76
  export type { CronTriggersAPI } from "./api/cronTriggersApi";
74
77
  export type { CronTriggerInfo, CreateCronTriggerParams, UpdateCronTriggerParams, CronTriggerListResult, ObjectStatus, } from "./api/cronTriggersApi";
75
- export type { CreateDocumentOptions, CreateOfflineOptions, CreateWithAliasOptions, GetOrCreateWithAliasOptions, DeleteDocumentOptions, DocumentAccessRequest, DocumentAccessRequestResponse, DocumentListOptions, DocumentListPage, EvictAllDocumentsOptions, EvictDocumentOptions, GrantGroupPermissionParams, ResolveAliasParams, SetAliasParams, UpdateDocumentData, DocumentIngestSession, DocumentIngestCounterBucket, DocumentIngestStageCounters, DocumentIngestChunkUpload, DocumentIngestChunkUploadResult, DocumentIngestPage, DocumentSnapshotBuild, DocumentSnapshotPage, DocumentSnapshotRequest, } from "./api/documentsApi";
78
+ export type { CreateDocumentOptions, CreateWithAliasOptions, GetOrCreateWithAliasOptions, DeleteDocumentOptions, DocumentAccessRequest, DocumentAccessRequestResponse, DocumentListOptions, DocumentListPage, EvictAllDocumentsOptions, EvictDocumentOptions, GrantGroupPermissionParams, ResolveAliasParams, SetAliasParams, UpdateDocumentData, DocumentIngestSession, DocumentIngestCounterBucket, DocumentIngestStageCounters, DocumentIngestChunkUpload, DocumentIngestChunkUploadResult, DocumentIngestPage, DocumentSnapshotBuild, DocumentSnapshotPage, DocumentSnapshotRequest, } from "./api/documentsApi";
76
79
  export type { CreateDatabaseParams, UpdateDatabaseParams } from "./api/databasesApi";
77
80
  export type { CreateCollectionParams, UpdateCollectionParams, GrantCollectionGroupPermissionParams, ListCollectionsOptions, } from "./api/collectionsApi";
78
81
  export type { ListResult } from "./api/listResult";
@@ -91,7 +94,7 @@ export type { DocumentDebugSnapshot, DocumentPermission, LocalDocumentEntry, Loc
91
94
  export type { LogLevel } from "./internal/logger";
92
95
  export type { RequestOptions } from "./internal/httpClient";
93
96
  export type { LocksAPI } from "./api/locksApi";
94
- export type { FunctionsAPI, FunctionInvokeOptions, FunctionInvokeResult, FunctionInvokeStatus, FunctionInvokeLimits, FunctionStartOptions, FunctionStartResult, FunctionRunRef, FunctionWaitForResult, FunctionRun, FunctionRunError, FunctionRunErrorCode, FunctionRunSettled, FunctionRunSlice, FunctionRunStatus, FunctionRunStatusValue, FunctionRunTerminalStatus, FunctionWaitOptions, } from "./api/functionsApi";
97
+ export type { FunctionsAPI, FunctionInvokeOptions, FunctionInvokeResult, FunctionInvokeStatus, FunctionInvokeLimits, FunctionStartOptions, FunctionStartResult, FunctionRunRef, FunctionRun, FunctionRunError, FunctionRunErrorCode, FunctionRunSettled, FunctionRunSlice, FunctionRunStatus, FunctionRunStatusValue, FunctionRunTerminalStatus, FunctionWaitOptions, } from "./api/functionsApi";
95
98
  export type { LockHandle, LockContention, AcquireResponse, AcquireOptions, BlockingAcquireOptions, ReleaseResult, RenewResult, LockStatus, LockListEntry, LockListResult, } from "./api/locksApi";
96
99
  export type { ResourceMetadataAPI } from "./api/resourceMetadataApi";
97
100
  export type { ResourceMetadataReadResult, ResourceMetadataWriteResult, ResourceMetadataBatchRequestItem, ResourceMetadataBatchParams, ResourceMetadataBatchCategoryResult, ResourceMetadataBatchResourceResult, ResourceMetadataBatchResult, ResourceMetadataListEntry, ResourceMetadataListResult, ResourceMetadataDeleteResult, ResourceMetadataResolveParams, ResourceMetadataResolveResult, } from "./api/resourceMetadataApi";
@@ -1388,8 +1391,6 @@ export interface ListWorkflowRunsResult {
1388
1391
  nextCursor?: string;
1389
1392
  /** True when a next page exists. */
1390
1393
  hasMore?: boolean;
1391
- /** @deprecated Alias of `nextCursor` kept for one deprecation window. */
1392
- cursor?: string;
1393
1394
  /**
1394
1395
  * How many runs the server examined to produce this page.
1395
1396
  *
@@ -2519,6 +2520,10 @@ export declare class JsBaoClient extends Observable<any> {
2519
2520
  /** Sub-API for managing document collections.
2520
2521
  * @group Sub-APIs */
2521
2522
  collections: CollectionsAPI;
2523
+ /** Sub-API for agents: `agents.sessions` lists, reads, renames and deletes
2524
+ * agent sessions and manages their members.
2525
+ * @group Sub-APIs */
2526
+ agents: AgentsAPI;
2522
2527
  /** Sub-API for managing rule sets.
2523
2528
  * @group Sub-APIs */
2524
2529
  ruleSets: RuleSetsAPI;
@@ -3037,14 +3042,6 @@ export declare class JsBaoClient extends Observable<any> {
3037
3042
  * @param documentId - The document to check for local persistence
3038
3043
  * @group Offline & Sync */
3039
3044
  hasIndexedDbPersistence(documentId: string): Promise<boolean>;
3040
- /** Update the local snapshot flag for a document.
3041
- * @param documentId - The document to update the snapshot flag for
3042
- * @param hasSnapshot - Whether the document has a local IndexedDB snapshot
3043
- * @deprecated No longer called internally — `hasIndexedDbSnapshot` is now
3044
- * ignored in favour of checking live ydoc content via `ydocHasData()`.
3045
- * Retained for external callers; will be removed in a future major version.
3046
- * @group Offline & Sync */
3047
- updateLocalSnapshotFlag(documentId: string, hasSnapshot: boolean): Promise<void>;
3048
3045
  private sendAwarenessState;
3049
3046
  /** Remove awareness states for specific clients.
3050
3047
  * @param documentId - The document to remove awareness from
@@ -4487,8 +4484,6 @@ export declare class JsBaoClient extends Observable<any> {
4487
4484
  * @param timeoutMs - Maximum time to wait before rejecting (ms, default 30000)
4488
4485
  * @group Offline & Sync */
4489
4486
  waitForInitialSync(documentId: string, timeoutMs?: number): Promise<void>;
4490
- /** @deprecated Use {@link waitForInitialSync} instead. */
4491
- waitForSync(documentId: string, timeoutMs?: number): Promise<void>;
4492
4487
  /**
4493
4488
  * Wait until the server confirms it has all of this client's writes.
4494
4489
  * Polls {@link checkStateVector} until `includesWrites` is true.
@@ -46,6 +46,7 @@ import { GroupTypeConfigsAPI } from "./api/groupTypeConfigsApi";
46
46
  import { CollectionTypeConfigsAPI } from "./api/collectionTypeConfigsApi";
47
47
  import { DatabaseTypeConfigsAPI } from "./api/databaseTypeConfigsApi";
48
48
  import { CollectionsAPI } from "./api/collectionsApi";
49
+ import { AgentsAPI } from "./api/agentSessionsApi";
49
50
  import { InvitationsAPI } from "./api/invitationsApi";
50
51
  import { NotificationsAPI } from "./api/notificationsApi";
51
52
  export { JsBaoError, isJsBaoError, LockTimeoutError, JsBaoApiError, isJsBaoApiError, JsBaoNetworkError, isJsBaoNetworkError, } from "./errors";
@@ -1190,6 +1191,7 @@ export class JsBaoClient extends Observable {
1190
1191
  this.databases = new DatabasesAPI(this);
1191
1192
  this.groups = new GroupsAPI(this);
1192
1193
  this.collections = new CollectionsAPI(this);
1194
+ this.agents = new AgentsAPI(this);
1193
1195
  this.ruleSets = new RuleSetsAPI(this);
1194
1196
  this.blobBuckets = new BlobBucketsAPI(this);
1195
1197
  this.groupTypeConfigs = new GroupTypeConfigsAPI(this);
@@ -1755,14 +1757,12 @@ export class JsBaoClient extends Observable {
1755
1757
  const path = `/${endpoint}${qs.length ? `?${qs.join("&")}` : ""}`;
1756
1758
  const response = await this.makeRequest("GET", path);
1757
1759
  if (Array.isArray(response)) {
1758
- return { items: response, cursor: null };
1760
+ return { items: response, nextCursor: null };
1759
1761
  }
1760
1762
  const page = response;
1761
- // #1316: prefer `nextCursor`; fall back to the deprecated `cursor`
1762
- // alias for older servers.
1763
1763
  return {
1764
1764
  items: page.items || [],
1765
- cursor: page.nextCursor ?? page.cursor ?? null,
1765
+ nextCursor: page.nextCursor ?? null,
1766
1766
  };
1767
1767
  };
1768
1768
  const allItems = [];
@@ -1782,7 +1782,7 @@ export class JsBaoClient extends Observable {
1782
1782
  allIds.add(id);
1783
1783
  allItems.push(item);
1784
1784
  }
1785
- cursor = page.cursor || null;
1785
+ cursor = page.nextCursor || null;
1786
1786
  } while (cursor);
1787
1787
  }
1788
1788
  items = allItems;
@@ -2077,13 +2077,13 @@ export class JsBaoClient extends Observable {
2077
2077
  // response says nothing about where the scope ends.
2078
2078
  if (Array.isArray(response))
2079
2079
  return null;
2080
- const items = response?.items ?? response?.documents;
2080
+ const items = response?.items;
2081
2081
  // A body that never mentioned `items` is not a page of this scope, and
2082
2082
  // an empty list read as the whole scope evicts everything.
2083
2083
  if (!Array.isArray(items))
2084
2084
  return null;
2085
2085
  collected.push(...items);
2086
- const next = response?.nextCursor ?? response?.cursor ?? null;
2086
+ const next = response?.nextCursor ?? null;
2087
2087
  if (!next) {
2088
2088
  // No continuation token. If the page nevertheless says more rows
2089
2089
  // remain, the walk cannot ask for them and so never reached the end
@@ -3733,16 +3733,13 @@ export class JsBaoClient extends Observable {
3733
3733
  const path = `/workflows/runs${params.length ? `?${params.join("&")}` : ""}`;
3734
3734
  const response = await this.makeRequest("GET", path);
3735
3735
  const page = response;
3736
- // #1316: prefer `nextCursor`; fall back to the deprecated `cursor` alias
3737
- // for older servers.
3738
- const nextCursor = page?.nextCursor ?? page?.cursor ?? undefined;
3736
+ const nextCursor = page?.nextCursor ?? undefined;
3739
3737
  const result = {
3740
3738
  items: page?.items ?? [],
3741
3739
  hasMore: typeof page?.hasMore === "boolean" ? page.hasMore : !!nextCursor,
3742
3740
  };
3743
3741
  if (nextCursor != null) {
3744
3742
  result.nextCursor = nextCursor;
3745
- result.cursor = nextCursor;
3746
3743
  }
3747
3744
  // #2237: filtered listings report how far the server's walk got. Only
3748
3745
  // surfaced when the server actually sent a number — `undefined` means
@@ -4701,52 +4698,6 @@ export class JsBaoClient extends Observable {
4701
4698
  }
4702
4699
  return false;
4703
4700
  }
4704
- /** Update the local snapshot flag for a document.
4705
- * @param documentId - The document to update the snapshot flag for
4706
- * @param hasSnapshot - Whether the document has a local IndexedDB snapshot
4707
- * @deprecated No longer called internally — `hasIndexedDbSnapshot` is now
4708
- * ignored in favour of checking live ydoc content via `ydocHasData()`.
4709
- * Retained for external callers; will be removed in a future major version.
4710
- * @group Offline & Sync */
4711
- async updateLocalSnapshotFlag(documentId, hasSnapshot) {
4712
- const metaIndex = this.docManager.metadataIndex;
4713
- const existing = metaIndex.get(documentId);
4714
- const currentFlag = existing?.hasIndexedDbSnapshot === true;
4715
- if (hasSnapshot === currentFlag)
4716
- return;
4717
- const next = (existing || { documentId });
4718
- const changedFields = ["hasIndexedDbSnapshot"];
4719
- if (hasSnapshot) {
4720
- next.hasIndexedDbSnapshot = true;
4721
- if (typeof next.localBytes !== "number" || next.localBytes <= 0) {
4722
- next.localBytes = 1;
4723
- changedFields.push("localBytes");
4724
- }
4725
- }
4726
- else {
4727
- delete next.hasIndexedDbSnapshot;
4728
- if (typeof next.localBytes === "number" && next.localBytes > 0) {
4729
- next.localBytes = 0;
4730
- changedFields.push("localBytes");
4731
- }
4732
- }
4733
- metaIndex.set(documentId, next);
4734
- try {
4735
- await this._putMetadataToIdb(next);
4736
- }
4737
- catch (_) { }
4738
- try {
4739
- this.emit("documentMetadataChanged", [
4740
- {
4741
- documentId,
4742
- metadata: next,
4743
- changedFields,
4744
- source: "local",
4745
- },
4746
- ]);
4747
- }
4748
- catch (_) { }
4749
- }
4750
4701
  // Send awareness state to server
4751
4702
  sendAwarenessState(documentId) {
4752
4703
  if (!this.ws || !this.wsconnected)
@@ -11606,10 +11557,6 @@ export class JsBaoClient extends Observable {
11606
11557
  this.on("sync", onSync);
11607
11558
  });
11608
11559
  }
11609
- /** @deprecated Use {@link waitForInitialSync} instead. */
11610
- waitForSync(documentId, timeoutMs = 30000) {
11611
- return this.waitForInitialSync(documentId, timeoutMs);
11612
- }
11613
11560
  /**
11614
11561
  * Wait until the server confirms it has all of this client's writes.
11615
11562
  * Polls {@link checkStateVector} until `includesWrites` is true.
@@ -18,24 +18,31 @@ export { encodeJsonColumn, decodeJsonColumn } from "./sessionModelRuntime";
18
18
  export type { PrimitiveQueueEntry } from "./sessionModelRuntime";
19
19
  /** The schema version a session row carries in `schemaVersion`. */
20
20
  export declare const AGENT_SESSION_SCHEMA_VERSION = 1;
21
+ /** Values this client recognizes for `PrimitiveSessionStatus`. */
21
22
  export declare const PRIMITIVE_SESSION_STATUSES: readonly ["idle", "thinking", "running_tool", "awaiting_answer", "failed", "expired", "cancelled"];
22
23
  /** `"unknown"` is a value a newer server sent that this client does not know. */
23
24
  export type PrimitiveSessionStatus = (typeof PRIMITIVE_SESSION_STATUSES)[number] | "unknown";
25
+ /** Values this client recognizes for `PrimitivePartKind`. */
24
26
  export declare const PRIMITIVE_PART_KINDS: readonly ["text", "reasoning", "tool_call", "file", "event"];
25
27
  /** `"unknown"` is a value a newer server sent that this client does not know. */
26
28
  export type PrimitivePartKind = (typeof PRIMITIVE_PART_KINDS)[number] | "unknown";
29
+ /** Values this client recognizes for `PrimitiveTextState`. */
27
30
  export declare const PRIMITIVE_TEXT_STATES: readonly ["streaming", "done"];
28
31
  /** `"unknown"` is a value a newer server sent that this client does not know. */
29
32
  export type PrimitiveTextState = (typeof PRIMITIVE_TEXT_STATES)[number] | "unknown";
33
+ /** Values this client recognizes for `PrimitiveToolCallState`. */
30
34
  export declare const PRIMITIVE_TOOL_CALL_STATES: readonly ["input-streaming", "input-available", "approval-requested", "approval-responded", "output-available", "output-error", "output-denied"];
31
35
  /** `"unknown"` is a value a newer server sent that this client does not know. */
32
36
  export type PrimitiveToolCallState = (typeof PRIMITIVE_TOOL_CALL_STATES)[number] | "unknown";
37
+ /** Values this client recognizes for `PrimitiveAuthorKind`. */
33
38
  export declare const PRIMITIVE_AUTHOR_KINDS: readonly ["user", "agent", "app"];
34
39
  /** `"unknown"` is a value a newer server sent that this client does not know. */
35
40
  export type PrimitiveAuthorKind = (typeof PRIMITIVE_AUTHOR_KINDS)[number] | "unknown";
41
+ /** Values this client recognizes for `PrimitiveStepKind`. */
36
42
  export declare const PRIMITIVE_STEP_KINDS: readonly ["model_call", "tool_call"];
37
43
  /** `"unknown"` is a value a newer server sent that this client does not know. */
38
44
  export type PrimitiveStepKind = (typeof PRIMITIVE_STEP_KINDS)[number] | "unknown";
45
+ /** Values this client recognizes for `PrimitiveStepStatus`. */
39
46
  export declare const PRIMITIVE_STEP_STATUSES: readonly ["running", "completed", "failed"];
40
47
  /** `"unknown"` is a value a newer server sent that this client does not know. */
41
48
  export type PrimitiveStepStatus = (typeof PRIMITIVE_STEP_STATUSES)[number] | "unknown";
@@ -182,18 +189,21 @@ interface PrimitivePartRecordBase {
182
189
  modifiedAt?: string;
183
190
  row?: PrimitivePartRow;
184
191
  }
192
+ /** A decoded `PrimitivePart` record with `kind: "text"`. */
185
193
  export interface PrimitiveTextPartRecord extends PrimitivePartRecordBase {
186
194
  kind: "text";
187
195
  state?: PrimitiveTextState;
188
196
  text?: string;
189
197
  providerMetadata?: Record<string, unknown>;
190
198
  }
199
+ /** A decoded `PrimitivePart` record with `kind: "reasoning"`. */
191
200
  export interface PrimitiveReasoningPartRecord extends PrimitivePartRecordBase {
192
201
  kind: "reasoning";
193
202
  state?: PrimitiveTextState;
194
203
  text?: string;
195
204
  providerMetadata?: Record<string, unknown>;
196
205
  }
206
+ /** A decoded `PrimitivePart` record with `kind: "tool_call"`. */
197
207
  export interface PrimitiveToolCallPartRecord extends PrimitivePartRecordBase {
198
208
  kind: "tool_call";
199
209
  state?: PrimitiveToolCallState;
@@ -213,6 +223,7 @@ export interface PrimitiveToolCallPartRecord extends PrimitivePartRecordBase {
213
223
  artifactBlobId?: string;
214
224
  providerMetadata?: Record<string, unknown>;
215
225
  }
226
+ /** A decoded `PrimitivePart` record with `kind: "file"`. */
216
227
  export interface PrimitiveFilePartRecord extends PrimitivePartRecordBase {
217
228
  kind: "file";
218
229
  mediaType?: string;
@@ -220,6 +231,7 @@ export interface PrimitiveFilePartRecord extends PrimitivePartRecordBase {
220
231
  blobId?: string;
221
232
  sizeBytes?: number;
222
233
  }
234
+ /** A decoded `PrimitivePart` record with `kind: "event"`. */
223
235
  export interface PrimitiveEventPartRecord extends PrimitivePartRecordBase {
224
236
  kind: "event";
225
237
  eventKind?: string;
@@ -233,6 +245,7 @@ export interface PrimitiveUnknownPartRecord extends PrimitivePartRecordBase {
233
245
  rawKind: string;
234
246
  row: PrimitivePartRow;
235
247
  }
248
+ /** A decoded `PrimitivePart` record, including unrecognized kinds. */
236
249
  export type PrimitivePartRecord = PrimitiveTextPartRecord | PrimitiveReasoningPartRecord | PrimitiveToolCallPartRecord | PrimitiveFilePartRecord | PrimitiveEventPartRecord | PrimitiveUnknownPartRecord;
237
250
  /** The attributes of a `PrimitivePart` model instance. */
238
251
  export interface PrimitivePartAttrs {
@@ -20,6 +20,7 @@ import { decodeModelRow, encodeModelRecord, registerSessionModels, sessionRowInv
20
20
  export { encodeJsonColumn, decodeJsonColumn } from "./sessionModelRuntime";
21
21
  /** The schema version a session row carries in `schemaVersion`. */
22
22
  export const AGENT_SESSION_SCHEMA_VERSION = 1;
23
+ /** Values this client recognizes for `PrimitiveSessionStatus`. */
23
24
  export const PRIMITIVE_SESSION_STATUSES = [
24
25
  "idle",
25
26
  "thinking",
@@ -29,6 +30,7 @@ export const PRIMITIVE_SESSION_STATUSES = [
29
30
  "expired",
30
31
  "cancelled",
31
32
  ];
33
+ /** Values this client recognizes for `PrimitivePartKind`. */
32
34
  export const PRIMITIVE_PART_KINDS = [
33
35
  "text",
34
36
  "reasoning",
@@ -36,7 +38,9 @@ export const PRIMITIVE_PART_KINDS = [
36
38
  "file",
37
39
  "event",
38
40
  ];
41
+ /** Values this client recognizes for `PrimitiveTextState`. */
39
42
  export const PRIMITIVE_TEXT_STATES = ["streaming", "done"];
43
+ /** Values this client recognizes for `PrimitiveToolCallState`. */
40
44
  export const PRIMITIVE_TOOL_CALL_STATES = [
41
45
  "input-streaming",
42
46
  "input-available",
@@ -46,8 +50,11 @@ export const PRIMITIVE_TOOL_CALL_STATES = [
46
50
  "output-error",
47
51
  "output-denied",
48
52
  ];
53
+ /** Values this client recognizes for `PrimitiveAuthorKind`. */
49
54
  export const PRIMITIVE_AUTHOR_KINDS = ["user", "agent", "app"];
55
+ /** Values this client recognizes for `PrimitiveStepKind`. */
50
56
  export const PRIMITIVE_STEP_KINDS = ["model_call", "tool_call"];
57
+ /** Values this client recognizes for `PrimitiveStepStatus`. */
51
58
  export const PRIMITIVE_STEP_STATUSES = [
52
59
  "running",
53
60
  "completed",
@@ -0,0 +1,152 @@
1
+ import type { JsBaoClient } from "../JsBaoClient";
2
+ import type { ListResult } from "./listResult";
3
+ /**
4
+ * A member's role in an agent session. A `viewer` reads the session and
5
+ * holds a `reader` grant on its document; a `participant` also sends
6
+ * messages and holds a `read-write` grant.
7
+ */
8
+ export type AgentSessionMemberRole = "viewer" | "participant";
9
+ /** A session's members, each list in the order they were added. */
10
+ export interface AgentSessionMembers {
11
+ viewers: string[];
12
+ participants: string[];
13
+ }
14
+ /**
15
+ * One agent session, as `client.agents.sessions.get()` answers it: who it
16
+ * belongs to, which agent it runs, its members, and the document that holds
17
+ * its conversation. The conversation itself is read by opening `documentId`
18
+ * with the document client, never through this call.
19
+ */
20
+ export interface AgentSessionInfo {
21
+ sessionId: string;
22
+ /** The agent prompt the session is bound to. */
23
+ agentKey: string;
24
+ /** The session's conversation document. */
25
+ documentId: string;
26
+ ownerUserId: string;
27
+ /** ISO-8601. */
28
+ createdAt: string;
29
+ title: string | null;
30
+ scope: string | null;
31
+ /** ISO-8601; null when the session's listing entry is missing. */
32
+ lastActivityAt: string | null;
33
+ members: AgentSessionMembers;
34
+ /**
35
+ * The caller's standing: their role in the session, or `admin` when they
36
+ * reached it as an app owner or admin without being in it.
37
+ */
38
+ role: "owner" | "participant" | "viewer" | "admin";
39
+ }
40
+ /**
41
+ * One entry of `client.agents.sessions.list()`: what an app shows in a
42
+ * session list without opening any document.
43
+ */
44
+ export interface AgentSessionListItem {
45
+ sessionId: string;
46
+ agentKey: string;
47
+ scope: string | null;
48
+ documentId: string;
49
+ ownerUserId: string;
50
+ /** The listed user's role in the session. */
51
+ role: "owner" | "participant" | "viewer";
52
+ title: string | null;
53
+ /** ISO-8601. */
54
+ lastActivityAt: string;
55
+ createdAt: string | null;
56
+ }
57
+ /** Filters and paging for `client.agents.sessions.list()`. */
58
+ export interface ListAgentSessionsOptions {
59
+ /**
60
+ * Whose sessions to list. Omit it for your own; naming another user
61
+ * requires being an app owner or admin.
62
+ */
63
+ userId?: string;
64
+ /** Only this agent's sessions. */
65
+ agent?: string;
66
+ /** Only sessions created with exactly this scope. */
67
+ scope?: string;
68
+ /** Page size, at most 100 (default 50). */
69
+ limit?: number;
70
+ /** The `nextCursor` of the previous page. */
71
+ cursor?: string;
72
+ }
73
+ /** What `client.agents.sessions.rename()` answers. */
74
+ export interface AgentSessionRenameResult {
75
+ sessionId: string;
76
+ title: string;
77
+ }
78
+ /** What `client.agents.sessions.delete()` answers. */
79
+ export interface AgentSessionDeleteResult {
80
+ deleted: boolean;
81
+ sessionId: string;
82
+ documentId: string;
83
+ }
84
+ /** What the member calls answer: the members after the change. */
85
+ export interface AgentSessionMembersResult {
86
+ members: AgentSessionMembers;
87
+ }
88
+ /**
89
+ * Agent sessions, available as `client.agents.sessions`.
90
+ *
91
+ * A session is created by a server function (`ctx.agents.createSession`);
92
+ * from a client you list the sessions you own or belong to, read one, and —
93
+ * as its owner — rename it, delete it and manage its members. App owners and
94
+ * admins may also list any user's sessions and get or delete any session.
95
+ * A refusal rejects with the client's ordinary request error carrying the
96
+ * server's `code` (for example `AGENT_SESSION_OWNER_ONLY` or
97
+ * `AGENT_SESSION_NOT_FOUND`).
98
+ */
99
+ export declare class AgentSessionsAPI {
100
+ private client;
101
+ /** @internal */
102
+ constructor(client: JsBaoClient);
103
+ /**
104
+ * List one user's sessions — your own by default — newest first. Pages may
105
+ * be shorter than `limit` when `scope` filters entries out; follow
106
+ * `nextCursor` while `hasMore` is true.
107
+ * @param options - Whose sessions, filters and paging
108
+ */
109
+ list(options?: ListAgentSessionsOptions): Promise<ListResult<AgentSessionListItem>>;
110
+ /**
111
+ * Get one session. Members, the owner, app owners and admins may; anyone
112
+ * else is answered `AGENT_SESSION_NOT_FOUND`.
113
+ * @param sessionId - The session
114
+ */
115
+ get(sessionId: string): Promise<AgentSessionInfo>;
116
+ /**
117
+ * Rename a session (owner only). The title changes on the session, in every
118
+ * member's list, and on the document.
119
+ * @param sessionId - The session
120
+ * @param title - 1 to 255 characters
121
+ */
122
+ rename(sessionId: string, title: string): Promise<AgentSessionRenameResult>;
123
+ /**
124
+ * Delete a session and its document (the owner, an app owner or an admin).
125
+ * Deleting a session that is already deleted succeeds again.
126
+ * @param sessionId - The session
127
+ */
128
+ delete(sessionId: string): Promise<AgentSessionDeleteResult>;
129
+ /**
130
+ * Add a member, or change an existing member's role (owner only). The user
131
+ * must be an existing user of this app; a session holds at most 50 members.
132
+ * @param sessionId - The session
133
+ * @param userId - The user to add
134
+ * @param role - `viewer` or `participant`
135
+ */
136
+ addMember(sessionId: string, userId: string, role: AgentSessionMemberRole): Promise<AgentSessionMembersResult>;
137
+ /**
138
+ * Remove a member (owner only): their grant on the document is revoked and
139
+ * the session leaves their list. Removing someone who is not a member
140
+ * succeeds with the members unchanged.
141
+ * @param sessionId - The session
142
+ * @param userId - The member to remove
143
+ */
144
+ removeMember(sessionId: string, userId: string): Promise<AgentSessionMembersResult>;
145
+ }
146
+ /** Agents, available as `client.agents`. */
147
+ export declare class AgentsAPI {
148
+ /** Agent sessions: list, get, rename, delete and members. */
149
+ readonly sessions: AgentSessionsAPI;
150
+ /** @internal */
151
+ constructor(client: JsBaoClient);
152
+ }
@@ -0,0 +1,91 @@
1
+ import { normalizeListEnvelope } from "../internal/listEnvelope.js";
2
+ /**
3
+ * Agent sessions, available as `client.agents.sessions`.
4
+ *
5
+ * A session is created by a server function (`ctx.agents.createSession`);
6
+ * from a client you list the sessions you own or belong to, read one, and —
7
+ * as its owner — rename it, delete it and manage its members. App owners and
8
+ * admins may also list any user's sessions and get or delete any session.
9
+ * A refusal rejects with the client's ordinary request error carrying the
10
+ * server's `code` (for example `AGENT_SESSION_OWNER_ONLY` or
11
+ * `AGENT_SESSION_NOT_FOUND`).
12
+ */
13
+ export class AgentSessionsAPI {
14
+ /** @internal */
15
+ constructor(client) {
16
+ this.client = client;
17
+ }
18
+ /**
19
+ * List one user's sessions — your own by default — newest first. Pages may
20
+ * be shorter than `limit` when `scope` filters entries out; follow
21
+ * `nextCursor` while `hasMore` is true.
22
+ * @param options - Whose sessions, filters and paging
23
+ */
24
+ async list(options) {
25
+ const params = new URLSearchParams();
26
+ if (options?.userId !== undefined)
27
+ params.set("userId", options.userId);
28
+ if (options?.agent !== undefined)
29
+ params.set("agent", options.agent);
30
+ if (options?.scope !== undefined)
31
+ params.set("scope", options.scope);
32
+ if (options?.limit !== undefined)
33
+ params.set("limit", String(options.limit));
34
+ if (options?.cursor)
35
+ params.set("cursor", options.cursor);
36
+ const qs = params.toString();
37
+ return normalizeListEnvelope(await this.client.makeRequest("GET", `/agent-sessions${qs ? `?${qs}` : ""}`));
38
+ }
39
+ /**
40
+ * Get one session. Members, the owner, app owners and admins may; anyone
41
+ * else is answered `AGENT_SESSION_NOT_FOUND`.
42
+ * @param sessionId - The session
43
+ */
44
+ async get(sessionId) {
45
+ return this.client.makeRequest("GET", `/agent-sessions/${encodeURIComponent(sessionId)}`);
46
+ }
47
+ /**
48
+ * Rename a session (owner only). The title changes on the session, in every
49
+ * member's list, and on the document.
50
+ * @param sessionId - The session
51
+ * @param title - 1 to 255 characters
52
+ */
53
+ async rename(sessionId, title) {
54
+ return this.client.makeRequest("PATCH", `/agent-sessions/${encodeURIComponent(sessionId)}`, { title });
55
+ }
56
+ /**
57
+ * Delete a session and its document (the owner, an app owner or an admin).
58
+ * Deleting a session that is already deleted succeeds again.
59
+ * @param sessionId - The session
60
+ */
61
+ async delete(sessionId) {
62
+ return this.client.makeRequest("DELETE", `/agent-sessions/${encodeURIComponent(sessionId)}`);
63
+ }
64
+ /**
65
+ * Add a member, or change an existing member's role (owner only). The user
66
+ * must be an existing user of this app; a session holds at most 50 members.
67
+ * @param sessionId - The session
68
+ * @param userId - The user to add
69
+ * @param role - `viewer` or `participant`
70
+ */
71
+ async addMember(sessionId, userId, role) {
72
+ return this.client.makeRequest("POST", `/agent-sessions/${encodeURIComponent(sessionId)}/members`, { userId, role });
73
+ }
74
+ /**
75
+ * Remove a member (owner only): their grant on the document is revoked and
76
+ * the session leaves their list. Removing someone who is not a member
77
+ * succeeds with the members unchanged.
78
+ * @param sessionId - The session
79
+ * @param userId - The member to remove
80
+ */
81
+ async removeMember(sessionId, userId) {
82
+ return this.client.makeRequest("DELETE", `/agent-sessions/${encodeURIComponent(sessionId)}/members/${encodeURIComponent(userId)}`);
83
+ }
84
+ }
85
+ /** Agents, available as `client.agents`. */
86
+ export class AgentsAPI {
87
+ /** @internal */
88
+ constructor(client) {
89
+ this.sessions = new AgentSessionsAPI(client);
90
+ }
91
+ }