@xkwdstore/agent 2.0.6 → 2.0.7

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/README.md CHANGED
@@ -6,7 +6,7 @@ Terminal-only, cryptographically authenticated CLI for XKWDStore browser automat
6
6
 
7
7
  > **@xkwdstore/agent 2.0.3 is the last version published on npm.**
8
8
  >
9
- > The current source version is **2.0.6** (Tweet/Comment/Follow confirmation-safety fixes). It is
9
+ > The current source version is **2.0.7** (robust post-action confirmation). It is
10
10
  > NOT claimed to be published unless the release workflow has published it — see
11
11
  > `reports/` for the authoritative publication state.
12
12
 
@@ -29,7 +29,7 @@ curl -L -o "%TEMP%\xkwdstore-install.ps1" https://raw.githubusercontent.com/Essa
29
29
  The generated launcher runs the pinned command:
30
30
 
31
31
  ```powershell
32
- npx --yes @xkwdstore/agent@2.0.6 start
32
+ npx --yes @xkwdstore/agent@2.0.7 start
33
33
  ```
34
34
 
35
35
  Automated installer tests use `-NoLaunch` or a mocked `npx` command so the
@@ -177,10 +177,10 @@ The agent does NOT update itself. To use a newer version, change the version
177
177
  number in the command. The pinned command for this release is:
178
178
 
179
179
  ```powershell
180
- npx --yes @xkwdstore/agent@2.0.6 start
180
+ npx --yes @xkwdstore/agent@2.0.7 start
181
181
  ```
182
182
 
183
- > 2.0.6 is the current local agent version (Tweet/Comment/Follow confirmation-safety fixes).
183
+ > 2.0.7 is the current local agent version (robust post-action confirmation).
184
184
  > 2.0.3 was the previous release.
185
185
  >
186
186
  > The server checks compatibility at startup and displays a clear message if
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xkwdstore/agent",
3
- "version": "2.0.6",
3
+ "version": "2.0.7",
4
4
  "description": "XKWDStore Agent — terminal-only, cryptographically authenticated CLI for browser automation",
5
5
  "main": "src/cli.js",
