@yu_robotics/remote-cli 1.6.209 → 1.6.213

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 (66) hide show
  1. package/README.md +6 -0
  2. package/dist/client/MessageHandler.d.ts.map +1 -1
  3. package/dist/client/MessageHandler.js +6 -4
  4. package/dist/client/MessageHandler.js.map +1 -1
  5. package/dist/delegation/DelegatedWorkerLaneCleanup.d.ts.map +1 -1
  6. package/dist/delegation/DelegatedWorkerLaneCleanup.js +2 -22
  7. package/dist/delegation/DelegatedWorkerLaneCleanup.js.map +1 -1
  8. package/dist/delegation/DelegatedWorkerSessionStore.d.ts +31 -1
  9. package/dist/delegation/DelegatedWorkerSessionStore.d.ts.map +1 -1
  10. package/dist/delegation/DelegatedWorkerSessionStore.js +204 -15
  11. package/dist/delegation/DelegatedWorkerSessionStore.js.map +1 -1
  12. package/dist/delegation/DelegatedWorkspaceManager.d.ts +2 -0
  13. package/dist/delegation/DelegatedWorkspaceManager.d.ts.map +1 -1
  14. package/dist/delegation/DelegatedWorkspaceManager.js +1 -1
  15. package/dist/delegation/DelegatedWorkspaceManager.js.map +1 -1
  16. package/dist/delegation/DelegationManager.d.ts +14 -1
  17. package/dist/delegation/DelegationManager.d.ts.map +1 -1
  18. package/dist/delegation/DelegationManager.js +183 -15
  19. package/dist/delegation/DelegationManager.js.map +1 -1
  20. package/dist/delegation/KimiSessionDeletion.d.ts +20 -0
  21. package/dist/delegation/KimiSessionDeletion.d.ts.map +1 -0
  22. package/dist/delegation/KimiSessionDeletion.js +102 -0
  23. package/dist/delegation/KimiSessionDeletion.js.map +1 -0
  24. package/dist/delegation/LinuxHistoryAnchor.d.ts +24 -0
  25. package/dist/delegation/LinuxHistoryAnchor.d.ts.map +1 -0
  26. package/dist/delegation/LinuxHistoryAnchor.js +161 -0
  27. package/dist/delegation/LinuxHistoryAnchor.js.map +1 -0
  28. package/dist/delegation/NativeHistoryFiles.d.ts +84 -0
  29. package/dist/delegation/NativeHistoryFiles.d.ts.map +1 -0
  30. package/dist/delegation/NativeHistoryFiles.js +342 -0
  31. package/dist/delegation/NativeHistoryFiles.js.map +1 -0
  32. package/dist/delegation/NativeSessionDeletion.d.ts +80 -0
  33. package/dist/delegation/NativeSessionDeletion.d.ts.map +1 -0
  34. package/dist/delegation/NativeSessionDeletion.js +439 -0
  35. package/dist/delegation/NativeSessionDeletion.js.map +1 -0
  36. package/dist/executor/AcpExecutor.d.ts +14 -0
  37. package/dist/executor/AcpExecutor.d.ts.map +1 -1
  38. package/dist/executor/AcpExecutor.js +111 -5
  39. package/dist/executor/AcpExecutor.js.map +1 -1
  40. package/dist/executor/AgyExecutor.d.ts.map +1 -1
  41. package/dist/executor/AgyExecutor.js +1 -0
  42. package/dist/executor/AgyExecutor.js.map +1 -1
  43. package/dist/executor/ClaudePersistentExecutor.d.ts +12 -0
  44. package/dist/executor/ClaudePersistentExecutor.d.ts.map +1 -1
  45. package/dist/executor/ClaudePersistentExecutor.js +96 -0
  46. package/dist/executor/ClaudePersistentExecutor.js.map +1 -1
  47. package/dist/executor/CodexAppServerExecutor.d.ts +6 -0
  48. package/dist/executor/CodexAppServerExecutor.d.ts.map +1 -1
  49. package/dist/executor/CodexAppServerExecutor.js +26 -1
  50. package/dist/executor/CodexAppServerExecutor.js.map +1 -1
  51. package/dist/executor/IExecutor.d.ts +6 -0
  52. package/dist/executor/IExecutor.d.ts.map +1 -1
  53. package/dist/executor/KimiExecutor.d.ts.map +1 -1
  54. package/dist/executor/KimiExecutor.js +11 -0
  55. package/dist/executor/KimiExecutor.js.map +1 -1
  56. package/dist/executor/PiExecutor.d.ts +14 -0
  57. package/dist/executor/PiExecutor.d.ts.map +1 -1
  58. package/dist/executor/PiExecutor.js +150 -7
  59. package/dist/executor/PiExecutor.js.map +1 -1
  60. package/dist/executor/acp/AcpClient.d.ts.map +1 -1
  61. package/dist/executor/acp/AcpClient.js +3 -1
  62. package/dist/executor/acp/AcpClient.js.map +1 -1
  63. package/dist/executor/pi/PiTypes.js +2 -2
  64. package/dist/executor/pi/PiTypes.js.map +1 -1
  65. package/dist/maintenance/release-notes.json +1 -1
  66. package/package.json +1 -1
