@yu_robotics/remote-cli 1.2.0 → 1.4.0

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.
@@ -0,0 +1,637 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.AgyExecutor = void 0;
37
+ const child_process_1 = require("child_process");
38
+ const string_decoder_1 = require("string_decoder");
39
+ const fs = __importStar(require("fs"));
40
+ const os = __importStar(require("os"));
41
+ const path = __importStar(require("path"));
42
+ const compactHandoff_1 = require("./compactHandoff");
43
+ /** Default inactivity timeout (ms) — a silent agy process fails the command. */
44
+ const DEFAULT_INACTIVITY_TIMEOUT_MS = 10 * 60 * 1000;
45
+ /** Default grace period (ms) before SIGTERM escalates to SIGKILL. */
46
+ const DEFAULT_KILL_ESCALATION_MS = 3_000;
47
+ /**
48
+ * Map an AGY tool call to a Claude-compatible { name, input } shape so the
49
+ * router's ToolFormatter renders it with the same card style as Claude tools.
50
+ * Unknown tools keep their raw name and parameters (generic rendering).
51
+ *
52
+ * AGY parameter keys are PascalCase (e.g. run_command takes `CommandLine`).
53
+ */
54
+ function mapAgyTool(toolName, parameters) {
55
+ switch (toolName) {
56
+ case 'run_command':
57
+ return { name: 'Bash', input: { command: parameters.CommandLine ?? '' } };
58
+ case 'view_file':
59
+ return { name: 'Read', input: { file_path: parameters.AbsolutePath ?? parameters.Path ?? '' } };
60
+ case 'write_to_file':
61
+ return { name: 'Write', input: { file_path: parameters.AbsolutePath ?? parameters.Path ?? '' } };
62
+ case 'replace_file_content':
63
+ case 'multi_replace_file_content':
64
+ case 'sed_file':
65
+ return { name: 'Edit', input: { file_path: parameters.AbsolutePath ?? parameters.Path ?? '' } };
66
+ case 'grep_search':
67
+ return { name: 'Grep', input: parameters };
68
+ case 'find_by_name':
69
+ return { name: 'Glob', input: parameters };
70
+ case 'search_web':
71
+ return { name: 'WebSearch', input: { query: parameters.Query ?? '' } };
72
+ case 'read_url_content':
73
+ return { name: 'WebFetch', input: { url: parameters.Url ?? '' } };
74
+ default:
75
+ return { name: toolName, input: parameters };
76
+ }
77
+ }
78
+ /** Result statuses that mean the turn was aborted rather than failed. */
79
+ const ABORTED_STATUSES = new Set(['INTERRUPTED', 'CANCELED']);
80
+ /**
81
+ * IExecutor implementation for the Antigravity CLI (`agy`) — Google's
82
+ * agentic CLI from the Antigravity suite.
83
+ *
84
+ * agy speaks a Claude-Code-style stream-json protocol: one persistent
85
+ * process per conversation, NDJSON prompts in on stdin
86
+ * ({"event":"user","message":{"content":"..."}}), NDJSON events out on
87
+ * stdout (init / step_update / result). Conversations survive process
88
+ * restarts via `--conversation <id>`, which we persist per thread.
89
+ *
90
+ * The process is respawned (resuming the conversation) when:
91
+ * - setWorkingDirectory() changes cwd
92
+ * - the process exits unexpectedly
93
+ * - abort() kills it mid-command
94
+ * resetContext()/compactWhenFull() additionally drop the conversation id,
95
+ * so the next command starts a fresh session (agy has no /compact).
96
+ *
97
+ * Note: agy stream-json input supports text blocks only — image
98
+ * attachments are silently dropped (with a log line).
99
+ */
100
+ class AgyExecutor {
101
+ directoryGuard;
102
+ currentWorkingDirectory;
103
+ /** Model for the next spawn. Mutable: setModel() updates it in place. */
104
+ model;
105
+ autoApprove;
106
+ agyCommand;
107
+ threadId;
108
+ proc = null;
109
+ conversationId = null;
110
+ sessionFilePath;
111
+ commandQueue = [];
112
+ isProcessing = false;
113
+ isDestroyed = false;
114
+ activeCommand = null;
115
+ currentOutputBuffer = [];
116
+ stdoutBuffer = '';
117
+ decoder = new string_decoder_1.StringDecoder('utf8');
118
+ inactivityTimer = null;
119
+ inactivityTimeoutMs;
120
+ killEscalationMs;
121
+ attachmentWarningShown = false;
122
+ /** Model switch requested while a command was running — respawn when it finishes. */
123
+ pendingModelChange = false;
124
+ /** Handoff summary from compactWhenFull, wrapped into the next prompt (consumed once). */
125
+ pendingContextSeed = null;
126
+ constructor(directoryGuard, options = {}) {
127
+ this.directoryGuard = directoryGuard;
128
+ this.model = options.model;
129
+ this.autoApprove = options.autoApprove ?? true;
130
+ this.agyCommand = options.agyCommand ?? 'agy';
131
+ this.threadId = options.threadId;
132
+ this.inactivityTimeoutMs = options.inactivityTimeoutMs ?? DEFAULT_INACTIVITY_TIMEOUT_MS;
133
+ this.killEscalationMs = options.killEscalationMs ?? DEFAULT_KILL_ESCALATION_MS;
134
+ if (options.initialWorkingDirectory) {
135
+ try {
136
+ this.currentWorkingDirectory = this.directoryGuard.resolveWorkingDirectory(options.initialWorkingDirectory);
137
+ }
138
+ catch (error) {
139
+ console.warn(`[AgyExecutor] Failed to use initial working directory: ${options.initialWorkingDirectory}`, error);
140
+ this.currentWorkingDirectory = process.cwd();
141
+ }
142
+ }
143
+ else {
144
+ this.currentWorkingDirectory = process.cwd();
145
+ }
146
+ if (this.threadId) {
147
+ const sessionsDir = path.join(os.homedir(), '.remote-cli', 'agy-sessions');
148
+ fs.mkdirSync(sessionsDir, { recursive: true });
149
+ this.sessionFilePath = path.join(sessionsDir, `${this.threadId}.json`);
150
+ }
151
+ else {
152
+ // Legacy: session file in working directory
153
+ this.sessionFilePath = path.join(this.currentWorkingDirectory, '.agy-session');
154
+ }
155
+ this.loadConversationId();
156
+ }
157
+ // ─── IExecutor required ───────────────────────────────────────────────────
158
+ async execute(prompt, options = {}) {
159
+ if (this.isDestroyed) {
160
+ return Promise.reject(new Error('Executor has been destroyed'));
161
+ }
162
+ return new Promise((resolve, reject) => {
163
+ this.commandQueue.push({ prompt, options, resolve, reject });
164
+ void this.processQueue();
165
+ });
166
+ }
167
+ getCurrentWorkingDirectory() {
168
+ return this.currentWorkingDirectory;
169
+ }
170
+ async setWorkingDirectory(targetPath) {
171
+ const resolved = this.directoryGuard.resolveWorkingDirectory(targetPath);
172
+ // Changing cwd requires a respawn (tools run relative to the process cwd).
173
+ // The conversation id is kept, so the respawn resumes context.
174
+ const needsRestart = this.currentWorkingDirectory !== resolved && this.proc !== null;
175
+ this.currentWorkingDirectory = resolved;
176
+ if (needsRestart) {
177
+ console.log(`[AgyExecutor] Restarting process in new directory: ${resolved}`);
178
+ this.killProcess();
179
+ }
180
+ }
181
+ resetContext() {
182
+ this.killProcess();
183
+ this.clearConversationId();
184
+ // /clear means a real fresh start — drop any carried-over compact seed
185
+ this.pendingContextSeed = null;
186
+ }
187
+ async abort() {
188
+ if (!this.proc || !this.activeCommand)
189
+ return false;
190
+ // agy's stream-json protocol has no cancel request (control_request is
191
+ // explicitly unsupported), so abort = kill the process. The conversation
192
+ // id survives, so the next command resumes context.
193
+ console.log('[AgyExecutor] Aborting: killing agy process');
194
+ this.killProcess('Aborted by user');
195
+ return true;
196
+ }
197
+ async destroy() {
198
+ if (this.isDestroyed)
199
+ return;
200
+ this.isDestroyed = true;
201
+ // Reject everything still queued — nothing may respawn after destroy
202
+ const queued = this.commandQueue.splice(0);
203
+ for (const command of queued) {
204
+ command.reject(new Error('Executor has been destroyed'));
205
+ }
206
+ const proc = this.proc;
207
+ if (proc) {
208
+ try {
209
+ proc.stdin?.end();
210
+ }
211
+ catch { /* already closed */ }
212
+ }
213
+ this.killProcess('Executor destroyed');
214
+ }
215
+ // ─── IExecutor optional ───────────────────────────────────────────────────
216
+ isProcessRunning() {
217
+ return this.proc !== null;
218
+ }
219
+ getSessionId() {
220
+ return this.conversationId;
221
+ }
222
+ /**
223
+ * Switch the model. agy takes --model at process start, so the process must
224
+ * respawn for the change to take effect — the conversation id survives, so
225
+ * context is preserved. If a command is in flight, the respawn is deferred
226
+ * until it finishes (the running turn keeps the old model).
227
+ * MessageHandler persists the choice on the thread; ThreadExecutorPool
228
+ * passes it back via the factory on restarts.
229
+ */
230
+ async setModel(model, _onStream) {
231
+ this.model = model;
232
+ if (this.proc && !this.activeCommand) {
233
+ console.log(`[AgyExecutor] Model set to ${model} — recycling idle process (conversation preserved)`);
234
+ this.killProcess();
235
+ }
236
+ else if (this.proc) {
237
+ console.log(`[AgyExecutor] Model set to ${model} — will respawn after the current command`);
238
+ this.pendingModelChange = true;
239
+ }
240
+ else {
241
+ console.log(`[AgyExecutor] Model set to ${model} (applies from the next command)`);
242
+ }
243
+ return {
244
+ success: true,
245
+ output: `Model set to ${model}. Takes effect on the next command (the agy process restarts; conversation context is preserved).`,
246
+ };
247
+ }
248
+ /**
249
+ * Compact via summarize-then-reset. agy has compaction only in its
250
+ * interactive TUI — over stream-json a '/compact' message reaches the model
251
+ * as plain text (verified live against agy 1.1.9: the model role-played a
252
+ * compaction and the transcript kept the full history). So we:
253
+ * 1. ask the current conversation for a dense handoff summary,
254
+ * 2. reset the conversation,
255
+ * 3. wrap the summary into the next user prompt (consumed once).
256
+ * If the summary turn fails (e.g. context already too full), fall back to
257
+ * a plain reset and say so honestly.
258
+ */
259
+ async compactWhenFull(onStream) {
260
+ if (!this.proc && !this.conversationId) {
261
+ return { success: true, output: 'No active conversation to compact.' };
262
+ }
263
+ onStream?.('Summarizing the conversation before resetting...\n');
264
+ let summary = null;
265
+ try {
266
+ const r = await this.execute(compactHandoff_1.COMPACT_HANDOFF_PROMPT, onStream ? { onStream } : {});
267
+ if (r.success && r.output?.trim())
268
+ summary = r.output.trim();
269
+ }
270
+ catch (error) {
271
+ console.warn('[AgyExecutor] Handoff summary failed, falling back to plain reset:', error);
272
+ }
273
+ this.resetContext();
274
+ if (summary) {
275
+ this.pendingContextSeed = summary;
276
+ return {
277
+ success: true,
278
+ output: '✅ Context compacted: the conversation was summarized and carried over to a fresh session.',
279
+ };
280
+ }
281
+ return {
282
+ success: true,
283
+ output: '⚠️ Handoff summary failed — the conversation was reset without carryover. Context starts fresh.',
284
+ };
285
+ }
286
+ /**
287
+ * Delete per-thread conversation state. Only removes OUR stored
288
+ * conversation id mapping — agy's own conversation store
289
+ * (~/.gemini/antigravity-cli/conversations) is left untouched.
290
+ */
291
+ async deleteThreadData(_threadId) {
292
+ await this.destroy();
293
+ this.clearConversationId();
294
+ }
295
+ // ─── Queue processing ─────────────────────────────────────────────────────
296
+ async processQueue() {
297
+ if (this.isProcessing || this.isDestroyed || this.commandQueue.length === 0)
298
+ return;
299
+ const command = this.commandQueue.shift();
300
+ if (!command)
301
+ return;
302
+ this.isProcessing = true;
303
+ try {
304
+ const result = await this.executeQueued(command.prompt, command.options);
305
+ command.resolve(result);
306
+ }
307
+ catch (error) {
308
+ command.reject(error instanceof Error ? error : new Error(String(error)));
309
+ }
310
+ finally {
311
+ this.isProcessing = false;
312
+ void this.processQueue();
313
+ }
314
+ }
315
+ executeQueued(prompt, options) {
316
+ return new Promise((resolve) => {
317
+ if (options.attachments?.length && !this.attachmentWarningShown) {
318
+ this.attachmentWarningShown = true;
319
+ console.warn('[AgyExecutor] agy stream-json input supports text only — attachments were dropped');
320
+ }
321
+ let proc;
322
+ try {
323
+ proc = this.ensureProcess();
324
+ }
325
+ catch (error) {
326
+ resolve({
327
+ success: false,
328
+ error: error instanceof Error ? error.message : String(error),
329
+ });
330
+ return;
331
+ }
332
+ const active = { options, resolve };
333
+ if (options.timeout && options.timeout > 0) {
334
+ active.timeoutTimer = setTimeout(() => {
335
+ console.warn(`[AgyExecutor] Command timed out after ${options.timeout}ms, killing process`);
336
+ this.killProcess(`Command timed out after ${options.timeout}ms`);
337
+ }, options.timeout);
338
+ }
339
+ this.activeCommand = active;
340
+ this.currentOutputBuffer = [];
341
+ this.armInactivityTimer();
342
+ // A carried-over compact summary wraps the first prompt after a reset
343
+ const finalPrompt = this.pendingContextSeed
344
+ ? (0, compactHandoff_1.seedPromptWithHandoff)(this.pendingContextSeed, prompt)
345
+ : prompt;
346
+ this.pendingContextSeed = null;
347
+ const line = JSON.stringify({
348
+ event: 'user',
349
+ message: { content: finalPrompt },
350
+ }) + '\n';
351
+ try {
352
+ proc.stdin.write(line);
353
+ }
354
+ catch (error) {
355
+ this.completeActiveCommand({
356
+ success: false,
357
+ error: `Failed to send prompt to agy: ${error instanceof Error ? error.message : String(error)}`,
358
+ });
359
+ }
360
+ });
361
+ }
362
+ completeActiveCommand(result) {
363
+ const active = this.activeCommand;
364
+ if (!active)
365
+ return;
366
+ this.activeCommand = null;
367
+ this.clearInactivityTimer();
368
+ if (active.timeoutTimer)
369
+ clearTimeout(active.timeoutTimer);
370
+ if (result.success && result.output === undefined) {
371
+ result.output = this.currentOutputBuffer.join('');
372
+ }
373
+ if (result.success) {
374
+ result.sessionAbbr = this.conversationId?.slice(0, 8);
375
+ }
376
+ active.resolve(result);
377
+ // A model switch requested mid-command takes effect now that the
378
+ // command has finished — recycle the process (conversation preserved).
379
+ if (this.pendingModelChange) {
380
+ this.pendingModelChange = false;
381
+ if (this.proc)
382
+ this.killProcess();
383
+ }
384
+ }
385
+ /**
386
+ * Arm the inactivity watchdog: any stdout line counts as activity. If agy
387
+ * goes silent mid-command for longer than the limit, fail the command and
388
+ * kill the process (the conversation resumes on the next command).
389
+ */
390
+ armInactivityTimer() {
391
+ this.clearInactivityTimer();
392
+ this.inactivityTimer = setTimeout(() => {
393
+ console.warn(`[AgyExecutor] No output for ${this.inactivityTimeoutMs}ms, killing process`);
394
+ this.killProcess(`No output from agy for ${this.inactivityTimeoutMs}ms (inactivity timeout)`);
395
+ }, this.inactivityTimeoutMs);
396
+ }
397
+ clearInactivityTimer() {
398
+ if (this.inactivityTimer !== null) {
399
+ clearTimeout(this.inactivityTimer);
400
+ this.inactivityTimer = null;
401
+ }
402
+ }
403
+ // ─── Process lifecycle ────────────────────────────────────────────────────
404
+ ensureProcess() {
405
+ if (this.proc)
406
+ return this.proc;
407
+ if (this.isDestroyed) {
408
+ throw new Error('Executor has been destroyed');
409
+ }
410
+ const args = this.buildArgs();
411
+ console.log(`[AgyExecutor] Spawning: ${this.agyCommand} ${args.join(' ')} (cwd: ${this.currentWorkingDirectory})`);
412
+ // Fresh stream state for the new process
413
+ this.stdoutBuffer = '';
414
+ this.decoder = new string_decoder_1.StringDecoder('utf8');
415
+ const proc = (0, child_process_1.spawn)(this.agyCommand, args, {
416
+ cwd: this.currentWorkingDirectory,
417
+ env: { ...process.env },
418
+ stdio: ['pipe', 'pipe', 'pipe'],
419
+ });
420
+ proc.stdout.on('data', (data) => this.handleStdout(proc, data));
421
+ proc.stderr.on('data', (data) => {
422
+ // Diagnostics (progress, permission notices) — log only
423
+ console.log(`[AgyExecutor stderr] ${data.toString().trim().slice(0, 300)}`);
424
+ });
425
+ // Async stdin socket errors (e.g. EPIPE if agy exits mid-write) must not
426
+ // crash the whole CLI process — the exit/error handler reports the failure.
427
+ proc.stdin.on('error', (error) => {
428
+ console.warn(`[AgyExecutor] stdin error: ${error.message}`);
429
+ });
430
+ proc.on('error', (error) => {
431
+ if (proc !== this.proc)
432
+ return;
433
+ console.error('[AgyExecutor] Process error:', error);
434
+ this.proc = null;
435
+ const friendly = error.message.includes('ENOENT')
436
+ ? '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.'
437
+ : `agy process error: ${error.message}`;
438
+ this.completeActiveCommand({ success: false, error: friendly });
439
+ });
440
+ proc.on('exit', (code, signal) => {
441
+ if (proc !== this.proc)
442
+ return;
443
+ this.proc = null;
444
+ if (this.activeCommand) {
445
+ console.error(`[AgyExecutor] Process exited unexpectedly (code=${code}, signal=${signal})`);
446
+ this.completeActiveCommand({
447
+ success: false,
448
+ error: `agy process exited unexpectedly (code ${code ?? signal}). The conversation will resume on the next command.`,
449
+ });
450
+ }
451
+ });
452
+ this.proc = proc;
453
+ return proc;
454
+ }
455
+ buildArgs() {
456
+ const args = ['--input-format=stream-json', '--output-format=stream-json'];
457
+ if (this.autoApprove) {
458
+ args.push('--dangerously-skip-permissions');
459
+ }
460
+ if (this.model) {
461
+ args.push('--model', this.model);
462
+ }
463
+ if (this.conversationId) {
464
+ args.push('--conversation', this.conversationId);
465
+ }
466
+ return args;
467
+ }
468
+ killProcess(reason) {
469
+ const proc = this.proc;
470
+ this.proc = null;
471
+ if (proc) {
472
+ let exited = false;
473
+ proc.once('exit', () => { exited = true; });
474
+ proc.kill(); // SIGTERM
475
+ // Escalate to SIGKILL if the process ignores SIGTERM — a lingering
476
+ // process would share the conversation store with the next respawn.
477
+ const escalate = setTimeout(() => {
478
+ if (!exited) {
479
+ console.warn('[AgyExecutor] Process ignored SIGTERM, escalating to SIGKILL');
480
+ proc.kill('SIGKILL');
481
+ }
482
+ }, this.killEscalationMs);
483
+ // Never let the watchdog hold the event loop open by itself
484
+ if (typeof escalate.unref === 'function')
485
+ escalate.unref();
486
+ }
487
+ // Never leave an in-flight command hanging when its process dies.
488
+ if (this.activeCommand) {
489
+ this.completeActiveCommand({
490
+ success: false,
491
+ error: reason ?? 'agy process was terminated mid-command',
492
+ });
493
+ }
494
+ }
495
+ // ─── Wire protocol parsing ────────────────────────────────────────────────
496
+ handleStdout(proc, data) {
497
+ if (proc !== this.proc)
498
+ return; // stale process
499
+ // StringDecoder handles multi-byte UTF-8 characters split across chunks
500
+ this.stdoutBuffer += this.decoder.write(data);
501
+ const lines = this.stdoutBuffer.split('\n');
502
+ this.stdoutBuffer = lines.pop() ?? '';
503
+ for (const line of lines) {
504
+ if (line.trim())
505
+ this.handleLine(line);
506
+ }
507
+ }
508
+ handleLine(line) {
509
+ let message;
510
+ try {
511
+ message = JSON.parse(line);
512
+ }
513
+ catch {
514
+ console.warn(`[AgyExecutor] Skipping malformed NDJSON line: ${line.slice(0, 120)}`);
515
+ return;
516
+ }
517
+ // Any valid line counts as activity for the inactivity watchdog
518
+ if (this.activeCommand)
519
+ this.armInactivityTimer();
520
+ switch (message.event) {
521
+ case 'init': {
522
+ const conversationId = message.conversation_id;
523
+ if (typeof conversationId === 'string' && conversationId) {
524
+ console.log(`[AgyExecutor] Conversation initialized: ${conversationId}`);
525
+ this.setConversationId(conversationId);
526
+ }
527
+ break;
528
+ }
529
+ case 'step_update':
530
+ this.handleStepUpdate(message.step_update);
531
+ break;
532
+ case 'result':
533
+ this.handleResult(message.result);
534
+ break;
535
+ default:
536
+ // Unknown events are safely ignored (agy may add new ones)
537
+ console.warn(`[AgyExecutor] Ignoring unknown event: ${message.event}`);
538
+ }
539
+ }
540
+ handleStepUpdate(step) {
541
+ if (!step || !this.activeCommand)
542
+ return;
543
+ const { options } = this.activeCommand;
544
+ if (step.step_type === 'agent_response') {
545
+ const delta = step.text_delta;
546
+ if (typeof delta === 'string' && delta.length > 0) {
547
+ this.currentOutputBuffer.push(delta);
548
+ options.onStream?.(delta);
549
+ }
550
+ return;
551
+ }
552
+ if (step.step_type === 'tool' && typeof step.tool_name === 'string') {
553
+ const toolUseId = `agy-step-${step.step_index}`;
554
+ const toolInfo = step.tool_info ?? {};
555
+ const parameters = (toolInfo.parameters ?? {});
556
+ if (step.state === 'ACTIVE') {
557
+ const { name, input } = mapAgyTool(step.tool_name, parameters);
558
+ options.onToolUse?.({ id: toolUseId, name, input });
559
+ }
560
+ else if (step.state === 'DONE') {
561
+ const isError = !!toolInfo.error;
562
+ const content = typeof toolInfo.output === 'string'
563
+ ? toolInfo.output
564
+ : (toolInfo.error?.message ?? '');
565
+ options.onToolResult?.({ tool_use_id: toolUseId, content, is_error: isError });
566
+ }
567
+ return;
568
+ }
569
+ // user_input / system_message / checkpoint / unknown step types: ignore
570
+ }
571
+ handleResult(result) {
572
+ if (!result || !this.activeCommand) {
573
+ // Late result from an aborted/killed turn — nothing to complete
574
+ return;
575
+ }
576
+ const conversationId = result.conversation_id;
577
+ if (typeof conversationId === 'string' && conversationId && conversationId !== this.conversationId) {
578
+ this.setConversationId(conversationId);
579
+ }
580
+ if (result.status === 'SUCCESS') {
581
+ const accumulated = this.currentOutputBuffer.join('');
582
+ this.completeActiveCommand({
583
+ success: true,
584
+ output: accumulated || result.response || '',
585
+ });
586
+ return;
587
+ }
588
+ if (ABORTED_STATUSES.has(result.status)) {
589
+ this.completeActiveCommand({ success: false, error: `Command ${String(result.status).toLowerCase()}` });
590
+ return;
591
+ }
592
+ this.completeActiveCommand({
593
+ success: false,
594
+ error: result.error || `agy command failed with status ${result.status}`,
595
+ });
596
+ }
597
+ // ─── Conversation persistence ─────────────────────────────────────────────
598
+ loadConversationId() {
599
+ try {
600
+ if (fs.existsSync(this.sessionFilePath)) {
601
+ const data = fs.readFileSync(this.sessionFilePath, 'utf-8');
602
+ const session = JSON.parse(data);
603
+ if (session.id) {
604
+ this.conversationId = session.id;
605
+ console.log(`[AgyExecutor] Loaded conversation ID: ${this.conversationId}`);
606
+ }
607
+ }
608
+ }
609
+ catch (error) {
610
+ console.error('[AgyExecutor] Failed to load conversation ID:', error);
611
+ this.conversationId = null;
612
+ }
613
+ }
614
+ setConversationId(conversationId) {
615
+ this.conversationId = conversationId;
616
+ try {
617
+ const data = JSON.stringify({ id: conversationId, savedAt: new Date().toISOString() });
618
+ fs.writeFileSync(this.sessionFilePath, data, 'utf-8');
619
+ }
620
+ catch (error) {
621
+ console.error('[AgyExecutor] Failed to save conversation ID:', error);
622
+ }
623
+ }
624
+ clearConversationId() {
625
+ this.conversationId = null;
626
+ try {
627
+ if (fs.existsSync(this.sessionFilePath)) {
628
+ fs.unlinkSync(this.sessionFilePath);
629
+ }
630
+ }
631
+ catch (error) {
632
+ console.error('[AgyExecutor] Failed to delete conversation file:', error);
633
+ }
634
+ }
635
+ }
636
+ exports.AgyExecutor = AgyExecutor;
637
+ //# sourceMappingURL=AgyExecutor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AgyExecutor.js","sourceRoot":"","sources":["../../src/executor/AgyExecutor.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iDAAoD;AACpD,mDAA+C;AAC/C,uCAAyB;AACzB,uCAAyB;AACzB,2CAA6B;AAG7B,qDAAiF;AAsBjF,gFAAgF;AAChF,MAAM,6BAA6B,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AACrD,qEAAqE;AACrE,MAAM,0BAA0B,GAAG,KAAK,CAAC;AAEzC;;;;;;GAMG;AACH,SAAS,UAAU,CACjB,QAAgB,EAChB,UAAmC;IAEnC,QAAQ,QAAQ,EAAE,CAAC;QACjB,KAAK,aAAa;YAChB,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,OAAO,EAAE,UAAU,CAAC,WAAW,IAAI,EAAE,EAAE,EAAE,CAAC;QAC5E,KAAK,WAAW;YACd,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,SAAS,EAAE,UAAU,CAAC,YAAY,IAAI,UAAU,CAAC,IAAI,IAAI,EAAE,EAAE,EAAE,CAAC;QAClG,KAAK,eAAe;YAClB,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,SAAS,EAAE,UAAU,CAAC,YAAY,IAAI,UAAU,CAAC,IAAI,IAAI,EAAE,E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