// Force strict mode and setup for ESM
"use strict";
import {
  Client,
  StdioClientTransport
} from "./chunk-TI4GXJKO.js";
import "./chunk-AKBFRR6J.js";
import {
  safeJsonStringify
} from "./chunk-W57YDFU5.js";
import {
  BaseDeclarativeTool,
  BaseToolInvocation
} from "./chunk-R2B65CAN.js";
import "./chunk-ACBGEKB7.js";
import "./chunk-QWSRH265.js";
import {
  init_esbuild_shims
} from "./chunk-A4BMJM77.js";
import {
  __name
} from "./chunk-J2S4EL5Y.js";

// packages/core/src/tools/computer-use/index.ts
init_esbuild_shims();

// packages/core/src/tools/computer-use/tool.ts
init_esbuild_shims();

// packages/core/src/tools/computer-use/client.ts
init_esbuild_shims();

// packages/core/src/tools/computer-use/constants.ts
init_esbuild_shims();
var PINNED_OPEN_COMPUTER_USE_VERSION = "0.1.51";
function resolveComputerUsePackageSpec() {
  return process.env["QWEN_COMPUTER_USE_PACKAGE"] ?? `open-computer-use@${PINNED_OPEN_COMPUTER_USE_VERSION}`;
}
__name(resolveComputerUsePackageSpec, "resolveComputerUsePackageSpec");

// packages/core/src/tools/computer-use/client.ts
var ComputerUseClient = class _ComputerUseClient {
  static {
    __name(this, "ComputerUseClient");
  }
  static singleton;
  packageSpec;
  onProgress;
  client;
  startPromise;
  constructor(options) {
    this.packageSpec = options.packageSpec;
    this.onProgress = options.onProgress ?? (() => {
    });
  }
  /**
   * Shared singleton instance, created with default options on first
   * access. Tests can replace it via `setSharedForTest()`.
   */
  static shared() {
    if (!_ComputerUseClient.singleton) {
      _ComputerUseClient.singleton = new _ComputerUseClient({
        packageSpec: resolveComputerUsePackageSpec()
      });
    }
    return _ComputerUseClient.singleton;
  }
  /** Test-only: replace the singleton. */
  static setSharedForTest(replacement) {
    _ComputerUseClient.singleton = replacement;
  }
  isStarted() {
    return this.client !== void 0;
  }
  /**
   * Start the upstream MCP server. Idempotent: concurrent callers share
   * the same in-flight start promise.
   *
   * An optional `onProgress` callback can be supplied to receive download
   * and startup messages during this call. It overrides the instance-level
   * callback for the duration of the start operation only.
   *
   * Throws on spawn failure (network down, npx missing, etc.). The
   * caller (bootstrap state machine) is responsible for mapping the
   * throw into user-facing UX.
   */
  async start(onProgress) {
    if (this.client) return;
    if (this.startPromise) return this.startPromise;
    this.startPromise = this.doStart(onProgress).finally(() => {
      this.startPromise = void 0;
    });
    return this.startPromise;
  }
  async doStart(onProgress) {
    const progress = onProgress ?? this.onProgress;
    progress("Starting Computer Use...");
    const downloadHintTimer = setTimeout(() => {
      progress(
        "Downloading Computer Use binary (this can take ~60s on first use)..."
      );
    }, 3e3);
    try {
      const transport = new StdioClientTransport({
        command: "npx",
        args: ["-y", this.packageSpec, "mcp"],
        // Inherit env so HTTPS_PROXY etc. flow through to npx
        env: { ...process.env }
      });
      const client = new Client(
        { name: "qwen-code-computer-use", version: "1.0.0" },
        { capabilities: {} }
      );
      await client.connect(transport);
      this.client = client;
    } finally {
      clearTimeout(downloadHintTimer);
    }
  }
  /**
   * List the tools exposed by the upstream server. Used by the schema
   * sync script and bootstrap diagnostics.
   */
  async listTools() {
    if (!this.client) throw new Error("ComputerUseClient not started");
    return this.client.listTools();
  }
  /**
   * Call a tool by upstream name (NOT the qwen-code-facing
   * `computer_use__` prefixed name). Returns the raw MCP result so the
   * caller can inspect `isError` and parse text content.
   *
   * On transport-closed errors (e.g. macOS kills the upstream binary after
   * the user grants Screen Recording permission), this method transparently
   * tears down the stale connection, reconnects, and retries the call once.
   * If the retry also fails, the error is re-thrown without further
   * reconnect attempts.
   */
  async callTool(name, args) {
    if (!this.client) throw new Error("ComputerUseClient not started");
    try {
      return await this.client.callTool({
        name,
        arguments: args
      });
    } catch (err) {
      if (!isTransportClosedError(err)) throw err;
      await this.stop();
      await this.start();
      if (!this.client) throw new Error("ComputerUseClient reconnect failed");
      return await this.client.callTool({
        name,
        arguments: args
      });
    }
  }
  /** Tear down the child process. Safe to call multiple times. */
  async stop() {
    const client = this.client;
    this.client = void 0;
    if (client) {
      try {
        await client.close();
      } catch {
      }
    }
  }
};
function isTransportClosedError(err) {
  const msg = err instanceof Error ? err.message : String(err);
  return /connection closed|not connected/i.test(msg);
}
__name(isTransportClosedError, "isTransportClosedError");

