@ohos-perf/core 0.20.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.
package/dist/index.d.ts CHANGED
@@ -4850,6 +4850,21 @@ interface RunOptions {
4850
4850
  /** Injected clock, for tests. */
4851
4851
  readonly now?: () => number;
4852
4852
  }
4853
+ /**
4854
+ * Evaluate a step's `expect` block against one dump.
4855
+ *
4856
+ * Every clause is evaluated even after one fails: a reader looking at a
4857
+ * failed step wants to know that the screen also lost the toolbar, not just
4858
+ * that it lost the first thing checked. `foreground` comes last so the
4859
+ * clauses an author wrote in order appear in that order, and a screenshot
4860
+ * showing the launcher explains the `present` misses above it.
4861
+ *
4862
+ * `foreground` means the app owns at least one node. A system dialog drawn
4863
+ * over the app is still the app's screen — the title bar and the window frame
4864
+ * belong to it — so requiring the app to own *every* node would fail on the
4865
+ * one case an author most wants to assert.
4866
+ */
4867
+ declare function evaluateExpectation(expect: StepExpectation, nodes: readonly UiNode[], app: string): ExpectationOutcome[];
4853
4868
  /**
4854
4869
  * Run a scenario: every selected (round, step) pair, one scene each.
4855
4870
  *
@@ -4889,6 +4904,255 @@ declare class ScenarioRunner {
4889
4904
  */
4890
4905
  declare function writeRunFiles(outDir: string, result: RunResult): void;
4891
4906
 
