@bobannomi/client 0.3.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -36,11 +36,13 @@ const terminals = await session.terminals.list();
36
36
 
37
37
  文件路径相对于 daemon 上的会话执行目录。`session.prompt(input)` 返回输入接纳结果,有 `run.id` 时用 `session.waitForRun(run.id, { signal })` 取得该次运行的终态和消息。取消等待只结束观察,停止后台运行用 `session.interrupt({ expectedRunId: run.id })`。权限请求继续由调用方处理。已有会话的应用自定义数据通过 `session.updateAppMetadata(data)` 更新。改名、置顶、归档和删除从 `session.management` 读取版本再提交。 [可运行示例](../../apps/client-docs/examples/README.md) · [Client SDK 使用指南](../../docs/client-sdk.md)
38
38
 
39
- ## 独立客户端管理模型供应商
39
+ ## 在应用里使用自带供应商
40
+
41
+ 初始化 `BobanNomiClient` 时,传入应用的 `providers`。每项包含模型列表和 `connection: { baseUrl, apiKey, apiFormat: "openai" }`。`providers` 和 `connection` 都可以按需加载。用 `client.models.list()` 展示模型选项,再用选中的供应商和模型 ID 创建会话并发送消息。省略 `providers` 时读取 daemon 的模型目录。 [完整调用示例](../../apps/client-docs/src/content/docs/guides/models-schedules.mdx#在应用里使用自带供应商)
40
42
 
41
- 向 `new BobanNomiClient({ ...connectionOptions, providers })` 传入 `ModelProviderInfo[]` 或接收 `{ signal }` 的异步读取函数,可用自己的目录。`client.models.list()` 按需从该目录读数据。省略 `providers` 时请求 daemon 的 `/models`。目录包含 ID、显示名和能力,连接地址、密钥、请求头另行通过管理入口配置。 [完整调用示例](../../apps/client-docs/src/content/docs/guides/models-schedules.mdx#提供自己的模型目录)
43
+ ## 独立客户端管理模型供应商
42
44
 
43
- 在 Node 中使用后台的管理 Bearer Token 连接。页面或会话连接可用 `client.models.list()` 读取允许使用的模型。供应商管理、连接测试及全局默认设置需要有管理权限的后台连接。内置工作台由 Electron Main 验证页面身份和数据范围后代为请求。
45
+ 用管理权限连接 daemon,可以为工作台和其他客户端统一保存模型连接、测试连接及设置全局默认模型。Node 管理脚本使用后台的管理 token。内置工作台由 Electron Main 验证页面身份和数据范围后代为请求。 [后台管理步骤](../../apps/client-docs/src/content/docs/guides/models-schedules.mdx#管理后台的供应商和默认模型)
44
46
 
45
47
  ```ts
46
48
  import { BobanNomiClient } from "@bobannomi/client";
package/dist/index.d.ts CHANGED
@@ -539,44 +539,6 @@ interface PermissionRequestRecord {
539
539
  updatedAt: number;
540
540
  }
541
541
 
542
- interface PluginUiInventory {
543
- manifestCount: number;
544
- componentCount: number | null;
545
- validatedComponentCount: number;
546
- }
547
- interface PluginUiInstanceRecord {
548
- schemaVersion: 2;
549
- instanceId: string;
550
- sessionId: string;
551
- sourceRunId: string;
552
- sourcePartId: string;
553
- sourceToolUseId: string;
554
- sourceToolName: string;
555
- pluginId: string;
556
- pluginVersion: string;
557
- pluginDigest: string;
558
- componentId: string;
559
- componentDigest: string;
560
- title: string;
561
- surface: "tool-result" | "session-sidebar";
562
- status: "open" | "resolved" | "dismissed";
563
- revision: number;
564
- data: Record<string, JsonValue>;
565
- activeActionRunId?: string;
566
- lastActionRunId?: string;
567
- dismissal?: {
568
- requestId: string;
569
- requestFingerprint: string;
570
- expectedRevision: number;
571
- revision: number;
572
- dismissedAt: number;
573
- };
574
- createdAt: number;
575
- updatedAt: number;
576
- }
577
- /** Shape validation only; the Server must also verify ownership against the actual Part. */
578
- declare function readPluginUiInstance(metadata: unknown): PluginUiInstanceRecord | undefined;
579
-
580
542
  type SessionManagementAction = "rename" | "pin" | "archive" | "delete";
581
543
  interface SessionMutationResult {
582
544
  readonly sessionId: string;
@@ -1918,7 +1880,6 @@ interface PluginInfo {
1918
1880
  };
1919
1881
  runtimeStatus: PluginRuntimeStatus;
1920
1882
  inventory: Record<string, number>;
1921
- uiInventory?: PluginUiInventory;
1922
1883
  permissions: {
1923
1884
  requested: string[];
1924
1885
  approved: string[];
@@ -2239,11 +2200,13 @@ interface RawRequestOptions extends RequestInit {
2239
2200
  query?: Record<string, unknown>;
2240
2201
  auth?: boolean;
2241
2202
  }
2242
- /** HTTP API 非 2xx 时抛出;携带 status 与原始响应体。 */
2203
+ /** HTTP API 非 2xx 时抛出,保留状态、响应体、可识别的错误码与服务端追踪 ID。 */
2243
2204
  declare class BobanNomiApiError extends Error {
2244
2205
  readonly status: number;
2245
2206
  readonly body: unknown;
2246
- constructor(message: string, status: number, body: unknown);
2207
+ readonly traceId?: string | undefined;
2208
+ readonly code?: string;
2209
+ constructor(message: string, status: number, body: unknown, traceId?: string | undefined);
2247
2210
  }
2248
2211
  declare function responseField(value: unknown, field: string): unknown;
2249
2212
  declare function responseArray<T>(value: unknown, field: string, decode: (item: unknown) => T): T[];
@@ -2948,6 +2911,14 @@ declare function selectSessionTasks(bucket: SessionBucket | undefined): SessionE
2948
2911
  declare function selectSessionPermissions(bucket: SessionBucket | undefined): PermissionRequestRecord[];
2949
2912
  declare function selectFirstPendingPermission(state: BobanNomiClientState, sessionId?: string): PermissionRequestRecord | undefined;
2950
2913
 
2914
+ interface SessionObservation {
2915
+ source: SyncEventUpdate["source"];
2916
+ messages: SessionMessageWithParts[];
2917
+ inputs: SessionInputRecord[];
2918
+ runs: SessionRunRecord[];
2919
+ permissions: PermissionRequestRecord[];
2920
+ }
2921
+
2951
2922
  interface RunResult {
2952
2923
  run: SessionRunRecord;
2953
2924
  messages: SessionMessageWithParts[];
@@ -2963,6 +2934,10 @@ interface SessionHandle {
2963
2934
  getState(options?: RequestOptions$8 & {
2964
2935
  partView?: "summary";
2965
2936
  }): Promise<AgentSessionStateSnapshot>;
2937
+ /** Observe the current messages, inputs, runs and permission requests for this session. */
2938
+ observe(options?: RequestOptions$8 & {
2939
+ partView?: "summary";
2940
+ }): AsyncIterable<SessionObservation>;
2966
2941
  /** Merge JSON fields into this session's application metadata on the daemon. */
2967
2942
  updateAppMetadata(metadata: Record<string, unknown>, options?: RequestOptions$8): Promise<SessionRecord>;
2968
2943
  /** Submit an input and return its admission result. */
@@ -4160,5 +4135,5 @@ declare function isWorkMode(value: unknown): value is WorkMode;
4160
4135
  declare function readSessionRuntimeConfig(session: SessionRecord, defaults?: Partial<SessionRuntimeConfig>): SessionRuntimeConfig;
4161
4136
  declare function patchSessionRuntimeMetadata(metadata: Record<string, unknown>, patch: SessionRuntimeConfigPatch): Record<string, unknown>;
4162
4137
 
4163
- export { AttachmentResource, BobanNomiApiError, BobanNomiClient, CURRENT_PROTOCOL_VERSION, ChannelResource, CommandResource, ContextResource, DiagnosticResource, EventResource, GitResource, HookResource, HttpTransport, IncompatibleProtocolError, MaintenanceResource, McpResource, McpServersResource, MemoryResource, PermissionResource, PluginMarketplaceResource, PluginResource, ProjectResource, ProtocolClient, ProtocolValidationError, ScheduleResource, SessionResource, SessionSyncController, SettingsResource, SseTransport, TerminalResource, UnsupportedSessionEventSchemaVersionError, WorktreeResource, applyEvent, applyEvents, attachmentRangeHeader, checkProtocolCompatibility, createClientState, createSessionRequestId, getVisibleSessionMessages, hydrateState, isSupersededModelPart, isWorkMode, normalizeApprovalMode, normalizeDaemonBaseUrl, parseCreateSessionGoalInput, parseGoalActionInput, parseMcpCallResultData, parseUpdateSessionGoalInput, patchSessionRuntimeMetadata, readPluginUiInstance, readRuntimeMetadata, readSessionModelRetryState, readSessionModelUsage, readSessionRuntimeConfig, readWorkspaceChangesMetadata, replaceSessionState, responseArray, responseField, selectFirstPendingPermission, selectSessionInputs, selectSessionMessagesWithParts, selectSessionModelRetry, selectSessionModelUsage, selectSessionOrderedMessages, selectSessionParts, selectSessionPermissions, selectSessionRuns, selectSessionTasks, streamServerSentEvents, supportsFeature, syncEvents };
4164
- export type { AdmitClientPromptInput, AdmitPromptAttachmentInput, AgentEnvironmentCapabilities, AgentPersonaInfo, ApprovalMode, ApprovalReviewRecord, AttachmentAssetRecord, AttachmentStorageGcResult, AttachmentStorageIssue, AttachmentStorageRepairResult, AttachmentStorageReport, AuthStatus, BobanNomiClientOptions, BobanNomiClientState, BobanNomiServerHealth, CancelQueuedClientPromptInput, CancelQueuedPromptResponse, CancelResponseMode, ChannelConnectorRuntimeStatus, ChannelDeliveryRecord, ChannelDeliveryStatus, ChannelDenialNotice, ChannelDomain, ChannelQuery, ChannelRuntimeControlInput, ChannelRuntimeState, ChannelRuntimeStatus, ChannelStatusSnapshot, CleanupCandidate, CleanupPreview, CleanupResult, ClearMemoryInput, ClientModelConnection, ClientModelProvider, ClientProtocolSupport, CommandCatalogEntry, CommandKind, CommandSelection, CommandSource, ConfigureClientSessionInput, ContextBucketId, ContextUsageBucket, ContextUsageSnapshot, ContextUsageTip, ContextUsageTipCode, CreateBackgroundShellInput, CreateBackgroundShellResult, CreateClientSessionInput, CreateScheduledTaskInput, CreateSessionByProjectInput, CreateSessionGoalInput, CreateSessionWithDirectoryInput, CustomModelProviderInput, DaemonRestartPreview, DiagnosticExecutionQuery, DispatchedSessionCreation, DispatchedSessionCreationRequest, DownloadAttachmentOptions, DraftComposerOptions, DraftComposerTarget, DurableChannelMessageInput, DurableChannelMessageResult, EditLatestClientPromptInput, EventSyncOptions, ExecutionInstructions, ExpectedModelConnection, ExternalConversationRecord, FactReplacementResult, FeishuAllowInput, FeishuChannelSnapshot, FeishuComposedSnapshot, FeishuConnectInput, FeishuPatchInput, FeishuRegistrationSnapshot, FeishuRegistrationStartInput, FeishuRegistrationState, ForkClientSessionInput, GlobalSettingsPatch, GoalActionInput, GoalExternalWait, GoalStopReason, HookInfo, HostDiagnosticSnapshots, HttpRequestOptions, HttpTransportOptions, InputDelivery, InterruptSessionResponse, JobCancelReceipt, JobCapabilities, JobInputReceipt, JobKind, JobListResult, JobReadResult, JobSnapshot, JobStatus, JobTarget, JobWaitResult, JsonValue, ListClientMessagePartsOptions, ListCommandsOptions, ListEventsOptions, ListMessagePartsOptions, ListMessagesOptions, ListPermissionsOptions, ListProjectsOptions, ListSessionJobsOptions, ListSessionsOptions, MaintenanceBackupManifest, MaintenanceBackupResult, MarketplaceAddSourceRequest, MarketplaceCancelRequest, MarketplaceCancelResponse, MarketplaceCatalog, MarketplaceCatalogRequest, MarketplaceEntry, MarketplaceInstallInput, MarketplaceInstallRequest, MarketplaceOperation, MarketplacePreview, MarketplacePreviewRequest, MarketplaceProvenance, MarketplaceSelection, MarketplaceSource, MarketplaceSourceEnabledRequest, MarketplaceSourceView, MarketplaceSourcesResponse, McpConfigOperationResult, McpManagedServerConfig, McpManagedServerSummary, McpOAuthLoginInput, McpOAuthLoginResponse, McpOAuthStatusSnapshot, McpRuntimeStatus, McpRuntimeSyncResult, McpServerRuntimeRef, McpServerStatus, MemoryEntryRecord, MemoryListResponse, MemoryRevision, ModelInfo, ModelProviderConnection, ModelProviderInfo, ModelProviderRequest, OAuthOperationEvent, OAuthOperationView, OutputStyleInfo, PermissionRequestRecord, PermissionStatus, PluginArchiveError, PluginArchiveInstallInput, PluginArchivePreview, PluginArchivePreviewInput, PluginGitInstallInput, PluginGitPreview, PluginGitPreviewInput, PluginInfo, PluginListResult, PluginLocalInstallInput, PluginLocalPreview, PluginLocalPreviewInput, PluginRuntimeStatus, PluginUiInstanceRecord, PluginUiInventory, ProjectFactRecord, ProjectRecord, PromoteQueuedClientPromptInput, PromoteQueuedPromptResponse, PromptResponse, ProtocolCompatibility, ProviderConnectionTestResult, ProviderDefaultsRequest, ProviderDefaultsSnapshot, ProviderInfo, QueuedPromptCancelReceipt, RawRequestOptions, RecordChannelDeliveryInput, ReloadPluginsResponse, RememberSessionResponse, ReplyPermissionInput, ResolvedSessionConfiguration, ResumeInterruptedRunInput, ResumeInterruptedRunResponse, RewindSessionResponse, RunResult, ScheduledRunRecord, ScheduledTaskRecord, ScheduledTaskStatusSummary, SearchSessionsOptions, ServerCapabilities, SessionActivityPage, SessionAttachmentMessagePartRecord, SessionBucket, SessionComposerContext, SessionConfigurationInput, SessionConfigurationOptions, SessionConfigurationResultInput, SessionConfigurationSnapshot, SessionControlOriginal, SessionControlReceipt, SessionControls, SessionCreationInput, SessionCreationReceipt, SessionDirectoryEntry, SessionDirectoryPage, SessionDirectoryResult, SessionEventRecord, SessionExecutionRecord, SessionExportResponse, SessionFileErrorCode, SessionFileFindInput, SessionFileFindOptions, SessionFileInfo, SessionFileListInput, SessionFileListOptions, SessionFileReadInput, SessionFileReadOptions, SessionFileRequestOptions, SessionFileSearchInput, SessionFileSearchMatch, SessionFileSearchOptions, SessionFileStatInput, SessionFindFilesResult, SessionGoal, SessionGoalRequestReceipt, SessionHandle, SessionInputAttachmentRecord, SessionInputRecord, SessionManagementAction, SessionMessagePartRecord, SessionMessageRecord, SessionMessageWithParts, SessionModelRetryState, SessionModelUsageSummary, SessionMutationPublicReceipt, SessionRecord, SessionResourceRevision, SessionRunAttemptRecord, SessionRunRecord, SessionRuntimeConfig, SessionRuntimeConfigPatch, SessionSearchFilesResult, SessionSearchResult, AgentSessionStateSnapshot as SessionStateSnapshot, SessionSyncControllerOptions, SessionTextFileResult, SessionTransformationMessagePartRecord, SessionUsageResponse, SessionUserInputItem, SkillInfo, SkillMarketplaceEntry, SkillMarketplaceInstallInput, SkillProject, SkillSnapshot, SkillSource, StartDreamResponse, StorageCategory, StorageReport, StorageRetentionPolicy, SyncConnectionStatus, SyncEventUpdate, SyncEventsClient, TaskWorktreeRecord, TerminalCreateRequest, TerminalEvent, TerminalReadRequest, TerminalReadResult, TerminalResizeRequest, TerminalRuntime, TerminalSessionInfo, TerminalSessionStatus, TerminalSignal, TerminalSource, TerminalWriteRequest, UpdateMemoryEntryInput, UpdateScheduledTaskInput, UpdateSessionGoalInput, UploadAttachmentInput, UsageFilter, UsagePrice, UsageReport, UsageRequest, UsageSettings, WorkMode, WorkspaceChangeFile, WorkspaceChangesMetadata };
4138
+ export { AttachmentResource, BobanNomiApiError, BobanNomiClient, CURRENT_PROTOCOL_VERSION, ChannelResource, CommandResource, ContextResource, DiagnosticResource, EventResource, GitResource, HookResource, HttpTransport, IncompatibleProtocolError, MaintenanceResource, McpResource, McpServersResource, MemoryResource, PermissionResource, PluginMarketplaceResource, PluginResource, ProjectResource, ProtocolClient, ProtocolValidationError, ScheduleResource, SessionResource, SessionSyncController, SettingsResource, SseTransport, TerminalResource, UnsupportedSessionEventSchemaVersionError, WorktreeResource, applyEvent, applyEvents, attachmentRangeHeader, checkProtocolCompatibility, createClientState, createSessionRequestId, getVisibleSessionMessages, hydrateState, isSupersededModelPart, isWorkMode, normalizeApprovalMode, normalizeDaemonBaseUrl, parseCreateSessionGoalInput, parseGoalActionInput, parseMcpCallResultData, parseUpdateSessionGoalInput, patchSessionRuntimeMetadata, readRuntimeMetadata, readSessionModelRetryState, readSessionModelUsage, readSessionRuntimeConfig, readWorkspaceChangesMetadata, replaceSessionState, responseArray, responseField, selectFirstPendingPermission, selectSessionInputs, selectSessionMessagesWithParts, selectSessionModelRetry, selectSessionModelUsage, selectSessionOrderedMessages, selectSessionParts, selectSessionPermissions, selectSessionRuns, selectSessionTasks, streamServerSentEvents, supportsFeature, syncEvents };
4139
+ export type { AdmitClientPromptInput, AdmitPromptAttachmentInput, AgentEnvironmentCapabilities, AgentPersonaInfo, ApprovalMode, ApprovalReviewRecord, AttachmentAssetRecord, AttachmentStorageGcResult, AttachmentStorageIssue, AttachmentStorageRepairResult, AttachmentStorageReport, AuthStatus, BobanNomiClientOptions, BobanNomiClientState, BobanNomiServerHealth, CancelQueuedClientPromptInput, CancelQueuedPromptResponse, CancelResponseMode, ChannelConnectorRuntimeStatus, ChannelDeliveryRecord, ChannelDeliveryStatus, ChannelDenialNotice, ChannelDomain, ChannelQuery, ChannelRuntimeControlInput, ChannelRuntimeState, ChannelRuntimeStatus, ChannelStatusSnapshot, CleanupCandidate, CleanupPreview, CleanupResult, ClearMemoryInput, ClientModelConnection, ClientModelProvider, ClientProtocolSupport, CommandCatalogEntry, CommandKind, CommandSelection, CommandSource, ConfigureClientSessionInput, ContextBucketId, ContextUsageBucket, ContextUsageSnapshot, ContextUsageTip, ContextUsageTipCode, CreateBackgroundShellInput, CreateBackgroundShellResult, CreateClientSessionInput, CreateScheduledTaskInput, CreateSessionByProjectInput, CreateSessionGoalInput, CreateSessionWithDirectoryInput, CustomModelProviderInput, DaemonRestartPreview, DiagnosticExecutionQuery, DispatchedSessionCreation, DispatchedSessionCreationRequest, DownloadAttachmentOptions, DraftComposerOptions, DraftComposerTarget, DurableChannelMessageInput, DurableChannelMessageResult, EditLatestClientPromptInput, EventSyncOptions, ExecutionInstructions, ExpectedModelConnection, ExternalConversationRecord, FactReplacementResult, FeishuAllowInput, FeishuChannelSnapshot, FeishuComposedSnapshot, FeishuConnectInput, FeishuPatchInput, FeishuRegistrationSnapshot, FeishuRegistrationStartInput, FeishuRegistrationState, ForkClientSessionInput, GlobalSettingsPatch, GoalActionInput, GoalExternalWait, GoalStopReason, HookInfo, HostDiagnosticSnapshots, HttpRequestOptions, HttpTransportOptions, InputDelivery, InterruptSessionResponse, JobCancelReceipt, JobCapabilities, JobInputReceipt, JobKind, JobListResult, JobReadResult, JobSnapshot, JobStatus, JobTarget, JobWaitResult, JsonValue, ListClientMessagePartsOptions, ListCommandsOptions, ListEventsOptions, ListMessagePartsOptions, ListMessagesOptions, ListPermissionsOptions, ListProjectsOptions, ListSessionJobsOptions, ListSessionsOptions, MaintenanceBackupManifest, MaintenanceBackupResult, MarketplaceAddSourceRequest, MarketplaceCancelRequest, MarketplaceCancelResponse, MarketplaceCatalog, MarketplaceCatalogRequest, MarketplaceEntry, MarketplaceInstallInput, MarketplaceInstallRequest, MarketplaceOperation, MarketplacePreview, MarketplacePreviewRequest, MarketplaceProvenance, MarketplaceSelection, MarketplaceSource, MarketplaceSourceEnabledRequest, MarketplaceSourceView, MarketplaceSourcesResponse, McpConfigOperationResult, McpManagedServerConfig, McpManagedServerSummary, McpOAuthLoginInput, McpOAuthLoginResponse, McpOAuthStatusSnapshot, McpRuntimeStatus, McpRuntimeSyncResult, McpServerRuntimeRef, McpServerStatus, MemoryEntryRecord, MemoryListResponse, MemoryRevision, ModelInfo, ModelProviderConnection, ModelProviderInfo, ModelProviderRequest, OAuthOperationEvent, OAuthOperationView, OutputStyleInfo, PermissionRequestRecord, PermissionStatus, PluginArchiveError, PluginArchiveInstallInput, PluginArchivePreview, PluginArchivePreviewInput, PluginGitInstallInput, PluginGitPreview, PluginGitPreviewInput, PluginInfo, PluginListResult, PluginLocalInstallInput, PluginLocalPreview, PluginLocalPreviewInput, PluginRuntimeStatus, ProjectFactRecord, ProjectRecord, PromoteQueuedClientPromptInput, PromoteQueuedPromptResponse, PromptResponse, ProtocolCompatibility, ProviderConnectionTestResult, ProviderDefaultsRequest, ProviderDefaultsSnapshot, ProviderInfo, QueuedPromptCancelReceipt, RawRequestOptions, RecordChannelDeliveryInput, ReloadPluginsResponse, RememberSessionResponse, ReplyPermissionInput, ResolvedSessionConfiguration, ResumeInterruptedRunInput, ResumeInterruptedRunResponse, RewindSessionResponse, RunResult, ScheduledRunRecord, ScheduledTaskRecord, ScheduledTaskStatusSummary, SearchSessionsOptions, ServerCapabilities, SessionActivityPage, SessionAttachmentMessagePartRecord, SessionBucket, SessionComposerContext, SessionConfigurationInput, SessionConfigurationOptions, SessionConfigurationResultInput, SessionConfigurationSnapshot, SessionControlOriginal, SessionControlReceipt, SessionControls, SessionCreationInput, SessionCreationReceipt, SessionDirectoryEntry, SessionDirectoryPage, SessionDirectoryResult, SessionEventRecord, SessionExecutionRecord, SessionExportResponse, SessionFileErrorCode, SessionFileFindInput, SessionFileFindOptions, SessionFileInfo, SessionFileListInput, SessionFileListOptions, SessionFileReadInput, SessionFileReadOptions, SessionFileRequestOptions, SessionFileSearchInput, SessionFileSearchMatch, SessionFileSearchOptions, SessionFileStatInput, SessionFindFilesResult, SessionGoal, SessionGoalRequestReceipt, SessionHandle, SessionInputAttachmentRecord, SessionInputRecord, SessionManagementAction, SessionMessagePartRecord, SessionMessageRecord, SessionMessageWithParts, SessionModelRetryState, SessionModelUsageSummary, SessionMutationPublicReceipt, SessionObservation, SessionRecord, SessionResourceRevision, SessionRunAttemptRecord, SessionRunRecord, SessionRuntimeConfig, SessionRuntimeConfigPatch, SessionSearchFilesResult, SessionSearchResult, AgentSessionStateSnapshot as SessionStateSnapshot, SessionSyncControllerOptions, SessionTextFileResult, SessionTransformationMessagePartRecord, SessionUsageResponse, SessionUserInputItem, SkillInfo, SkillMarketplaceEntry, SkillMarketplaceInstallInput, SkillProject, SkillSnapshot, SkillSource, StartDreamResponse, StorageCategory, StorageReport, StorageRetentionPolicy, SyncConnectionStatus, SyncEventUpdate, SyncEventsClient, TaskWorktreeRecord, TerminalCreateRequest, TerminalEvent, TerminalReadRequest, TerminalReadResult, TerminalResizeRequest, TerminalRuntime, TerminalSessionInfo, TerminalSessionStatus, TerminalSignal, TerminalSource, TerminalWriteRequest, UpdateMemoryEntryInput, UpdateScheduledTaskInput, UpdateSessionGoalInput, UploadAttachmentInput, UsageFilter, UsagePrice, UsageReport, UsageRequest, UsageSettings, WorkMode, WorkspaceChangeFile, WorkspaceChangesMetadata };
package/dist/index.js CHANGED
@@ -659,50 +659,6 @@ var AUTO_REVIEW_VERDICT_SET = new Set(AUTO_REVIEW_VERDICTS);
659
659
  var AUTO_REVIEW_SEVERITY_SET = new Set(AUTO_REVIEW_SEVERITIES);
660
660
  var AUTO_REVIEW_REASON_SET = new Set(AUTO_REVIEW_REASONS);
661
661
 
662
- // ../json-data/src/json.ts
663
- function isJsonObject(value) {
664
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
665
- const prototype = Object.getPrototypeOf(value);
666
- return prototype === Object.prototype || prototype === null;
667
- }
668
- function isJsonRecord(value, byteLimit) {
669
- return validateJsonRecord(value, byteLimit).valid;
670
- }
671
- function validateJsonRecord(value, byteLimit) {
672
- if (!isJsonObject(value)) return { valid: false, reason: "invalid_json" };
673
- try {
674
- if (new TextEncoder().encode(stringifyCanonicalJson(value)).byteLength > byteLimit) {
675
- return { valid: false, reason: "payload_too_large" };
676
- }
677
- return { valid: true, value };
678
- } catch {
679
- return { valid: false, reason: "invalid_json" };
680
- }
681
- }
682
- function stringifyCanonicalJson(value) {
683
- const render = (item, depth) => {
684
- if (item === null || typeof item === "string" || typeof item === "boolean") {
685
- return JSON.stringify(item);
686
- }
687
- if (typeof item === "number" && Number.isFinite(item))
688
- return JSON.stringify(item);
689
- if (typeof item !== "object" || item === null)
690
- throw new Error("Finite requires JSON data");
691
- if (depth >= 20)
692
- throw new Error("Finite JSON nesting limit exceeded");
693
- if (Array.isArray(item)) {
694
- return `[${Array.from(item, (child) => render(child, depth + 1)).join(",")}]`;
695
- }
696
- const prototype = Object.getPrototypeOf(item);
697
- if (prototype !== Object.prototype && prototype !== null) {
698
- throw new Error("Finite requires plain JSON objects");
699
- }
700
- const record5 = item;
701
- return `{${Object.keys(record5).sort().map((key) => `${JSON.stringify(key)}:${render(record5[key], depth + 1)}`).join(",")}}`;
702
- };
703
- return render(value, 0);
704
- }
705
-
706
662
  // ../plugin-contracts/src/manifest/limits.ts
707
663
  var PLUGIN_APP_MANIFEST_LIMITS = Object.freeze({
708
664
  manifestCount: 8,
@@ -716,76 +672,6 @@ var PLUGIN_APP_DATA_LIMITS = Object.freeze({ maxArgsBytes: 64 * 1024 * 1024, jso
716
672
  // ../domain-contracts/src/plugin-apps/limits.ts
717
673
  var PLUGIN_APP_INPUT_LIMITS = Object.freeze({ handoffBytes: 32 * 1024, messageCharacters: 4096, maxComposerContexts: 8 });
718
674
 
719
- // ../domain-contracts/src/plugin-apps/history.ts
720
- var isPluginUiRevision = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
721
- var isPluginUiUuid = (value) => typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
722
- var PLUGIN_UI_LIMITS = { dataBytes: 256 * 1024, actionArgsBytes: 64 * 1024 };
723
- function exactFields(record5, required, optional = []) {
724
- return required.every((key) => Object.hasOwn(record5, key)) && Object.keys(record5).every(
725
- (key) => required.includes(key) || optional.includes(key)
726
- );
727
- }
728
- function nonempty(value) {
729
- return typeof value === "string" && value.trim().length > 0;
730
- }
731
- function digest(value) {
732
- return typeof value === "string" && /^[0-9a-f]{64}$/i.test(value);
733
- }
734
- function finite(value) {
735
- return typeof value === "number" && Number.isFinite(value);
736
- }
737
- function readPluginUiInstance(metadata) {
738
- if (!isJsonObject(metadata) || !Object.hasOwn(metadata, "pluginUi"))
739
- return void 0;
740
- const record5 = metadata.pluginUi;
741
- const source = [
742
- "sessionId",
743
- "sourceRunId",
744
- "sourcePartId",
745
- "sourceToolUseId",
746
- "sourceToolName",
747
- "pluginId",
748
- "pluginVersion",
749
- "componentId",
750
- "title"
751
- ];
752
- if (!isJsonObject(record5) || !exactFields(
753
- record5,
754
- [
755
- "schemaVersion",
756
- "instanceId",
757
- ...source,
758
- "pluginDigest",
759
- "componentDigest",
760
- "surface",
761
- "status",
762
- "revision",
763
- "data",
764
- "createdAt",
765
- "updatedAt"
766
- ],
767
- ["activeActionRunId", "lastActionRunId", "dismissal"]
768
- ))
769
- return void 0;
770
- if (record5.schemaVersion !== 2 || !isPluginUiUuid(record5.instanceId) || !source.every((key) => nonempty(record5[key])) || !digest(record5.pluginDigest) || !digest(record5.componentDigest) || record5.surface !== "tool-result" && record5.surface !== "session-sidebar" || !["open", "resolved", "dismissed"].includes(record5.status) || !isPluginUiRevision(record5.revision) || !finite(record5.createdAt) || !finite(record5.updatedAt) || !isJsonRecord(record5.data, PLUGIN_UI_LIMITS.dataBytes))
771
- return void 0;
772
- for (const key of ["activeActionRunId", "lastActionRunId"]) {
773
- if (Object.hasOwn(record5, key) && !nonempty(record5[key])) return void 0;
774
- }
775
- if (Object.hasOwn(record5, "dismissal")) {
776
- const dismissal = record5.dismissal;
777
- if (!isJsonObject(dismissal) || !exactFields(dismissal, [
778
- "requestId",
779
- "requestFingerprint",
780
- "expectedRevision",
781
- "revision",
782
- "dismissedAt"
783
- ]) || !isPluginUiUuid(dismissal.requestId) || !digest(dismissal.requestFingerprint) || !isPluginUiRevision(dismissal.expectedRevision) || !isPluginUiRevision(dismissal.revision) || !finite(dismissal.dismissedAt))
784
- return void 0;
785
- }
786
- return record5;
787
- }
788
-
789
675
  // ../protocol/src/serialization/json.ts
790
676
  function isUuid(value) {
791
677
  return typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
@@ -2465,14 +2351,22 @@ var ProtocolClient = class {
2465
2351
 
2466
2352
  // src/transport/http-transport.ts
2467
2353
  var BobanNomiApiError = class extends Error {
2468
- constructor(message, status, body) {
2354
+ constructor(message, status, body, traceId) {
2469
2355
  super(message);
2470
2356
  this.status = status;
2471
2357
  this.body = body;
2358
+ this.traceId = traceId;
2472
2359
  this.name = "BobanNomiApiError";
2360
+ if (!body || typeof body !== "object" || Array.isArray(body)) return;
2361
+ const { code, error } = body;
2362
+ const machineCode = [code, error].find(
2363
+ (value) => typeof value === "string" && /^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/.test(value)
2364
+ );
2365
+ if (machineCode !== void 0) this.code = machineCode;
2473
2366
  }
2474
2367
  status;
2475
2368
  body;
2369
+ traceId;
2476
2370
  };
2477
2371
  function responseField(value, field) {
2478
2372
  if (!value || typeof value !== "object" || Array.isArray(value)) {
@@ -2549,14 +2443,20 @@ function assertPositiveSafeInteger(value, field) {
2549
2443
  }
2550
2444
  }
2551
2445
  async function throwResponseError(response) {
2446
+ const traceHeader = response.headers.get("x-bobannomi-trace-id");
2447
+ const traceId = traceHeader && /^[A-Za-z0-9._:-]{1,128}$/.test(traceHeader) ? traceHeader : void 0;
2552
2448
  const text3 = await response.text().catch(() => "");
2553
2449
  let body = text3;
2554
2450
  try {
2555
2451
  body = JSON.parse(text3);
2556
2452
  } catch {
2557
2453
  }
2558
- const message = body && typeof body === "object" && "error" in body && typeof body.error === "string" ? body.error : body && typeof body === "object" && "message" in body && typeof body.message === "string" ? body.message : `BobanNomi API request failed with ${response.status}`;
2559
- throw new BobanNomiApiError(message, response.status, body);
2454
+ let message = `BobanNomi API request failed with ${response.status}`;
2455
+ if (body && typeof body === "object") {
2456
+ if ("message" in body && typeof body.message === "string") message = body.message;
2457
+ else if ("error" in body && typeof body.error === "string") message = body.error;
2458
+ }
2459
+ throw new BobanNomiApiError(message, response.status, body, traceId);
2560
2460
  }
2561
2461
  var HttpTransport = class {
2562
2462
  protocolHandshake;
@@ -3715,6 +3615,7 @@ async function* runEventSync(client, options, initialState = createClientState()
3715
3615
  if (error instanceof UnsupportedSessionEventSchemaVersionError) throw error;
3716
3616
  if (isAbortError(error) || signal?.aborted) return;
3717
3617
  if (options.shouldRetry?.(error) === false) throw error;
3618
+ if (error && typeof error === "object" && "code" in error && error.code === "connection_revoked") throw error;
3718
3619
  if (error instanceof BobanNomiApiError && error.status >= 400 && error.status < 500 && ![408, 425, 429].includes(error.status)) throw error;
3719
3620
  }
3720
3621
  if (signal?.aborted) return;
@@ -3746,6 +3647,20 @@ function isAbortError(error) {
3746
3647
  return Boolean(error && typeof error === "object" && "name" in error && error.name === "AbortError");
3747
3648
  }
3748
3649
 
3650
+ // src/state/session-observation.ts
3651
+ async function* observeSession(client, options) {
3652
+ for await (const { source, state } of syncEvents(client, options)) {
3653
+ const bucket = state.buckets[options.sessionId];
3654
+ yield {
3655
+ source,
3656
+ messages: getVisibleSessionMessages(bucket),
3657
+ inputs: selectSessionInputs(bucket),
3658
+ runs: selectSessionRuns(bucket),
3659
+ permissions: selectSessionPermissions(bucket)
3660
+ };
3661
+ }
3662
+ }
3663
+
3749
3664
  // src/state/wait-for-run.ts
3750
3665
  async function waitForRun(client, options) {
3751
3666
  options.signal?.throwIfAborted();
@@ -4031,6 +3946,7 @@ function createSessionHandle(transport, syncClient, management, sessionId, prepa
4031
3946
  }
4032
3947
  return {
4033
3948
  id: sessionId,
3949
+ observe: (options) => observeSession(syncClient, { ...options, sessionId }),
4034
3950
  waitForRun: (runId, options) => waitForRun(syncClient, { sessionId, runId, signal: options?.signal }),
4035
3951
  async updateAppMetadata(metadata, options) {
4036
3952
  const body = parseUpdateSessionRequest({ metadata: { app: metadata } });
@@ -4299,6 +4215,7 @@ var SessionResource = class {
4299
4215
  #transport;
4300
4216
  /** Bind a session ID locally. Operations use this resource's daemon connection when called. */
4301
4217
  byId(sessionId) {
4218
+ if (typeof sessionId !== "string" || sessionId.length === 0) throw new TypeError("sessionId is required");
4302
4219
  return createSessionHandle(this.#transport, { sessions: this, events: this.#events }, this.#management, sessionId, this.prepareModel);
4303
4220
  }
4304
4221
  /** `GET /sessions/search` - search saved conversation text without opening it. */
@@ -5649,7 +5566,6 @@ export {
5649
5566
  parseMcpCallResultData,
5650
5567
  parseUpdateSessionGoalInput2 as parseUpdateSessionGoalInput,
5651
5568
  patchSessionRuntimeMetadata,
5652
- readPluginUiInstance,
5653
5569
  readRuntimeMetadata2 as readRuntimeMetadata,
5654
5570
  readSessionModelRetryState,
5655
5571
  readSessionModelUsage,