File size: 27,170 Bytes
e249c6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
import { stripSystemPromptCacheBoundary } from "@openclaw/ai/internal/shared";
import { clampPositiveTimerTimeoutMs } from "@openclaw/normalization-core/number-coercion";
import { isRecord } from "@openclaw/normalization-core/record-coerce";
import { toErrorObject } from "../../infra/errors.js";
import { resolveExecutablePath } from "../../infra/executable-path.js";
import { mergePathPrepend } from "../../infra/path-prepend.js";
import { BLOCKED_TOOL_CALL_ABORT_FLOOR_MS } from "../../logging/diagnostic-run-activity.js";
import type {
  CliBackendExecute,
  CliBackendToolPermissionRequest,
  CliBackendToolPermissionResult,
  CliBackendUserInputRequest,
  CliBackendUserInputResult,
} from "../../plugins/cli-backend.types.js";
import type { RunExit, TerminationReason } from "../../process/supervisor/types.js";
import { runBeforeToolCallHook } from "../agent-tools.before-tool-call.js";
import type { CliTerminalInterruption } from "../cli-output-contracts.js";
import { resolveExecDefaults } from "../exec-defaults.js";
import { FailoverError, isSignalTimeoutReason } from "../failover-error.js";
import { withAgentQuestionAnswerAuthority } from "../harness/host-private-capabilities.js";
import { runStructuredInput } from "../harness/structured-input-execution.js";
import { compileStructuredInputQuestions } from "../harness/structured-input.js";
import { resolveExecToolConfig } from "../lazy-exec-tool.js";
import { recordAgentCleanupFailure } from "../run-cleanup-timeout.js";
import { resolveToolLoopDetectionConfig } from "../tool-loop-detection-config.js";
import { normalizeToolPolicyName } from "../tool-policy.js";
import {
  restartCliLiveSession,
  createCliLiveSessionCapability,
  getCliLiveSessionApprovalGrants,
} from "./cli-live-session-registry.js";
import {
  requestCliNativeToolApproval,
  resolveCliNativeToolApprovalPlan,
} from "./cli-native-tool-approval.js";
import { createCliAbortError } from "./execute-node-claude.js";
import { createCliRunCurrentAssertion } from "./execution-target.js";
import { createCliFailoverError as failover } from "./exit-error.js";
import * as noOutputPolicy from "./no-output-timeout-policy.js";
import type { PreparedCliRunContext } from "./types.js";

const PLUGIN_ITERATOR_CLOSE_TIMEOUT_MS = 5_000;

function denyTool(message: string): CliBackendToolPermissionResult {
  return { behavior: "deny", message };
}

