@causyne/agent 1.20.12 → 1.20.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/package.json +1 -1
- package/src/SmartTools.js +33 -0
- package/src/SmartTools.ts +37 -0
- package/src/acp/client.js +157 -4
- package/src/acp/client.ts +152 -5
- package/src/agentLoop.js +857 -178
- package/src/agentLoop.ts +865 -183
- package/src/browser/browserRuntime.js +8 -1
- package/src/browser/browserRuntime.ts +8 -1
- package/src/browser/causyneBrowser.js +20 -4
- package/src/browser/causyneBrowser.ts +20 -4
- package/src/browser/urlPolicy.js +35 -0
- package/src/browser/urlPolicy.ts +34 -0
- package/src/cliMode.js +6 -2
- package/src/commands.js +14 -0
- package/src/contextManager.d.ts +1 -0
- package/src/core/contextCompactor.js +277 -0
- package/src/core/contextCompactor.ts +353 -0
- package/src/decideTools.js +157 -0
- package/src/decideTools.ts +195 -0
- package/src/decisionPolicy.js +5 -3
- package/src/decisionPolicy.ts +5 -3
- package/src/implementationPlan.js +284 -0
- package/src/implementationPlan.ts +275 -0
- package/src/observer/coldObserver.js +10 -4
- package/src/observer/coldObserver.ts +15 -7
- package/src/observer/evidence.js +11 -5
- package/src/observer/evidence.ts +13 -6
- package/src/observer.js +196 -0
- package/src/observer.ts +287 -0
- package/src/providers/acp.js +362 -109
- package/src/providers/acp.ts +359 -111
- package/src/providers/antigravity.js +133 -105
- package/src/providers/antigravity.ts +130 -109
- package/src/providers/base.d.ts +3 -0
- package/src/providers/budgetEnforcer.js +13 -0
- package/src/providers/budgetEnforcer.ts +13 -3
- package/src/provisioning/capabilityProvisioner.js +14 -10
- package/src/sandbox.js +4 -2
- package/src/saveTools.js +146 -0
- package/src/saveTools.ts +169 -0
- package/src/session/cachePressure.js +77 -0
- package/src/session/cachePressure.ts +122 -0
- package/src/smartToolsUse.js +69 -12
- package/src/smartToolsUse.ts +103 -12
- package/src/taskShape.js +7 -7
- package/src/taskShape.ts +7 -7
- package/src/timeMachine.js +55 -20
- package/src/timeMachine.ts +64 -20
- package/src/toolPacks.js +217 -310
- package/src/toolPacks.ts +505 -0
- package/src/tools/deferredMcpSearch.js +21 -13
- package/src/tools/deferredMcpSearch.ts +23 -15
- package/src/tools/updatePlan.js +2 -2
- package/src/tools/updatePlan.ts +2 -2
- package/src/toolsList.js +203 -0
- package/src/toolsList.ts +224 -0
- package/src/tui/chatRenderer.js +49 -14
- package/src/tui/codeStreamRenderer.js +16 -5
- package/src/tui/codeStreamRenderer.ts +14 -4
- package/src/tui/prompt.js +4 -2
- package/src/tui/sessionSidebar.js +10 -2
- package/src/tui/sessionSidebar.ts +10 -3
- package/src/tui/stageSurface.js +27 -1
- package/src/tui/text.d.ts +1 -0
- package/src/tui/turnRail.js +274 -0
- package/src/tui/turnRail.ts +334 -0
- package/src/types/contracts.ts +103 -0
- package/src/verificationPlan.js +141 -0
- package/src/verificationPlan.ts +166 -0
- package/src/toolPacks.d.ts +0 -10
package/LICENSE
CHANGED
package/package.json
CHANGED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { packForTool } from './toolPacks.js';
|
|
2
|
+
import { refineToolDecision } from './smartToolsUse.js';
|
|
3
|
+
/** Schema selection is a context optimization, never an authorization mechanism. */
|
|
4
|
+
export const DISCOVERY_CONTROLS = ['tool_search', 'update_plan', 'request_decision'];
|
|
5
|
+
export class SmartTools {
|
|
6
|
+
schemaOrder = [];
|
|
7
|
+
refine(decision, context) {
|
|
8
|
+
// An explicit selection must not silently discard tools beyond a fixed cap.
|
|
9
|
+
const refined = refineToolDecision(decision, context);
|
|
10
|
+
const admittedTools = context.admittedTools ?? new Set();
|
|
11
|
+
return decision.source === 'request'
|
|
12
|
+
? { ...refined, tools: decision.tools.filter((name) => !admittedTools.has(name)), deferred: [] }
|
|
13
|
+
: refined;
|
|
14
|
+
}
|
|
15
|
+
schemas(eligible, selected, packs, grantAll = false) {
|
|
16
|
+
const definitions = new Map(eligible.map((definition) => [definition.name, definition]));
|
|
17
|
+
const requested = new Set(DISCOVERY_CONTROLS);
|
|
18
|
+
for (const name of selected)
|
|
19
|
+
requested.add(name);
|
|
20
|
+
for (const definition of eligible) {
|
|
21
|
+
const pack = packForTool(definition.name);
|
|
22
|
+
if (grantAll || (pack && packs.has(pack)))
|
|
23
|
+
requested.add(definition.name);
|
|
24
|
+
}
|
|
25
|
+
for (const name of requested) {
|
|
26
|
+
if (definitions.has(name) && !this.schemaOrder.includes(name))
|
|
27
|
+
this.schemaOrder.push(name);
|
|
28
|
+
}
|
|
29
|
+
// Revalidate on every turn: a saved ID cannot override a changed policy.
|
|
30
|
+
return this.schemaOrder.filter((name) => requested.has(name) && definitions.has(name))
|
|
31
|
+
.map((name) => definitions.get(name));
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { packForTool } from './toolPacks.js';
|
|
2
|
+
import { refineToolDecision } from './smartToolsUse.js';
|
|
3
|
+
import type { SmartToolsContext, RefinedToolDecision } from './smartToolsUse.js';
|
|
4
|
+
import type { ToolDecision } from './decideTools.js';
|
|
5
|
+
|
|
6
|
+
/** Schema selection is a context optimization, never an authorization mechanism. */
|
|
7
|
+
export const DISCOVERY_CONTROLS = ['tool_search', 'update_plan', 'request_decision'] as const;
|
|
8
|
+
|
|
9
|
+
export class SmartTools {
|
|
10
|
+
private readonly schemaOrder: string[] = [];
|
|
11
|
+
|
|
12
|
+
refine(decision: ToolDecision, context: SmartToolsContext): RefinedToolDecision {
|
|
13
|
+
// An explicit selection must not silently discard tools beyond a fixed cap.
|
|
14
|
+
const refined = refineToolDecision(decision, context);
|
|
15
|
+
const admittedTools = context.admittedTools ?? new Set<string>();
|
|
16
|
+
return decision.source === 'request'
|
|
17
|
+
? { ...refined, tools: decision.tools.filter((name) => !admittedTools.has(name)), deferred: [] }
|
|
18
|
+
: refined;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
schemas<T extends { name: string }>(eligible: readonly T[], selected: ReadonlySet<string>,
|
|
22
|
+
packs: ReadonlySet<string>, grantAll = false): T[] {
|
|
23
|
+
const definitions = new Map(eligible.map((definition) => [definition.name, definition]));
|
|
24
|
+
const requested = new Set<string>(DISCOVERY_CONTROLS);
|
|
25
|
+
for (const name of selected) requested.add(name);
|
|
26
|
+
for (const definition of eligible) {
|
|
27
|
+
const pack = packForTool(definition.name);
|
|
28
|
+
if (grantAll || (pack && packs.has(pack))) requested.add(definition.name);
|
|
29
|
+
}
|
|
30
|
+
for (const name of requested) {
|
|
31
|
+
if (definitions.has(name) && !this.schemaOrder.includes(name)) this.schemaOrder.push(name);
|
|
32
|
+
}
|
|
33
|
+
// Revalidate on every turn: a saved ID cannot override a changed policy.
|
|
34
|
+
return this.schemaOrder.filter((name) => requested.has(name) && definitions.has(name))
|
|
35
|
+
.map((name) => definitions.get(name)!);
|
|
36
|
+
}
|
|
37
|
+
}
|
package/src/acp/client.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
|
+
import fsSync from 'node:fs';
|
|
2
3
|
import fs from 'node:fs/promises';
|
|
4
|
+
import os from 'node:os';
|
|
3
5
|
import path from 'node:path';
|
|
4
6
|
import { ACP_ERROR_CODES, ACP_METHODS, ACP_PROTOCOL_VERSION, extractAcpSessionModels, isJsonRpcRequest, isJsonRpcResponse } from './protocol.js';
|
|
5
7
|
function createAbortError(message = 'ACP operation aborted by user') {
|
|
@@ -104,11 +106,13 @@ export class AcpClient {
|
|
|
104
106
|
if (this.closed)
|
|
105
107
|
return;
|
|
106
108
|
this.buffer += chunk;
|
|
109
|
+
this.notifyPendingActivity();
|
|
107
110
|
void this.drain();
|
|
108
111
|
});
|
|
109
112
|
child.stderr.setEncoding('utf8');
|
|
110
113
|
child.stderr.on('data', (chunk) => {
|
|
111
114
|
this.stderrTail = `${this.stderrTail}${chunk}`.slice(-MAX_STDERR_CHARS);
|
|
115
|
+
this.notifyPendingActivity();
|
|
112
116
|
});
|
|
113
117
|
child.on('error', (error) => this.failAll(new Error(`agent process failed: ${error.message}`)));
|
|
114
118
|
child.on('exit', (code, exitSignal) => {
|
|
@@ -200,6 +204,7 @@ export class AcpClient {
|
|
|
200
204
|
const collector = (update) => {
|
|
201
205
|
if (signal?.aborted)
|
|
202
206
|
return;
|
|
207
|
+
this.notifyPendingActivity();
|
|
203
208
|
// handleLine already notifies options.onUpdate for this session. Calling
|
|
204
209
|
// it again here duplicated every live chunk and file-action frame.
|
|
205
210
|
if (update.sessionUpdate === 'agent_message_chunk' && update.content.type === 'text') {
|
|
@@ -210,6 +215,7 @@ export class AcpClient {
|
|
|
210
215
|
this.updateListener = (sessionIdFromEvent, update) => {
|
|
211
216
|
if (signal?.aborted)
|
|
212
217
|
return;
|
|
218
|
+
this.notifyPendingActivity();
|
|
213
219
|
previous?.(sessionIdFromEvent, update);
|
|
214
220
|
if (sessionIdFromEvent === sessionId)
|
|
215
221
|
collector(update);
|
|
@@ -227,7 +233,10 @@ export class AcpClient {
|
|
|
227
233
|
const response = await this.request(ACP_METHODS.PROMPT, {
|
|
228
234
|
sessionId,
|
|
229
235
|
prompt: blocks
|
|
230
|
-
}, this.options.promptTimeoutMs ?? 15 * 60 * 1000, signal
|
|
236
|
+
}, this.options.promptTimeoutMs ?? 15 * 60 * 1000, signal, {
|
|
237
|
+
sessionId,
|
|
238
|
+
inactivityTimeoutMs: this.options.inactivityTimeoutMs ?? 120_000
|
|
239
|
+
});
|
|
231
240
|
return {
|
|
232
241
|
stopReason: response?.stopReason ?? 'end_turn',
|
|
233
242
|
...(response?.usage ? { usage: response.usage } : {}),
|
|
@@ -456,6 +465,10 @@ export class AcpClient {
|
|
|
456
465
|
if (!pending)
|
|
457
466
|
return;
|
|
458
467
|
clearTimeout(pending.timer);
|
|
468
|
+
if (pending.inactivityTimer)
|
|
469
|
+
clearTimeout(pending.inactivityTimer);
|
|
470
|
+
if (pending.snifferInterval)
|
|
471
|
+
clearInterval(pending.snifferInterval);
|
|
459
472
|
pending.cleanup?.();
|
|
460
473
|
this.pending.delete(response.id);
|
|
461
474
|
if (response.error) {
|
|
@@ -467,7 +480,89 @@ export class AcpClient {
|
|
|
467
480
|
}
|
|
468
481
|
pending.resolve(response.result);
|
|
469
482
|
}
|
|
470
|
-
|
|
483
|
+
notifyPendingActivity() {
|
|
484
|
+
for (const pending of this.pending.values()) {
|
|
485
|
+
pending.notifyActivity?.();
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
inspectPeerDiagnostics(sessionId) {
|
|
489
|
+
if (this.exitError) {
|
|
490
|
+
return this.exitError.message;
|
|
491
|
+
}
|
|
492
|
+
if (this.child && this.child.exitCode !== null) {
|
|
493
|
+
const detail = this.stderrTail.trim() || `exit code ${this.child.exitCode}`;
|
|
494
|
+
return `agent process exited: ${detail}`;
|
|
495
|
+
}
|
|
496
|
+
if (this.stderrTail) {
|
|
497
|
+
const fatalPatterns = [
|
|
498
|
+
/free usage limit reached/i,
|
|
499
|
+
/ai_apicallerror/i,
|
|
500
|
+
/ai_retryerror/i,
|
|
501
|
+
/rate limit/i,
|
|
502
|
+
/quota exceeded/i,
|
|
503
|
+
/insufficient_quota/i,
|
|
504
|
+
/unauthorized/i,
|
|
505
|
+
/authentication failed/i,
|
|
506
|
+
/invalid api key/i
|
|
507
|
+
];
|
|
508
|
+
for (const pat of fatalPatterns) {
|
|
509
|
+
if (pat.test(this.stderrTail)) {
|
|
510
|
+
const match = this.stderrTail.split('\n').find(l => pat.test(l));
|
|
511
|
+
if (match)
|
|
512
|
+
return match.trim();
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
const cmd = (this.options.command || '').toLowerCase();
|
|
517
|
+
const isOpencode = cmd.includes('opencode')
|
|
518
|
+
|| (this.options.args && this.options.args.some(a => String(a).toLowerCase().includes('opencode')));
|
|
519
|
+
if (isOpencode) {
|
|
520
|
+
const opencodeErr = this.inspectOpencodeLog(sessionId);
|
|
521
|
+
if (opencodeErr)
|
|
522
|
+
return opencodeErr;
|
|
523
|
+
}
|
|
524
|
+
return null;
|
|
525
|
+
}
|
|
526
|
+
inspectOpencodeLog(sessionId) {
|
|
527
|
+
try {
|
|
528
|
+
const logPath = path.join(os.homedir(), '.local', 'share', 'opencode', 'log', 'opencode.log');
|
|
529
|
+
if (!fsSync.existsSync(logPath))
|
|
530
|
+
return null;
|
|
531
|
+
const stat = fsSync.statSync(logPath);
|
|
532
|
+
if (stat.size === 0)
|
|
533
|
+
return null;
|
|
534
|
+
const readBytes = Math.min(stat.size, 65536);
|
|
535
|
+
const buffer = Buffer.alloc(readBytes);
|
|
536
|
+
const fd = fsSync.openSync(logPath, 'r');
|
|
537
|
+
try {
|
|
538
|
+
fsSync.readSync(fd, buffer, 0, readBytes, stat.size - readBytes);
|
|
539
|
+
}
|
|
540
|
+
finally {
|
|
541
|
+
fsSync.closeSync(fd);
|
|
542
|
+
}
|
|
543
|
+
const text = buffer.toString('utf8');
|
|
544
|
+
const lines = text.split('\n').filter(Boolean);
|
|
545
|
+
for (let i = lines.length - 1; i >= Math.max(0, lines.length - 60); i--) {
|
|
546
|
+
const line = lines[i];
|
|
547
|
+
if (!line)
|
|
548
|
+
continue;
|
|
549
|
+
if (sessionId && !line.includes(sessionId))
|
|
550
|
+
continue;
|
|
551
|
+
if (line.includes('level=ERROR') || line.includes('AI_APICallError') || line.includes('Free usage limit reached') || line.includes('AI_RetryError')) {
|
|
552
|
+
const match = line.match(/error\.error="([^"]+)"/) || line.match(/message="([^"]+)"/);
|
|
553
|
+
if (match && match[1]) {
|
|
554
|
+
return match[1].replace(/\\n/g, ' ').trim();
|
|
555
|
+
}
|
|
556
|
+
return line.trim();
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
catch {
|
|
561
|
+
// ignore log inspection errors
|
|
562
|
+
}
|
|
563
|
+
return null;
|
|
564
|
+
}
|
|
565
|
+
request(method, params, timeoutMs, signal, options) {
|
|
471
566
|
if (signal?.aborted)
|
|
472
567
|
return Promise.reject(createAbortError());
|
|
473
568
|
if (!this.child || this.closed)
|
|
@@ -476,8 +571,14 @@ export class AcpClient {
|
|
|
476
571
|
return Promise.reject(this.exitError);
|
|
477
572
|
const id = this.nextId++;
|
|
478
573
|
return new Promise((resolve, reject) => {
|
|
574
|
+
let inactivityTimer;
|
|
575
|
+
let snifferInterval;
|
|
479
576
|
const cleanup = () => {
|
|
480
577
|
signal?.removeEventListener('abort', onAbort);
|
|
578
|
+
if (inactivityTimer)
|
|
579
|
+
clearTimeout(inactivityTimer);
|
|
580
|
+
if (snifferInterval)
|
|
581
|
+
clearInterval(snifferInterval);
|
|
481
582
|
};
|
|
482
583
|
const onAbort = () => {
|
|
483
584
|
clearTimeout(timer);
|
|
@@ -488,17 +589,65 @@ export class AcpClient {
|
|
|
488
589
|
const timer = setTimeout(() => {
|
|
489
590
|
cleanup();
|
|
490
591
|
this.pending.delete(id);
|
|
491
|
-
|
|
592
|
+
const diag = this.inspectPeerDiagnostics(options?.sessionId);
|
|
593
|
+
if (diag) {
|
|
594
|
+
reject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${diag}`));
|
|
595
|
+
}
|
|
596
|
+
else {
|
|
597
|
+
reject(new Error(`${method} timed out after ${timeoutMs}ms`));
|
|
598
|
+
}
|
|
492
599
|
}, timeoutMs);
|
|
493
600
|
if (typeof timer.unref === 'function')
|
|
494
601
|
timer.unref();
|
|
602
|
+
const resetInactivity = () => {
|
|
603
|
+
const timeoutMsInact = options?.inactivityTimeoutMs;
|
|
604
|
+
if (!timeoutMsInact)
|
|
605
|
+
return;
|
|
606
|
+
if (inactivityTimer)
|
|
607
|
+
clearTimeout(inactivityTimer);
|
|
608
|
+
inactivityTimer = setTimeout(() => {
|
|
609
|
+
cleanup();
|
|
610
|
+
this.pending.delete(id);
|
|
611
|
+
const diag = this.inspectPeerDiagnostics(options?.sessionId);
|
|
612
|
+
if (diag) {
|
|
613
|
+
reject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${diag}`));
|
|
614
|
+
}
|
|
615
|
+
else {
|
|
616
|
+
reject(new Error(`${method} stalled: no activity from peer in ${Math.round(timeoutMsInact / 1000)}s`));
|
|
617
|
+
}
|
|
618
|
+
}, timeoutMsInact);
|
|
619
|
+
if (typeof inactivityTimer.unref === 'function')
|
|
620
|
+
inactivityTimer.unref();
|
|
621
|
+
};
|
|
622
|
+
const sid = options?.sessionId;
|
|
623
|
+
if (sid) {
|
|
624
|
+
snifferInterval = setInterval(() => {
|
|
625
|
+
const fatalDiag = this.inspectPeerDiagnostics(sid);
|
|
626
|
+
if (fatalDiag) {
|
|
627
|
+
cleanup();
|
|
628
|
+
clearTimeout(timer);
|
|
629
|
+
this.pending.delete(id);
|
|
630
|
+
try {
|
|
631
|
+
this.notifyCancel(sid);
|
|
632
|
+
}
|
|
633
|
+
catch { /* ignore */ }
|
|
634
|
+
reject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${fatalDiag}`));
|
|
635
|
+
}
|
|
636
|
+
}, 1500);
|
|
637
|
+
if (typeof snifferInterval.unref === 'function')
|
|
638
|
+
snifferInterval.unref();
|
|
639
|
+
}
|
|
640
|
+
resetInactivity();
|
|
495
641
|
signal?.addEventListener('abort', onAbort, { once: true });
|
|
496
642
|
this.pending.set(id, {
|
|
497
643
|
resolve: (value) => resolve(value),
|
|
498
644
|
reject,
|
|
499
645
|
timer,
|
|
646
|
+
inactivityTimer,
|
|
647
|
+
snifferInterval,
|
|
500
648
|
method,
|
|
501
|
-
cleanup
|
|
649
|
+
cleanup,
|
|
650
|
+
notifyActivity: resetInactivity
|
|
502
651
|
});
|
|
503
652
|
this.write({ jsonrpc: '2.0', id, method, params });
|
|
504
653
|
});
|
|
@@ -507,6 +656,10 @@ export class AcpClient {
|
|
|
507
656
|
this.exitError = error;
|
|
508
657
|
for (const [id, pending] of this.pending) {
|
|
509
658
|
clearTimeout(pending.timer);
|
|
659
|
+
if (pending.inactivityTimer)
|
|
660
|
+
clearTimeout(pending.inactivityTimer);
|
|
661
|
+
if (pending.snifferInterval)
|
|
662
|
+
clearInterval(pending.snifferInterval);
|
|
510
663
|
pending.cleanup?.();
|
|
511
664
|
pending.reject(error);
|
|
512
665
|
this.pending.delete(id);
|
package/src/acp/client.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
2
|
import type { ChildProcessWithoutNullStreams } from 'node:child_process';
|
|
3
|
+
import fsSync from 'node:fs';
|
|
3
4
|
import fs from 'node:fs/promises';
|
|
5
|
+
import os from 'node:os';
|
|
4
6
|
import path from 'node:path';
|
|
5
7
|
import {
|
|
6
8
|
ACP_ERROR_CODES,
|
|
@@ -38,6 +40,7 @@ export interface AcpClientOptions {
|
|
|
38
40
|
env?: NodeJS.ProcessEnv;
|
|
39
41
|
clientVersion?: string;
|
|
40
42
|
promptTimeoutMs?: number;
|
|
43
|
+
inactivityTimeoutMs?: number;
|
|
41
44
|
allowHostTools?: boolean;
|
|
42
45
|
permissionHandler?: (request: RequestPermissionRequest) => Promise<RequestPermissionResponse['outcome']>;
|
|
43
46
|
onUpdate?: (sessionId: string, update: SessionUpdate) => void;
|
|
@@ -55,8 +58,11 @@ interface PendingRequest {
|
|
|
55
58
|
resolve: (value: unknown) => void;
|
|
56
59
|
reject: (error: Error) => void;
|
|
57
60
|
timer: NodeJS.Timeout;
|
|
61
|
+
inactivityTimer?: NodeJS.Timeout | undefined;
|
|
62
|
+
snifferInterval?: NodeJS.Timeout | undefined;
|
|
58
63
|
method: string;
|
|
59
|
-
cleanup?: () => void;
|
|
64
|
+
cleanup?: (() => void) | undefined;
|
|
65
|
+
notifyActivity?: (() => void) | undefined;
|
|
60
66
|
}
|
|
61
67
|
|
|
62
68
|
function createAbortError(message = 'ACP operation aborted by user'): Error {
|
|
@@ -172,11 +178,13 @@ export class AcpClient {
|
|
|
172
178
|
child.stdout.on('data', (chunk: string) => {
|
|
173
179
|
if (this.closed) return;
|
|
174
180
|
this.buffer += chunk;
|
|
181
|
+
this.notifyPendingActivity();
|
|
175
182
|
void this.drain();
|
|
176
183
|
});
|
|
177
184
|
child.stderr.setEncoding('utf8');
|
|
178
185
|
child.stderr.on('data', (chunk: string) => {
|
|
179
186
|
this.stderrTail = `${this.stderrTail}${chunk}`.slice(-MAX_STDERR_CHARS);
|
|
187
|
+
this.notifyPendingActivity();
|
|
180
188
|
});
|
|
181
189
|
child.on('error', (error) => this.failAll(new Error(`agent process failed: ${error.message}`)));
|
|
182
190
|
child.on('exit', (code, exitSignal) => {
|
|
@@ -274,6 +282,7 @@ export class AcpClient {
|
|
|
274
282
|
let collected = '';
|
|
275
283
|
const collector = (update: SessionUpdate): void => {
|
|
276
284
|
if (signal?.aborted) return;
|
|
285
|
+
this.notifyPendingActivity();
|
|
277
286
|
// handleLine already notifies options.onUpdate for this session. Calling
|
|
278
287
|
// it again here duplicated every live chunk and file-action frame.
|
|
279
288
|
if (update.sessionUpdate === 'agent_message_chunk' && update.content.type === 'text') {
|
|
@@ -283,6 +292,7 @@ export class AcpClient {
|
|
|
283
292
|
const previous = this.updateListener;
|
|
284
293
|
this.updateListener = (sessionIdFromEvent, update) => {
|
|
285
294
|
if (signal?.aborted) return;
|
|
295
|
+
this.notifyPendingActivity();
|
|
286
296
|
previous?.(sessionIdFromEvent, update);
|
|
287
297
|
if (sessionIdFromEvent === sessionId) collector(update);
|
|
288
298
|
};
|
|
@@ -298,7 +308,10 @@ export class AcpClient {
|
|
|
298
308
|
const response = await this.request<PromptResponse>(ACP_METHODS.PROMPT, {
|
|
299
309
|
sessionId,
|
|
300
310
|
prompt: blocks
|
|
301
|
-
}, this.options.promptTimeoutMs ?? 15 * 60 * 1000, signal
|
|
311
|
+
}, this.options.promptTimeoutMs ?? 15 * 60 * 1000, signal, {
|
|
312
|
+
sessionId,
|
|
313
|
+
inactivityTimeoutMs: this.options.inactivityTimeoutMs ?? 120_000
|
|
314
|
+
});
|
|
302
315
|
return {
|
|
303
316
|
stopReason: response?.stopReason ?? 'end_turn',
|
|
304
317
|
...(response?.usage ? { usage: response.usage } : {}),
|
|
@@ -516,6 +529,8 @@ export class AcpClient {
|
|
|
516
529
|
const pending = this.pending.get(response.id);
|
|
517
530
|
if (!pending) return;
|
|
518
531
|
clearTimeout(pending.timer);
|
|
532
|
+
if (pending.inactivityTimer) clearTimeout(pending.inactivityTimer);
|
|
533
|
+
if (pending.snifferInterval) clearInterval(pending.snifferInterval);
|
|
519
534
|
pending.cleanup?.();
|
|
520
535
|
this.pending.delete(response.id);
|
|
521
536
|
if (response.error) {
|
|
@@ -528,14 +543,102 @@ export class AcpClient {
|
|
|
528
543
|
pending.resolve(response.result);
|
|
529
544
|
}
|
|
530
545
|
|
|
531
|
-
private
|
|
546
|
+
private notifyPendingActivity(): void {
|
|
547
|
+
for (const pending of this.pending.values()) {
|
|
548
|
+
pending.notifyActivity?.();
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
inspectPeerDiagnostics(sessionId?: string): string | null {
|
|
553
|
+
if (this.exitError) {
|
|
554
|
+
return this.exitError.message;
|
|
555
|
+
}
|
|
556
|
+
if (this.child && this.child.exitCode !== null) {
|
|
557
|
+
const detail = this.stderrTail.trim() || `exit code ${this.child.exitCode}`;
|
|
558
|
+
return `agent process exited: ${detail}`;
|
|
559
|
+
}
|
|
560
|
+
if (this.stderrTail) {
|
|
561
|
+
const fatalPatterns = [
|
|
562
|
+
/free usage limit reached/i,
|
|
563
|
+
/ai_apicallerror/i,
|
|
564
|
+
/ai_retryerror/i,
|
|
565
|
+
/rate limit/i,
|
|
566
|
+
/quota exceeded/i,
|
|
567
|
+
/insufficient_quota/i,
|
|
568
|
+
/unauthorized/i,
|
|
569
|
+
/authentication failed/i,
|
|
570
|
+
/invalid api key/i
|
|
571
|
+
];
|
|
572
|
+
for (const pat of fatalPatterns) {
|
|
573
|
+
if (pat.test(this.stderrTail)) {
|
|
574
|
+
const match = this.stderrTail.split('\n').find(l => pat.test(l));
|
|
575
|
+
if (match) return match.trim();
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
const cmd = (this.options.command || '').toLowerCase();
|
|
580
|
+
const isOpencode = cmd.includes('opencode')
|
|
581
|
+
|| (this.options.args && this.options.args.some(a => String(a).toLowerCase().includes('opencode')));
|
|
582
|
+
if (isOpencode) {
|
|
583
|
+
const opencodeErr = this.inspectOpencodeLog(sessionId);
|
|
584
|
+
if (opencodeErr) return opencodeErr;
|
|
585
|
+
}
|
|
586
|
+
return null;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
private inspectOpencodeLog(sessionId?: string): string | null {
|
|
590
|
+
try {
|
|
591
|
+
const logPath = path.join(os.homedir(), '.local', 'share', 'opencode', 'log', 'opencode.log');
|
|
592
|
+
if (!fsSync.existsSync(logPath)) return null;
|
|
593
|
+
const stat = fsSync.statSync(logPath);
|
|
594
|
+
if (stat.size === 0) return null;
|
|
595
|
+
const readBytes = Math.min(stat.size, 65536);
|
|
596
|
+
const buffer = Buffer.alloc(readBytes);
|
|
597
|
+
const fd = fsSync.openSync(logPath, 'r');
|
|
598
|
+
try {
|
|
599
|
+
fsSync.readSync(fd, buffer, 0, readBytes, stat.size - readBytes);
|
|
600
|
+
} finally {
|
|
601
|
+
fsSync.closeSync(fd);
|
|
602
|
+
}
|
|
603
|
+
const text = buffer.toString('utf8');
|
|
604
|
+
const lines = text.split('\n').filter(Boolean);
|
|
605
|
+
for (let i = lines.length - 1; i >= Math.max(0, lines.length - 60); i--) {
|
|
606
|
+
const line = lines[i];
|
|
607
|
+
if (!line) continue;
|
|
608
|
+
if (sessionId && !line.includes(sessionId)) continue;
|
|
609
|
+
if (line.includes('level=ERROR') || line.includes('AI_APICallError') || line.includes('Free usage limit reached') || line.includes('AI_RetryError')) {
|
|
610
|
+
const match = line.match(/error\.error="([^"]+)"/) || line.match(/message="([^"]+)"/);
|
|
611
|
+
if (match && match[1]) {
|
|
612
|
+
return match[1].replace(/\\n/g, ' ').trim();
|
|
613
|
+
}
|
|
614
|
+
return line.trim();
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
} catch {
|
|
618
|
+
// ignore log inspection errors
|
|
619
|
+
}
|
|
620
|
+
return null;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
private request<T>(
|
|
624
|
+
method: string,
|
|
625
|
+
params: unknown,
|
|
626
|
+
timeoutMs: number,
|
|
627
|
+
signal?: AbortSignal,
|
|
628
|
+
options?: { sessionId?: string; inactivityTimeoutMs?: number }
|
|
629
|
+
): Promise<T> {
|
|
532
630
|
if (signal?.aborted) return Promise.reject(createAbortError());
|
|
533
631
|
if (!this.child || this.closed) return Promise.reject(new Error('agent process is not running'));
|
|
534
632
|
if (this.exitError) return Promise.reject(this.exitError);
|
|
535
633
|
const id = this.nextId++;
|
|
536
634
|
return new Promise<T>((resolve, reject) => {
|
|
635
|
+
let inactivityTimer: NodeJS.Timeout | undefined;
|
|
636
|
+
let snifferInterval: NodeJS.Timeout | undefined;
|
|
637
|
+
|
|
537
638
|
const cleanup = (): void => {
|
|
538
639
|
signal?.removeEventListener('abort', onAbort);
|
|
640
|
+
if (inactivityTimer) clearTimeout(inactivityTimer);
|
|
641
|
+
if (snifferInterval) clearInterval(snifferInterval);
|
|
539
642
|
};
|
|
540
643
|
const onAbort = (): void => {
|
|
541
644
|
clearTimeout(timer);
|
|
@@ -546,16 +649,58 @@ export class AcpClient {
|
|
|
546
649
|
const timer = setTimeout(() => {
|
|
547
650
|
cleanup();
|
|
548
651
|
this.pending.delete(id);
|
|
549
|
-
|
|
652
|
+
const diag = this.inspectPeerDiagnostics(options?.sessionId);
|
|
653
|
+
if (diag) {
|
|
654
|
+
reject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${diag}`));
|
|
655
|
+
} else {
|
|
656
|
+
reject(new Error(`${method} timed out after ${timeoutMs}ms`));
|
|
657
|
+
}
|
|
550
658
|
}, timeoutMs);
|
|
551
659
|
if (typeof timer.unref === 'function') timer.unref();
|
|
660
|
+
|
|
661
|
+
const resetInactivity = (): void => {
|
|
662
|
+
const timeoutMsInact = options?.inactivityTimeoutMs;
|
|
663
|
+
if (!timeoutMsInact) return;
|
|
664
|
+
if (inactivityTimer) clearTimeout(inactivityTimer);
|
|
665
|
+
inactivityTimer = setTimeout(() => {
|
|
666
|
+
cleanup();
|
|
667
|
+
this.pending.delete(id);
|
|
668
|
+
const diag = this.inspectPeerDiagnostics(options?.sessionId);
|
|
669
|
+
if (diag) {
|
|
670
|
+
reject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${diag}`));
|
|
671
|
+
} else {
|
|
672
|
+
reject(new Error(`${method} stalled: no activity from peer in ${Math.round(timeoutMsInact / 1000)}s`));
|
|
673
|
+
}
|
|
674
|
+
}, timeoutMsInact);
|
|
675
|
+
if (typeof inactivityTimer.unref === 'function') inactivityTimer.unref();
|
|
676
|
+
};
|
|
677
|
+
|
|
678
|
+
const sid = options?.sessionId;
|
|
679
|
+
if (sid) {
|
|
680
|
+
snifferInterval = setInterval(() => {
|
|
681
|
+
const fatalDiag = this.inspectPeerDiagnostics(sid);
|
|
682
|
+
if (fatalDiag) {
|
|
683
|
+
cleanup();
|
|
684
|
+
clearTimeout(timer);
|
|
685
|
+
this.pending.delete(id);
|
|
686
|
+
try { this.notifyCancel(sid); } catch { /* ignore */ }
|
|
687
|
+
reject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${fatalDiag}`));
|
|
688
|
+
}
|
|
689
|
+
}, 1500);
|
|
690
|
+
if (typeof snifferInterval.unref === 'function') snifferInterval.unref();
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
resetInactivity();
|
|
552
694
|
signal?.addEventListener('abort', onAbort, { once: true });
|
|
553
695
|
this.pending.set(id, {
|
|
554
696
|
resolve: (value) => resolve(value as T),
|
|
555
697
|
reject,
|
|
556
698
|
timer,
|
|
699
|
+
inactivityTimer,
|
|
700
|
+
snifferInterval,
|
|
557
701
|
method,
|
|
558
|
-
cleanup
|
|
702
|
+
cleanup,
|
|
703
|
+
notifyActivity: resetInactivity
|
|
559
704
|
});
|
|
560
705
|
this.write({ jsonrpc: '2.0', id, method, params });
|
|
561
706
|
});
|
|
@@ -565,6 +710,8 @@ export class AcpClient {
|
|
|
565
710
|
this.exitError = error;
|
|
566
711
|
for (const [id, pending] of this.pending) {
|
|
567
712
|
clearTimeout(pending.timer);
|
|
713
|
+
if (pending.inactivityTimer) clearTimeout(pending.inactivityTimer);
|
|
714
|
+
if (pending.snifferInterval) clearInterval(pending.snifferInterval);
|
|
568
715
|
pending.cleanup?.();
|
|
569
716
|
pending.reject(error);
|
|
570
717
|
this.pending.delete(id);
|