@thinkrun/cli 0.1.35 → 0.1.36

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 (39) hide show
  1. package/README.md +13 -2
  2. package/dist/shared/local-audit-sync.js +1 -0
  3. package/dist/src/adapters/cloud.d.ts.map +1 -1
  4. package/dist/src/adapters/cloud.js +27 -1
  5. package/dist/src/adapters/cloud.js.map +1 -1
  6. package/dist/src/adapters/local.d.ts +18 -7
  7. package/dist/src/adapters/local.d.ts.map +1 -1
  8. package/dist/src/adapters/local.js +242 -58
  9. package/dist/src/adapters/local.js.map +1 -1
  10. package/dist/src/commands/actions.d.ts +2 -0
  11. package/dist/src/commands/actions.d.ts.map +1 -1
  12. package/dist/src/commands/actions.js +176 -43
  13. package/dist/src/commands/actions.js.map +1 -1
  14. package/dist/src/commands/audit.d.ts.map +1 -1
  15. package/dist/src/commands/audit.js +35 -5
  16. package/dist/src/commands/audit.js.map +1 -1
  17. package/dist/src/commands/cloud.d.ts.map +1 -1
  18. package/dist/src/commands/cloud.js +14 -6
  19. package/dist/src/commands/cloud.js.map +1 -1
  20. package/dist/src/commands/doctor.d.ts +7 -0
  21. package/dist/src/commands/doctor.d.ts.map +1 -1
  22. package/dist/src/commands/doctor.js +72 -9
  23. package/dist/src/commands/doctor.js.map +1 -1
  24. package/dist/src/commands/release.d.ts.map +1 -1
  25. package/dist/src/commands/release.js +303 -23
  26. package/dist/src/commands/release.js.map +1 -1
  27. package/dist/src/session/cli-session-sync.d.ts +18 -3
  28. package/dist/src/session/cli-session-sync.d.ts.map +1 -1
  29. package/dist/src/session/cli-session-sync.js +188 -31
  30. package/dist/src/session/cli-session-sync.js.map +1 -1
  31. package/dist/src/session/context.d.ts +22 -3
  32. package/dist/src/session/context.d.ts.map +1 -1
  33. package/dist/src/session/context.js +132 -16
  34. package/dist/src/session/context.js.map +1 -1
  35. package/dist/src/working-location.d.ts +52 -4
  36. package/dist/src/working-location.d.ts.map +1 -1
  37. package/dist/src/working-location.js +648 -22
  38. package/dist/src/working-location.js.map +1 -1
  39. package/package.json +1 -1
@@ -15,11 +15,31 @@ import { config } from '../config/store.js';
15
15
  import { resolveTabAuditState, writeTabAuditState } from '../../shared/audit-state.js';
16
16
  import { clearLocalSessionContext, getCloudSessionContext, getLocalSessionContext, setLocalSessionContext, } from '../session/context.js';
17
17
  import { isBlockedOutcome } from '../protected-flow/types.js';
18
- import { setWorkingLocation, releaseWorkingLocation, getLockedBy } from '../working-location.js';
19
- import { initCliSession, closeCliSession } from '../session/cli-session-sync.js';
18
+ import { reserveLock, reserveRelease, commitReleaseReservation, getLockedBy, rollbackLockReservation, setWorkingLocation, withAgentBindingClaim, } from '../working-location.js';
19
+ import { ensureCliSession, closeCliSession, } from '../session/cli-session-sync.js';
20
20
  import { resolveAgentId } from '../session/agent-identity.js';
21
21
  import { clampEvaluateTimeoutMs } from './evaluate-helpers.js';
22
22
  import { getNativeCodeHint } from '../adapters/local.js';
