@gestaltrun/dsh-im-runtime 0.1.0 → 0.1.5

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.
Files changed (62) hide show
  1. package/README.i18n.yaml +35 -20
  2. package/README.md +142 -10
  3. package/README.zh.md +141 -9
  4. package/lib/index.js +140 -2
  5. package/lib/inline-image-DuX6vSEI.js +20 -0
  6. package/lib/read-receipts.js +413 -0
  7. package/lib/read-state-CnUZKCuY.js +1868 -0
  8. package/lib/runtime-Bm6iSEpv.js +10939 -0
  9. package/lib/tools.js +1 -1
  10. package/lib/types/account-placement.d.ts +22 -0
  11. package/lib/types/admission-annotations.d.ts +40 -0
  12. package/lib/types/agent-coordinator.d.ts +47 -2
  13. package/lib/types/agent-media.d.ts +46 -0
  14. package/lib/types/agent-prompt.d.ts +8 -2
  15. package/lib/types/checkpoint-recovery.d.ts +32 -0
  16. package/lib/types/checkpoint.d.ts +127 -0
  17. package/lib/types/consumer-chat-links.d.ts +59 -0
  18. package/lib/types/delivery-schema.d.ts +126 -2
  19. package/lib/types/delivery-sqlite.d.ts +206 -6
  20. package/lib/types/delivery-types.d.ts +97 -1
  21. package/lib/types/delivery.d.ts +29 -6
  22. package/lib/types/errors.d.ts +1 -1
  23. package/lib/types/evaluation-accounts.d.ts +86 -0
  24. package/lib/types/index.d.ts +34 -2
  25. package/lib/types/inline-image.d.ts +7 -0
  26. package/lib/types/input-drain.d.ts +73 -0
  27. package/lib/types/knowledge-image.d.ts +64 -0
  28. package/lib/types/media-lifetime.d.ts +22 -0
  29. package/lib/types/media.d.ts +32 -0
  30. package/lib/types/message-preview.d.ts +4 -0
  31. package/lib/types/message-upload.d.ts +55 -0
  32. package/lib/types/nas-host-lease.d.ts +33 -0
  33. package/lib/types/placement-slice.d.ts +30 -0
  34. package/lib/types/policies.d.ts +10 -0
  35. package/lib/types/preset-model.d.ts +50 -0
  36. package/lib/types/read-context.d.ts +27 -0
  37. package/lib/types/read-receipts.d.ts +10 -0
  38. package/lib/types/read-records.d.ts +30 -0
  39. package/lib/types/read-state.d.ts +18 -0
  40. package/lib/types/read-types.d.ts +28 -0
  41. package/lib/types/restart-recovery.d.ts +38 -0
  42. package/lib/types/runtime.d.ts +318 -10
  43. package/lib/types/schema.d.ts +13 -2
  44. package/lib/types/script-clock.d.ts +14 -0
  45. package/lib/types/sdk.d.ts +108 -0
  46. package/lib/types/service-types.d.ts +161 -4
  47. package/lib/types/session-events.d.ts +9 -9
  48. package/lib/types/simulation-batch.d.ts +40 -0
  49. package/lib/types/simulation-controller.d.ts +16 -3
  50. package/lib/types/simulation-operator.d.ts +19 -0
  51. package/lib/types/sqlite-connection.d.ts +27 -0
  52. package/lib/types/time.d.ts +13 -0
  53. package/lib/types/transport.d.ts +44 -4
  54. package/lib/types/transports.d.ts +7 -0
  55. package/lib/types/types.d.ts +22 -5
  56. package/lib/types/typing.d.ts +33 -0
  57. package/lib/types/upload-types.d.ts +121 -0
  58. package/lib/types.js +2 -1
  59. package/locale/en.json +1 -1
  60. package/locale/zh.json +1 -1
  61. package/package.json +67 -41
  62. package/lib/runtime-C0-S-_CC.js +0 -6758