6
6
  "bin": {
@@ -1,154 +1,153 @@
1
- 'use strict';
2
-
3
- /**
4
- * Comment action — post a reply/comment on a tweet.
5
- * Ported from backend/routes/browser.js doComment().
6
- */
7
-
8
- const { sleep, humanDelay, randDelay, naturalNavigate, humanPreAction, humanType, humanClick, detectStage } = require('./helpers');
9
-
10
- async function comment(page, payload) {
11
- const { tweetUrl, commentText } = payload;
12
- if (!tweetUrl || !commentText) throw new Error('tweetUrl and commentText required');
13
-
14
- // Navigate to the tweet
15
- await page.goto(tweetUrl, { waitUntil: 'domcontentloaded', timeout: 30000 }).catch(() => {});
16
- await randDelay(1800, 3200);
17
-
18
- if (page.url().includes('/login') || page.url().includes('/i/flow')) {
19
- throw new Error('Not logged in — open browser and login first');
20
- }
21
-
22
- // Find and click the reply button
23
- const tweetIdMatch = tweetUrl.match(/\/status\/(\d+)/);
24
- const tweetId = tweetIdMatch ? tweetIdMatch[1] : null;
25
- const replySelectors = [
26
- 'button[data-testid="reply"]',
27
- '[data-testid="reply"]',
28
- 'button[aria-label*="Reply"]',
29
- ];
30
-
31
- let replyClicked = false;
32
- for (const sel of replySelectors) {
33
- const scoped = tweetId ? `article:has(a[href*="/status/${tweetId}"]) ${sel}` : sel;
34
- const btn = page.locator(scoped).first();
35
- if (await btn.isVisible({ timeout: 3000 }).catch(() => false)) {
36
- await humanClick(page, btn);
37
- replyClicked = true;
38
- break;
39
- }
40
- }
41
-
42
- if (!replyClicked && tweetId) {
43
- // Fallback for tweet detail pages where the target article does not include
44
- // a status link back to itself.
45
- for (const sel of replySelectors) {
46
- const btn = page.locator(sel).first();
47
- if (await btn.isVisible({ timeout: 3000 }).catch(() => false)) {
48
- await humanClick(page, btn);
49
- replyClicked = true;
50
- break;
51
- }
52
- }
53
- }
54
-
55
- if (!replyClicked) throw new Error('Could not find reply button');
56
-
57
- // Wait for dialog or inline editor
58
- await sleep(1500);
59
- const editorSelectors = [
60
- 'div[role="dialog"] [data-testid="tweetTextarea_0"] div[contenteditable="true"][role="textbox"]',
61
- '[data-testid="tweetTextarea_0"] div[contenteditable="true"][role="textbox"]',
62
- '.public-DraftEditor-content',
63
- ];
64
-
65
- let editor = null;
66
- for (const sel of editorSelectors) {
67
- const el = page.locator(sel).first();
68
- if (await el.isVisible({ timeout: 5000 }).catch(() => false)) {
69
- editor = el;
70
- break;
71
- }
72
- }
73
-
74
- if (!editor) throw new Error('Could not find comment editor');
75
- await editor.click();
76
- await humanDelay(300, 600);
77
-
78
- // Clear any existing text
79
- await page.keyboard.press('Control+a');
80
- await page.keyboard.press('Backspace');
81
-
82
- // Type comment
83
- const isRTL = /[\u0600-\u06FF\u0750-\u077F]/.test(commentText);
84
- if (isRTL) {
85
- await page.evaluate(() => {
86
- const el = document.querySelector('[data-testid="tweetTextarea_0"]');
87
- if (el) el.setAttribute('dir', 'rtl');
88
- });
89
- const words = commentText.split(' ');
90
- for (const word of words) {
91
- await page.evaluate((w) => document.execCommand('insertText', false, w + ' '), word);
92
- await humanDelay(50, 100);
93
- }
94
- } else {
95
- await humanType(page, commentText, { delayMin: 50, delayMax: 150 });
96
- }
97
-
98
- await humanDelay(500, 1000);
99
-
100
- // Click send/reply button
101
- const sendSelectors = [
102
- 'div[role="dialog"] [data-testid="tweetButton"]',
103
- '[data-testid="tweetButton"]',
104
- '[data-testid="tweetButtonInline"]',
105
- ];
106
-
107
- let sent = false;
108
- for (const sel of sendSelectors) {
109
- const btn = page.locator(sel).first();
110
- if (await btn.isVisible({ timeout: 3000 }).catch(() => false)) {
111
- await humanClick(page, btn);
112
- sent = true;
113
- break;
114
- }
115
- }
116
-
117
- if (!sent) {
118
- await page.keyboard.press('Control+Enter');
119
- }
120
-
121
- // Wait for the compose surface to close. The comment editor detaching is the
122
- // ONLY reliable success signal we have; if it never closes the comment may or
123
- // may not have been submitted, so the outcome is UNKNOWN — never report
124
- // success (and never auto-retry, since a comment is not idempotent).
125
- let editorDetached = false;
126
- try {
127
- await page.waitForSelector('[data-testid="tweetTextarea_0"]', { state: 'detached', timeout: 15000 });
128
- editorDetached = true;
129
- } catch {
130
- await page.keyboard.press('Control+Enter');
131
- await sleep(3000);
132
- const stillVisible = await page.locator('[data-testid="tweetTextarea_0"]').first().isVisible({ timeout: 2000 }).catch(() => false);
133
- editorDetached = !stillVisible;
134
- }
135
-
136
- // Check for failure
137
- const bodyText = await page.evaluate(() => document.body.innerText).catch(() => '');
138
- if (/something went wrong|try again|failed/i.test(bodyText)) {
139
- throw new Error('Comment submit reported a failure');
140
- }
141
-
142
- if (!editorDetached) {
143
- return {
144
- success: false,
145
- code: 'UNKNOWN_OUTCOME',
146
- outcome: 'unknown',
147
- error: 'Comment submit could not be confirmed (editor is still open); outcome unknown',
148
- };
149
- }
150
-
151
- return { success: true, message: 'Comment posted' };
152
- }
153
-
154
- module.exports = { comment };
1
+ 'use strict';
2
+
3
+ /**
4
+ * Comment action — post a reply/comment on a tweet.
5
+ *
6
+ * NON-IDEMPOTENT. The submit mutation is dispatched AT MOST ONCE. After that
7
+ * the outcome is established by PASSIVE, read-only confirmation bound to the
8
+ * exact compose surface used; if that cannot prove success the result is
9
+ * UNKNOWN_OUTCOME (never a second submit, never a false success).
10
+ */
11
+
12
+ const { sleep, humanDelay, randDelay, naturalNavigate, humanPreAction, humanType, humanClick, detectStage } = require('./helpers');
13
+ const { captureComposeSurface, countArticlesWithText, confirmSubmission, SUBMIT_CONFIRM_TIMEOUT_MS } = require('./confirmation');
14
+
15
+ const FAILURE_TOAST = /something went wrong|try again|failed/i;
16
+
17
+ async function comment(page, payload) {
18
+ const { tweetUrl, commentText } = payload;
19
+ if (!tweetUrl || !commentText) throw new Error('tweetUrl and commentText required');
20
+
21
+ // Navigate to the tweet
22
+ await page.goto(tweetUrl, { waitUntil: 'domcontentloaded', timeout: 30000 }).catch(() => {});
23
+ await randDelay(1800, 3200);
24
+
25
+ if (page.url().includes('/login') || page.url().includes('/i/flow')) {
26
+ throw new Error('Not logged in — open browser and login first');
27
+ }
28
+
29
+ // Find and click the reply button
30
+ const tweetIdMatch = tweetUrl.match(/\/status\/(\d+)/);
31
+ const tweetId = tweetIdMatch ? tweetIdMatch[1] : null;
32
+ const replySelectors = [
33
+ 'button[data-testid="reply"]',
34
+ '[data-testid="reply"]',
35
+ 'button[aria-label*="Reply"]',
36
+ ];
37
+
38
+ let replyClicked = false;
39
+ for (const sel of replySelectors) {
40
+ const scoped = tweetId ? `article:has(a[href*="/status/${tweetId}"]) ${sel}` : sel;
41
+ const btn = page.locator(scoped).first();
42
+ if (await btn.isVisible({ timeout: 3000 }).catch(() => false)) {
43
+ await humanClick(page, btn);
44
+ replyClicked = true;
45
+ break;
46
+ }
47
+ }
48
+
49
+ if (!replyClicked && tweetId) {
50
+ // Fallback for tweet detail pages where the target article does not include
51
+ // a status link back to itself.
52
+ for (const sel of replySelectors) {
53
+ const btn = page.locator(sel).first();
54
+ if (await btn.isVisible({ timeout: 3000 }).catch(() => false)) {
55
+ await humanClick(page, btn);
56
+ replyClicked = true;
57
+ break;
58
+ }
59
+ }
60
+ }
61
+
62
+ if (!replyClicked) throw new Error('Could not find reply button');
63
+
64
+ // Wait for dialog or inline editor
65
+ await sleep(1500);
66
+ const editorSelectors = [
67
+ 'div[role="dialog"] [data-testid="tweetTextarea_0"] div[contenteditable="true"][role="textbox"]',
68
+ '[data-testid="tweetTextarea_0"] div[contenteditable="true"][role="textbox"]',
69
+ '.public-DraftEditor-content',
70
+ ];
71
+
72
+ let editor = null;
73
+ for (const sel of editorSelectors) {
74
+ const el = page.locator(sel).first();
75
+ if (await el.isVisible({ timeout: 5000 }).catch(() => false)) {
76
+ editor = el;
77
+ break;
78
+ }
79
+ }
80
+
81
+ if (!editor) throw new Error('Could not find comment editor');
82
+ await editor.click();
83
+ await humanDelay(300, 600);
84
+
85
+ // Clear any existing text
86
+ await page.keyboard.press('Control+a');
87
+ await page.keyboard.press('Backspace');
88
+
89
+ // Type comment
90
+ const isRTL = /[\u0600-\u06FF\u0750-\u077F]/.test(commentText);
91
+ if (isRTL) {
92
+ await page.evaluate(() => {
93
+ const el = document.querySelector('[data-testid="tweetTextarea_0"]');
94
+ if (el) el.setAttribute('dir', 'rtl');
95
+ });
96
+ const words = commentText.split(' ');
97
+ for (const word of words) {
98
+ await page.evaluate((w) => document.execCommand('insertText', false, w + ' '), word);
99
+ await humanDelay(50, 100);
100
+ }
101
+ } else {
102
+ await humanType(page, commentText, { delayMin: 50, delayMax: 150 });
103
+ }
104
+
105
+ await humanDelay(500, 1000);
106
+
107
+ // ── Bind confirmation to the EXACT compose surface used ──────────────────
108
+ const surface = await captureComposeSurface(page);
109
+ const matchesBefore = (await countArticlesWithText(page, commentText)) || 0;
110
+
111
+ // ── ONE submission. Exactly one of {send-button click, Ctrl+Enter}. ──────
112
+ const sendSelectors = [
113
+ 'div[role="dialog"] [data-testid="tweetButton"]',
114
+ '[data-testid="tweetButton"]',
115
+ '[data-testid="tweetButtonInline"]',
116
+ ];
117
+
118
+ let submitted = false;
119
+ for (const sel of sendSelectors) {
120
+ const btn = page.locator(sel).first();
121
+ if (await btn.isVisible({ timeout: 3000 }).catch(() => false)) {
122
+ await humanClick(page, btn);
123
+ submitted = true;
124
+ break;
125
+ }
126
+ }
127
+ if (!submitted) {
128
+ await page.keyboard.press('Control+Enter');
129
+ }
130
+
131
+ // ── PASSIVE confirmation. NEVER submit again. ────────────────────────────
132
+ const confirmed = await confirmSubmission(page, {
133
+ surface, text: commentText, matchesBefore, timeoutMs: SUBMIT_CONFIRM_TIMEOUT_MS,
134
+ });
135
+
136
+ if (confirmed) return { success: true, message: 'Comment posted' };
137
+
138
+ // Not confirmed: a clear X failure toast is a KNOWN failure (the submit is
139
+ // never repeated either way).
140
+ const bodyText = await page.evaluate(() => document.body.innerText).catch(() => '');
141
+ if (FAILURE_TOAST.test(bodyText)) {
142
+ throw new Error('Comment submit reported a failure');
143
+ }
144
+
145
+ return {
146
+ success: false,
147
+ code: 'UNKNOWN_OUTCOME',
148
+ outcome: 'unknown',
149
+ error: 'Comment submit could not be confirmed; outcome unknown',
150
+ };
151
+ }
152
+
153
+ module.exports = { comment };
@@ -0,0 +1,129 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Passive submission confirmation for NON-IDEMPOTENT actions (tweet, comment).
5
+ *
6
+ * Invariant: once ANY submit mutation has been dispatched, this module performs
7
+ * NO further mutation. It only OBSERVES. If positive evidence cannot be
8
+ * established it reports "unconfirmed" and the caller returns UNKNOWN_OUTCOME.
9
+ *
10
+ * The false-negative this fixes: the old code waited on the GLOBAL selector
11
+ * `[data-testid="tweetTextarea_0"]` to detach, then pressed Control+Enter a
12
+ * SECOND time. On a tweet page the reply MODAL closes but an INLINE
13
+ * "Post your reply" editor remains, so the global selector never detaches, the
14
+ * second Ctrl+Enter retried a non-idempotent post, and the result was still
15
+ * reported UNKNOWN despite a successful submission. Confirmation must be bound
16
+ * to the EXACT compose surface that was submitted.
17
+ */
18
+
19
+ const { sleep } = require('./helpers');
20
+
21
+ /** Parse a bounded integer env override; invalid/out-of-range falls back. */
22
+ function boundedIntEnv(name, def, min, max) {
23
+ const raw = process.env[name];
24
+ if (raw === undefined || raw === null || raw === '') return def;
25
+ const v = Number.parseInt(String(raw), 10);
26
+ if (!Number.isFinite(v) || v < min || v > max) return def;
27
+ return v;
28
+ }
29
+
30
+ // Bounded and comfortably below the server runAction budget (180000 ms).
31
+ const SUBMIT_CONFIRM_TIMEOUT_MS = boundedIntEnv('LOCAL_AGENT_SUBMIT_CONFIRM_TIMEOUT_MS', 15000, 2000, 60000);
32
+ const CONFIRM_POLL_MS = boundedIntEnv('LOCAL_AGENT_SUBMIT_CONFIRM_POLL_MS', 250, 50, 2000);
33
+
34
+ const DEFAULT_EDITOR_SELECTOR = '[data-testid="tweetTextarea_0"]';
35
+
36
+ /**
37
+ * Capture the EXACT compose surface in use, IMMEDIATELY before submission.
38
+ * Read-only. Returns a descriptor the confirmation binds to.
39
+ */
40
+ async function captureComposeSurface(page, editorSelector = DEFAULT_EDITOR_SELECTOR) {
41
+ let dialogCount = 0;
42
+ try { dialogCount = await page.locator('div[role="dialog"]').count(); } catch { dialogCount = 0; }
43
+ const inDialog = dialogCount > 0;
44
+ const scope = inDialog ? `div[role="dialog"] ${editorSelector}` : editorSelector;
45
+ let scopeCount = 0;
46
+ try { scopeCount = await page.locator(scope).count(); } catch { scopeCount = 0; }
47
+ return { editorSelector, inDialog, scope, scopeCountBefore: scopeCount };
48
+ }
49
+
50
+ /** Read-only: has the captured compose surface closed / detached? */
51
+ async function composeSurfaceGone(page, surface) {
52
+ if (!surface) return false;
53
+ try {
54
+ if (surface.inDialog) {
55
+ const dialogs = await page.locator('div[role="dialog"]').count();
56
+ if (dialogs === 0) return true;
57
+ }
58
+ const n = await page.locator(surface.scope).count();
59
+ return n === 0;
60
+ } catch {
61
+ return false;
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Read-only: how many `article` elements contain the exact submitted text?
67
+ * Used as STRONG secondary evidence of a new reply/post (bound to the exact
68
+ * text; the caller compares against the pre-submit count so a pre-existing
69
+ * identical item never counts).
70
+ */
71
+ async function countArticlesWithText(page, text) {
72
+ if (!text) return null;
73
+ try {
74
+ return await page.evaluate((needle) => {
75
+ const arts = Array.from(document.querySelectorAll('article'));
76
+ return arts.filter((a) => (a.innerText || '').includes(needle)).length;
77
+ }, text);
78
+ } catch {
79
+ return null;
80
+ }
81
+ }
82
+
83
+ /**
84
+ * PASSIVE confirmation loop. NEVER clicks, types, or presses. Bounded.
85
+ * Returns true only on positive evidence bound to the captured surface:
86
+ * - the exact compose surface used has closed/detached, OR
87
+ * - a NEW article containing the exact submitted text appeared, OR
88
+ * - an action-supplied extraProbe() (read-only) reports a known post-submit state.
89
+ */
90
+ async function confirmSubmission(page, opts = {}) {
91
+ const {
92
+ surface = null,
93
+ text = null,
94
+ matchesBefore = 0,
95
+ timeoutMs = SUBMIT_CONFIRM_TIMEOUT_MS,
96
+ pollMs = CONFIRM_POLL_MS,
97
+ extraProbe = null,
98
+ sleepFn = sleep,
99
+ now = Date.now,
100
+ } = opts;
101
+
102
+ const probe = async () => {
103
+ if (await composeSurfaceGone(page, surface)) return true;
104
+ if (text) {
105
+ const matches = await countArticlesWithText(page, text);
106
+ if (matches !== null && matches > matchesBefore) return true;
107
+ }
108
+ if (extraProbe) { try { if (await extraProbe()) return true; } catch { /* read-only probe must never throw */ } }
109
+ return false;
110
+ };
111
+
112
+ const deadline = now() + timeoutMs;
113
+ while (now() < deadline) {
114
+ if (await probe()) return true;
115
+ await sleepFn(pollMs);
116
+ }
117
+ return await probe();
118
+ }
119
+
120
+ module.exports = {
121
+ captureComposeSurface,
122
+ composeSurfaceGone,
123
+ countArticlesWithText,
124
+ confirmSubmission,
125
+ boundedIntEnv,
126
+ SUBMIT_CONFIRM_TIMEOUT_MS,
127
+ CONFIRM_POLL_MS,
128
+ DEFAULT_EDITOR_SELECTOR,
129
+ };
@@ -1,123 +1,179 @@
1
- 'use strict';
2
-
3
- /**
4
- * Follow action — follow a user on X.
5
- * Ported from backend/routes/browser.js doFollow().
6
- */
7
-
8
- const { sleep, humanDelay, randDelay, naturalNavigate, humanPreAction, humanClick, detectStage } = require('./helpers');
9
-
10
- // Follow button labels in multiple languages
11
- const FOLLOW_LABELS = [
12
- 'follow', 'seguir', 'suivre', 'folgen', 'تابع', 'フォロー',
13
- 'segui', 'volgen', 'śledź', 'seguir', '关注', '팔로우',
14
- ];
15
-
16
- const FOLLOWING_LABELS = [
17
- 'following', 'siguiendo', 'abonné', 'folgt', 'يتابعك', 'フォロー中',
18
- 'following', 'volgend', 'obserwujesz', 'seguindo', '已关注', '팔로잉',
19
- 'unfollow', 'dejar de seguir', 'ne plus suivre', 'entfolgen', 'إلغاء المتابعة',
20
- ];
21
-
22
- /**
23
- * Confirm a follow actually took effect. A click that did not throw is NOT
24
- * evidence. We accept the standard post-follow signals (the unfollow testid or
25
- * a Following/Unfollow control). Bounded wait; never throws.
26
- */
27
- const FOLLOW_CONFIRM_TIMEOUT_MS = parseInt(process.env.LOCAL_AGENT_FOLLOW_CONFIRM_TIMEOUT_MS || '8000', 10);
28
-
29
- async function confirmFollow(page, cleanUsername) {
30
- const deadline = Date.now() + FOLLOW_CONFIRM_TIMEOUT_MS;
31
- while (Date.now() < deadline) {
32
- const candidates = [
33
- `[data-testid="${cleanUsername}-unfollow"]`,
34
- '[data-testid="unfollow"]',
35
- '[role="button"][aria-label*="Following"]',
36
- '[role="button"][aria-label*="Unfollow"]',
37
- 'button[aria-label*="Following"]',
38
- 'button[aria-label*="Unfollow"]',
39
- ];
40
- for (const sel of candidates) {
41
- const el = page.locator(sel).first();
42
- if (await el.isVisible({ timeout: 500 }).catch(() => false)) return true;
43
- }
44
- await sleep(1000);
45
- }
46
- return false;
47
- }
48
-
49
- function unconfirmedFollow(cleanUsername) {
50
- return {
51
- success: false,
52
- code: 'UNKNOWN_OUTCOME',
53
- outcome: 'unknown',
54
- error: `Follow click for @${cleanUsername} could not be confirmed; outcome unknown`,
55
- };
56
- }
57
-
58
- async function follow(page, payload) {
59
- const { username } = payload;
60
- if (!username) throw new Error('username required');
61
-
62
- const cleanUsername = String(username).replace(/^@/, '').replace(/^.*x\.com\//, '');
63
- await naturalNavigate(page, `https://x.com/${cleanUsername}`);
64
- await humanPreAction(page);
65
-
66
- // Check if page loaded properly
67
- if (page.url().includes('/login') || page.url().includes('/i/flow')) {
68
- throw new Error('Not logged in — open browser and login first');
69
- }
70
-
71
- // Check for suspended/not-found
72
- const title = await page.title().catch(() => '');
73
- const bodyText = await page.evaluate(() => document.body.innerText).catch(() => '');
74
- if (/account suspended|doesn't exist|page doesn't exist/i.test(title + bodyText)) {
75
- throw new Error(`Account @${cleanUsername} is suspended or not found`);
76
- }
77
-
78
- // Strategy 1: data-testid selectors
79
- const testIdSelectors = [
80
- `[data-testid="${cleanUsername}-follow"]`,
81
- '[data-testid="follow"]',
82
- ];
83
- for (const sel of testIdSelectors) {
84
- const btn = page.locator(sel).first();
85
- if (await btn.isVisible({ timeout: 2000 }).catch(() => false)) {
86
- await humanClick(page, btn);
87
- if (await confirmFollow(page, cleanUsername)) {
88
- return { success: true, message: `Following @${cleanUsername}` };
89
- }
90
- return unconfirmedFollow(cleanUsername);
91
- }
92
- }
93
-
94
- // Strategy 2: scan buttons for follow labels
95
- const buttons = page.locator('[role="button"], button');
96
- const count = await buttons.count();
97
- for (let i = 0; i < count; i++) {
98
- const btn = buttons.nth(i);
99
- const text = (await btn.innerText().catch(() => '')).toLowerCase().trim();
100
- if (FOLLOW_LABELS.some(label => text === label || text.includes(label))) {
101
- // Check if it's actually "following" (already following)
102
- if (FOLLOWING_LABELS.some(label => text.includes(label))) continue;
103
- await humanClick(page, btn);
104
- if (await confirmFollow(page, cleanUsername)) {
105
- return { success: true, message: `Following @${cleanUsername}` };
106
- }
107
- return unconfirmedFollow(cleanUsername);
108
- }
109
- }
110
-
111
- // Check if already following
112
- for (let i = 0; i < count; i++) {
113
- const btn = buttons.nth(i);
114
- const text = (await btn.innerText().catch(() => '')).toLowerCase().trim();
115
- if (FOLLOWING_LABELS.some(label => text.includes(label))) {
116
- return { success: true, message: `Already following @${cleanUsername}`, status: 'already_following' };
117
- }
118
- }
119
-
120
- throw new Error(`Could not find follow button for @${cleanUsername}`);
121
- }
122
-
123
- module.exports = { follow };
1
+ 'use strict';
2
+
3
+ /**
4
+ * Follow action — follow a user on X.
5
+ *
6
+ * Hardened 2.0.7:
7
+ * - the clicked control is PROVEN to belong to the target profile (bound by
8
+ * the target handle in the aria-label or a handle-based testid). A
9
+ * recommendation/suggestion Follow button can never satisfy the selector.
10
+ * - the numeric X user-id testid form (`<digits>-follow` / `<digits>-unfollow`)
11
+ * that current X renders is supported via the target-bound aria/state.
12
+ * - pre-action state is classified: ALREADY_FOLLOWING returns success WITHOUT
13
+ * clicking; FOLLOWABLE_TARGET is clicked EXACTLY ONCE; an ambiguous control
14
+ * fails safely BEFORE any mutation.
15
+ * - post-click confirmation is READ-ONLY and reuses FOLLOWING_LABELS (not
16
+ * English-only). Bounded, validated window (default 15 s).
17
+ * - a successful click that cannot be confirmed is UNKNOWN_OUTCOME, never a
18
+ * false success and never an auto-retry; the click is never repeated.
19
+ */
20
+
21
+ const { sleep, humanDelay, randDelay, naturalNavigate, humanPreAction, humanClick, detectStage } = require('./helpers');
22
+ const { boundedIntEnv } = require('./confirmation');
23
+
24
+ // Follow button labels in multiple languages
25
+ const FOLLOW_LABELS = [
26
+ 'follow', 'seguir', 'suivre', 'folgen', 'تابع', 'フォロー',
27
+ 'segui', 'volgen', 'śledź', 'seguir', '关注', '팔로우',
28
+ ];
29
+
30
+ const FOLLOWING_LABELS = [
31
+ 'following', 'siguiendo', 'abonné', 'folgt', 'يتابعك', 'متابعة', 'フォロー中',
32
+ 'following', 'volgend', 'obserwujesz', 'seguindo', '已关注', '팔로잉',
33
+ 'unfollow', 'dejar de seguir', 'ne plus suivre', 'entfolgen', 'إلغاء المتابعة',
34
+ ];
35
+
36
+ // Bounded and comfortably below runAction's server budget (180000 ms).
37
+ const FOLLOW_CONFIRM_TIMEOUT_MS = boundedIntEnv('LOCAL_AGENT_FOLLOW_CONFIRM_TIMEOUT_MS', 15000, 2000, 60000);
38
+ const FOLLOW_CONFIRM_POLL_MS = boundedIntEnv('LOCAL_AGENT_FOLLOW_CONFIRM_POLL_MS', 400, 50, 2000);
39
+
40
+ function norm(value) { return String(value == null ? '' : value).toLowerCase().replace(/\s+/g, ' ').trim(); }
41
+ function escapeRe(s) { return String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }
42
+
43
+ function mentionsHandle(aria, username) { return norm(aria).includes('@' + norm(username)); }
44
+ function testidMatchesHandle(testid, username) {
45
+ return new RegExp(`^${escapeRe(String(username))}-(follow|unfollow)$`, 'i').test(String(testid || ''));
46
+ }
47
+ function isUnfollowTestid(testid) { return /-unfollow$/i.test(String(testid || '')); }
48
+ function isFollowTestid(testid) { return /-follow$/i.test(String(testid || '')); }
49
+ function textIndicatesFollowing(text) { const n = norm(text); return FOLLOWING_LABELS.some((l) => n.includes(norm(l))); }
50
+ function textIndicatesFollow(text) { const n = norm(text); return FOLLOW_LABELS.some((l) => n.includes(norm(l))); }
51
+
52
+ /**
53
+ * PURE: pick the control that is PROVEN to belong to the target profile.
54
+ * Target-bound = the aria-label mentions the target handle, or the testid is the
55
+ * handle-based follow/unfollow form. Controls inside a UserCell (suggestion) are
56
+ * rejected outright, and a bare numeric testid is never target-bound on its own.
57
+ */
58
+ function selectTargetControl(controls, username) {
59
+ const list = Array.isArray(controls) ? controls : [];
60
+ for (const c of list) {
61
+ if (!c || c.visible === false || c.inUserCell) continue;
62
+ if (mentionsHandle(c.aria, username) || testidMatchesHandle(c.testid, username)) return c;
63
+ }
64
+ return null;
65
+ }
66
+
67
+ /** PURE: classify the target control's pre-action state. */
68
+ function classifyControl(control) {
69
+ if (!control) return 'unknown';
70
+ const combined = `${control.text || ''} ${control.aria || ''}`;
71
+ if (isUnfollowTestid(control.testid) || textIndicatesFollowing(combined)) return 'following';
72
+ if (isFollowTestid(control.testid)) return 'followable';
73
+ if (textIndicatesFollow(combined)) return 'followable';
74
+ return 'unknown';
75
+ }
76
+
77
+ /** Read-only: descriptors for every button/[role=button], in DOM order. */
78
+ async function readActionControls(page) {
79
+ return await page.evaluate(() => {
80
+ const els = Array.from(document.querySelectorAll('button, [role="button"]'));
81
+ return els.map((el, i) => ({
82
+ i,
83
+ text: (el.innerText || '').trim().slice(0, 80),
84
+ aria: el.getAttribute('aria-label') || '',
85
+ testid: el.getAttribute('data-testid') || '',
86
+ inUserCell: !!el.closest('[data-testid="UserCell"]'),
87
+ visible: !!(el.offsetParent !== null || el.getClientRects().length > 0),
88
+ }));
89
+ });
90
+ }
91
+
92
+ function controlLocator(page, index) {
93
+ return page.locator('button, [role="button"]').nth(index);
94
+ }
95
+
96
+ /**
97
+ * READ-ONLY wait until the TARGET control reports a followed state.
98
+ * Never clicks. Bounded.
99
+ */
100
+ async function confirmFollow(page, username, timeoutMs = FOLLOW_CONFIRM_TIMEOUT_MS) {
101
+ const deadline = Date.now() + timeoutMs;
102
+ while (Date.now() < deadline) {
103
+ const control = selectTargetControl(await readActionControls(page), username);
104
+ if (control && classifyControl(control) === 'following') return true;
105
+ await sleep(FOLLOW_CONFIRM_POLL_MS);
106
+ }
107
+ const control = selectTargetControl(await readActionControls(page), username);
108
+ return !!(control && classifyControl(control) === 'following');
109
+ }
110
+
111
+ async function follow(page, payload) {
112
+ const { username } = payload;
113
+ if (!username) throw new Error('username required');
114
+
115
+ const cleanUsername = String(username).replace(/^@/, '').replace(/^.*x\.com\//, '');
116
+ await naturalNavigate(page, `https://x.com/${cleanUsername}`);
117
+ await humanPreAction(page);
118
+
119
+ if (page.url().includes('/login') || page.url().includes('/i/flow')) {
120
+ throw new Error('Not logged in — open browser and login first');
121
+ }
122
+
123
+ // Check for suspended/not-found
124
+ const title = await page.title().catch(() => '');
125
+ const bodyText = await page.evaluate(() => document.body.innerText).catch(() => '');
126
+ if (/account suspended|doesn't exist|page doesn't exist/i.test(title + bodyText)) {
127
+ throw new Error(`Account @${cleanUsername} is suspended or not found`);
128
+ }
129
+
130
+ // ── Pre-action: resolve the TARGET profile control and its state. ─────────
131
+ const controls = await readActionControls(page);
132
+ const control = selectTargetControl(controls, cleanUsername);
133
+ if (!control) {
134
+ // No target-bound control → nothing to click. Known pre-action failure (no
135
+ // mutation happened). A suggestion's Follow button can never satisfy this.
136
+ throw new Error(`Could not find the target follow control for @${cleanUsername}`);
137
+ }
138
+
139
+ const state = classifyControl(control);
140
+ if (state === 'following') {
141
+ return { success: true, message: `Already following @${cleanUsername}`, status: 'already_following' };
142
+ }
143
+ if (state !== 'followable') {
144
+ // Ambiguous target control → fail safely BEFORE any mutation.
145
+ throw new Error(`Target follow control for @${cleanUsername} is in an ambiguous state`);
146
+ }
147
+
148
+ // ── EXACTLY ONE target-bound click. ───────────────────────────────────────
149
+ await humanClick(page, controlLocator(page, control.i));
150
+ await sleep(1000);
151
+
152
+ // ── READ-ONLY confirmation. Never clicks again. ───────────────────────────
153
+ if (await confirmFollow(page, cleanUsername, FOLLOW_CONFIRM_TIMEOUT_MS)) {
154
+ return { success: true, message: `Following @${cleanUsername}` };
155
+ }
156
+
157
+ return {
158
+ success: false,
159
+ code: 'UNKNOWN_OUTCOME',
160
+ outcome: 'unknown',
161
+ error: `Follow click for @${cleanUsername} could not be confirmed; outcome unknown`,
162
+ };
163
+ }
164
+
165
+ module.exports = {
166
+ follow,
167
+ _internals: {
168
+ norm,
169
+ mentionsHandle,
170
+ testidMatchesHandle,
171
+ isUnfollowTestid,
172
+ isFollowTestid,
173
+ textIndicatesFollowing,
174
+ textIndicatesFollow,
175
+ selectTargetControl,
176
+ classifyControl,
177
+ FOLLOW_CONFIRM_TIMEOUT_MS,
178
+ },
179
+ };
@@ -1,107 +1,107 @@
1
- 'use strict';
2
-
3
- /**
4
- * Tweet action — compose and post a tweet.
5
- * Ported from backend/routes/browser.js doTweet().
6
- */
7
-
8
- const { sleep, humanDelay, randDelay, naturalNavigate, humanPreAction, humanType, humanClick, detectStage, waitForLoggedIn, injectCookies } = require('./helpers');
9
-
10
- async function tweet(page, payload) {
11
- const { text } = payload;
12
- if (!text) throw new Error('Tweet text required');
13
-
14
- // Navigate to compose page
15
- await page.goto('https://x.com/compose/post', { waitUntil: 'domcontentloaded', timeout: 30000 }).catch(() => {});
16
- await randDelay(2000, 4000);
17
-
18
- // Check if logged in
19
- const stage = await detectStage(page);
20
- if (stage === 'login_required' || stage === 'login_username_step' || stage === 'login_password_step') {
21
- throw new Error('Not logged in — open browser and login first');
22
- }
23
-
24
- // Wait for the compose textarea
25
- const editorSelector = '[data-testid="tweetTextarea_0"]';
26
- await page.waitForSelector(editorSelector, { timeout: 15000 });
27
- const editor = page.locator(editorSelector).first();
28
- await editor.click();
29
- await humanDelay(300, 600);
30
-
31
- // Detect RTL (Arabic) text
32
- const isRTL = /[\u0600-\u06FF\u0750-\u077F]/.test(text);
33
- if (isRTL) {
34
- await page.evaluate((t) => {
35
- const el = document.querySelector('[data-testid="tweetTextarea_0"]');
36
- if (el) { el.setAttribute('dir', 'rtl'); }
37
- }, text);
38
- // Type word by word for RTL
39
- const words = text.split(' ');
40
- for (const word of words) {
41
- await page.evaluate((w) => {
42
- document.execCommand('insertText', false, w + ' ');
43
- }, word);
44
- await humanDelay(50, 120);
45
- }
46
- } else {
47
- // Humanized typing with randomized delays, pauses, and rare typos
48
- await humanType(page, text, { delayMin: 50, delayMax: 150 });
49
- }
50
-
51
- await humanDelay(500, 1000);
52
-
53
- // Click the post button
54
- const postSelectors = [
55
- '[data-testid="tweetButton"]',
56
- '[data-testid="tweetButtonInline"]',
57
- ];
58
- let posted = false;
59
- for (const sel of postSelectors) {
60
- const btn = page.locator(sel).first();
61
- if (await btn.isVisible({ timeout: 3000 }).catch(() => false)) {
62
- await humanClick(page, btn);
63
- posted = true;
64
- break;
65
- }
66
- }
67
-
68
- if (!posted) {
69
- // Fallback: Ctrl+Enter
70
- await page.keyboard.press('Control+Enter');
71
- }
72
-
73
- // Wait for the compose surface to close. Detachment of the composer is the
74
- // ONLY reliable success signal we have; if it never closes the tweet may or
75
- // may not have been submitted, so the outcome is UNKNOWN — never report
76
- // success (and never auto-retry, since a tweet is not idempotent).
77
- let editorDetached = false;
78
- try {
79
- await page.waitForSelector(editorSelector, { state: 'detached', timeout: 15000 });
80
- editorDetached = true;
81
- } catch {
82
- // Retry with Ctrl+Enter
83
- await page.keyboard.press('Control+Enter');
84
- await sleep(3000);
85
- const stillVisible = await page.locator(editorSelector).first().isVisible({ timeout: 2000 }).catch(() => false);
86
- editorDetached = !stillVisible;
87
- }
88
-
89
- // Check for failure toast
90
- const bodyText = await page.evaluate(() => document.body.innerText).catch(() => '');
91
- if (/something went wrong|try again|failed/i.test(bodyText)) {
92
- throw new Error('Tweet submit reported a failure toast');
93
- }
94
-
95
- if (!editorDetached) {
96
- return {
97
- success: false,
98
- code: 'UNKNOWN_OUTCOME',
99
- outcome: 'unknown',
100
- error: 'Tweet submit could not be confirmed (compose box is still open); outcome unknown',
101
- };
102
- }
103
-
104
- return { success: true, message: 'Tweet posted' };
105
- }
106
-
107
- module.exports = { tweet };
1
+ 'use strict';
2
+
3
+ /**
4
+ * Tweet action — compose and post a tweet.
5
+ *
6
+ * NON-IDEMPOTENT. The submit mutation is dispatched AT MOST ONCE. The outcome
7
+ * is then established by PASSIVE, read-only confirmation bound to the exact
8
+ * compose surface used; if success cannot be proven the result is
9
+ * UNKNOWN_OUTCOME (never a second Ctrl+Enter, never a false success).
10
+ */
11
+
12
+ const { sleep, humanDelay, randDelay, naturalNavigate, humanPreAction, humanType, humanClick, detectStage, waitForLoggedIn, injectCookies } = require('./helpers');
13
+ const { captureComposeSurface, countArticlesWithText, confirmSubmission, SUBMIT_CONFIRM_TIMEOUT_MS } = require('./confirmation');
14
+
15
+ const FAILURE_TOAST = /something went wrong|try again|failed/i;
16
+ const COMPOSE_URL_MARKER = '/compose/post';
17
+
18
+ async function tweet(page, payload) {
19
+ const { text } = payload;
20
+ if (!text) throw new Error('Tweet text required');
21
+
22
+ // Navigate to compose page
23
+ await page.goto('https://x.com/compose/post', { waitUntil: 'domcontentloaded', timeout: 30000 }).catch(() => {});
24
+ await randDelay(2000, 4000);
25
+
26
+ // Check if logged in
27
+ const stage = await detectStage(page);
28
+ if (stage === 'login_required' || stage === 'login_username_step' || stage === 'login_password_step') {
29
+ throw new Error('Not logged in — open browser and login first');
30
+ }
31
+
32
+ // Wait for the compose textarea
33
+ const editorSelector = '[data-testid="tweetTextarea_0"]';
34
+ await page.waitForSelector(editorSelector, { timeout: 15000 });
35
+ const editor = page.locator(editorSelector).first();
36
+ await editor.click();
37
+ await humanDelay(300, 600);
38
+
39
+ // Detect RTL (Arabic) text
40
+ const isRTL = /[\u0600-\u06FF\u0750-\u077F]/.test(text);
41
+ if (isRTL) {
42
+ await page.evaluate((t) => {
43
+ const el = document.querySelector('[data-testid="tweetTextarea_0"]');
44
+ if (el) { el.setAttribute('dir', 'rtl'); }
45
+ }, text);
46
+ const words = text.split(' ');
47
+ for (const word of words) {
48
+ await page.evaluate((w) => {
49
+ document.execCommand('insertText', false, w + ' ');
50
+ }, word);
51
+ await humanDelay(50, 120);
52
+ }
53
+ } else {
54
+ await humanType(page, text, { delayMin: 50, delayMax: 150 });
55
+ }
56
+
57
+ await humanDelay(500, 1000);
58
+
59
+ // ── Bind confirmation to the EXACT compose surface used ──────────────────
60
+ const surface = await captureComposeSurface(page);
61
+ const matchesBefore = (await countArticlesWithText(page, text)) || 0;
62
+
63
+ // ── ONE submission. Exactly one of {post-button click, Ctrl+Enter}. ──────
64
+ const postSelectors = [
65
+ '[data-testid="tweetButton"]',
66
+ '[data-testid="tweetButtonInline"]',
67
+ ];
68
+ let submitted = false;
69
+ for (const sel of postSelectors) {
70
+ const btn = page.locator(sel).first();
71
+ if (await btn.isVisible({ timeout: 3000 }).catch(() => false)) {
72
+ await humanClick(page, btn);
73
+ submitted = true;
74
+ break;
75
+ }
76
+ }
77
+ if (!submitted) {
78
+ await page.keyboard.press('Control+Enter');
79
+ }
80
+
81
+ // ── PASSIVE confirmation. NEVER submit again. ────────────────────────────
82
+ const confirmed = await confirmSubmission(page, {
83
+ surface,
84
+ text,
85
+ matchesBefore,
86
+ timeoutMs: SUBMIT_CONFIRM_TIMEOUT_MS,
87
+ // The composer leaves /compose/post on a successful post (read-only).
88
+ extraProbe: async () => !page.url().includes(COMPOSE_URL_MARKER),
89
+ });
90
+
91
+ if (confirmed) return { success: true, message: 'Tweet posted' };
92
+
93
+ // Not confirmed: a clear X failure toast is a KNOWN failure (never resubmit).
94
+ const bodyText = await page.evaluate(() => document.body.innerText).catch(() => '');
95
+ if (FAILURE_TOAST.test(bodyText)) {
96
+ throw new Error('Tweet submit reported a failure toast');
97
+ }
98
+
99
+ return {
100
+ success: false,
101
+ code: 'UNKNOWN_OUTCOME',
102
+ outcome: 'unknown',
103
+ error: 'Tweet submit could not be confirmed; outcome unknown',
104
+ };
105
+ }
106
+
107
+ module.exports = { tweet };
package/src/cli.js CHANGED
@@ -24,7 +24,7 @@ const crypto = require('crypto');
24
24
  const os = require('os');
25
25
  const path = require('path');
26
26
 
27
- const CLI_VERSION = '2.0.6';
27
+ const CLI_VERSION = '2.0.7';
28
28
  const PROTOCOL_VERSION = 2;
29
29
 
30
30
  // ── Command parsing ──────────────────────────────────────────────────────────