@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,370 @@
1
+ // `x_read`: one tool, one mode per documented x.md endpoint (5b). Every result carries the warnings, the degraded
2
+ // flag, the API key status and the remaining quota; nothing is filled in when x.md returns less (C1).
3
+ import { circle } from './circle.js';
4
+ import { classifyXUrl, isTcoUrl, resolveTco } from './urls.js';
5
+ import { DEFAULT_PAGE_BUDGET, failureLine, statusLines, warningText } from './xmd.js';
6
+
7
+ export const X_READ_TOOL = 'x_read';
8
+ export const X_READ_MODES = Object.freeze(['post', 'replies', 'search', 'profile', 'followers', 'following', 'history', 'circle']);
9
+ export const SEARCH_FEEDS = Object.freeze(['latest', 'top', 'photos', 'videos', 'users']);
10
+ /** Model-visible text is capped; the cut is said. */
11
+ export const MAX_TEXT_CHARS = 60_000;
12
+
13
+ export const X_READ_DESCRIPTION =
14
+ 'Read public X (Twitter) content through x.md: a post or thread, its replies, search, a profile, followers/following, an account’s post history (bulk import), or an interaction circle. Read-only; private, protected, DM and List content is unsupported. Results always report x.md warnings, degraded search and remaining quota; never fill gaps with invented posts.';
15
+
16
+ export const X_READ_PARAMETERS = Object.freeze({
17
+ type: 'object',
18
+ properties: {
19
+ mode: { type: 'string', enum: [...X_READ_MODES], description: 'post | replies | search | profile | followers | following | history | circle.' },
20
+ url: { type: 'string', description: 'post/replies: an x.com, twitter.com or t.co status URL.' },
21
+ handle: { type: 'string', description: 'Account handle without @ (profile, followers, following, history, circle; post with id).' },
22
+ id: { type: 'string', description: 'Numeric status id (post with handle; replies).' },
23
+ q: { type: 'string', description: 'search: the query; X operators such as from: and to: pass through.' },
24
+ feed: { type: 'string', enum: ['latest', 'top', 'photos', 'videos', 'users', 'media'], description: 'search feed (default latest; media = photos).' },
25
+ limit: { type: 'integer', minimum: 1, maximum: 100, description: 'Items per page: ≤ 100 (search photos/videos/users ≤ 20).' },
26
+ pages: { type: 'integer', minimum: 1, maximum: 50, description: 'Page budget for list modes and history continuations (default 5).' },
27
+ cursor: { type: 'string', description: 'An opaque nextCursor from an earlier result of the same mode, query and feed. Never edit it.' },
28
+ since: { type: 'string', description: 'search/history: oldest post (ISO date, ISO datetime or unix time).' },
29
+ until: { type: 'string', description: 'search/profile/history/circle: newest post (same formats).' },
30
+ thread: { type: 'string', description: 'post: off | full | conversation | 2..100.' },
31
+ context: { type: 'string', enum: ['full', 'thread'], description: 'post: surrounding context.' },
32
+ replies: { type: 'string', enum: ['top', 'recent', 'off'], description: 'post: reply ordering.' },
33
+ userinfo: { type: 'string', enum: ['off', 'author', 'all'], description: 'post: author details.' },
34
+ full: { type: 'boolean', description: 'Dates, stats and expanded details.' },
35
+ format: { type: 'string', enum: ['markdown', 'json', 'obsidian', 'ndjson'], description: 'markdown (default) or json; post also obsidian; history json or ndjson.' },
36
+ include_posts: { type: 'boolean', description: 'profile: false reads identity only.' },
37
+ with_replies: { type: 'boolean', description: 'profile/history: include replies.' },
38
+ with_reposts: { type: 'boolean', description: 'profile/history: include reposts.' },
39
+ only_replies: { type: 'boolean', description: 'history: replies only.' },
40
+ max_posts: { type: 'integer', minimum: 1, maximum: 5000, description: 'history: most posts (default 500, max 5000).' },
41
+ concurrency: { type: 'integer', minimum: 1, maximum: 32, description: 'history: parallel upstream chains (≤ 32).' },
42
+ index: { type: 'boolean', description: 'history: archive coverage only; spends no import quota.' },
43
+ require_live: { type: 'boolean', description: 'search: fail (503) instead of returning web snippets when live search is down.' },
44
+ days: { type: 'integer', minimum: 1, maximum: 365, description: 'circle: window in days (default 120).' },
45
+ fresh: { type: 'boolean', description: 'Bypass x.md caches (nocache/refresh). Only when the user asks for fresh data; cache hits spend no quota.' },
46
+ },
47
+ required: ['mode'],
48
+ additionalProperties: false,
49
+ });
50
+
51
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
52
+ const str = (value) => (typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined);
53
+ const bool = (value) => (typeof value === 'boolean' ? value : undefined);
54
+ const intIn = (value, min, max) => {
55
+ if (value === undefined || value === null || value === '') return undefined;
56
+ const n = Math.floor(Number(value));
57
+ if (!Number.isFinite(n)) return undefined;
58
+ return Math.max(min, Math.min(max, n));
59
+ };
60
+ const handleOf = (value) => str(value)?.replace(/^@/, '');
61
+
62
+ export function normalizeFeed(feed) {
63
+ const value = str(feed)?.toLowerCase();
64
+ if (value === undefined) return undefined;
65
+ if (value === 'media') return 'photos';
66
+ return SEARCH_FEEDS.includes(value) ? value : 'latest';
67
+ }
68
+
69
+ /** The documented search limit: ≤ 100 on latest/top, ≤ 20 on feeds served by own accounts. */
70
+ export function searchLimit(limit, feed) {
71
+ const cap = feed === undefined || feed === 'latest' || feed === 'top' ? 100 : 20;
72
+ return intIn(limit, 1, cap);
73
+ }
74
+
75
+ function capText(text) {
76
+ if (text.length <= MAX_TEXT_CHARS) return text;
77
+ return `${text.slice(0, MAX_TEXT_CHARS)}\n\n[x_read: output cut at ${MAX_TEXT_CHARS} characters; ask for a smaller limit, fewer pages or one post.]`;
78
+ }
79
+
80
+ const STOP_LINES = {
81
+ complete: 'Stopped: nextCursor absent (nothing more to fetch).',
82
+ page_budget: 'Stopped: page budget reached; more pages exist.',
83
+ repeated_cursor: 'Stopped: x.md returned a repeated cursor (no progress). Coverage is incomplete; retry the same cursor later.',
84
+ empty_page: 'Stopped: x.md reported an empty upstream page (empty_page). Coverage is incomplete; retry the same cursor later.',
85
+ degraded: 'Stopped: degraded search has no further pages.',
86
+ error: 'Stopped: a later page failed; the pages above were kept.',
87
+ };
88
+
89
+ /** One post as a compact Markdown line (used when x.md returned no rendered Markdown, e.g. bulk imports). */
90
+ export function postLine(post) {
91
+ if (!isRecord(post)) return '';
92
+ const author = post.author?.screen_name ?? '?';
93
+ const when = typeof post.created_at === 'string' ? ` ${new Date(post.created_at).toISOString().slice(0, 10)}` : '';
94
+ const replyTo = isRecord(post.replying_to) && post.replying_to.screen_name ? ` ↩ @${post.replying_to.screen_name}` : Array.isArray(post.replying_to) && post.replying_to.length > 0 ? ` ↩ ${post.replying_to.map((h) => `@${h}`).join(' ')}` : '';
95
+ const repost = post.reposted_by?.screen_name ? ` (reposted by @${post.reposted_by.screen_name})` : '';
96
+ const text = String(post.text ?? '').replace(/\s+/g, ' ').trim();
97
+ const link = typeof post.url === 'string' ? ` — ${post.url}` : '';
98
+ return `- @${author}${when}${replyTo}${repost}: ${text}${link}`;
99
+ }
100
+
101
+ function userLine(user) {
102
+ if (!isRecord(user)) return '';
103
+ const followers = typeof user.followers === 'number' ? ` · ${user.followers} followers` : '';
104
+ const bio = typeof user.description === 'string' && user.description.trim() !== '' ? ` — ${user.description.replace(/\s+/g, ' ').trim()}` : '';
105
+ return `- @${user.screen_name ?? '?'} (${user.name ?? ''})${followers}${bio}`;
106
+ }
107
+
108
+ function header(title, res, extra = []) {
109
+ const lines = [`x_read ${title}`];
110
+ lines.push(...extra.filter(Boolean));
111
+ lines.push(...statusLines(res));
112
+ return lines;
113
+ }
114
+
115
+ function warningLines(warnings) {
116
+ if (!Array.isArray(warnings) || warnings.length === 0) return [];
117
+ return [`Warnings (${warnings.length}): ${warnings.map(warningText).join('; ')}`];
118
+ }
119
+
120
+ function done(lines, body, value) {
121
+ const text = capText([...lines, '', body].join('\n').trimEnd());
122
+ return { isError: false, text, value };
123
+ }
124
+
125
+ function fail(title, res, value = {}) {
126
+ const lines = header(title, res, [failureLine(res)]);
127
+ return { isError: true, text: lines.join('\n'), value: { ok: false, status: res?.status, code: res?.problem?.code, retryAfter: res?.retryAfter, ...value } };
128
+ }
129
+
130
+ async function postTarget(args, deps) {
131
+ let url = str(args.url);
132
+ if (url !== undefined && isTcoUrl(url)) {
133
+ const resolved = await resolveTco(url, { fetch: deps.fetch, signal: deps.signal });
134
+ if (!resolved.ok) return { error: resolved.error };
135
+ url = resolved.url;
136
+ }
137
+ if (url !== undefined) {
138
+ const target = classifyXUrl(url);
139
+ if (target.kind !== 'post') return { error: `not a status URL: ${url} (${target.reason ?? target.kind})` };
140
+ return { url: target.url, id: target.id, handle: target.handle };
141
+ }
142
+ const handle = handleOf(args.handle);
143
+ const id = str(args.id);
144
+ if (id !== undefined && /^\d+$/.test(id)) return handle === undefined ? { id } : { handle, id };
145
+ return { error: 'post needs url, or handle + id' };
146
+ }
147
+
148
+ // ---- modes -----------------------------------------------------------------------------------------------------
149
+
150
+ async function readPost(client, args, deps) {
151
+ const target = await postTarget(args, deps);
152
+ if (target.error !== undefined) return { isError: true, text: `x_read post: ${target.error}`, value: { ok: false } };
153
+ const format = args.format === 'json' || args.format === 'obsidian' ? args.format : 'markdown';
154
+ const params = {
155
+ ...(target.url !== undefined ? { url: target.url } : target.handle !== undefined ? { handle: target.handle, id: target.id } : { url: `https://x.com/i/status/${target.id}` }),
156
+ thread: str(args.thread),
157
+ context: str(args.context),
158
+ replies: str(args.replies),
159
+ userinfo: str(args.userinfo),
160
+ full: bool(args.full),
161
+ // Obsidian is rendered text; Markdown and JSON both come from the JSON body, which carries `warnings`.
162
+ format: format === 'obsidian' ? 'obsidian' : 'json',
163
+ nocache: args.fresh === true ? true : undefined,
164
+ };
165
+ const res = await client.request('/api/v1/posts', params, { accept: format === 'obsidian' ? 'text/markdown' : 'application/json', signal: deps.signal });
166
+ if (!res.ok) return fail('post', res);
167
+ if (format === 'obsidian') {
168
+ const note = res.warningsHeader ? [`Warnings: x.md reported ${res.warningsHeader} (X-Warnings); read with format=json for the list.`] : [];
169
+ return done(header(`post · obsidian`, res, note), res.text, { ok: true, mode: 'post', format, warningsCount: res.warningsHeader ?? 0, apiKeyStatus: res.apiKeyStatus });
170
+ }
171
+ const body = isRecord(res.json) ? res.json : {};
172
+ const posts = Array.isArray(body.posts) ? body.posts : [];
173
+ const warnings = Array.isArray(body.warnings) ? body.warnings : [];
174
+ const summary = `${posts.length} post${posts.length === 1 ? '' : 's'}${body.source ? ` · source ${body.source}` : ''}${body.cache ? ` · cache ${body.cache}` : ''}`;
175
+ const lines = header(`post · ${summary}`, res, [body.url ? `Post: ${body.url}` : '', ...warningLines(warnings)]);
176
+ const text = format === 'json' ? JSON.stringify({ url: body.url, posts, warnings }, null, 1) : String(body.markdown ?? posts.map(postLine).join('\n'));
177
+ return done(lines, text, { ok: true, mode: 'post', count: posts.length, warnings, apiKeyStatus: res.apiKeyStatus, url: body.url });
178
+ }
179
+
180
+ async function readReplies(client, args, deps) {
181
+ let id = str(args.id);
182
+ if (id === undefined && str(args.url) !== undefined) {
183
+ const target = await postTarget(args, deps);
184
+ if (target.error !== undefined) return { isError: true, text: `x_read replies: ${target.error}`, value: { ok: false } };
185
+ id = target.id;
186
+ }
187
+ if (id === undefined || !/^\d+$/.test(id)) return { isError: true, text: 'x_read replies: needs the numeric status id (or url)', value: { ok: false } };
188
+ const res = await client.request(`/api/v1/posts/${id}/replies`, { limit: intIn(args.limit, 1, 100), format: 'json', nocache: args.fresh === true ? true : undefined }, { signal: deps.signal });
189
+ if (!res.ok) return fail('replies', res);
190
+ const body = isRecord(res.json) ? res.json : {};
191
+ const posts = Array.isArray(body.posts) ? body.posts : [];
192
+ const warnings = Array.isArray(body.warnings) ? body.warnings : [];
193
+ const lines = header(`replies · ${posts.length} replies to ${id}`, res, ['A bounded recent sample, not paginated and not exhaustive.', ...warningLines(warnings)]);
194
+ const text = args.format === 'json' ? JSON.stringify({ posts, warnings }, null, 1) : String(body.markdown ?? posts.map(postLine).join('\n'));
195
+ return done(lines, text, { ok: true, mode: 'replies', count: posts.length, warnings, apiKeyStatus: res.apiKeyStatus });
196
+ }
197
+
198
+ function listResult(mode, title, walk, args, itemsKey) {
199
+ const last = walk.last;
200
+ if (walk.pages.length === 0) return fail(mode, last);
201
+ const lines = header(`${title} · ${walk.items.length} ${itemsKey} over ${walk.pages.length} page${walk.pages.length === 1 ? '' : 's'}`, last, [
202
+ STOP_LINES[walk.stop] ?? `Stopped: ${walk.stop}.`,
203
+ walk.stop === 'error' ? `Failed page: ${failureLine(last)}` : '',
204
+ walk.resumeCursor !== undefined ? `Resume cursor (pass back unchanged, same ${mode} and options): ${walk.resumeCursor}` : '',
205
+ ...warningLines(walk.warnings),
206
+ ]);
207
+ const text = args.format === 'json'
208
+ ? JSON.stringify({ [itemsKey]: walk.items, ...(walk.pages[0]?.profile ? { profile: walk.pages[0].profile } : {}), warnings: walk.warnings, nextCursor: walk.resumeCursor }, null, 1)
209
+ : walk.pages.map((page) => (typeof page.markdown === 'string' ? page.markdown : (Array.isArray(page[itemsKey]) ? page[itemsKey] : []).map(itemsKey === 'users' ? userLine : postLine).join('\n'))).join('\n\n---\n\n');
210
+ return done(lines, text, {
211
+ ok: true,
212
+ mode,
213
+ count: walk.items.length,
214
+ pages: walk.pages.length,
215
+ stop: walk.stop,
216
+ warnings: walk.warnings,
217
+ degraded: walk.degraded,
218
+ ...(walk.resumeCursor === undefined ? {} : { nextCursor: walk.resumeCursor }),
219
+ apiKeyStatus: last?.apiKeyStatus,
220
+ rateLimit: last?.rateLimit,
221
+ });
222
+ }
223
+
224
+ async function readSearch(client, args, deps) {
225
+ const q = str(args.q);
226
+ if (q === undefined) return { isError: true, text: 'x_read search: needs q', value: { ok: false } };
227
+ const feed = normalizeFeed(args.feed);
228
+ const params = {
229
+ q,
230
+ feed,
231
+ limit: searchLimit(args.limit, feed),
232
+ since: str(args.since),
233
+ until: str(args.until),
234
+ cursor: str(args.cursor),
235
+ full: bool(args.full),
236
+ require_live: bool(args.require_live),
237
+ format: 'json',
238
+ nocache: args.fresh === true ? true : undefined,
239
+ };
240
+ const itemsKey = feed === 'users' ? 'users' : 'posts';
241
+ const walk = await client.paginate('/api/v1/search', params, { itemsKey, pageBudget: args.pages ?? DEFAULT_PAGE_BUDGET, signal: deps.signal });
242
+ const result = listResult('search', `search "${q}" · feed ${feed ?? 'latest'}`, walk, args, itemsKey);
243
+ if (walk.pages.length === 0 && walk.last?.status === 503 && args.require_live === true) {
244
+ result.text += '\nLive X search is down (require_live=true answered 503); no web snippets were substituted.';
245
+ }
246
+ return result;
247
+ }
248
+
249
+ async function readProfile(client, args, deps) {
250
+ const handle = handleOf(args.handle);
251
+ if (handle === undefined) return { isError: true, text: 'x_read profile: needs handle', value: { ok: false } };
252
+ const params = {
253
+ include_posts: bool(args.include_posts),
254
+ limit: intIn(args.limit, 1, 100),
255
+ with_replies: bool(args.with_replies),
256
+ with_reposts: bool(args.with_reposts),
257
+ until: str(args.until),
258
+ cursor: str(args.cursor),
259
+ full: bool(args.full),
260
+ format: 'json',
261
+ nocache: args.fresh === true ? true : undefined,
262
+ };
263
+ const path = `/api/v1/profiles/${encodeURIComponent(handle)}`;
264
+ if (args.include_posts === false) {
265
+ const res = await client.request(path, params, { signal: deps.signal });
266
+ if (!res.ok) return fail('profile', res);
267
+ const body = isRecord(res.json) ? res.json : {};
268
+ const lines = header(`profile @${handle} · identity only`, res, warningLines(body.warnings));
269
+ const text = args.format === 'json' ? JSON.stringify({ profile: body.profile ?? null, warnings: body.warnings ?? [] }, null, 1) : String(body.markdown ?? JSON.stringify(body.profile ?? null, null, 1));
270
+ return done(lines, text, { ok: true, mode: 'profile', profile: body.profile, warnings: body.warnings ?? [], apiKeyStatus: res.apiKeyStatus });
271
+ }
272
+ const walk = await client.paginate(path, params, { itemsKey: 'posts', pageBudget: args.pages ?? DEFAULT_PAGE_BUDGET, signal: deps.signal });
273
+ return listResult('profile', `profile @${handle}`, walk, args, 'posts');
274
+ }
275
+
276
+ async function readConnections(client, mode, args, deps) {
277
+ const handle = handleOf(args.handle);
278
+ if (handle === undefined) return { isError: true, text: `x_read ${mode}: needs handle`, value: { ok: false } };
279
+ const params = { limit: intIn(args.limit, 1, 100), cursor: str(args.cursor), full: bool(args.full), format: 'json', nocache: args.fresh === true ? true : undefined };
280
+ const walk = await client.paginate(`/api/v1/profiles/${encodeURIComponent(handle)}/${mode}`, params, { itemsKey: 'users', pageBudget: args.pages ?? DEFAULT_PAGE_BUDGET, signal: deps.signal });
281
+ return listResult(mode, `${mode} of @${handle}`, walk, args, 'users');
282
+ }
283
+
284
+ async function readHistory(client, args, deps) {
285
+ const handle = handleOf(args.handle);
286
+ if (handle === undefined) return { isError: true, text: 'x_read history: needs handle', value: { ok: false } };
287
+ if (args.index === true) {
288
+ const { res, index } = await client.history(handle, { index: true }, { signal: deps.signal });
289
+ if (!res.ok) return fail('history index', res);
290
+ const archive = isRecord(index?.archive) ? index.archive : undefined;
291
+ const lines = header(`history @${handle} · archive index (no import quota spent)`, res, [
292
+ archive === undefined ? 'The archive holds nothing for this account yet.' : `Archived: ${archive.count ?? 0} posts, ${archive.oldest ?? '?'} → ${archive.newest ?? '?'}; covered ${archive.covered_since ?? '?'} → ${archive.covered_until ?? '?'}; floor_reached ${archive.floor_reached === true}`,
293
+ index?.persistent === false ? 'Archive is in-memory on this deployment (persistent: false).' : '',
294
+ ]);
295
+ return done(lines, JSON.stringify(index ?? null, null, 1), { ok: true, mode: 'history', index: true, archive, apiKeyStatus: res.apiKeyStatus });
296
+ }
297
+ const format = args.format === 'ndjson' ? 'ndjson' : 'json';
298
+ const params = {
299
+ since: str(args.since),
300
+ until: str(args.until),
301
+ max_posts: intIn(args.max_posts, 1, 5000),
302
+ with_replies: bool(args.with_replies),
303
+ with_reposts: bool(args.with_reposts),
304
+ only_replies: bool(args.only_replies),
305
+ concurrency: intIn(args.concurrency, 1, 32),
306
+ refresh: args.fresh === true ? true : undefined,
307
+ format,
308
+ };
309
+ const walk = await client.history(handle, params, { pageBudget: args.pages ?? DEFAULT_PAGE_BUDGET, signal: deps.signal });
310
+ if (walk.stop === 'error' && walk.posts.length === 0) return fail('history', walk.res);
311
+ const meta = walk.meta ?? {};
312
+ const stopLine = {
313
+ complete: 'Walk finished for the requested range.',
314
+ page_budget: `Stopped: page budget reached while meta.truncated; continue with until=${walk.nextUntil} and the same since.`,
315
+ truncated: 'meta.truncated is true without next_until; retry the same range later.',
316
+ repeated_cursor: 'Stopped: next_until did not move; retry the same range later.',
317
+ stream_error: `The NDJSON stream ended with an error line: ${warningText(walk.error?.code ? walk.error : JSON.stringify(walk.error))}${walk.error?.retry_after ? ` (retry after ${walk.error.retry_after} s)` : ''}. The posts above it were kept.`,
318
+ stream_incomplete: 'The NDJSON stream ended without its meta line; the walk did not finish.',
319
+ error: `A continuation failed: ${failureLine(walk.res)} The posts collected before it were kept.`,
320
+ }[walk.stop];
321
+ const lines = header(`history @${handle} · ${walk.posts.length} posts over ${walk.metas.length || 1} request${walk.metas.length > 1 ? 's' : ''}`, walk.res, [
322
+ `Range: since ${walk.since ?? '(as far back as X serves)'} · oldest ${meta.oldest ?? '?'} · newest ${meta.newest ?? '?'}`,
323
+ stopLine,
324
+ `meta.truncated: ${walk.truncated} · meta.floor_reached: ${walk.floorReached}${walk.floorReached ? ' (accessible history exhausted; not proof every post ever published is available)' : ''}`,
325
+ isRecord(meta.archive) ? `Archive: served ${meta.archive.served ?? 0}, added ${meta.archive.added ?? 0}, walked ${Array.isArray(meta.archive.walked) ? meta.archive.walked.join('/') : '?'}` : '',
326
+ ...warningLines(walk.warnings),
327
+ walk.warnings.length > 0 ? 'x.md asks for a retry of the same range when warnings are present.' : '',
328
+ ]);
329
+ const text = args.format === 'json' ? JSON.stringify({ profile: walk.profile ?? null, posts: walk.posts, meta: walk.meta ?? null }, null, 1) : walk.posts.map(postLine).join('\n');
330
+ return done(lines, text, {
331
+ ok: walk.stop !== 'error' && walk.stop !== 'stream_error',
332
+ mode: 'history',
333
+ count: walk.posts.length,
334
+ stop: walk.stop,
335
+ truncated: walk.truncated,
336
+ floorReached: walk.floorReached,
337
+ ...(walk.nextUntil === undefined ? {} : { nextUntil: walk.nextUntil }),
338
+ warnings: walk.warnings,
339
+ ...(walk.error === undefined ? {} : { streamError: walk.error }),
340
+ apiKeyStatus: walk.res?.apiKeyStatus,
341
+ });
342
+ }
343
+
344
+ /**
345
+ * Run one `x_read` call. `client` is an {@link XmdClient}; `deps` carries `{signal, fetch, now}`.
346
+ * Resolves `{isError, text, value}`; `text` is the model-visible result.
347
+ */
348
+ export async function runXRead(client, rawArgs, deps = {}) {
349
+ const args = isRecord(rawArgs) ? rawArgs : {};
350
+ const mode = str(args.mode);
351
+ switch (mode) {
352
+ case 'post':
353
+ return readPost(client, args, deps);
354
+ case 'replies':
355
+ return readReplies(client, args, deps);
356
+ case 'search':
357
+ return readSearch(client, args, deps);
358
+ case 'profile':
359
+ return readProfile(client, args, deps);
360
+ case 'followers':
361
+ case 'following':
362
+ return readConnections(client, mode, args, deps);
363
+ case 'history':
364
+ return readHistory(client, args, deps);
365
+ case 'circle':
366
+ return circle(client, args, deps);
367
+ default:
368
+ return { isError: true, text: `x_read: mode must be one of ${X_READ_MODES.join(', ')}`, value: { ok: false } };
369
+ }
370
+ }
@@ -0,0 +1,38 @@
1
+ // 5a: the automatic rewrite. An `x.com` / `twitter.com` / `mobile.twitter.com` / `t.co` URL given to `web_fetch` is
2
+ // fetched through the x.md base URL instead, on the versioned surface, with `Accept: text/markdown`. `t.co` is
3
+ // resolved first; a short link that leads off X is handed back so the engine's own fetcher reads it.
4
+ import { isTcoUrl, isXUrl, resolveTco, rewriteXUrl } from './urls.js';
5
+ import { failureLine, statusLines } from './xmd.js';
6
+
7
+ /**
8
+ * `{handled:false, url}` when the engine's fetcher should read `url` (not X, an unsupported X path, or a `t.co` link
9
+ * that leads elsewhere); otherwise `{handled:true, result}` with the engine's web-fetch result shape
10
+ * `{url, statusCode, body:{kind:'text', content}, truncated}`. A transport failure throws (the tool reports it).
11
+ */
12
+ export async function fetchThroughXmd(rawUrl, { client, signal, fetch: fetchImpl } = {}) {
13
+ let url = String(rawUrl ?? '');
14
+ if (!isXUrl(url)) return { handled: false, url };
15
+ if (isTcoUrl(url)) {
16
+ const resolved = await resolveTco(url, { fetch: fetchImpl, signal });
17
+ if (!resolved.ok) throw new Error(resolved.error);
18
+ url = resolved.url;
19
+ if (!isXUrl(url)) return { handled: false, url };
20
+ }
21
+ const request = rewriteXUrl(url);
22
+ if (request === undefined) return { handled: false, url };
23
+ const res = await client.request(request.path, request.params, { accept: 'text/markdown', signal });
24
+ if (res.status === 0) throw new Error(res.error ?? 'x.md request failed');
25
+ const notes = [];
26
+ if (res.ok) {
27
+ if (res.warningsHeader > 0) notes.push(`x.md reported ${res.warningsHeader} warning${res.warningsHeader === 1 ? '' : 's'} for this read (missing or gated context can shorten a thread); tool_call x_read with format json lists them.`);
28
+ notes.push(...statusLines(res).filter((line) => !line.startsWith('API key')));
29
+ }
30
+ const content = res.ok
31
+ ? `${res.text.trimEnd()}${notes.length > 0 ? `\n\n---\n${notes.map((line) => `> ${line}`).join('\n')}` : ''}\n`
32
+ : `${failureLine(res)}\n`;
33
+ return {
34
+ handled: true,
35
+ target: request.target,
36
+ result: { url: res.url, statusCode: res.status, body: { kind: 'text', content }, truncated: false },
37
+ };
38
+ }
@@ -0,0 +1,131 @@
1
+ // The x.md reader's settings, shared by the Mac and the CLI/TUI.
2
+ //
3
+ // settings.xReader = { enabled: boolean, baseUrl: string, format: 'markdown' | 'obsidian' }
4
+ //
5
+ // in the shared `settings.json` (`PICASSO_SETTINGS_ROOT ?? <PICASSO_HOME ?? ~/.picasso>/settings`), read live with an
6
+ // mtime cache. Absent = on, https://mdfromx.com, Markdown. `PICASSO_X_READER=off` turns it off for one process.
7
+ //
8
+ // The optional API key is never in that file. It is one generic password in the system keychain (service
9
+ // `com.picassohq.x-reader`, account `api-key`), written by the CLI (`picasso settings x-reader key`) and by the Mac
10
+ // relay with the shared-home D7 ACL (`/usr/bin/security` + Picasso.app), so either client and the engine can read
11
+ // it without a prompt. Linux uses libsecret (`secret-tool`). `PICASSO_X_READER_API_KEY` overrides it (tests, CI).
12
+ import { execFile } from 'node:child_process';
13
+ import { readFileSync, statSync } from 'node:fs';
14
+ import { homedir } from 'node:os';
15
+ import { join } from 'node:path';
16
+
17
+ import { DEFAULT_BASE_URL, normalizeBaseUrl } from './xmd.js';
18
+
19
+ export const X_READER_KEYCHAIN_SERVICE = 'com.picassohq.x-reader';
20
+ export const X_READER_KEYCHAIN_ACCOUNT = 'api-key';
21
+ export const X_READER_KEYCHAIN_LABEL = 'Picasso x.md API key';
22
+ export const X_READER_FORMATS = Object.freeze(['markdown', 'obsidian']);
23
+ export const DEFAULT_X_READER = Object.freeze({ enabled: true, baseUrl: DEFAULT_BASE_URL, format: 'markdown' });
24
+ /** The note shown next to the toggle on both clients. */
25
+ export const X_READER_PRIVACY_NOTE = 'X links you open are sent to this third-party service';
26
+ export const X_READER_TOGGLE_LABEL = 'Read X links through x.md (mdfromx.com)';
27
+ const KEY_CACHE_MS = 30_000;
28
+
29
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
30
+
31
+ /** `PICASSO_SETTINGS_ROOT ?? <PICASSO_HOME ?? ~/.picasso>/settings`/settings.json. */
32
+ export function defaultSettingsFile(env = process.env) {
33
+ const root = typeof env.PICASSO_SETTINGS_ROOT === 'string' && env.PICASSO_SETTINGS_ROOT.trim() !== '' ? env.PICASSO_SETTINGS_ROOT : undefined;
34
+ if (root) return join(root, 'settings.json');
35
+ const home = typeof env.PICASSO_HOME === 'string' && env.PICASSO_HOME.trim() !== '' ? env.PICASSO_HOME : join(env.HOME ?? homedir(), '.picasso');
36
+ return join(home, 'settings', 'settings.json');
37
+ }
38
+
39
+ /** The effective `xReader` value from a parsed settings file (defaults for anything absent or malformed). */
40
+ export function xReaderSetting(file, env = process.env) {
41
+ const settings = isRecord(file) && isRecord(file.settings) ? file.settings : {};
42
+ const stored = isRecord(settings.xReader) ? settings.xReader : {};
43
+ let baseUrl = DEFAULT_BASE_URL;
44
+ try {
45
+ baseUrl = normalizeBaseUrl(typeof stored.baseUrl === 'string' ? stored.baseUrl : '');
46
+ } catch {
47
+ baseUrl = DEFAULT_BASE_URL;
48
+ }
49
+ const off = String(env.PICASSO_X_READER ?? '').trim().toLowerCase();
50
+ return {
51
+ enabled: (off === 'off' || off === '0' || off === 'false') ? false : typeof stored.enabled === 'boolean' ? stored.enabled : DEFAULT_X_READER.enabled,
52
+ baseUrl: typeof env.PICASSO_X_READER_BASE_URL === 'string' && env.PICASSO_X_READER_BASE_URL.trim() !== '' ? normalizeBaseUrl(env.PICASSO_X_READER_BASE_URL) : baseUrl,
53
+ format: X_READER_FORMATS.includes(stored.format) ? stored.format : DEFAULT_X_READER.format,
54
+ };
55
+ }
56
+
57
+ /** A live reader over the settings file: re-parsed only when its mtime changes; unreadable reads as defaults. */
58
+ export function settingsReader({ settingsFile, env = process.env } = {}) {
59
+ const file = typeof settingsFile === 'string' && settingsFile !== '' ? settingsFile : defaultSettingsFile(env);
60
+ let mtime;
61
+ let cached = xReaderSetting(undefined, env);
62
+ return () => {
63
+ let stat;
64
+ try {
65
+ stat = statSync(file);
66
+ } catch {
67
+ mtime = undefined;
68
+ cached = xReaderSetting(undefined, env);
69
+ return cached;
70
+ }
71
+ if (stat.mtimeMs !== mtime) {
72
+ mtime = stat.mtimeMs;
73
+ try {
74
+ cached = xReaderSetting(JSON.parse(readFileSync(file, 'utf8')), env);
75
+ } catch {
76
+ cached = xReaderSetting(undefined, env);
77
+ }
78
+ }
79
+ return cached;
80
+ };
81
+ }
82
+
83
+ function run(cmd, args) {
84
+ return new Promise((resolve) => {
85
+ execFile(cmd, args, { timeout: 5000, maxBuffer: 64 * 1024 }, (error, stdout) => {
86
+ resolve({ ok: error === null, stdout: String(stdout ?? '') });
87
+ });
88
+ });
89
+ }
90
+
91
+ /** Read the stored key from the system keychain; `undefined` when there is none. */
92
+ export async function readKeychainApiKey({ platform = process.platform, runner = run } = {}) {
93
+ if (platform === 'darwin') {
94
+ const result = await runner('/usr/bin/security', ['find-generic-password', '-s', X_READER_KEYCHAIN_SERVICE, '-a', X_READER_KEYCHAIN_ACCOUNT, '-w']);
95
+ const key = result.ok ? result.stdout.trim() : '';
96
+ return key === '' ? undefined : key;
97
+ }
98
+ if (platform === 'linux') {
99
+ const result = await runner('secret-tool', ['lookup', 'service', X_READER_KEYCHAIN_SERVICE, 'account', X_READER_KEYCHAIN_ACCOUNT]);
100
+ const key = result.ok ? result.stdout.trim() : '';
101
+ return key === '' ? undefined : key;
102
+ }
103
+ return undefined;
104
+ }
105
+
106
+ /**
107
+ * The API key source: `PICASSO_X_READER_API_KEY` first, else the keychain (cached for 30 s so a key saved in either
108
+ * client is picked up without restarting the engine). `deps.readKeychain` replaces the keychain in tests.
109
+ */
110
+ export function apiKeyReader({ env = process.env, readKeychain = readKeychainApiKey, now = Date.now } = {}) {
111
+ let cachedAt = -Infinity;
112
+ let cached;
113
+ const read = async () => {
114
+ const fromEnv = typeof env.PICASSO_X_READER_API_KEY === 'string' ? env.PICASSO_X_READER_API_KEY.trim() : '';
115
+ if (fromEnv !== '') return fromEnv;
116
+ if (now() - cachedAt < KEY_CACHE_MS) return cached;
117
+ try {
118
+ cached = await readKeychain();
119
+ } catch {
120
+ cached = undefined;
121
+ }
122
+ cachedAt = now();
123
+ return cached;
124
+ };
125
+ /** Forget the cached key (the process that just saved or removed it). */
126
+ read.invalidate = () => {
127
+ cachedAt = -Infinity;
128
+ cached = undefined;
129
+ };
130
+ return read;
131
+ }