@picassohq/cli 0.0.0-stage → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/agents/browser_agent.yaml +53 -0
  2. package/agents/code_reviewer.yaml +49 -0
  3. package/agents/codebase_investigator.yaml +70 -0
  4. package/agents/design_auditor.yaml +50 -0
  5. package/agents/devex_auditor.yaml +50 -0
  6. package/agents/doc_writer.yaml +54 -0
  7. package/agents/engineering_architect.yaml +51 -0
  8. package/agents/generalist.yaml +55 -0
  9. package/agents/migration_planner.yaml +51 -0
  10. package/agents/product_reviewer.yaml +48 -0
  11. package/agents/qa_operator.yaml +52 -0
  12. package/agents/release_engineer.yaml +50 -0
  13. package/agents/security_auditor.yaml +62 -0
  14. package/agents/test_writer.yaml +52 -0
  15. package/assets/first-light-lockup.png +0 -0
  16. package/assets/first-light-tagline.png +0 -0
  17. package/assets/house/README.md +26 -0
  18. package/assets/house/auraone-banner.png +0 -0
  19. package/assets/house/auraone-logo.png +0 -0
  20. package/assets/house/kiro-prism-banner.png +0 -0
  21. package/assets/house/kiro-prism-logo.png +0 -0
  22. package/assets/house/picasso-banner.png +0 -0
  23. package/assets/house/picasso-logo.png +0 -0
  24. package/assets/wordmark-app.png +0 -0
  25. package/assets/wordmark-tight.png +0 -0
  26. package/assets/wordmark.png +0 -0
  27. package/design/styles.css +1042 -0
  28. package/dist/build-info.json +37 -0
  29. package/dist/index.js +3062 -0
  30. package/goals/cli-hardening.yaml +40 -0
  31. package/goals/repo-maintenance.yaml +40 -0
  32. package/package.json +49 -4
  33. package/runtime/dsh/picasso-ecosystem.community.amendments.yml +24 -0
  34. package/runtime/dsh/picasso-ecosystem.community.json +185 -0
  35. package/runtime/dsh/picasso-ecosystem.community.patch.yml +40 -0
  36. package/runtime/dsh/picasso-ecosystem.cordis.patch.yml +143 -0
  37. package/runtime/dsh/picasso-isolation.patch.yml +25 -0
  38. package/runtime/dsh/picasso-providers.patch.yml +373 -0
  39. package/runtime/dsh/picasso-runtime.cordis.yml +738 -0
  40. package/runtime/dsh/picasso-sdk.patch.yml +204 -0
  41. package/runtime/engine-manifest.json +215 -0
  42. package/runtime/package.json +6 -0
  43. package/runtime/packages/picasso-cache-probe/cordis.patch.yml +5 -0
  44. package/runtime/packages/picasso-cache-probe/index.js +477 -0
  45. package/runtime/packages/picasso-cache-probe/package.json +38 -0
  46. package/runtime/packages/picasso-commands/cordis.patch.yml +4 -0
  47. package/runtime/packages/picasso-commands/fresh-review.js +573 -0
  48. package/runtime/packages/picasso-commands/index.js +497 -0
  49. package/runtime/packages/picasso-commands/package.json +28 -0
  50. package/runtime/packages/picasso-instructions/conflicts.js +115 -0
  51. package/runtime/packages/picasso-instructions/formats.js +145 -0
  52. package/runtime/packages/picasso-instructions/frontmatter.js +175 -0
  53. package/runtime/packages/picasso-instructions/glob.js +114 -0
  54. package/runtime/packages/picasso-instructions/globals.js +90 -0
  55. package/runtime/packages/picasso-instructions/imports.js +123 -0
  56. package/runtime/packages/picasso-instructions/index.js +326 -0
  57. package/runtime/packages/picasso-instructions/modes.js +64 -0
  58. package/runtime/packages/picasso-instructions/package.json +30 -0
  59. package/runtime/packages/picasso-instructions/parse.js +134 -0
  60. package/runtime/packages/picasso-instructions/report.js +161 -0
  61. package/runtime/packages/picasso-instructions/resolve.js +939 -0
  62. package/runtime/packages/picasso-instructions/scan.js +181 -0
  63. package/runtime/packages/picasso-instructions/settings.js +150 -0
  64. package/runtime/packages/picasso-instructions/skills.js +345 -0
  65. package/runtime/packages/picasso-lean-context/cordis.patch.yml +13 -0
  66. package/runtime/packages/picasso-lean-context/index.js +6280 -0
  67. package/runtime/packages/picasso-lean-context/package.json +26 -0
  68. package/runtime/packages/picasso-lean-context/read-image-recovery.js +306 -0
  69. package/runtime/packages/picasso-lean-context/timeline.js +418 -0
  70. package/runtime/packages/picasso-librarian/classify.js +146 -0
  71. package/runtime/packages/picasso-librarian/cordis.patch.yml +10 -0
  72. package/runtime/packages/picasso-librarian/index.js +878 -0
  73. package/runtime/packages/picasso-librarian/notes.js +159 -0
  74. package/runtime/packages/picasso-librarian/package.json +34 -0
  75. package/runtime/packages/picasso-librarian/state.js +478 -0
  76. package/runtime/packages/picasso-memory/index.js +1184 -0
  77. package/runtime/packages/picasso-memory/package.json +21 -0
  78. package/runtime/packages/picasso-model-router/connections.js +912 -0
  79. package/runtime/packages/picasso-model-router/cordis.patch.yml +17 -0
  80. package/runtime/packages/picasso-model-router/index.js +1083 -0
  81. package/runtime/packages/picasso-model-router/package.json +30 -0
  82. package/runtime/packages/picasso-options/cordis.patch.yml +4 -0
  83. package/runtime/packages/picasso-options/index.js +263 -0
  84. package/runtime/packages/picasso-options/package.json +28 -0
  85. package/runtime/packages/picasso-progress-reports/cordis.patch.yml +10 -0
  86. package/runtime/packages/picasso-progress-reports/index.js +267 -0
  87. package/runtime/packages/picasso-progress-reports/package.json +30 -0
  88. package/runtime/packages/picasso-progress-reports/report.js +235 -0
  89. package/runtime/packages/picasso-sdk-server/aside.js +142 -0
  90. package/runtime/packages/picasso-sdk-server/connections.js +38 -0
  91. package/runtime/packages/picasso-sdk-server/context-timeline.js +27 -0
  92. package/runtime/packages/picasso-sdk-server/egress-gate.js +520 -0
  93. package/runtime/packages/picasso-sdk-server/failure-policy.js +246 -0
  94. package/runtime/packages/picasso-sdk-server/file-input.js +169 -0
  95. package/runtime/packages/picasso-sdk-server/goal.js +131 -0
  96. package/runtime/packages/picasso-sdk-server/ignore-file.js +458 -0
  97. package/runtime/packages/picasso-sdk-server/ignore-plugin.js +12 -0
  98. package/runtime/packages/picasso-sdk-server/ignore-sandbox.js +122 -0
  99. package/runtime/packages/picasso-sdk-server/ignore-snapshot.js +131 -0
  100. package/runtime/packages/picasso-sdk-server/image-input.js +44 -0
  101. package/runtime/packages/picasso-sdk-server/index.js +891 -0
  102. package/runtime/packages/picasso-sdk-server/instructions.js +34 -0
  103. package/runtime/packages/picasso-sdk-server/jobs.js +113 -0
  104. package/runtime/packages/picasso-sdk-server/mcp-gate.js +51 -0
  105. package/runtime/packages/picasso-sdk-server/model-selection.js +162 -0
  106. package/runtime/packages/picasso-sdk-server/package.json +50 -0
  107. package/runtime/packages/picasso-sdk-server/picasso-records.js +50 -0
  108. package/runtime/packages/picasso-sdk-server/provider-reload.js +84 -0
  109. package/runtime/packages/picasso-sdk-server/queue.js +322 -0
  110. package/runtime/packages/picasso-sdk-server/requester.js +43 -0
  111. package/runtime/packages/picasso-sdk-server/rewind.js +108 -0
  112. package/runtime/packages/picasso-sdk-server/schedule.js +187 -0
  113. package/runtime/packages/picasso-sdk-server/session-grants.js +35 -0
  114. package/runtime/packages/picasso-sdk-server/session-state.js +118 -0
  115. package/runtime/packages/picasso-sdk-server/shell-paths.js +869 -0
  116. package/runtime/packages/picasso-sdk-server/stream-deltas.js +211 -0
  117. package/runtime/packages/picasso-sdk-server/team-tasks.js +451 -0
  118. package/runtime/packages/picasso-sdk-server/tool-output.js +128 -0
  119. package/runtime/packages/picasso-sdk-server/tools-list.js +51 -0
  120. package/runtime/packages/picasso-sdk-server/wave2-hooks.js +612 -0
  121. package/runtime/packages/picasso-sdk-server/workspace-archive.js +170 -0
  122. package/runtime/packages/picasso-sdk-server/workspace-restore.js +180 -0
  123. package/runtime/packages/picasso-web-search/backends.js +412 -0
  124. package/runtime/packages/picasso-web-search/config.js +121 -0
  125. package/runtime/packages/picasso-web-search/cordis.patch.yml +7 -0
  126. package/runtime/packages/picasso-web-search/failure.js +116 -0
  127. package/runtime/packages/picasso-web-search/format.js +42 -0
  128. package/runtime/packages/picasso-web-search/index.js +71 -0
  129. package/runtime/packages/picasso-web-search/package.json +38 -0
  130. package/runtime/packages/picasso-web-search/router.js +156 -0
  131. package/runtime/packages/picasso-x-reader/circle.js +324 -0
  132. package/runtime/packages/picasso-x-reader/command.js +169 -0
  133. package/runtime/packages/picasso-x-reader/cordis.patch.yml +8 -0
  134. package/runtime/packages/picasso-x-reader/index.js +170 -0
  135. package/runtime/packages/picasso-x-reader/package.json +39 -0
  136. package/runtime/packages/picasso-x-reader/read.js +370 -0
  137. package/runtime/packages/picasso-x-reader/rewrite.js +38 -0
  138. package/runtime/packages/picasso-x-reader/settings.js +131 -0
  139. package/runtime/packages/picasso-x-reader/urls.js +154 -0
  140. package/runtime/packages/picasso-x-reader/xmd.js +512 -0
  141. package/runtime/plugins/picasso-auth-bridge/index.js +380 -0
  142. package/runtime/plugins/picasso-auth-bridge/package.json +28 -0
  143. package/runtime/plugins/picasso-auto-approve/index.js +1003 -0
  144. package/runtime/plugins/picasso-auto-approve/package.json +28 -0
  145. package/runtime/plugins/picasso-browser/index.js +424 -0
  146. package/runtime/plugins/picasso-browser/package.json +28 -0
  147. package/runtime/plugins/picasso-checkpoints/evidence.js +210 -0
  148. package/runtime/plugins/picasso-checkpoints/index.js +885 -0
  149. package/runtime/plugins/picasso-checkpoints/package.json +29 -0
  150. package/runtime/plugins/picasso-commands/fresh-review.js +573 -0
  151. package/runtime/plugins/picasso-commands/index.js +497 -0
  152. package/runtime/plugins/picasso-commands/package.json +28 -0
  153. package/runtime/plugins/picasso-instructions/conflicts.js +115 -0
  154. package/runtime/plugins/picasso-instructions/formats.js +145 -0
  155. package/runtime/plugins/picasso-instructions/frontmatter.js +175 -0
  156. package/runtime/plugins/picasso-instructions/glob.js +114 -0
  157. package/runtime/plugins/picasso-instructions/globals.js +90 -0
  158. package/runtime/plugins/picasso-instructions/imports.js +123 -0
  159. package/runtime/plugins/picasso-instructions/index.js +326 -0
  160. package/runtime/plugins/picasso-instructions/modes.js +64 -0
  161. package/runtime/plugins/picasso-instructions/package.json +30 -0
  162. package/runtime/plugins/picasso-instructions/parse.js +134 -0
  163. package/runtime/plugins/picasso-instructions/report.js +161 -0
  164. package/runtime/plugins/picasso-instructions/resolve.js +939 -0
  165. package/runtime/plugins/picasso-instructions/scan.js +181 -0
  166. package/runtime/plugins/picasso-instructions/settings.js +150 -0
  167. package/runtime/plugins/picasso-instructions/skills.js +345 -0
  168. package/runtime/plugins/picasso-lean-context/index.js +6280 -0
  169. package/runtime/plugins/picasso-lean-context/package.json +26 -0
  170. package/runtime/plugins/picasso-lean-context/read-image-recovery.js +306 -0
  171. package/runtime/plugins/picasso-lean-context/timeline.js +418 -0
  172. package/runtime/plugins/picasso-librarian/classify.js +146 -0
  173. package/runtime/plugins/picasso-librarian/index.js +878 -0
  174. package/runtime/plugins/picasso-librarian/notes.js +159 -0
  175. package/runtime/plugins/picasso-librarian/package.json +34 -0
  176. package/runtime/plugins/picasso-librarian/state.js +478 -0
  177. package/runtime/plugins/picasso-lifecycle-hooks/index.js +186 -0
  178. package/runtime/plugins/picasso-lifecycle-hooks/package.json +25 -0
  179. package/runtime/plugins/picasso-mail/inbox.js +207 -0
  180. package/runtime/plugins/picasso-mail/index.js +293 -0
  181. package/runtime/plugins/picasso-mail/package.json +22 -0
  182. package/runtime/plugins/picasso-memory/index.js +1184 -0
  183. package/runtime/plugins/picasso-memory/package.json +21 -0
  184. package/runtime/plugins/picasso-model-router/connections.js +912 -0
  185. package/runtime/plugins/picasso-model-router/index.js +1083 -0
  186. package/runtime/plugins/picasso-model-router/package.json +30 -0
  187. package/runtime/plugins/picasso-options/index.js +263 -0
  188. package/runtime/plugins/picasso-options/package.json +28 -0
  189. package/runtime/plugins/picasso-progress-reports/index.js +267 -0
  190. package/runtime/plugins/picasso-progress-reports/package.json +30 -0
  191. package/runtime/plugins/picasso-progress-reports/report.js +235 -0
  192. package/runtime/plugins/picasso-provider-models/index.js +436 -0
  193. package/runtime/plugins/picasso-provider-models/package.json +28 -0
  194. package/runtime/plugins/picasso-repo-index/index.js +1850 -0
  195. package/runtime/plugins/picasso-repo-index/package.json +28 -0
  196. package/runtime/plugins/picasso-schedule-pause/index.js +344 -0
  197. package/runtime/plugins/picasso-schedule-pause/package.json +28 -0
  198. package/runtime/plugins/picasso-session-lifecycle/index.js +796 -0
  199. package/runtime/plugins/picasso-session-lifecycle/package.json +28 -0
  200. package/runtime/plugins/picasso-trackers/index.js +895 -0
  201. package/runtime/plugins/picasso-trackers/package.json +28 -0
  202. package/runtime/plugins/picasso-web-search/backends.js +412 -0
  203. package/runtime/plugins/picasso-web-search/config.js +121 -0
  204. package/runtime/plugins/picasso-web-search/failure.js +116 -0
  205. package/runtime/plugins/picasso-web-search/format.js +42 -0
  206. package/runtime/plugins/picasso-web-search/index.js +71 -0
  207. package/runtime/plugins/picasso-web-search/package.json +38 -0
  208. package/runtime/plugins/picasso-web-search/router.js +156 -0
  209. package/runtime/plugins/picasso-x-reader/circle.js +324 -0
  210. package/runtime/plugins/picasso-x-reader/command.js +169 -0
  211. package/runtime/plugins/picasso-x-reader/index.js +170 -0
  212. package/runtime/plugins/picasso-x-reader/package.json +39 -0
  213. package/runtime/plugins/picasso-x-reader/read.js +370 -0
  214. package/runtime/plugins/picasso-x-reader/rewrite.js +38 -0
  215. package/runtime/plugins/picasso-x-reader/settings.js +131 -0
  216. package/runtime/plugins/picasso-x-reader/urls.js +154 -0
  217. package/runtime/plugins/picasso-x-reader/xmd.js +512 -0
  218. package/runtime/relay/attachment-text.mjs +737 -0
  219. package/runtime/relay/companion/companion.css +126 -0
  220. package/runtime/relay/companion/companion.js +648 -0
  221. package/runtime/relay/companion/icon.svg +5 -0
  222. package/runtime/relay/companion/index.html +25 -0
  223. package/runtime/relay/companion/manifest.json +13 -0
  224. package/runtime/relay/companion/sw.js +41 -0
  225. package/runtime/relay/main.mjs +38580 -0
  226. package/runtime/relay/model-listing.mjs +614 -0
  227. package/runtime/relay/versions-routes.mjs +1400 -0
  228. package/runtime/verify-plugins.mjs +205 -0
  229. package/runtime-lock/package-lock.json +10779 -0
  230. package/runtime-lock/package.json +7 -0
  231. package/scripts/install-runtime.mjs +400 -0
  232. package/README.md +0 -3
