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 into
main fromrefs/pull/5505/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- @@ -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";@@ -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+);@@ -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 protocol149+ * 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+}@@ -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+}
- @@ -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+);@@ -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+}@@ -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 protocol149+ * 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+}@@ -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";
- @@ -297,4 +337,12 @@297337 return { relativePath: target.relativePath };298338 });299339300- 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(@@ -321 +373,21 @@321373374+ // Directory reveals (e.g. right after creating a folder) expand ancestors375+ // and select the row once per request, without touching the file-selection376+ // 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 = "";@@ -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 a165+ * single trailing `\r`; `StringDecoder` handles UTF-8 multi-byte sequences166+ * that span chunk boundaries.167+ */168+export function makePiRecordSplitter(): {
- @@ -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+}@@ -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+ ...(requestedStartModelId708+ ? { model: requestedStartModelId }709+ : boundModelId710+ ? { model: boundModelId }711+ : {}),@@ -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+ });
- @@ -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 the207+ // abort handler below settles the run.208+ response("prompt", id, { ok: true });209+ return;210+ }211+ emitMockToolCalls();@@ -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 dead656+ // 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+ }@@ -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* openClawRuntime144+ .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));@@ -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+ }@@ -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+ unknown234+> =>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);@@ -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 teardown130+ // 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 state136+ // 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, {@@ -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(@@ -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) =>@@ -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)) {@@ -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,@@ -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 the207+ // 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 settles216+ // (settleDelayMs is only about agent_end/agent_settled).217+ response("prompt", id, { ok: true });218+ setTimeout(() => {219+ emitAgentEnd();220+ emitAgentSettled();221+ }, settleDelayMs);@@ -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) {@@ -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(@@ -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 = rawOptions481+ .map((entry): UserInputQuestion["options"][number] | undefined => {@@ -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);
t3dotgg(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
3ce0fd77-5e2f-424e-af1d-c78dac55fed2You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
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