ronantakizawa/codereview-bench huggingface dataset:
Repository: basecamp/omarchy
File: install/config/powerprofilesctl-rules.sh (Shell)

Code before:
if omarchy-battery-present; then
  mapfile -t profiles < <(omarchy-powerprofiles-list)

  if [[ ${#profiles[@]} -eq 0 ]]; then
    echo "Error: No power profiles available"
    exit 1
  fi

  # Default AC profile:
  # 3 profiles → performance
  # 2 profiles → balanced
  # 1 profile  → profiles[0]
  ac_profile="${profiles[2]:-${profiles[1]:-${profiles[0]}}}"

  # Default Battery profile:
  # 3 profiles → balanced
  # 2 profiles → balanced
  # 1 profile  → profiles[0]
  battery_profile="${profiles[1]:-${profiles[0]}}"

  cat <<EOF | sudo tee "/etc/udev/rules.d/99-power-profile.rules"
SUBSYSTEM=="power_supply", ATTR{type}=="Mains", ATTR{online}=="0", RUN+="/usr/bin/powerprofilesctl set $battery_profile"
SUBSYSTEM=="power_supply", ATTR{type}=="Mains", ATTR{online}=="1", RUN+="/usr/bin/powerprofilesctl set $ac_profile"
EOF

  sudo udevadm control --reload
  sudo udevadm trigger --subsystem-match=power_supply
fi


Review comment (suggestion):
Since this is running during setup, we don't want any error message output or exits. So think just wrap everything in this conditional, rather than treating it as a precondition.

Code after:
if omarchy-battery-present; then
  mapfile -t profiles < <(omarchy-powerprofiles-list)

  if [[ ${#profiles[@]} -gt 0 ]]; then

    # Default AC profile:
    # 3 profiles → performance
    # 2 profiles → balanced
    # 1 profile  → profiles[0]
    ac_profile="${profiles[2]:-${profiles[1]:-${profiles[0]}}}"

    # Default Battery profile:
    # 3 profiles → balanced
    # 2 profiles → balanced
    # 1 profile  → profiles[0]
    battery_profile="${profiles[1]:-${profiles[0]}}"

    cat <<EOF | sudo tee "/etc/udev/rules.d/99-power-profile.rules"
SUBSYSTEM=="power_supply", ATTR{type}=="Mains", ATTR{online}=="0", RUN+="/usr/bin/powerprofilesctl set $battery_profile"
SUBSYSTEM=="power_supply", ATTR{type}=="Mains", ATTR{online}=="1", RUN+="/usr/bin/powerprofilesctl set $ac_profile"
EOF

    sudo udevadm control --reload
    sudo udevadm trigger --subsystem-match=power_supply
  fi
fi
Repository: browserbase/stagehand
File: lib/StagehandPage.ts (TypeScript)

Code before:
      variables = {},
      domSettleTimeoutMs,
      slowDomBasedAct = false,
    } = actionOrOptions;

    if (typeof useVision !== "undefined") {
      this.stagehand.log({
        category: "deprecation",
        message:
          "Warning: vision is not supported in this version of Stagehand",
        level: 1,
      });
    }

    if (this.api) {
      const result = await this.api.act(actionOrOptions);
      await this._refreshPageFromAPI();
      return result;
    }

    const requestId = Math.random().toString(36).substring(2);
    const llmClient: LLMClient = modelName
      ? this.stagehand.llmProvider.getClient(modelName, modelClientOptions)
      : this.llmClient;

    if (!slowDomBasedAct) {
      const observeResults = await this.observe({
        instruction: `Find the action that is most relevant to the following action: ${action}. Only return one action.`,
        modelName,
        modelClientOptions,
        domSettleTimeoutMs,
        returnAction: true,
        drawOverlay: true,
      });

      if (observeResults.length === 0) {
        throw new Error("No observe results found");
      }

      const observeResult = observeResults[0];

      return this.actHandler.actFromObserveResult(observeResult);
    }

    this.stagehand.log({
      category: "act",
      message: "running act",
      level: 1,
      auxiliary: {
        action: {
          value: action,

Review comment (performance):
We need to account for `selfHeal:true/false` It basically automatically tries the slowDom approach whenever act from observeResult throws an error

Code after:
      variables = {},
      domSettleTimeoutMs,
      slowDomBasedAct = false,
    } = actionOrOptions;

    if (typeof useVision !== "undefined") {
      this.stagehand.log({
        category: "deprecation",
        message:
          "Warning: vision is not supported in this version of Stagehand",
        level: 1,
      });
    }

    if (this.api) {
      const result = await this.api.act(actionOrOptions);
      await this._refreshPageFromAPI();
      return result;
    }

    const requestId = Math.random().toString(36).substring(2);
    const llmClient: LLMClient = modelName
      ? this.stagehand.llmProvider.getClient(modelName, modelClientOptions)
      : this.llmClient;

    if (!slowDomBasedAct) {
      return this.actHandler.observeAct(action);
    }

    this.stagehand.log({
      category: "act",
      message: "running act",
      level: 1,
      auxiliary: {
        action: {
          value: action,
          type: "string",
        },
        requestId: {
          value: requestId,
          type: "string",
        },
        modelName: {
          value: llmClient.modelName,
          type: "string",
        },
      },
    });

    // `useVision` is no longer passed to the handler
    return this.actHandler
Repository: browserbase/stagehand
File: types/stagehand.ts (TypeScript)

Code before:
  /**
   * Customize the Stagehand system prompt
   */
  systemPrompt?: string;
  /**
   * Offload Stagehand method calls to the Stagehand API.
   * Must have a valid API key to use
   */
  useAPI?: boolean;
  /**
   * Wait for captchas to be solved after navigation when using Browserbase environment.
   *
   * @default false
   */
  waitForCaptchaSolves?: boolean;
  /**
   * The parameters to use for launching a local browser
   */
  localBrowserLaunchOptions?: LocalBrowserLaunchOptions;
  /**
   * Log the inference to a file
   */
  logInferenceToFile?: boolean;
  selfHeal?: boolean;
  /**
   * Whether Stagehand is running in a test environment
   */
  disablePino?: boolean;
}

export interface InitResult {
  debugUrl: string;
  sessionUrl: string;
  sessionId: string;
}

export interface ActOptions {
  action: string;
  modelName?: AvailableModel;
  modelClientOptions?: ClientOptions;
  variables?: Record<string, string>;
  domSettleTimeoutMs?: number;
  timeoutMs?: number;
}

export interface ActResult {
  success: boolean;
  message: string;
  action: string;
}


Review comment (suggestion):
```suggestion
   * Disable Pino (helpful for Next.js or test environments)
```

Code after:
  /**
   * Customize the Stagehand system prompt
   */
  systemPrompt?: string;
  /**
   * Offload Stagehand method calls to the Stagehand API.
   * Must have a valid API key to use
   */
  useAPI?: boolean;
  /**
   * Wait for captchas to be solved after navigation when using Browserbase environment.
   *
   * @default false
   */
  waitForCaptchaSolves?: boolean;
  /**
   * The parameters to use for launching a local browser
   */
  localBrowserLaunchOptions?: LocalBrowserLaunchOptions;
  /**
   * Log the inference to a file
   */
  logInferenceToFile?: boolean;
  selfHeal?: boolean;
  /**
   * Disable Pino (helpful for Next.js or test environments)
   */
  disablePino?: boolean;
}

export interface InitResult {
  debugUrl: string;
  sessionUrl: string;
  sessionId: string;
}

export interface ActOptions {
  action: string;
  modelName?: AvailableModel;
  modelClientOptions?: ClientOptions;
  variables?: Record<string, string>;
  domSettleTimeoutMs?: number;
  timeoutMs?: number;
}

export interface ActResult {
  success: boolean;
  message: string;
  action: string;
}
Repository: browserbase/stagehand
File: lib/llm/LLMProvider.ts (TypeScript)

Code before:
  openai,
  anthropic,
  google,
  xai,
  azure,
  groq,
  cerebras,
  togetherai,
  mistral,
  deepseek,
  perplexity,
  ollama,
};
const AISDKProvidersWithAPIKey: Record<string, AISDKCreator> = {
  openai: createOpenAI,
  anthropic: createAnthropic,
  google: createGoogleGenerativeAI,
  xai: createXai,
  azure: createAzure,
  groq: createGroq,
  cerebras: createCerebras,
  togetherai: createTogetherAI,
  mistral: createMistral,
  deepseek: createDeepSeek,
  perplexity: createPerplexity,
};

const modelToProviderMap: { [key in AvailableModel]: ModelProvider } = {
  "gpt-4.1": "openai",
  "gpt-4.1-mini": "openai",
  "gpt-4.1-nano": "openai",
  "o4-mini": "openai",
  //prettier-ignore
  "o3": "openai",
  "o3-mini": "openai",
  //prettier-ignore
  "o1": "openai",
  "o1-mini": "openai",
  "gpt-4o": "openai",
  "gpt-4o-mini": "openai",
  "gpt-4o-2024-08-06": "openai",
  "gpt-4.5-preview": "openai",
  "o1-preview": "openai",
  "claude-3-5-sonnet-latest": "anthropic",
  "claude-3-5-sonnet-20240620": "anthropic",
  "claude-3-5-sonnet-20241022": "anthropic",
  "claude-3-7-sonnet-20250219": "anthropic",
  "claude-3-7-sonnet-latest": "anthropic",
  "cerebras-llama-3.3-70b": "cerebras",
  "cerebras-llama-3.1-8b": "cerebras",
  "groq-llama-3.3-70b-versatile": "groq",

Review comment (suggestion):
if we override, then this is not needed. For example, AI SDK returns `openai`, `anthropic`, ... and so on, which are essentially constants returned from `createOpenAI`, `createAnthropic`,... in the same package. It is possible to define:
```ts
const openai = createOpenAI({})
```

Code after:
  openai,
  anthropic,
  google,
  xai,
  azure,
  groq,
  cerebras,
  togetherai,
  mistral,
  deepseek,
  perplexity,
  ollama,
};
const AISDKProvidersWithAPIKey: Record<string, AISDKCustomProvider> = {
  openai: createOpenAI,
  anthropic: createAnthropic,
  google: createGoogleGenerativeAI,
  xai: createXai,
  azure: createAzure,
  groq: createGroq,
  cerebras: createCerebras,
  togetherai: createTogetherAI,
  mistral: createMistral,
  deepseek: createDeepSeek,
  perplexity: createPerplexity,
};

const modelToProviderMap: { [key in AvailableModel]: ModelProvider } = {
  "gpt-4.1": "openai",
  "gpt-4.1-mini": "openai",
  "gpt-4.1-nano": "openai",
  "o4-mini": "openai",
  //prettier-ignore
  "o3": "openai",
  "o3-mini": "openai",
  //prettier-ignore
  "o1": "openai",
  "o1-mini": "openai",
  "gpt-4o": "openai",
  "gpt-4o-mini": "openai",
  "gpt-4o-2024-08-06": "openai",
  "gpt-4.5-preview": "openai",
  "o1-preview": "openai",
  "claude-3-5-sonnet-latest": "anthropic",
  "claude-3-5-sonnet-20240620": "anthropic",
  "claude-3-5-sonnet-20241022": "anthropic",
  "claude-3-7-sonnet-20250219": "anthropic",
  "claude-3-7-sonnet-latest": "anthropic",
  "cerebras-llama-3.3-70b": "cerebras",
  "cerebras-llama-3.1-8b": "cerebras",
  "groq-llama-3.3-70b-versatile": "groq",
Repository: browserbase/stagehand
File: types/api.ts (TypeScript)

Code before:
  logger: (message: LogLine) => void;
}

export interface ExecuteActionParams {
  method: "act" | "extract" | "observe" | "navigate" | "end" | "agentExecute";
  args?: unknown;
  params?: unknown;
}

export interface StartSessionParams {
  modelName: string;
  modelApiKey: string;
  domSettleTimeoutMs: number;
  verbose: number;
  debugDom: boolean;
  systemPrompt?: string;
  browserbaseSessionCreateParams?: Browserbase.Sessions.SessionCreateParams;
  selfHeal?: boolean;
  waitForCaptchaSolves?: boolean;
  actionTimeoutMs?: number;
  browserbaseSessionID?: string;
}

export interface StartSessionResult {
  sessionId: string;
  unavailable?: boolean;
}

export interface SuccessResponse<T> {
  success: true;
  data: T;
}

export interface ErrorResponse {
  success: false;
  message: string;
}

export type ApiResponse<T> = SuccessResponse<T> | ErrorResponse;


Review comment (suggestion):
this is a little unintuitive -- having a true/false field for `apiEnabled` from the API would be cleaner than a true/undefined `unavailable` field

Code after:
  logger: (message: LogLine) => void;
}

export interface ExecuteActionParams {
  method: "act" | "extract" | "observe" | "navigate" | "end" | "agentExecute";
  args?: unknown;
  params?: unknown;
}

export interface StartSessionParams {
  modelName: string;
  modelApiKey: string;
  domSettleTimeoutMs: number;
  verbose: number;
  debugDom: boolean;
  systemPrompt?: string;
  browserbaseSessionCreateParams?: Browserbase.Sessions.SessionCreateParams;
  selfHeal?: boolean;
  waitForCaptchaSolves?: boolean;
  actionTimeoutMs?: number;
  browserbaseSessionID?: string;
}

export interface StartSessionResult {
  sessionId: string;
  available?: boolean;
}

export interface SuccessResponse<T> {
  success: true;
  data: T;
}

export interface ErrorResponse {
  success: false;
  message: string;
}

export type ApiResponse<T> = SuccessResponse<T> | ErrorResponse;
Repository: browserbase/stagehand
File: lib/llm/aisdk.ts (TypeScript)

Code before:
          return assistantMessage;
        }
      }

      return {
        role: message.role,
        content: message.content,
      };
    });

    if (options.response_model) {
      const response = await generateObject({
        model: this.model,
        messages: formattedMessages,
        schema: options.response_model.schema,
      });

      const result = {
        data: response.object,
        usage: {
          prompt_tokens: response.usage.promptTokens ?? 0,
          completion_tokens: response.usage.completionTokens ?? 0,
          total_tokens: response.usage.totalTokens ?? 0,
        },
      } as T;

      if (this.enableCaching) {
        this.logger?.({
          category: "llm_cache",
          message: "caching response",
          level: 1,
          auxiliary: {
            requestId: {
              value: options.requestId,
              type: "string",
            },
            cacheOptions: {
              value: JSON.stringify(cacheOptions),
              type: "object",
            },
            response: {
              value: JSON.stringify(result),
              type: "object",
            },
          },
        });
        this.cache.set(cacheOptions, result, options.requestId);
      }

      this.logger?.({
        category: "aisdk",

Review comment (suggestion):
can just do `{ value: JSON.stringify(err), type: "object" }`

Code after:
          };
          return assistantMessage;
        }
      }

      return {
        role: message.role,
        content: message.content,
      };
    });

    let objectResponse: Awaited<ReturnType<typeof generateObject>>;
    if (options.response_model) {
      try {
        objectResponse = await generateObject({
          model: this.model,
          messages: formattedMessages,
          schema: options.response_model.schema,
        });
      } catch (err) {
        if (NoObjectGeneratedError.isInstance(err)) {
          this.logger?.({
            category: "AISDK error",
            message: err.message,
            level: 0,
            auxiliary: {
              cause: {
                value: JSON.stringify(err.cause ?? {}),
                type: "object",
              },
              text: {
                value: err.text ?? "",
                type: "string",
              },
              response: {
                value: JSON.stringify(err.response ?? {}),
                type: "object",
              },
              usage: {
                value: JSON.stringify(err.usage ?? {}),
                type: "object",
              },
              finishReason: {
                value: err.finishReason ?? "unknown",
                type: "string",
              },
              requestId: {
                value: options.requestId,
                type: "string",
              },
            },
Repository: ccxt/ccxt
File: php/async/Exchange.php (PHP)

Code before:
use ccxt\RateLimitExceeded;
use ccxt\NullResponse;
use ccxt\InvalidAddress;
use ccxt\InvalidOrder;
use ccxt\BadResponse;
use ccxt\BadRequest;
use React\Promise;

use React;
use React\Async;
use React\EventLoop\Loop;

use Exception;

$version = '4.3.77';

class Exchange extends \ccxt\Exchange {

    const VERSION = '4.3.77';

    public $browser;
    public $marketsLoading = null;
    public $reloadingMarkets = null;
    public $tokenBucket;
    public $throttler;
    public $default_connector = null;

    public $streaming = array(
        'keepAlive' => 30000,
        'heartbeat' => true,
        'ping' => null,
        'maxPingPongMisses' => 2.0,
    );

    public $proxy_files_dir = __DIR__ . '/../static_dependencies/proxies/';

    use ClientTrait;

    public function __construct($options = array()) {
        parent::__construct($options);
        $this->default_connector = $this->create_connector();
        $this->set_request_browser($this->default_connector);
    }

    public function newThrottler() {
        return new Throttler($this->tokenBucket);
    }

    public function set_request_browser($connector) {
        $this->browser = (new React\Http\Browser($connector, Loop::get()))->withRejectErrorResponse(false);
    }

Review comment (suggestion):
temporarily removed, because in sync base there is no type `Throttler` and for now, i've simplified the process. however, i'll do something in separate PR thereafter to place this type back

Code after:
use ccxt\RateLimitExceeded;
use ccxt\UnsubscribeError;
use ccxt\NullResponse;
use ccxt\InvalidAddress;
use ccxt\InvalidOrder;
use ccxt\BadResponse;
use ccxt\BadRequest;
use React\Promise;

use React;
use React\Async;
use React\EventLoop\Loop;

use Exception;

$version = '4.4.59';

class Exchange extends \ccxt\Exchange {

    const VERSION = '4.4.59';

    public $browser;
    public $marketsLoading = null;
    public $reloadingMarkets = null;
    public $tokenBucket;
    public Throttler $throttler;
    public $default_connector = null;

    public $streaming = array(
        'keepAlive' => 30000,
        'heartbeat' => true,
        'ping' => null,
        'maxPingPongMisses' => 2.0,
    );

    public $proxy_files_dir = __DIR__ . '/../static_dependencies/proxies/';

    use ClientTrait;

    public function __construct($options = array()) {
        parent::__construct($options);
        $this->default_connector = $this->create_connector();
        $this->set_request_browser($this->default_connector);
    }

    public function set_request_browser($connector) {
        $this->browser = (new React\Http\Browser($connector, Loop::get()))->withRejectErrorResponse(false);
    }

    public function create_connector ($connector_options = array()){
        $connector = new React\Socket\Connector(array_merge(array(
Repository: ccxt/ccxt
File: ts/src/test/base/test.afterConstructor.ts (TypeScript)

Code before:

// AUTO_TRANSPILE_ENABLED

import assert from 'assert';
import ccxt from '../../../ccxt.js';
import testSharedMethods from '../Exchange/base/test.sharedMethods.js';

function helperTestInitThrottler () {
    const exchange = new ccxt.Exchange ({
        'id': 'sampleexchange',
        'rateLimit': 10.8,
    });
    // todo: assert (exchange.MAX_VALUE !== undefined);

    const tockenBucket = exchange.getProperty (exchange, 'tokenBucket'); // trick for uncamelcase transpilation
    const rateLimit = exchange.getProperty (exchange, 'rateLimit');
    assert (rateLimit === 10.8);
    assert (tockenBucket !== undefined);
    assert (tockenBucket['delay'] === 0.001);
    assert (tockenBucket['refillRate'] === 1 / rateLimit);
    // fix decimal/integer issues across langs
    assert (exchange.inArray (tockenBucket['capacity'], [ 1, 1.0 ]));
    const cost = exchange.parseToNumeric (exchange.safeString2 (tockenBucket, 'cost', 'defaultCost')); // python sync, todo fix
    assert (exchange.inArray (cost, [ 1, 1.0 ]));
    assert (!('maxCapacity' in tockenBucket) || exchange.inArray (tockenBucket['maxCapacity'], [ 1000, 1000.0 ]));
    // todo: assert (exchange.throttler !== undefined);
    // todo: add after change assertion
    // todo: add initial tockenbtucket test
}

function helperTestSandboxState (exchange, shouldBeEnabled = true) {
    assert (exchange.urls !== undefined);
    assert ('test' in exchange.urls);

Review comment (refactor):
in C#, if function starts with `test` , the C# bootstraper tests all those methods, so we need to prefix "in-file helper methods" with different name to avoid C# from picking up them

Code after:

// AUTO_TRANSPILE_ENABLED

import assert from 'assert';
import ccxt from '../../../ccxt.js';
import testSharedMethods from '../Exchange/base/test.sharedMethods.js';

function helperTestInitThrottler () {
    const exchange = new ccxt.Exchange ({
        'id': 'sampleexchange',
        'rateLimit': 10.8,
    });
    // todo: assert (exchange.MAX_VALUE !== undefined);

    let tokenBucket = exchange.getProperty (exchange, 'tokenBucket'); // trick for uncamelcase transpilation
    if (tokenBucket === undefined) {
        tokenBucket = exchange.getProperty (exchange, 'TokenBucket');
    }
    assert (tokenBucket !== undefined);
    assert ('GO_SKIP_START');
    const rateLimit = exchange.getProperty (exchange, 'rateLimit');
    assert (rateLimit === 10.8);
    assert (tokenBucket['delay'] === 0.001);
    assert (tokenBucket['refillRate'] === 1 / rateLimit);
    assert ('GO_SKIP_END');
    // fix decimal/integer issues across langs
    assert (exchange.inArray (tokenBucket['capacity'], [ 1, 1.0 ]));
    const cost = exchange.parseToNumeric (exchange.safeString2 (tokenBucket, 'cost', 'defaultCost')); // python sync, todo fix
    assert (exchange.inArray (cost, [ 1, 1.0 ]));
    assert (!('maxCapacity' in tokenBucket) || exchange.inArray (tokenBucket['maxCapacity'], [ 1000, 1000.0 ]));
    // todo: assert (exchange.throttler !== undefined);
    // todo: add after change assertion
    // todo: add initial tockenbtucket test
Repository: ccxt/ccxt
File: ts/src/static_dependencies/dydx-v4-client/helpers.ts (TypeScript)

Code before:
/**
* This file and any referenced files were automatically generated by @osmonauts/telescope@0.86.0
* DO NOT MODIFY BY HAND. Instead, download the latest proto files for your chain
* and run the transpile command or yarn proto command to regenerate this bundle.
*/

let _m0: any;
try {
    // import _m0 from "protobufjs/minimal.js";
    _m0 = require("protobufjs/minimal.js");
} catch (e) {
    // do nothing
}

import Long from './long/index.cjs';

// @ts-ignore
// const Long = (long !== undefined && long.default !== undefined) ? long.default : long;
if (_m0 && _m0.util.Long !== Long) {
    _m0.util.Long = (Long as any);
    _m0.configure();
}

export { Long }

declare var self: any | undefined;
declare var window: any | undefined;
declare var global: any | undefined;
var globalThis: any = (() => {
    if (typeof globalThis !== 'undefined') return globalThis;
    if (typeof self !== 'undefined') return self;
    if (typeof window !== 'undefined') return window;
    if (typeof global !== 'undefined') return global;
    throw 'Unable to locate global object';
})();

Review comment (suggestion):
@carlosmiei IMHO, we may need to change to import, eg `(await import ("protobufjs/minimal.js")).default;`.

Code after:
/**
* This file and any referenced files were automatically generated by @osmonauts/telescope@0.86.0
* DO NOT MODIFY BY HAND. Instead, download the latest proto files for your chain
* and run the transpile command or yarn proto command to regenerate this bundle.
*/

let _m0: any;
let loaded = false;

(async () => {
    await loadProtoBuf();
})();

import Long from './long/index.cjs';


if (!loaded) {
    (async () => {
        await loadProtoBuf();
    })();
}
// @ts-ignore
// const Long = (long !== undefined && long.default !== undefined) ? long.default : long;
if (_m0 && _m0.util.Long !== Long) {
    _m0.util.Long = (Long as any);
    _m0.configure();
}

async function loadProtoBuf() {
    try {
        if (loaded) {
            return;
        }
        loaded = true;
        // import _m0 from "protobufjs/minimal.js";