// packages/core/src/tools/computer-use/bootstrap.ts
init_esbuild_shims();
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { homedir as homedir2 } from "node:os";

// packages/core/src/tools/computer-use/install-state.ts
init_esbuild_shims();
import { readFile, writeFile, mkdir } from "node:fs/promises";
import { homedir } from "node:os";
import { join, dirname } from "node:path";
function installStatePathFor(home = homedir()) {
  return join(home, ".qwen", "computer-use", "installed.json");
}
__name(installStatePathFor, "installStatePathFor");
async function loadInstallState(home = homedir()) {
  try {
    const text = await readFile(installStatePathFor(home), "utf8");
    const parsed = JSON.parse(text);
    if (typeof parsed?.approvedPackageSpec !== "string") return void 0;
    if (typeof parsed?.approvedAtIso !== "string") return void 0;
    return parsed;
  } catch (err) {
    if (err?.code === "ENOENT") return void 0;
    return void 0;
  }
}
__name(loadInstallState, "loadInstallState");
async function saveInstallState(home = homedir(), state) {
  const path = installStatePathFor(home);
  await mkdir(dirname(path), { recursive: true });
  await writeFile(path, JSON.stringify(state, null, 2), "utf8");
}
__name(saveInstallState, "saveInstallState");
async function isPackageSpecApproved(home = homedir(), packageSpec) {
  const state = await loadInstallState(home);
  return state?.approvedPackageSpec === packageSpec;
}
__name(isPackageSpecApproved, "isPackageSpecApproved");

// packages/core/src/tools/computer-use/permission-detector.ts
init_esbuild_shims();

