dsh-browserpaw 5.0.0 → 5.0.1

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.
@@ -17,7 +17,12 @@
17
17
  "x",
18
18
  "twitter",
19
19
  "search",
20
- "posts"
20
+ "posts",
21
+ "推特",
22
+ "推文",
23
+ "推特搜索",
24
+ "搜索推文",
25
+ "X搜索"
21
26
  ],
22
27
  "startUrl": "https://x.com/search?q={{query}}&src=typed_query&f=live",
23
28
  "inputSchema": {
@@ -51,6 +56,9 @@
51
56
  "status": {
52
57
  "const": "ok"
53
58
  },
59
+ "coverage": {
60
+ "const": "visible_only"
61
+ },
54
62
  "query": {
55
63
  "type": "string",
56
64
  "minLength": 1
@@ -118,6 +126,9 @@
118
126
  "status": {
119
127
  "const": "empty"
120
128
  },
129
+ "coverage": {
130
+ "const": "visible_only"
131
+ },
121
132
  "query": {
122
133
  "type": "string",
123
134
  "minLength": 1
@@ -149,45 +160,6 @@
149
160
  "sources"
150
161
  ],
151
162
  "additionalProperties": false
152
- },
153
- {
154
- "type": "object",
155
- "properties": {
156
- "success": {
157
- "const": false
158
- },
159
- "status": {
160
- "enum": [
161
- "requires_auth",
162
- "loading_timeout",
163
- "unreadable"
164
- ]
165
- },
166
- "requiresLogin": {
167
- "type": "boolean"
168
- },
169
- "message": {
170
- "type": "string",
171
- "minLength": 1
172
- },
173
- "query": {
174
- "type": "string",
175
- "minLength": 1
176
- },
177
- "source": {
178
- "type": "string",
179
- "pattern": "^https://(?:x|twitter)\\.com/"
180
- }
181
- },
182
- "required": [
183
- "success",
184
- "status",
185
- "requiresLogin",
186
- "message",
187
- "query",
188
- "source"
189
- ],
190
- "additionalProperties": false
191
163
  }
192
164
  ]
193
165
  },
