@sedum-dev/core 0.1.0-alpha.11 → 0.1.0-alpha.12

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
@@ -1748,10 +1748,12 @@ declare class ReusableBrowserDriver implements BrowserDriver {
1748
1748
  }
1749
1749
 
1750
1750
  declare const CACHE_FORMAT = 1;
1751
- declare const MATCHER_VERSION = 1;
1751
+ declare const MATCHER_VERSION = 5;
1752
1752
  type CacheMissReason = "absent"
1753
1753
  /** The target has no signal that can safely find it again, such as an input button. */
1754
- | "not_cacheable" | "disabled" | "ci_default" | "outside_git" | "runtime_dependent" | "format_mismatch" | "matcher_mismatch" | "corrupt" | "storage_error" | "conflict" | "target_missing" | "strong_signal_conflict" | "low_score" | "near_tie" | "candidate_set_incomplete" | "not_actionable";
1754
+ | "not_cacheable" | "disabled" | "ci_default" | "outside_git" | "runtime_dependent" | "format_mismatch" | "matcher_mismatch" | "corrupt" | "storage_error" | "conflict" | "target_missing" | "strong_signal_conflict" | "low_score" | "near_tie"
1755
+ /** Another current control may also satisfy the sentence's target description. */
1756
+ | "context_not_unique" | "candidate_set_incomplete" | "not_actionable";
1755
1757
  interface CacheEntry {
1756
1758
  readonly format: number;
1757
1759
  readonly matcher: number;
@@ -1762,6 +1764,8 @@ interface CacheEntry {
1762
1764
  readonly editable: boolean;
1763
1765
  readonly disabled: boolean;
1764
1766
  readonly path: string;
1767
+ /** Incomplete item context admitted only with unique ID and full sentence clues. */
1768
+ readonly boundedContext?: boolean;
1765
1769
  readonly digests: {
1766
1770
  readonly hook?: string;
1767
1771
  readonly id?: string;
package/dist/index.js CHANGED
@@ -1020,7 +1020,7 @@ function projectDigest(result) {
1020
1020
  // src/page-cache.ts
1021
1021
  import { createHmac } from "crypto";
1022
1022
  var CACHE_FORMAT = 1;
1023
- var MATCHER_VERSION = 1;
1023
+ var MATCHER_VERSION = 5;
1024
1024
  var HASH = /^[a-f0-9]{64}$/u;
1025
1025
  var DIGEST_FIELDS = ["hook", "id", "name", "label", "href"];
1026
1026
  function validDigest(value) {
@@ -1054,6 +1054,7 @@ var ENTRY_VALIDATORS = [
1054
1054
  (item) => typeof item.inputType === "string",
1055
1055
  (item) => typeof item.editable === "boolean",
1056
1056
  (item) => typeof item.disabled === "boolean",
1057
+ (item) => item.boundedContext === void 0 || typeof item.boundedContext === "boolean",
1057
1058
  (item) => validDigests(item.digests)
1058
1059
  ];
1059
1060
  function validEntry(value) {
@@ -1085,7 +1086,23 @@ function pageKey(key, route, operation, sentence) {
1085
1086
  function words(value) {
1086
1087
  return normalizeSignal(value).toLowerCase().match(/\p{L}[\p{L}\p{N}]*/gu) ?? [];
1087
1088
  }
1088
- function contextClues(sentence, label) {
1089
+ function controlNoun(tokens, index, name, role) {
1090
+ if (!["button", "link"].includes(role)) return false;
1091
+ if (tokens[index] !== role || name.length === 0) return false;
1092
+ if (index < name.length) return false;
1093
+ return tokens.slice(index - name.length, index).join(" ") === name.join(" ");
1094
+ }
1095
+ function contestedControlNoun(sentence, candidate, candidates) {
1096
+ const name = words(candidate.name);
1097
+ if (name.includes(candidate.role)) return false;
1098
+ const tokens = words(sentence.replace(/\{\{[^{}]+\}\}/gu, " "));
1099
+ if (!tokens.some((_, index) => controlNoun(tokens, index, name, candidate.role)))
1100
+ return false;
1101
+ return candidates.some(
1102
+ (other) => other.ref !== candidate.ref && other.role === candidate.role && words(other.name).includes(candidate.role)
1103
+ );
1104
+ }
1105
+ function contextClues(sentence, label, role) {
1089
1106
  const labelWords = new Set(words(label));
1090
1107
  const commands = /* @__PURE__ */ new Set([
1091
1108
  "add",
@@ -1111,13 +1128,17 @@ function contextClues(sentence, label) {
1111
1128
  "input",
1112
1129
  "box"
1113
1130
  ]);
1114
- return words(sentence.replace(/\{\{[^{}]+\}\}/gu, " ")).filter(
1115
- (word) => Array.from(word).length >= 3 && !labelWords.has(word) && !commands.has(word)
1131
+ const tokens = words(sentence.replace(/\{\{[^{}]+\}\}/gu, " "));
1132
+ const name = words(label);
1133
+ return tokens.filter(
1134
+ (word, index) => !controlNoun(tokens, index, name, role) && Array.from(word).length >= 3 && !labelWords.has(word) && !commands.has(word)
1116
1135
  );
1117
1136
  }
1118
- function hasTargetContext(sentence, label, context) {
1137
+ function hasTargetContext(sentence, candidate, context) {
1119
1138
  const contextWords = new Set(words(context));
1120
- return contextClues(sentence, label).some((word) => contextWords.has(word));
1139
+ return contextClues(sentence, candidate.name, candidate.role).some(
1140
+ (word) => contextWords.has(word)
1141
+ );
1121
1142
  }
1122
1143
  function unsafeRole(candidate) {
1123
1144
  if (candidate.role === "") return false;
@@ -1154,22 +1175,55 @@ function contextualCandidate(request) {
1154
1175
  if (!candidate.signals.contextComplete) return false;
1155
1176
  const peer = candidate.peers[0];
1156
1177
  if (!peer || isWeakPeer(peer)) return false;
1157
- return hasTargetContext(sentence, candidate.name, peer);
1178
+ return hasTargetContext(sentence, candidate, peer);
1158
1179
  }
1159
1180
  function hasStableSignal(candidate) {
1160
1181
  if (candidate.signals.hook) return true;
1161
1182
  if (candidate.signals.id) return true;
1162
1183
  return !!candidate.signals.name && !!candidate.name;
1163
1184
  }
1185
+ function boundedPeer(candidate) {
1186
+ const peer = candidate.peers[0];
1187
+ if (!peer) return;
1188
+ if (isWeakPeer(peer)) return;
1189
+ if (codePoints(peer) >= PEER_LIMIT) return;
1190
+ return peer;
1191
+ }
1192
+ function fullContextMatch(sentence, candidate) {
1193
+ const peer = boundedPeer(candidate);
1194
+ if (!peer) return false;
1195
+ const clues = contextClues(sentence, candidate.name, candidate.role);
1196
+ const context = new Set(words(peer));
1197
+ return clues.length > 0 && clues.every((clue) => context.has(clue));
1198
+ }
1199
+ function boundedContextCandidate(candidate, candidates, sentence) {
1200
+ if (candidate.tag !== "button" || !candidate.signals.id) return false;
1201
+ if (!fullContextMatch(sentence, candidate)) return false;
1202
+ const sameId = candidates.filter(
1203
+ (other) => other.signals.id === candidate.signals.id
1204
+ );
1205
+ const sameNamed = candidates.filter(
1206
+ (other) => normalizeSignal(other.name).toLowerCase() === normalizeSignal(candidate.name).toLowerCase() && other.role === candidate.role
1207
+ );
1208
+ if (sameNamed.some((other) => !boundedPeer(other))) return false;
1209
+ const sameContext = sameNamed.filter(
1210
+ (other) => fullContextMatch(sentence, other)
1211
+ );
1212
+ return sameId.length === 1 && sameContext.length === 1;
1213
+ }
1214
+ function unqualifiedIdentity(request) {
1215
+ return !repeatedCandidate(request.candidate, request.eligible) && contextClues(
1216
+ request.sentence,
1217
+ request.candidate.name,
1218
+ request.candidate.role
1219
+ ).length === 0 && hasStableSignal(request.candidate);
1220
+ }
1164
1221
  function assertDistinguishable(request) {
1165
1222
  const { candidate, eligible, sentence } = request;
1166
1223
  if (contextualCandidate(request)) return;
1167
- if (repeatedCandidate(candidate, eligible))
1168
- throw new Error("candidate_not_distinguishable");
1169
- if (contextClues(sentence, candidate.name).length > 0)
1170
- throw new Error("candidate_not_distinguishable");
1171
- if (!hasStableSignal(candidate))
1172
- throw new Error("candidate_not_distinguishable");
1224
+ if (boundedContextCandidate(candidate, eligible.candidates, sentence)) return;
1225
+ if (unqualifiedIdentity(request)) return;
1226
+ throw new Error("candidate_not_distinguishable");
1173
1227
  }
1174
1228
  function digestField(field, value, key) {
1175
1229
  return value ? { [field]: keyedDigest(key, value) } : {};
@@ -1177,6 +1231,7 @@ function digestField(field, value, key) {
1177
1231
  function createEntry(request) {
1178
1232
  const { candidate, key, operation, route, sentence } = request;
1179
1233
  const signals = candidate.signals;
1234
+ const boundedContext = !contextualCandidate(request) && boundedContextCandidate(candidate, request.eligible.candidates, sentence);
1180
1235
  return {
1181
1236
  format: CACHE_FORMAT,
1182
1237
  matcher: MATCHER_VERSION,
@@ -1187,6 +1242,7 @@ function createEntry(request) {
1187
1242
  editable: candidate.editable,
1188
1243
  disabled: candidate.disabled,
1189
1244
  path: signals.path,
1245
+ ...boundedContext ? { boundedContext: true } : {},
1190
1246
  digests: {
1191
1247
  ...digestField("hook", signals.hook, key),
1192
1248
  ...digestField("id", signals.id, key),
@@ -1336,12 +1392,23 @@ function rankedResult(ranked) {
1336
1392
  if (miss) return { hit: false, reason: miss };
1337
1393
  return { hit: true, candidate: best.candidate };
1338
1394
  }
1395
+ function contextResult(request, result) {
1396
+ if (!result.hit) return result;
1397
+ if (contestedControlNoun(request.sentence, result.candidate, request.candidates))
1398
+ return { hit: false, reason: "context_not_unique" };
1399
+ if (!request.entry?.boundedContext) return result;
1400
+ return boundedContextCandidate(
1401
+ result.candidate,
1402
+ request.candidates,
1403
+ request.sentence
1404
+ ) ? result : { hit: false, reason: "context_not_unique" };
1405
+ }
1339
1406
  function match(request) {
1340
1407
  const miss = entryMiss(request);
1341
1408
  if (miss) return { hit: false, reason: miss };
1342
1409
  if (!request.complete)
1343
1410
  return { hit: false, reason: "candidate_set_incomplete" };
1344
- return rankedResult(rankedCandidates(request));
1411
+ return contextResult(request, rankedResult(rankedCandidates(request)));
1345
1412
  }
1346
1413
  function matchEntry(...args) {
1347
1414
  const [
@@ -2528,7 +2595,6 @@ async function executeStep(page, command, options = {}) {
2528
2595
  );
2529
2596
  if (aimed.aim.document !== before.document || aimed.aim.route !== before.route || aimed.aim.revision !== before.revision)
2530
2597
  throw new StepExecutionError(op, "stale", phase);
2531
- const timeoutMs = remaining(8e3, phase);
2532
2598
  if (options.beforeAction) {
2533
2599
  await active(
2534
2600
  options.beforeAction(aimed.aim.box ?? null, target.version)
@@ -2538,6 +2604,7 @@ async function executeStep(page, command, options = {}) {
2538
2604
  }
2539
2605
  if (options.signal?.aborted)
2540
2606
  throw new StepExecutionError(op, "canceled", phase);
2607
+ const timeoutMs = remaining(8e3, phase);
2541
2608
  phase = "post_dispatch";
2542
2609
  const result = await active(
2543
2610
  page.clickRef(aimed.aim, {
@@ -8898,6 +8965,116 @@ async function executeAssertion(context) {
8898
8965
  );
8899
8966
  }
8900
8967
 
8968
+ // src/flow-runner/action-recovery.ts
8969
+ import { setTimeout as delay2 } from "timers/promises";
8970
+ async function refreshAfterQuiet(page, remainingMs, signal, locate) {
8971
+ const deadline = performance.now() + remainingMs;
8972
+ const quiet = await quietPage(page, 80, Math.min(4e3, remainingMs)).catch(
8973
+ () => ({ quiet: false })
8974
+ );
8975
+ if (!quiet.quiet) return void 0;
8976
+ if (signal.aborted || performance.now() >= deadline) return void 0;
8977
+ return locate(signal, deadline - performance.now());
8978
+ }
8979
+ function isNoMatch(option) {
8980
+ return option?.name === "(no match)" && option.role === "";
8981
+ }
8982
+ function pendingTarget(result) {
8983
+ if (result.kind === "resolved") return false;
8984
+ if (["none", "no_candidates"].includes(result.reason)) return true;
8985
+ const [first, second] = result.diagnostic.topOptions;
8986
+ return result.reason === "ambiguous" && result.diagnostic.gate === "low_confidence_or_margin" && isNoMatch(second) && (first?.probability ?? 1) - second.probability < 0.2;
8987
+ }
8988
+ async function performWithRecovery(options) {
8989
+ await new ActionAttempts(options).run();
8990
+ }
8991
+ var ActionAttempts = class {
8992
+ constructor(options) {
8993
+ this.options = options;
8994
+ const budget = options.timeoutMs ?? 8e3;
8995
+ this.deadline = this.started + budget;
8996
+ const timeout = AbortSignal.timeout(Math.max(1, Math.ceil(budget)));
8997
+ this.signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
8998
+ this.last = new StepExecutionError(options.op, "timeout", "pre_dispatch");
8999
+ }
9000
+ options;
9001
+ started = performance.now();
9002
+ deadline;
9003
+ signal;
9004
+ last;
9005
+ attempts = 0;
9006
+ remaining() {
9007
+ return this.signal.aborted ? 0 : Math.max(0, this.deadline - performance.now());
9008
+ }
9009
+ async run() {
9010
+ while (this.remaining() > 0) {
9011
+ if (!await this.prepareRetry()) continue;
9012
+ if (this.remaining() <= 0) break;
9013
+ if (await this.perform()) return;
9014
+ }
9015
+ throw this.exhausted();
9016
+ }
9017
+ async prepareRetry() {
9018
+ if (this.attempts === 0) return true;
9019
+ if (!this.options.allowed()) throw this.last;
9020
+ await this.pause();
9021
+ if (this.remaining() <= 0) return false;
9022
+ if (this.last.code !== "stale") return true;
9023
+ return this.refresh();
9024
+ }
9025
+ async refresh() {
9026
+ const refreshed = await this.options.refresh(this.remaining(), this.signal);
9027
+ if (!refreshed && this.options.op !== "click") throw this.last;
9028
+ return refreshed;
9029
+ }
9030
+ async pause() {
9031
+ await delay2(Math.min(100, this.remaining()), void 0, {
9032
+ signal: this.signal
9033
+ }).catch(() => void 0);
9034
+ }
9035
+ retryable(error2) {
9036
+ if (!(error2 instanceof StepExecutionError)) return false;
9037
+ if (!error2.retryable || !this.options.allowed()) return false;
9038
+ if (this.options.op !== "click")
9039
+ return this.attempts === 0 && error2.code === "stale";
9040
+ return ["stale", "not_actionable"].includes(error2.code);
9041
+ }
9042
+ async perform() {
9043
+ try {
9044
+ await this.options.perform(this.remaining());
9045
+ return true;
9046
+ } catch (error2) {
9047
+ if (!this.retryable(error2)) throw error2;
9048
+ this.last = error2;
9049
+ this.attempts++;
9050
+ return false;
9051
+ }
9052
+ }
9053
+ exhausted() {
9054
+ if (this.options.signal?.aborted)
9055
+ return new StepExecutionError(
9056
+ this.options.op,
9057
+ "canceled",
9058
+ "pre_dispatch"
9059
+ );
9060
+ return this.refusalAfterWait();
9061
+ }
9062
+ refusalAfterWait() {
9063
+ const op = this.options.op;
9064
+ const waitedMs = Math.round(performance.now() - this.started);
9065
+ return new StepExecutionError(
9066
+ op,
9067
+ this.last.code,
9068
+ "pre_dispatch",
9069
+ [
9070
+ ...this.last.callLog,
9071
+ `Waited ${waitedMs} ms for a ready target; no input dispatched.`
9072
+ ],
9073
+ `${op} failed: ${this.last.code} after waiting ${waitedMs} ms for a ready target.`
9074
+ );
9075
+ }
9076
+ };
9077
+
8901
9078
  // src/locator/observation.ts
8902
9079
  var LocateRetryError = class extends Error {
8903
9080
  constructor(priorCalls) {
@@ -9433,7 +9610,7 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries, pr
9433
9610
  );
9434
9611
  const cacheSentence = step.op === "type" && typeOperand && "operand" in typeOperand ? `${step.text.slice(0, typeOperand.operand.start)}${step.text.slice(typeOperand.operand.end)}`.replace(/\s+/gu, " ").trim() : step.text;
9435
9612
  let visionAttempted = false;
9436
- const locate = () => resolveTarget(page, dependencies.provider, {
9613
+ const locate = (signal = dependencies.signal, timeoutMs) => resolveTarget(page, dependencies.provider, {
9437
9614
  // Disabling transmission or exhausting the request budget must not
9438
9615
  // restore permissive repeated-member picks.
9439
9616
  ...dependencies.visionResolver && step.op === "click" ? { repeatedMember: {} } : {},
@@ -9451,7 +9628,8 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries, pr
9451
9628
  runtimeDependent,
9452
9629
  ...dependencies.locatorCache ? { cache: dependencies.locatorCache } : {},
9453
9630
  projectText: (text) => redactOpaqueText(text, opaqueEntries),
9454
- ...dependencies.signal ? { signal: dependencies.signal } : {}
9631
+ ...signal ? { signal } : {},
9632
+ ...timeoutMs === void 0 ? {} : { timeoutMs }
9455
9633
  });
9456
9634
  let resolved;
9457
9635
  try {
@@ -9497,7 +9675,7 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries, pr
9497
9675
  }
9498
9676
  );
9499
9677
  }
9500
- const missing = (result) => result.kind !== "resolved" && (result.reason === "none" || result.reason === "no_candidates");
9678
+ const missing = (result) => !visionAttempted && pendingTarget(result);
9501
9679
  const actionGraceMs = dependencies.verifyGraceMs ?? 0;
9502
9680
  if (missing(resolved) && actionGraceMs > 0) {
9503
9681
  const deadline = performance.now() + actionGraceMs;
@@ -9591,7 +9769,8 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries, pr
9591
9769
  ) : void 0;
9592
9770
  let replayFrame;
9593
9771
  let targetBox = null;
9594
- const performAction = () => executeStep(page, command, {
9772
+ const performAction = (timeoutMs) => executeStep(page, command, {
9773
+ timeoutMs,
9595
9774
  ...dependencies.signal ? { signal: dependencies.signal } : {},
9596
9775
  ...report?.replay ? {
9597
9776
  beforeAction: async (box, aimVersion) => {
@@ -9606,35 +9785,48 @@ async function executeSentence(page, step, dependencies, data, opaqueEntries, pr
9606
9785
  } : {}
9607
9786
  });
9608
9787
  try {
9609
- try {
9610
- await performAction();
9611
- } catch (error2) {
9612
- if (!(error2 instanceof StepExecutionError) || error2.code !== "stale" || !error2.retryable || visionAttempted)
9613
- throw error2;
9614
- const priorCalls = resolved.calls;
9615
- replayFrame = void 0;
9616
- targetBox = null;
9617
- const quiet2 = await quietPage(page, 80, 4e3).catch(() => ({
9618
- quiet: false
9619
- }));
9620
- if (!quiet2.quiet) throw error2;
9621
- const retried = await locate();
9622
- if (retried.kind !== "resolved") {
9623
- resolved = { ...resolved, calls: [...priorCalls, ...retried.calls] };
9624
- throw error2;
9788
+ let observation = 1;
9789
+ await performWithRecovery({
9790
+ op: step.op,
9791
+ ...dependencies.signal ? { signal: dependencies.signal } : {},
9792
+ perform: performAction,
9793
+ allowed: () => !visionAttempted,
9794
+ refresh: async (remainingMs, signal) => {
9795
+ const priorCalls = resolved.calls;
9796
+ replayFrame = void 0;
9797
+ targetBox = null;
9798
+ const retried = await refreshAfterQuiet(
9799
+ page,
9800
+ remainingMs,
9801
+ signal,
9802
+ locate
9803
+ );
9804
+ if (!retried) return false;
9805
+ if (retried.kind !== "resolved") {
9806
+ resolved = { ...resolved, calls: [...priorCalls, ...retried.calls] };
9807
+ if (![
9808
+ "stale",
9809
+ "none",
9810
+ "no_candidates",
9811
+ "ambiguous",
9812
+ "timeout"
9813
+ ].includes(retried.reason))
9814
+ throw new Error("The target could not be resolved.");
9815
+ return false;
9816
+ }
9817
+ resolved = { ...retried, calls: [...priorCalls, ...retried.calls] };
9818
+ command = commandFor(resolved.target);
9819
+ locatedPage = report ? await reportPage(
9820
+ page,
9821
+ `${stepId}:observation:${++observation}`,
9822
+ report.privacy,
9823
+ resolved.target.driverTarget().version
9824
+ ) : void 0;
9825
+ replayFrame = void 0;
9826
+ targetBox = null;
9827
+ return true;
9625
9828
  }
9626
- resolved = { ...retried, calls: [...priorCalls, ...retried.calls] };
9627
- command = commandFor(resolved.target);
9628
- locatedPage = report ? await reportPage(
9629
- page,
9630
- `${stepId}:observation:2`,
9631
- report.privacy,
9632
- resolved.target.driverTarget().version
9633
- ) : void 0;
9634
- replayFrame = void 0;
9635
- targetBox = null;
9636
- await performAction();
9637
- }
9829
+ });
9638
9830
  let recordedLocator = resolved;
9639
9831
  if (resolved.cacheSeed && dependencies.locatorCache?.key) {
9640
9832
  const seed = resolved.cacheSeed;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sedum-dev/core",
3
- "version": "0.1.0-alpha.11",
3
+ "version": "0.1.0-alpha.12",
4
4
  "repository": "https://github.com/sedum-dev/sedum",
5
5
  "publishConfig": {
6
6
  "access": "public"