function createPluginToolPermissionHandler(params: {
  context: PreparedCliRunContext;
  abortSignal: AbortSignal;
  onPendingApproval: (delta: 1 | -1) => void;
  env: NodeJS.ProcessEnv;
}): (request: CliBackendToolPermissionRequest) => Promise<CliBackendToolPermissionResult> {
  const run = params.context.params;
  const permission = resolveExecDefaults({
    cfg: run.config,
    sessionEntry: run.sessionEntry,
    execOverrides: run.execOverrides,
    agentId: run.agentId,
    sessionKey: run.runtimePolicySessionKey ?? run.sessionKey,
  });
  const grants = new Set<string>();

  return async (request) => {
    const signal = request.abortSignal
      ? AbortSignal.any([params.abortSignal, request.abortSignal])
      : params.abortSignal;
    const assertActive = createCliRunCurrentAssertion(run, signal);
    try {
      assertActive();
    } catch {
      return denyTool("OpenClaw denied native tool use: the admitted run is no longer active.");
    }

    const toolName = request.toolName.trim();
    if (!toolName) {
      return denyTool("OpenClaw denied an unnamed native tool.");
    }
    if (run.cliToolAvailability && !run.cliToolAvailability.native.includes(toolName)) {
      return denyTool(`OpenClaw denied native tool ${toolName}: it is unavailable to this run.`);
    }

    // Provider schemas are not policy schemas: match canonical names and file operands.
    const canonicalToolName = normalizeToolPolicyName(
      toolName.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").replace(/([a-z0-9])([A-Z])/g, "$1_$2"),
    );
    const nativeFileTool =
      ["read", "write", "edit"].includes(canonicalToolName) &&
      Object.hasOwn(request.toolInput, "file_path");
    let policyInput = request.toolInput;
    if (nativeFileTool) {
      const nativePath = request.toolInput.file_path;
      if (typeof nativePath !== "string") {
        return denyTool("OpenClaw denied native file tool use: invalid file path.");
      }
      if (Object.hasOwn(request.toolInput, "path") && request.toolInput.path !== nativePath) {
        return denyTool("OpenClaw denied native file tool use: conflicting file paths.");
      }
      policyInput = { ...request.toolInput, path: nativePath };
      if (canonicalToolName === "edit") {
        const { old_string: oldText, new_string: newText, edits } = request.toolInput;
        if (typeof oldText !== "string" || typeof newText !== "string") {
          return denyTool("OpenClaw denied native edit tool use: invalid replacement.");
        }
        if (
          edits !== undefined &&
          (!Array.isArray(edits) ||
            edits.length !== 1 ||
            !isRecord(edits[0]) ||
            edits[0].oldText !== oldText ||
            edits[0].newText !== newText)
        ) {
          return denyTool("OpenClaw denied native edit tool use: conflicting replacements.");
        }
        policyInput.edits = [{ oldText, newText }];
      }
    }

    const requester = {
      ...((run.messageChannel ?? run.messageProvider)
        ? { channel: run.messageChannel ?? run.messageProvider }
        : {}),
      ...(run.agentAccountId ? { accountId: run.agentAccountId } : {}),
      ...(run.senderId ? { senderId: run.senderId } : {}),
      ...(run.senderIsOwner !== undefined ? { senderIsOwner: run.senderIsOwner } : {}),
    };
    const hookResult = await runBeforeToolCallHook({
      toolName: canonicalToolName,
      params: policyInput,
      ...(request.toolCallId ? { toolCallId: request.toolCallId } : {}),
      signal,
      ctx: {
        ...(run.agentId ? { agentId: run.agentId } : {}),
        ...(run.config ? { config: run.config } : {}),
        cwd: params.context.cwd ?? params.context.workspaceDir,
        workspaceDir: params.context.workspaceDir,
        ...(run.sessionKey ? { sessionKey: run.sessionKey } : {}),
        sessionId: run.sessionId,
        runId: run.runId,
        ...(run.trigger ? { trigger: run.trigger } : {}),
        ...(run.approvalReviewerDeviceId
          ? { approvalReviewerDeviceId: run.approvalReviewerDeviceId }
          : {}),
        ...(run.currentChannelId ? { channelId: run.currentChannelId } : {}),
        ...(Object.keys(requester).length > 0 ? { requester } : {}),
        turnSourceChannel: run.messageChannel ?? run.messageProvider,
        turnSourceTo: run.chatId ?? run.currentChannelId,
        turnSourceAccountId: run.agentAccountId,
        turnSourceThreadId: run.currentThreadTs,
        loopDetection: resolveToolLoopDetectionConfig({
          cfg: run.config,
          agentId: run.agentId,
        }),
      },
    });
    try {
      assertActive();
    } catch {
      return denyTool("OpenClaw denied native tool use: the admitted run closed during policy.");
    }
    if (hookResult.blocked) {
      return denyTool(hookResult.reason);
    }
    if (!isRecord(hookResult.params)) {
      return denyTool("OpenClaw denied native tool use: before_tool_call returned invalid input.");
    }
    let toolInput = hookResult.params;
    // SDK permission replies must return the native schema, never policy-only aliases.
    if (nativeFileTool) {
      if (typeof toolInput.path !== "string") {
        return denyTool("OpenClaw denied native file tool use: invalid rewritten file path.");
      }
      if (toolInput === policyInput) {
        toolInput = request.toolInput;
      } else {
        toolInput = { ...toolInput, file_path: toolInput.path };
        if (!Object.hasOwn(request.toolInput, "path")) {
          delete toolInput.path;
        }
        if (canonicalToolName === "edit") {
          const edits = toolInput.edits;
          if (
            !Array.isArray(edits) ||
            edits.length !== 1 ||
            !isRecord(edits[0]) ||
            typeof edits[0].oldText !== "string" ||
            typeof edits[0].newText !== "string"
          ) {
            return denyTool("OpenClaw denied an unrepresentable native edit rewrite.");
          }
          toolInput.old_string = edits[0].oldText;
          toolInput.new_string = edits[0].newText;
          if (!Object.hasOwn(request.toolInput, "edits")) {
            delete toolInput.edits;
          }
        }
      }
    }

    const plan = resolveCliNativeToolApprovalPlan(permission);
    if (plan === "deny") {
      return denyTool(
        `OpenClaw exec policy denied native tool use (security=${permission.security}, ask=${permission.ask}).`,
      );
    }
    const currentGrants = getCliLiveSessionApprovalGrants(params.context) ?? grants;
    if (plan === "allow" || (permission.ask !== "always" && currentGrants.has(toolName))) {
      assertActive();
      return { behavior: "allow", updatedInput: toolInput };
    }

    params.onPendingApproval(1);
    let outcome: Awaited<ReturnType<typeof requestCliNativeToolApproval>>;
    try {
      outcome = await requestCliNativeToolApproval({
        toolName,
        toolInput,
        pluginId: params.context.backendResolved.id,
        sessionKey: run.sessionKey,
        agentId: run.agentId,
        toolCallId: request.toolCallId,
        cwd: request.cwd,
        fallbackCwd: params.context.cwd ?? params.context.workspaceDir,
        bindingEnv: params.env,
        env: {
          ...params.env,
          PATH: mergePathPrepend(
            params.env.PATH,
            resolveExecToolConfig({ cfg: run.config, agentId: run.agentId }).pathPrepend ?? [],
          ),
        },
        assertActive,
        abortSignal: signal,
        ask: permission.ask,
      });
    } finally {
      params.onPendingApproval(-1);
    }
    // Approval itself may outlive, replace, or close the exact admitted turn.
    // The host rechecks authority immediately before returning any capability.
    try {
      assertActive();
    } catch {
      return denyTool("OpenClaw denied native tool use: the admitted run closed during approval.");
    }
    if (outcome.kind !== "allow") {
      return denyTool(
        outcome.message ??
          (outcome.reason === "user"
            ? `OpenClaw user denied native tool use (${toolName}).`
            : `OpenClaw approval was not granted for native tool use (${toolName}).`),
      );
    }
    if (outcome.grantAlways) {
      currentGrants.add(toolName);
    }
    return { behavior: "allow", updatedInput: outcome.updatedInput ?? toolInput };
  };
}

