"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }



var _chunk5MHMD5JXjs = require('./chunk-5MHMD5JX.js');





var _chunkIHUBTSSWjs = require('./chunk-IHUBTSSW.js');






var _chunkUXPZNWPHjs = require('./chunk-UXPZNWPH.js');

// src/ai-model/action-executor.ts
var _assert = require('assert'); var _assert2 = _interopRequireDefault(_assert);
var Executor = class {
  constructor(name, options) {
    this.status = (options == null ? void 0 : options.tasks) && options.tasks.length > 0 ? "pending" : "init";
    this.name = name;
    this.tasks = ((options == null ? void 0 : options.tasks) || []).map(
      (item) => this.markTaskAsPending(item)
    );
    this.onTaskStart = options == null ? void 0 : options.onTaskStart;
  }
  markTaskAsPending(task) {
    return {
      status: "pending",
      ...task
    };
  }
  async append(task) {
    var _a, _b;
    _assert2.default.call(void 0, 
      this.status !== "error",
      `executor is in error state, cannot append task
error=${(_a = this.latestErrorTask()) == null ? void 0 : _a.error}
${(_b = this.latestErrorTask()) == null ? void 0 : _b.errorStack}`
    );
    if (Array.isArray(task)) {
      this.tasks.push(...task.map((item) => this.markTaskAsPending(item)));
    } else {
      this.tasks.push(this.markTaskAsPending(task));
    }
    if (this.status !== "running") {
      this.status = "pending";
    }
  }
  async flush() {
    if (this.status === "init" && this.tasks.length > 0) {
      console.warn(
        "illegal state for executor, status is init but tasks are not empty"
      );
    }
    _assert2.default.call(void 0, this.status !== "running", "executor is already running");
    _assert2.default.call(void 0, this.status !== "completed", "executor is already completed");
    _assert2.default.call(void 0, this.status !== "error", "executor is in error state");
    const nextPendingIndex = this.tasks.findIndex(
      (task) => task.status === "pending"
    );
    if (nextPendingIndex < 0) {
      return;
    }
    this.status = "running";
    let taskIndex = nextPendingIndex;
    let successfullyCompleted = true;
    let previousFindOutput;
    while (taskIndex < this.tasks.length) {
      const task = this.tasks[taskIndex];
      _assert2.default.call(void 0, 
        task.status === "pending",
        `task status should be pending, but got: ${task.status}`
      );
      task.timing = {
        start: Date.now()
      };
      try {
        task.status = "running";
        try {
          if (this.onTaskStart) {
            await this.onTaskStart(task);
          }
        } catch (e) {
          console.error("error in onTaskStart", e);
        }
        _assert2.default.call(void 0, 
          ["Insight", "Action", "Planning"].indexOf(task.type) >= 0,
          `unsupported task type: ${task.type}`
        );
        const { executor, param } = task;
        _assert2.default.call(void 0, executor, `executor is required for task type: ${task.type}`);
        let returnValue;
        const executorContext = {
          task,
          element: previousFindOutput == null ? void 0 : previousFindOutput.element
        };
        if (task.type === "Insight") {
          _assert2.default.call(void 0, 
            task.subType === "Locate" || task.subType === "Query" || task.subType === "Assert",
            `unsupported insight subType: ${task.subType}`
          );
          returnValue = await task.executor(param, executorContext);
          if (task.subType === "Locate") {
            previousFindOutput = returnValue == null ? void 0 : returnValue.output;
          }
        } else if (task.type === "Action" || task.type === "Planning") {
          returnValue = await task.executor(param, executorContext);
        } else {
          console.warn(
            `unsupported task type: ${task.type}, will try to execute it directly`
          );
          returnValue = await task.executor(param, executorContext);
        }
        Object.assign(task, returnValue);
        task.status = "finished";
        task.timing.end = Date.now();
        task.timing.cost = task.timing.end - task.timing.start;
        task.timing.aiCost = (returnValue == null ? void 0 : returnValue.aiCost) || 0;
        taskIndex++;
      } catch (e) {
        successfullyCompleted = false;
        task.error = (e == null ? void 0 : e.message) || (typeof e === "string" ? e : "error-without-message");
        task.errorStack = e.stack;
        task.status = "failed";
        task.timing.end = Date.now();
        task.timing.cost = task.timing.end - task.timing.start;
        break;
      }
    }
    for (let i = taskIndex + 1; i < this.tasks.length; i++) {
      this.tasks[i].status = "cancelled";
    }
    if (successfullyCompleted) {
      this.status = "completed";
    } else {
      this.status = "error";
    }
    if (this.tasks.length) {
      const outputIndex = Math.min(taskIndex, this.tasks.length - 1);
      return this.tasks[outputIndex].output;
    }
  }
  isInErrorState() {
    return this.status === "error";
  }
  latestErrorTask() {
    if (this.status !== "error") {
      return null;
    }
    const errorTaskIndex = this.tasks.findIndex(
      (task) => task.status === "failed"
    );
    if (errorTaskIndex >= 0) {
      return this.tasks[errorTaskIndex];
    }
    return null;
  }
  dump() {
    const dumpData = {
      sdkVersion: _chunk5MHMD5JXjs.getVersion.call(void 0, ),
      model_name: _chunkUXPZNWPHjs.getAIConfig.call(void 0, _chunkUXPZNWPHjs.MIDSCENE_MODEL_NAME) || "",
      logTime: Date.now(),
      name: this.name,
      tasks: this.tasks
    };
    return dumpData;
  }
};

