Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat(provider): add OpenClaw, Hermes, and PiAgent harnesses with reasoning controls #5505

ClosedHioness(GitHub profile, opens in a new tab)wants to merge 2 commits intomain fromrefs/pull/5505/headopened View on GitHub

Problem

OpenClaw, Hermes, and Grok did not show a reasoning control in the composer. Every other harness has one.

Fix

This PR adds the OpenClaw, Hermes, and PiAgent harnesses. It also adds the reasoning controls that the new harnesses did not have.

OpenClaw now advertises a reasoningEffort descriptor. The adapter already sent the selection to the gateway. The control appears now that the catalog declares it.

Grok and Hermes read the effort or reasoning session config option during ACP discovery. They advertise it as a reasoning descriptor and apply the selection on each turn. The control stays hidden when the CLI does not expose such an option.

The UI is descriptor-driven. Web, desktop, and mobile show the control without client changes.

Tests

Server typecheck passes. All 130 targeted tests pass. New tests cover the ACP reasoning bridge, the provider catalogs, and the adapter apply path.

Model

Model: deepseek-v4-flash. Harness: opencode.


Note

High Risk Large new surface area: spawns external CLIs/gateways, WebSocket sessions, and turn/approval lifecycle; misconfiguration or process leaks could affect orchestration reliability.

Overview Adds Pi, Hermes, and OpenClaw as first-class provider drivers (adapters, snapshots, text generation, and driver registration), with CI-friendly mock pi and OpenClaw gateway scripts driving the same protocols as production.

Reasoning in the composer is wired through shared ACP reasoning helpers: Grok and Hermes discover effort/reasoning session config options and expose them as model reasoning descriptors, then apply selections via session/set_config_option on session start and each turn (including effort on turn.started). Hermes also gets a full ACP adapter (permissions, steering, MCP skip when bound). OpenClaw uses a shared gateway holder and WebSocket runtime with broad adapter tests.

Mobile picks up provider icons and display labels for the new drivers. RPC auth gains operate scopes for projectsMakeDirectory and projectsDeleteFile.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 219abf457dcee016ac20a9e5d946d297ba365497. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Note

Add OpenClaw, Hermes, and PiAgent provider harnesses with reasoning controls

  • Registers three new providers (piAgent, hermes, openclaw) end-to-end: contracts, server drivers, adapters, text generation services, UI icons, settings schemas, picker entries, and user docs.
  • Each provider has a CLI-backed or HTTP-backed adapter (HermesAdapter, PiAgentAdapter, OpenClawAdapter) that maps native protocol events to the canonical ProviderRuntimeEvent stream, including session lifecycle, tool calls, approvals, and token usage.
  • Reasoning/effort controls are surfaced via a new AcpReasoningConfig bridge that reads ACP SessionConfigOption entries and constructs a reasoning select descriptor; Grok discovery also gains this capability.
  • Adds makeDirectory and deleteFile workspace RPC endpoints (projects.makeDirectory, projects.deleteFile) with path-safety checks, recursive-deletion guards, cache invalidation, and authorization scope enforcement.
  • Extends the file browser with toolbar and context-menu actions for creating files/folders and deleting them, plus programmatic directory reveal; deleted file surfaces auto-close in the right panel.
  • Replaces scattered navigator.clipboard.writeText calls with a centralized writeTextToClipboard helper that falls back to document.execCommand('copy') on insecure origins.
  • Risk: piAgent rollback is explicitly unsupported and returns a ProviderAdapterValidationError; OpenClaw also lacks rollback and free-form user input support.
📊 Macroscope summarized 219abf4. 25 files reviewed, 0 issues evaluated, 0 issues filtered, 0 comments posted

🗂️ Filtered Issues