function cancelUserInput(message: string): CliBackendUserInputResult {
  return { status: "cancelled", message };
}

function createPluginUserInputHandler(params: {
  context: PreparedCliRunContext;
  abortSignal: AbortSignal;
  onPendingInput: (delta: 1 | -1) => void;
}): (request: CliBackendUserInputRequest) => Promise<CliBackendUserInputResult> {
  const run = params.context.params;
  return async (request) => {
    const signal = request.abortSignal
      ? AbortSignal.any([params.abortSignal, request.abortSignal])
      : params.abortSignal;
    const assertActive = createCliRunCurrentAssertion(run, signal);
    try {
      assertActive();
    } catch {
      return cancelUserInput(
        "OpenClaw cancelled operator input: the admitted run is no longer active.",
      );
    }

    const toolName = request.toolName.trim();
    if (
      !toolName ||
      (run.cliToolAvailability && !run.cliToolAvailability.native.includes(toolName))
    ) {
      return cancelUserInput(
        toolName
          ? `OpenClaw cancelled operator input from ${toolName}: it is unavailable to this run.`
          : "OpenClaw cancelled an unnamed operator input request.",
      );
    }
    if (request.questions.length === 0 || request.questions.length > 12) {
      return cancelUserInput("OpenClaw cancelled an invalid operator input request.");
    }

    const questionAuthority = params.context.bindQuestionAnswerAuthority?.(assertActive);
    const assertQuestionActive = () => {
      assertActive();
      questionAuthority?.assertActive();
    };
    params.onPendingInput(1);
    try {
      const result = await withAgentQuestionAnswerAuthority(questionAuthority, () =>
        runStructuredInput({
          input: compileStructuredInputQuestions({
            questions: request.questions.map((question) => ({
              ...question,
              isSecret: false,
            })),
            intro: request.intro?.trim() || "Agent needs input:",
          }),
          sessionKey: run.sessionKey ?? run.sessionId,
          agentId: run.agentId,
          runId: run.runId,
          timeoutMs: run.timeoutMs,
          delivery: {
            onBlockReply: run.onBlockReply,
            onPartialReply: run.onPartialReply,
          },
          signal,
          isActive: () => {
            try {
              assertQuestionActive();
              return true;
            } catch {
              return false;
            }
          },
          questionId: request.toolCallId ? (batch) => `${request.toolCallId}:${batch}` : undefined,
        }),
      );
      try {
        assertQuestionActive();
      } catch {
        return cancelUserInput(
          "OpenClaw cancelled operator input: the admitted run closed before the answer was committed.",
        );
      }
      return result.status === "answered"
        ? { status: "answered", answers: result.answers }
        : cancelUserInput(
            result.message ??
              "OpenClaw cancelled operator input; continue with your best judgment.",
          );
    } catch {
      return cancelUserInput(
        "OpenClaw could not collect operator input; continue with your best judgment.",
      );
    } finally {
      params.onPendingInput(-1);
    }
  };
}