// src/insight/index.ts


// src/insight/utils.ts

var _utils = require('@aico-test/shared/utils');
var logContent = [];
var logIdIndexMap = {};
function emitInsightDump(data, logId, dumpSubscriber) {
  const logDir = _chunk5MHMD5JXjs.getLogDir.call(void 0, );
  _assert2.default.call(void 0, logDir, "logDir should be set before writing dump file");
  const id = logId || _utils.uuid.call(void 0, );
  let modelDescription = "";
  if (_chunkUXPZNWPHjs.getAIConfigInBoolean.call(void 0, _chunkUXPZNWPHjs.MIDSCENE_USE_VLM_UI_TARS)) {
    modelDescription = "vlm-ui-tars mode";
  } else if (_chunkUXPZNWPHjs.getAIConfigInBoolean.call(void 0, _chunkUXPZNWPHjs.MIDSCENE_USE_QWEN_VL)) {
    modelDescription = "qwen-vl mode";
  }
  const baseData = {
    sdkVersion: _chunk5MHMD5JXjs.getVersion.call(void 0, ),
    logTime: Date.now(),
    model_name: _chunkUXPZNWPHjs.getAIConfig.call(void 0, _chunkUXPZNWPHjs.MIDSCENE_MODEL_NAME) || "",
    model_description: modelDescription
  };
  const finalData = {
    logId: id,
    ...baseData,
    ...data
  };
  dumpSubscriber == null ? void 0 : dumpSubscriber(finalData);
  const dataString = _chunk5MHMD5JXjs.stringifyDumpData.call(void 0, finalData, 2);
  if (typeof logIdIndexMap[id] === "number") {
    logContent[logIdIndexMap[id]] = dataString;
  } else {
    const length = logContent.push(dataString);
    logIdIndexMap[id] = length - 1;
  }
  return id;
}

