@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,235 @@
1
+ // Progress-report detection and parsing — the one contract every surface follows.
2
+ //
3
+ // A progress report is real assistant text (C1: parsed and condensed, never invented) that has
4
+ // 1. a heading: a line whose first 100 characters (markdown stripped) say "progress" or "status"
5
+ // (`**Progress report** · 45%`, `## Status update`, `10-Minute Progress Status Update 1. …`), and
6
+ // 2. at least MIN_FIELDS distinct known field labels after it, each followed by `:` (or ` - `/` — `).
7
+ //
8
+ // The labels cover both Picasso's compact format (Goal / Done / In progress / Next / Blockers) and the
9
+ // ten-field policy format (Original task / goal, Total work packages, Fully completed, Partially completed
10
+ // (in-progress), Not started, Blocked, Overall completion %, Work completed in the last 10 minutes,
11
+ // Current work, Next steps). Labels are found anywhere in the body, so a report squeezed onto one line
12
+ // (`… 1. Original Task / Goal: X 2. Total work packages: 7 …`) parses the same as a multi-line one.
13
+ //
14
+ // Mirrors: packages/tui/src/progress-report.ts (TS) and
15
+ // apps/mac/Picasso/Features/Thread/ProgressReport.swift (Swift). All three run
16
+ // test/fixtures/reports.json, so they agree on every fixture.
17
+
18
+ export const MIN_FIELDS = 3;
19
+ export const ONE_LINE_PART_MAX = 72;
20
+
21
+ /** Field key → label alternation (longest first inside each; the scan takes the earliest match position). */
22
+ export const FIELD_LABELS = Object.freeze([
23
+ ['recent', String.raw`(?:work\s+)?(?:done|completed|finished)\s+(?:in\s+)?(?:the\s+)?(?:last|past)\s+10\s*-?\s*m(?:in(?:ute)?s?)?|(?:in\s+)?(?:the\s+)?(?:last|past)\s+10\s*-?\s*m(?:in(?:ute)?s?)?|since\s+(?:the\s+)?last\s+(?:update|report)`],
24
+ ['goal', String.raw`original\s+(?:task|goal|request)(?:\s*\/\s*goal)?|task\s*\/\s*goal|goal|objective`],
25
+ ['total', String.raw`total(?:\s+number\s+of)?\s+work[\s-]*packages|total\s+(?:steps|tasks)|work[\s-]*packages`],
26
+ ['inProgress', String.raw`partially\s+completed|in[\s-]+progress`],
27
+ ['notStarted', String.raw`not[\s-]+(?:yet\s+)?started|remaining`],
28
+ ['done', String.raw`fully\s+completed|completed|done|finished`],
29
+ ['blocked', String.raw`blocked(?:\s+work\s+packages)?|blockers?`],
30
+ ['percent', String.raw`overall(?:\s+(?:completion|progress))?(?:\s*%)?|completion(?:\s*%)?|percent(?:age)?(?:\s+complete)?`],
31
+ ['current', String.raw`current(?:ly)?(?:\s+work)?|working\s+on|now`],
32
+ ['next', String.raw`next(?:\s+steps?)?|up\s+next`],
33
+ ]);
34
+
35
+ const LABEL_SOURCE = FIELD_LABELS.map(([key, source]) => `(?<${key}>${source})`).join('|');
36
+ // A label starts a line, follows a list marker / number / separator, and ends at `:` (or a spaced dash),
37
+ // optionally after `**`, a parenthetical, or `%`.
38
+ const LABEL_RE = new RegExp(
39
+ String.raw`(?:^|(?<=[\s>*_#•·|(]|\d[.)]))(?:${LABEL_SOURCE})(?:\*\*|__)?\s*(?:\([^)\n]{0,40}\))?\s*(?:\*\*|__)?\s*(?::|\s[-–—]\s)`,
40
+ 'gimu',
41
+ );
42
+ const HEADING_RE = /\b(?:progress|status)\b/iu;
43
+ const PERCENT_RE = /(\d{1,3}(?:\.\d+)?)\s*%/u;
44
+
45
+ /** Markdown emphasis/heading marks removed, so labels and headings match plain text. */
46
+ export function stripMarkdown(text) {
47
+ return String(text ?? '')
48
+ .replace(/\r\n?/gu, '\n')
49
+ .replace(/^\s{0,3}#{1,6}\s+/gmu, '')
50
+ .replace(/\*\*|__|`/gu, '')
51
+ .replace(/^\s{0,3}>\s?/gmu, '');
52
+ }
53
+
54
+ const collapse = (value) => value.replace(/\s+/gu, ' ').trim();
55
+
56
+ /** One field value: whitespace collapsed, a trailing list number (`… 3.`) and separators removed. */
57
+ function cleanValue(raw) {
58
+ let value = collapse(raw);
59
+ value = value.replace(/(?:^|\s)(?:\d{1,2}[.)]|[-*•·|])\s*$/u, '').trim();
60
+ value = value.replace(/^[-*•·|]\s*/u, '').trim();
61
+ return value;
62
+ }
63
+
64
+ /** The first sentence-ish clause of a value, capped for one line. */
65
+ export function clip(value, max = ONE_LINE_PART_MAX) {
66
+ const line = collapse(String(value ?? ''));
67
+ if (line.length <= max) return line;
68
+ const cut = line.slice(0, max - 1);
69
+ const space = cut.lastIndexOf(' ');
70
+ return `${(space > max * 0.6 ? cut.slice(0, space) : cut).replace(/[\s,;:.]+$/u, '')}…`;
71
+ }
72
+
73
+ /** The heading line's index in `lines`, or -1. */
74
+ function headingIndex(lines) {
75
+ for (let index = 0; index < lines.length; index += 1) {
76
+ const line = lines[index].trim();
77
+ if (line.length === 0) continue;
78
+ if (HEADING_RE.test(line.slice(0, 100))) return index;
79
+ }
80
+ return -1;
81
+ }
82
+
83
+ /**
84
+ * Parse `text` as a progress report. Returns `undefined` when it is not one; otherwise
85
+ * `{heading, title, percent?, method?, fields: {key: value}, fieldCount, oneLine}` built only from the text.
86
+ */
87
+ export function parseProgressReport(text) {
88
+ if (typeof text !== 'string' || text.length === 0) return undefined;
89
+ const plain = stripMarkdown(text);
90
+ const lines = plain.split('\n');
91
+ const at = headingIndex(lines);
92
+ if (at < 0) return undefined;
93
+ const body = lines.slice(at).join('\n');
94
+ const matches = [];
95
+ LABEL_RE.lastIndex = 0;
96
+ for (let match = LABEL_RE.exec(body); match !== null; match = LABEL_RE.exec(body)) {
97
+ const key = Object.entries(match.groups ?? {}).find(([, value]) => value !== undefined)?.[0];
98
+ if (key !== undefined) matches.push({ key, start: match.index, end: match.index + match[0].length });
99
+ if (match[0].length === 0) LABEL_RE.lastIndex += 1;
100
+ }
101
+ const fields = {};
102
+ for (let index = 0; index < matches.length; index += 1) {
103
+ const { key, end } = matches[index];
104
+ if (fields[key] !== undefined) continue;
105
+ const stop = index + 1 < matches.length ? matches[index + 1].start : body.length;
106
+ const value = cleanValue(body.slice(end, stop));
107
+ if (value.length > 0) fields[key] = value;
108
+ }
109
+ const fieldCount = Object.keys(fields).length;
110
+ if (fieldCount < MIN_FIELDS) return undefined;
111
+ const headingLine = lines[at].trim();
112
+ // A one-line report runs its fields into the heading line: the heading is the text before the first label,
113
+ // without the list number (`… Update 1.`) that introduced it.
114
+ const inline = matches.length > 0 && matches[0].start < headingLine.length;
115
+ const heading = inline
116
+ ? collapse(headingLine.slice(0, matches[0].start)).replace(/(?:\s*(?:\d{1,2}[.)]|[-*•·|]))+\s*$/u, '').trim()
117
+ : collapse(headingLine);
118
+ let percent;
119
+ let method;
120
+ for (const source of [fields.percent, heading, body]) {
121
+ if (typeof source !== 'string') continue;
122
+ const found = PERCENT_RE.exec(source);
123
+ if (found === null) continue;
124
+ const value = Number(found[1]);
125
+ if (!Number.isFinite(value) || value < 0 || value > 100) continue;
126
+ percent = Math.round(value);
127
+ const rest = source.slice(found.index + found[0].length).replace(/^[\s·:,-]+/u, '');
128
+ const paren = /^\(([^)]{1,120})\)/u.exec(rest);
129
+ if (source !== body && (paren || rest.length > 0)) method = clip(paren ? paren[1] : rest.split(/\s[·|]\s/u)[0], 80);
130
+ break;
131
+ }
132
+ const now = fields.current ?? fields.inProgress;
133
+ const parts = [];
134
+ if (percent !== undefined) parts.push(`${percent}%`);
135
+ if (now) parts.push(`Now: ${clip(now)}`);
136
+ if (fields.next) parts.push(`Next: ${clip(fields.next)}`);
137
+ if (parts.length < 2 && fields.done) parts.push(`Done: ${clip(fields.done)}`);
138
+ // The card title: the heading without its inline percent/method tail (`Progress report · 45% (…)` → `Progress report`).
139
+ const title = (heading.split(/\s[·|–—-]\s|\s\d{1,3}(?:\.\d+)?\s*%/u)[0] ?? '').replace(/[\s:·|–—-]+$/u, '').trim();
140
+ return {
141
+ heading: heading || 'Progress report',
142
+ title: title || 'Progress report',
143
+ ...(percent === undefined ? {} : { percent }),
144
+ ...(method ? { method } : {}),
145
+ fields,
146
+ fieldCount,
147
+ oneLine: parts.join(' · '),
148
+ };
149
+ }
150
+
151
+ /** Whether `text` is a progress report (see `parseProgressReport`). */
152
+ export function isProgressReport(text) {
153
+ return parseProgressReport(text) !== undefined;
154
+ }
155
+
156
+ // ── The full report as markdown ───────────────────────────────────────────────────────────────────────────────
157
+ //
158
+ // The model often writes a report as plain `Label: text` lines, which every surface drew as run-on prose. The
159
+ // expanded card renders `formatReportMarkdown(text)` instead: the heading line goes (the card already shows the title
160
+ // and percent), each `Label: value` line gets a bold label, and a value of several `;`-separated items (outside
161
+ // parentheses, brackets and code) becomes a bullet list under its label. Words are never changed (C1). A one-line
162
+ // report (fields on the heading line) is returned as written.
163
+
164
+ /** A line that starts with a short label and `:` — optional list marker, optional `**`/`__` around the label. */
165
+ const LABEL_LINE_RE = /^(\s*)((?:[-*•]|\d{1,2}[.)])\s+)?(?:\*\*|__)?([A-Za-z][A-Za-z0-9 /%()'&-]{0,48}?)(?:\*\*|__)?\s*:(?:\*\*|__)?\s+(\S.*)$/u;
166
+ const MAX_LABEL_WORDS = 8;
167
+
168
+ /** `value` split at `;` outside (), [], {} and backticks; parts trimmed, empties dropped. */
169
+ export function splitReportItems(value) {
170
+ const parts = [];
171
+ let depth = 0;
172
+ let code = false;
173
+ let start = 0;
174
+ for (let index = 0; index < value.length; index += 1) {
175
+ const char = value[index];
176
+ if (char === '`') code = !code;
177
+ else if (code) continue;
178
+ else if (char === '(' || char === '[' || char === '{') depth += 1;
179
+ else if ((char === ')' || char === ']' || char === '}') && depth > 0) depth -= 1;
180
+ else if (char === ';' && depth === 0) {
181
+ parts.push(value.slice(start, index));
182
+ start = index + 1;
183
+ }
184
+ }
185
+ parts.push(value.slice(start));
186
+ return parts.map((part) => part.trim()).filter((part) => part.length > 0);
187
+ }
188
+
189
+ /** The report text as markdown with bold labels and per-item bullets (see above). */
190
+ export function formatReportMarkdown(text) {
191
+ const source = String(text ?? '').replace(/\r\n?/gu, '\n');
192
+ const lines = source.split('\n');
193
+ const plain = stripMarkdown(source).split('\n');
194
+ let heading = -1;
195
+ for (let index = 0; index < plain.length; index += 1) {
196
+ const line = plain[index].trim();
197
+ if (line === '') continue;
198
+ if (HEADING_RE.test(line.slice(0, 100))) heading = index;
199
+ break;
200
+ }
201
+ if (heading >= 0) {
202
+ LABEL_RE.lastIndex = 0;
203
+ if (LABEL_RE.test(plain[heading])) return source.trim();
204
+ LABEL_RE.lastIndex = 0;
205
+ }
206
+ const out = [];
207
+ const blank = () => { if (out.length > 0 && out[out.length - 1] !== '') out.push(''); };
208
+ let fence = false;
209
+ lines.forEach((line, index) => {
210
+ if (index === heading) return;
211
+ if (/^\s*(```|~~~)/u.test(line)) fence = !fence;
212
+ const match = fence ? null : LABEL_LINE_RE.exec(line);
213
+ const label = match?.[3]?.trim() ?? '';
214
+ if (match === null || label.split(/\s+/u).length > MAX_LABEL_WORDS) {
215
+ out.push(line);
216
+ return;
217
+ }
218
+ const [, indent, marker, , value] = match;
219
+ // A list item (`3. Done: …`) keeps its list tight: bold label only, no blank lines, no nested bullets.
220
+ if (marker !== undefined || indent !== '') {
221
+ out.push(`${indent}${marker ?? ''}**${label}:** ${value.trim()}`);
222
+ return;
223
+ }
224
+ const items = splitReportItems(value);
225
+ blank();
226
+ if (items.length >= 2) {
227
+ out.push(`**${label}:**`);
228
+ for (const item of items) out.push(`- ${item}`);
229
+ } else {
230
+ out.push(`**${label}:** ${value.trim()}`);
231
+ }
232
+ out.push('');
233
+ });
234
+ return out.join('\n').replace(/\n{3,}/gu, '\n\n').trim();
235
+ }
@@ -0,0 +1,436 @@
1
+ // @picasso/provider-models — a provider route's live model listing, read inside dsh with the route's stored key.
2
+ //
3
+ // dsh's `llm/discoverModels` resolves a route's stored credential but keeps only ids, names and context windows, so a
4
+ // hand-declared pi-ai model never learns which reasoning efforts it takes. A client outside dsh can't read the key
5
+ // (by design: dsh never hands key values out), so it can't ask an authenticated `/models` itself. This plugin adds one
6
+ // Host Remote service, `providerModels`, that does the request inside dsh:
7
+ // list {provider} finds the route in dsh's configurable-provider directory (`ctx.llm.listConfigurableProviders`),
8
+ // reads its profile from settings (endpoint, protocol, headers, `apiKeyEnv`), resolves the key
9
+ // through `ctx.credentials` (the path llm-pi-ai's `resolveApiKey` takes), GETs the listing and
10
+ // returns only `{models:[{id, contextWindow?, reasoningEfforts?:[level…]}], authenticated}`.
11
+ // The key is sent only to the route's own configured endpoint (never a caller-supplied URL), never returned, logged or
12
+ // put in an error; a reply that would contain it is refused.
13
+ //
14
+ // Zero runtime dependencies, like @picasso/schedule-pause: Remote methods use the gateway's source-mode markers and
15
+ // failures are structural dsh RemoteErrors (`isDSHRemoteError`, code `providerModels/<code>`).
16
+
17
+ export const name = 'picasso-provider-models';
18
+ export const dshTarget = '0.2.2-rc.3';
19
+ export const SERVICE_KEY = 'providerModels';
20
+ const REMOTE_METHOD_DESCRIPTOR = '@deepseek-ai/dsh-typert-protocol/remote-methods';
21
+ /** dsh's pi-ai thinking levels, in its order. `off` is never declared from a listing. */
22
+ export const THINKING_LEVELS = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
23
+ /** The levels Claude's thinking control takes: the only ones read off an Anthropic Messages listing. */
24
+ export const CLAUDE_THINKING_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'];
25
+ const OPENAI_EFFORTS = ['low', 'medium', 'high'];
26
+ const ANTHROPIC_VERSION = '2023-06-01';
27
+ const MAX_LISTING_BYTES = 4 * 1024 * 1024;
28
+ const LISTING_TIMEOUT_MS = 15_000;
29
+ /** A whole listing, every page, is read within this. */
30
+ const LISTING_DEADLINE_MS = 45_000;
31
+ const MAX_LISTING_PAGES = 20;
32
+ const MAX_REDIRECTS = 3;
33
+ const CLOUDFLARE_PER_PAGE = 100;
34
+
35
+ export class ProviderModelsError extends Error {
36
+ constructor(code, message, details = {}) {
37
+ super(message);
38
+ this.name = 'RemoteError';
39
+ this.code = `providerModels/${code}`;
40
+ this.details = details;
41
+ this.isDSHRemoteError = true;
42
+ }
43
+ }
44
+
45
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
46
+ const text = (value) => (typeof value === 'string' && value.trim() ? value.trim() : undefined);
47
+
48
+ /** The levels a Gemini model the native listing marks `thinking: true` takes (the Gemini route's own declaration). */
49
+ const GEMINI_THINKING_LEVELS = Object.freeze(['low', 'medium', 'high']);
50
+
51
+ /** Google's Gemini API host, native or OpenAI-compatible path. */
52
+ export function isGeminiHost(baseURL) {
53
+ try {
54
+ return new URL(baseURL).hostname === 'generativelanguage.googleapis.com';
55
+ } catch {
56
+ return false;
57
+ }
58
+ }
59
+
60
+ /** Google's native Gemini API (`generativelanguage.googleapis.com`), not its OpenAI-compatible `/openai` path. */
61
+ export function isGeminiNative(baseURL) {
62
+ try {
63
+ return new URL(baseURL).hostname === 'generativelanguage.googleapis.com' && !baseURL.replace(/\/+$/, '').endsWith('/openai');
64
+ } catch {
65
+ return false;
66
+ }
67
+ }
68
+
69
+ /** The Workers AI account an endpoint names (`api.cloudflare.com/client/v4/accounts/<id>[/ai[/v1]]`), if it is one. */
70
+ export function cloudflareAccount(baseURL) {
71
+ try {
72
+ const url = new URL(baseURL);
73
+ if (url.hostname !== 'api.cloudflare.com') return undefined;
74
+ return /^\/client\/v4\/accounts\/([^/]+)(?:\/ai(?:\/.*)?)?\/?$/u.exec(url.pathname)?.[1];
75
+ } catch {
76
+ return undefined;
77
+ }
78
+ }
79
+
80
+ /** The listing URL pi-ai reads for a protocol (its `listingUrl`); for Workers AI, the account's model search. */
81
+ export function listingUrl(baseURL, api) {
82
+ const base = baseURL.replace(/\/+$/, '');
83
+ // Gemini's native listing pages at 50 by default; one page holds every model.
84
+ if (isGeminiNative(base)) return `${base}/models?pageSize=1000`;
85
+ const account = cloudflareAccount(base);
86
+ if (account !== undefined) return `https://api.cloudflare.com/client/v4/accounts/${account}/ai/models/search?per_page=${CLOUDFLARE_PER_PAGE}`;
87
+ if (api !== 'anthropic-messages') return `${base}/models`;
88
+ return `${base.endsWith('/v1') ? base.slice(0, -3) : base}/v1/models?limit=1000`;
89
+ }
90
+
91
+ /**
92
+ * The reasoning levels one listing entry advertises, in dsh's order: Codex-style `supported_reasoning_levels`
93
+ * (`[{effort}]`), `reasoning_efforts`-style lists, Claude thinking levels; failing those, an OpenAI-protocol entry whose
94
+ * `supported_parameters` names `reasoning_effort` (or OpenRouter's `reasoning`) takes the API's low/medium/high.
95
+ * Undefined when nothing is advertised. Mirrors apps/desktop-helper/src/model-listing.ts `advertisedEfforts`.
96
+ */
97
+ export function advertisedLevels(entry, api) {
98
+ const allowed = api === 'anthropic-messages' ? CLAUDE_THINKING_LEVELS : THINKING_LEVELS.filter((level) => level !== 'off');
99
+ const reasoning = isRecord(entry.reasoning) ? entry.reasoning : {};
100
+ const capabilities = isRecord(entry.capabilities) ? entry.capabilities : {};
101
+ const thinking = isRecord(capabilities.thinking) ? capabilities.thinking : {};
102
+ // Anthropic's Models API: `capabilities.effort: {supported, low: {supported}, …, max}`.
103
+ const effort = isRecord(capabilities.effort) ? capabilities.effort : undefined;
104
+ if (effort !== undefined && effort.supported !== false) {
105
+ const levels = allowed.filter((level) => isRecord(effort[level]) && effort[level].supported === true);
106
+ if (levels.length > 0) return ordered(levels);
107
+ }
108
+ const candidates = [
109
+ entry.supported_reasoning_levels, entry.supported_reasoning_efforts, entry.reasoning_efforts, entry.reasoningEfforts,
110
+ reasoning.efforts, reasoning.levels, capabilities.reasoning_efforts, thinking.levels, thinking.efforts,
111
+ ];
112
+ for (const candidate of candidates) {
113
+ const levels = levelNames(candidate).filter((level) => allowed.includes(level));
114
+ if (levels.length > 0) return ordered(levels);
115
+ }
116
+ // Gemini's native listing marks a model that can think with `thinking: true` and names no levels.
117
+ if (entry.thinking === true && api !== 'anthropic-messages') return [...GEMINI_THINKING_LEVELS];
118
+ if (api !== 'anthropic-messages' && Array.isArray(entry.supported_parameters)) {
119
+ const parameters = entry.supported_parameters.filter((value) => typeof value === 'string');
120
+ if (parameters.includes('reasoning_effort') || parameters.includes('reasoning')) return [...OPENAI_EFFORTS];
121
+ }
122
+ return undefined;
123
+ }
124
+
125
+ /**
126
+ * A listing body (`{data:[…]}`, Gemini's native `{models:[{name:"models/<id>",…}]}` or `{models:{id:{…}}}`) as
127
+ * `[{id, contextWindow?, reasoningEfforts?}]`, or undefined.
128
+ */
129
+ export function parseListing(body, api, options = {}) {
130
+ let listed;
131
+ if (Array.isArray(body)) listed = body.filter(isRecord).map((raw) => ({ raw }));
132
+ else if (!isRecord(body)) return undefined;
133
+ // Cloudflare Workers AI (`{result: [{id: <uuid>, name: "@cf/…", task, properties}], result_info}`): the model name is the id.
134
+ else if (Array.isArray(body.result)) listed = body.result.filter(isRecord).map((raw) => ({ key: text(raw.name) ?? text(raw.id), raw }));
135
+ else if (Array.isArray(body.data)) listed = body.data.filter(isRecord).map((raw) => ({ raw }));
136
+ else if (Array.isArray(body.models)) listed = body.models.filter(isRecord).map((raw) => ({ key: text(raw.name)?.replace(/^models\//u, '') ?? text(raw.id), raw }));
137
+ else if (isRecord(body.models)) listed = Object.entries(body.models).filter(([, raw]) => isRecord(raw)).map(([key, raw]) => ({ key, raw }));
138
+ else return undefined;
139
+ const models = listed.flatMap(({ key, raw }) => {
140
+ const named = text(key) ?? text(raw.id);
141
+ const id = options.stripModelsPrefix === true ? named?.replace(/^models\//u, '') : named;
142
+ if (!id || !chatCapable({ ...raw, id })) return [];
143
+ const contextWindow = capacity(raw.context_window, raw.context_length, raw.contextWindow, raw.max_input_tokens, raw.max_context_length, raw.inputTokenLimit, isRecord(raw.limit) ? raw.limit.context : undefined, isRecord(raw.top_provider) ? raw.top_provider.context_length : undefined, propertyValues(raw.properties).context_window);
144
+ const reasoningEfforts = advertisedLevels(raw, api);
145
+ return [{ id, ...(contextWindow !== undefined ? { contextWindow } : {}), ...(reasoningEfforts ? { reasoningEfforts } : {}) }];
146
+ });
147
+ return mergeModels([], models);
148
+ }
149
+
150
+ /** `later` folded into `earlier` by id: the first position is kept; a later entry's stated fields fill or replace. */
151
+ function mergeModels(earlier, later) {
152
+ const byId = new Map(earlier.map((model) => [model.id, model]));
153
+ for (const model of later) {
154
+ const known = byId.get(model.id);
155
+ byId.set(model.id, known ? { ...known, ...model } : model);
156
+ }
157
+ return [...byId.values()];
158
+ }
159
+
160
+ /** Workers AI's `properties: [{property_id, value}]` as numbers by name. */
161
+ function propertyValues(value) {
162
+ const out = {};
163
+ if (!Array.isArray(value)) return out;
164
+ for (const item of value) {
165
+ if (!isRecord(item) || typeof item.property_id !== 'string') continue;
166
+ const number = Number(item.value);
167
+ if (Number.isSafeInteger(number) && number > 0) out[item.property_id] = number;
168
+ }
169
+ return out;
170
+ }
171
+
172
+ /** Model ids a chat route can never serve: embeddings, speech, image/video, moderation, rerank, realtime, legacy completion-only. */
173
+ const NON_CHAT_ID = /(?:^|[-_./])(?:embed|embedding|embeddings|whisper|tts|transcribe|dall-e|gpt-image|moderation|moderations|rerank|reranker|realtime|sora|imagen|veo|davinci-002|babbage-002)(?:[-_./\d]|$)/u;
174
+ const NON_CHAT_KIND = new Set(['embedding', 'embeddings', 'image', 'image_generation', 'audio', 'audio_speech', 'audio_transcription', 'speech', 'tts', 'moderation', 'moderations', 'rerank', 'video', 'video_generation', 'ocr']);
175
+
176
+ /**
177
+ * Whether a listing entry is a model a chat route serves (mirrors the relay's `chatCapable`): Gemini's
178
+ * `supportedGenerationMethods`, Mistral's `capabilities.completion_chat`, OpenRouter's output modalities, Workers AI's
179
+ * `task.name`, gateways' `type`/`mode`; an id-only listing (OpenAI's) is judged by the id.
180
+ */
181
+ export function chatCapable(entry) {
182
+ const capabilities = isRecord(entry.capabilities) ? entry.capabilities : {};
183
+ if (capabilities.completion_chat === false) return false;
184
+ const methods = entry.supportedGenerationMethods;
185
+ if (Array.isArray(methods) && !methods.includes('generateContent') && !methods.includes('streamGenerateContent')) return false;
186
+ const architecture = isRecord(entry.architecture) ? entry.architecture : {};
187
+ const outputs = Array.isArray(architecture.output_modalities) ? architecture.output_modalities : undefined;
188
+ if (outputs !== undefined && outputs.length > 0 && !outputs.includes('text')) return false;
189
+ const modality = typeof architecture.modality === 'string' ? architecture.modality : undefined;
190
+ if (outputs === undefined && modality?.includes('->') && !(modality.split('->')[1] ?? '').includes('text')) return false;
191
+ const task = isRecord(entry.task) ? text(entry.task.name) : undefined;
192
+ if (task !== undefined && task !== 'Text Generation') return false;
193
+ for (const kind of [entry.type, entry.mode]) if (typeof kind === 'string' && NON_CHAT_KIND.has(kind.toLowerCase())) return false;
194
+ const id = text(entry.id);
195
+ return id === undefined || !NON_CHAT_ID.test(id.toLowerCase());
196
+ }
197
+
198
+ /** The URL for display: no credentials, query or fragment. */
199
+ function shown(url) {
200
+ try {
201
+ const parsed = new URL(url);
202
+ return `${parsed.origin}${parsed.pathname}`;
203
+ } catch {
204
+ return 'the endpoint';
205
+ }
206
+ }
207
+
208
+ /** Reads a body of at most `cap` bytes; undefined when larger (judged on the bytes read, not the length declared). */
209
+ async function readCapped(response, cap) {
210
+ const declared = Number(response.headers.get('content-length'));
211
+ if (Number.isFinite(declared) && declared > cap) {
212
+ await response.body?.cancel().catch(() => undefined);
213
+ return undefined;
214
+ }
215
+ if (!response.body) return '';
216
+ const reader = response.body.getReader();
217
+ const chunks = [];
218
+ let total = 0;
219
+ for (;;) {
220
+ const { done, value } = await reader.read();
221
+ if (done) break;
222
+ total += value.byteLength;
223
+ if (total > cap) {
224
+ await reader.cancel().catch(() => undefined);
225
+ return undefined;
226
+ }
227
+ chunks.push(value);
228
+ }
229
+ return Buffer.concat(chunks).toString('utf8');
230
+ }
231
+
232
+ /** The next page's URL (the first URL plus the family's cursor), or undefined at the last page. */
233
+ function nextPage(first, body, pageNumber) {
234
+ if (!isRecord(body)) return undefined;
235
+ if (body.has_more === true && typeof body.last_id === 'string' && body.last_id) return `${first}&after_id=${encodeURIComponent(body.last_id)}`;
236
+ if (typeof body.nextPageToken === 'string' && body.nextPageToken) return `${first}&pageToken=${encodeURIComponent(body.nextPageToken)}`;
237
+ if (Array.isArray(body.result)) {
238
+ const info = isRecord(body.result_info) ? body.result_info : {};
239
+ const count = body.result.length;
240
+ const current = capacity(info.page) ?? pageNumber;
241
+ const perPage = capacity(info.per_page) ?? CLOUDFLARE_PER_PAGE;
242
+ const total = capacity(info.total_count);
243
+ const pages = capacity(info.total_pages) ?? (total !== undefined ? Math.ceil(total / perPage) : undefined);
244
+ if (count === 0) return undefined;
245
+ if (pages !== undefined ? current >= pages : count < perPage) return undefined;
246
+ return `${first}&page=${current + 1}`;
247
+ }
248
+ return undefined;
249
+ }
250
+
251
+ /**
252
+ * The service. `llm`, `settings` and `credentials` are dsh's services, resolved on each call so the plugin can start
253
+ * before them; `fetch` is injectable for tests.
254
+ */
255
+ export class ProviderModels {
256
+ constructor(options) {
257
+ this.llm = typeof options.llm === 'function' ? options.llm : () => options.llm;
258
+ this.settings = typeof options.settings === 'function' ? options.settings : () => options.settings;
259
+ this.credentials = typeof options.credentials === 'function' ? options.credentials : () => options.credentials;
260
+ this.fetch = options.fetch ?? ((url, init) => fetch(url, init));
261
+ }
262
+
263
+ /** `providerModels/list {provider}` → `{provider, models, authenticated}`. */
264
+ async list(provider) {
265
+ const route = requireString(provider, 'provider');
266
+ const entry = this.directory().find((candidate) => candidate.provider === route);
267
+ if (!entry) throw new ProviderModelsError('not-found', `No provider named ${route}.`, { provider: route });
268
+ const profile = this.profile(entry);
269
+ const baseURL = text(profile.baseURL) ?? text(entry.defaultBaseURL) ?? (await this.cloudflareEndpoint(route));
270
+ if (!baseURL || !/^https?:\/\//i.test(baseURL)) throw new ProviderModelsError('no-endpoint', `${route} has no endpoint to read its models from.`, { provider: route });
271
+ const api = text(profile.api) ?? 'openai-completions';
272
+ const key = await this.key(profile);
273
+ const first = listingUrl(baseURL, api);
274
+ const headers = new Headers();
275
+ if (isRecord(profile.headers)) for (const [header, value] of Object.entries(profile.headers)) if (typeof value === 'string') headers.set(header, value);
276
+ headers.set('accept', 'application/json');
277
+ if (api === 'anthropic-messages') {
278
+ headers.set('anthropic-version', ANTHROPIC_VERSION);
279
+ if (key) headers.set('x-api-key', key);
280
+ } else if (isGeminiNative(baseURL)) {
281
+ // Google's native API takes its key in `x-goog-api-key`; a bearer token is refused.
282
+ if (key) headers.set('x-goog-api-key', key);
283
+ } else if (key) headers.set('authorization', `Bearer ${key}`);
284
+ const deadline = Date.now() + LISTING_DEADLINE_MS;
285
+ let models = [];
286
+ let url = first;
287
+ for (let page = 1; ; page += 1) {
288
+ if (page > MAX_LISTING_PAGES) throw new ProviderModelsError('listing-failed', `${shown(first)} has more model pages than will be read (${MAX_LISTING_PAGES}).`, { provider: route });
289
+ const where = shown(url);
290
+ let response;
291
+ let target = url;
292
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
293
+ try {
294
+ response = await this.fetch(target, { method: 'GET', headers, redirect: 'manual', signal: AbortSignal.timeout(Math.max(1, Math.min(LISTING_TIMEOUT_MS, deadline - Date.now()))) });
295
+ } catch {
296
+ throw new ProviderModelsError('listing-failed', `Couldn't reach ${where}.`, { provider: route });
297
+ }
298
+ const location = response.status >= 300 && response.status < 400 ? response.headers.get('location') : null;
299
+ if (location === null) break;
300
+ await response.body?.cancel().catch(() => undefined);
301
+ response = undefined;
302
+ let next;
303
+ try {
304
+ next = new URL(location, target);
305
+ } catch {
306
+ throw new ProviderModelsError('listing-failed', `${where} redirected somewhere that is not a URL.`, { provider: route });
307
+ }
308
+ // The key rides in a header the runtime would forward: only the same origin is followed.
309
+ if (next.origin !== new URL(target).origin) throw new ProviderModelsError('listing-failed', `${where} redirected to ${next.origin}; set that address as the route's endpoint instead.`, { provider: route });
310
+ target = next.href;
311
+ }
312
+ if (response === undefined) throw new ProviderModelsError('listing-failed', `${where} redirected too many times.`, { provider: route });
313
+ if (!response.ok) {
314
+ const auth = response.status === 401 || response.status === 403;
315
+ throw new ProviderModelsError('listing-failed', `${where} answered ${response.status}${auth ? (key ? '; the stored key was refused' : '; the route has no stored key') : ''}.`, { provider: route, status: response.status });
316
+ }
317
+ let body;
318
+ try {
319
+ const raw = await readCapped(response, MAX_LISTING_BYTES);
320
+ if (raw === undefined) throw new Error('too large');
321
+ body = JSON.parse(raw);
322
+ } catch {
323
+ throw new ProviderModelsError('listing-failed', `${where} did not answer with a JSON model listing.`, { provider: route });
324
+ }
325
+ const listed = parseListing(body, api, { stripModelsPrefix: isGeminiHost(baseURL) });
326
+ if (!listed) throw new ProviderModelsError('listing-failed', `${where} did not answer with a model listing.`, { provider: route });
327
+ models = mergeModels(models, listed);
328
+ const next = nextPage(first, body, page);
329
+ if (next === undefined) break;
330
+ url = next;
331
+ }
332
+ const reply = { provider: route, models, authenticated: key !== undefined };
333
+ // A server that echoed the key into a model id must not carry it back out of dsh.
334
+ if (key && JSON.stringify(reply).includes(key)) throw new ProviderModelsError('listing-refused', `${shown(first)} answered with a listing that repeats the key; refusing it.`, { provider: route });
335
+ return reply;
336
+ }
337
+
338
+ /**
339
+ * A Workers AI route stores its account as the credential `CLOUDFLARE_ACCOUNT_ID` and no endpoint (each catalog model
340
+ * carries its own account URL), so its listing endpoint is built from that credential. Undefined for any other route,
341
+ * or when the stored value is not a plain account id.
342
+ */
343
+ async cloudflareEndpoint(route) {
344
+ if (route !== 'cloudflare-workers-ai') return undefined;
345
+ const credentials = this.credentials();
346
+ if (!credentials || typeof credentials.resolve !== 'function') return undefined;
347
+ let hit;
348
+ try {
349
+ hit = await credentials.resolve('CLOUDFLARE_ACCOUNT_ID');
350
+ } catch {
351
+ return undefined;
352
+ }
353
+ const account = typeof hit?.value === 'string' ? hit.value.trim() : '';
354
+ return /^[A-Za-z0-9_-]{1,64}$/.test(account) ? `https://api.cloudflare.com/client/v4/accounts/${account}/ai/v1` : undefined;
355
+ }
356
+
357
+ directory() {
358
+ const llm = this.llm();
359
+ if (!llm || typeof llm.listConfigurableProviders !== 'function') throw new ProviderModelsError('unavailable', 'dsh\'s llm service is not mounted.');
360
+ const entries = llm.listConfigurableProviders();
361
+ return Array.isArray(entries) ? entries : [];
362
+ }
363
+
364
+ /** The route's effective profile (unredacted: header values are sent with the request, never returned). */
365
+ profile(entry) {
366
+ const settings = this.settings();
367
+ if (!settings || typeof settings.describe !== 'function') throw new ProviderModelsError('unavailable', 'dsh\'s settings service is not mounted.');
368
+ const namespace = settings.describe().find((candidate) => candidate.ns === entry.settingsNs);
369
+ let profile = namespace?.value;
370
+ for (const key of entry.settingsPath ?? []) profile = isRecord(profile) ? profile[key] : undefined;
371
+ return isRecord(profile) ? profile : {};
372
+ }
373
+
374
+ /** The route's key from dsh's credential store, as llm-pi-ai resolves `apiKeyEnv`; undefined when it names none. */
375
+ async key(profile) {
376
+ const ref = text(profile.apiKeyEnv);
377
+ if (!ref) return undefined;
378
+ const credentials = this.credentials();
379
+ if (!credentials || typeof credentials.resolve !== 'function') throw new ProviderModelsError('unavailable', 'dsh\'s credentials service is not mounted.');
380
+ let hit;
381
+ try {
382
+ hit = await credentials.resolve(ref);
383
+ } catch {
384
+ throw new ProviderModelsError('credential-unavailable', `dsh couldn't read the credential ${ref}.`, { ref });
385
+ }
386
+ const value = typeof hit?.value === 'string' ? hit.value.trim() : '';
387
+ if (!value) throw new ProviderModelsError('credential-missing', `The route names ${ref}, which dsh does not hold. Add the key in Edit.`, { ref });
388
+ if (/[^\x21-\x7e]/.test(value)) throw new ProviderModelsError('credential-unusable', `The stored ${ref} has characters no HTTP header can carry.`, { ref });
389
+ return value;
390
+ }
391
+ }
392
+
393
+ const REMOTE_METHODS = ['list'];
394
+
395
+ Object.defineProperty(ProviderModels.prototype, REMOTE_METHOD_DESCRIPTOR, {
396
+ configurable: true,
397
+ value: Object.freeze({ version: 1, methods: Object.freeze(REMOTE_METHODS.map((method) => Object.freeze({ method, invocation: Object.freeze({ kind: 'direct' }) }))) }),
398
+ });
399
+
400
+ function levelNames(value) {
401
+ if (Array.isArray(value)) {
402
+ return value.flatMap((item) => {
403
+ if (typeof item === 'string') return [item.toLowerCase()];
404
+ if (isRecord(item)) {
405
+ const level = text(item.effort) ?? text(item.level) ?? text(item.id) ?? text(item.name);
406
+ return level ? [level.toLowerCase()] : [];
407
+ }
408
+ return [];
409
+ });
410
+ }
411
+ if (isRecord(value)) return Object.entries(value).filter(([, wire]) => wire !== false).map(([level]) => level.toLowerCase());
412
+ return [];
413
+ }
414
+
415
+ const ordered = (levels) => THINKING_LEVELS.filter((level) => levels.includes(level));
416
+
417
+ function capacity(...values) {
418
+ for (const value of values) if (typeof value === 'number' && Number.isSafeInteger(value) && value > 0) return value;
419
+ return undefined;
420
+ }
421
+
422
+ function requireString(value, field) {
423
+ if (typeof value !== 'string' || value.length === 0 || value.length > 256) throw new ProviderModelsError('bad-request', `${field} must be a non-empty string.`);
424
+ return value;
425
+ }
426
+
427
+ /** Cordis entry. Provides `providerModels`, bound for the Typert gateway (`typertRemote`). */
428
+ export function apply(ctx) {
429
+ const service = new ProviderModels({
430
+ llm: () => ctx.get('llm'),
431
+ settings: () => ctx.get('settings'),
432
+ credentials: () => ctx.get('credentials'),
433
+ });
434
+ service.typertRemote = Object.freeze({ service, serviceKey: SERVICE_KEY, namespace: SERVICE_KEY });
435
+ ctx.provide(SERVICE_KEY, service);
436
+ }