No issues evaluated.

    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 3ce0fd77-5e2f-424e-af1d-c78dac55fed2

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review

      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

      ❤️ Share
      Comment `@coderabbitai help` to get the list of available commands.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    3. Effect service conventions review — findings in the new OpenClawRuntime service module (apps/server/src/provider/openclawRuntime.ts) and its consumer OpenClawProvider.ts. The Hermes/Pi adapters, drivers, and AcpReasoningConfig look consistent with the conventions (namespace subpath imports, Context.Service-free helper modules, scoped resource ownership, no hidden runtimes).

      Posted via Macroscope — Effect Service Conventions
      @@ -0,0 +37,21 @@
      37+ { value: "xhigh", label: "Extra High" },
      38+ { value: "max", label: "Max" },
      39+];
      40+
      41+function openClawModelCapabilities() {
      42+ return createModelCapabilities({
      43+ optionDescriptors: [
      44+ buildSelectOptionDescriptor({
      45+ id: "reasoningEffort",
      46+ label: "Reasoning",
      47+ options: OPENCLAW_REASONING_OPTIONS,
      48+ }),
      49+ ],
      50+ });
      51+}
      52+import {
      53+ OpenClawRuntime,
      54+ openClawRuntimeErrorDetail,
      55+ type OpenClawGatewayConnection,
      56+ type OpenClawRuntimeShape,
      57+} from "../openclawRuntime.ts";
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      This import sits mid-file, after the reasoning-option constants and openClawModelCapabilities. Suggest hoisting it into the top import block so the module keeps the canonical order (imports first).

      Posted via Macroscope — Effect Service Conventions
      @@ -0,0 +756,21 @@
      756+ const code = typeof error.code === "string" ? error.code : "unknown";
      757+ const message = typeof error.message === "string" ? error.message : "";
      758+ if (message.length > 0) {
      759+ return `${code}: ${message}`;
      760+ }
      761+ const details = error.details;
      762+ if (isRecord(details) && typeof details.reason === "string") {
      763+ return `${code}: ${details.reason}`;
      764+ }
      765+ return `Gateway request failed (${code}).`;
      766+ }
      767+ return "Gateway request failed.";
      768+}
      769+
      770+export class OpenClawRuntime extends Context.Service<OpenClawRuntime, OpenClawRuntimeShape>()(
      771+ "t3/provider/openclawRuntime",
      772+) {}
      773+
      774+export const OpenClawRuntimeLive = Layer.effect(OpenClawRuntime, makeOpenClawRuntime).pipe(
      775+ Layer.provideMerge(NetService.layer),
      776+);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Canonical single-file order for a service module is imports, errors/schemas, the Context.Service tag (with its inline interface), then make, then layer — here the tag lands after makeOpenClawRuntime. Consider also exporting a real make and naming the canonical layer layer (export const layer = Layer.effect(OpenClawRuntime, make)), so namespace consumers read OpenClawRuntime.layer in server.ts and the tests.

      Posted via Macroscope — Effect Service Conventions
      @@ -0,0 +146,21 @@
      146+ /**
      147+ * Resolve the gateway for this instance: connect to `gatewayUrl` when set,
      148+ * otherwise spawn `binaryPath gateway --port <free>` and wait for protocol
      149+ * readiness. The child process lifetime is bound to the caller's scope.
      150+ */
      151+ readonly connectToOpenClawGateway: (input: {
      152+ readonly binaryPath: string;
      153+ readonly gatewayUrl?: string;
      154+ readonly gatewayToken?: string;
      155+ readonly environment?: NodeJS.ProcessEnv;
      156+ readonly stateDir?: string;
      157+ readonly launchArgs?: ReadonlyArray<string>;
      158+ readonly port?: number;
      159+ readonly timeoutMs?: number;
      160+ }) => Effect.Effect<OpenClawGatewayConnection, OpenClawRuntimeError, Scope.Scope>;
      161+ readonly runOpenClawCommand: (input: {
      162+ readonly binaryPath: string;
      163+ readonly args: ReadonlyArray<string>;
      164+ readonly environment?: NodeJS.ProcessEnv;
      165+ }) => Effect.Effect<OpenClawCommandResult, OpenClawRuntimeError>;
      166+}
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Consider defining this interface inline in the Context.Service declaration rather than keeping a standalone OpenClawRuntimeShape, and referring to the inferred interface as OpenClawRuntime["Service"] at the implementation and at consumers (OpenClawProvider.ts imports the shape type today).

      Posted via Macroscope — Effect Service Conventions
      @@ -0,0 +56,21 @@
      56+import * as Ref from "effect/Ref";
      57+import * as Scope from "effect/Scope";
      58+import * as Stream from "effect/Stream";
      59+import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
      60+
      61+import * as NetService from "@t3tools/shared/Net";
      62+import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
      63+import { resolveSpawnCommand } from "@t3tools/shared/shell";
      64+
      65+import { isWindowsCommandNotFound } from "../processRunner.ts";
      66+import { collectStreamAsString } from "./providerSnapshot.ts";
      67+
      68+const OPENCLAW_RUNTIME_ERROR_TAG = "OpenClawRuntimeError";
      69+export class OpenClawRuntimeError extends Data.TaggedError(OPENCLAW_RUNTIME_ERROR_TAG)<{
      70+ readonly operation: string;
      71+ readonly cause?: unknown;
      72+ readonly detail: string;
      73+}> {
      74+ static readonly is = (u: unknown): u is OpenClawRuntimeError =>
      75+ P.isTagged(u, OPENCLAW_RUNTIME_ERROR_TAG);
      76+}
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Service failures should be declared with Schema.TaggedErrorClass and structured attributes (like apps/server/src/provider/Errors.ts), with message derived from those attributes and cause: Schema.optional(Schema.Defect()) instead of cause?: unknown. The hand-rolled static is predicate would then become an exported schema predicate (export const isOpenClawRuntimeError = Schema.is(OpenClawRuntimeError)), which the OpenClawRuntimeError.is(...) call sites here and in OpenClawAdapter.ts can use.

      Posted via Macroscope — Effect Service Conventions
    4. Effect service conventions review — findings in the new OpenClawRuntime service module (apps/server/src/provider/openclawRuntime.ts) and its consumer OpenClawProvider.ts. The Hermes/Pi adapters, drivers, and AcpReasoningConfig look consistent with the conventions (namespace subpath imports, Context.Service-free helper modules, scoped resource ownership, no hidden runtimes).

      Posted via Macroscope — Effect Service Conventions
      @@ -0,0 +756,21 @@
      756+ const code = typeof error.code === "string" ? error.code : "unknown";
      757+ const message = typeof error.message === "string" ? error.message : "";
      758+ if (message.length > 0) {
      759+ return `${code}: ${message}`;
      760+ }
      761+ const details = error.details;
      762+ if (isRecord(details) && typeof details.reason === "string") {
      763+ return `${code}: ${details.reason}`;
      764+ }
      765+ return `Gateway request failed (${code}).`;
      766+ }
      767+ return "Gateway request failed.";
      768+}
      769+
      770+export class OpenClawRuntime extends Context.Service<OpenClawRuntime, OpenClawRuntimeShape>()(
      771+ "t3/provider/openclawRuntime",
      772+) {}
      773+
      774+export const OpenClawRuntimeLive = Layer.effect(OpenClawRuntime, makeOpenClawRuntime).pipe(
      775+ Layer.provideMerge(NetService.layer),
      776+);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Canonical single-file order for a service module is imports, errors/schemas, the Context.Service tag (with its inline interface), then make, then layer — here the tag lands after makeOpenClawRuntime. Consider also exporting a real make and naming the canonical layer layer (export const layer = Layer.effect(OpenClawRuntime, make)), so namespace consumers read OpenClawRuntime.layer in server.ts and the tests.

      Posted via Macroscope — Effect Service Conventions
      @@ -0,0 +56,21 @@
      56+import * as Ref from "effect/Ref";
      57+import * as Scope from "effect/Scope";
      58+import * as Stream from "effect/Stream";
      59+import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
      60+
      61+import * as NetService from "@t3tools/shared/Net";
      62+import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
      63+import { resolveSpawnCommand } from "@t3tools/shared/shell";
      64+
      65+import { isWindowsCommandNotFound } from "../processRunner.ts";
      66+import { collectStreamAsString } from "./providerSnapshot.ts";
      67+
      68+const OPENCLAW_RUNTIME_ERROR_TAG = "OpenClawRuntimeError";
      69+export class OpenClawRuntimeError extends Data.TaggedError(OPENCLAW_RUNTIME_ERROR_TAG)<{
      70+ readonly operation: string;
      71+ readonly cause?: unknown;
      72+ readonly detail: string;
      73+}> {
      74+ static readonly is = (u: unknown): u is OpenClawRuntimeError =>
      75+ P.isTagged(u, OPENCLAW_RUNTIME_ERROR_TAG);
      76+}
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Service failures should be declared with Schema.TaggedErrorClass and structured attributes (like apps/server/src/provider/Errors.ts), with message derived from those attributes and cause: Schema.optional(Schema.Defect()) instead of cause?: unknown. The hand-rolled static is predicate would then become an exported schema predicate (export const isOpenClawRuntimeError = Schema.is(OpenClawRuntimeError)), which the OpenClawRuntimeError.is(...) call sites here and in OpenClawAdapter.ts can use.

      Posted via Macroscope — Effect Service Conventions
      @@ -0,0 +146,21 @@
      146+ /**
      147+ * Resolve the gateway for this instance: connect to `gatewayUrl` when set,
      148+ * otherwise spawn `binaryPath gateway --port <free>` and wait for protocol
      149+ * readiness. The child process lifetime is bound to the caller's scope.
      150+ */
      151+ readonly connectToOpenClawGateway: (input: {
      152+ readonly binaryPath: string;
      153+ readonly gatewayUrl?: string;
      154+ readonly gatewayToken?: string;
      155+ readonly environment?: NodeJS.ProcessEnv;
      156+ readonly stateDir?: string;
      157+ readonly launchArgs?: ReadonlyArray<string>;
      158+ readonly port?: number;
      159+ readonly timeoutMs?: number;
      160+ }) => Effect.Effect<OpenClawGatewayConnection, OpenClawRuntimeError, Scope.Scope>;
      161+ readonly runOpenClawCommand: (input: {
      162+ readonly binaryPath: string;
      163+ readonly args: ReadonlyArray<string>;
      164+ readonly environment?: NodeJS.ProcessEnv;
      165+ }) => Effect.Effect<OpenClawCommandResult, OpenClawRuntimeError>;
      166+}
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Consider defining this interface inline in the Context.Service declaration rather than keeping a standalone OpenClawRuntimeShape, and referring to the inferred interface as OpenClawRuntime["Service"] at the implementation and at consumers (OpenClawProvider.ts imports the shape type today).

      Posted via Macroscope — Effect Service Conventions
      @@ -0,0 +37,21 @@
      37+ { value: "xhigh", label: "Extra High" },
      38+ { value: "max", label: "Max" },
      39+];
      40+
      41+function openClawModelCapabilities() {
      42+ return createModelCapabilities({
      43+ optionDescriptors: [
      44+ buildSelectOptionDescriptor({
      45+ id: "reasoningEffort",
      46+ label: "Reasoning",
      47+ options: OPENCLAW_REASONING_OPTIONS,
      48+ }),
      49+ ],
      50+ });
      51+}
      52+import {
      53+ OpenClawRuntime,
      54+ openClawRuntimeErrorDetail,
      55+ type OpenClawGatewayConnection,
      56+ type OpenClawRuntimeShape,
      57+} from "../openclawRuntime.ts";
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      This import sits mid-file, after the reasoning-option constants and openClawModelCapabilities. Suggest hoisting it into the top import block so the module keeps the canonical order (imports first).

      Posted via Macroscope — Effect Service Conventions
    5. @@ -297,4 +337,12 @@
      297337 return { relativePath: target.relativePath };
      298338 });
      299339
      300- return WorkspaceFileSystem.of({ readFile, writeFile });
      340+ const makeDirectory: WorkspaceFileSystem["Service"]["makeDirectory"] = Effect.fn(
      341+ "WorkspaceFileSystem.makeDirectory",
      342+ )(function* (input) {
      343+ const target = yield* workspacePaths.resolveRelativePathWithinRoot({
      344+ workspaceRoot: input.cwd,
      345+ relativePath: input.relativePath,
      346+ });
      347+
      348+ yield* fileSystem.makeDirectory(target.absolutePath, { recursive: true }).pipe(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High workspace/WorkspaceFileSystem.ts:348

      makeDirectory creates directories outside the workspace root when a symlinked parent is traversed. If workspace/link is a symlink to /outside, calling makeDirectory with relativePath: "link/new-directory" resolves the path lexically inside the root, then calls fileSystem.makeDirectory(target.absolutePath, { recursive: true }), which creates /outside/new-directory outside the workspace. Unlike readFile, which calls NodeFSP.realpath on both the workspace root and target and checks that the real target path stays inside the real workspace root, makeDirectory only relies on resolveRelativePathWithinRoot — a lexical check that does not follow symlinks. Consider adding the same real-path containment check before mutating the target.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/workspace/WorkspaceFileSystem.ts around line 348:
      
      `makeDirectory` creates directories outside the workspace root when a symlinked parent is traversed. If `workspace/link` is a symlink to `/outside`, calling `makeDirectory` with `relativePath: "link/new-directory"` resolves the path lexically inside the root, then calls `fileSystem.makeDirectory(target.absolutePath, { recursive: true })`, which creates `/outside/new-directory` outside the workspace. Unlike `readFile`, which calls `NodeFSP.realpath` on both the workspace root and target and checks that the real target path stays inside the real workspace root, `makeDirectory` only relies on `resolveRelativePathWithinRoot` — a lexical check that does not follow symlinks. Consider adding the same real-path containment check before mutating the target.
      @@ -321 +373,21 @@
      321373
      374+ // Directory reveals (e.g. right after creating a folder) expand ancestors
      375+ // and select the row once per request, without touching the file-selection
      376+ // sync above.
      377+ const handledDirectoryRevealRef = useRef<{ path: string; revealId: number } | null>(null);
      378+ useEffect(() => {
      379+ const request = revealDirectoryRequest;
      380+ if (!request) {
      381+ handledDirectoryRevealRef.current = null;
      382+ return;
      383+ }
      384+ const handled = handledDirectoryRevealRef.current;
      385+ if (handled?.path === request.path && handled.revealId === request.revealId) return;
      386+ if (entryKinds.get(request.path) !== "directory") return;
      387+ const directoryPath = `${request.path}/`;
      388+ const selectedItem = model.getItem(directoryPath);
      389+ if (!selectedItem) return;
      390+ handledDirectoryRevealRef.current = request;
      391+
      392+ const segments = request.path.split("/");
      393+ let ancestorPath = "";
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium files/FileBrowserPanel.tsx:390

      The directory-reveal effect calls selectedItem.select() and model.scrollToPath() without first closing the active tree search. When a folder is created while a search query is active, the hide-non-matches search mode keeps the new directory row hidden, so the reveal request has no visible effect. The file-reveal effect above calls model.closeSearch() before selecting and scrolling — the directory-reveal effect should do the same.

      Suggested change
      390- handledDirectoryRevealRef.current = request;
      391-
      392- const segments = request.path.split("/");
      393- let ancestorPath = "";
      390+ handledDirectoryRevealRef.current = request;
      391+
      392+ model.closeSearch();
      393+ const segments = request.path.split("/");
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/components/files/FileBrowserPanel.tsx around lines 390-393:
      
      The directory-reveal effect calls `selectedItem.select()` and `model.scrollToPath()` without first closing the active tree search. When a folder is created while a search query is active, the `hide-non-matches` search mode keeps the new directory row hidden, so the reveal request has no visible effect. The file-reveal effect above calls `model.closeSearch()` before selecting and scrolling — the directory-reveal effect should do the same.
      @@ -0,0 +148,21 @@
      148+ readonly command: string;
      149+ readonly deferred: Deferred.Deferred<PiRpcResponse, PiSessionRuntimeError>;
      150+}
      151+
      152+function isRecord(value: unknown): value is Record<string, unknown> {
      153+ return typeof value === "object" && value !== null && !Array.isArray(value);
      154+}
      155+
      156+function isPiResponseRecord(value: unknown): value is Record<string, unknown> & {
      157+ readonly type: "response";
      158+ readonly command: string;
      159+} {
      160+ return isRecord(value) && value.type === "response" && typeof value.command === "string";
      161+}
      162+
      163+/**
      164+ * Record framing for pi's JSONL protocol. Splits on `\n` only and strips a
      165+ * single trailing `\r`; `StringDecoder` handles UTF-8 multi-byte sequences
      166+ * that span chunk boundaries.
      167+ */
      168+export function makePiRecordSplitter(): {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Layers/PiAgentSessionRuntime.ts:168

      flush() silently drops the last JSON record if it has no trailing \n. When pi writes a final response object and closes stdout immediately after it, flushRecords() returns [] because remainder contains no newline, so the response is discarded and its pending RPC waits until timeout. The remaining content should still be emitted as a record (even without a trailing newline). Additionally, the stdout consumer never calls flush() at EOF, so any partial final record is lost regardless. Consider emitting remainder (if non-empty) from flushRecords() when called by flush(), and invoking recordSplitter.flush() after the stdout stream completes.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/PiAgentSessionRuntime.ts around line 168:
      
      `flush()` silently drops the last JSON record if it has no trailing `\n`. When pi writes a final response object and closes stdout immediately after it, `flushRecords()` returns `[]` because `remainder` contains no newline, so the response is discarded and its pending RPC waits until timeout. The remaining content should still be emitted as a record (even without a trailing newline). Additionally, the stdout consumer never calls `flush()` at EOF, so any partial final record is lost regardless. Consider emitting `remainder` (if non-empty) from `flushRecords()` when called by `flush()`, and invoking `recordSplitter.flush()` after the stdout stream completes.
    6. Cursor Bugbot has reviewed your changes using high effort and found 3 potential issues.

      Fix All in Cursor ❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).

      Want fixes drafted automatically? Bugbot Autofix can create code changes for findings. A team admin can enable Autofix in the Cursor dashboard.

      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 219abf457dcee016ac20a9e5d946d297ba365497. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -0,0 +62,21 @@
      62+];
      63+
      64+function piModelCapabilities(reasoning: boolean): ModelCapabilities {
      65+ return createModelCapabilities({
      66+ optionDescriptors: [
      67+ buildSelectOptionDescriptor({
      68+ id: "reasoningEffort",
      69+ label: "Reasoning",
      70+ options: [
      71+ { value: "off", label: "Off" },
      72+ { value: "minimal", label: "Minimal" },
      73+ { value: "low", label: "Low" },
      74+ { value: "medium", label: "Medium", isDefault: true },
      75+ { value: "high", label: "High" },
      76+ { value: "xhigh", label: "Extra High" },
      77+ { value: "max", label: "Max" },
      78+ ],
      79+ }),
      80+ ],
      81+ });
      82+}

      Pi ignores reasoning capability flag

      Medium Severity

      The reasoning flag in piModelCapabilities is not used to conditionally include the reasoningEffort option. This results in all models, even those without reasoning capabilities, incorrectly displaying the reasoningEffort control. The issue is compounded during RPC model discovery, where the Pi RPC reasoning field is ignored, and piModelCapabilities(true) is always applied.

      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 219abf457dcee016ac20a9e5d946d297ba365497. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -0,0 +691,21 @@
      691+ mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause),
      692+ });
      693+ yield* applyAcpReasoningConfig({
      694+ runtime: acp,
      695+ selections: hermesModelSelection?.options,
      696+ mapError: (cause) =>
      697+ mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_config_option", cause),
      698+ });
      699+
      700+ const now = yield* nowIso;
      701+ const session: ProviderSession = {
      702+ provider: PROVIDER,
      703+ providerInstanceId: boundInstanceId,
      704+ status: "ready",
      705+ runtimeMode: input.runtimeMode,
      706+ cwd,
      707+ ...(requestedStartModelId
      708+ ? { model: requestedStartModelId }
      709+ : boundModelId
      710+ ? { model: boundModelId }
      711+ : {}),

      Hermes stores ACP model encoding

      Medium Severity

      When no model selection is provided, startSession falls back to boundModelId from ACP, which is provider:model, and stores that on session.model. T3 catalogs and defaults use provider/model slugs (hermesModelSlugFromAcpModelId already exists for this). Grok normalizes before storing; Hermes does not, so session model state can fail to match catalog slugs.

      Additional Locations (1)
      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 219abf457dcee016ac20a9e5d946d297ba365497. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -0,0 +800,21 @@
      800+ };
      801+ const ctx: OpenClawSessionContext = {
      802+ threadId: input.threadId,
      803+ sessionKey: resolved.key,
      804+ session,
      805+ activeTurnId: undefined,
      806+ activeRunId: undefined,
      807+ interruptedTurnIds: new Set(),
      808+ pendingApprovals: new Map(),
      809+ stopped: false,
      810+ };
      811+ sessions.set(input.threadId, ctx);
      812+
      813+ yield* offerRuntimeEvent({
      814+ type: "session.started",
      815+ ...(yield* makeEventStamp()),
      816+ provider: PROVIDER,
      817+ providerInstanceId: boundInstanceId,
      818+ threadId: input.threadId,
      819+ payload: { resume: resumeKey !== undefined },
      820+ });

      OpenClaw resume flag wrong on recreate

      Medium Severity

      session.started sets resume from whether a resume cursor was supplied, not whether the existing gateway session was actually reused. When sessions.describe returns not-found and a fresh session is created, the event still reports resume: true.

      Additional Locations (1)
      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 219abf457dcee016ac20a9e5d946d297ba365497. Configure [here](https://www.cursor.com/dashboard/bugbot).
    7. Approvability

      Verdict: Needs human review

      3 blocking correctness issues found. Diff is too large for automated approval analysis. A human reviewer should evaluate this PR.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    8. @@ -0,0 +191,21 @@
      191+ isStreaming = true;
      192+ emitAgentStart();
      193+ emitExtensionUi();
      194+ if (emitExtensionError) {
      195+ writeRecord({ type: "extension_error", message: "mock extension failure" });
      196+ response("prompt", id, undefined, "extension_error");
      197+ isStreaming = false;
      198+ return;
      199+ }
      200+ if (failPrompt) {
      201+ response("prompt", id, undefined, "mock prompt failure");
      202+ isStreaming = false;
      203+ return;
      204+ }
      205+ if (hangPromptForever) {
      206+ // Ack the prompt but never emit agent events; the test aborts, and the
      207+ // abort handler below settles the run.
      208+ response("prompt", id, { ok: true });
      209+ return;
      210+ }
      211+ emitMockToolCalls();
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium scripts/pi-mock-agent.ts:211

      handlePrompt calls emitMockToolCalls() unconditionally, so every prompt — including the documented minimal happy-path with no T3_PI_* flags set — emits a full bash tool execution lifecycle (tool_execution_start, tool_execution_update, tool_execution_end). The emitToolCalls flag parsed from T3_PI_EMIT_TOOL_CALLS is never consulted, so tests that omit that flag still receive tool events and cannot use the mock to simulate a tool-free turn. Gate the call behind if (emitToolCalls) so tool events are only emitted when explicitly requested.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/scripts/pi-mock-agent.ts around line 211:
      
      `handlePrompt` calls `emitMockToolCalls()` unconditionally, so every prompt — including the documented minimal happy-path with no `T3_PI_*` flags set — emits a full `bash` tool execution lifecycle (`tool_execution_start`, `tool_execution_update`, `tool_execution_end`). The `emitToolCalls` flag parsed from `T3_PI_EMIT_TOOL_CALLS` is never consulted, so tests that omit that flag still receive tool events and cannot use the mock to simulate a tool-free turn. Gate the call behind `if (emitToolCalls)` so tool events are only emitted when explicitly requested.
      @@ -0,0 +650,21 @@
      650+ return;
      651+ }
      652+ if (event.method === "session/exited") {
      653+ const message = event.message ?? "Pi session exited.";
      654+ const exitKind = message.includes("code") ? "error" : "graceful";
      655+ // Clear run state so a later sendTurn cannot steer into the dead
      656+ // process's turn.
      657+ ctx.activeTurnId = undefined;
      658+ ctx.promptsInFlight = 0;
      659+ ctx.session = {
      660+ ...ctx.session,
      661+ status: exitKind === "error" ? "error" : "closed",
      662+ activeTurnId: undefined,
      663+ };
      664+ if (activeTurnId && exitKind === "error") {
      665+ yield* offerRuntimeEvent({
      666+ ...base,
      667+ type: "turn.completed",
      668+ payload: { state: "failed", errorMessage: message },
      669+ });
      670+ }
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Layers/PiAgentAdapter.ts:664

      When the Pi process exits with code 0 during an active turn, the turn is never completed — consumers receive session.exited but no turn.completed. The handler clears activeTurnId and emits turn.completed only when exitKind === "error", so a graceful exit leaves the active turn permanently unfinished. Consider emitting a turn.completed event for the active turn on every exit, not just error exits.

                  if (activeTurnId) {
      +             const interrupted = ctx.interruptedTurnIds.has(activeTurnId);
      +             ctx.interruptedTurnIds.delete(activeTurnId);
                    yield* offerRuntimeEvent({
                      ...base,
                      type: "turn.completed",
      -               payload: { state: "failed", errorMessage: message },
      +               payload: interrupted
      +                 ? { state: "interrupted" }
      +                 : exitKind === "error"
      +                   ? { state: "failed", errorMessage: message }
      +                   : { state: "cancelled", errorMessage: message },
                    });
                  }
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/PiAgentAdapter.ts around lines 664-670:
      
      When the Pi process exits with code 0 during an active turn, the turn is never completed — consumers receive `session.exited` but no `turn.completed`. The handler clears `activeTurnId` and emits `turn.completed` only when `exitKind === "error"`, so a graceful exit leaves the active turn permanently unfinished. Consider emitting a `turn.completed` event for the active turn on every exit, not just error exits.
      @@ -0,0 +133,21 @@
      133+ const cached = yield* Ref.make<Option.Option<OpenClawGatewayConnection>>(Option.none());
      134+ const mutex = yield* Semaphore.make(1);
      135+ return {
      136+ acquire: (input) =>
      137+ mutex.withPermit(
      138+ Effect.gen(function* () {
      139+ const existing = yield* Ref.get(cached);
      140+ if (Option.isSome(existing)) {
      141+ return existing.value;
      142+ }
      143+ const connection = yield* openClawRuntime
      144+ .connectToOpenClawGateway({
      145+ binaryPath: input.binaryPath,
      146+ ...(input.gatewayUrl?.trim() ? { gatewayUrl: input.gatewayUrl } : {}),
      147+ ...(input.gatewayToken?.trim() ? { gatewayToken: input.gatewayToken } : {}),
      148+ ...(input.environment !== undefined ? { environment: input.environment } : {}),
      149+ ...(input.stateDir !== undefined ? { stateDir: input.stateDir } : {}),
      150+ ...(input.launchArgs !== undefined ? { launchArgs: input.launchArgs } : {}),
      151+ })
      152+ .pipe(Effect.provideService(Scope.Scope, gatewayScope));
      153+ yield* Ref.set(cached, Option.some(connection));
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Layers/OpenClawAdapter.ts:153

      After the gateway WebSocket closes or the spawned process exits, acquire keeps returning the cached OpenClawGatewayConnection forever. Subsequent startSession, sendTurn, and other calls reuse the dead connection instead of reconnecting, so the provider stays unusable until the entire driver scope is recreated. The holder caches the connection in cached but never clears it when markSessionsClosed fires on the closed event or the process exits. Consider resetting cached to Option.none() when the connection's events stream emits closed, so acquire reconnects on the next call.

      -            yield* Ref.set(cached, Option.some(connection));
      +            yield* Ref.set(cached, Option.some(connection));
      +            yield* connection.events.pipe(
      +              Stream.runForEach((event) =>
      +                event.kind === "closed"
      +                  ? Ref.set(cached, Option.none())
      +                  : Effect.void
      +              ),
      +              Effect.forkScoped,
      +            );
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/OpenClawAdapter.ts around line 153:
      
      After the gateway WebSocket closes or the spawned process exits, `acquire` keeps returning the cached `OpenClawGatewayConnection` forever. Subsequent `startSession`, `sendTurn`, and other calls reuse the dead connection instead of reconnecting, so the provider stays unusable until the entire driver scope is recreated. The holder caches the connection in `cached` but never clears it when `markSessionsClosed` fires on the `closed` event or the process exits. Consider resetting `cached` to `Option.none()` when the connection's `events` stream emits `closed`, so `acquire` reconnects on the next call.
      @@ -0,0 +458,21 @@
      458+ const phase = asString(data.phase);
      459+ if (phase === "end") {
      460+ yield* emitTurnCompleted(ctx, "completed");
      461+ } else if (phase === "error") {
      462+ const message =
      463+ trimText(data.error) ?? trimText(data.message) ?? "OpenClaw agent run failed.";
      464+ yield* emitTurnCompleted(ctx, "failed", { errorMessage: message });
      465+ yield* offerRuntimeEvent({
      466+ type: "runtime.error",
      467+ ...(yield* makeEventStamp()),
      468+ ...base,
      469+ payload: { message, class: "provider_error", detail: data },
      470+ });
      471+ }
      472+ return;
      473+ }
      474+ case "assistant": {
      475+ const delta = trimText(data.delta) ?? trimText(data.text);
      476+ if (!delta) {
      477+ return;
      478+ }
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/OpenClawAdapter.ts:474

      handleAgentEvent trims every assistant and thinking delta with trimText, stripping leading/trailing whitespace from each chunk. When a streaming delta arrives with boundary whitespace (e.g. " hello " then "world"), consumers concatenating content.delta events receive "helloworld" instead of " hello world". Use the raw data.delta/data.text value and only skip chunks when the field is absent or not a string, rather than discarding whitespace-only chunks.

            case "assistant": {
      -        const delta = trimText(data.delta) ?? trimText(data.text);
      -        if (!delta) {
      +        const delta = asString(data.delta) ?? asString(data.text);
      +        if (delta === undefined) {
                return;
              }
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/OpenClawAdapter.ts around lines 474-478:
      
      `handleAgentEvent` trims every `assistant` and `thinking` delta with `trimText`, stripping leading/trailing whitespace from each chunk. When a streaming delta arrives with boundary whitespace (e.g. `" hello "` then `"world"`), consumers concatenating `content.delta` events receive `"helloworld"` instead of `" hello world"`. Use the raw `data.delta`/`data.text` value and only skip chunks when the field is absent or not a string, rather than discarding whitespace-only chunks.
      @@ -0,0 +225,21 @@
      225+ * handshake (version) + `models.list`. The connection is scoped to the probe.
      226+ */
      227+const probeExternalGateway = (
      228+ openClawRuntime: OpenClawRuntimeShape,
      229+ openClawSettings: OpenClawSettings,
      230+ environment: NodeJS.ProcessEnv,
      231+): Effect.Effect<
      232+ { readonly version: string; readonly models: ReadonlyArray<ServerProviderModel> },
      233+ unknown
      234+> =>
      235+ Effect.scoped(
      236+ Effect.gen(function* () {
      237+ const connection = yield* openClawRuntime.connectToOpenClawGateway({
      238+ binaryPath: openClawSettings.binaryPath,
      239+ gatewayUrl: openClawSettings.gatewayUrl,
      240+ ...(openClawSettings.gatewayToken?.trim()
      241+ ? { gatewayToken: openClawSettings.gatewayToken }
      242+ : {}),
      243+ environment,
      244+ });
      245+ const catalogResult = yield* loadGatewayModels(connection).pipe(Effect.result);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/OpenClawProvider.ts:245

      probeExternalGateway has no timeout around loadGatewayModels(connection), so if the external gateway completes the handshake but never responds to models.list, checkOpenClawProviderStatus hangs indefinitely. Both CLI probes (--version and models list) are bounded by Effect.timeoutOption, but the gateway models.list request is not. Apply a timeout (e.g. MODEL_PROBE_TIMEOUT_MS) and fall back to the static catalog on expiry, the same way the CLI path already does.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/OpenClawProvider.ts around line 245:
      
      `probeExternalGateway` has no timeout around `loadGatewayModels(connection)`, so if the external gateway completes the handshake but never responds to `models.list`, `checkOpenClawProviderStatus` hangs indefinitely. Both CLI probes (`--version` and `models list`) are bounded by `Effect.timeoutOption`, but the gateway `models.list` request is not. Apply a timeout (e.g. `MODEL_PROBE_TIMEOUT_MS`) and fall back to the static catalog on expiry, the same way the CLI path already does.
      @@ -0,0 +119,21 @@
      119+ accentColor,
      120+ continuationGroupKey: continuationIdentity.continuationKey,
      121+ });
      122+ const effectiveConfig = { ...config, enabled } satisfies OpenClawSettings;
      123+ const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
      124+ binaryPath: effectiveConfig.binaryPath,
      125+ env: processEnv,
      126+ });
      127+
      128+ // One gateway per instance, shared by the adapter and text generation.
      129+ // The scope owns the spawned gateway process; closing it on teardown
      130+ // kills the child and interrupts the event pump.
      131+ const gatewayScope = yield* Scope.make();
      132+ yield* Effect.addFinalizer(() => Scope.close(gatewayScope, Exit.void).pipe(Effect.ignore));
      133+ const gateway = yield* makeOpenClawGatewayHolder(gatewayScope);
      134+
      135+ // Spawned gateways get an isolated state dir under the T3 instance state
      136+ // so they never touch a user's `~/.openclaw`.
      137+ const stateDir = path.join(serverConfig.stateDir, "providers", "openclaw", instanceId);
      138+
      139+ const adapter = yield* makeOpenClawAdapter(effectiveConfig, {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Drivers/OpenClawDriver.ts:139

      The adapter's scope finalizer calls nativeEventLogger.close(), but the logger passed in is the shared, process-wide ProviderEventLoggers.native instance. Closing that logger stops native event logging for every remaining provider instance. Consider not passing the shared logger as an adapter-owned resource, or wrapping it per-adapter so one teardown cannot close the shared writer.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Drivers/OpenClawDriver.ts around line 139:
      
      The adapter's scope finalizer calls `nativeEventLogger.close()`, but the logger passed in is the shared, process-wide `ProviderEventLoggers.native` instance. Closing that logger stops native event logging for every remaining provider instance. Consider not passing the shared logger as an adapter-owned resource, or wrapping it per-adapter so one teardown cannot close the shared writer.
      @@ -0,0 +1162,21 @@
      1162+ }),
      1163+ );
      1164+ }).pipe(
      1165+ Effect.ensuring(
      1166+ Effect.gen(function* () {
      1167+ if (yield* Ref.get(promptSettled)) {
      1168+ return;
      1169+ }
      1170+
      1171+ const promptResult = yield* Ref.get(promptResultRef);
      1172+ if (promptResult !== undefined) {
      1173+ const liveCtx = sessions.get(input.threadId);
      1174+ if (liveCtx && !liveCtx.stopped && liveCtx.acpSessionId === prepared.acpSessionId) {
      1175+ appendPromptResultToTurn(
      1176+ liveCtx,
      1177+ prepared.turnId,
      1178+ prepared.promptParts,
      1179+ promptResult,
      1180+ );
      1181+ }
      1182+ yield* withThreadLock(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/HermesAdapter.ts:1166

      readThread returns corrupted turn history with duplicate prompt entries. When the main settlement path appends a prompt result at line 1104 but the fiber is interrupted before promptSettled is set, the Effect.ensuring cleanup at line 1175 appends the same result again because it only checks promptResultRef, not whether the append already happened. Consider tracking the append state in the same Ref that guards settlement, or making appendPromptResultToTurn idempotent.

                 Effect.gen(function* () {
                   if (yield* Ref.get(promptSettled)) {
                     return;
                   }
      
                   const promptResult = yield* Ref.get(promptResultRef);
                   if (promptResult !== undefined) {
      +              yield* Ref.set(promptSettled, true);
                     const liveCtx = sessions.get(input.threadId);
                     if (liveCtx && !liveCtx.stopped && liveCtx.acpSessionId === prepared.acpSessionId) {
                       appendPromptResultToTurn(
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/HermesAdapter.ts around lines 1166-1182:
      
      `readThread` returns corrupted turn history with duplicate prompt entries. When the main settlement path appends a prompt result at line 1104 but the fiber is interrupted before `promptSettled` is set, the `Effect.ensuring` cleanup at line 1175 appends the same result again because it only checks `promptResultRef`, not whether the append already happened. Consider tracking the append state in the same `Ref` that guards settlement, or making `appendPromptResultToTurn` idempotent.
      @@ -0,0 +290,21 @@
      290+ emitEvent({ kind: "session", threadId: options.threadId, method, message });
      291+
      292+ /** Write one JSON record to the pi process stdin, serialized by a mutex. */
      293+ const writeLine = (record: unknown) =>
      294+ stdinMutex.withPermits(1)(
      295+ Effect.gen(function* () {
      296+ const encoded = `${JSON.stringify(record)}\n`;
      297+ yield* Stream.run(Stream.encodeText(Stream.make(encoded)), child.stdin).pipe(
      298+ Effect.mapError(
      299+ (cause) =>
      300+ new PiSessionRuntimeError({
      301+ operation: "write",
      302+ detail: `Failed to write to pi process: ${cause.message ?? String(cause)}`,
      303+ cause,
      304+ }),
      305+ ),
      306+ );
      307+ }),
      308+ );
      309+
      310+ const failAllPendingRpcs = (detail: string) =>
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/PiAgentSessionRuntime.ts:310

      failAllPendingRpcs calls Ref.get(pendingRpcRef), then later Ref.set(pendingRpcRef, new Map()). A concurrent sendCommand that inserts its entry between those two operations has its deferred silently overwritten by the empty map, so the caller hangs until the full RPC timeout instead of receiving the close/process-exit failure. The snapshot-and-clear must be atomic — use Ref.getAndSet so the old map is captured and replaced in one step.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/PiAgentSessionRuntime.ts around line 310:
      
      `failAllPendingRpcs` calls `Ref.get(pendingRpcRef)`, then later `Ref.set(pendingRpcRef, new Map())`. A concurrent `sendCommand` that inserts its entry between those two operations has its deferred silently overwritten by the empty map, so the caller hangs until the full RPC timeout instead of receiving the close/process-exit failure. The snapshot-and-clear must be atomic — use `Ref.getAndSet` so the old map is captured and replaced in one step.
      @@ -0,0 +163,21 @@
      163+ }
      164+ if (isRecord(entry)) {
      165+ if (entry.available === false || entry.missing === true) {
      166+ continue;
      167+ }
      168+ const rawId = typeof entry.id === "string" ? entry.id : entry.key;
      169+ const id = typeof rawId === "string" ? rawId.trim() : undefined;
      170+ if (id) {
      171+ entries.push({
      172+ id,
      173+ ...(typeof entry.name === "string" && entry.name.trim()
      174+ ? { name: entry.name.trim() }
      175+ : {}),
      176+ });
      177+ }
      178+ }
      179+ }
      180+ return entries;
      181+ };
      182+
      183+ if (!isRecord(payload)) {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Layers/OpenClawProvider.ts:183

      parseOpenClawModelsList returns undefined when the gateway/CLI reports a valid catalog with zero usable models (e.g., every entry has available: false or missing: true). Both probe paths treat undefined as "unrecognized payload" and fall back to OPENCLAW_BUILT_IN_MODELS, so the provider advertises models the gateway explicitly marked unavailable. Selecting one leads to avoidable session failures. Distinguish a successfully parsed empty catalog from an unrecognized payload so the fallback to built-in models only happens when nothing could be parsed.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/OpenClawProvider.ts around line 183:
      
      `parseOpenClawModelsList` returns `undefined` when the gateway/CLI reports a valid catalog with zero usable models (e.g., every entry has `available: false` or `missing: true`). Both probe paths treat `undefined` as "unrecognized payload" and fall back to `OPENCLAW_BUILT_IN_MODELS`, so the provider advertises models the gateway explicitly marked unavailable. Selecting one leads to avoidable session failures. Distinguish a successfully parsed empty catalog from an unrecognized payload so the fallback to built-in models only happens when nothing could be parsed.
      @@ -0,0 +812,21 @@
      812+ case "ContentDelta":
      813+ yield* offerRuntimeEvent(
      814+ makeAcpContentDeltaEvent({
      815+ stamp,
      816+ provider: PROVIDER,
      817+ threadId: ctx.threadId,
      818+ turnId: notificationTurnId,
      819+ ...(event.itemId ? { itemId: event.itemId } : {}),
      820+ text: event.text,
      821+ rawPayload: event.rawPayload,
      822+ }),
      823+ );
      824+ return;
      825+ }
      826+ }),
      827+ ),
      828+ ).pipe(
      829+ Effect.catch((cause) =>
      830+ Effect.logError("Failed to process Hermes runtime notification.", { cause }),
      831+ ),
      832+ Effect.forkChild,
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Layers/HermesAdapter.ts:832

      The ACP notification drain stream is forked with Effect.forkChild, so it is supervised by the startSession fiber rather than the long-lived sessionScope. When startSession returns, Effect interrupts its child fibers, killing the notification drain. As a result, all subsequent Hermes ACP notifications (ContentDelta, tool calls, plans, etc.) stop being forwarded to runtimeEventPubSub even though the session is still active. Use Effect.forkIn(sessionScope) instead of Effect.forkChild so the drain survives until stopSessionInternal closes the scope.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/HermesAdapter.ts around line 832:
      
      The ACP notification drain stream is forked with `Effect.forkChild`, so it is supervised by the `startSession` fiber rather than the long-lived `sessionScope`. When `startSession` returns, Effect interrupts its child fibers, killing the notification drain. As a result, all subsequent Hermes ACP notifications (`ContentDelta`, tool calls, plans, etc.) stop being forwarded to `runtimeEventPubSub` even though the session is still active. Use `Effect.forkIn(sessionScope)` instead of `Effect.forkChild` so the drain survives until `stopSessionInternal` closes the scope.
      @@ -0,0 +201,21 @@
      201+ response("prompt", id, undefined, "mock prompt failure");
      202+ isStreaming = false;
      203+ return;
      204+ }
      205+ if (hangPromptForever) {
      206+ // Ack the prompt but never emit agent events; the test aborts, and the
      207+ // abort handler below settles the run.
      208+ response("prompt", id, { ok: true });
      209+ return;
      210+ }
      211+ emitMockToolCalls();
      212+ writeRecord({ type: "turn_start" });
      213+ emitMessageTurn();
      214+ writeRecord({ type: "turn_end", message: { id: "mock-msg-1" }, toolResults: [] });
      215+ // Ack the prompt immediately; the agent keeps working until it settles
      216+ // (settleDelayMs is only about agent_end/agent_settled).
      217+ response("prompt", id, { ok: true });
      218+ setTimeout(() => {
      219+ emitAgentEnd();
      220+ emitAgentSettled();
      221+ }, settleDelayMs);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium scripts/pi-mock-agent.ts:218

      The setTimeout at line 218 is never stored or cancelled, so aborting a delayed run produces duplicate agent_end/agent_settled events when the orphaned timer fires. Worse, if a new prompt starts before that timer expires, its callback sets isStreaming=false and emits terminal events for the new run, corrupting its lifecycle. Save the timer handle and clearTimeout it in handleAbort before emitting the terminal events.

        setTimeout(() => {
      +    settleTimer = undefined;
          emitAgentEnd();
          emitAgentSettled();
        }, settleDelayMs);
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/scripts/pi-mock-agent.ts around lines 218-221:
      
      The `setTimeout` at line 218 is never stored or cancelled, so aborting a delayed run produces duplicate `agent_end`/`agent_settled` events when the orphaned timer fires. Worse, if a new prompt starts before that timer expires, its callback sets `isStreaming=false` and emits terminal events for the new run, corrupting its lifecycle. Save the timer handle and `clearTimeout` it in `handleAbort` before emitting the terminal events.
      @@ -0,0 +696,21 @@
      696+ });
      697+
      698+ const startSession: OpenClawAdapterShape["startSession"] = (input) =>
      699+ Effect.gen(function* () {
      700+ if (input.provider !== undefined && input.provider !== PROVIDER) {
      701+ return yield* new ProviderAdapterValidationError({
      702+ provider: PROVIDER,
      703+ operation: "startSession",
      704+ issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
      705+ });
      706+ }
      707+ if (!input.cwd?.trim()) {
      708+ return yield* new ProviderAdapterValidationError({
      709+ provider: PROVIDER,
      710+ operation: "startSession",
      711+ issue: "cwd is required and must be non-empty.",
      712+ });
      713+ }
      714+ const cwd = path.resolve(input.cwd.trim());
      715+ const existing = sessions.get(input.threadId);
      716+ if (existing && !existing.stopped) {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Layers/OpenClawAdapter.ts:716

      stopAll calls stopSessionInternal directly, so it never sends chat.abort for sessions with an active run — OpenClaw keeps generating remotely after the local context is deleted, with no way for this adapter to interrupt the orphaned run. The same problem occurs in startSession: replacing an existing session calls stopSessionInternal(existing) instead of the aborting stopSession path, so an active run on the old context continues in the background after the new context is installed. Both paths should go through stopSession (or otherwise send chat.abort before deleting the context) so in-flight runs are cancelled.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/OpenClawAdapter.ts around line 716:
      
      `stopAll` calls `stopSessionInternal` directly, so it never sends `chat.abort` for sessions with an active run — OpenClaw keeps generating remotely after the local context is deleted, with no way for this adapter to interrupt the orphaned run. The same problem occurs in `startSession`: replacing an existing session calls `stopSessionInternal(existing)` instead of the aborting `stopSession` path, so an active run on the old context continues in the background after the new context is installed. Both paths should go through `stopSession` (or otherwise send `chat.abort` before deleting the context) so in-flight runs are cancelled.
      @@ -0,0 +203,21 @@
      203+ decision === "acceptForSession"
      204+ ? (["allow_session", "allow_always"] as const)
      205+ : decision === "accept"
      206+ ? (["allow_once"] as const)
      207+ : (["deny", "deny_always"] as const);
      208+ for (const optionId of preferredIds) {
      209+ if (request.options.some((entry) => entry.optionId === optionId)) {
      210+ return optionId;
      211+ }
      212+ }
      213+ const kind =
      214+ decision === "acceptForSession"
      215+ ? "allow_always"
      216+ : decision === "accept"
      217+ ? "allow_once"
      218+ : "reject_once";
      219+ const byKind = request.options.find((entry) => entry.kind === kind);
      220+ return byKind?.optionId.trim() || acpPermissionOutcome(decision);
      221+}
      222+
      223+function selectAutoApprovedHermesPermissionOption(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Layers/HermesAdapter.ts:223

      selectAutoApprovedHermesPermissionOption never reaches its "accept" fallback. When a permission request offers only allow_once, full-access mode sends the synthetic allow-always outcome string as the option ID. Hermes does not recognize that ID and maps it to denial, so a permission that should be auto-approved is denied. The issue is that selectHermesPermissionOptionId falls back to acpPermissionOutcome(decision) (which returns "allow-always" for "acceptForSession") when no matching option is present, producing a non-undefined return that short-circuits the ?? chain. Consider checking whether the selected value is actually one of request.options before returning it, or excluding the acpPermissionOutcome fallback in the auto-approve path so undefined propagates and the "accept" alternative is tried.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/HermesAdapter.ts around line 223:
      
      `selectAutoApprovedHermesPermissionOption` never reaches its `"accept"` fallback. When a permission request offers only `allow_once`, full-access mode sends the synthetic `allow-always` outcome string as the option ID. Hermes does not recognize that ID and maps it to denial, so a permission that should be auto-approved is denied. The issue is that `selectHermesPermissionOptionId` falls back to `acpPermissionOutcome(decision)` (which returns `"allow-always"` for `"acceptForSession"`) when no matching option is present, producing a non-`undefined` return that short-circuits the `??` chain. Consider checking whether the selected value is actually one of `request.options` before returning it, or excluding the `acpPermissionOutcome` fallback in the auto-approve path so `undefined` propagates and the `"accept"` alternative is tried.
      @@ -0,0 +461,21 @@
      461+ trimText(typeof request.title === "string" ? request.title : undefined) ?? "Pi request";
      462+ const message = trimText(typeof request.message === "string" ? request.message : undefined);
      463+ const question = message ?? header;
      464+
      465+ if (method === "confirm") {
      466+ return [
      467+ {
      468+ id: `${requestId}:confirm`,
      469+ header,
      470+ question,
      471+ options: [
      472+ { label: "Allow", description: "Allow the requested action" },
      473+ { label: "Deny", description: "Deny the requested action" },
      474+ ],
      475+ },
      476+ ];
      477+ }
      478+
      479+ const rawOptions = Array.isArray(request.options) ? request.options : [];
      480+ const options = rawOptions
      481+ .map((entry): UserInputQuestion["options"][number] | undefined => {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Layers/PiAgentAdapter.ts:481

      select requests discard each option's protocol value and expose only its display label. When the user picks an option, respondToUserInput sends that label back to Pi as value. For any request where option values differ from labels (e.g. { value: "model-id", label: "Model Name" }), Pi receives "Model Name" instead of "model-id", so the user's selection is misinterpreted or rejected. Consider preserving a label-to-value mapping when the pending request is created so the answer can be translated back to the original value before responding.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/PiAgentAdapter.ts around line 481:
      
      `select` requests discard each option's protocol `value` and expose only its display `label`. When the user picks an option, `respondToUserInput` sends that label back to Pi as `value`. For any request where option values differ from labels (e.g. `{ value: "model-id", label: "Model Name" }`), Pi receives `"Model Name"` instead of `"model-id"`, so the user's selection is misinterpreted or rejected. Consider preserving a label-to-value mapping when the pending request is created so the answer can be translated back to the original value before responding.
      @@ -0,0 +953,21 @@
      953+
      954+ const ctx: PiSessionContext = {
      955+ threadId: input.threadId,
      956+ scope: sessionScope,
      957+ runtime,
      958+ eventFiber: undefined,
      959+ session,
      960+ activeTurnId: undefined,
      961+ promptsInFlight: 0,
      962+ interruptedTurnIds: new Set(),
      963+ pendingUserInputs: new Map(),
      964+ stopped: false,
      965+ };
      966+
      967+ const eventFiber = yield* Stream.runForEach(runtime.events, (event) =>
      968+ handlePiEvent(ctx, event).pipe(
      969+ Effect.catch((cause) =>
      970+ Effect.logError("Failed to process Pi runtime notification.", { cause }),
      971+ ),
      972+ ),
      973+ ).pipe(Effect.forkChild);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Layers/PiAgentAdapter.ts:973

      The Pi event consumer fiber is forked with Effect.forkChild inside the Effect.scoped wrapping startSession, so the scope closes and interrupts the fiber when startSession returns — even though sessionScope was transferred separately. This stops all Pi event processing after startup: assistant output, tool events, agent_settled, extension requests, and process exit are never consumed, so turns hang and clients receive no runtime updates. Fork the consumer into sessionScope instead so it survives the startSession scope.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/PiAgentAdapter.ts around line 973:
      
      The Pi event consumer fiber is forked with `Effect.forkChild` inside the `Effect.scoped` wrapping `startSession`, so the scope closes and interrupts the fiber when `startSession` returns — even though `sessionScope` was transferred separately. This stops all Pi event processing after startup: assistant output, tool events, `agent_settled`, extension requests, and process exit are never consumed, so turns hang and clients receive no runtime updates. Fork the consumer into `sessionScope` instead so it survives the `startSession` scope.
    9. Note

      🤖 GPT-5.6 Sol responding on behalf of Theo

      Closing this PR after an automated pass over open pull requests. Adds OpenClaw, Hermes, and PiAgent together across 78 files.

Sign in to join this conversation.