// src/insight/index.ts
var Insight = class {
  constructor(context, opt) {
    this.aiVendorFn = _chunkIHUBTSSWjs.callAiFn;
    _assert2.default.call(void 0, context, "context is required for Insight");
    if (typeof context === "function") {
      this.contextRetrieverFn = context;
    } else {
      this.contextRetrieverFn = () => Promise.resolve(context);
    }
    this.generateElement = opt == null ? void 0 : opt.generateElement;
    if (typeof (opt == null ? void 0 : opt.aiVendorFn) !== "undefined") {
      this.aiVendorFn = opt.aiVendorFn;
    }
    if (typeof (opt == null ? void 0 : opt.taskInfo) !== "undefined") {
      this.taskInfo = opt.taskInfo;
    }
  }
  async locate(queryPrompt, opt) {
    var _a;
    const { callAI } = opt || {};
    _assert2.default.call(void 0, 
      queryPrompt || (opt == null ? void 0 : opt.quickAnswer),
      "query or quickAnswer is required for locate"
    );
    const dumpSubscriber = this.onceDumpUpdatedFn;
    this.onceDumpUpdatedFn = void 0;
    const context = await this.contextRetrieverFn("locate");
    const startTime = Date.now();
    const { parseResult, elementById, rawResponse, usage } = await _chunkIHUBTSSWjs.AiInspectElement.call(void 0, {
      callAI: callAI || this.aiVendorFn,
      context,
      targetElementDescription: queryPrompt,
      quickAnswer: opt == null ? void 0 : opt.quickAnswer
    });
    const timeCost = Date.now() - startTime;
    const taskInfo = {
      ...this.taskInfo ? this.taskInfo : {},
      durationMs: timeCost,
      rawResponse: JSON.stringify(rawResponse),
      formatResponse: JSON.stringify(parseResult),
      usage
    };
    let errorLog;
    if ((_a = parseResult.errors) == null ? void 0 : _a.length) {
      errorLog = `locate - AI response error: 
${parseResult.errors.join("\n")}`;
    }
    const dumpData = {
      type: "locate",
      context,
      userQuery: {
        element: queryPrompt
      },
      quickAnswer: opt == null ? void 0 : opt.quickAnswer,
      matchedSection: [],
      matchedElement: [],
      data: null,
      taskInfo,
      error: errorLog
    };
    const logId = emitInsightDump(dumpData, void 0, dumpSubscriber);
    if (errorLog) {
      console.error(errorLog);
      throw new Error(errorLog);
    }
    const elements = [];
    parseResult.elements.forEach((item) => {
      if ("id" in item) {
        const element = elementById(item.id);
        if (!element) {
          console.warn(
            `locate: cannot find element id=${item.id}. Maybe an unstable response from AI model`
          );
          return;
        }
        elements.push(element);
      }
    });
    emitInsightDump(
      {
        ...dumpData,
        matchedElement: elements
      },
      logId,
      dumpSubscriber
    );
    if (elements.length >= 2) {
      console.warn(
        `locate: multiple elements found, return the first one. (query: ${queryPrompt})`
      );
      return elements[0];
    }
    if (elements.length === 1) {
      return elements[0];
    }
    return null;
  }
  async extract(dataDemand) {
    var _a;
    _assert2.default.call(void 0, 
      typeof dataDemand === "object" || typeof dataDemand === "string",
      `dataDemand should be object or string, but get ${typeof dataDemand}`
    );
    const dumpSubscriber = this.onceDumpUpdatedFn;
    this.onceDumpUpdatedFn = void 0;
    const context = await this.contextRetrieverFn("extract");
    const startTime = Date.now();
    const { parseResult, usage } = await _chunkIHUBTSSWjs.AiExtractElementInfo.call(void 0, {
      context,
      dataQuery: dataDemand
    });
    const timeCost = Date.now() - startTime;
    const taskInfo = {
      ...this.taskInfo ? this.taskInfo : {},
      durationMs: timeCost,
      rawResponse: JSON.stringify(parseResult)
    };
    let errorLog;
    if ((_a = parseResult.errors) == null ? void 0 : _a.length) {
      errorLog = `AI response error: 
${parseResult.errors.join("\n")}`;
    }
    const dumpData = {
      type: "extract",
      context,
      userQuery: {
        dataDemand
      },
      matchedSection: [],
      matchedElement: [],
      data: null,
      taskInfo,
      error: errorLog
    };
    const logId = emitInsightDump(dumpData, void 0, dumpSubscriber);
    const { data } = parseResult;
    if (errorLog && !data) {
      console.error(errorLog);
      throw new Error(errorLog);
    }
    emitInsightDump(
      {
        ...dumpData,
        matchedSection: [],
        data
      },
      logId,
      dumpSubscriber
    );
    return {
      data,
      usage
    };
  }
  async assert(assertion) {
    if (typeof assertion !== "string") {
      throw new Error(
        "This is the assert method for Midscene, the first argument should be a string. If you want to use the assert method from Node.js, please import it from the Node.js assert module."
      );
    }
    const dumpSubscriber = this.onceDumpUpdatedFn;
    this.onceDumpUpdatedFn = void 0;
    const context = await this.contextRetrieverFn("assert");
    const startTime = Date.now();
    const assertResult = await _chunkIHUBTSSWjs.AiAssert.call(void 0, {
      assertion,
      context
    });
    const timeCost = Date.now() - startTime;
    const taskInfo = {
      ...this.taskInfo ? this.taskInfo : {},
      durationMs: timeCost,
      rawResponse: JSON.stringify(assertResult.content)
    };
    const { thought, pass } = assertResult.content;
    const dumpData = {
      type: "assert",
      context,
      userQuery: {
        assertion
      },
      matchedSection: [],
      matchedElement: [],
      data: null,
      taskInfo,
      assertionPass: pass,
      assertionThought: thought,
      error: pass ? void 0 : thought
    };
    emitInsightDump(dumpData, void 0, dumpSubscriber);
    return {
      pass,
      thought,
      usage: assertResult.usage
    };
  }
};

// src/index.ts
var src_default = Insight;





exports.Executor = Executor; exports.Insight = Insight; exports.src_default = src_default;

//# sourceMappingURL=chunk-QMEBSUXP.js.map