@thinkrun/cli 0.1.39 → 0.1.42

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 (100) hide show
  1. package/README.md +27 -0
  2. package/dist/bin/thinkrun.js +9 -2
  3. package/dist/bin/thinkrun.js.map +1 -1
  4. package/dist/scripts/browse.sh +40 -7
  5. package/dist/shared/analysis-plans.d.ts +10 -0
  6. package/dist/shared/analysis-plans.js +12 -0
  7. package/dist/shared/batch-steps.d.ts +49 -0
  8. package/dist/shared/batch-steps.js +171 -0
  9. package/dist/shared/batch-steps.test.js +127 -0
  10. package/dist/shared/group-binding-key.d.ts +5 -0
  11. package/dist/shared/group-binding-key.js +15 -0
  12. package/dist/shared/group-binding-key.test.js +50 -0
  13. package/dist/shared/issue-report.d.ts +10 -0
  14. package/dist/shared/issue-report.js +126 -0
  15. package/dist/shared/issue-report.test.ts +110 -0
  16. package/dist/shared/native-type-budget.d.ts +16 -0
  17. package/dist/shared/native-type-budget.js +28 -0
  18. package/dist/shared/navigation-retry.d.ts +2 -0
  19. package/dist/shared/navigation-retry.js +26 -0
  20. package/dist/shared/navigation-retry.test.js +25 -0
  21. package/dist/shared/onboarding-drips.d.ts +13 -0
  22. package/dist/shared/onboarding-drips.js +100 -0
  23. package/dist/shared/onboarding-metrics.d.ts +4 -0
  24. package/dist/shared/onboarding-metrics.js +53 -0
  25. package/dist/shared/selector-hints.d.ts +1 -0
  26. package/dist/shared/selector-hints.js +43 -0
  27. package/dist/shared/selector-hints.test.js +31 -0
  28. package/dist/shared/slack-report.d.ts +21 -0
  29. package/dist/shared/slack-report.js +381 -0
  30. package/dist/src/adapters/cloud.d.ts +2 -0
  31. package/dist/src/adapters/cloud.d.ts.map +1 -1
  32. package/dist/src/adapters/cloud.js +112 -17
  33. package/dist/src/adapters/cloud.js.map +1 -1
  34. package/dist/src/adapters/index.d.ts.map +1 -1
  35. package/dist/src/adapters/index.js +30 -5
  36. package/dist/src/adapters/index.js.map +1 -1
  37. package/dist/src/adapters/local.d.ts +3 -0
  38. package/dist/src/adapters/local.d.ts.map +1 -1
  39. package/dist/src/adapters/local.js +52 -13
  40. package/dist/src/adapters/local.js.map +1 -1
  41. package/dist/src/commands/actions.d.ts +12 -0
  42. package/dist/src/commands/actions.d.ts.map +1 -1
  43. package/dist/src/commands/actions.js +115 -28
  44. package/dist/src/commands/actions.js.map +1 -1
  45. package/dist/src/commands/analyze.d.ts.map +1 -1
  46. package/dist/src/commands/analyze.js +29 -1
  47. package/dist/src/commands/analyze.js.map +1 -1
  48. package/dist/src/commands/audit.d.ts.map +1 -1
  49. package/dist/src/commands/audit.js +5 -4
  50. package/dist/src/commands/audit.js.map +1 -1
  51. package/dist/src/commands/cloud.d.ts.map +1 -1
  52. package/dist/src/commands/cloud.js +3 -1
  53. package/dist/src/commands/cloud.js.map +1 -1
  54. package/dist/src/commands/config.d.ts.map +1 -1
  55. package/dist/src/commands/config.js +15 -0
  56. package/dist/src/commands/config.js.map +1 -1
  57. package/dist/src/commands/evaluate-helpers.d.ts.map +1 -1
  58. package/dist/src/commands/evaluate-helpers.js +10 -2
  59. package/dist/src/commands/evaluate-helpers.js.map +1 -1
  60. package/dist/src/commands/install-skills.d.ts +27 -0
  61. package/dist/src/commands/install-skills.d.ts.map +1 -0
  62. package/dist/src/commands/install-skills.js +81 -0
  63. package/dist/src/commands/install-skills.js.map +1 -0
  64. package/dist/src/commands/install.d.ts.map +1 -1
  65. package/dist/src/commands/install.js +44 -1
  66. package/dist/src/commands/install.js.map +1 -1
  67. package/dist/src/commands/login.d.ts +3 -0
  68. package/dist/src/commands/login.d.ts.map +1 -0
  69. package/dist/src/commands/login.js +62 -0
  70. package/dist/src/commands/login.js.map +1 -0
  71. package/dist/src/commands/setup.d.ts.map +1 -1
  72. package/dist/src/commands/setup.js +8 -16
  73. package/dist/src/commands/setup.js.map +1 -1
  74. package/dist/src/config/store.d.ts.map +1 -1
  75. package/dist/src/config/store.js +1 -0
  76. package/dist/src/config/store.js.map +1 -1
  77. package/dist/src/local-bridge-timing.d.ts +3 -0
  78. package/dist/src/local-bridge-timing.d.ts.map +1 -1
  79. package/dist/src/local-bridge-timing.js +3 -0
  80. package/dist/src/local-bridge-timing.js.map +1 -1
  81. package/dist/src/session/account-guidance.d.ts +10 -0
  82. package/dist/src/session/account-guidance.d.ts.map +1 -0
  83. package/dist/src/session/account-guidance.js +32 -0
  84. package/dist/src/session/account-guidance.js.map +1 -0
  85. package/dist/src/session/browser-login.d.ts +6 -0
  86. package/dist/src/session/browser-login.d.ts.map +1 -0
  87. package/dist/src/session/browser-login.js +83 -0
  88. package/dist/src/session/browser-login.js.map +1 -0
  89. package/dist/src/types.d.ts +3 -1
  90. package/dist/src/types.d.ts.map +1 -1
  91. package/dist/src/utils.d.ts +9 -3
  92. package/dist/src/utils.d.ts.map +1 -1
  93. package/dist/src/utils.js +24 -3
  94. package/dist/src/utils.js.map +1 -1
  95. package/dist/src/working-location.d.ts +1 -1
  96. package/dist/src/working-location.d.ts.map +1 -1
  97. package/dist/src/working-location.js +89 -67
  98. package/dist/src/working-location.js.map +1 -1
  99. package/package.json +3 -2
  100. package/skills/thinkrun/SKILL.md +66 -0