// packages/core/src/tools/computer-use/bootstrap.ts
var execFileAsync = promisify(execFile);
function parseDoctorStdout(stdout) {
  const accessibilityGranted = /accessibility\s*=\s*granted/i.test(stdout);
  const screenRecordingGranted = /screenrecording\s*=\s*granted/i.test(stdout);
  if (!accessibilityGranted) return "accessibility";
  if (!screenRecordingGranted) return "screenRecording";
  return "ok";
}
__name(parseDoctorStdout, "parseDoctorStdout");
async function probePermissionsViaDoctor(packageSpec) {
  try {
    const { stdout } = await execFileAsync(
      "npx",
      ["-y", packageSpec, "doctor"],
      {
        timeout: 3e4,
        env: process.env
      }
    );
    return parseDoctorStdout(stdout);
  } catch {
    return "other";
  }
}
__name(probePermissionsViaDoctor, "probePermissionsViaDoctor");
function defaultDeps() {
  const packageSpec = resolveComputerUsePackageSpec();
  return {
    homeDir: homedir2(),
    packageSpec,
    platform: process.platform,
    promptInstallApproval: /* @__PURE__ */ __name(async (spec) => {
      process.stderr.write(
        `
[Computer Use] First-time install
  Package: ${spec}
  This will fetch ~50MB from the npm registry the first time.
  Computer Use can click, type, and read your desktop apps.
  On macOS you'll be guided through Accessibility and Screen Recording permissions next.
Set QWEN_COMPUTER_USE_AUTO_APPROVE=1 to skip this prompt.
`
      );
      return process.env["QWEN_COMPUTER_USE_AUTO_APPROVE"] === "1";
    }, "promptInstallApproval"),
    probePermissions: probePermissionsViaDoctor
  };
}
__name(defaultDeps, "defaultDeps");
async function runBootstrap(client, ctx, depsOverride) {
  const deps = { ...defaultDeps(), ...depsOverride };
  const pollIntervalMs = deps.pollIntervalMs ?? 5e3;
  const pollTimeoutMs = deps.pollTimeoutMs ?? 10 * 6e4;
  const approved = await isPackageSpecApproved(deps.homeDir, deps.packageSpec);
  if (!approved) {
    ctx.updateOutput?.("Computer Use needs to be installed (first use).");
    const ok = await deps.promptInstallApproval(deps.packageSpec);
    if (!ok) {
      throw new Error(
        `Computer Use install declined by user. Re-invoke the tool to be prompted again.`
      );
    }
    await saveInstallState(deps.homeDir, {
      approvedPackageSpec: deps.packageSpec,
      approvedAtIso: (/* @__PURE__ */ new Date()).toISOString()
    });
  }
  const wasAlreadyStarted = client.isStarted();
  if (!wasAlreadyStarted) {
    await client.start(ctx.updateOutput);
  }
  if (wasAlreadyStarted) return;
  if (deps.platform !== "darwin") return;
  const probe = await deps.probePermissions(deps.packageSpec);
  if (probe === "ok" || probe === "other") {
    return;
  }
  ctx.updateOutput?.(
    `Computer Use needs macOS permissions (${probe}). The onboarding window is opening \u2014 please grant Accessibility and Screen Recording, then this will continue automatically.`
  );
  let lastProbeKind = probe;
  const startedAt = Date.now();
  for (; ; ) {
    if (ctx.signal.aborted) {
      throw new Error("Computer Use bootstrap aborted.");
    }
    if (Date.now() - startedAt > pollTimeoutMs) {
      throw new Error(
        `Computer Use permission grant timed out after ${Math.round(pollTimeoutMs / 1e3)}s. Re-invoke the tool to retry.`
      );
    }
    await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
    const next = await deps.probePermissions(deps.packageSpec);
    if (next === "ok" || next === "other") return;
    if (next !== lastProbeKind) {
      ctx.updateOutput?.(
        `Now waiting for ${next} permission. The onboarding window remains open \u2014 please grant this permission to continue.`
      );
      lastProbeKind = next;
    }
    const elapsedSec = Math.round((Date.now() - startedAt) / 1e3);
    ctx.updateOutput?.(`Waiting for ${next} permission... (${elapsedSec}s)`);
  }
}
__name(runBootstrap, "runBootstrap");