@@ -195,7 +167,7 @@
195
167
  {
196
168
  "tool": "chrome_javascript",
197
169
  "args": {
198
- "code": "const query = String(input.query || '').trim();\nconst limit = Math.max(1, Math.min(Number(input.limit) || 8, 20));\nconst source = new URL('/search', location.origin);\nsource.searchParams.set('q', query);\nsource.searchParams.set('src', 'typed_query');\nsource.searchParams.set('f', 'live');\nconst loginPath = /^\\/(?:i\\/flow\\/login|login)(?:\\/|$)/.test(location.pathname);\nconst isVisible = element => {\n if (!element || !element.getBoundingClientRect) return false;\n if (element.hidden || (typeof element.getAttribute === 'function' && element.getAttribute('aria-hidden') === 'true')) return false;\n const rect = element.getBoundingClientRect();\n const style = typeof getComputedStyle === 'function' ? getComputedStyle(element) : null;\n return rect.width > 0 && rect.height > 0 && (!style || (style.display !== 'none' && style.visibility !== 'hidden'));\n};\nconst hasVisibleLoginForm = () => Array.from(document.querySelectorAll('form')).some(form =>\n isVisible(form) && Array.from(form.querySelectorAll('input[autocomplete=\"username\"], input[name=\"text\"], input[type=\"password\"]')).some(isVisible)\n);\nconst hasExplicitEmptyState = () => {\n if (typeof document.querySelector !== 'function') return false;\n const element = document.querySelector('main [data-testid=\"emptyState\"]');\n if (!isVisible(element)) return false;\n const normalizeQuotes = value => value.replace(/[“”]/g, '\"').replace(/[‘’]/g, \"'\");\n const text = normalizeQuotes(String(element.innerText || element.textContent || '')).replace(/\\s+/g, ' ').trim().toLowerCase();\n const normalizedQuery = normalizeQuotes(query).replace(/\\s+/g, ' ').trim().toLowerCase();\n return !!normalizedQuery && (\n text.includes(`no results for \"${normalizedQuery}\"`) ||\n text.includes(`no results for '${normalizedQuery}'`) ||\n text.includes(`没有关于\"${normalizedQuery}\"的结果`) ||\n text.includes(`没有关于'${normalizedQuery}'的结果`)\n );\n};\nconst sleep = ms => new Promise(resolve => setTimeout(resolve, ms));\nlet articles = [];\nlet loginForm = false;\nlet emptyState = false;\nfor (let attempt = 0; attempt < 40; attempt += 1) {\n if (loginPath) break;\n articles = Array.from(document.querySelectorAll('article'));\n if (articles.length) break;\n loginForm = hasVisibleLoginForm();\n if (loginForm) break;\n emptyState = hasExplicitEmptyState();\n if (emptyState) break;\n if (attempt < 39) await sleep(250);\n}\nif (loginPath || loginForm) {\n return {\n success: false,\n status: 'requires_auth',\n requiresLogin: true,\n message: 'X requires authentication to read this search timeline',\n query,\n source: source.href\n };\n}\nif (emptyState) {\n return { success: true, status: 'empty', query, posts: [], sources: { page: source.href } };\n}\nif (!articles.length) {\n return { success: false, status: 'loading_timeout', requiresLogin: false, message: 'X search articles did not become visible within 10 seconds', query, source: source.href };\n}\nconst mainStatusLink = article => Array.from(article.querySelectorAll('a:has(time)')).find(link => {\n const href = link.getAttribute('href') || '';\n try {\n return /^\\/[^/]+\\/status\\/\\d+$/.test(new URL(href, location.origin).pathname);\n } catch {\n return false;\n }\n});\nconst posts = articles.slice(0, limit).map(article => {\n const text = String(article.querySelector('[data-testid=\"tweetText\"]') && article.querySelector('[data-testid=\"tweetText\"]').innerText || '').trim();\n const nameBlock = String(article.querySelector('[data-testid=\"User-Name\"]') && article.querySelector('[data-testid=\"User-Name\"]').innerText || '').trim();\n const author = nameBlock.split('\\n').map(part => part.trim()).find(Boolean) || '';\n const statusLink = mainStatusLink(article);\n const href = statusLink ? statusLink.getAttribute('href') || '' : '';\n const time = statusLink ? statusLink.querySelector('time') : null;\n return {\n text,\n author,\n url: href ? new URL(href, location.origin).href : '',\n publishedAt: time ? String(time.getAttribute('datetime') || '') : ''\n };\n}).filter(post => post.text && post.url);\nif (!posts.length) {\n return { success: false, status: 'unreadable', requiresLogin: false, message: 'Visible X articles did not expose readable text and main status links', query, source: source.href };\n}\nreturn { success: true, status: 'ok', query, posts, sources: { page: source.href } };",
170
+ "code": "const query = String(input.query || '').trim();\nconst limit = Math.max(1, Math.min(Number(input.limit) || 8, 20));\nconst fallbackSource = new URL('/search', 'https://x.com');\nfallbackSource.searchParams.set('q', query);\nfallbackSource.searchParams.set('src', 'typed_query');\nfallbackSource.searchParams.set('f', 'live');\nconst origin = typeof location !== 'undefined' && typeof location.origin === 'string' && /^https:\\/\\/(?:mobile\\.)?(?:x|twitter)\\.com$/i.test(location.origin) ? location.origin : '';\nif (!origin) {\n return {\n success: false,\n status: 'page_not_ready',\n requiresLogin: false,\n message: 'X search page origin is not ready',\n query,\n source: fallbackSource.href\n };\n}\nconst canonicalOrigin = origin.replace(/^https:\\/\\/mobile\\./i, 'https://');\nconst source = new URL('/search', canonicalOrigin);\nsource.searchParams.set('q', query);\nsource.searchParams.set('src', 'typed_query');\nsource.searchParams.set('f', 'live');\nconst loginPath = /^\\/(?:i\\/flow\\/login|login)(?:\\/|$)/.test(String(location.pathname || ''));\nconst isVisible = element => {\n if (!element || !element.getBoundingClientRect) return false;\n if (element.hidden === true) return false;\n if (typeof element.getAttribute === 'function') {\n if (element.getAttribute('aria-hidden') === 'true') return false;\n const hiddenAttr = element.getAttribute('hidden');\n if (hiddenAttr !== null && hiddenAttr !== undefined) return false;\n }\n if (element.style && (element.style.display === 'none' || element.style.visibility === 'hidden')) return false;\n const rect = element.getBoundingClientRect();\n const style = typeof getComputedStyle === 'function' ? getComputedStyle(element) : null;\n return Boolean(rect) && rect.width > 0 && rect.height > 0 && (!style || (style.display !== 'none' && style.visibility !== 'hidden'));\n};\nconst isArticleVisible = element => {\n if (!element) return false;\n if (element.hidden === true) return false;\n if (typeof element.getAttribute === 'function') {\n if (element.getAttribute('aria-hidden') === 'true') return false;\n const hiddenAttr = element.getAttribute('hidden');\n if (hiddenAttr !== null && hiddenAttr !== undefined) return false;\n }\n if (element.style && (element.style.display === 'none' || element.style.visibility === 'hidden')) return false;\n const style = typeof getComputedStyle === 'function' ? getComputedStyle(element) : null;\n if (style && (style.display === 'none' || style.visibility === 'hidden')) return false;\n if (typeof element.getBoundingClientRect === 'function') {\n const rect = element.getBoundingClientRect();\n if (!rect || rect.width <= 0 || rect.height <= 0) return false;\n }\n return true;\n};\nconst hasVisibleLoginForm = () => {\n if (typeof document === 'undefined' || !document || typeof document.querySelectorAll !== 'function') return false;\n return Array.from(document.querySelectorAll('form')).some(form =>\n isVisible(form) && Array.from(form.querySelectorAll('input[autocomplete=\"username\"], input[name=\"text\"], input[type=\"password\"]')).some(isVisible)\n );\n};\nconst hasExplicitEmptyState = () => {\n if (typeof document === 'undefined' || !document || typeof document.querySelector !== 'function') return false;\n const element = document.querySelector('main [data-testid=\"emptyState\"]') || document.querySelector('[data-testid=\"emptyState\"]');\n if (!isVisible(element)) return false;\n const normalizeQuotes = value => value.replace(/[“”]/g, '\"').replace(/[‘’]/g, \"'\");\n const text = normalizeQuotes(String(element.innerText || element.textContent || '')).replace(/\\s+/g, ' ').trim().toLowerCase();\n const normalizedQuery = normalizeQuotes(query).replace(/\\s+/g, ' ').trim().toLowerCase();\n if (!normalizedQuery) return false;\n const escaped = normalizedQuery.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const boundaryRe = new RegExp('no results for (?:[\"' + \"'\" + ']' + escaped + '[\"' + \"'\" + ']|' + escaped + '(?=$|[^a-z0-9_]))');\n return (\n boundaryRe.test(text) ||\n text.includes('没有关于\"' + normalizedQuery + '\"的结果') ||\n text.includes(\"没有关于'\" + normalizedQuery + \"'的结果\") ||\n text.includes('沒有關於\"' + normalizedQuery + '\"的結果') ||\n text.includes(\"沒有關於'\" + normalizedQuery + \"'的結果\")\n );\n};\nconst queryArticles = () => {\n if (typeof document === 'undefined' || !document || typeof document.querySelectorAll !== 'function') return [];\n const primary = Array.from(document.querySelectorAll('article[data-testid=\"tweet\"]'));\n return primary.length ? primary : Array.from(document.querySelectorAll('article'));\n};\nconst isInsideQuote = (article, el) => {\n if (!el || typeof el.closest !== 'function') return false;\n const quoteWrap = el.closest('div[role=\"link\"], [data-testid=\"quoteTweet\"], [data-testid=\"card.wrapper\"]');\n if (quoteWrap && quoteWrap !== article && (typeof article.contains !== 'function' || article.contains(quoteWrap))) return true;\n const nestedArticle = el.closest('article');\n return Boolean(nestedArticle && nestedArticle !== article);\n};\nconst isPromoted = article => {\n if (!article) return false;\n if (typeof article.closest === 'function' && article.closest('[data-testid=\"placementTracking\"]')) return true;\n if (typeof article.querySelector === 'function') {\n if (article.querySelector('[data-testid=\"placementTracking\"]')) return true;\n const social = article.querySelector('[data-testid=\"socialContext\"], [data-testid=\"SocialContext\"]');\n if (social && !isInsideQuote(article, social)) {\n const sText = String(social.innerText || social.textContent || '').trim();\n if (/\\b(?:promoted|sponsored|ad)\\b|推广|广告/i.test(sText)) return true;\n }\n }\n if (typeof article.querySelectorAll === 'function') {\n const spans = Array.from(article.querySelectorAll('span'));\n if (spans.some(sp => {\n if (typeof sp.closest === 'function' && sp.closest('[data-testid=\"tweetText\"], [data-testid=\"User-Name\"]')) return false;\n if (isInsideQuote(article, sp)) return false;\n const t = String(sp.innerText || sp.textContent || '').trim();\n return /^(?:Ad|Promoted|Sponsored|广告|推广)$/i.test(t);\n })) return true;\n }\n return false;\n};\nconst sleep = ms => new Promise(resolve => setTimeout(resolve, ms));\nlet articles = [];\nlet loginForm = false;\nlet emptyState = false;\nfor (let attempt = 0; attempt < 40; attempt += 1) {\n if (loginPath) break;\n articles = queryArticles().filter(article => isArticleVisible(article) && !isPromoted(article));\n if (articles.length) break;\n loginForm = hasVisibleLoginForm();\n if (loginForm) break;\n emptyState = hasExplicitEmptyState();\n if (emptyState) break;\n if (attempt < 39) await sleep(250);\n}\nif (loginPath || loginForm) {\n return {\n success: false,\n status: 'requires_auth',\n requiresLogin: true,\n message: 'X requires authentication to read this search timeline',\n query,\n source: source.href\n };\n}\nif (emptyState) {\n return { success: true, status: 'empty', query, posts: [], sources: { page: source.href } };\n}\nif (!articles.length) {\n return { success: false, status: 'loading_timeout', requiresLogin: false, message: 'X search articles did not become visible within 10 seconds', query, source: source.href };\n}\nconst mainStatusLink = article => {\n const links = typeof article.querySelectorAll === 'function' ? Array.from(article.querySelectorAll('a:has(time)')) : [];\n const candidates = links.filter(link => !isInsideQuote(article, link));\n const pool = candidates.length ? candidates : links;\n return pool.find(link => {\n const href = link.getAttribute('href') || '';\n try {\n return /^\\/[^/]+\\/status\\/\\d+$/.test(new URL(href, canonicalOrigin).pathname);\n } catch {\n return false;\n }\n });\n};\nconst firstPrimaryEl = (article, selector) => {\n const list = typeof article.querySelectorAll === 'function' ? Array.from(article.querySelectorAll(selector)) : [];\n if (list.length) return list.find(el => !isInsideQuote(article, el)) || null;\n const single = typeof article.querySelector === 'function' ? article.querySelector(selector) : null;\n return single && !isInsideQuote(article, single) ? single : null;\n};\nconst posts = articles.map(article => {\n const textEl = firstPrimaryEl(article, '[data-testid=\"tweetText\"]');\n const text = String((textEl && (textEl.innerText || textEl.textContent)) || '').trim();\n const userEl = firstPrimaryEl(article, '[data-testid=\"User-Name\"]');\n const nameBlock = String((userEl && (userEl.innerText || userEl.textContent)) || '').trim();\n const statusLink = mainStatusLink(article);\n const href = statusLink ? statusLink.getAttribute('href') || '' : '';\n const statusUrl = href ? new URL(href, canonicalOrigin).href : '';\n const statusAuthorMatch = statusUrl ? new URL(statusUrl).pathname.match(/^\\/([^/]+)\\/status\\/\\d+$/) : null;\n const handlePart = nameBlock.split('\\n').map(part => part.trim()).find(part => /^@[A-Za-z0-9_]{1,15}$/.test(part));\n const handleInline = !handlePart ? (nameBlock.match(/@[A-Za-z0-9_]{1,15}/) || [])[0] : '';\n const author = handlePart || handleInline || (statusAuthorMatch ? '@' + statusAuthorMatch[1] : '') || nameBlock.split('\\n').map(part => part.trim()).find(Boolean) || '';\n const time = statusLink && typeof statusLink.querySelector === 'function' ? statusLink.querySelector('time') : null;\n return {\n text,\n author,\n url: statusUrl,\n publishedAt: time ? String(time.getAttribute('datetime') || '') : ''\n };\n}).filter(post => post.text && post.url).slice(0, limit);\nif (!posts.length) {\n return { success: false, status: 'unreadable', requiresLogin: false, message: 'Visible X articles did not expose readable text and main status links', query, source: source.href };\n}\nreturn { success: true, status: 'ok', coverage: 'visible_only', query, posts, sources: { page: source.href } };",
199
171
  "timeoutMs": 20000
200
172
  },
201
173
  "resultPath": "/result"
@@ -19,7 +19,11 @@
19
19
  "twitter",
20
20
  "thread",
21
21
  "visible",
22
- "focal"
22
+ "focal",
23
+ "推特帖子",
24
+ "推文串",
25
+ "推特回复",
26
+ "可见讨论"
23
27
  ],