function waitForIteratorValue<T>(
  iterator: AsyncIterator<T>,
  signal: AbortSignal,
): Promise<IteratorResult<T>> {
  if (signal.aborted) {
    return Promise.reject(toErrorObject(signal.reason, "CLI plugin execution was aborted."));
  }
  return new Promise((resolve, reject) => {
    const rejectAborted = () =>
      reject(toErrorObject(signal.reason, "CLI plugin execution was aborted."));
    signal.addEventListener("abort", rejectAborted, { once: true });
    void iterator.next().then(
      (value) => {
        signal.removeEventListener("abort", rejectAborted);
        resolve(value);
      },
      (error: unknown) => {
        signal.removeEventListener("abort", rejectAborted);
        reject(toErrorObject(error, "CLI plugin execution stream failed."));
      },
    );
  });
}

async function closePluginIterator(
  iterator: AsyncIterator<Record<string, unknown>> | undefined,
): Promise<void> {
  if (!iterator?.return) {
    return;
  }
  let timeout: ReturnType<typeof setTimeout> | undefined;
  try {
    await Promise.race([
      iterator.return(),
      new Promise<never>((_, reject) => {
        timeout = setTimeout(
          () => reject(new Error("CLI plugin runtime did not close after its run ended.")),
          PLUGIN_ITERATOR_CLOSE_TIMEOUT_MS,
        );
        timeout.unref();
      }),
    ]);
  } catch (error) {
    recordAgentCleanupFailure();
    throw error;
  } finally {
    clearTimeout(timeout);
  }
}