// packages/core/src/tools/computer-use/tool.ts
import { homedir as homedir3 } from "node:os";
var INSTALL_REASON = "This will install the open-computer-use binary (~50MB) via npx the first time. Computer Use can click, type, and read your desktop apps. On macOS you'll be guided through Accessibility / Screen Recording permissions next.";
var ComputerUseInvocation = class extends BaseToolInvocation {
  constructor(upstreamName, params) {
    super(params);
    this.upstreamName = upstreamName;
  }
  static {
    __name(this, "ComputerUseInvocation");
  }
  getDescription() {
    return safeJsonStringify(this.params);
  }
  /**
   * Always returns 'ask' so every desktop action surfaces through the
   * standard tool-permission dialog. The PermissionManager rule system
   * handles "always allow" per tool via ProceedAlwaysTool — that's the
   * single source of truth for repeat-approval behavior.
   *
   * Earlier this returned 'allow' once the install-state file existed,
   * which conflated install approval with per-action approval and
   * effectively granted blanket permission for all 9 computer_use__*
   * tools (including mutating actions like click / type_text / drag)
   * after the first install confirmation. See PR #4590 review for the
   * full discussion.
   */
  async getDefaultPermission() {
    return "ask";
  }
  /**
   * Builds the confirmation dialog. Two variants:
   *
   * 1. Install not yet approved → show install info (download size,
   *    permission flow to follow). onConfirm writes the install state
   *    so runBootstrap() inside execute() skips its env-var fallback
   *    prompt for headless contexts.
   *
   * 2. Install already approved → show per-action info (which tool +
   *    which args) so the user can decide whether THIS specific action
   *    is OK to perform.
   *
   * Both variants set permissionRules so the standard "Always allow"
   * outcomes (ProceedAlwaysTool / ProceedAlwaysUser / ProceedAlwaysProject)
   * add a rule via PermissionManager — subsequent calls of the SAME
   * tool then skip the dialog. Different tools each need their own
   * "always allow" choice; install approval no longer grants blanket
   * access.
   *
   * On Cancel: install state is NOT written; execute() / runBootstrap()
   * will use the env-var fallback (QWEN_COMPUTER_USE_AUTO_APPROVE),
   * which defaults to refusing — producing a clear error message.
   */
  async getConfirmationDetails(_abortSignal) {
    const permissionRules = [`computer_use__${this.upstreamName}`];
    const installApproved = await isPackageSpecApproved(
      homedir3(),
      resolveComputerUsePackageSpec()
    );
    const prompt = installApproved ? `Tool: computer_use__${this.upstreamName}

Args: ${safeJsonStringify(this.params)}

This will act on your desktop via the Computer Use binary.` : `Tool: computer_use__${this.upstreamName}

${INSTALL_REASON}`;
    const details = {
      type: "info",
      title: `Allow Computer Use (${this.upstreamName})`,
      prompt,
      permissionRules,
      onConfirm: /* @__PURE__ */ __name(async (outcome, _payload) => {
        if (outcome !== "cancel" /* Cancel */) {
          await saveInstallState(homedir3(), {
            approvedPackageSpec: resolveComputerUsePackageSpec(),
            approvedAtIso: (/* @__PURE__ */ new Date()).toISOString()
          });
        }
      }, "onConfirm")
    };
    return details;
  }
  async execute(signal, updateOutput) {
    const client = ComputerUseClient.shared();
    await runBootstrap(client, { signal, updateOutput });
    let mcpResult;
    try {
      mcpResult = await client.callTool(this.upstreamName, this.params);
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      return {
        llmContent: `Computer Use tool '${this.upstreamName}' failed: ${message}`,
        returnDisplay: `Error: ${message}`,
        error: { message }
      };
    }
    const llmContent = buildLlmContent(mcpResult.content, this.upstreamName);
    const returnDisplay = buildDisplayText(mcpResult.content);
    if (mcpResult.isError) {
      const errorText = returnDisplay || `Tool '${this.upstreamName}' returned isError=true`;
      return {
        llmContent: llmContent || errorText,
        returnDisplay: errorText,
        error: { message: errorText }
      };
    }
    return {
      llmContent,
      returnDisplay
    };
  }
};
var ComputerUseTool = class extends BaseDeclarativeTool {
  constructor(upstreamName, schema) {
    const qwenName = `computer_use__${upstreamName}`;
    super(
      qwenName,
      qwenName,
      // displayName == name; no MCP branding in UI
      schema.description,
      "other" /* Other */,
      schema.parameterSchema,
      true,
      // isOutputMarkdown — many results are JSON-ish text or screenshots
      true,
      // canUpdateOutput — bootstrap streams progress
      true,
      // shouldDefer — surface only via ToolSearch
      false,
      // alwaysLoad
      `computer use desktop click type screenshot mouse keyboard scroll drag automation gui app native`
    );
    this.upstreamName = upstreamName;
  }
  static {
    __name(this, "ComputerUseTool");
  }
  /**
   * Coerce parameter types before schema validation.
   * Models can send the wrong JS type for a field:
   *  - qwen3.6 sends `element_index: 2` (number) but upstream wants "2" (string)
   *  - Some models send `x: "500"` (string) but upstream wants 500 (number)
   * Pre-coercing avoids spurious validation failures without loosening schema types.
   */
  validateToolParams(params) {
    const coerced = coerceTypes(
      params,
      this.parameterSchema
    );
    return super.validateToolParams(coerced);
  }
  build(params) {
    const coerced = coerceTypes(
      params,
      this.parameterSchema
    );
    return super.build(coerced);
  }
  createInvocation(params) {
    return new ComputerUseInvocation(this.upstreamName, params);
  }
};
function coerceTypes(params, schema) {
  const properties = schema.properties;
  if (!properties) return params;
  const result = { ...params };
  for (const [key, value] of Object.entries(result)) {
    const fieldType = properties[key]?.type;
    if ((fieldType === "integer" || fieldType === "number") && typeof value === "string") {
      const trimmed = value.trim();
      if (/^-?\d+(\.\d+)?$/.test(trimmed)) {
        const parsed = fieldType === "integer" ? parseInt(trimmed, 10) : parseFloat(trimmed);
        if (Number.isFinite(parsed)) {
          result[key] = parsed;
        }
      }
    } else if (fieldType === "string" && typeof value === "number") {
      result[key] = String(value);
    }
  }
  return result;
}
__name(coerceTypes, "coerceTypes");
function buildLlmContent(content, toolName) {
  const parts = [];
  for (const block of content) {
    if (block.type === "text" && block.text) {
      parts.push({ text: block.text });
    } else if ((block.type === "image" || block.type === "audio") && block.mimeType && block.data) {
      parts.push({
        text: `[Tool '${toolName}' provided the following ${block.type} data with mime-type: ${block.mimeType}]`
      });
      parts.push({
        inlineData: {
          mimeType: block.mimeType,
          data: block.data
        }
      });
    }
  }
  const hasNonText = parts.some((p) => p.inlineData !== void 0);
  if (!hasNonText) {
    return parts.map((p) => p.text ?? "").filter(Boolean).join("\n");
  }
  return parts;
}
__name(buildLlmContent, "buildLlmContent");
function buildDisplayText(content) {
  return content.map((block) => block.type === "text" ? block.text ?? "" : "").filter(Boolean).join("\n");
}
__name(buildDisplayText, "buildDisplayText");