package/README.md CHANGED
@@ -4,6 +4,22 @@ CLI for ThinkRun browser automation.
4
4
 
5
5
  `thinkrun` is the single CLI for controlling browsers via ThinkRun cloud and local (native host) infrastructure.
6
6
 
7
+ ## Try ThinkRun in your own browser
8
+
9
+ You can control a Chrome tab locally before creating an account.
10
+
11
+ 1. Install the [ThinkRun Chrome extension](https://chromewebstore.google.com/detail/thinkrun-screen-recorder/affbcanbhbnolapiokgjnkfjccdmefmd). With the CLI, run `thinkrun setup` to install the native host. With MCP, run `npx @thinkrun/mcp install-native-host`. Open Chrome and enable or reload the extension.
12
+ 2. Use `thinkrun doctor` or `npx @thinkrun/mcp doctor` to check the connection. In the CLI, run `thinkrun tabs`, then `thinkrun attach <tabId>`. In MCP, ask your agent to attach to your chosen local tab.
13
+ 3. Give the agent a small job, such as checking that a saved item is still there after reloading the page.
14
+ 4. To save evidence, run `thinkrun login` to connect a [free ThinkRun account](https://thinkrun.ai/signup). In MCP, ask the agent to save the local session. Enable audit mode before repeating the check to capture screenshots of subsequent actions.
15
+ 5. Open the saved session in your [Activity Feed](https://thinkrun.ai/activity). Review what happened, record feedback for your agent, or prepare a GitHub issue from the evidence you choose to share.
16
+
17
+ For a hosted browser, configure a ThinkRun API key and run `thinkrun cloud start` or select cloud mode in MCP.
18
+
19
+ ### Optional onboarding metrics
20
+
21
+ To share onboarding milestones with ThinkRun, set `THINKRUN_ONBOARDING_METRICS=1` in the CLI or MCP server environment. Collection is off by default. Events contain a random installation ID, the client type, and milestones for local connection, account connection, and saving a session. Opening the generated review link can record a dashboard review using a session-specific marker. Event payloads exclude tab URLs, browser content, credentials, and account identifiers. Unset the variable or set `DO_NOT_TRACK=1` to stop sending client events.
22
+
7
23
  ## Requirements
8
24
 
9
25
  - Node.js 18+ (uses native `fetch`)
@@ -230,6 +246,17 @@ appends by default, while `--clear` uses replacement semantics. Both modes rejec
230
246
  missing, hidden, disabled, or non-editable targets instead of reporting success.
231
247
  The per-character delay must be an integer from 0 through 5000 milliseconds.
232
248
 
249
+ ### Batch
250
+
251
+ Run up to 50 actions in one call. Every step is checked first, the first failure stops the rest, and typed values are not echoed in the result.
252
+
253
+ ```bash
254
+ thinkrun batch '[{"action":"navigate","url":"https://example.com"},{"action":"fill","selector":"input[name=q]","value":"shoes"},{"action":"press","key":"Enter"},{"action":"wait_for_text","text":"results"}]'
255
+ thinkrun batch --file steps.json
256
+ ```
257
+
258
+ Actions: `navigate` (url), `click` and `hover` (selector), `fill` and `select` (selector, value), `type` (selector, text), `press` (key), `wait` (selector or ms), `wait_for_text` (text), `evaluate` (script). Check the result before relying on later page state.
259
+
233
260
  ### Waiting
234
261
 
235
262
  | Command | Description |
@@ -16,13 +16,14 @@ import { createAuditCommand } from '../src/commands/audit.js';
16
16
  import { createResetConnectionCommand } from '../src/commands/reset-connection.js';
17
17
  import { createInstallCommand } from '../src/commands/install.js';
18
18
  import { createSessionDebugCommand } from '../src/commands/session-debug.js';
19
+ import { createLoginCommand } from '../src/commands/login.js';
19
20
  import { createSetupCommand } from '../src/commands/setup.js';
20
21
  import { createAnalyzeCommand } from '../src/commands/analyze.js';
21
22
  import { createSessionsCommand } from '../src/commands/sessions.js';
22
23
  import { createReleaseCommand } from '../src/commands/release.js';
23
24
  import { createRecordingCommand } from '../src/commands/recording.js';
24
25
  import { createAgentInitCommand } from '../src/commands/agent-init.js';
25
- import { createNavigateCommand, createClickCommand, createClickAtCommand, createTypeCommand, createFillCommand, createScrollCommand, createWaitCommand, createWaitForTextCommand, createHoverCommand, createSelectCommand, createPressCommand, createBackCommand, createForwardCommand, createResumeCommand, createSnapshotCommand, createScreenshotCommand, createExtractCommand, createEvaluateCommand, createDialogCommand, createConsoleCommand, createNetworkCommand, createTabsCommand, createNewTabCommand, createCloseTabCommand, createAttachCommand, createUrlCommand, createTitleCommand, createHtmlCommand, createClearLogsCommand, createSwitchTabCommand, createFocusCommand, createNewWindowCommand, createTaskCommand, createTaskStatusCommand, createTaskCancelCommand, } from '../src/commands/actions.js';
26
+ import { createNavigateCommand, createClickCommand, createClickAtCommand, createTypeCommand, createFillCommand, createBatchCommand, createScrollCommand, createWaitCommand, createWaitForTextCommand, createHoverCommand, createSelectCommand, createPressCommand, createBackCommand, createForwardCommand, createResumeCommand, createSnapshotCommand, createScreenshotCommand, createExtractCommand, createEvaluateCommand, createDialogCommand, createConsoleCommand, createNetworkCommand, createTabsCommand, createNewTabCommand, createCloseTabCommand, createAttachCommand, createUrlCommand, createTitleCommand, createHtmlCommand, createClearLogsCommand, createSwitchTabCommand, createFocusCommand, createNewWindowCommand, createTaskCommand, createTaskStatusCommand, createTaskCancelCommand, } from '../src/commands/actions.js';
26
27
  const __filename = fileURLToPath(import.meta.url);
27
28
  const __dirname = dirname(__filename);
28
29
  function resolvePackageJsonPath() {
@@ -45,7 +46,11 @@ program
45
46
  .option('--json', 'Output in JSON format (default for non-TTY)')
46
47
  .option('--quiet', 'Suppress non-error output')
47
48
  .option('--verbose', 'Verbose output with debugging info');
48
- program.addHelpText('after', '\nDocs:\n' +
49
+ program.addHelpText('after', '\nCoding agents: run \'thinkrun install --skills\' to add the agent skill to this project.\n' +
50
+ '\nYour Chrome tabs: install the ThinkRun extension, run thinkrun setup and thinkrun doctor, then thinkrun tabs and thinkrun attach <tabId>.\n' +
51
+ ' https://chromewebstore.google.com/detail/thinkrun-screen-recorder/affbcanbhbnolapiokgjnkfjccdmefmd\n' +
52
+ ' To save and review local sessions, run thinkrun login (free account: https://thinkrun.ai/signup).\n' +
53
+ '\nDocs:\n' +
49
54
  ' https://thinkrun.ai/docs\n' +
50
55
  ' https://thinkrun.ai/llms.txt\n');
51
56
  // Activate JSON mode before any command runs if --json flag is set.
@@ -57,6 +62,7 @@ program.hook('preAction', () => {
57
62
  });
58
63
  // Add commands
59
64
  program.addCommand(createSetupCommand());
65
+ program.addCommand(createLoginCommand());
60
66
  program.addCommand(createConfigCommand());
61
67
  program.addCommand(createCloudCommand());
62
68
  program.addCommand(createCacheCommand());
@@ -73,6 +79,7 @@ program.addCommand(createClickCommand());
73
79
  program.addCommand(createClickAtCommand());
74
80
  program.addCommand(createTypeCommand());
75
81
  program.addCommand(createFillCommand());
82
+ program.addCommand(createBatchCommand());
76
83
  program.addCommand(createPressCommand());
77
84
  program.addCommand(createScrollCommand());
78
85
  program.addCommand(createHoverCommand());
@@ -1 +1 @@
1
- {"version":3,"file":"thinkrun.js","sourceRoot":"","sources":["../../bin/thinkrun.ts"],"names":[],"mappings":";AAEA;;GAEG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAC9C,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,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AC5E,yEAAyE;AACzE,wEAAwE;AACxE,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAG,gBAAgB,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAI,+BAA+B;AAC1F,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,gBAAgB,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,wCAAwC;AAEnG,kBAAkB;AAClB,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;AAE5B,mCAAmC;AACnC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;IAClC,OAAO,CAAC,UAAU,EAAE,CAAC;AACvB,CAAC"}
@@ -554,24 +554,57 @@ case "${1:-help}" in
554
554
  echo "$RESP" >&2
555
555
  exit 1
556
556
  fi
557
- # Poll until ready (max 120s for cold machine start)
558
- for i in $(seq 1 40); do
559
- STATUS=$(curl -s "${H[@]}" "$BASE/api/sessions/$SID" | jq -r '.data.status // .status // "unknown"')
557
+ # Each status GET and sleep consumes the same 120s elapsed-seconds budget.
558
+ READY_TIMEOUT_SECONDS=120
559
+ READY_MAX_POLLS=40
560
+ READY_SLEEP_SECONDS=3
561
+ READY_STARTED_SECONDS=$SECONDS
562
+ for i in $(seq 1 "$READY_MAX_POLLS"); do
563
+ READY_ELAPSED_SECONDS=$((SECONDS - READY_STARTED_SECONDS))
564
+ READY_REMAINING_SECONDS=$((READY_TIMEOUT_SECONDS - READY_ELAPSED_SECONDS))
565
+ if [ "$READY_REMAINING_SECONDS" -le 0 ]; then
566
+ break
567
+ fi
568
+ REQUEST_TIMEOUT_SECONDS="$READY_REMAINING_SECONDS"
569
+ STATUS_RESPONSE=$(curl -s --max-time "$REQUEST_TIMEOUT_SECONDS" "${H[@]}" \
570
+ "$BASE/api/sessions/$SID" 2>/dev/null || true)
571
+ READY_ELAPSED_SECONDS=$((SECONDS - READY_STARTED_SECONDS))
572
+ if [ "$READY_ELAPSED_SECONDS" -ge "$READY_TIMEOUT_SECONDS" ]; then
573
+ break
574
+ fi
575
+ CANONICAL_SESSION=$(printf '%s' "$STATUS_RESPONSE" | jq -cse 'if length != 1 then {} else .[0] as $root | if ($root | type) != "object" or $root.success == false then {} elif ($root | has("data")) then (if ($root.data | type) == "object" then $root.data else {} end) else $root end end' 2>/dev/null) || CANONICAL_SESSION='{}'
576
+ STATUS=$(printf '%s' "$CANONICAL_SESSION" | jq -r 'if (.status | type) == "string" then .status else "unknown" end' 2>/dev/null) || STATUS="unknown"
577
+ BROWSER_READY=$(printf '%s' "$CANONICAL_SESSION" | jq -r 'if (.browserReady | type) == "boolean" then (.browserReady | tostring) else "missing" end' 2>/dev/null) || BROWSER_READY="missing"
560
578
  case "$STATUS" in
561
579
  ready|active|running)
562
- echo "$SID"
563
- exit 0
580
+ if [ "$BROWSER_READY" = "true" ]; then
581
+ echo "$SID"
582
+ exit 0
583
+ fi
584
+ printf "." >&2
564
585
  ;;
565
586
  creating|provisioning|pending)
566
587
  printf "." >&2
567
- sleep 3
568
588
  ;;
569
- failed|error|terminated)
589
+ failed|error|terminated|closed|completed|cancelled)
570
590
  echo "" >&2
571
591
  echo "ERROR: Session $SID failed with status: $STATUS" >&2
572
592
  exit 1
573
593
  ;;
594
+ *)
595
+ printf "." >&2
596
+ ;;
574
597
  esac