/** Runs a prepared plugin transport while keeping cancellation and approvals host-owned. */
export async function executePluginOwnedProcess(params: {
  context: PreparedCliRunContext;
  execute: CliBackendExecute;
  executionCommand: string;
  executionArgv0?: string;
  executionArgs: readonly string[];
  env: Record<string, string>;
  prompt: string;
  promptContext?: PreparedCliRunContext["promptContext"];
  useResume: boolean;
  forceNewSession?: boolean;
  sessionId?: string;
  noOutputTimeoutMs: number;
  consumeStdout: (chunk: string) => void;
  onOutstandingWorkChange?: (active: boolean) => void;
  activeToolCount?: () => number;
  getActiveLoopbackAskUserDeadline?: () => number | undefined;
  onActiveLoopbackAskUserDeadlineChange?: (listener: () => void) => () => void;
  onNoOutputTimeout?: (error: FailoverError) => void;
  onInterrupted?: (reason: CliTerminalInterruption["reason"]) => boolean;
  mcpCapture?: {
    captureKey?: string;
    beginCapture: (captureKey: string | undefined, assertCurrent: () => void) => void;
  };
  liveSession?: {
    requiredGeneration?: string;
  };
}): Promise<RunExit> {
  const run = params.context.params;
  const cwd = params.context.cwd ?? params.context.workspaceDir;
  const command = resolveExecutablePath(params.executionCommand, { cwd, env: params.env });
  if (!command) {
    throw new Error(`CLI backend executable could not be resolved: ${params.executionCommand}`);
  }

  const startedAt = Date.now();
  const controller = new AbortController();
  const signal = run.abortSignal
    ? AbortSignal.any([controller.signal, run.abortSignal])
    : controller.signal;
  const assertCurrent = createCliRunCurrentAssertion(run, signal);
  const assertRunCurrent = createCliRunCurrentAssertion(run);
  const termination: { reason: TerminationReason } = { reason: "exit" };
  // Normal cleanup closes native callbacks; MCP results retain their admitted
  // caller through the capture drain. Cancellation and timeouts still close both.
  const assertCaptureCurrent = () =>
    (termination.reason === "exit" ? assertRunCurrent : assertCurrent)();
  const outstanding = {
    approvals: 0,
    background: 0,
    lastOutputAt: startedAt,
    observed: false,
    replayUnsafe: false,
  };
  const reportOutstandingWork = () =>
    params.onOutstandingWorkChange?.(outstanding.approvals > 0 || outstanding.background > 0);
  const updatePendingApproval = (delta: number) => {
    outstanding.approvals = Math.max(0, outstanding.approvals + delta);
    reportOutstandingWork();
  };
  let noOutputTimer: ReturnType<typeof setTimeout> | undefined;
  const overallTimeoutMs = clampPositiveTimerTimeoutMs(run.timeoutMs);
  const noOutputTimeoutMs = clampPositiveTimerTimeoutMs(params.noOutputTimeoutMs);
  const overallTimer =
    overallTimeoutMs === undefined
      ? undefined
      : setTimeout(() => {
          termination.reason = "overall-timeout";
          controller.abort(new Error("CLI plugin runtime exceeded its execution timeout."));
        }, overallTimeoutMs);
  const activeToolCount = () => Math.max(params.activeToolCount?.() ?? 0, outstanding.approvals);
  const resetNoOutputTimer = (delayMs?: number) => {
    clearTimeout(noOutputTimer);
    if (noOutputTimeoutMs === undefined) {
      return;
    }
    const activeAskUserDeadline = params.getActiveLoopbackAskUserDeadline?.();
    const baselineDeadline = outstanding.lastOutputAt + noOutputTimeoutMs;
    const effectiveDelayMs =
      delayMs ??
      Math.max(
        0,
        (activeAskUserDeadline === undefined
          ? baselineDeadline
          : Math.max(baselineDeadline, activeAskUserDeadline)) - Date.now(),
      );
    noOutputTimer = setTimeout(() => {
      const quietDurationMs = Date.now() - outstanding.lastOutputAt;
      const askUserDeadline = params.getActiveLoopbackAskUserDeadline?.();
      const decision = noOutputPolicy.resolveCliNoOutputTimeoutDecision({
        context: {
          provider: run.provider,
          model: params.context.modelId,
          sessionId: run.sessionId,
          lane: run.lane,
        },
        timeoutMs: noOutputTimeoutMs,
        quietDurationMs,
        cliTimeout: {
          mode: "no-output",
          timeoutSeconds: Math.round(quietDurationMs / 1000),
          observedActivity: outstanding.observed,
          activeToolCount: activeToolCount(),
          backgroundTaskCount: outstanding.background,
        },
        hasOutputText: false,
        useResume: params.useResume,
        hasReplayUnsafeActivity: outstanding.replayUnsafe,
        allowResumeControlOnlyRetry: true,
        outstandingWorkGraceMs:
          askUserDeadline === undefined
            ? BLOCKED_TOOL_CALL_ABORT_FLOOR_MS
            : Math.max(
                BLOCKED_TOOL_CALL_ABORT_FLOOR_MS,
                askUserDeadline - outstanding.lastOutputAt,
              ),
      });
      if (decision.deferMs !== undefined) {
        resetNoOutputTimer(decision.deferMs);
        return;
      }
      termination.reason = "no-output-timeout";
      params.onNoOutputTimeout?.(decision.error);
      controller.abort(decision.error);
    }, effectiveDelayMs);
  };
  const stopAskUserDeadlineListener = params.onActiveLoopbackAskUserDeadlineChange?.(() =>
    resetNoOutputTimer(),
  );

  const replyBackendHandle = run.replyOperation
    ? {
        kind: "cli" as const,
        runId: run.runId,
        toolAuthorityFingerprint: run.toolAuthorityFingerprint,
        cancel: () => {
          termination.reason = "manual-cancel";
          controller.abort(createCliAbortError());
        },
      }
    : undefined;
  if (replyBackendHandle) {
    run.replyOperation?.attachBackend(replyBackendHandle);
  }

  let iterator: AsyncIterator<Record<string, unknown>> | undefined;
  let liveSession: ReturnType<typeof createCliLiveSessionCapability> | undefined;
  let terminalResult: "none" | "success" | "error" = "none";
  try {
    assertCurrent();
    resetNoOutputTimer();
    if (
      params.liveSession &&
      (params.forceNewSession ||
        (Boolean(params.context.preparedBackend.backend.resumeArgs?.length) && !params.useResume))
    ) {
      if (params.liveSession.requiredGeneration) {
        throw new Error("The required CLI live session cannot be replaced by a fresh process.");
      }
      await restartCliLiveSession(params.context, signal);
    }
    assertCurrent();
    if (params.liveSession) {
      liveSession = createCliLiveSessionCapability({
        context: params.context,
        argv: [command, ...params.executionArgs],
        argv0: params.executionArgv0,
        env: params.env,
        ...params.liveSession,
        captureKey: params.mcpCapture?.captureKey,
        beginCapture: (captureKey) =>
          params.mcpCapture?.beginCapture(captureKey, assertCaptureCurrent),
        abortSignal: signal,
        claimResources: params.context.preparedBackend.claimLiveSessionResources,
      });
    } else {
      params.mcpCapture?.beginCapture(params.mcpCapture.captureKey, assertCaptureCurrent);
    }
    assertCurrent();
    const execution = params.execute({
      command,
      argv0: params.executionArgv0,
      args: params.executionArgs,
      cwd,
      env: params.env,
      prompt: params.prompt,
      ...(params.promptContext ? { promptContext: params.promptContext } : {}),
      modelId: params.context.normalizedModel,
      systemPrompt: stripSystemPromptCacheBoundary(params.context.systemPrompt).trim(),
      ...(params.sessionId ? { sessionId: params.sessionId } : {}),
      useResume: params.useResume,
      abortSignal: signal,
      assertCurrent,
      timeoutMs: run.timeoutMs,
      ...(run.executionMode ? { executionMode: run.executionMode } : {}),
      ...(run.cliToolAvailability ? { toolAvailability: run.cliToolAvailability } : {}),
      ...(liveSession ? { liveSession } : {}),
      requestToolPermission: createPluginToolPermissionHandler({
        context: params.context,
        abortSignal: signal,
        onPendingApproval: updatePendingApproval,
        env: params.env,
      }),
      requestUserInput: createPluginUserInputHandler({
        context: params.context,
        abortSignal: signal,
        onPendingInput: updatePendingApproval,
      }),
    });
    iterator = execution[Symbol.asyncIterator]();

    for (;;) {
      const next = await waitForIteratorValue(iterator, signal);
      if (next.done) {
        break;
      }
      if (!isRecord(next.value)) {
        outstanding.replayUnsafe = true;
        throw new Error("CLI plugin runtime emitted an invalid structured stream event.");
      }
      if (next.value.type === "result") {
        terminalResult =
          terminalResult === "error" ||
          next.value.is_error === true ||
          (typeof next.value.subtype === "string" && next.value.subtype.startsWith("error_"))
            ? "error"
            : "success";
      }
      if (
        next.value.type === "system" &&
        next.value.subtype === "background_tasks_changed" &&
        Array.isArray(next.value.tasks)
      ) {
        outstanding.background = next.value.tasks.filter(isRecord).length;
        reportOutstandingWork();
      }
      params.consumeStdout(`${JSON.stringify(next.value)}\n`);
      outstanding.observed = true;
      if (
        !(next.value.type === "system" && next.value.subtype === "init") &&
        next.value.type !== "command_lifecycle"
      ) {
        outstanding.replayUnsafe = true;
      }
      outstanding.lastOutputAt = Date.now();
      resetNoOutputTimer();
    }

    if (terminalResult === "none") {
      throw new Error("CLI plugin runtime completed without a terminal result.");
    }
  } catch (error) {
    if (run.abortSignal?.aborted || termination.reason === "manual-cancel") {
      const reason = isSignalTimeoutReason(run.abortSignal?.reason) ? "timeout" : "aborted";
      if (!params.onInterrupted?.(reason)) {
        throw createCliAbortError();
      }
      termination.reason = "manual-cancel";
    }
    if (termination.reason === "exit" && terminalResult !== "error") {
      if (
        params.liveSession?.requiredGeneration &&
        noOutputPolicy.isReplaySafeCliResumeControlOnly(
          params.useResume,
          outstanding.replayUnsafe,
          Boolean(outstanding.approvals || outstanding.background || params.activeToolCount?.()),
        )
      ) {
        try {
          liveSession?.current();
        } catch (sessionError) {
          if (sessionError instanceof FailoverError && sessionError.reason === "session_expired") {
            const { code, message, reason } = sessionError;
            throw failover(message, reason, sessionError, { cause: error, code });
          }
        }
      }
      throw error;
    }
  } finally {
    clearTimeout(overallTimer);
    clearTimeout(noOutputTimer);
    stopAskUserDeadlineListener?.();
    params.onOutstandingWorkChange?.(false);
    // Permission callbacks can be retained by the plugin or its subprocess.
    // Closing the turn fences those capabilities before any outer cleanup runs.
    if (!controller.signal.aborted) {
      controller.abort(new Error("CLI plugin runtime turn is no longer active."));
    }
    if (replyBackendHandle) {
      run.replyOperation?.detachBackend(replyBackendHandle);
    }
    await closePluginIterator(iterator);
  }

  return {
    reason: termination.reason,
    exitCode: termination.reason === "exit" ? 0 : null,
    exitSignal: null,
    durationMs: Date.now() - startedAt,
    stdout: "",
    stderr: "",
    timedOut:
      termination.reason === "overall-timeout" || termination.reason === "no-output-timeout",
    noOutputTimedOut: termination.reason === "no-output-timeout",
  };
}