4907
+ /**
4908
+ * The model-driven UI agent (HapRay parity row 5).
4909
+ *
4910
+ * HapRay's `gui-agent` wraps the external `phone_agent` package: the model is
4911
+ * shown a screenshot, answers with one action, and says `finished` when it
4912
+ * believes the task is done. Three things make that unusable as a measurement
4913
+ * tool, and each is fixed here rather than reproduced.
4914
+ *
4915
+ * 1. **`finished` is taken on faith.** A model that taps a button which does
4916
+ * nothing and then declares success is recorded as a success. Here a
4917
+ * completion claim carries an expectation, the expectation is evaluated
4918
+ * against a fresh dump, and a claim the screen contradicts is recorded as
4919
+ * `unverified` — a failure with the clause that failed named.
4920
+ * 2. **The safety rule lives only in the prompt.** HapRay tells the model to
4921
+ * avoid payment, ordering and transfers; a model that ignores the sentence
4922
+ * acts anyway. Here the guard reads the node the tap lands on and refuses
4923
+ * the gesture outright. An irreversible action stops the run: a model that
4924
+ * reached for a payment button has lost the thread of the task, and asking
4925
+ * it again spends steps on the one thing that must not happen.
4926
+ * 3. **The log cannot be replayed.** HapRay records `{action, thinking,
4927
+ * message}` as prose, so two runs of the same task are two unrelated logs.
4928
+ * Here every step records the gesture and the screen hash either side of
4929
+ * it, so {@link replayAgent} can walk the same path on another build
4930
+ * without a model, and stop at the first screen that is not the recorded
4931
+ * one.
4932
+ *
4933
+ * The model is injected, never bundled: {@link AgentModel} is one method, so a
4934
+ * caller supplies whatever client it has, and the loop is tested without a
4935
+ * network or a device.
4936
+ */
4937
+
4938
+ /** The device surface the loop needs. `Device` satisfies it structurally. */
4939
+ interface AgentDevice {
4940
+ readonly id: string;
4941
+ /** A fresh flattened dump, as `Device.uiTree` returns. */
4942
+ uiTree(): Promise<readonly UiNode[]>;
4943
+ gesture(g: Gesture): Promise<GestureResult>;
4944
+ }
4945
+ /** What the model answers: one gesture, or a claim that the task is done. */
4946
+ type AgentDecision = {
4947
+ readonly action: Gesture;
4948
+ readonly reason: string;
4949
+ } | {
4950
+ readonly done: true;
4951
+ readonly reason: string;
4952
+ readonly expect?: StepExpectation;
4953
+ };
4954
+ /** One earlier step, as the model sees it when deciding the next. */
4955
+ interface AgentHistoryEntry {
4956
+ readonly step: number;
4957
+ readonly status: AgentStepStatus;
4958
+ readonly reason: string;
4959
+ /** What the step did, as `describeDecision` renders it. */
4960
+ readonly did?: string;
4961
+ readonly detail?: string;
4962
+ }
4963
+ /** Everything a model is shown. A client renders this into its own prompt. */
4964
+ interface AgentTurn {
4965
+ readonly task: string;
4966
+ readonly app: string;
4967
+ /** Zero-based index of the step being decided. */
4968
+ readonly step: number;
4969
+ readonly maxSteps: number;
4970
+ /** The current screen, one line per node. */
4971
+ readonly screen: string;
4972
+ /** The steps already taken, oldest first. */
4973
+ readonly history: readonly AgentHistoryEntry[];
4974
+ }
4975
+ /** The injected client. One method, so any endpoint fits. */
4976
+ interface AgentModel {
4977
+ decide(request: AgentTurn): Promise<AgentDecision>;
4978
+ }
4979
+ /**
4980
+ * How a step ended.
4981
+ *
4982
+ * `acted` is a gesture the device accepted, `failed` one it rejected,
4983
+ * `refused` one the guard stopped before it reached the device, `verified` a
4984
+ * completion claim the screen confirmed, and `unverified` one it did not.
4985
+ */
4986
+ type AgentStepStatus = 'acted' | 'failed' | 'refused' | 'verified' | 'unverified';
4987
+ interface AgentStep {
4988
+ readonly index: number;
4989
+ readonly status: AgentStepStatus;
4990
+ readonly reason: string;
4991
+ /** The gesture performed or attempted; absent for a refusal or a claim. */
4992
+ readonly action?: Gesture;
4993
+ /** Why the step ended that way, when the status alone does not say. */
4994
+ readonly detail?: string;
4995
+ /** The screen hash before the step. */
4996
+ readonly before: string;
4997
+ /** The screen hash after it; equal to `before` when nothing moved. */
4998
+ readonly after: string;
4999
+ readonly navigated: boolean;
5000
+ }
5001
+ type AgentStatus = 'completed' | 'unverified' | 'refused' | 'exhausted';
5002
+ /** A run, complete enough to replay and to compare against another run. */
5003
+ interface AgentTranscript {
5004
+ readonly version: 1;
5005
+ readonly task: string;
5006
+ readonly app: string;
5007
+ readonly steps: readonly AgentStep[];
5008
+ readonly status: AgentStatus;
5009
+ /** Distinct screen hashes reached, including the one it started on. */
5010
+ readonly statesReached: number;
5011
+ }
5012
+ type AgentResult = AgentTranscript;
5013
+ interface AgentOptions {
5014
+ readonly task: string;
5015
+ readonly app: string;
5016
+ /** Hard cap on model turns. HapRay's default is 50. */
5017
+ readonly maxSteps: number;
5018
+ /** Let the guard's refusals through. Off by default. */
5019
+ readonly allowIrreversible?: boolean;
5020
+ }
5021
+ /** One irreversible action the guard recognises. */
5022
+ interface IrreversiblePattern {
5023
+ readonly pattern: RegExp;
5024
+ /** Why the action is refused; the text a refusal records. */
5025
+ readonly why: string;
5026
+ /** A label that matches `pattern`, so a test can prove the row is live. */
5027
+ readonly sample: string;
5028
+ }
5029
+ /**
5030
+ * The actions the guard refuses.
5031
+ *
5032
+ * Each pattern names an act, not a topic: `Payment settings` is a screen a
5033
+ * walk may legitimately open, while `立即支付` is money leaving an account.
5034
+ * Matching on a bare substring would block the settings page a task needs.
5035
+ */
5036
+ declare const IRREVERSIBLE_PATTERNS: readonly IrreversiblePattern[];
5037
+ /** Why tapping this node is irreversible, or `undefined` when it is safe. */
5038
+ declare function irreversibleReason(node: UiNode): string | undefined;
5039
+ /** One line naming what a decision does, for a transcript or a history entry. */
5040
+ declare function describeDecision(decision: AgentDecision): string;
5041
+ /**
5042
+ * Render a dump for a model prompt: one line per node, in tree order.
5043
+ *
5044
+ * The fields are the ones a decision is made from — what it says, what it is,
5045
+ * what it is called, where it is, and whether it can be tapped. A node that
5046
+ * cannot be tapped is marked so the model does not spend a step on it, which
5047
+ * is the single most common wasted turn in HapRay's runs.
5048
+ */
5049
+ declare function renderTree(tree: readonly UiNode[]): string;
5050
+ /**
5051
+ * The prompt for one decision.
5052
+ *
5053
+ * A plain string, not a message list: whatever client a caller brings turns
5054
+ * this into its own request shape. It states the answer format literally
5055
+ * because a model that invents a gesture name fails far from the answer that
5056
+ * caused it, and it shows the history because a model that cannot see its own
5057
+ * steps repeats them.
5058
+ */
5059
+ declare function agentPrompt(request: AgentTurn): string;
5060
+ /**
5061
+ * Read a model's answer.
5062
+ *
5063
+ * The answer is data from outside this package, so every field is checked
5064
+ * here: an unknown gesture name, a malformed expectation, or an object that is
5065
+ * both an action and a completion is a refusal naming what was wrong. A
5066
+ * refusal now beats a confusing failure inside the gesture driver or the
5067
+ * expectation evaluator, where the cause is no longer visible.
5068
+ */
5069
+ declare function parseDecision(text: string): AgentDecision;
5070
+ /**
5071
+ * Run the loop until the model's claim is verified, the guard refuses, or the
5072
+ * step budget runs out.
5073
+ *
5074
+ * The order of checks matters: an irreversible target is refused *before* the
5075
+ * gesture reaches the device, and a completion claim is evaluated against the
5076
+ * screen the model was shown rather than a fresh one — the model has to be
5077
+ * judged on what it saw.
5078
+ */
5079
+ declare function runAgent(device: AgentDevice, model: AgentModel, options: AgentOptions): Promise<AgentResult>;
5080
+ /** What a replay did. */
5081
+ interface ReplayResult {
5082
+ /** Steps whose gesture reached the device. */
5083
+ readonly performed: number;
5084
+ /** Steps skipped because they never touched the device. */
5085
+ readonly skipped: number;
5086
+ /** The step whose recorded screen did not match; absent when it matched. */
5087
+ readonly divergedAt?: number;
5088
+ }
5089
+ /**
5090
+ * Walk a recorded transcript again, without a model.
5091
+ *
5092
+ * The recorded gesture is a coordinate, so it only means what it meant on the
5093
+ * screen it was recorded against. Each step re-dumps, compares the hash to the
5094
+ * recorded `before`, and stops at the first mismatch: continuing would send
5095
+ * taps into whatever the new build put in those places.
5096
+ *
5097
+ * A step with no gesture (a refusal, or a completion claim) is skipped: it
5098
+ * never touched the device, so there is nothing to replay.
5099
+ */
5100
+ declare function replayAgent(device: AgentDevice, transcript: AgentTranscript): Promise<ReplayResult>;
5101
+
5102
+ /**
5103
+ * The HTTP model client for the GUI agent (HapRay parity row 5).
5104
+ *
5105
+ * HapRay's `gui-agent` imports the external `phone_agent` package, whose client
5106
+ * reads `GLM_BASE_URL` / `GLM_API_KEY` / `GLM_MODEL` and posts to an
5107
+ * OpenAI-compatible `/chat/completions` endpoint. This is that protocol,
5108
+ * written here so the package does not depend on `phone_agent`, and with
5109
+ * `fetch` injected so a test never opens a socket and a caller can point it at
5110
+ * any endpoint that speaks the same shape.
5111
+ *
5112
+ * Two things differ from HapRay's client:
5113
+ *
5114
+ * - **An unparseable answer is refused here.** HapRay passes the model's prose
5115
+ * through to the loop, so a formatting mistake surfaces as an agent failure.
5116
+ * Here {@link parseDecision} runs inside the client, so the error names the
5117
+ * answer that caused it.
5118
+ * - **Nothing is defaulted silently.** No base URL is guessed and no key is
5119
+ * invented: a host with no configuration gets a refusal naming the variables
5120
+ * to set, not a request to a host the user never named.
5121
+ */
5122
+
5123
+ /** The slice of `fetch` this client needs. Injected, never imported. */
5124
+ type AgentFetch = (url: string, init: RequestInit) => Promise<Response>;
5125
+ interface HttpAgentModelOptions {
5126
+ /** The endpoint root, without `/chat/completions`. */
5127
+ readonly baseUrl: string;
5128
+ readonly apiKey: string;
5129
+ readonly model: string;
5130
+ readonly fetch: AgentFetch;
5131
+ /** Request timeout in ms. Defaults to 60 s. */
5132
+ readonly timeoutMs?: number;
5133
+ }
5134
+ interface AgentConfig {
5135
+ readonly baseUrl: string;
5136
+ readonly apiKey: string;
5137
+ readonly model: string;
5138
+ }
5139
+ /**
5140
+ * Read the client configuration from the environment.
5141
+ *
5142
+ * `undefined` when no endpoint is configured: a caller then refuses with a
5143
+ * message naming the variables, which is better than a request to a guessed
5144
+ * host. A base URL without a key is also `undefined` — half a configuration is
5145
+ * a mistake, not a default.
5146
+ */
5147
+ declare function readAgentConfig(env: Record<string, string | undefined>): AgentConfig | undefined;
5148
+ /**
5149
+ * A model client over an OpenAI-compatible endpoint.
5150
+ *
5151
+ * The options are validated once, at construction, so a misconfiguration fails
5152
+ * before a device is touched rather than on the first decision.
5153
+ */
5154
+ declare function httpAgentModel(options: HttpAgentModelOptions): AgentModel;
5155
+
4892
5156
  /**
4893
5157
  * One `native_hook` row with camelCase field names.
4894
5158
  *
@@ -6655,4 +6919,4 @@ interface FlamegraphPageInput {
6655
6919
  */
