@yu_robotics/remote-cli 1.6.255 → 1.6.261

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 (136) hide show
  1. package/dist/client/MessageHandler.d.ts +5 -12
  2. package/dist/client/MessageHandler.d.ts.map +1 -1
  3. package/dist/client/MessageHandler.js +53 -252
  4. package/dist/client/MessageHandler.js.map +1 -1
  5. package/dist/commands/start.d.ts.map +1 -1
  6. package/dist/commands/start.js +0 -3
  7. package/dist/commands/start.js.map +1 -1
  8. package/dist/delegation/DelegatedWorkerLaneCleanup.d.ts.map +1 -1
  9. package/dist/delegation/DelegatedWorkerLaneCleanup.js +10 -1
  10. package/dist/delegation/DelegatedWorkerLaneCleanup.js.map +1 -1
  11. package/dist/delegation/DelegationManager.d.ts +1 -1
  12. package/dist/delegation/DelegationManager.js +2 -2
  13. package/dist/delegation/DelegationManager.js.map +1 -1
  14. package/dist/executor/AcpExecutor.d.ts.map +1 -1
  15. package/dist/executor/AcpExecutor.js.map +1 -1
  16. package/dist/executor/AgyExecutor.d.ts +48 -168
  17. package/dist/executor/AgyExecutor.d.ts.map +1 -1
  18. package/dist/executor/AgyExecutor.js +377 -1082
  19. package/dist/executor/AgyExecutor.js.map +1 -1
  20. package/dist/executor/ClaudePersistentExecutor.d.ts +3 -7
  21. package/dist/executor/ClaudePersistentExecutor.d.ts.map +1 -1
  22. package/dist/executor/ClaudePersistentExecutor.js +14 -224
  23. package/dist/executor/ClaudePersistentExecutor.js.map +1 -1
  24. package/dist/executor/DshExecutor.d.ts +7 -14
  25. package/dist/executor/DshExecutor.d.ts.map +1 -1
  26. package/dist/executor/DshExecutor.js +48 -50
  27. package/dist/executor/DshExecutor.js.map +1 -1
  28. package/dist/executor/IExecutor.d.ts +2 -2
  29. package/dist/executor/IExecutor.d.ts.map +1 -1
  30. package/dist/executor/acp/AcpClient.d.ts +15 -1
  31. package/dist/executor/acp/AcpClient.d.ts.map +1 -1
  32. package/dist/executor/acp/AcpClient.js +85 -7
  33. package/dist/executor/acp/AcpClient.js.map +1 -1
  34. package/dist/executor/agy/AgyAcpDiagnostics.d.ts +8 -0
  35. package/dist/executor/agy/AgyAcpDiagnostics.d.ts.map +1 -0
  36. package/dist/executor/agy/AgyAcpDiagnostics.js +47 -0
  37. package/dist/executor/agy/AgyAcpDiagnostics.js.map +1 -0
  38. package/dist/executor/agy/AgyAcpRuntime.d.ts +39 -24
  39. package/dist/executor/agy/AgyAcpRuntime.d.ts.map +1 -1
  40. package/dist/executor/agy/AgyAcpRuntime.js +234 -202
  41. package/dist/executor/agy/AgyAcpRuntime.js.map +1 -1
  42. package/dist/executor/agy/AgyChatHost.d.ts +34 -0
  43. package/dist/executor/agy/AgyChatHost.d.ts.map +1 -0
  44. package/dist/executor/agy/AgyChatHost.js +106 -0
  45. package/dist/executor/agy/AgyChatHost.js.map +1 -0
  46. package/dist/executor/agy/AgyPermissions.d.ts +13 -0
  47. package/dist/executor/agy/AgyPermissions.d.ts.map +1 -0
  48. package/dist/executor/agy/AgyPermissions.js +61 -0
  49. package/dist/executor/agy/AgyPermissions.js.map +1 -0
  50. package/dist/executor/agy/AgySessionSelection.d.ts +8 -0
  51. package/dist/executor/agy/AgySessionSelection.d.ts.map +1 -0
  52. package/dist/executor/agy/AgySessionSelection.js +86 -0
  53. package/dist/executor/agy/AgySessionSelection.js.map +1 -0
  54. package/dist/executor/agy/AgySessionSettings.d.ts +14 -0
  55. package/dist/executor/agy/AgySessionSettings.d.ts.map +1 -0
  56. package/dist/executor/agy/AgySessionSettings.js +73 -0
  57. package/dist/executor/agy/AgySessionSettings.js.map +1 -0
  58. package/dist/executor/dsh/DshAcpClient.d.ts +1 -1
  59. package/dist/executor/dsh/DshAcpClient.d.ts.map +1 -1
  60. package/dist/executor/dsh/DshAcpClient.js +3 -1
  61. package/dist/executor/dsh/DshAcpClient.js.map +1 -1
  62. package/dist/executor/index.d.ts +2 -1
  63. package/dist/executor/index.d.ts.map +1 -1
  64. package/dist/executor/index.js +3 -3
  65. package/dist/executor/index.js.map +1 -1
  66. package/dist/maintenance/release-notes.json +1 -1
  67. package/dist/scheduling/ScheduleCapabilities.d.ts +2 -2
  68. package/dist/scheduling/ScheduleCapabilities.js +4 -4
  69. package/dist/scheduling/ScheduleCapabilities.js.map +1 -1
  70. package/dist/scheduling/SchedulePurgeVerification.js +1 -1
  71. package/dist/scheduling/SchedulePurgeVerification.js.map +1 -1
  72. package/dist/scheduling/ScheduleService.d.ts +10 -29
  73. package/dist/scheduling/ScheduleService.d.ts.map +1 -1
  74. package/dist/scheduling/ScheduleService.js +160 -627
  75. package/dist/scheduling/ScheduleService.js.map +1 -1
  76. package/dist/scheduling/agy/AgyHookOwnership.d.ts +13 -0
  77. package/dist/scheduling/agy/AgyHookOwnership.d.ts.map +1 -0
  78. package/dist/scheduling/agy/AgyHookOwnership.js +449 -0
  79. package/dist/scheduling/agy/AgyHookOwnership.js.map +1 -0
  80. package/dist/scheduling/agy/AgyHookRelay.d.ts +3 -4
  81. package/dist/scheduling/agy/AgyHookRelay.d.ts.map +1 -1
  82. package/dist/scheduling/agy/AgyHookRelay.js +14 -98
  83. package/dist/scheduling/agy/AgyHookRelay.js.map +1 -1
  84. package/dist/scheduling/agy/AgySessionSchedules.d.ts +5 -5
  85. package/dist/scheduling/agy/AgySessionSchedules.d.ts.map +1 -1
  86. package/dist/scheduling/agy/AgySessionSchedules.js +20 -17
  87. package/dist/scheduling/agy/AgySessionSchedules.js.map +1 -1
  88. package/dist/scheduling/claude/ClaudeScheduleOwnership.d.ts +2 -6
  89. package/dist/scheduling/claude/ClaudeScheduleOwnership.d.ts.map +1 -1
  90. package/dist/scheduling/claude/ClaudeScheduleOwnership.js +12 -67
  91. package/dist/scheduling/claude/ClaudeScheduleOwnership.js.map +1 -1
  92. package/dist/scheduling/claude/ClaudeSessionSchedules.d.ts +4 -26
  93. package/dist/scheduling/claude/ClaudeSessionSchedules.d.ts.map +1 -1
  94. package/dist/scheduling/claude/ClaudeSessionSchedules.js +22 -145
  95. package/dist/scheduling/claude/ClaudeSessionSchedules.js.map +1 -1
  96. package/dist/scheduling/dsh/ScheduledSessionGuard.d.ts +12 -0
  97. package/dist/scheduling/dsh/ScheduledSessionGuard.d.ts.map +1 -0
  98. package/dist/scheduling/dsh/ScheduledSessionGuard.js +96 -0
  99. package/dist/scheduling/dsh/ScheduledSessionGuard.js.map +1 -0
  100. package/dist/scheduling/dsh/SessionScheduleBridge.d.ts.map +1 -1
  101. package/dist/scheduling/dsh/SessionScheduleBridge.js +0 -25
  102. package/dist/scheduling/dsh/SessionScheduleBridge.js.map +1 -1
  103. package/dist/scheduling/dsh/SessionScheduleClient.d.ts.map +1 -1
  104. package/dist/scheduling/dsh/SessionScheduleClient.js +0 -8
  105. package/dist/scheduling/dsh/SessionScheduleClient.js.map +1 -1
  106. package/dist/scheduling/dsh/sessionLaunch.js +1 -1
  107. package/dist/scheduling/dsh/sessionLaunch.js.map +1 -1
  108. package/dist/scheduling/types.d.ts +26 -77
  109. package/dist/scheduling/types.d.ts.map +1 -1
  110. package/dist/scheduling/types.js +1 -10
  111. package/dist/scheduling/types.js.map +1 -1
  112. package/dist/service/ServiceManager.js +1 -1
  113. package/dist/thread/ThreadExecutorPool.d.ts +4 -1
  114. package/dist/thread/ThreadExecutorPool.d.ts.map +1 -1
  115. package/dist/thread/ThreadExecutorPool.js +6 -3
  116. package/dist/thread/ThreadExecutorPool.js.map +1 -1
  117. package/dist/thread/ThreadManager.d.ts.map +1 -1
  118. package/dist/thread/ThreadManager.js +23 -2
  119. package/dist/thread/ThreadManager.js.map +1 -1
  120. package/native/prebuilds/darwin-arm64/managed_native.node +0 -0
  121. package/native/prebuilds/darwin-arm64/manifest.json +1 -1
  122. package/native/prebuilds/darwin-x64/managed_native.node +0 -0
  123. package/native/prebuilds/darwin-x64/manifest.json +1 -1
  124. package/native/prebuilds/win32-arm64/managed_native.node +0 -0
  125. package/native/prebuilds/win32-arm64/manifest.json +1 -1
  126. package/native/prebuilds/win32-x64/managed_native.node +0 -0
  127. package/native/prebuilds/win32-x64/manifest.json +1 -1
  128. package/package.json +1 -1
  129. package/dist/executor/agy/AgyDelegationConfig.d.ts +0 -3
  130. package/dist/executor/agy/AgyDelegationConfig.d.ts.map +0 -1
  131. package/dist/executor/agy/AgyDelegationConfig.js +0 -105
  132. package/dist/executor/agy/AgyDelegationConfig.js.map +0 -1
  133. package/dist/scheduling/agy/AgyCheckpoint.d.ts +0 -35
  134. package/dist/scheduling/agy/AgyCheckpoint.d.ts.map +0 -1
  135. package/dist/scheduling/agy/AgyCheckpoint.js +0 -160
  136. package/dist/scheduling/agy/AgyCheckpoint.js.map +0 -1
@@ -34,28 +34,20 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.AgyExecutor = exports.parseAgyModels = void 0;
37
- const AgyCheckpoint_1 = require("../scheduling/agy/AgyCheckpoint");
38
37
  const AgyAcpRuntime_1 = require("./agy/AgyAcpRuntime");
39
- const ManagedSpawn_1 = require("./ManagedSpawn");
38
+ const AgySessionSelection_1 = require("./agy/AgySessionSelection");
39
+ const OwnershipRuntime_1 = require("../delegation/OwnershipRuntime");
40
40
  const child_process_1 = require("child_process");
41
- const ManagedProcessGroups_1 = require("./ManagedProcessGroups");
42
- const string_decoder_1 = require("string_decoder");
43
41
  const fs = __importStar(require("fs"));
44
42
  const os = __importStar(require("os"));
45
43
  const path = __importStar(require("path"));