598
+ READY_ELAPSED_SECONDS=$((SECONDS - READY_STARTED_SECONDS))
599
+ READY_REMAINING_SECONDS=$((READY_TIMEOUT_SECONDS - READY_ELAPSED_SECONDS))
600
+ if [ "$READY_REMAINING_SECONDS" -le 0 ]; then
601
+ break
602
+ fi
603
+ SLEEP_SECONDS="$READY_SLEEP_SECONDS"
604
+ if [ "$READY_REMAINING_SECONDS" -lt "$SLEEP_SECONDS" ]; then
605
+ SLEEP_SECONDS="$READY_REMAINING_SECONDS"
606
+ fi
607
+ sleep "$SLEEP_SECONDS"
575
608
  done
576
609
  echo "" >&2
577
610
  echo "ERROR: Session $SID not ready after 120s" >&2
@@ -0,0 +1,10 @@
1
+ export type AnalysisPlanId = 'pro20' | 'pro40' | 'pro80';
2
+ export declare const ANALYSIS_PLANS: {
3
+ readonly [Id in AnalysisPlanId]: {
4
+ readonly id: Id;
5
+ readonly priceUsdMonthly: number;
6
+ readonly includedHours: number;
7
+ };
8
+ };
9
+ export declare const ANALYSIS_EXTRA_MINUTE_CENTS: 5;
10
+ export declare function isAnalysisPlanId(value: unknown): value is AnalysisPlanId;
@@ -0,0 +1,12 @@
1
+ /** Monthly analysis allowances; IDs identify the purchased offer across billing and metering. */
2
+ export const ANALYSIS_PLANS = Object.freeze({
3
+ pro20: Object.freeze({ id: 'pro20', priceUsdMonthly: 19, includedHours: 2 }),
4
+ pro40: Object.freeze({ id: 'pro40', priceUsdMonthly: 39, includedHours: 10 }),
5
+ pro80: Object.freeze({ id: 'pro80', priceUsdMonthly: 79, includedHours: 25 }),
6
+ });
7
+
8
+ export const ANALYSIS_EXTRA_MINUTE_CENTS = 5;
9
+
10
+ export function isAnalysisPlanId(value) {
11
+ return typeof value === 'string' && Object.prototype.hasOwnProperty.call(ANALYSIS_PLANS, value);
12
+ }
@@ -0,0 +1,49 @@
1
+ export type BatchStep =
2
+ | { action: 'navigate'; url: string }
3
+ | { action: 'click' | 'hover'; selector: string }
4
+ | { action: 'fill' | 'select'; selector: string; value: string }
5
+ | { action: 'type'; selector: string; text: string }
6
+ | { action: 'press'; key: string }
7
+ | { action: 'wait'; selector: string; ms?: undefined }
8
+ | { action: 'wait'; ms: number; selector?: undefined }
9
+ | { action: 'wait_for_text'; text: string }
10
+ | { action: 'evaluate'; script: string };
11
+
12
+ export interface BatchStepResult {
13
+ step: number;
14
+ action: string;
15
+ success: boolean;
16
+ error?: string;
17
+ /** The step changed the page even though the batch stopped here. */
18
+ applied?: boolean;
19
+ blocked?: boolean;
20
+ handoffRequired?: boolean;
21
+ category?: string;
22
+ changed?: boolean;
23
+ matchCount?: number;
24
+ matchIndex?: number;
25
+ result?: unknown;
26
+ truncated?: boolean;
27
+ }
28
+
29
+ export interface BatchResult {
30
+ success: boolean;
31
+ total: number;
32
+ completed: number;
33
+ failedStep?: number;
34
+ notRun?: number;
35
+ steps: BatchStepResult[];
36
+ }
37
+
38
+ export declare const MAX_BATCH_STEPS: number;
39
+ export declare const MAX_BATCH_WAIT_MS: number;
40
+ export declare const MAX_BATCH_DURATION_MS: number;
41
+ export declare const BATCH_ACTIONS: string[];
42
+ export declare function validateBatchSteps(input: unknown):
43
+ | { ok: true; steps: BatchStep[] }
44
+ | { ok: false; error: string };
45
+ export declare function runBatchSteps(
46
+ steps: BatchStep[],
47
+ execute: (step: BatchStep) => Promise<unknown>,
48
+ options?: { maxDurationMs?: number; now?: () => number },
49
+ ): Promise<BatchResult>;
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Runs a fixed list of browser actions in order from a single CLI or MCP call.
3
+ * The whole list is validated before anything runs, and the first failure stops
4
+ * the rest, so a failed fill can't be followed by a submit. Results never echo
5
+ * typed values.
6
+ */
7
+ export const MAX_BATCH_STEPS = 50;
8
+ export const MAX_BATCH_WAIT_MS = 30_000;
9
+ export const MAX_BATCH_DURATION_MS = 5 * 60_000;
10
+ const MAX_RESULT_CHARS = 4_000;
11
+
12
+ const REQUIRED_FIELDS = {
13
+ navigate: ['url'],
14
+ click: ['selector'],
15
+ fill: ['selector', 'value'],
16
+ type: ['selector', 'text'],
17
+ press: ['key'],
18
+ select: ['selector', 'value'],
19
+ hover: ['selector'],
20
+ wait_for_text: ['text'],
21
+ evaluate: ['script'],
22
+ };
23
+ export const BATCH_ACTIONS = [...Object.keys(REQUIRED_FIELDS), 'wait'];
24
+
25
+ function isValidUrl(value) {
26
+ try {
27
+ new URL(value);
28
+ return true;
29
+ } catch {
30
+ return false;
31
+ }
32
+ }
33
+
34
+ function validateStep(step, index) {
35
+ const label = `Step ${index + 1}`;
36
+ if (!step || typeof step !== 'object' || Array.isArray(step)) return `${label} must be an object.`;
37
+ const { action, ...fields } = step;
38
+ if (!BATCH_ACTIONS.includes(action)) {
39
+ return `${label} has unknown action ${JSON.stringify(action)}. Use one of: ${BATCH_ACTIONS.join(', ')}.`;
40
+ }
41
+ if (action === 'wait') {
42
+ const keys = Object.keys(fields);
43
+ const validSelector = typeof fields.selector === 'string' && fields.selector.length > 0;
44
+ const validMs = Number.isInteger(fields.ms) && fields.ms >= 0 && fields.ms <= MAX_BATCH_WAIT_MS;
45
+ if (keys.length !== 1 || !(validSelector || validMs)) {
46
+ return `${label} (wait) needs either selector or ms, with ms from 0 to ${MAX_BATCH_WAIT_MS}.`;
47
+ }
48
+ return null;
49
+ }
50
+ const required = REQUIRED_FIELDS[action];
51
+ for (const field of required) {
52
+ if (typeof fields[field] !== 'string') return `${label} (${action}) needs a string ${field}.`;
53
+ }
54
+ if (action === 'navigate' && !isValidUrl(fields.url)) return `${label} (navigate) needs a valid absolute URL.`;
55
+ const extra = Object.keys(fields).find((field) => !required.includes(field));
56
+ if (extra) return `${label} (${action}) has unknown field ${JSON.stringify(extra)}.`;
57
+ return null;
58
+ }
59
+
60
+ export function validateBatchSteps(input) {
61
+ if (!Array.isArray(input) || input.length === 0) {
62
+ return { ok: false, error: 'Batch steps must be a non-empty array.' };
63
+ }
64
+ if (input.length > MAX_BATCH_STEPS) {
65
+ return { ok: false, error: `A batch can have at most ${MAX_BATCH_STEPS} steps; this one has ${input.length}.` };
66
+ }
67
+ for (let index = 0; index < input.length; index += 1) {
68
+ const error = validateStep(input[index], index);
69
+ if (error) return { ok: false, error };
70
+ }
71
+ return { ok: true, steps: input };
72
+ }
73
+
74
+ function boundedResult(value) {
75
+ if (value === undefined) return {};
76
+ const text = JSON.stringify(value);
77
+ if (text === undefined) return {};
78
+ if (text.length <= MAX_RESULT_CHARS) return { result: value };
79
+ return { result: text.slice(0, MAX_RESULT_CHARS), truncated: true };
80
+ }
81
+
82
+ /** Only evaluate results and fill match details go back, to keep the batch response small. */
83
+ function summarize(step, outcome) {
84
+ const data = outcome && typeof outcome === 'object' ? outcome : {};
85
+ if (step.action === 'evaluate') return boundedResult(data.result ?? data.data ?? data.value);
86
+ const details = data.data && typeof data.data === 'object' ? data.data : data;
87
+ const summary = {};
88
+ if (typeof details.changed === 'boolean') summary.changed = details.changed;
89
+ if (typeof details.matchCount === 'number') summary.matchCount = details.matchCount;
90
+ if (typeof details.matchIndex === 'number') summary.matchIndex = details.matchIndex;
91
+ return summary;
92
+ }
93
+
94
+ function errorText(error) {
95
+ if (error instanceof Error) return error.message;
96
+ return typeof error === 'string' ? error : 'Step failed';
97
+ }
98
+
99
+ /** A client error could quote what was typed, and batch results must not. */
100
+ function scrubTyped(message, step) {
101
+ const typed = step.value ?? step.text;
102
+ return typeof typed === 'string' && typed ? message.split(typed).join('[typed value]') : message;
103
+ }
104
+
105
+ /** Keep what tells an agent that a person has to step in, so it does not just retry. */
106
+ function handoffDetails(outcome) {
107
+ const data = outcome.data && typeof outcome.data === 'object' ? outcome.data : {};
108
+ return {
109
+ ...(data.blocked === true ? { blocked: true } : {}),
110
+ ...(typeof data.handoffRequired === 'boolean' ? { handoffRequired: data.handoffRequired } : {}),
111
+ ...(typeof data.category === 'string' ? { category: data.category } : {}),
112
+ };
113
+ }
114
+
115
+ /** A blocked action may explain itself in data rather than error. */
116
+ function failureText(outcome) {
117
+ if (typeof outcome.error === 'string') return outcome.error;
118
+ const data = outcome.data && typeof outcome.data === 'object' ? outcome.data : {};
119
+ const reason = [data.message, data.reason, data.blockedBy, data.outcome, data.code].find((value) => typeof value === 'string' && value);
120
+ if (reason) return reason;
121
+ return 'Step failed with no reason given';
122
+ }
123
+
124
+ /**
125
+ * @param {Array<Record<string, unknown>>} steps Steps accepted by validateBatchSteps.
126
+ * @param {(step: Record<string, unknown>) => Promise<unknown>} execute
127
+ * @param {{ maxDurationMs?: number, now?: () => number }} [options] The limit is checked between steps.
128
+ */
129
+ export async function runBatchSteps(steps, execute, { maxDurationMs = MAX_BATCH_DURATION_MS, now = Date.now } = {}) {
130
+ const results = [];
131
+ const deadline = now() + maxDurationMs;
132
+ for (let index = 0; index < steps.length; index += 1) {
133
+ const step = steps[index];
134
+ if (now() >= deadline) {
135
+ results.push({ step: index + 1, action: step.action, success: false, error: `Batch stopped: it reached the ${Math.round(maxDurationMs / 1000)} second limit before this step.` });
136
+ break;
137
+ }
138
+ try {
139
+ const outcome = await execute(step);
140
+ if (outcome && typeof outcome === 'object' && outcome.success === false) {
141
+ results.push({ step: index + 1, action: step.action, success: false, error: scrubTyped(failureText(outcome), step), ...handoffDetails(outcome) });
142
+ break;
143
+ }
144
+ const summary = summarize(step, outcome);
145
+ // A broad selector may have filled the wrong field, so stop before anything can submit it.
146
+ if ((step.action === 'fill' || step.action === 'type') && summary.matchCount > 1) {
147
+ results.push({
148
+ step: index + 1,
149
+ action: step.action,
150
+ success: false,
151
+ applied: true,
152
+ ...summary,
153
+ error: `The selector matched ${summary.matchCount} elements, and the value went into match ${summary.matchIndex + 1}. Stopped so nothing is submitted. Check the page, then use a more specific selector.`,
154
+ });
155
+ break;
156
+ }
157
+ results.push({ step: index + 1, action: step.action, success: true, ...summary });
158
+ } catch (error) {
159
+ results.push({ step: index + 1, action: step.action, success: false, error: scrubTyped(errorText(error), step) });
160
+ break;
161
+ }
162
+ }
163
+ const failed = results.find((result) => !result.success);
164
+ return {
165
+ success: !failed,
166
+ total: steps.length,
167
+ completed: results.filter((result) => result.success).length,
168
+ ...(failed ? { failedStep: failed.step, notRun: steps.length - results.length } : {}),
169
+ steps: results,
170
+ };
171
+ }
@@ -0,0 +1,127 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { MAX_BATCH_STEPS, runBatchSteps, validateBatchSteps } from './batch-steps.js';
3
+
4
+ describe('validateBatchSteps', () => {
5
+ test('accepts every action', () => {
6
+ const steps = [
7
+ { action: 'navigate', url: 'https://example.com' }, { action: 'click', selector: 'a' }, { action: 'fill', selector: 'i', value: '' },
8
+ { action: 'type', selector: 'i', text: 'x' }, { action: 'press', key: 'Enter' }, { action: 'select', selector: 's', value: 'v' },
9
+ { action: 'hover', selector: 'a' }, { action: 'wait', selector: 'a' }, { action: 'wait', ms: 10 }, { action: 'wait_for_text', text: 'x' },
10
+ { action: 'evaluate', script: '1+1' },
11
+ ];
12
+ expect(validateBatchSteps(steps)).toEqual({ ok: true, steps });
13
+ });
14
+
15
+ test.each([
16
+ [[], 'non-empty'],
17
+ ['x', 'non-empty'],
18
+ [[null], 'Step 1 must be an object'],
19
+ [[{ action: 'delete_everything' }], 'unknown action'],
20
+ [[{ action: 'constructor' }], 'unknown action'],
21
+ [[{ action: 'click' }], 'needs a string selector'],
22
+ [[{ action: 'fill', selector: 'a' }], 'needs a string value'],
23
+ [[{ action: 'click', selector: 'a', force: true }], 'unknown field'],
24
+ [[{ action: 'wait' }], 'selector or ms'],
25
+ [[{ action: 'wait', ms: 30_001 }], 'selector or ms'],
26
+ [[{ action: 'wait', selector: 'a', ms: 1 }], 'selector or ms'],
27
+ [[{ action: 'navigate', url: 'not a url' }], 'valid absolute URL'],
28
+ ])('rejects %j', (input, message) => {
29
+ const result = validateBatchSteps(input);
30
+ expect(result.ok).toBe(false);
31
+ expect(result.error).toContain(message);
32
+ });
33
+
34
+ test('names the bad step and enforces the limit', () => {
35
+ expect(validateBatchSteps(Array.from({ length: MAX_BATCH_STEPS }, () => ({ action: 'press', key: 'a' }))).ok).toBe(true);
36
+ expect(validateBatchSteps([{ action: 'press', key: 'a' }, { action: 'nope' }]).error).toContain('Step 2');
37
+ const tooMany = Array.from({ length: MAX_BATCH_STEPS + 1 }, () => ({ action: 'press', key: 'a' }));
38
+ expect(validateBatchSteps(tooMany).error).toContain('at most 50');
39
+ });
40
+ });
41
+
42
+ describe('runBatchSteps', () => {
43
+ test('runs steps in order and reports success', async () => {
44
+ const seen = [];
45
+ const result = await runBatchSteps([{ action: 'click', selector: 'a' }, { action: 'press', key: 'Enter' }], async (step) => { seen.push(step.action); return { success: true }; });
46
+ expect(seen).toEqual(['click', 'press']);
47
+ expect(result).toEqual({ success: true, total: 2, completed: 2, steps: [
48
+ { step: 1, action: 'click', success: true }, { step: 2, action: 'press', success: true },
49
+ ] });
50
+ });
51
+
52
+ test('stops after a thrown error, so a failed fill never reaches the submit', async () => {
53
+ const seen = [];
54
+ const result = await runBatchSteps(
55
+ [{ action: 'fill', selector: 'i', value: 'secret' }, { action: 'click', selector: 'submit' }, { action: 'press', key: 'Enter' }],
56
+ async (step) => { seen.push(step.action); throw new Error('Target is not editable: hidden input'); },
57
+ );
58
+ expect(seen).toEqual(['fill']);
59
+ expect(result).toMatchObject({ success: false, total: 3, completed: 0, failedStep: 1, notRun: 2 });
60
+ expect(result.steps[0].error).toContain('not editable');
61
+ });
62
+
63
+ test('stops after a success: false result', async () => {
64
+ const result = await runBatchSteps([{ action: 'click', selector: 'a' }, { action: 'click', selector: 'b' }], async () => ({ success: false, error: 'blocked' }));
65
+ expect(result).toMatchObject({ success: false, completed: 0, failedStep: 1, notRun: 1 });
66
+ expect(result.steps[0].error).toBe('blocked');
67
+ });
68
+
69
+ test('uses the reason from a blocked result', async () => {
70
+ const blocked = await runBatchSteps([{ action: 'click', selector: 'a' }], async () => ({ success: false, data: { outcome: 'blocked', reason: 'cookie banner' } }));
71
+ expect(blocked.steps[0].error).toBe('cookie banner');
72
+ const silent = await runBatchSteps([{ action: 'click', selector: 'a' }], async () => ({ success: false }));
73
+ expect(silent.steps[0].error).toBe('Step failed with no reason given');
74
+ });
75
+
76
+ test('keeps handoff details so an agent can stop for a person', async () => {
77
+ const result = await runBatchSteps([{ action: 'click', selector: 'a' }, { action: 'click', selector: 'b' }], async () => ({ success: false, data: { blocked: true, handoffRequired: true, category: 'login', message: 'Sign in required', password: 'x' } }));
78
+ expect(result.steps).toEqual([{ step: 1, action: 'click', success: false, error: 'Sign in required', blocked: true, handoffRequired: true, category: 'login' }]);
79
+ expect(result.notRun).toBe(1);
80
+ });
81
+
82
+ test('scrubs typed values from error messages', async () => {
83
+ const thrown = await runBatchSteps([{ action: 'fill', selector: 'i', value: 'hunter2' }], async () => { throw new Error('could not set hunter2 on i'); });
84
+ expect(thrown.steps[0].error).toBe('could not set [typed value] on i');
85
+ const returned = await runBatchSteps([{ action: 'type', selector: 'i', text: 'hunter2' }], async () => ({ success: false, error: 'bad hunter2' }));
86
+ expect(returned.steps[0].error).toBe('bad [typed value]');
87
+ });
88
+
89
+ test('stops at the time limit, between steps', async () => {
90
+ let time = 0;
91
+ const seen = [];
92
+ const result = await runBatchSteps(
93
+ [{ action: 'press', key: 'a' }, { action: 'press', key: 'b' }, { action: 'press', key: 'c' }],
94
+ async (step) => { seen.push(step.key); time += 600; return { success: true }; },
95
+ { maxDurationMs: 1000, now: () => time },
96
+ );
97
+ expect(seen).toEqual(['a', 'b']);
98
+ expect(result).toMatchObject({ success: false, completed: 2, failedStep: 3, notRun: 0 });
99
+ expect(result.steps[2].error).toContain('1 second limit');
100
+ });
101
+
102
+ test('never echoes typed values', async () => {
103
+ const result = await runBatchSteps([{ action: 'fill', selector: 'i', value: 'hunter2' }, { action: 'type', selector: 'i', text: 'hunter3' }], async () => ({ success: true, data: { changed: true, value: 'hunter2' } }));
104
+ expect(JSON.stringify(result)).not.toContain('hunter');
105
+ expect(result.steps[0]).toEqual({ step: 1, action: 'fill', success: true, changed: true });
106
+ });
107
+
108
+ test('a fill that matched several elements stops before the submit, and says it applied', async () => {
109
+ const seen = [];
110
+ const result = await runBatchSteps(
111
+ [{ action: 'fill', selector: 'form input', value: '2' }, { action: 'click', selector: 'button' }],
112
+ async (step) => { seen.push(step.action); return { success: true, data: { changed: true, matchCount: 2, matchIndex: 1 } }; },
113
+ );
114
+ expect(seen).toEqual(['fill']);
115
+ expect(result).toMatchObject({ success: false, completed: 0, failedStep: 1, notRun: 1 });
116
+ expect(result.steps[0]).toMatchObject({ applied: true, matchCount: 2, matchIndex: 1 });
117
+ expect(result.steps[0].error).toContain('match 2');
118
+ });
119
+
120
+ test('returns evaluate results and bounds large ones', async () => {
121
+ const small = await runBatchSteps([{ action: 'evaluate', script: '1' }], async () => ({ success: true, result: { total: '$10' } }));
122
+ expect(small.steps[0].result).toEqual({ total: '$10' });
123
+ const large = await runBatchSteps([{ action: 'evaluate', script: '1' }], async () => ({ success: true, data: 'x'.repeat(9000) }));
124
+ expect(large.steps[0].truncated).toBe(true);
125
+ expect(String(large.steps[0].result).length).toBe(4000);
126
+ });
127
+ });
@@ -0,0 +1,5 @@
1
+ /** Return a collision-resistant filesystem key for a caller-provided group name. */
2
+ export declare function getGroupBindingKey(group: string): string;
3
+
4
+ /** Return the historical key for read-only legacy lookup and safe cleanup. */
5
+ export declare function getLegacyGroupBindingKey(group: string): string;
@@ -0,0 +1,15 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ const GROUP_KEY_STEM_LIMIT = 64;
4
+
5
+ /** Return a collision-resistant filesystem key for a caller-provided group name. */
6
+ export function getGroupBindingKey(group) {
7
+ const stem = group.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, GROUP_KEY_STEM_LIMIT);
8
+ const digest = createHash('sha256').update(Buffer.from(group, 'utf16le')).digest('hex');
9
+ return `${stem}~${digest}`;
10
+ }
11
+
12
+ /** Return the historical key for read-only legacy lookup and safe cleanup. */
13
+ export function getLegacyGroupBindingKey(group) {
14
+ return group.replace(/[^A-Za-z0-9_-]/g, '_') || 'default';
15
+ }
@@ -0,0 +1,50 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { createHash } from 'node:crypto';
3
+ import { getGroupBindingKey, getLegacyGroupBindingKey } from './group-binding-key.js';
4
+
5
+ describe('group binding keys', () => {
6
+ test('puts every name in a bounded hashed namespace', () => {
7
+ for (const group of ['agent_42-team', 'a'.repeat(240), 'a'.repeat(241)]) {
8
+ const key = getGroupBindingKey(group);
9
+ expect(key).not.toBe(group);
10
+ expect(key).toMatch(/^[A-Za-z0-9_-]*~[a-f0-9]{64}$/);
11
+ expect(key.length).toBeLessThanOrEqual(129);
12
+ }
13
+ });
14
+
15
+ test('case-folding variants get distinct keys on case-insensitive filesystems', () => {
16
+ const keys = ['Team', 'team', 'TEAM'].map(getGroupBindingKey);
17
+ expect(new Set(keys).size).toBe(3);
18
+ });
19
+
20
+ test('Windows device basenames are hashed into valid non-device filenames', () => {
21
+ for (const group of ['con', 'prn', 'aux', 'nul', 'com1', 'com9', 'lpt1', 'lpt9']) {
22
+ const key = getGroupBindingKey(group);
23
+ expect(key).not.toBe(group);
24
+ expect(key).toMatch(/^[a-z0-9_-]*~[a-f0-9]{64}$/);
25
+ expect(key).not.toMatch(/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/);
26
+ }
27
+ });
28
+
29
+ test('separates names that collided under the historical sanitizer', () => {
30
+ expect(getLegacyGroupBindingKey('a b')).toBe(getLegacyGroupBindingKey('a_b'));
31
+ expect(getGroupBindingKey('a b')).not.toBe(getGroupBindingKey('a_b'));
32
+ });
33
+
34
+ test('hashes Unicode and lone surrogate code units distinctly within the path bound', () => {
35
+ for (const group of ['研究', '\uD800', '\uDC00', 'x'.repeat(400) + ' /unsafe']) {
36
+ const key = getGroupBindingKey(group);
37
+ const expectedHash = createHash('sha256').update(Buffer.from(group, 'utf16le')).digest('hex');
38
+ expect(key.endsWith(`~${expectedHash}`)).toBe(true);
39
+ expect(key.length).toBeLessThanOrEqual(129);
40
+ expect(key).toMatch(/^[A-Za-z0-9_-]*~[a-f0-9]{64}$/);
41
+ }
42
+ expect(getGroupBindingKey('\uD800')).not.toBe(getGroupBindingKey('\uDC00'));
43
+ });
44
+
45
+ test('empty input hashes independently of the legacy default alias', () => {
46
+ expect(getLegacyGroupBindingKey('')).toBe('default');
47
+ expect(getGroupBindingKey('')).not.toBe('default');
48
+ expect(getGroupBindingKey('')).toMatch(/^~[a-f0-9]{64}$/);
49
+ });
50
+ });
@@ -0,0 +1,10 @@
1
+ export const ISSUE_REPORT_VERSION: 1;
2
+ export const REPORT_BODY_LIMIT: number;
3
+ export interface ReportSelection { feedbackIds: string[]; observationIds: string[]; suggestionIds: string[] }
4
+ export interface IssueReport { version: 1; source: { sourceType: string; sourceId?: string; shareToken?: string; schemaVersion: string; shareUrl: string }; selection: ReportSelection; title: string; body: string }
5
+ export type IssueReportScope = { kind: 'combined' } | { kind: 'issue'; issueId: string };
6
+ export interface IdentifiedReportIssue { id: string; title: string; description: string; timestampMs?: number; selection: ReportSelection; evidenceRefs: Array<{ type?: string; index?: number; timestampMs?: number; startMs?: number; endMs?: number; [key: string]: unknown }>; expectedBehavior: string }
7
+ export function getIssueReportScopes(bundle: unknown): IdentifiedReportIssue[];
8
+ export function durableShareUrl(value: string): string;
9
+ export function buildIssueReport(bundle: unknown, options?: { sourceUrl?: string; scope?: IssueReportScope; selection?: Partial<ReportSelection> }): IssueReport;
10
+ export function serializeIssueReport(report: Pick<IssueReport, 'title' | 'body'>): string;