24
28
  "startUrl": "https://x.com/{{author}}/status/{{postId}}",
25
29
  "inputSchema": {
@@ -27,6 +31,7 @@
27
31
  "properties": {
28
32
  "author": {
29
33
  "type": "string",
34
+ "description": "X handle without leading @",
30
35
  "pattern": "^[A-Za-z0-9_]{1,15}$"
31
36
  },
32
37
  "postId": {
@@ -47,99 +52,51 @@
47
52
  "additionalProperties": false
48
53
  },
49
54
  "outputSchema": {
50
- "oneOf": [
51
- {
52
- "type": "object",
53
- "properties": {
54
- "success": {
55
- "const": true
56
- },
57
- "status": {
58
- "const": "ok"
59
- },
60
- "focal": {
61
- "$ref": "#/definitions/post"
62
- },
63
- "posts": {
64
- "type": "array",
65
- "minItems": 1,
66
- "maxItems": 20,
67
- "items": {
68
- "$ref": "#/definitions/post"
69
- }
70
- },
71
- "coverage": {
72
- "const": "visible_only"
73
- },
74
- "sources": {
75
- "type": "object",
76
- "properties": {
77
- "page": {
78
- "type": "string",
79
- "pattern": "^https://(?:x|twitter)\\.com/[A-Za-z0-9_]+/status/[0-9]+$"
80
- }
81
- },
82
- "required": [
83
- "page"
84
- ],
85
- "additionalProperties": false
86
- }
87
- },
88
- "required": [
89
- "success",
90
- "status",
91
- "focal",
92
- "posts",
93
- "coverage",
94
- "sources"
95
- ],
96
- "additionalProperties": false
55
+ "type": "object",
56
+ "properties": {
57
+ "success": {
58
+ "const": true
59
+ },
60
+ "status": {
61
+ "const": "ok"
62
+ },
63
+ "focal": {
64
+ "$ref": "#/definitions/post"
97
65
  },
98
- {
66
+ "posts": {
67
+ "type": "array",
68
+ "minItems": 1,
69
+ "maxItems": 20,
70
+ "items": {
71
+ "$ref": "#/definitions/post"
72
+ }
73
+ },
74
+ "coverage": {
75
+ "const": "visible_only"
76
+ },
77
+ "sources": {
99
78
  "type": "object",
100
79
  "properties": {
101
- "success": {
102
- "const": false
103
- },
104
- "status": {
105
- "enum": [
106
- "requires_auth",
107
- "loading_timeout",
108
- "unreadable"
109
- ]
110
- },
111
- "requiresLogin": {
112
- "type": "boolean"
113
- },
114
- "message": {
115
- "type": "string",
116
- "minLength": 1
117
- },
118
- "author": {
119
- "type": "string",
120
- "pattern": "^[A-Za-z0-9_]{1,15}$"
121
- },
122
- "postId": {
123
- "type": "string",
124
- "pattern": "^[0-9]+$"
125
- },
126
- "source": {
80
+ "page": {
127
81
  "type": "string",
128
82
  "pattern": "^https://(?:x|twitter)\\.com/[A-Za-z0-9_]+/status/[0-9]+$"
129
83
  }
130
84
  },
131
85
  "required": [
132
- "success",
133
- "status",
134
- "requiresLogin",
135
- "message",
136
- "author",
137
- "postId",
138
- "source"
86
+ "page"
139
87
  ],
140
88
  "additionalProperties": false
141
89
  }
90
+ },
91
+ "required": [
92
+ "success",
93
+ "status",
94
+ "focal",
95
+ "posts",
96
+ "coverage",
97
+ "sources"
142
98
  ],
99
+ "additionalProperties": false,
143
100
  "definitions": {
144
101
  "post": {
145
102
  "type": "object",
@@ -187,7 +144,7 @@
187
144
  {
188
145
  "tool": "chrome_javascript",
189
146
  "args": {
190
- "code": "const author = String(input.author || '').trim().replace(/^@/, '');\nconst postId = String(input.postId || '').trim();\nconst limit = Math.max(1, Math.min(Number(input.limit) || 8, 20));\nconst source = new URL('/' + encodeURIComponent(author) + '/status/' + encodeURIComponent(postId), location.origin);\nconst loginPath = /^\\/(?:i\\/flow\\/login|login)(?:\\/|$)/.test(location.pathname);\nconst isVisible = element => {\n if (!element || !element.getBoundingClientRect) return false;\n const rect = element.getBoundingClientRect();\n const style = typeof getComputedStyle === 'function' ? getComputedStyle(element) : null;\n return rect.width > 0 && rect.height > 0 && (!style || (style.display !== 'none' && style.visibility !== 'hidden'));\n};\nconst hasVisibleLoginForm = () => Array.from(document.querySelectorAll('form')).some(form =>\n isVisible(form) && Array.from(form.querySelectorAll('input[autocomplete=\"username\"], input[name=\"text\"], input[type=\"password\"]')).some(isVisible)\n);\nconst identityOf = article => {\n const link = Array.from(article.querySelectorAll('a:has(time)')).find(candidate => {\n const href = candidate.getAttribute('href') || '';\n try {\n return /^\\/[^/]+\\/status\\/\\d+$/.test(new URL(href, location.origin).pathname);\n } catch {\n return false;\n }\n });\n if (!link) return null;\n const url = new URL(link.getAttribute('href') || '', location.origin);\n const parts = url.pathname.split('/').filter(Boolean);\n if (parts.length !== 3 || parts[1] !== 'status' || !/^\\d+$/.test(parts[2])) return null;\n return { link, author: parts[0], postId: parts[2], url: url.href };\n};\nconst parentOf = (article, postId) => {\n const key = Object.keys(article).find(name => name.startsWith('__reactFiber'));\n let fiber = key ? article[key] : null;\n for (let depth = 0; fiber && depth < 30; depth += 1, fiber = fiber.return) {\n const tweet = fiber.memoizedProps && fiber.memoizedProps.tweet;\n if (tweet && tweet.id_str === postId) return typeof tweet.in_reply_to_status_id_str === 'string' ? tweet.in_reply_to_status_id_str : null;\n }\n return null;\n};\nconst matchesFocal = identity => Boolean(identity && identity.postId === postId && identity.author.toLowerCase() === author.toLowerCase());\nconst sleep = ms => new Promise(resolve => setTimeout(resolve, ms));\nlet articles = [];\nlet focal = null;\nlet loginForm = false;\nfor (let attempt = 0; attempt < 40; attempt += 1) {\n if (loginPath) break;\n articles = Array.from(document.querySelectorAll('article'));\n focal = articles.find(article => matchesFocal(identityOf(article))) || null;\n if (focal) break;\n loginForm = hasVisibleLoginForm();\n if (loginForm) break;\n if (attempt < 39) await sleep(250);\n}\nif (loginPath || loginForm) {\n return {\n success: false,\n status: 'requires_auth',\n requiresLogin: true,\n message: 'X requires authentication to read this focal thread',\n author,\n postId,\n source: source.href\n };\n}\nif (!focal) {\n return { success: false, status: 'loading_timeout', requiresLogin: false, message: 'Focal X article did not become visible within 10 seconds', author, postId, source: source.href };\n}\nconst focalIdentity = identityOf(focal);\nconst section = focal.closest('section[aria-labelledby]') || focal.closest('section');\nconst sectionArticles = section ? Array.from(section.querySelectorAll('article')) : articles;\nconst focalIndex = sectionArticles.indexOf(focal);\nconst ordered = focalIndex >= 0 ? sectionArticles.slice(focalIndex) : articles.slice(articles.indexOf(focal));\nconst posts = [];\nconst seen = new Set();\nfor (const article of ordered) {\n if (!isVisible(article)) continue;\n const identity = identityOf(article);\n if (!identity) continue;\n if (article !== focal && identity.author.toLowerCase() !== focalIdentity.author.toLowerCase()) continue;\n if (seen.has(identity.postId)) continue;\n const parentId = parentOf(article, identity.postId);\n if (article !== focal && !seen.has(parentId)) continue;\n const text = String(article.querySelector('[data-testid=\"tweetText\"]') && article.querySelector('[data-testid=\"tweetText\"]').innerText || '').trim();\n const time = identity.link.querySelector('time');\n if (!text) continue;\n seen.add(identity.postId);\n posts.push({\n author: identity.author,\n postId: identity.postId,\n parentId,\n text,\n url: identity.url,\n publishedAt: time ? String(time.getAttribute('datetime') || '') : ''\n });\n if (posts.length >= limit) break;\n}\nif (!posts.length || posts[0].postId !== focalIdentity.postId) {\n return { success: false, status: 'unreadable', requiresLogin: false, message: 'Focal X article was visible but its text or main status link was unreadable', author, postId, source: source.href };\n}\nreturn {\n success: true,\n status: 'ok',\n focal: posts[0],\n posts,\n coverage: 'visible_only',\n sources: { page: source.href }\n};",
147
+ "code": "const author = String(input.author || '').trim().replace(/^@/, '');\nconst postId = String(input.postId || '').trim();\nconst limit = Math.max(1, Math.min(Number(input.limit) || 8, 20));\nconst fallbackSource = 'https://x.com/' + encodeURIComponent(author) + '/status/' + encodeURIComponent(postId);\nconst origin = typeof location !== 'undefined' && typeof location.origin === 'string' && /^https:\\/\\/(?:mobile\\.)?(?:x|twitter)\\.com$/i.test(location.origin) ? location.origin : '';\nif (!origin) {\n return {\n success: false,\n status: 'page_not_ready',\n requiresLogin: false,\n message: 'X thread page origin is not ready',\n author,\n postId,\n source: fallbackSource\n };\n}\nconst canonicalOrigin = origin.replace(/^https:\\/\\/mobile\\./i, 'https://');\nconst source = new URL('/' + encodeURIComponent(author) + '/status/' + encodeURIComponent(postId), canonicalOrigin);\nconst loginPath = /^\\/(?:i\\/flow\\/login|login)(?:\\/|$)/.test(String(location.pathname || ''));\nconst isVisible = element => {\n if (!element || !element.getBoundingClientRect) return false;\n if (element.hidden === true) return false;\n if (typeof element.getAttribute === 'function') {\n if (element.getAttribute('aria-hidden') === 'true') return false;\n const hiddenAttr = element.getAttribute('hidden');\n if (hiddenAttr !== null && hiddenAttr !== undefined) return false;\n }\n if (element.style && (element.style.display === 'none' || element.style.visibility === 'hidden')) return false;\n const rect = element.getBoundingClientRect();\n const style = typeof getComputedStyle === 'function' ? getComputedStyle(element) : null;\n return Boolean(rect) && rect.width > 0 && rect.height > 0 && (!style || (style.display !== 'none' && style.visibility !== 'hidden'));\n};\nconst hasVisibleLoginForm = () => {\n if (typeof document === 'undefined' || !document || typeof document.querySelectorAll !== 'function') return false;\n return Array.from(document.querySelectorAll('form')).some(form =>\n isVisible(form) && Array.from(form.querySelectorAll('input[autocomplete=\"username\"], input[name=\"text\"], input[type=\"password\"]')).some(isVisible)\n );\n};\nconst isInsideQuote = (article, el) => {\n if (!el || typeof el.closest !== 'function') return false;\n const quoteWrap = el.closest('div[role=\"link\"], [data-testid=\"quoteTweet\"], [data-testid=\"card.wrapper\"]');\n if (quoteWrap && quoteWrap !== article && (typeof article.contains !== 'function' || article.contains(quoteWrap))) return true;\n const nestedArticle = el.closest('article');\n return Boolean(nestedArticle && nestedArticle !== article);\n};\nconst firstPrimaryEl = (article, selector) => {\n const list = typeof article.querySelectorAll === 'function' ? Array.from(article.querySelectorAll(selector)) : [];\n if (list.length) return list.find(el => !isInsideQuote(article, el)) || null;\n const single = typeof article.querySelector === 'function' ? article.querySelector(selector) : null;\n return single && !isInsideQuote(article, single) ? single : null;\n};\nconst queryArticles = root => {\n if (!root || typeof root.querySelectorAll !== 'function') return [];\n const primary = Array.from(root.querySelectorAll('article[data-testid=\"tweet\"]'));\n return primary.length ? primary : Array.from(root.querySelectorAll('article'));\n};\nconst identityOf = article => {\n const links = typeof article.querySelectorAll === 'function' ? Array.from(article.querySelectorAll('a:has(time)')) : [];\n const candidates = links.filter(link => !isInsideQuote(article, link));\n const pool = candidates.length ? candidates : links;\n const link = pool.find(candidate => {\n const href = candidate.getAttribute('href') || '';\n try {\n return /^\\/[^/]+\\/status\\/\\d+$/.test(new URL(href, canonicalOrigin).pathname);\n } catch {\n return false;\n }\n });\n if (!link) return null;\n const url = new URL(link.getAttribute('href') || '', canonicalOrigin);\n const parts = url.pathname.split('/').filter(Boolean);\n if (parts.length !== 3 || parts[1] !== 'status' || !/^\\d+$/.test(parts[2])) return null;\n return { link, author: parts[0], postId: parts[2], url: url.href };\n};\nconst parentOf = (article, id) => {\n try {\n if (!article || typeof article !== 'object') return { foundFiber: false, parentId: null };\n const key = Object.keys(article).find(name => name.startsWith('__reactFiber') || name.startsWith('__reactInternalInstance'));\n let fiber = key ? article[key] : null;\n const foundFiber = Boolean(fiber);\n for (let depth = 0; fiber && depth < 35; depth += 1, fiber = fiber.return) {\n const tweet = (fiber.memoizedProps && fiber.memoizedProps.tweet) || (fiber.pendingProps && fiber.pendingProps.tweet);\n if (tweet && tweet.id_str === id) {\n return {\n foundFiber: true,\n parentId: typeof tweet.in_reply_to_status_id_str === 'string' ? tweet.in_reply_to_status_id_str : null\n };\n }\n }\n return { foundFiber, parentId: null };\n } catch {\n return { foundFiber: false, parentId: null };\n }\n};\nconst matchesFocal = identity => Boolean(identity && identity.postId === postId && identity.author.toLowerCase() === author.toLowerCase());\nconst sleep = ms => new Promise(resolve => setTimeout(resolve, ms));\nlet articles = [];\nlet focal = null;\nlet loginForm = false;\nfor (let attempt = 0; attempt < 40; attempt += 1) {\n if (loginPath) break;\n articles = queryArticles(typeof document !== 'undefined' ? document : null);\n focal = articles.find(article => matchesFocal(identityOf(article))) || null;\n if (focal) break;\n loginForm = hasVisibleLoginForm();\n if (loginForm) break;\n if (attempt < 39) await sleep(250);\n}\nif (loginPath || loginForm) {\n return {\n success: false,\n status: 'requires_auth',\n requiresLogin: true,\n message: 'X requires authentication to read this focal thread',\n author,\n postId,\n source: source.href\n };\n}\nif (!focal) {\n return { success: false, status: 'loading_timeout', requiresLogin: false, message: 'Focal X article did not become visible within 10 seconds', author, postId, source: source.href };\n}\nconst focalIdentity = identityOf(focal);\nconst section = typeof focal.closest === 'function' ? (focal.closest('section[aria-labelledby]') || focal.closest('section')) : null;\nconst sectionArticles = section ? queryArticles(section) : articles;\nconst focalIndex = sectionArticles.indexOf(focal);\nconst ordered = focalIndex >= 0 ? sectionArticles.slice(focalIndex) : articles.slice(articles.indexOf(focal));\nconst posts = [];\nconst seen = new Set();\nlet sawFiber = false;\nfor (const article of ordered) {\n if (!isVisible(article)) continue;\n const identity = identityOf(article);\n if (!identity) continue;\n if (article !== focal && identity.author.toLowerCase() !== focalIdentity.author.toLowerCase()) continue;\n if (seen.has(identity.postId)) continue;\n const parentInfo = parentOf(article, identity.postId);\n if (parentInfo.foundFiber) sawFiber = true;\n const parentId = parentInfo.parentId;\n if (article !== focal && !seen.has(parentId)) continue;\n seen.add(identity.postId);\n const textEl = firstPrimaryEl(article, '[data-testid=\"tweetText\"]');\n const text = String((textEl && (textEl.innerText || textEl.textContent)) || '').trim();\n const time = identity.link && typeof identity.link.querySelector === 'function' ? identity.link.querySelector('time') : null;\n if (!text) continue;\n posts.push({\n author: identity.author,\n postId: identity.postId,\n parentId,\n text,\n url: identity.url,\n publishedAt: time ? String(time.getAttribute('datetime') || '') : ''\n });\n if (posts.length >= limit) break;\n}\nif (!posts.length || posts[0].postId !== focalIdentity.postId) {\n return {\n success: false,\n status: 'unreadable',\n requiresLogin: false,\n message: sawFiber\n ? 'Focal X article was visible but its text or main status link was unreadable'\n : 'Focal X article was visible but its text, main status link, or React tweet metadata was unreadable',\n author,\n postId,\n source: source.href\n };\n}\nreturn {\n success: true,\n status: 'ok',\n focal: posts[0],\n posts,\n coverage: 'visible_only',\n sources: { page: source.href }\n};",
191
148
  "timeoutMs": 20000
192
149
  },
193
150
  "resultPath": "/result"
@@ -0,0 +1,279 @@
1
+ {
2
+ "id": "youtube-search-videos",
3
+ "name": "YouTube video search",
4
+ "description": "Search YouTube videos on youtube.com/results using ytInitialData with visible video card DOM fallback.",
5
+ "source": {
6
+ "type": "builtin",
7
+ "urls": [
8
+ "https://www.youtube.com/results?search_query=typescript+tutorial",
9
+ "https://www.youtube.com/results?search_query=javascript+async"
10
+ ]
11
+ },
12
+ "domains": [
13
+ "www.youtube.com",
14
+ "m.youtube.com",
15
+ "youtube.com"
16
+ ],
17
+ "keywords": [
18
+ "youtube",
19
+ "油管",
20
+ "search",
21
+ "video",
22
+ "videos",
23
+ "视频搜索",
24
+ "搜索",
25
+ "油管搜索",
26
+ "YouTube搜索",
27
+ "油管视频"
28
+ ],
29
+ "startUrl": "https://www.youtube.com/results?search_query={{query}}",
30
+ "inputSchema": {
31
+ "type": "object",
32
+ "properties": {
33
+ "query": {
34
+ "type": "string",
35
+ "minLength": 1,
36
+ "maxLength": 200
37
+ },
38
+ "limit": {
39
+ "type": "integer",
40
+ "minimum": 1,
41
+ "maximum": 15,
42
+ "default": 5
43
+ }
44
+ },
45
+ "required": [
46
+ "query"
47
+ ],
48
+ "additionalProperties": false
49
+ },
50
+ "outputSchema": {
51
+ "oneOf": [
52
+ {
53
+ "type": "object",
54
+ "properties": {
55
+ "success": {
56
+ "const": true
57
+ },
58
+ "status": {
59
+ "const": "ok"
60
+ },
61
+ "query": {
62
+ "type": "string",
63
+ "minLength": 1
64
+ },
65
+ "videos": {
66
+ "type": "array",
67
+ "minItems": 1,
68
+ "maxItems": 15,
69
+ "items": {
70
+ "type": "object",
71
+ "properties": {
72
+ "videoId": {
73
+ "type": "string",
74
+ "pattern": "^[A-Za-z0-9_-]{11}$"
75
+ },
76
+ "title": {
77
+ "type": "string",
78
+ "minLength": 1
79
+ },
80
+ "url": {
81
+ "type": "string",
82
+ "pattern": "^https://www\\.youtube\\.com/watch\\?v=[A-Za-z0-9_-]{11}$"
83
+ },
84
+ "channel": {
85
+ "type": "string"
86
+ },
87
+ "viewsText": {
88
+ "type": "string"
89
+ },
90
+ "publishedText": {
91
+ "type": "string"
92
+ },
93
+ "durationText": {
94
+ "type": "string"
95
+ }
96
+ },
97
+ "required": [
98
+ "videoId",
99
+ "title",
100
+ "url",
101
+ "channel",
102
+ "viewsText",
103
+ "publishedText",
104
+ "durationText"
105
+ ],
106
+ "additionalProperties": false
107
+ }
108
+ },
109
+ "sources": {
110
+ "type": "object",
111
+ "properties": {
112
+ "page": {
113
+ "type": "string",
114
+ "pattern": "^https://www\\.youtube\\.com/results\\?"
115
+ }
116
+ },
117
+ "required": [
118
+ "page"
119
+ ],
120
+ "additionalProperties": false
121
+ }
122
+ },
123
+ "required": [
124
+ "success",
125
+ "status",
126
+ "query",
127
+ "videos",
128
+ "sources"
129
+ ],
130
+ "additionalProperties": false
131
+ },
132
+ {
133
+ "type": "object",
134
+ "properties": {
135
+ "success": {
136
+ "const": true
137
+ },
138
+ "status": {
139
+ "const": "empty"
140
+ },
141
+ "query": {
142
+ "type": "string",
143
+ "minLength": 1
144
+ },
145
+ "videos": {
146
+ "type": "array",
147
+ "minItems": 0,
148
+ "maxItems": 0
149
+ },
150
+ "sources": {
151
+ "type": "object",
152
+ "properties": {
153
+ "page": {
154
+ "type": "string",
155
+ "pattern": "^https://www\\.youtube\\.com/results\\?"
156
+ }
157
+ },
158
+ "required": [
159
+ "page"
160
+ ],
161
+ "additionalProperties": false
162
+ }
163
+ },
164
+ "required": [
165
+ "success",
166
+ "status",
167
+ "query",
168
+ "videos",
169
+ "sources"
170
+ ],
171
+ "additionalProperties": false
172
+ }
173
+ ]
174
+ },
175
+ "steps": [
176
+ {
177
+ "tool": "chrome_javascript",
178
+ "args": {
179
+ "code": "const query = String(input.query || '').trim();\nconst limit = Math.max(1, Math.min(Number(input.limit) || 5, 15));\nconst sourceUrl = new URL('/results', 'https://www.youtube.com');\nsourceUrl.searchParams.set('search_query', query);\nconst currentOrigin = typeof location !== 'undefined' && typeof location.origin === 'string' ? location.origin : '';\nconst currentHref = typeof location !== 'undefined' && typeof location.href === 'string' ? location.href : sourceUrl.href;\nconst currentPath = typeof location !== 'undefined' && typeof location.pathname === 'string' ? location.pathname : '';\nif (/^https:\\/\\/consent\\.youtube\\.com$/i.test(currentOrigin)) {\n return { success: false, status: 'consent_required', query, message: 'YouTube consent wall requires user acceptance', source: currentHref };\n}\nif (!/^https:\\/\\/(?:www\\.|m\\.)?youtube\\.com$/i.test(currentOrigin)) {\n return { success: false, status: 'page_not_ready', query, message: 'YouTube page origin is not ready', source: sourceUrl.href };\n}\nif (/^\\/sorry(?:\\/|$)/i.test(currentPath)) {\n return { success: false, status: 'bot_check', query, requiresLogin: true, message: 'YouTube requested bot verification', source: currentHref };\n}\nconst sleep = ms => new Promise(resolve => setTimeout(resolve, ms));\nconst norm = value => String(value || '').trim().replace(/\\s+/g, ' ').toLowerCase();\nconst readText = node => {\n if (!node) return '';\n if (typeof node === 'string') return node.trim();\n if (typeof node.simpleText === 'string') return node.simpleText.trim();\n if (typeof node.content === 'string') return node.content.trim();\n if (Array.isArray(node.runs)) return node.runs.map(r => String((r && r.text) || '')).join('').trim();\n return '';\n};\nconst looksLikeMetricOrTime = text => /\\b(?:views?|watching|ago|streamed|premiered|live|scheduled)\\b|观看|次|正在观看|前|直播|首播|预告/i.test(text);\nconst extractVideoIdFromUrl = href => {\n const raw = String(href || '').trim();\n if (!raw) return '';\n try {\n const u = new URL(raw, 'https://www.youtube.com');\n const v = u.searchParams.get('v') || '';\n if (/^[A-Za-z0-9_-]{11}$/.test(v)) return v;\n const sm = u.pathname.match(/^\\/shorts\\/([A-Za-z0-9_-]{11})(?:\\/|$)/);\n if (sm) return sm[1];\n } catch {}\n return '';\n};\nconst isHiddenOrAd = el => {\n if (!el || typeof el !== 'object') return false;\n if (el.hidden === true) return true;\n if (typeof el.hasAttribute === 'function' && el.hasAttribute('hidden')) return true;\n if (typeof el.getAttribute === 'function' && el.getAttribute('aria-hidden') === 'true') return true;\n if (typeof el.closest === 'function') {\n try {\n if (el.closest('[hidden], [aria-hidden=\"true\"], ytd-page-manager > [hidden], ytd-ad-slot-renderer, ytd-promoted-sparkles-web-renderer, ytd-in-feed-ad-layout-renderer')) return true;\n } catch {}\n }\n if (typeof getComputedStyle === 'function') {\n try {\n const style = getComputedStyle(el);\n if (style && (style.display === 'none' || style.visibility === 'hidden')) return true;\n } catch {}\n }\n return false;\n};\nconst hasChannelEndpoint = part => {\n const runs = part && part.text && Array.isArray(part.text.commandRuns) ? part.text.commandRuns : [];\n for (const run of runs) {\n const cmd = run && run.onTap && run.onTap.innertubeCommand;\n const url = String((cmd && cmd.commandMetadata && cmd.commandMetadata.webCommandMetadata && cmd.commandMetadata.webCommandMetadata.url) || '').trim();\n const browseId = String((cmd && cmd.browseEndpoint && cmd.browseEndpoint.browseId) || '').trim();\n if (/^\\/(?:@|channel\\/|c\\/|user\\/)/.test(url) || /^UC/.test(browseId)) return true;\n }\n return false;\n};\nconst extractLockupVideo = lockup => {\n if (!lockup || typeof lockup !== 'object') return null;\n if (lockup.contentType && lockup.contentType !== 'LOCKUP_CONTENT_TYPE_VIDEO' && lockup.contentType !== 'LOCKUP_CONTENT_TYPE_SHORTS') return null;\n const videoId = String(lockup.contentId || '').trim();\n if (!/^[A-Za-z0-9_-]{11}$/.test(videoId)) return null;\n const metaVm = lockup.metadata && lockup.metadata.lockupMetadataViewModel;\n const title = readText(metaVm && metaVm.title);\n if (!title) return null;\n const rows = (metaVm && metaVm.metadata && metaVm.metadata.contentMetadataViewModel && Array.isArray(metaVm.metadata.contentMetadataViewModel.metadataRows)) ? metaVm.metadata.contentMetadataViewModel.metadataRows : [];\n let channel = '';\n const avatarA11y = String((metaVm && metaVm.image && metaVm.image.decoratedAvatarViewModel && metaVm.image.decoratedAvatarViewModel.a11yLabel) || '').trim();\n const a11yChannel = avatarA11y ? avatarA11y.replace(/^.*?(?:Go to channel|前往频道)[::\\s]+/i, '').trim() : '';\n const rowTexts = [];\n for (const row of rows) {\n if (!row || row.isSpacerRow) continue;\n const extType = row.lockupContentMetadataRowExtension && row.lockupContentMetadataRowExtension.contentType;\n if (extType && extType !== 'METADATA_ROW_CONTENT_TYPE_BYLINE') continue;\n const parts = Array.isArray(row.metadataParts) ? row.metadataParts : [];\n const currentRow = [];\n for (const part of parts) {\n if (!part || typeof part !== 'object') continue;\n const stackText = readText(part.avatarStack && part.avatarStack.avatarStackViewModel && part.avatarStack.avatarStackViewModel.text);\n if (stackText) {\n if (!channel) channel = stackText;\n continue;\n }\n const partText = readText(part.text);\n if (!partText) continue;\n if (hasChannelEndpoint(part) && !channel) {\n channel = partText;\n continue;\n }\n currentRow.push(partText);\n }\n if (currentRow.length > 0) rowTexts.push(currentRow);\n if (rowTexts.length >= 3) break;\n }\n if (!channel && a11yChannel) channel = a11yChannel;\n const filteredRows = rowTexts.map(r => r.filter(t => t !== channel)).filter(r => r.length > 0);\n if (!channel && filteredRows.length >= 2 && filteredRows[0].length === 1 && !looksLikeMetricOrTime(filteredRows[0][0])) {\n channel = filteredRows[0][0];\n filteredRows.shift();\n }\n const stats = filteredRows.flat();\n if (!channel && stats.length >= 3 && !looksLikeMetricOrTime(stats[0])) {\n channel = stats.shift();\n }\n const viewsText = stats[0] || '';\n const publishedText = stats[1] || '';\n let durationText = '';\n const overlays = (lockup.contentImage && lockup.contentImage.thumbnailViewModel && Array.isArray(lockup.contentImage.thumbnailViewModel.overlays)) ? lockup.contentImage.thumbnailViewModel.overlays : [];\n for (const overlay of overlays) {\n const badges = overlay && overlay.thumbnailBottomOverlayViewModel && Array.isArray(overlay.thumbnailBottomOverlayViewModel.badges) ? overlay.thumbnailBottomOverlayViewModel.badges : [];\n for (const badge of badges) {\n const text = String((badge && badge.thumbnailBadgeViewModel && badge.thumbnailBadgeViewModel.text) || '').trim();\n if (text) {\n durationText = text;\n break;\n }\n }\n if (durationText) break;\n }\n return {\n videoId,\n title,\n url: 'https://www.youtube.com/watch?v=' + videoId,\n channel,\n viewsText,\n publishedText,\n durationText: durationText || (lockup.contentType === 'LOCKUP_CONTENT_TYPE_SHORTS' ? 'SHORTS' : '')\n };\n};\nconst extractShortsLockup = s => {\n if (!s || typeof s !== 'object') return null;\n const nav = s.onTap && s.onTap.innertubeCommand;\n const videoId = String((nav && nav.reelWatchEndpoint && nav.reelWatchEndpoint.videoId) || extractVideoIdFromUrl(nav && nav.commandMetadata && nav.commandMetadata.webCommandMetadata && nav.commandMetadata.webCommandMetadata.url) || '').trim();\n const title = readText(s.overlayMetadata && s.overlayMetadata.primaryText) || readText(s.accessibilityText);\n if (!/^[A-Za-z0-9_-]{11}$/.test(videoId) || !title) return null;\n return {\n videoId,\n title,\n url: 'https://www.youtube.com/watch?v=' + videoId,\n channel: '',\n viewsText: readText(s.overlayMetadata && s.overlayMetadata.secondaryText),\n publishedText: '',\n durationText: 'SHORTS'\n };\n};\nconst inspectInitialData = data => {\n if (!data || typeof data !== 'object') return { matched: false, mismatched: false };\n const targetNorm = norm(query);\n const candidateQueries = [];\n const topbar = data.topbar;\n const desktopSearch = topbar && topbar.desktopTopbarRenderer && topbar.desktopTopbarRenderer.searchbox && topbar.desktopTopbarRenderer.searchbox.fusionSearchboxRenderer && topbar.desktopTopbarRenderer.searchbox.fusionSearchboxRenderer.searchEndpoint;\n if (desktopSearch) {\n if (desktopSearch.searchEndpoint && typeof desktopSearch.searchEndpoint.query === 'string' && desktopSearch.searchEndpoint.query.trim()) candidateQueries.push(desktopSearch.searchEndpoint.query);\n if (typeof desktopSearch.query === 'string' && desktopSearch.query.trim()) candidateQueries.push(desktopSearch.query);\n }\n const mobileSearch = topbar && topbar.mobileTopbarRenderer && topbar.mobileTopbarRenderer.searchbox && topbar.mobileTopbarRenderer.searchbox.searchboxRenderer && topbar.mobileTopbarRenderer.searchbox.searchboxRenderer.endpoint && topbar.mobileTopbarRenderer.searchbox.searchboxRenderer.endpoint.searchEndpoint;\n if (mobileSearch && typeof mobileSearch.query === 'string' && mobileSearch.query.trim()) candidateQueries.push(mobileSearch.query);\n const candidateUrls = [];\n if (typeof data.currentUrl === 'string' && data.currentUrl) candidateUrls.push(data.currentUrl);\n if (typeof data.url === 'string' && data.url) candidateUrls.push(data.url);\n if (data.responseContext && typeof data.responseContext.url === 'string' && data.responseContext.url) candidateUrls.push(data.responseContext.url);\n const stp = data.responseContext && Array.isArray(data.responseContext.serviceTrackingParams) ? data.responseContext.serviceTrackingParams : [];\n for (const svc of stp) {\n const params = svc && Array.isArray(svc.params) ? svc.params : [];\n for (const p of params) {\n if (!p || typeof p.value !== 'string' || !p.value.trim()) continue;\n if (p.key === 'search_query' || p.key === 'q') candidateQueries.push(p.value);\n if (p.key === 'url') candidateUrls.push(p.value);\n }\n }\n let matched = false;\n for (const cq of candidateQueries) {\n if (norm(cq) !== targetNorm) return { matched: false, mismatched: true };\n matched = true;\n }\n for (const cu of candidateUrls) {\n try {\n const parsed = new URL(cu, 'https://www.youtube.com');\n if (parsed.pathname !== '/results') return { matched: false, mismatched: true };\n const uq = parsed.searchParams.get('search_query');\n if (uq !== null) {\n if (norm(uq) !== targetNorm) return { matched: false, mismatched: true };\n matched = true;\n }\n } catch {}\n }\n return { matched, mismatched: false };\n};\nconst fromData = data => {\n if (!data || typeof data !== 'object') return null;\n const sections = data.contents && data.contents.twoColumnSearchResultsRenderer && data.contents.twoColumnSearchResultsRenderer.primaryContents && data.contents.twoColumnSearchResultsRenderer.primaryContents.sectionListRenderer && data.contents.twoColumnSearchResultsRenderer.primaryContents.sectionListRenderer.contents;\n if (!Array.isArray(sections)) return null;\n const found = [];\n const seen = new Set();\n let hasNoResults = false;\n const isAdEntry = e => Boolean(e && (e.adSlotRenderer || e.promotedSparklesWebRenderer || e.inFeedAdLayoutRenderer || e.searchPyvRenderer || (e.richItemRenderer && e.richItemRenderer.content && (e.richItemRenderer.content.adSlotRenderer || e.richItemRenderer.content.promotedSparklesWebRenderer || e.richItemRenderer.content.inFeedAdLayoutRenderer))));\n for (const section of sections) {\n const items = section && section.itemSectionRenderer && Array.isArray(section.itemSectionRenderer.contents) ? section.itemSectionRenderer.contents : [];\n for (const entry of items) {\n if (!entry || isAdEntry(entry)) continue;\n if (entry.backgroundPromoRenderer) hasNoResults = true;\n const v = entry.videoRenderer;\n if (v) {\n const videoId = String(v.videoId || '').trim();\n const title = readText(v.title);\n if (/^[A-Za-z0-9_-]{11}$/.test(videoId) && title && !seen.has(videoId)) {\n seen.add(videoId);\n found.push({\n videoId,\n title,\n url: 'https://www.youtube.com/watch?v=' + videoId,\n channel: readText(v.ownerText) || readText(v.longBylineText) || readText(v.shortBylineText),\n viewsText: readText(v.shortViewCountText) || readText(v.viewCountText),\n publishedText: readText(v.publishedTimeText),\n durationText: readText(v.lengthText)\n });\n if (found.length >= limit) break;\n continue;\n }\n }\n const lockupVideo = extractLockupVideo(entry.lockupViewModel || (entry.richItemRenderer && entry.richItemRenderer.content && entry.richItemRenderer.content.lockupViewModel));\n if (lockupVideo && !seen.has(lockupVideo.videoId)) {\n seen.add(lockupVideo.videoId);\n found.push(lockupVideo);\n if (found.length >= limit) break;\n continue;\n }\n const reelItems = entry.reelShelfRenderer && Array.isArray(entry.reelShelfRenderer.items) ? entry.reelShelfRenderer.items : (entry.gridShelfViewModel && Array.isArray(entry.gridShelfViewModel.contents) ? entry.gridShelfViewModel.contents : []);\n for (const rItem of reelItems) {\n const sLockup = extractShortsLockup(rItem && (rItem.shortsLockupViewModel || rItem));\n if (sLockup && !seen.has(sLockup.videoId)) {\n seen.add(sLockup.videoId);\n found.push(sLockup);\n if (found.length >= limit) break;\n continue;\n }\n const reel = rItem && rItem.reelItemRenderer;\n if (reel) {\n const rId = String(reel.videoId || '').trim();\n const rTitle = readText(reel.headline);\n if (/^[A-Za-z0-9_-]{11}$/.test(rId) && rTitle && !seen.has(rId)) {\n seen.add(rId);\n found.push({\n videoId: rId,\n title: rTitle,\n url: 'https://www.youtube.com/watch?v=' + rId,\n channel: '',\n viewsText: readText(reel.viewCountText),\n publishedText: '',\n durationText: 'SHORTS'\n });\n if (found.length >= limit) break;\n }\n }\n }\n if (found.length >= limit) break;\n }\n if (found.length >= limit) break;\n }\n return { videos: found, hasNoResults };\n};\nconst fromDom = () => {\n if (typeof document === 'undefined' || !document || typeof document.querySelectorAll !== 'function') return [];\n const out = [];\n const seen = new Set();\n const legacyCards = Array.from(document.querySelectorAll('ytd-video-renderer'));\n for (const card of legacyCards) {\n if (isHiddenOrAd(card)) continue;\n const link = card.querySelector('a#video-title');\n if (!link) continue;\n const href = String(link.getAttribute('href') || '');\n const videoId = extractVideoIdFromUrl(href);\n if (!videoId || seen.has(videoId)) continue;\n const title = String(link.getAttribute('title') || link.innerText || link.textContent || '').trim();\n if (!title) continue;\n const channelEl = card.querySelector('#channel-name a, ytd-channel-name a');\n const metaSpans = Array.from(card.querySelectorAll('#metadata-line span')).map(el => String(el.innerText || el.textContent || '').trim()).filter(Boolean);\n const durationEl = card.querySelector('ytd-thumbnail-overlay-time-status-renderer span, badge-shape .badge-shape-wiz__text');\n seen.add(videoId);\n out.push({\n videoId,\n title,\n url: 'https://www.youtube.com/watch?v=' + videoId,\n channel: channelEl ? String(channelEl.innerText || channelEl.textContent || '').trim() : '',\n viewsText: metaSpans[0] || '',\n publishedText: metaSpans[1] || '',\n durationText: durationEl ? String(durationEl.innerText || durationEl.textContent || '').trim() : (href.includes('/shorts/') ? 'SHORTS' : '')\n });\n if (out.length >= limit) return out;\n }\n const lockupCards = Array.from(document.querySelectorAll('yt-lockup-view-model'));\n for (const card of lockupCards) {\n if (isHiddenOrAd(card)) continue;\n if (card.querySelector('a[href*=\"/playlist?list=\"]')) continue;\n const titleLink = card.querySelector('h3 a[href*=\"/watch?v=\"], h3 a[href*=\"/shorts/\"], a[href*=\"/watch?v=\"][title], a[href*=\"/shorts/\"][title]');\n if (!titleLink) continue;\n const href = String(titleLink.getAttribute('href') || '');\n const videoId = extractVideoIdFromUrl(href);\n if (!videoId || seen.has(videoId)) continue;\n const title = String(titleLink.getAttribute('title') || titleLink.innerText || titleLink.textContent || '').trim();\n if (!title) continue;\n const channelEl = card.querySelector('a[href^=\"/@\"], a[href^=\"/channel/\"], a[href^=\"/c/\"], a[href^=\"/user/\"]');\n let channel = channelEl ? String(channelEl.innerText || channelEl.textContent || '').trim() : '';\n const durationEl = card.querySelector('yt-thumbnail-badge-view-model .yt-badge-shape__text, badge-shape .yt-badge-shape__text, badge-shape .badge-shape-wiz__text');\n const metaRowEls = Array.from(card.querySelectorAll('.yt-content-metadata-view-model__metadata-row'));\n const rowTextLists = metaRowEls.map(row => String(row.innerText || row.textContent || '').split(/[•·\\n]/).map(s => s.trim()).filter(Boolean)).filter(r => r.length > 0);\n if (!channel && rowTextLists.length >= 2 && rowTextLists[0].length === 1 && !looksLikeMetricOrTime(rowTextLists[0][0])) {\n channel = rowTextLists[0][0];\n }\n const statParts = rowTextLists.flat().filter(s => s !== channel);\n if (!channel && statParts.length >= 3 && !looksLikeMetricOrTime(statParts[0])) {\n channel = statParts.shift();\n }\n seen.add(videoId);\n out.push({\n videoId,\n title,\n url: 'https://www.youtube.com/watch?v=' + videoId,\n channel,\n viewsText: statParts[0] || '',\n publishedText: statParts[1] || '',\n durationText: durationEl ? String(durationEl.innerText || durationEl.textContent || '').trim() : (href.includes('/shorts/') ? 'SHORTS' : '')\n });\n if (out.length >= limit) return out;\n }\n const shortsCards = Array.from(document.querySelectorAll('ytm-shorts-lockup-view-model, ytm-shorts-lockup-view-model-v2'));\n for (const card of shortsCards) {\n if (isHiddenOrAd(card)) continue;\n const link = card.querySelector('a[href*=\"/shorts/\"], a[href*=\"/watch?v=\"]');\n if (!link) continue;\n const href = String(link.getAttribute('href') || '');\n const videoId = extractVideoIdFromUrl(href);\n if (!videoId || seen.has(videoId)) continue;\n const titleEl = card.querySelector('.shortsLockupViewModelHostMetadataTitle, h3, [title]');\n const title = String((titleEl && (titleEl.getAttribute && titleEl.getAttribute('title') || titleEl.innerText || titleEl.textContent)) || link.getAttribute('title') || link.innerText || '').trim();\n if (!title) continue;\n const viewsEl = card.querySelector('.shortsLockupViewModelHostMetadataSubhead');\n seen.add(videoId);\n out.push({\n videoId,\n title,\n url: 'https://www.youtube.com/watch?v=' + videoId,\n channel: '',\n viewsText: viewsEl ? String(viewsEl.innerText || viewsEl.textContent || '').trim() : '',\n publishedText: '',\n durationText: 'SHORTS'\n });\n if (out.length >= limit) break;\n }\n return out;\n};\nconst detectWall = () => {\n if (typeof document === 'undefined' || !document) return null;\n if (typeof document.querySelector === 'function') {\n const consentEl = document.querySelector('form[action*=\"consent.youtube.com\"], ytd-consent-bump-v2-lightbox, tp-yt-paper-dialog[aria-label*=\"consent\" i], #consent-bump');\n if (consentEl && !isHiddenOrAd(consentEl)) {\n return { success: false, status: 'consent_required', query, message: 'YouTube consent wall is blocking search results', source: currentHref };\n }\n }\n const bodyText = String((document.body && (document.body.innerText || document.body.textContent)) || '').trim();\n if (/sign in to confirm you(?:'|\\u2019)?re not a bot/i.test(bodyText) || /unusual traffic from your computer network/i.test(bodyText)) {\n return { success: false, status: 'bot_check', query, requiresLogin: true, message: 'YouTube requested bot verification', source: currentHref };\n }\n if (/before you continue to youtube/i.test(bodyText)) {\n return { success: false, status: 'consent_required', query, message: 'YouTube consent wall is blocking search results', source: currentHref };\n }\n return null;\n};\nlet videos = [];\nlet empty = false;\nlet wallError = null;\nfor (let attempt = 0; attempt < 25; attempt += 1) {\n const domVideos = fromDom();\n const searchEl = typeof document !== 'undefined' && document && typeof document.querySelector === 'function' ? document.querySelector('ytd-search:not([hidden])') : null;\n const liveSearchData = searchEl && searchEl.data && typeof searchEl.data === 'object' ? fromData(searchEl.data) : null;\n const root = typeof globalThis !== 'undefined' ? globalThis : {};\n const initState = inspectInitialData(root.ytInitialData);\n const initial = !initState.mismatched ? fromData(root.ytInitialData) : null;\n if (liveSearchData && liveSearchData.videos.length > 0) {\n videos = liveSearchData.videos;\n break;\n }\n if (initState.matched && initial && initial.videos.length > 0) {\n videos = initial.videos;\n break;\n }\n if (domVideos.length > 0) {\n videos = domVideos;\n break;\n }\n if (!initState.mismatched && initial && initial.videos.length > 0) {\n videos = initial.videos;\n break;\n }\n if ((liveSearchData && liveSearchData.hasNoResults) || (initial && initial.hasNoResults)) {\n empty = true;\n break;\n }\n wallError = detectWall();\n if (wallError) break;\n if (attempt < 24) await sleep(200);\n}\nif (wallError) {\n return wallError;\n}\nif (empty) {\n return { success: true, status: 'empty', query, videos: [], sources: { page: sourceUrl.href } };\n}\nif (!videos.length) {\n return { success: false, status: 'loading_timeout', query, message: 'YouTube search results did not become visible', source: sourceUrl.href };\n}\nreturn {\n success: true,\n status: 'ok',\n query,\n videos,\n sources: { page: sourceUrl.href }\n};",
180
+ "timeoutMs": 20000
181
+ },
182
+ "resultPath": "/result"
183
+ }
184
+ ],
185
+ "verification": {
186
+ "tool": "chrome_read_dom",
187
+ "args": {
188
+ "format": "compact",
189
+ "activeViewportOnly": false,
190
+ "limit": 80,
191
+ "maxTextLength": 220
192
+ },
193
+ "resultPath": "/treeString"
194
+ },
195
+ "tests": [
196
+ {
197
+ "inputs": {
198
+ "query": "typescript tutorial",
199
+ "limit": 3
200
+ },
201
+ "expect": {
202
+ "type": "object",
203
+ "properties": {
204
+ "success": {
205
+ "const": true
206
+ },
207
+ "status": {
208
+ "const": "ok"
209
+ },
210
+ "query": {
211
+ "const": "typescript tutorial"
212
+ },
213
+ "videos": {
214
+ "type": "array",
215
+ "minItems": 1
216
+ },
217
+ "sources": {
218
+ "type": "object",
219
+ "required": [
220
+ "page"
221
+ ]
222
+ }
223
+ },
224
+ "required": [
225
+ "success",
226
+ "status",
227
+ "query",
228
+ "videos",
229
+ "sources"
230
+ ]
231
+ },
232
+ "observe": {
233
+ "type": "string",
234
+ "pattern": "TypeScript|typescript|YouTube"
235
+ }
236
+ },
237
+ {
238
+ "inputs": {
239
+ "query": "javascript async",
240
+ "limit": 3
241
+ },
242
+ "expect": {
243
+ "type": "object",
244
+ "properties": {
245
+ "success": {
246
+ "const": true
247
+ },
248
+ "status": {
249
+ "const": "ok"
250
+ },
251
+ "query": {
252
+ "const": "javascript async"
253
+ },
254
+ "videos": {
255
+ "type": "array",
256
+ "minItems": 1
257
+ },
258
+ "sources": {
259
+ "type": "object",
260
+ "required": [
261
+ "page"
262
+ ]
263
+ }
264
+ },
265
+ "required": [
266
+ "success",
267
+ "status",
268
+ "query",
269
+ "videos",
270
+ "sources"
271
+ ]
272
+ },
273
+ "observe": {
274
+ "type": "string",
275
+ "pattern": "JavaScript|javascript|async|YouTube"
276
+ }
277
+ }
278
+ ]
279
+ }