@@ -0,0 +1,108 @@
1
+ /** Optional Host SDK capability of an IM transport; account configuration remains runtime-owned. */
2
+ import type { ImAccountId } from './types.ts';
3
+ import type { Branded } from '@deepseek-ai/dsh-brand';
4
+ import type { ImOutboundRequestId } from './delivery-types.ts';
5
+ /** Verified platform single-chat identity, distinct from runtime delivery scopes. */
6
+ export type ImSdkConversationId = Branded<'ImSdkConversationId'>;
7
+ /** Platform message identity linked to persisted inbound or outbound data. */
8
+ export type ImSdkMessageId = Branded<'ImSdkMessageId'>;
9
+ /** Verified platform message recipient UID. */
10
+ export type ImSdkReceiverId = Branded<'ImSdkReceiverId'>;
11
+ declare module '@deepseek-ai/cordis' {
12
+ interface Context {
13
+ imSdk: ImSdkProvider;
14
+ }
15
+ }
16
+ /** Credential-free process state of an SDK connection. */
17
+ export type ImSdkState = 'offline' | 'connecting' | 'online' | 'reconnecting' | 'refreshing' | 'kicked' | 'login-required' | 'failed' | 'unknown';
18
+ /** Stable SDK failure categories suitable for localized UI. */
19
+ export type ImSdkFailureCode = 'SDK_AUTH_FAILED' | 'SDK_IDENTITY_MISMATCH' | 'SDK_LOGIN_REQUIRED' | 'SDK_STORAGE_FAILED' | 'SDK_REFRESH_UNKNOWN' | 'SDK_REFRESH_FAILED' | 'SDK_TOKEN_NOT_READY' | 'SDK_TOKEN_UNKNOWN' | 'SDK_NETWORK_FAILED' | 'SDK_CLOSED';
20
+ /** Safe SDK process projection; generation identifies one admitted connection. */
21
+ export interface ImSdkStatus {
22
+ readonly accountId: ImAccountId;
23
+ readonly state: ImSdkState;
24
+ readonly generation: number;
25
+ readonly error?: ImSdkFailureCode;
26
+ }
27
+ /** Host-only protocol notification. Readers validate message/recipient ownership before persistence or model use. */
28
+ export interface ImSdkEvent {
29
+ readonly accountId: ImAccountId;
30
+ readonly generation: number;
31
+ readonly kind: 'message' | 'read-to-reader' | 'read-to-sender' | 'receipt' | 'typing';
32
+ readonly data: Readonly<Record<string, unknown>>;
33
+ }
34
+ /** Host-authorized bytes and verified direct buyer identity. Files require the observed buyer nickname; images do not. Bytes never enter the status Remote API. */
35
+ export type ImSdkUpload = {
36
+ readonly name: string;
37
+ readonly mime: string;
38
+ readonly bytes: Uint8Array;
39
+ readonly receiver: ImSdkReceiverId;
40
+ readonly conversationId: ImSdkConversationId;
41
+ } & ({
42
+ readonly kind: 'image';
43
+ } | {
44
+ readonly kind: 'file';
45
+ readonly receiverNick: string;
46
+ });
47
+ /** Upload metadata is opaque platform JSON, never a local path or an authorization credential. */
48
+ export type ImSdkUploaded = {
49
+ readonly kind: 'image';
50
+ readonly metadata: Readonly<Record<string, unknown>>;
51
+ } | {
52
+ readonly kind: 'file';
53
+ readonly metadata: Readonly<Record<string, unknown>> | string;
54
+ };
55
+ /** One prepared submission. Media and text are exclusive; `requestId` is the SDK `clientId`. */
56
+ export type ImSdkSend = {
57
+ readonly conversationId: ImSdkConversationId;
58
+ readonly receiver: ImSdkReceiverId;
59
+ readonly requestId: ImOutboundRequestId;
60
+ } & ({
61
+ readonly media: ImSdkUploaded;
62
+ readonly text?: undefined;
63
+ } | {
64
+ readonly text: string;
65
+ readonly media?: undefined;
66
+ });
67
+ /** One authenticated connection lease; methods reject after generation revocation. */
68
+ export interface ImSdkLease {
69
+ readonly generation: number;
70
+ readonly signal: AbortSignal;
71
+ /** @param conversationId - verified single chat. @param messageIds - persisted inbound platform messages. @returns only after platform acknowledgement. */
72
+ markRead(conversationId: ImSdkConversationId, messageIds: readonly ImSdkMessageId[]): Promise<void>;
73
+ /** @param conversationId - verified single chat. @param messageId - linked platform message. @returns explicit per-recipient states; absence remains unknown. */
74
+ queryRead(conversationId: ImSdkConversationId, messageId: ImSdkMessageId): Promise<readonly {
75
+ readonly uid: ImSdkReceiverId;
76
+ readonly status: number;
77
+ }[]>;
78
+ /** @param conversationId - opaque cid from the raw SDK message. @param signal - optional caller cancellation within this generation. @returns true only when one SDK detail query confirms type 1 for that cid; absent capability, no result or an unconfirmed type leaves realtime reception to SaaS. */
79
+ isDirectConversation?(conversationId: ImSdkConversationId, signal?: AbortSignal): Promise<boolean>;
80
+ /** @param receiver - verified buyer UID, never a text transport conversation id. @param signal - optional operation cancellation. @returns SDK-owned single-chat identity; failure occurs before message submission. */
81
+ resolveConversation(receiver: ImSdkReceiverId, signal?: AbortSignal): Promise<ImSdkConversationId>;
82
+ /** @param file - authorized private bytes. @param signal - optional upload cancellation within the admitted connection. @returns preparation metadata; no chat message is submitted. */
83
+ upload(file: ImSdkUpload, signal?: AbortSignal): Promise<ImSdkUploaded>;
84
+ /** @param media - persisted upload metadata of an owned file message. @returns a fresh HTTPS download URL, never cached as a permanent file reference. */
85
+ downloadUrl(media: ImSdkUploaded): Promise<string>;
86
+ /** @param request - prepared media or text. `requestId` is sent as `clientId`. @param signal - caller cancellation. @param authorizeSubmission - optional automatic authority, called once after conversation resolution and immediately before page request dispatch; false refuses without submission. @returns the platform `messageId`, or `failed` only when nothing was submitted. A missing id, timeout, teardown, or rejection after dispatch is `unknown` and must not be resent automatically. */
87
+ sendMessages(request: ImSdkSend, signal?: AbortSignal, authorizeSubmission?: () => boolean): Promise<{
88
+ readonly state: 'sent';
89
+ readonly messageId: ImSdkMessageId;
90
+ } | {
91
+ readonly state: 'failed' | 'unknown';
92
+ }>;
93
+ }
94
+ /** Product SDK Provider projected through its existing platform transport. */
95
+ export interface ImSdkProvider {
96
+ /** @param accountId - configured runtime account. @returns safe process status; no SDK initialization occurs. */
97
+ status(accountId: ImAccountId): ImSdkStatus;
98
+ /** @param accountId - configured account selected by the operator or admitted startup or placement recovery. @param signal - optional restoration cancellation; abort revokes connection admission before cleanup. @returns verified terminal login status. */
99
+ login(accountId: ImAccountId, signal?: AbortSignal): Promise<ImSdkStatus>;
100
+ /** @param accountId - account stopped by an explicit command or placement handoff; this method does not mutate online intent. @returns offline status after accepted SDK work, kickout intent writes and page cleanup settle; rejects if cleanup or required intent persistence fails. */
101
+ logout(accountId: ImAccountId): Promise<ImSdkStatus>;
102
+ /** @param listener - safe process-state observer. @returns disposer. */
103
+ subscribe(listener: () => void): () => void;
104
+ /** @param listener - trusted protocol consumer, responsible for recovery of its mutated state; a throwing consumer is withdrawn and reported without payloads. @returns disposer that stops admission and joins accepted callbacks. */
105
+ subscribeEvents(listener: (event: ImSdkEvent) => void | Promise<void>): () => Promise<void>;
106
+ /** @param accountId - account whose online generation is required. @param generation - generation observed from this Provider instance. @param consume - trusted Host consumer; must honor signal and keep private protocol data out of logs. @returns consumer result; rejected when stale or the Provider is withdrawn. */
107
+ withConnection<T>(accountId: ImAccountId, generation: number, consume: (lease: ImSdkLease) => Promise<T>): Promise<T>;
108
+ }
@@ -1,10 +1,11 @@
1
1
  /** Host service and event declarations kept out of the client-safe DTO entry. */
2
2
  import type { ImAutomaticSendAuthorization } from './transport.ts';
3
+ import type { ImInjectSimulationOperatorRequest, ImSimulationOperatorReceipt } from './simulation-operator.ts';
3
4
  import type { WorkspaceId } from '@deepseek-ai/dsh-workspace';
4
5
  import type { UserMessage } from '@deepseek-ai/dsh-llm';
5
6
  import type { SessionId } from '@deepseek-ai/dsh-session';