// packages/core/src/tools/computer-use/schemas.ts
init_esbuild_shims();
var COMPUTER_USE_TOOL_NAMES = [
  "click",
  "drag",
  "get_app_state",
  "list_apps",
  "perform_secondary_action",
  "press_key",
  "scroll",
  "set_value",
  "type_text"
];
var COMPUTER_USE_SCHEMAS = {
  click: {
    description: "Click an element by index or pixel coordinates from screenshot. This tool is part of plugin `Computer Use`.",
    parameterSchema: {
      type: "object",
      properties: {
        click_count: {
          type: "integer",
          description: "Number of clicks. Defaults to 1"
        },
        mouse_button: {
          description: "Mouse button to click. Defaults to left.",
          enum: ["left", "right", "middle"],
          type: "string"
        },
        element_index: {
          type: "string",
          description: "Element index to click"
        },
        y: {
          type: "number",
          description: "Y coordinate in screenshot pixel coordinates"
        },
        app: {
          type: "string",
          description: "App name or bundle identifier"
        },
        x: {
          description: "X coordinate in screenshot pixel coordinates",
          type: "number"
        }
      },
      required: ["app"],
      additionalProperties: false
    }
  },
  drag: {
    description: "Drag from one point to another using pixel coordinates. This tool is part of plugin `Computer Use`.",
    parameterSchema: {
      type: "object",
      properties: {
        app: {
          type: "string",
          description: "App name or bundle identifier"
        },
        from_x: {
          description: "Start X coordinate",
          type: "number"
        },
        from_y: {
          type: "number",
          description: "Start Y coordinate"
        },
        to_x: {
          description: "End X coordinate",
          type: "number"
        },
        to_y: {
          type: "number",
          description: "End Y coordinate"
        }
      },
      required: ["app", "from_x", "from_y", "to_x", "to_y"],
      additionalProperties: false
    }
  },
  get_app_state: {
    description: "Start an app use session if needed, then get the state of the app's key window and return a screenshot and accessibility tree. This must be called once per assistant turn before interacting with the app. This tool is part of plugin `Computer Use`.",
    parameterSchema: {
      type: "object",
      properties: {
        app: {
          description: "App name or bundle identifier",
          type: "string"
        }
      },
      required: ["app"],
      additionalProperties: false
    }
  },
  list_apps: {
    description: "List the apps on this computer. Returns the set of apps that are currently running, as well as any that have been used in the last 14 days, including details on usage frequency. This tool is part of plugin `Computer Use`.",
    parameterSchema: {
      type: "object",
      properties: {},
      additionalProperties: false
    }
  },
  perform_secondary_action: {
    description: "Invoke a secondary accessibility action exposed by an element. This tool is part of plugin `Computer Use`.",
    parameterSchema: {
      type: "object",
      properties: {
        action: {
          description: "Secondary accessibility action name",
          type: "string"
        },
        app: {
          description: "App name or bundle identifier",
          type: "string"
        },
        element_index: {
          description: "Element identifier",
          type: "string"
        }
      },
      required: ["app", "element_index", "action"],
      additionalProperties: false
    }
  },
  press_key: {
    description: 'Press a key or key-combination on the keyboard, including modifier and navigation keys.\n  - This supports xdotool\'s `key` syntax.\n  - Examples: "a", "Return", "Tab", "super+c", "Up", "KP_0" (for the numpad 0 key). This tool is part of plugin `Computer Use`.',
    parameterSchema: {
      type: "object",
      properties: {
        app: {
          description: "App name or bundle identifier",
          type: "string"
        },
        key: {
          type: "string",
          description: "Key or key combination to press"
        }
      },
      required: ["app", "key"],
      additionalProperties: false
    }
  },
  scroll: {
    description: "Scroll an element in a direction by a number of pages. This tool is part of plugin `Computer Use`.",
    parameterSchema: {
      type: "object",
      properties: {
        pages: {
          type: "number",
          description: "Number of pages to scroll. Fractional values are supported. Defaults to 1"
        },
        app: {
          description: "App name or bundle identifier",
          type: "string"
        },
        element_index: {
          description: "Element identifier",
          type: "string"
        },
        direction: {
          description: "Scroll direction: up, down, left, or right",
          type: "string"
        }
      },
      required: ["app", "element_index", "direction"],
      additionalProperties: false
    }
  },
  set_value: {
    description: "Set the value of a settable accessibility element. This tool is part of plugin `Computer Use`.",
    parameterSchema: {
      type: "object",
      properties: {
        element_index: {
          type: "string",
          description: "Element identifier"
        },
        value: {
          type: "string",
          description: "Value to assign"
        },
        app: {
          description: "App name or bundle identifier",
          type: "string"
        }
      },
      required: ["app", "element_index", "value"],
      additionalProperties: false
    }
  },
  type_text: {
    description: "Type literal text using keyboard input. This tool is part of plugin `Computer Use`.",
    parameterSchema: {
      type: "object",
      properties: {
        app: {
          type: "string",
          description: "App name or bundle identifier"
        },
        text: {
          type: "string",
          description: "Literal text to type"
        }
      },
      required: ["app", "text"],
      additionalProperties: false
    }
  }
};

// packages/core/src/tools/computer-use/index.ts
async function registerComputerUseTools(registerLazy) {
  for (const upstreamName of COMPUTER_USE_TOOL_NAMES) {
    const schema = COMPUTER_USE_SCHEMAS[upstreamName];
    const qwenName = `computer_use__${upstreamName}`;
    await registerLazy(
      qwenName,
      async () => new ComputerUseTool(upstreamName, schema)
    );
  }
}
__name(registerComputerUseTools, "registerComputerUseTools");
export {
  COMPUTER_USE_SCHEMAS,
  COMPUTER_USE_TOOL_NAMES,
  ComputerUseClient,
  ComputerUseTool,
  registerComputerUseTools
};
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