46
44
  const ExecutionMetadata_1 = require("./ExecutionMetadata");
47
45
  const compactHandoff_1 = require("./compactHandoff");
48
46
  const stripAnsi_1 = require("../utils/stripAnsi");
49
- const WorkingDirectory_1 = require("../utils/WorkingDirectory");
50
- const AgyDelegationConfig_1 = require("./agy/AgyDelegationConfig");
51
47
  const contract_1 = require("../delegation/contract");
52
- const Activity_1 = require("./Activity");
53
48
  const AgyModels_1 = require("./agy/AgyModels");
54
49
  Object.defineProperty(exports, "parseAgyModels", { enumerable: true, get: function () { return AgyModels_1.parseAgyModels; } });
55
- /** Default inactivity timeout (ms) — a silent agy process fails the command. */
56
50
  const DEFAULT_INACTIVITY_TIMEOUT_MS = 10 * 60 * 1000;
57
- /** Default grace period (ms) before SIGTERM escalates to SIGKILL. */
58
- const DEFAULT_KILL_ESCALATION_MS = 3_000;
59
51
  const ACCOUNT_USAGE_TIMEOUT_MS = 15_000;
60
52
  const ACCOUNT_USAGE_MAX_BUFFER = 128 * 1024;
61
53
  const SUPPORTED_EFFORTS = ['low', 'medium', 'high'];
@@ -108,157 +100,74 @@ function mapAgyTool(toolName, parameters) {
108
100
  return { name: toolName, input: parameters };
109
101
  }
110
102
  }