23
+ function activityPersistenceFields(result) {
24
+ return {
25
+ activityPersistence: result.status,
26
+ activityFeedConnected: result.status === 'persisted' || result.status === 'existing',
27
+ };
28
+ }
29
+ async function ensureActivityPersistence(tabId) {
30
+ try {
31
+ return await ensureCliSession(tabId);
32
+ }
33
+ catch {
34
+ return { status: 'unavailable' };
35
+ }
36
+ }
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>.');
42
+ }
23
43
  function withModeOption(command) {
24
44
  return command.addOption(new Option('--mode <mode>', 'Execution mode override: local|cloud').choices(['local', 'cloud']));
25
45
  }
@@ -39,6 +59,15 @@ function validateTabId(value, source) {
39
59
  }
40
60
  return String(parsed);
41
61
  }
62
+ /** Parse the public type delay option without accepting parseInt-style prefixes. */
63
+ export function parseTypeDelay(value) {
64
+ const normalized = value.trim();
65
+ const parsed = Number(normalized);
66
+ if (!/^(0|[1-9]\d*)$/.test(normalized) || !Number.isInteger(parsed) || parsed > 5_000) {
67
+ throw new Error(`Invalid --delay "${value}". Must be an integer from 0 to 5000 milliseconds.`);
68
+ }
69
+ return parsed;
70
+ }
42
71
  /** Resolve tab override from --tab flag or THINKRUN_TAB_ID env var. */
