@adhdev/session-host-core 1.0.82-rc.36 → 1.0.82-rc.37

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/dist/index.d.mts CHANGED
@@ -250,6 +250,26 @@ interface ResizeSessionPayload {
250
250
  interface StopSessionPayload {
251
251
  sessionId: string;
252
252
  }
253
+ /**
254
+ * Expected logical + physical identity for a cleanup stop. Captured before any
255
+ * async host RPC and re-checked inside the host stop critical section.
256
+ * All of taskId/attemptId/generation/dispatchNonce null means expected unbound
257
+ * (no meshActiveAssignment) so a later claim cannot be stopped by stale cleanup.
258
+ */
259
+ interface SessionCleanupExpectedAssignment {
260
+ sessionId: string;
261
+ hostBootId: string;
262
+ runtimeKey: string;
263
+ startedAt: number;
264
+ taskId: string | null;
265
+ attemptId: string | null;
266
+ generation: number | null;
267
+ dispatchNonce: number | null;
268
+ }
269
+ interface StopSessionIfExpectedPayload {
270
+ sessionId: string;
271
+ expected: SessionCleanupExpectedAssignment;
272
+ }
253
273
  interface MeshWriterAssignment {
254
274
  meshId: string;
255
275
  nodeId: string;
@@ -275,6 +295,13 @@ interface DeleteSessionPayload {
275
295
  /** Stop a live runtime before deleting the persisted record. */
276
296
  force?: boolean;
277
297
  }
298
+ /** Expected identity for record deletion; old hosts must refuse this distinct kind. */
299
+ interface DeleteSessionIfExpectedPayload {
300
+ sessionId: string;
301
+ expected: SessionCleanupExpectedAssignment;
302
+ /** Stop the matching live runtime before deleting that exact incarnation. */
303
+ force?: boolean;
304
+ }
278
305
  interface ResumeSessionPayload {
279
306
  sessionId: string;
280
307
  }
@@ -393,6 +420,13 @@ interface SessionHostDiagnostics {
393
420
  * must treat `undefined` as "unknown", never as a match.
394
421
  */
395
422
  hostEntryPath?: string;
423
+ /**
424
+ * Authoritative host boot identity used by cleanup expected-assignment CAS.
425
+ * Same value `stop_session_if_expected` refuses against: upgrade-lease bootId
426
+ * when the host was launched with a native upgrade binding, otherwise `hs:<hostStartedAt>`.
427
+ * Optional so older hosts omit it; callers must not invent an upgrade UUID.
428
+ */
429
+ hostBootId?: string;
396
430
  runtimeCount: number;
397
431
  supportedRequestTypes?: SessionHostRequestType[];
398
432
  sessions?: SessionHostRecord[];
@@ -471,12 +505,22 @@ type SessionHostRequest = {
471
505
  } | {
472
506
  type: 'stop_session';
473
507
  payload: StopSessionPayload;
508
+ }
509
+ /** Distinct kind: old hosts must refuse instead of stopping by session id alone. */
510
+ | {
511
+ type: 'stop_session_if_expected';
512
+ payload: StopSessionIfExpectedPayload;
474
513
  } | {
475
514
  type: 'stop_mesh_writer';
476
515
  payload: StopMeshWriterPayload;
477
516
  } | {
478
517
  type: 'delete_session';
479
518
  payload: DeleteSessionPayload;
519
+ }
520
+ /** Distinct kind: old hosts must refuse instead of deleting by session id alone. */
521
+ | {
522
+ type: 'delete_session_if_expected';
523
+ payload: DeleteSessionIfExpectedPayload;
480
524
  } | {
481
525
  type: 'resume_session';
482
526
  payload: ResumeSessionPayload;
@@ -619,6 +663,34 @@ interface SessionHostEventEnvelope {
619
663
  }
620
664
  type SessionHostWireEnvelope = SessionHostRequestEnvelope | SessionHostResponseEnvelope | SessionHostEventEnvelope;
621
665
 
666
+ /** Shared cleanup expected-assignment / host-boot helpers (daemon + host). */
667
+
668
+ /**
669
+ * Prefix on delete_session_if_expected refusals after runtime.stop was requested.
670
+ * Client durable fences must not abort on these — the writer may already be dying.
671
+ * Before-action refusals keep the bare CLEANUP_HOST_REFUSAL_CODES (abort-safe proof).
672
+ */
673
+ declare const CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX = "cleanup_after_stop_side_effect:";
674
+ declare function tagCleanupAfterStopSideEffect(code: string): string;
675
+ declare function stripCleanupAfterStopSideEffect(raw: string): {
676
+ afterStop: boolean;
677
+ code: string;
678
+ };
679
+ declare function hostBootIdFromStartedAt(hostStartedAt: number): string;
680
+ declare function resolveHostBootId(opts: {
681
+ upgradeBootId?: string | null;
682
+ hostStartedAt: number;
683
+ }): string | null;
684
+ /** Sanitized refusal codes only — never echo assignment contents. */
685
+ declare function refuseCleanupExpectedStop(record: SessionHostRecord | null | undefined, expected: SessionCleanupExpectedAssignment, currentHostBootId: string | null, hasRuntime: boolean): string | null;
686
+ /**
687
+ * Delete CAS: same identity/assignment proof as stop. A replaced incarnation or a
688
+ * newly bound writer must survive — never delete a record that no longer matches
689
+ * the captured expected tuple. `force` is required to stop a still-live runtime
690
+ * before deleting that exact incarnation.
691
+ */
692
+ declare function refuseCleanupExpectedDelete(record: SessionHostRecord | null | undefined, expected: SessionCleanupExpectedAssignment, currentHostBootId: string | null, hasRuntime: boolean, force: boolean): string | null;
693
+
622
694
  interface ClassifyTerminationInput {
623
695
  exitCode: number | null;
624
696
  signal?: number | null;
@@ -1083,11 +1155,28 @@ interface SessionHostSnapshot {
1083
1155
  */
1084
1156
  interface SessionHostControlPlane {
1085
1157
  getDiagnostics(payload?: GetHostDiagnosticsPayload): Promise<SessionHostDiagnostics>;
1158
+ /**
1159
+ * Authoritative host boot identity for idle inventory / cleanup expected CAS.
1160
+ * Prefers diagnostics.hostBootId (host SoT), else proves upgrade lease bootId
1161
+ * via get_upgrade_lease, else hs:<hostStartedAt> for non-upgrade / old hosts.
1162
+ * Ambiguous upgrade-lease failures fail closed (null) — never invent a UUID.
1163
+ */
1164
+ resolveHostBootId(): Promise<string | null>;
1086
1165
  listSessions(): Promise<SessionHostRecord[]>;
1087
1166
  stopSession(sessionId: string): Promise<SessionHostRecord | null>;
1167
+ /** Host CAS stop: refuses without mutating when expected assignment/boot/incarnation drift. */
1168
+ stopSessionIfExpected(sessionId: string, expected: SessionCleanupExpectedAssignment): Promise<SessionHostRecord | null>;
1088
1169
  deleteSession(sessionId: string, opts?: {
1089
1170
  force?: boolean;
1090
1171
  }): Promise<SessionHostRecord | null>;
1172
+ /** Host CAS delete: refuses without mutating when expected assignment/boot/incarnation drift. */
1173
+ deleteSessionIfExpected(sessionId: string, expected: SessionCleanupExpectedAssignment, opts?: {
1174
+ force?: boolean;
1175
+ }): Promise<{
1176
+ sessionId: string;
1177
+ deleted: boolean;
1178
+ alreadyAbsent?: boolean;
1179
+ } | null>;
1091
1180
  resumeSession(sessionId: string): Promise<SessionHostRecord | null>;
1092
1181
  restartSession(sessionId: string): Promise<SessionHostRecord | null>;
1093
1182
  sendSignal(sessionId: string, signal: string): Promise<SessionHostRecord | null>;
@@ -1126,4 +1215,4 @@ interface SessionHostControlTransport {
1126
1215
  */
1127
1216
  declare function createSessionHostControlPlane(transport: SessionHostControlTransport): SessionHostControlPlane;
1128
1217
 
1129
- export { type AcquireWritePayload, type AttachSessionPayload, CLI_CHILD_NICE_ENV, CLI_CHILD_NICE_INCREMENT, CLI_CHILD_SCHEDULING_ENV, type ClearSessionBufferPayload, type CreateSessionPayload, DEFAULT_CONFIG_DIR_NAME, DEFAULT_SESSION_RING_BUFFER_MAX_BYTES, type DetachSessionPayload, type ForceDetachClientPayload, type GetHostDiagnosticsPayload, type GetSnapshotPayload, type GetTerminalSnapshotPayload, type HostUpgradeLeasePayload, type MeshWriterAssignment, type MeshWriterStopTarget, type NiceLaunch, OPERATOR_RECOVERY_TARGET, type PruneDuplicateSessionsPayload, type RecoveryHostBinding, RecoveryOwnerAdmission, type RecoveryOwnerChallenge, type RecoveryOwnerEnrollment, type RecoveryOwnerGrant, type RecoveryOwnerOperation, type RecoveryPhysicalProof, type ReleaseWritePayload, type ResizeSessionPayload, type RestartSessionPayload, type ResumeSessionPayload, SESSION_HOST_SUPPORTED_REQUEST_TYPES, type SendInputPayload, type SendSignalPayload, type SessionAttachedClient, type SessionBufferSnapshot, type SessionClientType, type SessionHostCategory, type SessionHostCensus, SessionHostClient, type SessionHostClientOptions, type SessionHostControlPlane, type SessionHostControlTransport, type SessionHostDiagnostics, type SessionHostDisconnectInfo, type SessionHostDisconnectReason, type SessionHostDuplicateSessionGroup, type SessionHostEndpoint, type SessionHostEndpointOptions, type SessionHostEvent, type SessionHostEventEnvelope, type SessionHostLogEntry, type SessionHostPruneDuplicatesResult, type SessionHostRecord, SessionHostRegistry, type SessionHostRequest, type SessionHostRequestEnvelope, type SessionHostRequestTrace, type SessionHostRequestType, type SessionHostResponse, type SessionHostResponseEnvelope, type SessionHostRuntimeTransition, type SessionHostSnapshot, type SessionHostSurfaceKind, type SessionHostSurfaceRecordLike, type SessionHostWireEnvelope, type SessionLaunchCommand, type SessionLifecycle, type SessionOwnerType, SessionRingBuffer, type SessionRingBufferOptions, type SessionTerminalSnapshot, type SessionTerminalState, type SessionTermination, type SessionTransport, type SessionWriteOwner, type StopMeshWriterPayload, type StopSessionPayload, type UpdateSessionMetaPayload, applyTerminalColorEnv, assertRecoveryLaunchIdentity, assertTestStorageIsolated, buildRuntimeDisplayName, buildRuntimeKey, canonicalizeInstancePath, classifyTermination, createCliChildPriorityPolicy, createLineParser, createResponseEnvelope, createSessionHostControlPlane, disconnectSessionHostClients, ensureNodePtySpawnHelperPermissions, findConnectedSessionHostClient, formatRuntimeOwner, getDefaultSessionHostEndpoint, getSessionHostRecoveryLabel, getSessionHostSurfaceKind, getWorkspaceLabel, hiddenSpawn as hiddenSpawnProcess, isDefaultInstanceConfigDir, isRecoveryEndpoint, isSessionHostLiveRuntime, isSessionHostRecoverySnapshot, isTerminalRecord, niceLaunch, partitionSessionHostDiagnosticsSessions, partitionSessionHostRecords, recoveryTargetBytes, replayLaunchEnv, resolveAttachableRuntimeRecord, resolveInstanceConfigDir, resolveRuntimeRecord, resolveSessionHostIpcKey, sanitizeSpawnEnv, spawnCliChild, validateSessionHostEndpoint, writeEnvelope };
1218
+ export { type AcquireWritePayload, type AttachSessionPayload, CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX, CLI_CHILD_NICE_ENV, CLI_CHILD_NICE_INCREMENT, CLI_CHILD_SCHEDULING_ENV, type ClearSessionBufferPayload, type CreateSessionPayload, DEFAULT_CONFIG_DIR_NAME, DEFAULT_SESSION_RING_BUFFER_MAX_BYTES, type DeleteSessionIfExpectedPayload, type DetachSessionPayload, type ForceDetachClientPayload, type GetHostDiagnosticsPayload, type GetSnapshotPayload, type GetTerminalSnapshotPayload, type HostUpgradeLeasePayload, type MeshWriterAssignment, type MeshWriterStopTarget, type NiceLaunch, OPERATOR_RECOVERY_TARGET, type PruneDuplicateSessionsPayload, type RecoveryHostBinding, RecoveryOwnerAdmission, type RecoveryOwnerChallenge, type RecoveryOwnerEnrollment, type RecoveryOwnerGrant, type RecoveryOwnerOperation, type RecoveryPhysicalProof, type ReleaseWritePayload, type ResizeSessionPayload, type RestartSessionPayload, type ResumeSessionPayload, SESSION_HOST_SUPPORTED_REQUEST_TYPES, type SendInputPayload, type SendSignalPayload, type SessionAttachedClient, type SessionBufferSnapshot, type SessionCleanupExpectedAssignment, type SessionClientType, type SessionHostCategory, type SessionHostCensus, SessionHostClient, type SessionHostClientOptions, type SessionHostControlPlane, type SessionHostControlTransport, type SessionHostDiagnostics, type SessionHostDisconnectInfo, type SessionHostDisconnectReason, type SessionHostDuplicateSessionGroup, type SessionHostEndpoint, type SessionHostEndpointOptions, type SessionHostEvent, type SessionHostEventEnvelope, type SessionHostLogEntry, type SessionHostPruneDuplicatesResult, type SessionHostRecord, SessionHostRegistry, type SessionHostRequest, type SessionHostRequestEnvelope, type SessionHostRequestTrace, type SessionHostRequestType, type SessionHostResponse, type SessionHostResponseEnvelope, type SessionHostRuntimeTransition, type SessionHostSnapshot, type SessionHostSurfaceKind, type SessionHostSurfaceRecordLike, type SessionHostWireEnvelope, type SessionLaunchCommand, type SessionLifecycle, type SessionOwnerType, SessionRingBuffer, type SessionRingBufferOptions, type SessionTerminalSnapshot, type SessionTerminalState, type SessionTermination, type SessionTransport, type SessionWriteOwner, type StopMeshWriterPayload, type StopSessionIfExpectedPayload, type StopSessionPayload, type UpdateSessionMetaPayload, applyTerminalColorEnv, assertRecoveryLaunchIdentity, assertTestStorageIsolated, buildRuntimeDisplayName, buildRuntimeKey, canonicalizeInstancePath, classifyTermination, createCliChildPriorityPolicy, createLineParser, createResponseEnvelope, createSessionHostControlPlane, disconnectSessionHostClients, ensureNodePtySpawnHelperPermissions, findConnectedSessionHostClient, formatRuntimeOwner, getDefaultSessionHostEndpoint, getSessionHostRecoveryLabel, getSessionHostSurfaceKind, getWorkspaceLabel, hiddenSpawn as hiddenSpawnProcess, hostBootIdFromStartedAt, isDefaultInstanceConfigDir, isRecoveryEndpoint, isSessionHostLiveRuntime, isSessionHostRecoverySnapshot, isTerminalRecord, niceLaunch, partitionSessionHostDiagnosticsSessions, partitionSessionHostRecords, recoveryTargetBytes, refuseCleanupExpectedDelete, refuseCleanupExpectedStop, replayLaunchEnv, resolveAttachableRuntimeRecord, resolveHostBootId, resolveInstanceConfigDir, resolveRuntimeRecord, resolveSessionHostIpcKey, sanitizeSpawnEnv, spawnCliChild, stripCleanupAfterStopSideEffect, tagCleanupAfterStopSideEffect, validateSessionHostEndpoint, writeEnvelope };
package/dist/index.d.ts CHANGED
@@ -250,6 +250,26 @@ interface ResizeSessionPayload {
250
250
  interface StopSessionPayload {
251
251
  sessionId: string;
252
252
  }
253
+ /**
254
+ * Expected logical + physical identity for a cleanup stop. Captured before any
255
+ * async host RPC and re-checked inside the host stop critical section.
256
+ * All of taskId/attemptId/generation/dispatchNonce null means expected unbound
257
+ * (no meshActiveAssignment) so a later claim cannot be stopped by stale cleanup.
258
+ */
259
+ interface SessionCleanupExpectedAssignment {
260
+ sessionId: string;
261
+ hostBootId: string;
262
+ runtimeKey: string;
263
+ startedAt: number;
264
+ taskId: string | null;
265
+ attemptId: string | null;
266
+ generation: number | null;
267
+ dispatchNonce: number | null;
268
+ }
269
+ interface StopSessionIfExpectedPayload {
270
+ sessionId: string;
271
+ expected: SessionCleanupExpectedAssignment;
272
+ }
253
273
  interface MeshWriterAssignment {
254
274
  meshId: string;
255
275
  nodeId: string;
@@ -275,6 +295,13 @@ interface DeleteSessionPayload {
275
295
  /** Stop a live runtime before deleting the persisted record. */
276
296
  force?: boolean;
277
297
  }
298
+ /** Expected identity for record deletion; old hosts must refuse this distinct kind. */
299
+ interface DeleteSessionIfExpectedPayload {
300
+ sessionId: string;
301
+ expected: SessionCleanupExpectedAssignment;
302
+ /** Stop the matching live runtime before deleting that exact incarnation. */
303
+ force?: boolean;
304
+ }
278
305
  interface ResumeSessionPayload {
279
306
  sessionId: string;
280
307
  }
@@ -393,6 +420,13 @@ interface SessionHostDiagnostics {
393
420
  * must treat `undefined` as "unknown", never as a match.
394
421
  */
395
422
  hostEntryPath?: string;
423
+ /**
424
+ * Authoritative host boot identity used by cleanup expected-assignment CAS.
425
+ * Same value `stop_session_if_expected` refuses against: upgrade-lease bootId
426
+ * when the host was launched with a native upgrade binding, otherwise `hs:<hostStartedAt>`.
427
+ * Optional so older hosts omit it; callers must not invent an upgrade UUID.
428
+ */
429
+ hostBootId?: string;
396
430
  runtimeCount: number;
397
431
  supportedRequestTypes?: SessionHostRequestType[];
398
432
  sessions?: SessionHostRecord[];
@@ -471,12 +505,22 @@ type SessionHostRequest = {
471
505
  } | {
472
506
  type: 'stop_session';
473
507
  payload: StopSessionPayload;
508
+ }
509
+ /** Distinct kind: old hosts must refuse instead of stopping by session id alone. */
510
+ | {
511
+ type: 'stop_session_if_expected';
512
+ payload: StopSessionIfExpectedPayload;
474
513
  } | {
475
514
  type: 'stop_mesh_writer';
476
515
  payload: StopMeshWriterPayload;
477
516
  } | {
478
517
  type: 'delete_session';
479
518
  payload: DeleteSessionPayload;
519
+ }
520
+ /** Distinct kind: old hosts must refuse instead of deleting by session id alone. */
521
+ | {
522
+ type: 'delete_session_if_expected';
523
+ payload: DeleteSessionIfExpectedPayload;
480
524
  } | {
481
525
  type: 'resume_session';
482
526
  payload: ResumeSessionPayload;
@@ -619,6 +663,34 @@ interface SessionHostEventEnvelope {
619
663
  }
620
664
  type SessionHostWireEnvelope = SessionHostRequestEnvelope | SessionHostResponseEnvelope | SessionHostEventEnvelope;
621
665
 
666
+ /** Shared cleanup expected-assignment / host-boot helpers (daemon + host). */
667
+
668
+ /**
669
+ * Prefix on delete_session_if_expected refusals after runtime.stop was requested.
670
+ * Client durable fences must not abort on these — the writer may already be dying.
671
+ * Before-action refusals keep the bare CLEANUP_HOST_REFUSAL_CODES (abort-safe proof).
672
+ */
673
+ declare const CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX = "cleanup_after_stop_side_effect:";
674
+ declare function tagCleanupAfterStopSideEffect(code: string): string;
675
+ declare function stripCleanupAfterStopSideEffect(raw: string): {
676
+ afterStop: boolean;
677
+ code: string;
678
+ };
679
+ declare function hostBootIdFromStartedAt(hostStartedAt: number): string;
680
+ declare function resolveHostBootId(opts: {
681
+ upgradeBootId?: string | null;
682
+ hostStartedAt: number;
683
+ }): string | null;
684
+ /** Sanitized refusal codes only — never echo assignment contents. */
685
+ declare function refuseCleanupExpectedStop(record: SessionHostRecord | null | undefined, expected: SessionCleanupExpectedAssignment, currentHostBootId: string | null, hasRuntime: boolean): string | null;
686
+ /**
687
+ * Delete CAS: same identity/assignment proof as stop. A replaced incarnation or a
688
+ * newly bound writer must survive — never delete a record that no longer matches
689
+ * the captured expected tuple. `force` is required to stop a still-live runtime
690
+ * before deleting that exact incarnation.
691
+ */
692
+ declare function refuseCleanupExpectedDelete(record: SessionHostRecord | null | undefined, expected: SessionCleanupExpectedAssignment, currentHostBootId: string | null, hasRuntime: boolean, force: boolean): string | null;
693
+
622
694
  interface ClassifyTerminationInput {
623
695
  exitCode: number | null;
624
696
  signal?: number | null;
@@ -1083,11 +1155,28 @@ interface SessionHostSnapshot {
1083
1155
  */
1084
1156
  interface SessionHostControlPlane {
1085
1157
  getDiagnostics(payload?: GetHostDiagnosticsPayload): Promise<SessionHostDiagnostics>;
1158
+ /**
1159
+ * Authoritative host boot identity for idle inventory / cleanup expected CAS.
1160
+ * Prefers diagnostics.hostBootId (host SoT), else proves upgrade lease bootId
1161
+ * via get_upgrade_lease, else hs:<hostStartedAt> for non-upgrade / old hosts.
1162
+ * Ambiguous upgrade-lease failures fail closed (null) — never invent a UUID.
1163
+ */
1164
+ resolveHostBootId(): Promise<string | null>;
1086
1165
  listSessions(): Promise<SessionHostRecord[]>;
1087
1166
  stopSession(sessionId: string): Promise<SessionHostRecord | null>;
1167
+ /** Host CAS stop: refuses without mutating when expected assignment/boot/incarnation drift. */
1168
+ stopSessionIfExpected(sessionId: string, expected: SessionCleanupExpectedAssignment): Promise<SessionHostRecord | null>;
1088
1169
  deleteSession(sessionId: string, opts?: {
1089
1170
  force?: boolean;
1090
1171
  }): Promise<SessionHostRecord | null>;
1172
+ /** Host CAS delete: refuses without mutating when expected assignment/boot/incarnation drift. */
1173
+ deleteSessionIfExpected(sessionId: string, expected: SessionCleanupExpectedAssignment, opts?: {
1174
+ force?: boolean;
1175
+ }): Promise<{
1176
+ sessionId: string;
1177
+ deleted: boolean;
1178
+ alreadyAbsent?: boolean;
1179
+ } | null>;
1091
1180
  resumeSession(sessionId: string): Promise<SessionHostRecord | null>;
1092
1181
  restartSession(sessionId: string): Promise<SessionHostRecord | null>;
1093
1182
  sendSignal(sessionId: string, signal: string): Promise<SessionHostRecord | null>;
@@ -1126,4 +1215,4 @@ interface SessionHostControlTransport {
1126
1215
  */
1127
1216
  declare function createSessionHostControlPlane(transport: SessionHostControlTransport): SessionHostControlPlane;
1128
1217
 
1129
- export { type AcquireWritePayload, type AttachSessionPayload, CLI_CHILD_NICE_ENV, CLI_CHILD_NICE_INCREMENT, CLI_CHILD_SCHEDULING_ENV, type ClearSessionBufferPayload, type CreateSessionPayload, DEFAULT_CONFIG_DIR_NAME, DEFAULT_SESSION_RING_BUFFER_MAX_BYTES, type DetachSessionPayload, type ForceDetachClientPayload, type GetHostDiagnosticsPayload, type GetSnapshotPayload, type GetTerminalSnapshotPayload, type HostUpgradeLeasePayload, type MeshWriterAssignment, type MeshWriterStopTarget, type NiceLaunch, OPERATOR_RECOVERY_TARGET, type PruneDuplicateSessionsPayload, type RecoveryHostBinding, RecoveryOwnerAdmission, type RecoveryOwnerChallenge, type RecoveryOwnerEnrollment, type RecoveryOwnerGrant, type RecoveryOwnerOperation, type RecoveryPhysicalProof, type ReleaseWritePayload, type ResizeSessionPayload, type RestartSessionPayload, type ResumeSessionPayload, SESSION_HOST_SUPPORTED_REQUEST_TYPES, type SendInputPayload, type SendSignalPayload, type SessionAttachedClient, type SessionBufferSnapshot, type SessionClientType, type SessionHostCategory, type SessionHostCensus, SessionHostClient, type SessionHostClientOptions, type SessionHostControlPlane, type SessionHostControlTransport, type SessionHostDiagnostics, type SessionHostDisconnectInfo, type SessionHostDisconnectReason, type SessionHostDuplicateSessionGroup, type SessionHostEndpoint, type SessionHostEndpointOptions, type SessionHostEvent, type SessionHostEventEnvelope, type SessionHostLogEntry, type SessionHostPruneDuplicatesResult, type SessionHostRecord, SessionHostRegistry, type SessionHostRequest, type SessionHostRequestEnvelope, type SessionHostRequestTrace, type SessionHostRequestType, type SessionHostResponse, type SessionHostResponseEnvelope, type SessionHostRuntimeTransition, type SessionHostSnapshot, type SessionHostSurfaceKind, type SessionHostSurfaceRecordLike, type SessionHostWireEnvelope, type SessionLaunchCommand, type SessionLifecycle, type SessionOwnerType, SessionRingBuffer, type SessionRingBufferOptions, type SessionTerminalSnapshot, type SessionTerminalState, type SessionTermination, type SessionTransport, type SessionWriteOwner, type StopMeshWriterPayload, type StopSessionPayload, type UpdateSessionMetaPayload, applyTerminalColorEnv, assertRecoveryLaunchIdentity, assertTestStorageIsolated, buildRuntimeDisplayName, buildRuntimeKey, canonicalizeInstancePath, classifyTermination, createCliChildPriorityPolicy, createLineParser, createResponseEnvelope, createSessionHostControlPlane, disconnectSessionHostClients, ensureNodePtySpawnHelperPermissions, findConnectedSessionHostClient, formatRuntimeOwner, getDefaultSessionHostEndpoint, getSessionHostRecoveryLabel, getSessionHostSurfaceKind, getWorkspaceLabel, hiddenSpawn as hiddenSpawnProcess, isDefaultInstanceConfigDir, isRecoveryEndpoint, isSessionHostLiveRuntime, isSessionHostRecoverySnapshot, isTerminalRecord, niceLaunch, partitionSessionHostDiagnosticsSessions, partitionSessionHostRecords, recoveryTargetBytes, replayLaunchEnv, resolveAttachableRuntimeRecord, resolveInstanceConfigDir, resolveRuntimeRecord, resolveSessionHostIpcKey, sanitizeSpawnEnv, spawnCliChild, validateSessionHostEndpoint, writeEnvelope };
1218
+ export { type AcquireWritePayload, type AttachSessionPayload, CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX, CLI_CHILD_NICE_ENV, CLI_CHILD_NICE_INCREMENT, CLI_CHILD_SCHEDULING_ENV, type ClearSessionBufferPayload, type CreateSessionPayload, DEFAULT_CONFIG_DIR_NAME, DEFAULT_SESSION_RING_BUFFER_MAX_BYTES, type DeleteSessionIfExpectedPayload, type DetachSessionPayload, type ForceDetachClientPayload, type GetHostDiagnosticsPayload, type GetSnapshotPayload, type GetTerminalSnapshotPayload, type HostUpgradeLeasePayload, type MeshWriterAssignment, type MeshWriterStopTarget, type NiceLaunch, OPERATOR_RECOVERY_TARGET, type PruneDuplicateSessionsPayload, type RecoveryHostBinding, RecoveryOwnerAdmission, type RecoveryOwnerChallenge, type RecoveryOwnerEnrollment, type RecoveryOwnerGrant, type RecoveryOwnerOperation, type RecoveryPhysicalProof, type ReleaseWritePayload, type ResizeSessionPayload, type RestartSessionPayload, type ResumeSessionPayload, SESSION_HOST_SUPPORTED_REQUEST_TYPES, type SendInputPayload, type SendSignalPayload, type SessionAttachedClient, type SessionBufferSnapshot, type SessionCleanupExpectedAssignment, type SessionClientType, type SessionHostCategory, type SessionHostCensus, SessionHostClient, type SessionHostClientOptions, type SessionHostControlPlane, type SessionHostControlTransport, type SessionHostDiagnostics, type SessionHostDisconnectInfo, type SessionHostDisconnectReason, type SessionHostDuplicateSessionGroup, type SessionHostEndpoint, type SessionHostEndpointOptions, type SessionHostEvent, type SessionHostEventEnvelope, type SessionHostLogEntry, type SessionHostPruneDuplicatesResult, type SessionHostRecord, SessionHostRegistry, type SessionHostRequest, type SessionHostRequestEnvelope, type SessionHostRequestTrace, type SessionHostRequestType, type SessionHostResponse, type SessionHostResponseEnvelope, type SessionHostRuntimeTransition, type SessionHostSnapshot, type SessionHostSurfaceKind, type SessionHostSurfaceRecordLike, type SessionHostWireEnvelope, type SessionLaunchCommand, type SessionLifecycle, type SessionOwnerType, SessionRingBuffer, type SessionRingBufferOptions, type SessionTerminalSnapshot, type SessionTerminalState, type SessionTermination, type SessionTransport, type SessionWriteOwner, type StopMeshWriterPayload, type StopSessionIfExpectedPayload, type StopSessionPayload, type UpdateSessionMetaPayload, applyTerminalColorEnv, assertRecoveryLaunchIdentity, assertTestStorageIsolated, buildRuntimeDisplayName, buildRuntimeKey, canonicalizeInstancePath, classifyTermination, createCliChildPriorityPolicy, createLineParser, createResponseEnvelope, createSessionHostControlPlane, disconnectSessionHostClients, ensureNodePtySpawnHelperPermissions, findConnectedSessionHostClient, formatRuntimeOwner, getDefaultSessionHostEndpoint, getSessionHostRecoveryLabel, getSessionHostSurfaceKind, getWorkspaceLabel, hiddenSpawn as hiddenSpawnProcess, hostBootIdFromStartedAt, isDefaultInstanceConfigDir, isRecoveryEndpoint, isSessionHostLiveRuntime, isSessionHostRecoverySnapshot, isTerminalRecord, niceLaunch, partitionSessionHostDiagnosticsSessions, partitionSessionHostRecords, recoveryTargetBytes, refuseCleanupExpectedDelete, refuseCleanupExpectedStop, replayLaunchEnv, resolveAttachableRuntimeRecord, resolveHostBootId, resolveInstanceConfigDir, resolveRuntimeRecord, resolveSessionHostIpcKey, sanitizeSpawnEnv, spawnCliChild, stripCleanupAfterStopSideEffect, tagCleanupAfterStopSideEffect, validateSessionHostEndpoint, writeEnvelope };
package/dist/index.js CHANGED
@@ -30,6 +30,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX: () => CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX,
33
34
  CLI_CHILD_NICE_ENV: () => CLI_CHILD_NICE_ENV,
34
35
  CLI_CHILD_NICE_INCREMENT: () => CLI_CHILD_NICE_INCREMENT,
35
36
  CLI_CHILD_SCHEDULING_ENV: () => CLI_CHILD_SCHEDULING_ENV,
@@ -63,6 +64,7 @@ __export(index_exports, {
63
64
  getSessionHostSurfaceKind: () => getSessionHostSurfaceKind,
64
65
  getWorkspaceLabel: () => getWorkspaceLabel,
65
66
  hiddenSpawnProcess: () => hiddenSpawn,
67
+ hostBootIdFromStartedAt: () => hostBootIdFromStartedAt,
66
68
  isDefaultInstanceConfigDir: () => isDefaultInstanceConfigDir,
67
69
  isRecoveryEndpoint: () => isRecoveryEndpoint,
68
70
  isSessionHostLiveRuntime: () => isSessionHostLiveRuntime,
@@ -72,8 +74,11 @@ __export(index_exports, {
72
74
  partitionSessionHostDiagnosticsSessions: () => partitionSessionHostDiagnosticsSessions,
73
75
  partitionSessionHostRecords: () => partitionSessionHostRecords,
74
76
  recoveryTargetBytes: () => recoveryTargetBytes,
77
+ refuseCleanupExpectedDelete: () => refuseCleanupExpectedDelete,
78
+ refuseCleanupExpectedStop: () => refuseCleanupExpectedStop,
75
79
  replayLaunchEnv: () => replayLaunchEnv,
76
80
  resolveAttachableRuntimeRecord: () => resolveAttachableRuntimeRecord,
81
+ resolveHostBootId: () => resolveHostBootId,
77
82
  resolveInstanceConfigDir: () => resolveInstanceConfigDir,
78
83
  resolveRuntimeRecord: () => resolveRuntimeRecord,
79
84
  resolveSessionHostCols: () => resolveSessionHostCols,
@@ -81,6 +86,8 @@ __export(index_exports, {
81
86
  resolveSessionHostRows: () => resolveSessionHostRows,
82
87
  sanitizeSpawnEnv: () => sanitizeSpawnEnv,
83
88
  spawnCliChild: () => spawnCliChild,
89
+ stripCleanupAfterStopSideEffect: () => stripCleanupAfterStopSideEffect,
90
+ tagCleanupAfterStopSideEffect: () => tagCleanupAfterStopSideEffect,
84
91
  validateSessionHostEndpoint: () => validateSessionHostEndpoint,
85
92
  writeEnvelope: () => writeEnvelope
86
93
  });
@@ -222,8 +229,10 @@ var SESSION_HOST_SUPPORTED_REQUEST_TYPES = [
222
229
  "get_input_state",
223
230
  "resize_session",
224
231
  "stop_session",
232
+ "stop_session_if_expected",
225
233
  "stop_mesh_writer",
226
234
  "delete_session",
235
+ "delete_session_if_expected",
227
236
  "resume_session",
228
237
  "acquire_write",
229
238
  "release_write",
@@ -241,6 +250,71 @@ var SESSION_HOST_SUPPORTED_REQUEST_TYPES = [
241
250
  "list_sessions"
242
251
  ];
243
252
 
253
+ // src/cleanup-expected.ts
254
+ var CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX = "cleanup_after_stop_side_effect:";
255
+ function tagCleanupAfterStopSideEffect(code) {
256
+ return `${CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX}${code}`;
257
+ }
258
+ function stripCleanupAfterStopSideEffect(raw) {
259
+ if (raw.startsWith(CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX)) {
260
+ return { afterStop: true, code: raw.slice(CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX.length) };
261
+ }
262
+ return { afterStop: false, code: raw };
263
+ }
264
+ function hostBootIdFromStartedAt(hostStartedAt) {
265
+ return `hs:${hostStartedAt}`;
266
+ }
267
+ function resolveHostBootId(opts) {
268
+ if (typeof opts.upgradeBootId === "string" && opts.upgradeBootId) return opts.upgradeBootId;
269
+ if (!Number.isFinite(opts.hostStartedAt) || opts.hostStartedAt <= 0) return null;
270
+ return hostBootIdFromStartedAt(opts.hostStartedAt);
271
+ }
272
+ function refuseCleanupExpectedIdentity(record, expected, currentHostBootId) {
273
+ if (!expected || expected.sessionId !== (record?.sessionId ?? "") || typeof expected.hostBootId !== "string" || !expected.hostBootId || typeof expected.runtimeKey !== "string" || !expected.runtimeKey || !Number.isSafeInteger(expected.startedAt) || expected.startedAt <= 0) {
274
+ return "cleanup_expected_malformed";
275
+ }
276
+ if (!currentHostBootId) return "cleanup_host_boot_unknown";
277
+ if (expected.hostBootId !== currentHostBootId) return "cleanup_host_boot_mismatch";
278
+ if (!record) return "cleanup_session_not_running";
279
+ if (record.runtimeKey !== expected.runtimeKey || record.startedAt !== expected.startedAt) {
280
+ return "cleanup_native_incarnation_mismatch";
281
+ }
282
+ return null;
283
+ }
284
+ function refuseCleanupExpectedAssignment(record, expected, opts = {}) {
285
+ const active = record.meta?.meshActiveAssignment;
286
+ if (expected.taskId === null) {
287
+ if (active && typeof active.taskId === "string" && active.taskId) return "cleanup_expected_unbound_now_bound";
288
+ return null;
289
+ }
290
+ if (!active || typeof active.taskId !== "string" || !active.taskId) {
291
+ return opts.allowClearedBound ? null : "cleanup_expected_bound_now_unbound";
292
+ }
293
+ if (active.taskId !== expected.taskId || active.attemptId !== expected.attemptId || active.generation !== expected.generation || active.dispatchNonce !== expected.dispatchNonce) {
294
+ return "cleanup_assignment_mismatch";
295
+ }
296
+ return null;
297
+ }
298
+ function refuseCleanupExpectedStop(record, expected, currentHostBootId, hasRuntime) {
299
+ const identity = refuseCleanupExpectedIdentity(record, expected, currentHostBootId);
300
+ if (identity) return identity;
301
+ if (!record || record.termination || !hasRuntime || record.lifecycle !== "running") {
302
+ return "cleanup_session_not_running";
303
+ }
304
+ return refuseCleanupExpectedAssignment(record, expected);
305
+ }
306
+ function refuseCleanupExpectedDelete(record, expected, currentHostBootId, hasRuntime, force) {
307
+ if (!record) return "cleanup_session_not_running";
308
+ const identity = refuseCleanupExpectedIdentity(record, expected, currentHostBootId);
309
+ if (identity) return identity;
310
+ if (hasRuntime) {
311
+ if (!force) return "cleanup_session_still_running";
312
+ if (record.termination || record.lifecycle !== "running") return "cleanup_session_not_running";
313
+ return refuseCleanupExpectedAssignment(record, expected);
314
+ }
315
+ return refuseCleanupExpectedAssignment(record, expected, { allowClearedBound: true });
316
+ }
317
+
244
318
  // src/termination.ts
245
319
  function classifyTermination(input) {
246
320
  const { exitCode, terminatedAt } = input;
@@ -1567,15 +1641,48 @@ function createSessionHostControlPlane(transport) {
1567
1641
  getDiagnostics(payload = {}) {
1568
1642
  return transport.request("get_host_diagnostics", payload);
1569
1643
  },
1644
+ async resolveHostBootId() {
1645
+ let diagnostics;
1646
+ try {
1647
+ diagnostics = await transport.request("get_host_diagnostics", {});
1648
+ } catch {
1649
+ return null;
1650
+ }
1651
+ if (typeof diagnostics.hostBootId === "string" && diagnostics.hostBootId) {
1652
+ return diagnostics.hostBootId;
1653
+ }
1654
+ try {
1655
+ const proof = await transport.request("get_upgrade_lease", {});
1656
+ return resolveHostBootId({
1657
+ upgradeBootId: typeof proof?.bootId === "string" ? proof.bootId : null,
1658
+ hostStartedAt: diagnostics.hostStartedAt
1659
+ });
1660
+ } catch (error) {
1661
+ const msg = error instanceof Error ? error.message : String(error);
1662
+ if (msg.includes("native_host_upgrade_binding_unavailable") || /unsupported|unknown request/i.test(msg)) {
1663
+ return resolveHostBootId({ hostStartedAt: diagnostics.hostStartedAt });
1664
+ }
1665
+ return null;
1666
+ }
1667
+ },
1570
1668
  listSessions() {
1571
1669
  return transport.request("list_sessions", {});
1572
1670
  },
1573
1671
  stopSession(sessionId) {
1574
1672
  return transport.request("stop_session", { sessionId });
1575
1673
  },
1674
+ stopSessionIfExpected(sessionId, expected) {
1675
+ return transport.request("stop_session_if_expected", { sessionId, expected });
1676
+ },
1576
1677
  deleteSession(sessionId, opts = {}) {
1577
1678
  return transport.request("delete_session", { sessionId, force: opts.force === true });
1578
1679
  },
1680
+ deleteSessionIfExpected(sessionId, expected, opts = {}) {
1681
+ return transport.request(
1682
+ "delete_session_if_expected",
1683
+ { sessionId, expected, force: opts.force === true }
1684
+ );
1685
+ },
1579
1686
  resumeSession(sessionId) {
1580
1687
  return transport.request("resume_session", { sessionId });
1581
1688
  },
@@ -1604,6 +1711,7 @@ function createSessionHostControlPlane(transport) {
1604
1711
  }
1605
1712
  // Annotate the CommonJS export names for ESM import in node:
1606
1713
  0 && (module.exports = {
1714
+ CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX,
1607
1715
  CLI_CHILD_NICE_ENV,
1608
1716
  CLI_CHILD_NICE_INCREMENT,
1609
1717
  CLI_CHILD_SCHEDULING_ENV,
@@ -1637,6 +1745,7 @@ function createSessionHostControlPlane(transport) {
1637
1745
  getSessionHostSurfaceKind,
1638
1746
  getWorkspaceLabel,
1639
1747
  hiddenSpawnProcess,
1748
+ hostBootIdFromStartedAt,
1640
1749
  isDefaultInstanceConfigDir,
1641
1750
  isRecoveryEndpoint,
1642
1751
  isSessionHostLiveRuntime,
@@ -1646,8 +1755,11 @@ function createSessionHostControlPlane(transport) {
1646
1755
  partitionSessionHostDiagnosticsSessions,
1647
1756
  partitionSessionHostRecords,
1648
1757
  recoveryTargetBytes,
1758
+ refuseCleanupExpectedDelete,
1759
+ refuseCleanupExpectedStop,
1649
1760
  replayLaunchEnv,
1650
1761
  resolveAttachableRuntimeRecord,
1762
+ resolveHostBootId,
1651
1763
  resolveInstanceConfigDir,
1652
1764
  resolveRuntimeRecord,
1653
1765
  resolveSessionHostCols,
@@ -1655,6 +1767,8 @@ function createSessionHostControlPlane(transport) {
1655
1767
  resolveSessionHostRows,
1656
1768
  sanitizeSpawnEnv,
1657
1769
  spawnCliChild,
1770
+ stripCleanupAfterStopSideEffect,
1771
+ tagCleanupAfterStopSideEffect,
1658
1772
  validateSessionHostEndpoint,
1659
1773
  writeEnvelope
1660
1774
  });