@@ -0,0 +1,154 @@
1
+ // X URL recognition and the x.md rewrite (5a).
2
+ //
3
+ // `x.com`, `twitter.com`, `mobile.twitter.com` (and their `www.`/`mobile.` forms) map onto the versioned x.md
4
+ // routes; `t.co` short links are resolved first. A media permalink (`/status/{id}/photo/1`, `/video/1`) reads the
5
+ // post it belongs to. Post reads send `thread=full`, `context=full`, `replies=top` unless the URL already sets them;
6
+ // the documented post options the URL carries pass through.
7
+
8
+ export const X_HOSTS = Object.freeze(['x.com', 'www.x.com', 'mobile.x.com', 'twitter.com', 'www.twitter.com', 'mobile.twitter.com']);
9
+ export const TCO_HOST = 't.co';
10
+ export const POST_DEFAULTS = Object.freeze({ thread: 'full', context: 'full', replies: 'top' });
11
+ /** Post options a user's URL may set (`thread=off|full|conversation|2..100`, `context`, `replies`, `userinfo`, `full`). */
12
+ export const POST_PASSTHROUGH = Object.freeze(['thread', 'context', 'replies', 'userinfo', 'full']);
13
+ const POST_VALUES = Object.freeze({
14
+ thread: (v) => /^(off|full|conversation)$/.test(v) || (/^\d+$/.test(v) && Number(v) >= 2 && Number(v) <= 100),
15
+ context: (v) => v === 'full' || v === 'thread',
16
+ replies: (v) => v === 'top' || v === 'recent' || v === 'off',
17
+ userinfo: (v) => v === 'off' || v === 'author' || v === 'all',
18
+ full: (v) => /^(true|false|1|0|yes|no)$/i.test(v),
19
+ });
20
+ /** First path segments on x.com that are not handles. */
21
+ const RESERVED = new Set([
22
+ 'home', 'explore', 'notifications', 'messages', 'settings', 'compose', 'login', 'logout', 'signup', 'i', 'intent',
23
+ 'share', 'hashtag', 'search', 'tos', 'privacy', 'jobs', 'about', 'download', 'account', 'lists', 'communities',
24
+ 'bookmarks', 'premium', 'verified-choose', 'who_to_follow', 'topics', 'help', 'en', 'oauth', 'safety',
25
+ ]);
26
+ const HANDLE = /^[A-Za-z0-9_]{1,15}$/;
27
+
28
+ function parse(input) {
29
+ if (input instanceof URL) return input;
30
+ try {
31
+ return new URL(String(input ?? '').trim());
32
+ } catch {
33
+ return undefined;
34
+ }
35
+ }
36
+
37
+ export function isXHost(host) {
38
+ return X_HOSTS.includes(String(host ?? '').toLowerCase());
39
+ }
40
+
41
+ /** True for a URL the rewrite owns: an X host or a `t.co` short link, over http(s). */
42
+ export function isXUrl(input) {
43
+ const url = parse(input);
44
+ if (url === undefined || (url.protocol !== 'https:' && url.protocol !== 'http:')) return false;
45
+ const host = url.hostname.toLowerCase();
46
+ return isXHost(host) || host === TCO_HOST;
47
+ }
48
+
49
+ export function isTcoUrl(input) {
50
+ const url = parse(input);
51
+ return url !== undefined && url.hostname.toLowerCase() === TCO_HOST;
52
+ }
53
+
54
+ /** Find every X / t.co URL in free text (paste handling). */
55
+ export function findXUrls(text) {
56
+ const out = [];
57
+ for (const match of String(text ?? '').matchAll(/https?:\/\/[^\s<>"'`)\]]+/gi)) {
58
+ const candidate = match[0].replace(/[.,;:!?]+$/, '');
59
+ if (isXUrl(candidate) && !out.includes(candidate)) out.push(candidate);
60
+ }
61
+ return out;
62
+ }
63
+
64
+ /**
65
+ * What an X URL names: `{kind:'post', handle, id}`, `{kind:'profile', handle, withReplies?}`,
66
+ * `{kind:'followers'|'following', handle}`, `{kind:'search', q, feed?}`, or `{kind:'unsupported', reason}`.
67
+ * Media permalinks (`/photo/N`, `/video/N`) are the post.
68
+ */
69
+ export function classifyXUrl(input) {
70
+ const url = parse(input);
71
+ if (url === undefined || !isXHost(url.hostname)) return { kind: 'unsupported', reason: 'not an X URL' };
72
+ const segments = url.pathname.split('/').filter(Boolean).map((segment) => decodeURIComponent(segment));
73
+ if (segments.length === 0) return { kind: 'unsupported', reason: 'the X home page has no public content' };
74
+ const [first, second, third] = segments;
75
+ // /i/status/{id} and /i/web/status/{id}: a post without its handle.
76
+ if (first === 'i' && (second === 'status' || (second === 'web' && third === 'status'))) {
77
+ const id = second === 'status' ? third : segments[3];
78
+ if (id !== undefined && /^\d+$/.test(id)) return { kind: 'post', handle: 'i', id, url: `https://x.com/i/status/${id}` };
79
+ return { kind: 'unsupported', reason: 'malformed status URL' };
80
+ }
81
+ if (first === 'search') {
82
+ const q = url.searchParams.get('q') ?? '';
83
+ if (q.trim() === '') return { kind: 'unsupported', reason: 'search URL without a query' };
84
+ const f = (url.searchParams.get('f') ?? '').toLowerCase();
85
+ const feed = { live: 'latest', top: 'top', user: 'users', users: 'users', media: 'photos', image: 'photos', video: 'videos' }[f];
86
+ return { kind: 'search', q, ...(feed === undefined ? {} : { feed }) };
87
+ }
88
+ if (RESERVED.has(first.toLowerCase())) return { kind: 'unsupported', reason: `x.com/${first} is not public read-only content (lists, DMs, notifications and the home timeline are unsupported)` };
89
+ if (!HANDLE.test(first)) return { kind: 'unsupported', reason: 'not an X handle' };
90
+ if (second === undefined) return { kind: 'profile', handle: first };
91
+ if (second === 'status' || second === 'statuses') {
92
+ if (third !== undefined && /^\d+$/.test(third)) return { kind: 'post', handle: first, id: third, url: `https://x.com/${first}/status/${third}` };
93
+ return { kind: 'unsupported', reason: 'malformed status URL' };
94
+ }
95
+ if (second === 'followers' || second === 'verified_followers') return { kind: 'followers', handle: first };
96
+ if (second === 'following') return { kind: 'following', handle: first };
97
+ if (second === 'with_replies') return { kind: 'profile', handle: first, withReplies: true };
98
+ if (second === 'media' || second === 'highlights' || second === 'articles') return { kind: 'profile', handle: first };
99
+ return { kind: 'unsupported', reason: `x.com/${first}/${second} is not supported (X Lists, likes and private views are unsupported)` };
100
+ }
101
+
102
+ /** Post options from the user's URL that pass through (valid values only; anything else keeps the default). */
103
+ export function postOptionsFrom(input) {
104
+ const url = parse(input);
105
+ const out = { ...POST_DEFAULTS };
106
+ if (url === undefined) return out;
107
+ for (const key of POST_PASSTHROUGH) {
108
+ const value = url.searchParams.get(key);
109
+ if (value !== null && POST_VALUES[key](value.toLowerCase())) out[key] = value.toLowerCase();
110
+ }
111
+ return out;
112
+ }
113
+
114
+ /**
115
+ * The versioned x.md request for an X URL: `{path, params, target}` or `undefined` when the URL names nothing x.md
116
+ * serves. `target` is what was classified.
117
+ */
118
+ export function rewriteXUrl(input) {
119
+ const target = classifyXUrl(input);
120
+ switch (target.kind) {
121
+ case 'post':
122
+ return { path: '/api/v1/posts', params: { url: target.url, ...postOptionsFrom(input) }, target };
123
+ case 'profile':
124
+ return { path: `/api/v1/profiles/${encodeURIComponent(target.handle)}`, params: target.withReplies ? { with_replies: true } : {}, target };
125
+ case 'followers':
126
+ case 'following':
127
+ return { path: `/api/v1/profiles/${encodeURIComponent(target.handle)}/${target.kind}`, params: {}, target };
128
+ case 'search':
129
+ return { path: '/api/v1/search', params: { q: target.q, ...(target.feed === undefined ? {} : { feed: target.feed }) }, target };
130
+ default:
131
+ return undefined;
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Resolve a `t.co` short link to where it points, reading one redirect's `Location` (no body is fetched).
137
+ * Resolves `{ok:true, url}` or `{ok:false, error}`.
138
+ */
139
+ export async function resolveTco(input, { fetch: fetchImpl = globalThis.fetch, signal, timeoutMs = 15_000 } = {}) {
140
+ const url = parse(input);
141
+ if (url === undefined) return { ok: false, error: 'not a URL' };
142
+ url.protocol = 'https:';
143
+ const timeout = AbortSignal.timeout(timeoutMs);
144
+ const combined = signal && typeof AbortSignal.any === 'function' ? AbortSignal.any([signal, timeout]) : timeout;
145
+ try {
146
+ const response = await fetchImpl(url, { method: 'GET', redirect: 'manual', headers: { 'user-agent': 'Picasso-x-reader/0.1', accept: 'text/html' }, signal: combined });
147
+ const location = response.headers.get('location');
148
+ await response.body?.cancel?.().catch?.(() => {});
149
+ if (location) return { ok: true, url: new URL(location, url).toString() };
150
+ return { ok: false, error: `t.co answered HTTP ${response.status} without a redirect` };
151
+ } catch (error) {
152
+ return { ok: false, error: `t.co could not be resolved: ${error?.message ?? String(error)}` };
153
+ }
154
+ }
@@ -0,0 +1,512 @@
1
+ // x.md (mdfromx.com) HTTP client: the one place Picasso talks to the x.md read API.
2
+ //
3
+ // Everything here follows the published contract (https://mdfromx.com/docs, /openapi.json):
4
+ // - machine calls use only the versioned surface `/api/v1/*` (`/api/convert` is deprecated, sunset 2027-09-15);
5
+ // - an optional issued key travels only as `Authorization: Bearer …`, never in the URL;
6
+ // - 429/502/503 carrying `rate_limited`, `import_busy`, `upstream_unavailable` or `upstream_rate_limited` wait
7
+ // `Retry-After` plus jitter and retry the identical request at most twice; 400 and 401 are never retried;
8
+ // - list routes follow `nextCursor` until it is absent (a short page is not the end), never decode or reuse a
9
+ // cursor, stop on a repeated cursor or an `empty_page` warning and say so, inside a caller-set page budget;
10
+ // - history imports continue with `until=meta.next_until` (same `since`, ids deduplicated), parse NDJSON line by
11
+ // line including a trailing `{"error":…}` on HTTP 200, and use a 125 s client timeout.
12
+ //
13
+ // C1: nothing here fabricates a post. Every gap (warnings, degraded search, a refused or failed page) is returned to
14
+ // the caller as data so it can be said out loud.
15
+ //
16
+ // Zero runtime dependencies: it ships beside the engine as a plain plugin and is imported by the CLI and the relay.
17
+
18
+ export const DEFAULT_BASE_URL = 'https://mdfromx.com';
19
+ /** Client timeout for ordinary reads. */
20
+ export const DEFAULT_TIMEOUT_MS = 30_000;
21
+ /** The history route allows 120 s server-side; the docs ask clients for a 125 s timeout. */
22
+ export const HISTORY_TIMEOUT_MS = 125_000;
23
+ /** Retries of one identical request after a retryable refusal (the documented maximum). */
24
+ export const MAX_RETRIES = 2;
25
+ /** A longer `Retry-After` is not waited inline: the call returns the refusal with the deadline instead. */
26
+ export const MAX_INLINE_WAIT_SECONDS = 60;
27
+ /** Used when a retryable refusal names no wait at all. */
28
+ export const DEFAULT_RETRY_SECONDS = 5;
29
+ /** Default page budget for list routes and history continuations. */
30
+ export const DEFAULT_PAGE_BUDGET = 5;
31
+ export const RETRYABLE_STATUSES = Object.freeze([429, 502, 503]);
32
+ export const RETRYABLE_CODES = Object.freeze(['rate_limited', 'import_busy', 'upstream_unavailable', 'upstream_rate_limited']);
33
+ export const USER_AGENT = 'Picasso-x-reader/0.1 (+https://picassohq.com)';
34
+
35
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
36
+
37
+ /** Normalise a configured base URL: https by default, no trailing slash, no path beyond the deployment root. */
38
+ export function normalizeBaseUrl(raw) {
39
+ const text = typeof raw === 'string' ? raw.trim() : '';
40
+ if (text === '') return DEFAULT_BASE_URL;
41
+ let url;
42
+ try {
43
+ url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(text) ? text : `https://${text}`);
44
+ } catch {
45
+ throw new Error(`x.md base URL is not a URL: ${text}`);
46
+ }
47
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') throw new Error(`x.md base URL must be http(s): ${text}`);
48
+ if (url.username || url.password) throw new Error('x.md base URL must not carry credentials');
49
+ url.search = '';
50
+ url.hash = '';
51
+ return url.toString().replace(/\/+$/, '');
52
+ }
53
+
54
+ /** The key travels only over https, or plain http to this machine (a local deployment); never in cleartext off-host. */
55
+ export function keyTransportAllowed(baseUrl) {
56
+ try {
57
+ const url = new URL(baseUrl);
58
+ if (url.protocol === 'https:') return true;
59
+ return url.protocol === 'http:' && /^(localhost|127(?:\.\d{1,3}){3}|\[::1\])$/i.test(url.hostname);
60
+ } catch {
61
+ return false;
62
+ }
63
+ }
64
+
65
+ // ---- headers ---------------------------------------------------------------------------------------------------
66
+
67
+ /** One IETF structured-field list item: `"name";k=v;k2=v2`. */
68
+ function parseSfList(header) {
69
+ const out = [];
70
+ if (typeof header !== 'string' || header.trim() === '') return out;
71
+ for (const item of header.split(',')) {
72
+ const parts = item.trim().split(';').map((part) => part.trim()).filter(Boolean);
73
+ if (parts.length === 0) continue;
74
+ const name = parts[0].replace(/^"|"$/g, '');
75
+ const params = {};
76
+ for (const part of parts.slice(1)) {
77
+ const eq = part.indexOf('=');
78
+ if (eq <= 0) continue;
79
+ const key = part.slice(0, eq).trim();
80
+ const value = Number(part.slice(eq + 1).trim().replace(/^"|"$/g, ''));
81
+ if (Number.isFinite(value)) params[key] = value;
82
+ }
83
+ out.push({ name, params });
84
+ }
85
+ return out;
86
+ }
87
+
88
+ /**
89
+ * `RateLimit`, `RateLimit-Policy` and the `RateLimit-Limit`/`-Remaining`/`-Reset` trio, as one object:
90
+ * `{policies: {name: {remaining?, reset?, quota?, window?}}, limit?, remaining?, reset?}`.
91
+ */
92
+ export function parseRateLimit(headers) {
93
+ const get = (name) => (typeof headers?.get === 'function' ? headers.get(name) : undefined) ?? undefined;
94
+ const policies = {};
95
+ for (const { name, params } of parseSfList(get('ratelimit'))) {
96
+ policies[name] = { ...(policies[name] ?? {}), ...(params.r === undefined ? {} : { remaining: params.r }), ...(params.t === undefined ? {} : { reset: params.t }) };
97
+ }
98
+ for (const { name, params } of parseSfList(get('ratelimit-policy'))) {
99
+ policies[name] = { ...(policies[name] ?? {}), ...(params.q === undefined ? {} : { quota: params.q }), ...(params.w === undefined ? {} : { window: params.w }) };
100
+ }
101
+ const num = (name) => {
102
+ const value = get(name);
103
+ if (value === undefined || value === null || value === '') return undefined;
104
+ const parsed = Number(value);
105
+ return Number.isFinite(parsed) ? parsed : undefined;
106
+ };
107
+ const out = { policies };
108
+ const limit = num('ratelimit-limit');
109
+ const remaining = num('ratelimit-remaining');
110
+ const reset = num('ratelimit-reset');
111
+ if (limit !== undefined) out.limit = limit;
112
+ if (remaining !== undefined) out.remaining = remaining;
113
+ if (reset !== undefined) out.reset = reset;
114
+ return out;
115
+ }
116
+
117
+ /** `Retry-After` in seconds (delta-seconds or an HTTP date), else the problem body's `retry_after`. */
118
+ export function retryAfterSeconds(headers, problem, now = Date.now()) {
119
+ const raw = typeof headers?.get === 'function' ? headers.get('retry-after') : undefined;
120
+ if (typeof raw === 'string' && raw.trim() !== '') {
121
+ const seconds = Number(raw.trim());
122
+ if (Number.isFinite(seconds) && seconds >= 0) return seconds;
123
+ const date = Date.parse(raw);
124
+ if (Number.isFinite(date)) return Math.max(0, Math.ceil((date - now) / 1000));
125
+ }
126
+ if (isRecord(problem) && typeof problem.retry_after === 'number' && Number.isFinite(problem.retry_after)) return Math.max(0, problem.retry_after);
127
+ return undefined;
128
+ }
129
+
130
+ /** A short human line for the remaining search allowance, from the `search-*` and `account-*` policies. */
131
+ export function quotaSummary(rateLimit) {
132
+ const policies = isRecord(rateLimit?.policies) ? rateLimit.policies : {};
133
+ const parts = [];
134
+ for (const [name, policy] of Object.entries(policies)) {
135
+ if (!/^(search|account|import)/.test(name)) continue;
136
+ if (policy.remaining === undefined && policy.quota === undefined) continue;
137
+ const of = policy.quota === undefined ? '' : `/${policy.quota}`;
138
+ const window = policy.window ?? policy.reset;
139
+ parts.push(`${name} ${policy.remaining ?? '?'}${of} left${window === undefined ? '' : ` per ${window}s`}`);
140
+ }
141
+ return parts.join(', ');
142
+ }
143
+
144
+ // ---- warnings --------------------------------------------------------------------------------------------------
145
+
146
+ /** The machine code of one `warnings` entry (strings or `{code|type, message}` objects). */
147
+ export function warningCode(warning) {
148
+ if (typeof warning === 'string') return warning;
149
+ if (isRecord(warning)) return String(warning.code ?? warning.type ?? warning.kind ?? '');
150
+ return '';
151
+ }
152
+
153
+ /** One `warnings` entry as text. */
154
+ export function warningText(warning) {
155
+ if (typeof warning === 'string') return warning;
156
+ if (isRecord(warning)) {
157
+ const code = warningCode(warning);
158
+ const message = typeof warning.message === 'string' ? warning.message : typeof warning.detail === 'string' ? warning.detail : '';
159
+ return code && message ? `${code}: ${message}` : code || message || JSON.stringify(warning);
160
+ }
161
+ return String(warning);
162
+ }
163
+
164
+ export function warningsOf(body) {
165
+ const list = [];
166
+ if (isRecord(body) && Array.isArray(body.warnings)) list.push(...body.warnings);
167
+ if (isRecord(body?.meta) && Array.isArray(body.meta.warnings)) list.push(...body.meta.warnings);
168
+ return list;
169
+ }
170
+
171
+ // ---- the request ------------------------------------------------------------------------------------------------
172
+
173
+ const sleepDefault = (ms, signal) => new Promise((resolve, reject) => {
174
+ if (signal?.aborted) return reject(signal.reason ?? new Error('aborted'));
175
+ const timer = setTimeout(() => {
176
+ signal?.removeEventListener?.('abort', onAbort);
177
+ resolve();
178
+ }, ms);
179
+ const onAbort = () => {
180
+ clearTimeout(timer);
181
+ reject(signal.reason ?? new Error('aborted'));
182
+ };
183
+ signal?.addEventListener?.('abort', onAbort, { once: true });
184
+ });
185
+
186
+ function paramString(value) {
187
+ if (typeof value === 'boolean') return value ? 'true' : 'false';
188
+ return String(value);
189
+ }
190
+
191
+ /** Append defined, non-empty params in the given order (stable URLs, so cached responses match). */
192
+ export function buildUrl(baseUrl, path, params = {}) {
193
+ const url = new URL(`${normalizeBaseUrl(baseUrl)}${path.startsWith('/') ? path : `/${path}`}`);
194
+ for (const [key, value] of Object.entries(params)) {
195
+ if (value === undefined || value === null || value === '') continue;
196
+ url.searchParams.set(key, paramString(value));
197
+ }
198
+ return url;
199
+ }
200
+
201
+ function combinedSignal(signal, timeoutMs) {
202
+ const timeout = AbortSignal.timeout(timeoutMs);
203
+ if (signal === undefined || signal === null) return timeout;
204
+ return typeof AbortSignal.any === 'function' ? AbortSignal.any([signal, timeout]) : signal;
205
+ }
206
+
207
+ /** Parse NDJSON text: `{"post":…}` lines, a final `{"meta":…,"profile":…}`, and a trailing `{"error":…}`. */
208
+ export function parseNdjson(text) {
209
+ const posts = [];
210
+ let meta;
211
+ let profile;
212
+ let error;
213
+ const malformed = [];
214
+ const lines = String(text ?? '').split('\n');
215
+ lines.forEach((line, index) => {
216
+ const trimmed = line.trim();
217
+ if (trimmed === '') return;
218
+ let value;
219
+ try {
220
+ value = JSON.parse(trimmed);
221
+ } catch {
222
+ malformed.push(index + 1);
223
+ return;
224
+ }
225
+ if (!isRecord(value)) return;
226
+ if (value.post !== undefined) posts.push(value.post);
227
+ if (value.meta !== undefined) meta = value.meta;
228
+ if (value.profile !== undefined) profile = value.profile;
229
+ if (value.error !== undefined) error = value.error;
230
+ });
231
+ return { posts, meta, profile, error, malformedLines: malformed };
232
+ }
233
+
234
+ /**
235
+ * The x.md client. `deps.fetch` (default `globalThis.fetch`), `deps.sleep`, `deps.random` and `deps.now` are
236
+ * injectable so tests run against a local fake server without real waits.
237
+ */
238
+ export class XmdClient {
239
+ constructor({ baseUrl = DEFAULT_BASE_URL, apiKey, fetch: fetchImpl, sleep, random, now, userAgent } = {}) {
240
+ this.baseUrl = normalizeBaseUrl(baseUrl);
241
+ this.apiKey = typeof apiKey === 'string' && apiKey.trim() !== '' ? apiKey.trim() : undefined;
242
+ this.fetchImpl = fetchImpl ?? globalThis.fetch;
243
+ this.sleep = sleep ?? sleepDefault;
244
+ this.random = random ?? Math.random;
245
+ this.now = now ?? Date.now;
246
+ this.userAgent = userAgent ?? USER_AGENT;
247
+ }
248
+
249
+ headers(accept) {
250
+ const headers = { accept, 'user-agent': this.userAgent };
251
+ if (this.apiKey !== undefined && keyTransportAllowed(this.baseUrl)) headers.authorization = `Bearer ${this.apiKey}`;
252
+ return headers;
253
+ }
254
+
255
+ /**
256
+ * One GET with the documented retry policy. Resolves (never throws for HTTP errors) to
257
+ * `{ok, status, url, headers, text, json?, problem?, rateLimit, apiKeyStatus?, degraded, warningsHeader?, retries,
258
+ * retryAfter?, deferred?}`. Network failures and timeouts resolve as `{ok:false, status:0, error}`.
259
+ */
260
+ async request(path, params = {}, { accept = 'application/json', timeoutMs = DEFAULT_TIMEOUT_MS, signal, ndjson = false } = {}) {
261
+ const url = buildUrl(this.baseUrl, path, params);
262
+ let retries = 0;
263
+ for (;;) {
264
+ let response;
265
+ let text = '';
266
+ try {
267
+ response = await this.fetchImpl(url, { method: 'GET', headers: this.headers(accept), redirect: 'follow', signal: combinedSignal(signal, timeoutMs) });
268
+ text = await response.text();
269
+ } catch (error) {
270
+ if (signal?.aborted) throw signal.reason ?? error;
271
+ const timedOut = error?.name === 'TimeoutError' || error?.name === 'AbortError';
272
+ return {
273
+ ok: false,
274
+ status: 0,
275
+ url: url.toString(),
276
+ error: timedOut ? `x.md did not answer within ${Math.round(timeoutMs / 1000)} s` : `x.md request failed: ${error?.message ?? String(error)}`,
277
+ retries,
278
+ rateLimit: { policies: {} },
279
+ degraded: false,
280
+ };
281
+ }
282
+ const headers = response.headers;
283
+ const contentType = headers.get('content-type') ?? '';
284
+ let json;
285
+ let problem;
286
+ // A refusal is a problem+json document even when NDJSON was asked for: read it so its code drives the retry.
287
+ if (/json/i.test(contentType) && !/ndjson/i.test(contentType) && (!ndjson || !response.ok)) {
288
+ try {
289
+ json = JSON.parse(text);
290
+ } catch {
291
+ json = undefined;
292
+ }
293
+ }
294
+ if (!response.ok && isRecord(json)) problem = json;
295
+ const result = {
296
+ ok: response.ok,
297
+ status: response.status,
298
+ url: url.toString(),
299
+ headers,
300
+ contentType,
301
+ text,
302
+ ...(json === undefined ? {} : { json }),
303
+ ...(problem === undefined ? {} : { problem }),
304
+ rateLimit: parseRateLimit(headers),
305
+ ...(headers.get('x-api-key-status') ? { apiKeyStatus: headers.get('x-api-key-status') } : {}),
306
+ degraded: (headers.get('x-search-degraded') ?? '').trim().toLowerCase() === 'true' || json?.degraded === true,
307
+ ...(headers.get('x-warnings') ? { warningsHeader: Number(headers.get('x-warnings')) } : {}),
308
+ retries,
309
+ };
310
+ if (response.ok) return result;
311
+ const code = typeof problem?.code === 'string' ? problem.code : undefined;
312
+ const retryable = RETRYABLE_STATUSES.includes(response.status) && (code === undefined ? response.status === 429 : RETRYABLE_CODES.includes(code));
313
+ if (!retryable) return result;
314
+ const wait = retryAfterSeconds(headers, problem, this.now()) ?? DEFAULT_RETRY_SECONDS;
315
+ result.retryAfter = wait;
316
+ if (retries >= MAX_RETRIES) return result;
317
+ if (wait > MAX_INLINE_WAIT_SECONDS) {
318
+ // Not waited inline: the caller reports the deadline (queued recovery), never a shortened retry.
319
+ result.deferred = true;
320
+ result.retryAt = new Date(this.now() + wait * 1000).toISOString();
321
+ return result;
322
+ }
323
+ const jitterMs = Math.floor(this.random() * 1000);
324
+ await this.sleep(wait * 1000 + jitterMs, signal);
325
+ retries += 1;
326
+ }
327
+ }
328
+
329
+ /**
330
+ * Follow `nextCursor` across pages of one list route (search, profile, followers, following).
331
+ * `itemsKey` is `posts` or `users`. Returns `{pages, items, stop, resumeCursor?, warnings, degraded, last}` where
332
+ * `stop` is `complete` | `page_budget` | `repeated_cursor` | `empty_page` | `degraded` | `error`.
333
+ */
334
+ async paginate(path, params, { itemsKey = 'posts', pageBudget = DEFAULT_PAGE_BUDGET, signal } = {}) {
335
+ const budget = Math.max(1, Math.min(50, Math.floor(Number(pageBudget) || DEFAULT_PAGE_BUDGET)));
336
+ const seenCursors = new Set();
337
+ const seenIds = new Set();
338
+ const items = [];
339
+ const pages = [];
340
+ const warnings = [];
341
+ let cursor = typeof params.cursor === 'string' && params.cursor !== '' ? params.cursor : undefined;
342
+ if (cursor !== undefined) seenCursors.add(cursor);
343
+ let degraded = false;
344
+ let stop = 'page_budget';
345
+ let last;
346
+ for (let page = 0; page < budget; page += 1) {
347
+ const { cursor: _drop, ...rest } = params;
348
+ const res = await this.request(path, cursor === undefined ? rest : { ...rest, cursor }, { signal });
349
+ last = res;
350
+ if (!res.ok) {
351
+ stop = 'error';
352
+ break;
353
+ }
354
+ const body = isRecord(res.json) ? res.json : {};
355
+ pages.push(body);
356
+ const list = Array.isArray(body[itemsKey]) ? body[itemsKey] : [];
357
+ for (const item of list) {
358
+ const id = isRecord(item) ? String(item.id ?? item.id_str ?? item.screen_name ?? '') : '';
359
+ if (id !== '' && seenIds.has(id)) continue;
360
+ if (id !== '') seenIds.add(id);
361
+ items.push(item);
362
+ }
363
+ const pageWarnings = warningsOf(body);
364
+ warnings.push(...pageWarnings);
365
+ if (res.degraded) {
366
+ degraded = true;
367
+ stop = 'degraded';
368
+ break;
369
+ }
370
+ const codes = pageWarnings.map(warningCode);
371
+ if (codes.some((code) => /empty_page/.test(code))) {
372
+ stop = 'empty_page';
373
+ break;
374
+ }
375
+ if (codes.some((code) => /repeated_cursor/.test(code))) {
376
+ stop = 'repeated_cursor';
377
+ break;
378
+ }
379
+ const next = typeof body.nextCursor === 'string' && body.nextCursor !== '' ? body.nextCursor : undefined;
380
+ if (next === undefined) {
381
+ stop = 'complete';
382
+ cursor = undefined;
383
+ break;
384
+ }
385
+ if (seenCursors.has(next)) {
386
+ stop = 'repeated_cursor';
387
+ break;
388
+ }
389
+ seenCursors.add(next);
390
+ cursor = next;
391
+ }
392
+ const out = { pages, items, stop, warnings, degraded, last };
393
+ // The cursor to resume from later, unmodified: the one that was next (budget), or the one that made no progress.
394
+ if (stop !== 'complete' && cursor !== undefined) out.resumeCursor = cursor;
395
+ return out;
396
+ }
397
+
398
+ /**
399
+ * One bulk import (`/api/v1/profiles/{handle}/posts`), continued with `until=meta.next_until` while
400
+ * `meta.truncated` (same `since`, ids deduplicated) up to `pageBudget` requests. Every continuation spends an
401
+ * import. `index: true` asks for the archive coverage only (spends no import quota).
402
+ */
403
+ async history(handle, params = {}, { pageBudget = DEFAULT_PAGE_BUDGET, signal } = {}) {
404
+ const path = `/api/v1/profiles/${encodeURIComponent(handle)}/posts`;
405
+ const ndjson = params.format === 'ndjson';
406
+ if (params.index === true) {
407
+ const res = await this.request(path, { index: true }, { timeoutMs: DEFAULT_TIMEOUT_MS, signal });
408
+ return { kind: 'index', res, index: res.json };
409
+ }
410
+ const budget = Math.max(1, Math.min(20, Math.floor(Number(pageBudget) || DEFAULT_PAGE_BUDGET)));
411
+ const posts = [];
412
+ const seen = new Set();
413
+ const metas = [];
414
+ const warnings = [];
415
+ let profile;
416
+ let error;
417
+ let res;
418
+ let until = params.until;
419
+ let stop = 'complete';
420
+ for (let request = 0; request < budget; request += 1) {
421
+ res = await this.request(path, { ...params, until }, {
422
+ accept: ndjson ? 'application/x-ndjson' : 'application/json',
423
+ timeoutMs: HISTORY_TIMEOUT_MS,
424
+ signal,
425
+ ndjson,
426
+ });
427
+ if (!res.ok) {
428
+ stop = 'error';
429
+ break;
430
+ }
431
+ let page;
432
+ if (ndjson) {
433
+ page = parseNdjson(res.text);
434
+ if (page.error !== undefined) error = page.error;
435
+ } else {
436
+ page = isRecord(res.json) ? { posts: Array.isArray(res.json.posts) ? res.json.posts : [], meta: res.json.meta, profile: res.json.profile } : { posts: [] };
437
+ }
438
+ if (page.profile !== undefined && profile === undefined) profile = page.profile;
439
+ for (const post of page.posts) {
440
+ const id = isRecord(post) ? String(post.id ?? '') : '';
441
+ if (id !== '' && seen.has(id)) continue;
442
+ if (id !== '') seen.add(id);
443
+ posts.push(post);
444
+ }
445
+ if (isRecord(page.meta)) {
446
+ metas.push(page.meta);
447
+ if (Array.isArray(page.meta.warnings)) warnings.push(...page.meta.warnings);
448
+ }
449
+ if (error !== undefined) {
450
+ stop = 'stream_error';
451
+ break;
452
+ }
453
+ if (!isRecord(page.meta)) {
454
+ // An NDJSON stream that ended without its meta line did not finish the walk.
455
+ stop = ndjson ? 'stream_incomplete' : 'complete';
456
+ break;
457
+ }
458
+ if (page.meta.truncated === true && typeof page.meta.next_until === 'string' && page.meta.next_until !== '') {
459
+ if (page.meta.next_until === until) {
460
+ stop = 'repeated_cursor';
461
+ break;
462
+ }
463
+ until = page.meta.next_until;
464
+ stop = 'page_budget';
465
+ continue;
466
+ }
467
+ stop = page.meta.truncated === true ? 'truncated' : 'complete';
468
+ break;
469
+ }
470
+ const lastMeta = metas.at(-1);
471
+ return {
472
+ kind: 'history',
473
+ res,
474
+ posts,
475
+ profile,
476
+ metas,
477
+ meta: lastMeta,
478
+ warnings,
479
+ error,
480
+ stop,
481
+ ...(stop === 'page_budget' ? { nextUntil: until } : {}),
482
+ floorReached: metas.some((meta) => meta.floor_reached === true),
483
+ truncated: stop !== 'complete' || lastMeta?.truncated === true,
484
+ since: params.since,
485
+ };
486
+ }
487
+ }
488
+
489
+ // ---- reporting -------------------------------------------------------------------------------------------------
490
+
491
+ /** The problem document (or transport error) of a failed call as one honest line. */
492
+ export function failureLine(res) {
493
+ if (res === undefined) return 'x.md did not answer.';
494
+ if (res.status === 0) return res.error ?? 'x.md request failed.';
495
+ const problem = res.problem;
496
+ const code = typeof problem?.code === 'string' ? ` ${problem.code}` : '';
497
+ const detail = typeof problem?.detail === 'string' ? problem.detail : typeof problem?.error === 'string' ? problem.error : res.text?.slice(0, 300) ?? '';
498
+ const resolution = typeof problem?.resolution === 'string' ? ` ${problem.resolution}` : '';
499
+ const retry = res.retryAfter === undefined ? '' : res.deferred ? ` Retry after ${res.retryAfter} s (at ${res.retryAt}); not retried inline.` : ` Gave up after ${res.retries} retr${res.retries === 1 ? 'y' : 'ies'} (Retry-After ${res.retryAfter} s).`;
500
+ return `x.md answered HTTP ${res.status}${code}: ${detail}${resolution}${retry}`.trim();
501
+ }
502
+
503
+ /** The status lines every tool result carries: key status, degraded search, remaining quota. */
504
+ export function statusLines(res) {
505
+ const lines = [];
506
+ if (res === undefined) return lines;
507
+ if (res.apiKeyStatus !== undefined) lines.push(`API key: ${res.apiKeyStatus}`);
508
+ if (res.degraded) lines.push('X-Search-Degraded: true — live X search was unavailable; these are web-indexed snippets (ordering, coverage and text can differ), and there are no further pages.');
509
+ const quota = quotaSummary(res.rateLimit);
510
+ if (quota !== '') lines.push(`Remaining quota: ${quota}`);
511
+ return lines;
512
+ }