@ohos-perf/core 0.23.0 → 0.24.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 +305 -37
  2. package/dist/index.js +513 -111
  3. package/package.json +1 -1
package/dist/index.d.ts CHANGED
@@ -4594,12 +4594,18 @@ declare function executeAction(device: ActionDevice, app: string, action: Scenar
4594
4594
 
4595
4595
  /** The three orders HapRay offers, kept under their names. */
4596
4596
  type ExplorationStrategy = 'depth_first' | 'breadth_first' | 'random';
4597
+ /** Which way a scroll gesture's content moves. */
4598
+ type ScrollDirection = 'up' | 'down';
4597
4599
  /** What exploration needs from a device. `Device` satisfies it structurally. */
4598
4600
  interface ExplorationDevice {
4599
4601
  /** The flattened on-screen tree, as `flattenUiTree` returns it. */
4600
4602
  dump(): Promise<readonly UiNode[]>;
4601
4603
  /** Tap the centre of `bounds`. Throws when the device refuses the gesture. */
4602
4604
  tap(bounds: string): Promise<void>;
4605
+ /** Swipe inside a scrollable node. Absent when the device cannot scroll. */
4606
+ swipe?(bounds: string, direction: ScrollDirection): Promise<void>;
4607
+ /** Press the system back button. Absent when the device cannot go back. */
4608
+ back?(): Promise<void>;
4603
4609
  }
4604
4610
  interface ExplorationState {
4605
4611
  readonly tree: readonly UiNode[];
@@ -4608,6 +4614,12 @@ interface ExplorationState {
4608
4614
  readonly strategy: ExplorationStrategy;
4609
4615
  /** Required by `random`; ignored by the ordered strategies. */
4610
4616
  readonly seed?: number;
4617
+ /**
4618
+ * The bundle the walk must stay inside. Nodes from another bundle are not
4619
+ * offered and not tapped; a screen with none of this app's nodes means the
4620
+ * walk has left the app.
4621
+ */
4622
+ readonly app?: string;
4611
4623
  }
4612
4624
  /** The next tap, or `undefined` when this screen has nothing left to offer. */
4613
4625
  interface ExplorationAction {
@@ -4615,18 +4627,33 @@ interface ExplorationAction {
4615
4627
  readonly nodeId: string;
4616
4628
  readonly bounds: string;
4617
4629
  }
4618
- /** Whether a tap moved the screen. */
4619
- type ExplorationOutcome = 'navigated' | 'no_change';
4620
- /** One tap, with the state hash either side of it. */
4630
+ /**
4631
+ * What a step did.
4632
+ *
4633
+ * `navigated` reached a different page, `updated` changed the screen without
4634
+ * changing the page (new data on the same template, a scroll), and `no_change`
4635
+ * left the screen exactly as it was.
4636
+ */
4637
+ type ExplorationOutcome = 'navigated' | 'updated' | 'no_change';
4638
+ /** What a step performed. */
4639
+ type ExplorationStepKind = 'tap' | 'scroll' | 'back';
4640
+ /** One step, with the state hash either side of it. */
4621
4641
  interface ExplorationStep {
4622
4642
  readonly index: number;
4623
- readonly nodeId: string;
4624
- readonly bounds: string;
4625
- /** The screen hash before the tap. */
4643
+ readonly kind: ExplorationStepKind;
4644
+ /** Present for a tap: the identity of the node that was tapped. */
4645
+ readonly nodeId?: string;
4646
+ /** Present for a tap or a scroll: the bounds the gesture was aimed at. */
4647
+ readonly bounds?: string;
4648
+ /** The screen hash before the step. */
4626
4649
  readonly before: string;
4627
4650
  /** The screen hash after it; equal to `before` means `no_change`. */
4628
4651
  readonly after: string;
4629
4652
  readonly outcome: ExplorationOutcome;
4653
+ /** Who picked this step: the deterministic order, or a supplied chooser. */
4654
+ readonly decidedBy: 'strategy' | 'model';
4655
+ /** The chooser's one-line reason, for a step it decided. */
4656
+ readonly reason?: string;
4630
4657
  }
4631
4658
  interface ExplorationResult {
4632
4659
  readonly strategy: ExplorationStrategy;
@@ -4635,18 +4662,106 @@ interface ExplorationResult {
4635
4662
  readonly steps: readonly ExplorationStep[];
4636
4663
  /** Distinct screen hashes reached, including the one it started on. */
4637
4664
  readonly statesReached: number;
4638
- /** True when it stopped because this screen had no unvisited clickable. */
4665
+ /** Distinct page templates reached, including the one it started on. */
4666
+ readonly pagesReached: number;
4667
+ /** The page hashes in first-reach order, the way a reader follows the walk. */
4668
+ readonly pages: readonly string[];
4669
+ /** How many scroll steps were spent. */
4670
+ readonly scrolls: number;
4671
+ /** How many back steps were spent. */
4672
+ readonly backs: number;
4673
+ /**
4674
+ * Why the walk ended: the step cap, nothing left to try, the model asked to
4675
+ * stop, or the walk left the target app and could not return.
4676
+ */
4677
+ readonly stoppedBy: 'budget' | 'exhausted' | 'model' | 'left_app';
4678
+ /** True when it stopped because nothing was left to tap, scroll or return to. */
4639
4679
  readonly exhausted: boolean;
4680
+ /**
4681
+ * What a supplied chooser proposed, when one was supplied: how many proposals
4682
+ * the walk used, and every answer it refused with the reason. A refusal is
4683
+ * evidence, not an error — the deterministic order decides instead.
4684
+ */
4685
+ readonly proposals?: {
4686
+ readonly used: number;
4687
+ readonly refused: number;
4688
+ readonly refusals: readonly {
4689
+ readonly step: number;
4690
+ readonly detail: string;
4691
+ }[];
4692
+ };
4693
+ }
4694
+ /** One element a chooser may name, as the walk saw it. */
4695
+ interface ExplorationCandidate {
4696
+ /** The identity the walk records for this element; the answer must match it. */
4697
+ readonly identity: string;
4698
+ readonly type: string;
4699
+ readonly text: string;
4700
+ readonly bounds: string;
4701
+ readonly depth: number;
4640
4702
  }
4703
+ /** Everything a chooser is shown about the moment it decides. */
4704
+ interface ExplorationChoiceContext {
4705
+ /** The bundle the walk must stay inside, when one was named. */
4706
+ readonly app?: string;
4707
+ /** Zero-based index of the step being decided. */
4708
+ readonly step: number;
4709
+ readonly maxSteps: number;
4710
+ /** The exact tree the offer was computed from. */
4711
+ readonly screen: readonly UiNode[];
4712
+ /** The elements the chooser may choose, in document order. */
4713
+ readonly candidates: readonly ExplorationCandidate[];
4714
+ /** The steps already taken, oldest first. */
4715
+ readonly history: readonly ExplorationStep[];
4716
+ /** Whether this step could scroll. */
4717
+ readonly canScroll: boolean;
4718
+ /** Whether this step could go back. */
4719
+ readonly canBack: boolean;
4720
+ }
4721
+ /** What a chooser answers: one action, or a refusal it could not parse a choice from. */
4722
+ type ExplorationProposal = {
4723
+ readonly kind: 'tap';
4724
+ readonly identity: string;
4725
+ readonly reason: string;
4726
+ } | {
4727
+ readonly kind: 'scroll';
4728
+ readonly direction: ScrollDirection;
4729
+ readonly reason: string;
4730
+ } | {
4731
+ readonly kind: 'back';
4732
+ readonly reason: string;
4733
+ } | {
4734
+ readonly kind: 'stop';
4735
+ readonly reason: string;
4736
+ } | {
4737
+ readonly kind: 'refusal';
4738
+ readonly detail: string;
4739
+ };
4740
+ /**
4741
+ * An optional decision-maker consulted at each step that has an element to
4742
+ * choose. Its answer is verified against the offer before it decides anything;
4743
+ * a name that was not offered is recorded as a refusal.
4744
+ */
4745
+ type ExplorationChooser = (context: ExplorationChoiceContext) => Promise<ExplorationProposal>;
4641
4746
  interface ExplorationOptions {
4642
- /** Hard cap on taps. HapRay's default is 30. */
4747
+ /** Hard cap on steps. HapRay's default is 30. */
4643
4748
  readonly maxSteps: number;
4644
4749
  readonly strategy: ExplorationStrategy;
4645
4750
  /** Makes `random` reproducible. Defaults to 0, never to the clock. */
4646
4751
  readonly seed?: number;
4752
+ /** The bundle the walk must stay inside. */
4753
+ readonly app?: string;
4754
+ /**
4755
+ * A model (or anything else) that may choose each step. Absent means the
4756
+ * deterministic order decides every step. With a chooser, irreversible
4757
+ * targets are not offered at all.
4758
+ */
4759
+ readonly choose?: ExplorationChooser;
4647
4760
  }
4648
4761
  /** A short hex digest of a screen, stable across runs and hosts. */
4649
4762
  declare function hashTree(tree: readonly UiNode[]): string;
4763
+ /** A short digest of a page's structure: two trees with the same shape share it. */
4764
+ declare function hashPageShape(tree: readonly UiNode[]): string;
4650
4765
  /**
4651
4766
  * The next tap on one screen.
4652
4767
  *
@@ -4655,13 +4770,21 @@ declare function hashTree(tree: readonly UiNode[]): string;
4655
4770
  */
4656
4771
  declare function planNextAction(state: ExplorationState): ExplorationAction | undefined;
4657
4772
  /**
4658
- * Walk the app until the step budget runs out or the screen is exhausted.
4773
+ * Walk the app until the step budget runs out or nothing is left to try.
4659
4774
  *
4660
- * `statesReached` counts distinct hashes rather than taps, so a walk that
4775
+ * `statesReached` counts distinct hashes rather than steps, so a walk that
4661
4776
  * bounced between two screens reports two states however many steps it spent.
4662
- * The returned steps carry the hash either side of each tap: a saved run can be
4663
- * re-read without the device, and two runs that disagree can be compared by
4777
+ * The returned steps carry the hash either side of each action: a saved run can
4778
+ * be re-read without the device, and two runs that disagree can be compared by
4664
4779
  * hash instead of by prose.
4780
+ *
4781
+ * Navigation is measured, not assumed. A scroll is spent only when a
4782
+ * scrollable node is on screen and this exact screen has had fewer than
4783
+ * {@link SCROLLS_PER_SCREEN}; a back only when the trail has a parent and this
4784
+ * screen has had fewer than {@link BACKS_PER_SCREEN}. The trail itself is
4785
+ * updated from the page the screen actually became, so a tap that lands on an
4786
+ * earlier page rewinds it exactly as a back would — HapRay's state stack does
4787
+ * the same thing, but asks a model whether the page matches.
4665
4788
  */
4666
4789
  declare function explore(device: ExplorationDevice, options: ExplorationOptions): Promise<ExplorationResult>;
4667
4790
  /**
@@ -4677,6 +4800,10 @@ interface ExplorationHost {
4677
4800
  dump(): Promise<readonly UiNode[]>;
4678
4801
  /** One tap at the centre of `bounds`. */
4679
4802
  tap(bounds: string): Promise<void>;
4803
+ /** One swipe inside `bounds`. Absent when the host cannot scroll. */
4804
+ swipe?(bounds: string, direction: ScrollDirection): Promise<void>;
4805
+ /** One system back. Absent when the host cannot go back. */
4806
+ back?(): Promise<void>;
4680
4807
  now(): number;
4681
4808
  sleep(ms: number): Promise<void>;
4682
4809
  }
@@ -4910,6 +5037,38 @@ declare class ScenarioRunner {
4910
5037
  */
4911
5038
  declare function writeRunFiles(outDir: string, result: RunResult): void;
4912
5039
 
5040
+ /**
5041
+ * The irreversible-action guard, shared by the GUI agent and model-guided
5042
+ * exploration.
5043
+ *
5044
+ * It lives in its own module because `agent.ts` and `explore.ts` both need it,
5045
+ * and an import in either direction between those two would make a cycle:
5046
+ * `agent.ts` already imports `hashTree` from `explore.ts`.
5047
+ *
5048
+ * The rule is the same on both paths: a label that names an act is refused,
5049
+ * while a screen that merely mentions a topic is not. `Payment settings` is a
5050
+ * page a walk may open; `立即支付` is money leaving an account.
5051
+ */
5052
+
5053
+ /** One irreversible action the guard recognises. */
5054
+ interface IrreversiblePattern {
5055
+ readonly pattern: RegExp;
5056
+ /** Why the action is refused; the text a refusal records. */
5057
+ readonly why: string;
5058
+ /** A label that matches `pattern`, so a test can prove the row is live. */
5059
+ readonly sample: string;
5060
+ }
5061
+ /**
5062
+ * The actions the guard refuses.
5063
+ *
5064
+ * Each pattern names an act, not a topic: `Payment settings` is a screen a
5065
+ * walk may legitimately open, while `立即支付` is money leaving an account.
5066
+ * Matching on a bare substring would block the settings page a task needs.
5067
+ */
5068
+ declare const IRREVERSIBLE_PATTERNS: readonly IrreversiblePattern[];
5069
+ /** Why tapping this node is irreversible, or `undefined` when it is safe. */
5070
+ declare function irreversibleReason(node: UiNode): string | undefined;
5071
+
4913
5072
  /**
4914
5073
  * The model-driven UI agent (HapRay parity row 5).
4915
5074
  *
@@ -5031,24 +5190,6 @@ interface AgentOptions {
5031
5190
  /** Let the guard's refusals through. Off by default. */
5032
5191
  readonly allowIrreversible?: boolean;
5033
5192
  }
5034
- /** One irreversible action the guard recognises. */
5035
- interface IrreversiblePattern {
5036
- readonly pattern: RegExp;
5037
- /** Why the action is refused; the text a refusal records. */
5038
- readonly why: string;
5039
- /** A label that matches `pattern`, so a test can prove the row is live. */
5040
- readonly sample: string;
5041
- }
5042
- /**
5043
- * The actions the guard refuses.
5044
- *
5045
- * Each pattern names an act, not a topic: `Payment settings` is a screen a
5046
- * walk may legitimately open, while `立即支付` is money leaving an account.
5047
- * Matching on a bare substring would block the settings page a task needs.
5048
- */
5049
- declare const IRREVERSIBLE_PATTERNS: readonly IrreversiblePattern[];
5050
- /** Why tapping this node is irreversible, or `undefined` when it is safe. */
5051
- declare function irreversibleReason(node: UiNode): string | undefined;
5052
5193
  /** One line naming what a decision does, for a transcript or a history entry. */
5053
5194
  declare function describeDecision(decision: AgentDecision): string;
5054
5195
  /**
@@ -5403,7 +5544,8 @@ interface AgentTurnShape {
5403
5544
  }
5404
5545
  /** The GUI-driving shape: a screen to act on, an action or a verified `done`. */
5405
5546
  declare const GUI_TURN: AgentTurnShape;
5406
- interface HttpAgentModelOptions {
5547
+ /** What any OpenAI-compatible client needs: an endpoint, a key, a model. */
5548
+ interface HttpModelOptions {
5407
5549
  /** The endpoint root, without `/chat/completions`. */
5408
5550
  readonly baseUrl: string;
5409
5551
  readonly apiKey: string;
@@ -5411,17 +5553,31 @@ interface HttpAgentModelOptions {
5411
5553
  readonly fetch: AgentFetch;
5412
5554
  /** Request timeout in ms. Defaults to 60 s. */
5413
5555
  readonly timeoutMs?: number;
5556
+ }
5557
+ interface HttpAgentModelOptions extends HttpModelOptions {
5414
5558
  /**
5415
5559
  * How a turn becomes a request and how its answer is read. Defaults to
5416
5560
  * {@link GUI_TURN}.
5417
5561
  *
5418
5562
  * A caller whose turn is not a screen to drive — the root-cause report, whose
5419
- * turn carries the evidence — supplies its own shape. Without this the model
5420
- * would be told to answer with a gesture and an `expect` block, and a
5421
- * correct answer would then be rejected for having neither.
5563
+ * turn carries the evidence, or exploration, whose turn carries a list of
5564
+ * elements — supplies its own shape. Without this the model would be told to
5565
+ * answer with a gesture and an `expect` block, and a correct answer would
5566
+ * then be rejected for having neither.
5422
5567
  */
5423
5568
  readonly shape?: AgentTurnShape;
5424
5569
  }
5570
+ /**
5571
+ * A text-in, text-out model client.
5572
+ *
5573
+ * Exploration needs exactly this: one prompt, one answer it parses itself. It
5574
+ * is the same transport as {@link httpAgentModel} without the GUI turn contract,
5575
+ * so a caller that has its own prompt does not have to pretend it is driving a
5576
+ * screen.
5577
+ */
5578
+ interface ChatModel {
5579
+ complete(prompt: string): Promise<string>;
5580
+ }
5425
5581
  interface AgentConfig {
5426
5582
  readonly baseUrl: string;
5427
5583
  readonly apiKey: string;
@@ -5437,13 +5593,125 @@ interface AgentConfig {
5437
5593
  */
5438
5594
  declare function readAgentConfig(env: Record<string, string | undefined>): AgentConfig | undefined;
5439
5595
  /**
5440
- * A model client over an OpenAI-compatible endpoint.
5596
+ * A text completion client over an OpenAI-compatible endpoint.
5441
5597
  *
5442
5598
  * The options are validated once, at construction, so a misconfiguration fails
5443
- * before a device is touched rather than on the first decision.
5599
+ * before a device is touched rather than on the first prompt.
5600
+ */
5601
+ declare function httpChatModel(options: HttpModelOptions): ChatModel;
5602
+ /**
5603
+ * A model client for a GUI-driving turn.
5604
+ *
5605
+ * The shape is applied here rather than by the caller so the two halves of a
5606
+ * turn — the prompt that asks and the parser that reads — are always the same
5607
+ * pair. Parsing happens in the client, so an error names the answer rather than
5608
+ * the step, which is where the cause actually is.
5444
5609
  */
5445
5610
  declare function httpAgentModel(options: HttpAgentModelOptions): AgentModel;
5446
5611
 
5612
+ /**
5613
+ * The model-guided exploration turn (HapRay parity row 38).
5614
+ *
5615
+ * HapRay's `llm_strategy.py` annotates a screenshot with red boxes, asks a
5616
+ * vision model which numbered element to tap, and then trusts the answer: an
5617
+ * index past the end of the list silently clicks element 0, an unparseable
5618
+ * answer clicks the first element, and a failed call clicks the first button.
5619
+ * The model also decides `scroll` / `back` / `stop`, and a second model call
5620
+ * per stack entry decides whether the screen counts as a new page.
5621
+ *
5622
+ * This is the same decision, made checkable:
5623
+ *
5624
+ * - **The offer is the screen.** The elements in the prompt are exactly the
5625
+ * elements the walk found in the dump it just took. An answer names an index
5626
+ * into that list; the chooser maps it back to the identity the walk records,
5627
+ * and an index outside the list is a refusal naming both numbers. There is no
5628
+ * silent fallback to element 0.
5629
+ * - **The turn is text.** The tree already carries the labels and the bounds;
5630
+ * sending rendered nodes costs fewer tokens than a screenshot and has no
5631
+ * annotation step whose failure mode is "the boxes are in the wrong place".
5632
+ * - **The model cannot invent a gesture.** It chooses among `tap` (an offered
5633
+ * element), `scroll`, `back` and `stop`. It never supplies coordinates, so
5634
+ * the worst a hostile answer can do is pick a bad node the walk already
5635
+ * considered — and irreversible ones are not offered at all.
5636
+ * - **No state comparator is needed.** HapRay asks a model "same page?" on
5637
+ * every transition. The answer to that is `hashPageShape`, computed from the
5638
+ * tree: same structure, different data (or a scroll) is the same page. The
5639
+ * walk measures it and rewinds its trail; no second model call, no guess.
5640
+ */
5641
+
5642
+ /** One element offered to the model, with its position in the offer. */
5643
+ interface StrategyElement {
5644
+ readonly index: number;
5645
+ readonly type: string;
5646
+ readonly text: string;
5647
+ readonly bounds: string;
5648
+ readonly depth: number;
5649
+ }
5650
+ /** Everything one exploration prompt contains. */
5651
+ interface StrategyTurn {
5652
+ /** The bundle the walk must stay inside, when one was named. */
5653
+ readonly app?: string;
5654
+ /** Zero-based index of the step being decided. */
5655
+ readonly step: number;
5656
+ readonly maxSteps: number;
5657
+ /** The current screen, as `renderTree` renders it. */
5658
+ readonly screen: string;
5659
+ readonly elements: readonly StrategyElement[];
5660
+ /** Recent steps, oldest first, as one line each. */
5661
+ readonly history: readonly string[];
5662
+ readonly canScroll: boolean;
5663
+ readonly canBack: boolean;
5664
+ }
5665
+ /** What a model may answer. */
5666
+ type StrategyAnswer = {
5667
+ readonly action: 'tap';
5668
+ readonly element: number;
5669
+ readonly reason: string;
5670
+ } | {
5671
+ readonly action: 'scroll';
5672
+ readonly direction: ScrollDirection;
5673
+ readonly reason: string;
5674
+ } | {
5675
+ readonly action: 'back';
5676
+ readonly reason: string;
5677
+ } | {
5678
+ readonly action: 'stop';
5679
+ readonly reason: string;
5680
+ };
5681
+ /** An answer that could not be read, with what was wrong. */
5682
+ interface StrategyRefusal {
5683
+ readonly action: 'refused';
5684
+ readonly detail: string;
5685
+ }
5686
+ /**
5687
+ * The prompt for one exploration step.
5688
+ *
5689
+ * Deterministic: the same turn renders to the same string. The answer formats
5690
+ * are written out literally because a model that invents an action name fails
5691
+ * far from the answer that caused it, and only the actions the screen allows
5692
+ * are listed — asking for an action the walk will refuse wastes a turn.
5693
+ */
5694
+ declare function explorationPrompt(turn: StrategyTurn): string;
5695
+ /**
5696
+ * Read a model's answer.
5697
+ *
5698
+ * The answer is data from outside the package, so every field is checked. A
5699
+ * content problem becomes a refusal, not a thrown error: a confused model
5700
+ * should cost one step, not the walk. Transport failures are the caller's
5701
+ * (the chooser does not catch them) because an unreachable endpoint is a
5702
+ * configuration problem and continuing would hide it.
5703
+ */
5704
+ declare function parseStrategyAnswer(content: string): StrategyAnswer | StrategyRefusal;
5705
+ /**
5706
+ * A chooser over one model client.
5707
+ *
5708
+ * The index is mapped to the identity the walk offered, and every answer the
5709
+ * walk cannot honour becomes a `refusal` — the walk records it and lets the
5710
+ * deterministic order decide. The prompt and parser are one pair here for the
5711
+ * same reason the GUI agent's are: a prompt asks for what its parser reads.
5712
+ */
5713
+ declare function llmChooser(model: ChatModel): ExplorationChooser;
5714
+
5447
5715
  /**
5448
5716
  * One `native_hook` row with camelCase field names.
5449
5717
  *
@@ -7337,4 +7605,4 @@ declare function askRootCause(model: AgentModel, document: RootCauseDocument, op
7337
7605
  */
7338
7606
  declare function renderRootCauseMarkdown(document: RootCauseDocument): string;
7339
7607
 
7340
- export { ANIMATION_BANDS, type ActionContext, type ActionDevice, type ActionOutcome, type ActiveAlloc, type AddressRef, 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 AgentTurnShape, 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, type FunctionRange, GEOMETRY_TOLERANCE_PX, GUI_TURN, 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 NamingAnswer, type NamingCase, type NamingQuestion, type NamingReport, 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, PROMPT_EVIDENCE_LIMIT, 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, ROOT_CAUSE_SCHEMA_VERSION, ROOT_CAUSE_TURN, type RecoveredSymbol, type RecoveryResult, 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, type RootCauseAnalysis, type RootCauseDocument, type RootCauseGenerator, type RootCauseInput, type RootCauseObservation, type RootCauseScene, type RootCauseSummary, type RootCauseSuspect, 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 UnresolvedAddress, type VsyncAnalysis, VsyncAnalyzer, type VsyncPeriod, type VsyncPeriodKind, type VsyncSeverity, type WakeupEvent, type WindowHitches, type ZipArchive, type ZipEntry, addressOfOffset, agentPrompt, aggregateUnreleased, analyseAnimations, analyzeBinaries, analyzeHap, analyzeThreadWakeup, animationSeverity, askRootCause, buildDepGraph, buildHiprofilerConfig, buildInventory, buildMatrix, buildNativeTimeline, buildReport, buildRootCauseDocument, 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, functionAt, gpuPlugin, groundingVocabulary, hapSection, hashTree, hiperfRecordCommand, httpAgentModel, ingestScene, inspectBinary, irreversibleReason, isUnresolvedSymbol, isZip, loadCases, lookupQuery, markRegions, matchHapRules, matchRules, matchSelector, measureNaming, memoryPlugin, metric, nativeEventKind, nativehookPlugin, nodeIdentity, normaliseName, openDb, openZip, optimizationSection, pairNativeMemory, paritySummary, parseBounds, parseCoverageReport, parseDecision, parseFpsCounts, parseHilogLine, parseHilogText, parseHiperfSummary, parseHitches, parseProcfsStatus, parseRedundantFile, parseRootCauseAnswer, parseScenario, parseSelector, parseSmapsRollup, planNextAction, queryDefinitions, rankObservations, readAgentConfig, readElf, readHidumperCapture, readHilogText, readJsheapSnapshot, readProcfsSamples, readSceneMetadata, readUiTree, recoverSymbols, renderBundle, renderEvidenceCsv, renderFlamegraphHtml, renderFlamegraphSvg, renderMetricsCsv, renderReportHtml, renderReportJson, renderReportXlsx, renderRootCauseMarkdown, renderScenesComparison, renderSummaryJson, renderTree, renderTrendHtml, renderTrendJson, renderUiDiffHtml, replayAgent, resolveAppIdentity, resolveAppIpids, resolveQueryLimit, resolveSelector, rootCausePrompt, round2HalfEven, runAgent, runAnalyzerSections, runAnalyzers, runDrillDown, runNamedQuery, runProbe, sortSteps, summarizeReport, symbolIndex, tableRowCounts, trendRunFromReport, ungroundedNames, unknownQueryError, validateRules, writeProcfsSamples, writeRunFiles, writeSceneMetadata, xpowerPlugin };
7608
+ export { ANIMATION_BANDS, type ActionContext, type ActionDevice, type ActionOutcome, type ActiveAlloc, type AddressRef, 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 AgentTurnShape, 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 ChatModel, 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 ExplorationCandidate, type ExplorationChoiceContext, type ExplorationChooser, type ExplorationClock, type ExplorationDevice, type ExplorationDeviceOptions, type ExplorationHost, type ExplorationOptions, type ExplorationOutcome, type ExplorationProposal, type ExplorationResult, type ExplorationState, type ExplorationStep, type ExplorationStepKind, 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, type FunctionRange, GEOMETRY_TOLERANCE_PX, GUI_TURN, 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, type HttpModelOptions, 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 NamingAnswer, type NamingCase, type NamingQuestion, type NamingReport, 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, PROMPT_EVIDENCE_LIMIT, 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, ROOT_CAUSE_SCHEMA_VERSION, ROOT_CAUSE_TURN, type RecoveredSymbol, type RecoveryResult, 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, type RootCauseAnalysis, type RootCauseDocument, type RootCauseGenerator, type RootCauseInput, type RootCauseObservation, type RootCauseScene, type RootCauseSummary, type RootCauseSuspect, 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 ScrollDirection, type Selector, type SelectorRect, type SmapsRollup, StartupAnalyzer, StartupQuery, type StartupRecord, type StepCapture, type StepComparison, type StepExpectation, type StepStatus, type StrategyAnswer, type StrategyElement, type StrategyRefusal, type StrategyTurn, 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 UnresolvedAddress, type VsyncAnalysis, VsyncAnalyzer, type VsyncPeriod, type VsyncPeriodKind, type VsyncSeverity, type WakeupEvent, type WindowHitches, type ZipArchive, type ZipEntry, addressOfOffset, agentPrompt, aggregateUnreleased, analyseAnimations, analyzeBinaries, analyzeHap, analyzeThreadWakeup, animationSeverity, askRootCause, buildDepGraph, buildHiprofilerConfig, buildInventory, buildMatrix, buildNativeTimeline, buildReport, buildRootCauseDocument, 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, explorationPrompt, explore, extractBinaries, filterEmptyFrames, flattenUiTree, ftracePlugin, functionAt, gpuPlugin, groundingVocabulary, hapSection, hashPageShape, hashTree, hiperfRecordCommand, httpAgentModel, httpChatModel, ingestScene, inspectBinary, irreversibleReason, isUnresolvedSymbol, isZip, llmChooser, loadCases, lookupQuery, markRegions, matchHapRules, matchRules, matchSelector, measureNaming, memoryPlugin, metric, nativeEventKind, nativehookPlugin, nodeIdentity, normaliseName, openDb, openZip, optimizationSection, pairNativeMemory, paritySummary, parseBounds, parseCoverageReport, parseDecision, parseFpsCounts, parseHilogLine, parseHilogText, parseHiperfSummary, parseHitches, parseProcfsStatus, parseRedundantFile, parseRootCauseAnswer, parseScenario, parseSelector, parseSmapsRollup, parseStrategyAnswer, planNextAction, queryDefinitions, rankObservations, readAgentConfig, readElf, readHidumperCapture, readHilogText, readJsheapSnapshot, readProcfsSamples, readSceneMetadata, readUiTree, recoverSymbols, renderBundle, renderEvidenceCsv, renderFlamegraphHtml, renderFlamegraphSvg, renderMetricsCsv, renderReportHtml, renderReportJson, renderReportXlsx, renderRootCauseMarkdown, renderScenesComparison, renderSummaryJson, renderTree, renderTrendHtml, renderTrendJson, renderUiDiffHtml, replayAgent, resolveAppIdentity, resolveAppIpids, resolveQueryLimit, resolveSelector, rootCausePrompt, round2HalfEven, runAgent, runAnalyzerSections, runAnalyzers, runDrillDown, runNamedQuery, runProbe, sortSteps, summarizeReport, symbolIndex, tableRowCounts, trendRunFromReport, ungroundedNames, unknownQueryError, validateRules, writeProcfsSamples, writeRunFiles, writeSceneMetadata, xpowerPlugin };
package/dist/index.js CHANGED
@@ -6395,8 +6395,8 @@ var PARITY_ROWS = [
6395
6395
  {
6396
6396
  row: 38,
6397
6397
  name: "LLM exploration strategy and state comparator (`haptest`)",
6398
- status: "missing",
6399
- reason: "HapRay hands the whole step to a model: `llm_strategy.py` asks it which node to tap, and `llm_state_comparator.py` asks whether the screen changed. Neither answer is checked, so a model that taps a dead button reports progress. Not ported yet; P29 covers it, and the design requires the model's answer to be verified against the screen it was given before the step counts."
6398
+ status: "ported",
6399
+ reason: ""
6400
6400
  },
6401
6401
  {
6402
6402
  row: 39,
@@ -8082,6 +8082,51 @@ function swipeInside(rect, direction, travel) {
8082
8082
 
8083
8083
  // src/scenario/explore.ts
8084
8084
  import { createHash as createHash2 } from "node:crypto";
8085
+
8086
+ // src/scenario/guard.ts
8087
+ var IRREVERSIBLE_PATTERNS = [
8088
+ {
8089
+ pattern: /\bpay\b|\bpay now\b|立即支付|确认支付|去支付|立即购买/i,
8090
+ why: "payment is irreversible",
8091
+ sample: "\u7ACB\u5373\u652F\u4ED8"
8092
+ },
8093
+ {
8094
+ pattern: /\b(?:confirm order|place order|submit order|buy now)\b|提交订单|确认下单/i,
8095
+ why: "placing an order is irreversible",
8096
+ sample: "Confirm order"
8097
+ },
8098
+ {
8099
+ pattern: /\btransfer\b|\bsend money\b|\bremit\b|转账/i,
8100
+ why: "a transfer moves money and cannot be undone",
8101
+ sample: "Transfer"
8102
+ },
8103
+ {
8104
+ pattern: /\b(?:log ?in|sign ?in|register|sign ?up)\b|登录|注册/i,
8105
+ why: "signing in changes the account state",
8106
+ sample: "Log in"
8107
+ },
8108
+ {
8109
+ pattern: /\b(?:delete|unsubscribe|publish|post|share)\b|删除|注销|发布/i,
8110
+ why: "the action destroys or publishes content",
8111
+ sample: "Delete"
8112
+ }
8113
+ ];
8114
+ function labelsOf(node) {
8115
+ const labels = [node.text.trim(), node.id.replace(/[_-]+/g, " ").trim()];
8116
+ return labels.filter((label2) => label2 !== "");
8117
+ }
8118
+ function irreversibleReason(node) {
8119
+ for (const label2 of labelsOf(node)) {
8120
+ for (const entry of IRREVERSIBLE_PATTERNS) {
8121
+ if (entry.pattern.test(label2)) return entry.why;
8122
+ }
8123
+ }
8124
+ return void 0;
8125
+ }
8126
+
8127
+ // src/scenario/explore.ts
8128
+ var SCROLLS_PER_SCREEN = 3;
8129
+ var BACKS_PER_SCREEN = 1;
8085
8130
  var DEFAULT_SEED = 0;
8086
8131
  var DIGEST_CHARS = 16;
8087
8132
  function canonical(tree) {
@@ -8100,7 +8145,25 @@ function canonical(tree) {
8100
8145
  return tree.map(line).join("");
8101
8146
  }
8102
8147
  function hashTree(tree) {
8103
- return createHash2("sha256").update(canonical(tree)).digest("hex").slice(0, DIGEST_CHARS);
8148
+ return digest(canonical(tree));
8149
+ }
8150
+ function digest(text2) {
8151
+ return createHash2("sha256").update(text2).digest("hex").slice(0, DIGEST_CHARS);
8152
+ }
8153
+ function pageCanonical(tree) {
8154
+ const line = (node) => [
8155
+ node.bundleName,
8156
+ node.abilityName,
8157
+ node.depth,
8158
+ node.type,
8159
+ node.clickable ? "1" : "0",
8160
+ node.enabled ? "1" : "0",
8161
+ node.scrollable ? "1" : "0"
8162
+ ].map((field2) => `${String(field2).length}:${String(field2)}`).join("");
8163
+ return tree.map(line).join("");
8164
+ }
8165
+ function hashPageShape(tree) {
8166
+ return digest(pageCanonical(tree));
8104
8167
  }
8105
8168
  function mulberry32(seed) {
8106
8169
  let state = seed >>> 0;
@@ -8138,25 +8201,57 @@ function rectOf(node) {
8138
8201
  return node.boundsRect ?? parseBounds(node.bounds);
8139
8202
  }
8140
8203
  function planNextAction(state) {
8141
- const ids = identities(state.tree);
8142
- const candidates = state.tree.filter(
8143
- (node2) => node2.clickable && node2.enabled && rectOf(node2) !== void 0 && !state.visited.has(ids.get(node2))
8144
- );
8145
- if (candidates.length === 0) return void 0;
8146
- let ordered2;
8147
- switch (state.strategy) {
8204
+ const first = orderCandidates(candidatesOf(state), state.strategy, state.seed)[0];
8205
+ if (first === void 0) return void 0;
8206
+ return { kind: "tap", nodeId: first.identity, bounds: first.node.bounds };
8207
+ }
8208
+ function orderCandidates(candidates, strategy, seed) {
8209
+ switch (strategy) {
8148
8210
  case "depth_first":
8149
- ordered2 = candidates;
8150
- break;
8211
+ return candidates;
8151
8212
  case "breadth_first":
8152
- ordered2 = [...candidates].sort((a, b) => a.depth - b.depth);
8153
- break;
8213
+ return [...candidates].sort((a, b) => a.node.depth - b.node.depth);
8154
8214
  case "random":
8155
- ordered2 = shuffled(candidates, state.seed ?? DEFAULT_SEED);
8156
- break;
8215
+ return shuffled(candidates, seed ?? DEFAULT_SEED);
8216
+ }
8217
+ }
8218
+ function offerOf(candidate) {
8219
+ return {
8220
+ identity: candidate.identity,
8221
+ type: candidate.node.type,
8222
+ text: candidate.node.text,
8223
+ bounds: candidate.node.bounds,
8224
+ depth: candidate.node.depth
8225
+ };
8226
+ }
8227
+ function candidatesOf(state) {
8228
+ const ids = identities(state.tree);
8229
+ const out = [];
8230
+ for (const node of state.tree) {
8231
+ if (!node.clickable || !node.enabled) continue;
8232
+ if (rectOf(node) === void 0) continue;
8233
+ if (state.app !== void 0 && node.bundleName !== "" && node.bundleName !== state.app) continue;
8234
+ const identity = ids.get(node);
8235
+ if (state.visited.has(identity)) continue;
8236
+ out.push({ node, identity });
8237
+ }
8238
+ return out;
8239
+ }
8240
+ function scrollableNode(tree, app) {
8241
+ return tree.find(
8242
+ (node) => node.scrollable && node.enabled && rectOf(node) !== void 0 && (app === void 0 || node.bundleName === "" || node.bundleName === app)
8243
+ );
8244
+ }
8245
+ function isOutsideApp(tree, app) {
8246
+ if (app === void 0) return false;
8247
+ const bundles = tree.map((node) => node.bundleName).filter((bundle) => bundle !== "");
8248
+ return bundles.length > 0 && !bundles.includes(app);
8249
+ }
8250
+ function trailIndexFor(trail, page) {
8251
+ for (let index = trail.length - 1; index >= 0; index -= 1) {
8252
+ if (trail[index].page === page) return index;
8157
8253
  }
8158
- const node = ordered2[0];
8159
- return { kind: "tap", nodeId: ids.get(node), bounds: node.bounds };
8254
+ return -1;
8160
8255
  }
8161
8256
  async function explore(device, options) {
8162
8257
  if (!Number.isSafeInteger(options.maxSteps) || options.maxSteps < 1) {
@@ -8167,45 +8262,175 @@ async function explore(device, options) {
8167
8262
  const seed = options.strategy === "random" ? options.seed ?? DEFAULT_SEED : void 0;
8168
8263
  const steps = [];
8169
8264
  const states = /* @__PURE__ */ new Set();
8265
+ const pages = /* @__PURE__ */ new Set();
8170
8266
  const visitedByScreen = /* @__PURE__ */ new Map();
8267
+ const scrollsByScreen = /* @__PURE__ */ new Map();
8268
+ const backsByScreen = /* @__PURE__ */ new Map();
8269
+ const proposals = options.choose === void 0 ? void 0 : { used: 0, refused: 0, refusals: [] };
8171
8270
  let tree = await device.dump();
8172
8271
  let hash = hashTree(tree);
8272
+ let page = hashPageShape(tree);
8173
8273
  states.add(hash);
8174
- let exhausted = false;
8274
+ pages.add(page);
8275
+ const trail = [{ hash, page }];
8276
+ let stoppedBy = "budget";
8175
8277
  while (steps.length < options.maxSteps) {
8176
- const visited = visitedByScreen.get(hash) ?? /* @__PURE__ */ new Set();
8177
- const action = planNextAction({
8278
+ const state = {
8178
8279
  tree,
8179
- visited,
8280
+ visited: visitedByScreen.get(hash) ?? /* @__PURE__ */ new Set(),
8180
8281
  strategy: options.strategy,
8181
- ...seed === void 0 ? {} : { seed }
8182
- });
8183
- if (action === void 0) {
8184
- exhausted = true;
8282
+ ...seed === void 0 ? {} : { seed },
8283
+ ...options.app === void 0 ? {} : { app: options.app }
8284
+ };
8285
+ const outside = isOutsideApp(tree, options.app);
8286
+ const target = outside ? void 0 : scrollableNode(tree, options.app);
8287
+ const canScroll = device.swipe !== void 0 && target !== void 0 && (scrollsByScreen.get(hash) ?? 0) < SCROLLS_PER_SCREEN;
8288
+ const canBack = device.back !== void 0 && trail.length > 1 && (backsByScreen.get(hash) ?? 0) < BACKS_PER_SCREEN;
8289
+ const all = candidatesOf(state);
8290
+ const allowed = options.choose === void 0 ? all : all.filter((candidate) => irreversibleReason(candidate.node) === void 0);
8291
+ const ordered2 = orderCandidates(allowed, options.strategy, seed);
8292
+ let decision;
8293
+ let decidedBy = "strategy";
8294
+ let reason;
8295
+ if (options.choose !== void 0 && allowed.length > 0) {
8296
+ const proposal = await options.choose({
8297
+ ...options.app === void 0 ? {} : { app: options.app },
8298
+ step: steps.length,
8299
+ maxSteps: options.maxSteps,
8300
+ screen: tree,
8301
+ candidates: allowed.map(offerOf),
8302
+ history: steps.slice(),
8303
+ canScroll,
8304
+ canBack
8305
+ });
8306
+ let refusal2;
8307
+ switch (proposal.kind) {
8308
+ case "tap": {
8309
+ const match2 = allowed.find(
8310
+ (candidate) => candidate.identity === proposal.identity
8311
+ );
8312
+ if (match2 === void 0) {
8313
+ refusal2 = `the chooser named ${JSON.stringify(proposal.identity)}, which is not among the ${allowed.length} offered element(s)`;
8314
+ } else {
8315
+ decision = { kind: "tap", nodeId: match2.identity, bounds: match2.node.bounds };
8316
+ decidedBy = "model";
8317
+ reason = proposal.reason;
8318
+ }
8319
+ break;
8320
+ }
8321
+ case "scroll":
8322
+ if (!canScroll) {
8323
+ refusal2 = "the chooser asked to scroll, but this screen has no scrollable node left to swipe";
8324
+ } else {
8325
+ decision = {
8326
+ kind: "scroll",
8327
+ bounds: target.bounds,
8328
+ direction: proposal.direction
8329
+ };
8330
+ decidedBy = "model";
8331
+ reason = proposal.reason;
8332
+ }
8333
+ break;
8334
+ case "back":
8335
+ if (!canBack) {
8336
+ refusal2 = "the chooser asked to go back, but the walk has no earlier page to return to";
8337
+ } else {
8338
+ decision = { kind: "back" };
8339
+ decidedBy = "model";
8340
+ reason = proposal.reason;
8341
+ }
8342
+ break;
8343
+ case "stop":
8344
+ stoppedBy = "model";
8345
+ break;
8346
+ case "refusal":
8347
+ refusal2 = proposal.detail;
8348
+ break;
8349
+ }
8350
+ if (proposals !== void 0) {
8351
+ if (decision !== void 0) proposals.used += 1;
8352
+ if (refusal2 !== void 0) {
8353
+ proposals.refused += 1;
8354
+ proposals.refusals.push({ step: steps.length, detail: refusal2 });
8355
+ }
8356
+ }
8357
+ if (stoppedBy === "model") break;
8358
+ }
8359
+ if (decision === void 0) {
8360
+ if (outside) {
8361
+ if (canBack) decision = { kind: "back" };
8362
+ } else {
8363
+ const first = ordered2[0];
8364
+ if (first !== void 0) {
8365
+ decision = { kind: "tap", nodeId: first.identity, bounds: first.node.bounds };
8366
+ } else if (canScroll) {
8367
+ decision = { kind: "scroll", bounds: target.bounds, direction: "up" };
8368
+ } else if (canBack) {
8369
+ decision = { kind: "back" };
8370
+ }
8371
+ }
8372
+ }
8373
+ if (decision === void 0) {
8374
+ stoppedBy = outside ? "left_app" : "exhausted";
8185
8375
  break;
8186
8376
  }
8187
- visited.add(action.nodeId);
8188
- visitedByScreen.set(hash, visited);
8189
- await device.tap(action.bounds);
8377
+ switch (decision.kind) {
8378
+ case "tap": {
8379
+ const visited = visitedByScreen.get(hash) ?? /* @__PURE__ */ new Set();
8380
+ visited.add(decision.nodeId);
8381
+ visitedByScreen.set(hash, visited);
8382
+ await device.tap(decision.bounds);
8383
+ break;
8384
+ }
8385
+ case "scroll":
8386
+ scrollsByScreen.set(hash, (scrollsByScreen.get(hash) ?? 0) + 1);
8387
+ await device.swipe(decision.bounds, decision.direction);
8388
+ break;
8389
+ case "back":
8390
+ backsByScreen.set(hash, (backsByScreen.get(hash) ?? 0) + 1);
8391
+ await device.back();
8392
+ break;
8393
+ }
8190
8394
  tree = await device.dump();
8191
8395
  const after = hashTree(tree);
8396
+ const afterPage = hashPageShape(tree);
8192
8397
  states.add(after);
8398
+ pages.add(afterPage);
8399
+ const outcome = after === hash ? "no_change" : afterPage === page ? "updated" : "navigated";
8193
8400
  steps.push({
8194
8401
  index: steps.length,
8195
- nodeId: action.nodeId,
8196
- bounds: action.bounds,
8402
+ kind: decision.kind,
8403
+ ...decision.kind === "tap" ? { nodeId: decision.nodeId, bounds: decision.bounds } : decision.kind === "scroll" ? { bounds: decision.bounds } : {},
8197
8404
  before: hash,
8198
8405
  after,
8199
- outcome: after === hash ? "no_change" : "navigated"
8406
+ outcome,
8407
+ decidedBy,
8408
+ ...reason === void 0 ? {} : { reason }
8200
8409
  });
8410
+ const match = trailIndexFor(trail, afterPage);
8411
+ if (match !== -1) {
8412
+ trail.length = match + 1;
8413
+ trail[match] = { hash: after, page: afterPage };
8414
+ } else if (afterPage !== page) {
8415
+ trail.push({ hash: after, page: afterPage });
8416
+ } else {
8417
+ trail[trail.length - 1] = { hash: after, page: afterPage };
8418
+ }
8201
8419
  hash = after;
8420
+ page = afterPage;
8202
8421
  }
8203
8422
  return {
8204
8423
  strategy: options.strategy,
8205
8424
  ...seed === void 0 ? {} : { seed },
8206
8425
  steps,
8207
8426
  statesReached: states.size,
8208
- exhausted
8427
+ pagesReached: pages.size,
8428
+ pages: [...pages],
8429
+ scrolls: steps.filter((step) => step.kind === "scroll").length,
8430
+ backs: steps.filter((step) => step.kind === "back").length,
8431
+ stoppedBy,
8432
+ exhausted: stoppedBy === "exhausted",
8433
+ ...proposals === void 0 ? {} : { proposals }
8209
8434
  };
8210
8435
  }
8211
8436
  var DEFAULT_SETTLE_MS = 5e3;
@@ -8224,27 +8449,30 @@ function explorationDevice(host, options = {}) {
8224
8449
  if (settled === void 0) settled = await host.dump();
8225
8450
  return settled;
8226
8451
  };
8227
- return {
8228
- dump: read,
8229
- async tap(bounds) {
8230
- const before = hashTree(await read());
8231
- await host.tap(bounds);
8232
- const deadline = host.now() + settleMs;
8233
- for (; ; ) {
8234
- const next = await host.dump();
8235
- if (hashTree(next) !== before) {
8236
- settled = next;
8237
- return;
8238
- }
8239
- const remaining = deadline - host.now();
8240
- if (remaining <= 0) {
8241
- settled = next;
8242
- return;
8243
- }
8244
- await host.sleep(Math.min(pollMs, remaining));
8452
+ const act = async (perform) => {
8453
+ const before = hashTree(await read());
8454
+ await perform();
8455
+ const deadline = host.now() + settleMs;
8456
+ for (; ; ) {
8457
+ const next = await host.dump();
8458
+ if (hashTree(next) !== before) {
8459
+ settled = next;
8460
+ return;
8461
+ }
8462
+ const remaining = deadline - host.now();
8463
+ if (remaining <= 0) {
8464
+ settled = next;
8465
+ return;
8245
8466
  }
8467
+ await host.sleep(Math.min(pollMs, remaining));
8246
8468
  }
8247
8469
  };
8470
+ return {
8471
+ dump: read,
8472
+ tap: (bounds) => act(() => host.tap(bounds)),
8473
+ ...host.swipe === void 0 ? {} : { swipe: (bounds, direction) => act(() => host.swipe(bounds, direction)) },
8474
+ ...host.back === void 0 ? {} : { back: () => act(() => host.back()) }
8475
+ };
8248
8476
  }
8249
8477
  var ACCEPTED_MARKER3 = "No Error";
8250
8478
  function deviceExplorationHost(device, options = {}) {
@@ -8256,6 +8484,15 @@ function deviceExplorationHost(device, options = {}) {
8256
8484
  ...options.settleMs === void 0 ? {} : { settleMs: options.settleMs },
8257
8485
  ...options.pollMs === void 0 ? {} : { pollMs: options.pollMs }
8258
8486
  };
8487
+ const perform = async (gesture, label2) => {
8488
+ const result = await device.gesture(gesture);
8489
+ if (!result.output.includes(ACCEPTED_MARKER3)) {
8490
+ throw new OhosPerfError(
8491
+ `exploration: uitest uiInput ${label2} did not report "${ACCEPTED_MARKER3}": ${result.output === "" ? "(no output)" : result.output}`,
8492
+ { code: "SCENARIO_ACTION_FAILED" }
8493
+ );
8494
+ }
8495
+ };
8259
8496
  return explorationDevice(
8260
8497
  {
8261
8498
  dump: () => device.uiTree(),
@@ -8268,20 +8505,54 @@ function deviceExplorationHost(device, options = {}) {
8268
8505
  { code: "SCENARIO_EXPLORE_STALE" }
8269
8506
  );
8270
8507
  }
8271
- const result = await device.gesture({ action: "click", x: point.x, y: point.y });
8272
- if (!result.output.includes(ACCEPTED_MARKER3)) {
8508
+ await perform({ action: "click", x: point.x, y: point.y }, "click");
8509
+ },
8510
+ swipe: async (bounds, direction) => {
8511
+ const rect = rectOfBounds(bounds);
8512
+ const tree = await device.uiTree();
8513
+ const target = tree.find((candidate) => candidate.bounds === bounds);
8514
+ if (target === void 0) {
8515
+ throw new OhosPerfError(
8516
+ `exploration: no node on the current screen carries these bounds ${JSON.stringify(bounds)}; the target is not on the screen any more`,
8517
+ { code: "SCENARIO_EXPLORE_STALE" }
8518
+ );
8519
+ }
8520
+ if (!target.scrollable) {
8273
8521
  throw new OhosPerfError(
8274
- `exploration: uitest uiInput click did not report "${ACCEPTED_MARKER3}": ${result.output === "" ? "(no output)" : result.output}`,
8275
- { code: "SCENARIO_ACTION_FAILED" }
8522
+ `exploration: the node at ${JSON.stringify(bounds)} is not scrollable, so a swipe on it would drag whatever happens to be under that rect`,
8523
+ { code: "SCENARIO_EXPLORE_STALE" }
8276
8524
  );
8277
8525
  }
8526
+ const { from, to } = swipePoints(rect, direction);
8527
+ await perform(
8528
+ { action: "swipe", fromX: from.x, fromY: from.y, toX: to.x, toY: to.y },
8529
+ `swipe ${direction}`
8530
+ );
8278
8531
  },
8532
+ back: () => perform({ action: "key", key: "Back" }, "key Back"),
8279
8533
  now: () => clock.now(),
8280
8534
  sleep: (ms) => clock.sleep(ms)
8281
8535
  },
8282
8536
  settleOptions
8283
8537
  );
8284
8538
  }
8539
+ function rectOfBounds(bounds) {
8540
+ const rect = parseBounds(bounds);
8541
+ if (rect === void 0) {
8542
+ throw new OhosPerfError(
8543
+ `exploration: ${JSON.stringify(bounds)} is not a "[l,t][r,b]" bounds string; it has no swipe path`,
8544
+ { code: "SCENARIO_EXPLORE_STALE" }
8545
+ );
8546
+ }
8547
+ return rect;
8548
+ }
8549
+ function swipePoints(rect, direction) {
8550
+ const x = Math.round((rect.left + rect.right) / 2);
8551
+ const height = rect.bottom - rect.top;
8552
+ const upper = Math.round(rect.top + height * 0.2);
8553
+ const lower = Math.round(rect.top + height * 0.8);
8554
+ return direction === "up" ? { from: { x, y: lower }, to: { x, y: upper } } : { from: { x, y: upper }, to: { x, y: lower } };
8555
+ }
8285
8556
  function centreOfBounds(bounds) {
8286
8557
  const rect = parseBounds(bounds);
8287
8558
  if (rect === void 0) {
@@ -8607,45 +8878,6 @@ function writeRunFiles(outDir, result) {
8607
8878
  }
8608
8879
 
8609
8880
  // src/scenario/agent.ts
8610
- var IRREVERSIBLE_PATTERNS = [
8611
- {
8612
- pattern: /\bpay\b|\bpay now\b|立即支付|确认支付|去支付|立即购买/i,
8613
- why: "payment is irreversible",
8614
- sample: "\u7ACB\u5373\u652F\u4ED8"
8615
- },
8616
- {
8617
- pattern: /\b(?:confirm order|place order|submit order|buy now)\b|提交订单|确认下单/i,
8618
- why: "placing an order is irreversible",
8619
- sample: "Confirm order"
8620
- },
8621
- {
8622
- pattern: /\btransfer\b|\bsend money\b|\bremit\b|转账/i,
8623
- why: "a transfer moves money and cannot be undone",
8624
- sample: "Transfer"
8625
- },
8626
- {
8627
- pattern: /\b(?:log ?in|sign ?in|register|sign ?up)\b|登录|注册/i,
8628
- why: "signing in changes the account state",
8629
- sample: "Log in"
8630
- },
8631
- {
8632
- pattern: /\b(?:delete|unsubscribe|publish|post|share)\b|删除|注销|发布/i,
8633
- why: "the action destroys or publishes content",
8634
- sample: "Delete"
8635
- }
8636
- ];
8637
- function labelsOf(node) {
8638
- const labels = [node.text.trim(), node.id.replace(/[_-]+/g, " ").trim()];
8639
- return labels.filter((label2) => label2 !== "");
8640
- }
8641
- function irreversibleReason(node) {
8642
- for (const label2 of labelsOf(node)) {
8643
- for (const entry of IRREVERSIBLE_PATTERNS) {
8644
- if (entry.pattern.test(label2)) return entry.why;
8645
- }
8646
- }
8647
- return void 0;
8648
- }
8649
8881
  function describeDecision(decision) {
8650
8882
  if ("done" in decision) return "done";
8651
8883
  const action = decision.action;
@@ -9353,21 +9585,20 @@ function contentOf(body) {
9353
9585
  }
9354
9586
  return content;
9355
9587
  }
9356
- function httpAgentModel(options) {
9588
+ function httpChatModel(options) {
9357
9589
  const baseUrl = options.baseUrl.trim().replace(/\/+$/, "");
9358
9590
  const model = options.model.trim();
9359
- if (baseUrl === "") throw badClient("the agent base URL must not be empty");
9360
- if (model === "") throw badClient("the agent model name must not be empty");
9591
+ if (baseUrl === "") throw badClient("the model base URL must not be empty");
9592
+ if (model === "") throw badClient("the model name must not be empty");
9361
9593
  const url = `${baseUrl}/chat/completions`;
9362
9594
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS4;
9363
- const shape = options.shape ?? GUI_TURN;
9364
9595
  return {
9365
- async decide(turn) {
9596
+ async complete(prompt) {
9366
9597
  const body = {
9367
9598
  model,
9368
- messages: [{ role: "user", content: shape.prompt(turn) }],
9369
- // The answer is JSON the loop parses, so the endpoint is asked for JSON
9370
- // rather than for prose that happens to contain some.
9599
+ messages: [{ role: "user", content: prompt }],
9600
+ // The answers this package reads are JSON, so the endpoint is asked
9601
+ // for JSON rather than for prose that happens to contain some.
9371
9602
  response_format: { type: "json_object" }
9372
9603
  };
9373
9604
  let response;
@@ -9383,14 +9614,14 @@ function httpAgentModel(options) {
9383
9614
  });
9384
9615
  } catch (err) {
9385
9616
  throw new OhosPerfError(
9386
- `the agent endpoint could not be reached: ${err.message}`,
9617
+ `the model endpoint could not be reached: ${err.message}`,
9387
9618
  { code: "AGENT_UNREACHABLE", cause: err }
9388
9619
  );
9389
9620
  }
9390
9621
  const text2 = await response.text();
9391
9622
  if (!response.ok) {
9392
9623
  throw new OhosPerfError(
9393
- `the agent endpoint answered ${response.status}: ${text2.slice(0, EXCERPT_CHARS)}`,
9624
+ `the model endpoint answered ${response.status}: ${text2.slice(0, EXCERPT_CHARS)}`,
9394
9625
  { code: "AGENT_HTTP_ERROR" }
9395
9626
  );
9396
9627
  }
@@ -9400,7 +9631,16 @@ function httpAgentModel(options) {
9400
9631
  code: "AGENT_BAD_RESPONSE"
9401
9632
  });
9402
9633
  }
9403
- return shape.parse(content);
9634
+ return content;
9635
+ }
9636
+ };
9637
+ }
9638
+ function httpAgentModel(options) {
9639
+ const shape = options.shape ?? GUI_TURN;
9640
+ const chat = httpChatModel(options);
9641
+ return {
9642
+ async decide(turn) {
9643
+ return shape.parse(await chat.complete(shape.prompt(turn)));
9404
9644
  }
9405
9645
  };
9406
9646
  }
@@ -9415,6 +9655,163 @@ function safeJson(text2) {
9415
9655
  }
9416
9656
  }
9417
9657
 
9658
+ // src/scenario/llm-strategy.ts
9659
+ var HISTORY_LIMIT = 8;
9660
+ var EXCERPT_CHARS2 = 200;
9661
+ function refusal(detail11) {
9662
+ return { action: "refused", detail: detail11 };
9663
+ }
9664
+ function explorationPrompt(turn) {
9665
+ const elements = turn.elements.length === 0 ? "(no element is left to choose on this screen)" : turn.elements.map(
9666
+ (element) => `${element.index}. ${element.type} ${JSON.stringify(oneLine2(element.text))} bounds=${element.bounds} depth=${element.depth}`
9667
+ ).join("\n");
9668
+ const history = turn.history.length === 0 ? "(no steps yet)" : turn.history.join("\n");
9669
+ const actions = [
9670
+ "tap",
9671
+ ...turn.canScroll ? ["scroll"] : [],
9672
+ ...turn.canBack ? ["back"] : [],
9673
+ "stop"
9674
+ ];
9675
+ const formats = [
9676
+ ' {"action": "tap", "element": 0, "reason": "why this element"}',
9677
+ ...turn.canScroll ? [' {"action": "scroll", "direction": "up", "reason": "why"}'] : [],
9678
+ ...turn.canBack ? [' {"action": "back", "reason": "why"}'] : [],
9679
+ ' {"action": "stop", "reason": "why"}'
9680
+ ];
9681
+ return [
9682
+ `You are exploring the OHOS app ${turn.app ?? "(the app on screen)"} to reach as many distinct pages as possible.`,
9683
+ `Step ${turn.step + 1} of ${turn.maxSteps}.`,
9684
+ "",
9685
+ "The current screen, one node per line:",
9686
+ turn.screen,
9687
+ "",
9688
+ "Elements you may choose, with their index:",
9689
+ elements,
9690
+ "",
9691
+ "Steps so far:",
9692
+ history,
9693
+ "",
9694
+ `Available actions: ${actions.join(", ")}.`,
9695
+ "Answer with one JSON object and nothing else:",
9696
+ ...formats,
9697
+ "An element index that was not offered is refused."
9698
+ ].join("\n");
9699
+ }
9700
+ function oneLine2(text2) {
9701
+ return text2.replace(/\s+/g, " ").trim();
9702
+ }
9703
+ function unfence2(text2) {
9704
+ const match = /^\s*```(?:json)?\s*\n([\s\S]*?)\n\s*```\s*$/.exec(text2);
9705
+ return match === null ? text2 : match[1];
9706
+ }
9707
+ var ACTIONS = /* @__PURE__ */ new Set(["tap", "scroll", "back", "stop"]);
9708
+ function parseStrategyAnswer(content) {
9709
+ let parsed;
9710
+ try {
9711
+ parsed = JSON.parse(unfence2(content.trim()));
9712
+ } catch {
9713
+ return refusal(
9714
+ `the model's answer is not JSON: ${JSON.stringify(content.slice(0, EXCERPT_CHARS2))}`
9715
+ );
9716
+ }
9717
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
9718
+ return refusal("the model's answer is not a JSON object");
9719
+ }
9720
+ const record = parsed;
9721
+ const action = record["action"];
9722
+ if (typeof action !== "string" || !ACTIONS.has(action)) {
9723
+ return refusal(
9724
+ `the model's answer must have an "action" of tap, scroll, back or stop (got ${JSON.stringify(action)})`
9725
+ );
9726
+ }
9727
+ const reason = typeof record["reason"] === "string" ? record["reason"] : "";
9728
+ switch (action) {
9729
+ case "tap": {
9730
+ const element = record["element"];
9731
+ if (typeof element !== "number" || !Number.isSafeInteger(element) || element < 0) {
9732
+ return refusal(
9733
+ `the model's "element" must be a non-negative integer (got ${JSON.stringify(element)})`
9734
+ );
9735
+ }
9736
+ return { action: "tap", element, reason };
9737
+ }
9738
+ case "scroll": {
9739
+ const direction = record["direction"];
9740
+ if (direction !== "up" && direction !== "down") {
9741
+ return refusal(
9742
+ `the model's scroll "direction" must be up or down (got ${JSON.stringify(direction)})`
9743
+ );
9744
+ }
9745
+ return { action: "scroll", direction, reason };
9746
+ }
9747
+ case "back":
9748
+ return { action: "back", reason };
9749
+ default:
9750
+ return { action: "stop", reason };
9751
+ }
9752
+ }
9753
+ function strategyTurn(context) {
9754
+ return {
9755
+ ...context.app === void 0 ? {} : { app: context.app },
9756
+ step: context.step,
9757
+ maxSteps: context.maxSteps,
9758
+ screen: renderTree(context.screen),
9759
+ elements: context.candidates.map((candidate, index) => ({
9760
+ index,
9761
+ type: candidate.type,
9762
+ text: candidate.text,
9763
+ bounds: candidate.bounds,
9764
+ depth: candidate.depth
9765
+ })),
9766
+ history: context.history.slice(-HISTORY_LIMIT).map(historyLine),
9767
+ canScroll: context.canScroll,
9768
+ canBack: context.canBack
9769
+ };
9770
+ }
9771
+ function historyLine(step) {
9772
+ const what = step.kind === "tap" ? `tap ${step.nodeId ?? "(unknown)"}` : step.kind;
9773
+ const why = step.reason === void 0 ? "" : ` \u2014 ${step.reason}`;
9774
+ return `${step.index + 1}. ${what} \u2192 ${step.outcome}${why}`;
9775
+ }
9776
+ function llmChooser(model) {
9777
+ return async (context) => {
9778
+ const answer = parseStrategyAnswer(
9779
+ await model.complete(explorationPrompt(strategyTurn(context)))
9780
+ );
9781
+ if (answer.action === "refused") return { kind: "refusal", detail: answer.detail };
9782
+ switch (answer.action) {
9783
+ case "tap": {
9784
+ const candidate = context.candidates[answer.element];
9785
+ if (candidate === void 0) {
9786
+ return {
9787
+ kind: "refusal",
9788
+ detail: `the model chose element ${answer.element}, but ${context.candidates.length} element(s) were offered`
9789
+ };
9790
+ }
9791
+ return { kind: "tap", identity: candidate.identity, reason: answer.reason };
9792
+ }
9793
+ case "scroll":
9794
+ if (!context.canScroll) {
9795
+ return {
9796
+ kind: "refusal",
9797
+ detail: "the model asked to scroll, but this screen has no scrollable node left to swipe"
9798
+ };
9799
+ }
9800
+ return { kind: "scroll", direction: answer.direction, reason: answer.reason };
9801
+ case "back":
9802
+ if (!context.canBack) {
9803
+ return {
9804
+ kind: "refusal",
9805
+ detail: "the model asked to go back, but the walk has no earlier page to return to"
9806
+ };
9807
+ }
9808
+ return { kind: "back", reason: answer.reason };
9809
+ default:
9810
+ return { kind: "stop", reason: answer.reason };
9811
+ }
9812
+ };
9813
+ }
9814
+
9418
9815
  // src/query/rows.ts
9419
9816
  function num(value) {
9420
9817
  if (value == null) return 0;
@@ -19564,9 +19961,9 @@ function findDuplicates(archive, inventory) {
19564
19961
  for (const file of bucket) {
19565
19962
  const entry = entriesByName.get(file.path);
19566
19963
  if (entry === void 0) continue;
19567
- const digest = sha256(archive.read(entry));
19568
- const group = byHash.get(digest);
19569
- if (group === void 0) byHash.set(digest, [file]);
19964
+ const digest2 = sha256(archive.read(entry));
19965
+ const group = byHash.get(digest2);
19966
+ if (group === void 0) byHash.set(digest2, [file]);
19570
19967
  else group.push(file);
19571
19968
  }
19572
19969
  }
@@ -20101,7 +20498,7 @@ var ROOT_CAUSE_TURN = {
20101
20498
  prompt: (turn) => turn.screen,
20102
20499
  parse(content) {
20103
20500
  try {
20104
- JSON.parse(unfence2(content));
20501
+ JSON.parse(unfence3(content));
20105
20502
  } catch {
20106
20503
  throw badResponse(
20107
20504
  `the model's answer is not JSON: ${JSON.stringify(content.slice(0, 200))}`
@@ -20110,7 +20507,7 @@ var ROOT_CAUSE_TURN = {
20110
20507
  return { done: true, reason: content };
20111
20508
  }
20112
20509
  };
20113
- function unfence2(text2) {
20510
+ function unfence3(text2) {
20114
20511
  const match = /^\s*```(?:json)?\s*\n([\s\S]*?)\n\s*```\s*$/.exec(text2);
20115
20512
  return match === null ? text2 : match[1];
20116
20513
  }
@@ -20134,7 +20531,7 @@ function confidenceOf(value) {
20134
20531
  function parseRootCauseAnswer(content, document, model) {
20135
20532
  let parsed;
20136
20533
  try {
20137
- parsed = JSON.parse(unfence2(content));
20534
+ parsed = JSON.parse(unfence3(content));
20138
20535
  } catch {
20139
20536
  throw badResponse(
20140
20537
  `the model's answer is not JSON: ${JSON.stringify(content.slice(0, 200))}`
@@ -20491,6 +20888,7 @@ export {
20491
20888
  evidence,
20492
20889
  executeAction,
20493
20890
  explorationDevice,
20891
+ explorationPrompt,
20494
20892
  explore,
20495
20893
  extractBinaries,
20496
20894
  filterEmptyFrames,
@@ -20500,14 +20898,17 @@ export {
20500
20898
  gpuPlugin,
20501
20899
  groundingVocabulary,
20502
20900
  hapSection,
20901
+ hashPageShape,
20503
20902
  hashTree,
20504
20903
  hiperfRecordCommand,
20505
20904
  httpAgentModel,
20905
+ httpChatModel,
20506
20906
  ingestScene,
20507
20907
  inspectBinary,
20508
20908
  irreversibleReason,
20509
20909
  isUnresolvedSymbol,
20510
20910
  isZip,
20911
+ llmChooser,
20511
20912
  loadCases,
20512
20913
  lookupQuery,
20513
20914
  markRegions,
@@ -20540,6 +20941,7 @@ export {
20540
20941
  parseScenario,
20541
20942
  parseSelector,
20542
20943
  parseSmapsRollup,
20944
+ parseStrategyAnswer,
20543
20945
  planNextAction,
20544
20946
  queryDefinitions,
20545
20947
  rankObservations,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ohos-perf/core",
3
- "version": "0.23.0",
3
+ "version": "0.24.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",