6
- import type { ImBeginOutboundAttemptRequest, ImOutboundAttemptId, ImBeginOutboundAttemptResult, ImAgentTaskView, ImCancelPendingAiRequest, ImCommitProviderCursorRequest, ImConversationCursor, ImCustomerListPage, ImCustomerListRequest, ImCustomerReadAckRequest, ImDeliveryChange, ImDeliveryOperationId, ImDeliveryScope, ImGetOutboundRequest, ImHandlingControl, ImHistoryPage, ImHistoryQueryRequest, ImImportJsonlHistoryRequest, ImImportJsonlHistoryResult, ImInboundMessageView, ImInboundSenderEvidence, ImInboundOperationQuery, ImInboundPageResult, ImIngestInboundPageRequest, ImMarkSubmittedRequest, ImMarkSubmittedResult, ImManualMessageQuery, ImManualMessageQueryRequest, ImManualMessageResult, ImMessageId, ImMessageSource, ImOutboundPage, ImOutboundQueryRequest, ImOutboundView, ImPendingInboundRequest, ImProviderCursorCommitResult, ImProviderCursorOperationQuery, ImProviderCursorOwner, ImProviderCursorView, ImRealDeliveryScope, ImRealSessionBinding, ImRegisterOutboundRequest, ImRetryManualMessageRequest, ImSendManualMessageRequest, ImSetHandlingControlRequest, ImSettleOutboundAttemptRequest, ImSettleSimulationOutboundRequest, ImSessionReconciliationResult, ImSenderAttribution, ImScopeId } from './delivery-types.ts';
7
- import type { ImAccountId, ImAccountCandidate, ImAccountSetupId, ImAccountSetupPreview, ImCancelAccountSetupResult, ImConfirmAccountSetupRequest, ImAccountLifecycleRequest, ImAccountMutationResult, ImAccountOperationQuery, ImAccountSetupRequest, ImAccountView, ImAssignedActorCandidate, ImConversationCandidate, ImConversationCandidatePage, ImConversationKind, ImCreateRouteRequest, ImDeleteRouteRequest, ImOperationId, ImPlatform, ImPlatformLoginAttemptId, ImPlatformLoginStatus, ImRebindRouteRequest, ImRemoveSimulationTargetRequest, ImRouteMutationResult, ImRouteOperationQuery, ImRouteResolution, ImRuntimeChange, ImRuntimeSnapshot, ImSaveRouteRequest, ImSaveSimulationTargetRequest, ImSetAccountPausedRequest, ImSimulationTargetMutationResult, ImSimulationTargetOperationQuery, ImCreateSimulationInstanceRequest, ImSimulationInjectionQuery, ImInjectSimulationManagedHumanRequest, ImInjectSimulationMemberRequest, ImImportSimulationHistoryRequest, ImImportSimulationHistoryResult, ImSimulationInstanceView, ImSimulationSessionScope } from './types.ts';
7
+ import type { ImBeginOutboundAttemptRequest, ImOutboundAttemptId, ImBeginOutboundAttemptResult, ImAgentTaskView, ImCancelPendingAiRequest, ImCommitProviderCursorRequest, ImConversationCursor, ImConversationProjection, ImConversationRecords, ImCustomerSessionListRequest, ImCustomerSessionPage, ImCustomerListPage, ImCustomerListRequest, ImCustomerReadAckRequest, ImDeliveryChange, ImDeliveryOperationId, ImDeliveryScope, ImGetOutboundRequest, ImHandlingControl, ImHistoryPage, ImHistoryQueryRequest, ImImportJsonlHistoryRequest, ImImportJsonlHistoryResult, ImInboundMessageView, ImInboundSenderEvidence, ImInboundOperationQuery, ImInboundPageResult, ImIngestInboundPageRequest, ImMarkSubmittedRequest, ImMarkSubmittedResult, ImManualMessageQuery, ImManualMessageQueryRequest, ImManualMessageResult, ImMessageId, ImMessageSource, ImOutboundPage, ImOutboundQueryRequest, ImOutboundView, ImPendingInboundRequest, ImProviderCursorCommitResult, ImProviderCursorOperationQuery, ImProviderCursorOwner, ImProviderCursorView, ImRealDeliveryScope, ImRealSessionBinding, ImRegisterOutboundRequest, ImRetryManualMessageRequest, ImSendManualMessageRequest, ImSetHandlingControlRequest, ImSettleOutboundAttemptRequest, ImSettleSimulationOutboundRequest, ImSessionReconciliationResult, ImSenderAttribution, ImScopeId } from './delivery-types.ts';
8
+ import type { ImAccountId, ImAccountCandidate, ImAccountSetupId, ImAccountSetupPreview, ImCancelAccountSetupResult, ImConfirmAccountSetupRequest, ImAccountLifecycleRequest, ImAccountMutationResult, ImAccountOperationQuery, ImAccountSetupRequest, ImAccountView, ImAssignedActorCandidate, ImConversationCandidate, ImConversationCandidatePage, ImConversationKind, ImCreateRouteRequest, ImDeleteRouteRequest, ImOperationId, ImPlatform, ImPlatformLoginAttemptId, ImPlatformLoginStatus, ImRebindRouteRequest, ImRevision, ImRouteView, ImRemoveSimulationTargetRequest, ImRouteMutationResult, ImRouteOperationQuery, ImRouteResolution, ImRuntimeChange, ImRuntimeSnapshot, ImSaveRouteRequest, ImSaveSimulationTargetRequest, ImSetAccountPausedRequest, ImSimulationTargetMutationResult, ImSimulationTargetOperationQuery, ImCreateSimulationInstanceRequest, ImCreateManualSimulationInstanceRequest, ImSimulationInjectionQuery, ImInjectSimulationManagedHumanRequest, ImInjectSimulationMemberRequest, ImImportSimulationHistoryRequest, ImImportSimulationHistoryResult, ImSimulationInstanceView, ImSimulationSessionScope } from './types.ts';
8
9
  declare module '@deepseek-ai/cordis' {
9
10
  interface Context {
10
11
  imRuntime: ImRuntimeService;
@@ -28,20 +29,105 @@ declare module '@deepseek-ai/dsh-llm' {
28
29
  interface MessageSourceMap {
29
30
  /** Stable IM identity used to reconcile a Session append with the delivery domain. */
30
31
  im: ImMessageSource;
32
+ /** 重启中断的稳定日志位置;普通 user/message 和 inbox 事件持有同一输入。 */
33
+ 'im-restart': {
34
+ readonly kind: 'im-restart';
35
+ readonly turnStartSeq: import('@deepseek-ai/dsh-session').SessionSeq;
36
+ };
31
37
  }
32
38
  }
33
39
  /** Read and mutation surface consumed by the product BFF. */
34
40
  export interface ImRuntimeService {
41
+ /** Process-local sidebar typing; never persisted or sent to an Agent. */
42
+ readonly typing: Pick<import('./typing.ts').ImTyping, 'snapshot' | 'subscribe'>;
43
+ /** Instance-private evaluation root and simulation upload queue; absent when using formal storage. */
44
+ readonly standbyStorageRoot?: string | undefined;
45
+ /**
46
+ * Whether this runtime bound a NAS host lease.
47
+ * This is the condition `ensureEvaluationAccount` uses to reject with `正式云端接待不能创建评测账号`. It stays true after hosting intent is turned off: intent only changes the projected route and does not dispose the lease or call `releaseHostingLease`.
48
+ * `NasHostLease.holderIdentity()` is a different read. It is undefined before admission and after a fence, while this method can still be true.
49
+ * The control plane releases the lease only from `CloudNasHostLease.releaseOnStop`, and only when `shouldReleaseOnStop()` is true. The cloud host sets that flag in `releaseFailedPlacement` and `stopLive`, immediately before disposing the lease fiber. A fence or `stopHost` exits without `releaseHostingLease`; the control-plane holder remains until it expires.
50
+ * Evaluation command proxy (#1216) reads this method, not hosting intent and not `CsHostingEvaluationSummary.canStart`.
51
+ * @returns True when `nasHostLease` was bound at IM startup, including before admission and while hosting intent is off.
52
+ */
53
+ holdsNasLease(): boolean;
54
+ /** @param sellerId - Host-verified seller. @param workspaceId - Tested Workspace, aligned on every call. @returns Credential-free account and its fixed disabled route; leased cloud runtimes (`holdsNasLease()`), conflicting formal ids and unavailable evaluation data reject. Calls for one runtime are serialized. */
55
+ ensureEvaluationAccount(sellerId: string, workspaceId: WorkspaceId): Promise<{
56
+ readonly account: ImAccountView;
57
+ readonly route: ImRouteView;
58
+ }>;
59
+ /** @param accountId - Account to classify by its evaluation domain. @param sellerId - Optional exact seller identity. @returns Whether the stored evaluation account matches; names and id prefixes grant no evaluation authority. */
60
+ isEvaluationAccount(accountId: ImAccountId, sellerId?: string): boolean;
61
+ /** @param accountId - Evaluation account whose run finished. @param observedRevision - Route generation held by the run. @returns True after removing that route, or if already absent; false for unknown accounts or a changed generation. The account remains durable. Formal routes cannot be removed. */
62
+ releaseEvaluationAccountRoute(accountId: ImAccountId, observedRevision: ImRevision): Promise<boolean>;
63
+ /** @returns After evaluation consumers and handles close; failures reject. */
64
+ closeEvaluationResources(): Promise<void>;
65
+ /** @returns After reload against an admitted lease; caller reacquires consumers. */
66
+ reloadWithNasLease(): Promise<void>;
67
+ /** @param annotator - Product-owned optional admission analysis. @returns Disposer that prevents further calls. */
68
+ registerAdmissionAnnotator(annotator: import('./admission-annotations.ts').ImAdmissionAnnotator): () => Promise<void>;
69
+ /** @param request - owned manual file message and Session or scope. @returns a fresh URL requiring an authenticated SDK generation. */
70
+ mediaDownloadUrl(request: ImManualMessageQueryRequest): Promise<string>;
71
+ /** @param request - scope-verified media and private bytes. @param signal - operation lifetime. @returns durable outbox result without automatic resubmission. */
72
+ sendMediaMessage(request: import('./delivery-types.ts').ImSendMediaMessageRequest, signal?: AbortSignal): Promise<ImOutboundView>;
73
+ /** @returns 暂停新输入的所有权;等待已准入工作后由调用者恢复。 */
74
+ pauseInput(): import('./input-drain.ts').ImInputPause;
75
+ /** @param accountId - 待交接账号。 @returns 仅该账号的暂停;不改变路由代次或其他 Workspace 的运行。停止监听后 resume 拒绝,必须核验交接。 */
76
+ pauseAccountInput(accountId: ImAccountId): import('./input-drain.ts').ImInputPause;
77
+ /** @param accountId - 已持有账号输入暂停的账号;只取消其当前实际拥有的运行任务,保留 inbox。 */
78
+ cancelAccountActivityForPlacement(accountId: ImAccountId): void;
79
+ /** @param accountId - 已排空账号。 @returns SDK 已主动登出、已接纳踢线意图已提交、监听已停止且未发送自动回复已取消;保留在线意图,失败不恢复。 */
80
+ stopAccountForPlacement(accountId: ImAccountId): Promise<void>;
81
+ /** @param accountId - 已鉴权的旺旺账号。 @param workspaceId - 来源客服内置 Workspace。 @returns 最终导出前须排空的独立切片。 */
82
+ exportAccountForPlacement(accountId: ImAccountId, workspaceId: WorkspaceId): import('./account-placement.ts').ImAccountPlacementSlice;
83
+ /** @param accountId - Incoming leased account in a Host without startup or maintenance pause, including a previously exported account. @param signal - Drain and incoming transfer lifetime. @returns Account standby held and owned Agent persistence locks released before Session import; failures retain reception stop. */
84
+ beginAccountPlacementImport(accountId: ImAccountId, signal: AbortSignal): Promise<void>;
85
+ /** @param accountId - Successfully established incoming account standby; caller must obtain fresh lease authorization and prepare Agents first. Releases this account's import hold and schedules reception without releasing Host startup holds. */
86
+ releaseAccountPlacement(accountId: ImAccountId): void;
87
+ /** @param accountId - Account under import hold with its listener stopped. @param checkpoint - Parsed cursor-only checkpoint. @param signal - Pre-CAS validation lifetime. @returns Existing nonnull local cursors match exactly and checkpoint counts are zero; failures preserve stopped reception. */
88
+ validateAccountCheckpointRecovery(accountId: ImAccountId, checkpoint: import('./checkpoint-recovery.ts').ImAccountCheckpointRecovery['checkpoint'], signal: AbortSignal): Promise<void>;
89
+ /** @param accountId - Fenced recovery account with an established account import hold. @param request - Parsed checkpoint and caller-verified continuous source fence. @param signal - Activation lifetime. @returns New local task generations are prepared with a logged history-gap notice; old Sessions stay untouched and reception stays paused. Nonzero checkpoint pending/unknown counts reject. */
90
+ recoverAccountPlacement(accountId: ImAccountId, request: import('./checkpoint-recovery.ts').ImAccountCheckpointRecovery, signal: AbortSignal): Promise<void>;
91
+ /** @param slice - 已鉴权并校验的切片。 @param workspaceId - 目标内置 Workspace。 @returns 提交配置与投递事实,保持停止;失败可能部分提交,调用者核验。 */
92
+ importAccountForPlacement(slice: import('./account-placement.ts').ImAccountPlacementSlice, workspaceId: WorkspaceId): Promise<void>;
93
+ /** @param accountId - 已导入或已在本端接待的账号。 @param prepare - 接收同一空闲 Agent 及已核验账号、Workspace 和持久化会话头的当前任务,准备续写。 @param signal - 激活与身份寿命。 @returns 当前任务准备完毕;未知 Session 不会被创建,失败保留启动暂停。 */
94
+ prepareAccountPlacement(accountId: ImAccountId, prepare: (agent: import('@deepseek-ai/dsh-agent').Agent, task: import('./delivery-types.ts').ImAgentTaskView) => Promise<void>, signal: AbortSignal): Promise<void>;
95
+ /** @param accountId - 已释放启动暂停的账号。 @param signal - 激活与身份寿命。 @returns 当前监听已就绪并完成初始追平,或账号按原连接意图保持空闲;失败不代表激活完成。 */
96
+ waitAccountPlacementReady(accountId: ImAccountId, signal: AbortSignal): Promise<void>;
97
+ /** @param accountId - 当前账号。 @returns 账号停止、账号暂停或启动暂停中的任一门禁是否生效。 */
98
+ inputPaused(accountId: ImAccountId): boolean;
99
+ /** 控制面授权、导入和 prepareResume 完成后幂等释放目标启动暂停,不授予租约。 */
100
+ releasePlacementStartup(): void;
101
+ /** 首次开通已生成的账号。之后确认旺旺账号时使用它,不再另生成。 */
102
+ reservePlacementAccount(accountId: ImAccountId): void;
35
103
  /** @param platform - installed provider selected by the operator. @param signal - caller lifetime until safe instructions are available. @returns current safe interactive login state. */
36
104
  startPlatformLogin(platform: ImPlatform, signal?: AbortSignal): Promise<ImPlatformLoginStatus>;
37
105
  /** @param platform - owning provider. @param attemptId - login identity returned by start. @returns current safe login state. */
38
106
  platformLoginStatus(platform: ImPlatform, attemptId: ImPlatformLoginAttemptId): ImPlatformLoginStatus;
39
107
  /** @param platform - owning provider. @param attemptId - login identity returned by start. @returns cancelled or already-terminal state. */
40
108
  cancelPlatformLogin(platform: ImPlatform, attemptId: ImPlatformLoginAttemptId): Promise<ImPlatformLoginStatus>;
41
- /** @returns the current durable configuration projection. */
109
+ /** @returns Formal accounts, their routes and simulation targets referencing visible formal accounts; evaluation resources are excluded. */
42
110
  snapshot(): ImRuntimeSnapshot;
43
111
  /** @param listener - post-commit change observer. @returns disposer for this subscription. */
44
112
  subscribe(listener: (change: ImRuntimeChange) => void): () => void;
113
+ /** In standby, only evaluation simulation messages are uploaded from private storage. @param binding - hosted traffic eligibility and authenticated upload. @returns async disposer that aborts and awaits requests. */
114
+ bindMessageUpload(binding: import('./upload-types.ts').ImUploadBinding): () => Promise<void>;
115
+ /**
116
+ * Send throttled hosting checkpoints through this transport.
117
+ * The runtime calls it for durable cursors and reception state changes. The transport owns the lease epoch.
118
+ * @param transport - one server reporter. A later bind replaces it.
119
+ * @param activity - current product intent, admission and model availability.
120
+ * @returns disposer that stops reporting. Local cursors stay.
121
+ */
122
+ bindCheckpointTransport(transport: import('./checkpoint.ts').ImCheckpointTransport, activity?: (accountId: ImAccountId) => Omit<import('./checkpoint.ts').ImCheckpointActivity, 'inFlight'>): () => void;
123
+ /** @param accountId - account whose reception intent, admission, or model state changed. */
124
+ noteCheckpoint(accountId: ImAccountId): void;
125
+ /**
126
+ * Report again after the held lease epoch changes.
127
+ * A rejected epoch is not reused.
128
+ * @param accountId - account whose new epoch is now held.
129
+ */
130
+ resumeCheckpoint(accountId: ImAccountId): void;
45
131
  /** @param platform - provider whose installed or admitted identities are requested. @param signal - caller lifetime. @returns safe selectable candidates. */
46
132
  listAccountCandidates(platform: ImPlatform, signal?: AbortSignal): Promise<readonly ImAccountCandidate[]>;
47
133
  /** @param accountId - configured account whose provider conversations are listed. @param signal - caller lifetime. @returns provider-known titles with stable conversation ids. */
@@ -60,11 +146,26 @@ export interface ImRuntimeService {
60
146
  resolveRoute(accountId: ImAccountId, conversationKind: ImConversationKind, conversationId: string, assignedActorId?: string): ImRouteResolution;
61
147
  /** @param request - candidate-bound setup input for non-interactive Host consumers. @param signal - caller lifetime. @returns the persisted safe account. */
62
148
  addAccount(request: ImAccountSetupRequest, signal?: AbortSignal): Promise<ImAccountView>;
149
+ /** @param request - account and observed revision. @param setup - verified credentials for the same merchant. @param signal - optional generation cancellation; absent uses an uncancelled operation. @returns durable renewal receipt preserving pause, intent, rules, and history. */
150
+ renewAccount(request: ImAccountLifecycleRequest, setup: ImAccountSetupRequest, signal?: AbortSignal): Promise<ImAccountMutationResult>;
151
+ /** @returns all retained Host account facts, including replaced records omitted from Client snapshots. */
152
+ retainedAccounts(): readonly {
153
+ readonly account: ImAccountView;
154
+ readonly replacedHidden: boolean;
155
+ }[];
156
+ /** @param request - old account and observed revision after replacement OAuth succeeds. @returns durable disconnection and list removal; rules and history remain retained. */
157
+ hideReplacedAccount(request: ImAccountLifecycleRequest): Promise<ImAccountMutationResult>;
158
+ /** @param request - retained account and observed revision. @param setup - new verified credentials for the same merchant. @param signal - optional authorization generation; absent does not cancel. @returns explicit restoration of a replaced account; concurrent lifecycle changes win. */
159
+ restoreReplacedAccount(request: ImAccountLifecycleRequest, setup: ImAccountSetupRequest, signal?: AbortSignal): Promise<ImAccountMutationResult>;
63
160
  /** @param request - guarded account pause mutation. @returns its durable outcome. */
64
161
  setAccountPaused(request: ImSetAccountPausedRequest): Promise<ImAccountMutationResult>;
65
162
  /** @param request - guarded persistent disconnect intent. @returns its durable outcome. */
66
163
  disconnectAccount(request: ImAccountLifecycleRequest): Promise<ImAccountMutationResult>;
67
- /** @param request - guarded persistent reconnect intent. @returns its durable outcome. */
164
+ /** @param accountId - retained runtime account. @param intent - explicit online intent, persistent kickout, or absence after logout. @param expectedIntent - optional intent-generation CAS for asynchronous connection observations. @returns whether the account write was accepted; rejects if durability cannot be confirmed. */
165
+ setSdkConnectionIntent(accountId: ImAccountId, intent: ImAccountView['sdkConnectionIntent'], expectedIntent?: {
166
+ readonly revision: ImAccountView['sdkConnectionIntentRevision'];
167
+ }): Promise<boolean>;
168
+ /** @param request - account revision and idempotent operation for a disconnected account or failed listener. @returns durable intent acknowledgement; a fresh accepted operation resets the listener retry budget and starts reconciliation. */
68
169
  reconnectAccount(request: ImAccountLifecycleRequest): Promise<ImAccountMutationResult>;
69
170
  /** @param request - guarded account deletion. @returns its durable outcome; conversation history remains. */
70
171
  deleteAccount(request: ImAccountLifecycleRequest): Promise<ImAccountMutationResult>;
@@ -93,8 +194,14 @@ export interface ImRuntimeService {
93
194
  }): () => void;
94
195
  /** @param request - guarded simulation-target save. @returns its durable outcome. */
95
196
  saveSimulationTarget(request: ImSaveSimulationTargetRequest): Promise<ImSimulationTargetMutationResult>;
197
+ /** @param request - Formal route and observed target revision. @returns Durable result; evaluation requested, current or receipt targets reject inside the serialized operation before any write. */
198
+ saveFormalSimulationTarget(request: ImSaveSimulationTargetRequest): Promise<ImSimulationTargetMutationResult>;
199
+ /** @param workspaceId - Simulated-user Workspace. @returns Its current Host target, including evaluation targets. */
200
+ simulationTargetForWorkspace(workspaceId: WorkspaceId): import('./types.ts').ImSimulationTargetView | undefined;
96
201
  /** @param request - guarded simulation-target removal. @returns its durable outcome. */
97
202
  removeSimulationTarget(request: ImRemoveSimulationTargetRequest): Promise<ImSimulationTargetMutationResult>;
203
+ /** @param request - Workspace and observed formal target revision. @returns Durable result; evaluation current or receipt targets reject inside the serialized operation before any write. */
204
+ removeFormalSimulationTarget(request: ImRemoveSimulationTargetRequest): Promise<ImSimulationTargetMutationResult>;
98
205
  /** @param workspaceId - target-owning workspace. @param operationId - idempotency identifier. @returns stored result or an explicit miss. */
99
206
  querySimulationTargetOperation(workspaceId: WorkspaceId, operationId: ImOperationId): ImSimulationTargetOperationQuery;
100
207
  /** @param sessionId - durable real IM task Session. @returns its frozen target plus current safe account, listener, presentation, and sync facts. */
@@ -122,14 +229,52 @@ export interface ImRuntimeService {
122
229
  listSimulationInstances(): readonly ImSimulationInstanceView[];
123
230
  /** @param instanceId - Host-minted instance identity. @returns its durable state or absence. */
124
231
  getSimulationInstance(instanceId: import('./delivery-types.ts').ImSimulationInstanceId): ImSimulationInstanceView | undefined;
232
+ /**
233
+ * Pause automatic buyer delivery and remove simulation operator tools while a Host drives the buyer.
234
+ * @param instanceId - Running paired simulation; only one Host driver may hold it.
235
+ * @returns Idempotent disposer; release after stopping the instance, otherwise queued replies resume automatic delivery.
236
+ */
237
+ holdSimulationBuyer(instanceId: import('./delivery-types.ts').ImSimulationInstanceId): () => void;
238
+ /**
239
+ * Deliver pending AI replies and, during a Host-driven confirmed handoff, received human-dsh replies through native IM input.
240
+ * AI rows are marked submitted. Staff rows keep their received stage; durable buyer input deduplicates their delivery.
241
+ * The Host must prepare its buyer state before calling; delivery wakes the buyer Agent.
242
+ * @param instanceId - Running paired simulation held by exactly one Host driver; otherwise rejects.
243
+ * @returns Number of AI and eligible staff replies durably delivered to the buyer Session or inbox; zero when none are pending.
244
+ */
245
+ deliverSimulationBuyerReplies(instanceId: import('./delivery-types.ts').ImSimulationInstanceId): Promise<number>;
246
+ /** IANA shop zone configured at runtime load; defaults to Asia/Shanghai. */
247
+ readonly timeZone: string;
248
+ /**
249
+ * Register an external clock for both Sessions of one creating or running simulation.
250
+ * The source is sampled synchronously for every request step; the caller advances it only
251
+ * between settled steps. It must return valid Unix milliseconds; its failures stop preparation.
252
+ * Registration is Host-local and is not persisted or transferred. Re-register after restart.
253
+ * Real Sessions and other instances always retain their own source or the system clock.
254
+ * @param instanceId - Host-minted simulation identity; unknown, terminal, or already registered instances fail without mutation.
255
+ * @param source - caller-owned clock; never modified or disposed by the runtime.
256
+ * @returns Idempotent disposer restoring system time; also released at instance termination or runtime disposal.
257
+ */
258
+ registerSimulationClock(instanceId: import('./delivery-types.ts').ImSimulationInstanceId, source: import('./time.ts').ImClockSource): () => void;
259
+ /**
260
+ * @param sessionId - either simulation Session or any real/ordinary Session.
261
+ * @returns Current Unix milliseconds from that instance's registered source, or Date.now when absent. Source errors propagate.
262
+ */
263
+ currentTime(sessionId: SessionId): number;
125
264
  /** @param sessionId - either side of a simulation pair. @returns Host-authoritative role, peer, workspace, and delivery scope. */
126
265
  scopeForSession(sessionId: SessionId): ImSimulationSessionScope | undefined;
266
+ /** @param request - enabled all-direct route. @returns a durable tested Session with no simulated-user Session. */
267
+ createManualSimulationInstance(request: ImCreateManualSimulationInstanceRequest): Promise<ImSimulationInstanceView>;
127
268
  /** @param request - live simulated-user Session and optional all-route conversation. @returns durable pair after tested Session flush. */
128
269
  createSimulationInstance(request: ImCreateSimulationInstanceRequest): Promise<ImSimulationInstanceView>;
270
+ /** @param request - Live simulated-user Session and optional conversation. @returns A pair using a non-evaluation account; evaluation targets reject inside the serialized creation operation. */
271
+ createFormalSimulationInstance(request: ImCreateSimulationInstanceRequest): Promise<ImSimulationInstanceView>;
129
272
  /** @param request - allow-listed member identity and text. @returns shared-path durable inbound message. */
130
273
  injectSimulationMember(request: ImInjectSimulationMemberRequest): Promise<ImInboundMessageView>;
131
274
  /** @param request - instance and text; Host derives the frozen account actor. @returns shared-path durable inbound message. */
132
275
  injectSimulationManagedHuman(request: ImInjectSimulationManagedHumanRequest): Promise<ImInboundMessageView>;
276
+ /** @param request - Private operator text and retry identity for a running instance. @returns Durable acceptance in the tested Session; no IM row or transport send. */
277
+ injectSimulationOperator(request: ImInjectSimulationOperatorRequest): Promise<ImSimulationOperatorReceipt>;
133
278
  /** @param request - original injection identity. @returns durable receipt; never resends. */
134
279
  querySimulationInjection(request: ImSimulationInjectionQuery): ImInboundOperationQuery;
135
280
  /** @param instanceId - instance to close. @returns durable stopping or terminal state without awaiting caller activity. */
@@ -148,6 +293,12 @@ export interface ImRuntimeService {
148
293
  queryInboundOperation(scope: ImDeliveryScope, operationId: ImDeliveryOperationId): ImInboundOperationQuery;
149
294
  /** @param scope - complete conversation identity. @returns current live-delivery cursor. */
150
295
  getConversationCursor(scope: ImDeliveryScope): ImConversationCursor;
296
+ /**
297
+ * Derive one value per conversation whenever its document is parsed or written, so later reads need no document read.
298
+ * @param project - pure function of one conversation's records; the result must depend only on them and must not keep them.
299
+ * @returns accessor of the derived values; the caller disposes it with its own lifetime.
300
+ */
301
+ projectConversations<T extends object>(project: (records: ImConversationRecords) => T): ImConversationProjection<T>;
151
302
  /** @param owner - platform account and provider feed identity. @returns current feed cursor without claiming conversation ownership. */
152
303
  getProviderCursor(owner: ImProviderCursorOwner): ImProviderCursorView;
153
304
  /** @param request - feed cursor CAS and every durable conversation-page receipt. @returns stored cursor outcome. */
@@ -158,6 +309,8 @@ export interface ImRuntimeService {
158
309
  queryHistory(request: ImHistoryQueryRequest): ImHistoryPage;
159
310
  /** @param request - account, real/simulation filter, optional substring, and reader. @returns a keyset page of customer rows. */
160
311
  listCustomers(request: ImCustomerListRequest): ImCustomerListPage;
312
+ /** @param request - account, source, search and cursor. @returns customer Session references without unread calculations. */
313
+ listCustomerSessions(request: ImCustomerSessionListRequest): ImCustomerSessionPage;
161
314
  /** @param request - reader, scope, and observed arrival sequence. */
162
315
  ackCustomerRead(request: ImCustomerReadAckRequest): void;
163
316
  /** @param request - scope and pause fields. @returns the stored handling control. */
@@ -174,6 +327,8 @@ export interface ImRuntimeService {
174
327
  pendingInbound(request: ImPendingInboundRequest): readonly ImInboundMessageView[];
175
328
  /** @param scope - complete conversation identity. @returns frozen Agent task assignment, or absence before admission. */
176
329
  getAgentTask(scope: ImDeliveryScope): ImAgentTaskView | undefined;
330
+ /** @param sessionId - real or simulated IM Agent Session. @returns its newest retained task generation, or absence without creating an Agent or reading Session history. */
331
+ executionForSession(sessionId: SessionId): ImAgentTaskView | undefined;
177
332
  /** @param scope - complete conversation identity. @param messageId - stored inbound identity. @returns source for an existing Session user/message event. */
178
333
  messageSource(scope: ImDeliveryScope, messageId: ImMessageId): ImMessageSource;
179
334
  /** @param scope - complete conversation identity. @param messageId - stored inbound identity. @returns identified Session user message with durable IM source. */
@@ -202,6 +357,8 @@ export interface ImRuntimeService {
202
357
  queryOutbound(request: ImOutboundQueryRequest): ImOutboundPage;
203
358
  /** @param request - scope and terminal reason. @returns discarded automated rows. */
204
359
  cancelPendingAi(request: ImCancelPendingAiRequest): Promise<readonly ImOutboundView[]>;
360
+ /** @param accountId - authenticated SDK account. @param messageId - platform message ID. @param clientId - SDK UUID. @returns exact durable single-chat matches, without matching content. */
361
+ matchSdkMessage(accountId: ImAccountId, messageId: string, clientId?: string): readonly import('./read-types.ts').ImSdkMessageMatch[];
205
362
  /** @param scope - complete real scope. @param externalMessageId - provider message identity. @returns matching sent outbox evidence. */
206
363
  findSentOutbound(scope: ImRealDeliveryScope, externalMessageId: string): ImOutboundView | undefined;
207
364
  /** @param scope - complete real conversation. @param evidence - provider actor or echo facts without message-text heuristics. @returns evidence-backed sender category, including human-native for remembered native-client actors. */
@@ -1,13 +1,11 @@
1
- /**
2
- * Session log of one IM automatic-handling pause.
3
- *
4
- * Written when `setHandlingControl` pauses a scope that already has an Agent
5
- * Session (live or persisted). When no Session log exists, the event is not
6
- * written; SQLite handling control remains the source of truth.
7
- * Required-on-read. Secrets stay out.
8
- * @module @gestaltrun/dsh-im-runtime/session-events
9
- */
10
1
  import type { ImDeliveryScope } from './delivery-types.ts';
2
+ /** Confirmed buyer reading of one exact durable outbound; observation time is not the buyer's reading time. */
3
+ export interface ImMessageReadEvent {
4
+ readonly scope: import('./delivery-types.ts').ImRealDeliveryScope;
5
+ readonly requestId: import('./delivery-types.ts').ImOutboundRequestId;
6
+ readonly platformMessageId: import('./sdk.ts').ImSdkMessageId;
7
+ readonly observedAt: string;
8
+ }
11
9
  /** Payload recorded when automatic handling is paused for one conversation. */
12
10
  export interface ImHandlingPausedEvent {
13
11
  /** Frozen conversation identity. */
@@ -19,6 +17,8 @@ export interface ImHandlingPausedEvent {
19
17
  }
20
18
  declare module '@deepseek-ai/dsh-session/types' {
21
19
  interface SessionEventMap {
20
+ /** Buyer read evidence for one identified outbound. Required-on-read; the corresponding im-read context is reconstructed from this fact. */
21
+ 'im/message-read': ImMessageReadEvent;
22
22
  /**
23
23
  * Automatic handling was paused for one IM scope. Records the scope, pause
24
24
  * reason, and initiating call id. Contains no secrets. Required-on-read.
@@ -0,0 +1,40 @@
1
+ import type { ImRuntimeService } from './service-types.ts';
2
+ import type { ImCreateSimulationInstanceRequest, ImSimulationInstanceView } from './types.ts';
3
+ /** Deployment limits for one batch controller. */
4
+ export interface ImSimulationBatchConfig {
5
+ /** Maximum simultaneous instances; defaults to 2. */
6
+ readonly maxConcurrency?: number;
7
+ }
8
+ /** A caller-owned simulated-user Session and its work against one paired instance. */
9
+ export interface ImSimulationBatchJob<T> {
10
+ readonly request: ImCreateSimulationInstanceRequest;
11
+ /** @param instance - Running pair owned by this batch. @param signal - Batch and caller cancellation. @returns Job result after all step work settles. */
12
+ execute(instance: ImSimulationInstanceView, signal: AbortSignal): Promise<T>;
13
+ }
14
+ /** Per-job result in input order; a failed job never discards completed siblings. */
15
+ export type ImSimulationBatchResult<T> = {
16
+ readonly status: 'fulfilled';
17
+ readonly value: T;
18
+ } | {
19
+ readonly status: 'rejected';
20
+ readonly error: unknown;
21
+ };
22
+ type Runtime = Pick<ImRuntimeService, 'createSimulationInstance' | 'beginStopSimulation' | 'waitSimulationStopped'>;
23
+ /** Batch owner; caller-owned simulated-user Sessions remain available after instance cleanup. */
24
+ export declare class ImSimulationBatch {
25
+ private readonly runtime;
26
+ private readonly concurrency;
27
+ private active;
28
+ /** @param runtime - Host instance lifecycle authority. @param config - Validated concurrency limit. */
29
+ constructor(runtime: Runtime, config?: ImSimulationBatchConfig);
30
+ /**
31
+ * Run one batch, retaining input order and stopping every created instance before resolving.
32
+ * @param jobs - Distinct live simulated-user Sessions; callbacks must settle on cancellation.
33
+ * @param signal - Optional caller cancellation; absent means only stop() can cancel the batch.
34
+ * @returns One result per job; cleanup failure cancels remaining jobs and retains both failures. Concurrent run calls reject.
35
+ */
36
+ run<T>(jobs: readonly ImSimulationBatchJob<T>[], signal?: AbortSignal): Promise<readonly ImSimulationBatchResult<T>[]>;
37
+ /** Cancel active work and queued creation, then await all callbacks and terminal cleanup. */
38
+ stop(): Promise<void>;
39
+ }
40
+ export {};
@@ -3,7 +3,8 @@ import type { KvTable } from '@deepseek-ai/dsh-storage-domain';
3
3
  import type { ImInboundMessageView, ImInboundOperationQuery, ImOutboundView, ImSimulationDeliveryScope, ImSimulationInstanceId } from './delivery-types.ts';
4
4
  import type { ImAgentCoordinator } from './agent-coordinator.ts';
5
5
  import type { ImRuntime } from './runtime.ts';
6
- import type { ImCreateSimulationInstanceRequest, ImInjectSimulationManagedHumanRequest, ImInjectSimulationMemberRequest, ImSimulationInstanceView, ImSimulationInjectionQuery } from './types.ts';
6
+ import { type ImInjectSimulationOperatorRequest, type ImSimulationOperatorReceipt } from './simulation-operator.ts';
7
+ import type { ImCreateSimulationInstanceRequest, ImCreateManualSimulationInstanceRequest, ImInjectSimulationManagedHumanRequest, ImInjectSimulationMemberRequest, ImSimulationInstanceView, ImSimulationInjectionQuery } from './types.ts';
7
8
  /** Runtime-owned controller; durable state is authoritative and live handles are only execution resources. */
8
9
  export declare class ImSimulationController {
9
10
  private readonly ctx;
@@ -17,6 +18,7 @@ export declare class ImSimulationController {
17
18
  private readonly stopping;
18
19
  private readonly replyClosures;
19
20
  private creationTail;
21
+ private readonly hostBuyers;
20
22
  private disposed;
21
23
  private disposeCreated?;
22
24
  private disposeDisposed?;
@@ -28,12 +30,16 @@ export declare class ImSimulationController {
28
30
  dispose(): Promise<void>;
29
31
  /** Re-evaluate tool availability after target or instance state changes. */
30
32
  refreshAllTools(): void;
31
- /** Create and durably publish one tested Session paired with the live simulated-user Session. */
32
- create(request: ImCreateSimulationInstanceRequest): Promise<ImSimulationInstanceView>;
33
+ /** @param request - Live simulated-user Session and target conversation. @param formalOnly - Reject evaluation targets inside the serialized creation operation. @returns The durably published tested Session pair. */
34
+ create(request: ImCreateSimulationInstanceRequest, formalOnly: boolean): Promise<ImSimulationInstanceView>;
35
+ /** @param request - enabled all-direct route. @returns the empty, persisted tested Session. */
36
+ createManual(request: ImCreateManualSimulationInstanceRequest): Promise<ImSimulationInstanceView>;
33
37
  /** Inject one allow-listed participant through the instance-local adapter. */
34
38
  injectMember(request: ImInjectSimulationMemberRequest): Promise<ImInboundMessageView>;
35
39
  /** Inject the frozen account owner locally as operator input, never as a member. */
36
40
  injectManagedHuman(request: ImInjectSimulationManagedHumanRequest): Promise<ImInboundMessageView>;
41
+ /** @param request - Private operator text and retry identity. @returns Durable acceptance only in the running tested Session. */
42
+ injectOperator(request: ImInjectSimulationOperatorRequest): Promise<ImSimulationOperatorReceipt>;
37
43
  /** @param request - original instance and request id. @returns persisted inbound receipt without executing input. */
38
44
  queryInjection(request: ImSimulationInjectionQuery): ImInboundOperationQuery;
39
45
  private validateInjection;
@@ -46,11 +52,18 @@ export declare class ImSimulationController {
46
52
  /** Convert one locally settled tested-Agent reply into isolated inbound for its simulated-user Session. */
47
53
  deliverTestedReply(scope: ImSimulationDeliveryScope, outbound: ImOutboundView): Promise<void>;
48
54
  private createSerialized;
55
+ /** Creation includes conversation initialization; failure releases the tested handle and persists a failed instance. */
56
+ private completeCreation;
49
57
  private recoverCreating;
58
+ private seedManualConversation;
50
59
  private task;
51
60
  private createTestedAgent;
52
61
  private ingest;
53
62
  private queueReplies;
63
+ /** @param id - Running pair driven by a deterministic Host role. @returns Disposer restoring automatic buyer delivery after its owner stops the case. */
64
+ holdBuyer(id: ImSimulationInstanceId): () => void;
65
+ /** @param id - Running pair held by a Host driver. @returns Number of AI and eligible staff replies durably delivered to the buyer; rejects if the buyer is not held or live. */
66
+ deliverBuyerReplies(id: ImSimulationInstanceId): Promise<number>;
54
67
  private driveReplies;
55
68
  private submit;
56
69
  private scheduleStop;
@@ -0,0 +1,19 @@
1
+ import { type MessageId, type UserMessage } from '@deepseek-ai/dsh-llm';
2
+ import type { Session, SessionId } from '@deepseek-ai/dsh-session';
3
+ import type { ImDeliveryOperationId, ImSimulationInstanceId } from './delivery-types.ts';
4
+ /** Caller-owned identity and text for one private operator message. */
5
+ export interface ImInjectSimulationOperatorRequest {
6
+ readonly instanceId: ImSimulationInstanceId;
7
+ readonly requestId: ImDeliveryOperationId;
8
+ readonly text: string;
9
+ }
10
+ /** Durable inbox acceptance; it does not imply that the target has answered. */
11
+ export interface ImSimulationOperatorReceipt {
12
+ readonly sessionId: SessionId;
13
+ readonly messageId: MessageId;
14
+ readonly status: 'accepted';
15
+ }
16
+ /** @param request - Private message with a stable retry identity. @returns Immutable, unlabelled user input with the same identity on retries. */
17
+ export declare function simulationOperatorMessage(request: ImInjectSimulationOperatorRequest): UserMessage;
18
+ /** @param session - Target's persisted event view. @param message - Expected retry identity and content. @returns Whether the same message is already queued or consumed; conflicting reuse throws. */
19
+ export declare function hasSimulationOperatorMessage(session: Session, message: UserMessage): boolean;
@@ -0,0 +1,27 @@
1
+ /** Connection-local SQLite locking and page-cache settings shared by product journals. */
2
+ import type { DatabaseSync } from 'node:sqlite';
3
+ /** SQLite locking policy; EXCLUSIVE requires sole ownership until connection close. */
4
+ export type SqliteLockingMode = 'NORMAL' | 'EXCLUSIVE';
5
+ /** Deployment settings; an absent cache budget keeps SQLite's default page cache. */
6
+ export interface SqliteConnectionConfig {
7
+ readonly lockingMode?: SqliteLockingMode | undefined;
8
+ readonly cacheSizeKiB?: number | undefined;
9
+ }
10
+ /** Validated connection settings; null preserves SQLite's default cache budget. */
11
+ export interface SqliteConnectionSpec {
12
+ readonly lockingMode: SqliteLockingMode;
13
+ readonly cacheSizeKiB: number | null;
14
+ }
15
+ /**
16
+ * Validate deployment settings before acquiring filesystem or database resources.
17
+ * @param config - Requested connection-local settings.
18
+ * @returns Explicit locking policy and optional page-cache budget in KiB.
19
+ */
20
+ export declare function resolveSqliteConnectionSpec(config: SqliteConnectionConfig): SqliteConnectionSpec;
21
+ /**
22
+ * Apply and verify connection-local settings before any reads or migrations; the caller closes on failure.
23
+ * EXCLUSIVE retains the file lock after a transaction, preventing other connections from reading or writing.
24
+ * @param db - Newly opened connection owned by the caller.
25
+ * @param spec - Validated deployment settings.
26
+ */
27
+ export declare function configureSqliteConnection(db: DatabaseSync, spec: SqliteConnectionSpec): void;
@@ -0,0 +1,13 @@
1
+ /** Minute-precision shop time for IM records and customer-service clock context. */
2
+ /**
3
+ * Format an absolute instant in a configured shop time zone.
4
+ * @param instant - ISO timestamp or milliseconds since the Unix epoch.
5
+ * @param timeZone - IANA time zone; invalid zones fail immediately.
6
+ * @returns Gregorian YYYY-MM-DD HH:mm with a 24-hour clock.
7
+ */
8
+ export declare function formatImTime(instant: string | number, timeZone: string): string;
9
+ /** Instance-owned running clock; the Host can jump forward between completed steps. */
10
+ export interface ImClockSource {
11
+ /** @returns Absolute Unix milliseconds. Throwing stops request preparation; there is no system-time fallback. */
12
+ now(): number;
13
+ }