43
72
  function resolveTabOverride(options) {
44
73
  let tabId;
@@ -322,26 +351,27 @@ export function createClickAtCommand() {
322
351
  // Type
323
352
  export function createTypeCommand() {
324
353
  return withActionOptions(new Command('type'))
325
- .argument('<selector>', 'CSS selector of input element')
354
+ .argument('<selector>', 'CSS selector of an input, textarea, or contenteditable element; local mode also supports role=textbox')
326
355
  .argument('<text>', 'Text to type')
327
- .option('--delay <ms>', 'Delay between keystrokes', '0')
328
- .option('--clear', 'Clear field before typing')
356
+ .option('--delay <ms>', 'Delay of 0-5000 ms per character', '0')
357
+ .option('--clear', 'Clear first to replace existing content instead of appending')
329
358
  .option('--mask', 'Mask text in output (for passwords)')
330
- .description('Type text into an element')
359
+ .description('Appends text to an editable element; use --clear to replace its content')
331
360
  .action(async (selector, text, options) => {
332
361
  const startMs = Date.now();
333
362
  const displayText = options.mask ? '***' : text;
334
363
  const spinner = createSpinner(`Typing into ${selector}...`);
335
364
  try {
365
+ const delay = parseTypeDelay(options.delay);
336
366
  const adapter = await getCommandAdapter(options);
337
367
  const result = await adapter.type(selector, text, {
338
- delay: parseInt(options.delay),
368
+ delay,
339
369
  clear: options.clear,
340
370
  mask: options.mask,
341
371
  });
342
372
  handleBlockedResult(result, 'type', startMs, spinner);
343
373
  if (isJsonMode()) {
344
- emitJson({ success: true, command: 'type', durationMs: Date.now() - startMs });
374
+ emitJson({ success: true, command: 'type', durationMs: Date.now() - startMs, data: result.data });
345
375
  return;
346
376
  }
347
377
  spinner.succeed(`Typed "${displayText}" into ${selector}`);
@@ -355,9 +385,9 @@ export function createTypeCommand() {
355
385
  // Fill (clears field first, then sets value)
356
386
  export function createFillCommand() {
357
387
  return withActionOptions(new Command('fill'))
358
- .argument('<selector>', 'CSS selector of input element')
388
+ .argument('<selector>', 'CSS selector of an input, textarea, or contenteditable element; local mode also supports role=textbox')
359
389
  .argument('<value>', 'Value to fill')
360
- .description('Fill a form field (clears existing value first)')
390
+ .description('Fill an editable element; directly replaces its existing content')
361
391
  .action(async (selector, value, options) => {
362
392
  const startMs = Date.now();
363
393
  const spinner = createSpinner(`Filling ${selector}...`);
@@ -366,7 +396,7 @@ export function createFillCommand() {
366
396
  const result = await adapter.fill(selector, value);
367
397
  handleBlockedResult(result, 'fill', startMs, spinner);
368
398
  if (isJsonMode()) {
369
- emitJson({ success: true, command: 'fill', durationMs: Date.now() - startMs });
399
+ emitJson({ success: true, command: 'fill', durationMs: Date.now() - startMs, data: result.data });
370
400
  return;
371
401
  }
372
402
  spinner.succeed(`Filled ${selector}`);
@@ -1654,7 +1684,12 @@ export function createAttachCommand() {
1654
1684
  }
1655
1685
  const group = options?.group;
1656
1686
  const spinner = createSpinner(`Attaching to tab ${tabId}...`);
1687
+ let lockReservation;
1688
+ let lockCommitted = false;
1657
1689
  try {
1690
+ // Establish local authority before the bridge can switch or register
1691
+ // anything. A foreign TAB_LOCKED failure therefore makes zero bridge calls.
1692
+ lockReservation = reserveLock(tabId, group);
1658
1693
  const port = readBridgePort();
1659
1694
  const ctxBefore = getLocalSessionContext();
1660
1695
  const attachSessionId = ctxBefore?.tabId === String(tabId) && ctxBefore.agentSessionId
@@ -1663,6 +1698,10 @@ export function createAttachCommand() {
1663
1698
  const result = await switchTabOnBridge(port, tabId, attachSessionId ? { sessionId: attachSessionId } : undefined);
1664
1699
  if (!result.ok) {
1665
1700
  spinner.fail('Failed to attach to tab');
1701
+ // The structured failure helper terminates the process in production,
1702
+ // so rollback cannot be deferred to the surrounding catch block.
1703
+ rollbackLockReservation(lockReservation);
1704
+ lockReservation = undefined;
1666
1705
  exitWithSwitchTabFailure(tabId, result, 'attach', startMs);
1667
1706
  }
1668
1707
  // Idempotent re-attach: same tab + known session — refresh registry without unregistering first.
@@ -1672,16 +1711,19 @@ export function createAttachCommand() {
1672
1711
  const liveTab = await readLiveTabMetadata(port, tabId);
1673
1712
  const windowIdIdem = liveTab.windowId ?? idem.windowId;
1674
1713
  const agentSessionIdIdem = idem.sessionId ?? ctxBefore.agentSessionId;
1675
- setWorkingLocation({
1676
- tabId,
1677
- ...(windowIdIdem !== undefined ? { windowId: windowIdIdem } : {}),
1678
- ...(group ? { group } : {}),
1714
+ withAgentBindingClaim(() => {
1715
+ setWorkingLocation({
1716
+ tabId,
1717
+ ...(windowIdIdem !== undefined ? { windowId: windowIdIdem } : {}),
1718
+ ...(group ? { group } : {}),
1719
+ }, true, lockReservation);
1720
+ lockCommitted = true;
1721
+ if (options?.audit === true) {
1722
+ writeTabAuditState(String(tabId), true, undefined, { explicit: true });
1723
+ }
1724
+ setLocalSessionContext(String(tabId), agentSessionIdIdem, windowIdIdem, true);
1679
1725
  });
1680
- if (options?.audit === true) {
1681
- writeTabAuditState(String(tabId), true, undefined, { explicit: true });
1682
- }
1683
- setLocalSessionContext(String(tabId), agentSessionIdIdem, windowIdIdem);
1684
- initCliSession(String(tabId)).catch(() => { });
1726
+ const activityPersistence = await ensureActivityPersistence(String(tabId));
1685
1727
  const refreshedContext = getLocalSessionContext();
1686
1728
  const requestedAudit = resolveTabAuditState({ tabId, flagEnabled: options?.audit === true });
1687
1729
  if (isJsonMode()) {
@@ -1698,6 +1740,7 @@ export function createAttachCommand() {
1698
1740
  ...(group ? { group } : {}),
1699
1741
  auditEnabled: requestedAudit.enabled,
1700
1742
  auditSource: requestedAudit.source,
1743
+ ...activityPersistenceFields(activityPersistence),
1701
1744
  },
1702
1745
  });
1703
1746
  return;
@@ -1712,27 +1755,46 @@ export function createAttachCommand() {
1712
1755
  auditEnabled: requestedAudit.enabled,
1713
1756
  auditSource: requestedAudit.source,
1714
1757
  });
1758
+ printActivityPersistenceWarning(activityPersistence);
1715
1759
  return;
1716
1760
  }
1717
1761
  }
1718
1762
  const prevSessionId = getLocalSessionContext()?.agentSessionId;
1719
1763
  const reg = await registerSessionOnBridge(port, tabId);
1720
1764
  if (!reg.ok) {
1765
+ // exitWithRegisterFailure does not return under real process semantics.
1766
+ rollbackLockReservation(lockReservation);
1767
+ lockReservation = undefined;
1721
1768
  exitWithRegisterFailure(reg, 'attach', startMs, spinner);
1722
1769
  }
1723
1770
  const liveTab = await readLiveTabMetadata(port, tabId);
1724
1771
  let windowId = liveTab.windowId ?? reg.windowId;
1725
1772
  let agentSessionId = reg.sessionId;
1726
1773
  // Acquire per-process working location lock (throws TAB_LOCKED if contested).
1727
- setWorkingLocation({ tabId, ...(windowId !== undefined ? { windowId } : {}), ...(group ? { group } : {}) });
1728
- if (options?.audit === true) {
1729
- writeTabAuditState(String(tabId), true, undefined, { explicit: true });
1730
- }
1731
- // Lock acquired — safe to update session context now.
1732
- setLocalSessionContext(String(tabId), agentSessionId, windowId);
1733
- // Fire-and-forget: register CLI session in the cloud activity feed.
1734
- // Must never block or throw to the caller — cloud sync is best-effort.
1735
- initCliSession(String(tabId)).catch(() => { });
1774
+ try {
1775
+ withAgentBindingClaim(() => {
1776
+ setWorkingLocation({ tabId, ...(windowId !== undefined ? { windowId } : {}), ...(group ? { group } : {}) }, true, lockReservation);
1777
+ lockCommitted = true;
1778
+ if (options?.audit === true) {
1779
+ writeTabAuditState(String(tabId), true, undefined, { explicit: true });
1780
+ }
1781
+ // Commit the working pointer and private/shared context as one binding.
1782
+ setLocalSessionContext(String(tabId), agentSessionId, windowId, true);
1783
+ });
1784
+ }
1785
+ catch (error) {
1786
+ if (error?.message?.startsWith('TAB_LOCKED') && agentSessionId && agentSessionId !== prevSessionId) {
1787
+ try {
1788
+ await unregisterLocalAgentSession(port, agentSessionId);
1789
+ }
1790
+ catch { /* best-effort rollback */ }
1791
+ }
1792
+ throw error;
1793
+ }
1794
+ // Wait for the bounded persistence attempt so the next CLI process can
1795
+ // reliably read the durable session receipt. Local control remains valid
1796
+ // for every non-success outcome.
1797
+ const activityPersistence = await ensureActivityPersistence(String(tabId));
1736
1798
  if (prevSessionId && prevSessionId !== agentSessionId) {
1737
1799
  try {
1738
1800
  await unregisterLocalAgentSession(port, prevSessionId);
@@ -1756,6 +1818,7 @@ export function createAttachCommand() {
1756
1818
  ...(group ? { group } : {}),
1757
1819
  auditEnabled: requestedAudit.enabled,
1758
1820
  auditSource: requestedAudit.source,
1821
+ ...activityPersistenceFields(activityPersistence),
1759
1822
  },
1760
1823
  });
1761
1824
  return;
@@ -1769,8 +1832,12 @@ export function createAttachCommand() {
1769
1832
  auditEnabled: requestedAudit.enabled,
1770
1833
  auditSource: requestedAudit.source,
1771
1834
  });
1835
+ printActivityPersistenceWarning(activityPersistence);
1772
1836
  }
1773
1837
  catch (error) {
1838
+ if (lockReservation && !lockCommitted) {
1839
+ rollbackLockReservation(lockReservation);
1840
+ }
1774
1841
  const errMsg = error instanceof Error ? error.message : String(error);
1775
1842
  if (errMsg.startsWith('TAB_LOCKED')) {
1776
1843
  if (isJsonMode()) {
@@ -1860,14 +1927,28 @@ export function createNewWindowCommand() {
1860
1927
  console.error(chalk.yellow('Tip:'), 'Run: thinkrun attach <tabId> or thinkrun session debug --json');
1861
1928
  process.exit(1);
1862
1929
  }
1863
- // Acquire per-process working location lock BEFORE updating session context
1864
- // so a TAB_LOCKED failure doesn't leave context pointing at a contested tab.
1865
- setWorkingLocation({ tabId, ...(windowId !== undefined ? { windowId } : {}), ...(group ? { group } : {}) });
1866
- // Fire-and-forget: register CLI session in the cloud activity feed.
1867
- // Must never block or throw to the caller — cloud sync is best-effort.
1868
- // Lock acquired — safe to update session context now.
1869
- setLocalSessionContext(String(tabId), agentSessionId, windowId);
1870
- initCliSession(String(tabId)).catch(() => { });
1930
+ // Commit the working pointer and private/shared context atomically with
1931
+ // respect to release and other same-agent binding changes.
1932
+ try {
1933
+ withAgentBindingClaim(() => {
1934
+ setWorkingLocation({ tabId, ...(windowId !== undefined ? { windowId } : {}), ...(group ? { group } : {}) }, true);
1935
+ setLocalSessionContext(String(tabId), agentSessionId, windowId, true);
1936
+ });
1937
+ }
1938
+ catch (error) {
1939
+ if (error?.message?.startsWith('TAB_LOCKED')) {
1940
+ try {
1941
+ await unregisterLocalAgentSession(port, agentSessionId);
1942
+ }
1943
+ catch { /* best-effort rollback */ }
1944
+ try {
1945
+ await closeTabOnBridge(port, tabId, { sessionId: agentSessionId });
1946
+ }
1947
+ catch { /* best-effort rollback */ }
1948
+ }
1949
+ throw error;
1950
+ }
1951
+ const activityPersistence = await ensureActivityPersistence(String(tabId));
1871
1952
  if (previousLocalSessionId) {
1872
1953
  try {
1873
1954
  await unregisterLocalAgentSession(port, previousLocalSessionId);
@@ -1890,6 +1971,7 @@ export function createNewWindowCommand() {
1890
1971
  ? { controlSessionLabel: summarizeControlSessionLabel(localContext.controlSessionId) }
1891
1972
  : {}),
1892
1973
  ...(group ? { group } : {}),
1974
+ ...activityPersistenceFields(activityPersistence),
1893
1975
  },
1894
1976
  });
1895
1977
  return;
@@ -1902,6 +1984,7 @@ export function createNewWindowCommand() {
1902
1984
  group,
1903
1985
  controlSessionId: localContext?.controlSessionId,
1904
1986
  });
1987
+ printActivityPersistenceWarning(activityPersistence);
1905
1988
  }
1906
1989
  catch (error) {
1907
1990
  if (error?.message?.startsWith('TAB_LOCKED')) {
@@ -1966,14 +2049,25 @@ export function createCloseTabCommand() {
1966
2049
  process.exit(1);
1967
2050
  }
1968
2051
  }
2052
+ const isCurrentTab = currentCtx?.tabId === String(resolvedTabId);
2053
+ let releaseReservation;
2054
+ try {
2055
+ releaseReservation = reserveRelease(resolvedTabId);
2056
+ }
2057
+ catch (error) {
2058
+ console.error(chalk.red('Error:'), error?.message ?? `Tab ${resolvedTabId} has a lock transaction in progress.`);
2059
+ process.exit(1);
2060
+ }
1969
2061
  const spinner = createSpinner(`Closing tab ${resolvedTabId}...`);
2062
+ let clearedContext = false;
1970
2063
  try {
1971
2064
  const port = readBridgePort();
1972
- const isCurrentTab = currentCtx?.tabId === String(resolvedTabId);
1973
2065
  const result = await closeTabOnBridge(port, resolvedTabId, {
1974
2066
  sessionId: currentCtx?.tabId === String(resolvedTabId) ? currentCtx.agentSessionId : undefined,
1975
2067
  });
1976
2068
  if (!result.ok) {
2069
+ if (releaseReservation)
2070
+ rollbackLockReservation(releaseReservation);
1977
2071
  spinner.fail('Failed to close tab');
1978
2072
  exitWithSwitchTabFailure(resolvedTabId, result, 'close-tab', startMs);
1979
2073
  }
@@ -1985,26 +2079,65 @@ export function createCloseTabCommand() {
1985
2079
  // best-effort cleanup after the close succeeds; local context cleanup still proceeds
1986
2080
  }
1987
2081
  }
2082
+ let committed = { released: false, contextCleared: false };
2083
+ try {
2084
+ withAgentBindingClaim(() => {
2085
+ committed = releaseReservation
2086
+ ? commitReleaseReservation(releaseReservation, undefined, true, undefined, true)
2087
+ : committed;
2088
+ if (isCurrentTab && committed.contextCleared) {
2089
+ clearedContext = clearLocalSessionContext(true);
2090
+ }
2091
+ });
2092
+ }
2093
+ catch (error) {
2094
+ if (!error?.message?.startsWith('TAB_LOCKED'))
2095
+ throw error;
2096
+ }
2097
+ if (!committed.released) {
2098
+ const exactReservationGone = !!releaseReservation
2099
+ && getLockedBy(resolvedTabId)?.reservationId !== releaseReservation.reservationId;
2100
+ if (isCurrentTab && exactReservationGone) {
2101
+ closeCliSession(String(resolvedTabId), 'completed');
2102
+ }
2103
+ spinner.fail('Tab closed, but local binding cleanup is still contended');
2104
+ if (isJsonMode()) {
2105
+ emitJson({
2106
+ success: false,
2107
+ command: 'close-tab',
2108
+ durationMs: Date.now() - startMs,
2109
+ error: 'Tab closed, but another binding transaction prevented final cleanup',
2110
+ code: 'TAB_LOCKED',
2111
+ retryable: true,
2112
+ hint: 'Retry: thinkrun release',
2113
+ });
2114
+ process.exit(1);
2115
+ }
2116
+ console.error(chalk.yellow('Retry:'), 'thinkrun release');
2117
+ process.exit(1);
2118
+ }
1988
2119
  if (isCurrentTab) {
1989
- releaseWorkingLocation();
1990
- clearLocalSessionContext();
1991
- closeCliSession(String(resolvedTabId), 'completed');
2120
+ if (committed.released) {
2121
+ closeCliSession(String(resolvedTabId), 'completed');
2122
+ }
1992
2123
  }
1993
2124
  if (isJsonMode()) {
1994
2125
  emitJson({
1995
2126
  success: true,
1996
2127
  command: 'close-tab',
1997
2128
  durationMs: Date.now() - startMs,
1998
- data: { tabId: resolvedTabId, clearedContext: Boolean(isCurrentTab) },
2129
+ data: { tabId: resolvedTabId, clearedContext },
1999
2130
  });
2000
2131
  return;
2001
2132
  }
2002
2133
  spinner.succeed(`Closed tab ${resolvedTabId}`);
2003
- if (isCurrentTab) {
2134
+ if (clearedContext) {
2004
2135
  console.log(chalk.gray('Cleared attached local session context.'));
2005
2136
  }
2006
2137
  }
2007
2138
  catch (error) {
2139
+ if (releaseReservation)
2140
+ rollbackLockReservation(releaseReservation);
2008
2141
  spinner.fail('Failed to close tab');
2009
2142
  if (isBridgeUnreachableError(error)) {
2010
2143
  exitWithBridgeUnreachable('close-tab', startMs, error);