@yu_robotics/remote-cli 1.6.259 → 1.6.263

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