@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
@@ -7,9 +7,11 @@ import { Command, Option } from 'commander';
7
7
  import chalk from 'chalk';
8
8
  import { writeFileSync, copyFileSync, unlinkSync } from 'fs';
9
9
  import { getAdapter, getResolutionInfo } from '../adapters/index.js';
10
- import { ApiError } from '../errors.js';
10
+ import { ApiError, ThinkRunError } from '../errors.js';
11
11
  import { handleError, readBridgePort, BRIDGE_HEALTH_PROBE_TIMEOUT_MS, BRIDGE_REQUEST_TIMEOUT_MS } from '../utils.js';
12
+ import { LOCAL_BRIDGE_BROWSER_CREATION_TIMEOUT_MS } from '../local-bridge-timing.js';
12
13
  import { isJsonMode } from '../output/mode.js';
14
+ import { runBatchSteps, validateBatchSteps } from '../../shared/batch-steps.js';
13
15
  import { emitJson, createSpinner } from '../output/formatter.js';
14
16
  import { config } from '../config/store.js';
15
17
  import { resolveTabAuditState, writeTabAuditState } from '../../shared/audit-state.js';
@@ -17,28 +19,37 @@ import { clearLocalSessionContext, getCloudSessionContext, getLocalSessionContex
17
19
  import { isBlockedOutcome } from '../protected-flow/types.js';
18
20
  import { reserveLock, reserveRelease, commitReleaseReservation, getLockedBy, rollbackLockReservation, setWorkingLocation, withAgentBindingClaim, } from '../working-location.js';
19
21
  import { ensureCliSession, closeCliSession, } from '../session/cli-session-sync.js';
22
+ import { recordOnboardingStep } from '../../shared/onboarding-metrics.js';
23
+ import { accountGuidance, connectChrome } from '../session/account-guidance.js';
20
24
  import { resolveAgentId } from '../session/agent-identity.js';
21
25
  import { clampEvaluateTimeoutMs } from './evaluate-helpers.js';
22
26
  import { getNativeCodeHint } from '../adapters/local.js';
23
27
  function activityPersistenceFields(result) {
24
28
  return {
25
29
  activityPersistence: result.status,
30
+ nextStep: accountGuidance(result, true),
26
31
  activityFeedConnected: result.status === 'persisted' || result.status === 'existing',
27
32
  };
28
33
  }
29
34
  async function ensureActivityPersistence(tabId) {
30
35
  try {
31
- return await ensureCliSession(tabId);
36
+ const [result] = await Promise.all([ensureCliSession(tabId), recordOnboardingStep('cli', 'local_connected')]);
37
+ if ((result.status === 'persisted' || result.status === 'existing') && result.sessionId) {
38
+ await Promise.all([
39
+ recordOnboardingStep('cli', 'account_connected'),
40
+ recordOnboardingStep('cli', 'session_saved', result.sessionId),
41
+ ]);
42
+ }
43
+ return result;
32
44
  }
33
45
  catch {
34
46
  return { status: 'unavailable' };
35
47
  }
36
48
  }
37
- function printActivityPersistenceWarning(result) {
38
- if (result.status === 'not_configured' || result.status === 'persisted' || result.status === 'existing')
39
- return;
40
- console.error(chalk.yellow('Warning:'), 'Local control is ready, but this session was not connected to the Activity Feed.');
41
- console.error(chalk.yellow('Tip:'), 'Run: thinkrun doctor, then re-run thinkrun attach <tabId>.');
49
+ function printActivityGuidance(result) {
50
+ const guidance = accountGuidance(result, true);
51
+ if (guidance)
52
+ console.error([guidance.message, guidance.url].filter(Boolean).join(' '));
42
53
  }
43
54
  function withModeOption(command) {
44
55
  return command.addOption(new Option('--mode <mode>', 'Execution mode override: local|cloud').choices(['local', 'cloud']));
@@ -270,7 +281,7 @@ export function createNavigateCommand() {
270
281
  // Click
271
282
  export function createClickCommand() {
272
283
  return withActionOptions(new Command('click'))
273
- .argument('<selector>', 'CSS selector of element to click')
284
+ .argument('<selector>', 'CSS selector, or text such as button:has-text("Add") or text=Add')
274
285
  .option('--button <type>', 'Mouse button: left|right|middle', 'left')
275
286
  .option('--count <n>', 'Click count (for double-click)', '1')
276
287
  .option('--delay <ms>', 'Delay between mouse down and up', '0')
@@ -427,35 +438,30 @@ export function createScrollCommand() {
427
438
  }
428
439
  else if (options.direction) {
429
440
  if (options.direction !== 'up' && options.direction !== 'down') {
430
- spinner.fail('--direction must be "up" or "down"');
431
- process.exit(1);
441
+ throw new ThinkRunError('--direction must be "up" or "down"', 'INVALID_ARGUMENT');
432
442
  }
433
443
  const px = parseStrictIntPixels(String(options.amount ?? '500'));
434
444
  if (px === null || px <= 0) {
435
- spinner.fail('--amount must be a positive integer (pixels)');
436
- process.exit(1);
445
+ throw new ThinkRunError('--amount must be a positive integer (pixels)', 'INVALID_ARGUMENT');
437
446
  }
438
447
  scrollOptions.y = options.direction === 'up' ? -px : px;
439
448
  }
440
449
  else if (options.down) {
441
450
  const n = parseStrictIntPixels(String(options.down));
442
451
  if (n === null || n <= 0) {
443
- spinner.fail('--down must be a positive integer (pixels)');
444
- process.exit(1);
452
+ throw new ThinkRunError('--down must be a positive integer (pixels)', 'INVALID_ARGUMENT');
445
453
  }
446
454
  scrollOptions.y = n;
447
455
  }
448
456
  else if (options.up) {
449
457
  const n = parseStrictIntPixels(String(options.up));
450
458
  if (n === null || n <= 0) {
451
- spinner.fail('--up must be a positive integer (pixels)');
452
- process.exit(1);
459
+ throw new ThinkRunError('--up must be a positive integer (pixels)', 'INVALID_ARGUMENT');
453
460
  }
454
461
  scrollOptions.y = -n;
455
462
  }
456
463
  else {
457
- spinner.fail('Specify --down <px>, --up <px>, --direction <up|down> [--amount <px>], or --to <selector>');
458
- process.exit(1);
464
+ throw new ThinkRunError('Specify --down <px>, --up <px>, --direction <up|down> [--amount <px>], or --to <selector>', 'INVALID_ARGUMENT');
459
465
  }
460
466
  await scrollWithRetryAndFallback(adapter, scrollOptions);
461
467
  if (isJsonMode()) {
@@ -876,6 +882,81 @@ export function createEvaluateCommand() {
876
882
  }
877
883
  });
878
884
  }
885
+ /** Run one validated batch step through the adapter. Exported for tests. */
886
+ export function executeBatchStep(adapter, step) {
887
+ switch (step.action) {
888
+ case 'navigate': return adapter.navigate(step.url);
889
+ case 'click': return adapter.click(step.selector);
890
+ case 'fill': return adapter.fill(step.selector, step.value);
891
+ case 'type': return adapter.type(step.selector, step.text);
892
+ case 'press': return adapter.press(step.key);
893
+ case 'select': return adapter.select(step.selector, step.value);
894
+ case 'hover': return adapter.hover(step.selector);
895
+ case 'wait': return adapter.wait(step.selector ?? step.ms);
896
+ case 'wait_for_text': return adapter.waitForText(step.text);
897
+ case 'evaluate': return adapter.evaluate(step.script, [], { timeout: 30_000 });
898
+ default: {
899
+ const unhandled = step;
900
+ throw new Error(`Unhandled batch action: ${JSON.stringify(unhandled)}`);
901
+ }
902
+ }
903
+ }
904
+ // Batch
905
+ export function createBatchCommand() {
906
+ return withActionOptions(new Command('batch'))
907
+ .argument('[steps]', 'JSON array of steps, such as [{"action":"click","selector":"a"}]')
908
+ .option('--file <path>', 'Read steps from a JSON file')
909
+ .option('--stdin', 'Read steps from stdin')
910
+ .description('Run several browser actions in one call, stopping at the first failure. Actions: navigate, click, fill, type, press, select, hover, wait, wait_for_text, evaluate')
911
+ .action(async (stepsArg, options) => {
912
+ const startMs = Date.now();
913
+ try {
914
+ const sources = [stepsArg !== undefined, Boolean(options.file), Boolean(options.stdin)].filter(Boolean).length;
915
+ if (sources !== 1)
916
+ throw new ThinkRunError('Provide steps as one of: an argument, --file, or --stdin.', 'INVALID_BATCH');
917
+ let text = stepsArg;
918
+ if (options.file || options.stdin) {
919
+ const { readFileSync } = await import('fs');
920
+ if (options.stdin) {
921
+ const { isatty } = await import('tty');
922
+ if (isatty(0))
923
+ throw new ThinkRunError('--stdin requires piped or redirected input.', 'INVALID_BATCH');
924
+ }
925
+ text = readFileSync(options.file ?? 0, 'utf-8');
926
+ }
927
+ let parsed;
928
+ try {
929
+ parsed = JSON.parse(text);
930
+ }
931
+ catch {
932
+ throw new ThinkRunError('Batch steps are not valid JSON.', 'INVALID_BATCH');
933
+ }
934
+ // Validate the whole list before connecting, so a bad step never leaves a batch half done.
935
+ const validation = validateBatchSteps(parsed);
936
+ if (!validation.ok)
937
+ throw new ThinkRunError(validation.error, 'INVALID_BATCH');
938
+ const adapter = await getCommandAdapter(options);
939
+ const result = await runBatchSteps(validation.steps, (step) => executeBatchStep(adapter, step));
940
+ if (isJsonMode()) {
941
+ emitJson({ success: result.success, command: 'batch', durationMs: Date.now() - startMs, data: result });
942
+ }
943
+ else {
944
+ for (const step of result.steps) {
945
+ const mark = step.success ? chalk.green('ok') : chalk.red('failed');
946
+ console.log(`${step.step}. ${step.action}: ${mark}${step.error ? ` - ${step.error}` : ''}`);
947
+ if (step.result !== undefined)
948
+ console.log(step.result);
949
+ }
950
+ console.log(`${result.completed} of ${result.total} steps completed.`);
951
+ }
952
+ if (!result.success)
953
+ process.exitCode = 1;
954
+ }
955
+ catch (error) {
956
+ handleError(error, 'batch', startMs);
957
+ }
958
+ });
959
+ }
879
960
  // Dialog
880
961
  export function createDialogCommand() {
881
962
  const dialogCmd = new Command('dialog')
@@ -1085,13 +1166,15 @@ export function isBridgeUnreachableError(error) {
1085
1166
  return /ECONNREFUSED|fetch failed/i.test(msg);
1086
1167
  }
1087
1168
  function isRetryableScrollFailure(e) {
1088
- if (isBridgeUnreachableError(e))
1089
- return true;
1090
1169
  if (e instanceof ApiError) {
1091
1170
  if (e.retryable === true)
1092
1171
  return true;
1093
1172
  if (e.retryable === false)
1094
1173
  return false;
1174
+ }
1175
+ if (isBridgeUnreachableError(e))
1176
+ return true;
1177
+ if (e instanceof ApiError) {
1095
1178
  const c = e.nativeCode ?? e.code;
1096
1179
  if (c === 'NATIVE_HOST_UNREACHABLE')
1097
1180
  return true;
@@ -1155,6 +1238,7 @@ function exitWithSwitchTabFailure(tabId, result, jsonCommand, startMs) {
1155
1238
  durationMs: Date.now() - startMs,
1156
1239
  error: result.message || `HTTP ${result.status}`,
1157
1240
  code: result.code ?? 'SWITCH_TAB_FAILED',
1241
+ ...(result.code === 'EXTENSION_NOT_CONNECTED' ? { hint: connectChrome } : {}),
1158
1242
  });
1159
1243
  process.exit(1);
1160
1244
  }
@@ -1164,7 +1248,7 @@ function exitWithSwitchTabFailure(tabId, result, jsonCommand, startMs) {
1164
1248
  process.exit(1);
1165
1249
  }
1166
1250
  if (result.code === 'EXTENSION_NOT_CONNECTED') {
1167
- console.error(chalk.red('Error:'), 'Extension not connected. Open your Chromium-based browser with the ThinkRun extension and try again. Run `thinkrun doctor` to diagnose.');
1251
+ console.error(chalk.red('Error:'), connectChrome);
1168
1252
  process.exit(1);
1169
1253
  }
1170
1254
  console.error(chalk.red('Error:'), result.message || `HTTP ${result.status}`, chalk.gray('Run `thinkrun doctor` if this persists.'));
@@ -1179,10 +1263,11 @@ function exitWithBridgeUnreachable(command, startMs, error) {
1179
1263
  durationMs: Date.now() - startMs,
1180
1264
  error: msg,
1181
1265
  code: 'BRIDGE_UNREACHABLE',
1266
+ hint: connectChrome,
1182
1267
  });
1183
1268
  process.exit(1);
1184
1269
  }
1185
- console.error(chalk.red('Error:'), 'Bridge not running. Run `thinkrun doctor` to diagnose.');
1270
+ console.error(chalk.red('Error:'), 'Bridge not running. ' + connectChrome);
1186
1271
  process.exit(1);
1187
1272
  }
1188
1273
  /**
@@ -1228,7 +1313,7 @@ export async function newTabOnBridge(port, url, fetchFn = fetch) {
1228
1313
  method: 'POST',
1229
1314
  headers: { 'Content-Type': 'application/json' },
1230
1315
  body: JSON.stringify(url ? { url } : {}),
1231
- signal: AbortSignal.timeout(BRIDGE_REQUEST_TIMEOUT_MS),
1316
+ signal: AbortSignal.timeout(LOCAL_BRIDGE_BROWSER_CREATION_TIMEOUT_MS),
1232
1317
  });
1233
1318
  const text = await res.text();
1234
1319
  let body = {};
@@ -1404,7 +1489,7 @@ export function createTabsCommand() {
1404
1489
  if (isJsonMode()) {
1405
1490
  // Write structured error to stderr so agents reading stdout don't mix error
1406
1491
  // envelopes with success envelopes.
1407
- process.stderr.write(JSON.stringify({ success: false, command: 'tabs', durationMs: Date.now() - startMs, error: errMsg, code: 'NATIVE_HOST_ERROR' }) + '\n');
1492
+ process.stderr.write(JSON.stringify({ success: false, command: 'tabs', durationMs: Date.now() - startMs, error: errMsg, code: 'NATIVE_HOST_ERROR', hint: 'Run thinkrun doctor to check the Chrome connection.' }) + '\n');
1408
1493
  }
1409
1494
  process.exit(1);
1410
1495
  }
@@ -1427,6 +1512,8 @@ export function createTabsCommand() {
1427
1512
  }
1428
1513
  catch (error) {
1429
1514
  spinner.fail('Failed to fetch tabs');
1515
+ if (isBridgeUnreachableError(error))
1516
+ exitWithBridgeUnreachable('tabs', startMs, error);
1430
1517
  handleError(error, 'tabs', startMs);
1431
1518
  }
1432
1519
  });
@@ -1755,7 +1842,7 @@ export function createAttachCommand() {
1755
1842
  auditEnabled: requestedAudit.enabled,
1756
1843
  auditSource: requestedAudit.source,
1757
1844
  });
1758
- printActivityPersistenceWarning(activityPersistence);
1845
+ printActivityGuidance(activityPersistence);
1759
1846
  return;
1760
1847
  }
1761
1848
  }
@@ -1832,7 +1919,7 @@ export function createAttachCommand() {
1832
1919
  auditEnabled: requestedAudit.enabled,
1833
1920
  auditSource: requestedAudit.source,
1834
1921
  });
1835
- printActivityPersistenceWarning(activityPersistence);
1922
+ printActivityGuidance(activityPersistence);
1836
1923
  }
1837
1924
  catch (error) {
1838
1925
  if (lockReservation && !lockCommitted) {
@@ -1887,7 +1974,7 @@ export function createNewWindowCommand() {
1887
1974
  method: 'POST',
1888
1975
  headers: { 'Content-Type': 'application/json' },
1889
1976
  body: JSON.stringify({ url, focused: opts.focus }),
1890
- signal: AbortSignal.timeout(10000),
1977
+ signal: AbortSignal.timeout(LOCAL_BRIDGE_BROWSER_CREATION_TIMEOUT_MS),
1891
1978
  });
1892
1979
  if (!res.ok) {
1893
1980
  const body = await res.json().catch(() => ({}));
@@ -1984,7 +2071,7 @@ export function createNewWindowCommand() {
1984
2071
  group,
1985
2072
  controlSessionId: localContext?.controlSessionId,
1986
2073
  });
1987
- printActivityPersistenceWarning(activityPersistence);
2074
+ printActivityGuidance(activityPersistence);
1988
2075
  }
1989
2076
  catch (error) {
1990
2077
  if (error?.message?.startsWith('TAB_LOCKED')) {