@ohos-perf/core 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.d.ts +489 -2
  2. package/dist/index.js +1011 -72
  3. package/package.json +48 -48
package/dist/index.js CHANGED
@@ -1836,8 +1836,8 @@ function readChunk(bytes, offset) {
1836
1836
  if (offset + 8 > bytes.length) {
1837
1837
  throw bad("PNG_TRUNCATED", `PNG is truncated at byte ${offset}: no chunk header`);
1838
1838
  }
1839
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1840
- const length = view.getUint32(offset);
1839
+ const view2 = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1840
+ const length = view2.getUint32(offset);
1841
1841
  const type = String.fromCharCode(
1842
1842
  bytes[offset + 4],
1843
1843
  bytes[offset + 5],
@@ -1944,13 +1944,13 @@ function decodePng(bytes) {
1944
1944
  if (chunk2.body.length !== 13) {
1945
1945
  throw bad("PNG_BAD_IHDR", `IHDR is ${chunk2.body.length} bytes, expected 13`);
1946
1946
  }
1947
- const view = new DataView(
1947
+ const view2 = new DataView(
1948
1948
  chunk2.body.buffer,
1949
1949
  chunk2.body.byteOffset,
1950
1950
  chunk2.body.byteLength
1951
1951
  );
1952
- width = view.getUint32(0);
1953
- height = view.getUint32(4);
1952
+ width = view2.getUint32(0);
1953
+ height = view2.getUint32(4);
1954
1954
  bitDepth = chunk2.body[8];
1955
1955
  colourType = chunk2.body[9];
1956
1956
  interlace = chunk2.body[12];
@@ -2571,9 +2571,9 @@ var CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
2571
2571
  function badGesture(message3) {
2572
2572
  return new OhosPerfError(message3, { code: "UITEST_BAD_GESTURE" });
2573
2573
  }
2574
- function assertPosition(field, value) {
2574
+ function assertPosition(field2, value) {
2575
2575
  if (!Number.isSafeInteger(value) || value < 0) {
2576
- throw badGesture(`gesture ${field} must be a non-negative integer (got ${String(value)})`);
2576
+ throw badGesture(`gesture ${field2} must be a non-negative integer (got ${String(value)})`);
2577
2577
  }
2578
2578
  }
2579
2579
  function assertVelocity(velocity) {
@@ -4167,7 +4167,7 @@ function messageOf(err) {
4167
4167
  return err instanceof Error ? err.message : String(err);
4168
4168
  }
4169
4169
  function isConnectedTcp(target) {
4170
- const fields2 = target.raw.split(" ").filter((field) => field !== "");
4170
+ const fields2 = target.raw.split(" ").filter((field2) => field2 !== "");
4171
4171
  return target.connected && fields2[1] === "TCP";
4172
4172
  }
4173
4173
  function isLoopback(id) {
@@ -5980,7 +5980,7 @@ function parseStep(value, path, seen) {
5980
5980
  if (seen.has(id)) throw stepError(idPath, `duplicate step id ${JSON.stringify(id)}`);
5981
5981
  seen.add(id);
5982
5982
  const name = step.name === void 0 ? id : requiredString(step.name, `${path}.name`, stepError);
5983
- const expect = step.expect === void 0 ? void 0 : parseExpect(step.expect, `${path}.expect`);
5983
+ const expect = step.expect === void 0 ? void 0 : parseExpectation(step.expect, `${path}.expect`);
5984
5984
  return {
5985
5985
  id,
5986
5986
  name,
@@ -5991,7 +5991,7 @@ function parseStep(value, path, seen) {
5991
5991
  ...expect === void 0 ? {} : { expect }
5992
5992
  };
5993
5993
  }
5994
- function parseExpect(value, path) {
5994
+ function parseExpectation(value, path) {
5995
5995
  const block = fields(value, path, ["present", "absent", "foreground"], stepError);
5996
5996
  let present;
5997
5997
  if (block.present !== void 0) {
@@ -6179,8 +6179,8 @@ var PARITY_ROWS = [
6179
6179
  {
6180
6180
  row: 5,
6181
6181
  name: "LLM GUI agent (`gui-agent`)",
6182
- status: "out",
6183
- reason: "Requires a network LLM endpoint and an API key, and never verifies task success; the agent skill is the deterministic replacement."
6182
+ status: "ported",
6183
+ reason: ""
6184
6184
  },
6185
6185
  {
6186
6186
  row: 6,
@@ -6316,8 +6316,8 @@ var PARITY_ROWS = [
6316
6316
  {
6317
6317
  row: 27,
6318
6318
  name: "Optimization detector (`opt-detector`)",
6319
- status: "out",
6320
- reason: "Requires a ~2 GB TensorFlow LSTM plus an sklearn classifier and is AArch64-only; it is a probabilistic guess, not a measurement."
6319
+ status: "ported",
6320
+ reason: ""
6321
6321
  },
6322
6322
  {
6323
6323
  row: 28,
@@ -8061,7 +8061,7 @@ function canonical(tree) {
8061
8061
  node.clickable ? "1" : "0",
8062
8062
  node.enabled ? "1" : "0",
8063
8063
  node.scrollable ? "1" : "0"
8064
- ].map((field) => `${String(field).length}:${String(field)}`).join("");
8064
+ ].map((field2) => `${String(field2).length}:${String(field2)}`).join("");
8065
8065
  return tree.map(line).join("");
8066
8066
  }
8067
8067
  function hashTree(tree) {
@@ -8081,10 +8081,10 @@ function shuffled(items, seed) {
8081
8081
  const out = [...items];
8082
8082
  const next = mulberry32(seed);
8083
8083
  for (let index = out.length - 1; index > 0; index -= 1) {
8084
- const pick = Math.floor(next() * (index + 1));
8084
+ const pick2 = Math.floor(next() * (index + 1));
8085
8085
  const held = out[index];
8086
- out[index] = out[pick];
8087
- out[pick] = held;
8086
+ out[index] = out[pick2];
8087
+ out[pick2] = held;
8088
8088
  }
8089
8089
  return out;
8090
8090
  }
@@ -8301,7 +8301,7 @@ async function resolveAppVersion(device, app) {
8301
8301
  return void 0;
8302
8302
  }
8303
8303
  }
8304
- function evaluate2(expect, nodes, app) {
8304
+ function evaluateExpectation(expect, nodes, app) {
8305
8305
  const outcomes = [];
8306
8306
  for (const clause of expect.present ?? []) {
8307
8307
  const matched = matchSelector(nodes, clause.selector);
@@ -8479,7 +8479,7 @@ var ScenarioRunner = class {
8479
8479
  );
8480
8480
  }
8481
8481
  const nodes = await this.device.uiTree();
8482
- expectations = evaluate2(step.expect, nodes, scenario.app);
8482
+ expectations = evaluateExpectation(step.expect, nodes, scenario.app);
8483
8483
  failure ??= failureOf(expectations);
8484
8484
  } catch (err) {
8485
8485
  failure ??= `expectation could not be evaluated: ${message2(err)}`;
@@ -8571,6 +8571,436 @@ function writeRunFiles(outDir, result) {
8571
8571
  write("pids.json", result.pids);
8572
8572
  }
8573
8573
 
8574
+ // src/scenario/agent.ts
8575
+ var IRREVERSIBLE_PATTERNS = [
8576
+ {
8577
+ pattern: /\bpay\b|\bpay now\b|立即支付|确认支付|去支付|立即购买/i,
8578
+ why: "payment is irreversible",
8579
+ sample: "\u7ACB\u5373\u652F\u4ED8"
8580
+ },
8581
+ {
8582
+ pattern: /\b(?:confirm order|place order|submit order|buy now)\b|提交订单|确认下单/i,
8583
+ why: "placing an order is irreversible",
8584
+ sample: "Confirm order"
8585
+ },
8586
+ {
8587
+ pattern: /\btransfer\b|\bsend money\b|\bremit\b|转账/i,
8588
+ why: "a transfer moves money and cannot be undone",
8589
+ sample: "Transfer"
8590
+ },
8591
+ {
8592
+ pattern: /\b(?:log ?in|sign ?in|register|sign ?up)\b|登录|注册/i,
8593
+ why: "signing in changes the account state",
8594
+ sample: "Log in"
8595
+ },
8596
+ {
8597
+ pattern: /\b(?:delete|unsubscribe|publish|post|share)\b|删除|注销|发布/i,
8598
+ why: "the action destroys or publishes content",
8599
+ sample: "Delete"
8600
+ }
8601
+ ];
8602
+ function labelsOf(node) {
8603
+ const labels = [node.text.trim(), node.id.replace(/[_-]+/g, " ").trim()];
8604
+ return labels.filter((label2) => label2 !== "");
8605
+ }
8606
+ function irreversibleReason(node) {
8607
+ for (const label2 of labelsOf(node)) {
8608
+ for (const entry of IRREVERSIBLE_PATTERNS) {
8609
+ if (entry.pattern.test(label2)) return entry.why;
8610
+ }
8611
+ }
8612
+ return void 0;
8613
+ }
8614
+ function describeDecision(decision) {
8615
+ if ("done" in decision) return "done";
8616
+ const action = decision.action;
8617
+ switch (action.action) {
8618
+ case "click":
8619
+ return `click at (${action.x}, ${action.y})`;
8620
+ case "swipe":
8621
+ return `swipe (${action.fromX}, ${action.fromY}) to (${action.toX}, ${action.toY})`;
8622
+ case "key":
8623
+ return `key ${String(action.key)}`;
8624
+ case "inputText":
8625
+ return `type ${JSON.stringify(action.text)} at (${action.x}, ${action.y})`;
8626
+ case "text":
8627
+ return `type ${JSON.stringify(action.text)}`;
8628
+ }
8629
+ }
8630
+ function oneLine(text) {
8631
+ return text.replace(/\r?\n/g, "\\n").replace(/\t/g, "\\t");
8632
+ }
8633
+ function renderTree(tree) {
8634
+ if (tree.length === 0) {
8635
+ return "(the screen is empty: no nodes were dumped)";
8636
+ }
8637
+ return tree.map((node) => {
8638
+ const parts = [
8639
+ `${" ".repeat(Math.max(0, node.depth - 1))}${node.type}`,
8640
+ node.text.trim() === "" ? "" : JSON.stringify(oneLine(node.text)),
8641
+ node.id === "" ? "" : `id=${node.id}`,
8642
+ node.bounds,
8643
+ node.clickable ? "clickable" : "unclickable"
8644
+ ];
8645
+ if (!node.enabled) parts.push("disabled");
8646
+ if (node.scrollable) parts.push("scrollable");
8647
+ return parts.filter((part) => part !== "").join(" ");
8648
+ }).join("\n");
8649
+ }
8650
+ function badInput(message3) {
8651
+ return new OhosPerfError(message3, { code: "SCENARIO_BAD_INPUT" });
8652
+ }
8653
+ function assertOptions(options) {
8654
+ if (options.task.trim() === "") {
8655
+ throw badInput("agent task must not be empty");
8656
+ }
8657
+ if (!Number.isSafeInteger(options.maxSteps) || options.maxSteps < 1) {
8658
+ throw badInput(
8659
+ `agent maxSteps must be a positive integer (got ${String(options.maxSteps)})`
8660
+ );
8661
+ }
8662
+ }
8663
+ function assertDecision(decision, step) {
8664
+ if (typeof decision !== "object" || decision === null) {
8665
+ throw badInput(`agent step ${step}: the model returned no decision`);
8666
+ }
8667
+ const record = decision;
8668
+ const hasAction = record["action"] !== void 0;
8669
+ const hasDone = record["done"] === true;
8670
+ if (hasAction === hasDone) {
8671
+ throw badInput(
8672
+ `agent step ${step}: the model must answer with exactly one of an action or done`
8673
+ );
8674
+ }
8675
+ return decision;
8676
+ }
8677
+ function agentPrompt(request) {
8678
+ const history = request.history.length === 0 ? "(no steps yet)" : request.history.map((entry) => {
8679
+ const did = entry.did === void 0 ? entry.status : `${entry.did} \u2014 ${entry.status}`;
8680
+ const detail11 = entry.detail === void 0 ? "" : ` (${entry.detail})`;
8681
+ return ` ${entry.step + 1}. ${did}: ${entry.reason}${detail11}`;
8682
+ }).join("\n");
8683
+ return [
8684
+ `You are driving the app ${request.app} on an OHOS device to complete a task.`,
8685
+ `Task: ${request.task}`,
8686
+ "",
8687
+ `Step ${request.step + 1} of ${request.maxSteps}.`,
8688
+ "",
8689
+ "The current screen, one node per line:",
8690
+ request.screen,
8691
+ "",
8692
+ "Steps so far:",
8693
+ history,
8694
+ "",
8695
+ "Answer with one JSON object and nothing else. To act:",
8696
+ ' {"action": {"action": "click", "x": 540, "y": 1170}, "reason": "why"}',
8697
+ "Allowed gestures: click, swipe, key, inputText, text.",
8698
+ "To finish, include the expectation that proves the task is done:",
8699
+ ' {"done": true, "reason": "why", "expect": {"present": [{"selector": {"kind": "text", "text": "Done"}}]}}',
8700
+ "A done answer without an expectation is recorded as unverified, not as success.",
8701
+ "Do not tap payment, ordering, transfer, sign-in, delete or publish actions."
8702
+ ].join("\n");
8703
+ }
8704
+ var GESTURE_NAMES = /* @__PURE__ */ new Set(["click", "swipe", "key", "inputText", "text"]);
8705
+ function parseGesture(value) {
8706
+ if (typeof value !== "object" || value === null) {
8707
+ throw badInput(`the answer's "action" must be a gesture object`);
8708
+ }
8709
+ const record = value;
8710
+ const name = record["action"];
8711
+ if (typeof name !== "string" || !GESTURE_NAMES.has(name)) {
8712
+ throw badInput(
8713
+ `the answer's gesture must be one of ${[...GESTURE_NAMES].join(", ")} (got ${JSON.stringify(name)})`
8714
+ );
8715
+ }
8716
+ return value;
8717
+ }
8718
+ function unfence(text) {
8719
+ const match = /^\s*```(?:json)?\s*\n([\s\S]*?)\n\s*```\s*$/.exec(text);
8720
+ return match === null ? text : match[1];
8721
+ }
8722
+ function parseDecision(text) {
8723
+ let parsed;
8724
+ try {
8725
+ parsed = JSON.parse(unfence(text));
8726
+ } catch {
8727
+ throw badInput(
8728
+ `the model's answer is not JSON: ${JSON.stringify(text.slice(0, 120))}`
8729
+ );
8730
+ }
8731
+ const decision = assertDecision(parsed, 0);
8732
+ const record = parsed;
8733
+ const reason = typeof record["reason"] === "string" ? record["reason"] : "";
8734
+ if ("done" in decision) {
8735
+ const expect = record["expect"] === void 0 ? void 0 : parseExpectation(record["expect"], "expect");
8736
+ return { done: true, reason, ...expect === void 0 ? {} : { expect } };
8737
+ }
8738
+ return { action: parseGesture(record["action"]), reason };
8739
+ }
8740
+ function targetOf(tree, x, y) {
8741
+ const containing = tree.filter((node) => {
8742
+ const rect = node.boundsRect ?? parseBounds(node.bounds);
8743
+ if (rect === void 0) return false;
8744
+ return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
8745
+ });
8746
+ const area = (node) => {
8747
+ const rect = node.boundsRect ?? parseBounds(node.bounds);
8748
+ return (rect.right - rect.left) * (rect.bottom - rect.top);
8749
+ };
8750
+ return containing.slice().sort((a, b) => Number(b.clickable) - Number(a.clickable) || area(a) - area(b))[0];
8751
+ }
8752
+ function unmetExpectation(expect, tree, app) {
8753
+ const outcomes = evaluateExpectation(expect, tree, app);
8754
+ const failed = outcomes.filter((outcome) => !outcome.ok);
8755
+ if (failed.length === 0) return void 0;
8756
+ return failed.map((outcome) => outcome.detail === void 0 ? outcome.label : `${outcome.label}: ${outcome.detail}`).join("; ");
8757
+ }
8758
+ async function runAgent(device, model, options) {
8759
+ assertOptions(options);
8760
+ const steps = [];
8761
+ const history = [];
8762
+ const states = /* @__PURE__ */ new Set();
8763
+ let status = "exhausted";
8764
+ for (let index = 0; index < options.maxSteps; index += 1) {
8765
+ const tree = await device.uiTree();
8766
+ const before = hashTree(tree);
8767
+ states.add(before);
8768
+ const decision = assertDecision(
8769
+ await model.decide({
8770
+ task: options.task,
8771
+ app: options.app,
8772
+ step: index,
8773
+ maxSteps: options.maxSteps,
8774
+ screen: renderTree(tree),
8775
+ history: [...history]
8776
+ }),
8777
+ index
8778
+ );
8779
+ if ("done" in decision) {
8780
+ if (decision.expect === void 0) {
8781
+ status = "unverified";
8782
+ steps.push({
8783
+ index,
8784
+ status: "unverified",
8785
+ reason: decision.reason,
8786
+ detail: "the model claimed done with no expectation, so the screen proves nothing",
8787
+ before,
8788
+ after: before,
8789
+ navigated: false
8790
+ });
8791
+ break;
8792
+ }
8793
+ const unmet = unmetExpectation(decision.expect, tree, options.app);
8794
+ if (unmet === void 0) {
8795
+ status = "completed";
8796
+ steps.push({
8797
+ index,
8798
+ status: "verified",
8799
+ reason: decision.reason,
8800
+ before,
8801
+ after: before,
8802
+ navigated: false
8803
+ });
8804
+ break;
8805
+ }
8806
+ status = "unverified";
8807
+ steps.push({
8808
+ index,
8809
+ status: "unverified",
8810
+ reason: decision.reason,
8811
+ detail: unmet,
8812
+ before,
8813
+ after: before,
8814
+ navigated: false
8815
+ });
8816
+ break;
8817
+ }
8818
+ const gesture = decision.action;
8819
+ const point = gesture.action === "click" || gesture.action === "inputText" ? { x: gesture.x, y: gesture.y } : void 0;
8820
+ const target = point === void 0 ? void 0 : targetOf(tree, point.x, point.y);
8821
+ const refused = target === void 0 ? void 0 : irreversibleReason(target);
8822
+ if (refused !== void 0 && options.allowIrreversible !== true) {
8823
+ status = "refused";
8824
+ steps.push({
8825
+ index,
8826
+ status: "refused",
8827
+ reason: decision.reason,
8828
+ action: gesture,
8829
+ detail: refused,
8830
+ before,
8831
+ after: before,
8832
+ navigated: false
8833
+ });
8834
+ break;
8835
+ }
8836
+ let failure;
8837
+ try {
8838
+ await device.gesture(gesture);
8839
+ } catch (err) {
8840
+ failure = err.message;
8841
+ }
8842
+ const nextTree = await device.uiTree();
8843
+ const after = hashTree(nextTree);
8844
+ states.add(after);
8845
+ const step = {
8846
+ index,
8847
+ status: failure === void 0 ? "acted" : "failed",
8848
+ reason: decision.reason,
8849
+ action: gesture,
8850
+ ...failure === void 0 ? {} : { detail: failure },
8851
+ before,
8852
+ after,
8853
+ navigated: after !== before
8854
+ };
8855
+ steps.push(step);
8856
+ history.push({
8857
+ step: index,
8858
+ status: step.status,
8859
+ reason: decision.reason,
8860
+ did: describeDecision(decision),
8861
+ ...failure === void 0 ? {} : { detail: failure }
8862
+ });
8863
+ }
8864
+ return {
8865
+ version: 1,
8866
+ task: options.task,
8867
+ app: options.app,
8868
+ steps,
8869
+ status,
8870
+ statesReached: states.size
8871
+ };
8872
+ }
8873
+ async function replayAgent(device, transcript) {
8874
+ let performed = 0;
8875
+ let skipped = 0;
8876
+ for (const step of transcript.steps) {
8877
+ if (step.action === void 0) {
8878
+ skipped += 1;
8879
+ continue;
8880
+ }
8881
+ const tree = await device.uiTree();
8882
+ if (hashTree(tree) !== step.before) {
8883
+ return { performed, skipped, divergedAt: step.index };
8884
+ }
8885
+ await device.gesture(step.action);
8886
+ performed += 1;
8887
+ }
8888
+ return { performed, skipped };
8889
+ }
8890
+
8891
+ // src/scenario/agent-client.ts
8892
+ var OWN_BASE_URL = "OHOS_PERF_AGENT_BASE_URL";
8893
+ var OWN_API_KEY = "OHOS_PERF_AGENT_API_KEY";
8894
+ var OWN_MODEL = "OHOS_PERF_AGENT_MODEL";
8895
+ var FALLBACK_BASE_URL = "GLM_BASE_URL";
8896
+ var FALLBACK_API_KEY = "GLM_API_KEY";
8897
+ var FALLBACK_MODEL = "GLM_MODEL";
8898
+ var DEFAULT_MODEL = "autoglm-phone-9b";
8899
+ var DEFAULT_TIMEOUT_MS4 = 6e4;
8900
+ var EXCERPT_CHARS = 200;
8901
+ function pick(env, own, fallback) {
8902
+ const value = env[own];
8903
+ if (value !== void 0 && value.trim() !== "") return value.trim();
8904
+ const other = env[fallback];
8905
+ return other !== void 0 && other.trim() !== "" ? other.trim() : void 0;
8906
+ }
8907
+ function readAgentConfig(env) {
8908
+ const baseUrl = pick(env, OWN_BASE_URL, FALLBACK_BASE_URL);
8909
+ const apiKey = pick(env, OWN_API_KEY, FALLBACK_API_KEY);
8910
+ if (baseUrl === void 0 || apiKey === void 0) return void 0;
8911
+ return {
8912
+ baseUrl,
8913
+ apiKey,
8914
+ model: pick(env, OWN_MODEL, FALLBACK_MODEL) ?? DEFAULT_MODEL
8915
+ };
8916
+ }
8917
+ function badClient(message3) {
8918
+ return new OhosPerfError(message3, { code: "AGENT_BAD_CONFIG" });
8919
+ }
8920
+ function contentOf(body) {
8921
+ if (typeof body !== "object" || body === null) {
8922
+ throw new OhosPerfError("the model endpoint returned a body that is not an object", {
8923
+ code: "AGENT_BAD_RESPONSE"
8924
+ });
8925
+ }
8926
+ const choices = body["choices"];
8927
+ if (!Array.isArray(choices) || choices.length === 0) {
8928
+ throw new OhosPerfError(
8929
+ "the model endpoint returned no choices; expected an OpenAI-compatible /chat/completions response",
8930
+ { code: "AGENT_BAD_RESPONSE" }
8931
+ );
8932
+ }
8933
+ const first = choices[0];
8934
+ const message3 = first?.["message"];
8935
+ const content = message3?.["content"];
8936
+ if (typeof content !== "string") {
8937
+ throw new OhosPerfError("the model endpoint returned a choice with no message content", {
8938
+ code: "AGENT_BAD_RESPONSE"
8939
+ });
8940
+ }
8941
+ return content;
8942
+ }
8943
+ function httpAgentModel(options) {
8944
+ const baseUrl = options.baseUrl.trim().replace(/\/+$/, "");
8945
+ const model = options.model.trim();
8946
+ if (baseUrl === "") throw badClient("the agent base URL must not be empty");
8947
+ if (model === "") throw badClient("the agent model name must not be empty");
8948
+ const url = `${baseUrl}/chat/completions`;
8949
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS4;
8950
+ return {
8951
+ async decide(turn) {
8952
+ const body = {
8953
+ model,
8954
+ messages: [{ role: "user", content: agentPrompt(turn) }],
8955
+ // The answer is JSON the loop parses, so the endpoint is asked for JSON
8956
+ // rather than for prose that happens to contain some.
8957
+ response_format: { type: "json_object" }
8958
+ };
8959
+ let response;
8960
+ try {
8961
+ response = await options.fetch(url, {
8962
+ method: "POST",
8963
+ headers: {
8964
+ "Content-Type": "application/json",
8965
+ Authorization: `Bearer ${options.apiKey}`
8966
+ },
8967
+ body: JSON.stringify(body),
8968
+ signal: AbortSignal.timeout(timeoutMs)
8969
+ });
8970
+ } catch (err) {
8971
+ throw new OhosPerfError(
8972
+ `the agent endpoint could not be reached: ${err.message}`,
8973
+ { code: "AGENT_UNREACHABLE", cause: err }
8974
+ );
8975
+ }
8976
+ const text = await response.text();
8977
+ if (!response.ok) {
8978
+ throw new OhosPerfError(
8979
+ `the agent endpoint answered ${response.status}: ${text.slice(0, EXCERPT_CHARS)}`,
8980
+ { code: "AGENT_HTTP_ERROR" }
8981
+ );
8982
+ }
8983
+ const content = contentOf(safeJson(text));
8984
+ if (content.trim() === "") {
8985
+ throw new OhosPerfError("the model returned an empty answer", {
8986
+ code: "AGENT_BAD_RESPONSE"
8987
+ });
8988
+ }
8989
+ return parseDecision(content);
8990
+ }
8991
+ };
8992
+ }
8993
+ function safeJson(text) {
8994
+ try {
8995
+ return JSON.parse(text);
8996
+ } catch {
8997
+ throw new OhosPerfError(
8998
+ `the agent endpoint answered with something that is not JSON: ${text.slice(0, EXCERPT_CHARS)}`,
8999
+ { code: "AGENT_BAD_RESPONSE" }
9000
+ );
9001
+ }
9002
+ }
9003
+
8574
9004
  // src/query/rows.ts
8575
9005
  function num(value) {
8576
9006
  if (value == null) return 0;
@@ -16088,10 +16518,10 @@ function round2HalfEven(value) {
16088
16518
  return negative ? -result : result;
16089
16519
  }
16090
16520
  function decompose(value) {
16091
- const view = new DataView(new ArrayBuffer(8));
16092
- view.setFloat64(0, value);
16093
- const high = view.getUint32(0);
16094
- const low = view.getUint32(4);
16521
+ const view2 = new DataView(new ArrayBuffer(8));
16522
+ view2.setFloat64(0, value);
16523
+ const high = view2.getUint32(0);
16524
+ const low = view2.getUint32(4);
16095
16525
  const exponentBits = high >>> 20 & 2047;
16096
16526
  let mantissa = BigInt(high & 1048575) << 32n | BigInt(low);
16097
16527
  if (exponentBits === 0) return { mantissa, exponent: -1074 };
@@ -17763,6 +18193,495 @@ function openZip(bytes) {
17763
18193
  };
17764
18194
  }
17765
18195
 
18196
+ // src/hap/elf.ts
18197
+ var EM_AARCH64 = 183;
18198
+ var SHT_SYMTAB = 2;
18199
+ var SHT_NOBITS = 8;
18200
+ var SHT_DYNSYM = 11;
18201
+ function fail2(message3, cause) {
18202
+ throw new OhosPerfError(message3, { code: "ELF_INVALID", ...cause === void 0 ? {} : { cause } });
18203
+ }
18204
+ function view(bytes) {
18205
+ return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
18206
+ }
18207
+ function field(dv, at, size, what) {
18208
+ if (at < 0 || at + size > dv.byteLength) {
18209
+ fail2(`ELF is truncated: ${what} at offset ${at} runs past the ${dv.byteLength}-byte file`);
18210
+ }
18211
+ if (size === 1) return dv.getUint8(at);
18212
+ if (size === 2) return dv.getUint16(at, true);
18213
+ if (size === 4) return dv.getUint32(at, true);
18214
+ return dv.getUint32(at, true) + dv.getUint32(at + 4, true) * 2 ** 32;
18215
+ }
18216
+ function readString(table, offset) {
18217
+ if (offset < 0 || offset >= table.length) return "";
18218
+ const end = table.indexOf(0, offset);
18219
+ return new TextDecoder("utf-8").decode(
18220
+ table.subarray(offset, end === -1 ? table.length : end)
18221
+ );
18222
+ }
18223
+ function bindOf(info) {
18224
+ const bind = info >> 4;
18225
+ if (bind === 0) return "local";
18226
+ if (bind === 1) return "global";
18227
+ if (bind === 2) return "weak";
18228
+ return "other";
18229
+ }
18230
+ function typeOf(info) {
18231
+ const type = info & 15;
18232
+ if (type === 0) return "notype";
18233
+ if (type === 1) return "object";
18234
+ if (type === 2) return "func";
18235
+ if (type === 3) return "section";
18236
+ if (type === 4) return "file";
18237
+ return "other";
18238
+ }
18239
+ function symbolTableOf(dv, sections, links, bytes, index) {
18240
+ const section = sections[index];
18241
+ const link = links[index];
18242
+ const strings = link >= 0 && link < sections.length ? bytes.subarray(sections[link].offset, sections[link].offset + sections[link].size) : new Uint8Array(0);
18243
+ const entrySize = section.entrySize === 0 ? 24 : section.entrySize;
18244
+ const count = Math.floor(section.size / entrySize);
18245
+ const symbols = [];
18246
+ for (let at = 0; at < count; at += 1) {
18247
+ const base = section.offset + at * entrySize;
18248
+ if (at === 0) continue;
18249
+ const nameOffset = field(dv, base, 4, "st_name");
18250
+ const info = field(dv, base + 4, 1, "st_info");
18251
+ const sectionIndex = field(dv, base + 6, 2, "st_shndx");
18252
+ const size = field(dv, base + 16, 8, "st_size");
18253
+ const name = readString(strings, nameOffset);
18254
+ symbols.push({ name, bind: bindOf(info), type: typeOf(info), size, sectionIndex });
18255
+ }
18256
+ return symbols;
18257
+ }
18258
+ function readElf(bytes) {
18259
+ if (bytes.length < 4) {
18260
+ fail2(`ELF is truncated: ${bytes.length} bytes is shorter than the 4-byte magic`);
18261
+ }
18262
+ if (bytes[0] !== 127 || bytes[1] !== 69 || bytes[2] !== 76 || bytes[3] !== 70) {
18263
+ fail2("not an ELF file: the first four bytes are not \\x7fELF");
18264
+ }
18265
+ if (bytes.length < 16) {
18266
+ fail2(`ELF is truncated: ${bytes.length} bytes is shorter than the 16-byte ident`);
18267
+ }
18268
+ const bits = bytes[4] === 2 ? 64 : bytes[4] === 1 ? 32 : 0;
18269
+ if (bits === 0) {
18270
+ fail2(`unsupported ELF class ${String(bytes[4])}: only 32-bit and 64-bit are defined`);
18271
+ }
18272
+ const endian = bytes[5] === 1 ? "little" : bytes[5] === 2 ? "big" : void 0;
18273
+ if (endian === void 0) {
18274
+ fail2(`unsupported ELF data encoding ${String(bytes[5])}: only little and big endian are defined`);
18275
+ }
18276
+ if (bits !== 64 || endian !== "little") {
18277
+ fail2(`unsupported ELF: ${String(bits)}-bit ${endian}-endian; OHOS ships 64-bit little-endian`);
18278
+ }
18279
+ const headerSize = 64;
18280
+ if (bytes.length < headerSize) {
18281
+ fail2(`ELF is truncated: ${bytes.length} bytes is shorter than the ${headerSize}-byte header`);
18282
+ }
18283
+ const dv = view(bytes);
18284
+ const machine = field(dv, 18, 2, "e_machine");
18285
+ const type = field(dv, 16, 2, "e_type");
18286
+ const shoff = field(dv, 40, 8, "e_shoff");
18287
+ const shentsize = field(dv, 58, 2, "e_shentsize");
18288
+ const shnum = field(dv, 60, 2, "e_shnum");
18289
+ const shstrndx = field(dv, 62, 2, "e_shstrndx");
18290
+ if (shnum === 0) {
18291
+ return {
18292
+ bits: 64,
18293
+ endian,
18294
+ machine,
18295
+ type,
18296
+ sections: [],
18297
+ symbols: [],
18298
+ section: () => void 0,
18299
+ bytesOf: () => new Uint8Array(0)
18300
+ };
18301
+ }
18302
+ if (shentsize !== 64) {
18303
+ fail2(`unsupported section header size ${shentsize}: a 64-bit ELF uses 64`);
18304
+ }
18305
+ if (shoff + shnum * shentsize > bytes.length) {
18306
+ fail2(
18307
+ `ELF is truncated: the section header table at offset ${shoff} with ${shnum} entries runs past the ${bytes.length}-byte file`
18308
+ );
18309
+ }
18310
+ if (shstrndx >= shnum) {
18311
+ fail2(`e_shstrndx ${shstrndx} names a section beyond the ${shnum} the file declares`);
18312
+ }
18313
+ const raw = [];
18314
+ const links = [];
18315
+ for (let index = 0; index < shnum; index += 1) {
18316
+ const at = shoff + index * shentsize;
18317
+ raw.push({
18318
+ nameOffset: field(dv, at, 4, `section[${index}].sh_name`),
18319
+ type: field(dv, at + 4, 4, `section[${index}].sh_type`),
18320
+ flags: field(dv, at + 8, 8, `section[${index}].sh_flags`),
18321
+ offset: field(dv, at + 24, 8, `section[${index}].sh_offset`),
18322
+ size: field(dv, at + 32, 8, `section[${index}].sh_size`),
18323
+ link: field(dv, at + 40, 4, `section[${index}].sh_link`),
18324
+ entrySize: field(dv, at + 56, 8, `section[${index}].sh_entsize`)
18325
+ });
18326
+ links.push(raw[index].link);
18327
+ }
18328
+ for (const [index, section] of raw.entries()) {
18329
+ if (section.type === SHT_NOBITS || section.type === 0) continue;
18330
+ if (section.offset + section.size > bytes.length) {
18331
+ fail2(
18332
+ `ELF is truncated: section ${index} at offset ${section.offset} with size ${section.size} runs past the ${bytes.length}-byte file`
18333
+ );
18334
+ }
18335
+ }
18336
+ const nameTable = raw[shstrndx];
18337
+ const strings = bytes.subarray(nameTable.offset, nameTable.offset + nameTable.size);
18338
+ const sections = raw.map((section) => ({
18339
+ name: readString(strings, section.nameOffset),
18340
+ type: section.type,
18341
+ flags: section.flags,
18342
+ offset: section.offset,
18343
+ size: section.size,
18344
+ entrySize: section.entrySize
18345
+ }));
18346
+ const symbols = [];
18347
+ for (const [index, section] of sections.entries()) {
18348
+ if (section.type !== SHT_SYMTAB && section.type !== SHT_DYNSYM) continue;
18349
+ symbols.push(...symbolTableOf(dv, sections, links, bytes, index));
18350
+ }
18351
+ const byName = new Map(sections.map((section) => [section.name, section]));
18352
+ return {
18353
+ bits: 64,
18354
+ endian,
18355
+ machine,
18356
+ type,
18357
+ sections,
18358
+ symbols,
18359
+ section: (name) => byName.get(name),
18360
+ bytesOf: (name) => {
18361
+ const section = byName.get(name);
18362
+ if (section === void 0 || section.type === SHT_NOBITS) return new Uint8Array(0);
18363
+ return bytes.subarray(section.offset, section.offset + section.size);
18364
+ }
18365
+ };
18366
+ }
18367
+ function classifyInstruction(word) {
18368
+ const masked = (mask) => (word & mask) >>> 0;
18369
+ if (masked(4294966303) === 3596550144) return "ret";
18370
+ if (masked(4294966303) === 3594452992) return "blr";
18371
+ if (masked(4294966303) === 3592355840) return "br";
18372
+ if (masked(4227858432) === 2483027968) return "bl";
18373
+ if (masked(4227858432) === 335544320) return "b";
18374
+ if (masked(4278190096) === 1409286144) return "bcond";
18375
+ if (masked(2113929216) === 872415232) return "cbz";
18376
+ if (masked(2113929216) === 905969664) return "tbz";
18377
+ if (masked(2667577344) === 2415919104) return "adrp";
18378
+ if (masked(2667577344) === 268435456) return "adr";
18379
+ if (masked(989855744) === 956301312) {
18380
+ return masked(4194304) === 0 ? "str" : "ldr";
18381
+ }
18382
+ if (masked(520093696) === 285212672) return "add";
18383
+ if (masked(167772160) === 167772160) return "vector";
18384
+ return "other";
18385
+ }
18386
+ function countInstructions(payload) {
18387
+ const counts = {
18388
+ total: 0,
18389
+ ret: 0,
18390
+ blr: 0,
18391
+ br: 0,
18392
+ bl: 0,
18393
+ b: 0,
18394
+ bcond: 0,
18395
+ cbz: 0,
18396
+ tbz: 0,
18397
+ adrp: 0,
18398
+ adr: 0,
18399
+ ldr: 0,
18400
+ str: 0,
18401
+ add: 0,
18402
+ vector: 0,
18403
+ other: 0
18404
+ };
18405
+ const dv = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
18406
+ const words = Math.floor(payload.length / 4);
18407
+ for (let index = 0; index < words; index += 1) {
18408
+ const cls = classifyInstruction(dv.getUint32(index * 4, true));
18409
+ counts[cls] += 1;
18410
+ counts.total += 1;
18411
+ }
18412
+ return counts;
18413
+ }
18414
+
18415
+ // src/hap/optimization.ts
18416
+ var OFFLINE_WINDOW = { startNs: 0, endNs: 0 };
18417
+ var LTO_PATTERNS = [
18418
+ { pattern: /^lto_priv\./, why: "lto_priv symbol" },
18419
+ { pattern: /^\.gnu\.lto_/, why: ".gnu.lto section" },
18420
+ { pattern: /^\.gnu\.lto$/, why: ".gnu.lto section" },
18421
+ { pattern: /^lto_[0-9]+\.[0-9]+$/, why: "lto_N.M symbol" }
18422
+ ];
18423
+ var RECORDED_FLAG = /^-(O[0-3s]|Oz|Ofast)$/;
18424
+ var LEVEL_OF_FLAG = {
18425
+ "-O0": "unoptimized",
18426
+ "-O1": "low",
18427
+ "-O2": "medium",
18428
+ "-O3": "high",
18429
+ "-Os": "medium",
18430
+ "-Oz": "medium",
18431
+ "-Ofast": "high"
18432
+ };
18433
+ var VECTOR_DENSITY_HIGH = 0.1;
18434
+ var VECTOR_DENSITY_NONE = 0.02;
18435
+ function byString6(a, b) {
18436
+ return a < b ? -1 : a > b ? 1 : 0;
18437
+ }
18438
+ function decode(bytes) {
18439
+ return new TextDecoder("utf-8").decode(bytes);
18440
+ }
18441
+ function commentStrings(bytes) {
18442
+ return decode(bytes).split("\0").map((part) => part.trim()).filter((part) => part !== "");
18443
+ }
18444
+ function inspectBinary(input) {
18445
+ let elf;
18446
+ try {
18447
+ elf = readElf(input.bytes);
18448
+ } catch (err) {
18449
+ throw new OhosPerfError(
18450
+ `${input.path}: ${err.message}`,
18451
+ { code: "ELF_INVALID", cause: err }
18452
+ );
18453
+ }
18454
+ const textSection = elf.section(".text");
18455
+ const textBytes = textSection?.size ?? 0;
18456
+ const instructions = countInstructions(elf.bytesOf(".text"));
18457
+ const symbolTablePresent = elf.sections.some(
18458
+ (section) => section.type === 2 || section.type === 11
18459
+ );
18460
+ const ltoMarkers = [];
18461
+ for (const section of elf.sections) {
18462
+ if (LTO_PATTERNS.some((entry) => entry.pattern.test(section.name))) {
18463
+ ltoMarkers.push(section.name);
18464
+ }
18465
+ }
18466
+ for (const symbol of elf.symbols) {
18467
+ if (LTO_PATTERNS.some((entry) => entry.pattern.test(symbol.name))) {
18468
+ ltoMarkers.push(symbol.name);
18469
+ }
18470
+ }
18471
+ const lto = ltoMarkers.length > 0 ? "present" : symbolTablePresent ? "absent" : "unknown";
18472
+ const debugSections = elf.sections.map((section) => section.name).filter((name) => name.startsWith(".debug_") || name === ".zdebug_info");
18473
+ const commentSection = elf.section(".comment");
18474
+ const compiler = commentSection === void 0 ? [] : commentStrings(elf.bytesOf(".comment"));
18475
+ const recordedFlags = [];
18476
+ for (const line of compiler) {
18477
+ for (const token of line.split(/\s+/)) {
18478
+ if (RECORDED_FLAG.test(token) && !recordedFlags.includes(token)) recordedFlags.push(token);
18479
+ }
18480
+ }
18481
+ const functions = elf.symbols.filter((symbol) => symbol.type === "func");
18482
+ const countBind = (bind) => functions.filter((symbol) => symbol.bind === bind).length;
18483
+ return {
18484
+ path: input.path,
18485
+ size: input.bytes.length,
18486
+ machine: elf.machine,
18487
+ textBytes,
18488
+ instructions,
18489
+ lto,
18490
+ ltoMarkers,
18491
+ debug: debugSections.length > 0,
18492
+ debugSections,
18493
+ compiler,
18494
+ recordedFlags,
18495
+ symbols: {
18496
+ functions: functions.length,
18497
+ global: countBind("global"),
18498
+ local: countBind("local"),
18499
+ weak: countBind("weak")
18500
+ },
18501
+ stripped: functions.length === 0
18502
+ };
18503
+ }
18504
+ function classifyOptimization(facts) {
18505
+ for (const flag2 of facts.recordedFlags) {
18506
+ const level = LEVEL_OF_FLAG[flag2];
18507
+ if (level !== void 0) return { level, basis: "recorded", signals: [] };
18508
+ }
18509
+ const total = facts.instructions.total;
18510
+ if (total === 0) {
18511
+ return { level: "unknown", basis: "none", signals: [] };
18512
+ }
18513
+ const vectorDensity = facts.instructions.vector / total;
18514
+ if (vectorDensity >= VECTOR_DENSITY_HIGH) {
18515
+ return { level: "high", basis: "inferred", signals: ["vector_density"] };
18516
+ }
18517
+ if (facts.debug) {
18518
+ return {
18519
+ level: "unoptimized",
18520
+ basis: "inferred",
18521
+ signals: vectorDensity <= VECTOR_DENSITY_NONE ? ["debug_sections", "no_vector_code"] : ["debug_sections"]
18522
+ };
18523
+ }
18524
+ if (vectorDensity <= VECTOR_DENSITY_NONE) {
18525
+ return { level: "low", basis: "inferred", signals: ["no_vector_code"] };
18526
+ }
18527
+ return { level: "medium", basis: "inferred", signals: ["vector_density"] };
18528
+ }
18529
+ var ARM64_LIBRARY = /^(?:libs|lib)\/arm64(?:-v8a)?\//;
18530
+ var SHARED_OBJECT = /\.so(?:\.|$)/;
18531
+ function extractBinaries(input) {
18532
+ if (input.path.endsWith(".a")) {
18533
+ throw new OhosPerfError(
18534
+ `${input.path}: an .a archive is not read by this package; pass the .so files (or the package that contains them) instead`,
18535
+ { code: "SCENARIO_BAD_INPUT" }
18536
+ );
18537
+ }
18538
+ if (!isZip(input.bytes)) {
18539
+ return [{ path: input.path, bytes: input.bytes }];
18540
+ }
18541
+ const archive = openZip(input.bytes);
18542
+ const binaries = [];
18543
+ for (const entry of archive.entries) {
18544
+ if (!ARM64_LIBRARY.test(entry.name)) continue;
18545
+ if (!SHARED_OBJECT.test(entry.name)) continue;
18546
+ const bytes = archive.read(entry);
18547
+ if (bytes.length < 4 || bytes[0] !== 127 || bytes[1] !== 69) continue;
18548
+ binaries.push({ path: entry.name, bytes });
18549
+ }
18550
+ if (binaries.length === 0) {
18551
+ throw new OhosPerfError(
18552
+ `${input.path}: no arm64 libraries (libs/arm64/*.so) in the package`,
18553
+ { code: "SCENARIO_BAD_INPUT" }
18554
+ );
18555
+ }
18556
+ return binaries;
18557
+ }
18558
+ function offlineProvenance(rows) {
18559
+ return { collector: "offline", table: "elf", rows, device: "offline" };
18560
+ }
18561
+ var LEVEL_IDS = {
18562
+ unoptimized: "binary.unoptimized.files.count",
18563
+ low: "binary.low.optimization.files.count",
18564
+ medium: "binary.medium.optimization.files.count",
18565
+ high: "binary.high.optimization.files.count",
18566
+ unknown: "binary.unknown.optimization.files.count"
18567
+ };
18568
+ function buildMetrics(binaries) {
18569
+ const rows = binaries.length;
18570
+ const make = (id, value, unit, fidelity) => metric({
18571
+ id,
18572
+ value,
18573
+ unit,
18574
+ fidelity,
18575
+ provenance: offlineProvenance(rows),
18576
+ window: OFFLINE_WINDOW
18577
+ });
18578
+ const metrics = [
18579
+ make("binary.files.count", rows, "count", "exact"),
18580
+ make("binary.text.bytes", binaries.reduce((sum, b) => sum + b.facts.textBytes, 0), "bytes", "exact"),
18581
+ make(
18582
+ "binary.instructions.count",
18583
+ binaries.reduce((sum, b) => sum + b.facts.instructions.total, 0),
18584
+ "count",
18585
+ "exact"
18586
+ ),
18587
+ make("binary.lto.files.count", binaries.filter((b) => b.facts.lto === "present").length, "count", "exact"),
18588
+ make("binary.lto.unknown.files.count", binaries.filter((b) => b.facts.lto === "unknown").length, "count", "exact"),
18589
+ make("binary.debug.files.count", binaries.filter((b) => b.facts.debug).length, "count", "exact"),
18590
+ make("binary.stripped.files.count", binaries.filter((b) => b.facts.stripped).length, "count", "exact")
18591
+ ];
18592
+ const byLevel = /* @__PURE__ */ new Map();
18593
+ for (const binary of binaries) {
18594
+ byLevel.set(binary.verdict.level, (byLevel.get(binary.verdict.level) ?? 0) + 1);
18595
+ }
18596
+ for (const level of ["unoptimized", "low", "medium", "high", "unknown"]) {
18597
+ const count = byLevel.get(level) ?? 0;
18598
+ if (count === 0) continue;
18599
+ metrics.push(make(LEVEL_IDS[level], count, "count", "proxy"));
18600
+ }
18601
+ return metrics.sort((a, b) => byString6(a.id, b.id));
18602
+ }
18603
+ function buildEvidence(packageName, binaries) {
18604
+ const subject = { process: packageName };
18605
+ const items = [];
18606
+ for (const binary of binaries) {
18607
+ if (binary.facts.lto === "present") {
18608
+ items.push(evidence({
18609
+ kind: "optimization",
18610
+ severity: "info",
18611
+ subject,
18612
+ window: OFFLINE_WINDOW,
18613
+ signals: {
18614
+ path: binary.path,
18615
+ lto: "present",
18616
+ markers: binary.facts.ltoMarkers.length,
18617
+ level: binary.verdict.level,
18618
+ basis: binary.verdict.basis
18619
+ },
18620
+ explain: `${binary.path} was linked with LTO: ${binary.facts.ltoMarkers.slice(0, 3).join(", ")}` + (binary.facts.ltoMarkers.length > 3 ? `, and ${binary.facts.ltoMarkers.length - 3} more` : ""),
18621
+ drillDown: [],
18622
+ key: `${binary.path}:lto`
18623
+ }));
18624
+ }
18625
+ if (binary.facts.instructions.total === 0) {
18626
+ items.push(evidence({
18627
+ kind: "no_data",
18628
+ severity: "info",
18629
+ subject,
18630
+ window: OFFLINE_WINDOW,
18631
+ signals: { path: binary.path },
18632
+ explain: `${binary.path} has no instructions in .text, so its optimization level was not measured; a binary with no code carries no evidence either way`,
18633
+ drillDown: [],
18634
+ key: `${binary.path}:no-text`
18635
+ }));
18636
+ }
18637
+ if (binary.verdict.level === "unoptimized" || binary.verdict.level === "low") {
18638
+ items.push(evidence({
18639
+ kind: "optimization",
18640
+ severity: binary.verdict.level === "unoptimized" ? "warn" : "info",
18641
+ subject,
18642
+ window: OFFLINE_WINDOW,
18643
+ signals: {
18644
+ path: binary.path,
18645
+ level: binary.verdict.level,
18646
+ basis: binary.verdict.basis,
18647
+ signals: [...binary.verdict.signals],
18648
+ vectorDensity: binary.facts.instructions.total === 0 ? 0 : Math.round(binary.facts.instructions.vector / binary.facts.instructions.total * 1e4) / 1e4
18649
+ },
18650
+ explain: `${binary.path} reads as ${binary.verdict.level} optimization` + (binary.verdict.basis === "recorded" ? ` from its recorded flag ${binary.facts.recordedFlags.join(" ")}` : ` from its instruction mix (${binary.verdict.signals.join(", ")})`),
18651
+ drillDown: [],
18652
+ key: `${binary.path}:level`
18653
+ }));
18654
+ }
18655
+ }
18656
+ return items.sort((a, b) => byString6(a.kind, b.kind) || byString6(a.id, b.id));
18657
+ }
18658
+ function analyzeBinaries(inputs, packageName) {
18659
+ const binaries = [...inputs].sort((a, b) => byString6(a.path, b.path)).map((input) => {
18660
+ const facts = inspectBinary(input);
18661
+ return { path: facts.path, facts, verdict: classifyOptimization(facts) };
18662
+ });
18663
+ return {
18664
+ schemaVersion: 1,
18665
+ package: packageName,
18666
+ binaries,
18667
+ totals: {
18668
+ binaries: binaries.length,
18669
+ lto: binaries.filter((binary) => binary.facts.lto === "present").length,
18670
+ debug: binaries.filter((binary) => binary.facts.debug).length,
18671
+ stripped: binaries.filter((binary) => binary.facts.stripped).length
18672
+ },
18673
+ metrics: buildMetrics(binaries),
18674
+ evidence: buildEvidence(packageName, binaries)
18675
+ };
18676
+ }
18677
+ function optimizationSection(analysis) {
18678
+ return {
18679
+ analyzerId: "optimization",
18680
+ status: "measured",
18681
+ result: { metrics: analysis.metrics, evidence: analysis.evidence }
18682
+ };
18683
+ }
18684
+
17766
18685
  // src/hap/inventory.ts
17767
18686
  var CATEGORY_EXTENSIONS = {
17768
18687
  images: ["png", "jpg", "jpeg", "gif", "bmp", "webp", "svg"],
@@ -17817,7 +18736,7 @@ function buildInventory(archive) {
17817
18736
  // src/hap/rules.ts
17818
18737
  var EXCLUDE_PATTERNS = ["resources/base/.*"];
17819
18738
  var KINDS2 = ["filename", "path", "extension", "magic", "content", "combined"];
17820
- function fail2(ruleId, message3) {
18739
+ function fail3(ruleId, message3) {
17821
18740
  throw new OhosPerfError(`rule ${JSON.stringify(ruleId)}: ${message3}`, { code: "HAP_BAD_RULE" });
17822
18741
  }
17823
18742
  function basename3(path) {
@@ -17827,7 +18746,7 @@ function compile(ruleId, source) {
17827
18746
  try {
17828
18747
  return new RegExp(source);
17829
18748
  } catch (err) {
17830
- return fail2(ruleId, `invalid pattern ${JSON.stringify(source)}: ${err.message}`);
18749
+ return fail3(ruleId, `invalid pattern ${JSON.stringify(source)}: ${err.message}`);
17831
18750
  }
17832
18751
  }
17833
18752
  var EntryReader = class {
@@ -17983,15 +18902,15 @@ function matchHapRules(rules, archive, inventory) {
17983
18902
  function validateRules(rules) {
17984
18903
  const seen = /* @__PURE__ */ new Set();
17985
18904
  for (const rule of rules) {
17986
- if (seen.has(rule.id)) fail2(rule.id, "duplicate rule id");
18905
+ if (seen.has(rule.id)) fail3(rule.id, "duplicate rule id");
17987
18906
  seen.add(rule.id);
17988
- if (rule.fileRules.length === 0) fail2(rule.id, "has no file rules");
18907
+ if (rule.fileRules.length === 0) fail3(rule.id, "has no file rules");
17989
18908
  if (rule.requireMetadata === true && (rule.metadataPatterns ?? []).length === 0) {
17990
- fail2(rule.id, "requires metadata but names no metadata pattern");
18909
+ fail3(rule.id, "requires metadata but names no metadata pattern");
17991
18910
  }
17992
18911
  for (const pattern of rule.metadataPatterns ?? []) {
17993
18912
  if (pattern.source !== "content" && pattern.source !== "path" && pattern.source !== "filename") {
17994
- fail2(rule.id, `metadata field ${JSON.stringify(pattern.field)} has unknown source ${JSON.stringify(pattern.source)}`);
18913
+ fail3(rule.id, `metadata field ${JSON.stringify(pattern.field)} has unknown source ${JSON.stringify(pattern.source)}`);
17995
18914
  }
17996
18915
  compile(rule.id, pattern.pattern);
17997
18916
  }
@@ -18000,28 +18919,28 @@ function validateRules(rules) {
18000
18919
  }
18001
18920
  function validateFileRules(ruleId, rules) {
18002
18921
  for (const rule of rules) {
18003
- if (!KINDS2.includes(rule.kind)) fail2(ruleId, `unknown rule kind ${JSON.stringify(rule.kind)}`);
18922
+ if (!KINDS2.includes(rule.kind)) fail3(ruleId, `unknown rule kind ${JSON.stringify(rule.kind)}`);
18004
18923
  switch (rule.kind) {
18005
18924
  case "filename":
18006
18925
  case "path":
18007
18926
  case "content":
18008
- if ((rule.patterns ?? []).length === 0) fail2(ruleId, `a ${rule.kind} rule names no pattern`);
18927
+ if ((rule.patterns ?? []).length === 0) fail3(ruleId, `a ${rule.kind} rule names no pattern`);
18009
18928
  for (const item of rule.patterns ?? []) compile(ruleId, typeof item === "string" ? item : item.pattern);
18010
18929
  break;
18011
18930
  case "extension":
18012
- if ((rule.extensions ?? []).length === 0) fail2(ruleId, "an extension rule names no extension");
18931
+ if ((rule.extensions ?? []).length === 0) fail3(ruleId, "an extension rule names no extension");
18013
18932
  break;
18014
18933
  case "magic":
18015
- if ((rule.bytes ?? []).length === 0) fail2(ruleId, "a magic rule names no bytes");
18934
+ if ((rule.bytes ?? []).length === 0) fail3(ruleId, "a magic rule names no bytes");
18016
18935
  for (const byte of rule.bytes ?? []) {
18017
- if (!Number.isInteger(byte) || byte < 0 || byte > 255) fail2(ruleId, `magic byte ${byte} is not a byte`);
18936
+ if (!Number.isInteger(byte) || byte < 0 || byte > 255) fail3(ruleId, `magic byte ${byte} is not a byte`);
18018
18937
  }
18019
18938
  break;
18020
18939
  case "combined":
18021
18940
  if (rule.operator !== "and" && rule.operator !== "or" && rule.operator !== "not") {
18022
- fail2(ruleId, `combined rule has operator ${JSON.stringify(rule.operator)}`);
18941
+ fail3(ruleId, `combined rule has operator ${JSON.stringify(rule.operator)}`);
18023
18942
  }
18024
- if ((rule.rules ?? []).length === 0) fail2(ruleId, "a combined rule names no sub-rules");
18943
+ if ((rule.rules ?? []).length === 0) fail3(ruleId, "a combined rule names no sub-rules");
18025
18944
  validateFileRules(ruleId, rule.rules ?? []);
18026
18945
  break;
18027
18946
  }
@@ -18404,10 +19323,10 @@ var TECH_RULES = [
18404
19323
 
18405
19324
  // src/hap/analyze.ts
18406
19325
  import { createHash as createHash3 } from "node:crypto";
18407
- var OFFLINE_WINDOW = { startNs: 0, endNs: 0 };
19326
+ var OFFLINE_WINDOW2 = { startNs: 0, endNs: 0 };
18408
19327
  var LARGEST_COUNT = 10;
18409
19328
  var EXPLAIN_PATHS = 5;
18410
- function byString6(a, b) {
19329
+ function byString7(a, b) {
18411
19330
  return a < b ? -1 : a > b ? 1 : 0;
18412
19331
  }
18413
19332
  function sha256(bytes) {
@@ -18459,7 +19378,7 @@ function findDuplicates(archive, inventory) {
18459
19378
  const groups = [];
18460
19379
  for (const [hash, files] of byHash) {
18461
19380
  if (files.length < 2) continue;
18462
- const sorted = [...files].sort((a, b) => byString6(a.path, b.path));
19381
+ const sorted = [...files].sort((a, b) => byString7(a.path, b.path));
18463
19382
  const size = sorted[0].size;
18464
19383
  groups.push({
18465
19384
  sha256: hash,
@@ -18469,7 +19388,7 @@ function findDuplicates(archive, inventory) {
18469
19388
  paths: sorted.map((file) => file.path)
18470
19389
  });
18471
19390
  }
18472
- return groups.sort((a, b) => byString6(a.sha256, b.sha256));
19391
+ return groups.sort((a, b) => byString7(a.sha256, b.sha256));
18473
19392
  }
18474
19393
  function findOversized(inventory) {
18475
19394
  return inventory.filter((file) => file.size > CATEGORY_MAX_BYTES[file.category]).map((file) => ({
@@ -18477,7 +19396,7 @@ function findOversized(inventory) {
18477
19396
  category: file.category,
18478
19397
  size: file.size,
18479
19398
  threshold: CATEGORY_MAX_BYTES[file.category]
18480
- })).sort((a, b) => b.size - a.size || byString6(a.path, b.path));
19399
+ })).sort((a, b) => b.size - a.size || byString7(a.path, b.path));
18481
19400
  }
18482
19401
  function categoryTotals(inventory) {
18483
19402
  const totals = /* @__PURE__ */ new Map();
@@ -18490,72 +19409,72 @@ function categoryTotals(inventory) {
18490
19409
  compressedSize: (current?.compressedSize ?? 0) + file.compressedSize
18491
19410
  });
18492
19411
  }
18493
- return [...totals.values()].sort((a, b) => byString6(a.name, b.name));
19412
+ return [...totals.values()].sort((a, b) => byString7(a.name, b.name));
18494
19413
  }
18495
19414
  function listPaths(paths) {
18496
19415
  const shown = paths.slice(0, EXPLAIN_PATHS).join(", ");
18497
19416
  return paths.length > EXPLAIN_PATHS ? `${shown}, and ${paths.length - EXPLAIN_PATHS} more` : shown;
18498
19417
  }
18499
- function offlineProvenance(rows) {
19418
+ function offlineProvenance2(rows) {
18500
19419
  return { collector: "offline", table: "hap", rows, device: "offline" };
18501
19420
  }
18502
- function buildMetrics(analysis) {
19421
+ function buildMetrics2(analysis) {
18503
19422
  const metrics = [
18504
19423
  metric({
18505
19424
  id: "hap.files.count",
18506
19425
  value: analysis.totals.files,
18507
19426
  unit: "count",
18508
- provenance: offlineProvenance(analysis.totals.files),
19427
+ provenance: offlineProvenance2(analysis.totals.files),
18509
19428
  fidelity: "exact",
18510
- window: OFFLINE_WINDOW
19429
+ window: OFFLINE_WINDOW2
18511
19430
  }),
18512
19431
  metric({
18513
19432
  id: "hap.size.bytes",
18514
19433
  value: analysis.totals.size,
18515
19434
  unit: "bytes",
18516
- provenance: offlineProvenance(analysis.totals.files),
19435
+ provenance: offlineProvenance2(analysis.totals.files),
18517
19436
  fidelity: "exact",
18518
- window: OFFLINE_WINDOW
19437
+ window: OFFLINE_WINDOW2
18519
19438
  }),
18520
19439
  metric({
18521
19440
  id: "hap.size.compressed.bytes",
18522
19441
  value: analysis.totals.compressedSize,
18523
19442
  unit: "bytes",
18524
- provenance: offlineProvenance(analysis.totals.files),
19443
+ provenance: offlineProvenance2(analysis.totals.files),
18525
19444
  fidelity: "exact",
18526
- window: OFFLINE_WINDOW
19445
+ window: OFFLINE_WINDOW2
18527
19446
  }),
18528
19447
  metric({
18529
19448
  id: "hap.techstack.count",
18530
19449
  value: analysis.technologies.length,
18531
19450
  unit: "count",
18532
- provenance: offlineProvenance(analysis.technologies.length),
19451
+ provenance: offlineProvenance2(analysis.technologies.length),
18533
19452
  fidelity: "exact",
18534
- window: OFFLINE_WINDOW
19453
+ window: OFFLINE_WINDOW2
18535
19454
  }),
18536
19455
  metric({
18537
19456
  id: "hap.duplicates.groups",
18538
19457
  value: analysis.duplicates.length,
18539
19458
  unit: "count",
18540
- provenance: offlineProvenance(analysis.duplicates.length),
19459
+ provenance: offlineProvenance2(analysis.duplicates.length),
18541
19460
  fidelity: "exact",
18542
- window: OFFLINE_WINDOW
19461
+ window: OFFLINE_WINDOW2
18543
19462
  }),
18544
19463
  metric({
18545
19464
  id: "hap.duplicates.wasted.bytes",
18546
19465
  value: analysis.duplicates.reduce((sum, group) => sum + group.wastedBytes, 0),
18547
19466
  unit: "bytes",
18548
- provenance: offlineProvenance(analysis.duplicates.length),
19467
+ provenance: offlineProvenance2(analysis.duplicates.length),
18549
19468
  fidelity: "exact",
18550
- window: OFFLINE_WINDOW
19469
+ window: OFFLINE_WINDOW2
18551
19470
  }),
18552
19471
  metric({
18553
19472
  id: "hap.oversized.count",
18554
19473
  value: analysis.oversized.length,
18555
19474
  unit: "count",
18556
- provenance: offlineProvenance(analysis.oversized.length),
19475
+ provenance: offlineProvenance2(analysis.oversized.length),
18557
19476
  fidelity: "exact",
18558
- window: OFFLINE_WINDOW
19477
+ window: OFFLINE_WINDOW2
18559
19478
  })
18560
19479
  ];
18561
19480
  const byType = /* @__PURE__ */ new Map();
@@ -18567,9 +19486,9 @@ function buildMetrics(analysis) {
18567
19486
  id: `hap.techstack.${type}.files`,
18568
19487
  value: files,
18569
19488
  unit: "count",
18570
- provenance: offlineProvenance(files),
19489
+ provenance: offlineProvenance2(files),
18571
19490
  fidelity: "exact",
18572
- window: OFFLINE_WINDOW
19491
+ window: OFFLINE_WINDOW2
18573
19492
  }));
18574
19493
  }
18575
19494
  for (const category of analysis.categories) {
@@ -18577,14 +19496,14 @@ function buildMetrics(analysis) {
18577
19496
  id: `hap.category.${category.name}.bytes`,
18578
19497
  value: category.size,
18579
19498
  unit: "bytes",
18580
- provenance: offlineProvenance(category.files),
19499
+ provenance: offlineProvenance2(category.files),
18581
19500
  fidelity: "exact",
18582
- window: OFFLINE_WINDOW
19501
+ window: OFFLINE_WINDOW2
18583
19502
  }));
18584
19503
  }
18585
- return metrics.sort((a, b) => byString6(a.id, b.id));
19504
+ return metrics.sort((a, b) => byString7(a.id, b.id));
18586
19505
  }
18587
- function buildEvidence(analysis) {
19506
+ function buildEvidence2(analysis) {
18588
19507
  const subject = { process: analysis.package.bundleName === "" ? analysis.package.name : analysis.package.bundleName };
18589
19508
  const items = [];
18590
19509
  for (const match of analysis.technologies) {
@@ -18592,7 +19511,7 @@ function buildEvidence(analysis) {
18592
19511
  kind: "tech_stack",
18593
19512
  severity: "info",
18594
19513
  subject,
18595
- window: OFFLINE_WINDOW,
19514
+ window: OFFLINE_WINDOW2,
18596
19515
  signals: {
18597
19516
  rule: match.ruleId,
18598
19517
  type: match.type,
@@ -18610,7 +19529,7 @@ function buildEvidence(analysis) {
18610
19529
  kind: "duplicate_asset",
18611
19530
  severity: "warn",
18612
19531
  subject,
18613
- window: OFFLINE_WINDOW,
19532
+ window: OFFLINE_WINDOW2,
18614
19533
  signals: {
18615
19534
  hash: group.sha256,
18616
19535
  size: group.size,
@@ -18627,14 +19546,14 @@ function buildEvidence(analysis) {
18627
19546
  kind: "oversized_asset",
18628
19547
  severity: "info",
18629
19548
  subject,
18630
- window: OFFLINE_WINDOW,
19549
+ window: OFFLINE_WINDOW2,
18631
19550
  signals: { category: file.category, size: file.size, threshold: file.threshold },
18632
19551
  explain: `${file.path} is ${file.size} bytes, above the ${file.category} limit of ${file.threshold} bytes`,
18633
19552
  drillDown: [],
18634
19553
  key: file.path
18635
19554
  }));
18636
19555
  }
18637
- return items.sort((a, b) => byString6(a.kind, b.kind) || a.window.startNs - b.window.startNs || byString6(a.id, b.id));
19556
+ return items.sort((a, b) => byString7(a.kind, b.kind) || a.window.startNs - b.window.startNs || byString7(a.id, b.id));
18638
19557
  }
18639
19558
  function analyzeHap(bytes, packageName) {
18640
19559
  const archive = openZip(bytes);
@@ -18650,7 +19569,7 @@ function analyzeHap(bytes, packageName) {
18650
19569
  size: inventory.reduce((sum, file) => sum + file.size, 0),
18651
19570
  compressedSize: inventory.reduce((sum, file) => sum + file.compressedSize, 0)
18652
19571
  };
18653
- const largest = [...inventory].sort((a, b) => b.size - a.size || byString6(a.path, b.path)).slice(0, LARGEST_COUNT).map((file) => ({ path: file.path, size: file.size }));
19572
+ const largest = [...inventory].sort((a, b) => b.size - a.size || byString7(a.path, b.path)).slice(0, LARGEST_COUNT).map((file) => ({ path: file.path, size: file.size }));
18654
19573
  const analysis = {
18655
19574
  schemaVersion: 1,
18656
19575
  package: { name: packageName, ...packageBlock },
@@ -18664,8 +19583,8 @@ function analyzeHap(bytes, packageName) {
18664
19583
  return {
18665
19584
  ...analysis,
18666
19585
  files: inventory,
18667
- metrics: buildMetrics(analysis),
18668
- evidence: buildEvidence(analysis)
19586
+ metrics: buildMetrics2(analysis),
19587
+ evidence: buildEvidence2(analysis)
18669
19588
  };
18670
19589
  }
18671
19590
  function hapSection(analysis) {
@@ -18871,6 +19790,7 @@ export {
18871
19790
  DEVICE_UI_PATH,
18872
19791
  Device,
18873
19792
  DeviceNotFoundError,
19793
+ EM_AARCH64,
18874
19794
  EXCLUDE_PATTERNS,
18875
19795
  EmptyFrameAnalyzer,
18876
19796
  EmulatorClient,
@@ -18903,6 +19823,7 @@ export {
18903
19823
  HiprofilerCollector,
18904
19824
  HitraceCollector,
18905
19825
  IGNORED_ATTRIBUTES,
19826
+ IRREVERSIBLE_PATTERNS,
18906
19827
  IngestError,
18907
19828
  InstantQuery,
18908
19829
  JsheapCollector,
@@ -18943,8 +19864,10 @@ export {
18943
19864
  UiAnalyzer,
18944
19865
  UitestCollector,
18945
19866
  VsyncAnalyzer,
19867
+ agentPrompt,
18946
19868
  aggregateUnreleased,
18947
19869
  analyseAnimations,
19870
+ analyzeBinaries,
18948
19871
  analyzeHap,
18949
19872
  analyzeThreadWakeup,
18950
19873
  animationSeverity,
@@ -18956,7 +19879,9 @@ export {
18956
19879
  buildReport,
18957
19880
  buildTrend,
18958
19881
  categorize,
19882
+ classifyInstruction,
18959
19883
  classifyNativePath,
19884
+ classifyOptimization,
18960
19885
  compareImages,
18961
19886
  compareRegion,
18962
19887
  compareResults,
@@ -18972,20 +19897,24 @@ export {
18972
19897
  computeThreadAnalysis,
18973
19898
  computeVsyncAnomalies,
18974
19899
  connect,
19900
+ countInstructions,
18975
19901
  createSceneLayout,
18976
19902
  cropRegion,
18977
19903
  decodePng,
18978
19904
  defaultAnalyzers,
19905
+ describeDecision,
18979
19906
  deviceExplorationHost,
18980
19907
  dhash,
18981
19908
  diffTrees,
18982
19909
  discoverCases,
18983
19910
  encodePng,
18984
19911
  escapeHtml,
19912
+ evaluateExpectation,
18985
19913
  evidence,
18986
19914
  executeAction,
18987
19915
  explorationDevice,
18988
19916
  explore,
19917
+ extractBinaries,
18989
19918
  filterEmptyFrames,
18990
19919
  flattenUiTree,
18991
19920
  ftracePlugin,
@@ -18993,7 +19922,10 @@ export {
18993
19922
  hapSection,
18994
19923
  hashTree,
18995
19924
  hiperfRecordCommand,
19925
+ httpAgentModel,
18996
19926
  ingestScene,
19927
+ inspectBinary,
19928
+ irreversibleReason,
18997
19929
  isUnresolvedSymbol,
18998
19930
  isZip,
18999
19931
  loadCases,
@@ -19009,10 +19941,12 @@ export {
19009
19941
  nodeIdentity,
19010
19942
  openDb,
19011
19943
  openZip,
19944
+ optimizationSection,
19012
19945
  pairNativeMemory,
19013
19946
  paritySummary,
19014
19947
  parseBounds,
19015
19948
  parseCoverageReport,
19949
+ parseDecision,
19016
19950
  parseFpsCounts,
19017
19951
  parseHilogLine,
19018
19952
  parseHilogText,
@@ -19025,6 +19959,8 @@ export {
19025
19959
  parseSmapsRollup,
19026
19960
  planNextAction,
19027
19961
  queryDefinitions,
19962
+ readAgentConfig,
19963
+ readElf,
19028
19964
  readHidumperCapture,
19029
19965
  readHilogText,
19030
19966
  readJsheapSnapshot,
@@ -19041,14 +19977,17 @@ export {
19041
19977
  renderReportXlsx,
19042
19978
  renderScenesComparison,
19043
19979
  renderSummaryJson,
19980
+ renderTree,
19044
19981
  renderTrendHtml,
19045
19982
  renderTrendJson,
19046
19983
  renderUiDiffHtml,
19984
+ replayAgent,
19047
19985
  resolveAppIdentity,
19048
19986
  resolveAppIpids,
19049
19987
  resolveQueryLimit,
19050
19988
  resolveSelector,
19051
19989
  round2HalfEven,
19990
+ runAgent,
19052
19991
  runAnalyzerSections,
19053
19992
  runAnalyzers,
19054
19993
  runDrillDown,