111
- /** Result statuses that mean the turn was aborted rather than failed. */
112
- const ABORTED_STATUSES = new Set(['INTERRUPTED', 'CANCELED']);
113
- /**
114
- * IExecutor implementation for the Antigravity CLI (`agy`) — Google's
115
- * agentic CLI from the Antigravity suite.
116
- *
117
- * Fresh production conversations use AgyAcpRuntime for shared native scheduling.
118
- * Saved conversations and managed workers retain the compatible transport below.
119
- * The legacy path speaks a Claude-Code-style stream-json protocol: one persistent
120
- * process per conversation, NDJSON prompts in on stdin
121
- * ({"event":"user","message":{"content":"..."}}), NDJSON events out on
122
- * stdout (init / step_update / result). Conversations survive process
123
- * restarts via `--conversation <id>`, which we persist per thread.
124
- *
125
- * The process is respawned (resuming the conversation) when:
126
- * - the process exits unexpectedly
127
- * - abort() kills it mid-command
128
- * Directory changes and resetContext()/compactWhenFull() drop the conversation id,
129
- * so the next command starts a fresh session (agy has no /compact).
130
- *
131
- * Note: agy stream-json input supports text blocks only — image
132
- * attachments are silently dropped (with a log line).
133
- */
103
+ /** ACP is the sole conversation transport. Legacy metadata remains readable only
104
+ * for explicit selection reset and exact history cleanup. */
134
105
  class AgyExecutor {
135
106
  directoryGuard;
136
107
  currentWorkingDirectory;
137
- /** Model for the next spawn. Mutable: setModel() updates it in place. */
138
108
  model;
139
- /** Reasoning effort for the next spawn. Mutable: setEffort() updates it in place. */
140
109
  effort;
141
110
  autoApprove;
142
111
  agyCommand;
143
112
  threadId;
144
- proc = null;
145
- conversationId = null;
146
- sessionFilePath;
147
- /**
148
- * Per-thread HOME directory for the agy child process. agy stores every
149
- * conversation under $HOME/.gemini/antigravity-cli — one global store shared
150
- * by all threads. A per-thread HOME redirects agy's default data lookup,
151
- * but tools still run with the user's filesystem permissions and inherit
152
- * this HOME. Undefined on the legacy no-threadId path.
153
- */
154
113
  agyHome;
155
- commandQueue = [];
156
- isProcessing = false;
157
- isDestroyed = false;
158
- activeCommand = null;
159
- currentOutputBuffer = [];
160
- stdoutBuffer = '';
161
- decoder = new string_decoder_1.StringDecoder('utf8');
162
- inactivityTimer = null;
163
- inactivityTimeoutMs;
164
- killEscalationMs;
165
- attachmentWarningShown = false;
166
- /** Model or effort switch requested while a command was running — respawn when it finishes. */
167
- pendingSettingsChange = false;
168
- delegationConnection;
169
114
  delegationWorker;
170
- managedProcesses = new WeakSet();
171
- workerGroups = new ManagedProcessGroups_1.ManagedProcessGroups();
172
- delegationConfigured = false;
173
- configuringTools = false;
174
- pendingExits = new Set();
175
- /** A timeout is not exit evidence. Only an explicit joined retirement clears it. */
115
+ inactivityTimeoutMs;
116
+ sessionFilePath;
117
+ conversationId = null;
118
+ legacy = false;
119
+ acpLeaseUnconfirmed = false;
120
+ acp;
121
+ isDestroyed = false;
122
+ isProcessing = false;
123
+ transitioning = false;
176
124
  shutdownUncertain = false;
177
- /** Invalidates prompts waiting for a predecessor when abort/reset retires their context. */
178
- contextRevision = 0;
179
- /** Handoff summary from compactWhenFull, wrapped into the next prompt (consumed once). */
180
125
  pendingContextSeed = null;
181
- activityTracker = new Activity_1.ActivityTracker();
126
+ delegationConnection;
182
127
  nativeObserver;
183
128
  nativeCaptureFailure;
184
- nativeReceiptOperations = Promise.resolve();
185
- nativeReceiptPending = 0;
186
129
  nativeCaptureUnconfirmed = false;
187
- nativeCaptureFailed = false;
188
- nativeCreationScope;
189
- preexistingNativeIds = new Set();
190
- observedNativeIds = new Set();
191
- resettingNativeContext = false;
192
- acp;
193
- acpEligible = false;
194
- acpLeaseUnconfirmed = false;
195
- nativeAcp;
196
- resumePermit;
197
- restoringCheckpoint;
198
- cleanCheckpoint() {
199
- try {
200
- const value = this.checkpoint().read();
201
- return value?.state === 'clean' ? value : undefined;
130
+ workerProof;
131
+ scheduleOwner;
132
+ resumeCurrent = false;
133
+ allocationUnconfirmed = false;
134
+ constructor(directoryGuard, options = {}) {
135
+ this.directoryGuard = directoryGuard;
136
+ this.model = options.model;
137
+ this.effort = options.effort;
138
+ this.autoApprove = options.autoApprove ?? true;
139
+ this.agyCommand = options.agyCommand ?? 'agy';
140
+ this.threadId = options.threadId;
141
+ this.delegationWorker = options.delegationWorker ?? false;
142
+ this.inactivityTimeoutMs = options.inactivityTimeoutMs ?? DEFAULT_INACTIVITY_TIMEOUT_MS;
143
+ this.currentWorkingDirectory = options.initialWorkingDirectory ? directoryGuard.resolveWorkingDirectory(options.initialWorkingDirectory) : process.cwd();
144
+ if (this.threadId) {
145
+ const sessions = path.join(os.homedir(), '.remote-cli', 'agy-sessions');
146
+ fs.mkdirSync(sessions, { recursive: true });
147
+ this.sessionFilePath = path.join(sessions, `${this.threadId}.json`);
148
+ this.agyHome = path.join(os.homedir(), '.remote-cli', 'agy-homes', this.threadId);
202
149
  }
203
- catch {
204
- return;
205
- } // Incompatible proof never grants admission or breaks legacy chat.
206
- }
207
- resumeCleanChat() {
208
- if (this.acp || this.resumePermit || this.proc || this.acpLeaseUnconfirmed || this.scheduleOwner?.retired === false || !this.conversationId)
209
- return;
210
- const proof = this.cleanCheckpoint();
211
- if (proof?.sessionId === this.conversationId && Object.keys(proof.jobs).length === 0) {
212
- this.resumePermit = this.checkpoint().consume(this.conversationId);
213
- if (this.scheduleOwner) {
214
- fs.rmSync(this.sessionFilePath + '.native-schedules', { force: true });
215
- this.scheduleOwner = undefined;
216
- }
150
+ else
151
+ this.sessionFilePath = path.join(this.currentWorkingDirectory, '.agy-session');
152
+ this.allocationUnconfirmed = fs.existsSync(this.sessionFilePath + '.allocation-unconfirmed');
153
+ if (fs.existsSync(this.sessionFilePath)) {
154
+ const pointer = JSON.parse(fs.readFileSync(this.sessionFilePath, 'utf8'));
155
+ if (typeof pointer.id !== 'string' || !/^[a-zA-Z0-9_-]{1,128}$/.test(pointer.id))
156
+ throw new Error('Saved AGY identity is invalid; retained state was not changed.');
157
+ this.conversationId = pointer.id;
158
+ this.legacy = pointer.transport !== 'acp';
159
+ this.acpLeaseUnconfirmed = !this.legacy;
160
+ }
161
+ if (fs.existsSync(this.sessionFilePath + '.native-schedules')) {
162
+ const owner = JSON.parse(fs.readFileSync(this.sessionFilePath + '.native-schedules', 'utf8'));
163
+ if (!this.conversationId || typeof owner.sessionId !== 'string' || typeof owner.hostId !== 'string' || typeof owner.retired !== 'boolean')
164
+ throw new Error('AGY schedule ownership journal is unreadable; admission is blocked.');
165
+ this.scheduleOwner = owner;
166
+ }
167
+ if (this.delegationWorker && fs.existsSync(this.sessionFilePath + '.worker-policy')) {
168
+ this.workerProof = JSON.parse(fs.readFileSync(this.sessionFilePath + '.worker-policy', 'utf8'));
217
169
  }
218
170
  }
219
- recoveryIdentity() { return JSON.stringify({ sessionId: this.conversationId, configuration: this.checkpoint().configuration }); }
220
- checkpoint() {
221
- return new AgyCheckpoint_1.AgyCheckpoint(this.sessionFilePath + '.checkpoint', (0, AgyCheckpoint_1.definitionDigest)([this.threadId, this.currentWorkingDirectory, this.agyCommand, this.model ?? null, this.effort ?? null, this.autoApprove]));
222
- }
223
- get nativeScheduleRecovery() {
224
- if (!this.nativeAcp || !this.threadId || this.delegationWorker)
225
- return;
226
- return {
227
- provider: 'agy-before-first-wake-v1', strategy: 'reconstruct', orderlyOnly: true,
228
- describe: () => this.recoveryIdentity(),
229
- finishRestart: async () => {
230
- if (!this.acp?.checkpointClean)
231
- throw new Error('AGY exact deadline-bounded handoff is not clean.');
232
- await this.acp.close();
233
- this.acp = undefined;
234
- this.restoringCheckpoint = undefined;
235
- },
236
- reconcile: async (record, context, emit) => {
237
- const checkpoint = this.checkpoint();
238
- if (record.rule.kind === 'once' && Date.parse(record.rule.at) <= Date.now())
239
- throw new Error('Expired AGY one-shot will not be reconstructed.');
240
- if (record.recovery?.handoff !== 'clean' || record.recovery.identity !== this.recoveryIdentity()
241
- || !context.isCurrent() || context.signal.aborted || record.cancelRequested)
242
- throw new Error('AGY clean recovery ownership changed.');
243
- const input = { id: record.id, backend: record.backend, threadId: record.threadId, cwd: record.cwd,
244
- prompt: record.prompt, rule: record.rule, ...record.execution, recovery: record.recovery };
245
- const proof = this.restoringCheckpoint ?? checkpoint.read();
246
- if (!proof || proof.jobs[record.id] !== (0, AgyCheckpoint_1.scheduleDigest)(input))
247
- throw new Error('AGY definition has no exact handoff proof.');
248
- if (!this.restoringCheckpoint) {
249
- if (this.acp || this.proc || this.acpLeaseUnconfirmed || this.scheduleOwner?.retired === false)
250
- throw new Error('AGY predecessor retirement is not confirmed.');
251
- this.resumePermit = checkpoint.consume(this.conversationId);
252
- this.restoringCheckpoint = proof;
253
- this.acp = undefined;
254
- }
255
- // Consume per-job proof before mutation. A partial restore is not a retry permit.
256
- delete this.restoringCheckpoint.jobs[record.id];
257
- return this.createNativeSchedule(input, emit, () => context.isOwnerCurrent?.() ?? context.isCurrent(), context.canAdmitOccurrence);
258
- },
259
- };
260
- }
261
- scheduleOwner;
262
171
  writeNativeState(file, data) {
263
172
  const temporary = file + '.tmp';
264
173
  const fd = fs.openSync(temporary, 'w', 0o600);
@@ -270,137 +179,138 @@ class AgyExecutor {
270
179
  fs.closeSync(fd);
271
180
  }
272
181
  fs.renameSync(temporary, file);
182
+ (0, OwnershipRuntime_1.syncDirectory)(path.dirname(file));
183
+ }
184
+ saveWorkerProof() {
185
+ if (this.workerProof)
186
+ this.writeNativeState(this.sessionFilePath + '.worker-policy', this.workerProof);
273
187
  }
274
188
  assertNoRetainedSchedules() {
275
- if (this.acp?.hasJobs || this.scheduleOwner?.sessionId === this.conversationId) {
276
- throw new Error('AGY native notifications may remain queued. Reconfiguration/recovery of this conversation is unavailable; keep its schedule evidence and use a new thread.');
277
- }
189
+ if (this.acp?.hasJobs || this.scheduleOwner)
190
+ throw new Error('AGY native notifications remain owned and unconfirmed. Settings and transport changes are unavailable; inspect /schedule list.');
278
191
  }
279
- assertScheduleResettable() {
192
+ assertScheduleResettable(allowOwnedRetirement = false, detachSelection = false) {
193
+ if (this.allocationUnconfirmed || fs.existsSync(this.sessionFilePath + '.allocation-unconfirmed'))
194
+ throw new Error('AGY allocation ownership is unconfirmed; retain its evidence.');
280
195
  if (fs.existsSync(this.sessionFilePath + '.checkpoint.lock'))
281
196
  throw new Error('AGY checkpoint transition is unconfirmed; retained state cannot be discarded.');
282
- if (this.acpLeaseUnconfirmed && !this.acp)
283
- throw new Error('Previous AGY ACP host retirement is unconfirmed; retained session and hook evidence cannot be discarded.');
284
- if (this.scheduleOwner?.sessionId === this.conversationId && !this.scheduleOwner.retired) {
285
- throw new Error('AGY native notifications have unresolved ownership; confirm exact host retirement before explicitly discarding this context.');
286
- }
287
- }
288
- async stopForContextReset() {
289
- if (this.acp)
290
- await this.acp.close();
291
- else
292
- await this.abort();
293
- }
294
- acpRuntime() {
197
+ if (this.acpLeaseUnconfirmed && !this.acp && !detachSelection)
198
+ throw new Error('Saved AGY ACP host retirement is unconfirmed; keep the original history.');
199
+ if (this.scheduleOwner && this.scheduleOwner.sessionId !== this.conversationId)
200
+ throw new Error('AGY schedule owner does not match the original conversation.');
201
+ if (this.scheduleOwner && !this.scheduleOwner.retired && !(allowOwnedRetirement && this.acp?.canRetireForContextReset))
202
+ throw new Error('AGY native notifications have unresolved ownership; use a new thread.');
203
+ }
204
+ async runtime() {
295
205
  if (this.acp)
296
206
  return this.acp;
297
- this.resumeCleanChat();
298
- if (((!this.acpEligible || this.conversationId) && !this.resumePermit) || !this.agyHome || !this.threadId || this.proc || this.isDestroyed) {
299
- throw new Error('AGY scheduling requires a fresh ACP conversation. This saved/legacy conversation remains on its compatible transport; use a new AGY thread.');
207
+ if (this.allocationUnconfirmed)
208
+ throw new Error('AGY allocation reply was lost. Native ownership is unconfirmed; do not retry this worker or conversation automatically.');
209
+ if (this.isDestroyed || this.shutdownUncertain)
210
+ throw new Error('AGY executor is closed or its process exit is unconfirmed.');
211
+ if (!this.threadId || !this.agyHome)
212
+ throw new Error('AGY ACP requires a thread-scoped HOME. Select a thread before chatting.');
213
+ if (this.legacy)
214
+ throw new Error(this.delegationWorker
215
+ ? 'Legacy AGY worker history cannot execute over ACP. Use this worker card Clear action or parent /clear after task/artifact closeout; original history is retained.'
216
+ : 'Legacy AGY conversation cannot execute over ACP. Use explicit /clear to start fresh; original native history is retained.');
217
+ if (this.conversationId) {
218
+ if (this.scheduleOwner)
219
+ throw new Error('AGY saved chat cannot safely resume: native notifications remain unconfirmed. Use a new thread.');
220
+ const proof = this.workerProof;
221
+ if (!this.resumeCurrent && !(this.delegationWorker && proof?.sessionId === this.conversationId
222
+ && proof.policy === 'hook-denial-v2' && proof.settled && proof.closed)) {
223
+ throw new Error('Saved AGY ACP chat cannot safely resume: pending work is unconfirmed. Use explicit /clear when no schedule owner remains, or a new thread; original history is retained.');
224
+ }
300
225
  }
301
226
  const env = this.buildEnv();
302
- // Both native HOME conventions must point to this thread on every platform.
303
227
  env.HOME = this.agyHome;
304
228
  env.USERPROFILE = this.agyHome;
305
- this.acp = new AgyAcpRuntime_1.AgyAcpRuntime({ command: this.agyCommand, home: this.agyHome,
306
- cwd: this.currentWorkingDirectory, threadId: this.threadId, model: this.model, effort: this.effort,
307
- autoApprove: this.autoApprove, env, checkpoint: this.checkpoint(), resume: this.resumePermit, mcpServers: (0, contract_1.delegationSessionServers)(this.delegationConnection), mapTool: mapAgyTool,
308
- saveSession: id => {
309
- // Unlike legacy best-effort persistence, native scheduling cannot proceed
310
- // without an original-session pointer on disk.
311
- this.writeNativeState(this.sessionFilePath, { id, transport: 'acp', retired: false, savedAt: new Date().toISOString() });
229
+ let scope;
230
+ let preexisting = new Set();
231
+ if (this.nativeObserver && !this.conversationId) {
232
+ const root = path.join(this.agyHome, '.gemini', 'antigravity-cli');
233
+ if (fs.realpathSync(root) !== root)
234
+ throw new Error('AGY creation root is redirected.');
235
+ const stat = fs.lstatSync(root, { bigint: true });
236
+ scope = { path: root, dev: String(stat.dev), ino: String(stat.ino) };
237
+ const store = path.join(root, 'conversations');
238
+ if (fs.existsSync(store) && fs.realpathSync(store) !== store)
239
+ throw new Error('AGY history is redirected.');
240
+ const names = fs.existsSync(store) ? fs.readdirSync(store) : [];
241
+ if (names.length > 4096)
242
+ throw new Error('AGY history inventory is too large.');
243
+ preexisting = new Set(names.map(name => name.replace(/\.db(?:-wal|-shm|-journal)?$/, '')));
244
+ }
245
+ const original = this.conversationId;
246
+ // A controlled reconnect is single-use; a failed load cannot authorize retries.
247
+ this.resumeCurrent = false;
248
+ if (this.workerProof) {
249
+ this.workerProof.closed = false;
250
+ this.saveWorkerProof();
251
+ }
252
+ this.acp = new AgyAcpRuntime_1.AgyAcpRuntime({ command: this.agyCommand, home: this.agyHome, cwd: this.currentWorkingDirectory,
253
+ threadId: this.threadId, env, model: this.model, effort: this.effort, autoApprove: this.autoApprove,
254
+ sessionId: original ?? undefined, worker: this.delegationWorker,
255
+ mcpServers: (0, contract_1.delegationSessionServers)(this.delegationConnection), mapTool: mapAgyTool,
256
+ beforeAllocation: () => this.writeNativeState(this.sessionFilePath + '.allocation-unconfirmed', { kind: 'agy-acp-allocation' }),
257
+ saveSession: async (id) => {
258
+ if (original) {
259
+ if (id !== original)
260
+ throw new Error('AGY loaded identity changed.');
261
+ return;
262
+ }
312
263
  this.conversationId = id;
313
264
  this.acpLeaseUnconfirmed = true;
265
+ this.writeNativeState(this.sessionFilePath, { id, transport: 'acp', retired: false, savedAt: new Date().toISOString() });
266
+ fs.rmSync(this.sessionFilePath + '.allocation-unconfirmed', { force: true });
267
+ if (this.delegationWorker) {
268
+ this.workerProof = { sessionId: id, policy: 'hook-denial-v2', settled: true, closed: false };
269
+ this.saveWorkerProof();
270
+ }
271
+ if (this.nativeObserver) {
272
+ try {
273
+ if (!scope || preexisting.has(id))
274
+ throw new Error('AGY allocation is not a fresh owned identity.');
275
+ const { captureAgyDeletionTarget } = await Promise.resolve().then(() => __importStar(require('../delegation/AgySessionDeletion')));
276
+ const target = await captureAgyDeletionTarget({ sessionId: id, executorThreadId: this.threadId, home: os.homedir(), cwd: this.currentWorkingDirectory, command: this.agyCommand });
277
+ if (target.scope.dev !== scope.dev || target.scope.ino !== scope.ino)
278
+ throw new Error('AGY creation root changed.');
279
+ await this.nativeObserver(target);
280
+ }
281
+ catch {
282
+ this.nativeCaptureUnconfirmed = true;
283
+ if (this.workerProof) {
284
+ this.workerProof.settled = false;
285
+ this.saveWorkerProof();
286
+ }
287
+ await this.nativeCaptureFailure?.();
288
+ throw new Error('AGY creation receipt could not be persisted. No prompt was sent.');
289
+ }
290
+ }
314
291
  },
315
- retireSession: id => {
316
- this.writeNativeState(this.sessionFilePath, { id, transport: 'acp', retired: true, savedAt: new Date().toISOString() });
317
- this.acpLeaseUnconfirmed = false;
292
+ beforePrompt: () => { if (this.workerProof) {
293
+ this.workerProof.settled = false;
294
+ this.saveWorkerProof();
295
+ } },
296
+ settledPrompt: reusable => { if (this.workerProof) {
297
+ this.workerProof.settled = reusable;
298
+ this.saveWorkerProof();
299
+ } },
300
+ ownedSessionClosed: id => {
301
+ if (id === this.conversationId)
302
+ this.acpLeaseUnconfirmed = false;
303
+ if (this.workerProof?.sessionId === id) {
304
+ this.workerProof.closed = true;
305
+ this.saveWorkerProof();
306
+ }
318
307
  },
319
308
  retainScheduleOwner: (sessionId, hostId, retired) => {
320
- const owner = { sessionId, hostId, retired };
321
- const file = this.sessionFilePath + '.native-schedules';
322
- this.writeNativeState(file, owner);
323
- this.scheduleOwner = owner;
324
- },
325
- });
326
- this.resumePermit = undefined;
309
+ this.scheduleOwner = { sessionId, hostId, retired };
310
+ this.writeNativeState(this.sessionFilePath + '.native-schedules', this.scheduleOwner);
311
+ }, });
327
312
  return this.acp;
328
313
  }
329
- async withNativeScheduleOperation(id, current, run, inTurn) {
330
- if (this.configuringTools || this.resettingNativeContext || this.shutdownUncertain)
331
- throw new Error('AGY context transition is pending.');
332
- return this.acpRuntime().withOperation(id, current, run, inTurn);
333
- }
334
- nativeScheduleAction(id) { return this.acp?.action(id); }
335
- async createNativeSchedule(input, emit, current = () => true, admit = () => true) {
336
- if (input.cwd !== this.currentWorkingDirectory || input.threadId !== this.threadId || input.model !== this.model || input.effort !== this.effort) {
337
- throw new Error('AGY schedule configuration does not match the original session.');
338
- }
339
- const runtime = this.acpRuntime();
340
- await runtime.start();
341
- if (input.recovery)
342
- input = { ...input, recovery: { ...input.recovery, identity: this.recoveryIdentity() } };
343
- return runtime.create(input, emit, () => !this.isDestroyed && current() && admit());
344
- }
345
- preservesProcessOnAbort() { return !!this.acp; }
346
- hasPendingCancellation() { return !!this.acp?.hasJobs && !!this.acp.blocked; }
347
- hasPendingScheduleMutation() { return this.acp?.pendingMutation ?? false; }
348
- constructor(directoryGuard, options = {}) {
349
- this.directoryGuard = directoryGuard;
350
- this.nativeAcp = options.nativeAcp === true && !options.delegationWorker && options.autoApprove !== false;
351
- this.model = options.model;
352
- this.effort = options.effort;
353
- this.autoApprove = options.autoApprove ?? true;
354
- this.agyCommand = options.agyCommand ?? 'agy';
355
- this.threadId = options.threadId;
356
- this.delegationWorker = options.delegationWorker ?? false;
357
- this.inactivityTimeoutMs = options.inactivityTimeoutMs ?? DEFAULT_INACTIVITY_TIMEOUT_MS;
358
- this.killEscalationMs = options.killEscalationMs ?? DEFAULT_KILL_ESCALATION_MS;
359
- if (options.initialWorkingDirectory) {
360
- try {
361
- this.currentWorkingDirectory = this.directoryGuard.resolveWorkingDirectory(options.initialWorkingDirectory);
362
- }
363
- catch (error) {
364
- console.warn(`[AgyExecutor] Failed to use initial working directory: ${options.initialWorkingDirectory}`, error);
365
- this.currentWorkingDirectory = process.cwd();
366
- }
367
- }
368
- else {
369
- this.currentWorkingDirectory = process.cwd();
370
- }
371
- if (this.threadId) {
372
- const sessionsDir = path.join(os.homedir(), '.remote-cli', 'agy-sessions');
373
- fs.mkdirSync(sessionsDir, { recursive: true });
374
- this.sessionFilePath = path.join(sessionsDir, `${this.threadId}.json`);
375
- this.agyHome = path.join(os.homedir(), '.remote-cli', 'agy-homes', this.threadId);
376
- }
377
- else {
378
- // Legacy: session file in working directory, shared HOME for agy
379
- this.sessionFilePath = path.join(this.currentWorkingDirectory, '.agy-session');
380
- }
381
- this.loadConversationId();
382
- this.acpEligible = this.nativeAcp && !!this.threadId && !this.conversationId;
383
- try {
384
- if (!fs.existsSync(this.sessionFilePath + '.native-schedules'))
385
- return;
386
- const owner = JSON.parse(fs.readFileSync(this.sessionFilePath + '.native-schedules', 'utf8'));
387
- if (typeof owner.sessionId !== 'string' || typeof owner.hostId !== 'string' || typeof owner.retired !== 'boolean')
388
- throw new Error('Invalid AGY schedule owner.');
389
- if (!this.conversationId)
390
- throw new Error('Missing original AGY schedule conversation pointer.');
391
- this.scheduleOwner = owner;
392
- }
393
- catch (error) {
394
- if (error.code !== 'ENOENT')
395
- throw new Error('AGY schedule ownership journal is unreadable; admission is blocked.');
396
- }
397
- }
398
- // ─── Per-thread HOME isolation ────────────────────────────────────────────
399
- /**
400
- * Environment for the agy child process. With a threadId, HOME points at the
401
- * per-thread directory (set up lazily here). A setup failure prevents the
402
- * process from starting so it cannot use the shared conversation store.
403
- */
404
314
  buildEnv() {
405
315
  const delegationEnv = this.delegationConnection ? (0, contract_1.delegationEnvironment)(this.delegationConnection)
406
316
  : this.delegationWorker ? { REMOTE_CLI_DELEGATION_URL: undefined, REMOTE_CLI_DELEGATION_TOKEN: undefined } : {};
@@ -421,8 +331,21 @@ class AgyExecutor {
421
331
  fs.mkdirSync(threadGemini, { recursive: true });
422
332
  for (const name of AGY_HOME_SHARED_FILES)
423
333
  this.linkShared(realGemini, threadGemini, name, 'file');
424
- for (const name of AGY_HOME_SHARED_DIRS)
334
+ for (const name of AGY_HOME_SHARED_DIRS) {
335
+ if (name === 'config') {
336
+ // An interrupted overlay transaction may temporarily have no config
337
+ // directory. Only its kernel-gated restoration may replace that entry.
338
+ try {
339
+ fs.lstatSync(path.join(this.agyHome, '.remote-cli-agy-hooks.owner.json'));
340
+ continue;
341
+ }
342
+ catch (error) {
343
+ if (error.code !== 'ENOENT')
344
+ throw error;
345
+ }
346
+ }
425
347
  this.linkShared(realGemini, threadGemini, name, 'dir');
348
+ }
426
349
  const realCli = path.join(realGemini, 'antigravity-cli');
427
350
  const threadCli = path.join(threadGemini, 'antigravity-cli');
428
351
  fs.mkdirSync(threadCli, { recursive: true });
@@ -465,341 +388,255 @@ class AgyExecutor {
465
388
  }
466
389
  fs.symlinkSync(master, link, type);
467
390
  }
468
- // ─── IExecutor required ───────────────────────────────────────────────────
391
+ getCurrentWorkingDirectory() { return this.currentWorkingDirectory; }
392
+ getSessionId() { return this.conversationId; }
393
+ getExecutionMetadata() { return (0, ExecutionMetadata_1.configuredExecutionMetadata)(this.model, this.effort); }
394
+ isProcessRunning() { return !!this.acp?.running; }
395
+ isBusy() { return this.isProcessing || this.transitioning || this.shutdownUncertain || !!this.acp?.busy; }
396
+ hasUncertainShutdown() { return this.shutdownUncertain; }
397
+ isWaitingInput() { return this.acp?.isWaitingInput() ?? false; }
398
+ sendInput(input) { return this.acp?.sendInput(input) ?? false; }
399
+ respondToApproval(id, action) { return this.acp?.respondToApproval(id, action) ?? false; }
400
+ preservesProcessOnAbort() { return true; }
401
+ hasPendingCancellation() { return !!this.acp?.hasJobs && !!this.acp.blocked; }
402
+ hasPendingScheduleMutation() { return this.acp?.cleanupMutationPending ?? false; }
403
+ // Shared destructive-settings recovery is not an AGY capability. Busy
404
+ // transitions are already enforced by isBusy/resetContext and must not bypass
405
+ // the caller's schedule-idle guard.
406
+ hasPendingSettingsChange() { return false; }
469
407
  async execute(prompt, options = {}) {
470
- if (this.isDestroyed) {
471
- return Promise.reject(new Error('Executor has been destroyed'));
408
+ if (this.isBusy() || this.isDestroyed)
409
+ throw new Error('AGY executor is busy or destroyed.');
410
+ this.isProcessing = true;
411
+ try {
412
+ const runtime = await this.runtime();
413
+ try {
414
+ await runtime.start();
415
+ }
416
+ catch (error) {
417
+ if (runtime.allocationUnconfirmed) {
418
+ this.allocationUnconfirmed = true;
419
+ this.nativeCaptureUnconfirmed = true;
420
+ await this.nativeCaptureFailure?.();
421
+ }
422
+ if (!runtime.running)
423
+ this.acp = undefined;
424
+ throw error;
425
+ }
426
+ if (this.pendingContextSeed) {
427
+ const seed = this.pendingContextSeed;
428
+ this.pendingContextSeed = null;
429
+ const resolve = options.resolvePrompt;
430
+ options = { ...options, resolvePrompt: id => (0, compactHandoff_1.seedPromptWithHandoff)(seed, resolve?.(id) ?? prompt) };
431
+ }
432
+ return await runtime.execute(prompt, { ...options, inactivityTimeout: options.inactivityTimeout ?? this.inactivityTimeoutMs });
433
+ }
434
+ finally {
435
+ this.isProcessing = false;
472
436
  }
473
- return new Promise((resolve, reject) => {
474
- this.commandQueue.push({ prompt, options, resolve, reject });
475
- void this.processQueue();
476
- });
477
- }
478
- getCurrentWorkingDirectory() {
479
- return this.currentWorkingDirectory;
480
437
  }
481
- async configureManagedTools(connection) {
438
+ async configureManagedTools(connection) { await this.configureDelegation(connection); }
439
+ async configureDelegation(connection) {
482
440
  if (this.delegationWorker && connection)
483
441
  throw new Error('Managed child workers cannot register control tools.');
484
- await this.configureDelegation(connection);
485
- }
486
- async configureDelegation(connection) {
487
- if (this.configuringTools)
488
- throw new Error('AGY managed-tool configuration is already in progress');
489
- if (this.delegationConfigured && (0, contract_1.sameConnection)(this.delegationConnection, connection))
490
- return;
491
- if (this.isProcessing || this.resettingNativeContext)
492
- throw new Error('Cannot change delegation during an active turn or context reset');
493
- if (!this.agyHome) {
494
- if (connection)
495
- throw new Error('AGY delegation requires a thread-scoped HOME');
442
+ if ((0, contract_1.sameConnection)(this.delegationConnection, connection))
496
443
  return;
497
- }
498
- if (!this.cleanCheckpoint())
499
- this.assertNoRetainedSchedules();
500
- this.configuringTools = true;
444
+ if (this.isBusy())
445
+ throw new Error('AGY work or native notifications are busy.');
446
+ this.assertNoRetainedSchedules();
447
+ this.transitioning = true;
501
448
  try {
502
449
  if (this.acp) {
450
+ if (!this.acp.reusable)
451
+ throw new Error('AGY chat outcome is unconfirmed; reconnect was refused.');
503
452
  await this.acp.close();
504
453
  this.acp = undefined;
505
- this.acpEligible = false;
454
+ this.resumeCurrent = true;
506
455
  }
507
- this.killProcess();
508
- await this.waitForExit();
509
- if (this.isDestroyed)
510
- throw new Error('Executor has been destroyed');
511
- this.ensureThreadHome();
512
- await (0, AgyDelegationConfig_1.configureAgyDelegation)(this.agyCommand, this.agyHome, !!connection);
513
456
  this.delegationConnection = connection;
514
- this.delegationConfigured = true;
515
457
  }
516
458
  finally {
517
- this.configuringTools = false;
459
+ this.transitioning = false;
518
460
  }
519
461
  }
520
- async getAccountUsage() {
521
- let env;
522
- try {
523
- env = this.buildEnv();
524
- }
525
- catch (error) {
526
- console.warn('[AgyExecutor] Account usage environment is unavailable:', error);
527
- return null;
528
- }
529
- const [usage, credits] = await Promise.all([
530
- this.runInformationalCommand('/usage', env),
531
- this.runInformationalCommand('/credits', env),
532
- ]);
533
- const sections = [
534
- usage ? `Model quota:\n${usage}` : null,
535
- credits ? `Credits:\n${credits}` : null,
536
- ].filter((section) => section !== null);
537
- return sections.length > 0 ? sections.join('\n\n') : null;
538
- }
539
- runInformationalCommand(command, env) {
540
- return new Promise((resolve) => {
541
- (0, child_process_1.execFile)(this.agyCommand, ['-p', command], {
542
- cwd: this.currentWorkingDirectory,
543
- env,
544
- encoding: 'utf8',
545
- timeout: ACCOUNT_USAGE_TIMEOUT_MS,
546
- maxBuffer: ACCOUNT_USAGE_MAX_BUFFER,
547
- }, (error, stdout) => {
548
- if (error) {
549
- console.warn(`[AgyExecutor] ${command} is unavailable: ${error.message}`);
550
- resolve(null);
551
- return;
552
- }
553
- resolve((0, stripAnsi_1.stripAnsi)(stdout).trim() || null);
554
- });
555
- });
556
- }
557
- isBusy() {
558
- return !!this.acp?.busy || this.isProcessing || this.activeCommand !== null || this.commandQueue.length > 0
559
- || this.resettingNativeContext || this.configuringTools || this.shutdownUncertain || !this.proc && this.pendingExits.size > 0;
560
- }
561
- hasUncertainShutdown() {
562
- return this.shutdownUncertain;
563
- }
564
- async setWorkingDirectory(targetPath) {
565
- const resolved = this.directoryGuard.resolveWorkingDirectory(targetPath, this.currentWorkingDirectory);
462
+ async setWorkingDirectory(target) {
463
+ const resolved = this.directoryGuard.resolveWorkingDirectory(target, this.currentWorkingDirectory);
566
464
  if (resolved === this.currentWorkingDirectory)
567
465
  return;
568
- if (this.isBusy())
569
- throw new Error('Cannot change working directory while AGY is busy');
570
466
  await this.resetContext();
571
467
  this.currentWorkingDirectory = resolved;
572
468
  }
573
469
  async resetContext() {
574
- if (this.resettingNativeContext || this.configuringTools)
575
- throw new Error('AGY context reset or managed-tool configuration is already in progress');
576
- this.assertScheduleResettable();
577
- this.resettingNativeContext = true;
578
- this.contextRevision++;
470
+ if (this.allocationUnconfirmed)
471
+ throw new Error('AGY allocation ownership is unconfirmed; use a new thread and retain this evidence.');
472
+ if (this.isBusy())
473
+ throw new Error('Cannot clear AGY while work, native notifications or process retirement is pending.');
474
+ const detach = !this.acp && !!this.conversationId && !this.scheduleOwner;
475
+ this.assertScheduleResettable(true, detach);
476
+ this.transitioning = true;
579
477
  try {
580
478
  if (this.acp) {
581
479
  await this.acp.close();
480
+ this.assertScheduleResettable();
582
481
  this.acp = undefined;
583
482
  }
584
- this.killProcess();
585
- await this.waitForExit();
586
- // Keep the old pointer until admitted observations finish. The caller must await reset.
587
- if (this.nativeObserver)
588
- await this.nativeReceiptOperations;
589
- this.shutdownUncertain = false;
590
- // /clear means a real fresh start. Do not erase resume evidence before exit.
591
- this.pendingContextSeed = null;
592
- this.clearConversationId();
483
+ if (this.acpLeaseUnconfirmed && !this.legacy) {
484
+ if (!(0, AgySessionSelection_1.detachAgySelection)(this.sessionFilePath))
485
+ throw new Error('AGY selection changed; clear was refused.');
486
+ }
487
+ else
488
+ fs.rmSync(this.sessionFilePath, { force: true });
489
+ this.conversationId = null;
490
+ this.legacy = false;
593
491
  this.acpLeaseUnconfirmed = false;
594
- this.resumePermit = undefined;
595
- this.restoringCheckpoint = undefined;
596
- fs.rmSync(this.sessionFilePath + '.checkpoint', { force: true });
492
+ this.resumeCurrent = false;
493
+ this.pendingContextSeed = null;
494
+ this.workerProof = undefined;
495
+ fs.rmSync(this.sessionFilePath + '.worker-policy', { force: true });
597
496
  if (this.scheduleOwner?.retired) {
598
497
  fs.rmSync(this.sessionFilePath + '.native-schedules', { force: true });
599
498
  this.scheduleOwner = undefined;
600
499
  }
601
- this.acpEligible = this.nativeAcp && !!this.threadId;
602
500
  }
603
501
  finally {
604
- this.resettingNativeContext = false;
605
- }
606
- }
607
- async abort() {
608
- if (this.acp) {
609
- const runtime = this.acp;
610
- const cancelled = await runtime.abort();
611
- // No managed native definitions/notifications have ever been admitted:
612
- // ordinary abort may retire the host and resume the SAME saved conversation
613
- // on its compatible transport. Scheduled sessions remain visibly fenced.
614
- if (!runtime.hasJobs && (cancelled || runtime.blocked)) {
615
- await runtime.close();
616
- this.acp = undefined;
617
- this.acpEligible = false;
618
- }
619
- return cancelled;
502
+ this.transitioning = false;
620
503
  }
621
- const retiring = this.pendingExits.size > 0 && !this.proc;
622
- if (!this.activeCommand && !this.isProcessing && !retiring && !this.shutdownUncertain)
623
- return false;
624
- // agy's stream-json protocol has no cancel request (control_request is
625
- // explicitly unsupported), so abort = kill the process. The conversation
626
- // id survives, so the next command resumes context.
627
- console.log('[AgyExecutor] Aborting: killing agy process');
628
- this.contextRevision++;
629
- this.killProcess('Aborted by user');
630
- await this.waitForExit();
631
- this.shutdownUncertain = false;
632
- return true;
633
504
  }
505
+ async stopForContextReset() { if (this.acp)
506
+ await this.acp.close(); }
507
+ async abort() { return await this.acp?.abort() ?? false; }
634
508
  abortStatusMessage() {
635
- if (this.acp?.continuationSucceeded)
636
- return 'AGY foreground cancelled; eligible future schedules resumed automatically in the same conversation after deadline-bounded predecessor retirement.';
637
- if (this.acp?.hasJobs && this.acp.blocked)
638
- return 'AGY foreground cancelled; native timers may still queue reminders. Dispatch is blocked. Original schedule ownership and recovery evidence are retained; use /schedule list. Uncertain work will not be replayed.';
639
- if (this.acp?.hasJobs)
640
- return 'No foreground command was cancelled. Native schedules remain on their current host.';
641
- return 'AGY stream-json abort stops its host. Conversation context can resume after confirmed exit; native session-only timers are not restored.';
509
+ return this.acp?.hasJobs ? 'AGY foreground interrupted; native timers may still queue reminders and dispatch is blocked. Inspect /schedule list. No work is replayed.'
510
+ : 'AGY foreground cancelled. Completed tool side effects remain; unconfirmed outcomes stay blocked.';
642
511
  }
643
512
  async destroy() {
644
- if (this.isDestroyed) {
645
- if (this.acp)
646
- await this.acp.close();
647
- await this.waitForExit();
648
- return;
649
- }
650
513
  this.isDestroyed = true;
651
- this.contextRevision++;
652
- if (this.acp)
653
- await this.acp.close();
654
- // Reject everything still queued — nothing may respawn after destroy
655
- const queued = this.commandQueue.splice(0);
656
- for (const command of queued) {
657
- command.reject(new Error('Executor has been destroyed'));
658
- }
659
- const proc = this.proc;
660
- if (proc) {
661
- try {
662
- proc.stdin?.end();
663
- }
664
- catch { /* already closed */ }
514
+ try {
515
+ await this.acp?.close();
516
+ this.shutdownUncertain = false;
665
517
  }
666
- this.killProcess('Executor destroyed');
667
- await this.waitForExit();
668
- if (this.nativeObserver)
669
- await this.nativeReceiptOperations;
670
- if (this.agyHome && this.delegationConnection) {
671
- await (0, AgyDelegationConfig_1.configureAgyDelegation)(this.agyCommand, this.agyHome, false);
672
- this.delegationConnection = undefined;
518
+ catch (error) {
519
+ this.shutdownUncertain = true;
520
+ throw error;
673
521
  }
674
522
  }
675
- // ─── IExecutor optional ───────────────────────────────────────────────────
676
- /** Coordinator bridges this typed hook into the shared native-target union. */
523
+ async waitForExit() { if (this.isDestroyed)
524
+ await this.destroy(); }
525
+ async waitForManagedProcessGroupExit() {
526
+ if (!this.delegationWorker || this.nativeCaptureUnconfirmed)
527
+ throw new Error('AGY worker creation or ownership remains unconfirmed.');
528
+ await this.acp?.waitForManagedProcessGroupExit();
529
+ }
677
530
  observeNativeSessionCreation(observer, onFailure) {
678
- if (!this.delegationWorker || !this.threadId?.startsWith('delegate-lane-') || this.proc) {
679
- throw new Error('AGY native observation requires an unstarted managed worker');
680
- }
531
+ if (!this.delegationWorker || !this.threadId?.startsWith('delegate-lane-') || this.acp)
532
+ throw new Error('AGY native observation requires an unstarted managed worker.');
681
533
  this.nativeObserver = observer;
682
534
  this.nativeCaptureFailure = onFailure;
683
535
  }
684
- async waitForExit() {
685
- if (!this.pendingExits.size)
686
- return;
687
- let timer;
536
+ async settings(change) {
537
+ this.assertNoRetainedSchedules();
538
+ if (this.isBusy() || this.isDestroyed)
539
+ throw new Error('AGY is busy or destroyed.');
540
+ this.transitioning = true;
541
+ let runtime;
688
542
  try {
689
- await Promise.race([Promise.all(this.pendingExits), new Promise((_, reject) => {
690
- timer = setTimeout(() => reject(new Error('AGY process exit could not be confirmed')), this.killEscalationMs + 5_000);
691
- })]);
543
+ runtime = await this.runtime();
544
+ await runtime.changeSettings(change);
692
545
  }
693
546
  catch (error) {
694
- this.shutdownUncertain = true;
547
+ if (runtime?.allocationUnconfirmed) {
548
+ this.allocationUnconfirmed = true;
549
+ this.nativeCaptureUnconfirmed = true;
550
+ await this.nativeCaptureFailure?.();
551
+ }
552
+ if (runtime && !runtime.running)
553
+ this.acp = undefined;
695
554
  throw error;
696
555
  }
697
556
  finally {
698
- if (timer)
699
- clearTimeout(timer);
557
+ this.transitioning = false;
700
558
  }
701
559
  }
702
- async waitForManagedProcessGroupExit() {
703
- if (!this.delegationWorker)
704
- throw new Error('Managed worker process-group tracking was not enabled');
705
- if (this.nativeReceiptPending || this.nativeCaptureUnconfirmed)
706
- throw new Error('AGY native creation coverage could not be persisted');
707
- await this.workerGroups.waitForExit();
560
+ async setModel(model) {
561
+ await this.settings({ model });
562
+ this.model = model;
563
+ return { success: true, output: `AGY model confirmed: ${model}.` };
708
564
  }
709
- isProcessRunning() {
710
- return !!this.acp?.running || this.proc !== null;
565
+ /** AGY-specific control; no shared backend mode semantics are changed. */
566
+ async setMode(mode) {
567
+ await this.settings({ mode });
568
+ return { success: true, output: `AGY mode confirmed: ${mode}.` };
711
569
  }
712
- getSessionId() {
713
- return this.conversationId;
570
+ async clearModel() { await this.settings({ resetModel: true }); this.model = undefined; }
571
+ async setEffort(effort) {
572
+ const value = effort.trim().toLowerCase();
573
+ if (value !== 'auto' && !SUPPORTED_EFFORTS.includes(value))
574
+ return { success: false, error: 'Supported AGY efforts: auto, low, medium, high.' };
575
+ await this.settings(value === 'auto' ? { resetEffort: true } : { effort: value });
576
+ this.effort = value === 'auto' ? undefined : value;
577
+ return { success: true, output: `AGY effort confirmed: ${value}.` };
714
578
  }
715
- getExecutionMetadata() {
716
- return (0, ExecutionMetadata_1.configuredExecutionMetadata)(this.model, this.effort);
579
+ async withNativeScheduleOperation(id, current, run, inTurn) {
580
+ if (this.transitioning || this.shutdownUncertain)
581
+ throw new Error('AGY context transition is pending.');
582
+ return (await this.runtime()).withOperation(id, current, run, inTurn);
717
583
  }
718
- /**
719
- * Switch the model. agy takes --model at process start, so the process must
720
- * respawn for the change to take effect — the conversation id survives, so
721
- * context is preserved. If a command is in flight, the respawn is deferred
722
- * until it finishes (the running turn keeps the old model).
723
- * MessageHandler persists the choice on the thread; ThreadExecutorPool
724
- * passes it back via the factory on restarts.
725
- */
726
- async setModel(model, _onStream) {
727
- this.assertNoRetainedSchedules();
728
- if (this.acp) {
729
- if (this.acp.busy)
730
- throw new Error('AGY is busy.');
731
- await this.acp.close();
732
- this.acp = undefined;
733
- this.acpEligible = false;
734
- }
735
- this.model = model;
736
- if (this.proc && !this.activeCommand) {
737
- console.log(`[AgyExecutor] Model set to ${model} — recycling idle process (conversation preserved)`);
738
- this.killProcess();
739
- }
740
- else if (this.proc) {
741
- console.log(`[AgyExecutor] Model set to ${model} — will respawn after the current command`);
742
- this.pendingSettingsChange = true;
584
+ nativeScheduleAction(id) { return this.acp?.action(id); }
585
+ async createNativeSchedule(input, emit, current = () => true, admit = () => true) {
586
+ if (this.transitioning || this.isDestroyed || this.shutdownUncertain)
587
+ throw new Error('AGY context transition is pending.');
588
+ if (this.delegationWorker)
589
+ throw new Error('Managed workers cannot create native schedules.');
590
+ if (input.cwd !== this.currentWorkingDirectory || input.threadId !== this.threadId || input.model !== this.model || input.effort !== this.effort)
591
+ throw new Error('AGY schedule configuration does not match the original session.');
592
+ const runtime = await this.runtime();
593
+ try {
594
+ return await runtime.create(input, emit, () => !this.isDestroyed && current() && admit());
743
595
  }
744
- else {
745
- console.log(`[AgyExecutor] Model set to ${model} (applies from the next command)`);
596
+ catch (error) {
597
+ if (runtime.allocationUnconfirmed)
598
+ this.allocationUnconfirmed = true;
599
+ if (!runtime.running)
600
+ this.acp = undefined;
601
+ throw error;
746
602
  }
747
- return {
748
- success: true,
749
- output: `Model set to ${model}. Takes effect on the next command (the agy process restarts; conversation context is preserved).`,
750
- };
751
603
  }
752
- async setEffort(effort) {
753
- const normalized = effort.trim().toLowerCase();
754
- if (normalized !== 'auto' && !SUPPORTED_EFFORTS.includes(normalized)) {
755
- return {
756
- success: false,
757
- error: `Unsupported AGY reasoning effort: ${effort}. Supported values: auto, ${SUPPORTED_EFFORTS.join(', ')}.`,
758
- };
759
- }
760
- this.assertNoRetainedSchedules();
761
- if (this.acp) {
762
- if (this.acp.busy)
763
- throw new Error('AGY is busy.');
764
- await this.acp.close();
765
- this.acp = undefined;
766
- this.acpEligible = false;
767
- }
768
- this.effort = normalized === 'auto' ? undefined : normalized;
769
- if (this.proc && !this.activeCommand) {
770
- console.log(`[AgyExecutor] Reasoning effort set to ${normalized} — recycling idle process (conversation preserved)`);
771
- this.killProcess();
772
- }
773
- else if (this.proc) {
774
- console.log(`[AgyExecutor] Reasoning effort set to ${normalized} — will respawn after the current command`);
775
- this.pendingSettingsChange = true;
604
+ async getAccountUsage() {
605
+ let env;
606
+ try {
607
+ env = this.buildEnv();
776
608
  }
777
- else {
778
- console.log(`[AgyExecutor] Reasoning effort set to ${normalized} (applies from the next command)`);
609
+ catch (error) {
610
+ console.warn('[AgyExecutor] Account usage environment is unavailable:', error);
611
+ return null;
779
612
  }
780
- return {
781
- success: true,
782
- output: normalized === 'auto'
783
- ? 'Reasoning effort restored to the AGY default. Takes effect on the next command.'
784
- : `Reasoning effort set to ${normalized}. Takes effect on the next command.`,
785
- };
613
+ const [usage, credits] = await Promise.all([
614
+ this.runInformationalCommand('/usage', env),
615
+ this.runInformationalCommand('/credits', env),
616
+ ]);
617
+ const sections = [
618
+ usage ? `Model quota:\n${usage}` : null,
619
+ credits ? `Credits:\n${credits}` : null,
620
+ ].filter((section) => section !== null);
621
+ return sections.length > 0 ? sections.join('\n\n') : null;
786
622
  }
787
- async clearModel() {
788
- this.assertNoRetainedSchedules();
789
- if (this.acp) {
790
- if (this.acp.busy)
791
- throw new Error('AGY is busy.');
792
- await this.acp.close();
793
- this.acp = undefined;
794
- this.acpEligible = false;
795
- }
796
- this.model = undefined;
797
- if (this.proc && !this.activeCommand) {
798
- this.killProcess();
799
- }
800
- else if (this.proc) {
801
- this.pendingSettingsChange = true;
802
- }
623
+ runInformationalCommand(command, env) {
624
+ return new Promise((resolve) => {
625
+ (0, child_process_1.execFile)(this.agyCommand, ['-p', command], {
626
+ cwd: this.currentWorkingDirectory,
627
+ env,
628
+ encoding: 'utf8',
629
+ timeout: ACCOUNT_USAGE_TIMEOUT_MS,
630
+ maxBuffer: ACCOUNT_USAGE_MAX_BUFFER,
631
+ }, (error, stdout) => {
632
+ if (error) {
633
+ console.warn(`[AgyExecutor] ${command} is unavailable: ${error.message}`);
634
+ resolve(null);
635
+ return;
636
+ }
637
+ resolve((0, stripAnsi_1.stripAnsi)(stdout).trim() || null);
638
+ });
639
+ });
803
640
  }
804
641
  async listModels() {
805
642
  return new Promise((resolve, reject) => {
@@ -832,20 +669,11 @@ class AgyExecutor {
832
669
  supportsReset: true,
833
670
  };
834
671
  }
835
- /**
836
- * Compact via summarize-then-reset. agy has compaction only in its
837
- * interactive TUI — over stream-json a '/compact' message reaches the model
838
- * as plain text (verified live against agy 1.1.9: the model role-played a
839
- * compaction and the transcript kept the full history). So we:
840
- * 1. ask the current conversation for a dense handoff summary,
841
- * 2. reset the conversation,
842
- * 3. wrap the summary into the next user prompt (consumed once).
843
- * If the summary turn fails (e.g. context already too full), fall back to
844
- * a plain reset and say so honestly.
845
- */
846
672
  async compactWhenFull(onStream) {
847
673
  this.assertNoRetainedSchedules();
848
- if (!this.proc && !this.conversationId) {
674
+ if (this.acpLeaseUnconfirmed && !this.acp)
675
+ throw new Error('Saved AGY ACP chat cannot safely resume or compact. Use explicit /clear to select a fresh conversation when no schedule owner remains; original history is retained.');
676
+ if (!this.acp && !this.conversationId) {
849
677
  return { success: true, output: 'No active conversation to compact.' };
850
678
  }
851
679
  onStream?.('Summarizing the conversation before resetting...\n');
@@ -871,555 +699,22 @@ class AgyExecutor {
871
699
  output: '⚠️ Handoff summary failed — the conversation was reset without carryover. Context starts fresh.',
872
700
  };
873
701
  }
874
- /**
875
- * Delete per-thread conversation state. Removes OUR stored conversation id
876
- * mapping and the thread's isolated HOME; agy's shared store
877
- * (~/.gemini/antigravity-cli, legacy conversations from before per-thread
878
- * HOMEs) is left untouched.
879
- */
880
702
  async deleteThreadData(_threadId) {
881
- this.assertScheduleResettable();
703
+ if (fs.existsSync(this.sessionFilePath + '.detached-acp'))
704
+ throw new Error('Detached AGY history has unconfirmed predecessor ownership; data erasure is refused.');
705
+ this.assertScheduleResettable(true);
882
706
  await this.destroy();
883
- // Managed lanes retain brain deliverables and recovery evidence. Parent reset owns history cleanup.
884
- if (this.delegationWorker)
885
- return;
886
- this.clearConversationId();
887
- fs.rmSync(this.sessionFilePath + '.checkpoint', { force: true });
888
- if (this.scheduleOwner?.retired)
889
- fs.rmSync(this.sessionFilePath + '.native-schedules', { force: true });
890
- if (this.agyHome) {
891
- fs.rmSync(this.agyHome, { recursive: true, force: true });
892
- }
893
- }
894
- // ─── Queue processing ─────────────────────────────────────────────────────
895
- async processQueue() {
896
- if (this.isProcessing || this.isDestroyed || this.commandQueue.length === 0)
897
- return;
898
- const command = this.commandQueue.shift();
899
- if (!command)
900
- return;
901
- this.isProcessing = true;
902
- try {
903
- const result = await this.executeQueued(command.prompt, command.options);
904
- command.resolve(result);
905
- }
906
- catch (error) {
907
- command.reject(error instanceof Error ? error : new Error(String(error)));
908
- }
909
- finally {
910
- this.isProcessing = false;
911
- void this.processQueue();
912
- }
913
- }
914
- async executeQueued(prompt, options) {
915
- if (options.attachments?.length && !this.attachmentWarningShown) {
916
- this.attachmentWarningShown = true;
917
- console.warn('[AgyExecutor] AGY input supports text only — attachments were dropped');
918
- }
919
- this.resumeCleanChat();
920
- if (!this.acp && this.acpLeaseUnconfirmed)
921
- throw new Error('Previous AGY ACP host or hook restoration is unconfirmed. No saved conversation was resumed; retain its state for explicit recovery.');
922
- if (!this.acp && this.scheduleOwner?.sessionId === this.conversationId) {
923
- throw new Error('AGY native schedules from this saved conversation require unresolved queue recovery. No prompt was sent. Use /schedule list; automatic reconstruction is unavailable.');
924
- }
925
- if (this.acp || this.acpEligible || this.resumePermit) {
926
- const runtime = this.acpRuntime();
927
- // Do not silently abandon a newly allocated ACP conversation on error.
928
- try {
929
- await runtime.start();
930
- }
931
- catch (error) {
932
- if (runtime.safeFallback && !this.conversationId) {
933
- this.acp = undefined;
934
- this.acpEligible = false;
935
- console.warn('[AgyExecutor] Native ACP initialization unavailable; using compatible transport without scheduling.');
936
- return this.executeQueued(prompt, options);
937
- }
938
- throw error;
939
- }
940
- if (this.pendingContextSeed) {
941
- const seed = this.pendingContextSeed;
942
- this.pendingContextSeed = null;
943
- const resolve = options.resolvePrompt;
944
- options = { ...options, resolvePrompt: id => (0, compactHandoff_1.seedPromptWithHandoff)(resolve?.(id) ?? prompt, seed) };
945
- }
946
- try {
947
- return await runtime.execute(prompt, { ...options, inactivityTimeout: options.inactivityTimeout ?? this.inactivityTimeoutMs });
948
- }
949
- finally {
950
- if (!runtime.hasJobs && runtime.blocked) {
951
- await runtime.close();
952
- this.acp = undefined;
953
- this.acpEligible = false;
954
- }
955
- }
956
- }
957
- const revision = this.contextRevision;
958
- let proc;
959
- try {
960
- this.assertExecutionContext(revision);
961
- if (!this.proc && this.pendingExits.size)
962
- await this.waitForExit();
963
- proc = this.ensureProcess(revision);
964
- prompt = options.resolvePrompt?.(this.conversationId) ?? prompt;
965
- }
966
- catch (error) {
967
- return {
968
- success: false,
969
- error: error instanceof Error ? error.message : String(error),
970
- };
971
- }
972
- return new Promise((resolve) => {
973
- const active = { options, resolve, inactivityTimeoutMs: options.inactivityTimeout };
974
- this.activityTracker.setCallback(options.onActivity);
975
- this.activityTracker.reset();
976
- if (options.timeout && options.timeout > 0) {
977
- active.timeoutTimer = setTimeout(() => {
978
- console.warn(`[AgyExecutor] Command timed out after ${options.timeout}ms, killing process`);
979
- this.killProcess(`Command timed out after ${options.timeout}ms`);
980
- }, options.timeout);
981
- }
982
- this.activeCommand = active;
983
- this.currentOutputBuffer = [];
984
- this.armInactivityTimer();
985
- // A carried-over compact summary wraps the first prompt after a reset
986
- const finalPrompt = this.pendingContextSeed
987
- ? (0, compactHandoff_1.seedPromptWithHandoff)(this.pendingContextSeed, prompt)
988
- : prompt;
989
- this.pendingContextSeed = null;
990
- const line = JSON.stringify({
991
- event: 'user',
992
- message: { content: finalPrompt },
993
- }) + '\n';
994
- try {
995
- proc.stdin.write(line);
996
- }
997
- catch (error) {
998
- this.completeActiveCommand({
999
- success: false,
1000
- error: `Failed to send prompt to agy: ${error instanceof Error ? error.message : String(error)}`,
1001
- });
1002
- }
1003
- });
1004
- }
1005
- completeActiveCommand(result) {
1006
- const active = this.activeCommand;
1007
- if (!active)
1008
- return;
1009
- this.activeCommand = null;
1010
- this.activityTracker.reset();
1011
- this.activityTracker.setCallback(undefined);
1012
- this.clearInactivityTimer();
1013
- if (active.timeoutTimer)
1014
- clearTimeout(active.timeoutTimer);
1015
- if (result.success && result.output === undefined) {
1016
- result.output = this.currentOutputBuffer.join('');
1017
- }
1018
- if (result.success) {
1019
- result.sessionAbbr = this.conversationId?.slice(0, 8);
1020
- }
1021
- if (this.nativeObserver) {
1022
- // AGY can emit init only after the first prompt. Do not report success ahead of its durable receipt.
1023
- if (!this.conversationId && !this.nativeCaptureFailed) {
1024
- this.nativeReceiptPending++;
1025
- this.nativeReceiptOperations = this.nativeReceiptOperations.then(() => this.reportNativeCaptureFailure())
1026
- .catch(() => { this.nativeCaptureUnconfirmed = true; })
1027
- .finally(() => { this.nativeReceiptPending--; });
1028
- }
1029
- const admitted = this.nativeReceiptOperations;
1030
- void (async () => {
1031
- await admitted;
1032
- if (result.success && this.nativeCaptureFailed) {
1033
- result = { ...result, success: false, error: 'AGY native creation receipt could not be confirmed' };
1034
- }
1035
- active.resolve(result);
1036
- })().catch(() => active.resolve({ ...result, success: false, error: 'AGY native creation coverage could not be persisted' }));
1037
- }
1038
- else
1039
- active.resolve(result);
1040
- // A model or effort switch requested mid-command takes effect now that
1041
- // the command has finished — recycle the process (conversation preserved).
1042
- if (this.pendingSettingsChange) {
1043
- this.pendingSettingsChange = false;
1044
- if (this.proc)
1045
- this.killProcess();
1046
- }
1047
- }
1048
- /**
1049
- * Arm the inactivity watchdog: any stdout line counts as activity. If agy
1050
- * goes silent mid-command for longer than the limit, fail the command and
1051
- * kill the process (the conversation resumes on the next command).
1052
- */
1053
- armInactivityTimer() {
1054
- this.clearInactivityTimer();
1055
- const inactivityTimeoutMs = this.activeCommand?.inactivityTimeoutMs ?? this.inactivityTimeoutMs;
1056
- if (!Number.isFinite(inactivityTimeoutMs) || inactivityTimeoutMs <= 0)
1057
- return;
1058
- this.inactivityTimer = setTimeout(() => {
1059
- console.warn(`[AgyExecutor] No output for ${inactivityTimeoutMs}ms, killing process`);
1060
- this.killProcess(`No output from agy for ${inactivityTimeoutMs}ms (inactivity timeout)`);
1061
- }, inactivityTimeoutMs);
1062
- }
1063
- clearInactivityTimer() {
1064
- if (this.inactivityTimer !== null) {
1065
- clearTimeout(this.inactivityTimer);
1066
- this.inactivityTimer = null;
1067
- }
1068
- }
1069
- // ─── Process lifecycle ────────────────────────────────────────────────────
1070
- assertExecutionContext(revision) {
1071
- if (this.isDestroyed) {
1072
- throw new Error('Executor has been destroyed');
1073
- }
1074
- if (revision !== this.contextRevision || this.resettingNativeContext)
1075
- throw new Error('AGY execution context retired before prompt dispatch');
1076
- if (this.configuringTools)
1077
- throw new Error('AGY managed-tool configuration is still in progress');
1078
- if (this.shutdownUncertain)
1079
- throw new Error('AGY process exit is unconfirmed. Retry /abort before sending more work.');
1080
- }
1081
- ensureProcess(revision) {
1082
- this.assertExecutionContext(revision);
1083
- (0, WorkingDirectory_1.assertWorkingDirectoryExists)(this.currentWorkingDirectory);
1084
- if (this.proc)
1085
- return this.proc;
1086
- // Signalling, leader exit and transport close are different boundaries. The
1087
- // predecessor must close before a successor opens the same native database.
1088
- // This is a host/transport fence, not proof that escaped descendants retired.
1089
- if (this.pendingExits.size)
1090
- throw new Error('AGY predecessor transport has not closed');
1091
- // Compatible transport can admit unobserved native work. Revoke any older
1092
- // clean ACP proof before spawning it, even when configuration later reverts.
1093
- if (this.sessionFilePath && fs.existsSync(this.sessionFilePath + '.checkpoint'))
1094
- fs.rmSync(this.sessionFilePath + '.checkpoint', { force: true });
1095
- const env = this.buildEnv();
1096
- if (this.nativeObserver && this.agyHome) {
1097
- const scope = path.join(this.agyHome, '.gemini', 'antigravity-cli');
1098
- if (fs.realpathSync.native(scope) !== scope) {
1099
- throw new Error('AGY managed history is redirected');
1100
- }
1101
- const stat = fs.lstatSync(scope, { bigint: true });
1102
- this.nativeCreationScope = { path: scope, dev: String(stat.dev), ino: String(stat.ino) };
1103
- const conversations = path.join(scope, 'conversations');
1104
- if (fs.existsSync(conversations) && fs.realpathSync.native(conversations) !== conversations)
1105
- throw new Error('AGY conversations are redirected');
1106
- const names = fs.existsSync(conversations) ? fs.readdirSync(conversations) : [];
1107
- if (names.length > 4096)
1108
- throw new Error('AGY creation inventory exceeds the inspection limit');
1109
- this.preexistingNativeIds = new Set(names.map(name => name.replace(/\.db(?:-wal|-shm|-journal)?$/, '')));
1110
- if (this.conversationId)
1111
- this.preexistingNativeIds.add(this.conversationId);
1112
- }
1113
- if (this.agyHome && this.conversationId) {
1114
- const conversationsDir = path.join(this.agyHome, '.gemini', 'antigravity-cli', 'conversations');
1115
- if (path.basename(this.conversationId) !== this.conversationId ||
1116
- !fs.existsSync(path.join(conversationsDir, `${this.conversationId}.db`))) {
1117
- throw new Error('AGY saved conversation is missing from this thread HOME. Restore its database using the one-time migration steps in README.md, or use /clear to start a new conversation.');
1118
- }
1119
- }
1120
- const args = this.buildArgs();
1121
- console.log(`[AgyExecutor] Spawning: ${this.agyCommand} ${args.join(' ')} (cwd: ${this.currentWorkingDirectory})`);
1122
- // Fresh stream state for the new process
1123
- this.stdoutBuffer = '';
1124
- this.decoder = new string_decoder_1.StringDecoder('utf8');
1125
- const proc = (0, ManagedSpawn_1.spawnManaged)(this.delegationWorker, this.agyCommand, args, {
1126
- cwd: this.currentWorkingDirectory,
1127
- env,
1128
- stdio: ['pipe', 'pipe', 'pipe'],
1129
- ...((this.delegationWorker || this.delegationConnection) && process.platform !== 'win32' ? { detached: true } : {}),
1130
- });
1131
- if (this.delegationWorker || this.delegationConnection)
1132
- this.managedProcesses.add(proc);
707
+ this.assertScheduleResettable();
1133
708
  if (this.delegationWorker)
1134
- this.workerGroups.track(proc);
1135
- const exited = new Promise(resolve => proc.once('close', () => resolve()));
1136
- this.pendingExits.add(exited);
1137
- void exited.then(() => this.pendingExits.delete(exited));
1138
- proc.stdout.on('data', (data) => this.handleStdout(proc, data));
1139
- proc.stderr.on('data', (data) => {
1140
- // Diagnostics (progress, permission notices) — log only
1141
- console.log(`[AgyExecutor stderr] ${data.toString().trim().slice(0, 300)}`);
1142
- });
1143
- // Async stdin socket errors (e.g. EPIPE if agy exits mid-write) must not
1144
- // crash the whole CLI process — the exit/error handler reports the failure.
1145
- proc.stdin.on('error', (error) => {
1146
- console.warn(`[AgyExecutor] stdin error: ${error.message}`);
1147
- });
1148
- proc.on('error', (error) => {
1149
- if (proc !== this.proc)
1150
- return;
1151
- console.error('[AgyExecutor] Process error:', error);
1152
- const friendly = error.message.includes('ENOENT')
1153
- ? 'AGY CLI (agy) is not installed or not found on PATH. Install it from https://antigravity.google/cli, or use /backend to switch to another backend.'
1154
- : `agy process error: ${error.message}`;
1155
- this.killProcess(friendly);
1156
- });
1157
- proc.on('exit', (code, signal) => {
1158
- if (proc !== this.proc)
1159
- return;
1160
- this.proc = null;
1161
- if (this.activeCommand) {
1162
- console.error(`[AgyExecutor] Process exited unexpectedly (code=${code}, signal=${signal})`);
1163
- this.completeActiveCommand({
1164
- success: false,
1165
- error: `agy process exited unexpectedly (code ${code ?? signal}). The conversation will resume on the next command.`,
1166
- });
1167
- }
1168
- });
1169
- this.proc = proc;
1170
- return proc;
1171
- }
1172
- buildArgs() {
1173
- const args = ['--input-format=stream-json', '--output-format=stream-json'];
1174
- if (this.autoApprove) {
1175
- args.push('--dangerously-skip-permissions');
1176
- }
1177
- if (this.model) {
1178
- args.push('--model', this.model);
1179
- }
1180
- if (this.effort) {
1181
- args.push('--effort', this.effort);
1182
- }
1183
- if (this.conversationId) {
1184
- args.push('--conversation', this.conversationId);
1185
- }
1186
- return args;
1187
- }
1188
- killProcess(reason) {
1189
- const proc = this.proc;
1190
- this.proc = null;
1191
- if (proc) {
1192
- let exited = false;
1193
- proc.once('exit', () => { exited = true; });
1194
- this.signalProcess(proc, 'SIGTERM');
1195
- // Escalate to SIGKILL if the process ignores SIGTERM — a lingering
1196
- // process would share the conversation store with the next respawn.
1197
- const escalate = setTimeout(() => {
1198
- if (!exited) {
1199
- console.warn('[AgyExecutor] Process ignored SIGTERM, escalating to SIGKILL');
1200
- this.signalProcess(proc, 'SIGKILL');
1201
- }
1202
- }, this.killEscalationMs);
1203
- // Never let the watchdog hold the event loop open by itself
1204
- if (typeof escalate.unref === 'function')
1205
- escalate.unref();
1206
- }
1207
- // Never leave an in-flight command hanging when its process dies.
1208
- if (this.activeCommand) {
1209
- this.completeActiveCommand({
1210
- success: false,
1211
- error: reason ?? 'agy process was terminated mid-command',
1212
- });
1213
- }
1214
- }
1215
- // ─── Wire protocol parsing ────────────────────────────────────────────────
1216
- signalProcess(proc, signal) {
1217
- if (this.managedProcesses.has(proc) && process.platform === 'linux' && proc.pid) {
1218
- try {
1219
- process.kill(-proc.pid, signal);
1220
- return;
1221
- }
1222
- catch { /* Fall back to the direct child. */ }
1223
- }
1224
- if (signal === 'SIGTERM')
1225
- proc.kill();
1226
- else
1227
- proc.kill(signal);
1228
- }
1229
- handleStdout(proc, data) {
1230
- if (proc !== this.proc)
1231
- return; // stale process
1232
- // StringDecoder handles multi-byte UTF-8 characters split across chunks
1233
- this.stdoutBuffer += this.decoder.write(data);
1234
- const lines = this.stdoutBuffer.split('\n');
1235
- this.stdoutBuffer = lines.pop() ?? '';
1236
- for (const line of lines) {
1237
- if (proc !== this.proc)
1238
- break;
1239
- if (line.trim())
1240
- this.handleLine(line);
1241
- }
1242
- }
1243
- handleLine(line) {
1244
- let message;
1245
- try {
1246
- message = JSON.parse(line);
1247
- }
1248
- catch {
1249
- console.warn(`[AgyExecutor] Skipping malformed NDJSON line: ${line.slice(0, 120)}`);
1250
709
  return;
1251
- }
1252
- // Any valid line counts as activity for the inactivity watchdog
1253
- if (this.activeCommand)
1254
- this.armInactivityTimer();
1255
- switch (message.event) {
1256
- case 'init': {
1257
- const conversationId = message.conversation_id;
1258
- if (typeof conversationId === 'string' && conversationId) {
1259
- console.log(`[AgyExecutor] Conversation initialized: ${conversationId}`);
1260
- this.setConversationId(conversationId);
1261
- }
1262
- break;
1263
- }
1264
- case 'step_update':
1265
- this.handleStepUpdate(message.step_update);
1266
- break;
1267
- case 'result':
1268
- this.handleResult(message.result);
1269
- break;
1270
- default:
1271
- // Unknown events are safely ignored (agy may add new ones)
1272
- console.warn(`[AgyExecutor] Ignoring unknown event: ${message.event}`);
1273
- }
1274
- }
1275
- handleStepUpdate(step) {
1276
- if (!step || !this.activeCommand)
1277
- return;
1278
- const { options } = this.activeCommand;
1279
- if (step.step_type === 'agent_response') {
1280
- const delta = step.text_delta;
1281
- if (typeof delta === 'string' && delta.length > 0) {
1282
- this.currentOutputBuffer.push(delta);
1283
- options.onStream?.(delta);
1284
- options.onDisplayText?.(delta);
1285
- this.activityTracker.emitPublicText(delta);
1286
- }
1287
- return;
1288
- }
1289
- if (step.step_type === 'tool' && typeof step.tool_name === 'string') {
1290
- const toolUseId = `agy-step-${step.step_index}`;
1291
- const toolInfo = step.tool_info ?? {};
1292
- const parameters = (toolInfo.parameters ?? {});
1293
- if (step.state === 'ACTIVE') {
1294
- const { name, input } = mapAgyTool(step.tool_name, parameters);
1295
- const description = [parameters.description, parameters.toolSummary, parameters.toolAction]
1296
- .map(value => typeof value === 'string' ? (0, Activity_1.sanitizeActivityText)(value) : '')
1297
- .find(value => value.length > 0);
1298
- options.onToolUse?.({ id: toolUseId, name, input,
1299
- ...(description ? { description } : {}),
1300
- ...(typeof parameters.title === 'string' ? { title: parameters.title } : {}),
1301
- });
1302
- this.activityTracker.emitTool(name, input, description ?? (typeof parameters.title === 'string' ? parameters.title : undefined));
1303
- }
1304
- else if (step.state === 'DONE') {
1305
- const isError = !!toolInfo.error;
1306
- const errorMessage = typeof toolInfo.error?.message === 'string' ? toolInfo.error.message : '';
1307
- const content = typeof toolInfo.output === 'string'
1308
- ? toolInfo.output
1309
- : [errorMessage, toolInfo.output != null ? JSON.stringify(toolInfo.output) : undefined].filter(Boolean).join('\n');
1310
- options.onToolResult?.({ tool_use_id: toolUseId, content, is_error: isError });
1311
- }
1312
- return;
1313
- }
1314
- // user_input / system_message / checkpoint / unknown step types: ignore
1315
- }
1316
- handleResult(result) {
1317
- if (!result || !this.activeCommand) {
1318
- // Late result from an aborted/killed turn — nothing to complete
1319
- return;
1320
- }
1321
- const conversationId = result.conversation_id;
1322
- if (typeof conversationId === 'string' && conversationId && conversationId !== this.conversationId) {
1323
- this.setConversationId(conversationId);
1324
- }
1325
- if (result.status === 'SUCCESS') {
1326
- const accumulated = this.currentOutputBuffer.join('');
1327
- if (!accumulated && typeof result.response === 'string')
1328
- this.activeCommand.options.onDisplayText?.(result.response);
1329
- this.completeActiveCommand({
1330
- success: true,
1331
- output: accumulated || result.response || '',
1332
- });
1333
- return;
1334
- }
1335
- if (ABORTED_STATUSES.has(result.status)) {
1336
- this.completeActiveCommand({ success: false, error: `Command ${String(result.status).toLowerCase()}` });
1337
- return;
1338
- }
1339
- this.completeActiveCommand({
1340
- success: false,
1341
- error: result.error || `agy command failed with status ${result.status}`,
1342
- });
1343
- }
1344
- // ─── Conversation persistence ─────────────────────────────────────────────
1345
- loadConversationId() {
1346
- try {
1347
- if (fs.existsSync(this.sessionFilePath)) {
1348
- const data = fs.readFileSync(this.sessionFilePath, 'utf-8');
1349
- const session = JSON.parse(data);
1350
- if (session.id) {
1351
- this.conversationId = session.id;
1352
- this.acpLeaseUnconfirmed = session.transport === 'acp' && session.retired !== true;
1353
- console.log(`[AgyExecutor] Loaded conversation ID: ${this.conversationId}`);
1354
- }
1355
- }
1356
- }
1357
- catch (error) {
1358
- if (this.nativeAcp)
1359
- throw new Error('Saved AGY conversation pointer is unreadable; no new conversation was allocated.');
1360
- console.error('[AgyExecutor] Failed to load conversation ID:', error);
1361
- this.conversationId = null;
1362
- }
1363
- }
1364
- setConversationId(conversationId) {
1365
- if (this.conversationId === conversationId)
1366
- return;
1367
- this.conversationId = conversationId;
1368
- let persisted = true;
1369
- try {
1370
- const data = JSON.stringify({ id: conversationId, savedAt: new Date().toISOString() });
1371
- fs.writeFileSync(this.sessionFilePath, data, 'utf-8');
1372
- }
1373
- catch (error) {
1374
- persisted = false;
1375
- console.error('[AgyExecutor] Failed to save conversation ID:', error);
1376
- }
1377
- if (this.nativeObserver && !this.observedNativeIds.has(conversationId)) {
1378
- const scope = this.nativeCreationScope;
1379
- const observer = this.nativeObserver;
1380
- const cwd = this.currentWorkingDirectory;
1381
- const home = os.homedir();
1382
- const preexisting = this.preexistingNativeIds.has(conversationId);
1383
- this.observedNativeIds.add(conversationId);
1384
- this.nativeReceiptPending++;
1385
- this.nativeReceiptOperations = this.nativeReceiptOperations.then(async () => {
1386
- try {
1387
- if (!persisted || preexisting || !scope || !this.threadId)
1388
- throw new Error('AGY native creation is unconfirmed');
1389
- const { captureAgyDeletionTarget } = await Promise.resolve().then(() => __importStar(require('../delegation/AgySessionDeletion')));
1390
- const target = await captureAgyDeletionTarget({ sessionId: conversationId, executorThreadId: this.threadId,
1391
- home, cwd, command: this.agyCommand });
1392
- if (target.scope.dev !== scope.dev || target.scope.ino !== scope.ino)
1393
- throw new Error('AGY creation root changed');
1394
- await observer(target);
1395
- }
1396
- catch {
1397
- await this.reportNativeCaptureFailure();
1398
- }
1399
- finally {
1400
- this.nativeReceiptPending--;
1401
- }
1402
- }).catch(() => { this.nativeCaptureUnconfirmed = true; });
1403
- }
1404
- }
1405
- async reportNativeCaptureFailure() {
1406
- this.nativeCaptureFailed = true;
1407
- this.nativeCaptureUnconfirmed = true;
1408
- if (this.nativeCaptureFailure) {
1409
- await this.nativeCaptureFailure();
1410
- this.nativeCaptureUnconfirmed = false;
1411
- }
1412
- }
1413
- clearConversationId() {
710
+ fs.rmSync(this.sessionFilePath, { force: true });
1414
711
  this.conversationId = null;
1415
- try {
1416
- if (fs.existsSync(this.sessionFilePath)) {
1417
- fs.unlinkSync(this.sessionFilePath);
1418
- }
1419
- }
1420
- catch (error) {
1421
- console.error('[AgyExecutor] Failed to delete conversation file:', error);
712
+ if (this.scheduleOwner?.retired) {
713
+ fs.rmSync(this.sessionFilePath + '.native-schedules', { force: true });
714
+ this.scheduleOwner = undefined;
1422
715
  }
716
+ if (this.agyHome)
717
+ fs.rmSync(this.agyHome, { recursive: true, force: true });
1423
718
  }
1424
719
  }
1425
720
  exports.AgyExecutor = AgyExecutor;