6656
6920
  declare function renderFlamegraphHtml(input: FlamegraphPageInput): string;
6657
6921
 
6658
- export { ANIMATION_BANDS, type ActionContext, type ActionDevice, type ActionOutcome, type ActiveAlloc, type AnalyzeContext, type AnalyzeResult, type Analyzer, type AnalyzerRun, type AnalyzerSection, type AnimationAnalysis, type AnimationLabel, type AnimationSeverity, type AppIdentity, BUNDLE_RENDERED_FILES, type BaselineComparison, type BelowThresholdPattern, type BinaryFacts, type BinaryInput, type BinaryReport, type BinderAnalysis, BinderAnalyzer, type BinderEndpoint, type BinderEvent, type BinderInterfaceStat, type BinderProcessStat, BinderQuery, type BinderThreadStat, type BinderTransaction, type BundleRerenderInput, CATEGORY_EXTENSIONS, CATEGORY_MAX_BYTES, COLLECTOR_NAMES, type CallchainSample, type CallstackEvent, type CallstackEventWithArgs, CallstackQuery, type CapabilityId, type CapabilityInputs, CapabilityMatrix, type CapabilityState, type CaseLoad, type CategoryTotal, type CollectOptions, type CollectSession, type Collector, type CollectorName, type CompiledRule, type ComponentReuse, ComponentReuseAnalyzer, type ConnectOptions, type ContentPattern, CoverageAnalyzer, type CoverageCounts, type CoverageFile, type CoverageRatio, type CoverageReport, type CreateEmulatorRequest, DEFAULT_HILOG_RULES, DEFAULT_QUERY_LIMIT, DEVICE_PERF_PATH, DEVICE_SCREENSHOT_PATH, DEVICE_UI_PATH, type DeltaStatus, type DepGraph, type DepGraphEdge, type DepGraphFile, Device, type DeviceDeps, type DeviceIdentity, DeviceNotFoundError, type DiscoveredCase, type DrillDownHandle, type DuplicateGroup, EM_AARCH64, EXCLUDE_PATTERNS, type ElfFile, type ElfSection, type ElfSymbol, EmptyFrameAnalyzer, type EmptyFrameFilter, type EmulatorBackend, EmulatorClient, type EmulatorClientOptions, EmulatorCommandError, type EmulatorImage, EmulatorImageMissingError, type EmulatorInstance, EmulatorLifecycle, type EmulatorLifecycleOptions, EmulatorNotFoundError, type EmulatorStartResult, type EmulatorStopResult, type Env, type Evidence, type EvidenceKind, type ExpectPresent, type ExpectationOutcome, type ExplorationAction, type ExplorationClock, type ExplorationDevice, type ExplorationDeviceOptions, type ExplorationHost, type ExplorationOptions, type ExplorationOutcome, type ExplorationResult, type ExplorationState, type ExplorationStep, type ExplorationStrategy, type ExplorationTargetDevice, FLAMEGRAPH_FILES, FPS_COMMAND, FTRACE_CATEGORIES, FaultTreeAnalyzer, type FaultTreeSignals, type Fidelity, type FileCategory, type FileRule, FlamegraphAnalyzer, type FlamegraphPageInput, type FoldedStack, type FpsBucket, type FpsWindow, type Frame, FrameAnalyzer, type FrameFlag, FrameLoadAnalyzer, FrameLoadIndex, type FrameLoadIndexInput, type FrameLoadThread, FrameQuery, type FrameStats, type FrameType, type FtraceOptions, GEOMETRY_TOLERANCE_PX, GcAnalyzer, type GcSignals, type Gesture, GestureDriver, type GestureResult, HILOG_COMMAND, HIPROFILER_PLUGIN_NAMES, HITCH_COMMAND, HITRACE_DEFAULT_CATEGORIES, type HapAnalysis, type HapPackage, type HarEdge, Hdc, HdcNotFoundError, type HdcOptions, type HdcResult, type HdcSlice, type HdcTarget, type HidumperCapture, HidumperCollector, type HidumperSnapshot, HilogAnalyzer, HilogCollector, type HilogLevel, type HilogLine, type HilogMatch, type HilogParseOptions, type HilogRule, type HiperfCapture, type HiperfCollectOptions, HiperfCollector, type HiprofilerCollectOptions, type HiprofilerCollectRequest, HiprofilerCollector, type HiprofilerConfigOptions, type HiprofilerPlugin, type HiprofilerPluginName, HitraceCollector, IGNORED_ATTRIBUTES, type ImageComparison, IngestError, InstantQuery, type InstructionClass, type InstructionCounts, type InventoryFile, type JsheapCapture, JsheapCollector, MAX_QUERY_LIMIT, METRIC_DIRECTIONS, MIN_BUFFER_PAGES, MIN_HASH_PIXELS, MemMeasureQuery, MemoryAnalyzer, MemoryMeasureAnalyzer, type MemoryPluginOptions, type MetadataPattern, type Metric, type MetricDelta, type MetricDirection, type MetricUnit, type ModuleDecl, type NamedQueryDefinition, type NamedQueryInfo, type NamedQueryResult, type NativeCategory, type NativeEventKind, type NativeHookEvent, type NativeHookFrame, NativeHookQuery, type NativeHookStatistic, NativeMemoryAnalyzer, type NativeMemoryResult, type NativeNames, type NativeTimelineBucket, type NativehookOptions, OhosPerfError, type OptimizationAnalysis, type OptimizationBasis, type OptimizationLevel, type OptimizationPotential, type OptimizationVerdict, type OversizedFile, PARITY_ROWS, PLANE_A_PLUGINS, type ParityRow, type ParityStatus, type PerfCallchain, type PerfFileAttribution, type PerfFunction, type PerfLeafAttribution, PerfQuery, type PerfSampleRow, type PerfThread, type PixelOnlyChange, type ProbeResult, type ProbeRunner, type ProbeSnapshot, type ProcessInfo, type ProcessMeasure, type ProcessMeasureFilter, ProcessQuery, ProcfsCollector, type ProcfsSample, type ProcfsStatus, type Provenance, type QueryArgument, type QueryContext, type QueryHandle, REPORT_SCHEMA_VERSION, type Rect, type RedundancyLevel, type RedundancyType, RedundantFileAnalyzer, type RedundantFileEntry, type RedundantFileReport, type RedundantThreadPattern, type RedundantThreadsSummary, type RegionPixelChange, RenderAnalyzer, type ReportGenerator, type ReportInput, type ReportModel, type ReportScenario, type ReportSection, type ReportSummary, type ReportTotals, type RgbaImage, RsSkipAnalyzer, type RsSkipFrame, type RsSkipResult, type RsSkipTraceMethod, type RuleMatch, type RuleMatchKind, type RunOptions, type RunResult, type RunStepResult, type RunnerCollectOptions, type RunnerDevice, SECTION_TITLES, type Scenario, type ScenarioAction, ScenarioRunner, type ScenarioStep, Scene, type SceneLayout, type SceneMetadata, type SceneStep, type SceneStepRef, type ScenesComparison, SchedQuery, type SchedSlice, type ScreenshotCapture, ScreenshotCollector, type Selector, type SelectorRect, type SmapsRollup, StartupAnalyzer, StartupQuery, type StartupRecord, type StepCapture, type StepComparison, type StepExpectation, type StepStatus, Streamer, StreamerNotFoundError, type StreamerOptions, type SymbolStat, SymbolsAnalyzer, TECH_RULES, type TechRule, type ThreadAnalysis, type ThreadAnalysisSummary, ThreadAnalyzer, type ThreadInfo, ThreadQuery, type ThreadState, ThreadStateQuery, type ThreadWakeupResult, type ThreadWakeupThread, type TimeRange, type TimingCycle, type TraceCollectOptions, type Trend, type TrendOrder, type TrendPoint, type TrendRun, type TrendSeries, UI_DIFF_FILES, UiAnalyzer, type UiCompareOptions, type UiDiff, type UiDiffSide, type UiNode, type UiTreeDiff, type UiTreeDifference, UitestCollector, type UnmeasuredRegion, type UnreleasedRow, type VsyncAnalysis, VsyncAnalyzer, type VsyncPeriod, type VsyncPeriodKind, type VsyncSeverity, type WakeupEvent, type WindowHitches, type ZipArchive, type ZipEntry, aggregateUnreleased, analyseAnimations, analyzeBinaries, analyzeHap, analyzeThreadWakeup, animationSeverity, buildDepGraph, buildHiprofilerConfig, buildInventory, buildMatrix, buildNativeTimeline, buildReport, buildTrend, categorize, classifyInstruction, classifyNativePath, classifyOptimization, compareImages, compareRegion, compareResults, compareSceneDirs, compareScenes, compileRules, computeBinderAnalysis, computeComponentReuse, computeFaultTree, computeFpsWindows, computeGc, computeRsSkip, computeThreadAnalysis, computeVsyncAnomalies, connect, countInstructions, createSceneLayout, cropRegion, decodePng, defaultAnalyzers, deviceExplorationHost, dhash, diffTrees, discoverCases, encodePng, escapeHtml, evidence, executeAction, explorationDevice, explore, extractBinaries, filterEmptyFrames, flattenUiTree, ftracePlugin, gpuPlugin, hapSection, hashTree, hiperfRecordCommand, ingestScene, inspectBinary, isUnresolvedSymbol, isZip, loadCases, lookupQuery, markRegions, matchHapRules, matchRules, matchSelector, memoryPlugin, metric, nativeEventKind, nativehookPlugin, nodeIdentity, openDb, openZip, optimizationSection, pairNativeMemory, paritySummary, parseBounds, parseCoverageReport, parseFpsCounts, parseHilogLine, parseHilogText, parseHiperfSummary, parseHitches, parseProcfsStatus, parseRedundantFile, parseScenario, parseSelector, parseSmapsRollup, planNextAction, queryDefinitions, readElf, readHidumperCapture, readHilogText, readJsheapSnapshot, readProcfsSamples, readSceneMetadata, readUiTree, renderBundle, renderEvidenceCsv, renderFlamegraphHtml, renderFlamegraphSvg, renderMetricsCsv, renderReportHtml, renderReportJson, renderReportXlsx, renderScenesComparison, renderSummaryJson, renderTrendHtml, renderTrendJson, renderUiDiffHtml, resolveAppIdentity, resolveAppIpids, resolveQueryLimit, resolveSelector, round2HalfEven, runAnalyzerSections, runAnalyzers, runDrillDown, runNamedQuery, runProbe, sortSteps, summarizeReport, tableRowCounts, trendRunFromReport, unknownQueryError, validateRules, writeProcfsSamples, writeRunFiles, writeSceneMetadata, xpowerPlugin };
6922
+ export { ANIMATION_BANDS, type ActionContext, type ActionDevice, type ActionOutcome, type ActiveAlloc, type AgentConfig, type AgentDecision, type AgentDevice, type AgentFetch, type AgentHistoryEntry, type AgentModel, type AgentOptions, type AgentResult, type AgentStatus, type AgentStep, type AgentStepStatus, type AgentTranscript, type AgentTurn, type AnalyzeContext, type AnalyzeResult, type Analyzer, type AnalyzerRun, type AnalyzerSection, type AnimationAnalysis, type AnimationLabel, type AnimationSeverity, type AppIdentity, BUNDLE_RENDERED_FILES, type BaselineComparison, type BelowThresholdPattern, type BinaryFacts, type BinaryInput, type BinaryReport, type BinderAnalysis, BinderAnalyzer, type BinderEndpoint, type BinderEvent, type BinderInterfaceStat, type BinderProcessStat, BinderQuery, type BinderThreadStat, type BinderTransaction, type BundleRerenderInput, CATEGORY_EXTENSIONS, CATEGORY_MAX_BYTES, COLLECTOR_NAMES, type CallchainSample, type CallstackEvent, type CallstackEventWithArgs, CallstackQuery, type CapabilityId, type CapabilityInputs, CapabilityMatrix, type CapabilityState, type CaseLoad, type CategoryTotal, type CollectOptions, type CollectSession, type Collector, type CollectorName, type CompiledRule, type ComponentReuse, ComponentReuseAnalyzer, type ConnectOptions, type ContentPattern, CoverageAnalyzer, type CoverageCounts, type CoverageFile, type CoverageRatio, type CoverageReport, type CreateEmulatorRequest, DEFAULT_HILOG_RULES, DEFAULT_QUERY_LIMIT, DEVICE_PERF_PATH, DEVICE_SCREENSHOT_PATH, DEVICE_UI_PATH, type DeltaStatus, type DepGraph, type DepGraphEdge, type DepGraphFile, Device, type DeviceDeps, type DeviceIdentity, DeviceNotFoundError, type DiscoveredCase, type DrillDownHandle, type DuplicateGroup, EM_AARCH64, EXCLUDE_PATTERNS, type ElfFile, type ElfSection, type ElfSymbol, EmptyFrameAnalyzer, type EmptyFrameFilter, type EmulatorBackend, EmulatorClient, type EmulatorClientOptions, EmulatorCommandError, type EmulatorImage, EmulatorImageMissingError, type EmulatorInstance, EmulatorLifecycle, type EmulatorLifecycleOptions, EmulatorNotFoundError, type EmulatorStartResult, type EmulatorStopResult, type Env, type Evidence, type EvidenceKind, type ExpectPresent, type ExpectationOutcome, type ExplorationAction, type ExplorationClock, type ExplorationDevice, type ExplorationDeviceOptions, type ExplorationHost, type ExplorationOptions, type ExplorationOutcome, type ExplorationResult, type ExplorationState, type ExplorationStep, type ExplorationStrategy, type ExplorationTargetDevice, FLAMEGRAPH_FILES, FPS_COMMAND, FTRACE_CATEGORIES, FaultTreeAnalyzer, type FaultTreeSignals, type Fidelity, type FileCategory, type FileRule, FlamegraphAnalyzer, type FlamegraphPageInput, type FoldedStack, type FpsBucket, type FpsWindow, type Frame, FrameAnalyzer, type FrameFlag, FrameLoadAnalyzer, FrameLoadIndex, type FrameLoadIndexInput, type FrameLoadThread, FrameQuery, type FrameStats, type FrameType, type FtraceOptions, GEOMETRY_TOLERANCE_PX, GcAnalyzer, type GcSignals, type Gesture, GestureDriver, type GestureResult, HILOG_COMMAND, HIPROFILER_PLUGIN_NAMES, HITCH_COMMAND, HITRACE_DEFAULT_CATEGORIES, type HapAnalysis, type HapPackage, type HarEdge, Hdc, HdcNotFoundError, type HdcOptions, type HdcResult, type HdcSlice, type HdcTarget, type HidumperCapture, HidumperCollector, type HidumperSnapshot, HilogAnalyzer, HilogCollector, type HilogLevel, type HilogLine, type HilogMatch, type HilogParseOptions, type HilogRule, type HiperfCapture, type HiperfCollectOptions, HiperfCollector, type HiprofilerCollectOptions, type HiprofilerCollectRequest, HiprofilerCollector, type HiprofilerConfigOptions, type HiprofilerPlugin, type HiprofilerPluginName, HitraceCollector, type HttpAgentModelOptions, IGNORED_ATTRIBUTES, IRREVERSIBLE_PATTERNS, type ImageComparison, IngestError, InstantQuery, type InstructionClass, type InstructionCounts, type InventoryFile, type IrreversiblePattern, type JsheapCapture, JsheapCollector, MAX_QUERY_LIMIT, METRIC_DIRECTIONS, MIN_BUFFER_PAGES, MIN_HASH_PIXELS, MemMeasureQuery, MemoryAnalyzer, MemoryMeasureAnalyzer, type MemoryPluginOptions, type MetadataPattern, type Metric, type MetricDelta, type MetricDirection, type MetricUnit, type ModuleDecl, type NamedQueryDefinition, type NamedQueryInfo, type NamedQueryResult, type NativeCategory, type NativeEventKind, type NativeHookEvent, type NativeHookFrame, NativeHookQuery, type NativeHookStatistic, NativeMemoryAnalyzer, type NativeMemoryResult, type NativeNames, type NativeTimelineBucket, type NativehookOptions, OhosPerfError, type OptimizationAnalysis, type OptimizationBasis, type OptimizationLevel, type OptimizationPotential, type OptimizationVerdict, type OversizedFile, PARITY_ROWS, PLANE_A_PLUGINS, type ParityRow, type ParityStatus, type PerfCallchain, type PerfFileAttribution, type PerfFunction, type PerfLeafAttribution, PerfQuery, type PerfSampleRow, type PerfThread, type PixelOnlyChange, type ProbeResult, type ProbeRunner, type ProbeSnapshot, type ProcessInfo, type ProcessMeasure, type ProcessMeasureFilter, ProcessQuery, ProcfsCollector, type ProcfsSample, type ProcfsStatus, type Provenance, type QueryArgument, type QueryContext, type QueryHandle, REPORT_SCHEMA_VERSION, type Rect, type RedundancyLevel, type RedundancyType, RedundantFileAnalyzer, type RedundantFileEntry, type RedundantFileReport, type RedundantThreadPattern, type RedundantThreadsSummary, type RegionPixelChange, RenderAnalyzer, type ReplayResult, type ReportGenerator, type ReportInput, type ReportModel, type ReportScenario, type ReportSection, type ReportSummary, type ReportTotals, type RgbaImage, RsSkipAnalyzer, type RsSkipFrame, type RsSkipResult, type RsSkipTraceMethod, type RuleMatch, type RuleMatchKind, type RunOptions, type RunResult, type RunStepResult, type RunnerCollectOptions, type RunnerDevice, SECTION_TITLES, type Scenario, type ScenarioAction, ScenarioRunner, type ScenarioStep, Scene, type SceneLayout, type SceneMetadata, type SceneStep, type SceneStepRef, type ScenesComparison, SchedQuery, type SchedSlice, type ScreenshotCapture, ScreenshotCollector, type Selector, type SelectorRect, type SmapsRollup, StartupAnalyzer, StartupQuery, type StartupRecord, type StepCapture, type StepComparison, type StepExpectation, type StepStatus, Streamer, StreamerNotFoundError, type StreamerOptions, type SymbolStat, SymbolsAnalyzer, TECH_RULES, type TechRule, type ThreadAnalysis, type ThreadAnalysisSummary, ThreadAnalyzer, type ThreadInfo, ThreadQuery, type ThreadState, ThreadStateQuery, type ThreadWakeupResult, type ThreadWakeupThread, type TimeRange, type TimingCycle, type TraceCollectOptions, type Trend, type TrendOrder, type TrendPoint, type TrendRun, type TrendSeries, UI_DIFF_FILES, UiAnalyzer, type UiCompareOptions, type UiDiff, type UiDiffSide, type UiNode, type UiTreeDiff, type UiTreeDifference, UitestCollector, type UnmeasuredRegion, type UnreleasedRow, type VsyncAnalysis, VsyncAnalyzer, type VsyncPeriod, type VsyncPeriodKind, type VsyncSeverity, type WakeupEvent, type WindowHitches, type ZipArchive, type ZipEntry, agentPrompt, aggregateUnreleased, analyseAnimations, analyzeBinaries, analyzeHap, analyzeThreadWakeup, animationSeverity, buildDepGraph, buildHiprofilerConfig, buildInventory, buildMatrix, buildNativeTimeline, buildReport, buildTrend, categorize, classifyInstruction, classifyNativePath, classifyOptimization, compareImages, compareRegion, compareResults, compareSceneDirs, compareScenes, compileRules, computeBinderAnalysis, computeComponentReuse, computeFaultTree, computeFpsWindows, computeGc, computeRsSkip, computeThreadAnalysis, computeVsyncAnomalies, connect, countInstructions, createSceneLayout, cropRegion, decodePng, defaultAnalyzers, describeDecision, deviceExplorationHost, dhash, diffTrees, discoverCases, encodePng, escapeHtml, evaluateExpectation, evidence, executeAction, explorationDevice, explore, extractBinaries, filterEmptyFrames, flattenUiTree, ftracePlugin, gpuPlugin, hapSection, hashTree, hiperfRecordCommand, httpAgentModel, ingestScene, inspectBinary, irreversibleReason, isUnresolvedSymbol, isZip, loadCases, lookupQuery, markRegions, matchHapRules, matchRules, matchSelector, memoryPlugin, metric, nativeEventKind, nativehookPlugin, nodeIdentity, openDb, openZip, optimizationSection, pairNativeMemory, paritySummary, parseBounds, parseCoverageReport, parseDecision, parseFpsCounts, parseHilogLine, parseHilogText, parseHiperfSummary, parseHitches, parseProcfsStatus, parseRedundantFile, parseScenario, parseSelector, parseSmapsRollup, planNextAction, queryDefinitions, readAgentConfig, readElf, readHidumperCapture, readHilogText, readJsheapSnapshot, readProcfsSamples, readSceneMetadata, readUiTree, renderBundle, renderEvidenceCsv, renderFlamegraphHtml, renderFlamegraphSvg, renderMetricsCsv, renderReportHtml, renderReportJson, renderReportXlsx, renderScenesComparison, renderSummaryJson, renderTree, renderTrendHtml, renderTrendJson, renderUiDiffHtml, replayAgent, resolveAppIdentity, resolveAppIpids, resolveQueryLimit, resolveSelector, round2HalfEven, runAgent, runAnalyzerSections, runAnalyzers, runDrillDown, runNamedQuery, runProbe, sortSteps, summarizeReport, tableRowCounts, trendRunFromReport, unknownQueryError, validateRules, writeProcfsSamples, writeRunFiles, writeSceneMetadata, xpowerPlugin };
package/dist/index.js CHANGED
@@ -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,
@@ -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;
@@ -19393,6 +19823,7 @@ export {
19393
19823
  HiprofilerCollector,
19394
19824
  HitraceCollector,
19395
19825
  IGNORED_ATTRIBUTES,
19826
+ IRREVERSIBLE_PATTERNS,
19396
19827
  IngestError,
19397
19828
  InstantQuery,
19398
19829
  JsheapCollector,
@@ -19433,6 +19864,7 @@ export {
19433
19864
  UiAnalyzer,
19434
19865
  UitestCollector,
19435
19866
  VsyncAnalyzer,
19867
+ agentPrompt,
19436
19868
  aggregateUnreleased,
19437
19869
  analyseAnimations,
19438
19870
  analyzeBinaries,
@@ -19470,12 +19902,14 @@ export {
19470
19902
  cropRegion,
19471
19903
  decodePng,
19472
19904
  defaultAnalyzers,
19905
+ describeDecision,
19473
19906
  deviceExplorationHost,
19474
19907
  dhash,
19475
19908
  diffTrees,
19476
19909
  discoverCases,
19477
19910
  encodePng,
19478
19911
  escapeHtml,
19912
+ evaluateExpectation,
19479
19913
  evidence,
19480
19914
  executeAction,
19481
19915
  explorationDevice,
@@ -19488,8 +19922,10 @@ export {
19488
19922
  hapSection,
19489
19923
  hashTree,
19490
19924
  hiperfRecordCommand,
19925
+ httpAgentModel,
19491
19926
  ingestScene,
19492
19927
  inspectBinary,
19928
+ irreversibleReason,
19493
19929
  isUnresolvedSymbol,
19494
19930
  isZip,
19495
19931
  loadCases,
@@ -19510,6 +19946,7 @@ export {
19510
19946
  paritySummary,
19511
19947
  parseBounds,
19512
19948
  parseCoverageReport,
19949
+ parseDecision,
19513
19950
  parseFpsCounts,
19514
19951
  parseHilogLine,
19515
19952
  parseHilogText,
@@ -19522,6 +19959,7 @@ export {
19522
19959
  parseSmapsRollup,
19523
19960
  planNextAction,
19524
19961
  queryDefinitions,
19962
+ readAgentConfig,
19525
19963
  readElf,
19526
19964
  readHidumperCapture,
19527
19965
  readHilogText,
@@ -19539,14 +19977,17 @@ export {
19539
19977
  renderReportXlsx,
19540
19978
  renderScenesComparison,
19541
19979
  renderSummaryJson,
19980
+ renderTree,
19542
19981
  renderTrendHtml,
19543
19982
  renderTrendJson,
19544
19983
  renderUiDiffHtml,
19984
+ replayAgent,
19545
19985
  resolveAppIdentity,
19546
19986
  resolveAppIpids,
19547
19987
  resolveQueryLimit,
19548
19988
  resolveSelector,
19549
19989
  round2HalfEven,
19990
+ runAgent,
19550
19991
  runAnalyzerSections,
19551
19992
  runAnalyzers,
19552
19993
  runDrillDown,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ohos-perf/core",
3
- "version": "0.20.0",
3
+ "version": "0.21.0",
4
4
  "description": "HarmonyOS performance analysis: capability probing, nine collectors, trace ingest, typed queries, twenty-one analyzers with provenance and fidelity, reports and a scenario runner",
5
5
  "keywords": [
6
6
  "harmonyos",