@openagents-org/agent-launcher 0.2.214 → 0.2.216

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,813 @@
1
+ /**
2
+ * Kiro CLI adapter for OpenAgents workspace.
3
+ *
4
+ * Bridges Kiro's terminal agent (`kiro-cli`, installed by cli.kiro.dev/install)
5
+ * to an OpenAgents workspace over the Agent Client Protocol:
6
+ * - polling loop + per-channel task dispatch (inherited from BaseAdapter)
7
+ * - one `kiro-cli acp` server per user message, driven with JSON-RPC over
8
+ * stdio (acp-client.js): initialize → session/new | session/load →
9
+ * session/prompt, streaming session/update frames into the channel
10
+ * - workspace tools over MCP, handed to the CLI in session/new's
11
+ * `mcpServers` — the token is passed to Kiro over stdin in the MCP
12
+ * server env; it is never in argv or written to disk by OpenAgents
13
+ * (whether Kiro persists session state including that env is up to Kiro)
14
+ * - session continuity per channel: the ACP session id is remembered and
15
+ * resumed with session/load from the same working directory
16
+ *
17
+ * Decisions worth knowing before editing this file (the verified CLI facts
18
+ * behind them are in kiro-runtime.js):
19
+ *
20
+ * ONE KIRO AGENT PROFILE PER OPENAGENTS AGENT. KIRO_AGENT (per-agent env)
21
+ * selects a Kiro agent profile with `--agent`. That profile is where the
22
+ * agent's own prompt, tools and MCP servers live — the workspace server is
23
+ * added next to them, not instead of them. Kiro silently falls back to its
24
+ * default agent for an unknown profile; the adapter refuses that turn
25
+ * rather than run an agent without its own instructions and data sources.
26
+ *
27
+ * APPROVALS ARE ANSWERED HERE. No `--trust-all-tools`: every approval the
28
+ * CLI asks for arrives as session/request_permission. Execute mode allows
29
+ * each call once (never "always", which would persist trust into the
30
+ * user's Kiro settings); plan mode allows read-only tools and the
31
+ * workspace's own tools and refuses the rest.
32
+ *
33
+ * THE BRIEFING IS PART OF THE PROMPT. ACP has no system-prompt field. The
34
+ * workspace briefing is sent as the first content block of a session's
35
+ * first turn, and again only when it changes (mode, pinned knowledge), so
36
+ * a long thread does not pay for it on every message.
37
+ *
38
+ * STOP CANCELS, THEN KILLS THE TREE. session/cancel ends the turn cleanly;
39
+ * the server is then ended with its descendants (MCP servers, shell
40
+ * commands), read from the process table while it is still alive.
41
+ */
42
+
43
+ 'use strict';
44
+
45
+ const fs = require('fs');
46
+ const os = require('os');
47
+ const path = require('path');
48
+ const crypto = require('crypto');
49
+ const { execFileSync } = require('child_process');
50
+ // spawn() here is the WSL bridge from ../wsl: same signature as
51
+ // child_process.spawn, and a straight pass-through unless the resolved CLI
52
+ // lives on the other side of the Windows/WSL boundary.
53
+ const { spawn } = require('../wsl');
54
+
55
+ const BaseAdapter = require('./base');
56
+ const { AcpClient, AcpRpcError, AcpClosedError, AcpTimeoutError } = require('./acp-client');
57
+ const { formatAttachmentsForPrompt, SESSION_DEFAULT_RE, generateSessionTitle, redactSecrets } = require('./utils');
58
+ const { buildClaudeSystemPrompt } = require('./workspace-prompt');
59
+ const { classifyRunFailure } = require('./run-failure');
60
+ const { REASON } = require('./health-status');
61
+ const { defaultAgentWorkdir, whichBinary, getEnhancedEnv } = require('../paths');
62
+ // The process-table walk is the one the Qoder adapter verified for CLIs that
63
+ // leave MCP servers and detached shell commands behind.
64
+ const { descendantsOf, parseProcessTable } = require('./qoder-runtime');
65
+ const {
66
+ KIRO_BINARY,
67
+ KIRO_MIN_VERSION,
68
+ ACP_PROTOCOL_VERSION,
69
+ WORKSPACE_MCP_NAME,
70
+ KIRO_GUIDANCE,
71
+ installHint,
72
+ classifyKiroVersion,
73
+ resolveKiroSettings,
74
+ buildKiroArgs,
75
+ toAcpMcpServer,
76
+ truncate,
77
+ interpretUpdate,
78
+ permissionOutcome,
79
+ isStaleSessionError,
80
+ rpcErrorText,
81
+ agentNotFoundMessage,
82
+ } = require('./kiro-runtime');
83
+
84
+ const IS_WINDOWS = process.platform === 'win32';
85
+
86
+ // Handshake budget: initialize + session/new start the CLI and every MCP
87
+ // server the agent profile declares, which can take a while on a cold start.
88
+ const HANDSHAKE_TIMEOUT_MS = 120000;
89
+
90
+ // Idle watchdog, as in the Qoder adapter: with no frame for this long we nudge
91
+ // the channel, and after MAX consecutive silences we end a run that is
92
+ // probably wedged. It pauses while a tool call is out.
93
+ const WATCHDOG_INTERVAL_MS = 15000;
94
+ const WATCHDOG_NUDGE_AT = 2; // ~30s of silence → "still working"
95
+ const WATCHDOG_MAX = 20; // ~5 min of silence → kill
96
+
97
+ const VERSION_PROBE_TTL_MS = 60000;
98
+ const STOP_GRACE_MS = 3000;
99
+ const CANCEL_GRACE_MS = 1500;
100
+ const STDERR_CAP = 8000;
101
+ const THINKING_PREVIEW = 600;
102
+
103
+ class KiroAdapter extends BaseAdapter {
104
+ /**
105
+ * @param {object} opts - BaseAdapter opts plus:
106
+ * @param {Set} [opts.disabledModules]
107
+ * @param {string} [opts.workingDir]
108
+ */
109
+ constructor(opts) {
110
+ super(opts);
111
+ this.disabledModules = opts.disabledModules || new Set();
112
+ this._usesPinnedContext = true;
113
+ // channel → { sessionId, workingDir, agent, briefing }
114
+ this._channelSessions = {};
115
+ // channel → child process (the in-flight `kiro-cli acp`)
116
+ this._channelProcesses = {};
117
+ // channel → { proc, client, sessionId, settled }
118
+ this._channelRuns = {};
119
+ this._sessionsFile = path.join(
120
+ os.homedir(), '.openagents', 'sessions',
121
+ `${this.workspaceId}_${this.agentName}_kiro.json`,
122
+ );
123
+ this._isWindows = IS_WINDOWS;
124
+ this._versionProbe = null; // { at, bin, version, supported }
125
+ this._watchdogIntervalMs = WATCHDOG_INTERVAL_MS;
126
+ this._watchdogMax = WATCHDOG_MAX;
127
+ this._handshakeTimeoutMs = HANDSHAKE_TIMEOUT_MS;
128
+ this._loadSessions();
129
+ }
130
+
131
+ /** The model the CLI is started with, so the workspace never shows another one. */
132
+ modelLabel() {
133
+ return resolveKiroSettings(this.agentEnv, this.workspaceModel).model || null;
134
+ }
135
+
136
+ // ------------------------------------------------------------------
137
+ // Session persistence (bound to the working directory and agent profile)
138
+ // ------------------------------------------------------------------
139
+
140
+ _loadSessions() {
141
+ try {
142
+ if (fs.existsSync(this._sessionsFile)) {
143
+ const data = JSON.parse(fs.readFileSync(this._sessionsFile, 'utf-8'));
144
+ if (data && typeof data === 'object') {
145
+ Object.assign(this._channelSessions, data);
146
+ this._log(`Loaded ${Object.keys(data).length} Kiro session(s)`);
147
+ }
148
+ }
149
+ } catch {
150
+ this._log('Could not load Kiro sessions file, starting fresh');
151
+ }
152
+ }
153
+
154
+ _saveSessions() {
155
+ try {
156
+ fs.mkdirSync(path.dirname(this._sessionsFile), { recursive: true });
157
+ fs.writeFileSync(this._sessionsFile, JSON.stringify(this._channelSessions));
158
+ } catch {}
159
+ }
160
+
161
+ /**
162
+ * A resumable session for this channel, or null. Kiro files sessions per
163
+ * working directory, and a session started under another agent profile
164
+ * carries that profile's instructions — neither is resumed across a change.
165
+ */
166
+ _resumableSession(channel, workingDir, agent) {
167
+ const entry = this._channelSessions[channel];
168
+ if (!entry || !entry.sessionId) return null;
169
+ if (entry.workingDir && workingDir && entry.workingDir !== workingDir) return null;
170
+ if ((entry.agent || null) !== (agent || null)) return null;
171
+ return entry;
172
+ }
173
+
174
+ _rememberSession(channel, record) {
175
+ if (!record || !record.sessionId) return;
176
+ this._channelSessions[channel] = record;
177
+ this._saveSessions();
178
+ }
179
+
180
+ _clearSession(channel) {
181
+ if (this._channelSessions[channel]) {
182
+ delete this._channelSessions[channel];
183
+ this._saveSessions();
184
+ }
185
+ }
186
+
187
+ // ------------------------------------------------------------------
188
+ // Binary + version
189
+ // ------------------------------------------------------------------
190
+
191
+ /**
192
+ * Locate the CLI through the shared lookup: ~/.local/bin (the official
193
+ * install.sh), /usr/local/bin (its system-wide mode) and
194
+ * %ProgramFiles%\Kiro-Cli (install.ps1's MSI) are all in getKnownBinDirs,
195
+ * so there is no private candidate list here (see CLAUDE.md).
196
+ */
197
+ _findKiroBinary() {
198
+ return whichBinary(KIRO_BINARY) || null;
199
+ }
200
+
201
+ /** Daemon gate before join: a missing CLI is reported, not joined. */
202
+ preflight() {
203
+ const bin = this._findKiroBinary();
204
+ if (!bin) {
205
+ return {
206
+ ok: false,
207
+ reason: REASON.RUNTIME_MISSING,
208
+ message: `Kiro CLI not found — install it with: ${installHint()}`,
209
+ };
210
+ }
211
+ this._log(`Kiro CLI resolved: ${bin}`);
212
+ return { ok: true };
213
+ }
214
+
215
+ /** Run `--version` and return raw output. Isolated for testing. */
216
+ _readVersionRaw(bin) {
217
+ try {
218
+ return execFileSync(bin, ['--version'], {
219
+ encoding: 'utf-8', timeout: 15000, windowsHide: true, env: getEnhancedEnv(this.agentEnv),
220
+ });
221
+ } catch (e) {
222
+ return (e && (e.stdout || e.stderr)) ? String(e.stdout || e.stderr) : '';
223
+ }
224
+ }
225
+
226
+ _checkVersion(bin) {
227
+ const now = Date.now();
228
+ if (this._versionProbe && this._versionProbe.bin === bin && now - this._versionProbe.at < VERSION_PROBE_TTL_MS) {
229
+ return this._versionProbe;
230
+ }
231
+ const verdict = classifyKiroVersion(this._readVersionRaw(bin));
232
+ this._versionProbe = { ...verdict, bin, at: now };
233
+ return this._versionProbe;
234
+ }
235
+
236
+ // ------------------------------------------------------------------
237
+ // Workspace MCP server
238
+ // ------------------------------------------------------------------
239
+
240
+ /**
241
+ * The workspace MCP server: this package's own CLI, run by the launcher's
242
+ * portable Node when present, else the one running the daemon. Returned in
243
+ * the ACP stdio shape; null when the CLI cannot be located (the turn runs
244
+ * without workspace tools rather than not at all).
245
+ */
246
+ _workspaceMcpServer(channel) {
247
+ const entry = path.resolve(__dirname, '..', '..', 'bin', 'agent-connector.js');
248
+ if (!fs.existsSync(entry)) {
249
+ this._log('Could not find the agent-connector CLI — workspace MCP tools are unavailable this run', 'warn');
250
+ return null;
251
+ }
252
+ const args = [
253
+ entry, 'mcp-server',
254
+ '--workspace-id', this.workspaceId,
255
+ '--channel-name', channel,
256
+ '--agent-name', this.agentName,
257
+ '--endpoint', this.endpoint,
258
+ ];
259
+ if (this.disabledModules.has('files')) args.push('--disable-files');
260
+ if (this.disabledModules.has('browser')) args.push('--disable-browser');
261
+ if (this.disabledModules.has('knowledge')) args.push('--disable-knowledge');
262
+ const env = { OA_WORKSPACE_TOKEN: this.token };
263
+ const requester = this.requesterEmailFor(channel);
264
+ if (requester) env.OPENAGENTS_REQUESTER_EMAIL = requester;
265
+ return toAcpMcpServer(WORKSPACE_MCP_NAME, { command: this._nodeBin(), args, env });
266
+ }
267
+
268
+ /** The launcher's portable Node when present, else the one running the daemon. */
269
+ _nodeBin() {
270
+ const root = path.join(os.homedir(), '.openagents', 'nodejs');
271
+ const candidates = this._isWindows
272
+ ? [path.join(root, 'node.exe')]
273
+ : [path.join(root, 'node'), path.join(root, 'bin', 'node')];
274
+ return candidates.find((c) => fs.existsSync(c)) || process.execPath;
275
+ }
276
+
277
+ // ------------------------------------------------------------------
278
+ // Prompt assembly
279
+ // ------------------------------------------------------------------
280
+
281
+ /** Recent channel chat, to seed a fresh session (a resumed one has it). */
282
+ async _buildChannelRecap(channel, currentMessage) {
283
+ try {
284
+ const messages = await this.client.getRecentMessages(this.workspaceId, channel, this.token, 30);
285
+ if (!messages || messages.length === 0) return null;
286
+ const lines = [];
287
+ for (const m of messages) {
288
+ const mt = m.messageType || 'chat';
289
+ if (mt === 'status' || mt === 'thinking' || mt === 'loading' || mt === 'todos') continue;
290
+ const text = (m.content || '').trim();
291
+ if (!text || text === currentMessage) continue;
292
+ const who = m.senderType === 'human' ? (m.senderName || 'user') : (m.senderName || 'agent');
293
+ lines.push(`[${who}] ${truncate(text, 800)}`);
294
+ }
295
+ if (lines.length === 0) return null;
296
+ return 'Recent conversation in this channel for context:\n\n' + lines.slice(-12).join('\n');
297
+ } catch {
298
+ return null;
299
+ }
300
+ }
301
+
302
+ _dirExists(p) {
303
+ try { return fs.statSync(p).isDirectory(); } catch { return false; }
304
+ }
305
+
306
+ // ------------------------------------------------------------------
307
+ // Shutdown + stop
308
+ // ------------------------------------------------------------------
309
+
310
+ stop() {
311
+ super.stop();
312
+ void this._stopAllProcesses('Agent stopped.');
313
+ }
314
+
315
+ async _stopAllProcesses(message = 'Execution stopped.') {
316
+ const entries = Object.entries(this._channelProcesses);
317
+ if (!entries.length) return;
318
+ this._log(`Stopping ${entries.length} running Kiro process(es)...`);
319
+ for (const [channel, proc] of entries) {
320
+ this._stoppingChannels.add(channel);
321
+ await this._stopProcess(proc);
322
+ delete this._channelProcesses[channel];
323
+ delete this._channelQueues[channel];
324
+ try { await this.sendResponse(channel, message); } catch {}
325
+ }
326
+ }
327
+
328
+ /**
329
+ * End a turn's `kiro-cli acp` and everything it started. A turn still
330
+ * running is cancelled through ACP first, so the session records the
331
+ * interruption and stays resumable. Resolves true once the CLI is gone.
332
+ */
333
+ async _stopProcess(proc) {
334
+ if (!proc || proc.exitCode !== null || proc.signalCode) return true;
335
+ const run = Object.values(this._channelRuns).find((r) => r && r.proc === proc);
336
+ if (run && run.client && run.sessionId && !run.client.closed && !run.done) {
337
+ run.client.notify('session/cancel', { sessionId: run.sessionId });
338
+ await Promise.race([run.settled, this._sleep(CANCEL_GRACE_MS)]);
339
+ }
340
+ return this._killTree(proc);
341
+ }
342
+
343
+ async _killTree(proc) {
344
+ if (!proc || proc.exitCode !== null || proc.signalCode) return true;
345
+ if (this._isWindows) {
346
+ this._taskkill(proc.pid);
347
+ let exited = await this._waitExit(proc, STOP_GRACE_MS);
348
+ if (!exited) {
349
+ try { proc.kill(); } catch {}
350
+ exited = await this._waitExit(proc, 1000);
351
+ }
352
+ return exited;
353
+ }
354
+
355
+ const groups = new Set([proc.pid]);
356
+ const pids = new Set();
357
+ for (const d of descendantsOf(this._processTable(), proc.pid)) {
358
+ pids.add(d.pid);
359
+ if (d.pgid > 1 && d.pgid !== process.pid) groups.add(d.pgid);
360
+ }
361
+ const signal = (sig) => {
362
+ for (const g of groups) { try { process.kill(-g, sig); } catch {} }
363
+ for (const p of pids) { try { process.kill(p, sig); } catch {} }
364
+ try { proc.kill(sig); } catch {}
365
+ };
366
+
367
+ signal('SIGTERM');
368
+ if (await this._waitExit(proc, STOP_GRACE_MS) && ![...pids].some((p) => this._alive(p))) return true;
369
+ signal('SIGKILL');
370
+ return this._waitExit(proc, 1000);
371
+ }
372
+
373
+ /** Kill a Windows process tree. Isolated for testing. */
374
+ _taskkill(pid) {
375
+ try {
376
+ execFileSync('taskkill', ['/F', '/T', '/PID', String(pid)], { timeout: 5000, windowsHide: true });
377
+ } catch {}
378
+ }
379
+
380
+ /** The process table as { pid, ppid, pgid } rows. Isolated for testing. */
381
+ _processTable() {
382
+ try {
383
+ return parseProcessTable(execFileSync('ps', ['-A', '-o', 'pid=,ppid=,pgid='], { encoding: 'utf-8', timeout: 3000 }));
384
+ } catch {
385
+ return [];
386
+ }
387
+ }
388
+
389
+ _alive(pid) {
390
+ try { process.kill(pid, 0); return true; } catch (e) { return !!(e && e.code === 'EPERM'); }
391
+ }
392
+
393
+ _waitExit(proc, ms) {
394
+ return new Promise((resolve) => {
395
+ if (proc.exitCode !== null || proc.signalCode) { resolve(true); return; }
396
+ const t = setTimeout(() => resolve(proc.exitCode !== null || !!proc.signalCode), ms);
397
+ proc.once('exit', () => { clearTimeout(t); resolve(true); });
398
+ });
399
+ }
400
+
401
+ // ------------------------------------------------------------------
402
+ // One turn over ACP
403
+ // ------------------------------------------------------------------
404
+
405
+ /** Spawn `kiro-cli acp`. Isolated for testing. */
406
+ _spawnKiro(bin, args, { cwd, env }) {
407
+ return spawn(bin, args, {
408
+ cwd,
409
+ env,
410
+ stdio: ['pipe', 'pipe', 'pipe'],
411
+ // Own process group: a stop reaches the CLI and the MCP servers it
412
+ // started (its shell commands are walked separately).
413
+ detached: !this._isWindows,
414
+ windowsHide: true,
415
+ });
416
+ }
417
+
418
+ /**
419
+ * Run one turn: start the server, open or resume the session, send the
420
+ * prompt, stream its updates into the channel, end the server.
421
+ *
422
+ * @returns {Promise<object>} { stopReason, text, sessionId, anyOutput,
423
+ * userStopped, staleSession, agentNotFound, error, stderr, watchdog }
424
+ */
425
+ async _runTurn({ channel, bin, args, cwd, env, resumeId, mcpServers, blocks, secrets }) {
426
+ if (this._stoppedBeforeStart(channel)) return { userStopped: true };
427
+
428
+ let proc;
429
+ try {
430
+ proc = this._spawnKiro(bin, args, { cwd, env });
431
+ } catch (e) {
432
+ return { spawnError: e && e.message };
433
+ }
434
+ this._log(`Spawning: ${path.basename(bin)} ${args.join(' ')} (cwd=${cwd})`);
435
+ this._channelProcesses[channel] = proc;
436
+
437
+ let stderr = '';
438
+ if (proc.stderr) {
439
+ proc.stderr.on('error', () => {});
440
+ proc.stderr.setEncoding('utf8');
441
+ proc.stderr.on('data', (chunk) => { stderr = truncate(stderr + chunk, STDERR_CAP); });
442
+ }
443
+
444
+ let spawnError = null;
445
+ proc.on('error', (e) => { spawnError = e && e.message; });
446
+
447
+ // ── stream state ──
448
+ let segment = ''; // text since the last tool call — the reply
449
+ const earlier = []; // narration before tool calls, kept as a fallback
450
+ let thought = '';
451
+ let anyOutput = false;
452
+ let lastLabel = null;
453
+ let agentNotFound = null;
454
+ const toolsInFlight = new Set();
455
+ const known = {}; // toolCallId → { toolKind, server }
456
+ const announced = new Set();
457
+ let pending = Promise.resolve();
458
+ const post = (fn) => { pending = pending.then(fn).catch(() => {}); };
459
+
460
+ const flushThought = () => {
461
+ const t = thought.trim();
462
+ thought = '';
463
+ if (t) post(() => this.sendThinking(channel, redactSecrets(truncate(t, THINKING_PREVIEW), secrets)));
464
+ };
465
+ const flushNarration = () => {
466
+ const t = segment.trim();
467
+ segment = '';
468
+ if (!t) return;
469
+ earlier.push(t);
470
+ post(() => this.sendThinking(channel, redactSecrets(truncate(t, THINKING_PREVIEW), secrets)));
471
+ };
472
+
473
+ let lastFrameAt = Date.now();
474
+ const onNotification = (method, params) => {
475
+ if (method === '_kiro.dev/agent/not_found') {
476
+ agentNotFound = params || {};
477
+ return;
478
+ }
479
+ if (method !== 'session/update') return;
480
+ const ev = interpretUpdate(params, secrets);
481
+ if (ev.kind === 'replay' || ev.kind === 'ignore') return;
482
+ anyOutput = true;
483
+ if (ev.kind === 'message') {
484
+ segment += ev.text;
485
+ } else if (ev.kind === 'thought') {
486
+ thought += ev.text;
487
+ } else if (ev.kind === 'tool_start') {
488
+ flushThought();
489
+ flushNarration();
490
+ if (ev.id) {
491
+ toolsInFlight.add(ev.id);
492
+ known[ev.id] = { toolKind: ev.toolKind, server: ev.server };
493
+ if (announced.has(ev.id)) return;
494
+ announced.add(ev.id);
495
+ }
496
+ if (ev.label && ev.label !== lastLabel) {
497
+ lastLabel = ev.label;
498
+ post(() => this.sendStatus(channel, ev.label));
499
+ }
500
+ } else if (ev.kind === 'tool_end') {
501
+ if (ev.id) toolsInFlight.delete(ev.id);
502
+ else toolsInFlight.clear();
503
+ } else if (ev.kind === 'plan') {
504
+ if (ev.todos.length) post(() => this.sendTodos(channel, ev.todos));
505
+ }
506
+ };
507
+
508
+ const onRequest = (method, params) => {
509
+ if (method === 'session/request_permission') {
510
+ const id = params && params.toolCall && params.toolCall.toolCallId;
511
+ const answer = permissionOutcome(params, { mode: this._mode, known: id ? known[id] : null });
512
+ if (this._mode === 'plan' && answer.outcome.optionId && /^reject/.test(answer.outcome.optionId)) {
513
+ this._log(`Plan mode: refused ${truncate((params.toolCall && params.toolCall.title) || 'a tool call', 80)}`);
514
+ }
515
+ return answer;
516
+ }
517
+ return undefined; // fs/* and terminal/* are not advertised
518
+ };
519
+
520
+ const client = new AcpClient(proc, {
521
+ onNotification,
522
+ onRequest,
523
+ onActivity: () => { lastFrameAt = Date.now(); },
524
+ onUnparsed: (line) => this._log(`Unparsed Kiro output (ignored): ${redactSecrets(truncate(line, 200), secrets)}`),
525
+ });
526
+
527
+ let settle;
528
+ const run = { proc, client, sessionId: null, done: false, settled: new Promise((r) => { settle = r; }) };
529
+ this._channelRuns[channel] = run;
530
+
531
+ // Watchdog
532
+ let silences = 0;
533
+ let killedByWatchdog = false;
534
+ const watchdog = setInterval(() => {
535
+ if (toolsInFlight.size) { silences = 0; return; }
536
+ if (Date.now() - lastFrameAt < this._watchdogIntervalMs) return;
537
+ silences += 1;
538
+ if (silences === WATCHDOG_NUDGE_AT) post(() => this.sendStatus(channel, 'still working...'));
539
+ if (silences >= this._watchdogMax) {
540
+ this._log('No output for ~5 minutes — ending a wedged Kiro run', 'warn');
541
+ killedByWatchdog = true;
542
+ void this._killTree(proc);
543
+ }
544
+ }, this._watchdogIntervalMs);
545
+
546
+ const result = {
547
+ stopReason: null, text: '', sessionId: null, anyOutput: false, userStopped: false,
548
+ staleSession: false, agentNotFound: null, error: null, stderr: '', watchdog: false,
549
+ };
550
+
551
+ try {
552
+ const hs = { timeoutMs: this._handshakeTimeoutMs };
553
+ await client.request('initialize', {
554
+ protocolVersion: ACP_PROTOCOL_VERSION,
555
+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
556
+ clientInfo: { name: 'openagents', version: this._clientVersion() },
557
+ }, hs);
558
+
559
+ let sessionId = null;
560
+ if (resumeId) {
561
+ try {
562
+ await client.request('session/load', { sessionId: resumeId, cwd, mcpServers }, hs);
563
+ sessionId = resumeId;
564
+ } catch (e) {
565
+ if (e instanceof AcpRpcError && isStaleSessionError(e.rpcError)) {
566
+ result.staleSession = true;
567
+ return result;
568
+ }
569
+ throw e;
570
+ }
571
+ } else {
572
+ const created = await client.request('session/new', { cwd, mcpServers }, hs);
573
+ sessionId = created && created.sessionId;
574
+ if (!sessionId) throw new Error('Kiro CLI did not return a session id');
575
+ }
576
+ run.sessionId = sessionId;
577
+ result.sessionId = sessionId;
578
+
579
+ if (agentNotFound) {
580
+ result.agentNotFound = agentNotFound;
581
+ return result;
582
+ }
583
+ if (this._stoppingChannels.has(channel)) {
584
+ result.userStopped = true;
585
+ return result;
586
+ }
587
+
588
+ const answer = await client.request('session/prompt', { sessionId, prompt: blocks });
589
+ result.stopReason = (answer && answer.stopReason) || 'end_turn';
590
+ } catch (e) {
591
+ result.error = e;
592
+ } finally {
593
+ run.done = true;
594
+ clearInterval(watchdog);
595
+ settle();
596
+ flushThought();
597
+ await pending;
598
+ result.text = segment.trim() || earlier.join('\n\n').trim();
599
+ result.anyOutput = anyOutput;
600
+ result.watchdog = killedByWatchdog;
601
+ result.userStopped = result.userStopped || this._stoppingChannels.has(channel) || result.stopReason === 'cancelled';
602
+ client.close('turn finished');
603
+ await this._killTree(proc);
604
+ if (this._channelProcesses[channel] === proc) delete this._channelProcesses[channel];
605
+ if (this._channelRuns[channel] === run) delete this._channelRuns[channel];
606
+ result.stderr = redactSecrets(stderr, secrets);
607
+ result.exitCode = proc.exitCode;
608
+ // A CLI that never started also fails `initialize`; the spawn error is
609
+ // the one that explains it.
610
+ if (spawnError) result.spawnError = spawnError;
611
+ }
612
+ return result;
613
+ }
614
+
615
+ _clientVersion() {
616
+ try { return require('../../package.json').version || '0.0.0'; } catch { return '0.0.0'; }
617
+ }
618
+
619
+ // ------------------------------------------------------------------
620
+ // Message handling
621
+ // ------------------------------------------------------------------
622
+
623
+ async _handleMessage(msg) {
624
+ let content = (msg.content || '').trim();
625
+ const attachments = msg.attachments || [];
626
+ const attText = formatAttachmentsForPrompt(attachments, 'mcp');
627
+ if (attText) content = content ? content + attText : attText.trim();
628
+ if (!content) return;
629
+
630
+ const channel = msg.sessionId || this.channelName;
631
+ this._stoppingChannels.delete(channel);
632
+ const sender = msg.senderName || msg.senderType || 'user';
633
+ this._log(`Processing message from ${sender} in ${channel}: ${this._redact(truncate(content, 80))}`);
634
+
635
+ // Never silently fall back to the launcher/repo dir.
636
+ const workingDir = this.workingDir || defaultAgentWorkdir(this.agentName);
637
+ if (this.workingDir && !this._dirExists(this.workingDir)) {
638
+ await this.sendError(channel, `Working directory does not exist: ${this.workingDir}`);
639
+ return;
640
+ }
641
+
642
+ const bin = this._findKiroBinary();
643
+ if (!bin) {
644
+ await this.sendError(channel, `Kiro CLI not found. Install it with: ${installHint()}`);
645
+ return;
646
+ }
647
+
648
+ const ver = this._checkVersion(bin);
649
+ if (ver.supported === false) {
650
+ this._log(`Refusing to start: Kiro CLI ${ver.version} < minimum ${KIRO_MIN_VERSION}`, 'warn');
651
+ await this.sendError(channel,
652
+ `Kiro CLI ${ver.version} is below the minimum supported version ${KIRO_MIN_VERSION}. `
653
+ + 'Upgrade with: kiro-cli update');
654
+ return;
655
+ }
656
+ if (ver.supported === null) this._log('Could not determine the Kiro CLI version — proceeding leniently');
657
+
658
+ // Auto-title + resume-from on first encounter (parity with other adapters).
659
+ if (!this._titledSessions.has(channel)) {
660
+ this._titledSessions.add(channel);
661
+ try {
662
+ const info = await this.client.getSession(this.workspaceId, channel, this.token);
663
+ const resumeFrom = info.resumeFrom;
664
+ if (resumeFrom && !this._channelSessions[channel] && this._channelSessions[resumeFrom]) {
665
+ this._channelSessions[channel] = { ...this._channelSessions[resumeFrom] };
666
+ this._saveSessions();
667
+ }
668
+ const title = generateSessionTitle(content);
669
+ if (title && !info.titleManuallySet && SESSION_DEFAULT_RE.test(info.title || '')) {
670
+ await this.client.updateSession(this.workspaceId, channel, this.token, { title, autoTitle: true });
671
+ }
672
+ } catch {}
673
+ }
674
+
675
+ await this.sendStatus(channel, 'thinking...');
676
+
677
+ const settings = resolveKiroSettings(this.agentEnv, this.workspaceModel);
678
+ const browserEnabled = await this.getBrowserEnabled();
679
+ const briefing = buildClaudeSystemPrompt({
680
+ agentName: this.agentName,
681
+ workspaceId: this.workspaceId,
682
+ channelName: channel,
683
+ mode: this._mode,
684
+ model: this.modelLabel(),
685
+ browserEnabled,
686
+ toolMode: 'mcp',
687
+ ...this.pinnedPromptOpts(channel),
688
+ });
689
+ const briefingHash = crypto.createHash('sha256').update(briefing).digest('hex').slice(0, 16);
690
+
691
+ const env = getEnhancedEnv(this.agentEnv);
692
+ const secrets = this._knownSecrets();
693
+ const args = buildKiroArgs(settings);
694
+ const workspaceServer = this._workspaceMcpServer(channel);
695
+ const mcpServers = workspaceServer ? [workspaceServer] : [];
696
+
697
+ // One retry: a remembered session the CLI no longer has is worth
698
+ // re-running fresh rather than failing the message.
699
+ for (let attempt = 0; attempt < 2; attempt++) {
700
+ const resumable = attempt === 0 ? this._resumableSession(channel, workingDir, settings.agent) : null;
701
+ const resumeId = resumable ? resumable.sessionId : null;
702
+
703
+ const blocks = [];
704
+ if (!resumable || resumable.briefing !== briefingHash) {
705
+ blocks.push({
706
+ type: 'text',
707
+ text: `<openagents_workspace_briefing>\n${briefing}\n</openagents_workspace_briefing>`,
708
+ });
709
+ }
710
+ if (!resumable) {
711
+ const recap = await this._buildChannelRecap(channel, content);
712
+ if (recap) blocks.push({ type: 'text', text: recap });
713
+ }
714
+ blocks.push({ type: 'text', text: content });
715
+
716
+ const run = await this._runTurn({
717
+ channel, bin, args, cwd: workingDir, env, resumeId, mcpServers, blocks, secrets,
718
+ });
719
+
720
+ if (run.staleSession) {
721
+ this._log(`Kiro session ${resumeId} is gone — clearing and starting a fresh one`, 'warn');
722
+ this._clearSession(channel);
723
+ if (attempt === 0) {
724
+ await this.sendStatus(channel, 'Previous Kiro session was unavailable — starting a new one.');
725
+ continue;
726
+ }
727
+ }
728
+
729
+ const record = run.sessionId
730
+ ? { sessionId: run.sessionId, workingDir, agent: settings.agent, briefing: briefingHash }
731
+ : null;
732
+
733
+ if (run.userStopped) {
734
+ // A cancelled session stays resumable, so the channel keeps its thread.
735
+ if (record) this._rememberSession(channel, record);
736
+ return;
737
+ }
738
+
739
+ if (run.agentNotFound) {
740
+ this._log(`Kiro agent profile ${settings.agent} not found — turn refused`, 'warn');
741
+ await this.sendError(channel, agentNotFoundMessage(run.agentNotFound, settings.agent));
742
+ return;
743
+ }
744
+
745
+ if (run.spawnError) {
746
+ await this.sendError(channel,
747
+ `Kiro CLI could not be started (${redactSecrets(run.spawnError, secrets)}). Reinstall it with: ${installHint()}`);
748
+ return;
749
+ }
750
+
751
+ if (run.watchdog) {
752
+ if (record) this._rememberSession(channel, record);
753
+ await this.sendError(channel,
754
+ 'Kiro produced no output for about 5 minutes and was stopped. Try a smaller task, or check the CLI on this machine.');
755
+ return;
756
+ }
757
+
758
+ if (run.error) {
759
+ // A failure after the model answered still delivers the answer.
760
+ if (record && run.anyOutput) this._rememberSession(channel, record);
761
+ const verdict = this._classifyFailure(run, secrets);
762
+ if (run.text && verdict.kind !== 'auth') {
763
+ await this.sendResponse(channel, `${run.text}\n\n_${verdict.message}_`);
764
+ } else {
765
+ this._log(`Kiro run failed (${verdict.kind}): ${redactSecrets(truncate(run.stderr || '', 300), secrets)}`, 'warn');
766
+ await this.sendError(channel, verdict.message);
767
+ }
768
+ return;
769
+ }
770
+
771
+ if (record) this._rememberSession(channel, record);
772
+ const reply = this._finalText(run);
773
+ try { await this.sendResponse(channel, reply); } catch {}
774
+ return;
775
+ }
776
+ }
777
+
778
+ /** The reply for a finished turn, with a note when it did not end normally. */
779
+ _finalText(run) {
780
+ const text = run.text || '';
781
+ switch (run.stopReason) {
782
+ case 'max_tokens':
783
+ return `${text || 'Kiro hit its output limit before answering.'}\n\n_Kiro stopped at its output token limit._`.trim();
784
+ case 'max_turn_requests':
785
+ return `${text || 'Kiro hit its turn limit before answering.'}\n\n_Kiro stopped at its per-turn request limit._`.trim();
786
+ case 'refusal':
787
+ return text || 'Kiro declined to answer this request.';
788
+ default:
789
+ return text || 'No response generated. Please try again.';
790
+ }
791
+ }
792
+
793
+ /** A failed turn → { kind, message } with Kiro-specific guidance. */
794
+ _classifyFailure(run, secrets) {
795
+ const e = run.error;
796
+ let text = '';
797
+ if (e instanceof AcpRpcError) text = rpcErrorText(e.rpcError);
798
+ else if (e instanceof AcpTimeoutError) text = `${e.message} (timed out)`;
799
+ else if (e instanceof AcpClosedError) text = e.message;
800
+ else text = (e && e.message) || '';
801
+ return classifyRunFailure({
802
+ code: run.exitCode === undefined ? null : run.exitCode,
803
+ stderr: run.stderr,
804
+ error: text,
805
+ cli: 'Kiro CLI',
806
+ guidance: KIRO_GUIDANCE,
807
+ secrets,
808
+ codeLabel: e && e.method ? `${e.method}` : '',
809
+ });
810
+ }
811
+ }
812
+
813
+ module.exports = KiroAdapter;