@@ -5,6 +5,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.DelegationManager = exports.DELEGATION_TEXT_PROGRESS = exports.DELEGATION_LIMITS = void 0;
7
7
  exports.workspacesOverlap = workspacesOverlap;
8
+ const NativeSessionDeletion_1 = require("./NativeSessionDeletion");
9
+ const NativeHistoryFiles_1 = require("./NativeHistoryFiles");
10
+ const KimiSessionDeletion_1 = require("./KimiSessionDeletion");
8
11
  const crypto_1 = require("crypto");
9
12
  const fs_1 = __importDefault(require("fs"));
10
13
  const path_1 = __importDefault(require("path"));
@@ -129,6 +132,8 @@ class DelegationManager {
129
132
  guard;
130
133
  factory;
131
134
  cleanupMs;
135
+ nativeDeletionClientFactory;
136
+ kimiDeletionClientFactory;
132
137
  registry;
133
138
  store;
134
139
  laneStore;
@@ -141,6 +146,9 @@ class DelegationManager {
141
146
  reportedUnavailableWriterEvidence = false;
142
147
  publicOperations = new Set();
143
148
  maintenance;
149
+ nativeSessionDeletions;
150
+ nativeMaintenance;
151
+ nativeResetFences = new Map();
144
152
  maintenanceTimer;
145
153
  admissionGate = Promise.resolve();
146
154
  running = 0;
@@ -150,14 +158,17 @@ class DelegationManager {
150
158
  detachedScopes = new Map();
151
159
  detachedThreads = new Map();
152
160
  timeouts;
153
- constructor(guard, factory = executor_1.createExecutor, registry = new BackendRegistry_1.BackendRegistry(), store = new DelegationStore_1.DelegationStore(), timeoutInput = exports.DELEGATION_LIMITS, cleanupMs = 10_000, laneStore = new DelegatedWorkerSessionStore_1.DelegatedWorkerSessionStore(), workspaceManager = new DelegatedWorkspaceManager_1.DelegatedWorkspaceManager()) {
161
+ constructor(guard, factory = executor_1.createExecutor, registry = new BackendRegistry_1.BackendRegistry(), store = new DelegationStore_1.DelegationStore(), timeoutInput = exports.DELEGATION_LIMITS, cleanupMs = 10_000, laneStore = new DelegatedWorkerSessionStore_1.DelegatedWorkerSessionStore(), workspaceManager = new DelegatedWorkspaceManager_1.DelegatedWorkspaceManager(), nativeDeletionClientFactory, kimiDeletionClientFactory) {
154
162
  this.guard = guard;
155
163
  this.factory = factory;
156
164
  this.cleanupMs = cleanupMs;
165
+ this.nativeDeletionClientFactory = nativeDeletionClientFactory;
166
+ this.kimiDeletionClientFactory = kimiDeletionClientFactory;
157
167
  this.registry = registry;
158
168
  this.store = store;
159
169
  this.laneStore = laneStore;
160
170
  this.workspaceManager = workspaceManager;
171
+ this.nativeSessionDeletions = new NativeSessionDeletion_1.NativeSessionDeletionQueue(path_1.default.join(path_1.default.dirname(laneStore.storageDirectory), 'native-session-deletions'));
161
172
  this.timeouts = timeoutPolicy(timeoutInput);
162
173
  this.ownership = new DelegationOwnership_1.DelegationOwnership(laneStore.storageDirectory);
163
174
  this.laneStore.setInitializationGuard(() => this.ensureOwnership());
@@ -452,6 +463,8 @@ class DelegationManager {
452
463
  };
453
464
  const discardLane = async (lane) => {
454
465
  try {
466
+ if (await this.isNativeDeletionRequested(lane))
467
+ return false;
455
468
  if (source)
456
469
  await this.workspaceManager.preserveLane(lane.id);
457
470
  await (0, DelegatedWorkerLaneCleanup_1.cleanupDelegatedWorkerLane)(lane);
@@ -625,12 +638,17 @@ class DelegationManager {
625
638
  throw new Error('Worker lane is unavailable before native startup');
626
639
  const executionCwd = task.workspace?.cwd ?? cwd;
627
640
  const workerGuard = task.workspace ? new DirectoryGuard_1.DirectoryGuard([...this.guard.getAllowedDirectories(), executionCwd]) : this.guard;
641
+ // Invalidate inherited exit evidence before the factory can launch
642
+ // any native process, including a constructor that later throws.
643
+ await this.laneStore.markRunning(task.lane.id);
644
+ assertStartable();
628
645
  worker = this.factory(workerGuard, configuration, executionCwd, task.lane.executorThreadId, (0, ThreadExecutorPool_1.resolveThreadModel)(parent.thread, configuration), parent.thread.efforts?.[backend], { lifecycleHooks: false, delegationWorker: true, ...(parent.thread.speeds?.[backend] !== undefined ? { speed: parent.thread.speeds[backend] } : {}) });
629
646
  task.executor = worker;
647
+ const observedLane = task.lane;
648
+ worker.observeNativeSessionCreation?.(target => this.laneStore.captureNativeSession(observedLane.id, observedLane.contextGeneration ?? 0, target), () => this.laneStore.recordNativeCaptureFailure(observedLane.id, observedLane.contextGeneration ?? 0));
630
649
  if (fs_1.default.realpathSync(worker.getCurrentWorkingDirectory()) !== fs_1.default.realpathSync(executionCwd)) {
631
650
  throw new Error('Worker refused the delegated workspace; refusing a fallback directory');
632
651
  }
633
- await this.laneStore.markRunning(task.lane.id);
634
652
  assertStartable();
635
653
  task.preserveUnstartedLane = false;
636
654
  return worker;
@@ -658,6 +676,7 @@ class DelegationManager {
658
676
  if (!confirmGroup)
659
677
  throw new Error('Worker backend cannot confirm managed process-group exit; preserve the checkout');
660
678
  await deadline(() => confirmGroup.call(worker), this.cleanupMs);
679
+ await this.laneStore.markShutdownConfirmed(lane.id, lane.contextGeneration ?? 0, true);
661
680
  }
662
681
  }
663
682
  catch (error) {
@@ -716,10 +735,23 @@ class DelegationManager {
716
735
  // Native session IDs are distinct; policy was resolved against the real
717
736
  // parent thread before passing the synthetic worker identity to the factory.
718
737
  let acceptingActivity = true;
719
- const execution = worker.execute(`You are executing one delegated task in an isolated worker session. This session may contain context from earlier delegated tasks in this thread and workspace. Complete only this objective and return a concise result with verification and remaining issues. Do not delegate to other agents.${task.workspace
720
- ? `\nThis task runs in an owned Git worktree at ${task.workspace.cwd}, with a fresh detached task checkout based on checkpoint ${task.workspace.input.commit}. Previous task changes are NOT implicitly present. Re-read current files; earlier conversation context may be stale. Stay within this checkout. Do not merge into or edit the delivery directory, push, change branches, or remove the worktree. Your file changes will be captured as an artifact for explicit coordinator integration. Ignored files and dependencies are not copied from the delivery directory. This checkout is disposable: after delivery or retention it may be removed, including ignored files and dependencies. Include required source changes and deliverables in the captured Git artifact; never treat a path in this checkout as durable delivery. Failed captured changes are retained for recovery without automatic merging. A worktree is not an OS sandbox.${task.workspace.input.sharedLinks?.length ? `\nShared external links: ${task.workspace.input.sharedLinks.map(b => JSON.stringify(b.path)).join(', ')}. These links reach shared original data. Edits there are direct and are NOT captured, merged, reverted, or backed up by worktree artifacts. Do not stage or change the shared link nodes themselves.` : ''}` : ''}
721
-
722
- ${objective}${task.exports?.length ? `\nRequired durable output paths (relative to checkout root): ${JSON.stringify(task.exports)}` : ''}`, {
738
+ const workspaceKind = task.workspace ? 'git' : 'shared';
739
+ const fixedInstructions = 'You are executing one delegated task in an isolated worker session. This session may contain context from earlier delegated tasks in this thread and workspace.'
740
+ + (task.workspace ? '\nYour file changes will be captured as an artifact for explicit coordinator integration. Ignored files and dependencies are not copied from the delivery directory. This checkout is disposable: after delivery or retention it may be removed, including ignored files and dependencies. Include required source changes and deliverables in the captured Git artifact; never treat a path in this checkout as durable delivery. Failed captured changes are retained for recovery without automatic merging. A worktree is not an OS sandbox.' : '');
741
+ const taskInstructions = 'Complete only this objective and return a concise result with verification and remaining issues. Do not delegate to other agents.'
742
+ + (task.workspace
743
+ ? `\nThis task runs in an owned Git worktree at ${task.workspace.cwd}, with a fresh detached task checkout based on checkpoint ${task.workspace.input.commit}. Previous task changes are NOT implicitly present. Re-read current files; earlier conversation context may be stale. Stay within this checkout. Do not merge into or edit the delivery directory, push, change branches, or remove the worktree.${task.workspace.input.sharedLinks?.length ? `\nShared external links: ${task.workspace.input.sharedLinks.map(b => JSON.stringify(b.path)).join(', ')}. These links reach shared original data. Edits there are direct and are NOT captured, merged, reverted, or backed up by worktree artifacts. Do not stage or change the shared link nodes themselves.` : ''}`
744
+ : `\nCurrent working directory: ${cwd}. Re-read current files; earlier conversation context may be stale.`)
745
+ + `\n\n${objective}${task.exports?.length ? `\nRequired durable output paths (relative to checkout root): ${JSON.stringify(task.exports)}` : ''}`;
746
+ const fullPrompt = `${fixedInstructions}\n${taskInstructions}`;
747
+ let includedFixedInstructions = true;
748
+ const execution = worker.execute(fullPrompt, {
749
+ resolvePrompt: sessionId => {
750
+ const initialized = task.lane?.initializedPrompt;
751
+ includedFixedInstructions = !sessionId || initialized?.sessionId !== sessionId
752
+ || initialized.workspaceKind !== workspaceKind;
753
+ return includedFixedInstructions ? fullPrompt : taskInstructions;
754
+ },
723
755
  // The manager owns delegated-task liveness. Zero disables optional
724
756
  // backend-local limits that would otherwise ignore tool callbacks.
725
757
  timeout: 0,
@@ -811,6 +843,14 @@ ${prompt}`));
811
843
  finally {
812
844
  acceptingActivity = false;
813
845
  }
846
+ // A failed first turn cannot establish context. A confirmed resume may
847
+ // retain its earlier initialization even when this task itself fails.
848
+ const sessionId = worker.getSessionId?.();
849
+ const confirmedContext = result.success || (!includedFixedInstructions
850
+ && sessionId === task.lane?.initializedPrompt?.sessionId);
851
+ if (confirmedContext && sessionId && task.lane && !(0, DelegationStore_1.isTerminalTaskState)(task.record.state)) {
852
+ await this.laneStore.markPromptInitialized(task.lane.id, sessionId, workspaceKind);
853
+ }
814
854
  captureWorkerMetadata(task);
815
855
  metadataCaptured = true;
816
856
  if (!result.success && attempt === 0 && worker.consumeSessionResumeFailure?.()) {
@@ -864,16 +904,28 @@ ${prompt}`));
864
904
  // reserving the workspace indefinitely.
865
905
  task.discardLane = true;
866
906
  }
867
- if (task.workspace?.disposalPolicy === 1 && task.executor) {
907
+ let groupConfirmed = false;
908
+ if (source && task.executor?.waitForManagedProcessGroupExit) {
868
909
  const confirmGroup = task.executor.waitForManagedProcessGroupExit;
869
- if (!confirmGroup)
870
- throw new Error('Worker backend cannot confirm managed process-group exit; preserve the checkout');
871
- await deadline(() => confirmGroup.call(task.executor), this.cleanupMs);
910
+ try {
911
+ await deadline(() => confirmGroup.call(task.executor), this.cleanupMs);
912
+ groupConfirmed = true;
913
+ }
914
+ catch (error) {
915
+ if (task.workspace?.disposalPolicy === 1)
916
+ throw error;
917
+ // Preserve the existing shared/legacy task lifecycle, but never
918
+ // convert transport exit into permission to delete native history.
919
+ console.warn('[Delegation] Native session deletion remains held: managed process-group exit is unconfirmed.');
920
+ }
921
+ }
922
+ else if (task.workspace?.disposalPolicy === 1 && task.executor) {
923
+ throw new Error('Worker backend cannot confirm managed process-group exit; preserve the checkout');
872
924
  }
873
925
  nativeExitConfirmed = true;
874
926
  task.nativeExitConfirmed = released;
875
927
  if (released && task.lane) {
876
- await this.laneStore.markShutdownConfirmed(task.lane.id, task.lane.contextGeneration ?? 0);
928
+ await this.laneStore.markShutdownConfirmed(task.lane.id, task.lane.contextGeneration ?? 0, groupConfirmed);
877
929
  }
878
930
  if (released && task.lane && task.preserveUnstartedLane) {
879
931
  if (!task.workspacePreparationStarted) {
@@ -894,7 +946,8 @@ ${prompt}`));
894
946
  if (released && task.lane && !task.preserveUnstartedLane) {
895
947
  try {
896
948
  if (task.workspace) {
897
- task.artifact = await this.workspaceManager.collect(task.workspace, task.record.state === 'succeeded', { exitConfirmed: true, exports: task.exports });
949
+ task.artifact = await this.workspaceManager.collect(task.workspace, task.record.state === 'succeeded', { exitConfirmed: true, exports: task.exports,
950
+ preserveForRecovery: () => this.isNativeDeletionRequested(task.lane) });
898
951
  readyWorkspaceLane = task.lane;
899
952
  }
900
953
  else {
@@ -950,10 +1003,21 @@ ${prompt}`));
950
1003
  }
951
1004
  console.warn('[Delegation] Worker cleanup failed:', error instanceof Error ? error.message : 'Cleanup failure');
952
1005
  }
1006
+ // Shared-directory finalization keeps its original deadline. Optional
1007
+ // history-deletion evidence must not turn completed work into a failure.
1008
+ if (!source && released && task.lane && task.executor?.waitForManagedProcessGroupExit) {
1009
+ try {
1010
+ await deadline(() => task.executor.waitForManagedProcessGroupExit(), this.cleanupMs);
1011
+ await this.laneStore.markShutdownConfirmed(task.lane.id, task.lane.contextGeneration ?? 0, true);
1012
+ }
1013
+ catch {
1014
+ console.warn('[Delegation] Native session deletion remains held: managed process-group exit is unconfirmed.');
1015
+ }
1016
+ }
953
1017
  if (released && readyWorkspaceLane) {
954
1018
  // Reclamation awaits subprocess exit; a timeout race must not release a live removal.
955
1019
  // The lane stays non-ready until its checkout state is settled.
956
- if (task.artifact && task.artifact.disposition !== 'pending') {
1020
+ if (task.artifact && task.artifact.disposition !== 'pending' && !await this.isNativeDeletionRequested(readyWorkspaceLane)) {
957
1021
  await this.workspaceManager.reclaim(task.record.id);
958
1022
  }
959
1023
  try {
@@ -1444,6 +1508,104 @@ ${prompt}`));
1444
1508
  hasWorkspaceLease(threadId) {
1445
1509
  return [...this.workspaces.values()].some(owner => owner.threadId === threadId);
1446
1510
  }
1511
+ /** Persist before advancing the parent generation; no backend is started on the reset path. */
1512
+ async requestNativeSessionDeletion(threadId, throughGeneration) {
1513
+ if (!threadId || threadId.length > 200 || !Number.isSafeInteger(throughGeneration) || throughGeneration < 0) {
1514
+ throw new Error('Invalid native deletion reset fence');
1515
+ }
1516
+ // Reserve preservation synchronously: in-flight finalizers must not discard
1517
+ // evidence while the durable request is being written. No Git admission wait.
1518
+ this.nativeResetFences.set(threadId, Math.max(this.nativeResetFences.get(threadId) ?? 0, throughGeneration));
1519
+ return this.publicOperation(async () => {
1520
+ await this.nativeSessionDeletions.enqueue(threadId, throughGeneration);
1521
+ // An unreadable legacy inventory must not prevent fresh direct context.
1522
+ // The separate durable fence retains the whole request for later retry.
1523
+ try {
1524
+ await this.ensureOwnership();
1525
+ await this.laneStore.requestNativeDeletion(threadId, throughGeneration);
1526
+ }
1527
+ catch {
1528
+ console.warn('[Delegation] Native deletion is held: worker inventory is unavailable; reset intent was retained.');
1529
+ }
1530
+ this.scheduleMaintenance();
1531
+ });
1532
+ }
1533
+ async isNativeDeletionRequested(lane) {
1534
+ return lane.nativeDeleteRequested === true || lane.workspaceGeneration <= (this.nativeResetFences.get(lane.threadId) ?? -1)
1535
+ || (await this.nativeSessionDeletions.requests())
1536
+ .some(request => request.threadId === lane.threadId && lane.workspaceGeneration <= request.throughGeneration);
1537
+ }
1538
+ async retireRequestedNativeSessions() {
1539
+ const requests = await this.nativeSessionDeletions.requests();
1540
+ for (const request of requests) {
1541
+ this.nativeResetFences.set(request.threadId, Math.max(this.nativeResetFences.get(request.threadId) ?? 0, request.throughGeneration));
1542
+ await this.laneStore.requestNativeDeletion(request.threadId, request.throughGeneration);
1543
+ }
1544
+ return requests;
1545
+ }
1546
+ /** Independent maintenance retains ownership until the native transport has stopped. */
1547
+ async reconcileNativeSessionDeletions() {
1548
+ if (this.nativeMaintenance)
1549
+ return this.nativeMaintenance;
1550
+ const operation = this.publicOperation(async () => {
1551
+ await this.ensureOwnership();
1552
+ const requests = await this.retireRequestedNativeSessions();
1553
+ for (const lane of await this.laneStore.nativeDeletionCandidates()) {
1554
+ let result;
1555
+ if (!requests.some(request => request.threadId === lane.threadId && lane.workspaceGeneration <= request.throughGeneration)) {
1556
+ result = { state: 'held', reason: 'Durable parent reset authorization is unavailable' };
1557
+ }
1558
+ else if (!['codex', 'kimi', 'pi', 'claude'].includes(lane.backend)) {
1559
+ result = { state: 'unsupported', reason: `${lane.backend} has no verified permanent deletion adapter; native history was retained` };
1560
+ }
1561
+ else if (lane.nativeMaintenanceExitUnconfirmed) {
1562
+ result = { state: 'waiting-exit', reason: 'An earlier native maintenance writer exit is unconfirmed' };
1563
+ }
1564
+ else if (lane.nativeHistoryExitUnconfirmed) {
1565
+ result = { state: 'waiting-exit', reason: 'An earlier native worker exit is unconfirmed; a later executor cannot authorize its deletion' };
1566
+ }
1567
+ else if (lane.nativeGroupExitGeneration !== (lane.contextGeneration ?? 0)) {
1568
+ result = { state: 'waiting-exit', reason: 'Owned worker process-group exit is unconfirmed' };
1569
+ }
1570
+ else if ((!lane.nativeSession && !lane.nativeSessionHistory?.length) || lane.nativeSessionConflict) {
1571
+ result = { state: 'held', reason: 'Exact owned native session creation identity is unavailable or conflicting' };
1572
+ }
1573
+ else {
1574
+ result = { state: 'deleted', reason: 'All owned native session identities were deleted' };
1575
+ const targets = [...(lane.nativeSessionHistory ?? []), ...(lane.nativeSession ? [lane.nativeSession] : [])];
1576
+ for (const target of targets) {
1577
+ if (!await this.laneStore.isNativeIdentityExclusive(lane.id, target)) {
1578
+ result = { state: 'held', reason: 'Native session identity is referenced by another worker' };
1579
+ break;
1580
+ }
1581
+ const recovery = {
1582
+ detachedPointer: target !== lane.nativeSession || lane.contextRetired === true || lane.contextResetPending === true,
1583
+ prepared: lane.nativeDeletionPreparations?.[target.sessionId],
1584
+ persistPrepared: (prepared) => this.laneStore.prepareNativeDeletion(lane.id, lane.contextGeneration ?? 0, target, prepared),
1585
+ persistMaintenanceState: (unconfirmed) => this.laneStore.recordNativeMaintenance(lane.id, lane.contextGeneration ?? 0, unconfirmed),
1586
+ };
1587
+ const outcome = await this.ownership.withProcesses(() => target.backend === 'codex'
1588
+ ? (0, NativeSessionDeletion_1.deleteOwnedCodexSession)(target, this.nativeDeletionClientFactory, recovery)
1589
+ : target.backend === 'kimi' ? (0, KimiSessionDeletion_1.deleteOwnedKimiSession)(target, recovery, this.kimiDeletionClientFactory) : (0, NativeHistoryFiles_1.deleteOwnedHistoryFiles)(target, recovery));
1590
+ if (outcome.state !== 'deleted') {
1591
+ result = outcome;
1592
+ break;
1593
+ }
1594
+ }
1595
+ }
1596
+ await this.laneStore.recordNativeDeletion(lane.id, lane.contextGeneration ?? 0, result);
1597
+ if (result.state !== 'deleted')
1598
+ console.warn(`[Delegation] Native session deletion ${result.state}: ${result.reason}`);
1599
+ }
1600
+ });
1601
+ this.nativeMaintenance = operation;
1602
+ try {
1603
+ await operation;
1604
+ }
1605
+ finally {
1606
+ this.nativeMaintenance = undefined;
1607
+ }
1608
+ }
1447
1609
  /** Retry previously confirmed cleanup requests without touching uncertain interrupted workers. */
1448
1610
  async reconcilePendingWorkerLanes() {
1449
1611
  this.assertAcceptingOperations();
@@ -1453,12 +1615,16 @@ ${prompt}`));
1453
1615
  await this.ensureOwnership();
1454
1616
  if (this.scopes.size || this.detachedScopes.size || this.running || this.workspaces.size)
1455
1617
  return { removed: 0, failed: 0 };
1456
- await this.workspaceManager.retryReclamation({ limit: 25 });
1618
+ await this.retireRequestedNativeSessions();
1619
+ await this.workspaceManager.retryReclamation({ limit: 25,
1620
+ excludedLaneIds: new Set((await this.laneStore.nativeDeletionCandidates(true)).map(lane => lane.id)) });
1457
1621
  return this.removeWorkerLanes(await this.laneStore.cleanupCandidates(), true);
1458
1622
  });
1459
1623
  this.maintenance = operation;
1460
1624
  try {
1461
- return await operation;
1625
+ const result = await operation;
1626
+ await this.reconcileNativeSessionDeletions();
1627
+ return result;
1462
1628
  }
1463
1629
  finally {
1464
1630
  this.maintenance = undefined;
@@ -1530,6 +1696,8 @@ ${prompt}`));
1530
1696
  let failed = 0;
1531
1697
  for (const lane of lanes) {
1532
1698
  try {
1699
+ if (await this.isNativeDeletionRequested(lane))
1700
+ continue;
1533
1701
  await this.closeoutRemovedLane(lane);
1534
1702
  await (0, DelegatedWorkerLaneCleanup_1.cleanupDelegatedWorkerLane)(lane);
1535
1703
  await this.laneStore.remove(lane.id);